_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 |
|---|---|---|---|---|---|---|---|---|
2edf6ba0c47cbda11fd57bd477d0fcf73eac0c55b47aca19165b40bae1490b1d | VisionsGlobalEmpowerment/webchange | icon_page_text_big_at_bottom.cljs | (ns webchange.ui.components.icon.layout.icon-page-text-big-at-bottom)
(def data
[:svg {:xmlns ""
:width "104" :height "142" :viewBox "0 0 104 142"
:fill "none" :stroke "#DCE3F5" :stroke-width "2"
:class-name "stroke-colored"}
[:rect {:x "1" :y "1" :width "102" :height "140" :rx "5"}]
[:path {:d "M103 98.7213L71.8531 65.4578L53.3885 85.3911L69.8781 102L20.2587 52L0.999998 72.5675"}]
[:path {:d "M90.9396 26C90.9396 32.062 85.9523 37 79.7706 37C73.5889 37 68.6016 32.062 68.6016 26C68.6016 19.938 73.5889 15 79.7706 15C85.9523 15 90.9396 19.938 90.9396 26Z"}]
[:path {:d "M111 103 L 0 103"}]
[:path {:d "M12 111H91.3M12 117.656H91.3"}]
[:path {:d "M12 123.656H91.3M12 130.313H91.3"}]])
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/0df52dd08d54f14d4ec5d2717f48031849a7ee16/src/cljs/webchange/ui/components/icon/layout/icon_page_text_big_at_bottom.cljs | clojure | (ns webchange.ui.components.icon.layout.icon-page-text-big-at-bottom)
(def data
[:svg {:xmlns ""
:width "104" :height "142" :viewBox "0 0 104 142"
:fill "none" :stroke "#DCE3F5" :stroke-width "2"
:class-name "stroke-colored"}
[:rect {:x "1" :y "1" :width "102" :height "140" :rx "5"}]
[:path {:d "M103 98.7213L71.8531 65.4578L53.3885 85.3911L69.8781 102L20.2587 52L0.999998 72.5675"}]
[:path {:d "M90.9396 26C90.9396 32.062 85.9523 37 79.7706 37C73.5889 37 68.6016 32.062 68.6016 26C68.6016 19.938 73.5889 15 79.7706 15C85.9523 15 90.9396 19.938 90.9396 26Z"}]
[:path {:d "M111 103 L 0 103"}]
[:path {:d "M12 111H91.3M12 117.656H91.3"}]
[:path {:d "M12 123.656H91.3M12 130.313H91.3"}]])
| |
785b408ca7128a46cd45b0c246c14ec3cad411a4c40cb692ac0fec8aa9289720 | keera-studios/keera-hails | ReactiveModelInternals.hs | -- | This module holds the reactive program model. It holds a program model,
-- but includes events that other threads can listen to, so that a change
-- in a part of the model is notified to another part of the program. The
-- reactive model is not necessarily concurrent (it doesn't have its own thread),
-- although a facility is included to make it also concurrent (so that
-- event handlers can be called as soon as they are present).
--
Copyright : ( C ) Keera Studios Ltd , 2013
-- License : BSD3
Maintainer :
module Model.ReactiveModel.ReactiveModelInternals
( ReactiveModel
, GRM.basicModel
-- * Construction
, GRM.emptyRM
-- * Access
, GRM.pendingEvents
, GRM.pendingHandlers
-- * Modification
, GRM.getPendingHandler
, GRM.onEvent
, GRM.onBasicModel
, GRM.triggerEvent
)
where
-- Internal imports
import GenericModel .
import Model.Model
import Model.ReactiveModel.ModelEvents
import qualified Hails.MVC.Model.ReactiveModel as GRM
type ReactiveModel = GRM.ReactiveModel Model ModelEvent
| null | https://raw.githubusercontent.com/keera-studios/keera-hails/bf069e5aafc85a1f55fa119ae45a025a2bd4a3d0/demos/keera-hails-demos-gtk/elementarygtkprogram/src/Model/ReactiveModel/ReactiveModelInternals.hs | haskell | | This module holds the reactive program model. It holds a program model,
but includes events that other threads can listen to, so that a change
in a part of the model is notified to another part of the program. The
reactive model is not necessarily concurrent (it doesn't have its own thread),
although a facility is included to make it also concurrent (so that
event handlers can be called as soon as they are present).
License : BSD3
* Construction
* Access
* Modification
Internal imports | Copyright : ( C ) Keera Studios Ltd , 2013
Maintainer :
module Model.ReactiveModel.ReactiveModelInternals
( ReactiveModel
, GRM.basicModel
, GRM.emptyRM
, GRM.pendingEvents
, GRM.pendingHandlers
, GRM.getPendingHandler
, GRM.onEvent
, GRM.onBasicModel
, GRM.triggerEvent
)
where
import GenericModel .
import Model.Model
import Model.ReactiveModel.ModelEvents
import qualified Hails.MVC.Model.ReactiveModel as GRM
type ReactiveModel = GRM.ReactiveModel Model ModelEvent
|
cbef901825d030724dd2b203f45b77171bb569d8ba93a10346c027b63860a8f3 | iu-parfunc/lvars | bfs_lvish.hs | # LANGUAGE CPP , ScopedTypeVariables #
# LANGUAGE BangPatterns , RankNTypes #
import Data.Set as Set
-- Benchmark utils:
import PBBS.FileReader
import PBBS.Timing (wait_clocks, runAndReport)
calibrate , measureFreq , commaint ,
import Control.LVish
import Control.LVish.Internal
import Control.LVish.DeepFrz (runParThenFreezeIO)
import qualified Control.LVish.SchedIdempotent as L
import Control.Monad
import Control.Monad.Par.Combinator (parFor, InclusiveRange(..))
import Control.Monad.ST
import Control.Exception
import GHC.Conc
import Data.Word
import Data.Maybe
import Data.LVar.MaxCounter as C
import Data.Time.Clock
import qualified Data.Traversable as T
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as M
import qualified Data.Vector.Storable as UV
import qualified Data.Vector.Storable.Mutable as MV
import System.Mem (performGC)
import System.Environment (getArgs)
import System.Directory
import System.Process
-- define DEBUG_CHECKS
--------------------------------------------------------------------------------
#if 1
import Data.LVar.PureSet as S
#else
[ 2013.07.09 ] This one still is n't terminating on 125K+
Well , maybe it 's just slow ... 5000 takes 2 seconds .
Yes , it 's literally over 100 times slower currently .
import Data.LVar.SLSet as S
#endif
import qualified Data.LVar.SLSet as SL
import Data.LVar.IStructure as ISt
import Data.LVar.NatArray as NArr
An LVar - based version of bf_traverse . As we traverse the graph ,
the results of applying f to each node accumulate in an LVar , where
-- they are available to other computations, enabling pipelining.
bf_traverse : : Int -- iteration counter
- > Graph2 -- graph
- > ISet WorkRet -- LVar
- > IS.IntSet -- set of " seen " node labels , initially size 0
- > IS.IntSet -- set of " new " node labels , initially size 1
- > WorkFn -- function to be applied to each node
- > Par ( IS.IntSet )
bf_traverse 0 _ _ seen_rank new_rank _ = do
when verbose $ prnt $ " bf_traverse finished ! seen / new size : "
+ + show ( IS.size seen_rank , )
return ( IS.union seen_rank new_rank )
bf_traverse k ! ! l_acc ! seen_rank ! ! f = do
when verbose $ prnt $ " bf_traverse call ... "
+ + show k + + " seen / new size "
+ + show ( IS.size seen_rank , )
-- Nothing in the new_rank set means nothing left to traverse .
if IS.null then return seen_rank
else do
-- Add new_rank stuff to the " seen " list
let seen_rank ' = IS.union seen_rank new_rank
allNbr ' = IS.fold ( \i acc - > IS.union ( g V. ! i ) acc )
new_rank ' = IS.difference allNbr ' seen_rank '
-- We COULD use callbacks here , but rather we 're modeling what happens in the
-- current paper :
parMapM _ ( \x - > fork$ do
let elem = f x
S.insert elem l_acc
when dbg $ do
st < - unsafePeekSet l_acc
prnt$ " -- > Called S.insert , node " + + show x
+ + " size is " + + show(Set.size st )
+ + " elem is " + + show elem -- + + " " + + show st
)
( IS.toList new_rank ' ) -- toList is HORRIBLE
bf_traverse ( k-1 ) g l_acc seen_rank ' new_rank ' f
start_traverse : : Int -- iteration counter
- > Graph2 -- graph
- > Int -- start node
- > WorkFn -- function to be applied to each node
- > IO ( )
start_traverse k ! do
runParIO $ do
prnt $ " * Running on " + + show numCapabilities + + " parallel resources ... "
l_acc < - newEmptySet
-- " manually " add startNode
fork $ S.insert ( f startNode ) l_acc
-- pass in { startNode } as the initial " new " set
set < - bf_traverse k g l_acc IS.empty ( IS.singleton startNode ) f
prnt $ " * Done with bf_traverse ... "
let size = IS.size set
" * Waiting on " + + show size++ " set results ... "
when dbg $ do
forM _ [ 0 .. size ] $ \ s - > do
" ? Blocking on " + + show " elements to be in the set ... "
waitForSetSize s l_acc
-- Waiting is required in any case for correctness , whether or
-- not we consume the result
waitForSetSize ( size ) l_acc -- Depends on a bunch of forked computations
" * Set results all available ! ( " + + show size + + " ) "
s < - consumeSet l_acc : : Par ( Set . Set WorkRet )
liftIO ( do evaluate s ; return ( ) )
prnt $ " * Finished consumeSet : "
prnt $ " * Set size : " + + show ( Set.size s )
prnt $ " * Set sum : " + + show ( Set.fold ( \(x , _ ) y - > x+y ) 0 s )
parMapM _ f l =
do parMapM f l
return ( )
bf_traverse :: Int -- iteration counter
-> Graph2 -- graph
-> ISet WorkRet -- LVar
-> IS.IntSet -- set of "seen" node labels, initially size 0
-> IS.IntSet -- set of "new" node labels, initially size 1
-> WorkFn -- function to be applied to each node
-> Par (IS.IntSet)
bf_traverse 0 _ _ seen_rank new_rank _ = do
when verbose $ prnt $ "bf_traverse finished! seen/new size: "
++ show (IS.size seen_rank, IS.size new_rank)
return (IS.union seen_rank new_rank)
bf_traverse k !g !l_acc !seen_rank !new_rank !f = do
when verbose $ prnt $"bf_traverse call... "
++ show k ++ " seen/new size "
++ show (IS.size seen_rank, IS.size new_rank)
-- Nothing in the new_rank set means nothing left to traverse.
if IS.null new_rank
then return seen_rank
else do
-- Add new_rank stuff to the "seen" list
let seen_rank' = IS.union seen_rank new_rank
allNbr' = IS.fold (\i acc -> IS.union (g V.! i) acc)
IS.empty new_rank
new_rank' = IS.difference allNbr' seen_rank'
-- We COULD use callbacks here, but rather we're modeling what happens in the
-- current paper:
parMapM_ (\x -> fork$ do
let elem = f x
S.insert elem l_acc
when dbg $ do
st <- unsafePeekSet l_acc
prnt$ " --> Called S.insert, node "++show x
++" size is "++show(Set.size st)
++" elem is "++show elem -- ++" "++show st
)
(IS.toList new_rank') -- toList is HORRIBLE
bf_traverse (k-1) g l_acc seen_rank' new_rank' f
start_traverse :: Int -- iteration counter
-> Graph2 -- graph
-> Int -- start node
-> WorkFn -- function to be applied to each node
-> IO ()
start_traverse k !g startNode f = do
runParIO $ do
prnt $ " * Running on " ++ show numCapabilities ++ " parallel resources..."
l_acc <- newEmptySet
-- "manually" add startNode
fork $ S.insert (f startNode) l_acc
-- pass in { startNode } as the initial "new" set
set <- bf_traverse k g l_acc IS.empty (IS.singleton startNode) f
prnt $ " * Done with bf_traverse..."
let size = IS.size set
prnt$ " * Waiting on "++show size++" set results..."
when dbg $ do
forM_ [0..size] $ \ s -> do
prnt$ " ? Blocking on "++show s++" elements to be in the set..."
waitForSetSize s l_acc
-- Waiting is required in any case for correctness, whether or
-- not we consume the result
waitForSetSize (size) l_acc -- Depends on a bunch of forked computations
prnt$ " * Set results all available! (" ++ show size ++ ")"
s <- consumeSet l_acc :: Par (Set.Set WorkRet)
liftIO (do evaluate s; return ())
prnt $ " * Finished consumeSet:"
prnt $ " * Set size: " ++ show (Set.size s)
prnt $ " * Set sum: " ++ show (Set.fold (\(x,_) y -> x+y) 0 s)
parMapM_ f l =
do parMapM f l
return ()
-}
--------------------------------------------------------------------------------
-- Graph algorithms
--------------------------------------------------------------------------------
bfs_async :: AdjacencyGraph -> NodeID -> Par d s (ISet s NodeID)
bfs_async gr@(AdjacencyGraph vvec evec) start = do
st <- S.newFromList [start]
S.forEach st $ \ nd -> do
logDbgLn 1 $" [bfs] expanding node "++show nd++" to nbrs " ++ show (nbrs gr nd)
forVec (nbrs gr nd) (`S.insert` st)
return st
T.traverse _ ( ` S.insert ` st ) ( nbrs gr nd )
-- | A version that uses an array rather than set representation.
bfs_async_arr :: AdjacencyGraph -> NodeID -> Par d s (IStructure s Bool)
bfs_async_arr gr@(AdjacencyGraph vvec evec) start = do
arr <- newIStructure (U.length vvec)
let callback nd bool = do
let myNbrs = nbrs gr (fromIntegral nd)
logDbgLn 1 $" [bfs] expanding node "++show (nd,bool)++" to nbrs " ++ show myNbrs
-- TODO: possibly use a better for loop:
forVec myNbrs (\nbr -> ISt.put_ arr (fromIntegral nbr) True)
ISt.forEachHP Nothing arr callback
logDbgLn 1 $" [bfs] Seeding with start vertex... "
ISt.put_ arr (fromIntegral start) True
return arr
| Same , but with NatArray .
bfs_async_arr2 :: AdjacencyGraph -> NodeID -> Par d s (NatArray s Word8)
bfs_async_arr2 gr@(AdjacencyGraph vvec evec) start = do
arr <- newNatArray (U.length vvec)
let callback nd flg = do
let myNbrs = nbrs gr (fromIntegral nd)
-- logDbgLn 1 $" [bfs] expanding node "++show (nd,flg)++" to nbrs " ++ show myNbrs
forVec myNbrs (\nbr -> NArr.put arr (fromIntegral nbr) 1)
NArr.forEach arr callback
-- logDbgLn 1 $" [bfs] Seeding with start vertex... "
NArr.put arr (fromIntegral start) 1
return arr
------------------------------------------------------------------------------------------
A simple FOLD operation .
------------------------------------------------------------------------------------------
maxDegreeS :: AdjacencyGraph -> (ISet s NodeID) -> Par d s (MaxCounter s)
maxDegreeS gr component = do
mc <- newMaxCounter 0
S.forEach component $ \ nd ->
C.put mc (U.length$ nbrs gr nd)
return mc
maxDegreeN :: AdjacencyGraph -> (NatArray s Word8) -> Par d s (MaxCounter s)
maxDegreeN gr component = do
mc <- newMaxCounter 0
NArr.forEach component $ \ nd flg ->
when (flg == 1) $
C.put mc (U.length$ nbrs gr (fromIntegral nd))
return mc
maxDegreeI :: AdjacencyGraph -> (IStructure s Word8) -> Par d s (MaxCounter s)
maxDegreeI gr component = do
mc <- newMaxCounter 0
-- INEFFICIENT: this attaches a handler to ALL ivars:
ISt.forEachHP Nothing component $ \ nd flg -> do
when (flg == 1) $ do
let degree = U.length$ nbrs gr (fromIntegral nd)
-- logDbgLn 1$ " [maxDegreeI] Processing: "++show(nd,flg)++" with degree "++show degree
C.put mc degree
-- Better to just do this... wait for it to freeze and then loop.
-- Problem is, we need to add wait-till-frozen!
-- len <- ISt.getLength component
-- parForTiled (0,len) $ \ nd ->
when ( flg = = 1 ) $
-- C.put mc (U.length$ nbrs gr (fromIntegral nd))
return mc
------------------------------------------------------------------------------------------
-- A dummy per-node operation
------------------------------------------------------------------------------------------
workEachNode : : ( NatArray s Word8 ) - > ( Word8 - > Par d s ( ) ) - > Par d s ( MaxCounter s )
workEachNode :: Word64 -> (NatArray s Word8) -> Par d s ()
workEachNode clocks component = do
NArr.forEach component $ \ nd flg ->
when (flg == 1) $ do
liftIO$ wait_clocks clocks
return ()
-- After freezing... this is a parallel loop, but doesn't use any monotonic data.
workEachVec :: Word64 -> UV.Vector Word8 -> Par d s ()
workEachVec clocks vec = do
np <- liftIO$ getNumCapabilities
for _ ( 0,UV.length vec ) $ \ ix - >
parForTiled ( np*4 ) ( 0,UV.length vec ) $ \ ix - >
parForSimple ( 0,UV.length vec ) $ \ ix - >
parForTree (0,UV.length vec) $ \ ix ->
let flg = vec UV.! ix in
when (flg == 1) $ do
liftIO$ wait_clocks clocks
return ()
-- Sequential version:
-- UV.forM_ vec $ \ flg ->
when ( flg = = 1 ) $ do
-- liftIO$ wait_clocks clocks
-- return ()
workEachNodeI :: Word64 -> (IStructure s Word8) -> Par d s ()
workEachNodeI clocks component = do
ISt.forEachHP Nothing component $ \ nd flg ->
when (flg == 1) $ do
liftIO$ wait_clocks clocks
return ()
-- After freezing... this is a parallel loop, but doesn't use any monotonic data.
workEachVecMayb :: Word64 -> V.Vector (Maybe Word8) -> Par d s ()
workEachVecMayb clocks vec = do
np <- liftIO$ getNumCapabilities
for _ ( 0,UV.length vec ) $ \ ix - >
parForTiled ( np*4 ) ( 0,UV.length vec ) $ \ ix - >
parForSimple ( 0,UV.length vec ) $ \ ix - >
parForTree (0, V.length vec) $ \ ix ->
let flg = vec V.! ix in
when (flg == Just 1) $ do
liftIO$ wait_clocks clocks
return ()
------------------------------------------------------------------------------------------
-- Maximal Independent Set
------------------------------------------------------------------------------------------
-- Lattice where undecided = bot, and chosen/nbrchosen are disjoint middle states
flag_UNDECIDED :: Word8
flag_CHOSEN :: Word8
flag_NBRCHOSEN :: Word8
flag_UNDECIDED = 0
flag_CHOSEN = 1
flag_NBRCHOSEN = 2
# INLINE maximalIndependentSet #
maximalIndependentSet : : NodeID - > Par d s ( ISet s NodeID ) -- Operate on a subgraph
-- maximalIndependentSet :: AdjacencyGraph -> Par d s (ISet s NodeID) -- Operate on a whole graph.
maximalIndependentSet :: ParFor d s -> AdjacencyGraph -> Par d s (NatArray s Word8) -- Operate on a whole graph.
maximalIndependentSet parFor gr@(AdjacencyGraph vvec evec) = do
For each vertex , we record whether it is CHOSEN , not chosen , or undecided :
let numVerts = U.length vvec
flagsArr :: NatArray s Word8 <- newNatArray numVerts
let
-- Here's the loop that scans through the neighbors of a node.
loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
-- logDbgLn 1$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
-- If we got to the end of the neighbors below us, then we are NOT disqualified:
if nbrInd > selfInd
then thisNodeWins
else do
-- This should never block in a single-thread execution:
logDbgLn 1 (" [MIS] ! Getting on nbrInd "++show nbrInd)
nbrFlag <- NArr.get flagsArr (fromIntegral nbrInd)
logDbgLn 1 (" [MIS] ! Get completed on nbrInd "++show nbrInd)
if nbrFlag == flag_CHOSEN
then NArr.put flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = logDbgLn 1 (" [MIS] ! Node chosen: "++show selfInd) >>
NArr.put flagsArr (fromIntegral selfInd) flag_CHOSEN
parFor (0,numVerts) $ \ ndIx -> do
let nds = nbrs gr (fromIntegral ndIx)
logDbgLn 1 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show
loop (U.length nds) nds ndIx 0
return flagsArr
-- | DUPLICATE CODE: IStructure version.
maximalIndependentSet2 :: ParFor d s -> AdjacencyGraph -> Par d s (IStructure s Word8) -- Operate on a whole graph.
maximalIndependentSet2 parFor gr@(AdjacencyGraph vvec evec) = do
logDbgLn 1$ " [MIS] Beginning maximalIndependentSet / Istructures"
For each vertex , we record whether it is CHOSEN , not chosen , or undecided :
let numVerts = U.length vvec
flagsArr <- newIStructure numVerts
let
-- Here's the loop that scans through the neighbors of a node.
loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
-- logDbgLn 1$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
-- If we got to the end of the neighbors below us, then we are NOT disqualified:
if nbrInd > selfInd
then thisNodeWins
else do
-- This should never block in a single-thread execution:
logDbgLn 1 (" [MIS] ! Getting on nbrInd "++show nbrInd)
nbrFlag <- ISt.get flagsArr (fromIntegral nbrInd)
logDbgLn 1 (" [MIS] ! Get completed on nbrInd "++show nbrInd)
if nbrFlag == flag_CHOSEN
then ISt.put_ flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = logDbgLn 1 (" [MIS] ! Node chosen: "++show selfInd) >>
ISt.put_ flagsArr (fromIntegral selfInd) flag_CHOSEN
parFor (0,numVerts) $ \ ndIx -> do
let nds = nbrs gr (fromIntegral ndIx)
logDbgLn 1 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show
loop (U.length nds) nds ndIx 0
return flagsArr
-- | Sequential version.
maximalIndependentSet3 :: AdjacencyGraph -> (U.Vector Word8)
maximalIndependentSet3 gr@(AdjacencyGraph vvec evec) = U.create $ do
let numVerts = U.length vvec
flagsArr <- M.replicate numVerts 0
let loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
if nbrInd > selfInd
then thisNodeWins
else do
nbrFlag <- M.read flagsArr (fromIntegral nbrInd)
if nbrFlag == flag_CHOSEN
then M.write flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = M.write flagsArr (fromIntegral selfInd) flag_CHOSEN
for_ (0,numVerts) $ \ ndIx -> do
let nds = nbrs gr (fromIntegral ndIx)
loop (U.length nds) nds ndIx 0
return flagsArr
| Sequential version on NatArray ...
maximalIndependentSet3B :: AdjacencyGraph -> (UV.Vector Word8) -> (UV.Vector Word8)
maximalIndependentSet3B gr@(AdjacencyGraph vvec evec) vec = UV.create $ do
let numVerts = U.length vvec
flagsArr <- MV.replicate numVerts 0
let loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
if nbrInd > selfInd
then thisNodeWins
else do
nbrFlag <- MV.read flagsArr (fromIntegral nbrInd)
if nbrFlag == flag_CHOSEN
then MV.write flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = MV.write flagsArr (fromIntegral selfInd) flag_CHOSEN
for_ (0,numVerts) $ \ ndIx ->
when (vec UV.! ndIx == 1) $ do
let nds = nbrs gr (fromIntegral ndIx)
loop (U.length nds) nds ndIx 0
return flagsArr
-- MIS over a preexisting, filtered subgraph
------------------------------------------------------------
-- Right now this uses an IStructure because it's (temporarily) better at blocking gets:
maximalIndependentSet4 :: AdjacencyGraph -> (NatArray s Word8) -> Par d s (IStructure s Word8)
maximalIndependentSet4 gr@(AdjacencyGraph vvec evec) vertSubset = do
let numVerts = U.length vvec
-- Tradeoff: we use storage proportional to the ENTIRE graph. If the subset is
-- very small, this is silly and we could use a sparse representation:
flagsArr <- newIStructure numVerts
let
-- Here's the loop that scans through the neighbors of a node.
loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
-- If we got to the end of the neighbors below us, then we are NOT disqualified:
if nbrInd > selfInd
then thisNodeWins
else do
nbrFlag <- ISt.get flagsArr (fromIntegral nbrInd)
if nbrFlag == flag_CHOSEN
then ISt.put_ flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = ISt.put_ flagsArr (fromIntegral selfInd) flag_CHOSEN
NArr.forEach vertSubset $ \ ndIx _ ->
let nds = nbrs gr (fromIntegral ndIx) in
loop (U.length nds) nds ndIx 0
return flagsArr
--------------------------------------------------------------------------------
-- Misc helpers
--------------------------------------------------------------------------------
# INLINE forVec #
-- | Simple for-each loops over vector elements.
forVec :: U.Unbox a => U.Vector a -> (a -> Par d s ()) -> Par d s ()
forVec vec fn = loop 0
where
len = U.length vec
loop i | i == len = return ()
| otherwise = fn (U.unsafeIndex vec i) >>
loop (i+1)
type ParFor d s = (Int,Int) -> (Int -> Par d s ()) -> Par d s ()
--------------------------------------------------------------------------------
Main Program
--------------------------------------------------------------------------------
main = do
putStrLn "USAGE: ./bfs_lvish <version> <topo> <graphSize>"
putStrLn "USAGE: Topo must be one of: grid rmat rand chain"
putStrLn "USAGE: Version must be one of: "
putStrLn "USAGE: bfsS bfsN bfsI"
putStrLn "USAGE: misN1 misN2 misN3 misI3 misSeq"
--------------------------------------------------------------------------------
args <- getArgs
let (version,topo,size,wrksize::Double) =
case args of
[ver,tp,s,w] -> (ver, tp, read s, read w)
[ver,tp,s] -> (ver, tp, read s, 0)
[ver,tp] -> (ver, tp, 1000, 0)
[ver] -> (ver, "grid", 1000, 0)
[] -> ("bfsN","grid",1000, 0)
oth -> error "Too many command line args!"
existD d = do b <- doesDirectoryExist d
return$ if b then (Just d) else Nothing
-- Here's a silly hack to let this executable run from different working directories:
pbbsdirs <- fmap catMaybes $ mapM existD [ "../pbbs"
, "../../pbbs"
, "../../../pbbs"
, "../../../../pbbs"]
let pbbsroot = case pbbsdirs of
[] -> error "PBBS dir not found! Is the submodule checked out?"
hd:_ -> hd
datroot = pbbsroot++"/breadthFirstSearch/graphData/data/"
The PBBS Makefile knowns how to build the common graphs :
buildPBBSdat file = do
origdir <- getCurrentDirectory
setCurrentDirectory datroot
b <- doesFileExist file
unless b $ do
putStrLn "Input file does not exist! Building..."
system$ "make "++file
return ()
setCurrentDirectory origdir
file <- case topo of
"grid" -> do let f = "3Dgrid_J_"++show size
buildPBBSdat f
return (datroot ++ f)
-- Models social-network graphs:
"rmat" -> do let f = "rMatGraph_J_5_"++show size
buildPBBSdat f
return (datroot ++ f)
"rand" -> do let f = "randLocalGraph_J_5_"++show size
buildPBBSdat f
return (datroot ++ f)
"chain" -> do let f = "chain_"++show size
p = datroot ++ f
b <- doesFileExist p
unless b $ do
putStrLn$"Generating chain graph in "++p
system "ghc -threaded gen_chains_graph.hs -o ./gen_chains_graph.exe"
system$ "./gen_chains_graph.exe "++show size++" > "++p
return ()
return p
_ -> error$"Unknown graph topology: "++topo
putStrLn$"Running config: "++show(version,topo,size)
------------------------------------------------------------
wd <- getCurrentDirectory
putStrLn$ "Working dir: "++wd
putStrLn$ "Reading file: "++file
t0 <- getCurrentTime
gr <- readAdjacencyGraph file
t1 <- getCurrentTime
let numVerts = U.length (vertOffets gr)
putStrLn$ "graph read ("++show (diffUTCTime t1 t0)++
"): verts,edges: "++show (numVerts, U.length (allEdges gr))
putStrLn$ "max vert off "++show (U.foldl1 max (vertOffets gr))
putStrLn$ "max edge target "++show (U.foldl1 max (allEdges gr))
t2 <- getCurrentTime
putStrLn$ "time for those simple folds: "++show (diffUTCTime t2 t1)
performGC
-- writeFile "/tmp/debug" (show gr)
-- putStrLn$ "Dumped parsed graph to /tmp/debug"
runAndReport $ \ clocks_per_micro ->
let amountWork = (round (wrksize * clocks_per_micro)) in
case version of
----------------------------------------
"bfsS" -> do
putStrLn " ! Version 2: BFS only, with sets "
par2 : : Par d0 s0 ( ISet s0 NodeID )
par2 : : Par d0 s0 ( )
par2 = do comp <- bfs_async gr 0
waitSize numVerts comp -- A proxy for completeness... assumes fully connected graph.
return comp
_ <- runParIO_ par2
-- set:: Snapshot ISet NodeID <- runParThenFreezeIO par2
let ISetSnap s = set
-- putStrLn$ "Connected component, set size "++show (Set.size s)
return ()
----------------------------------------
"bfsI" -> do putStrLn " ! Version 3: BFS only, with IStructures "
par2 : : Par d0 s0 ( ISet s0 NodeID )
par3 :: Par d0 s0 (IStructure s0 Bool)
par3 = bfs_async_arr gr 0
_ <- runParIO_ par3
return ()
----------------------------------------
"bfsN" -> do putStrLn " ! Version 4: BFS only, with NatArrays "
par2 : : Par d0 s0 ( ISet s0 NodeID )
par4 :: Par d0 s0 (NatArray s0 Word8)
par4 = bfs_async_arr2 gr 0
_ <- runParIO_ par4
return ()
----------------------------------------
" misN1 " - > do
putStrLn " ! Version 5 : MIS only , with NatArrays / parForSimple "
let par : : Par d0 s0 ( NatArray s0 Word8 )
par = maximalIndependentSet parForSimple gr
# ifdef DEBUG_CHECKS
( x : : ) < - runParThenFreezeIO par
putStrLn$ " MIS : result prefix : " + + show ( UV.take 100 x )
putStrLn$ " MIS : number of vertices in result : " + + show ( UV.sum ( UV.filter (= = 1 ) x ) )
# else
_ < - runParIO _ par
# endif
return ( )
----------------------------------------
" misN2 " - > do
putStrLn " ! Version 6 : MIS only , with NatArrays / parForTree "
let par : : Par d0 s0 ( NatArray s0 Word8 )
par = maximalIndependentSet parForTree gr
_ < - runParIO _ par
return ( )
----------------------------------------
" misN3 " - > do
putStrLn " ! Version 7 : MIS only , with NatArrays / parForL "
let par : : Par d0 s0 ( NatArray s0 Word8 )
par = maximalIndependentSet parForL gr
_ < - runParIO _ par
return ( )
----------------------------------------
" misI3 " - > do
putStrLn " ! Version 8 : MIS only , with IStructures / parForL "
let par : : Par d0 s0 ( IStructure s0 Word8 )
par = maximalIndependentSet2 parForL gr
_ < - runParIO _ par
return ( )
-- This version does n't get the horrible parallel slowdown of version 5 - 7 .
-- But alas , version 7 sequential is better .
-- And version 9 sequential is WAY better ( > 50X faster )
----------------------------------------
" misSeq " - > do
putStrLn " ! Version 9 : MIS only , sequential "
evaluate $ maximalIndependentSet3 gr
return ( )
----------------------------------------
" bfsN_misI " - > do
putStrLn " ! Version 10 : BFS and then MIS w/ NatArrays / IStructure "
let par : : Par d0 s0 ( IStructure s0 Word8 )
par = do < - bfs_async_arr2 gr 0
maximalIndependentSet4 gr natarr
_ < - runParIO _ par
return ( )
----------------------------------------
" bfsN_misI_deg " - > do
putStrLn " ! Version 11 : BFS , MIS , and "
let par : : Par d0 s0 ( MaxCounter s0 )
par = do < - bfs_async_arr2 gr 0
narr2 < - maximalIndependentSet4 gr natarr
maxDegreeI gr narr2
mx < - runParThenFreezeIO par
putStrLn$ " degree in MIS was : " + + show(mx::Int )
----------------------------------------
" bfsN_work " - > do
putStrLn " ! Version 12 : BFS and per - vertex work "
let par : : Par d0 s0 ( )
par = do < - bfs_async_arr2 gr 0
workEachNode amountWork
_ < - runParIO _ par
return ( )
----------------------------------------
" bfsN_barrier_work " - > do
putStrLn " ! Version 13 : BFS , barrier , and per - vertex work "
let -- par : : Par d0 s0 ( )
par = bfs_async_arr2 gr 0
NatArraySnap vec < - runParThenFreezeIO par
runParIO _ $ workEachVec amountWork
return ( )
----------------------------------------
" misI_work " - > do
putStrLn " ! Version 14 : MIS and per - vertex work "
let par : : Par d0 s0 ( )
par = do istrct < - maximalIndependentSet2 parForL gr
workEachNodeI amountWork
_ < - runParIO _ par
return ( )
----------------------------------------
" misI_barrier_work " - > do
putStrLn " ! Version 15 : "
let -- par : : Par d0 s0 ( )
par = maximalIndependentSet2 parForL gr
IStructSnap vec < - runParThenFreezeIO par
runParIO _ $ workEachVecMayb amountWork
return ( )
----------------------------------------
" bfsN_misI_work " - > do
putStrLn " ! Version 16 : "
let par : : Par d0 s0 ( )
par = do < - bfs_async_arr2 gr 0
istrct < - maximalIndependentSet4 gr natarr
workEachNodeI amountWork
_ < - runParIO _ par
return ( )
----------------------------------------
" bfsN_barrier_misI_work " - > do
putStrLn " ! Version 17 : "
let par = bfs_async_arr2 gr 0
NatArraySnap vec < - runParThenFreezeIO par
let vec2 = maximalIndependentSet3B gr vec -- Sequential
runParIO _ $ workEachVec amountWork vec2
return ( )
----------------------------------------
" ? " - > do
putStrLn " ! Version 1 : work in progress testing combinations of graph ops ... "
let par1 : : Par d0 s0 ( MaxCounter s0 , ISet s0 NodeID )
par1 = do component < - bfs_async gr 0
liftIO$ " Got component ... "
mc < - maxDegreeS gr component
return ( mc , component )
( maxdeg::Int , set : : Snapshot ISet NodeID ) < - runParThenFreezeIO2 par1
putStrLn$ " Processing finished , max degree was : " + + show maxdeg
let ISetSnap s = set
putStrLn$ " Connected component , set size " + + show ( Set.size s )
----------------------------------------
"misN1" -> do
putStrLn " ! Version 5: MIS only, with NatArrays / parForSimple"
let par :: Par d0 s0 (NatArray s0 Word8)
par = maximalIndependentSet parForSimple gr
#ifdef DEBUG_CHECKS
NatArraySnap (x :: UV.Vector Word8) <- runParThenFreezeIO par
putStrLn$ "MIS: result prefix: "++show (UV.take 100 x)
putStrLn$ "MIS: number of vertices in result: "++show (UV.sum (UV.filter (==1) x))
#else
_ <- runParIO_ par
#endif
return ()
----------------------------------------
"misN2" -> do
putStrLn " ! Version 6: MIS only, with NatArrays / parForTree"
let par :: Par d0 s0 (NatArray s0 Word8)
par = maximalIndependentSet parForTree gr
_ <- runParIO_ par
return ()
----------------------------------------
"misN3" -> do
putStrLn " ! Version 7: MIS only, with NatArrays / parForL"
let par :: Par d0 s0 (NatArray s0 Word8)
par = maximalIndependentSet parForL gr
_ <- runParIO_ par
return ()
----------------------------------------
"misI3" -> do
putStrLn " ! Version 8: MIS only, with IStructures / parForL"
let par :: Par d0 s0 (IStructure s0 Word8)
par = maximalIndependentSet2 parForL gr
_ <- runParIO_ par
return ()
-- This version doesn't get the horrible parallel slowdown of version 5-7.
-- But alas, version 7 sequential is better.
-- And version 9 sequential is WAY better (>50X faster)
----------------------------------------
"misSeq" -> do
putStrLn " ! Version 9: MIS only, sequential"
evaluate $ maximalIndependentSet3 gr
return ()
----------------------------------------
"bfsN_misI" -> do
putStrLn " ! Version 10: BFS and then MIS w/ NatArrays/IStructure"
let par :: Par d0 s0 (IStructure s0 Word8)
par = do natarr <- bfs_async_arr2 gr 0
maximalIndependentSet4 gr natarr
_ <- runParIO_ par
return ()
----------------------------------------
"bfsN_misI_deg" -> do
putStrLn " ! Version 11: BFS, MIS, and maxDegree"
let par :: Par d0 s0 (MaxCounter s0)
par = do natarr <- bfs_async_arr2 gr 0
narr2 <- maximalIndependentSet4 gr natarr
maxDegreeI gr narr2
mx <- runParThenFreezeIO par
putStrLn$ "Max degree in MIS was: "++show(mx::Int)
----------------------------------------
"bfsN_work" -> do
putStrLn " ! Version 12: BFS and per-vertex work"
let par :: Par d0 s0 ()
par = do natarr <- bfs_async_arr2 gr 0
workEachNode amountWork natarr
_ <- runParIO_ par
return ()
----------------------------------------
"bfsN_barrier_work" -> do
putStrLn " ! Version 13: BFS, barrier, and per-vertex work"
let -- par :: Par d0 s0 ()
par = bfs_async_arr2 gr 0
NatArraySnap vec <- runParThenFreezeIO par
runParIO_ $ workEachVec amountWork vec
return ()
----------------------------------------
"misI_work" -> do
putStrLn " ! Version 14: MIS and per-vertex work"
let par :: Par d0 s0 ()
par = do istrct <- maximalIndependentSet2 parForL gr
workEachNodeI amountWork istrct
_ <- runParIO_ par
return ()
----------------------------------------
"misI_barrier_work" -> do
putStrLn " ! Version 15: "
let -- par :: Par d0 s0 ()
par = maximalIndependentSet2 parForL gr
IStructSnap vec <- runParThenFreezeIO par
runParIO_ $ workEachVecMayb amountWork vec
return ()
----------------------------------------
"bfsN_misI_work" -> do
putStrLn " ! Version 16: "
let par :: Par d0 s0 ()
par = do natarr <- bfs_async_arr2 gr 0
istrct <- maximalIndependentSet4 gr natarr
workEachNodeI amountWork istrct
_ <- runParIO_ par
return ()
----------------------------------------
"bfsN_barrier_misI_work" -> do
putStrLn " ! Version 17: "
let par = bfs_async_arr2 gr 0
NatArraySnap vec <- runParThenFreezeIO par
let vec2 = maximalIndependentSet3B gr vec -- Sequential
runParIO_ $ workEachVec amountWork vec2
return ()
----------------------------------------
"?" -> do
putStrLn " ! Version 1: work in progress testing combinations of graph ops..."
let par1 :: Par d0 s0 (MaxCounter s0, ISet s0 NodeID)
par1 = do component <- bfs_async gr 0
liftIO$ putStrLn "Got component..."
mc <- maxDegreeS gr component
return (mc,component)
(maxdeg::Int, set:: Snapshot ISet NodeID) <- runParThenFreezeIO2 par1
putStrLn$ "Processing finished, max degree was: "++show maxdeg
let ISetSnap s = set
putStrLn$ "Connected component, set size "++show (Set.size s)
-}
oth -> error$"Unknown benchmark mode "++oth
putStrLn$ "Done"
-- runParIO_ :: (forall s . Par d s a) -> IO ()
-- runParIO_ p = do runParIO p; return ()
Unsafe version , fix this :
runParIO_ :: (Par d s a) -> IO ()
runParIO_ (WrapPar p) = L.runParIO p >> return ()
| null | https://raw.githubusercontent.com/iu-parfunc/lvars/78e73c96a929aa75aa4f991d42b2f677849e433a/src/lvish-apps/pbbs/benchmarks/graphs/bfs_lvish.hs | haskell | Benchmark utils:
define DEBUG_CHECKS
------------------------------------------------------------------------------
they are available to other computations, enabling pipelining.
iteration counter
graph
LVar
set of " seen " node labels , initially size 0
set of " new " node labels , initially size 1
function to be applied to each node
Nothing in the new_rank set means nothing left to traverse .
Add new_rank stuff to the " seen " list
We COULD use callbacks here , but rather we 're modeling what happens in the
current paper :
+ + " " + + show st
toList is HORRIBLE
iteration counter
graph
start node
function to be applied to each node
" manually " add startNode
pass in { startNode } as the initial " new " set
Waiting is required in any case for correctness , whether or
not we consume the result
Depends on a bunch of forked computations
iteration counter
graph
LVar
set of "seen" node labels, initially size 0
set of "new" node labels, initially size 1
function to be applied to each node
Nothing in the new_rank set means nothing left to traverse.
Add new_rank stuff to the "seen" list
We COULD use callbacks here, but rather we're modeling what happens in the
current paper:
++" "++show st
toList is HORRIBLE
iteration counter
graph
start node
function to be applied to each node
"manually" add startNode
pass in { startNode } as the initial "new" set
Waiting is required in any case for correctness, whether or
not we consume the result
Depends on a bunch of forked computations
------------------------------------------------------------------------------
Graph algorithms
------------------------------------------------------------------------------
| A version that uses an array rather than set representation.
TODO: possibly use a better for loop:
logDbgLn 1 $" [bfs] expanding node "++show (nd,flg)++" to nbrs " ++ show myNbrs
logDbgLn 1 $" [bfs] Seeding with start vertex... "
----------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------
INEFFICIENT: this attaches a handler to ALL ivars:
logDbgLn 1$ " [maxDegreeI] Processing: "++show(nd,flg)++" with degree "++show degree
Better to just do this... wait for it to freeze and then loop.
Problem is, we need to add wait-till-frozen!
len <- ISt.getLength component
parForTiled (0,len) $ \ nd ->
C.put mc (U.length$ nbrs gr (fromIntegral nd))
----------------------------------------------------------------------------------------
A dummy per-node operation
----------------------------------------------------------------------------------------
After freezing... this is a parallel loop, but doesn't use any monotonic data.
Sequential version:
UV.forM_ vec $ \ flg ->
liftIO$ wait_clocks clocks
return ()
After freezing... this is a parallel loop, but doesn't use any monotonic data.
----------------------------------------------------------------------------------------
Maximal Independent Set
----------------------------------------------------------------------------------------
Lattice where undecided = bot, and chosen/nbrchosen are disjoint middle states
Operate on a subgraph
maximalIndependentSet :: AdjacencyGraph -> Par d s (ISet s NodeID) -- Operate on a whole graph.
Operate on a whole graph.
Here's the loop that scans through the neighbors of a node.
logDbgLn 1$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs
If we got to the end of the neighbors below us, then we are NOT disqualified:
This should never block in a single-thread execution:
| DUPLICATE CODE: IStructure version.
Operate on a whole graph.
Here's the loop that scans through the neighbors of a node.
logDbgLn 1$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs
If we got to the end of the neighbors below us, then we are NOT disqualified:
This should never block in a single-thread execution:
| Sequential version.
MIS over a preexisting, filtered subgraph
----------------------------------------------------------
Right now this uses an IStructure because it's (temporarily) better at blocking gets:
Tradeoff: we use storage proportional to the ENTIRE graph. If the subset is
very small, this is silly and we could use a sparse representation:
Here's the loop that scans through the neighbors of a node.
If we got to the end of the neighbors below us, then we are NOT disqualified:
------------------------------------------------------------------------------
Misc helpers
------------------------------------------------------------------------------
| Simple for-each loops over vector elements.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Here's a silly hack to let this executable run from different working directories:
Models social-network graphs:
----------------------------------------------------------
writeFile "/tmp/debug" (show gr)
putStrLn$ "Dumped parsed graph to /tmp/debug"
--------------------------------------
A proxy for completeness... assumes fully connected graph.
set:: Snapshot ISet NodeID <- runParThenFreezeIO par2
putStrLn$ "Connected component, set size "++show (Set.size s)
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
This version does n't get the horrible parallel slowdown of version 5 - 7 .
But alas , version 7 sequential is better .
And version 9 sequential is WAY better ( > 50X faster )
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
par : : Par d0 s0 ( )
--------------------------------------
--------------------------------------
par : : Par d0 s0 ( )
--------------------------------------
--------------------------------------
Sequential
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
This version doesn't get the horrible parallel slowdown of version 5-7.
But alas, version 7 sequential is better.
And version 9 sequential is WAY better (>50X faster)
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
par :: Par d0 s0 ()
--------------------------------------
--------------------------------------
par :: Par d0 s0 ()
--------------------------------------
--------------------------------------
Sequential
--------------------------------------
runParIO_ :: (forall s . Par d s a) -> IO ()
runParIO_ p = do runParIO p; return () | # LANGUAGE CPP , ScopedTypeVariables #
# LANGUAGE BangPatterns , RankNTypes #
import Data.Set as Set
import PBBS.FileReader
import PBBS.Timing (wait_clocks, runAndReport)
calibrate , measureFreq , commaint ,
import Control.LVish
import Control.LVish.Internal
import Control.LVish.DeepFrz (runParThenFreezeIO)
import qualified Control.LVish.SchedIdempotent as L
import Control.Monad
import Control.Monad.Par.Combinator (parFor, InclusiveRange(..))
import Control.Monad.ST
import Control.Exception
import GHC.Conc
import Data.Word
import Data.Maybe
import Data.LVar.MaxCounter as C
import Data.Time.Clock
import qualified Data.Traversable as T
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as M
import qualified Data.Vector.Storable as UV
import qualified Data.Vector.Storable.Mutable as MV
import System.Mem (performGC)
import System.Environment (getArgs)
import System.Directory
import System.Process
#if 1
import Data.LVar.PureSet as S
#else
[ 2013.07.09 ] This one still is n't terminating on 125K+
Well , maybe it 's just slow ... 5000 takes 2 seconds .
Yes , it 's literally over 100 times slower currently .
import Data.LVar.SLSet as S
#endif
import qualified Data.LVar.SLSet as SL
import Data.LVar.IStructure as ISt
import Data.LVar.NatArray as NArr
An LVar - based version of bf_traverse . As we traverse the graph ,
the results of applying f to each node accumulate in an LVar , where
- > Par ( IS.IntSet )
bf_traverse 0 _ _ seen_rank new_rank _ = do
when verbose $ prnt $ " bf_traverse finished ! seen / new size : "
+ + show ( IS.size seen_rank , )
return ( IS.union seen_rank new_rank )
bf_traverse k ! ! l_acc ! seen_rank ! ! f = do
when verbose $ prnt $ " bf_traverse call ... "
+ + show k + + " seen / new size "
+ + show ( IS.size seen_rank , )
if IS.null then return seen_rank
else do
let seen_rank ' = IS.union seen_rank new_rank
allNbr ' = IS.fold ( \i acc - > IS.union ( g V. ! i ) acc )
new_rank ' = IS.difference allNbr ' seen_rank '
parMapM _ ( \x - > fork$ do
let elem = f x
S.insert elem l_acc
when dbg $ do
st < - unsafePeekSet l_acc
prnt$ " -- > Called S.insert , node " + + show x
+ + " size is " + + show(Set.size st )
)
bf_traverse ( k-1 ) g l_acc seen_rank ' new_rank ' f
- > IO ( )
start_traverse k ! do
runParIO $ do
prnt $ " * Running on " + + show numCapabilities + + " parallel resources ... "
l_acc < - newEmptySet
fork $ S.insert ( f startNode ) l_acc
set < - bf_traverse k g l_acc IS.empty ( IS.singleton startNode ) f
prnt $ " * Done with bf_traverse ... "
let size = IS.size set
" * Waiting on " + + show size++ " set results ... "
when dbg $ do
forM _ [ 0 .. size ] $ \ s - > do
" ? Blocking on " + + show " elements to be in the set ... "
waitForSetSize s l_acc
" * Set results all available ! ( " + + show size + + " ) "
s < - consumeSet l_acc : : Par ( Set . Set WorkRet )
liftIO ( do evaluate s ; return ( ) )
prnt $ " * Finished consumeSet : "
prnt $ " * Set size : " + + show ( Set.size s )
prnt $ " * Set sum : " + + show ( Set.fold ( \(x , _ ) y - > x+y ) 0 s )
parMapM _ f l =
do parMapM f l
return ( )
-> Par (IS.IntSet)
bf_traverse 0 _ _ seen_rank new_rank _ = do
when verbose $ prnt $ "bf_traverse finished! seen/new size: "
++ show (IS.size seen_rank, IS.size new_rank)
return (IS.union seen_rank new_rank)
bf_traverse k !g !l_acc !seen_rank !new_rank !f = do
when verbose $ prnt $"bf_traverse call... "
++ show k ++ " seen/new size "
++ show (IS.size seen_rank, IS.size new_rank)
if IS.null new_rank
then return seen_rank
else do
let seen_rank' = IS.union seen_rank new_rank
allNbr' = IS.fold (\i acc -> IS.union (g V.! i) acc)
IS.empty new_rank
new_rank' = IS.difference allNbr' seen_rank'
parMapM_ (\x -> fork$ do
let elem = f x
S.insert elem l_acc
when dbg $ do
st <- unsafePeekSet l_acc
prnt$ " --> Called S.insert, node "++show x
++" size is "++show(Set.size st)
)
bf_traverse (k-1) g l_acc seen_rank' new_rank' f
-> IO ()
start_traverse k !g startNode f = do
runParIO $ do
prnt $ " * Running on " ++ show numCapabilities ++ " parallel resources..."
l_acc <- newEmptySet
fork $ S.insert (f startNode) l_acc
set <- bf_traverse k g l_acc IS.empty (IS.singleton startNode) f
prnt $ " * Done with bf_traverse..."
let size = IS.size set
prnt$ " * Waiting on "++show size++" set results..."
when dbg $ do
forM_ [0..size] $ \ s -> do
prnt$ " ? Blocking on "++show s++" elements to be in the set..."
waitForSetSize s l_acc
prnt$ " * Set results all available! (" ++ show size ++ ")"
s <- consumeSet l_acc :: Par (Set.Set WorkRet)
liftIO (do evaluate s; return ())
prnt $ " * Finished consumeSet:"
prnt $ " * Set size: " ++ show (Set.size s)
prnt $ " * Set sum: " ++ show (Set.fold (\(x,_) y -> x+y) 0 s)
parMapM_ f l =
do parMapM f l
return ()
-}
bfs_async :: AdjacencyGraph -> NodeID -> Par d s (ISet s NodeID)
bfs_async gr@(AdjacencyGraph vvec evec) start = do
st <- S.newFromList [start]
S.forEach st $ \ nd -> do
logDbgLn 1 $" [bfs] expanding node "++show nd++" to nbrs " ++ show (nbrs gr nd)
forVec (nbrs gr nd) (`S.insert` st)
return st
T.traverse _ ( ` S.insert ` st ) ( nbrs gr nd )
bfs_async_arr :: AdjacencyGraph -> NodeID -> Par d s (IStructure s Bool)
bfs_async_arr gr@(AdjacencyGraph vvec evec) start = do
arr <- newIStructure (U.length vvec)
let callback nd bool = do
let myNbrs = nbrs gr (fromIntegral nd)
logDbgLn 1 $" [bfs] expanding node "++show (nd,bool)++" to nbrs " ++ show myNbrs
forVec myNbrs (\nbr -> ISt.put_ arr (fromIntegral nbr) True)
ISt.forEachHP Nothing arr callback
logDbgLn 1 $" [bfs] Seeding with start vertex... "
ISt.put_ arr (fromIntegral start) True
return arr
| Same , but with NatArray .
bfs_async_arr2 :: AdjacencyGraph -> NodeID -> Par d s (NatArray s Word8)
bfs_async_arr2 gr@(AdjacencyGraph vvec evec) start = do
arr <- newNatArray (U.length vvec)
let callback nd flg = do
let myNbrs = nbrs gr (fromIntegral nd)
forVec myNbrs (\nbr -> NArr.put arr (fromIntegral nbr) 1)
NArr.forEach arr callback
NArr.put arr (fromIntegral start) 1
return arr
A simple FOLD operation .
maxDegreeS :: AdjacencyGraph -> (ISet s NodeID) -> Par d s (MaxCounter s)
maxDegreeS gr component = do
mc <- newMaxCounter 0
S.forEach component $ \ nd ->
C.put mc (U.length$ nbrs gr nd)
return mc
maxDegreeN :: AdjacencyGraph -> (NatArray s Word8) -> Par d s (MaxCounter s)
maxDegreeN gr component = do
mc <- newMaxCounter 0
NArr.forEach component $ \ nd flg ->
when (flg == 1) $
C.put mc (U.length$ nbrs gr (fromIntegral nd))
return mc
maxDegreeI :: AdjacencyGraph -> (IStructure s Word8) -> Par d s (MaxCounter s)
maxDegreeI gr component = do
mc <- newMaxCounter 0
ISt.forEachHP Nothing component $ \ nd flg -> do
when (flg == 1) $ do
let degree = U.length$ nbrs gr (fromIntegral nd)
C.put mc degree
when ( flg = = 1 ) $
return mc
workEachNode : : ( NatArray s Word8 ) - > ( Word8 - > Par d s ( ) ) - > Par d s ( MaxCounter s )
workEachNode :: Word64 -> (NatArray s Word8) -> Par d s ()
workEachNode clocks component = do
NArr.forEach component $ \ nd flg ->
when (flg == 1) $ do
liftIO$ wait_clocks clocks
return ()
workEachVec :: Word64 -> UV.Vector Word8 -> Par d s ()
workEachVec clocks vec = do
np <- liftIO$ getNumCapabilities
for _ ( 0,UV.length vec ) $ \ ix - >
parForTiled ( np*4 ) ( 0,UV.length vec ) $ \ ix - >
parForSimple ( 0,UV.length vec ) $ \ ix - >
parForTree (0,UV.length vec) $ \ ix ->
let flg = vec UV.! ix in
when (flg == 1) $ do
liftIO$ wait_clocks clocks
return ()
when ( flg = = 1 ) $ do
workEachNodeI :: Word64 -> (IStructure s Word8) -> Par d s ()
workEachNodeI clocks component = do
ISt.forEachHP Nothing component $ \ nd flg ->
when (flg == 1) $ do
liftIO$ wait_clocks clocks
return ()
workEachVecMayb :: Word64 -> V.Vector (Maybe Word8) -> Par d s ()
workEachVecMayb clocks vec = do
np <- liftIO$ getNumCapabilities
for _ ( 0,UV.length vec ) $ \ ix - >
parForTiled ( np*4 ) ( 0,UV.length vec ) $ \ ix - >
parForSimple ( 0,UV.length vec ) $ \ ix - >
parForTree (0, V.length vec) $ \ ix ->
let flg = vec V.! ix in
when (flg == Just 1) $ do
liftIO$ wait_clocks clocks
return ()
flag_UNDECIDED :: Word8
flag_CHOSEN :: Word8
flag_NBRCHOSEN :: Word8
flag_UNDECIDED = 0
flag_CHOSEN = 1
flag_NBRCHOSEN = 2
# INLINE maximalIndependentSet #
maximalIndependentSet parFor gr@(AdjacencyGraph vvec evec) = do
For each vertex , we record whether it is CHOSEN , not chosen , or undecided :
let numVerts = U.length vvec
flagsArr :: NatArray s Word8 <- newNatArray numVerts
let
loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
if nbrInd > selfInd
then thisNodeWins
else do
logDbgLn 1 (" [MIS] ! Getting on nbrInd "++show nbrInd)
nbrFlag <- NArr.get flagsArr (fromIntegral nbrInd)
logDbgLn 1 (" [MIS] ! Get completed on nbrInd "++show nbrInd)
if nbrFlag == flag_CHOSEN
then NArr.put flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = logDbgLn 1 (" [MIS] ! Node chosen: "++show selfInd) >>
NArr.put flagsArr (fromIntegral selfInd) flag_CHOSEN
parFor (0,numVerts) $ \ ndIx -> do
let nds = nbrs gr (fromIntegral ndIx)
logDbgLn 1 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show
loop (U.length nds) nds ndIx 0
return flagsArr
maximalIndependentSet2 parFor gr@(AdjacencyGraph vvec evec) = do
logDbgLn 1$ " [MIS] Beginning maximalIndependentSet / Istructures"
For each vertex , we record whether it is CHOSEN , not chosen , or undecided :
let numVerts = U.length vvec
flagsArr <- newIStructure numVerts
let
loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
if nbrInd > selfInd
then thisNodeWins
else do
logDbgLn 1 (" [MIS] ! Getting on nbrInd "++show nbrInd)
nbrFlag <- ISt.get flagsArr (fromIntegral nbrInd)
logDbgLn 1 (" [MIS] ! Get completed on nbrInd "++show nbrInd)
if nbrFlag == flag_CHOSEN
then ISt.put_ flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = logDbgLn 1 (" [MIS] ! Node chosen: "++show selfInd) >>
ISt.put_ flagsArr (fromIntegral selfInd) flag_CHOSEN
parFor (0,numVerts) $ \ ndIx -> do
let nds = nbrs gr (fromIntegral ndIx)
logDbgLn 1 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show
loop (U.length nds) nds ndIx 0
return flagsArr
maximalIndependentSet3 :: AdjacencyGraph -> (U.Vector Word8)
maximalIndependentSet3 gr@(AdjacencyGraph vvec evec) = U.create $ do
let numVerts = U.length vvec
flagsArr <- M.replicate numVerts 0
let loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
if nbrInd > selfInd
then thisNodeWins
else do
nbrFlag <- M.read flagsArr (fromIntegral nbrInd)
if nbrFlag == flag_CHOSEN
then M.write flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = M.write flagsArr (fromIntegral selfInd) flag_CHOSEN
for_ (0,numVerts) $ \ ndIx -> do
let nds = nbrs gr (fromIntegral ndIx)
loop (U.length nds) nds ndIx 0
return flagsArr
| Sequential version on NatArray ...
maximalIndependentSet3B :: AdjacencyGraph -> (UV.Vector Word8) -> (UV.Vector Word8)
maximalIndependentSet3B gr@(AdjacencyGraph vvec evec) vec = UV.create $ do
let numVerts = U.length vvec
flagsArr <- MV.replicate numVerts 0
let loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
if nbrInd > selfInd
then thisNodeWins
else do
nbrFlag <- MV.read flagsArr (fromIntegral nbrInd)
if nbrFlag == flag_CHOSEN
then MV.write flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = MV.write flagsArr (fromIntegral selfInd) flag_CHOSEN
for_ (0,numVerts) $ \ ndIx ->
when (vec UV.! ndIx == 1) $ do
let nds = nbrs gr (fromIntegral ndIx)
loop (U.length nds) nds ndIx 0
return flagsArr
maximalIndependentSet4 :: AdjacencyGraph -> (NatArray s Word8) -> Par d s (IStructure s Word8)
maximalIndependentSet4 gr@(AdjacencyGraph vvec evec) vertSubset = do
let numVerts = U.length vvec
flagsArr <- newIStructure numVerts
let
loop !numNbrs !nbrs !selfInd !i
| i == numNbrs = thisNodeWins
| otherwise = do
Find our Nbr 's NodeID
selfInd' = fromIntegral selfInd
if nbrInd > selfInd
then thisNodeWins
else do
nbrFlag <- ISt.get flagsArr (fromIntegral nbrInd)
if nbrFlag == flag_CHOSEN
then ISt.put_ flagsArr selfInd' flag_NBRCHOSEN
else loop numNbrs nbrs selfInd (i+1)
where
thisNodeWins = ISt.put_ flagsArr (fromIntegral selfInd) flag_CHOSEN
NArr.forEach vertSubset $ \ ndIx _ ->
let nds = nbrs gr (fromIntegral ndIx) in
loop (U.length nds) nds ndIx 0
return flagsArr
# INLINE forVec #
forVec :: U.Unbox a => U.Vector a -> (a -> Par d s ()) -> Par d s ()
forVec vec fn = loop 0
where
len = U.length vec
loop i | i == len = return ()
| otherwise = fn (U.unsafeIndex vec i) >>
loop (i+1)
type ParFor d s = (Int,Int) -> (Int -> Par d s ()) -> Par d s ()
Main Program
main = do
putStrLn "USAGE: ./bfs_lvish <version> <topo> <graphSize>"
putStrLn "USAGE: Topo must be one of: grid rmat rand chain"
putStrLn "USAGE: Version must be one of: "
putStrLn "USAGE: bfsS bfsN bfsI"
putStrLn "USAGE: misN1 misN2 misN3 misI3 misSeq"
args <- getArgs
let (version,topo,size,wrksize::Double) =
case args of
[ver,tp,s,w] -> (ver, tp, read s, read w)
[ver,tp,s] -> (ver, tp, read s, 0)
[ver,tp] -> (ver, tp, 1000, 0)
[ver] -> (ver, "grid", 1000, 0)
[] -> ("bfsN","grid",1000, 0)
oth -> error "Too many command line args!"
existD d = do b <- doesDirectoryExist d
return$ if b then (Just d) else Nothing
pbbsdirs <- fmap catMaybes $ mapM existD [ "../pbbs"
, "../../pbbs"
, "../../../pbbs"
, "../../../../pbbs"]
let pbbsroot = case pbbsdirs of
[] -> error "PBBS dir not found! Is the submodule checked out?"
hd:_ -> hd
datroot = pbbsroot++"/breadthFirstSearch/graphData/data/"
The PBBS Makefile knowns how to build the common graphs :
buildPBBSdat file = do
origdir <- getCurrentDirectory
setCurrentDirectory datroot
b <- doesFileExist file
unless b $ do
putStrLn "Input file does not exist! Building..."
system$ "make "++file
return ()
setCurrentDirectory origdir
file <- case topo of
"grid" -> do let f = "3Dgrid_J_"++show size
buildPBBSdat f
return (datroot ++ f)
"rmat" -> do let f = "rMatGraph_J_5_"++show size
buildPBBSdat f
return (datroot ++ f)
"rand" -> do let f = "randLocalGraph_J_5_"++show size
buildPBBSdat f
return (datroot ++ f)
"chain" -> do let f = "chain_"++show size
p = datroot ++ f
b <- doesFileExist p
unless b $ do
putStrLn$"Generating chain graph in "++p
system "ghc -threaded gen_chains_graph.hs -o ./gen_chains_graph.exe"
system$ "./gen_chains_graph.exe "++show size++" > "++p
return ()
return p
_ -> error$"Unknown graph topology: "++topo
putStrLn$"Running config: "++show(version,topo,size)
wd <- getCurrentDirectory
putStrLn$ "Working dir: "++wd
putStrLn$ "Reading file: "++file
t0 <- getCurrentTime
gr <- readAdjacencyGraph file
t1 <- getCurrentTime
let numVerts = U.length (vertOffets gr)
putStrLn$ "graph read ("++show (diffUTCTime t1 t0)++
"): verts,edges: "++show (numVerts, U.length (allEdges gr))
putStrLn$ "max vert off "++show (U.foldl1 max (vertOffets gr))
putStrLn$ "max edge target "++show (U.foldl1 max (allEdges gr))
t2 <- getCurrentTime
putStrLn$ "time for those simple folds: "++show (diffUTCTime t2 t1)
performGC
runAndReport $ \ clocks_per_micro ->
let amountWork = (round (wrksize * clocks_per_micro)) in
case version of
"bfsS" -> do
putStrLn " ! Version 2: BFS only, with sets "
par2 : : Par d0 s0 ( ISet s0 NodeID )
par2 : : Par d0 s0 ( )
par2 = do comp <- bfs_async gr 0
return comp
_ <- runParIO_ par2
let ISetSnap s = set
return ()
"bfsI" -> do putStrLn " ! Version 3: BFS only, with IStructures "
par2 : : Par d0 s0 ( ISet s0 NodeID )
par3 :: Par d0 s0 (IStructure s0 Bool)
par3 = bfs_async_arr gr 0
_ <- runParIO_ par3
return ()
"bfsN" -> do putStrLn " ! Version 4: BFS only, with NatArrays "
par2 : : Par d0 s0 ( ISet s0 NodeID )
par4 :: Par d0 s0 (NatArray s0 Word8)
par4 = bfs_async_arr2 gr 0
_ <- runParIO_ par4
return ()
" misN1 " - > do
putStrLn " ! Version 5 : MIS only , with NatArrays / parForSimple "
let par : : Par d0 s0 ( NatArray s0 Word8 )
par = maximalIndependentSet parForSimple gr
# ifdef DEBUG_CHECKS
( x : : ) < - runParThenFreezeIO par
putStrLn$ " MIS : result prefix : " + + show ( UV.take 100 x )
putStrLn$ " MIS : number of vertices in result : " + + show ( UV.sum ( UV.filter (= = 1 ) x ) )
# else
_ < - runParIO _ par
# endif
return ( )
" misN2 " - > do
putStrLn " ! Version 6 : MIS only , with NatArrays / parForTree "
let par : : Par d0 s0 ( NatArray s0 Word8 )
par = maximalIndependentSet parForTree gr
_ < - runParIO _ par
return ( )
" misN3 " - > do
putStrLn " ! Version 7 : MIS only , with NatArrays / parForL "
let par : : Par d0 s0 ( NatArray s0 Word8 )
par = maximalIndependentSet parForL gr
_ < - runParIO _ par
return ( )
" misI3 " - > do
putStrLn " ! Version 8 : MIS only , with IStructures / parForL "
let par : : Par d0 s0 ( IStructure s0 Word8 )
par = maximalIndependentSet2 parForL gr
_ < - runParIO _ par
return ( )
" misSeq " - > do
putStrLn " ! Version 9 : MIS only , sequential "
evaluate $ maximalIndependentSet3 gr
return ( )
" bfsN_misI " - > do
putStrLn " ! Version 10 : BFS and then MIS w/ NatArrays / IStructure "
let par : : Par d0 s0 ( IStructure s0 Word8 )
par = do < - bfs_async_arr2 gr 0
maximalIndependentSet4 gr natarr
_ < - runParIO _ par
return ( )
" bfsN_misI_deg " - > do
putStrLn " ! Version 11 : BFS , MIS , and "
let par : : Par d0 s0 ( MaxCounter s0 )
par = do < - bfs_async_arr2 gr 0
narr2 < - maximalIndependentSet4 gr natarr
maxDegreeI gr narr2
mx < - runParThenFreezeIO par
putStrLn$ " degree in MIS was : " + + show(mx::Int )
" bfsN_work " - > do
putStrLn " ! Version 12 : BFS and per - vertex work "
let par : : Par d0 s0 ( )
par = do < - bfs_async_arr2 gr 0
workEachNode amountWork
_ < - runParIO _ par
return ( )
" bfsN_barrier_work " - > do
putStrLn " ! Version 13 : BFS , barrier , and per - vertex work "
par = bfs_async_arr2 gr 0
NatArraySnap vec < - runParThenFreezeIO par
runParIO _ $ workEachVec amountWork
return ( )
" misI_work " - > do
putStrLn " ! Version 14 : MIS and per - vertex work "
let par : : Par d0 s0 ( )
par = do istrct < - maximalIndependentSet2 parForL gr
workEachNodeI amountWork
_ < - runParIO _ par
return ( )
" misI_barrier_work " - > do
putStrLn " ! Version 15 : "
par = maximalIndependentSet2 parForL gr
IStructSnap vec < - runParThenFreezeIO par
runParIO _ $ workEachVecMayb amountWork
return ( )
" bfsN_misI_work " - > do
putStrLn " ! Version 16 : "
let par : : Par d0 s0 ( )
par = do < - bfs_async_arr2 gr 0
istrct < - maximalIndependentSet4 gr natarr
workEachNodeI amountWork
_ < - runParIO _ par
return ( )
" bfsN_barrier_misI_work " - > do
putStrLn " ! Version 17 : "
let par = bfs_async_arr2 gr 0
NatArraySnap vec < - runParThenFreezeIO par
runParIO _ $ workEachVec amountWork vec2
return ( )
" ? " - > do
putStrLn " ! Version 1 : work in progress testing combinations of graph ops ... "
let par1 : : Par d0 s0 ( MaxCounter s0 , ISet s0 NodeID )
par1 = do component < - bfs_async gr 0
liftIO$ " Got component ... "
mc < - maxDegreeS gr component
return ( mc , component )
( maxdeg::Int , set : : Snapshot ISet NodeID ) < - runParThenFreezeIO2 par1
putStrLn$ " Processing finished , max degree was : " + + show maxdeg
let ISetSnap s = set
putStrLn$ " Connected component , set size " + + show ( Set.size s )
"misN1" -> do
putStrLn " ! Version 5: MIS only, with NatArrays / parForSimple"
let par :: Par d0 s0 (NatArray s0 Word8)
par = maximalIndependentSet parForSimple gr
#ifdef DEBUG_CHECKS
NatArraySnap (x :: UV.Vector Word8) <- runParThenFreezeIO par
putStrLn$ "MIS: result prefix: "++show (UV.take 100 x)
putStrLn$ "MIS: number of vertices in result: "++show (UV.sum (UV.filter (==1) x))
#else
_ <- runParIO_ par
#endif
return ()
"misN2" -> do
putStrLn " ! Version 6: MIS only, with NatArrays / parForTree"
let par :: Par d0 s0 (NatArray s0 Word8)
par = maximalIndependentSet parForTree gr
_ <- runParIO_ par
return ()
"misN3" -> do
putStrLn " ! Version 7: MIS only, with NatArrays / parForL"
let par :: Par d0 s0 (NatArray s0 Word8)
par = maximalIndependentSet parForL gr
_ <- runParIO_ par
return ()
"misI3" -> do
putStrLn " ! Version 8: MIS only, with IStructures / parForL"
let par :: Par d0 s0 (IStructure s0 Word8)
par = maximalIndependentSet2 parForL gr
_ <- runParIO_ par
return ()
"misSeq" -> do
putStrLn " ! Version 9: MIS only, sequential"
evaluate $ maximalIndependentSet3 gr
return ()
"bfsN_misI" -> do
putStrLn " ! Version 10: BFS and then MIS w/ NatArrays/IStructure"
let par :: Par d0 s0 (IStructure s0 Word8)
par = do natarr <- bfs_async_arr2 gr 0
maximalIndependentSet4 gr natarr
_ <- runParIO_ par
return ()
"bfsN_misI_deg" -> do
putStrLn " ! Version 11: BFS, MIS, and maxDegree"
let par :: Par d0 s0 (MaxCounter s0)
par = do natarr <- bfs_async_arr2 gr 0
narr2 <- maximalIndependentSet4 gr natarr
maxDegreeI gr narr2
mx <- runParThenFreezeIO par
putStrLn$ "Max degree in MIS was: "++show(mx::Int)
"bfsN_work" -> do
putStrLn " ! Version 12: BFS and per-vertex work"
let par :: Par d0 s0 ()
par = do natarr <- bfs_async_arr2 gr 0
workEachNode amountWork natarr
_ <- runParIO_ par
return ()
"bfsN_barrier_work" -> do
putStrLn " ! Version 13: BFS, barrier, and per-vertex work"
par = bfs_async_arr2 gr 0
NatArraySnap vec <- runParThenFreezeIO par
runParIO_ $ workEachVec amountWork vec
return ()
"misI_work" -> do
putStrLn " ! Version 14: MIS and per-vertex work"
let par :: Par d0 s0 ()
par = do istrct <- maximalIndependentSet2 parForL gr
workEachNodeI amountWork istrct
_ <- runParIO_ par
return ()
"misI_barrier_work" -> do
putStrLn " ! Version 15: "
par = maximalIndependentSet2 parForL gr
IStructSnap vec <- runParThenFreezeIO par
runParIO_ $ workEachVecMayb amountWork vec
return ()
"bfsN_misI_work" -> do
putStrLn " ! Version 16: "
let par :: Par d0 s0 ()
par = do natarr <- bfs_async_arr2 gr 0
istrct <- maximalIndependentSet4 gr natarr
workEachNodeI amountWork istrct
_ <- runParIO_ par
return ()
"bfsN_barrier_misI_work" -> do
putStrLn " ! Version 17: "
let par = bfs_async_arr2 gr 0
NatArraySnap vec <- runParThenFreezeIO par
runParIO_ $ workEachVec amountWork vec2
return ()
"?" -> do
putStrLn " ! Version 1: work in progress testing combinations of graph ops..."
let par1 :: Par d0 s0 (MaxCounter s0, ISet s0 NodeID)
par1 = do component <- bfs_async gr 0
liftIO$ putStrLn "Got component..."
mc <- maxDegreeS gr component
return (mc,component)
(maxdeg::Int, set:: Snapshot ISet NodeID) <- runParThenFreezeIO2 par1
putStrLn$ "Processing finished, max degree was: "++show maxdeg
let ISetSnap s = set
putStrLn$ "Connected component, set size "++show (Set.size s)
-}
oth -> error$"Unknown benchmark mode "++oth
putStrLn$ "Done"
Unsafe version , fix this :
runParIO_ :: (Par d s a) -> IO ()
runParIO_ (WrapPar p) = L.runParIO p >> return ()
|
f5e18679b10a3a5e61484bf3bfff4036b46f34d40df4bd9a9e43a9756ecb0222 | racketscript/racketscript | for.rkt | #lang racket
(define (fn lst)
(for ([v lst])
(displayln v)))
(fn (list 1 2 3 4))
;; string sequences
;; needs unsafe-string-length
(for ([c "string"])
(displayln c))
(for ([c (string->list "string")])
(displayln c))
| null | https://raw.githubusercontent.com/racketscript/racketscript/11400fdd9d11541e7dd40c536c015677a7fa4181/tests/basic/for.rkt | racket | string sequences
needs unsafe-string-length | #lang racket
(define (fn lst)
(for ([v lst])
(displayln v)))
(fn (list 1 2 3 4))
(for ([c "string"])
(displayln c))
(for ([c (string->list "string")])
(displayln c))
|
00838acd0984202621c5ec50167c175f12b6f4492d9ed6f40e13c63ce7ee43d4 | caadxyz/caad4lisp | autolisp-comm.lisp | (in-package :caad4lisp)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; autolisp command compatibility
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; BREAK
(defun Command-Break(entity p0 p1 )
(if (= Conf-AutoCAD-Version "2015+" )
(command-s ".BREAK" entity "F" p0 p1 )
(command ".BREAK" entity p0 p1 )
)
)
| null | https://raw.githubusercontent.com/caadxyz/caad4lisp/393eaa7893bdbf307a3615573fe22a8c1e2b9412/src/autolisp-comm.lisp | lisp |
autolisp command compatibility
BREAK | (in-package :caad4lisp)
(defun Command-Break(entity p0 p1 )
(if (= Conf-AutoCAD-Version "2015+" )
(command-s ".BREAK" entity "F" p0 p1 )
(command ".BREAK" entity p0 p1 )
)
)
|
846230ac270d298216412df9162b67b12d818cc895186951f6efbd24f9fd4e4c | MondayMorningHaskell/Monads | Functors.hs | module Functors where
import Data.Maybe (mapMaybe)
import qualified Data.Map as M
-- Motivating Examples!
-- Simple String conversion. It might fail, so it returns Maybe
tupleFromInputString :: String -> Maybe (String, String, Int)
tupleFromInputString input = if length stringComponents /= 3
then Nothing
else Just (stringComponents !! 0, stringComponents !! 1, age)
where
stringComponents = words input
age = read (stringComponents !! 2) :: Int
-- An alternative to using a tuple (String, String, Int)
data Person = Person
{ firstName :: String
, lastName :: String
, age :: Int
}
personFromTuple :: (String, String, Int) -> Person
personFromTuple (fName, lName, age) = Person fName lName age
Converting between the two formats
convertTuple :: Maybe (String, String, Int) -> Maybe Person
convertTuple Nothing = Nothing
convertTuple (Just t) = Just (personFromTuple t)
-- Could not use `convertTuple` with the results of this function!
Would have to write a new function of type [ ( String , String , Int ) ] - > [ Person ]
listFromInputString :: String -> [(String, String, Int)]
listFromInputString contents = mapMaybe tupleFromInputString (lines contents)
{- Functor Definitions:
class Functor f where
fmap :: (a -> b) -> f a -> f b
instance Functor [] where
fmap = map
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right y) = Right (f y)
-}
-- TODO: This function needs a type signature!
-- Make it as general as possible!
convertTupleFunctor = fmap personFromTuple
-- Making our own Functor
data GovDirectory a = GovDirectory {
mayor :: a,
interimMayor :: Maybe a,
cabinet :: M.Map String a,
councilMembers :: [a]
}
instance Functor GovDirectory where
-- TODO: Write out this functor instance!
fmap f oldDirectory = undefined
oldDirectory :: GovDirectory (String, String, Int)
oldDirectory = GovDirectory
("John", "Doe", 46)
Nothing
(M.fromList
[ ("Treasurer", ("Timothy", "Houston", 51))
, ("Historian", ("Bill", "Jefferson", 42))
, ("Sheriff", ("Susan", "Harrison", 49))
])
([("Sharon", "Stevens", 38), ("Christine", "Washington", 47)])
-- TODO: How can we do this in general terms, since we have
-- a Functor instance?
newDirectory :: GovDirectory Person
newDirectory = undefined
| null | https://raw.githubusercontent.com/MondayMorningHaskell/Monads/41bda26e0199c1c0734bd2c8c45f33b880ac3122/src/Functors.hs | haskell | Motivating Examples!
Simple String conversion. It might fail, so it returns Maybe
An alternative to using a tuple (String, String, Int)
Could not use `convertTuple` with the results of this function!
Functor Definitions:
class Functor f where
fmap :: (a -> b) -> f a -> f b
instance Functor [] where
fmap = map
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right y) = Right (f y)
TODO: This function needs a type signature!
Make it as general as possible!
Making our own Functor
TODO: Write out this functor instance!
TODO: How can we do this in general terms, since we have
a Functor instance? | module Functors where
import Data.Maybe (mapMaybe)
import qualified Data.Map as M
tupleFromInputString :: String -> Maybe (String, String, Int)
tupleFromInputString input = if length stringComponents /= 3
then Nothing
else Just (stringComponents !! 0, stringComponents !! 1, age)
where
stringComponents = words input
age = read (stringComponents !! 2) :: Int
data Person = Person
{ firstName :: String
, lastName :: String
, age :: Int
}
personFromTuple :: (String, String, Int) -> Person
personFromTuple (fName, lName, age) = Person fName lName age
Converting between the two formats
convertTuple :: Maybe (String, String, Int) -> Maybe Person
convertTuple Nothing = Nothing
convertTuple (Just t) = Just (personFromTuple t)
Would have to write a new function of type [ ( String , String , Int ) ] - > [ Person ]
listFromInputString :: String -> [(String, String, Int)]
listFromInputString contents = mapMaybe tupleFromInputString (lines contents)
convertTupleFunctor = fmap personFromTuple
data GovDirectory a = GovDirectory {
mayor :: a,
interimMayor :: Maybe a,
cabinet :: M.Map String a,
councilMembers :: [a]
}
instance Functor GovDirectory where
fmap f oldDirectory = undefined
oldDirectory :: GovDirectory (String, String, Int)
oldDirectory = GovDirectory
("John", "Doe", 46)
Nothing
(M.fromList
[ ("Treasurer", ("Timothy", "Houston", 51))
, ("Historian", ("Bill", "Jefferson", 42))
, ("Sheriff", ("Susan", "Harrison", 49))
])
([("Sharon", "Stevens", 38), ("Christine", "Washington", 47)])
newDirectory :: GovDirectory Person
newDirectory = undefined
|
2cc83bebdb63ef8b10ef385f81cb8b43cb2770446b59f7517a3b686add9d7989 | LispEngineer/aiband | fov.clj | Copyright 2016 , Jr.
symbolics _ at _ lisp.engineer
;; /
;;
Aiband - The Artificial Intelligence Roguelike
;;;; Field of view / Line of sight module
;; Calculates line of sight using a single parameter, distance.
;; As we are on a map where diagonal movement is the same as lateral,
;; you can see that distance in a square around you.
Distance 1 is a 3x3 square , Distance 2 is a 5x5 square , etc .
( Distance * 2 + 1 ) ^ 2 .
This is the Chebyshev distance , since movement on diagonals is
;; treated as on horiz/vertical.
;;
;;
;; We calculate the edges of the square, and then for each edge
;; coordinate, we calculate all the points from your current point
out to that edge , using a Bresenham algorithm .
( )
;;
;; Finally, and inefficiently, we traverse each of these "rays"
;; outward revealing terrain until we reach a coordinate that
;; blocks further visibility, and then we stop.
;; This is somewhat inefficient as the number of coordinates traversed
;; is now proportional to (perimeter * distance) =
( distance * 2 + 1 ) * 4 - 2 ) * distance
( 8 * distance + 2 ) * distance
8 * distance ^ 2 + 2 * distance
so in the worst we traverse every possibly visible coordinate ~8 times .
(ns aiband.fov
(:require [aiband.v2d :refer :all :reload true]
[aiband.clrjvm :refer :all :reload true]))
(defn box-coords
"Gets a seq of [x y] coordinates around [0 0] representing the
perimeter of a box 'distance' units from the center. These are not
in any particular order."
[dist]
(if (<= dist 0)
;; Degenerate case of just the origin
[[0 0]]
(let [[start-x end-x] [(- dist) dist]
[start-y end-y] [(- dist) dist]]
(concat
;; Bottom of perimeter starting at left
(map (fn [x] [x start-y]) (range start-x (inc end-x)))
;; Top of perimiter starting at left
(map (fn [x] [x end-y]) (range start-x (inc end-x)))
;; Left of perimeter - don't duplicate top or bottom
(map (fn [y] [start-x y]) (range (inc start-y) end-y))
;; Right of perimeter
(map (fn [y] [end-x y]) (range (inc start-y) end-y))))))
;; Based on algorithm here:
;; /~introcs/Fa11/notes/08.3_MoreGraphics/Bresenham.html?CurrentSlide=4
;; This seems to give a more pleasing line.
; var dy = y2-y1
; var dx = x2-x1
; var d = 2*dy - dx
; var x = x1
; var y = y1
; while (x <= x2) {
; Draw pixel at (x,y)
x++
; if( d<0 )
; d += dy + dy
; else {
; d += 2*(dy-dx)
y++
; }
; }
;; TODO: MEMOIZE ME
(defn origin-line-first-octant
"Gives a seq of [x y] coordinates, including the origin, from [0 0] to
the provided coordinate, which must be in the first octant
(y <= x, x > 0, y > 0)."
[[to-x to-y]]
(loop [x 0 y 0
d (- (* 2 to-y) to-x)
coords []] ; Our return value
(if (> x to-x)
;; We're done
coords
;; Pick a Y coord per error and draw that pixel
(if (< d 0)
;; Go up one in Y next time
(recur (inc x) y
(+ d to-y to-y)
(conj coords [x y]))
;; Stay at Y the next time
(recur (inc x) (inc y)
(+ d (* 2 (- to-y to-x)))
(conj coords [x y]))))))
;; TODO: MEMOIZE ME
(defn origin-line
"Handles coordinates of a line to any coordinate from the origin,
regardless of octant, by reflecting it (possibly several times)
to the first octant."
[[x y :as coords]]
(cond
First octant
(and (>= x 0) (>= y 0) (<= y x))
(origin-line-first-octant coords)
Second octant - swap x & y coords
(and (>= x 0) (>= y 0)) ; and y > x
(mapv (fn [[x y]] [y x]) (origin-line [y x]))
second or third QUADRANT
(< x 0)
(mapv (fn [[x y]] [(- x) y]) (origin-line [(- x) y]))
fourth QUADRANT
:else ; assert (< y 0)
(mapv (fn [[x y]] [x (- y)]) (origin-line [x (- y)]))
))
(defn line
"Gives coordinates of all points between the specified coordinates.
Handles it by translating the line to have a
first coordinate of [0 0] and then
drawing an origin-based line, and then translating it back."
[[x1 y1] [x2 y2]]
(mapv (fn [[x y]] [(+ x x1) (+ y y1)])
(origin-line [(- x2 x1) (- y2 y1)])))
;; TODO: MEMOIZE ME
(defn origin-los-rays
"Returns a seq of a seq containing all the line of sight ray
coordinates (2-vectors) from
the origin out to the specified distance.
You can take the origin out of this by doing (mapv rest (origin-los-rays dist))."
[dist]
(mapv (fn [coord] (origin-line coord)) (box-coords dist)))
(defn los-rays
"Returns a seq of a seq containing all the line of sight ray
coordinates (2-vectors) from
the specified coordinate out to the specified distance.
You can take the original coordinate out of this by doing
(mapv rest <result>) on the return value of this function."
[[o-x o-y] dist]
(mapv
(fn [ray] (mapv (fn [[x y]] [(+ x o-x) (+ y o-y)]) ray))
(origin-los-rays dist)))
| null | https://raw.githubusercontent.com/LispEngineer/aiband/c29181401ba8767099aac52120651f99d36af7a3/Assets/aiband/fov.clj | clojure | /
Field of view / Line of sight module
Calculates line of sight using a single parameter, distance.
As we are on a map where diagonal movement is the same as lateral,
you can see that distance in a square around you.
treated as on horiz/vertical.
We calculate the edges of the square, and then for each edge
coordinate, we calculate all the points from your current point
Finally, and inefficiently, we traverse each of these "rays"
outward revealing terrain until we reach a coordinate that
blocks further visibility, and then we stop.
This is somewhat inefficient as the number of coordinates traversed
is now proportional to (perimeter * distance) =
Degenerate case of just the origin
Bottom of perimeter starting at left
Top of perimiter starting at left
Left of perimeter - don't duplicate top or bottom
Right of perimeter
Based on algorithm here:
/~introcs/Fa11/notes/08.3_MoreGraphics/Bresenham.html?CurrentSlide=4
This seems to give a more pleasing line.
var dy = y2-y1
var dx = x2-x1
var d = 2*dy - dx
var x = x1
var y = y1
while (x <= x2) {
Draw pixel at (x,y)
if( d<0 )
d += dy + dy
else {
d += 2*(dy-dx)
}
}
TODO: MEMOIZE ME
Our return value
We're done
Pick a Y coord per error and draw that pixel
Go up one in Y next time
Stay at Y the next time
TODO: MEMOIZE ME
and y > x
assert (< y 0)
TODO: MEMOIZE ME | Copyright 2016 , Jr.
symbolics _ at _ lisp.engineer
Aiband - The Artificial Intelligence Roguelike
Distance 1 is a 3x3 square , Distance 2 is a 5x5 square , etc .
( Distance * 2 + 1 ) ^ 2 .
This is the Chebyshev distance , since movement on diagonals is
out to that edge , using a Bresenham algorithm .
( )
( distance * 2 + 1 ) * 4 - 2 ) * distance
( 8 * distance + 2 ) * distance
8 * distance ^ 2 + 2 * distance
so in the worst we traverse every possibly visible coordinate ~8 times .
(ns aiband.fov
(:require [aiband.v2d :refer :all :reload true]
[aiband.clrjvm :refer :all :reload true]))
(defn box-coords
"Gets a seq of [x y] coordinates around [0 0] representing the
perimeter of a box 'distance' units from the center. These are not
in any particular order."
[dist]
(if (<= dist 0)
[[0 0]]
(let [[start-x end-x] [(- dist) dist]
[start-y end-y] [(- dist) dist]]
(concat
(map (fn [x] [x start-y]) (range start-x (inc end-x)))
(map (fn [x] [x end-y]) (range start-x (inc end-x)))
(map (fn [y] [start-x y]) (range (inc start-y) end-y))
(map (fn [y] [end-x y]) (range (inc start-y) end-y))))))
x++
y++
(defn origin-line-first-octant
"Gives a seq of [x y] coordinates, including the origin, from [0 0] to
the provided coordinate, which must be in the first octant
(y <= x, x > 0, y > 0)."
[[to-x to-y]]
(loop [x 0 y 0
d (- (* 2 to-y) to-x)
(if (> x to-x)
coords
(if (< d 0)
(recur (inc x) y
(+ d to-y to-y)
(conj coords [x y]))
(recur (inc x) (inc y)
(+ d (* 2 (- to-y to-x)))
(conj coords [x y]))))))
(defn origin-line
"Handles coordinates of a line to any coordinate from the origin,
regardless of octant, by reflecting it (possibly several times)
to the first octant."
[[x y :as coords]]
(cond
First octant
(and (>= x 0) (>= y 0) (<= y x))
(origin-line-first-octant coords)
Second octant - swap x & y coords
(mapv (fn [[x y]] [y x]) (origin-line [y x]))
second or third QUADRANT
(< x 0)
(mapv (fn [[x y]] [(- x) y]) (origin-line [(- x) y]))
fourth QUADRANT
(mapv (fn [[x y]] [x (- y)]) (origin-line [x (- y)]))
))
(defn line
"Gives coordinates of all points between the specified coordinates.
Handles it by translating the line to have a
first coordinate of [0 0] and then
drawing an origin-based line, and then translating it back."
[[x1 y1] [x2 y2]]
(mapv (fn [[x y]] [(+ x x1) (+ y y1)])
(origin-line [(- x2 x1) (- y2 y1)])))
(defn origin-los-rays
"Returns a seq of a seq containing all the line of sight ray
coordinates (2-vectors) from
the origin out to the specified distance.
You can take the origin out of this by doing (mapv rest (origin-los-rays dist))."
[dist]
(mapv (fn [coord] (origin-line coord)) (box-coords dist)))
(defn los-rays
"Returns a seq of a seq containing all the line of sight ray
coordinates (2-vectors) from
the specified coordinate out to the specified distance.
You can take the original coordinate out of this by doing
(mapv rest <result>) on the return value of this function."
[[o-x o-y] dist]
(mapv
(fn [ray] (mapv (fn [[x y]] [(+ x o-x) (+ y o-y)]) ray))
(origin-los-rays dist)))
|
6402d2dd62e357f5fc1d3f537655bafce6618fdff15e60820c8d4a32edb25a4c | sirherrbatka/clusters | utils.lisp | (cl:in-package #:clusters.pam)
(defun clear-cluster-contents (state)
(setf (fill-pointer (access-cluster-contents state))
(read-medoids-count state))
(map nil
(curry #'(setf fill-pointer) 1)
(access-cluster-contents state)))
(defun order-medoids (state)
(setf (access-cluster-contents state)
(~> state
access-cluster-contents
(sort #'< :key #'first-elt))))
(defun medoidp (state index)
(declare (optimize (debug 3)))
(let* ((cluster-contents (access-cluster-contents state))
(position (position
index
cluster-contents
:key #'first-elt))
(cluster-count (length cluster-contents)))
(and (not (null position))
(< position cluster-count)
(= index (~> cluster-contents
(aref position)
first-elt)))))
(defun closest-medoid (state index)
(unless (medoidp state index)
(iterate
(declare (type number distance))
(with result = 0)
(with distance-matrix = (access-distance-matrix state))
(with cluster-contents = (access-cluster-contents state))
(with count = (~> distance-matrix
length
clusters.utils:half-matrix-size->count))
(for cluster in-vector cluster-contents)
(for i from 0)
(for medoid = (aref cluster 0))
(for distance = (clusters.utils:mref distance-matrix
index medoid count))
(minimize distance into mini)
(when (= mini distance)
(setf result i))
(finally (return result)))))
(defun choose-initial-medoids (state)
(iterate
(with indexes = (clusters:indexes state))
(with cluster-contents = (access-cluster-contents state))
(with generator = (clusters.utils:lazy-shuffle 0 (length indexes)))
(for cluster in-vector cluster-contents)
(for new-value = (funcall generator))
(assert new-value)
(setf (aref cluster 0) (aref indexes new-value)))
(order-medoids state))
(defmethod assign-data-points-to-medoids (state)
(map nil (curry #'(setf fill-pointer) 1)
(access-cluster-contents state))
(iterate
(with cluster-contents = (access-cluster-contents state))
(with assignments = (clusters.utils:pmap
(clusters:parallelp state)
'(vector (or null fixnum))
(curry #'closest-medoid state)
(clusters:indexes state)))
(for i in-vector (clusters:indexes state))
(for assignment in-vector assignments)
(for medoid-p = (null assignment))
(unless medoid-p
(vector-push-extend i (aref cluster-contents assignment)))))
(defun clear-unfinished-clusters (state)
(let ((cluster-contents (access-cluster-contents state)))
(setf #1=(access-unfinished-clusters state)
(adjust-array #1#
(length cluster-contents)
:fill-pointer (length cluster-contents)))
(map-into (access-unfinished-clusters state) (constantly nil))))
(-> choose-effective-medoid (algorithm-state (vector t)) boolean)
(defun choose-effective-medoid (state cluster)
(bind (((:flet swap-medoid (i))
(declare (type non-negative-fixnum i))
(rotatef (aref cluster i) (aref cluster 0)))
(distance-matrix (access-distance-matrix state))
(matrix-count (~> distance-matrix
length
clusters.utils:half-matrix-size->count))
((:flet total-distance-to-medoid (&optional old-cost))
(iterate
(for i from 1 below (length cluster))
(for distance = (clusters.utils:mref distance-matrix
(the fixnum (aref cluster 0))
(the fixnum (aref cluster i))
matrix-count))
(assert distance)
(sum distance into sum)
(unless (null old-cost)
(while (<= sum old-cost)))
(finally (return sum))))
(improved-something nil))
(iterate
(with minimal-distance-to-medoid = (total-distance-to-medoid))
(for i from 1 below (length cluster))
(swap-medoid i)
(for distance = (total-distance-to-medoid
minimal-distance-to-medoid))
(minf minimal-distance-to-medoid distance)
(for improved = (= distance minimal-distance-to-medoid))
(unless improved
(swap-medoid i))
(setf improved-something
(not (null (or improved improved-something)))))
improved-something))
(defun choose-effective-medoids (state)
(let ((unfinished-clusters (access-unfinished-clusters state))
(cluster-contents (access-cluster-contents state)))
(assert (eql (length unfinished-clusters) (length cluster-contents)))
(clusters.utils:pmap-into (clusters:parallelp state)
unfinished-clusters
(curry #'choose-effective-medoid state)
cluster-contents)
(order-medoids state)))
(defun unfinished-clusters-p (state)
(find t (access-unfinished-clusters state)))
(defun scan-for-clusters-of-invalid-size (state)
(clear-unfinished-clusters state)
(let ((merge-threshold (read-merge-threshold state))
(split-threshold (read-split-threshold state)))
(map-into (access-unfinished-clusters state)
(lambda (x)
(not (< merge-threshold
(length x)
split-threshold)))
(access-cluster-contents state))))
(defun fill-reclustering-index-vector (state indexes count-of-eliminated)
(iterate
(with cluster-contents = (access-cluster-contents state))
(with position = 0)
(for i from (~> cluster-contents length 1-) downto 0)
(repeat count-of-eliminated)
(for cluster = (aref cluster-contents i))
(iterate
(for value in-vector cluster)
(setf (aref indexes position) value)
(incf position)))
indexes)
(defun prepare-reclustering-index-vector (state)
(bind ((cluster-contents (access-cluster-contents state))
(merge-threshold (read-merge-threshold state))
(split-threshold (read-split-threshold state))
(count-of-eliminated (clusters.utils:swap-if
cluster-contents
(lambda (x)
(not (< merge-threshold
x
split-threshold)))
:key #'length))
(count-of-elements (iterate
(for i
from (~> cluster-contents length 1-)
downto 0)
(repeat count-of-eliminated)
(sum (~> cluster-contents
(aref i)
length))))
((:dflet expected-cluster-count ())
(round (/ count-of-elements
(/ (+ split-threshold merge-threshold)
2)))))
(iterate
(while (zerop (expected-cluster-count)))
(until (eql count-of-eliminated (length cluster-contents)))
(incf count-of-eliminated)
(incf count-of-elements (~>> (length cluster-contents)
(- _ count-of-eliminated)
(aref cluster-contents)
length)))
(values
(fill-reclustering-index-vector
state
(make-array count-of-elements :element-type 'non-negative-fixnum)
count-of-eliminated)
count-of-eliminated
(expected-cluster-count))))
(defun recluster-clusters-of-invalid-size (state)
(setf #1=(access-cluster-contents state) (shuffle #1#))
(bind (((:values indexes count-of-eliminated expected-cluster-count)
(prepare-reclustering-index-vector state))
(cluster-contents (access-cluster-contents state))
(fresh-state (make 'algorithm-state
:parameters (clusters:parameters state)
:indexes indexes
:medoids-count expected-cluster-count
:distance-matrix (access-distance-matrix state)
:data (clusters:data state))))
(build-clusters fresh-state nil)
(decf (fill-pointer cluster-contents) count-of-eliminated)
(map nil
(rcurry #'vector-push-extend cluster-contents)
(access-cluster-contents fresh-state))
(order-medoids state)))
(defun build-clusters (state &optional split-merge)
(bind ((optimal-content nil)
(clusters-with-optimal-size nil)
(select-medoids-attempts-count
(read-select-medoids-attempts-count state))
(merge-threshold (read-merge-threshold state))
(split-threshold (read-split-threshold state))
(split-merge-attempts-count
(read-split-merge-attempts-count state))
((:flet split-merge
(&aux (cluster-contents (access-cluster-contents state))))
(when (and split-merge
(not (zerop split-merge))
split-merge-attempts-count)
(iterate
(scan-for-clusters-of-invalid-size state)
(while (unfinished-clusters-p state))
(repeat (read-split-merge-attempts-count state))
(recluster-clusters-of-invalid-size state)
(for right-size =
(/ (count-if (lambda (x)
(< merge-threshold x split-threshold))
cluster-contents)
(length cluster-contents)))
(ensure clusters-with-optimal-size right-size)
(minf clusters-with-optimal-size right-size)
(when (= right-size clusters-with-optimal-size)
(setf optimal-content (map-into (copy-array cluster-contents)
#'copy-array
cluster-contents)))
(finally (setf (access-cluster-contents state)
optimal-content))))))
(iterate
(with attempts = select-medoids-attempts-count)
(for i from 0)
(unless (or (null attempts) (< i attempts))
(leave t))
(when (zerop (rem i 3))
(clear-cluster-contents state)
(choose-initial-medoids state)
(assign-data-points-to-medoids state))
(clear-unfinished-clusters state)
(choose-effective-medoids state)
(while (unfinished-clusters-p state))
(finally
(split-merge)
(clear-unfinished-clusters state)))))
(defun reset (object)
(bind (((:accessors (split-merge-attempts-count read-split-merge-attempts-count)
(merge-threshold read-merge-threshold)
(split-threshold read-split-threshold)
(unfinished-clusters access-unfinished-clusters)
(state-medoids-count access-medoids-count)
(data clusters:data)
(cluster-contents access-cluster-contents)
(cluster-size access-cluster-size))
object)
((:accessors (medoids-count read-medoids-count))
(clusters:parameters object)))
(if (zerop split-merge-attempts-count)
(progn (assert (null merge-threshold))
(assert (null split-threshold)))
(assert (< 0 merge-threshold split-threshold)))
(let ((length (length (clusters:indexes object))))
(when (null state-medoids-count)
(setf state-medoids-count
(if (not (null medoids-count))
(max (min medoids-count length) 1)
length)))
(if (not (null cluster-size))
(assert (< cluster-size))
(setf cluster-size (max 2 (round-to (/ length medoids-count)
2))))
(when (null cluster-contents)
(setf cluster-contents (make-array medoids-count
:adjustable t
:fill-pointer medoids-count))
(map-into cluster-contents
(lambda () (make-array cluster-size :adjustable t
:fill-pointer 1))))
(when (null unfinished-clusters)
(setf unfinished-clusters
(make-array medoids-count
:element-type 'boolean
:adjustable t
:fill-pointer medoids-count
:initial-element nil))))))
| null | https://raw.githubusercontent.com/sirherrbatka/clusters/20b8b60005ac8e27d12d05d277b26d8b5ca5c238/source/pam/utils.lisp | lisp | (cl:in-package #:clusters.pam)
(defun clear-cluster-contents (state)
(setf (fill-pointer (access-cluster-contents state))
(read-medoids-count state))
(map nil
(curry #'(setf fill-pointer) 1)
(access-cluster-contents state)))
(defun order-medoids (state)
(setf (access-cluster-contents state)
(~> state
access-cluster-contents
(sort #'< :key #'first-elt))))
(defun medoidp (state index)
(declare (optimize (debug 3)))
(let* ((cluster-contents (access-cluster-contents state))
(position (position
index
cluster-contents
:key #'first-elt))
(cluster-count (length cluster-contents)))
(and (not (null position))
(< position cluster-count)
(= index (~> cluster-contents
(aref position)
first-elt)))))
(defun closest-medoid (state index)
(unless (medoidp state index)
(iterate
(declare (type number distance))
(with result = 0)
(with distance-matrix = (access-distance-matrix state))
(with cluster-contents = (access-cluster-contents state))
(with count = (~> distance-matrix
length
clusters.utils:half-matrix-size->count))
(for cluster in-vector cluster-contents)
(for i from 0)
(for medoid = (aref cluster 0))
(for distance = (clusters.utils:mref distance-matrix
index medoid count))
(minimize distance into mini)
(when (= mini distance)
(setf result i))
(finally (return result)))))
(defun choose-initial-medoids (state)
(iterate
(with indexes = (clusters:indexes state))
(with cluster-contents = (access-cluster-contents state))
(with generator = (clusters.utils:lazy-shuffle 0 (length indexes)))
(for cluster in-vector cluster-contents)
(for new-value = (funcall generator))
(assert new-value)
(setf (aref cluster 0) (aref indexes new-value)))
(order-medoids state))
(defmethod assign-data-points-to-medoids (state)
(map nil (curry #'(setf fill-pointer) 1)
(access-cluster-contents state))
(iterate
(with cluster-contents = (access-cluster-contents state))
(with assignments = (clusters.utils:pmap
(clusters:parallelp state)
'(vector (or null fixnum))
(curry #'closest-medoid state)
(clusters:indexes state)))
(for i in-vector (clusters:indexes state))
(for assignment in-vector assignments)
(for medoid-p = (null assignment))
(unless medoid-p
(vector-push-extend i (aref cluster-contents assignment)))))
(defun clear-unfinished-clusters (state)
(let ((cluster-contents (access-cluster-contents state)))
(setf #1=(access-unfinished-clusters state)
(adjust-array #1#
(length cluster-contents)
:fill-pointer (length cluster-contents)))
(map-into (access-unfinished-clusters state) (constantly nil))))
(-> choose-effective-medoid (algorithm-state (vector t)) boolean)
(defun choose-effective-medoid (state cluster)
(bind (((:flet swap-medoid (i))
(declare (type non-negative-fixnum i))
(rotatef (aref cluster i) (aref cluster 0)))
(distance-matrix (access-distance-matrix state))
(matrix-count (~> distance-matrix
length
clusters.utils:half-matrix-size->count))
((:flet total-distance-to-medoid (&optional old-cost))
(iterate
(for i from 1 below (length cluster))
(for distance = (clusters.utils:mref distance-matrix
(the fixnum (aref cluster 0))
(the fixnum (aref cluster i))
matrix-count))
(assert distance)
(sum distance into sum)
(unless (null old-cost)
(while (<= sum old-cost)))
(finally (return sum))))
(improved-something nil))
(iterate
(with minimal-distance-to-medoid = (total-distance-to-medoid))
(for i from 1 below (length cluster))
(swap-medoid i)
(for distance = (total-distance-to-medoid
minimal-distance-to-medoid))
(minf minimal-distance-to-medoid distance)
(for improved = (= distance minimal-distance-to-medoid))
(unless improved
(swap-medoid i))
(setf improved-something
(not (null (or improved improved-something)))))
improved-something))
(defun choose-effective-medoids (state)
(let ((unfinished-clusters (access-unfinished-clusters state))
(cluster-contents (access-cluster-contents state)))
(assert (eql (length unfinished-clusters) (length cluster-contents)))
(clusters.utils:pmap-into (clusters:parallelp state)
unfinished-clusters
(curry #'choose-effective-medoid state)
cluster-contents)
(order-medoids state)))
(defun unfinished-clusters-p (state)
(find t (access-unfinished-clusters state)))
(defun scan-for-clusters-of-invalid-size (state)
(clear-unfinished-clusters state)
(let ((merge-threshold (read-merge-threshold state))
(split-threshold (read-split-threshold state)))
(map-into (access-unfinished-clusters state)
(lambda (x)
(not (< merge-threshold
(length x)
split-threshold)))
(access-cluster-contents state))))
(defun fill-reclustering-index-vector (state indexes count-of-eliminated)
(iterate
(with cluster-contents = (access-cluster-contents state))
(with position = 0)
(for i from (~> cluster-contents length 1-) downto 0)
(repeat count-of-eliminated)
(for cluster = (aref cluster-contents i))
(iterate
(for value in-vector cluster)
(setf (aref indexes position) value)
(incf position)))
indexes)
(defun prepare-reclustering-index-vector (state)
(bind ((cluster-contents (access-cluster-contents state))
(merge-threshold (read-merge-threshold state))
(split-threshold (read-split-threshold state))
(count-of-eliminated (clusters.utils:swap-if
cluster-contents
(lambda (x)
(not (< merge-threshold
x
split-threshold)))
:key #'length))
(count-of-elements (iterate
(for i
from (~> cluster-contents length 1-)
downto 0)
(repeat count-of-eliminated)
(sum (~> cluster-contents
(aref i)
length))))
((:dflet expected-cluster-count ())
(round (/ count-of-elements
(/ (+ split-threshold merge-threshold)
2)))))
(iterate
(while (zerop (expected-cluster-count)))
(until (eql count-of-eliminated (length cluster-contents)))
(incf count-of-eliminated)
(incf count-of-elements (~>> (length cluster-contents)
(- _ count-of-eliminated)
(aref cluster-contents)
length)))
(values
(fill-reclustering-index-vector
state
(make-array count-of-elements :element-type 'non-negative-fixnum)
count-of-eliminated)
count-of-eliminated
(expected-cluster-count))))
(defun recluster-clusters-of-invalid-size (state)
(setf #1=(access-cluster-contents state) (shuffle #1#))
(bind (((:values indexes count-of-eliminated expected-cluster-count)
(prepare-reclustering-index-vector state))
(cluster-contents (access-cluster-contents state))
(fresh-state (make 'algorithm-state
:parameters (clusters:parameters state)
:indexes indexes
:medoids-count expected-cluster-count
:distance-matrix (access-distance-matrix state)
:data (clusters:data state))))
(build-clusters fresh-state nil)
(decf (fill-pointer cluster-contents) count-of-eliminated)
(map nil
(rcurry #'vector-push-extend cluster-contents)
(access-cluster-contents fresh-state))
(order-medoids state)))
(defun build-clusters (state &optional split-merge)
(bind ((optimal-content nil)
(clusters-with-optimal-size nil)
(select-medoids-attempts-count
(read-select-medoids-attempts-count state))
(merge-threshold (read-merge-threshold state))
(split-threshold (read-split-threshold state))
(split-merge-attempts-count
(read-split-merge-attempts-count state))
((:flet split-merge
(&aux (cluster-contents (access-cluster-contents state))))
(when (and split-merge
(not (zerop split-merge))
split-merge-attempts-count)
(iterate
(scan-for-clusters-of-invalid-size state)
(while (unfinished-clusters-p state))
(repeat (read-split-merge-attempts-count state))
(recluster-clusters-of-invalid-size state)
(for right-size =
(/ (count-if (lambda (x)
(< merge-threshold x split-threshold))
cluster-contents)
(length cluster-contents)))
(ensure clusters-with-optimal-size right-size)
(minf clusters-with-optimal-size right-size)
(when (= right-size clusters-with-optimal-size)
(setf optimal-content (map-into (copy-array cluster-contents)
#'copy-array
cluster-contents)))
(finally (setf (access-cluster-contents state)
optimal-content))))))
(iterate
(with attempts = select-medoids-attempts-count)
(for i from 0)
(unless (or (null attempts) (< i attempts))
(leave t))
(when (zerop (rem i 3))
(clear-cluster-contents state)
(choose-initial-medoids state)
(assign-data-points-to-medoids state))
(clear-unfinished-clusters state)
(choose-effective-medoids state)
(while (unfinished-clusters-p state))
(finally
(split-merge)
(clear-unfinished-clusters state)))))
(defun reset (object)
(bind (((:accessors (split-merge-attempts-count read-split-merge-attempts-count)
(merge-threshold read-merge-threshold)
(split-threshold read-split-threshold)
(unfinished-clusters access-unfinished-clusters)
(state-medoids-count access-medoids-count)
(data clusters:data)
(cluster-contents access-cluster-contents)
(cluster-size access-cluster-size))
object)
((:accessors (medoids-count read-medoids-count))
(clusters:parameters object)))
(if (zerop split-merge-attempts-count)
(progn (assert (null merge-threshold))
(assert (null split-threshold)))
(assert (< 0 merge-threshold split-threshold)))
(let ((length (length (clusters:indexes object))))
(when (null state-medoids-count)
(setf state-medoids-count
(if (not (null medoids-count))
(max (min medoids-count length) 1)
length)))
(if (not (null cluster-size))
(assert (< cluster-size))
(setf cluster-size (max 2 (round-to (/ length medoids-count)
2))))
(when (null cluster-contents)
(setf cluster-contents (make-array medoids-count
:adjustable t
:fill-pointer medoids-count))
(map-into cluster-contents
(lambda () (make-array cluster-size :adjustable t
:fill-pointer 1))))
(when (null unfinished-clusters)
(setf unfinished-clusters
(make-array medoids-count
:element-type 'boolean
:adjustable t
:fill-pointer medoids-count
:initial-element nil))))))
| |
875f2c79be0bd7e3d62c47ab6a1a9e9bda7051235e811d5fa4d2f08ae35dc294 | uelis/IntML | compile.ml | (** Compilation to circuits
*)
open Term
open Unify
open Typing
(* Conveniencene function for n-ary let on WC level *)
let let_tupleW (x: var) ((sigma: var list), (f: Term.t)) : Term.t =
(* TODO: document *)
let rec remove_shadow sigma =
match sigma with
| [] -> []
| x :: rest ->
x :: remove_shadow
(List.map (fun y -> if x = y then Term.unusable_var else y)
rest)
in
let rec let_tuple x (sigma, f) =
match sigma with
| [] -> f
| z :: rest ->
mkLetW (mkVar x) ((x, z), let_tuple x (rest, f))
in let_tuple x (remove_shadow sigma, f)
let unTensorW a =
match Type.finddesc a with
| Type.TensorW(a1, a2) -> a1, a2
| _ -> assert false
(** A wire represents a dart in an undirected graph. *)
type wire = {
src: int;
dst: int;
type_forward: Type.t;
type_back: Type.t
}
let flip (w: wire) = {
src = w.dst;
dst = w.src;
type_forward = w.type_back;
type_back = w.type_forward
}
TODO : DOCUMENTATION
* Graph invariant : There are no two wires with w1.src = w2.src that are affixed
* to different nodes . I.e. w.src and w.dst are darts and must therefore be
* unique in the graph
* Graph invariant: There are no two wires with w1.src = w2.src that are affixed
* to different nodes. I.e. w.src and w.dst are darts and must therefore be
* unique in the graph *)
(* All wires are meant to 'leave' the instructions, i.e. they are all affixed
* with their src-label to the instruction.
* The type of the respective wires is indicated in the comments. *)
type instruction =
Axiom of wire (* [f] *) * (Term.var list * Term.t)
| Tensor of wire (* X *) * wire (* Y *) * wire (* X \otimes Y *)
| Der of wire (* \Tens A X *) * wire (* X *) * (Term.var list * Term.t)
| Contr of wire (* \Tens{A+B} X *) * wire (* \Tens A X *) * wire (* \Tens B X *)
| Door of wire (* X *) * wire (* \Tens A X *)
| ADoor of wire (* \Tens (A x B) X *) * wire (* \Tens B X *)
| LWeak of wire (* \Tens A X *) * wire (* \Tens B X *) (* where B <= A *)
| Epsilon of wire (* [A] *) * wire (* \Tens A [B] *) * wire (* [B] *)
type circuit =
{ output : wire;
instructions : instruction list
}
let rec wires (i: instruction list): wire list =
match i with
| [] -> []
| Axiom(w1, _) :: is -> w1 :: (wires is)
| Tensor(w1, w2, w3) :: is -> w1 :: w2 :: w3 :: (wires is)
| Der(w1, w2, _) :: is -> w1 :: w2 :: (wires is)
| Contr(w1, w2, w3) :: is -> w1 :: w2 :: w3 :: (wires is)
| Door(w1, w2) :: is -> w1 :: w2 :: (wires is)
| ADoor(w1, w2) :: is -> w1 :: w2 :: (wires is)
| LWeak(w1, w2) :: is -> w1 :: w2 :: (wires is)
| Epsilon(w1, w2, w3) :: is -> w1 :: w2 :: w3 :: (wires is)
let map_wires_instruction (f: wire -> wire): instruction -> instruction =
fun i ->
match i with
| Axiom(w, t) -> Axiom(f w, t)
| Tensor(w1, w2, w3) -> Tensor(f w1, f w2, f w3)
| Der(w1, w2, t) -> Der(f w1, f w2, t)
| Contr(w1, w2, w3) -> Contr(f w1, f w2, f w3)
| Door(w1, w2) -> Door(f w1, f w2)
| ADoor(w1, w2) -> ADoor(f w1, f w2)
| LWeak(w1, w2) -> LWeak(f w1, f w2)
| Epsilon(w1, w2, w3) -> Epsilon(f w1, f w2, f w3)
(* renaming of wires *)
let map_wire (f: int -> int): wire -> wire =
fun w ->
{src = f w.src;
dst = f w.dst;
type_forward = w.type_forward;
type_back = w.type_back
}
let map_instruction (f: int -> int): instruction -> instruction =
map_wires_instruction (map_wire f)
(* Wires for all the variables in the context.
* They point into the graph with their dst-label. *)
type ctx = (var * wire) list
module U = Unify(struct type t = unit end)
*
* Compilation of an upper - level term to a string diagram .
*
* The diagram is assumed to reside in a box of the functor
* { \Tens { An * ... * A1 } } . The components of the tuples
* are named by the variable names in sigma .
*
* Arguments :
* - sigma : Names with which the components can be accessed .
* sigma = [ c1 ; ... ; cn ] means that c1 corresponds to
* A1 and cn to An
* - gamma : Names of the wires for the context variables .
* They are directed so as to go into the diagram .
* - t : the term that is to be compiled .
*
* Result :
* - The wire that comes out of the diagram with the value of
* the term t.
* - The diagram as a list of instructions .
* Compilation of an upper-level term to a string diagram.
*
* The diagram is assumed to reside in a box of the functor
* {\Tens {An * ... * A1}}. The components of the tuples
* are named by the variable names in sigma.
*
* Arguments:
* - sigma: Names with which the components can be accessed.
* sigma = [c1; ... ;cn] means that c1 corresponds to
* A1 and cn to An
* - gamma: Names of the wires for the context variables.
* They are directed so as to go into the diagram.
* - t: the term that is to be compiled.
*
* Result:
* - The wire that comes out of the diagram with the value of
* the term t.
* - The diagram as a list of instructions.
*)
ASSUMPTION : all type annotations in t may only contain index types
* that are variables , i.e. not { 1 + 1}'a ' b , for example .
* that are variables, i.e. not {1+1}'a --o 'b, for example. *)
let circuit_of_termU (sigma: var list) (gamma: ctx) (t: Term.t): circuit =
let used_wirenames =
List.fold_right (fun (_, w) wns -> w.src :: w.dst :: wns) gamma [] in
let next_wirename = ref ((List.fold_right max used_wirenames (-1)) + 1) in
let fresh_wire () =
let n = !next_wirename in
next_wirename := !next_wirename + 2;
{ src = n;
dst = n + 1;
type_forward = Type.newty Type.Var;
type_back = Type.newty Type.Var
} in
let rec enter_box (gamma: ctx) : ctx * instruction list =
match gamma with
| [] -> ([], [])
| (x, w) :: rest ->
let (d, i) = enter_box rest in
let w' = fresh_wire () in
let w'' = fresh_wire () in
((x, w') :: d, LWeak(flip w, w'')::ADoor(flip w'', w') :: i)
in
let rec compile (sigma: var list) (gamma: ctx) (t: Term.t) =
match t.desc with
| Var(x) ->
let wx = List.assoc x gamma in
let w = fresh_wire () in
let w' = fresh_wire () in
(w, [Der(flip w', w,
(sigma, mkConstW (Some (Type.newty Type.OneW)) Cmin));
LWeak(flip wx, w')])
| HackU(_, t1) ->
let w = fresh_wire () in
(w, [(Axiom(w, (sigma, fresh_vars_for_missing_annots t1)))])
| PairU(s, t) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let (w_s, i_s) = compile sigma gamma_s s in
let (w_t, i_t) = compile sigma gamma_t t in
let w = fresh_wire () in
(w, Tensor(flip w_s, flip w_t, w) :: i_s @ i_t)
| LetU(s, (x, y, t)) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let (gamma_s_inbox, i_enter_box) = enter_box gamma_s in
let (w_s, i_s) = compile sigma gamma_s_inbox s in
let w_s_left = fresh_wire () in
let w_s_right = fresh_wire () in
let i_unpair = [Tensor(w_s_left, w_s_right, flip w_s)] in
let w_x = fresh_wire () in
let w_y = fresh_wire () in
let i_leavebox = [Door(flip w_s_left, w_x);
Door(flip w_s_right, w_y)] in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let (w_t, i_t) = compile sigma ((y, w_y) :: (x, w_x) :: gamma_t) t in
(w_t, i_t @ i_s @ i_enter_box @ i_unpair @ i_leavebox)
| AppU(s, t) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let (w_s, i_s) = compile sigma gamma_s s in
let (w_t, i_t) = compile_in_box unusable_var sigma gamma_t t in
let wr = fresh_wire () in
(wr, Tensor(flip w_t, wr, flip w_s) :: i_s @ i_t)
| CopyU(s, (x,y, t)) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let (w_s, i_s) = compile_in_box unusable_var sigma gamma_s s in
let w_x = fresh_wire () in
let w_y = fresh_wire () in
let (w_t, i_t) = compile sigma ((x, w_x) :: (y, w_y) :: gamma_t) t in
(w_t, Contr(flip w_s, w_x, w_y) :: i_s @ i_t)
| CaseU(f, (x, s), (y, t)) ->
let duplicate_and_enter_wire (w: wire)
: wire * wire * instruction list =
let w', wl, wr = fresh_wire (), fresh_wire (), fresh_wire () in
let wl_in_box, wr_in_box = fresh_wire (), fresh_wire () in
(wl_in_box, wr_in_box,
[Der(w', flip w, (sigma, fresh_vars_for_missing_annots f));
Contr(flip w', wl, wr);
Door(wl_in_box, flip wl); Door(wr_in_box, flip wr)])
in
let rec duplicate_and_enter_ctx (c: ctx)
: ctx * ctx * instruction list =
match c with
| [] -> ([], [], [])
| (x, w) :: rest ->
let (wl, wr, is) = duplicate_and_enter_wire w in
let (dl, dr, i') = duplicate_and_enter_ctx rest in
((x, wl) :: dl, (x, wr) :: dr, is @ i')
in
let (gammal, gammar, i_dup) = duplicate_and_enter_ctx gamma in
let (w_s_in_box, i_s) = compile (x :: sigma) gammal s in
let (w_t_in_box, i_t) = compile (y :: sigma) gammar t in
let w_s, w_t = fresh_wire (), fresh_wire () in
let i_leavebox = [Door(flip w_s_in_box, w_s);
Door(flip w_t_in_box, w_t)] in
let w_join = fresh_wire () in
let i_join = [Contr(w_join, flip w_s, flip w_t)] in
let w = fresh_wire () in
let i_der = [Der(flip w_join, w,
(sigma, fresh_vars_for_missing_annots f))] in
(w, i_der @ i_join @ i_leavebox @ i_s @ i_t @ i_dup)
| BoxTermU(t) ->
let w = fresh_wire () in
(w, [Axiom(w,
(sigma, mkLambdaW ((unusable_var, Some (Type.newty Type.OneW)),
fresh_vars_for_missing_annots t)))])
| LetBoxU(s, (c, t)) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let wr = fresh_wire () in
let (w_s, i_s) = compile sigma gamma_s s in
let (w_t, i_t) = compile_in_box c sigma gamma_t t in
(wr, Epsilon(flip w_s, flip w_t, wr) :: i_s @ i_t)
| LambdaU((x, None), s) ->
let wx = fresh_wire () in
let w = fresh_wire () in
let (w_s, i_s) = (compile sigma ((x, wx) :: gamma) s) in
(w, Tensor(wx, flip w_s, w) :: i_s)
| LambdaU((x, Some ty), s) ->
let tym, typ = Type.question_answer_pair (Type.freshen_index_types ty) in
let alpha1, alpha2 = Type.newty Type.Var, Type.newty Type.Var in
let sigma1, sigma2 = Type.newty Type.Var, Type.newty Type.Var in
let tyTensor (s, t) = Type.newty (Type.TensorW(s, t)) in
(* ASSUMPTION: all annotations must have type variables as index
* types.
* TODO: Give a warning otherwise! *)
let wx =
{ (fresh_wire ()) with
type_forward = tyTensor(sigma1, tyTensor(alpha1, typ));
type_back = tyTensor(sigma2, tyTensor(alpha2, tym))} in
let w = fresh_wire () in
let (w_s, i_s) = (compile sigma ((x, wx) :: gamma) s) in
(w, Tensor(wx, flip w_s, w) :: i_s)
| TypeAnnot (t, None) ->
compile sigma gamma t
| TypeAnnot (t, Some ty) ->
let (w, ins) = compile sigma gamma t in
let tyTensor (s, t) = Type.newty (Type.TensorW(s, t)) in
let sigma1, sigma2 = Type.newty Type.Var, Type.newty Type.Var in
let tym, typ = Type.question_answer_pair (Type.freshen_index_types ty) in
U.unify w.type_forward (tyTensor(sigma1, typ));
U.unify w.type_back (tyTensor(sigma1, tym));
(w, ins)
| TrW _|LambdaW (_, _)|AppW (_, _)|CaseW (_, _)| InW (_, _, _)
| LetBoxW(_,_) | LetW (_, _)|PairW (_, _)|ConstW (_, _)|UnitW ->
assert false
and compile_in_box (c: var) (sigma: var list) (gamma: ctx) (t: Term.t) =
let (gamma_in_box, i_enter_box) = enter_box gamma in
let (w_t, i_t) = compile (c :: sigma) gamma_in_box t in
let w = fresh_wire () in
(w, Door(flip w_t, w) :: i_t @ i_enter_box)
in
let w, is = compile sigma gamma t in
{ output = w; instructions = is }
* Infers types in the string diagram and instantiated the
* terms in the Der- and Axiom - nodes so that the pre_term
* computed below will in fact be a proper term and we
* wo n't have to run type inference on it .
*
* Inequality constraints are solved * after * all other equality constraints are
* solved . This corresponds to first computing the constraints that the rules
* impose locally and then connecting them with the inequality constraints .
* TODO : We should prove that this is correct !
* Infers types in the string diagram and instantiated the
* terms in the Der- and Axiom-nodes so that the pre_term
* computed below will in fact be a proper term and we
* won't have to run type inference on it.
*
* Inequality constraints are solved *after* all other equality constraints are
* solved. This corresponds to first computing the constraints that the rules
* impose locally and then connecting them with the inequality constraints.
* TODO: We should prove that this is correct!
*)
let infer_types (c : circuit) : Type.t =
let tensor s t = Type.newty (Type.TensorW(s, t)) in
let sum s t = Type.newty (Type.SumW [s; t]) in
let rec constraints (instructions: instruction list)
: Typing.type_constraint list =
match instructions with
| [] -> []
| Axiom(w1, (s, f))::rest ->
let sigma = Type.newty Type.Var in
let alpha = Type.newty Type.Var in
let x, y = "x", "y" in
let f' = variant f in (* ensure "x" and "y" are fresh *)
let s' = List.map variant_var s in
let tyfapp = principal_typeW
[(x, sigma); (y, alpha)]
(mkAppW (let_tupleW x (s', f')) (mkVar y)) in
Typing.eq_constraint
w1.type_forward
(Type.newty (Type.TensorW(sigma, tyfapp))) ::
Typing.eq_constraint
(flip w1).type_forward
(Type.newty (Type.TensorW(sigma, alpha))) ::
(constraints rest)
| Tensor(w1, w2, w3)::rest ->
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
Typing.eq_constraint
w3.type_forward (tensor sigma1 (sum alpha1 beta1)) ::
Typing.eq_constraint
w1.type_back (tensor sigma1 alpha1) ::
Typing.eq_constraint
w2.type_back (tensor sigma1 beta1) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward (tensor sigma2 alpha2) ::
Typing.eq_constraint
w2.type_forward (tensor sigma2 beta2) ::
Typing.eq_constraint
w3.type_back
(tensor sigma2 (sum alpha2 beta2)) ::
(constraints rest)
| Der(w1, w2, (s, f))::rest ->
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward (tensor sigma1 beta1) ::
Typing.eq_constraint
w1.type_back (tensor sigma1 (tensor alpha1 beta1)) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let x = "x" in
(* ensure "x" is fresh *)
let f' = variant f in
let s' = List.map variant_var s in
let tyf = principal_typeW [(x, sigma2)] (let_tupleW x (s', f')) in
Typing.eq_constraint
w1.type_forward (tensor sigma2 (tensor tyf alpha2)) ::
Typing.eq_constraint
w2.type_back (tensor sigma2 alpha2) ::
(constraints rest)
| Contr(w1 (* \Tens{A+B} X *),
w2 (* \Tens A X *), w3 (* \Tens B X *)) :: rest ->
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
let gamma1 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward
(tensor sigma1 (tensor (sum alpha1 beta1) gamma1)) ::
Typing.eq_constraint
w2.type_back (tensor sigma1 (tensor alpha1 gamma1)) ::
Typing.eq_constraint
w3.type_back (tensor sigma1 (tensor beta1 gamma1)) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
let gamma2 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward
(tensor sigma2 (tensor alpha2 gamma2)) ::
Typing.eq_constraint
w3.type_forward
(tensor sigma2 (tensor beta2 gamma2)) ::
Typing.eq_constraint
w1.type_back
(tensor sigma2 (tensor (sum alpha2 beta2) gamma2)) ::
(constraints rest)
| Door(w1 (* X *) , w2 (* \Tens A X *))::rest ->
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward (tensor sigma1 (tensor alpha1 beta1)) ::
Typing.eq_constraint
w1.type_back
(tensor (tensor sigma1 alpha1) beta1) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward
(tensor (tensor sigma2 alpha2) beta2) ::
Typing.eq_constraint
w2.type_back
(tensor sigma2 (tensor alpha2 beta2)) ::
(constraints rest)
| ADoor(w1 (* \Tens (A x B) X *), w2 (* \Tens B X *))::rest ->
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
let gamma1 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward
(tensor (tensor sigma1 alpha1) (tensor beta1 gamma1)) ::
Typing.eq_constraint
w1.type_back
(tensor sigma1 (tensor (tensor alpha1 beta1) gamma1)) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
let gamma2 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward
(tensor sigma2 (tensor (tensor alpha2 beta2) gamma2)) ::
Typing.eq_constraint
w2.type_back
(tensor (tensor sigma2 alpha2) (tensor beta2 gamma2)) ::
(constraints rest)
| LWeak(w1 (* \Tens A X*), w2 (* \Tens B X*)) (* B <= A *)::rest ->
let sigma = Type.newty Type.Var in
let alpha = Type.newty Type.Var in
let beta = Type.newty Type.Var in
let gamma1 = Type.newty Type.Var in
let gamma2 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward (tensor sigma (tensor alpha gamma1)) ::
Typing.eq_constraint
w1.type_back (tensor sigma (tensor alpha gamma2)) ::
Typing.eq_constraint
w2.type_forward (tensor sigma (tensor beta gamma2)) ::
Typing.eq_constraint
w2.type_back (tensor sigma (tensor beta gamma1)) ::
Typing.leq_constraint beta alpha ::
(constraints rest)
| Epsilon(w1 (* [A] *), w2 (* \Tens A [B] *), w3 (* [B] *)) :: rest ->
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward
(tensor sigma1 (tensor alpha1 (Type.newty Type.OneW))) ::
Typing.eq_constraint
w1.type_back
(tensor sigma1 alpha1) ::
let sigma2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
Typing.eq_constraint
w3.type_forward (tensor sigma2 beta2) ::
Typing.eq_constraint
w2.type_back
(tensor sigma2 (tensor alpha1 beta2))::
let sigma3 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward (tensor sigma3 (Type.newty Type.OneW)) ::
Typing.eq_constraint
w3.type_back (tensor sigma3 (Type.newty Type.OneW)) ::
(constraints rest) in
try
Typing.solve_constraints (constraints c.instructions);
let right_component ty =
match Type.finddesc ty with
| Type.TensorW(_, r) -> r
| _ -> failwith "Internal error: output wire has wrong type" in
Type.newty (Type.FunW(right_component (c.output.type_back),
right_component (c.output.type_forward)))
with
| U.Not_Unifiable _ ->
failwith "Internal error: cannot unify constraints in compilation"
module IntMap = Map.Make(
struct
type t = int
let compare = compare
end
)
let rec dot_of_circuit
?title:(title = "")
?wire_style:(wire_style = fun w -> "")
(c: circuit) : string =
let node_name ins =
match ins with
| Axiom(w1, _) ->
Printf.sprintf "\"Axiom({%i,%i})\"" w1.src w1.dst
| Tensor(w1, w2, w3) ->
Printf.sprintf "\"Tensor({%i,%i},{%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst w3.src w3.dst
| Der(w1, w2, _) ->
Printf.sprintf "\"Der({%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst
| Contr(w1, w2, w3) ->
Printf.sprintf "\"Contr({%i,%i},{%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst w3.src w3.dst
| Door(w1, w2) ->
Printf.sprintf "\"Door({%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst
| ADoor(w1, w2) ->
Printf.sprintf "\"ADoor({%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst
| LWeak(w1, w2) ->
Printf.sprintf "\"LWeak({%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst
| Epsilon(w1, w2, w3) ->
Printf.sprintf "\"Epsilon({%i,%i},{%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst w3.src w3.dst
in
let node_label ins =
match ins with
| Axiom(_, (_, { desc= LambdaW((x, None), _) }))
when x = unusable_var -> "[...]"
| Axiom(_, _) -> "hack(...)"
| Tensor(_, _, _) -> "⊗"
| Der(_, _, _) -> "π_..."
| Contr(_, _, _) -> "a+"
| Door(_, w) ->
if w.src = -1 then "\", shape=\"plaintext" else "↑"
| ADoor(_, _) -> "↓"
| LWeak(_, _) -> "lweak"
| Epsilon(_, _, _) -> "π"
in
let instructions_with_result =
(Door(flip c.output,
{ src = (-1);
dst = (-2);
type_forward = Type.newty Type.Var;
type_back = Type.newty Type.Var})) :: c.instructions in
let node_map_by_src =
let rec build_dst_map i =
match i with
| [] -> IntMap.empty
| node :: rest ->
List.fold_right (fun w map -> IntMap.add w.src node map)
(wires [node]) (build_dst_map rest)
in build_dst_map instructions_with_result in
let buf = Buffer.create 1024 in
let nodes () =
List.iter (fun ins ->
Buffer.add_string buf (node_name ins);
Buffer.add_string buf "[label=\"";
Buffer.add_string buf (node_label ins);
Buffer.add_string buf "\"];\n") instructions_with_result
in
let edges () =
let edge srcins (w: wire) =
try
let dstins = IntMap.find w.dst node_map_by_src in
Buffer.add_string buf (node_name srcins);
Buffer.add_string buf " -> ";
Buffer.add_string buf (node_name dstins);
Buffer.add_string buf (wire_style w);
Buffer.add_string buf ";\n ";
with Not_found -> () (* Weakening *) in
List.iter (fun srcins -> List.iter (edge srcins) (wires [srcins]))
instructions_with_result
in
Buffer.add_string buf "digraph G {\n labelloc=t; label=\"";
Buffer.add_string buf title;
Buffer.add_string buf "\";fontname=Monospace;fontcolor=blue;fontsize=36;";
nodes ();
edges ();
Buffer.add_string buf "}";
Buffer.contents buf
(* Injection into the k-th component (from the left) of an n-fold sum.
* Assumes 0 <= k < n.
*)
let rec in_k (k: int) (n: int) (t: Term.t): Term.t =
assert (0 <= k && k < n);
if k = 0 then
mkInlW t
else
mkInrW (mkInW (n-1) (k-1) t)
(* inverse to in_k: out_k (in_k k n t) n = (k, t) *)
let rec out_k (t: Term.t) (n: int) : int * Term.t =
match t.desc with
| InW(2, 0, s) -> (0, s)
| InW(2, 1, {desc = InW(n', k, s)}) when n = n' + 1 -> (k + 1, s)
| _ -> failwith "out_k"
exception Not_Leq
If alpha < = beta then ( embed alpha beta ) is a corresponding
* embedding from alpha to beta .
* The function raises Not_Leq if it discovers that alpha < = beta
* does not hold .
*
* embedding from alpha to beta.
* The function raises Not_Leq if it discovers that alpha <= beta
* does not hold.
* *)
let rec embed (a: Type.t) (b: Type.t) : Term.t =
if Type.equals a b then Term.mkLambdaW(("x", None), Term.mkVar "x")
else
match Type.finddesc b with
| Type.SumW[b1; b2] ->
begin try
Term.mkLambdaW(("x", None),
Term.mkInlW
(Term.mkAppW (embed a b1) (Term.mkVar "x")))
with Not_Leq ->
Term.mkLambdaW(("x", None),
Term.mkInrW
(Term.mkAppW (embed a b2) (Term.mkVar "x")))
end
| Type.TensorW(b1, b2) ->
begin try
Term.mkLambdaW(("x", None),
Term.mkPairW
(Term.mkAppW (embed a b1) (Term.mkVar "x"))
(Term.mkConstW (Some b2) Cmin))
with Not_Leq ->
Term.mkLambdaW(("x", None),
Term.mkPairW
(Term.mkConstW (Some b1) Cmin)
(Term.mkAppW (embed a b2) (Term.mkVar "x")))
end
| _ -> raise Not_Leq
If alpha < = beta then ( embed alpha beta ) is a corresponding
* embedding from beta to alpha . The functions ( embed a b ) and
* ( project a b)form a section - retraction pair .
* The function raises Not_Leq if it discovers that alpha < = beta
* does not hold .
*
* embedding from beta to alpha. The functions (embed a b) and
* (project a b)form a section-retraction pair.
* The function raises Not_Leq if it discovers that alpha <= beta
* does not hold.
* *)
let rec project (a: Type.t) (b: Type.t) : Term.t =
if Type.equals a b then Term.mkLambdaW(("x", None), Term.mkVar "x")
else
match Type.finddesc b with
| Type.SumW[b1; b2] ->
begin try
Term.mkLambdaW(
("x", None),
Term.mkCaseW (Term.mkVar "x")
[("y", Term.mkAppW (project a b1) (Term.mkVar "y"));
("y", Term.mkConstW (Some a) Cmin)])
with Not_Leq ->
Term.mkLambdaW(
("x", None),
Term.mkCaseW (Term.mkVar "x")
[("y", Term.mkConstW (Some a) Cmin);
("y", Term.mkAppW (project a b2) (Term.mkVar "y"))])
end
| Type.TensorW(b1, b2) ->
begin try
Term.mkLambdaW(("x", None),
Term.mkLetW (Term.mkVar "x")
(("y", "z"),
Term.mkAppW (project a b1) (Term.mkVar "y")))
with Not_Leq ->
Term.mkLambdaW(("x", None),
Term.mkLetW (Term.mkVar "x")
(("y", "z"),
Term.mkAppW (project a b2) (Term.mkVar "z")))
end
| _ -> raise Not_Leq
(** Compilation of string diagram into a lower-level term. *)
let message_passing_term (c: circuit): Term.t =
(* Information about the wires in the graph *)
let all_wires = wires c.instructions in
let max_wire_src_dst =
List.fold_right (fun w m -> max w.src (max w.dst m)) all_wires 0 in
(* Rename the variables in the instruction list so that
* they do not clash with the name supply below.
* *)
let instructions_fresh =
let prep_var_y x = "y" ^ x in
let prep_y (sigma, f) =
(List.map prep_var_y sigma, rename_vars prep_var_y f) in
let rec i_fresh instructions =
match instructions with
| [] -> []
| Der(w1, w2, (sigma, f)) :: rest ->
Der(w1, w2, prep_y (sigma, f)) :: (i_fresh rest)
| Axiom(w, (sigma, f)) :: rest ->
Axiom(w, prep_y (sigma, f)) :: (i_fresh rest)
| node :: rest ->
node :: (i_fresh rest)
in i_fresh c.instructions
in
(* Supply of fresh variable names.
* (The instructions do not contain a free variable starting with "x")
*)
let fresh_var = Vargen.mkVarGenerator "x" ~avoid:[] in
Build a map of nodes , indexed by the src - label of wires .
* Note : This uses the assumption that only one wire with a
* given node - label appears in a graph
* Note: This uses the assumption that only one wire with a
* given node-label appears in a graph *)
let node_map_by_src =
let rec build_dst_map i =
match i with
| [] -> IntMap.empty
| node :: rest ->
let ws = wires [node] in
List.fold_right (fun w map -> IntMap.add w.src node map) ws
(build_dst_map rest)
in build_dst_map instructions_fresh in
(* action finds the node to which dst is connected
* and returns the action that must happen if the token
* is passed along that path
*)
let rec action dst =
let x = fresh_var() in
let y = fresh_var() in
let sigma, v, c, d = fresh_var(), fresh_var(), fresh_var(), fresh_var() in
let to_dart d t =
(x, mkLetW (mkVar x)
((sigma, v), in_k d (max_wire_src_dst + 1) t)) in
try
begin
match IntMap.find dst node_map_by_src with
| Axiom(w1, f) when w1.src = dst ->
to_dart w1.src
(mkPairW (mkVar sigma)
(mkAppW (let_tupleW sigma f) (mkVar v)))
| Tensor(w1, w2, w3) when w1.src = dst ->
to_dart w3.src (mkPairW (mkVar sigma) (mkInlW (mkVar v)))
| Tensor(w1, w2, w3) when w2.src = dst ->
to_dart w3.src (mkPairW (mkVar sigma) (mkInrW (mkVar v)))
| Tensor(w1, w2, w3) when w3.src = dst ->
(x, mkLetW (mkVar x)
((sigma, x),
mkCaseW (mkVar x)
[(v, in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkVar v))) ;
(v, in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkVar v)))]
)
)
| Der(w1, w2, f) when w1.src = dst ->
(x, mkLetW (mkVar x) ((sigma, x),
mkLetW (mkVar x) ((c, v),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkVar v))))
)
| Der(w1, w2, f) when w2.src = dst ->
(x, mkLetW (mkVar x) ((sigma, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (let_tupleW sigma f) (mkVar v)))
))
| Contr(w1 (* \Tens{A+B} X *),
w2 (* \Tens A X *),
w3 (* \Tens B X *)) when w1.src = dst ->
(x, mkLetW (mkVar x) ((sigma, v),
mkLetW (mkVar v) ((c, v),
mkCaseW (mkVar c)
[(c, in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkVar c) (mkVar v)))) ;
(d, in_k w3.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkVar d) (mkVar v)))) ]
)
)
)
| Contr(w1 (* \Tens{A+B} X *),
w2 (* \Tens A X *),
w3 (* \Tens B X *)) when w2.src = dst ->
(x, mkLetW (mkVar x) ((sigma, v),
mkLetW (mkVar v) ((c, y),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkInlW (mkVar c)) (mkVar y)))
)
))
| Contr(w1 (* \Tens{A+B} X *),
w2 (* \Tens A X *),
w3 (* \Tens B X *)) when w3.src = dst ->
(x, mkLetW (mkVar x) ((sigma, v),
mkLetW (mkVar v) ((d, y),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkInrW (mkVar d)) (mkVar y)))
)
))
| Door(w1 (* X *) , w2 (* \Tens A X *)) when w1.src = dst ->
(* <<sigma, c>, v> -> <sigma, <c, v>> *)
(x, mkLetW (mkVar x) ((x, v),
mkLetW (mkVar x) ((sigma, c),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkPairW (mkVar c) (mkVar v))))
))
| Door(w1 (* X *) , w2 (* \Tens A X *)) when w2.src = dst ->
(* <sigma, <c, v>> -> <<sigma, c>, v> *)
(x, mkLetW (mkVar x) ((sigma, x),
mkLetW (mkVar x) ((c, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkPairW (mkVar sigma) (mkVar c)) (mkVar v)))))
| ADoor(w1 (* \Tens (A x B) X *),
w2 (* \Tens B X *)) when w1.src = dst ->
(* <sigma, <<d, c>, v>> -> <<sigma, d>, <c, v>> *)
(x, mkLetW (mkVar x) ((sigma, x),
mkLetW (mkVar x) ((x, v),
mkLetW (mkVar x) ((d, c),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkPairW (mkVar sigma) (mkVar d))
(mkPairW (mkVar c) (mkVar v)))))
))
| ADoor(w1 (* \Tens (A x B) X *),
w2 (* \Tens B X *)) when w2.src = dst ->
(* <<sigma, d>, <c, v>> -> <sigma, <<d, c>, v>> *)
(x, mkLetW (mkVar x) ((x, y),
mkLetW (mkVar x) ((sigma, d),
mkLetW (mkVar y) ((c, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkPairW (mkVar d) (mkVar c)) (mkVar v)))))
))
| LWeak(w1 (* \Tens A X *),
w2 (* \Tens B X *)) (* B <= A *) when w1.src = dst ->
(* <sigma, <c, v>> @ w1 -> <sigma, <project b a c, v>> @ w2 *)
let a = fst (unTensorW (snd (unTensorW w1.type_back))) in
let b = fst (unTensorW (snd (unTensorW w2.type_forward))) in
(x, mkLetW (mkVar x)
((sigma, y),
mkLetW (mkVar y)
((c, v),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkAppW (project b a) (mkVar c))
(mkVar v)))))
)
| LWeak(w1 (* \Tens A X *),
w2 (* \Tens B X *)) (* B <= A *) when w2.src = dst ->
(* <sigma, <c, v>> @ w2 -> <sigma, <embed b a c, v>> @ w1 *)
let a = fst (unTensorW (snd (unTensorW w1.type_forward))) in
let b = fst (unTensorW (snd (unTensorW w2.type_back))) in
(x, mkLetW (mkVar x)
((sigma, y),
mkLetW (mkVar y)
((c, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkAppW (embed b a) (mkVar c))
(mkVar v)))))
)
| Epsilon(w1 (* [A] *),
w2 (* \Tens A [B] *),
w3 (* [B] *)) when w1.src = dst ->
(* <sigma, v> @ w1 -> <sigma, <v,*>> @ w2 *)
(x, mkLetW (mkVar x) ((sigma, v),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkPairW (mkVar v) mkUnitW)))
)
| Epsilon(w1 (* [A] *),
w2 (* \Tens A [B] *),
w3 (* [B] *)) when w2.src = dst ->
(* <sigma, <c, v>> @ w1 -> <sigma, v> @ w3 *)
(x, mkLetW (mkVar x) ((sigma, x),
mkLetW (mkVar x) ((c, v),
in_k w3.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkVar v))
))
)
| Epsilon(w1 (* [A] *),
w2 (* \Tens A [B] *),
w3 (* [B] *)) when w3.src = dst ->
(* <sigma, v> @ w3 -> <sigma, *> @ w1 *)
(x, mkLetW (mkVar x) ((sigma, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) mkUnitW))
)
| _ ->
assert false
end
with
| Not_found ->
if 0 = dst then (* output *)
(x, in_k 0 (max_wire_src_dst + 1) (mkVar x))
else (* wire must be unused because of weakening *)
(x, mkConstW None Cbot)
in
(* the term describing what happens to dart number k *)
let rec part src wrs =
match wrs with
| [] ->
if 0 = src then
action c.output.src
else
let x = fresh_var () in
(x, mkConstW None Cbot)
| w::rest ->
if w.src = src then action w.dst else part src rest
in
let rec whole =
let x = fresh_var () in
let y = fresh_var () in
let rec mkitoj i j = if i > j then [] else i :: (mkitoj (i+1) j) in
(x, mkCaseW (mkVar x)
[part 0 all_wires;
(y, mkCaseW (mkVar y)
(List.map (fun k -> part k all_wires)
(mkitoj 1 max_wire_src_dst)))])
in
let (x, w) = whole in
mkLambdaW ((x, None), w)
let termW_of_circuit (c: circuit) : Term.t =
(* Rename the wires so that the output wire has label 0 *)
let pi i =
if i = 0 then c.output.dst else if i = c.output.dst then 0 else i in
let c' = { output = map_wire pi c.output;
instructions = List.map (map_instruction pi) c.instructions} in
let mp_term = message_passing_term c' in
let compiled_term = mkTrW (mp_term) in
(* compiled_term has type 'a * X --> 'a * Y, we extract the X --> Y part.
* Note: The compiled term is closed, so "x" cannot capture anything. *)
mkLambdaW (("x", None),
mkLetW (mkAppW compiled_term (mkPairW mkUnitW (mkVar "x")))
((unusable_var, "x"), mkVar "x")
)
let compile_termU (t: Term.t) : Term.t * Type.t =
let t = t in ( * TODO : ? ? ?
let graph = circuit_of_termU [] [] t in
let a = infer_types graph in
let compiled_term = termW_of_circuit graph in
(* let a = principal_typeW [] compiled_term in *)
(compiled_term, a)
| null | https://raw.githubusercontent.com/uelis/IntML/d0d29b689e2503642aeb9c0b9a35cc61a26419a6/compile.ml | ocaml | * Compilation to circuits
Conveniencene function for n-ary let on WC level
TODO: document
* A wire represents a dart in an undirected graph.
All wires are meant to 'leave' the instructions, i.e. they are all affixed
* with their src-label to the instruction.
* The type of the respective wires is indicated in the comments.
[f]
X
Y
X \otimes Y
\Tens A X
X
\Tens{A+B} X
\Tens A X
\Tens B X
X
\Tens A X
\Tens (A x B) X
\Tens B X
\Tens A X
\Tens B X
where B <= A
[A]
\Tens A [B]
[B]
renaming of wires
Wires for all the variables in the context.
* They point into the graph with their dst-label.
ASSUMPTION: all annotations must have type variables as index
* types.
* TODO: Give a warning otherwise!
ensure "x" and "y" are fresh
ensure "x" is fresh
\Tens{A+B} X
\Tens A X
\Tens B X
X
\Tens A X
\Tens (A x B) X
\Tens B X
\Tens A X
\Tens B X
B <= A
[A]
\Tens A [B]
[B]
Weakening
Injection into the k-th component (from the left) of an n-fold sum.
* Assumes 0 <= k < n.
inverse to in_k: out_k (in_k k n t) n = (k, t)
* Compilation of string diagram into a lower-level term.
Information about the wires in the graph
Rename the variables in the instruction list so that
* they do not clash with the name supply below.
*
Supply of fresh variable names.
* (The instructions do not contain a free variable starting with "x")
action finds the node to which dst is connected
* and returns the action that must happen if the token
* is passed along that path
\Tens{A+B} X
\Tens A X
\Tens B X
\Tens{A+B} X
\Tens A X
\Tens B X
\Tens{A+B} X
\Tens A X
\Tens B X
X
\Tens A X
<<sigma, c>, v> -> <sigma, <c, v>>
X
\Tens A X
<sigma, <c, v>> -> <<sigma, c>, v>
\Tens (A x B) X
\Tens B X
<sigma, <<d, c>, v>> -> <<sigma, d>, <c, v>>
\Tens (A x B) X
\Tens B X
<<sigma, d>, <c, v>> -> <sigma, <<d, c>, v>>
\Tens A X
\Tens B X
B <= A
<sigma, <c, v>> @ w1 -> <sigma, <project b a c, v>> @ w2
\Tens A X
\Tens B X
B <= A
<sigma, <c, v>> @ w2 -> <sigma, <embed b a c, v>> @ w1
[A]
\Tens A [B]
[B]
<sigma, v> @ w1 -> <sigma, <v,*>> @ w2
[A]
\Tens A [B]
[B]
<sigma, <c, v>> @ w1 -> <sigma, v> @ w3
[A]
\Tens A [B]
[B]
<sigma, v> @ w3 -> <sigma, *> @ w1
output
wire must be unused because of weakening
the term describing what happens to dart number k
Rename the wires so that the output wire has label 0
compiled_term has type 'a * X --> 'a * Y, we extract the X --> Y part.
* Note: The compiled term is closed, so "x" cannot capture anything.
let a = principal_typeW [] compiled_term in | open Term
open Unify
open Typing
let let_tupleW (x: var) ((sigma: var list), (f: Term.t)) : Term.t =
let rec remove_shadow sigma =
match sigma with
| [] -> []
| x :: rest ->
x :: remove_shadow
(List.map (fun y -> if x = y then Term.unusable_var else y)
rest)
in
let rec let_tuple x (sigma, f) =
match sigma with
| [] -> f
| z :: rest ->
mkLetW (mkVar x) ((x, z), let_tuple x (rest, f))
in let_tuple x (remove_shadow sigma, f)
let unTensorW a =
match Type.finddesc a with
| Type.TensorW(a1, a2) -> a1, a2
| _ -> assert false
type wire = {
src: int;
dst: int;
type_forward: Type.t;
type_back: Type.t
}
let flip (w: wire) = {
src = w.dst;
dst = w.src;
type_forward = w.type_back;
type_back = w.type_forward
}
TODO : DOCUMENTATION
* Graph invariant : There are no two wires with w1.src = w2.src that are affixed
* to different nodes . I.e. w.src and w.dst are darts and must therefore be
* unique in the graph
* Graph invariant: There are no two wires with w1.src = w2.src that are affixed
* to different nodes. I.e. w.src and w.dst are darts and must therefore be
* unique in the graph *)
type instruction =
type circuit =
{ output : wire;
instructions : instruction list
}
let rec wires (i: instruction list): wire list =
match i with
| [] -> []
| Axiom(w1, _) :: is -> w1 :: (wires is)
| Tensor(w1, w2, w3) :: is -> w1 :: w2 :: w3 :: (wires is)
| Der(w1, w2, _) :: is -> w1 :: w2 :: (wires is)
| Contr(w1, w2, w3) :: is -> w1 :: w2 :: w3 :: (wires is)
| Door(w1, w2) :: is -> w1 :: w2 :: (wires is)
| ADoor(w1, w2) :: is -> w1 :: w2 :: (wires is)
| LWeak(w1, w2) :: is -> w1 :: w2 :: (wires is)
| Epsilon(w1, w2, w3) :: is -> w1 :: w2 :: w3 :: (wires is)
let map_wires_instruction (f: wire -> wire): instruction -> instruction =
fun i ->
match i with
| Axiom(w, t) -> Axiom(f w, t)
| Tensor(w1, w2, w3) -> Tensor(f w1, f w2, f w3)
| Der(w1, w2, t) -> Der(f w1, f w2, t)
| Contr(w1, w2, w3) -> Contr(f w1, f w2, f w3)
| Door(w1, w2) -> Door(f w1, f w2)
| ADoor(w1, w2) -> ADoor(f w1, f w2)
| LWeak(w1, w2) -> LWeak(f w1, f w2)
| Epsilon(w1, w2, w3) -> Epsilon(f w1, f w2, f w3)
let map_wire (f: int -> int): wire -> wire =
fun w ->
{src = f w.src;
dst = f w.dst;
type_forward = w.type_forward;
type_back = w.type_back
}
let map_instruction (f: int -> int): instruction -> instruction =
map_wires_instruction (map_wire f)
type ctx = (var * wire) list
module U = Unify(struct type t = unit end)
*
* Compilation of an upper - level term to a string diagram .
*
* The diagram is assumed to reside in a box of the functor
* { \Tens { An * ... * A1 } } . The components of the tuples
* are named by the variable names in sigma .
*
* Arguments :
* - sigma : Names with which the components can be accessed .
* sigma = [ c1 ; ... ; cn ] means that c1 corresponds to
* A1 and cn to An
* - gamma : Names of the wires for the context variables .
* They are directed so as to go into the diagram .
* - t : the term that is to be compiled .
*
* Result :
* - The wire that comes out of the diagram with the value of
* the term t.
* - The diagram as a list of instructions .
* Compilation of an upper-level term to a string diagram.
*
* The diagram is assumed to reside in a box of the functor
* {\Tens {An * ... * A1}}. The components of the tuples
* are named by the variable names in sigma.
*
* Arguments:
* - sigma: Names with which the components can be accessed.
* sigma = [c1; ... ;cn] means that c1 corresponds to
* A1 and cn to An
* - gamma: Names of the wires for the context variables.
* They are directed so as to go into the diagram.
* - t: the term that is to be compiled.
*
* Result:
* - The wire that comes out of the diagram with the value of
* the term t.
* - The diagram as a list of instructions.
*)
ASSUMPTION : all type annotations in t may only contain index types
* that are variables , i.e. not { 1 + 1}'a ' b , for example .
* that are variables, i.e. not {1+1}'a --o 'b, for example. *)
let circuit_of_termU (sigma: var list) (gamma: ctx) (t: Term.t): circuit =
let used_wirenames =
List.fold_right (fun (_, w) wns -> w.src :: w.dst :: wns) gamma [] in
let next_wirename = ref ((List.fold_right max used_wirenames (-1)) + 1) in
let fresh_wire () =
let n = !next_wirename in
next_wirename := !next_wirename + 2;
{ src = n;
dst = n + 1;
type_forward = Type.newty Type.Var;
type_back = Type.newty Type.Var
} in
let rec enter_box (gamma: ctx) : ctx * instruction list =
match gamma with
| [] -> ([], [])
| (x, w) :: rest ->
let (d, i) = enter_box rest in
let w' = fresh_wire () in
let w'' = fresh_wire () in
((x, w') :: d, LWeak(flip w, w'')::ADoor(flip w'', w') :: i)
in
let rec compile (sigma: var list) (gamma: ctx) (t: Term.t) =
match t.desc with
| Var(x) ->
let wx = List.assoc x gamma in
let w = fresh_wire () in
let w' = fresh_wire () in
(w, [Der(flip w', w,
(sigma, mkConstW (Some (Type.newty Type.OneW)) Cmin));
LWeak(flip wx, w')])
| HackU(_, t1) ->
let w = fresh_wire () in
(w, [(Axiom(w, (sigma, fresh_vars_for_missing_annots t1)))])
| PairU(s, t) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let (w_s, i_s) = compile sigma gamma_s s in
let (w_t, i_t) = compile sigma gamma_t t in
let w = fresh_wire () in
(w, Tensor(flip w_s, flip w_t, w) :: i_s @ i_t)
| LetU(s, (x, y, t)) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let (gamma_s_inbox, i_enter_box) = enter_box gamma_s in
let (w_s, i_s) = compile sigma gamma_s_inbox s in
let w_s_left = fresh_wire () in
let w_s_right = fresh_wire () in
let i_unpair = [Tensor(w_s_left, w_s_right, flip w_s)] in
let w_x = fresh_wire () in
let w_y = fresh_wire () in
let i_leavebox = [Door(flip w_s_left, w_x);
Door(flip w_s_right, w_y)] in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let (w_t, i_t) = compile sigma ((y, w_y) :: (x, w_x) :: gamma_t) t in
(w_t, i_t @ i_s @ i_enter_box @ i_unpair @ i_leavebox)
| AppU(s, t) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let (w_s, i_s) = compile sigma gamma_s s in
let (w_t, i_t) = compile_in_box unusable_var sigma gamma_t t in
let wr = fresh_wire () in
(wr, Tensor(flip w_t, wr, flip w_s) :: i_s @ i_t)
| CopyU(s, (x,y, t)) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let (w_s, i_s) = compile_in_box unusable_var sigma gamma_s s in
let w_x = fresh_wire () in
let w_y = fresh_wire () in
let (w_t, i_t) = compile sigma ((x, w_x) :: (y, w_y) :: gamma_t) t in
(w_t, Contr(flip w_s, w_x, w_y) :: i_s @ i_t)
| CaseU(f, (x, s), (y, t)) ->
let duplicate_and_enter_wire (w: wire)
: wire * wire * instruction list =
let w', wl, wr = fresh_wire (), fresh_wire (), fresh_wire () in
let wl_in_box, wr_in_box = fresh_wire (), fresh_wire () in
(wl_in_box, wr_in_box,
[Der(w', flip w, (sigma, fresh_vars_for_missing_annots f));
Contr(flip w', wl, wr);
Door(wl_in_box, flip wl); Door(wr_in_box, flip wr)])
in
let rec duplicate_and_enter_ctx (c: ctx)
: ctx * ctx * instruction list =
match c with
| [] -> ([], [], [])
| (x, w) :: rest ->
let (wl, wr, is) = duplicate_and_enter_wire w in
let (dl, dr, i') = duplicate_and_enter_ctx rest in
((x, wl) :: dl, (x, wr) :: dr, is @ i')
in
let (gammal, gammar, i_dup) = duplicate_and_enter_ctx gamma in
let (w_s_in_box, i_s) = compile (x :: sigma) gammal s in
let (w_t_in_box, i_t) = compile (y :: sigma) gammar t in
let w_s, w_t = fresh_wire (), fresh_wire () in
let i_leavebox = [Door(flip w_s_in_box, w_s);
Door(flip w_t_in_box, w_t)] in
let w_join = fresh_wire () in
let i_join = [Contr(w_join, flip w_s, flip w_t)] in
let w = fresh_wire () in
let i_der = [Der(flip w_join, w,
(sigma, fresh_vars_for_missing_annots f))] in
(w, i_der @ i_join @ i_leavebox @ i_s @ i_t @ i_dup)
| BoxTermU(t) ->
let w = fresh_wire () in
(w, [Axiom(w,
(sigma, mkLambdaW ((unusable_var, Some (Type.newty Type.OneW)),
fresh_vars_for_missing_annots t)))])
| LetBoxU(s, (c, t)) ->
let fv_s = free_vars s in
let fv_t = free_vars t in
let gamma_s = List.filter (fun (x,a) -> List.mem x fv_s) gamma in
let gamma_t = List.filter (fun (x,a) -> List.mem x fv_t
&& (not (List.mem x fv_s))) gamma in
let wr = fresh_wire () in
let (w_s, i_s) = compile sigma gamma_s s in
let (w_t, i_t) = compile_in_box c sigma gamma_t t in
(wr, Epsilon(flip w_s, flip w_t, wr) :: i_s @ i_t)
| LambdaU((x, None), s) ->
let wx = fresh_wire () in
let w = fresh_wire () in
let (w_s, i_s) = (compile sigma ((x, wx) :: gamma) s) in
(w, Tensor(wx, flip w_s, w) :: i_s)
| LambdaU((x, Some ty), s) ->
let tym, typ = Type.question_answer_pair (Type.freshen_index_types ty) in
let alpha1, alpha2 = Type.newty Type.Var, Type.newty Type.Var in
let sigma1, sigma2 = Type.newty Type.Var, Type.newty Type.Var in
let tyTensor (s, t) = Type.newty (Type.TensorW(s, t)) in
let wx =
{ (fresh_wire ()) with
type_forward = tyTensor(sigma1, tyTensor(alpha1, typ));
type_back = tyTensor(sigma2, tyTensor(alpha2, tym))} in
let w = fresh_wire () in
let (w_s, i_s) = (compile sigma ((x, wx) :: gamma) s) in
(w, Tensor(wx, flip w_s, w) :: i_s)
| TypeAnnot (t, None) ->
compile sigma gamma t
| TypeAnnot (t, Some ty) ->
let (w, ins) = compile sigma gamma t in
let tyTensor (s, t) = Type.newty (Type.TensorW(s, t)) in
let sigma1, sigma2 = Type.newty Type.Var, Type.newty Type.Var in
let tym, typ = Type.question_answer_pair (Type.freshen_index_types ty) in
U.unify w.type_forward (tyTensor(sigma1, typ));
U.unify w.type_back (tyTensor(sigma1, tym));
(w, ins)
| TrW _|LambdaW (_, _)|AppW (_, _)|CaseW (_, _)| InW (_, _, _)
| LetBoxW(_,_) | LetW (_, _)|PairW (_, _)|ConstW (_, _)|UnitW ->
assert false
and compile_in_box (c: var) (sigma: var list) (gamma: ctx) (t: Term.t) =
let (gamma_in_box, i_enter_box) = enter_box gamma in
let (w_t, i_t) = compile (c :: sigma) gamma_in_box t in
let w = fresh_wire () in
(w, Door(flip w_t, w) :: i_t @ i_enter_box)
in
let w, is = compile sigma gamma t in
{ output = w; instructions = is }
* Infers types in the string diagram and instantiated the
* terms in the Der- and Axiom - nodes so that the pre_term
* computed below will in fact be a proper term and we
* wo n't have to run type inference on it .
*
* Inequality constraints are solved * after * all other equality constraints are
* solved . This corresponds to first computing the constraints that the rules
* impose locally and then connecting them with the inequality constraints .
* TODO : We should prove that this is correct !
* Infers types in the string diagram and instantiated the
* terms in the Der- and Axiom-nodes so that the pre_term
* computed below will in fact be a proper term and we
* won't have to run type inference on it.
*
* Inequality constraints are solved *after* all other equality constraints are
* solved. This corresponds to first computing the constraints that the rules
* impose locally and then connecting them with the inequality constraints.
* TODO: We should prove that this is correct!
*)
let infer_types (c : circuit) : Type.t =
let tensor s t = Type.newty (Type.TensorW(s, t)) in
let sum s t = Type.newty (Type.SumW [s; t]) in
let rec constraints (instructions: instruction list)
: Typing.type_constraint list =
match instructions with
| [] -> []
| Axiom(w1, (s, f))::rest ->
let sigma = Type.newty Type.Var in
let alpha = Type.newty Type.Var in
let x, y = "x", "y" in
let s' = List.map variant_var s in
let tyfapp = principal_typeW
[(x, sigma); (y, alpha)]
(mkAppW (let_tupleW x (s', f')) (mkVar y)) in
Typing.eq_constraint
w1.type_forward
(Type.newty (Type.TensorW(sigma, tyfapp))) ::
Typing.eq_constraint
(flip w1).type_forward
(Type.newty (Type.TensorW(sigma, alpha))) ::
(constraints rest)
| Tensor(w1, w2, w3)::rest ->
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
Typing.eq_constraint
w3.type_forward (tensor sigma1 (sum alpha1 beta1)) ::
Typing.eq_constraint
w1.type_back (tensor sigma1 alpha1) ::
Typing.eq_constraint
w2.type_back (tensor sigma1 beta1) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward (tensor sigma2 alpha2) ::
Typing.eq_constraint
w2.type_forward (tensor sigma2 beta2) ::
Typing.eq_constraint
w3.type_back
(tensor sigma2 (sum alpha2 beta2)) ::
(constraints rest)
| Der(w1, w2, (s, f))::rest ->
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward (tensor sigma1 beta1) ::
Typing.eq_constraint
w1.type_back (tensor sigma1 (tensor alpha1 beta1)) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let x = "x" in
let f' = variant f in
let s' = List.map variant_var s in
let tyf = principal_typeW [(x, sigma2)] (let_tupleW x (s', f')) in
Typing.eq_constraint
w1.type_forward (tensor sigma2 (tensor tyf alpha2)) ::
Typing.eq_constraint
w2.type_back (tensor sigma2 alpha2) ::
(constraints rest)
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
let gamma1 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward
(tensor sigma1 (tensor (sum alpha1 beta1) gamma1)) ::
Typing.eq_constraint
w2.type_back (tensor sigma1 (tensor alpha1 gamma1)) ::
Typing.eq_constraint
w3.type_back (tensor sigma1 (tensor beta1 gamma1)) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
let gamma2 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward
(tensor sigma2 (tensor alpha2 gamma2)) ::
Typing.eq_constraint
w3.type_forward
(tensor sigma2 (tensor beta2 gamma2)) ::
Typing.eq_constraint
w1.type_back
(tensor sigma2 (tensor (sum alpha2 beta2) gamma2)) ::
(constraints rest)
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward (tensor sigma1 (tensor alpha1 beta1)) ::
Typing.eq_constraint
w1.type_back
(tensor (tensor sigma1 alpha1) beta1) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward
(tensor (tensor sigma2 alpha2) beta2) ::
Typing.eq_constraint
w2.type_back
(tensor sigma2 (tensor alpha2 beta2)) ::
(constraints rest)
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
let beta1 = Type.newty Type.Var in
let gamma1 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward
(tensor (tensor sigma1 alpha1) (tensor beta1 gamma1)) ::
Typing.eq_constraint
w1.type_back
(tensor sigma1 (tensor (tensor alpha1 beta1) gamma1)) ::
let sigma2 = Type.newty Type.Var in
let alpha2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
let gamma2 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward
(tensor sigma2 (tensor (tensor alpha2 beta2) gamma2)) ::
Typing.eq_constraint
w2.type_back
(tensor (tensor sigma2 alpha2) (tensor beta2 gamma2)) ::
(constraints rest)
let sigma = Type.newty Type.Var in
let alpha = Type.newty Type.Var in
let beta = Type.newty Type.Var in
let gamma1 = Type.newty Type.Var in
let gamma2 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward (tensor sigma (tensor alpha gamma1)) ::
Typing.eq_constraint
w1.type_back (tensor sigma (tensor alpha gamma2)) ::
Typing.eq_constraint
w2.type_forward (tensor sigma (tensor beta gamma2)) ::
Typing.eq_constraint
w2.type_back (tensor sigma (tensor beta gamma1)) ::
Typing.leq_constraint beta alpha ::
(constraints rest)
let sigma1 = Type.newty Type.Var in
let alpha1 = Type.newty Type.Var in
Typing.eq_constraint
w2.type_forward
(tensor sigma1 (tensor alpha1 (Type.newty Type.OneW))) ::
Typing.eq_constraint
w1.type_back
(tensor sigma1 alpha1) ::
let sigma2 = Type.newty Type.Var in
let beta2 = Type.newty Type.Var in
Typing.eq_constraint
w3.type_forward (tensor sigma2 beta2) ::
Typing.eq_constraint
w2.type_back
(tensor sigma2 (tensor alpha1 beta2))::
let sigma3 = Type.newty Type.Var in
Typing.eq_constraint
w1.type_forward (tensor sigma3 (Type.newty Type.OneW)) ::
Typing.eq_constraint
w3.type_back (tensor sigma3 (Type.newty Type.OneW)) ::
(constraints rest) in
try
Typing.solve_constraints (constraints c.instructions);
let right_component ty =
match Type.finddesc ty with
| Type.TensorW(_, r) -> r
| _ -> failwith "Internal error: output wire has wrong type" in
Type.newty (Type.FunW(right_component (c.output.type_back),
right_component (c.output.type_forward)))
with
| U.Not_Unifiable _ ->
failwith "Internal error: cannot unify constraints in compilation"
module IntMap = Map.Make(
struct
type t = int
let compare = compare
end
)
let rec dot_of_circuit
?title:(title = "")
?wire_style:(wire_style = fun w -> "")
(c: circuit) : string =
let node_name ins =
match ins with
| Axiom(w1, _) ->
Printf.sprintf "\"Axiom({%i,%i})\"" w1.src w1.dst
| Tensor(w1, w2, w3) ->
Printf.sprintf "\"Tensor({%i,%i},{%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst w3.src w3.dst
| Der(w1, w2, _) ->
Printf.sprintf "\"Der({%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst
| Contr(w1, w2, w3) ->
Printf.sprintf "\"Contr({%i,%i},{%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst w3.src w3.dst
| Door(w1, w2) ->
Printf.sprintf "\"Door({%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst
| ADoor(w1, w2) ->
Printf.sprintf "\"ADoor({%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst
| LWeak(w1, w2) ->
Printf.sprintf "\"LWeak({%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst
| Epsilon(w1, w2, w3) ->
Printf.sprintf "\"Epsilon({%i,%i},{%i,%i},{%i,%i})\""
w1.src w1.dst w2.src w2.dst w3.src w3.dst
in
let node_label ins =
match ins with
| Axiom(_, (_, { desc= LambdaW((x, None), _) }))
when x = unusable_var -> "[...]"
| Axiom(_, _) -> "hack(...)"
| Tensor(_, _, _) -> "⊗"
| Der(_, _, _) -> "π_..."
| Contr(_, _, _) -> "a+"
| Door(_, w) ->
if w.src = -1 then "\", shape=\"plaintext" else "↑"
| ADoor(_, _) -> "↓"
| LWeak(_, _) -> "lweak"
| Epsilon(_, _, _) -> "π"
in
let instructions_with_result =
(Door(flip c.output,
{ src = (-1);
dst = (-2);
type_forward = Type.newty Type.Var;
type_back = Type.newty Type.Var})) :: c.instructions in
let node_map_by_src =
let rec build_dst_map i =
match i with
| [] -> IntMap.empty
| node :: rest ->
List.fold_right (fun w map -> IntMap.add w.src node map)
(wires [node]) (build_dst_map rest)
in build_dst_map instructions_with_result in
let buf = Buffer.create 1024 in
let nodes () =
List.iter (fun ins ->
Buffer.add_string buf (node_name ins);
Buffer.add_string buf "[label=\"";
Buffer.add_string buf (node_label ins);
Buffer.add_string buf "\"];\n") instructions_with_result
in
let edges () =
let edge srcins (w: wire) =
try
let dstins = IntMap.find w.dst node_map_by_src in
Buffer.add_string buf (node_name srcins);
Buffer.add_string buf " -> ";
Buffer.add_string buf (node_name dstins);
Buffer.add_string buf (wire_style w);
Buffer.add_string buf ";\n ";
List.iter (fun srcins -> List.iter (edge srcins) (wires [srcins]))
instructions_with_result
in
Buffer.add_string buf "digraph G {\n labelloc=t; label=\"";
Buffer.add_string buf title;
Buffer.add_string buf "\";fontname=Monospace;fontcolor=blue;fontsize=36;";
nodes ();
edges ();
Buffer.add_string buf "}";
Buffer.contents buf
let rec in_k (k: int) (n: int) (t: Term.t): Term.t =
assert (0 <= k && k < n);
if k = 0 then
mkInlW t
else
mkInrW (mkInW (n-1) (k-1) t)
let rec out_k (t: Term.t) (n: int) : int * Term.t =
match t.desc with
| InW(2, 0, s) -> (0, s)
| InW(2, 1, {desc = InW(n', k, s)}) when n = n' + 1 -> (k + 1, s)
| _ -> failwith "out_k"
exception Not_Leq
If alpha < = beta then ( embed alpha beta ) is a corresponding
* embedding from alpha to beta .
* The function raises Not_Leq if it discovers that alpha < = beta
* does not hold .
*
* embedding from alpha to beta.
* The function raises Not_Leq if it discovers that alpha <= beta
* does not hold.
* *)
let rec embed (a: Type.t) (b: Type.t) : Term.t =
if Type.equals a b then Term.mkLambdaW(("x", None), Term.mkVar "x")
else
match Type.finddesc b with
| Type.SumW[b1; b2] ->
begin try
Term.mkLambdaW(("x", None),
Term.mkInlW
(Term.mkAppW (embed a b1) (Term.mkVar "x")))
with Not_Leq ->
Term.mkLambdaW(("x", None),
Term.mkInrW
(Term.mkAppW (embed a b2) (Term.mkVar "x")))
end
| Type.TensorW(b1, b2) ->
begin try
Term.mkLambdaW(("x", None),
Term.mkPairW
(Term.mkAppW (embed a b1) (Term.mkVar "x"))
(Term.mkConstW (Some b2) Cmin))
with Not_Leq ->
Term.mkLambdaW(("x", None),
Term.mkPairW
(Term.mkConstW (Some b1) Cmin)
(Term.mkAppW (embed a b2) (Term.mkVar "x")))
end
| _ -> raise Not_Leq
If alpha < = beta then ( embed alpha beta ) is a corresponding
* embedding from beta to alpha . The functions ( embed a b ) and
* ( project a b)form a section - retraction pair .
* The function raises Not_Leq if it discovers that alpha < = beta
* does not hold .
*
* embedding from beta to alpha. The functions (embed a b) and
* (project a b)form a section-retraction pair.
* The function raises Not_Leq if it discovers that alpha <= beta
* does not hold.
* *)
let rec project (a: Type.t) (b: Type.t) : Term.t =
if Type.equals a b then Term.mkLambdaW(("x", None), Term.mkVar "x")
else
match Type.finddesc b with
| Type.SumW[b1; b2] ->
begin try
Term.mkLambdaW(
("x", None),
Term.mkCaseW (Term.mkVar "x")
[("y", Term.mkAppW (project a b1) (Term.mkVar "y"));
("y", Term.mkConstW (Some a) Cmin)])
with Not_Leq ->
Term.mkLambdaW(
("x", None),
Term.mkCaseW (Term.mkVar "x")
[("y", Term.mkConstW (Some a) Cmin);
("y", Term.mkAppW (project a b2) (Term.mkVar "y"))])
end
| Type.TensorW(b1, b2) ->
begin try
Term.mkLambdaW(("x", None),
Term.mkLetW (Term.mkVar "x")
(("y", "z"),
Term.mkAppW (project a b1) (Term.mkVar "y")))
with Not_Leq ->
Term.mkLambdaW(("x", None),
Term.mkLetW (Term.mkVar "x")
(("y", "z"),
Term.mkAppW (project a b2) (Term.mkVar "z")))
end
| _ -> raise Not_Leq
let message_passing_term (c: circuit): Term.t =
let all_wires = wires c.instructions in
let max_wire_src_dst =
List.fold_right (fun w m -> max w.src (max w.dst m)) all_wires 0 in
let instructions_fresh =
let prep_var_y x = "y" ^ x in
let prep_y (sigma, f) =
(List.map prep_var_y sigma, rename_vars prep_var_y f) in
let rec i_fresh instructions =
match instructions with
| [] -> []
| Der(w1, w2, (sigma, f)) :: rest ->
Der(w1, w2, prep_y (sigma, f)) :: (i_fresh rest)
| Axiom(w, (sigma, f)) :: rest ->
Axiom(w, prep_y (sigma, f)) :: (i_fresh rest)
| node :: rest ->
node :: (i_fresh rest)
in i_fresh c.instructions
in
let fresh_var = Vargen.mkVarGenerator "x" ~avoid:[] in
Build a map of nodes , indexed by the src - label of wires .
* Note : This uses the assumption that only one wire with a
* given node - label appears in a graph
* Note: This uses the assumption that only one wire with a
* given node-label appears in a graph *)
let node_map_by_src =
let rec build_dst_map i =
match i with
| [] -> IntMap.empty
| node :: rest ->
let ws = wires [node] in
List.fold_right (fun w map -> IntMap.add w.src node map) ws
(build_dst_map rest)
in build_dst_map instructions_fresh in
let rec action dst =
let x = fresh_var() in
let y = fresh_var() in
let sigma, v, c, d = fresh_var(), fresh_var(), fresh_var(), fresh_var() in
let to_dart d t =
(x, mkLetW (mkVar x)
((sigma, v), in_k d (max_wire_src_dst + 1) t)) in
try
begin
match IntMap.find dst node_map_by_src with
| Axiom(w1, f) when w1.src = dst ->
to_dart w1.src
(mkPairW (mkVar sigma)
(mkAppW (let_tupleW sigma f) (mkVar v)))
| Tensor(w1, w2, w3) when w1.src = dst ->
to_dart w3.src (mkPairW (mkVar sigma) (mkInlW (mkVar v)))
| Tensor(w1, w2, w3) when w2.src = dst ->
to_dart w3.src (mkPairW (mkVar sigma) (mkInrW (mkVar v)))
| Tensor(w1, w2, w3) when w3.src = dst ->
(x, mkLetW (mkVar x)
((sigma, x),
mkCaseW (mkVar x)
[(v, in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkVar v))) ;
(v, in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkVar v)))]
)
)
| Der(w1, w2, f) when w1.src = dst ->
(x, mkLetW (mkVar x) ((sigma, x),
mkLetW (mkVar x) ((c, v),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkVar v))))
)
| Der(w1, w2, f) when w2.src = dst ->
(x, mkLetW (mkVar x) ((sigma, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (let_tupleW sigma f) (mkVar v)))
))
(x, mkLetW (mkVar x) ((sigma, v),
mkLetW (mkVar v) ((c, v),
mkCaseW (mkVar c)
[(c, in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkVar c) (mkVar v)))) ;
(d, in_k w3.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkVar d) (mkVar v)))) ]
)
)
)
(x, mkLetW (mkVar x) ((sigma, v),
mkLetW (mkVar v) ((c, y),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkInlW (mkVar c)) (mkVar y)))
)
))
(x, mkLetW (mkVar x) ((sigma, v),
mkLetW (mkVar v) ((d, y),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkInrW (mkVar d)) (mkVar y)))
)
))
(x, mkLetW (mkVar x) ((x, v),
mkLetW (mkVar x) ((sigma, c),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkPairW (mkVar c) (mkVar v))))
))
(x, mkLetW (mkVar x) ((sigma, x),
mkLetW (mkVar x) ((c, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkPairW (mkVar sigma) (mkVar c)) (mkVar v)))))
(x, mkLetW (mkVar x) ((sigma, x),
mkLetW (mkVar x) ((x, v),
mkLetW (mkVar x) ((d, c),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkPairW (mkVar sigma) (mkVar d))
(mkPairW (mkVar c) (mkVar v)))))
))
(x, mkLetW (mkVar x) ((x, y),
mkLetW (mkVar x) ((sigma, d),
mkLetW (mkVar y) ((c, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkPairW (mkVar d) (mkVar c)) (mkVar v)))))
))
let a = fst (unTensorW (snd (unTensorW w1.type_back))) in
let b = fst (unTensorW (snd (unTensorW w2.type_forward))) in
(x, mkLetW (mkVar x)
((sigma, y),
mkLetW (mkVar y)
((c, v),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkAppW (project b a) (mkVar c))
(mkVar v)))))
)
let a = fst (unTensorW (snd (unTensorW w1.type_forward))) in
let b = fst (unTensorW (snd (unTensorW w2.type_back))) in
(x, mkLetW (mkVar x)
((sigma, y),
mkLetW (mkVar y)
((c, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma)
(mkPairW (mkAppW (embed b a) (mkVar c))
(mkVar v)))))
)
(x, mkLetW (mkVar x) ((sigma, v),
in_k w2.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkPairW (mkVar v) mkUnitW)))
)
(x, mkLetW (mkVar x) ((sigma, x),
mkLetW (mkVar x) ((c, v),
in_k w3.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) (mkVar v))
))
)
(x, mkLetW (mkVar x) ((sigma, v),
in_k w1.src (max_wire_src_dst + 1)
(mkPairW (mkVar sigma) mkUnitW))
)
| _ ->
assert false
end
with
| Not_found ->
(x, in_k 0 (max_wire_src_dst + 1) (mkVar x))
(x, mkConstW None Cbot)
in
let rec part src wrs =
match wrs with
| [] ->
if 0 = src then
action c.output.src
else
let x = fresh_var () in
(x, mkConstW None Cbot)
| w::rest ->
if w.src = src then action w.dst else part src rest
in
let rec whole =
let x = fresh_var () in
let y = fresh_var () in
let rec mkitoj i j = if i > j then [] else i :: (mkitoj (i+1) j) in
(x, mkCaseW (mkVar x)
[part 0 all_wires;
(y, mkCaseW (mkVar y)
(List.map (fun k -> part k all_wires)
(mkitoj 1 max_wire_src_dst)))])
in
let (x, w) = whole in
mkLambdaW ((x, None), w)
let termW_of_circuit (c: circuit) : Term.t =
let pi i =
if i = 0 then c.output.dst else if i = c.output.dst then 0 else i in
let c' = { output = map_wire pi c.output;
instructions = List.map (map_instruction pi) c.instructions} in
let mp_term = message_passing_term c' in
let compiled_term = mkTrW (mp_term) in
mkLambdaW (("x", None),
mkLetW (mkAppW compiled_term (mkPairW mkUnitW (mkVar "x")))
((unusable_var, "x"), mkVar "x")
)
let compile_termU (t: Term.t) : Term.t * Type.t =
let t = t in ( * TODO : ? ? ?
let graph = circuit_of_termU [] [] t in
let a = infer_types graph in
let compiled_term = termW_of_circuit graph in
(compiled_term, a)
|
78f3ff215fce07486d3273e046fa00312f370e6b37e1c6fa24f6d7f098a132e7 | dyoo/whalesong | sharing.rkt | #lang whalesong
(define infinite-ones
(shared ([a (cons 1 a)])
a))
(car infinite-ones)
(car (cdr infinite-ones))
(car (cdr (cdr infinite-ones)))
(newline)
(equal? (shared ([a (cons 1 (cons 2 a))])
a)
(shared ([a (cons 1 b)]
[b (cons 2 c)]
[c (cons 1 b)])
a))
(equal? (shared ([a (cons 1 (cons 2 a))])
a)
(shared ([a (cons 1 b)]
[b (cons 2 b)])
a))
(newline)
(define 1-and-2 (shared ([a (cons 1 b)]
[b (cons 2 a)])
a))
(car 1-and-2)
(car (cdr 1-and-2))
(car (cdr (cdr 1-and-2)))
(car (cdr (cdr (cdr 1-and-2))))
(define vector-and-boxes
(shared ([a (vector b b b)]
[b (box 1)])
(set-box! b 5)
a))
(unbox (vector-ref vector-and-boxes 0))
(unbox (vector-ref vector-and-boxes 1))
(unbox (vector-ref vector-and-boxes 2))
(let ([v (shared ([a (cons 1 b)]
[b 7])
a)])
(displayln (car v))
(displayln (cdr v)))
(let ([v (shared ([a (cons 1 b)] ; b is early...
[b a])
a)])
(displayln (car v))
(displayln (cdr v)))
(let ([v (shared ([a (box b)]
[b (vector (unbox a) ; unbox after a is patched
(unbox c))] ; unbox before c is patched
[c (box b)])
b)])
(displayln (eq? (vector-ref v 0) v))
(displayln (vector-ref v 1))
(displayln (vector-length v)))
(define-struct person (name friends))
(let-values ([(a b c)
(shared ([a (make-person "jill" (list b c))]
[b (make-person "jack" (list a c))]
[c (make-person "jane" (list))])
(values a b c))])
(for-each displayln (map person-name (person-friends a)))
(newline)
(for-each displayln (map person-name (person-friends b)))
(newline)
(for-each displayln (map person-name (person-friends c)))
(newline))
;; Make sure cyclic lists are treated correctly by list?
(shared ([a (cons 1 a)])
(begin
(displayln (pair? a))
(displayln (list? a))))
(shared ([a (cons 1 a)])
a)
(shared ([a (cons 1 b)]
[b (cons 2 a)])
a)
| null | https://raw.githubusercontent.com/dyoo/whalesong/636e0b4e399e4523136ab45ef4cd1f5a84e88cdc/whalesong/tests/more-tests/sharing.rkt | racket | b is early...
unbox after a is patched
unbox before c is patched
Make sure cyclic lists are treated correctly by list? | #lang whalesong
(define infinite-ones
(shared ([a (cons 1 a)])
a))
(car infinite-ones)
(car (cdr infinite-ones))
(car (cdr (cdr infinite-ones)))
(newline)
(equal? (shared ([a (cons 1 (cons 2 a))])
a)
(shared ([a (cons 1 b)]
[b (cons 2 c)]
[c (cons 1 b)])
a))
(equal? (shared ([a (cons 1 (cons 2 a))])
a)
(shared ([a (cons 1 b)]
[b (cons 2 b)])
a))
(newline)
(define 1-and-2 (shared ([a (cons 1 b)]
[b (cons 2 a)])
a))
(car 1-and-2)
(car (cdr 1-and-2))
(car (cdr (cdr 1-and-2)))
(car (cdr (cdr (cdr 1-and-2))))
(define vector-and-boxes
(shared ([a (vector b b b)]
[b (box 1)])
(set-box! b 5)
a))
(unbox (vector-ref vector-and-boxes 0))
(unbox (vector-ref vector-and-boxes 1))
(unbox (vector-ref vector-and-boxes 2))
(let ([v (shared ([a (cons 1 b)]
[b 7])
a)])
(displayln (car v))
(displayln (cdr v)))
[b a])
a)])
(displayln (car v))
(displayln (cdr v)))
(let ([v (shared ([a (box b)]
[c (box b)])
b)])
(displayln (eq? (vector-ref v 0) v))
(displayln (vector-ref v 1))
(displayln (vector-length v)))
(define-struct person (name friends))
(let-values ([(a b c)
(shared ([a (make-person "jill" (list b c))]
[b (make-person "jack" (list a c))]
[c (make-person "jane" (list))])
(values a b c))])
(for-each displayln (map person-name (person-friends a)))
(newline)
(for-each displayln (map person-name (person-friends b)))
(newline)
(for-each displayln (map person-name (person-friends c)))
(newline))
(shared ([a (cons 1 a)])
(begin
(displayln (pair? a))
(displayln (list? a))))
(shared ([a (cons 1 a)])
a)
(shared ([a (cons 1 b)]
[b (cons 2 a)])
a)
|
0b27697e292c7c7bc2e1955d2a5547dcac20a0a2efbef5645f70d1696c20be1f | melange-re/melange | ounit_bal_tree_tests.ml | let ( >:: ), ( >::: ) = OUnit.(( >:: ), ( >::: ))
let ( =~ ) = OUnit.assert_equal
module Set_poly = struct
include Set_int
let of_sorted_list xs = Array.of_list xs |> of_sorted_array
let of_array l = Ext_array.fold_left l empty add
end
let suites =
__FILE__
>::: [
( __LOC__ >:: fun _ ->
OUnit.assert_bool __LOC__
(Set_poly.invariant
(Set_poly.of_array (Array.init 1000 (fun n -> n)))) );
( __LOC__ >:: fun _ ->
OUnit.assert_bool __LOC__
(Set_poly.invariant
(Set_poly.of_array (Array.init 1000 (fun n -> 1000 - n)))) );
( __LOC__ >:: fun _ ->
OUnit.assert_bool __LOC__
(Set_poly.invariant
(Set_poly.of_array (Array.init 1000 (fun _ -> Random.int 1000))))
);
( __LOC__ >:: fun _ ->
OUnit.assert_bool __LOC__
(Set_poly.invariant
(Set_poly.of_sorted_list
(Array.to_list (Array.init 1000 (fun n -> n))))) );
( __LOC__ >:: fun _ ->
let arr = Array.init 1000 (fun n -> n) in
let set = Set_poly.of_sorted_array arr in
OUnit.assert_bool __LOC__ (Set_poly.invariant set);
OUnit.assert_equal 1000 (Set_poly.cardinal set) );
( __LOC__ >:: fun _ ->
for i = 0 to 200 do
let arr = Array.init i (fun n -> n) in
let set = Set_poly.of_sorted_array arr in
OUnit.assert_bool __LOC__ (Set_poly.invariant set);
OUnit.assert_equal i (Set_poly.cardinal set)
done );
( __LOC__ >:: fun _ ->
let arr_size = 200 in
let arr_sets = Array.make 200 Set_poly.empty in
for i = 0 to arr_size - 1 do
let size = Random.int 1000 in
let arr = Array.init size (fun n -> n) in
arr_sets.(i) <- Set_poly.of_sorted_array arr
done;
let large = Array.fold_left Set_poly.union Set_poly.empty arr_sets in
OUnit.assert_bool __LOC__ (Set_poly.invariant large) );
( __LOC__ >:: fun _ ->
let arr_size = 1_00_000 in
let v = ref Set_int.empty in
for _ = 0 to arr_size - 1 do
let size = Random.int 0x3FFFFFFF in
v := Set_int.add !v size
done;
OUnit.assert_bool __LOC__ (Set_int.invariant !v) );
]
type ident = { stamp : int; name : string; mutable flags : int }
module Set_ident = Set.Make (struct
type t = ident
let compare = Stdlib.compare
end)
let compare_ident x y =
let a = compare (x.stamp : int) y.stamp in
if a <> 0 then a
else
let b = compare (x.name : string) y.name in
if b <> 0 then b else compare (x.flags : int) y.flags
let rec add (tree : _ Set_gen.t) x =
match tree with
| Empty -> Set_gen.singleton x
| Leaf v ->
let c = compare_ident x v in
if c = 0 then tree
else if c < 0 then Set_gen.unsafe_two_elements x v
else Set_gen.unsafe_two_elements v x
| Node { l; v; r } as t ->
let c = compare_ident x v in
if c = 0 then t
else if c < 0 then Set_gen.bal (add l x) v r
else Set_gen.bal l v (add r x)
let rec mem (tree : _ Set_gen.t) x =
match tree with
| Empty -> false
| Leaf v -> compare_ident x v = 0
| Node { l; v; r } ->
let c = compare_ident x v in
c = 0 || mem (if c < 0 then l else r) x
module Ident_set2 = Set.Make (struct
type t = ident
let compare = compare_ident
end)
let bench () =
let times = 1_000_000 in
Ounit_tests_util.time "functor set" (fun _ ->
let v = ref Set_ident.empty in
for i = 0 to times do
v := Set_ident.add { stamp = i; name = "name"; flags = -1 } !v
done;
for i = 0 to times do
ignore @@ Set_ident.mem { stamp = i; name = "name"; flags = -1 } !v
done);
Ounit_tests_util.time "functor set (specialized)" (fun _ ->
let v = ref Ident_set2.empty in
for i = 0 to times do
v := Ident_set2.add { stamp = i; name = "name"; flags = -1 } !v
done;
for i = 0 to times do
ignore @@ Ident_set2.mem { stamp = i; name = "name"; flags = -1 } !v
done);
Ounit_tests_util.time "poly set" (fun _ ->
let module Set_poly = Set_ident in
let v = ref Set_poly.empty in
for i = 0 to times do
v := Set_poly.add { stamp = i; name = "name"; flags = -1 } !v
done;
for i = 0 to times do
ignore @@ Set_poly.mem { stamp = i; name = "name"; flags = -1 } !v
done);
Ounit_tests_util.time "poly set (specialized)" (fun _ ->
let v = ref Set_gen.empty in
for i = 0 to times do
v := add !v { stamp = i; name = "name"; flags = -1 }
done;
for i = 0 to times do
ignore @@ mem !v { stamp = i; name = "name"; flags = -1 }
done)
| null | https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/ounit_tests/ounit_bal_tree_tests.ml | ocaml | let ( >:: ), ( >::: ) = OUnit.(( >:: ), ( >::: ))
let ( =~ ) = OUnit.assert_equal
module Set_poly = struct
include Set_int
let of_sorted_list xs = Array.of_list xs |> of_sorted_array
let of_array l = Ext_array.fold_left l empty add
end
let suites =
__FILE__
>::: [
( __LOC__ >:: fun _ ->
OUnit.assert_bool __LOC__
(Set_poly.invariant
(Set_poly.of_array (Array.init 1000 (fun n -> n)))) );
( __LOC__ >:: fun _ ->
OUnit.assert_bool __LOC__
(Set_poly.invariant
(Set_poly.of_array (Array.init 1000 (fun n -> 1000 - n)))) );
( __LOC__ >:: fun _ ->
OUnit.assert_bool __LOC__
(Set_poly.invariant
(Set_poly.of_array (Array.init 1000 (fun _ -> Random.int 1000))))
);
( __LOC__ >:: fun _ ->
OUnit.assert_bool __LOC__
(Set_poly.invariant
(Set_poly.of_sorted_list
(Array.to_list (Array.init 1000 (fun n -> n))))) );
( __LOC__ >:: fun _ ->
let arr = Array.init 1000 (fun n -> n) in
let set = Set_poly.of_sorted_array arr in
OUnit.assert_bool __LOC__ (Set_poly.invariant set);
OUnit.assert_equal 1000 (Set_poly.cardinal set) );
( __LOC__ >:: fun _ ->
for i = 0 to 200 do
let arr = Array.init i (fun n -> n) in
let set = Set_poly.of_sorted_array arr in
OUnit.assert_bool __LOC__ (Set_poly.invariant set);
OUnit.assert_equal i (Set_poly.cardinal set)
done );
( __LOC__ >:: fun _ ->
let arr_size = 200 in
let arr_sets = Array.make 200 Set_poly.empty in
for i = 0 to arr_size - 1 do
let size = Random.int 1000 in
let arr = Array.init size (fun n -> n) in
arr_sets.(i) <- Set_poly.of_sorted_array arr
done;
let large = Array.fold_left Set_poly.union Set_poly.empty arr_sets in
OUnit.assert_bool __LOC__ (Set_poly.invariant large) );
( __LOC__ >:: fun _ ->
let arr_size = 1_00_000 in
let v = ref Set_int.empty in
for _ = 0 to arr_size - 1 do
let size = Random.int 0x3FFFFFFF in
v := Set_int.add !v size
done;
OUnit.assert_bool __LOC__ (Set_int.invariant !v) );
]
type ident = { stamp : int; name : string; mutable flags : int }
module Set_ident = Set.Make (struct
type t = ident
let compare = Stdlib.compare
end)
let compare_ident x y =
let a = compare (x.stamp : int) y.stamp in
if a <> 0 then a
else
let b = compare (x.name : string) y.name in
if b <> 0 then b else compare (x.flags : int) y.flags
let rec add (tree : _ Set_gen.t) x =
match tree with
| Empty -> Set_gen.singleton x
| Leaf v ->
let c = compare_ident x v in
if c = 0 then tree
else if c < 0 then Set_gen.unsafe_two_elements x v
else Set_gen.unsafe_two_elements v x
| Node { l; v; r } as t ->
let c = compare_ident x v in
if c = 0 then t
else if c < 0 then Set_gen.bal (add l x) v r
else Set_gen.bal l v (add r x)
let rec mem (tree : _ Set_gen.t) x =
match tree with
| Empty -> false
| Leaf v -> compare_ident x v = 0
| Node { l; v; r } ->
let c = compare_ident x v in
c = 0 || mem (if c < 0 then l else r) x
module Ident_set2 = Set.Make (struct
type t = ident
let compare = compare_ident
end)
let bench () =
let times = 1_000_000 in
Ounit_tests_util.time "functor set" (fun _ ->
let v = ref Set_ident.empty in
for i = 0 to times do
v := Set_ident.add { stamp = i; name = "name"; flags = -1 } !v
done;
for i = 0 to times do
ignore @@ Set_ident.mem { stamp = i; name = "name"; flags = -1 } !v
done);
Ounit_tests_util.time "functor set (specialized)" (fun _ ->
let v = ref Ident_set2.empty in
for i = 0 to times do
v := Ident_set2.add { stamp = i; name = "name"; flags = -1 } !v
done;
for i = 0 to times do
ignore @@ Ident_set2.mem { stamp = i; name = "name"; flags = -1 } !v
done);
Ounit_tests_util.time "poly set" (fun _ ->
let module Set_poly = Set_ident in
let v = ref Set_poly.empty in
for i = 0 to times do
v := Set_poly.add { stamp = i; name = "name"; flags = -1 } !v
done;
for i = 0 to times do
ignore @@ Set_poly.mem { stamp = i; name = "name"; flags = -1 } !v
done);
Ounit_tests_util.time "poly set (specialized)" (fun _ ->
let v = ref Set_gen.empty in
for i = 0 to times do
v := add !v { stamp = i; name = "name"; flags = -1 }
done;
for i = 0 to times do
ignore @@ mem !v { stamp = i; name = "name"; flags = -1 }
done)
| |
d5e3d9ee63126ef8dfc81602b0c51cd38defb719a788d381b66d5de969b9aab7 | OCamlPro/ez_api | ezDebug.mli | (**************************************************************************)
(* *)
(* Copyright 2018-2023 OCamlPro *)
(* *)
(* 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. *)
(* *)
(**************************************************************************)
val printf : ('a, unit, string, unit) format4 -> 'a
val log : string -> unit
| null | https://raw.githubusercontent.com/OCamlPro/ez_api/5253f7dd8936e923290aa969ee43ebd3dc6fce2d/src/common/virtual/ezDebug.mli | ocaml | ************************************************************************
Copyright 2018-2023 OCamlPro
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************ | GNU Lesser General Public License version 2.1 , with the special
val printf : ('a, unit, string, unit) format4 -> 'a
val log : string -> unit
|
139103a96b5b0b1eccc98fd3fdf3e961fd82565878c1f93dabf1f1a50a153677 | coast-framework/db | core.clj | (ns db.core
(:require [db.connector]
[db.transactor]
[db.migrator]
[db.associator]
[db.migrator.helper]
[db.migrator.generator]
[db.defq]
[clojure.java.jdbc :as jdbc])
(:refer-clojure :exclude [update drop]))
(def query db.transactor/query)
(def execute db.transactor/execute)
(def insert db.transactor/insert)
(def insert-all db.transactor/insert-all)
(def update db.transactor/update)
(def update-all db.transactor/update-all)
(def upsert db.transactor/upsert)
(def upsert-all db.transactor/upsert-all)
(def delete db.transactor/delete)
(def delete-all db.transactor/delete-all)
(def fetch db.transactor/fetch)
(def from db.transactor/from)
(def q db.transactor/q)
(def pull db.transactor/pull)
(defmacro with-transaction [binder context & body]
`(jdbc/with-db-transaction [~binder ~context]
~@body))
(defmacro defq
([n filename]
`(let [q-fn# (-> (db.defq/query ~(str n) ~filename)
(assoc :ns *ns*)
(db.defq/query-fn))]
(db.defq/create-root-var ~(str n) q-fn#)))
([filename]
`(db.defq/query-fns ~filename)))
(def migration db.migrator.generator/migration)
(def migrate db.migrator/migrate)
(def rollback db.migrator/rollback)
(def create db.migrator/create)
(def drop db.migrator/drop)
(def create-table db.migrator.helper/create-table)
(def drop-table db.migrator.helper/drop-table)
(def add-column db.migrator.helper/add-column)
(def add-index db.migrator.helper/add-index)
(def add-foreign-key db.migrator.helper/add-foreign-key)
(def add-reference db.migrator.helper/add-reference)
(def drop-foreign-key db.migrator.helper/drop-foreign-key)
(def drop-column db.migrator.helper/drop-column)
(def drop-index db.migrator.helper/drop-index)
(def drop-reference db.migrator.helper/drop-reference)
(def text db.migrator.helper/text)
(def integer db.migrator.helper/integer)
(def bool db.migrator.helper/bool)
(def decimal db.migrator.helper/decimal)
(def uuid db.migrator.helper/uuid)
(def reference db.migrator.helper/reference)
(def tables db.associator/tables)
(def table db.associator/table)
(def primary-key db.associator/primary-key)
(def has-many db.associator/has-many)
(def belongs-to db.associator/belongs-to)
(def context db.connector/context)
(def connect db.connector/connect)
(def disconnect db.connector/disconnect)
| null | https://raw.githubusercontent.com/coast-framework/db/e738cd6402a89c591363ac6f3e7a6e08bcc28a0e/src/db/core.clj | clojure | (ns db.core
(:require [db.connector]
[db.transactor]
[db.migrator]
[db.associator]
[db.migrator.helper]
[db.migrator.generator]
[db.defq]
[clojure.java.jdbc :as jdbc])
(:refer-clojure :exclude [update drop]))
(def query db.transactor/query)
(def execute db.transactor/execute)
(def insert db.transactor/insert)
(def insert-all db.transactor/insert-all)
(def update db.transactor/update)
(def update-all db.transactor/update-all)
(def upsert db.transactor/upsert)
(def upsert-all db.transactor/upsert-all)
(def delete db.transactor/delete)
(def delete-all db.transactor/delete-all)
(def fetch db.transactor/fetch)
(def from db.transactor/from)
(def q db.transactor/q)
(def pull db.transactor/pull)
(defmacro with-transaction [binder context & body]
`(jdbc/with-db-transaction [~binder ~context]
~@body))
(defmacro defq
([n filename]
`(let [q-fn# (-> (db.defq/query ~(str n) ~filename)
(assoc :ns *ns*)
(db.defq/query-fn))]
(db.defq/create-root-var ~(str n) q-fn#)))
([filename]
`(db.defq/query-fns ~filename)))
(def migration db.migrator.generator/migration)
(def migrate db.migrator/migrate)
(def rollback db.migrator/rollback)
(def create db.migrator/create)
(def drop db.migrator/drop)
(def create-table db.migrator.helper/create-table)
(def drop-table db.migrator.helper/drop-table)
(def add-column db.migrator.helper/add-column)
(def add-index db.migrator.helper/add-index)
(def add-foreign-key db.migrator.helper/add-foreign-key)
(def add-reference db.migrator.helper/add-reference)
(def drop-foreign-key db.migrator.helper/drop-foreign-key)
(def drop-column db.migrator.helper/drop-column)
(def drop-index db.migrator.helper/drop-index)
(def drop-reference db.migrator.helper/drop-reference)
(def text db.migrator.helper/text)
(def integer db.migrator.helper/integer)
(def bool db.migrator.helper/bool)
(def decimal db.migrator.helper/decimal)
(def uuid db.migrator.helper/uuid)
(def reference db.migrator.helper/reference)
(def tables db.associator/tables)
(def table db.associator/table)
(def primary-key db.associator/primary-key)
(def has-many db.associator/has-many)
(def belongs-to db.associator/belongs-to)
(def context db.connector/context)
(def connect db.connector/connect)
(def disconnect db.connector/disconnect)
| |
1591be768a368f9077f0a2bcd76dee76b83f799a82cc2b5a1b09fc215938706d | vmchale/libmeme | Wide.hs | module Text.Convert.Wide ( toWide ) where
import qualified Data.Map as M
import Text.Convert.Common
uppercaseWide :: [Char]
uppercaseWide = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lowercaseWide :: [Char]
lowercaseWide = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
digitsWide :: [Char]
digitsWide = ['0','1','2','3','4','5','6','7','8','9']
wideTable :: M.Map Char Char
wideTable = M.fromList $
zip (alphabet ++ digits) (uppercaseWide ++ lowercaseWide ++ digitsWide)
-- | \\( O(n) \\)
toWide :: String -> String
toWide = fmap (withCharTable wideTable)
| null | https://raw.githubusercontent.com/vmchale/libmeme/a1880f9c1886260e8d7ebf2e0e7844c63b0ee02b/src/Text/Convert/Wide.hs | haskell | | \\( O(n) \\) | module Text.Convert.Wide ( toWide ) where
import qualified Data.Map as M
import Text.Convert.Common
uppercaseWide :: [Char]
uppercaseWide = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lowercaseWide :: [Char]
lowercaseWide = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
digitsWide :: [Char]
digitsWide = ['0','1','2','3','4','5','6','7','8','9']
wideTable :: M.Map Char Char
wideTable = M.fromList $
zip (alphabet ++ digits) (uppercaseWide ++ lowercaseWide ++ digitsWide)
toWide :: String -> String
toWide = fmap (withCharTable wideTable)
|
9a9101e20db9b031213d26de4dc0dc59b3d7f1cdfc558e8e76c94aab1ec8bca0 | schmee/daguerreo | core.clj | (ns daguerreo.core
(:require [clojure.spec.alpha :as s]
[daguerreo.impl.engine :as engine]
[daguerreo.impl.validation :as validation]
[daguerreo.impl.specs]))
(s/fdef validate-tasks
:args (s/cat :tasks :daguerreo/tasks))
(defn validate-tasks
"Validates the integrity of a sequence of tasks, to ensure that there are no cycles, that all dependencies are present etc. If any errors are found, raises an exception and prints an error
message explaining the cause of the error(s)."
[tasks]
(validation/validate-and-report tasks))
(defn cancel
"Cancels a job. When cancelled, the job is immediately realized with the context of all tasks that were completed and with a `:daugerreo.job/status` of `:job.status/cancelled`.
Any running tasks will be cancelled and any unscheduled tasks will be skipped."
[job]
(engine/cancel job))
(s/fdef run
:args (s/alt :tasks
(s/cat :tasks :daguerreo/tasks)
:tasks+opts
(s/cat :tasks :daguerreo/tasks
:opts :daguerreo.core/run-opts)))
(defn run
"Runs a set of tasks and returns a \"job\", a derefferable that when dereffed returns the job context after the job has reached a terminal state.
The job context will always contain `:daguerreo.job/status` (see specs for the set of possible values of this key).
Validates the tasks before running them via `validate-tasks`.
`opts` is a map that can contain the following keys:
- `:event-chan` - a core.async channel that will receive all the events sent from the scheduler. Will be closed when the job reaches a terminal state. NOTE: if this channel blocks it will block the entire scheduler, preventing any tasks from running. Make sure that you are reading of the channel, or use a dropping/sliding buffer to handle back-pressure.
- `:executor` - the `java.util.Executor` that is used to run tasks.
- `:max-concurrency` - the maximum number of tasks that will run concurrently.
- `:max-retries`: the maximum number of times a tasks is restarted after a timeout or exception. This does not include the original attempt, so with N max retries a task will be run at most (N + 1) times.
- `:timeout` - the job timeout in milliseconds. After this time has passed, the job will be realized immediately with a status of `:job.status/timed-out`."
([tasks]
(engine/run tasks {}))
([tasks opts]
(engine/run tasks opts)))
| null | https://raw.githubusercontent.com/schmee/daguerreo/872bab60f627c1cd38274f651c213c0d20c07000/src/daguerreo/core.clj | clojure | (ns daguerreo.core
(:require [clojure.spec.alpha :as s]
[daguerreo.impl.engine :as engine]
[daguerreo.impl.validation :as validation]
[daguerreo.impl.specs]))
(s/fdef validate-tasks
:args (s/cat :tasks :daguerreo/tasks))
(defn validate-tasks
"Validates the integrity of a sequence of tasks, to ensure that there are no cycles, that all dependencies are present etc. If any errors are found, raises an exception and prints an error
message explaining the cause of the error(s)."
[tasks]
(validation/validate-and-report tasks))
(defn cancel
"Cancels a job. When cancelled, the job is immediately realized with the context of all tasks that were completed and with a `:daugerreo.job/status` of `:job.status/cancelled`.
Any running tasks will be cancelled and any unscheduled tasks will be skipped."
[job]
(engine/cancel job))
(s/fdef run
:args (s/alt :tasks
(s/cat :tasks :daguerreo/tasks)
:tasks+opts
(s/cat :tasks :daguerreo/tasks
:opts :daguerreo.core/run-opts)))
(defn run
"Runs a set of tasks and returns a \"job\", a derefferable that when dereffed returns the job context after the job has reached a terminal state.
The job context will always contain `:daguerreo.job/status` (see specs for the set of possible values of this key).
Validates the tasks before running them via `validate-tasks`.
`opts` is a map that can contain the following keys:
- `:event-chan` - a core.async channel that will receive all the events sent from the scheduler. Will be closed when the job reaches a terminal state. NOTE: if this channel blocks it will block the entire scheduler, preventing any tasks from running. Make sure that you are reading of the channel, or use a dropping/sliding buffer to handle back-pressure.
- `:executor` - the `java.util.Executor` that is used to run tasks.
- `:max-concurrency` - the maximum number of tasks that will run concurrently.
- `:max-retries`: the maximum number of times a tasks is restarted after a timeout or exception. This does not include the original attempt, so with N max retries a task will be run at most (N + 1) times.
- `:timeout` - the job timeout in milliseconds. After this time has passed, the job will be realized immediately with a status of `:job.status/timed-out`."
([tasks]
(engine/run tasks {}))
([tasks opts]
(engine/run tasks opts)))
| |
bccfe02036871f93214f45a5586e58f64f5029acbe375d1e0a3dddb532ea6308 | ocaml-opam/opam-user-setup | ousMisc.ml | open OusTypes
let msg fmt = Printf.kprintf print_endline fmt
let (|>) a f = f a
let (@@) f a = f a
let (/) = Filename.concat
let (@>) f g x = g (f x)
module StringMap = Map.Make(struct type t = string let compare = compare end)
type 'a stringmap = 'a StringMap.t
let lines_of_string s =
let rex = Re.(compile (char '\n')) in
let s = Re.(replace_string (compile @@ seq [ bos; rep space]) "" s) in
let s = Re.(replace_string (compile @@ seq [ rep space; eos]) "" s) in
Re_pcre.split ~rex s
let lines_of_channel ic =
let rec aux acc =
let l = try Some (input_line ic) with End_of_file -> None in
match l with
| Some s -> aux (s::acc)
| None -> acc
in
List.rev (aux [])
let lines_of_file f =
if not (Sys.file_exists f) then [] else
let ic = open_in f in
let lines = lines_of_channel ic in
close_in ic;
lines
let lines_of_command c =
let ic = Unix.open_process_in c in
let lines = lines_of_channel ic in
close_in ic;
lines
let rec mkdir_p dir =
if Sys.file_exists dir then () else
(mkdir_p (Filename.dirname dir);
Unix.mkdir dir 0o777)
let lines_to_file ?(remove_if_empty=false) lines f =
if remove_if_empty && lines = [] && Sys.file_exists f then Unix.unlink f else
mkdir_p (Filename.dirname f);
let oc = open_out f in
List.iter (fun line -> output_string oc line; output_char oc '\n') lines;
close_out oc
let opam_var v =
let cmd = Printf.sprintf "opam config var %s" v in
match lines_of_command cmd with
| [value] -> value
| _ -> failwith (Printf.sprintf "Bad answer from '%s'" cmd)
let home =
try Sys.getenv "HOME"
with Not_found -> failwith "Could not get the HOME variable"
let has_command c =
let cmd = Printf.sprintf "/bin/sh -c \"command -v %s\" >/dev/null" c in
try Sys.command cmd = 0 with Sys_error _ -> false
| null | https://raw.githubusercontent.com/ocaml-opam/opam-user-setup/8208197c93189ed10db9e4c383377e8c3a1a43cf/ousMisc.ml | ocaml | open OusTypes
let msg fmt = Printf.kprintf print_endline fmt
let (|>) a f = f a
let (@@) f a = f a
let (/) = Filename.concat
let (@>) f g x = g (f x)
module StringMap = Map.Make(struct type t = string let compare = compare end)
type 'a stringmap = 'a StringMap.t
let lines_of_string s =
let rex = Re.(compile (char '\n')) in
let s = Re.(replace_string (compile @@ seq [ bos; rep space]) "" s) in
let s = Re.(replace_string (compile @@ seq [ rep space; eos]) "" s) in
Re_pcre.split ~rex s
let lines_of_channel ic =
let rec aux acc =
let l = try Some (input_line ic) with End_of_file -> None in
match l with
| Some s -> aux (s::acc)
| None -> acc
in
List.rev (aux [])
let lines_of_file f =
if not (Sys.file_exists f) then [] else
let ic = open_in f in
let lines = lines_of_channel ic in
close_in ic;
lines
let lines_of_command c =
let ic = Unix.open_process_in c in
let lines = lines_of_channel ic in
close_in ic;
lines
let rec mkdir_p dir =
if Sys.file_exists dir then () else
(mkdir_p (Filename.dirname dir);
Unix.mkdir dir 0o777)
let lines_to_file ?(remove_if_empty=false) lines f =
if remove_if_empty && lines = [] && Sys.file_exists f then Unix.unlink f else
mkdir_p (Filename.dirname f);
let oc = open_out f in
List.iter (fun line -> output_string oc line; output_char oc '\n') lines;
close_out oc
let opam_var v =
let cmd = Printf.sprintf "opam config var %s" v in
match lines_of_command cmd with
| [value] -> value
| _ -> failwith (Printf.sprintf "Bad answer from '%s'" cmd)
let home =
try Sys.getenv "HOME"
with Not_found -> failwith "Could not get the HOME variable"
let has_command c =
let cmd = Printf.sprintf "/bin/sh -c \"command -v %s\" >/dev/null" c in
try Sys.command cmd = 0 with Sys_error _ -> false
| |
fc95fc3afc06541c996784262cf65a67d422a3263733ec0b4b1c2cb5ecd35650 | syntax-objects/syntax-parse-example | render.rkt | #lang racket/base
;; Helper functions for documenting syntax-parse examples
(provide
(except-out
(all-from-out scribble/doclang scribble/example scribble/manual) #%module-begin)
(for-syntax
(all-from-out racket/base syntax/parse))
(rename-out [module-begin #%module-begin])
tech/guide
;; Usage: @tech/guide{text}
;; where `text` refers to a technical definition.
;; Short for @tech[#:doc ....]{text},
where the ` .... ` is the module path for The Racket Guide
tech/reference
Usage : @tech / reference{text }
;; where `text` refers to a technical definition.
;; Short for @tech[#:doc ....]{text},
;; where the `....` is the module path for The Racket Reference
;; (If the name is too long for you, `rename-in` to something shorter.)
tech/syntax
;; Usage: @tech/syntax{text}
;; where `text` refers to a definition from the `syntax` lib.
racketfile
;; Usage: @racketfile{filename}
;; where `filename` is a string representing a Racket file
;; Renders the contents of `filename` as if they were copy/pasted into
;; a `racketblock`
stxbee2021
;; Usage @stxbee2021[user issue]
Renders a thank - you note for a Syntax Bee 2021 submission
adapted-from
;; Usage @adapted-from[#:what [kind #f] name url]
stxbee2021-issue
)
(require
scribble/doclang
scribble/example
scribble/manual
(only-in racket/format ~a)
(for-syntax
racket/runtime-path
racket/path
racket/base
syntax/location
syntax/parse
(only-in racket/file file->list)))
;; =============================================================================
(define-syntax (module-begin stx)
(syntax-parse stx
[(_ id . body)
(syntax/loc stx
(#%module-begin id values () . body))]))
(define-syntax (racketfile stx)
(syntax-parse stx
[(_ file-name:str)
#:with (str* ...)
(file->list (let* ([fn (syntax-e #'file-name)]
[dir (syntax-source-directory stx)])
(cond
[(complete-path? fn)
fn]
[dir
(build-path dir fn)]
[else
(raise-argument-error 'racketfile "cannot find source for '~a'" fn)]))
(lambda (p)
(let ([v (read-line p)])
(if (eof-object? v) v (string-append v "\n")))))
(with-syntax ((ctx (syntax/loc stx #'file-name)))
(syntax/loc stx
(typeset-code
#:context ctx
(quote str*) ...)))]))
(define (tech/guide . text)
(apply tech text #:doc '(lib "scribblings/guide/guide.scrbl")))
(define (tech/reference . text)
(apply tech text #:doc '(lib "scribblings/reference/reference.scrbl")))
(define (tech/syntax . text)
(apply tech text #:doc '(lib "syntax/scribblings/syntax.scrbl")))
(define (github-user usr)
(hyperlink (format "/~a" usr) (tt usr)))
(define (github-issue owner repo item)
(hyperlink (format "/~a/~a/issues/~a" owner repo item) (tt "#" item)))
(define (stxbee2021-issue item)
(github-issue "syntax-objects" "Summer2021" item))
(define (nested-inset content)
(nested #:style 'inset content))
(define (stxbee2021 user issue)
(nested-inset
(emph "Contributed by "
(github-user user)
" ("
(stxbee2021-issue (~a issue))
") during the 2021 Syntax Parse Bee."
)))
(define (adapted-from #:what [what-type #f] name url)
(define-values [what-pre what-post]
(if what-type
(values " the " (string-append " " what-type))
(values " " "")))
(nested-inset
(emph "Adapted from"
what-pre
(hyperlink url name)
what-post ".")))
| null | https://raw.githubusercontent.com/syntax-objects/syntax-parse-example/0e0f34edcb5e69706b52d0e974b34486c33d8b0c/render.rkt | racket | Helper functions for documenting syntax-parse examples
Usage: @tech/guide{text}
where `text` refers to a technical definition.
Short for @tech[#:doc ....]{text},
where `text` refers to a technical definition.
Short for @tech[#:doc ....]{text},
where the `....` is the module path for The Racket Reference
(If the name is too long for you, `rename-in` to something shorter.)
Usage: @tech/syntax{text}
where `text` refers to a definition from the `syntax` lib.
Usage: @racketfile{filename}
where `filename` is a string representing a Racket file
Renders the contents of `filename` as if they were copy/pasted into
a `racketblock`
Usage @stxbee2021[user issue]
Usage @adapted-from[#:what [kind #f] name url]
============================================================================= | #lang racket/base
(provide
(except-out
(all-from-out scribble/doclang scribble/example scribble/manual) #%module-begin)
(for-syntax
(all-from-out racket/base syntax/parse))
(rename-out [module-begin #%module-begin])
tech/guide
where the ` .... ` is the module path for The Racket Guide
tech/reference
Usage : @tech / reference{text }
tech/syntax
racketfile
stxbee2021
Renders a thank - you note for a Syntax Bee 2021 submission
adapted-from
stxbee2021-issue
)
(require
scribble/doclang
scribble/example
scribble/manual
(only-in racket/format ~a)
(for-syntax
racket/runtime-path
racket/path
racket/base
syntax/location
syntax/parse
(only-in racket/file file->list)))
(define-syntax (module-begin stx)
(syntax-parse stx
[(_ id . body)
(syntax/loc stx
(#%module-begin id values () . body))]))
(define-syntax (racketfile stx)
(syntax-parse stx
[(_ file-name:str)
#:with (str* ...)
(file->list (let* ([fn (syntax-e #'file-name)]
[dir (syntax-source-directory stx)])
(cond
[(complete-path? fn)
fn]
[dir
(build-path dir fn)]
[else
(raise-argument-error 'racketfile "cannot find source for '~a'" fn)]))
(lambda (p)
(let ([v (read-line p)])
(if (eof-object? v) v (string-append v "\n")))))
(with-syntax ((ctx (syntax/loc stx #'file-name)))
(syntax/loc stx
(typeset-code
#:context ctx
(quote str*) ...)))]))
(define (tech/guide . text)
(apply tech text #:doc '(lib "scribblings/guide/guide.scrbl")))
(define (tech/reference . text)
(apply tech text #:doc '(lib "scribblings/reference/reference.scrbl")))
(define (tech/syntax . text)
(apply tech text #:doc '(lib "syntax/scribblings/syntax.scrbl")))
(define (github-user usr)
(hyperlink (format "/~a" usr) (tt usr)))
(define (github-issue owner repo item)
(hyperlink (format "/~a/~a/issues/~a" owner repo item) (tt "#" item)))
(define (stxbee2021-issue item)
(github-issue "syntax-objects" "Summer2021" item))
(define (nested-inset content)
(nested #:style 'inset content))
(define (stxbee2021 user issue)
(nested-inset
(emph "Contributed by "
(github-user user)
" ("
(stxbee2021-issue (~a issue))
") during the 2021 Syntax Parse Bee."
)))
(define (adapted-from #:what [what-type #f] name url)
(define-values [what-pre what-post]
(if what-type
(values " the " (string-append " " what-type))
(values " " "")))
(nested-inset
(emph "Adapted from"
what-pre
(hyperlink url name)
what-post ".")))
|
e7b400dfc117ee1886dc2f0335cdf1e82a274f4917d1d653a9b409a320514e4c | chenyukang/rubytt | trans.ml | open Core
open Node
open Type
open Global
open State
let new_bind node ty kind =
let bind = Type.new_binding node ty kind in
Global.register_bind bind;
bind
let state_add_mode = ref 0;; (* fixme *)
let state_insert st id node ty kind =
let b = new_bind node ty kind in
let qname = match ty.ty with
| Module_ty(_) -> "" (* fixme *)
| Fun_ty(_) -> (extend_path st id "#")
| _ -> extend_path st id "::"
in
set_bind_qname b qname;
(* Printf.printf "set qname: %s now: %d\n" qname !state_add_mode; *)
if !state_add_mode = 0 then
State.state_update_bind st id b
else
State.state_add_bind st id b
let put_ref node bind =
let bs = [bind] in
Global.put_refs node bs
let get_modulebinding_if_global st name =
let res = ref None in
if Util.is_global_name name then
if not (phys_equal global_table st) then
res := State.lookup_local global_table name;
!res
let rec state_lookup st name =
match get_modulebinding_if_global st name with
| None -> (
match State.lookup_local st name with
| Some(b) -> Some(b)
| None -> (
match State.parent st with
| Some(p) -> state_lookup p name
| None -> None
)
)
| Some(b) -> Some(b)
let looked = Hashtbl.Poly.create()
let rec lookup_attr state id =
match Hashtbl.find looked state with
| Some(_) -> None
| _ -> (
let bs = State.lookup_local state id in
match bs with
| Some(_) -> bs
| _ -> (
Hashtbl.add_exn looked ~key:state ~data:true;
let res = match State.parent state with
| Some(p) -> lookup_attr p id
| _ -> None in
Hashtbl.remove looked state;
res)
)
let rec lookup_attr_ty state id =
let bs = lookup_attr state id in
match bs with
| Some(_bs) -> make_unions_from_bs _bs
| _ -> (
match State.super state with
| Some(super) -> lookup_attr_ty super id
| _ -> unkown_ty)
let lookup_ty state id =
let bs = state_lookup state id in
match bs with
| Some(_bs) -> make_unions_from_bs _bs
| _ -> unkown_ty
let lookup_attr_tagged st attr tag =
lookup_attr st (Util.make_tag_id attr tag)
let rec bind state (target:node_t) rt kind =
match target.ty with
| Name _ -> bind_name state target rt kind
| Array(elems) -> (
a , b = 1 , 2
bind_array state elems rt kind
)
| Subscript(_, _) -> (
)
| _ -> ()
and lookup_or_create_module state locator file =
let existing = transform locator state in
let id = name_node_id locator in
match existing.ty with
| Module_ty _ -> existing
| _ when is_name locator -> (
let bindings = lookup_attr state id in
let ret = ref Type.cont_ty in
(match bindings with
| Some(bs) -> (
if List.length bs > 0 && (List.nth_exn bs 0).kind = Type.ModuleK then
ret := (List.nth_exn bs 0).bind_ty
)
| None -> ());
if (type_equal !ret Type.cont_ty) then (
ret := new_module_type id file (Some state);
);
!ret
)
| _ when is_attr locator -> (
Type.cont_ty
)
| _ -> (
new_module_type id "" (Some state)
)
and
bind_node state (target:node_t) rt =
let kind = match State.s_type state with
| State.Function -> Type.VariableK
| State.Class | State.Instance -> Type.AttributeK
| _ -> Type.ScopeK in
bind state target rt kind
and
bind_name state name (rt:type_t) kind =
let id = name_node_id name in
if Util.is_global_name id && (name_node_is_globalvar name) then (
let b = new_bind name rt kind in
(* Printf.printf "bind global name: %s ty: %s\n" id (Printer.type_to_str rt 0); *)
State.state_update_bind global_table id b;
put_ref name b;
) else (
(* Printf.printf "bind local name: %s ty: %s\n" id (Printer.type_to_str rt 0); *)
state_insert state id name rt kind
)
and
bind_array state elems rt kind =
let elems_size = List.length elems in
match rt.ty with
| List_ty(_, tys, _) -> (
let ty_size = List.length tys in
if ty_size <> elems_size then (
(* Printf.printf "error array assign size mismatch: %d %d\n" elems_size ty_size *)
)
else
List.iteri elems ~f:(fun i e ->
let ty = List.nth_exn tys i in
bind state e ty kind
)
)
( Printf.printf " error array assign size mismtach : % d 0\n " elems_size )
and
transform (node:node_t) state =
(* Printf.printf "trans: %s\n" (Printer.node_to_str node 0); *)
match node.ty with
| Nil -> Type.unkown_ty
| Int(_) -> Type.int_ty
| Float(_) -> Type.float_ty
| Regexp(_, _) -> Type.str_ty
| String(s) -> Type.new_str_type ~value:s ()
| Symbol(s) -> Type.new_sym_type ~name:s ()
| Void -> Type.cont_ty
| StrEmbed(s) -> (
ignore(transform s state); Type.str_ty
)
| Undef(nodes) -> (
List.iter nodes ~f:(fun n ->
let _ = transform n state in
match n.ty with
| Name(id, _) -> (State.remove state id)
| _ -> ()
);
Type.cont_ty
)
| Dict(keys, vals) -> (
let key_ty = resolve_union keys state in
let val_ty = resolve_union vals state in
Type.new_dict_ty key_ty val_ty
)
| Name(id, _) -> (
(* Printf.printf "lookup name: %s\n" id; *)
match state_lookup state id with
| Some(bs) -> (
(* Printf.printf "put ref name: %s\n" id; *)
Global.put_refs node bs;
Global.set_resolve node;
(* List.iter bs ~f:(fun t -> Printf.printf "now: %s\n" (Printer.type_to_str t.bind_ty 0)); *)
make_unions_from_bs bs
)
| _ when id = "true" || id = "false" -> (
Type.bool_ty
)
| _ -> (
(* Printf.printf "error: unbound variable for %s\n" id; *)
Global.set_unresolve node;
Type.unkown_ty
)
)
| BinOp(op, ln, rn) -> (
(* let str = Printer.node_to_str node 0 in *)
Printf.printf " now result : % s\n " str ;
let _ = transform ln state in
let rt = transform rn state in
if Node.is_logic_bin node then Type.bool_ty
else (
Printf.printf " rt type : % s\n " ( Printer.type_to_str rt 0 ) ;
if not (type_equal rt Type.unkown_ty) then rt
else Type.unkown_ty
)
)
| Array(elems) -> (
let list_ty = new_list_type() in
List.iter elems ~f:(fun e ->
let t = transform e state in
list_ty_add list_ty t;
);
list_ty
)
| UnaryOp(_, operand) -> (
let r = transform operand state in
if Node.is_logic_bin node then Type.bool_ty else r
)
| Assign(target, rvalue) -> (
let vt = transform rvalue state in
let _ = transform target state in
if Node.is_instance_var target then (
let this_ty = lookup_ty state "self" in
if not(Type.is_unkown_ty this_ty) then
bind_node this_ty.info.table target vt
) else (
(* let target_v = Printer.node_to_str target 0 in *)
(* let type_v = Printer.type_to_str vt 0 in *)
(* Printf.printf "%s -> %s\n" target_v type_v; *)
bind_node state target vt
);
vt
)
| Attribute(target, attr) -> (
if is_nil target then transform attr state
else (
let target_ty = transform target state in
let id = name_node_id attr in
let bs = lookup_attr target_ty.info.table id in
match bs with
| Some(_bs) -> (
Global.put_refs attr _bs;
make_unions_from_bs _bs
)
| _ -> (
(* Printf.printf "error: '%s' attribute not found for : %s\n" *)
(* id (Printer.type_to_str target_ty 0); *)
Type.unkown_ty
)
)
)
| Subscript(value, slices) -> (
let vt = transform value state in
let st = List.map slices ~f:(fun i -> transform i state) in
Type.get_subscript_ty vt st
)
| Block(nodes) -> (
let return_ty = ref Type.cont_ty in
List.iteri nodes ~f:(fun i n ->
let ty = transform n state in
if i = (List.length nodes) - 1 then return_ty := ty;
);
!return_ty
)
| Handler(_, _, handler, _else) -> (
let handle_ty = transform handler state in
let else_ty = transform _else state in
make_unions [handle_ty; else_ty]
)
(* | Raise() *)
| Control(_) -> Type.cont_ty
| For(_, _, body) -> transform body state
| If(test, body, _else) -> (
let _ = transform test state in
let body_ty = transform body state in
incr state_add_mode;
let else_ty = transform _else state in
decr state_add_mode;
make_unions [body_ty; else_ty]
)
| While(test, body) -> (
let _ = transform test state in
transform body state
)
| Try(body, rescue, _else, final) -> (
let rescue_ty = transform rescue state in
let body_ty = transform body state in
let else_ty = transform _else state in
let final_ty = transform final state in
make_unions [body_ty; else_ty; rescue_ty; final_ty]
)
| Func(info) -> (
let _state = ref state in (
if is_attr info.locator then
let loc_ty = transform (attr_target info.locator) state in
if not (type_equal loc_ty unkown_ty) then
_state := loc_ty.info.table
);
let func_ty = new_fun_ty node (Some !_state) in
let args_ty = List.map info.defaults ~f:(fun arg -> transform arg !_state) in
let state_ty = ty_of_state !_state in
if (not info.is_lambda) && (is_class_ty state_ty) then
fun_ty_set_class_ty func_ty (Some state_ty);
fun_ty_set_def_tys func_ty args_ty;
bind_name !_state info.name func_ty Type.MethodK;
State.set_parent func_ty.info.table !_state;
let id = name_node_id info.name in
State.set_path func_ty.info.table (State.extend_path !_state id "#");
Global.set_uncalled func_ty;
func_ty
)
| Call(func, pos, star, block_arg) -> (
let _func = ref func in
let _name = ref nil_node in
let func_str = Printer.node_to_str func 0 in
(* Printf.printf "func_str: %s\n" func_str; *)
if is_attr func then (
_func := attr_target func;
(* Printf.printf "attr target: %s\n" (Printer.node_to_str !_func 0); *)
_name := attr_attr func;
(* Printf.printf "attr name: %s\n" (Printer.node_to_str !_name 0) *)
);
let fun_ty = transform !_func state in
(* Printf.printf "type str: %s\n" (Printer.type_to_str fun_ty 0); *)
let args_ty = List.map pos ~f:(fun x -> transform x state) in
let star_ty = transform star state in
let block_arg_ty = transform block_arg state in
resolve_call fun_ty !_name args_ty star_ty block_arg_ty node state
)
| Module(locator, name, body, _) -> (
let module_ty = lookup_or_create_module state locator node.info.file in
bind state name module_ty Type.ModuleK;
state_insert module_ty.info.table "self" name module_ty Type.ScopeK;
ignore(transform body module_ty.info.table);
module_ty
)
| Class(name, super, body, _, static) -> (
if (is_nil name) = false && static then (
FIXME
);
let id = name_node_id name in
let parent = Some(state) in
let super_ty = transform super state in
let class_ty = new_class_type id parent ~super:(Some super_ty) () in
bind state name class_ty Type.ClassK;
state_insert class_ty.info.table "self" name class_ty Type.ScopeK;
add_inst_type_from_db class_ty;
ignore(transform body class_ty.info.table);
Type.cont_ty
)
| Kwd(_, v) | Return(v) | Starred(v) | Yield(v)
-> transform v state
| _ -> Type.unkown_ty
and resolve_union nodes state =
let ty = ref Type.unkown_ty in
List.iter nodes ~f:(fun n ->
ty := Type.union_ty (transform n state) !ty);
!ty
and resolve_call obj name args_ty star_ty block_arg_ty call state =
match obj.ty with
| Fun_ty(_) -> apply_func obj args_ty star_ty block_arg_ty call
| Class_ty(_) -> (
let id = name_node_id name in
match id with
| "new" | "create" -> (
(* class contructor *)
let class_ty = obj in
let inst_ty = new_instance_type class_ty in
let inst_state = inst_ty.info.table in
let init_func_ty = lookup_attr_ty inst_state "initialize" in
classty_set_canon class_ty (Some inst_ty);
if not (type_equal init_func_ty unkown_ty) then (
let bs = lookup_attr inst_state "initialize" in
(match bs with
| Some(_bs) -> Global.put_refs name _bs
| _ -> ());
fun_ty_set_self_ty init_func_ty (Some inst_ty);
ignore(apply_func init_func_ty args_ty star_ty block_arg_ty call);
);
inst_ty
)
| _ -> (
(* Printf.printf "error method name: %s\n" id; *)
(* ignore(failwith "resolve_call"); *)
transform name obj.info.table
)
)
| Instance_ty(class_ty) -> (
if not (Type.is_unkown_ty obj) then (
let id = name_node_id name in
let method_ty = lookup_attr_ty class_ty.info.table id in
if Type.is_unkown_ty method_ty then (
(* Printf.printf "error unkown method: %s\n" id; *)
unkown_ty
) else
apply_func method_ty args_ty star_ty block_arg_ty call
) else unkown_ty
)
| _ -> (
match name_node_id name with
| "to_s" -> Type.new_str_type()
| "to_sym" -> Type.new_sym_type()
| "to_i" -> Type.new_int_type()
| _ -> (
(* (Printf.printf "try to resolve_call: unkown_ty\n"); *)
match obj.ty with
| Int_ty | Str_ty _ | Float_ty -> obj
| _ -> Type.unkown_ty
))
and bind_param_tys env args args_types =
List.iteri args ~f:(fun i arg ->
if i < List.length args_types then (
let arg_ty = List.nth_exn args_types i in
bind env arg arg_ty Type.ParameterK
) else
bind env arg unkown_ty Type.ParameterK
)
and apply_func fun_ty args_ty star_ty block_arg_ty call =
(* Printf.printf "apply_func: \n" ; *)
Global.set_called fun_ty;
if not (Global.contains_call call) && (Type.is_fun_ty fun_ty) then (
let info = Type.fun_ty_info fun_ty in
let node_info = func_node_info info.fun_node in
let env = State.new_state ~parent:info.env State.Function in
let _ = Global.push_call call in
let _ = bind_param_tys env node_info.args args_ty in
let ret_ty = transform node_info.body env in
if not (Type.type_equal ret_ty fun_ty) then (
fun_ty_set_ret_ty fun_ty ret_ty; ret_ty)
else Type.unkown_ty)
else
Type.unkown_ty
(* add types which analyzed from scheme.rb *)
and add_inst_type_from_db class_ty =
let class_name = classty_get_name class_ty in
let table = class_ty.info.table in
let columns = Db.class_to_model_columns class_name in
List.iter columns ~f:(fun (name, ty_str, _) ->
Printf.printf " name : % s type : % s\n " name ;
let ty = match ty_str with
| "string" | "text" -> new_str_type()
| "boolean" -> new_bool_type()
| "integer" -> new_int_type()
| _ -> unkown_ty in
state_insert table name nil_node ty Type.ScopeK;
);
()
let apply_uncalled () =
TypeSet.iter (fun fun_ty ->
let info = Type.fun_ty_info fun_ty in
(* let node_info = func_node_info info.fun_node in *)
(* let id = name_node_id node_info.name in *)
(* Printf.printf "apply id: %s\n" id; *)
let env = State.new_state ~parent : info.env State . Function in
(* let ret_ty = transform node_info.body env in *)
(* ignore(fun_ty_set_ret_ty fun_ty ret_ty)) *)
let _ = apply_func fun_ty [] unkown_ty unkown_ty info.fun_node in
()) !Global.uncalled
let transform_expr node state =
ignore(transform node state);
apply_uncalled()
| null | https://raw.githubusercontent.com/chenyukang/rubytt/3b9898cd9e180594ee30fb74cea9a8356a6e0c14/src/trans.ml | ocaml | fixme
fixme
Printf.printf "set qname: %s now: %d\n" qname !state_add_mode;
Printf.printf "bind global name: %s ty: %s\n" id (Printer.type_to_str rt 0);
Printf.printf "bind local name: %s ty: %s\n" id (Printer.type_to_str rt 0);
Printf.printf "error array assign size mismatch: %d %d\n" elems_size ty_size
Printf.printf "trans: %s\n" (Printer.node_to_str node 0);
Printf.printf "lookup name: %s\n" id;
Printf.printf "put ref name: %s\n" id;
List.iter bs ~f:(fun t -> Printf.printf "now: %s\n" (Printer.type_to_str t.bind_ty 0));
Printf.printf "error: unbound variable for %s\n" id;
let str = Printer.node_to_str node 0 in
let target_v = Printer.node_to_str target 0 in
let type_v = Printer.type_to_str vt 0 in
Printf.printf "%s -> %s\n" target_v type_v;
Printf.printf "error: '%s' attribute not found for : %s\n"
id (Printer.type_to_str target_ty 0);
| Raise()
Printf.printf "func_str: %s\n" func_str;
Printf.printf "attr target: %s\n" (Printer.node_to_str !_func 0);
Printf.printf "attr name: %s\n" (Printer.node_to_str !_name 0)
Printf.printf "type str: %s\n" (Printer.type_to_str fun_ty 0);
class contructor
Printf.printf "error method name: %s\n" id;
ignore(failwith "resolve_call");
Printf.printf "error unkown method: %s\n" id;
(Printf.printf "try to resolve_call: unkown_ty\n");
Printf.printf "apply_func: \n" ;
add types which analyzed from scheme.rb
let node_info = func_node_info info.fun_node in
let id = name_node_id node_info.name in
Printf.printf "apply id: %s\n" id;
let ret_ty = transform node_info.body env in
ignore(fun_ty_set_ret_ty fun_ty ret_ty)) | open Core
open Node
open Type
open Global
open State
let new_bind node ty kind =
let bind = Type.new_binding node ty kind in
Global.register_bind bind;
bind
let state_insert st id node ty kind =
let b = new_bind node ty kind in
let qname = match ty.ty with
| Fun_ty(_) -> (extend_path st id "#")
| _ -> extend_path st id "::"
in
set_bind_qname b qname;
if !state_add_mode = 0 then
State.state_update_bind st id b
else
State.state_add_bind st id b
let put_ref node bind =
let bs = [bind] in
Global.put_refs node bs
let get_modulebinding_if_global st name =
let res = ref None in
if Util.is_global_name name then
if not (phys_equal global_table st) then
res := State.lookup_local global_table name;
!res
let rec state_lookup st name =
match get_modulebinding_if_global st name with
| None -> (
match State.lookup_local st name with
| Some(b) -> Some(b)
| None -> (
match State.parent st with
| Some(p) -> state_lookup p name
| None -> None
)
)
| Some(b) -> Some(b)
let looked = Hashtbl.Poly.create()
let rec lookup_attr state id =
match Hashtbl.find looked state with
| Some(_) -> None
| _ -> (
let bs = State.lookup_local state id in
match bs with
| Some(_) -> bs
| _ -> (
Hashtbl.add_exn looked ~key:state ~data:true;
let res = match State.parent state with
| Some(p) -> lookup_attr p id
| _ -> None in
Hashtbl.remove looked state;
res)
)
let rec lookup_attr_ty state id =
let bs = lookup_attr state id in
match bs with
| Some(_bs) -> make_unions_from_bs _bs
| _ -> (
match State.super state with
| Some(super) -> lookup_attr_ty super id
| _ -> unkown_ty)
let lookup_ty state id =
let bs = state_lookup state id in
match bs with
| Some(_bs) -> make_unions_from_bs _bs
| _ -> unkown_ty
let lookup_attr_tagged st attr tag =
lookup_attr st (Util.make_tag_id attr tag)
let rec bind state (target:node_t) rt kind =
match target.ty with
| Name _ -> bind_name state target rt kind
| Array(elems) -> (
a , b = 1 , 2
bind_array state elems rt kind
)
| Subscript(_, _) -> (
)
| _ -> ()
and lookup_or_create_module state locator file =
let existing = transform locator state in
let id = name_node_id locator in
match existing.ty with
| Module_ty _ -> existing
| _ when is_name locator -> (
let bindings = lookup_attr state id in
let ret = ref Type.cont_ty in
(match bindings with
| Some(bs) -> (
if List.length bs > 0 && (List.nth_exn bs 0).kind = Type.ModuleK then
ret := (List.nth_exn bs 0).bind_ty
)
| None -> ());
if (type_equal !ret Type.cont_ty) then (
ret := new_module_type id file (Some state);
);
!ret
)
| _ when is_attr locator -> (
Type.cont_ty
)
| _ -> (
new_module_type id "" (Some state)
)
and
bind_node state (target:node_t) rt =
let kind = match State.s_type state with
| State.Function -> Type.VariableK
| State.Class | State.Instance -> Type.AttributeK
| _ -> Type.ScopeK in
bind state target rt kind
and
bind_name state name (rt:type_t) kind =
let id = name_node_id name in
if Util.is_global_name id && (name_node_is_globalvar name) then (
let b = new_bind name rt kind in
State.state_update_bind global_table id b;
put_ref name b;
) else (
state_insert state id name rt kind
)
and
bind_array state elems rt kind =
let elems_size = List.length elems in
match rt.ty with
| List_ty(_, tys, _) -> (
let ty_size = List.length tys in
if ty_size <> elems_size then (
)
else
List.iteri elems ~f:(fun i e ->
let ty = List.nth_exn tys i in
bind state e ty kind
)
)
( Printf.printf " error array assign size mismtach : % d 0\n " elems_size )
and
transform (node:node_t) state =
match node.ty with
| Nil -> Type.unkown_ty
| Int(_) -> Type.int_ty
| Float(_) -> Type.float_ty
| Regexp(_, _) -> Type.str_ty
| String(s) -> Type.new_str_type ~value:s ()
| Symbol(s) -> Type.new_sym_type ~name:s ()
| Void -> Type.cont_ty
| StrEmbed(s) -> (
ignore(transform s state); Type.str_ty
)
| Undef(nodes) -> (
List.iter nodes ~f:(fun n ->
let _ = transform n state in
match n.ty with
| Name(id, _) -> (State.remove state id)
| _ -> ()
);
Type.cont_ty
)
| Dict(keys, vals) -> (
let key_ty = resolve_union keys state in
let val_ty = resolve_union vals state in
Type.new_dict_ty key_ty val_ty
)
| Name(id, _) -> (
match state_lookup state id with
| Some(bs) -> (
Global.put_refs node bs;
Global.set_resolve node;
make_unions_from_bs bs
)
| _ when id = "true" || id = "false" -> (
Type.bool_ty
)
| _ -> (
Global.set_unresolve node;
Type.unkown_ty
)
)
| BinOp(op, ln, rn) -> (
Printf.printf " now result : % s\n " str ;
let _ = transform ln state in
let rt = transform rn state in
if Node.is_logic_bin node then Type.bool_ty
else (
Printf.printf " rt type : % s\n " ( Printer.type_to_str rt 0 ) ;
if not (type_equal rt Type.unkown_ty) then rt
else Type.unkown_ty
)
)
| Array(elems) -> (
let list_ty = new_list_type() in
List.iter elems ~f:(fun e ->
let t = transform e state in
list_ty_add list_ty t;
);
list_ty
)
| UnaryOp(_, operand) -> (
let r = transform operand state in
if Node.is_logic_bin node then Type.bool_ty else r
)
| Assign(target, rvalue) -> (
let vt = transform rvalue state in
let _ = transform target state in
if Node.is_instance_var target then (
let this_ty = lookup_ty state "self" in
if not(Type.is_unkown_ty this_ty) then
bind_node this_ty.info.table target vt
) else (
bind_node state target vt
);
vt
)
| Attribute(target, attr) -> (
if is_nil target then transform attr state
else (
let target_ty = transform target state in
let id = name_node_id attr in
let bs = lookup_attr target_ty.info.table id in
match bs with
| Some(_bs) -> (
Global.put_refs attr _bs;
make_unions_from_bs _bs
)
| _ -> (
Type.unkown_ty
)
)
)
| Subscript(value, slices) -> (
let vt = transform value state in
let st = List.map slices ~f:(fun i -> transform i state) in
Type.get_subscript_ty vt st
)
| Block(nodes) -> (
let return_ty = ref Type.cont_ty in
List.iteri nodes ~f:(fun i n ->
let ty = transform n state in
if i = (List.length nodes) - 1 then return_ty := ty;
);
!return_ty
)
| Handler(_, _, handler, _else) -> (
let handle_ty = transform handler state in
let else_ty = transform _else state in
make_unions [handle_ty; else_ty]
)
| Control(_) -> Type.cont_ty
| For(_, _, body) -> transform body state
| If(test, body, _else) -> (
let _ = transform test state in
let body_ty = transform body state in
incr state_add_mode;
let else_ty = transform _else state in
decr state_add_mode;
make_unions [body_ty; else_ty]
)
| While(test, body) -> (
let _ = transform test state in
transform body state
)
| Try(body, rescue, _else, final) -> (
let rescue_ty = transform rescue state in
let body_ty = transform body state in
let else_ty = transform _else state in
let final_ty = transform final state in
make_unions [body_ty; else_ty; rescue_ty; final_ty]
)
| Func(info) -> (
let _state = ref state in (
if is_attr info.locator then
let loc_ty = transform (attr_target info.locator) state in
if not (type_equal loc_ty unkown_ty) then
_state := loc_ty.info.table
);
let func_ty = new_fun_ty node (Some !_state) in
let args_ty = List.map info.defaults ~f:(fun arg -> transform arg !_state) in
let state_ty = ty_of_state !_state in
if (not info.is_lambda) && (is_class_ty state_ty) then
fun_ty_set_class_ty func_ty (Some state_ty);
fun_ty_set_def_tys func_ty args_ty;
bind_name !_state info.name func_ty Type.MethodK;
State.set_parent func_ty.info.table !_state;
let id = name_node_id info.name in
State.set_path func_ty.info.table (State.extend_path !_state id "#");
Global.set_uncalled func_ty;
func_ty
)
| Call(func, pos, star, block_arg) -> (
let _func = ref func in
let _name = ref nil_node in
let func_str = Printer.node_to_str func 0 in
if is_attr func then (
_func := attr_target func;
_name := attr_attr func;
);
let fun_ty = transform !_func state in
let args_ty = List.map pos ~f:(fun x -> transform x state) in
let star_ty = transform star state in
let block_arg_ty = transform block_arg state in
resolve_call fun_ty !_name args_ty star_ty block_arg_ty node state
)
| Module(locator, name, body, _) -> (
let module_ty = lookup_or_create_module state locator node.info.file in
bind state name module_ty Type.ModuleK;
state_insert module_ty.info.table "self" name module_ty Type.ScopeK;
ignore(transform body module_ty.info.table);
module_ty
)
| Class(name, super, body, _, static) -> (
if (is_nil name) = false && static then (
FIXME
);
let id = name_node_id name in
let parent = Some(state) in
let super_ty = transform super state in
let class_ty = new_class_type id parent ~super:(Some super_ty) () in
bind state name class_ty Type.ClassK;
state_insert class_ty.info.table "self" name class_ty Type.ScopeK;
add_inst_type_from_db class_ty;
ignore(transform body class_ty.info.table);
Type.cont_ty
)
| Kwd(_, v) | Return(v) | Starred(v) | Yield(v)
-> transform v state
| _ -> Type.unkown_ty
and resolve_union nodes state =
let ty = ref Type.unkown_ty in
List.iter nodes ~f:(fun n ->
ty := Type.union_ty (transform n state) !ty);
!ty
and resolve_call obj name args_ty star_ty block_arg_ty call state =
match obj.ty with
| Fun_ty(_) -> apply_func obj args_ty star_ty block_arg_ty call
| Class_ty(_) -> (
let id = name_node_id name in
match id with
| "new" | "create" -> (
let class_ty = obj in
let inst_ty = new_instance_type class_ty in
let inst_state = inst_ty.info.table in
let init_func_ty = lookup_attr_ty inst_state "initialize" in
classty_set_canon class_ty (Some inst_ty);
if not (type_equal init_func_ty unkown_ty) then (
let bs = lookup_attr inst_state "initialize" in
(match bs with
| Some(_bs) -> Global.put_refs name _bs
| _ -> ());
fun_ty_set_self_ty init_func_ty (Some inst_ty);
ignore(apply_func init_func_ty args_ty star_ty block_arg_ty call);
);
inst_ty
)
| _ -> (
transform name obj.info.table
)
)
| Instance_ty(class_ty) -> (
if not (Type.is_unkown_ty obj) then (
let id = name_node_id name in
let method_ty = lookup_attr_ty class_ty.info.table id in
if Type.is_unkown_ty method_ty then (
unkown_ty
) else
apply_func method_ty args_ty star_ty block_arg_ty call
) else unkown_ty
)
| _ -> (
match name_node_id name with
| "to_s" -> Type.new_str_type()
| "to_sym" -> Type.new_sym_type()
| "to_i" -> Type.new_int_type()
| _ -> (
match obj.ty with
| Int_ty | Str_ty _ | Float_ty -> obj
| _ -> Type.unkown_ty
))
and bind_param_tys env args args_types =
List.iteri args ~f:(fun i arg ->
if i < List.length args_types then (
let arg_ty = List.nth_exn args_types i in
bind env arg arg_ty Type.ParameterK
) else
bind env arg unkown_ty Type.ParameterK
)
and apply_func fun_ty args_ty star_ty block_arg_ty call =
Global.set_called fun_ty;
if not (Global.contains_call call) && (Type.is_fun_ty fun_ty) then (
let info = Type.fun_ty_info fun_ty in
let node_info = func_node_info info.fun_node in
let env = State.new_state ~parent:info.env State.Function in
let _ = Global.push_call call in
let _ = bind_param_tys env node_info.args args_ty in
let ret_ty = transform node_info.body env in
if not (Type.type_equal ret_ty fun_ty) then (
fun_ty_set_ret_ty fun_ty ret_ty; ret_ty)
else Type.unkown_ty)
else
Type.unkown_ty
and add_inst_type_from_db class_ty =
let class_name = classty_get_name class_ty in
let table = class_ty.info.table in
let columns = Db.class_to_model_columns class_name in
List.iter columns ~f:(fun (name, ty_str, _) ->
Printf.printf " name : % s type : % s\n " name ;
let ty = match ty_str with
| "string" | "text" -> new_str_type()
| "boolean" -> new_bool_type()
| "integer" -> new_int_type()
| _ -> unkown_ty in
state_insert table name nil_node ty Type.ScopeK;
);
()
let apply_uncalled () =
TypeSet.iter (fun fun_ty ->
let info = Type.fun_ty_info fun_ty in
let env = State.new_state ~parent : info.env State . Function in
let _ = apply_func fun_ty [] unkown_ty unkown_ty info.fun_node in
()) !Global.uncalled
let transform_expr node state =
ignore(transform node state);
apply_uncalled()
|
696200b15cf52810a5ffc919002e268dafb054d733e4c3a37da08a2d3dae25ab | vikram/lisplibraries | conditions.lisp | Copyright ( c ) 2006 , 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.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 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.
;;;
;;; Conditions
;;;
conditions.lisp , v 1.3 2006/02/18 23:13:43 xach Exp
(in-package #:zpb-ttf)
(define-condition regrettable-value ()
((actual-value
:initarg :actual-value
:accessor actual-value)
(expected-values
:initarg :expected-values
:accessor expected-values)
(description
:initarg :description
:initform nil
:accessor description)
(location
:initarg :location
:initform nil
:accessor location))
(:report
(lambda (c s)
(format s "~:[Regrettable~;~:*~A~] value~:[~;~:* in ~A~]: ~
~A (expected ~{~A~^ or ~})"
(description c)
(location c)
(actual-value c)
(expected-values c)))))
(define-condition regrettable-hex-value (regrettable-value)
((size
:initarg :size
:initform 8
:accessor size)
(actual-value
:reader %actual-value)
(expected-values
:reader %expected-values)))
(defmethod actual-value ((c regrettable-hex-value))
(format nil "#x~v,'0X" (size c) (%actual-value c)))
(defmethod expected-values ((c regrettable-hex-value))
(mapcar (lambda (v)
(format nil "#x~v,'0X" (size c) v))
(%expected-values c)))
(define-condition bad-magic (regrettable-hex-value)
((description :initform "Bad magic")))
(define-condition unsupported-version (regrettable-hex-value)
((description :initform "Unsupported version")))
(define-condition unsupported-format (regrettable-hex-value)
((description :initform "Unsupported format")))
(define-condition unsupported-value (regrettable-value)
((description :initform "Unsupported")))
(defun check-version (location actual &rest expected)
(or (member actual expected :test #'=)
(error 'unsupported-version
:location location
:actual-value actual
:expected-values expected)))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/zpb-ttf-0.7/conditions.lisp | lisp |
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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
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 BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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.
Conditions
~:*~A~] value~:[~;~:* in ~A~]: ~ | Copyright ( c ) 2006 , All Rights Reserved
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
conditions.lisp , v 1.3 2006/02/18 23:13:43 xach Exp
(in-package #:zpb-ttf)
(define-condition regrettable-value ()
((actual-value
:initarg :actual-value
:accessor actual-value)
(expected-values
:initarg :expected-values
:accessor expected-values)
(description
:initarg :description
:initform nil
:accessor description)
(location
:initarg :location
:initform nil
:accessor location))
(:report
(lambda (c s)
~A (expected ~{~A~^ or ~})"
(description c)
(location c)
(actual-value c)
(expected-values c)))))
(define-condition regrettable-hex-value (regrettable-value)
((size
:initarg :size
:initform 8
:accessor size)
(actual-value
:reader %actual-value)
(expected-values
:reader %expected-values)))
(defmethod actual-value ((c regrettable-hex-value))
(format nil "#x~v,'0X" (size c) (%actual-value c)))
(defmethod expected-values ((c regrettable-hex-value))
(mapcar (lambda (v)
(format nil "#x~v,'0X" (size c) v))
(%expected-values c)))
(define-condition bad-magic (regrettable-hex-value)
((description :initform "Bad magic")))
(define-condition unsupported-version (regrettable-hex-value)
((description :initform "Unsupported version")))
(define-condition unsupported-format (regrettable-hex-value)
((description :initform "Unsupported format")))
(define-condition unsupported-value (regrettable-value)
((description :initform "Unsupported")))
(defun check-version (location actual &rest expected)
(or (member actual expected :test #'=)
(error 'unsupported-version
:location location
:actual-value actual
:expected-values expected)))
|
b0e5d332e0438675810574754acdbe0d26e6e29e3b3ab9837d8bc0243d8a1404 | foretspaisibles/blueprint | monadic_buffer.ml | MonadicBuffers -- Monadic output to a buffer
Author :
Date : Tue Sep 16 13:33:01 CEST 2014
Blueprint ( )
This file is part of Blueprint
Copyright © 2014
This file must be used under the terms of the CeCILL - B.
This source file is licensed as described in the file COPYING , which
you should have received as part of this distribution . The terms
are also available at
-B_V1-en.txt
Author: Michael Grünewald
Date: Tue Sep 16 13:33:01 CEST 2014
Blueprint ()
This file is part of Blueprint
Copyright © 2014 Michael Grünewald
This file must be used under the terms of the CeCILL-B.
This source file is licensed as described in the file COPYING, which
you should have received as part of this distribution. The terms
are also available at
-B_V1-en.txt *)
module MonadicBuffer : sig
type 'a t
val return : 'a -> 'a t
val bind : 'a t -> ('a -> 'b t) -> 'b t
val add_char : char -> unit t
val add_string : string -> unit t
val contents : int -> unit t -> string
val lift : ('a -> 'b) -> ('a t -> 'b t)
val ( >>= ) :'a t -> ('a -> 'b t) -> 'b t
val ( >> ) : 'a t -> 'b t -> 'b t
end = struct
type 'a t = Buffer.t -> 'a
let return x =
fun _ -> x
let bind m f =
fun buf -> f (m buf) buf
let add_string s buf =
Buffer.add_string buf s
let add_char c buf =
Buffer.add_char buf c
let contents sz m =
let buf = Buffer.create sz in
m buf;
Buffer.contents buf
let lift f m =
bind m (fun x -> return (f x))
let ( >>= ) =
bind
let ( >> ) m1 m2 =
bind m1 (fun _ -> m2)
end
let buffer_sz = 1000
let add_key k v =
let open MonadicBuffer in
return ()
>> add_string k
>> add_string ": "
>> add_string v
>> add_char '\n'
let rec add_alist lst =
let open MonadicBuffer in
match lst with
| [] -> return ()
| (k,v) :: tl -> add_key k v >> add_alist tl
let hackers_alist = [
"From", "DECWRL::\"\" \"Eddie Kuns 30-May-89 2216 EST\" 30-MAY-1989 19:19:47.60";
"To", "rnd%, , , dave%, lloyd!sunfs3!, ";
"CC", "";
"Subj", "Enjoy the following! I did! <grin>";
"Return-path", "";
"Received", "from B0VS02.FNAL.GOV by cancer.rutgers.edu; Tue, 30 May 89 10:34 EST";
"Date", "Sat, 27 May 1989 8:39:29 CDT";
"From", "";
"To", "";
"Message-Id", "<>";
"X-Vmsmail-To", "SMTP%\"\"";
"Received", "from decwrl.dec.com by LBL.Gov with INTERNET ; Thu, 25 May 89 11:05:38 PDT";
"Received", "by decwrl.dec.com (5.54.5/4.7.34) id AA04313; Thu, 25 May 89 11:05:36 PDT";
"Message-Id", "<>";
"Received", "by decwrl.dec.com (5.54.5/4.7.34) for ctday%; id AA04313; Thu, 25 May 89 11:05:36 PDT";
"From", "cvi% (C. van Ingen, HPS A/D, DTN 297-6186)";
"Date", "25 May 89 13:53";
"To", "russell%, ctday%";
"Subject", "Nerd Alert";
]
let hackers_monad =
let open MonadicBuffer in
return hackers_alist
>>= add_alist
|> contents buffer_sz
let rec buffer_add_alist buf alist =
match alist with
| [] -> ()
| (k,v) :: tl -> buffer_add_key buf k v; buffer_add_alist buf tl
and buffer_add_key buf k v =
let open Buffer in
add_string buf k;
add_string buf ": ";
add_string buf v;
add_char buf '\n'
let with_buffer sz f x =
let buf = Buffer.create sz in
f buf x;
Buffer.contents buf
let hackers_with_buffer =
with_buffer buffer_sz buffer_add_alist hackers_alist
let long_list sz =
let rec loop ax n =
if n = 0 then ax else loop (("XXXX", "YYYYY") :: ax) (n-1)
in
loop [] sz
let monadic alist =
let open MonadicBuffer in
return alist
>>= add_alist
|> contents buffer_sz
let higher_order alist =
with_buffer buffer_sz buffer_add_alist alist
let time f x =
let start = Sys.time () in
let stop = f x; Sys.time () in
stop -. start
let sample n step =
let rec loop ax i =
if i > n then List.rev ax else loop (i::ax) (i + step)
in
loop [] 0
let () =
let open Printf in
let time_method f label sample =
let comment = ref(sprintf "\t%% %s" label) in
let loop n =
let lst = long_list n in
printf "%d\t%f%s\n" n (time f lst) !comment;
comment := "";
in
List.iter loop sample;
printf "\n";
in
let loop sample (f, label) =
time_method f label sample
in
List.iter (loop (sample 100_000 500)) [
monadic, "Monadic";
higher_order, "Higher-Order";
]
| null | https://raw.githubusercontent.com/foretspaisibles/blueprint/e1f384c4e3424f8edc09d6676039a3cc84fb06e2/example/monadic_buffer.ml | ocaml | MonadicBuffers -- Monadic output to a buffer
Author :
Date : Tue Sep 16 13:33:01 CEST 2014
Blueprint ( )
This file is part of Blueprint
Copyright © 2014
This file must be used under the terms of the CeCILL - B.
This source file is licensed as described in the file COPYING , which
you should have received as part of this distribution . The terms
are also available at
-B_V1-en.txt
Author: Michael Grünewald
Date: Tue Sep 16 13:33:01 CEST 2014
Blueprint ()
This file is part of Blueprint
Copyright © 2014 Michael Grünewald
This file must be used under the terms of the CeCILL-B.
This source file is licensed as described in the file COPYING, which
you should have received as part of this distribution. The terms
are also available at
-B_V1-en.txt *)
module MonadicBuffer : sig
type 'a t
val return : 'a -> 'a t
val bind : 'a t -> ('a -> 'b t) -> 'b t
val add_char : char -> unit t
val add_string : string -> unit t
val contents : int -> unit t -> string
val lift : ('a -> 'b) -> ('a t -> 'b t)
val ( >>= ) :'a t -> ('a -> 'b t) -> 'b t
val ( >> ) : 'a t -> 'b t -> 'b t
end = struct
type 'a t = Buffer.t -> 'a
let return x =
fun _ -> x
let bind m f =
fun buf -> f (m buf) buf
let add_string s buf =
Buffer.add_string buf s
let add_char c buf =
Buffer.add_char buf c
let contents sz m =
let buf = Buffer.create sz in
m buf;
Buffer.contents buf
let lift f m =
bind m (fun x -> return (f x))
let ( >>= ) =
bind
let ( >> ) m1 m2 =
bind m1 (fun _ -> m2)
end
let buffer_sz = 1000
let add_key k v =
let open MonadicBuffer in
return ()
>> add_string k
>> add_string ": "
>> add_string v
>> add_char '\n'
let rec add_alist lst =
let open MonadicBuffer in
match lst with
| [] -> return ()
| (k,v) :: tl -> add_key k v >> add_alist tl
let hackers_alist = [
"From", "DECWRL::\"\" \"Eddie Kuns 30-May-89 2216 EST\" 30-MAY-1989 19:19:47.60";
"To", "rnd%, , , dave%, lloyd!sunfs3!, ";
"CC", "";
"Subj", "Enjoy the following! I did! <grin>";
"Return-path", "";
"Received", "from B0VS02.FNAL.GOV by cancer.rutgers.edu; Tue, 30 May 89 10:34 EST";
"Date", "Sat, 27 May 1989 8:39:29 CDT";
"From", "";
"To", "";
"Message-Id", "<>";
"X-Vmsmail-To", "SMTP%\"\"";
"Received", "from decwrl.dec.com by LBL.Gov with INTERNET ; Thu, 25 May 89 11:05:38 PDT";
"Received", "by decwrl.dec.com (5.54.5/4.7.34) id AA04313; Thu, 25 May 89 11:05:36 PDT";
"Message-Id", "<>";
"Received", "by decwrl.dec.com (5.54.5/4.7.34) for ctday%; id AA04313; Thu, 25 May 89 11:05:36 PDT";
"From", "cvi% (C. van Ingen, HPS A/D, DTN 297-6186)";
"Date", "25 May 89 13:53";
"To", "russell%, ctday%";
"Subject", "Nerd Alert";
]
let hackers_monad =
let open MonadicBuffer in
return hackers_alist
>>= add_alist
|> contents buffer_sz
let rec buffer_add_alist buf alist =
match alist with
| [] -> ()
| (k,v) :: tl -> buffer_add_key buf k v; buffer_add_alist buf tl
and buffer_add_key buf k v =
let open Buffer in
add_string buf k;
add_string buf ": ";
add_string buf v;
add_char buf '\n'
let with_buffer sz f x =
let buf = Buffer.create sz in
f buf x;
Buffer.contents buf
let hackers_with_buffer =
with_buffer buffer_sz buffer_add_alist hackers_alist
let long_list sz =
let rec loop ax n =
if n = 0 then ax else loop (("XXXX", "YYYYY") :: ax) (n-1)
in
loop [] sz
let monadic alist =
let open MonadicBuffer in
return alist
>>= add_alist
|> contents buffer_sz
let higher_order alist =
with_buffer buffer_sz buffer_add_alist alist
let time f x =
let start = Sys.time () in
let stop = f x; Sys.time () in
stop -. start
let sample n step =
let rec loop ax i =
if i > n then List.rev ax else loop (i::ax) (i + step)
in
loop [] 0
let () =
let open Printf in
let time_method f label sample =
let comment = ref(sprintf "\t%% %s" label) in
let loop n =
let lst = long_list n in
printf "%d\t%f%s\n" n (time f lst) !comment;
comment := "";
in
List.iter loop sample;
printf "\n";
in
let loop sample (f, label) =
time_method f label sample
in
List.iter (loop (sample 100_000 500)) [
monadic, "Monadic";
higher_order, "Higher-Order";
]
| |
1c63556ba522c4776bc83c9e3152cbde914b2516969fc5a2a5aef5a03691f745 | mwri/erlang-efuse | efuse_hellofs.erl | This file is part of the Erlang FUSE ( Filesystem in Userspace )
%% interface called 'efuse'.
%%
' efuse ' is free software , licensed under the MIT license .
%%
@author < >
2015 < >
%%
@doc Hello world FS example filesystem callback module for ' efuse ' app .
%%
%% The 'efuse_examplefs' is a very minimal example showing the
%% callbacks and how they need to be implemented.
%%
%% For a fuller more interesting example of an implementation, see the
%% 'efuse_erlfs' module, or 'efuse_examplefs' is like this, but with a
%% few more objects.
-module(efuse_hellofs).
-behviour(efuse_fs).
-export([efuse_init/1, efuse_readdir/2, efuse_getattr/2, efuse_readlink/2, efuse_read/2]).
-include("efuse.hrl").
-include("efuse_defs.hrl").
%% @doc Behaviour callback implementation for 'efuse_fs'.
efuse_init(_State) ->
ready
.
%% @doc Behaviour callback implementation for 'efuse_fs'.
efuse_readdir(State, <<"/">>) ->
{ok, [<<"hello">>, <<"world">>], State}
;
efuse_readdir(State, _) ->
{error, ?EFUSE_ERROR_NOENT, State}
.
%% @doc Behaviour callback implementation for 'efuse_fs'.
efuse_getattr(State, <<"/">>) ->
{ok, {8#0755, ?EFUSE_ATTR_DIR, 0}, State}
;
efuse_getattr(State, <<"/hello">>) ->
{ok, {8#0644, ?EFUSE_ATTR_FILE, byte_size(<<"Hello world!">>)}, State}
;
efuse_getattr(State, <<"/world">>) ->
{ok, {8#0755, ?EFUSE_ATTR_SYMLINK, length("hello")}, State}
;
efuse_getattr(State, _) ->
{error, ?EFUSE_ERROR_NOENT, State}
.
%% @doc Behaviour callback implementation for 'efuse_fs'.
efuse_readlink(State, <<"/world">>) ->
{ok, <<"hello">>, State}
;
efuse_readlink(State, _) ->
{error, ?EFUSE_ERROR_NOENT, State}
.
%% @doc Behaviour callback implementation for 'efuse_fs'.
efuse_read(State, <<"/hello">>) ->
{ok, <<"Hello world!">>, State}
;
efuse_read(State, _) ->
{error, ?EFUSE_ERROR_NOENT, State}
.
| null | https://raw.githubusercontent.com/mwri/erlang-efuse/dd2a55e2a17fbe688da0f18dcaccf222e299440b/src/efuse_hellofs.erl | erlang | interface called 'efuse'.
The 'efuse_examplefs' is a very minimal example showing the
callbacks and how they need to be implemented.
For a fuller more interesting example of an implementation, see the
'efuse_erlfs' module, or 'efuse_examplefs' is like this, but with a
few more objects.
@doc Behaviour callback implementation for 'efuse_fs'.
@doc Behaviour callback implementation for 'efuse_fs'.
@doc Behaviour callback implementation for 'efuse_fs'.
@doc Behaviour callback implementation for 'efuse_fs'.
@doc Behaviour callback implementation for 'efuse_fs'. | This file is part of the Erlang FUSE ( Filesystem in Userspace )
' efuse ' is free software , licensed under the MIT license .
@author < >
2015 < >
@doc Hello world FS example filesystem callback module for ' efuse ' app .
-module(efuse_hellofs).
-behviour(efuse_fs).
-export([efuse_init/1, efuse_readdir/2, efuse_getattr/2, efuse_readlink/2, efuse_read/2]).
-include("efuse.hrl").
-include("efuse_defs.hrl").
efuse_init(_State) ->
ready
.
efuse_readdir(State, <<"/">>) ->
{ok, [<<"hello">>, <<"world">>], State}
;
efuse_readdir(State, _) ->
{error, ?EFUSE_ERROR_NOENT, State}
.
efuse_getattr(State, <<"/">>) ->
{ok, {8#0755, ?EFUSE_ATTR_DIR, 0}, State}
;
efuse_getattr(State, <<"/hello">>) ->
{ok, {8#0644, ?EFUSE_ATTR_FILE, byte_size(<<"Hello world!">>)}, State}
;
efuse_getattr(State, <<"/world">>) ->
{ok, {8#0755, ?EFUSE_ATTR_SYMLINK, length("hello")}, State}
;
efuse_getattr(State, _) ->
{error, ?EFUSE_ERROR_NOENT, State}
.
efuse_readlink(State, <<"/world">>) ->
{ok, <<"hello">>, State}
;
efuse_readlink(State, _) ->
{error, ?EFUSE_ERROR_NOENT, State}
.
efuse_read(State, <<"/hello">>) ->
{ok, <<"Hello world!">>, State}
;
efuse_read(State, _) ->
{error, ?EFUSE_ERROR_NOENT, State}
.
|
4d70e2af9bff163ad359dbb5ff0270ce1626b7c2c0b19a85d4970227d4366bf6 | nomnom-insights/nomnom.lockjaw | core.clj | (ns lockjaw.core
(:require
[clojure.tools.logging :as log]
[com.stuartsierra.component :as component]
[lockjaw.operation :as operation]
[lockjaw.protocol :as lockjaw]
[lockjaw.util :as util]))
(defrecord Lockjaw
[name lock-id db-conn]
component/Lifecycle
(start
[this]
(let [lock-id (util/name-to-id name)]
(log/infof "name=%s status=starting lock-id=%s" name lock-id)
(assoc this :lock-id lock-id)))
(stop
[this]
(log/warnf "name=%s status=stopping lock-id=%s cleaning all locks!" name lock-id)
(operation/release-all-locks! db-conn)
(assoc this :lock-id nil))
lockjaw/Lockjaw
(acquire! [_]
(operation/acquire-lock db-conn lock-id))
(acquire-by-name! [_ lock-name]
(let [lock-id (util/name-to-id lock-name)]
(operation/acquire-lock db-conn lock-id)))
(acquired? [_]
(operation/lock-acquired? db-conn lock-id))
(acquired-by-name? [_ lock-name]
(let [lock-id (util/name-to-id lock-name)]
(operation/lock-acquired? db-conn lock-id)))
(release! [_]
(operation/release-lock db-conn lock-id))
(release-by-name! [_ lock-name]
(let [lock-id (util/name-to-id lock-name)]
(operation/release-lock db-conn lock-id)))
(release-all! [_]
(operation/release-all-locks! db-conn)))
(defn create
[{:keys [name] :as args}]
{:pre [(and (string? name) (not (.isEmpty ^String name)))]}
(map->Lockjaw args))
| null | https://raw.githubusercontent.com/nomnom-insights/nomnom.lockjaw/8d568d1ec36054ca25e798613ccd3e1d229c94cf/src/lockjaw/core.clj | clojure | (ns lockjaw.core
(:require
[clojure.tools.logging :as log]
[com.stuartsierra.component :as component]
[lockjaw.operation :as operation]
[lockjaw.protocol :as lockjaw]
[lockjaw.util :as util]))
(defrecord Lockjaw
[name lock-id db-conn]
component/Lifecycle
(start
[this]
(let [lock-id (util/name-to-id name)]
(log/infof "name=%s status=starting lock-id=%s" name lock-id)
(assoc this :lock-id lock-id)))
(stop
[this]
(log/warnf "name=%s status=stopping lock-id=%s cleaning all locks!" name lock-id)
(operation/release-all-locks! db-conn)
(assoc this :lock-id nil))
lockjaw/Lockjaw
(acquire! [_]
(operation/acquire-lock db-conn lock-id))
(acquire-by-name! [_ lock-name]
(let [lock-id (util/name-to-id lock-name)]
(operation/acquire-lock db-conn lock-id)))
(acquired? [_]
(operation/lock-acquired? db-conn lock-id))
(acquired-by-name? [_ lock-name]
(let [lock-id (util/name-to-id lock-name)]
(operation/lock-acquired? db-conn lock-id)))
(release! [_]
(operation/release-lock db-conn lock-id))
(release-by-name! [_ lock-name]
(let [lock-id (util/name-to-id lock-name)]
(operation/release-lock db-conn lock-id)))
(release-all! [_]
(operation/release-all-locks! db-conn)))
(defn create
[{:keys [name] :as args}]
{:pre [(and (string? name) (not (.isEmpty ^String name)))]}
(map->Lockjaw args))
| |
8d54cf8af593acb537d785a4299bde77b0f283cbc69b3695ca915cf6eb3c7077 | chef/concrete | concrete_app_sup.erl | -module({{name}}_sup).
-behaviour(supervisor).
-export([
init/1,
start_link/0
]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Restart = {one_for_one, 10, 10},
{ok, {Restart, []}}.
| null | https://raw.githubusercontent.com/chef/concrete/d29237681f93633c9200c8f0ad448ad47aa1d201/priv/templates/concrete_app_sup.erl | erlang | -module({{name}}_sup).
-behaviour(supervisor).
-export([
init/1,
start_link/0
]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Restart = {one_for_one, 10, 10},
{ok, {Restart, []}}.
| |
0ac0b3c466c5bcdaac5460d906b5753612cc846edca21745e99908767391d1d2 | mbenke/zpf2013 | sudoku2b.hs | import Sudoku
import Control.Exception
import System.Environment
import Control.Parallel.Strategies
import Control.DeepSeq
main :: IO ()
main = do
[f] <- getArgs
grids <- fmap lines $ readFile f
let (as,bs) = splitAt (length grids `div` 2) grids
evaluate $ runEval $ do
a <- rpar (force (map solve as))
b <- rpar (force (map solve bs))
rseq a
rseq b
return ()
| null | https://raw.githubusercontent.com/mbenke/zpf2013/85f32747e17f07a74e1c3cb064b1d6acaca3f2f0/Code/Par/Marlow/sudoku2b.hs | haskell | import Sudoku
import Control.Exception
import System.Environment
import Control.Parallel.Strategies
import Control.DeepSeq
main :: IO ()
main = do
[f] <- getArgs
grids <- fmap lines $ readFile f
let (as,bs) = splitAt (length grids `div` 2) grids
evaluate $ runEval $ do
a <- rpar (force (map solve as))
b <- rpar (force (map solve bs))
rseq a
rseq b
return ()
| |
9398261f95b2d22c23aaf0d93921748ee595985753abe5a7ae74e5fe2ac67e46 | MyDataFlow/ttalk-server | ws_echo.erl | %% Feel free to use, reuse and abuse the code in this file.
-module(ws_echo).
-behaviour(cowboy_websocket_handler).
-export([init/3]).
-export([websocket_init/3, websocket_handle/3,
websocket_info/3, websocket_terminate/3]).
init(_Any, _Req, _Opts) ->
{upgrade, protocol, cowboy_websocket}.
websocket_init(_TransportName, Req, _Opts) ->
Req2 = cowboy_req:compact(Req),
{ok, Req2, undefined}.
websocket_handle({text, Data}, Req, State) ->
{reply, {text, Data}, Req, State};
websocket_handle({binary, Data}, Req, State) ->
{reply, {binary, Data}, Req, State};
websocket_handle(_Frame, Req, State) ->
{ok, Req, State}.
websocket_info(_Info, Req, State) ->
{ok, Req, State}.
websocket_terminate(_Reason, _Req, _State) ->
ok.
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/cowboy/test/ws_SUITE_data/ws_echo.erl | erlang | Feel free to use, reuse and abuse the code in this file. |
-module(ws_echo).
-behaviour(cowboy_websocket_handler).
-export([init/3]).
-export([websocket_init/3, websocket_handle/3,
websocket_info/3, websocket_terminate/3]).
init(_Any, _Req, _Opts) ->
{upgrade, protocol, cowboy_websocket}.
websocket_init(_TransportName, Req, _Opts) ->
Req2 = cowboy_req:compact(Req),
{ok, Req2, undefined}.
websocket_handle({text, Data}, Req, State) ->
{reply, {text, Data}, Req, State};
websocket_handle({binary, Data}, Req, State) ->
{reply, {binary, Data}, Req, State};
websocket_handle(_Frame, Req, State) ->
{ok, Req, State}.
websocket_info(_Info, Req, State) ->
{ok, Req, State}.
websocket_terminate(_Reason, _Req, _State) ->
ok.
|
c4272f4c81e49d804d2e05d2da113481aa8556bff0b09d184a0ed50acc2f9068 | hsyl20/haskus-system | Helper.hs | # LANGUAGE DataKinds #
-- | Helpers for the graphics API
module Haskus.System.Linux.Graphics.Helper
( FrameSourceAction (..)
, setController
, switchFrameSource
)
where
import Haskus.System.Linux.Graphics.State
import Haskus.System.Linux.Graphics.Mode
import Haskus.System.Linux.Graphics.FrameSource
import Haskus.System.Linux.Graphics.Entities
import Haskus.System.Linux.ErrorCode
import Haskus.Format.Binary.Word
import Haskus.Utils.Flow
| How to configure frame source with setController
data FrameSourceAction
= SetSource FrameSource -- ^ Use this given source
^ Use the already set one
| ReleaseSource -- ^ Release the set source
deriving (Show)
-- | Configure a controller
--
A connected frame source is required to set a mode : if ReuseSource is passed , the
-- connected one is used.
setController :: MonadInIO m => Controller -> FrameSourceAction -> [Connector] -> Maybe Mode -> Excepts '[ErrorCode] m ()
setController ctrl frameSourceAction conns mode = do
let
mframe = case frameSourceAction of
SetSource fs -> Just $ Frame (frameID fs) 0 0
ReuseSource -> Just $ Frame (EntityID maxBound) 0 0
ReleaseSource -> Nothing
hdl = controllerHandle ctrl
setController' hdl (controllerID ctrl) mframe (fmap connectorID conns) mode
-- | Switch to another frame source for the given controller without doing a
-- full mode change
switchFrameSource :: MonadInIO m => Controller -> FrameSource -> PageFlipFlags -> Word64 -> Excepts '[ErrorCode] m ()
switchFrameSource ctrl fs flags udata =
switchFrameBuffer' (controllerHandle ctrl) (controllerID ctrl) (frameID fs) flags udata
| null | https://raw.githubusercontent.com/hsyl20/haskus-system/2f389c6ecae5b0180b464ddef51e36f6e567d690/haskus-system/src/lib/Haskus/System/Linux/Graphics/Helper.hs | haskell | | Helpers for the graphics API
^ Use this given source
^ Release the set source
| Configure a controller
connected one is used.
| Switch to another frame source for the given controller without doing a
full mode change | # LANGUAGE DataKinds #
module Haskus.System.Linux.Graphics.Helper
( FrameSourceAction (..)
, setController
, switchFrameSource
)
where
import Haskus.System.Linux.Graphics.State
import Haskus.System.Linux.Graphics.Mode
import Haskus.System.Linux.Graphics.FrameSource
import Haskus.System.Linux.Graphics.Entities
import Haskus.System.Linux.ErrorCode
import Haskus.Format.Binary.Word
import Haskus.Utils.Flow
| How to configure frame source with setController
data FrameSourceAction
^ Use the already set one
deriving (Show)
A connected frame source is required to set a mode : if ReuseSource is passed , the
setController :: MonadInIO m => Controller -> FrameSourceAction -> [Connector] -> Maybe Mode -> Excepts '[ErrorCode] m ()
setController ctrl frameSourceAction conns mode = do
let
mframe = case frameSourceAction of
SetSource fs -> Just $ Frame (frameID fs) 0 0
ReuseSource -> Just $ Frame (EntityID maxBound) 0 0
ReleaseSource -> Nothing
hdl = controllerHandle ctrl
setController' hdl (controllerID ctrl) mframe (fmap connectorID conns) mode
switchFrameSource :: MonadInIO m => Controller -> FrameSource -> PageFlipFlags -> Word64 -> Excepts '[ErrorCode] m ()
switchFrameSource ctrl fs flags udata =
switchFrameBuffer' (controllerHandle ctrl) (controllerID ctrl) (frameID fs) flags udata
|
4175e6049b1800400d5cb31ce3ce21a3d665e571e63220cf2db3d1fad8183ac8 | scicloj/notespace | channels.clj | (ns scicloj.notespace.v4.events.channels
(:require [clojure.core.async :as async :refer [<! go go-loop timeout chan thread]]
[scicloj.notespace.v4.log :as v4.log]
[scicloj.notespace.v4.state :as v4.state]
[scicloj.notespace.v4.events.handle]
[scicloj.notespace.v4.state :as v4.state]))
(defn pass-valid-events [in out]
(async/go-loop []
(let [{:keys [error] :as event} (<! in)]
(if error
(println "Error:" error)
;; else -- valid
(async/>! out event)))
(recur)))
;;
(defn batch-events [in out {:keys [max-time max-count]}]
(let [lim-1 (dec max-count)]
(async/go-loop [buf []
t (async/timeout max-time)]
(let [[v p] (async/alts! [in t])]
(cond
(= p t)
(do
(async/>! out buf)
(recur [] (async/timeout max-time)))
(nil? v)
(when (seq buf)
(async/>! out buf)
(recur [] (async/timeout max-time)))
(== (count buf) lim-1)
(do
(async/>! out (conj buf v))
(recur [] (async/timeout max-time)))
:else
(recur (conj buf v) t))))))
(def event-priorities
#:scicloj.notespace.v4.events.handle{:buffer-update 1
:eval 2
:value 2
:error 2
:done 2})
(defn cleanup-events [in out]
(async/go-loop []
(->> in
async/<!
(group-by (comp event-priorities :event/type))
(sort-by (fn [[priority _]]
(-> priority nil? not assert)
priority))
;; ((fn [grouped-events]
;; (when (-> grouped-events seq)
;; (v4.log/log-data
;; :debug1
;; {:grouped-events (->> grouped-events
;; (map (fn [[k events]]
;; [k (->> events
;; (map #(dissoc % :value)))])))}))
;; grouped-events))
(map (fn [[_ events]]
(->> events
(sort-by :event-counter))))
(mapcat (fn [events]
(if (-> events first :event/type (= :scicloj.notespace.v4.events.handle/buffer-update))
[(last events)]
events)))
;; ((fn [events]
;; (when (-> events seq)
;; (v4.log/log-data
: debug2
;; {:events (->> events
;; (map #(dissoc % :value)))}))
;; events))
(async/>! out))
(recur)))
(defn handle-events [in handler]
(async/go-loop []
(handler (async/<! in))
(recur)))
(defn start! [handler]
(let [events-channel (async/chan 100)
batched-events-channel (async/chan 20)
clean-events-channel (async/chan 20)]
(batch-events events-channel batched-events-channel
{:max-time 20
:max-count 1000})
(cleanup-events batched-events-channel clean-events-channel)
(handle-events clean-events-channel handler)
{:stop (fn []
(async/close! events-channel)
(async/close! batched-events-channel)
(async/close! clean-events-channel))
:process (fn [event]
(async/>!! events-channel
(assoc event :event-counter (v4.state/next-event-counter))))}))
| null | https://raw.githubusercontent.com/scicloj/notespace/a3fb553b6992f8f1abbf38cd16b81356d7b10d16/src/scicloj/notespace/v4/events/channels.clj | clojure | else -- valid
((fn [grouped-events]
(when (-> grouped-events seq)
(v4.log/log-data
:debug1
{:grouped-events (->> grouped-events
(map (fn [[k events]]
[k (->> events
(map #(dissoc % :value)))])))}))
grouped-events))
((fn [events]
(when (-> events seq)
(v4.log/log-data
{:events (->> events
(map #(dissoc % :value)))}))
events)) | (ns scicloj.notespace.v4.events.channels
(:require [clojure.core.async :as async :refer [<! go go-loop timeout chan thread]]
[scicloj.notespace.v4.log :as v4.log]
[scicloj.notespace.v4.state :as v4.state]
[scicloj.notespace.v4.events.handle]
[scicloj.notespace.v4.state :as v4.state]))
(defn pass-valid-events [in out]
(async/go-loop []
(let [{:keys [error] :as event} (<! in)]
(if error
(println "Error:" error)
(async/>! out event)))
(recur)))
(defn batch-events [in out {:keys [max-time max-count]}]
(let [lim-1 (dec max-count)]
(async/go-loop [buf []
t (async/timeout max-time)]
(let [[v p] (async/alts! [in t])]
(cond
(= p t)
(do
(async/>! out buf)
(recur [] (async/timeout max-time)))
(nil? v)
(when (seq buf)
(async/>! out buf)
(recur [] (async/timeout max-time)))
(== (count buf) lim-1)
(do
(async/>! out (conj buf v))
(recur [] (async/timeout max-time)))
:else
(recur (conj buf v) t))))))
(def event-priorities
#:scicloj.notespace.v4.events.handle{:buffer-update 1
:eval 2
:value 2
:error 2
:done 2})
(defn cleanup-events [in out]
(async/go-loop []
(->> in
async/<!
(group-by (comp event-priorities :event/type))
(sort-by (fn [[priority _]]
(-> priority nil? not assert)
priority))
(map (fn [[_ events]]
(->> events
(sort-by :event-counter))))
(mapcat (fn [events]
(if (-> events first :event/type (= :scicloj.notespace.v4.events.handle/buffer-update))
[(last events)]
events)))
: debug2
(async/>! out))
(recur)))
(defn handle-events [in handler]
(async/go-loop []
(handler (async/<! in))
(recur)))
(defn start! [handler]
(let [events-channel (async/chan 100)
batched-events-channel (async/chan 20)
clean-events-channel (async/chan 20)]
(batch-events events-channel batched-events-channel
{:max-time 20
:max-count 1000})
(cleanup-events batched-events-channel clean-events-channel)
(handle-events clean-events-channel handler)
{:stop (fn []
(async/close! events-channel)
(async/close! batched-events-channel)
(async/close! clean-events-channel))
:process (fn [event]
(async/>!! events-channel
(assoc event :event-counter (v4.state/next-event-counter))))}))
|
d9abd25f93d9316844c985122fbc642c28a60219f8b50aa3eddb4f4e43b958aa | haskell-servant/servant-snap | StreamingSpec.hs | # LANGUAGE DataKinds #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
-- | This module tests whether streaming works from client to server
-- with a server implemented with servant-server.
module Servant.StreamingSpec where
import Control.Concurrent
import Control.Exception hiding (Handler)
import Control.Monad.IO.Class
import qualified Data.ByteString as Strict
import Control.Monad.State (modify)
import qualified Data.ByteString.Lazy as Lazy
import Network.HTTP.Types
-- import Network.Wai
-- import Network.Wai.Internal
import Prelude
-- import Prelude.Compat
import Servant
import Snap.Core
import Snap.Internal.Http.Types
import Snap.Test
import Snap
import qualified System.Timeout
import qualified System.IO.Streams as IOS
import Test.Hspec
type TestAPI =
ReqBody '[OctetStream] Lazy.ByteString :> Post '[JSON] NoContent
testAPI :: Proxy TestAPI
testAPI = Proxy
spec :: Spec
spec = return ()
-- TODO: This test fails
spec : : Spec
spec = do
-- The idea of this test is this :
--
-- - The mock client will
-- - send some data in the request body , but not all ,
-- - wait for the server to acknowledge ( outside of http , through an MVar )
-- that the server received some data ,
-- - send the rest of the request body .
-- - The mock server will
-- - receive some data ,
-- - notify the client that it received some data ,
-- - receive the rest of the data ,
-- - respond with an empty result .
it " client to server can stream lazy ByteStrings " $ timeout $ do
serverReceivedFirstChunk < - newWaiter
-- - streams some test data
-- - waits for serverReceivedFirstChunk
-- - streams some more test data
streamTestData < - do
mvar : : MVar [ IO Strict . ByteString ] < - newMVar $
map return ( replicate 1000 " foo " ) + +
( waitFor serverReceivedFirstChunk > > return " foo " ) :
map return ( replicate 1000 " foo " )
return $ modifyMVar mvar $ \ actions - > case actions of
( a : r ) - > ( r , ) < $ > a
[ ] - > return ( [ ] , " " )
rqStream < - IOS.makeInputStream ( Just < $ > streamTestData )
rqStream2 < - IOS.makeInputStream ( return ( Just " foo " ) )
let makeRequest : : RequestBuilder IO ( )
makeRequest = do
postRaw @IO " / " " application / octet - stream " " barbar "
-- transformRequestBody $ \inStream - > return rqStream
-- modify $ \rq - > rq { rqBody = rqStream }
-- - receives the first chunk
-- - notifies serverReceivedFirstChunk
-- - receives the rest of the request
let handler : : Lazy . ByteString - > Snap NoContent
handler input = do
liftIO $ putStrLn $ " handler Hello1 "
-- rq < - getRequest
-- putRequest ( rq = rqStream } )
-- transformRequestBody $ \ _ - > return rqStream2
liftIO $ putStrLn $ " handler Hello2 "
liftIO $ do
print " handler Hello3 "
let prefix = Lazy.take 3 input
prefix ` shouldBe ` " foo "
print " handler "
notify serverReceivedFirstChunk ( )
print " handler Hello5 "
input ` shouldBe ` mconcat ( replicate 2001 " foo " )
return NoContent
app = serveSnap testAPI handler
putStrLn " Hello1 "
response < - executeRequest rqStream makeRequest app
rspStatus response ` shouldBe ` 200
executeRequest : : IOS.InputStream Strict . ByteString - > RequestBuilder IO ( ) - > Snap ( ) - > IO Response
executeRequest rqStream makeRequest act = do
putStrLn " Hello2 "
-- evalHandler ( buildRequest get ( Lazy.replicate " foo " 2001 ) ) ( act > > putMVar responseMVar response )
-- evalHandler makeRequest ( act > > get > > = \r - > liftIO ( ) )
evalHandler makeRequest $ do
liftIO $ putStrLn " Hello3 "
-- rq < - getRequest
liftIO $ putStrLn " Hello3.5 "
-- putRequest ( rq = rqStream } )
transformRequestBody $ \ _ - > return rqStream
liftIO $ putStrLn " Hello3.7 "
act
liftIO $ putStrLn " Hello4 "
r < - Snap.getResponse
liftIO ( putMVar )
-- ( act > > get > > = \r - > liftIO ( ) )
-- let respond response = do
-- putMVar responseMVar response
-- return -- ResponseReceived < - app request respond
takeMVar responseMVar
-- executeRequest : : Application - > Request - > IO Response
-- executeRequest app request = do
--
-- let respond response = do
-- putMVar responseMVar response
-- return
-- ResponseReceived < - app request respond
-- takeMVar responseMVar
timeout : : IO a - > IO a
timeout action = do
result < - System.Timeout.timeout 1000000 action
maybe ( throwIO $ ErrorCall " timeout " ) return result
-- * waiter
data a
= Waiter {
notify : : a - > IO ( ) ,
waitFor : : IO a
}
: : IO ( Waiter a )
= do
mvar < - newEmptyMVar
return $ Waiter {
notify = ,
waitFor = }
spec :: Spec
spec = do
-- The idea of this test is this:
--
-- - The mock client will
-- - send some data in the request body, but not all,
-- - wait for the server to acknowledge (outside of http, through an MVar)
-- that the server received some data,
-- - send the rest of the request body.
-- - The mock server will
-- - receive some data,
-- - notify the client that it received some data,
-- - receive the rest of the data,
-- - respond with an empty result.
it "client to server can stream lazy ByteStrings" $ timeout $ do
serverReceivedFirstChunk <- newWaiter
-- - streams some test data
-- - waits for serverReceivedFirstChunk
-- - streams some more test data
streamTestData <- do
mvar :: MVar [IO Strict.ByteString] <- newMVar $
map return (replicate 1000 "foo") ++
(waitFor serverReceivedFirstChunk >> return "foo") :
map return (replicate 1000 "foo")
return $ modifyMVar mvar $ \ actions -> case actions of
(a : r) -> (r, ) <$> a
[] -> return ([], "")
rqStream <- IOS.makeInputStream (Just <$> streamTestData)
rqStream2 <- IOS.makeInputStream (return (Just "foo"))
let makeRequest :: RequestBuilder IO ()
makeRequest = do
postRaw @IO "/" "application/octet-stream" "barbar"
-- transformRequestBody $ \inStream -> return rqStream
-- modify $ \rq -> rq { rqBody = rqStream }
-- - receives the first chunk
-- - notifies serverReceivedFirstChunk
-- - receives the rest of the request
let handler :: Lazy.ByteString -> Snap NoContent
handler input = do
liftIO $ putStrLn $ "handler Hello1"
-- rq <- getRequest
-- putRequest (rq { rqBody = rqStream })
-- transformRequestBody $ \_ -> return rqStream2
liftIO $ putStrLn $ "handler Hello2"
liftIO $ do
print "handler Hello3"
let prefix = Lazy.take 3 input
prefix `shouldBe` "foo"
print "handler Hello4"
notify serverReceivedFirstChunk ()
print "handler Hello5"
input `shouldBe` mconcat (replicate 2001 "foo")
return NoContent
app = serveSnap testAPI handler
putStrLn "Hello1"
response <- executeRequest rqStream makeRequest app
rspStatus response `shouldBe` 200
executeRequest :: IOS.InputStream Strict.ByteString -> RequestBuilder IO () -> Snap () -> IO Response
executeRequest rqStream makeRequest act = do
responseMVar <- newEmptyMVar
putStrLn "Hello2"
-- evalHandler (buildRequest get (Lazy.replicate "foo" 2001)) (act >> putMVar responseMVar response)
-- evalHandler makeRequest (act >> get >>= \r -> liftIO (putMVar responseMVar r))
evalHandler makeRequest $ do
liftIO $ putStrLn "Hello3"
-- rq <- getRequest
liftIO $ putStrLn "Hello3.5"
-- putRequest (rq { rqBody = rqStream })
transformRequestBody $ \_ -> return rqStream
liftIO $ putStrLn "Hello3.7"
act
liftIO $ putStrLn "Hello4"
r <- Snap.getResponse
liftIO (putMVar responseMVar r)
-- (act >> get >>= \r -> liftIO (putMVar responseMVar r))
-- let respond response = do
-- putMVar responseMVar response
-- return ResponseReceived
-- ResponseReceived <- app request respond
takeMVar responseMVar
-- executeRequest :: Application -> Request -> IO Response
-- executeRequest app request = do
-- responseMVar <- newEmptyMVar
-- let respond response = do
-- putMVar responseMVar response
-- return ResponseReceived
-- ResponseReceived <- app request respond
-- takeMVar responseMVar
timeout :: IO a -> IO a
timeout action = do
result <- System.Timeout.timeout 1000000 action
maybe (throwIO $ ErrorCall "timeout") return result
-- * waiter
data Waiter a
= Waiter {
notify :: a -> IO (),
waitFor :: IO a
}
newWaiter :: IO (Waiter a)
newWaiter = do
mvar <- newEmptyMVar
return $ Waiter {
notify = putMVar mvar,
waitFor = readMVar mvar
}
-}
| null | https://raw.githubusercontent.com/haskell-servant/servant-snap/b54c5da86f2f2ed994e9dfbb0694c72301b5a220/test/Servant/StreamingSpec.hs | haskell | # LANGUAGE OverloadedStrings #
| This module tests whether streaming works from client to server
with a server implemented with servant-server.
import Network.Wai
import Network.Wai.Internal
import Prelude.Compat
TODO: This test fails
The idea of this test is this :
- The mock client will
- send some data in the request body , but not all ,
- wait for the server to acknowledge ( outside of http , through an MVar )
that the server received some data ,
- send the rest of the request body .
- The mock server will
- receive some data ,
- notify the client that it received some data ,
- receive the rest of the data ,
- respond with an empty result .
- streams some test data
- waits for serverReceivedFirstChunk
- streams some more test data
transformRequestBody $ \inStream - > return rqStream
modify $ \rq - > rq { rqBody = rqStream }
- receives the first chunk
- notifies serverReceivedFirstChunk
- receives the rest of the request
rq < - getRequest
putRequest ( rq = rqStream } )
transformRequestBody $ \ _ - > return rqStream2
evalHandler ( buildRequest get ( Lazy.replicate " foo " 2001 ) ) ( act > > putMVar responseMVar response )
evalHandler makeRequest ( act > > get > > = \r - > liftIO ( ) )
rq < - getRequest
putRequest ( rq = rqStream } )
( act > > get > > = \r - > liftIO ( ) )
let respond response = do
putMVar responseMVar response
return -- ResponseReceived < - app request respond
executeRequest : : Application - > Request - > IO Response
executeRequest app request = do
let respond response = do
putMVar responseMVar response
return
ResponseReceived < - app request respond
takeMVar responseMVar
* waiter
The idea of this test is this:
- The mock client will
- send some data in the request body, but not all,
- wait for the server to acknowledge (outside of http, through an MVar)
that the server received some data,
- send the rest of the request body.
- The mock server will
- receive some data,
- notify the client that it received some data,
- receive the rest of the data,
- respond with an empty result.
- streams some test data
- waits for serverReceivedFirstChunk
- streams some more test data
transformRequestBody $ \inStream -> return rqStream
modify $ \rq -> rq { rqBody = rqStream }
- receives the first chunk
- notifies serverReceivedFirstChunk
- receives the rest of the request
rq <- getRequest
putRequest (rq { rqBody = rqStream })
transformRequestBody $ \_ -> return rqStream2
evalHandler (buildRequest get (Lazy.replicate "foo" 2001)) (act >> putMVar responseMVar response)
evalHandler makeRequest (act >> get >>= \r -> liftIO (putMVar responseMVar r))
rq <- getRequest
putRequest (rq { rqBody = rqStream })
(act >> get >>= \r -> liftIO (putMVar responseMVar r))
let respond response = do
putMVar responseMVar response
return ResponseReceived
ResponseReceived <- app request respond
executeRequest :: Application -> Request -> IO Response
executeRequest app request = do
responseMVar <- newEmptyMVar
let respond response = do
putMVar responseMVar response
return ResponseReceived
ResponseReceived <- app request respond
takeMVar responseMVar
* waiter | # LANGUAGE DataKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
module Servant.StreamingSpec where
import Control.Concurrent
import Control.Exception hiding (Handler)
import Control.Monad.IO.Class
import qualified Data.ByteString as Strict
import Control.Monad.State (modify)
import qualified Data.ByteString.Lazy as Lazy
import Network.HTTP.Types
import Prelude
import Servant
import Snap.Core
import Snap.Internal.Http.Types
import Snap.Test
import Snap
import qualified System.Timeout
import qualified System.IO.Streams as IOS
import Test.Hspec
type TestAPI =
ReqBody '[OctetStream] Lazy.ByteString :> Post '[JSON] NoContent
testAPI :: Proxy TestAPI
testAPI = Proxy
spec :: Spec
spec = return ()
spec : : Spec
spec = do
it " client to server can stream lazy ByteStrings " $ timeout $ do
serverReceivedFirstChunk < - newWaiter
streamTestData < - do
mvar : : MVar [ IO Strict . ByteString ] < - newMVar $
map return ( replicate 1000 " foo " ) + +
( waitFor serverReceivedFirstChunk > > return " foo " ) :
map return ( replicate 1000 " foo " )
return $ modifyMVar mvar $ \ actions - > case actions of
( a : r ) - > ( r , ) < $ > a
[ ] - > return ( [ ] , " " )
rqStream < - IOS.makeInputStream ( Just < $ > streamTestData )
rqStream2 < - IOS.makeInputStream ( return ( Just " foo " ) )
let makeRequest : : RequestBuilder IO ( )
makeRequest = do
postRaw @IO " / " " application / octet - stream " " barbar "
let handler : : Lazy . ByteString - > Snap NoContent
handler input = do
liftIO $ putStrLn $ " handler Hello1 "
liftIO $ putStrLn $ " handler Hello2 "
liftIO $ do
print " handler Hello3 "
let prefix = Lazy.take 3 input
prefix ` shouldBe ` " foo "
print " handler "
notify serverReceivedFirstChunk ( )
print " handler Hello5 "
input ` shouldBe ` mconcat ( replicate 2001 " foo " )
return NoContent
app = serveSnap testAPI handler
putStrLn " Hello1 "
response < - executeRequest rqStream makeRequest app
rspStatus response ` shouldBe ` 200
executeRequest : : IOS.InputStream Strict . ByteString - > RequestBuilder IO ( ) - > Snap ( ) - > IO Response
executeRequest rqStream makeRequest act = do
putStrLn " Hello2 "
evalHandler makeRequest $ do
liftIO $ putStrLn " Hello3 "
liftIO $ putStrLn " Hello3.5 "
transformRequestBody $ \ _ - > return rqStream
liftIO $ putStrLn " Hello3.7 "
act
liftIO $ putStrLn " Hello4 "
r < - Snap.getResponse
liftIO ( putMVar )
takeMVar responseMVar
timeout : : IO a - > IO a
timeout action = do
result < - System.Timeout.timeout 1000000 action
maybe ( throwIO $ ErrorCall " timeout " ) return result
data a
= Waiter {
notify : : a - > IO ( ) ,
waitFor : : IO a
}
: : IO ( Waiter a )
= do
mvar < - newEmptyMVar
return $ Waiter {
notify = ,
waitFor = }
spec :: Spec
spec = do
it "client to server can stream lazy ByteStrings" $ timeout $ do
serverReceivedFirstChunk <- newWaiter
streamTestData <- do
mvar :: MVar [IO Strict.ByteString] <- newMVar $
map return (replicate 1000 "foo") ++
(waitFor serverReceivedFirstChunk >> return "foo") :
map return (replicate 1000 "foo")
return $ modifyMVar mvar $ \ actions -> case actions of
(a : r) -> (r, ) <$> a
[] -> return ([], "")
rqStream <- IOS.makeInputStream (Just <$> streamTestData)
rqStream2 <- IOS.makeInputStream (return (Just "foo"))
let makeRequest :: RequestBuilder IO ()
makeRequest = do
postRaw @IO "/" "application/octet-stream" "barbar"
let handler :: Lazy.ByteString -> Snap NoContent
handler input = do
liftIO $ putStrLn $ "handler Hello1"
liftIO $ putStrLn $ "handler Hello2"
liftIO $ do
print "handler Hello3"
let prefix = Lazy.take 3 input
prefix `shouldBe` "foo"
print "handler Hello4"
notify serverReceivedFirstChunk ()
print "handler Hello5"
input `shouldBe` mconcat (replicate 2001 "foo")
return NoContent
app = serveSnap testAPI handler
putStrLn "Hello1"
response <- executeRequest rqStream makeRequest app
rspStatus response `shouldBe` 200
executeRequest :: IOS.InputStream Strict.ByteString -> RequestBuilder IO () -> Snap () -> IO Response
executeRequest rqStream makeRequest act = do
responseMVar <- newEmptyMVar
putStrLn "Hello2"
evalHandler makeRequest $ do
liftIO $ putStrLn "Hello3"
liftIO $ putStrLn "Hello3.5"
transformRequestBody $ \_ -> return rqStream
liftIO $ putStrLn "Hello3.7"
act
liftIO $ putStrLn "Hello4"
r <- Snap.getResponse
liftIO (putMVar responseMVar r)
takeMVar responseMVar
timeout :: IO a -> IO a
timeout action = do
result <- System.Timeout.timeout 1000000 action
maybe (throwIO $ ErrorCall "timeout") return result
data Waiter a
= Waiter {
notify :: a -> IO (),
waitFor :: IO a
}
newWaiter :: IO (Waiter a)
newWaiter = do
mvar <- newEmptyMVar
return $ Waiter {
notify = putMVar mvar,
waitFor = readMVar mvar
}
-}
|
48856702570deb32ad8e57035efd11a2e819f50220fe40fbaa354b073151d458 | sgbj/MaximaSharp | zgemv.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
;;; Using Lisp CMU Common Lisp 20d (20D Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :blas)
(let* ((one (f2cl-lib:cmplx 1.0 0.0)) (zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) one)
(type (f2cl-lib:complex16) zero)
(ignorable one zero))
(defun zgemv (trans m n alpha a lda x incx beta y incy)
(declare (type (array f2cl-lib:complex16 (*)) y x a)
(type (f2cl-lib:complex16) beta alpha)
(type (f2cl-lib:integer4) incy incx lda n m)
(type (simple-string *) trans))
(f2cl-lib:with-multi-array-data
((trans character trans-%data% trans-%offset%)
(a f2cl-lib:complex16 a-%data% a-%offset%)
(x f2cl-lib:complex16 x-%data% x-%offset%)
(y f2cl-lib:complex16 y-%data% y-%offset%))
(prog ((noconj nil) (i 0) (info 0) (ix 0) (iy 0) (j 0) (jx 0) (jy 0)
(kx 0) (ky 0) (lenx 0) (leny 0) (temp #C(0.0 0.0)))
(declare (type f2cl-lib:logical noconj)
(type (f2cl-lib:integer4) i info ix iy j jx jy kx ky lenx
leny)
(type (f2cl-lib:complex16) temp))
(setf info 0)
(cond
((and (not (lsame trans "N"))
(not (lsame trans "T"))
(not (lsame trans "C")))
(setf info 1))
((< m 0)
(setf info 2))
((< n 0)
(setf info 3))
((< lda (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 m)))
(setf info 6))
((= incx 0)
(setf info 8))
((= incy 0)
(setf info 11)))
(cond
((/= info 0)
(xerbla "ZGEMV " info)
(go end_label)))
(if (or (= m 0) (= n 0) (and (= alpha zero) (= beta one)))
(go end_label))
(setf noconj (lsame trans "T"))
(cond
((lsame trans "N")
(setf lenx n)
(setf leny m))
(t
(setf lenx m)
(setf leny n)))
(cond
((> incx 0)
(setf kx 1))
(t
(setf kx
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul
(f2cl-lib:int-sub lenx 1)
incx)))))
(cond
((> incy 0)
(setf ky 1))
(t
(setf ky
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul
(f2cl-lib:int-sub leny 1)
incy)))))
(cond
((/= beta one)
(cond
((= incy 1)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i leny) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
zero)
label10)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i leny) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(i)
((1 *))
y-%offset%)))
label20)))))
(t
(setf iy ky)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i leny) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
zero)
(setf iy (f2cl-lib:int-add iy incy))
label30)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i leny) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(iy)
((1 *))
y-%offset%)))
(setf iy (f2cl-lib:int-add iy incy))
label40))))))))
(if (= alpha zero) (go end_label))
(cond
((lsame trans "N")
(setf jx kx)
(cond
((= incy 1)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (jx) ((1 *))) zero)
(setf temp
(* alpha
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data%
(i)
((1 *))
y-%offset%)
(* temp
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%))))
label50))))
(setf jx (f2cl-lib:int-add jx incx))
label60)))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (jx) ((1 *))) zero)
(setf temp
(* alpha
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)))
(setf iy ky)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data%
(iy)
((1 *))
y-%offset%)
(* temp
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%))))
(setf iy (f2cl-lib:int-add iy incy))
label70))))
(setf jx (f2cl-lib:int-add jx incx))
label80)))))
(t
(setf jy ky)
(cond
((= incx 1)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp zero)
(cond
(noconj
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp
(+ temp
(*
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label90)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp
(+ temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label100))))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* alpha temp)))
(setf jy (f2cl-lib:int-add jy incy))
label110)))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp zero)
(setf ix kx)
(cond
(noconj
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp
(+ temp
(*
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
label120)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp
(+ temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
label130))))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* alpha temp)))
(setf jy (f2cl-lib:int-add jy incy))
label140))))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zgemv fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-string) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/lapack/blas/zgemv.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp 20d (20D Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
(in-package :blas)
(let* ((one (f2cl-lib:cmplx 1.0 0.0)) (zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) one)
(type (f2cl-lib:complex16) zero)
(ignorable one zero))
(defun zgemv (trans m n alpha a lda x incx beta y incy)
(declare (type (array f2cl-lib:complex16 (*)) y x a)
(type (f2cl-lib:complex16) beta alpha)
(type (f2cl-lib:integer4) incy incx lda n m)
(type (simple-string *) trans))
(f2cl-lib:with-multi-array-data
((trans character trans-%data% trans-%offset%)
(a f2cl-lib:complex16 a-%data% a-%offset%)
(x f2cl-lib:complex16 x-%data% x-%offset%)
(y f2cl-lib:complex16 y-%data% y-%offset%))
(prog ((noconj nil) (i 0) (info 0) (ix 0) (iy 0) (j 0) (jx 0) (jy 0)
(kx 0) (ky 0) (lenx 0) (leny 0) (temp #C(0.0 0.0)))
(declare (type f2cl-lib:logical noconj)
(type (f2cl-lib:integer4) i info ix iy j jx jy kx ky lenx
leny)
(type (f2cl-lib:complex16) temp))
(setf info 0)
(cond
((and (not (lsame trans "N"))
(not (lsame trans "T"))
(not (lsame trans "C")))
(setf info 1))
((< m 0)
(setf info 2))
((< n 0)
(setf info 3))
((< lda (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 m)))
(setf info 6))
((= incx 0)
(setf info 8))
((= incy 0)
(setf info 11)))
(cond
((/= info 0)
(xerbla "ZGEMV " info)
(go end_label)))
(if (or (= m 0) (= n 0) (and (= alpha zero) (= beta one)))
(go end_label))
(setf noconj (lsame trans "T"))
(cond
((lsame trans "N")
(setf lenx n)
(setf leny m))
(t
(setf lenx m)
(setf leny n)))
(cond
((> incx 0)
(setf kx 1))
(t
(setf kx
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul
(f2cl-lib:int-sub lenx 1)
incx)))))
(cond
((> incy 0)
(setf ky 1))
(t
(setf ky
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul
(f2cl-lib:int-sub leny 1)
incy)))))
(cond
((/= beta one)
(cond
((= incy 1)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i leny) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
zero)
label10)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i leny) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(i)
((1 *))
y-%offset%)))
label20)))))
(t
(setf iy ky)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i leny) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
zero)
(setf iy (f2cl-lib:int-add iy incy))
label30)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i leny) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(iy)
((1 *))
y-%offset%)))
(setf iy (f2cl-lib:int-add iy incy))
label40))))))))
(if (= alpha zero) (go end_label))
(cond
((lsame trans "N")
(setf jx kx)
(cond
((= incy 1)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (jx) ((1 *))) zero)
(setf temp
(* alpha
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data%
(i)
((1 *))
y-%offset%)
(* temp
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%))))
label50))))
(setf jx (f2cl-lib:int-add jx incx))
label60)))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (jx) ((1 *))) zero)
(setf temp
(* alpha
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)))
(setf iy ky)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data%
(iy)
((1 *))
y-%offset%)
(* temp
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%))))
(setf iy (f2cl-lib:int-add iy incy))
label70))))
(setf jx (f2cl-lib:int-add jx incx))
label80)))))
(t
(setf jy ky)
(cond
((= incx 1)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp zero)
(cond
(noconj
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp
(+ temp
(*
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label90)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp
(+ temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label100))))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* alpha temp)))
(setf jy (f2cl-lib:int-add jy incy))
label110)))
(t
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp zero)
(setf ix kx)
(cond
(noconj
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp
(+ temp
(*
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
label120)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i m) nil)
(tagbody
(setf temp
(+ temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
label130))))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* alpha temp)))
(setf jy (f2cl-lib:int-add jy incy))
label140))))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zgemv fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-string) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
|
ae8889b1be5664fc13f23a9a349c03430b0e82bfa6e6456759c235b7b54fd71c | sunng87/slacker | client.clj | (ns slacker.client
(:require [clojure.string :refer [split]]
[link.tcp :onlu [stop-clients]]
[slacker.common :refer :all :as c]
[slacker.client.common :refer :all]
[slacker.interceptor :as interceptor]))
(defonce ^{:doc "the default client factory using plain socket"}
cached-slacker-client-factory
(delay (create-client-factory nil)))
(defn slacker-client-factory
"Create a secure client factory from ssl-connect"
[ssl-context]
(create-client-factory ssl-context))
(defn slackerc
"Create connection to a slacker server."
[addr
& {:keys [content-type factory ping-interval timeout backlog
interrupt-on-timeout interceptors callback-executor
protocol-version]
:or {content-type :clj
interceptors interceptor/default-interceptors}}]
(let [factory (or factory @cached-slacker-client-factory)]
(delay (create-client factory addr content-type
{:timeout timeout
:backlog backlog
:ping-interval ping-interval
:interrupt-on-timeout interrupt-on-timeout
:interceptors interceptors
:callback-executor callback-executor
:protocol-version protocol-version}))))
(defn close-slackerc
"Close a slacker client"
[client]
(when (realized? client)
(close @client)))
(defn shutdown-slacker-client-factory
"Shutdown a client factory, close all clients derived from it."
([] (shutdown-factory @cached-slacker-client-factory))
([factory] (shutdown-factory factory)))
(defmacro defn-remote
"Define a facade for remote function. You have to provide the
connection and the function name. (Argument list is not required here.)"
([sc fname & {:keys [remote-ns remote-name async? fire-and-forget?
callback extensions]
:or {remote-ns (ns-name *ns*)
remote-name nil
async? false
fire-and-forget? false
callback nil}
:as options}]
(let [fname-str (str fname)
remote-ns-declared (> (.indexOf fname-str "/") 0)
[remote-ns remote-name] (if remote-ns-declared
(split fname-str #"/" 2)
[remote-ns
(or remote-name fname-str)])
facade-sym (if remote-ns-declared
(symbol remote-name)
fname)]
`(def ~facade-sym
(with-meta
(fn [& args#]
(apply invoke-slacker ~sc
[~remote-ns ~remote-name (into [] args#)]
(mapcat vec (into [] ~options))))
{:slacker-remote-fn true
:slacker-client ~sc
:slacker-remote-ns ~remote-ns
:slacker-remote-name ~remote-name})))))
(defn- defn-remote*
[sc-sym fname]
(eval (list 'slacker.client/defn-remote sc-sym (symbol fname))))
(defn call-remote
"call a remote function by its namespace and function name, without a
local `defn-remote` reference.
* `sc` the slacker client
* `remote-ns` remote namespace, string
* `remote-fn` remote function name, string
* `args` arguments, vec
* `:async? true` make this a async function, returns a manifold deferred
* `:callback (fn [r e] )` set a callback for this async function
* `:extensions {}` add extension data for the function call"
[sc remote-ns remote-fn args
& {:keys [async? callback extensions]
:as options}]
(apply invoke-slacker sc [remote-ns remote-fn args]
(mapcat vec (into [] options))))
(defn use-remote
"import remote functions the current namespace, this function
will generate remote call, use it carefully in a declarative style."
([sc-sym] (use-remote sc-sym (ns-name *ns*)))
([sc-sym rns] (use-remote sc-sym rns nil))
([sc-sym rns lns & {:keys [only exclude]
:or {only [] exclude []}}]
(if (and (not-empty only) (not-empty exclude))
(throw (IllegalArgumentException.
"do not provide :only and :exclude both")))
(let [name-fn #(str rns "/" %)
filter-fn (cond
(not-empty only)
#(contains? (set (map name-fn only)) %)
(not-empty exclude)
#(not (contains? (set (map name-fn exclude)) %))
:else (constantly true))
all-functions (functions-remote @(resolve sc-sym) (str rns))]
(binding [*ns* (or lns *ns*)]
(dorun (map defn-remote*
(repeat sc-sym)
(filter filter-fn all-functions)))))))
(defmacro with-slackerc
"call the slacker remote function with a client other than the client
used to declare the function"
[sc & body]
`(binding [*sc* ~sc] ~@body))
(defmacro with-callback
"call the slacker remote function with a custom callback, and make the
function an async one"
[& body]
(let [cb (last body)
body (drop-last body)]
`(binding [*callback* ~cb] ~@body)))
(defn slacker-meta
"Fetch metadata of a slacker function."
[f]
(let [metadata (meta f)
{sc :slacker-client
remote-ns :slacker-remote-ns
remote-fn :slacker-remote-name} metadata]
(if sc
(merge metadata
(meta-remote sc (str remote-ns "/" remote-fn)))
metadata)))
(defn slacker-server-status
"Fetch server status of current slacker server."
[sc]
(clients-remote sc))
| null | https://raw.githubusercontent.com/sunng87/slacker/8c5b9028e659b821c42f4351c055c1c4f577ae3f/src/slacker/client.clj | clojure | (ns slacker.client
(:require [clojure.string :refer [split]]
[link.tcp :onlu [stop-clients]]
[slacker.common :refer :all :as c]
[slacker.client.common :refer :all]
[slacker.interceptor :as interceptor]))
(defonce ^{:doc "the default client factory using plain socket"}
cached-slacker-client-factory
(delay (create-client-factory nil)))
(defn slacker-client-factory
"Create a secure client factory from ssl-connect"
[ssl-context]
(create-client-factory ssl-context))
(defn slackerc
"Create connection to a slacker server."
[addr
& {:keys [content-type factory ping-interval timeout backlog
interrupt-on-timeout interceptors callback-executor
protocol-version]
:or {content-type :clj
interceptors interceptor/default-interceptors}}]
(let [factory (or factory @cached-slacker-client-factory)]
(delay (create-client factory addr content-type
{:timeout timeout
:backlog backlog
:ping-interval ping-interval
:interrupt-on-timeout interrupt-on-timeout
:interceptors interceptors
:callback-executor callback-executor
:protocol-version protocol-version}))))
(defn close-slackerc
"Close a slacker client"
[client]
(when (realized? client)
(close @client)))
(defn shutdown-slacker-client-factory
"Shutdown a client factory, close all clients derived from it."
([] (shutdown-factory @cached-slacker-client-factory))
([factory] (shutdown-factory factory)))
(defmacro defn-remote
"Define a facade for remote function. You have to provide the
connection and the function name. (Argument list is not required here.)"
([sc fname & {:keys [remote-ns remote-name async? fire-and-forget?
callback extensions]
:or {remote-ns (ns-name *ns*)
remote-name nil
async? false
fire-and-forget? false
callback nil}
:as options}]
(let [fname-str (str fname)
remote-ns-declared (> (.indexOf fname-str "/") 0)
[remote-ns remote-name] (if remote-ns-declared
(split fname-str #"/" 2)
[remote-ns
(or remote-name fname-str)])
facade-sym (if remote-ns-declared
(symbol remote-name)
fname)]
`(def ~facade-sym
(with-meta
(fn [& args#]
(apply invoke-slacker ~sc
[~remote-ns ~remote-name (into [] args#)]
(mapcat vec (into [] ~options))))
{:slacker-remote-fn true
:slacker-client ~sc
:slacker-remote-ns ~remote-ns
:slacker-remote-name ~remote-name})))))
(defn- defn-remote*
[sc-sym fname]
(eval (list 'slacker.client/defn-remote sc-sym (symbol fname))))
(defn call-remote
"call a remote function by its namespace and function name, without a
local `defn-remote` reference.
* `sc` the slacker client
* `remote-ns` remote namespace, string
* `remote-fn` remote function name, string
* `args` arguments, vec
* `:async? true` make this a async function, returns a manifold deferred
* `:callback (fn [r e] )` set a callback for this async function
* `:extensions {}` add extension data for the function call"
[sc remote-ns remote-fn args
& {:keys [async? callback extensions]
:as options}]
(apply invoke-slacker sc [remote-ns remote-fn args]
(mapcat vec (into [] options))))
(defn use-remote
"import remote functions the current namespace, this function
will generate remote call, use it carefully in a declarative style."
([sc-sym] (use-remote sc-sym (ns-name *ns*)))
([sc-sym rns] (use-remote sc-sym rns nil))
([sc-sym rns lns & {:keys [only exclude]
:or {only [] exclude []}}]
(if (and (not-empty only) (not-empty exclude))
(throw (IllegalArgumentException.
"do not provide :only and :exclude both")))
(let [name-fn #(str rns "/" %)
filter-fn (cond
(not-empty only)
#(contains? (set (map name-fn only)) %)
(not-empty exclude)
#(not (contains? (set (map name-fn exclude)) %))
:else (constantly true))
all-functions (functions-remote @(resolve sc-sym) (str rns))]
(binding [*ns* (or lns *ns*)]
(dorun (map defn-remote*
(repeat sc-sym)
(filter filter-fn all-functions)))))))
(defmacro with-slackerc
"call the slacker remote function with a client other than the client
used to declare the function"
[sc & body]
`(binding [*sc* ~sc] ~@body))
(defmacro with-callback
"call the slacker remote function with a custom callback, and make the
function an async one"
[& body]
(let [cb (last body)
body (drop-last body)]
`(binding [*callback* ~cb] ~@body)))
(defn slacker-meta
"Fetch metadata of a slacker function."
[f]
(let [metadata (meta f)
{sc :slacker-client
remote-ns :slacker-remote-ns
remote-fn :slacker-remote-name} metadata]
(if sc
(merge metadata
(meta-remote sc (str remote-ns "/" remote-fn)))
metadata)))
(defn slacker-server-status
"Fetch server status of current slacker server."
[sc]
(clients-remote sc))
| |
fa17d9175b94e5b4e1d3d18d92e771616e5dd1f333c47af4c956c2d4129ebc67 | emptyflash/yinlang | Infer.hs | # LANGUAGE FlexibleInstances #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE GeneralizedNewtypeDeriving #
module Infer where
import Prelude hiding (foldr)
import Type
import Syntax
import Control.Monad.State
import Control.Monad.Except
import Data.Monoid
import Data.List (nub)
import Data.Foldable (foldr)
import qualified Data.Map as Map
import qualified Data.Set as Set
newtype TypeEnv = TypeEnv (Map.Map Var Scheme)
deriving (Semigroup, Monoid, Show)
data Unique = Unique { count :: Int }
type Infer = ExceptT TypeError (State Unique)
type Subst = Map.Map TVar Type
data TypeError
= UnificationFail Type Type Offset Offset
| InfiniteType TVar Type
| UnboundVariable String Offset Offset
deriving (Show, Eq, Ord)
glslStdLib :: TypeEnv
glslStdLib = TypeEnv $ Map.fromList
[ ("vec2", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Vec2))
, ("vec3", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Vec3))
, ("vec4", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Vec4))
, ("mat2", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Mat2))
, ("dot", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TCon Float))
, ("smoothstep", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a")))
, ("step", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a")))
, ("fract", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("sin", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("cos", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("floor", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("mix", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TCon Float `TArr` TVar (TV "a")))
, ("abs", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("mod", Forall [TV "a"] (TVar (TV "a") `TArr` TCon Float `TArr` TVar (TV "a")))
, ("clamp", Forall [TV "a"] (TVar (TV "a") `TArr` TCon Float `TArr` TCon Float `TArr` TVar (TV "a")))
, ("atan", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Float))
, ("length", Forall [TV "a"] (TVar (TV "a") `TArr` TCon Float))
, ("min", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a")))
, ("max", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a")))
, ("texture1D", Forall [] (TCon Sampler1D `TArr` TCon Float `TArr` TCon Vec4))
, ("texture2D", Forall [] (TCon Sampler2D `TArr` TCon Vec2 `TArr` TCon Vec4))
, ("texture3D", Forall [] (TCon Sampler3D `TArr` TCon Vec3 `TArr` TCon Vec4))
]
runInfer :: Infer (Subst, Type, Offsets) -> Either TypeError Scheme
runInfer m = case evalState (runExceptT m) initUnique of
Left err -> Left err
Right res -> Right $ closeOver res
closeOver :: (Subst, Type, Offsets) -> Scheme
closeOver (sub, ty, _) = normalize sc
where sc = generalize emptyTyenv (apply sub ty)
initUnique :: Unique
initUnique = Unique { count = 0 }
-- TODO: this should return an error if the name already exists and isn't the same type
extend :: TypeEnv -> (Var, Scheme) -> TypeEnv
extend (TypeEnv env) (x, s) = TypeEnv $ Map.insertWith (flip const) x s env
emptyTyenv :: TypeEnv
emptyTyenv = TypeEnv Map.empty
typeof :: TypeEnv -> Var -> Maybe Type.Scheme
typeof (TypeEnv env) name = Map.lookup name env
class Substitutable a where
apply :: Subst -> a -> a
ftv :: a -> Set.Set TVar
instance Substitutable Type where
apply _ (TCon a) = TCon a
apply s t@(TVar a) = Map.findWithDefault t a s
apply s (t1 `TArr` t2) = apply s t1 `TArr` apply s t2
ftv TCon{} = Set.empty
ftv (TVar a) = Set.singleton a
ftv (t1 `TArr` t2) = ftv t1 `Set.union` ftv t2
instance Substitutable Scheme where
apply s (Forall as t) = Forall as $ apply s' t
where s' = foldr Map.delete s as
ftv (Forall as t) = ftv t `Set.difference` Set.fromList as
instance Substitutable a => Substitutable [a] where
apply = fmap . apply
ftv = foldr (Set.union . ftv) Set.empty
instance Substitutable TypeEnv where
apply s (TypeEnv env) = TypeEnv $ Map.map (apply s) env
ftv (TypeEnv env) = ftv $ Map.elems env
nullSubst :: Subst
nullSubst = Map.empty
compose :: Subst -> Subst -> Subst
s1 `compose` s2 = Map.map (apply s1) s2 `Map.union` s1
unify :: Type -> Type -> (Offset, Offset) -> Infer Subst
unify (l `TArr` r) (l' `TArr` r') offsets = do
s1 <- unify l l' offsets
s2 <- unify (apply s1 r) (apply s1 r') offsets
return (s2 `compose` s1)
unify (TVar a) t _ = bind a t
unify t (TVar a) _ = bind a t
unify (TCon a) (TCon b) _ | a == b = return nullSubst
unify t1 t2 (s, e) = throwError $ UnificationFail t1 t2 s e
bind :: TVar -> Type -> Infer Subst
bind a t
| t == TVar a = return nullSubst
| occursCheck a t = throwError $ InfiniteType a t
| otherwise = return $ Map.singleton a t
occursCheck :: Substitutable a => TVar -> a -> Bool
occursCheck a t = a `Set.member` ftv t
letters :: [String]
letters = [1..] >>= flip replicateM ['a'..'z']
fresh :: Infer Type
fresh = do
s <- get
put s{count = count s + 1}
return $ TVar $ TV (letters !! count s)
instantiate :: Scheme -> Infer Type
instantiate (Forall as t) = do
as' <- mapM (const fresh) as
let s = Map.fromList $ zip as as'
return $ apply s t
generalize :: TypeEnv -> Type -> Scheme
generalize env t = Forall as t
where as = Set.toList $ ftv t `Set.difference` ftv env
ops :: Type -> Binop -> Type
ops tv Add = tv `TArr` tv `TArr` tv
ops tv Mul = tv `TArr` tv `TArr` tv
ops tv Sub = tv `TArr` tv `TArr` tv
ops tv Div = tv `TArr` tv `TArr` tv
ops tv Eql = tv `TArr` tv `TArr` typeBool
ops tv Gt = tv `TArr` tv `TArr` typeBool
ops tv Gte = tv `TArr` tv `TArr` typeBool
ops tv Lt = tv `TArr` tv `TArr` typeBool
ops tv Lte = tv `TArr` tv `TArr` typeBool
lookupEnv :: TypeEnv -> Var -> Offsets -> Infer (Subst, Type, Offsets)
lookupEnv (TypeEnv env) x (start, end) =
case Map.lookup x env of
Nothing -> throwError $ UnboundVariable (show x) start end
Just s -> do t <- instantiate s
return (nullSubst, t, (start, end))
extendDecl :: TypeEnv -> Decl -> Infer (Subst, TypeEnv)
extendDecl env (name, e) = do
(s, t, _) <- infer env e
let env' = apply s env
t' = generalize env' t
pure $ (s, env' `extend` (name, t'))
extendDecls :: TypeEnv -> [Decl] -> Infer (Subst, TypeEnv)
extendDecls env =
foldM step (nullSubst, env)
where
step (s, e) decl = do
(s1, e2) <- extendDecl e decl
pure (s1 `compose` s, e2)
swizzleType :: String -> Type
swizzleType sw = case length sw of
1 -> TCon Float
2 -> TCon Vec2
3 -> TCon Vec3
4 -> TCon Vec4
infer :: TypeEnv -> Expr -> Infer (Subst, Type, Offsets)
infer env ex = case ex of
Var x start end -> lookupEnv env x (start, end)
Lam x e _ _-> do
tv <- fresh
let env' = env `extend` (x, Forall [] tv)
(s1, t1, _) <- infer env' e
return (s1, apply s1 tv `TArr` t1, offsetsFromExpr ex)
App e1 e2 start end -> do
tv <- fresh
(s1, t1, _) <- infer env e1
(s2, t2, _) <- infer (apply s1 env) e2
s3 <- unify (apply s2 t1) (TArr t2 tv) (start, end)
return (s3 `compose` s2 `compose` s1, apply s3 tv, offsetsFromExpr ex)
Let decls e2 -> do
(s1, env') <- extendDecls env decls
(s2, t2, _) <- infer env' e2
return (s2 `compose` s1, t2, offsetsFromExpr ex)
If cond tr fl _ _ -> do
tv <- fresh
inferPrim env [cond, tr, fl] (typeBool `TArr` tv `TArr` tv `TArr` tv)
Op op e1 e2 _ _ -> do
tv <- fresh
inferPrim env [e1, e2] (ops tv op)
Swizzle var sw -> do
-- TODO Actually check that the swizzle is valid for the type and the name exists
-- Maybe use inferPrim?
return (nullSubst, swizzleType sw, offsetsFromExpr ex)
Lit (LInt _) -> return (nullSubst, typeInt, offsetsFromExpr ex)
Lit (LBool _) -> return (nullSubst, typeBool, offsetsFromExpr ex)
Lit (LFloat _) -> return (nullSubst, typeFloat, offsetsFromExpr ex)
inferPrim :: TypeEnv -> [Expr] -> Type -> Infer (Subst, Type, Offsets)
inferPrim env l t = do
tv <- fresh
(s1, tf, o) <- foldM inferStep (nullSubst, id, (0, 0)) l
s2 <- unify (apply s1 (tf tv)) t o
return (s2 `compose` s1, apply s2 tv, o)
where
inferStep (s, tf, _) exp = do
(s', t, o) <- infer (apply s env) exp
return (s' `compose` s, tf . (TArr t), o)
inferExpr :: TypeEnv -> Expr -> Either TypeError Scheme
inferExpr env = runInfer . infer env
inferTop :: TypeEnv -> [Decl] -> Either TypeError TypeEnv
inferTop env [] = Right env
inferTop env ((name, ParameterDecl (Uniform ty)):xs) = let
newEnv = extend env $ (name, Forall [] $ TCon ty)
in inferTop newEnv xs
inferTop env ((name, TypeAscription scheme):xs) = let
newEnv = extend env $ (name, scheme)
in inferTop newEnv xs
inferTop env ((name, ex):xs) = case inferExpr env ex of
Left err -> Left err
Right ty -> inferTop (extend env (name, ty)) xs
normalize :: Scheme -> Scheme
normalize (Forall ts body) = Forall (fmap snd ord) (normtype body)
where
ord = zip (nub $ fv body) (fmap TV letters)
fv (TVar a) = [a]
fv (TArr a b) = fv a ++ fv b
fv (TCon _) = []
normtype (TArr a b) = TArr (normtype a) (normtype b)
normtype (TCon a) = TCon a
normtype (TVar a) =
case lookup a ord of
Just x -> TVar x
Nothing -> error "type variable not in signature"
| null | https://raw.githubusercontent.com/emptyflash/yinlang/23a5f59fe7895e557e54a3a67fef363dce3639ef/src/Infer.hs | haskell | # LANGUAGE TypeSynonymInstances #
TODO: this should return an error if the name already exists and isn't the same type
TODO Actually check that the swizzle is valid for the type and the name exists
Maybe use inferPrim? | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
module Infer where
import Prelude hiding (foldr)
import Type
import Syntax
import Control.Monad.State
import Control.Monad.Except
import Data.Monoid
import Data.List (nub)
import Data.Foldable (foldr)
import qualified Data.Map as Map
import qualified Data.Set as Set
newtype TypeEnv = TypeEnv (Map.Map Var Scheme)
deriving (Semigroup, Monoid, Show)
data Unique = Unique { count :: Int }
type Infer = ExceptT TypeError (State Unique)
type Subst = Map.Map TVar Type
data TypeError
= UnificationFail Type Type Offset Offset
| InfiniteType TVar Type
| UnboundVariable String Offset Offset
deriving (Show, Eq, Ord)
glslStdLib :: TypeEnv
glslStdLib = TypeEnv $ Map.fromList
[ ("vec2", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Vec2))
, ("vec3", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Vec3))
, ("vec4", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Vec4))
, ("mat2", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Float `TArr` TCon Mat2))
, ("dot", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TCon Float))
, ("smoothstep", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a")))
, ("step", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a")))
, ("fract", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("sin", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("cos", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("floor", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("mix", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TCon Float `TArr` TVar (TV "a")))
, ("abs", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a")))
, ("mod", Forall [TV "a"] (TVar (TV "a") `TArr` TCon Float `TArr` TVar (TV "a")))
, ("clamp", Forall [TV "a"] (TVar (TV "a") `TArr` TCon Float `TArr` TCon Float `TArr` TVar (TV "a")))
, ("atan", Forall [] (TCon Float `TArr` TCon Float `TArr` TCon Float))
, ("length", Forall [TV "a"] (TVar (TV "a") `TArr` TCon Float))
, ("min", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a")))
, ("max", Forall [TV "a"] (TVar (TV "a") `TArr` TVar (TV "a") `TArr` TVar (TV "a")))
, ("texture1D", Forall [] (TCon Sampler1D `TArr` TCon Float `TArr` TCon Vec4))
, ("texture2D", Forall [] (TCon Sampler2D `TArr` TCon Vec2 `TArr` TCon Vec4))
, ("texture3D", Forall [] (TCon Sampler3D `TArr` TCon Vec3 `TArr` TCon Vec4))
]
runInfer :: Infer (Subst, Type, Offsets) -> Either TypeError Scheme
runInfer m = case evalState (runExceptT m) initUnique of
Left err -> Left err
Right res -> Right $ closeOver res
closeOver :: (Subst, Type, Offsets) -> Scheme
closeOver (sub, ty, _) = normalize sc
where sc = generalize emptyTyenv (apply sub ty)
initUnique :: Unique
initUnique = Unique { count = 0 }
extend :: TypeEnv -> (Var, Scheme) -> TypeEnv
extend (TypeEnv env) (x, s) = TypeEnv $ Map.insertWith (flip const) x s env
emptyTyenv :: TypeEnv
emptyTyenv = TypeEnv Map.empty
typeof :: TypeEnv -> Var -> Maybe Type.Scheme
typeof (TypeEnv env) name = Map.lookup name env
class Substitutable a where
apply :: Subst -> a -> a
ftv :: a -> Set.Set TVar
instance Substitutable Type where
apply _ (TCon a) = TCon a
apply s t@(TVar a) = Map.findWithDefault t a s
apply s (t1 `TArr` t2) = apply s t1 `TArr` apply s t2
ftv TCon{} = Set.empty
ftv (TVar a) = Set.singleton a
ftv (t1 `TArr` t2) = ftv t1 `Set.union` ftv t2
instance Substitutable Scheme where
apply s (Forall as t) = Forall as $ apply s' t
where s' = foldr Map.delete s as
ftv (Forall as t) = ftv t `Set.difference` Set.fromList as
instance Substitutable a => Substitutable [a] where
apply = fmap . apply
ftv = foldr (Set.union . ftv) Set.empty
instance Substitutable TypeEnv where
apply s (TypeEnv env) = TypeEnv $ Map.map (apply s) env
ftv (TypeEnv env) = ftv $ Map.elems env
nullSubst :: Subst
nullSubst = Map.empty
compose :: Subst -> Subst -> Subst
s1 `compose` s2 = Map.map (apply s1) s2 `Map.union` s1
unify :: Type -> Type -> (Offset, Offset) -> Infer Subst
unify (l `TArr` r) (l' `TArr` r') offsets = do
s1 <- unify l l' offsets
s2 <- unify (apply s1 r) (apply s1 r') offsets
return (s2 `compose` s1)
unify (TVar a) t _ = bind a t
unify t (TVar a) _ = bind a t
unify (TCon a) (TCon b) _ | a == b = return nullSubst
unify t1 t2 (s, e) = throwError $ UnificationFail t1 t2 s e
bind :: TVar -> Type -> Infer Subst
bind a t
| t == TVar a = return nullSubst
| occursCheck a t = throwError $ InfiniteType a t
| otherwise = return $ Map.singleton a t
occursCheck :: Substitutable a => TVar -> a -> Bool
occursCheck a t = a `Set.member` ftv t
letters :: [String]
letters = [1..] >>= flip replicateM ['a'..'z']
fresh :: Infer Type
fresh = do
s <- get
put s{count = count s + 1}
return $ TVar $ TV (letters !! count s)
instantiate :: Scheme -> Infer Type
instantiate (Forall as t) = do
as' <- mapM (const fresh) as
let s = Map.fromList $ zip as as'
return $ apply s t
generalize :: TypeEnv -> Type -> Scheme
generalize env t = Forall as t
where as = Set.toList $ ftv t `Set.difference` ftv env
ops :: Type -> Binop -> Type
ops tv Add = tv `TArr` tv `TArr` tv
ops tv Mul = tv `TArr` tv `TArr` tv
ops tv Sub = tv `TArr` tv `TArr` tv
ops tv Div = tv `TArr` tv `TArr` tv
ops tv Eql = tv `TArr` tv `TArr` typeBool
ops tv Gt = tv `TArr` tv `TArr` typeBool
ops tv Gte = tv `TArr` tv `TArr` typeBool
ops tv Lt = tv `TArr` tv `TArr` typeBool
ops tv Lte = tv `TArr` tv `TArr` typeBool
lookupEnv :: TypeEnv -> Var -> Offsets -> Infer (Subst, Type, Offsets)
lookupEnv (TypeEnv env) x (start, end) =
case Map.lookup x env of
Nothing -> throwError $ UnboundVariable (show x) start end
Just s -> do t <- instantiate s
return (nullSubst, t, (start, end))
extendDecl :: TypeEnv -> Decl -> Infer (Subst, TypeEnv)
extendDecl env (name, e) = do
(s, t, _) <- infer env e
let env' = apply s env
t' = generalize env' t
pure $ (s, env' `extend` (name, t'))
extendDecls :: TypeEnv -> [Decl] -> Infer (Subst, TypeEnv)
extendDecls env =
foldM step (nullSubst, env)
where
step (s, e) decl = do
(s1, e2) <- extendDecl e decl
pure (s1 `compose` s, e2)
swizzleType :: String -> Type
swizzleType sw = case length sw of
1 -> TCon Float
2 -> TCon Vec2
3 -> TCon Vec3
4 -> TCon Vec4
infer :: TypeEnv -> Expr -> Infer (Subst, Type, Offsets)
infer env ex = case ex of
Var x start end -> lookupEnv env x (start, end)
Lam x e _ _-> do
tv <- fresh
let env' = env `extend` (x, Forall [] tv)
(s1, t1, _) <- infer env' e
return (s1, apply s1 tv `TArr` t1, offsetsFromExpr ex)
App e1 e2 start end -> do
tv <- fresh
(s1, t1, _) <- infer env e1
(s2, t2, _) <- infer (apply s1 env) e2
s3 <- unify (apply s2 t1) (TArr t2 tv) (start, end)
return (s3 `compose` s2 `compose` s1, apply s3 tv, offsetsFromExpr ex)
Let decls e2 -> do
(s1, env') <- extendDecls env decls
(s2, t2, _) <- infer env' e2
return (s2 `compose` s1, t2, offsetsFromExpr ex)
If cond tr fl _ _ -> do
tv <- fresh
inferPrim env [cond, tr, fl] (typeBool `TArr` tv `TArr` tv `TArr` tv)
Op op e1 e2 _ _ -> do
tv <- fresh
inferPrim env [e1, e2] (ops tv op)
Swizzle var sw -> do
return (nullSubst, swizzleType sw, offsetsFromExpr ex)
Lit (LInt _) -> return (nullSubst, typeInt, offsetsFromExpr ex)
Lit (LBool _) -> return (nullSubst, typeBool, offsetsFromExpr ex)
Lit (LFloat _) -> return (nullSubst, typeFloat, offsetsFromExpr ex)
inferPrim :: TypeEnv -> [Expr] -> Type -> Infer (Subst, Type, Offsets)
inferPrim env l t = do
tv <- fresh
(s1, tf, o) <- foldM inferStep (nullSubst, id, (0, 0)) l
s2 <- unify (apply s1 (tf tv)) t o
return (s2 `compose` s1, apply s2 tv, o)
where
inferStep (s, tf, _) exp = do
(s', t, o) <- infer (apply s env) exp
return (s' `compose` s, tf . (TArr t), o)
inferExpr :: TypeEnv -> Expr -> Either TypeError Scheme
inferExpr env = runInfer . infer env
inferTop :: TypeEnv -> [Decl] -> Either TypeError TypeEnv
inferTop env [] = Right env
inferTop env ((name, ParameterDecl (Uniform ty)):xs) = let
newEnv = extend env $ (name, Forall [] $ TCon ty)
in inferTop newEnv xs
inferTop env ((name, TypeAscription scheme):xs) = let
newEnv = extend env $ (name, scheme)
in inferTop newEnv xs
inferTop env ((name, ex):xs) = case inferExpr env ex of
Left err -> Left err
Right ty -> inferTop (extend env (name, ty)) xs
normalize :: Scheme -> Scheme
normalize (Forall ts body) = Forall (fmap snd ord) (normtype body)
where
ord = zip (nub $ fv body) (fmap TV letters)
fv (TVar a) = [a]
fv (TArr a b) = fv a ++ fv b
fv (TCon _) = []
normtype (TArr a b) = TArr (normtype a) (normtype b)
normtype (TCon a) = TCon a
normtype (TVar a) =
case lookup a ord of
Just x -> TVar x
Nothing -> error "type variable not in signature"
|
c042f48944ed8ce019c80f996d945d0731e7fb680c83bac26bfd004e525825ff | braidchat/braid | state.cljs | (ns braid.base.client.state
(:require
[clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[re-frame.core :as re-frame]
[braid.core.common.util :as util]))
(defn initialize-state
[db]
(-> (db ::initial-state)
(merge (select-keys db [::state-spec
::initial-state]))))
(re-frame/reg-event-fx ::register-state!
(fn [{db :db} [_ state spec]]
{:db (-> db
(update ::initial-state merge state)
(update ::state-spec merge spec))}))
(defn register-state!
[state spec]
Dispatch sync because we want the module setup calls
;; to finish before initializing the db
(re-frame/dispatch-sync [::register-state! state spec]))
(re-frame/reg-sub :braid.state/valid?
(fn [db _]
(util/valid? (db ::state-spec) db)))
(def validate-schema-interceptor
(re-frame/after
(fn [db [event-id]]
(when-let [errors (s/explain-data
(ds/spec {:name ::app-state
:spec (db ::state-spec)})
db)]
(js/console.error
(str
"Event " event-id
" caused the state to be invalid:\n")
(pr-str (map (fn [problem]
{:path (problem :path)
:pred (problem :pred)})
(::s/problems errors))))))))
(if ^boolean goog.DEBUG
(defn reg-event-fx
([id handler-fn]
(reg-event-fx id nil handler-fn))
([id interceptors handler-fn]
(re-frame/reg-event-fx
id
[validate-schema-interceptor
interceptors]
handler-fn)))
(def reg-event-fx re-frame/reg-event-fx))
| null | https://raw.githubusercontent.com/braidchat/braid/2e44eb6e77f1d203115f9b9c529bd865fa3d7302/src/braid/base/client/state.cljs | clojure | to finish before initializing the db | (ns braid.base.client.state
(:require
[clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[re-frame.core :as re-frame]
[braid.core.common.util :as util]))
(defn initialize-state
[db]
(-> (db ::initial-state)
(merge (select-keys db [::state-spec
::initial-state]))))
(re-frame/reg-event-fx ::register-state!
(fn [{db :db} [_ state spec]]
{:db (-> db
(update ::initial-state merge state)
(update ::state-spec merge spec))}))
(defn register-state!
[state spec]
Dispatch sync because we want the module setup calls
(re-frame/dispatch-sync [::register-state! state spec]))
(re-frame/reg-sub :braid.state/valid?
(fn [db _]
(util/valid? (db ::state-spec) db)))
(def validate-schema-interceptor
(re-frame/after
(fn [db [event-id]]
(when-let [errors (s/explain-data
(ds/spec {:name ::app-state
:spec (db ::state-spec)})
db)]
(js/console.error
(str
"Event " event-id
" caused the state to be invalid:\n")
(pr-str (map (fn [problem]
{:path (problem :path)
:pred (problem :pred)})
(::s/problems errors))))))))
(if ^boolean goog.DEBUG
(defn reg-event-fx
([id handler-fn]
(reg-event-fx id nil handler-fn))
([id interceptors handler-fn]
(re-frame/reg-event-fx
id
[validate-schema-interceptor
interceptors]
handler-fn)))
(def reg-event-fx re-frame/reg-event-fx))
|
b651153bb5aa88a75635aa9f05c705a5bb14b7950e2b0b4776540ecb0406a18e | politrons/Dive_into_Haskell | FirstProgram.hs | module FirstProgram where
import Data.Char
import Data.List
whatTimeIsIt :: IO String
whatTimeIsIt = do
putStrLn "What time is it now?"
getLine
outputProgram = do
timeString <- whatTimeIsIt
putStrLn "Again!"
timeString2 <- whatTimeIsIt
putStrLn ("Ok, you said it was "
++ timeString
++ " and then you said it was "
++ timeString2)
| null | https://raw.githubusercontent.com/politrons/Dive_into_Haskell/fd9dec14b87aecba0b3561385c1d75cf969546a4/src/features/FirstProgram.hs | haskell | module FirstProgram where
import Data.Char
import Data.List
whatTimeIsIt :: IO String
whatTimeIsIt = do
putStrLn "What time is it now?"
getLine
outputProgram = do
timeString <- whatTimeIsIt
putStrLn "Again!"
timeString2 <- whatTimeIsIt
putStrLn ("Ok, you said it was "
++ timeString
++ " and then you said it was "
++ timeString2)
| |
bf392cf6583a90de75eeee0d84f8cecc6e7cbd824a59f8fd5311c84a945cd5e3 | xclerc/ocamljava | bytecodegen_constants.mli |
* This file is part of compiler .
* Copyright ( C ) 2007 - 2015 .
*
* compiler is free software ; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* ( with a change to choice of law ) .
*
* compiler 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
* Q Public License for more details .
*
* You should have received a copy of the Q Public License
* along with this program . If not , see
* < -1.0 > .
* This file is part of OCaml-Java compiler.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java compiler is free software; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* Trolltech (with a change to choice of law).
*
* OCaml-Java compiler 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
* Q Public License for more details.
*
* You should have received a copy of the Q Public License
* along with this program. If not, see
* <-1.0>.
*)
(** Compilation of atomic and structured constants. *)
val const_class_of_curr_class : string -> BaristaLibrary.Name.for_class
(** Returns the name of the class holding constants for the module whose
class name is passed. *)
val reset : unit -> unit
(** Resets the sets of atomic and structured constants. *)
val push_int : int64 -> Instrtree.t
(** Return the instructions pushing the passed constant as a boxed value. *)
val push_int32 : int32 -> Instrtree.t
(** Return the instructions pushing the passed constant as a boxed value. *)
val push_int64 : int64 -> Instrtree.t
(** Return the instructions pushing the passed constant as a boxed value. *)
val push_nativeint : nativeint -> Instrtree.t
(** Return the instructions pushing the passed constant as a boxed value. *)
val push_float : float -> Instrtree.t
(** Return the instructions pushing the passed constant as a boxed value. *)
val push_structured_constant : Lambda.structured_constant -> Instrtree.t
(** Return the instructions pushing the passed constant as a boxed value. *)
val get_fields_and_inits : unit -> BaristaLibrary.Field.t list * BaristaLibrary.Instruction.t list
(** Returns the fields used to store boxed constants, and the
instructions initializing these fields. *)
val compile_class : bool -> (string * BaristaLibrary.Bytes.t) list
(** Compiles the class holding the constants for the module, returning a
list of (entry path, entry contents) couples. The parameter indicates
whether marshalled data for constants is needed. *)
val init_class_fields_from_code : unit -> (bool * string * Instrtree.t) list
(** Returns the instructions initializing fields. *)
val init_class_fields_from_load : unit -> (bool * string * Instrtree.t) list
(** Returns the instructions initializing fields from a marshalled
entry. *)
val init_class_fields_from_split_load : unit -> (bool * string * Instrtree.t) list
(** Returns the instructions initializing fields from a marshalled
entry, splitting the code into several methods. *)
| null | https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/compiler/javacomp/bytecodegen_constants.mli | ocaml | * Compilation of atomic and structured constants.
* Returns the name of the class holding constants for the module whose
class name is passed.
* Resets the sets of atomic and structured constants.
* Return the instructions pushing the passed constant as a boxed value.
* Return the instructions pushing the passed constant as a boxed value.
* Return the instructions pushing the passed constant as a boxed value.
* Return the instructions pushing the passed constant as a boxed value.
* Return the instructions pushing the passed constant as a boxed value.
* Return the instructions pushing the passed constant as a boxed value.
* Returns the fields used to store boxed constants, and the
instructions initializing these fields.
* Compiles the class holding the constants for the module, returning a
list of (entry path, entry contents) couples. The parameter indicates
whether marshalled data for constants is needed.
* Returns the instructions initializing fields.
* Returns the instructions initializing fields from a marshalled
entry.
* Returns the instructions initializing fields from a marshalled
entry, splitting the code into several methods. |
* This file is part of compiler .
* Copyright ( C ) 2007 - 2015 .
*
* compiler is free software ; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* ( with a change to choice of law ) .
*
* compiler 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
* Q Public License for more details .
*
* You should have received a copy of the Q Public License
* along with this program . If not , see
* < -1.0 > .
* This file is part of OCaml-Java compiler.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java compiler is free software; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* Trolltech (with a change to choice of law).
*
* OCaml-Java compiler 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
* Q Public License for more details.
*
* You should have received a copy of the Q Public License
* along with this program. If not, see
* <-1.0>.
*)
val const_class_of_curr_class : string -> BaristaLibrary.Name.for_class
val reset : unit -> unit
val push_int : int64 -> Instrtree.t
val push_int32 : int32 -> Instrtree.t
val push_int64 : int64 -> Instrtree.t
val push_nativeint : nativeint -> Instrtree.t
val push_float : float -> Instrtree.t
val push_structured_constant : Lambda.structured_constant -> Instrtree.t
val get_fields_and_inits : unit -> BaristaLibrary.Field.t list * BaristaLibrary.Instruction.t list
val compile_class : bool -> (string * BaristaLibrary.Bytes.t) list
val init_class_fields_from_code : unit -> (bool * string * Instrtree.t) list
val init_class_fields_from_load : unit -> (bool * string * Instrtree.t) list
val init_class_fields_from_split_load : unit -> (bool * string * Instrtree.t) list
|
c2438f93904bae528b137f24c86f7bda00b3329f0f3bbc387e16d38abe3530ae | typelead/intellij-eta | Let00001.hs | module Layout00001 (
everyNth
) where
import Data.Either
import Data.Time.Calendar
everyNth :: Int -> Either WeekDay Int -> Day -> [Day]
everyNth n tp start = case tp of
WeekDay -> start : everyNth tp (addDays n start)
Int -> let (y, m, d) = toGregorian(start) start : everyNth tp ()
| null | https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/test/resources/fixtures/eta/sources/Let00001.hs | haskell | module Layout00001 (
everyNth
) where
import Data.Either
import Data.Time.Calendar
everyNth :: Int -> Either WeekDay Int -> Day -> [Day]
everyNth n tp start = case tp of
WeekDay -> start : everyNth tp (addDays n start)
Int -> let (y, m, d) = toGregorian(start) start : everyNth tp ()
| |
4b4a1acc2a1b830824b831ed94b8d89bbd61eb7ebee05d2b33fcd20ad921d848 | openbadgefactory/salava | rate_it.cljs | (ns salava.core.ui.rate-it
(:require [reagent.core :refer [create-class]]
[salava.core.i18n :refer [t]]))
(defn rate-it-stars [id value read-only]
[:div {:id id
:class "rateit"
:data-rateit-value (when value (/ value 10))
:data-rateit-readonly read-only}])
(defn rate-it
([id value]
(rate-it id value nil))
([id value value-atom]
(create-class {:reagent-render (fn []
(rate-it-stars id value (nil? value-atom)))
:component-did-mount (fn []
(.getScript (js* "$") "/js/rateit/jquery.rateit.min.js")
(when value-atom
(-> (js* "$('#rateit')")
(.bind "rated" (fn [e new-value]
(reset! value-atom (* 10 new-value))))
(.bind "reset" (fn []
(reset! value-atom nil))))))})))
| null | https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/src/cljs/salava/core/ui/rate_it.cljs | clojure | (ns salava.core.ui.rate-it
(:require [reagent.core :refer [create-class]]
[salava.core.i18n :refer [t]]))
(defn rate-it-stars [id value read-only]
[:div {:id id
:class "rateit"
:data-rateit-value (when value (/ value 10))
:data-rateit-readonly read-only}])
(defn rate-it
([id value]
(rate-it id value nil))
([id value value-atom]
(create-class {:reagent-render (fn []
(rate-it-stars id value (nil? value-atom)))
:component-did-mount (fn []
(.getScript (js* "$") "/js/rateit/jquery.rateit.min.js")
(when value-atom
(-> (js* "$('#rateit')")
(.bind "rated" (fn [e new-value]
(reset! value-atom (* 10 new-value))))
(.bind "reset" (fn []
(reset! value-atom nil))))))})))
| |
52f7b590fa216300a2fa8ac72554ce1df0f04d34b30b5b5480d5edf373df5b4a | wireapp/wire-server | Common.hs | # LANGUAGE GeneralizedNewtypeDeriving #
-- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero 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 Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Gundeck.Types.Common where
import Data.Aeson
import Data.Attoparsec.ByteString (takeByteString)
import qualified Data.ByteString.Char8 as Bytes
import Data.ByteString.Conversion
import qualified Data.Text as Text
import Imports
import qualified Network.URI as Net
newtype CannonId = CannonId
{ cannonId :: Text
}
deriving
( Eq,
Ord,
Show,
FromJSON,
ToJSON,
FromByteString,
ToByteString
)
newtype URI = URI
{ fromURI :: Net.URI
}
deriving (Eq, Ord, Show)
instance FromJSON URI where
parseJSON = withText "URI" (parse . Text.unpack)
instance ToJSON URI where
toJSON uri = String $ Text.pack (show (fromURI uri))
instance ToByteString URI where
builder = builder . show . fromURI
instance FromByteString URI where
parser = takeByteString >>= parse . Bytes.unpack
parse :: MonadFail m => String -> m URI
parse = maybe (fail "Invalid URI") (pure . URI) . Net.parseURI
| null | https://raw.githubusercontent.com/wireapp/wire-server/72a03a776d4a8607b0a9c3e622003467be914894/libs/gundeck-types/src/Gundeck/Types/Common.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
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 Affero General Public License for more
details.
with this program. If not, see </>. | # LANGUAGE GeneralizedNewtypeDeriving #
Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Gundeck.Types.Common where
import Data.Aeson
import Data.Attoparsec.ByteString (takeByteString)
import qualified Data.ByteString.Char8 as Bytes
import Data.ByteString.Conversion
import qualified Data.Text as Text
import Imports
import qualified Network.URI as Net
newtype CannonId = CannonId
{ cannonId :: Text
}
deriving
( Eq,
Ord,
Show,
FromJSON,
ToJSON,
FromByteString,
ToByteString
)
newtype URI = URI
{ fromURI :: Net.URI
}
deriving (Eq, Ord, Show)
instance FromJSON URI where
parseJSON = withText "URI" (parse . Text.unpack)
instance ToJSON URI where
toJSON uri = String $ Text.pack (show (fromURI uri))
instance ToByteString URI where
builder = builder . show . fromURI
instance FromByteString URI where
parser = takeByteString >>= parse . Bytes.unpack
parse :: MonadFail m => String -> m URI
parse = maybe (fail "Invalid URI") (pure . URI) . Net.parseURI
|
563d874dcd4759cdfa0dfc164c3b283096682a46d49f25a438534852087b4395 | joearms/elib1 | elib1_new_webkit.erl | Copyright ( c ) 2006 - 2009
See MIT - LICENSE for licensing information .
%% elib1_new_webkit
Time - stamp : < 2009 - 10 - 15 16:43:36 ejoearm >
%%---------------------------------------------------------------------------
Copyright ( c ) 2009 < >
Copyright ( c ) 2009 Whoomph Software AB
%%
%% Permission is hereby granted, free of charge, to any person
%% obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
%% restriction, including without limitation the rights to use, copy,
%% modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software , and to permit persons to whom the Software is
%% furnished to do so, subject to the following conditions:
%%
%% The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
%% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
%% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
%% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
%% ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
%% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
%% SOFTWARE.
%%---------------------------------------------------------------------------
This is an extemely simple , zero configuration webkit .
%% Using the webkit you can easily make a small HTTP server
%% running on localhost that is good enough for
%% backendign simple applications. It is by no means a
%% full-blown HTTP server, so it is not intended as a replacement
for a " proper " HTTP server , but as something that is
%% usful for interfaceing small scale web applicttions to your
%% browser.
%%
%% The webkit acts as a "middle man" and abstracts out details
%% of the real HTTP protocol converting it into a form
that is convenient for an Erlang program .
%%
%% that abstract the protocol in different ways
%% The simplest is
%% Messages from driver
{ Pid , { get , File , } }
{ Pid , { post , File , , Data } }
{ Pid , close }
%% To the client
{ page , FileExtension , DeepList }
%% {error, What}
%% close
-module(elib1_new_webkit).
-import(lists, [map/2, reverse/1, reverse/2]).
-compile(export_all).
-export([start/2,
start_batch_mod_server/1,
start_fold_server/3,
start_mod_server/2,
start_static_server/2,
serve_static_file/1,
serve_static_file_report_error/1,
classify/1,
forever/0,
mod_server/4,
header/1,
mime/1,
pre/1,
get_file/1
]).
start(Port, Fun) ->
{ok, Listen} = gen_tcp:listen(Port,
[binary,
%% {dontroute, true},
{nodelay,true},
{packet, 0},
{reuseaddr, true},
{active, true}]),
io:format("listen port:~p~n",[Port]),
spawn_link(fun() -> par_connect(Listen, Fun) end).
par_connect(Listen, Fun) ->
process_flag(trap_exit, true),
{ok, Socket} = gen_tcp:accept(Listen),
make another one
spawn_link(fun() -> par_connect(Listen, Fun) end),
%% When we get here we're off
process_flag(trap_exit, true),
Where = inet:peername(Socket),
S = self(),
io:format("http driver opened socket:~p~n",[Socket]),
Pid = spawn_link(fun() -> Fun(S, Where) end),
relay(Socket, Pid, {header, []}).
relay(Socket, Server, State) ->
receive
{tcp, Socket, Bin} ->
Data = binary_to_list(Bin),
io : ~s ~ n " , [ Data ] ) ,
parse_request(State, Socket, Server, Data);
{tcp_closed, Socket} ->
io:format("http driver got tcp closed (socket:~p) -"
" so browser closed connection~n",
[Socket]),
Server ! {self(), closed};
{Server, close} ->
io:format("server closed connection~n"),
gen_tcp:close(Socket);
{response, Tag, Data} ->
B1 = list_to_binary(Data),
Len = size(B1),
Mime = mime_type(Tag),
Packet = ["HTTP/1.1 200 Ok\r\n", content_type(Mime),
"Content-Length: ", integer_to_list(Len), "\r\n\r\n",
B1],
%% io:format("Packet=~p~n",[B1]),
gen_tcp:send(Socket, Packet),
relay(Socket, Server, State);
{response1,Code,Headers,Data} ->
Headers1 = [[Key,":",Val,"\r\n"] || {Key, Val} <- Headers],
Bin = list_to_binary(Data),
CL = ["Content-Length:",i2s(size(Bin)),"\r\n\r\n"],
Packet = ["HTTP/1.1", i2s(Code), " Ok\r\n", Headers1, CL, Bin],
gen_tcp:send(Socket, Packet),
relay(Socket, Server, State);
{error, Code} ->
Packet = ["HTTP/1.1 ",i2s(Code),
" Error\r\nContent-Length:0\r\n\r\n"],
%% io:format("Packet=~p~n",[B1]),
gen_tcp:send(Socket, Packet),
relay(Socket, Server, State);
{Server, {Headers, Data}} ->
%% io:format("--> ~p ~p~n", [Headers1, B1]),
gen_tcp:send(Socket, [Headers,Data]),
relay(Socket, Server, State);
{'EXIT', Server, Why} ->
io:format("elib1_new_webkit:relay Server exit reason-~p~n",[Why]),
gen_tcp:close(Socket);
Other ->
io:format("http_driver unexpected message:~p~n",[Other]),
relay(Socket, Server, State)
end.
parse_request({header, Buff}, Socket, Server, Data) ->
case scan_header(Data, Buff) of
{no, Buff1} ->
%% not enought data to parse the header
relay(Socket, Server, {header, Buff1});
{yes, Header, After} ->
%% we've now got enought data to parse the header
got_header(Socket, Server, Header, After)
end;
parse_request({post, Buff, Len, X}, Socket, Server, Data) ->
case collect_chunk(Len, Data, Buff) of
{yes,PostData,After} ->
Args2 = parse_uri_args(PostData),
{Op,Vsn,URI,Args1,Header} = X,
Request = {Op,Vsn,URI,Args1 ++ Args2,Header},
Server ! {self(), Request},
parse_request({header,[]}, Socket, Server, After);
{no,Buff1,Len1} ->
State = {post, Buff1, Len1, X},
relay(Socket, Server, State)
end.
got_header(Socket, Server, Header, After) ->
%% We've got the header - parse it
%% io:format("Header=~p~n",[Header]),
case parse_header(Header) of
{0, Result} ->
%% Send the parsed request to the server
%% io:format("**finally sending:~p~n",[{self(),Result}]),
Server ! {self(), Result},
%% go get the next request
parse_request({header,[]}, Socket, Server, After);
{ContentLen, Result} ->
%% only post commands have extra data
State = {post, [], ContentLen, Result},
parse_request(State, Socket, Server, After)
end.
collect_chunk(0, New, Buf) -> {yes, reverse(Buf), New};
collect_chunk(N, [H|T], Buff) -> collect_chunk(N-1, T, [H|Buff]);
collect_chunk(N, [], Buff) -> {no, Buff, N}.
%% scan_header is a reentrant scanner that collects data up to
%% \r\n\r\n
scan_header([$\n|T], [$\r,$\n,$\r|L]) -> {yes, reverse(L), T};
scan_header([H|T], L) -> scan_header(T, [H|L]);
scan_header([], L) -> {no, L}.
mime_type(gif) -> "image/gif";
mime_type(jpg) -> "image/jpeg";
mime_type(png) -> "image/png";
mime_type(css) -> "text/css";
mime_type(json) -> "application/json";
mime_type(swf) -> "application/x-shockwave-flash";
mime_type(html) -> "text/html";
mime_type(xul) -> "application/vnd.mozilla.xul+xml";
mime_type(js) -> "application/x-javascript";
mime_type(svg) -> "image/svg+xml";
mime_type(X) when is_atom(X) -> mime_type(html);
mime_type(FileName) -> mime_type(classify(FileName)).
mime(Tag) ->
content_type(mime_type(Tag)).
classify(FileName) ->
case string:to_lower(filename:extension(FileName)) of
".gif" -> gif;
".jpg" -> jpg;
".jpeg" -> jpg;
".css" -> css;
".js" -> js;
".svg" -> svg;
".xul" -> xul;
".html" -> html;
".htm" -> html;
_ -> html
end.
header(X) when is_atom(X) ->
["HTTP/1.0 200 Ok\r\n", powered_by(), content_type(mime_type(X))];
header({redirect,To}) ->
["HTTP/1.0 302 Come and get it!\r\n",
powered_by(), "Location: " ++ To ++ "\r\n"].
powered_by() ->
"X-Powered-By: Erlang \r\n".
content_type(X) ->
["Content-Type: ", X, "\r\n"].
parse_header(Str ) - > { ContentLength , { Verb , Vsn , URI , Args , Headers}\\
%% Verb = get | put\\
%% ContentLen = the length of any additional data that has to be
%% fetched
parse_header(Str) ->
{ ok , } = regexp : split(Str , " \r\n " ) ,
Fields = re:split(Str, "\r\n",[{return,list}]),
{Verb, Vsn, Path, Args} = parse_request(hd(Fields)),
Args = " KeyWord : Str " ..
Headers = map(fun isolate_arg/1, tl(Fields)),
Len = content_length(Headers),
{Len, {Verb, Vsn, Path, Args, Headers}}.
%% I've lower cased to header keys
%% so Content-Length is lower cased here
content_length([{"content-length",Str}|_]) -> list_to_integer(Str);
content_length([_|T]) -> content_length(T);
content_length([]) -> 0.
urlencoded2str([$%,Hi,Lo|T]) -> [decode_hex(Hi, Lo)|urlencoded2str(T)];
urlencoded2str([$+|T]) -> [$ |urlencoded2str(T)];
urlencoded2str([H|T]) -> [H|urlencoded2str(T)];
urlencoded2str([]) -> [].
isolate_arg(Str) -> isolate_arg(Str, []).
isolate_arg([$:,$ |T], L) -> {string:to_lower(reverse(L)), T};
isolate_arg([H|T], L) -> isolate_arg(T, [H|L]).
%% decode_hex ...
decode_hex(Hex1, Hex2) ->
hex2dec(Hex1)*16 + hex2dec(Hex2).
hex2dec(X) when X >=$0, X =<$9 -> X-$0;
hex2dec($A) -> 10;
hex2dec($B) -> 11;
hex2dec($C) -> 12;
hex2dec($D) -> 13;
hex2dec($E) -> 14;
hex2dec($F) -> 15;
hex2dec($a) -> 10;
hex2dec($b) -> 11;
hex2dec($c) -> 12;
hex2dec($d) -> 13;
hex2dec($e) -> 14;
hex2dec($f) -> 15.
%% parse_request(Str) -> {Verb,Vsn,Path,Args}
parse first line of an HTTP response
parse_request(Str) ->
{ ok , } = regexp : split(Str , " " ) ,
Fields = re:split(Str, " ",[{return,list}]),
case Fields of
["POST", URI, Vsn] ->
{Path, Args} = parse_uri(URI),
{post, parse_vsn(Vsn) , Path, Args};
["GET", URI, Vsn] ->
{Path, Args} = parse_uri(URI),
{get, parse_vsn(Vsn), Path, Args};
_ ->
exit({badRequest,Str})
end.
parse_vsn("HTTP/1.0") -> {1,0};
parse_vsn(X) -> X.
A typical URI looks
%% like
URI = " /a / b / c?password = aaa&invisible = Ahidden+value"+
parse_uri(URI) ->
case string:tokens(URI, "?") of
[Root] ->
{Root, []};
[Root, Args] ->
{Root, parse_uri_args(Args)}
end.
parse_uri_args(Args) ->
Args1 = string:tokens(Args, "&;"),
map(fun(KeyVal) ->
case string:tokens(KeyVal, "=") of
[Key, Val] ->
{urlencoded2str(Key), urlencoded2str(Val)};
[Key] ->
{urlencoded2str(Key), ""};
_ ->
io:format("Invalid str:~p~n",[KeyVal]),
{"error", "error"}
end
end, Args1).
i2s(I) ->
integer_to_list(I).
get_file(File) ->
case file:read_file("." ++ File) of
{ok, Bin} ->
Type = classify(File),
{ok, Type, Bin};
Error ->
Error
end.
pre(X) ->
["<pre>\n",quote(lists:flatten(io_lib:format("~p",[X]))), "</pre>"].
quote("<" ++ T) -> "<" ++ quote(T);
quote("&" ++ T) -> "&" ++ quote(T);
quote([H|T]) -> [H|quote(T)];
quote([]) -> [].
forever() ->
receive
after infinity ->
true
end.
%% Now for some specialised servers
Fun4(get|put , , , State ) - >
{ response , Type , Data , State ' }
{ resoponseH , Type , Data , State ' }
, Code , State ' }
start_fold_server(Port, Fun4, State) ->
%% From should be local host ... but I don't check
start(Port, fun(MM, _From) -> loop4(MM, Fun4, State) end).
loop4(MM, Fun4, State) ->
receive
{MM, {Tag, _Vsn, Uri, Args, _Headers}} ->
io : format("MM:~p ~p ~p ~ n",[Tag , , ] ) ,
case Fun4(Tag, Uri, Args, State) of
{response, Type, Data, State1} ->
MM ! {response, Type, Data},
loop4(MM, Fun4, State1);
{responseH, Type, Headers, Data, State1} ->
MM ! {response1, Type, Headers, Data},
loop4(MM, Fun4, State1);
{error, Code, State1} ->
MM ! {error, Code},
loop4(MM, Fun4, State1);
_ ->
io:format("elib1_webkit:Bad Fun=~p ~p~n",[Uri,Args]),
loop4(MM, Fun4, State)
end;
Other ->
io:format("Message dropped:~p~n",[Other]),
loop4(MM, Fun4, State)
end.
%%----------------------------------------------------------------------
start_static_server(Port , Fun3 ) a static server .
%% By static is meant a server that is stateless. Each time a request comes
Fun3(Tag , , ) is evaluated . This must return :
%% {response, Type, Data} Type = html,js,gif, ...
{ error , Code } Code = 400 , ...
%% {response1, Type, Headers, Data}
start_static_server(Port, Fun3) ->
%% From should be local host ... but I don't check
start(Port, fun(MM, _From) -> loop2(MM, Fun3) end).
loop2(MM, Fun) ->
receive
{MM, {Tag, _Vsn, Uri, Args, _Headers}} ->
io : format("MM:~p ~p ~p ~ n",[Tag , , ] ) ,
MM ! Fun(Tag, Uri, Args),
loop2(MM, Fun);
Other ->
io:format("Message dropped:~p~n",[Other]),
loop2(MM, Fun)
end.
serve_static_file(File) ->
case file:read_file(File) of
{ok, Bin} -> {response, classify(File), [Bin]};
{error, _} -> {error, 400}
end.
serve_static_file_report_error_as_html(File) ->
case file:read_file(File) of
{ok, Bin} -> {response, classify(File), [Bin]};
{error, _} -> {response, html,
["<h2>Missing file</h2>",
pre(File)]}
end.
serve_static_file_report_error(File) ->
case file:read_file(File) of
{ok, Bin} -> {response, classify(File), [Bin]};
{error, _} -> io:format("** missing file:~p~n",[File]),
{error, 400}
end.
%% start_mod_server(Port, RootDir)
%% example:
start_mod_server(2009 , " /home / / here / we / are " ) .
This starts a server on Port
With root directory RoorDir
%% GET requests to files are assumed to be relative to RootDir
%% If the path is the form /mod/Mod/Func?Args
%% Then Mod:Func(Args) will be called
%% Mod must be located in RootDir and will be recompiled if necessary
start_batch_mod_server([P,D]) ->
Port = list_to_integer(atom_to_list(P)),
Dir = atom_to_list(D),
start_mod_server(Port, Dir),
forever().
start_mod_server(Port, RootDir) ->
start_static_server(Port, fun(Tag, Uri, Args) ->
mod_server(Tag, Uri, Args,
filename:split(RootDir))
end).
mod_server(Tag, Uri, Args, Root) ->
io:format("Starting server Tag=~p Uri=~p Args=~p Root=~p~n",
[Tag, Uri, Args, Root]),
%% io:format("elib1_new_webkit mod_server URI=~p~n",[Uri]),
Parts = filename:split(Uri),
%% io:format("elib1_new_webkit parts=~p~n",[Parts]),
case Parts of
["/","mod"] ->
%% io:format("elib1_webkit: exec_mod Args=~p Rooot=~p~n",
%% [Args,Root]),
exec_mod(Args,Root);
["/"|F] ->
%% io:format("elib1_webkit mod_server F=~p~n",[F]),
Full = filename:join(Root ++ F),
io:format("Serve file:~p~n",[Full]),
serve_static_file_report_error_as_html(Full);
_Other ->
{response, html, [pre({mod_server,Parts,Tag,Uri,Args,Root})]}
end.
%% Rules:
exec_mod([{"mod", Str1},{"func", Str2}|Args], Root) ->
Mod = list_to_atom(Str1),
Func = list_to_atom(Str2),
Dir = filename:join(Root),
case (catch Mod:Func(Args, Dir)) of
{'EXIT', Why} ->
{response, html,
pre({evalError,Mod,Func,Args,Dir,Why})};
Other ->
Other
end.
error(X) ->
{response, html, [pre({error, X})]}.
%% ensure that
ensure_loaded("/home / joe / foo / bar " )
1 ) check /home / joe / foo / bar.erl exists
2 ) check is /home / joe / foo / bar.beam exists and is up - to - date
%% 3) if not uptodate recompiles and loads
%% 4) once loaded
%% ensure_loaded(PathToMod) -> {ok, Mod} | {error, Why}
ensure_loaded(PathToMod) ->
Erl = PathToMod ++ ".erl",
Beam = PathToMod ++ ".beam",
Mod = list_to_atom(filename:basename(Erl)),
case filelib:is_file(Erl) of
true ->
case elib1_misc:out_of_date(Erl, Beam) of
true ->
recompile_src_and_load(PathToMod);
false ->
%% Src and beam are OK -- but what happns if the
%% code is already loaded in some different place
case code:is_loaded(Mod) of
{file, Beam} ->
{ok, Mod};
_ ->
recompile_src_and_load(PathToMod)
end
end;
false ->
{error, {ebadMod,Mod}}
end.
recompile_src_and_load(PathToMod) ->
io:format("** recompiling:~p.erl~n",[pathToMod]),
OutDir = filename:dirname(PathToMod),
case compile:file(PathToMod ++ ".erl",
[report,{outdir,OutDir}]) of
{ok, Mod} ->
code:purge(Mod),
C = code:load_abs(PathToMod),
io:format("load_abs=~p ~p~n",[PathToMod,C]),
io:format("code:is_loaded=~p~n",[code:is_loaded(Mod)]),
{ok, Mod};
Error ->
{error, Error}
end.
| null | https://raw.githubusercontent.com/joearms/elib1/d617d0ec70a058ef102749eadf51c024444c28d9/src/elib1_new_webkit.erl | erlang | elib1_new_webkit
---------------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---------------------------------------------------------------------------
Using the webkit you can easily make a small HTTP server
running on localhost that is good enough for
backendign simple applications. It is by no means a
full-blown HTTP server, so it is not intended as a replacement
usful for interfaceing small scale web applicttions to your
browser.
The webkit acts as a "middle man" and abstracts out details
of the real HTTP protocol converting it into a form
that abstract the protocol in different ways
The simplest is
Messages from driver
To the client
{error, What}
close
{dontroute, true},
When we get here we're off
io:format("Packet=~p~n",[B1]),
io:format("Packet=~p~n",[B1]),
io:format("--> ~p ~p~n", [Headers1, B1]),
not enought data to parse the header
we've now got enought data to parse the header
We've got the header - parse it
io:format("Header=~p~n",[Header]),
Send the parsed request to the server
io:format("**finally sending:~p~n",[{self(),Result}]),
go get the next request
only post commands have extra data
scan_header is a reentrant scanner that collects data up to
\r\n\r\n
Verb = get | put\\
ContentLen = the length of any additional data that has to be
fetched
I've lower cased to header keys
so Content-Length is lower cased here
,Hi,Lo|T]) -> [decode_hex(Hi, Lo)|urlencoded2str(T)];
decode_hex ...
parse_request(Str) -> {Verb,Vsn,Path,Args}
like
Now for some specialised servers
From should be local host ... but I don't check
----------------------------------------------------------------------
By static is meant a server that is stateless. Each time a request comes
{response, Type, Data} Type = html,js,gif, ...
{response1, Type, Headers, Data}
From should be local host ... but I don't check
start_mod_server(Port, RootDir)
example:
GET requests to files are assumed to be relative to RootDir
If the path is the form /mod/Mod/Func?Args
Then Mod:Func(Args) will be called
Mod must be located in RootDir and will be recompiled if necessary
io:format("elib1_new_webkit mod_server URI=~p~n",[Uri]),
io:format("elib1_new_webkit parts=~p~n",[Parts]),
io:format("elib1_webkit: exec_mod Args=~p Rooot=~p~n",
[Args,Root]),
io:format("elib1_webkit mod_server F=~p~n",[F]),
Rules:
ensure that
3) if not uptodate recompiles and loads
4) once loaded
ensure_loaded(PathToMod) -> {ok, Mod} | {error, Why}
Src and beam are OK -- but what happns if the
code is already loaded in some different place | Copyright ( c ) 2006 - 2009
See MIT - LICENSE for licensing information .
Time - stamp : < 2009 - 10 - 15 16:43:36 ejoearm >
Copyright ( c ) 2009 < >
Copyright ( c ) 2009 Whoomph Software AB
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
This is an extemely simple , zero configuration webkit .
for a " proper " HTTP server , but as something that is
that is convenient for an Erlang program .
{ Pid , { get , File , } }
{ Pid , { post , File , , Data } }
{ Pid , close }
{ page , FileExtension , DeepList }
-module(elib1_new_webkit).
-import(lists, [map/2, reverse/1, reverse/2]).
-compile(export_all).
-export([start/2,
start_batch_mod_server/1,
start_fold_server/3,
start_mod_server/2,
start_static_server/2,
serve_static_file/1,
serve_static_file_report_error/1,
classify/1,
forever/0,
mod_server/4,
header/1,
mime/1,
pre/1,
get_file/1
]).
start(Port, Fun) ->
{ok, Listen} = gen_tcp:listen(Port,
[binary,
{nodelay,true},
{packet, 0},
{reuseaddr, true},
{active, true}]),
io:format("listen port:~p~n",[Port]),
spawn_link(fun() -> par_connect(Listen, Fun) end).
par_connect(Listen, Fun) ->
process_flag(trap_exit, true),
{ok, Socket} = gen_tcp:accept(Listen),
make another one
spawn_link(fun() -> par_connect(Listen, Fun) end),
process_flag(trap_exit, true),
Where = inet:peername(Socket),
S = self(),
io:format("http driver opened socket:~p~n",[Socket]),
Pid = spawn_link(fun() -> Fun(S, Where) end),
relay(Socket, Pid, {header, []}).
relay(Socket, Server, State) ->
receive
{tcp, Socket, Bin} ->
Data = binary_to_list(Bin),
io : ~s ~ n " , [ Data ] ) ,
parse_request(State, Socket, Server, Data);
{tcp_closed, Socket} ->
io:format("http driver got tcp closed (socket:~p) -"
" so browser closed connection~n",
[Socket]),
Server ! {self(), closed};
{Server, close} ->
io:format("server closed connection~n"),
gen_tcp:close(Socket);
{response, Tag, Data} ->
B1 = list_to_binary(Data),
Len = size(B1),
Mime = mime_type(Tag),
Packet = ["HTTP/1.1 200 Ok\r\n", content_type(Mime),
"Content-Length: ", integer_to_list(Len), "\r\n\r\n",
B1],
gen_tcp:send(Socket, Packet),
relay(Socket, Server, State);
{response1,Code,Headers,Data} ->
Headers1 = [[Key,":",Val,"\r\n"] || {Key, Val} <- Headers],
Bin = list_to_binary(Data),
CL = ["Content-Length:",i2s(size(Bin)),"\r\n\r\n"],
Packet = ["HTTP/1.1", i2s(Code), " Ok\r\n", Headers1, CL, Bin],
gen_tcp:send(Socket, Packet),
relay(Socket, Server, State);
{error, Code} ->
Packet = ["HTTP/1.1 ",i2s(Code),
" Error\r\nContent-Length:0\r\n\r\n"],
gen_tcp:send(Socket, Packet),
relay(Socket, Server, State);
{Server, {Headers, Data}} ->
gen_tcp:send(Socket, [Headers,Data]),
relay(Socket, Server, State);
{'EXIT', Server, Why} ->
io:format("elib1_new_webkit:relay Server exit reason-~p~n",[Why]),
gen_tcp:close(Socket);
Other ->
io:format("http_driver unexpected message:~p~n",[Other]),
relay(Socket, Server, State)
end.
parse_request({header, Buff}, Socket, Server, Data) ->
case scan_header(Data, Buff) of
{no, Buff1} ->
relay(Socket, Server, {header, Buff1});
{yes, Header, After} ->
got_header(Socket, Server, Header, After)
end;
parse_request({post, Buff, Len, X}, Socket, Server, Data) ->
case collect_chunk(Len, Data, Buff) of
{yes,PostData,After} ->
Args2 = parse_uri_args(PostData),
{Op,Vsn,URI,Args1,Header} = X,
Request = {Op,Vsn,URI,Args1 ++ Args2,Header},
Server ! {self(), Request},
parse_request({header,[]}, Socket, Server, After);
{no,Buff1,Len1} ->
State = {post, Buff1, Len1, X},
relay(Socket, Server, State)
end.
got_header(Socket, Server, Header, After) ->
case parse_header(Header) of
{0, Result} ->
Server ! {self(), Result},
parse_request({header,[]}, Socket, Server, After);
{ContentLen, Result} ->
State = {post, [], ContentLen, Result},
parse_request(State, Socket, Server, After)
end.
collect_chunk(0, New, Buf) -> {yes, reverse(Buf), New};
collect_chunk(N, [H|T], Buff) -> collect_chunk(N-1, T, [H|Buff]);
collect_chunk(N, [], Buff) -> {no, Buff, N}.
scan_header([$\n|T], [$\r,$\n,$\r|L]) -> {yes, reverse(L), T};
scan_header([H|T], L) -> scan_header(T, [H|L]);
scan_header([], L) -> {no, L}.
mime_type(gif) -> "image/gif";
mime_type(jpg) -> "image/jpeg";
mime_type(png) -> "image/png";
mime_type(css) -> "text/css";
mime_type(json) -> "application/json";
mime_type(swf) -> "application/x-shockwave-flash";
mime_type(html) -> "text/html";
mime_type(xul) -> "application/vnd.mozilla.xul+xml";
mime_type(js) -> "application/x-javascript";
mime_type(svg) -> "image/svg+xml";
mime_type(X) when is_atom(X) -> mime_type(html);
mime_type(FileName) -> mime_type(classify(FileName)).
mime(Tag) ->
content_type(mime_type(Tag)).
classify(FileName) ->
case string:to_lower(filename:extension(FileName)) of
".gif" -> gif;
".jpg" -> jpg;
".jpeg" -> jpg;
".css" -> css;
".js" -> js;
".svg" -> svg;
".xul" -> xul;
".html" -> html;
".htm" -> html;
_ -> html
end.
header(X) when is_atom(X) ->
["HTTP/1.0 200 Ok\r\n", powered_by(), content_type(mime_type(X))];
header({redirect,To}) ->
["HTTP/1.0 302 Come and get it!\r\n",
powered_by(), "Location: " ++ To ++ "\r\n"].
powered_by() ->
"X-Powered-By: Erlang \r\n".
content_type(X) ->
["Content-Type: ", X, "\r\n"].
parse_header(Str ) - > { ContentLength , { Verb , Vsn , URI , Args , Headers}\\
parse_header(Str) ->
{ ok , } = regexp : split(Str , " \r\n " ) ,
Fields = re:split(Str, "\r\n",[{return,list}]),
{Verb, Vsn, Path, Args} = parse_request(hd(Fields)),
Args = " KeyWord : Str " ..
Headers = map(fun isolate_arg/1, tl(Fields)),
Len = content_length(Headers),
{Len, {Verb, Vsn, Path, Args, Headers}}.
content_length([{"content-length",Str}|_]) -> list_to_integer(Str);
content_length([_|T]) -> content_length(T);
content_length([]) -> 0.
urlencoded2str([$+|T]) -> [$ |urlencoded2str(T)];
urlencoded2str([H|T]) -> [H|urlencoded2str(T)];
urlencoded2str([]) -> [].
isolate_arg(Str) -> isolate_arg(Str, []).
isolate_arg([$:,$ |T], L) -> {string:to_lower(reverse(L)), T};
isolate_arg([H|T], L) -> isolate_arg(T, [H|L]).
decode_hex(Hex1, Hex2) ->
hex2dec(Hex1)*16 + hex2dec(Hex2).
hex2dec(X) when X >=$0, X =<$9 -> X-$0;
hex2dec($A) -> 10;
hex2dec($B) -> 11;
hex2dec($C) -> 12;
hex2dec($D) -> 13;
hex2dec($E) -> 14;
hex2dec($F) -> 15;
hex2dec($a) -> 10;
hex2dec($b) -> 11;
hex2dec($c) -> 12;
hex2dec($d) -> 13;
hex2dec($e) -> 14;
hex2dec($f) -> 15.
parse first line of an HTTP response
parse_request(Str) ->
{ ok , } = regexp : split(Str , " " ) ,
Fields = re:split(Str, " ",[{return,list}]),
case Fields of
["POST", URI, Vsn] ->
{Path, Args} = parse_uri(URI),
{post, parse_vsn(Vsn) , Path, Args};
["GET", URI, Vsn] ->
{Path, Args} = parse_uri(URI),
{get, parse_vsn(Vsn), Path, Args};
_ ->
exit({badRequest,Str})
end.
parse_vsn("HTTP/1.0") -> {1,0};
parse_vsn(X) -> X.
A typical URI looks
URI = " /a / b / c?password = aaa&invisible = Ahidden+value"+
parse_uri(URI) ->
case string:tokens(URI, "?") of
[Root] ->
{Root, []};
[Root, Args] ->
{Root, parse_uri_args(Args)}
end.
parse_uri_args(Args) ->
Args1 = string:tokens(Args, "&;"),
map(fun(KeyVal) ->
case string:tokens(KeyVal, "=") of
[Key, Val] ->
{urlencoded2str(Key), urlencoded2str(Val)};
[Key] ->
{urlencoded2str(Key), ""};
_ ->
io:format("Invalid str:~p~n",[KeyVal]),
{"error", "error"}
end
end, Args1).
i2s(I) ->
integer_to_list(I).
get_file(File) ->
case file:read_file("." ++ File) of
{ok, Bin} ->
Type = classify(File),
{ok, Type, Bin};
Error ->
Error
end.
pre(X) ->
["<pre>\n",quote(lists:flatten(io_lib:format("~p",[X]))), "</pre>"].
quote("<" ++ T) -> "<" ++ quote(T);
quote("&" ++ T) -> "&" ++ quote(T);
quote([H|T]) -> [H|quote(T)];
quote([]) -> [].
forever() ->
receive
after infinity ->
true
end.
Fun4(get|put , , , State ) - >
{ response , Type , Data , State ' }
{ resoponseH , Type , Data , State ' }
, Code , State ' }
start_fold_server(Port, Fun4, State) ->
start(Port, fun(MM, _From) -> loop4(MM, Fun4, State) end).
loop4(MM, Fun4, State) ->
receive
{MM, {Tag, _Vsn, Uri, Args, _Headers}} ->
io : format("MM:~p ~p ~p ~ n",[Tag , , ] ) ,
case Fun4(Tag, Uri, Args, State) of
{response, Type, Data, State1} ->
MM ! {response, Type, Data},
loop4(MM, Fun4, State1);
{responseH, Type, Headers, Data, State1} ->
MM ! {response1, Type, Headers, Data},
loop4(MM, Fun4, State1);
{error, Code, State1} ->
MM ! {error, Code},
loop4(MM, Fun4, State1);
_ ->
io:format("elib1_webkit:Bad Fun=~p ~p~n",[Uri,Args]),
loop4(MM, Fun4, State)
end;
Other ->
io:format("Message dropped:~p~n",[Other]),
loop4(MM, Fun4, State)
end.
start_static_server(Port , Fun3 ) a static server .
Fun3(Tag , , ) is evaluated . This must return :
{ error , Code } Code = 400 , ...
start_static_server(Port, Fun3) ->
start(Port, fun(MM, _From) -> loop2(MM, Fun3) end).
loop2(MM, Fun) ->
receive
{MM, {Tag, _Vsn, Uri, Args, _Headers}} ->
io : format("MM:~p ~p ~p ~ n",[Tag , , ] ) ,
MM ! Fun(Tag, Uri, Args),
loop2(MM, Fun);
Other ->
io:format("Message dropped:~p~n",[Other]),
loop2(MM, Fun)
end.
serve_static_file(File) ->
case file:read_file(File) of
{ok, Bin} -> {response, classify(File), [Bin]};
{error, _} -> {error, 400}
end.
serve_static_file_report_error_as_html(File) ->
case file:read_file(File) of
{ok, Bin} -> {response, classify(File), [Bin]};
{error, _} -> {response, html,
["<h2>Missing file</h2>",
pre(File)]}
end.
serve_static_file_report_error(File) ->
case file:read_file(File) of
{ok, Bin} -> {response, classify(File), [Bin]};
{error, _} -> io:format("** missing file:~p~n",[File]),
{error, 400}
end.
start_mod_server(2009 , " /home / / here / we / are " ) .
This starts a server on Port
With root directory RoorDir
start_batch_mod_server([P,D]) ->
Port = list_to_integer(atom_to_list(P)),
Dir = atom_to_list(D),
start_mod_server(Port, Dir),
forever().
start_mod_server(Port, RootDir) ->
start_static_server(Port, fun(Tag, Uri, Args) ->
mod_server(Tag, Uri, Args,
filename:split(RootDir))
end).
mod_server(Tag, Uri, Args, Root) ->
io:format("Starting server Tag=~p Uri=~p Args=~p Root=~p~n",
[Tag, Uri, Args, Root]),
Parts = filename:split(Uri),
case Parts of
["/","mod"] ->
exec_mod(Args,Root);
["/"|F] ->
Full = filename:join(Root ++ F),
io:format("Serve file:~p~n",[Full]),
serve_static_file_report_error_as_html(Full);
_Other ->
{response, html, [pre({mod_server,Parts,Tag,Uri,Args,Root})]}
end.
exec_mod([{"mod", Str1},{"func", Str2}|Args], Root) ->
Mod = list_to_atom(Str1),
Func = list_to_atom(Str2),
Dir = filename:join(Root),
case (catch Mod:Func(Args, Dir)) of
{'EXIT', Why} ->
{response, html,
pre({evalError,Mod,Func,Args,Dir,Why})};
Other ->
Other
end.
error(X) ->
{response, html, [pre({error, X})]}.
ensure_loaded("/home / joe / foo / bar " )
1 ) check /home / joe / foo / bar.erl exists
2 ) check is /home / joe / foo / bar.beam exists and is up - to - date
ensure_loaded(PathToMod) ->
Erl = PathToMod ++ ".erl",
Beam = PathToMod ++ ".beam",
Mod = list_to_atom(filename:basename(Erl)),
case filelib:is_file(Erl) of
true ->
case elib1_misc:out_of_date(Erl, Beam) of
true ->
recompile_src_and_load(PathToMod);
false ->
case code:is_loaded(Mod) of
{file, Beam} ->
{ok, Mod};
_ ->
recompile_src_and_load(PathToMod)
end
end;
false ->
{error, {ebadMod,Mod}}
end.
recompile_src_and_load(PathToMod) ->
io:format("** recompiling:~p.erl~n",[pathToMod]),
OutDir = filename:dirname(PathToMod),
case compile:file(PathToMod ++ ".erl",
[report,{outdir,OutDir}]) of
{ok, Mod} ->
code:purge(Mod),
C = code:load_abs(PathToMod),
io:format("load_abs=~p ~p~n",[PathToMod,C]),
io:format("code:is_loaded=~p~n",[code:is_loaded(Mod)]),
{ok, Mod};
Error ->
{error, Error}
end.
|
716682b28eafa7c3784a7cc8b0b4cc0bfb50a39b1dcfb022f4afb97b9aa7bf47 | gowthamk/ocaml-irmin | monkey.ml | open Printf
(* Utility functions *)
U is a module with two functions
module U = struct
let string_of_list f l = "[ " ^ List.fold_left (fun a b -> a ^ (f b) ^ "; ") "" l ^ "]"
let print_header h =
begin
Printf.printf "%s\n" h;
flush_all();
end
let (>>=) = Lwt.Infix.(>>=)
let rec loop_until_y (msg:string) : unit Lwt.t =
Lwt_io.printf "%s" msg >>= fun _ ->
Lwt_io.read_line Lwt_io.stdin >>= fun str ->
if str="y" then Lwt.return ()
else loop_until_y msg
let fold f n b =
let rec fold_aux f i b =
if i >= n then b
else fold_aux f (i+1) @@ f i b in
fold_aux f 0 b
end
Canvas
let _ =
U.print_header "Heap"
module MkConfig (Vars: sig val root: string end) : Iheap_leftlist.Config = struct
let root = Vars.root
let shared = "/tmp/repos/shared.git"
let init () =
let _ = Sys.command (Printf.sprintf "rm -rf %s" root) in
let _ = Sys.command (Printf.sprintf "mkdir -p %s" root) in
()
end
module Atom = struct
type t = int64
let t = Irmin.Type.int64
let compare x y = Int64.to_int @@ Int64.sub x y
let to_string = Int64.to_string
let of_string = Int64.of_string
end
module CInit = MkConfig(struct let root = "/tmp/repos/heap_leftlist.git" end)
module MInit = Iheap_leftlist.MakeVersioned(CInit)(Atom)
module H = Heap_leftlist.Make(Atom)
module Vpst = MInit.Vpst
let heap_size = 512
let (>>=) = Vpst.bind
let loop_until_y msg = Vpst.liftLwt @@ U.loop_until_y msg
(* select a random number and insert it in the tree t *)
let do_an_insert t =
H.insert (Random.int64 9000000L) t
it uses delete_min which removes the minimum element from t
let do_a_remove t =
if H.is_empty t then t
else H.delete_min t
do_an_oper performs the operation either insert or remove
: if input choosen is random number 0 or 1 then it performs insert else it performs remove
: if input choosen is random number 0 or 1 then it performs insert else it performs remove *)
let do_an_oper t =
match Random.int 10 with
| 0 -> do_a_remove t
| _ -> do_an_insert t
(* comp_time is initialized as 0 which is mutable *)
let comp_time = ref 0.0
(* sync_time is initialized as 0 which is mutable *)
let sync_time = ref 0.0
no of operations per round is initialized to 30 which means we are doing 30 operations per round
let _n_ops_per_round = ref 30
no of rounds is initialized to 10 which means 10 rounds experiment is run
let _n_rounds = ref 10
let loop_iter i (pre: H.t Vpst.t) : H.t Vpst.t =
pre >>= fun t ->
(* Before time *)
let t1 = Sys.time() in
c ' is performing the operation represented by , n number of rounds on the data t
let c' = U.fold (fun _ c -> do_an_oper c) !_n_ops_per_round (t) in
(* After time *)
let t2 = Sys.time () in
(* Then we synchronize using sync operation between diff threads *)
Vpst.sync_next_version ~v:c' >>= fun v ->
(* After synchronization time *)
let t3 = Sys.time () in
let _ = flush_all() in
begin
(* comp_time represents the computation time (computation time for the operations) which is t2 - t1 *)
comp_time := !comp_time +. (t2 -. t1);
(* sync_time represents the syncing time which is t3 - t2 *)
sync_time := !sync_time +. (t3 -. t2);
printf "Round %d\n" i;
flush_all();
Vpst.return v
end
let n_done = ref 0
let work_loop () : H.t Vpst.t =
U.fold loop_iter !_n_rounds (Vpst.get_latest_version ()) >>= fun v ->
n_done := !n_done + 1;
Vpst.return v
(* resets all the time computed before *)
let reset () =
begin
comp_time := 0.0;
MInit.merge_time := 0.0;
MInit.merge_count := 0;
H.merge_time :=0.0;
end
let rec wait_till_done () : unit Vpst.t =
if !n_done = 3 then Vpst.return ()
else begin
Vpst.liftLwt @@ Lwt_unix.sleep 1.0 >>= fun _ ->
wait_till_done ()
end
let experiment_f (fp: out_channel) : unit =
begin
CInit.init ();
Vpst.with_init_version_do H.empty
begin
Vpst.fork_version (work_loop ()) >>= fun br1 ->
Vpst.fork_version ~parent:br1 (work_loop ()) >>= fun br2 ->
Vpst.set_parent br2 >>= fun () ->
(work_loop ()) >>= fun _ ->
wait_till_done ()
end;
let mtime = !MInit.merge_time in
let ctime = !comp_time in
let stime = !sync_time in
let mcount = !MInit.merge_count in
let real_mtime = !MInit.OM.merge_time in
let total_rounds = 3 * !_n_rounds in
let ctime_per_round = ctime/.(float total_rounds) in
let mdivisor1 = if mcount > total_rounds then mcount
else total_rounds in
let mdivisor2 = max mcount 1 in
let avg_mtime1 = real_mtime/.(float mdivisor1) in
let avg_mtime2 = real_mtime/.(float mdivisor2) in
fprintf fp "%d,%d,%fs,%fs,%fs,%d,%fs,%fs,%fs,%fs\n"
!_n_rounds !_n_ops_per_round
mtime ctime stime mcount real_mtime
ctime_per_round avg_mtime1 avg_mtime2;
reset ()
end
let main () =
begin
Logs.set_reporter @@ Logs.format_reporter ();
Logs.set_level @@ Some Logs.Error;
_n_rounds := int_of_string @@ Sys.argv.(1);
_n_ops_per_round := int_of_string @@ Sys.argv.(2);
if Array.length Sys.argv > 3 then
Random.init @@ int_of_string @@ Sys.argv.(3)
else Random.self_init ();
let fp = open_out_gen [Open_creat; Open_append] 0o777 "results.csv" in
experiment_f fp
end;;
main ();;
| null | https://raw.githubusercontent.com/gowthamk/ocaml-irmin/54775f6c3012e87d2d0308f37a2ec7b27477e887/heap_leftist/mem/monkey.ml | ocaml | Utility functions
select a random number and insert it in the tree t
comp_time is initialized as 0 which is mutable
sync_time is initialized as 0 which is mutable
Before time
After time
Then we synchronize using sync operation between diff threads
After synchronization time
comp_time represents the computation time (computation time for the operations) which is t2 - t1
sync_time represents the syncing time which is t3 - t2
resets all the time computed before | open Printf
U is a module with two functions
module U = struct
let string_of_list f l = "[ " ^ List.fold_left (fun a b -> a ^ (f b) ^ "; ") "" l ^ "]"
let print_header h =
begin
Printf.printf "%s\n" h;
flush_all();
end
let (>>=) = Lwt.Infix.(>>=)
let rec loop_until_y (msg:string) : unit Lwt.t =
Lwt_io.printf "%s" msg >>= fun _ ->
Lwt_io.read_line Lwt_io.stdin >>= fun str ->
if str="y" then Lwt.return ()
else loop_until_y msg
let fold f n b =
let rec fold_aux f i b =
if i >= n then b
else fold_aux f (i+1) @@ f i b in
fold_aux f 0 b
end
Canvas
let _ =
U.print_header "Heap"
module MkConfig (Vars: sig val root: string end) : Iheap_leftlist.Config = struct
let root = Vars.root
let shared = "/tmp/repos/shared.git"
let init () =
let _ = Sys.command (Printf.sprintf "rm -rf %s" root) in
let _ = Sys.command (Printf.sprintf "mkdir -p %s" root) in
()
end
module Atom = struct
type t = int64
let t = Irmin.Type.int64
let compare x y = Int64.to_int @@ Int64.sub x y
let to_string = Int64.to_string
let of_string = Int64.of_string
end
module CInit = MkConfig(struct let root = "/tmp/repos/heap_leftlist.git" end)
module MInit = Iheap_leftlist.MakeVersioned(CInit)(Atom)
module H = Heap_leftlist.Make(Atom)
module Vpst = MInit.Vpst
let heap_size = 512
let (>>=) = Vpst.bind
let loop_until_y msg = Vpst.liftLwt @@ U.loop_until_y msg
let do_an_insert t =
H.insert (Random.int64 9000000L) t
it uses delete_min which removes the minimum element from t
let do_a_remove t =
if H.is_empty t then t
else H.delete_min t
do_an_oper performs the operation either insert or remove
: if input choosen is random number 0 or 1 then it performs insert else it performs remove
: if input choosen is random number 0 or 1 then it performs insert else it performs remove *)
let do_an_oper t =
match Random.int 10 with
| 0 -> do_a_remove t
| _ -> do_an_insert t
let comp_time = ref 0.0
let sync_time = ref 0.0
no of operations per round is initialized to 30 which means we are doing 30 operations per round
let _n_ops_per_round = ref 30
no of rounds is initialized to 10 which means 10 rounds experiment is run
let _n_rounds = ref 10
let loop_iter i (pre: H.t Vpst.t) : H.t Vpst.t =
pre >>= fun t ->
let t1 = Sys.time() in
c ' is performing the operation represented by , n number of rounds on the data t
let c' = U.fold (fun _ c -> do_an_oper c) !_n_ops_per_round (t) in
let t2 = Sys.time () in
Vpst.sync_next_version ~v:c' >>= fun v ->
let t3 = Sys.time () in
let _ = flush_all() in
begin
comp_time := !comp_time +. (t2 -. t1);
sync_time := !sync_time +. (t3 -. t2);
printf "Round %d\n" i;
flush_all();
Vpst.return v
end
let n_done = ref 0
let work_loop () : H.t Vpst.t =
U.fold loop_iter !_n_rounds (Vpst.get_latest_version ()) >>= fun v ->
n_done := !n_done + 1;
Vpst.return v
let reset () =
begin
comp_time := 0.0;
MInit.merge_time := 0.0;
MInit.merge_count := 0;
H.merge_time :=0.0;
end
let rec wait_till_done () : unit Vpst.t =
if !n_done = 3 then Vpst.return ()
else begin
Vpst.liftLwt @@ Lwt_unix.sleep 1.0 >>= fun _ ->
wait_till_done ()
end
let experiment_f (fp: out_channel) : unit =
begin
CInit.init ();
Vpst.with_init_version_do H.empty
begin
Vpst.fork_version (work_loop ()) >>= fun br1 ->
Vpst.fork_version ~parent:br1 (work_loop ()) >>= fun br2 ->
Vpst.set_parent br2 >>= fun () ->
(work_loop ()) >>= fun _ ->
wait_till_done ()
end;
let mtime = !MInit.merge_time in
let ctime = !comp_time in
let stime = !sync_time in
let mcount = !MInit.merge_count in
let real_mtime = !MInit.OM.merge_time in
let total_rounds = 3 * !_n_rounds in
let ctime_per_round = ctime/.(float total_rounds) in
let mdivisor1 = if mcount > total_rounds then mcount
else total_rounds in
let mdivisor2 = max mcount 1 in
let avg_mtime1 = real_mtime/.(float mdivisor1) in
let avg_mtime2 = real_mtime/.(float mdivisor2) in
fprintf fp "%d,%d,%fs,%fs,%fs,%d,%fs,%fs,%fs,%fs\n"
!_n_rounds !_n_ops_per_round
mtime ctime stime mcount real_mtime
ctime_per_round avg_mtime1 avg_mtime2;
reset ()
end
let main () =
begin
Logs.set_reporter @@ Logs.format_reporter ();
Logs.set_level @@ Some Logs.Error;
_n_rounds := int_of_string @@ Sys.argv.(1);
_n_ops_per_round := int_of_string @@ Sys.argv.(2);
if Array.length Sys.argv > 3 then
Random.init @@ int_of_string @@ Sys.argv.(3)
else Random.self_init ();
let fp = open_out_gen [Open_creat; Open_append] 0o777 "results.csv" in
experiment_f fp
end;;
main ();;
|
4c4ee4716adb345b5a2d7b80013484b781a84760ba4020fd3751830cc1c493ba | tomahawkins/ecu | CANDBParser.hs | module Main (main) where
import Data.Bits
import Data.Char
import Data.List
import Data.Word
import Text.Printf
import System.Environment
import CANData
main :: IO ()
main = do
args <- getArgs
case args of
["-h"] -> help
["--help"] -> help
[ file ] -> do
dbc <- readFile file
let candb = mkCANDB dbc
writeCANDB candb
_ -> help
help :: IO ()
help = putStrLn $ unlines
[ ""
, "NAME"
, " parsedbc - create CANDB.hs from dbc file"
, ""
, "SYNOPSIS"
, " parsedbc FILE.dbc"
, ""
]
writeCANDB :: CANDB -> IO ()
writeCANDB candb = writeFile "CANDB.hs" $ concat
[ "{- Generated file. Do not modify -}\n"
, "module CANDB\n"
, " ( canDB\n"
, " ) where\n"
, "\n"
, "import CANData\n"
, "\n"
, "canDB :: CANDB\n"
, "canDB = CANDB\n"
, showCANDB candb
, "\n"
]
mkCANDB :: String -> CANDB
mkCANDB s = mkCANDB' nodes groups types attrs (CANDB name nodes [])
where
canLines = filter notBlank (lines s)
name = getName canLines
groups = getGroups canLines
nodes = getNodes canLines
types = getTypes canLines
attrs = getMsgAttrs canLines
mkCANDB' :: [String] -> [[String]] -> [(Word32,String,CANSignalType)] -> [(Word32,CANMsgAttr)] -> CANDB -> CANDB
mkCANDB' _ [] _ _ canDb = canDb
mkCANDB' nodes (group0:groups) types attrs canDb = mkCANDB' nodes groups types attrs (fillDB group0 types attrs canDb)
fillDB :: [String] -> [(Word32,String,CANSignalType)] -> [(Word32,CANMsgAttr)] -> CANDB -> CANDB
fillDB group0 types attrs canDB = getSignals types (tail group0) (getMessage (head group0) attrs canDB)
getMessage :: String -> [(Word32,CANMsgAttr)] -> CANDB -> CANDB
getMessage s attrs (CANDB dbname nodes msgs) = CANDB dbname nodes newMessages
where
newMessages = (msg:msgs)
msg = CANMsg
{ canMsgId = id0
, canMsgName = init c
, canMsgDlc = read d
, canMsgTxNode = e
, canMsgAttrs = map (\ (_,a) -> a) (filter (\ (i,_) -> i == id0) attrs)
, canMsgSignals = []
}
id0 = readId b
(_:b:c:d:e:_) = words s
getSignals :: [(Word32,String,CANSignalType)] -> [String] -> CANDB -> CANDB
getSignals _ [ ] ( dbname nodes ( msg : ) ) = dbname nodes ( ( sortByStartBit )
getSignals _ [] canDb = canDb
getSignals types (l:ls) canDb = sortByStartBit (getSignal types l (getSignals types ls canDb))
sortByStartBit :: CANDB -> CANDB
sortByStartBit (CANDB dbname nodes []) = CANDB dbname nodes []
sortByStartBit (CANDB dbname nodes (msg:msgs)) = CANDB dbname nodes (newMsg:msgs)
where
newMsg = msg { canMsgSignals = sortBy comparingStartBit (canMsgSignals msg) }
comparingStartBit :: CANSignal -> CANSignal -> Ordering
comparingStartBit a b = compare (canSignalStartBit a) (canSignalStartBit b)
getSignal :: [(Word32,String,CANSignalType)] -> String -> CANDB -> CANDB
getSignal _ [] canDb = canDb
getSignal _ _ (CANDB _ _ []) = error "CANDBParser.getSignal"
getSignal types l (CANDB dbname nodes (msg:msgs)) = CANDB dbname nodes (newMsg:msgs)
where
msgId = canMsgId msg
newMsg = msg { canMsgSignals = newSignal:(canMsgSignals msg) }
newSignal = CANSignal
{ canSignalName = name
, canSignalStartBit = (read startBitStr)
, canSignalBitLength = (read bitLengthStr)
, canSignalEndian = if bigEndianStr == '0' then CANBigEndian else CANLittleEndian
, canSignalSign = if signedStr == '-' then CANSigned else CANUnsigned
, canSignalFactor = (read (drop 1 (takeWhile (/= ',') e)))
, canSignalOffset = (read (takeWhile (/= ')') (drop 1 (dropWhile (/= ',') e))))
, canSignalMin = (read (drop 1 (takeWhile (/= '|') f)))
, canSignalMax = (read (takeWhile (/= ']') (drop 1 (dropWhile (/= '|') f))))
, canSignalUnit = unit
, canSignalRxNodes = rx
, canSignalType = matchTypes msgId name types
, canSignalMux = mux
}
startBitStr = takeWhile (/= '|') d
bitLengthStr = drop 1 (dropWhile (/= '|') (takeWhile (/= '@') d))
bigEndianStr = head (drop 1 (dropWhile (/= '@') d))
signedStr = last d
(_:name:maybeMux) = takeWhile (/= ":") (words l)
mux = case maybeMux of
[] -> CANSignalMuxNone
["M"] -> CANSignalMuxer
[('m':muxVal)] -> CANSignalMuxed (read muxVal)
_ -> error "CANDBParser.getSignal: error parsing \" SG_ ...\" line"
(_:d:e:f:_) = dropWhile (/= ":") (words l)
unitAndRx = dropWhile (/= '"') l
unit = (takeWhile (/= '"') (drop 1 unitAndRx))
rxlist = head (words (drop 1 (dropWhile (/= '"') (drop 1 unitAndRx))))
rx = wordsBy ',' rxlist
matchTypes :: Word32 -> String -> [(Word32,String,CANSignalType)] -> CANSignalType
matchTypes _ _ [] = CANSignalTypeNormal
matchTypes msgId0 sigName ((id0,name0,typ):types0) =
if (msgId0 == id0 && sigName == name0)
then typ
else matchTypes msgId0 sigName types0
wordsBy :: Char -> [Char] -> [String]
wordsBy sep s = case dropWhile (== sep) s of
"" -> []
s' -> w : wordsBy ',' s''
where
(w, s'') = break (== sep) s'
getName :: [String] -> String
getName [] = []
getName (l:ls) =
if isPrefixOf "BA_ \"DBName\" " l
then (takeWhile (/= '"') (drop 1 c))
else getName ls
where
(_:_:c:_) = words l
getNodes :: [String] -> [String]
getNodes (l:ls) =
if isPrefixOf "BU_: " l
then (words (drop 5 l))
else getNodes ls
getNodes [] = []
getTypes :: [String] -> [(Word32,String,CANSignalType)]
getTypes ls = getTypes' ls []
getTypes' :: [String] -> [(Word32,String,CANSignalType)] -> [(Word32,String,CANSignalType)]
getTypes' [] types = types
getTypes' (l:ls) types =
if isPrefixOf "SIG_VALTYPE_ " l
then getTypes' ls ((id0,name,typ):types)
else getTypes' ls types
where
typ = if typChar == '1' then CANSignalTypeFloat else CANSignalTypeDouble
typChar = head e
id0 = read b
name = c
(_:b:c:_:e:_) = words l
getMsgAttrs :: [String] -> [(Word32,CANMsgAttr)]
getMsgAttrs ls = getMsgAttrs' ls []
getMsgAttrs' :: [String] -> [(Word32,CANMsgAttr)] -> [(Word32,CANMsgAttr)]
getMsgAttrs' [] attrs = attrs
getMsgAttrs' (l:ls) attrs =
if isPrefixOf "BA_ " l && length (words l) == 5
then
if c == "BO_"
then getMsgAttrs' ls ((id0,attr):attrs)
else getMsgAttrs' ls attrs
else getMsgAttrs' ls attrs
where
id0 = readId d
attr = (tail (init b), init e)
(_:b:c:d:e:_) = words l
getGroups :: [String] -> [[String]]
getGroups ls = groupMessages ls [[]]
groupMessages :: [String] -> [[String]] -> [[String]]
groupMessages [] [] = [[]]
groupMessages [] sofar = map reverse sofar
groupMessages (l:ls) ([]:[]) = case take 4 l of
"BO_ " -> groupMessages ls [[l]]
_ -> groupMessages ls [[]]
groupMessages (l:ls) ((s:ss):gs) = case (take 4 l) of
"BO_ " -> groupMessages ls ([l]:(s:ss):gs)
" SG_" -> groupMessages ls ((l:s:ss):gs)
_ -> reverse (map reverse ((s:ss):gs))
groupMessages _ [] = error "CANDBParser.groupMessages"
groupMessages _ ([]:_) = error "CANDBParser.groupMessages"
notBlank :: String -> Bool
notBlank a = not (and (map isSpace a))
readId :: String -> Word32
readId str = (read str) .&. 0x7FFFFFFF
showCANDB :: CANDB -> String
showCANDB candb = concat
[ " { canDbName = " ++ show (canDbName candb) ++ "\n"
, " , canDbNodes =\n"
, " [" ++ (drop 7 (concatMap showNode (canDbNodes candb)))
, " ]\n"
, " , canDbMsgs =\n"
, " [" ++ (drop 7 (concatMap showMsg (canDbMsgs candb)))
, " ]\n"
, " }\n"
]
showNode :: String -> String
showNode x = " , " ++ show x ++ "\n"
showMsg :: CANMsg -> String
showMsg msg = concat
[ " , CANMsg\n"
, " { canMsgId = " ++ (printf "0x%08X" (canMsgId msg)) ++ "\n"
, " , canMsgName = " ++ show (canMsgName msg) ++ "\n"
, " , canMsgDlc = " ++ show (canMsgDlc msg) ++ "\n"
, " , canMsgTxNode = " ++ show (canMsgTxNode msg) ++ "\n"
, " , canMsgAttrs =\n"
, " [" ++ showMsgAttrs (canMsgAttrs msg)
, " ]\n"
, " , canMsgSignals =\n"
, " [" ++ showMsgSignals (canMsgSignals msg) ++ "\n"
, " ]\n"
, " }\n"
]
showMsgAttrs :: [CANMsgAttr] -> String
showMsgAttrs attrs = case attrs of
[] -> ""
x -> drop 15 (concatMap showMsgAttr x)
showMsgAttr :: CANMsgAttr -> String
showMsgAttr (a , b) = " , (" ++ show a ++ ", " ++ show b ++ ")\n"
showMsgSignals :: [CANSignal] -> String
showMsgSignals signals = case signals of
[] -> ""
x -> drop 15 (concatMap showMsgSignal x)
showMsgSignal :: CANSignal -> String
showMsgSignal signal = concat
[ " , CANSignal\n"
, " { canSignalName = " ++ show (canSignalName signal) ++ "\n"
, " , canSignalStartBit = " ++ show (canSignalStartBit signal) ++ "\n"
, " , canSignalBitLength = " ++ show (canSignalBitLength signal) ++ "\n"
, " , canSignalEndian = " ++ show (canSignalEndian signal) ++ "\n"
, " , canSignalSign = " ++ show (canSignalSign signal) ++ "\n"
, " , canSignalFactor = " ++ show (canSignalFactor signal) ++ "\n"
, " , canSignalOffset = " ++ show (canSignalOffset signal) ++ "\n"
, " , canSignalMin = " ++ show (canSignalMin signal) ++ "\n"
, " , canSignalMax = " ++ show (canSignalMax signal) ++ "\n"
, " , canSignalUnit = " ++ show (canSignalUnit signal) ++ "\n"
, " , canSignalRxNodes =\n"
, " [" ++ showCANSignalRxNodes (canSignalRxNodes signal)
, " ]\n"
, " , canSignalType = " ++ show (canSignalType signal) ++ "\n"
, " , canSignalMux = " ++ show (canSignalMux signal) ++ "\n"
, " }\n"
]
showCANSignalRxNodes :: [String] -> String
showCANSignalRxNodes nodes = case nodes of
[] -> ""
x -> drop 23 (concatMap showCANSignalRxNode x)
showCANSignalRxNode :: String -> String
showCANSignalRxNode x = " , " ++ show x ++ "\n"
| null | https://raw.githubusercontent.com/tomahawkins/ecu/7d294eb65de5860b3512c4cfb98e232368145775/src/CANDBParser.hs | haskell | module Main (main) where
import Data.Bits
import Data.Char
import Data.List
import Data.Word
import Text.Printf
import System.Environment
import CANData
main :: IO ()
main = do
args <- getArgs
case args of
["-h"] -> help
["--help"] -> help
[ file ] -> do
dbc <- readFile file
let candb = mkCANDB dbc
writeCANDB candb
_ -> help
help :: IO ()
help = putStrLn $ unlines
[ ""
, "NAME"
, " parsedbc - create CANDB.hs from dbc file"
, ""
, "SYNOPSIS"
, " parsedbc FILE.dbc"
, ""
]
writeCANDB :: CANDB -> IO ()
writeCANDB candb = writeFile "CANDB.hs" $ concat
[ "{- Generated file. Do not modify -}\n"
, "module CANDB\n"
, " ( canDB\n"
, " ) where\n"
, "\n"
, "import CANData\n"
, "\n"
, "canDB :: CANDB\n"
, "canDB = CANDB\n"
, showCANDB candb
, "\n"
]
mkCANDB :: String -> CANDB
mkCANDB s = mkCANDB' nodes groups types attrs (CANDB name nodes [])
where
canLines = filter notBlank (lines s)
name = getName canLines
groups = getGroups canLines
nodes = getNodes canLines
types = getTypes canLines
attrs = getMsgAttrs canLines
mkCANDB' :: [String] -> [[String]] -> [(Word32,String,CANSignalType)] -> [(Word32,CANMsgAttr)] -> CANDB -> CANDB
mkCANDB' _ [] _ _ canDb = canDb
mkCANDB' nodes (group0:groups) types attrs canDb = mkCANDB' nodes groups types attrs (fillDB group0 types attrs canDb)
fillDB :: [String] -> [(Word32,String,CANSignalType)] -> [(Word32,CANMsgAttr)] -> CANDB -> CANDB
fillDB group0 types attrs canDB = getSignals types (tail group0) (getMessage (head group0) attrs canDB)
getMessage :: String -> [(Word32,CANMsgAttr)] -> CANDB -> CANDB
getMessage s attrs (CANDB dbname nodes msgs) = CANDB dbname nodes newMessages
where
newMessages = (msg:msgs)
msg = CANMsg
{ canMsgId = id0
, canMsgName = init c
, canMsgDlc = read d
, canMsgTxNode = e
, canMsgAttrs = map (\ (_,a) -> a) (filter (\ (i,_) -> i == id0) attrs)
, canMsgSignals = []
}
id0 = readId b
(_:b:c:d:e:_) = words s
getSignals :: [(Word32,String,CANSignalType)] -> [String] -> CANDB -> CANDB
getSignals _ [ ] ( dbname nodes ( msg : ) ) = dbname nodes ( ( sortByStartBit )
getSignals _ [] canDb = canDb
getSignals types (l:ls) canDb = sortByStartBit (getSignal types l (getSignals types ls canDb))
sortByStartBit :: CANDB -> CANDB
sortByStartBit (CANDB dbname nodes []) = CANDB dbname nodes []
sortByStartBit (CANDB dbname nodes (msg:msgs)) = CANDB dbname nodes (newMsg:msgs)
where
newMsg = msg { canMsgSignals = sortBy comparingStartBit (canMsgSignals msg) }
comparingStartBit :: CANSignal -> CANSignal -> Ordering
comparingStartBit a b = compare (canSignalStartBit a) (canSignalStartBit b)
getSignal :: [(Word32,String,CANSignalType)] -> String -> CANDB -> CANDB
getSignal _ [] canDb = canDb
getSignal _ _ (CANDB _ _ []) = error "CANDBParser.getSignal"
getSignal types l (CANDB dbname nodes (msg:msgs)) = CANDB dbname nodes (newMsg:msgs)
where
msgId = canMsgId msg
newMsg = msg { canMsgSignals = newSignal:(canMsgSignals msg) }
newSignal = CANSignal
{ canSignalName = name
, canSignalStartBit = (read startBitStr)
, canSignalBitLength = (read bitLengthStr)
, canSignalEndian = if bigEndianStr == '0' then CANBigEndian else CANLittleEndian
, canSignalSign = if signedStr == '-' then CANSigned else CANUnsigned
, canSignalFactor = (read (drop 1 (takeWhile (/= ',') e)))
, canSignalOffset = (read (takeWhile (/= ')') (drop 1 (dropWhile (/= ',') e))))
, canSignalMin = (read (drop 1 (takeWhile (/= '|') f)))
, canSignalMax = (read (takeWhile (/= ']') (drop 1 (dropWhile (/= '|') f))))
, canSignalUnit = unit
, canSignalRxNodes = rx
, canSignalType = matchTypes msgId name types
, canSignalMux = mux
}
startBitStr = takeWhile (/= '|') d
bitLengthStr = drop 1 (dropWhile (/= '|') (takeWhile (/= '@') d))
bigEndianStr = head (drop 1 (dropWhile (/= '@') d))
signedStr = last d
(_:name:maybeMux) = takeWhile (/= ":") (words l)
mux = case maybeMux of
[] -> CANSignalMuxNone
["M"] -> CANSignalMuxer
[('m':muxVal)] -> CANSignalMuxed (read muxVal)
_ -> error "CANDBParser.getSignal: error parsing \" SG_ ...\" line"
(_:d:e:f:_) = dropWhile (/= ":") (words l)
unitAndRx = dropWhile (/= '"') l
unit = (takeWhile (/= '"') (drop 1 unitAndRx))
rxlist = head (words (drop 1 (dropWhile (/= '"') (drop 1 unitAndRx))))
rx = wordsBy ',' rxlist
matchTypes :: Word32 -> String -> [(Word32,String,CANSignalType)] -> CANSignalType
matchTypes _ _ [] = CANSignalTypeNormal
matchTypes msgId0 sigName ((id0,name0,typ):types0) =
if (msgId0 == id0 && sigName == name0)
then typ
else matchTypes msgId0 sigName types0
wordsBy :: Char -> [Char] -> [String]
wordsBy sep s = case dropWhile (== sep) s of
"" -> []
s' -> w : wordsBy ',' s''
where
(w, s'') = break (== sep) s'
getName :: [String] -> String
getName [] = []
getName (l:ls) =
if isPrefixOf "BA_ \"DBName\" " l
then (takeWhile (/= '"') (drop 1 c))
else getName ls
where
(_:_:c:_) = words l
getNodes :: [String] -> [String]
getNodes (l:ls) =
if isPrefixOf "BU_: " l
then (words (drop 5 l))
else getNodes ls
getNodes [] = []
getTypes :: [String] -> [(Word32,String,CANSignalType)]
getTypes ls = getTypes' ls []
getTypes' :: [String] -> [(Word32,String,CANSignalType)] -> [(Word32,String,CANSignalType)]
getTypes' [] types = types
getTypes' (l:ls) types =
if isPrefixOf "SIG_VALTYPE_ " l
then getTypes' ls ((id0,name,typ):types)
else getTypes' ls types
where
typ = if typChar == '1' then CANSignalTypeFloat else CANSignalTypeDouble
typChar = head e
id0 = read b
name = c
(_:b:c:_:e:_) = words l
getMsgAttrs :: [String] -> [(Word32,CANMsgAttr)]
getMsgAttrs ls = getMsgAttrs' ls []
getMsgAttrs' :: [String] -> [(Word32,CANMsgAttr)] -> [(Word32,CANMsgAttr)]
getMsgAttrs' [] attrs = attrs
getMsgAttrs' (l:ls) attrs =
if isPrefixOf "BA_ " l && length (words l) == 5
then
if c == "BO_"
then getMsgAttrs' ls ((id0,attr):attrs)
else getMsgAttrs' ls attrs
else getMsgAttrs' ls attrs
where
id0 = readId d
attr = (tail (init b), init e)
(_:b:c:d:e:_) = words l
getGroups :: [String] -> [[String]]
getGroups ls = groupMessages ls [[]]
groupMessages :: [String] -> [[String]] -> [[String]]
groupMessages [] [] = [[]]
groupMessages [] sofar = map reverse sofar
groupMessages (l:ls) ([]:[]) = case take 4 l of
"BO_ " -> groupMessages ls [[l]]
_ -> groupMessages ls [[]]
groupMessages (l:ls) ((s:ss):gs) = case (take 4 l) of
"BO_ " -> groupMessages ls ([l]:(s:ss):gs)
" SG_" -> groupMessages ls ((l:s:ss):gs)
_ -> reverse (map reverse ((s:ss):gs))
groupMessages _ [] = error "CANDBParser.groupMessages"
groupMessages _ ([]:_) = error "CANDBParser.groupMessages"
notBlank :: String -> Bool
notBlank a = not (and (map isSpace a))
readId :: String -> Word32
readId str = (read str) .&. 0x7FFFFFFF
showCANDB :: CANDB -> String
showCANDB candb = concat
[ " { canDbName = " ++ show (canDbName candb) ++ "\n"
, " , canDbNodes =\n"
, " [" ++ (drop 7 (concatMap showNode (canDbNodes candb)))
, " ]\n"
, " , canDbMsgs =\n"
, " [" ++ (drop 7 (concatMap showMsg (canDbMsgs candb)))
, " ]\n"
, " }\n"
]
showNode :: String -> String
showNode x = " , " ++ show x ++ "\n"
showMsg :: CANMsg -> String
showMsg msg = concat
[ " , CANMsg\n"
, " { canMsgId = " ++ (printf "0x%08X" (canMsgId msg)) ++ "\n"
, " , canMsgName = " ++ show (canMsgName msg) ++ "\n"
, " , canMsgDlc = " ++ show (canMsgDlc msg) ++ "\n"
, " , canMsgTxNode = " ++ show (canMsgTxNode msg) ++ "\n"
, " , canMsgAttrs =\n"
, " [" ++ showMsgAttrs (canMsgAttrs msg)
, " ]\n"
, " , canMsgSignals =\n"
, " [" ++ showMsgSignals (canMsgSignals msg) ++ "\n"
, " ]\n"
, " }\n"
]
showMsgAttrs :: [CANMsgAttr] -> String
showMsgAttrs attrs = case attrs of
[] -> ""
x -> drop 15 (concatMap showMsgAttr x)
showMsgAttr :: CANMsgAttr -> String
showMsgAttr (a , b) = " , (" ++ show a ++ ", " ++ show b ++ ")\n"
showMsgSignals :: [CANSignal] -> String
showMsgSignals signals = case signals of
[] -> ""
x -> drop 15 (concatMap showMsgSignal x)
showMsgSignal :: CANSignal -> String
showMsgSignal signal = concat
[ " , CANSignal\n"
, " { canSignalName = " ++ show (canSignalName signal) ++ "\n"
, " , canSignalStartBit = " ++ show (canSignalStartBit signal) ++ "\n"
, " , canSignalBitLength = " ++ show (canSignalBitLength signal) ++ "\n"
, " , canSignalEndian = " ++ show (canSignalEndian signal) ++ "\n"
, " , canSignalSign = " ++ show (canSignalSign signal) ++ "\n"
, " , canSignalFactor = " ++ show (canSignalFactor signal) ++ "\n"
, " , canSignalOffset = " ++ show (canSignalOffset signal) ++ "\n"
, " , canSignalMin = " ++ show (canSignalMin signal) ++ "\n"
, " , canSignalMax = " ++ show (canSignalMax signal) ++ "\n"
, " , canSignalUnit = " ++ show (canSignalUnit signal) ++ "\n"
, " , canSignalRxNodes =\n"
, " [" ++ showCANSignalRxNodes (canSignalRxNodes signal)
, " ]\n"
, " , canSignalType = " ++ show (canSignalType signal) ++ "\n"
, " , canSignalMux = " ++ show (canSignalMux signal) ++ "\n"
, " }\n"
]
showCANSignalRxNodes :: [String] -> String
showCANSignalRxNodes nodes = case nodes of
[] -> ""
x -> drop 23 (concatMap showCANSignalRxNode x)
showCANSignalRxNode :: String -> String
showCANSignalRxNode x = " , " ++ show x ++ "\n"
| |
7e3981d53126876515e8a65d4cafb0b1b0893e26bf0274d82557e218029ac2ea | nobutaka/nanopass | tests-6.4-req.scm | (add-tests-with-string-output "byte string"
[(string-size (make-byte-string 0)) => "0\n"]
[(string-size (make-byte-string 1)) => "1\n"]
[(string-size (make-byte-string 1000)) => "1000\n"]
[(let ([s (make-byte-string 1)])
(string-byte-set! s 0 12)
(string-byte-ref s 0)) => "12\n"]
[(let ([s (make-byte-string 1)])
(string-byte-set! s 0 12)
(string-byte-set! s 0 13)
(string-byte-set! s 0 (string-byte-ref s 0))
(string-byte-ref s 0)) => "13\n"]
[(let ([s (make-byte-string 2)])
(string-byte-set! s 1 13)
(string-byte-set! s 0 12)
(string-byte-ref s 1)) => "13\n"]
[(let ([s (make-byte-string 2)])
(string-byte-set! s 0 12)
(string-byte-set! s 1 13)
(string-byte-ref s 0)) => "12\n"]
[(let ([s (make-byte-string 1)])
(string-byte-set! s 0 255)
(string-byte-ref s 0)) => "255\n"]
[(let ([s (make-byte-string 1000)])
(string-byte-set! s 500 12)
(string-byte-ref s 500)) => "12\n"]
)
(add-tests-with-string-output "string-int-set! and ref"
[(let ([s (make-byte-string 4)])
(string-int-set! s 0 12)
(string-int-ref s 0)) => "12\n"]
[(let ([s (make-byte-string 8)])
(string-int-set! s 4 13)
(string-int-set! s 0 12)
(list (string-int-ref s 0) (string-int-ref s 4))) => "(12 13)\n"]
[(let ([s (make-byte-string 4)])
0xeeff
(list (string-byte-ref s 0) (string-byte-ref s 1))) => "(255 238)\n"] ; 0xff 0xee
)
(add-tests-with-string-output "string-float-set! and ref"
[(let ([s (make-byte-string 8)])
(string-float-set! s 3 1.2)
(string-float-ref s 3)) => "1.200000\n"]
)
(add-tests-with-string-output "box"
[(box? 0) => "#f\n"]
[(box? #f) => "#f\n"]
[(box? '()) => "#f\n"]
[(box? "s") => "#f\n"]
[(box? (make-byte-string 4)) => "#f\n"]
)
(add-tests-with-string-output "bytevector"
[(bytevector? 0) => "#f\n"]
[(bytevector? #f) => "#f\n"]
[(bytevector? '()) => "#f\n"]
[(bytevector? "s") => "#f\n"]
[(bytevector? (make-byte-string 1)) => "#f\n"]
[(bytevector? (make-bytevector 1)) => "#t\n"]
)
(add-tests-with-string-output "asciiz"
[(string->asciiz "abc") => "\"abc\\0\"\n"]
[(asciiz-length (string->asciiz "abc")) => "3\n"]
[(let ([bv (make-bytevector 10)])
(string-byte-set! bv 0 97)
(string-byte-set! bv 1 98)
(string-byte-set! bv 2 99)
(string-byte-set! bv 3 0)
(asciiz-length bv)) => "3\n"]
[(asciiz->string (string->asciiz "abc")) => "\"abc\"\n"]
[(let ([bv (make-bytevector 10)])
(string-byte-set! bv 0 97)
(string-byte-set! bv 1 98)
(string-byte-set! bv 2 99)
(string-byte-set! bv 3 0)
(asciiz->string bv)) => "\"abc\"\n"]
)
(add-tests-with-string-output "let*"
[(let* ([a 100] [b a] [c (cons a b)]) c) => "(100 . 100)\n"]
)
| null | https://raw.githubusercontent.com/nobutaka/nanopass/80e0344a1f143832a75d798be903e05b5dbdd079/tests/tests-6.4-req.scm | scheme | 0xff 0xee | (add-tests-with-string-output "byte string"
[(string-size (make-byte-string 0)) => "0\n"]
[(string-size (make-byte-string 1)) => "1\n"]
[(string-size (make-byte-string 1000)) => "1000\n"]
[(let ([s (make-byte-string 1)])
(string-byte-set! s 0 12)
(string-byte-ref s 0)) => "12\n"]
[(let ([s (make-byte-string 1)])
(string-byte-set! s 0 12)
(string-byte-set! s 0 13)
(string-byte-set! s 0 (string-byte-ref s 0))
(string-byte-ref s 0)) => "13\n"]
[(let ([s (make-byte-string 2)])
(string-byte-set! s 1 13)
(string-byte-set! s 0 12)
(string-byte-ref s 1)) => "13\n"]
[(let ([s (make-byte-string 2)])
(string-byte-set! s 0 12)
(string-byte-set! s 1 13)
(string-byte-ref s 0)) => "12\n"]
[(let ([s (make-byte-string 1)])
(string-byte-set! s 0 255)
(string-byte-ref s 0)) => "255\n"]
[(let ([s (make-byte-string 1000)])
(string-byte-set! s 500 12)
(string-byte-ref s 500)) => "12\n"]
)
(add-tests-with-string-output "string-int-set! and ref"
[(let ([s (make-byte-string 4)])
(string-int-set! s 0 12)
(string-int-ref s 0)) => "12\n"]
[(let ([s (make-byte-string 8)])
(string-int-set! s 4 13)
(string-int-set! s 0 12)
(list (string-int-ref s 0) (string-int-ref s 4))) => "(12 13)\n"]
[(let ([s (make-byte-string 4)])
0xeeff
)
(add-tests-with-string-output "string-float-set! and ref"
[(let ([s (make-byte-string 8)])
(string-float-set! s 3 1.2)
(string-float-ref s 3)) => "1.200000\n"]
)
(add-tests-with-string-output "box"
[(box? 0) => "#f\n"]
[(box? #f) => "#f\n"]
[(box? '()) => "#f\n"]
[(box? "s") => "#f\n"]
[(box? (make-byte-string 4)) => "#f\n"]
)
(add-tests-with-string-output "bytevector"
[(bytevector? 0) => "#f\n"]
[(bytevector? #f) => "#f\n"]
[(bytevector? '()) => "#f\n"]
[(bytevector? "s") => "#f\n"]
[(bytevector? (make-byte-string 1)) => "#f\n"]
[(bytevector? (make-bytevector 1)) => "#t\n"]
)
(add-tests-with-string-output "asciiz"
[(string->asciiz "abc") => "\"abc\\0\"\n"]
[(asciiz-length (string->asciiz "abc")) => "3\n"]
[(let ([bv (make-bytevector 10)])
(string-byte-set! bv 0 97)
(string-byte-set! bv 1 98)
(string-byte-set! bv 2 99)
(string-byte-set! bv 3 0)
(asciiz-length bv)) => "3\n"]
[(asciiz->string (string->asciiz "abc")) => "\"abc\"\n"]
[(let ([bv (make-bytevector 10)])
(string-byte-set! bv 0 97)
(string-byte-set! bv 1 98)
(string-byte-set! bv 2 99)
(string-byte-set! bv 3 0)
(asciiz->string bv)) => "\"abc\"\n"]
)
(add-tests-with-string-output "let*"
[(let* ([a 100] [b a] [c (cons a b)]) c) => "(100 . 100)\n"]
)
|
4756926b6f103b624e1cbfa0d334176489e31fff91f1a7f40f54f1f8e752b159 | ghcjs/jsaddle-dom | WebGLDrawBuffers.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.WebGLDrawBuffers
(drawBuffersWEBGL, pattern COLOR_ATTACHMENT0_WEBGL,
pattern COLOR_ATTACHMENT1_WEBGL, pattern COLOR_ATTACHMENT2_WEBGL,
pattern COLOR_ATTACHMENT3_WEBGL, pattern COLOR_ATTACHMENT4_WEBGL,
pattern COLOR_ATTACHMENT5_WEBGL, pattern COLOR_ATTACHMENT6_WEBGL,
pattern COLOR_ATTACHMENT7_WEBGL, pattern COLOR_ATTACHMENT8_WEBGL,
pattern COLOR_ATTACHMENT9_WEBGL, pattern COLOR_ATTACHMENT10_WEBGL,
pattern COLOR_ATTACHMENT11_WEBGL, pattern COLOR_ATTACHMENT12_WEBGL,
pattern COLOR_ATTACHMENT13_WEBGL, pattern COLOR_ATTACHMENT14_WEBGL,
pattern COLOR_ATTACHMENT15_WEBGL, pattern DRAW_BUFFER0_WEBGL,
pattern DRAW_BUFFER1_WEBGL, pattern DRAW_BUFFER2_WEBGL,
pattern DRAW_BUFFER3_WEBGL, pattern DRAW_BUFFER4_WEBGL,
pattern DRAW_BUFFER5_WEBGL, pattern DRAW_BUFFER6_WEBGL,
pattern DRAW_BUFFER7_WEBGL, pattern DRAW_BUFFER8_WEBGL,
pattern DRAW_BUFFER9_WEBGL, pattern DRAW_BUFFER10_WEBGL,
pattern DRAW_BUFFER11_WEBGL, pattern DRAW_BUFFER12_WEBGL,
pattern DRAW_BUFFER13_WEBGL, pattern DRAW_BUFFER14_WEBGL,
pattern DRAW_BUFFER15_WEBGL, pattern MAX_COLOR_ATTACHMENTS_WEBGL,
pattern MAX_DRAW_BUFFERS_WEBGL, WebGLDrawBuffers(..),
gTypeWebGLDrawBuffers)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/WebGLDrawBuffers.drawBuffersWEBGL Mozilla WebGLDrawBuffers.drawBuffersWEBGL documentation >
drawBuffersWEBGL ::
(MonadDOM m) => WebGLDrawBuffers -> [GLenum] -> m ()
drawBuffersWEBGL self buffers
= liftDOM
(void (self ^. jsf "drawBuffersWEBGL" [toJSVal (array buffers)]))
pattern COLOR_ATTACHMENT0_WEBGL = 36064
pattern COLOR_ATTACHMENT1_WEBGL = 36065
pattern COLOR_ATTACHMENT2_WEBGL = 36066
pattern COLOR_ATTACHMENT3_WEBGL = 36067
pattern COLOR_ATTACHMENT4_WEBGL = 36068
pattern COLOR_ATTACHMENT5_WEBGL = 36069
pattern COLOR_ATTACHMENT6_WEBGL = 36070
pattern COLOR_ATTACHMENT7_WEBGL = 36071
pattern COLOR_ATTACHMENT8_WEBGL = 36072
pattern COLOR_ATTACHMENT9_WEBGL = 36073
pattern COLOR_ATTACHMENT10_WEBGL = 36074
pattern COLOR_ATTACHMENT11_WEBGL = 36075
pattern COLOR_ATTACHMENT12_WEBGL = 36076
pattern COLOR_ATTACHMENT13_WEBGL = 36077
pattern COLOR_ATTACHMENT14_WEBGL = 36078
pattern COLOR_ATTACHMENT15_WEBGL = 36079
pattern DRAW_BUFFER0_WEBGL = 34853
pattern DRAW_BUFFER1_WEBGL = 34854
pattern DRAW_BUFFER2_WEBGL = 34855
pattern DRAW_BUFFER3_WEBGL = 34856
pattern DRAW_BUFFER4_WEBGL = 34857
pattern DRAW_BUFFER5_WEBGL = 34858
pattern DRAW_BUFFER6_WEBGL = 34859
pattern DRAW_BUFFER7_WEBGL = 34860
pattern DRAW_BUFFER8_WEBGL = 34861
pattern DRAW_BUFFER9_WEBGL = 34862
pattern DRAW_BUFFER10_WEBGL = 34863
pattern DRAW_BUFFER11_WEBGL = 34864
pattern DRAW_BUFFER12_WEBGL = 34865
pattern DRAW_BUFFER13_WEBGL = 34866
pattern DRAW_BUFFER14_WEBGL = 34867
pattern DRAW_BUFFER15_WEBGL = 34868
pattern MAX_COLOR_ATTACHMENTS_WEBGL = 36063
pattern MAX_DRAW_BUFFERS_WEBGL = 34852
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/WebGLDrawBuffers.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.WebGLDrawBuffers
(drawBuffersWEBGL, pattern COLOR_ATTACHMENT0_WEBGL,
pattern COLOR_ATTACHMENT1_WEBGL, pattern COLOR_ATTACHMENT2_WEBGL,
pattern COLOR_ATTACHMENT3_WEBGL, pattern COLOR_ATTACHMENT4_WEBGL,
pattern COLOR_ATTACHMENT5_WEBGL, pattern COLOR_ATTACHMENT6_WEBGL,
pattern COLOR_ATTACHMENT7_WEBGL, pattern COLOR_ATTACHMENT8_WEBGL,
pattern COLOR_ATTACHMENT9_WEBGL, pattern COLOR_ATTACHMENT10_WEBGL,
pattern COLOR_ATTACHMENT11_WEBGL, pattern COLOR_ATTACHMENT12_WEBGL,
pattern COLOR_ATTACHMENT13_WEBGL, pattern COLOR_ATTACHMENT14_WEBGL,
pattern COLOR_ATTACHMENT15_WEBGL, pattern DRAW_BUFFER0_WEBGL,
pattern DRAW_BUFFER1_WEBGL, pattern DRAW_BUFFER2_WEBGL,
pattern DRAW_BUFFER3_WEBGL, pattern DRAW_BUFFER4_WEBGL,
pattern DRAW_BUFFER5_WEBGL, pattern DRAW_BUFFER6_WEBGL,
pattern DRAW_BUFFER7_WEBGL, pattern DRAW_BUFFER8_WEBGL,
pattern DRAW_BUFFER9_WEBGL, pattern DRAW_BUFFER10_WEBGL,
pattern DRAW_BUFFER11_WEBGL, pattern DRAW_BUFFER12_WEBGL,
pattern DRAW_BUFFER13_WEBGL, pattern DRAW_BUFFER14_WEBGL,
pattern DRAW_BUFFER15_WEBGL, pattern MAX_COLOR_ATTACHMENTS_WEBGL,
pattern MAX_DRAW_BUFFERS_WEBGL, WebGLDrawBuffers(..),
gTypeWebGLDrawBuffers)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/WebGLDrawBuffers.drawBuffersWEBGL Mozilla WebGLDrawBuffers.drawBuffersWEBGL documentation >
drawBuffersWEBGL ::
(MonadDOM m) => WebGLDrawBuffers -> [GLenum] -> m ()
drawBuffersWEBGL self buffers
= liftDOM
(void (self ^. jsf "drawBuffersWEBGL" [toJSVal (array buffers)]))
pattern COLOR_ATTACHMENT0_WEBGL = 36064
pattern COLOR_ATTACHMENT1_WEBGL = 36065
pattern COLOR_ATTACHMENT2_WEBGL = 36066
pattern COLOR_ATTACHMENT3_WEBGL = 36067
pattern COLOR_ATTACHMENT4_WEBGL = 36068
pattern COLOR_ATTACHMENT5_WEBGL = 36069
pattern COLOR_ATTACHMENT6_WEBGL = 36070
pattern COLOR_ATTACHMENT7_WEBGL = 36071
pattern COLOR_ATTACHMENT8_WEBGL = 36072
pattern COLOR_ATTACHMENT9_WEBGL = 36073
pattern COLOR_ATTACHMENT10_WEBGL = 36074
pattern COLOR_ATTACHMENT11_WEBGL = 36075
pattern COLOR_ATTACHMENT12_WEBGL = 36076
pattern COLOR_ATTACHMENT13_WEBGL = 36077
pattern COLOR_ATTACHMENT14_WEBGL = 36078
pattern COLOR_ATTACHMENT15_WEBGL = 36079
pattern DRAW_BUFFER0_WEBGL = 34853
pattern DRAW_BUFFER1_WEBGL = 34854
pattern DRAW_BUFFER2_WEBGL = 34855
pattern DRAW_BUFFER3_WEBGL = 34856
pattern DRAW_BUFFER4_WEBGL = 34857
pattern DRAW_BUFFER5_WEBGL = 34858
pattern DRAW_BUFFER6_WEBGL = 34859
pattern DRAW_BUFFER7_WEBGL = 34860
pattern DRAW_BUFFER8_WEBGL = 34861
pattern DRAW_BUFFER9_WEBGL = 34862
pattern DRAW_BUFFER10_WEBGL = 34863
pattern DRAW_BUFFER11_WEBGL = 34864
pattern DRAW_BUFFER12_WEBGL = 34865
pattern DRAW_BUFFER13_WEBGL = 34866
pattern DRAW_BUFFER14_WEBGL = 34867
pattern DRAW_BUFFER15_WEBGL = 34868
pattern MAX_COLOR_ATTACHMENTS_WEBGL = 36063
pattern MAX_DRAW_BUFFERS_WEBGL = 34852
|
9e2e3557320aabb25fdecd8643d5b90d7613238564cef89adafadeec943a1a1d | lkuper/rust-redex | lambda-gc.rkt | A Redex model of the lambda - gc language from , Felleisen ,
and , " Abstract Models of Memory Management "
( /~rwh/papers/gc/fpca95.pdf ) .
#lang racket
(require redex)
(define-language lambda-gc
;; Programs.
(Var variable-not-otherwise-mentioned)
(Int number)
(Exp Var Int (pair Exp_1 Exp_2) (proj1 Exp) (proj2 Exp) (lambda (Var) Exp)
(Exp_1 Exp_2))
(Hval Int (pair Var_1 Var_2) (lambda (Var) Exp))
(Heap ((Var Hval) ...))
(Prog (letrec Heap in Exp))
(Ans (letrec Heap in Var))
;; Evaluation contexts and instruction expressions.
(Ctxt hole (pair Ctxt Exp) (pair Var Ctxt) (proj1 Ctxt) (proj2 Ctxt)
(Ctxt Exp) (Var Ctxt))
(Instr Hval (Proj Var) (Var Var))
(Proj proj1 proj2))
(define lambda-gc-red
(reduction-relation
lambda-gc
(--> (letrec Heap in (in-hole Ctxt Hval))
;; We use append rather than cons (here and in the app rule)
;; to match the semantics of the paper, where new bindings
;; get added at the end of the heap rather than the
;; beginning.
(letrec ,(append (term Heap) `((,(term Var) ,(term Hval))))
in (in-hole Ctxt Var))
Make sure that Var is a fresh variable , so we do n't
;; conflict with bindings already in the heap.
(where Var ,(variable-not-in (term Heap) (term Var)))
"alloc")
(--> (letrec Heap in (in-hole Ctxt (Proj Var)))
(letrec Heap in (in-hole Ctxt (project Proj Heap Var)))
"proj")
(--> (letrec Heap in (in-hole Ctxt (Var_1 Var_2)))
(letrec
,(append (term Heap)
;; New binding on the heap: the equivalent of
;; {z = H(y)} from the paper.
`((,(term Var) ,(term (heap-lookup Heap Var_2)))))
;; Put Exp in the evaluation context, replacing any
occurrences of Var_3 ( the binder from the lambda
expression on the heap ) with our fresh variable Var .
in (in-hole Ctxt (subst Exp Var_3 Var)))
should already be bound to a lambda expression in
;; the heap.
(where (lambda (Var_3) Exp) (heap-lookup Heap Var_1))
Make sure that Var is a fresh variable , so we do n't
;; conflict with bindings already in the heap.
(where Var ,(variable-not-in (term Heap) (term Var)))
"app")))
(define-metafunction lambda-gc
project : Proj Heap Var -> Var
Use second and third , instead of first and second , because pairs
;; start with the tag 'pair.
[(project proj1 Heap Var) ,(second (term (heap-lookup Heap Var)))]
[(project proj2 Heap Var) ,(third (term (heap-lookup Heap Var)))])
(define-metafunction lambda-gc
heap-lookup : Heap Var -> Hval
[(heap-lookup Heap Var) ,(second (assq (term Var) (term Heap)))])
;; A few tests.
(define (test-suite)
(test-->> lambda-gc-red
(term (letrec () in 3))
(term (letrec ((Var 3))
in Var)))
(test-->> lambda-gc-red
(term (letrec () in (pair 3 4)))
(term (letrec ((Var 3)
(Var1 4)
(Var2 (pair Var Var1)))
in Var2)))
(test-->> lambda-gc-red
(term (letrec () in (proj1 (pair 3 4))))
(term (letrec ((Var 3)
(Var1 4)
(Var2 (pair Var Var1)))
in Var)))
;; The example from the lambda-gc TR
;; (/~rwh/papers/gc/tr.pdf).
(test-->> lambda-gc-red
(term (letrec ((x 1)) in ((lambda (y) (proj1 y))
(pair x x))))
(term (letrec ((x 1)
(Var (lambda (y) (proj1 y)))
(Var1 (pair x x))
(Var2 (pair x x)))
in x)))
(test-->> lambda-gc-red
(term (letrec () in (pair ((lambda (x) x)
(proj2 (pair 1 2)))
((lambda (x) x)
(proj2 (pair 3 4))))))
(term (letrec ((Var (lambda (x) x))
(Var1 1)
(Var2 2)
(Var3 (pair Var1 Var2))
(Var4 2)
(Var5 (lambda (x) x))
(Var6 3)
(Var7 4)
(Var8 (pair Var6 Var7))
(Var9 4)
(Var10 (pair Var4 Var9)))
in
Var10)))
Naive substitution works -- here ' Var4 ' replaces ' x ' in ( lambda
;; (x) x), but it isn't a problem because the formal parameter 'x'
gets replaced with ' Var4 ' too !
(test-->> lambda-gc-red
(term (letrec () in (pair ((lambda (x)
((lambda (x) x) 3))
(proj2 (pair 1 2)))
((lambda (x) x)
(proj2 (pair 3 4))))))
should be a pair of 3 and 4
(term (letrec ((Var
(lambda (x)
((lambda (x) x)
3)))
(Var1 1)
(Var2 2)
(Var3
(pair Var1 Var2))
(Var4 2)
(Var5
(lambda (Var4)
Var4))
(Var6 3)
(Var7 3)
(Var8 (lambda (x) x))
(Var9 3)
(Var10 4)
(Var11
(pair Var9 Var10))
(Var12 4)
(Var13
(pair Var7 Var12)))
in
Var13)))
And if ' Var4 ' appears literally in the term , it 's not a problem
;; because the variable-not-in feature in the app rule doesn't allow
;; us to pick any variable that already appears anywhere in the heap
;; at all.
(test-->> lambda-gc-red
(term (letrec () in (pair ((lambda (x)
((lambda (x)
((lambda (Var4)
x) x)) 3))
(proj2 (pair 1 2)))
((lambda (x) x)
(proj2 (pair 3 4))))))
should be a pair of 3 and 4
(term (letrec ((Var
(lambda (x)
((lambda (x)
((lambda (Var4)
x)
x))
3)))
(Var1 1)
(Var2 2)
(Var3
(pair Var1 Var2))
(Var5 2)
(Var6
(lambda (Var5)
((lambda (Var4)
Var5)
Var5)))
(Var7 3)
(Var8 3)
(Var9
(lambda (Var4)
Var8))
(Var10 3)
(Var11
(lambda (x) x))
(Var12 3)
(Var13 4)
(Var14
(pair Var12 Var13))
(Var15 4)
(Var16
(pair Var8 Var15)))
in
Var16)))
(test-->> lambda-gc-red
(term (letrec () in ((lambda (f)
(pair (f (pair 1 2))
(f (pair 3 4))))
(lambda (p) (proj2 p)))))
(term (letrec ((Var (lambda (f)
(pair (f (pair 1 2))
(f (pair 3 4)))))
(Var1 (lambda (p) (proj2 p)))
(Var2 (lambda (p) (proj2 p)))
(Var3 1)
(Var4 2)
(Var5 (pair Var3 Var4))
(Var6 (pair Var3 Var4))
(Var7 3)
(Var8 4)
(Var9 (pair Var7 Var8))
(Var10 (pair Var7 Var8))
(Var11 (pair Var4 Var8)))
in
Var11)))
;; If some variable is already in the heap with a particular name,
;; we don't autogenerate that name again.
(test-->> lambda-gc-red
(term (letrec ((Var 0)
(Var1 1)
(Var2 2)) in (pair Var (pair Var1 Var2))))
(term (letrec ((Var 0)
(Var1 1)
(Var2 2)
(Var3 (pair Var1 Var2))
(Var4 (pair Var Var3)))
in
Var4)))
;; And using existing names as formal parameters isn't a problem,
;; either.
(test-->> lambda-gc-red
(term (letrec ((Var 0)
(Var1 1)
(Var2 2)) in
((lambda (Var1) Var1)
(pair
Var (pair Var1 Var2)))))
(term (letrec ((Var 0)
(Var1 1)
(Var2 2)
(Var3 (lambda (Var1) Var1))
(Var4 (pair Var1 Var2))
(Var5 (pair Var Var4))
(Var6 (pair Var Var4)))
in
Var6)))
(test-results))
;; This is just dumb textual substitution. Capture-avoiding
;; substitution isn't necessary.
(define-metafunction lambda-gc
;; (subst expr old-var new-expr): Read the arguments left-to-right
;; as "expr, but with occurrences of old-var replaced with
;; new-expr".
[(subst Var_1 Var_1 any_1) any_1]
[(subst (any_2 ...) Var_1 any_1)
((subst any_2 Var_1 any_1) ...)]
[(subst any_2 Var_1 any_1) any_2])
| null | https://raw.githubusercontent.com/lkuper/rust-redex/53d19f89f6e569891324e4313e17b19154ebbcf3/lambda-gc.rkt | racket | Programs.
Evaluation contexts and instruction expressions.
We use append rather than cons (here and in the app rule)
to match the semantics of the paper, where new bindings
get added at the end of the heap rather than the
beginning.
conflict with bindings already in the heap.
New binding on the heap: the equivalent of
{z = H(y)} from the paper.
Put Exp in the evaluation context, replacing any
the heap.
conflict with bindings already in the heap.
start with the tag 'pair.
A few tests.
The example from the lambda-gc TR
(/~rwh/papers/gc/tr.pdf).
(x) x), but it isn't a problem because the formal parameter 'x'
because the variable-not-in feature in the app rule doesn't allow
us to pick any variable that already appears anywhere in the heap
at all.
If some variable is already in the heap with a particular name,
we don't autogenerate that name again.
And using existing names as formal parameters isn't a problem,
either.
This is just dumb textual substitution. Capture-avoiding
substitution isn't necessary.
(subst expr old-var new-expr): Read the arguments left-to-right
as "expr, but with occurrences of old-var replaced with
new-expr". | A Redex model of the lambda - gc language from , Felleisen ,
and , " Abstract Models of Memory Management "
( /~rwh/papers/gc/fpca95.pdf ) .
#lang racket
(require redex)
(define-language lambda-gc
(Var variable-not-otherwise-mentioned)
(Int number)
(Exp Var Int (pair Exp_1 Exp_2) (proj1 Exp) (proj2 Exp) (lambda (Var) Exp)
(Exp_1 Exp_2))
(Hval Int (pair Var_1 Var_2) (lambda (Var) Exp))
(Heap ((Var Hval) ...))
(Prog (letrec Heap in Exp))
(Ans (letrec Heap in Var))
(Ctxt hole (pair Ctxt Exp) (pair Var Ctxt) (proj1 Ctxt) (proj2 Ctxt)
(Ctxt Exp) (Var Ctxt))
(Instr Hval (Proj Var) (Var Var))
(Proj proj1 proj2))
(define lambda-gc-red
(reduction-relation
lambda-gc
(--> (letrec Heap in (in-hole Ctxt Hval))
(letrec ,(append (term Heap) `((,(term Var) ,(term Hval))))
in (in-hole Ctxt Var))
Make sure that Var is a fresh variable , so we do n't
(where Var ,(variable-not-in (term Heap) (term Var)))
"alloc")
(--> (letrec Heap in (in-hole Ctxt (Proj Var)))
(letrec Heap in (in-hole Ctxt (project Proj Heap Var)))
"proj")
(--> (letrec Heap in (in-hole Ctxt (Var_1 Var_2)))
(letrec
,(append (term Heap)
`((,(term Var) ,(term (heap-lookup Heap Var_2)))))
occurrences of Var_3 ( the binder from the lambda
expression on the heap ) with our fresh variable Var .
in (in-hole Ctxt (subst Exp Var_3 Var)))
should already be bound to a lambda expression in
(where (lambda (Var_3) Exp) (heap-lookup Heap Var_1))
Make sure that Var is a fresh variable , so we do n't
(where Var ,(variable-not-in (term Heap) (term Var)))
"app")))
(define-metafunction lambda-gc
project : Proj Heap Var -> Var
Use second and third , instead of first and second , because pairs
[(project proj1 Heap Var) ,(second (term (heap-lookup Heap Var)))]
[(project proj2 Heap Var) ,(third (term (heap-lookup Heap Var)))])
(define-metafunction lambda-gc
heap-lookup : Heap Var -> Hval
[(heap-lookup Heap Var) ,(second (assq (term Var) (term Heap)))])
(define (test-suite)
(test-->> lambda-gc-red
(term (letrec () in 3))
(term (letrec ((Var 3))
in Var)))
(test-->> lambda-gc-red
(term (letrec () in (pair 3 4)))
(term (letrec ((Var 3)
(Var1 4)
(Var2 (pair Var Var1)))
in Var2)))
(test-->> lambda-gc-red
(term (letrec () in (proj1 (pair 3 4))))
(term (letrec ((Var 3)
(Var1 4)
(Var2 (pair Var Var1)))
in Var)))
(test-->> lambda-gc-red
(term (letrec ((x 1)) in ((lambda (y) (proj1 y))
(pair x x))))
(term (letrec ((x 1)
(Var (lambda (y) (proj1 y)))
(Var1 (pair x x))
(Var2 (pair x x)))
in x)))
(test-->> lambda-gc-red
(term (letrec () in (pair ((lambda (x) x)
(proj2 (pair 1 2)))
((lambda (x) x)
(proj2 (pair 3 4))))))
(term (letrec ((Var (lambda (x) x))
(Var1 1)
(Var2 2)
(Var3 (pair Var1 Var2))
(Var4 2)
(Var5 (lambda (x) x))
(Var6 3)
(Var7 4)
(Var8 (pair Var6 Var7))
(Var9 4)
(Var10 (pair Var4 Var9)))
in
Var10)))
Naive substitution works -- here ' Var4 ' replaces ' x ' in ( lambda
gets replaced with ' Var4 ' too !
(test-->> lambda-gc-red
(term (letrec () in (pair ((lambda (x)
((lambda (x) x) 3))
(proj2 (pair 1 2)))
((lambda (x) x)
(proj2 (pair 3 4))))))
should be a pair of 3 and 4
(term (letrec ((Var
(lambda (x)
((lambda (x) x)
3)))
(Var1 1)
(Var2 2)
(Var3
(pair Var1 Var2))
(Var4 2)
(Var5
(lambda (Var4)
Var4))
(Var6 3)
(Var7 3)
(Var8 (lambda (x) x))
(Var9 3)
(Var10 4)
(Var11
(pair Var9 Var10))
(Var12 4)
(Var13
(pair Var7 Var12)))
in
Var13)))
And if ' Var4 ' appears literally in the term , it 's not a problem
(test-->> lambda-gc-red
(term (letrec () in (pair ((lambda (x)
((lambda (x)
((lambda (Var4)
x) x)) 3))
(proj2 (pair 1 2)))
((lambda (x) x)
(proj2 (pair 3 4))))))
should be a pair of 3 and 4
(term (letrec ((Var
(lambda (x)
((lambda (x)
((lambda (Var4)
x)
x))
3)))
(Var1 1)
(Var2 2)
(Var3
(pair Var1 Var2))
(Var5 2)
(Var6
(lambda (Var5)
((lambda (Var4)
Var5)
Var5)))
(Var7 3)
(Var8 3)
(Var9
(lambda (Var4)
Var8))
(Var10 3)
(Var11
(lambda (x) x))
(Var12 3)
(Var13 4)
(Var14
(pair Var12 Var13))
(Var15 4)
(Var16
(pair Var8 Var15)))
in
Var16)))
(test-->> lambda-gc-red
(term (letrec () in ((lambda (f)
(pair (f (pair 1 2))
(f (pair 3 4))))
(lambda (p) (proj2 p)))))
(term (letrec ((Var (lambda (f)
(pair (f (pair 1 2))
(f (pair 3 4)))))
(Var1 (lambda (p) (proj2 p)))
(Var2 (lambda (p) (proj2 p)))
(Var3 1)
(Var4 2)
(Var5 (pair Var3 Var4))
(Var6 (pair Var3 Var4))
(Var7 3)
(Var8 4)
(Var9 (pair Var7 Var8))
(Var10 (pair Var7 Var8))
(Var11 (pair Var4 Var8)))
in
Var11)))
(test-->> lambda-gc-red
(term (letrec ((Var 0)
(Var1 1)
(Var2 2)) in (pair Var (pair Var1 Var2))))
(term (letrec ((Var 0)
(Var1 1)
(Var2 2)
(Var3 (pair Var1 Var2))
(Var4 (pair Var Var3)))
in
Var4)))
(test-->> lambda-gc-red
(term (letrec ((Var 0)
(Var1 1)
(Var2 2)) in
((lambda (Var1) Var1)
(pair
Var (pair Var1 Var2)))))
(term (letrec ((Var 0)
(Var1 1)
(Var2 2)
(Var3 (lambda (Var1) Var1))
(Var4 (pair Var1 Var2))
(Var5 (pair Var Var4))
(Var6 (pair Var Var4)))
in
Var6)))
(test-results))
(define-metafunction lambda-gc
[(subst Var_1 Var_1 any_1) any_1]
[(subst (any_2 ...) Var_1 any_1)
((subst any_2 Var_1 any_1) ...)]
[(subst any_2 Var_1 any_1) any_2])
|
8a582136408ae9fd716a429cfb12562400d1270ccc3c18bd51a83ade1a066688 | Clozure/ccl-tests | logical-pathname-translations.lsp | ;-*- Mode: Lisp -*-
Author :
Created : We d Dec 31 09:46:08 2003
;;;; Contains: Tests of LOGICAL-PATHNAME-TRANSLATIONS
(in-package :cl-test)
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/logical-pathname-translations.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of LOGICAL-PATHNAME-TRANSLATIONS | Author :
Created : We d Dec 31 09:46:08 2003
(in-package :cl-test)
|
cc0ae8662e9b65a5512fb5aa59936876a392e6bab57f691c13e0b843c979eba2 | gregtatcam/imaplet-lwt | maildir_storage.ml |
* Copyright ( c ) 2013 - 2014 < >
*
* 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-2014 Gregory Tsipenyuk <>
*
* 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.
*)
open Lwt
open Sexplib
open Sexplib.Conv
open Storage
open Storage_meta
open Imaplet_types
open Lazy_message
open Lazy_maildir_message
open Server_config
open Mail_file_name
exception EmptyPrivateKey
let acct_lock_pool = ref MapStr.empty
let pool_mutex = Lwt_mutex.create ()
module MapStr = Map.Make(String)
let _mail_path config user =
Utils.user_path ~path:config.Server_config.mail_path ~user ()
module MaildirPath : sig
type t
val create : Server_config.imapConfig -> string -> string -> t
val to_maildir : t -> string
val to_unix : t -> string
val to_unix_path : string -> string
val file_path : t -> [`Cur of string|`Tmp of string|`New of
string|`Metadata|`Uidlist|`Keywords] -> string
val file_path_of_maildir : t -> string -> [`Cur of string|`Tmp of string|`New of
string|`Metadata|`Uidlist|`Keywords] -> string
val basename_of_maildir : string -> string
val basename : t -> string
val dirname_of_maildir : string -> string
val dirname : t -> string
val mailbox : t -> string
val root : t -> string
val trim_mailbox : t -> string -> string
end = struct
root * mailbox
* root is location of Maildir , for inst . /User / dovecot / Maildir
* mailbox is relative to the root
* root is location of Maildir, for inst. /User/dovecot/Maildir
* mailbox is relative to the root
*)
type t = {root:string;mailbox:string;config:Server_config.imapConfig}
let mailbox t =
t.mailbox
let root t =
t.root
.Foo . Foo1.Foo2 - > Foo / Foo1 / Foo2
* structure is flat with subfolders separated by " . "
* imaplet internally maintains Unix mailbox path
* maildir structure is flat with subfolders separated by "."
* imaplet internally maintains Unix mailbox path
*)
let maildir_path_to_unix path =
let path = Regex.replace ~regx:"^\\." ~tmpl:"" path in
Regex.replace ~regx:"\\." ~tmpl:"/" path
convert unix path to maildir format / Foo1 / Foo2 - > .Foo . Foo1.Foo2
let unix_path_to_maildir path =
let path = Regex.replace ~regx:"^/" ~tmpl:"" path in
let path = Regex.replace ~regx:"/" ~tmpl:"." path in
"." ^ path
(* mailbox is in unix format i.e. foo/foo1/foo2
* will change to .foo.foo1.foo2 *)
let create config user mailbox =
let open Server_config in
let mailbox =
let lcase = String.lowercase mailbox in
inbox does n't have it 's own folder , messages are placed into
* tmp / cur / new under directly under
* tmp/cur/new under directly under Maildir
*)
if lcase = ".inbox" || lcase = "inbox" || mailbox = "." || mailbox = "" then
""
else
unix_path_to_maildir mailbox
in
{root=Configuration.mailboxes (_mail_path config user) user;mailbox;config}
(* return full mailbox path formated for use by OS *)
let to_maildir t =
if t.mailbox <> "" then
Filename.concat t.root t.mailbox
else
t.root
(* only convert the mailbox part to the unix format *)
let to_unix t =
maildir_path_to_unix t.mailbox
let to_unix_path mailbox =
maildir_path_to_unix mailbox
(* get location of a file under the mailbox *)
let file_path_of_maildir t maildir tp =
let maildir = if t.mailbox = "" then "" else maildir in
let (=^) parent child = Filename.concat parent child in
match tp with
| `Cur file -> root t =^ maildir =^ "cur" =^ file
| `Tmp file -> root t =^ maildir =^ "tmp" =^ file
| `New file -> root t =^ maildir =^ "new" =^ file
| `Metadata -> root t =^ maildir =^ "imaplet.meta"
| `Uidlist -> root t =^ maildir =^ "imaplet.uidlst"
| `Keywords -> root t =^ maildir =^ "imaplet.keywords"
(* get location of a file under the mailbox *)
let file_path t tp =
file_path_of_maildir t t.mailbox tp
(* like Filename.basename *)
let basename_of_maildir mailbox =
if mailbox = "" then
""
else (
let _ = Regex.match_regex ~regx:"\\.\\([^\\.]+\\)$" mailbox in
Str.matched_group 1 mailbox
)
let basename t =
basename_of_maildir t.mailbox
(* like Filename.dirname *)
let dirname_of_maildir mailbox =
if mailbox = "" then
""
else (
let _ = Regex.match_regex ~regx:"\\.\\([^\\.]+\\)$" mailbox in
Str.string_before mailbox (Str.match_beginning ())
)
let dirname t =
dirname_of_maildir t.mailbox
(* remove mailbox prefix from the file *)
let trim_mailbox t file =
let regx = Regex.replace ~regx:"\\." ~tmpl:"\\\\." t.mailbox in
let regx = "^" ^ regx in
Regex.replace ~regx ~tmpl:"" file
end
(* create an empty file *)
let create_file ?(overwrite=false) ?(perms=0o666) path =
let open Unix in
let flags =
if overwrite then
[O_NONBLOCK;O_WRONLY;O_CREAT;O_TRUNC]
else
[O_NONBLOCK;O_WRONLY;O_EXCL;O_CREAT]
in
Lwt_unix.openfile path flags perms >>= fun fd ->
Lwt_unix.close fd
let with_lock path f =
let lock = Imap_lock.create pool_mutex acct_lock_pool in
Imap_lock.with_lock lock path f
(* read mailbox metadata *)
let read_mailbox_metadata path =
let open Unix in
with_lock path (fun () ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_RDONLY] ~mode:Lwt_io.Input
(fun ci -> Lwt_io.read ci) >>= fun sexp_str ->
return (mailbox_metadata_of_sexp (Sexp.of_string sexp_str))
)
(* write mailbox metadata *)
let write_mailbox_metadata path metadata =
let open Unix in
with_lock path (fun () ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_WRONLY;O_TRUNC] ~mode:Lwt_io.Output
(fun co ->
Lwt_io.write co (Sexp.to_string (sexp_of_mailbox_metadata metadata)) >>
Lwt_io.flush co)
)
(* read mailbox uidlist: uid filename *)
let read_uidlist path =
let open Unix in
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_RDONLY] ~mode:Lwt_io.Input
(fun ci ->
let rec read_line cnt acc =
Lwt_io.read_line_opt ci >>= function
| Some line ->
let _ = Regex.match_regex ~regx:"^\\([0-9]+\\) \\(.+\\)$" line in
let uid = int_of_string (Str.matched_group 1 line) and
file = Str.matched_group 2 line in
read_line (cnt + 1) ((cnt,uid,file) :: acc)
| None -> return acc
in
with_lock path (fun() -> read_line 1 [])
) >>= fun l ->
return (List.rev l)
(* write mailbox uidlist *)
let write_uidlist path l =
let open Unix in
with_lock path (fun() ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_WRONLY;O_TRUNC] ~mode:Lwt_io.Output
(fun co ->
Lwt_list.iter_s (fun (_,uid,file) ->
Lwt_io.write_line co (String.concat " " [string_of_int uid ; file])
) l
)
)
append to uidlist
let append_uidlist path uid file =
let open Unix in
with_lock path (fun() ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_WRONLY;O_APPEND] ~mode:Lwt_io.Output
(fun co -> Lwt_io.write_line co (String.concat " " [string_of_int uid ; file]))
)
let subscribe_path mail_path user =
Filename.concat (Configuration.mailboxes (Utils.user_path ~path:mail_path ~user ()) user) "imaplet.subscribe"
(* read subscribe *)
let read_subscribe path =
let open Unix in
with_lock path (fun () ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_RDONLY] ~mode:Lwt_io.Input
(fun ci -> Lwt_io.read ci)
) >>= fun sexp_str ->
return (list_of_sexp (fun s -> string_of_sexp s) (Sexp.of_string sexp_str))
(* write subscribe *)
let write_subscribe path l =
let open Unix in
with_lock path (fun() ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_WRONLY;O_TRUNC] ~mode:Lwt_io.Output
(fun co ->
Lwt_io.write co (Sexp.to_string (sexp_of_list (fun s -> sexp_of_string s) l)) >>
Lwt_io.flush co
)
)
maildir storage type
type storage_ = {user: string; mailbox:
MaildirPath.t;config:Server_config.imapConfig;keys:Ssl_.keys;uidlist:(int*int*string) list option ref}
module MaildirStorage : Storage_intf with type t = storage_ =
struct
type t = storage_
(* user *)
let create config user mailbox keys =
return {user;mailbox = MaildirPath.create config user
mailbox;config;keys;uidlist=ref None}
(* mailbox supports both folders and messages *)
let exists t =
catch (fun () ->
Lwt_unix.stat (MaildirPath.to_maildir t.mailbox) >>= fun st ->
if st.Unix.st_kind = Unix.S_DIR then
return `Mailbox
else
return `No
) (fun _ -> return `No)
let current t file =
MaildirPath.file_path t.mailbox (`Cur file)
let fetch_mailbox_metadata t =
read_mailbox_metadata (MaildirPath.file_path t.mailbox `Metadata)
let update_mailbox_metadata t =
write_mailbox_metadata (MaildirPath.file_path t.mailbox `Metadata)
let fetch_uidlist t =
match !(t.uidlist) with
| None ->
read_uidlist (MaildirPath.file_path t.mailbox `Uidlist) >>= fun uidlist ->
t.uidlist := Some uidlist;
return uidlist
| Some uidlist -> return uidlist
let update_uidlist t l =
t.uidlist := Some l;
write_uidlist (MaildirPath.file_path t.mailbox `Uidlist) l
(* status *)
let status t =
fetch_mailbox_metadata t
(* select mailbox *)
let select t =
status t
(* examine mailbox *)
let examine t =
status t
(* create mailbox *)
let create_mailbox t =
(* inbox doesn't have it's own folder, so don't need to create *)
begin
if MaildirPath.basename t.mailbox <> "" then
Lwt_unix.mkdir (MaildirPath.to_maildir t.mailbox) 0o777
else
return ()
end >>
create_file (MaildirPath.file_path t.mailbox `Metadata ) >>
create_file (MaildirPath.file_path t.mailbox `Uidlist ) >>
Lwt_unix.mkdir (MaildirPath.file_path t.mailbox (`Cur "") ) 0o777 >>
Lwt_unix.mkdir (MaildirPath.file_path t.mailbox (`New "") ) 0o777 >>
Lwt_unix.mkdir (MaildirPath.file_path t.mailbox (`Tmp "") ) 0o777 >>
update_mailbox_metadata t (empty_mailbox_metadata ~uidvalidity:(new_uidvalidity()) ()) >>
update_uidlist t []
(* delete mailbox *)
let delete t =
Lwt_unix.system ("rm -rf " ^ (MaildirPath.to_maildir t.mailbox)) >>= fun _ ->
return ()
rename
let rename t mailbox2 =
Lwt_unix.rename (MaildirPath.to_maildir t.mailbox) mailbox2
(* subscribe mailbox *)
let subscribe t =
let mailbox = MaildirPath.basename t.mailbox in
let mailbox = if mailbox = "" then "inbox" else mailbox in
read_subscribe (subscribe_path t.config.mail_path t.user) >>= fun l ->
try
let _ = List.find (fun m -> m = mailbox) l in return ()
with Not_found -> write_subscribe (subscribe_path t.config.mail_path t.user) (mailbox :: l)
(* unsubscribe mailbox *)
let unsubscribe t =
let mailbox = MaildirPath.basename t.mailbox in
let mailbox = if mailbox = "" then "inbox" else mailbox in
read_subscribe (subscribe_path t.config.mail_path t.user) >>= fun l ->
write_subscribe (subscribe_path t.config.mail_path t.user) (List.filter (fun m -> m <> mailbox) l)
list
* returns list of files / folders with list of flags
* hierarchy is flat , get the list of all " folders "
* then figure out the children count
* returns list of files/folders with list of flags
* maildir hierarchy is flat, get the list of all "folders"
* then figure out the children count
*)
let list t ~subscribed ?(access=(fun _ -> true)) ~init ~f =
let subscription =
if subscribed then
Some (read_subscribe t.user)
else
None
in
remove root from the mailbox path
let mailbox = MaildirPath.mailbox t.mailbox in
maildir structure is flat ; mailboxes start with " . " , which is also the
* separator ; start listing with the maildir root and match against the
* starting mailbox ; the match is for subdirectories , so the starting
* mailbox itself is not included
* separator; start listing with the maildir root and match against the
* starting mailbox; the match is for subdirectories, so the starting
* mailbox itself is not included
*)
let strm = Lwt_unix.files_of_directory (MaildirPath.root t.mailbox) in
let strm = if mailbox = "" then Lwt_stream.choose [strm; Lwt_stream.of_list [".INBOX"]] else strm in
Lwt_stream.fold_s (fun file (counts,acc) ->
let regx = if mailbox = "" then "" else mailbox ^ "." in
let regx = Regex.replace ~regx:"\\.\\.$" ~tmpl:"." regx in
let regx = Regex.replace ~regx:"\\." ~tmpl:"\\\\." regx in
let regx = "^" ^ regx in
if file = "." || file = ".." || file.[0] <> '.' || Regex.match_regex ~regx file = false then (
return (counts,acc)
) else (
the mailbox has to match exactly , i.e. if the mailbox is Test and
* the file is then it 's not a match , pattern match is done in the
* caller
* the file is Test1 then it's not a match, pattern match is done in the
* caller
*)
read_mailbox_metadata (MaildirPath.file_path_of_maildir t.mailbox file `Metadata) >>= fun metadata ->
(* need to handle subscriptions TBD *)
if access file then (
let counts = MapStr.add file metadata.count counts in
let dirname = MaildirPath.dirname_of_maildir file in
let counts =
if dirname <> "." && dirname <> "" then
let cnt = try MapStr.find dirname counts with Not_found -> 0 in
MapStr.add dirname (cnt + 1) counts
else
counts
in
return (counts,file :: acc)
) else (
return (counts,acc)
)
)
) strm (MapStr.empty,[]) >>= fun (counts,mailboxes) ->
Lwt_list.fold_right_s (fun file acc ->
let cnt = try MapStr.find file counts with Not_found -> 0 in
let file = MaildirPath.trim_mailbox t.mailbox file in
f acc (`Mailbox (MaildirPath.to_unix_path file,cnt))
) mailboxes init
let encrypt t message =
let (pub_key,_) = t.keys in
if t.config.encrypt then (
Imap_crypto.encrypt ~compress:t.config.compress message pub_key
) else if t.config.compress then (
Imap_crypto.do_compress message
) else (
message
)
let decrypt t message =
let (_,priv_key) = t.keys in
let priv_key = Utils.option_value_exn ~ex:EmptyPrivateKey priv_key in
if t.config.encrypt then (
Imap_crypto.decrypt ~compressed:t.config.compress message priv_key
) else if t.config.compress then (
Imap_crypto.do_uncompress message
) else (
message
)
(* write message to the file *)
let write_message t file message =
let open Unix in
let open Lightparsemail in
let tmp_file = MaildirPath.file_path t.mailbox (`Tmp file) in
begin
if t.config.maildir_parse then
Message.to_parsed_message_with_header message
else
return message
end >>= fun message ->
let message = encrypt t message in
Lwt_io.with_file tmp_file ~flags:[O_NONBLOCK;O_CREAT;O_WRONLY] ~mode:Lwt_io.Output
(fun oc ->
Lwt_io.write oc message) >>= fun () ->
let cur_file = current t file in
Lwt_unix.link tmp_file cur_file >>
Lwt_unix.unlink tmp_file
(* append message(s) to selected mailbox *)
let append t message message_metadata =
let file = make_message_file_name (MaildirPath.to_maildir t.mailbox) message_metadata in
write_message t file message >>= fun () ->
t.uidlist := None;
append_uidlist (MaildirPath.file_path t.mailbox `Uidlist) message_metadata.uid file
return sequence , uid , file size , file name
let get_file t position uids =
let len = List.length uids in
if len = 0 then return `Eof
else
begin
let size t seq uid file =
catch (fun () ->
Lwt_unix.stat (current t file) >>= fun st ->
return (`Ok (seq,uid,st.Unix.st_size,file))
) (fun _ -> return `NotFound)
in
search through uid / filename list
let find uid uids =
List.find (fun (_,u,_) -> u = uid) uids
in
match position with
| `Sequence seq ->
if seq > len then
return `Eof
else if seq = 0 then
return `NotFound
else
let (_,uid,file) = List.nth uids (seq - 1)
in (size t seq uid file)
| `UID uid ->
try
let (seq,uid,file) = find uid uids in (size t seq uid file)
with _ ->
let (_,u,_) = List.nth uids (len - 1) in
if uid > u then
return `Eof
else
return `NotFound
end
(* delete a message *)
let delete_message t position =
fetch_uidlist t >>= fun uids ->
get_file t position uids >>= function
| `Ok (_,uid,_,file) ->
let uids = List.filter (fun (_,u,_) -> u <> uid) uids in
update_uidlist t uids >>= fun () ->
Lwt_unix.unlink (current t file)
| _ -> return ()
let fetch_ t position uids =
let open Lightparsemail in
Printexc.record_backtrace true;
get_file t position uids >>= function
| `Ok (_,uid,size,file) ->
let (internal_date,size,modseq,flags) = message_file_name_to_data t.mailbox file in
let metadata = {uid;modseq;internal_date;size;flags} in
let lazy_read = Lazy.from_fun (fun () ->
let t1 = Unix.gettimeofday () in
let path = current t file in
let open Unix in
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_RDONLY] ~mode:Lwt_io.Input (fun ci ->
Lwt_io.read ci
) >>= fun msg ->
let msg = decrypt t msg in
Stats.add_readt (Unix.gettimeofday() -. t1);
return msg) in
let lazy_message =
Lazy.from_fun (fun () ->
Lazy.force lazy_read >>= fun buffer ->
if t.config.maildir_parse then
return (Message.from_parsed_message_with_header buffer)
else
Message.parse buffer
)
in
let lazy_metadata = Lazy.from_fun (fun () -> return metadata) in
return (`Ok (Lazy_message.build_lazy_message_inst (module LazyMaildirMessage)
(lazy_read, lazy_message, lazy_metadata)))
| `Eof -> return `Eof
| `NotFound -> return `NotFound
let total_fetch = ref 0.
(* fetch messages from selected mailbox *)
let fetch t position =
fetch_uidlist t >>= fun uids ->
fetch_ t position uids
(* fetch messages from selected mailbox *)
let fetch_message_metadata t position =
fetch_uidlist t >>= fun uids ->
get_file t position uids >>= function
| `Ok (_,uid,size,file) ->
let (internal_date,_,modseq,flags) = message_file_name_to_data t.mailbox file in
return (`Ok {uid; modseq; internal_date; size; flags})
| `Eof -> return `Eof
| `NotFound -> return `NotFound
(* store flags to selected mailbox *)
let store t position message_metadata =
fetch_uidlist t >>= fun uids ->
get_file t position uids >>= function
| `Ok (seq,uid,_,src) ->
let dst = update_message_file_name (MaildirPath.to_maildir t.mailbox) src message_metadata in
Lwt_unix.rename (current t src) (current t dst) >>= fun () ->
let uids = List.fold_right (fun (s,u,f) acc ->
if u = uid then
(s,u,dst) :: acc
else
(s,u,f) :: acc
) uids [] in
update_uidlist t uids
| _ -> return ()
(* store mailbox metadata *)
let store_mailbox_metadata t mailbox_metadata =
update_mailbox_metadata t mailbox_metadata
(* copy messages from selected mailbox *)
let copy t pos t2 message_metadata =
fetch t pos >>= function
| `Eof | `NotFound -> return ()
| `Ok (module LazyMessage) ->
LazyMessage.LazyMessage.get_postmark LazyMessage.this >>= fun postmark ->
LazyMessage.LazyMessage.get_email LazyMessage.this >>= fun (module LE:LazyEmail_inst) ->
LE.LazyEmail.to_string LE.this >>= fun email ->
let message = String.concat Email_parse.crlf [postmark ; email] in
append t2 message message_metadata
let commit t =
return ()
let uid_to_seq t uid =
fetch_uidlist t >>= fun uids ->
get_file t (`UID uid) uids >>= function
| `Ok (seq,_,_,_) -> return (Some seq)
| _ -> return None
let create_account t =
let path = subscribe_path t.config.mail_path t.user in
Utils.exists path Unix.S_REG >>= fun res ->
if res then
return `Exists
else (
let open Unix in
Lwt_unix.openfile path [O_NONBLOCK;O_WRONLY;O_CREAT] 0o664 >>= fun fd ->
Lwt_unix.close fd >>
write_subscribe path [] >>
return `Ok
)
let delete_account t =
let path = subscribe_path t.config.mail_path t.user in
Lwt_unix.system ("rm -rf " ^ path) >>= fun _ ->
return ()
end
| null | https://raw.githubusercontent.com/gregtatcam/imaplet-lwt/d7b51253e79cffa97e98ab899ed833cd7cb44bb6/lib/commands/maildir_storage.ml | ocaml | mailbox is in unix format i.e. foo/foo1/foo2
* will change to .foo.foo1.foo2
return full mailbox path formated for use by OS
only convert the mailbox part to the unix format
get location of a file under the mailbox
get location of a file under the mailbox
like Filename.basename
like Filename.dirname
remove mailbox prefix from the file
create an empty file
read mailbox metadata
write mailbox metadata
read mailbox uidlist: uid filename
write mailbox uidlist
read subscribe
write subscribe
user
mailbox supports both folders and messages
status
select mailbox
examine mailbox
create mailbox
inbox doesn't have it's own folder, so don't need to create
delete mailbox
subscribe mailbox
unsubscribe mailbox
need to handle subscriptions TBD
write message to the file
append message(s) to selected mailbox
delete a message
fetch messages from selected mailbox
fetch messages from selected mailbox
store flags to selected mailbox
store mailbox metadata
copy messages from selected mailbox |
* Copyright ( c ) 2013 - 2014 < >
*
* 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-2014 Gregory Tsipenyuk <>
*
* 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.
*)
open Lwt
open Sexplib
open Sexplib.Conv
open Storage
open Storage_meta
open Imaplet_types
open Lazy_message
open Lazy_maildir_message
open Server_config
open Mail_file_name
exception EmptyPrivateKey
let acct_lock_pool = ref MapStr.empty
let pool_mutex = Lwt_mutex.create ()
module MapStr = Map.Make(String)
let _mail_path config user =
Utils.user_path ~path:config.Server_config.mail_path ~user ()
module MaildirPath : sig
type t
val create : Server_config.imapConfig -> string -> string -> t
val to_maildir : t -> string
val to_unix : t -> string
val to_unix_path : string -> string
val file_path : t -> [`Cur of string|`Tmp of string|`New of
string|`Metadata|`Uidlist|`Keywords] -> string
val file_path_of_maildir : t -> string -> [`Cur of string|`Tmp of string|`New of
string|`Metadata|`Uidlist|`Keywords] -> string
val basename_of_maildir : string -> string
val basename : t -> string
val dirname_of_maildir : string -> string
val dirname : t -> string
val mailbox : t -> string
val root : t -> string
val trim_mailbox : t -> string -> string
end = struct
root * mailbox
* root is location of Maildir , for inst . /User / dovecot / Maildir
* mailbox is relative to the root
* root is location of Maildir, for inst. /User/dovecot/Maildir
* mailbox is relative to the root
*)
type t = {root:string;mailbox:string;config:Server_config.imapConfig}
let mailbox t =
t.mailbox
let root t =
t.root
.Foo . Foo1.Foo2 - > Foo / Foo1 / Foo2
* structure is flat with subfolders separated by " . "
* imaplet internally maintains Unix mailbox path
* maildir structure is flat with subfolders separated by "."
* imaplet internally maintains Unix mailbox path
*)
let maildir_path_to_unix path =
let path = Regex.replace ~regx:"^\\." ~tmpl:"" path in
Regex.replace ~regx:"\\." ~tmpl:"/" path
convert unix path to maildir format / Foo1 / Foo2 - > .Foo . Foo1.Foo2
let unix_path_to_maildir path =
let path = Regex.replace ~regx:"^/" ~tmpl:"" path in
let path = Regex.replace ~regx:"/" ~tmpl:"." path in
"." ^ path
let create config user mailbox =
let open Server_config in
let mailbox =
let lcase = String.lowercase mailbox in
inbox does n't have it 's own folder , messages are placed into
* tmp / cur / new under directly under
* tmp/cur/new under directly under Maildir
*)
if lcase = ".inbox" || lcase = "inbox" || mailbox = "." || mailbox = "" then
""
else
unix_path_to_maildir mailbox
in
{root=Configuration.mailboxes (_mail_path config user) user;mailbox;config}
let to_maildir t =
if t.mailbox <> "" then
Filename.concat t.root t.mailbox
else
t.root
let to_unix t =
maildir_path_to_unix t.mailbox
let to_unix_path mailbox =
maildir_path_to_unix mailbox
let file_path_of_maildir t maildir tp =
let maildir = if t.mailbox = "" then "" else maildir in
let (=^) parent child = Filename.concat parent child in
match tp with
| `Cur file -> root t =^ maildir =^ "cur" =^ file
| `Tmp file -> root t =^ maildir =^ "tmp" =^ file
| `New file -> root t =^ maildir =^ "new" =^ file
| `Metadata -> root t =^ maildir =^ "imaplet.meta"
| `Uidlist -> root t =^ maildir =^ "imaplet.uidlst"
| `Keywords -> root t =^ maildir =^ "imaplet.keywords"
let file_path t tp =
file_path_of_maildir t t.mailbox tp
let basename_of_maildir mailbox =
if mailbox = "" then
""
else (
let _ = Regex.match_regex ~regx:"\\.\\([^\\.]+\\)$" mailbox in
Str.matched_group 1 mailbox
)
let basename t =
basename_of_maildir t.mailbox
let dirname_of_maildir mailbox =
if mailbox = "" then
""
else (
let _ = Regex.match_regex ~regx:"\\.\\([^\\.]+\\)$" mailbox in
Str.string_before mailbox (Str.match_beginning ())
)
let dirname t =
dirname_of_maildir t.mailbox
let trim_mailbox t file =
let regx = Regex.replace ~regx:"\\." ~tmpl:"\\\\." t.mailbox in
let regx = "^" ^ regx in
Regex.replace ~regx ~tmpl:"" file
end
let create_file ?(overwrite=false) ?(perms=0o666) path =
let open Unix in
let flags =
if overwrite then
[O_NONBLOCK;O_WRONLY;O_CREAT;O_TRUNC]
else
[O_NONBLOCK;O_WRONLY;O_EXCL;O_CREAT]
in
Lwt_unix.openfile path flags perms >>= fun fd ->
Lwt_unix.close fd
let with_lock path f =
let lock = Imap_lock.create pool_mutex acct_lock_pool in
Imap_lock.with_lock lock path f
let read_mailbox_metadata path =
let open Unix in
with_lock path (fun () ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_RDONLY] ~mode:Lwt_io.Input
(fun ci -> Lwt_io.read ci) >>= fun sexp_str ->
return (mailbox_metadata_of_sexp (Sexp.of_string sexp_str))
)
let write_mailbox_metadata path metadata =
let open Unix in
with_lock path (fun () ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_WRONLY;O_TRUNC] ~mode:Lwt_io.Output
(fun co ->
Lwt_io.write co (Sexp.to_string (sexp_of_mailbox_metadata metadata)) >>
Lwt_io.flush co)
)
let read_uidlist path =
let open Unix in
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_RDONLY] ~mode:Lwt_io.Input
(fun ci ->
let rec read_line cnt acc =
Lwt_io.read_line_opt ci >>= function
| Some line ->
let _ = Regex.match_regex ~regx:"^\\([0-9]+\\) \\(.+\\)$" line in
let uid = int_of_string (Str.matched_group 1 line) and
file = Str.matched_group 2 line in
read_line (cnt + 1) ((cnt,uid,file) :: acc)
| None -> return acc
in
with_lock path (fun() -> read_line 1 [])
) >>= fun l ->
return (List.rev l)
let write_uidlist path l =
let open Unix in
with_lock path (fun() ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_WRONLY;O_TRUNC] ~mode:Lwt_io.Output
(fun co ->
Lwt_list.iter_s (fun (_,uid,file) ->
Lwt_io.write_line co (String.concat " " [string_of_int uid ; file])
) l
)
)
append to uidlist
let append_uidlist path uid file =
let open Unix in
with_lock path (fun() ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_WRONLY;O_APPEND] ~mode:Lwt_io.Output
(fun co -> Lwt_io.write_line co (String.concat " " [string_of_int uid ; file]))
)
let subscribe_path mail_path user =
Filename.concat (Configuration.mailboxes (Utils.user_path ~path:mail_path ~user ()) user) "imaplet.subscribe"
let read_subscribe path =
let open Unix in
with_lock path (fun () ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_RDONLY] ~mode:Lwt_io.Input
(fun ci -> Lwt_io.read ci)
) >>= fun sexp_str ->
return (list_of_sexp (fun s -> string_of_sexp s) (Sexp.of_string sexp_str))
let write_subscribe path l =
let open Unix in
with_lock path (fun() ->
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_WRONLY;O_TRUNC] ~mode:Lwt_io.Output
(fun co ->
Lwt_io.write co (Sexp.to_string (sexp_of_list (fun s -> sexp_of_string s) l)) >>
Lwt_io.flush co
)
)
maildir storage type
type storage_ = {user: string; mailbox:
MaildirPath.t;config:Server_config.imapConfig;keys:Ssl_.keys;uidlist:(int*int*string) list option ref}
module MaildirStorage : Storage_intf with type t = storage_ =
struct
type t = storage_
let create config user mailbox keys =
return {user;mailbox = MaildirPath.create config user
mailbox;config;keys;uidlist=ref None}
let exists t =
catch (fun () ->
Lwt_unix.stat (MaildirPath.to_maildir t.mailbox) >>= fun st ->
if st.Unix.st_kind = Unix.S_DIR then
return `Mailbox
else
return `No
) (fun _ -> return `No)
let current t file =
MaildirPath.file_path t.mailbox (`Cur file)
let fetch_mailbox_metadata t =
read_mailbox_metadata (MaildirPath.file_path t.mailbox `Metadata)
let update_mailbox_metadata t =
write_mailbox_metadata (MaildirPath.file_path t.mailbox `Metadata)
let fetch_uidlist t =
match !(t.uidlist) with
| None ->
read_uidlist (MaildirPath.file_path t.mailbox `Uidlist) >>= fun uidlist ->
t.uidlist := Some uidlist;
return uidlist
| Some uidlist -> return uidlist
let update_uidlist t l =
t.uidlist := Some l;
write_uidlist (MaildirPath.file_path t.mailbox `Uidlist) l
let status t =
fetch_mailbox_metadata t
let select t =
status t
let examine t =
status t
let create_mailbox t =
begin
if MaildirPath.basename t.mailbox <> "" then
Lwt_unix.mkdir (MaildirPath.to_maildir t.mailbox) 0o777
else
return ()
end >>
create_file (MaildirPath.file_path t.mailbox `Metadata ) >>
create_file (MaildirPath.file_path t.mailbox `Uidlist ) >>
Lwt_unix.mkdir (MaildirPath.file_path t.mailbox (`Cur "") ) 0o777 >>
Lwt_unix.mkdir (MaildirPath.file_path t.mailbox (`New "") ) 0o777 >>
Lwt_unix.mkdir (MaildirPath.file_path t.mailbox (`Tmp "") ) 0o777 >>
update_mailbox_metadata t (empty_mailbox_metadata ~uidvalidity:(new_uidvalidity()) ()) >>
update_uidlist t []
let delete t =
Lwt_unix.system ("rm -rf " ^ (MaildirPath.to_maildir t.mailbox)) >>= fun _ ->
return ()
rename
let rename t mailbox2 =
Lwt_unix.rename (MaildirPath.to_maildir t.mailbox) mailbox2
let subscribe t =
let mailbox = MaildirPath.basename t.mailbox in
let mailbox = if mailbox = "" then "inbox" else mailbox in
read_subscribe (subscribe_path t.config.mail_path t.user) >>= fun l ->
try
let _ = List.find (fun m -> m = mailbox) l in return ()
with Not_found -> write_subscribe (subscribe_path t.config.mail_path t.user) (mailbox :: l)
let unsubscribe t =
let mailbox = MaildirPath.basename t.mailbox in
let mailbox = if mailbox = "" then "inbox" else mailbox in
read_subscribe (subscribe_path t.config.mail_path t.user) >>= fun l ->
write_subscribe (subscribe_path t.config.mail_path t.user) (List.filter (fun m -> m <> mailbox) l)
list
* returns list of files / folders with list of flags
* hierarchy is flat , get the list of all " folders "
* then figure out the children count
* returns list of files/folders with list of flags
* maildir hierarchy is flat, get the list of all "folders"
* then figure out the children count
*)
let list t ~subscribed ?(access=(fun _ -> true)) ~init ~f =
let subscription =
if subscribed then
Some (read_subscribe t.user)
else
None
in
remove root from the mailbox path
let mailbox = MaildirPath.mailbox t.mailbox in
maildir structure is flat ; mailboxes start with " . " , which is also the
* separator ; start listing with the maildir root and match against the
* starting mailbox ; the match is for subdirectories , so the starting
* mailbox itself is not included
* separator; start listing with the maildir root and match against the
* starting mailbox; the match is for subdirectories, so the starting
* mailbox itself is not included
*)
let strm = Lwt_unix.files_of_directory (MaildirPath.root t.mailbox) in
let strm = if mailbox = "" then Lwt_stream.choose [strm; Lwt_stream.of_list [".INBOX"]] else strm in
Lwt_stream.fold_s (fun file (counts,acc) ->
let regx = if mailbox = "" then "" else mailbox ^ "." in
let regx = Regex.replace ~regx:"\\.\\.$" ~tmpl:"." regx in
let regx = Regex.replace ~regx:"\\." ~tmpl:"\\\\." regx in
let regx = "^" ^ regx in
if file = "." || file = ".." || file.[0] <> '.' || Regex.match_regex ~regx file = false then (
return (counts,acc)
) else (
the mailbox has to match exactly , i.e. if the mailbox is Test and
* the file is then it 's not a match , pattern match is done in the
* caller
* the file is Test1 then it's not a match, pattern match is done in the
* caller
*)
read_mailbox_metadata (MaildirPath.file_path_of_maildir t.mailbox file `Metadata) >>= fun metadata ->
if access file then (
let counts = MapStr.add file metadata.count counts in
let dirname = MaildirPath.dirname_of_maildir file in
let counts =
if dirname <> "." && dirname <> "" then
let cnt = try MapStr.find dirname counts with Not_found -> 0 in
MapStr.add dirname (cnt + 1) counts
else
counts
in
return (counts,file :: acc)
) else (
return (counts,acc)
)
)
) strm (MapStr.empty,[]) >>= fun (counts,mailboxes) ->
Lwt_list.fold_right_s (fun file acc ->
let cnt = try MapStr.find file counts with Not_found -> 0 in
let file = MaildirPath.trim_mailbox t.mailbox file in
f acc (`Mailbox (MaildirPath.to_unix_path file,cnt))
) mailboxes init
let encrypt t message =
let (pub_key,_) = t.keys in
if t.config.encrypt then (
Imap_crypto.encrypt ~compress:t.config.compress message pub_key
) else if t.config.compress then (
Imap_crypto.do_compress message
) else (
message
)
let decrypt t message =
let (_,priv_key) = t.keys in
let priv_key = Utils.option_value_exn ~ex:EmptyPrivateKey priv_key in
if t.config.encrypt then (
Imap_crypto.decrypt ~compressed:t.config.compress message priv_key
) else if t.config.compress then (
Imap_crypto.do_uncompress message
) else (
message
)
let write_message t file message =
let open Unix in
let open Lightparsemail in
let tmp_file = MaildirPath.file_path t.mailbox (`Tmp file) in
begin
if t.config.maildir_parse then
Message.to_parsed_message_with_header message
else
return message
end >>= fun message ->
let message = encrypt t message in
Lwt_io.with_file tmp_file ~flags:[O_NONBLOCK;O_CREAT;O_WRONLY] ~mode:Lwt_io.Output
(fun oc ->
Lwt_io.write oc message) >>= fun () ->
let cur_file = current t file in
Lwt_unix.link tmp_file cur_file >>
Lwt_unix.unlink tmp_file
let append t message message_metadata =
let file = make_message_file_name (MaildirPath.to_maildir t.mailbox) message_metadata in
write_message t file message >>= fun () ->
t.uidlist := None;
append_uidlist (MaildirPath.file_path t.mailbox `Uidlist) message_metadata.uid file
return sequence , uid , file size , file name
let get_file t position uids =
let len = List.length uids in
if len = 0 then return `Eof
else
begin
let size t seq uid file =
catch (fun () ->
Lwt_unix.stat (current t file) >>= fun st ->
return (`Ok (seq,uid,st.Unix.st_size,file))
) (fun _ -> return `NotFound)
in
search through uid / filename list
let find uid uids =
List.find (fun (_,u,_) -> u = uid) uids
in
match position with
| `Sequence seq ->
if seq > len then
return `Eof
else if seq = 0 then
return `NotFound
else
let (_,uid,file) = List.nth uids (seq - 1)
in (size t seq uid file)
| `UID uid ->
try
let (seq,uid,file) = find uid uids in (size t seq uid file)
with _ ->
let (_,u,_) = List.nth uids (len - 1) in
if uid > u then
return `Eof
else
return `NotFound
end
let delete_message t position =
fetch_uidlist t >>= fun uids ->
get_file t position uids >>= function
| `Ok (_,uid,_,file) ->
let uids = List.filter (fun (_,u,_) -> u <> uid) uids in
update_uidlist t uids >>= fun () ->
Lwt_unix.unlink (current t file)
| _ -> return ()
let fetch_ t position uids =
let open Lightparsemail in
Printexc.record_backtrace true;
get_file t position uids >>= function
| `Ok (_,uid,size,file) ->
let (internal_date,size,modseq,flags) = message_file_name_to_data t.mailbox file in
let metadata = {uid;modseq;internal_date;size;flags} in
let lazy_read = Lazy.from_fun (fun () ->
let t1 = Unix.gettimeofday () in
let path = current t file in
let open Unix in
Lwt_io.with_file path ~flags:[O_NONBLOCK;O_RDONLY] ~mode:Lwt_io.Input (fun ci ->
Lwt_io.read ci
) >>= fun msg ->
let msg = decrypt t msg in
Stats.add_readt (Unix.gettimeofday() -. t1);
return msg) in
let lazy_message =
Lazy.from_fun (fun () ->
Lazy.force lazy_read >>= fun buffer ->
if t.config.maildir_parse then
return (Message.from_parsed_message_with_header buffer)
else
Message.parse buffer
)
in
let lazy_metadata = Lazy.from_fun (fun () -> return metadata) in
return (`Ok (Lazy_message.build_lazy_message_inst (module LazyMaildirMessage)
(lazy_read, lazy_message, lazy_metadata)))
| `Eof -> return `Eof
| `NotFound -> return `NotFound
let total_fetch = ref 0.
let fetch t position =
fetch_uidlist t >>= fun uids ->
fetch_ t position uids
let fetch_message_metadata t position =
fetch_uidlist t >>= fun uids ->
get_file t position uids >>= function
| `Ok (_,uid,size,file) ->
let (internal_date,_,modseq,flags) = message_file_name_to_data t.mailbox file in
return (`Ok {uid; modseq; internal_date; size; flags})
| `Eof -> return `Eof
| `NotFound -> return `NotFound
let store t position message_metadata =
fetch_uidlist t >>= fun uids ->
get_file t position uids >>= function
| `Ok (seq,uid,_,src) ->
let dst = update_message_file_name (MaildirPath.to_maildir t.mailbox) src message_metadata in
Lwt_unix.rename (current t src) (current t dst) >>= fun () ->
let uids = List.fold_right (fun (s,u,f) acc ->
if u = uid then
(s,u,dst) :: acc
else
(s,u,f) :: acc
) uids [] in
update_uidlist t uids
| _ -> return ()
let store_mailbox_metadata t mailbox_metadata =
update_mailbox_metadata t mailbox_metadata
let copy t pos t2 message_metadata =
fetch t pos >>= function
| `Eof | `NotFound -> return ()
| `Ok (module LazyMessage) ->
LazyMessage.LazyMessage.get_postmark LazyMessage.this >>= fun postmark ->
LazyMessage.LazyMessage.get_email LazyMessage.this >>= fun (module LE:LazyEmail_inst) ->
LE.LazyEmail.to_string LE.this >>= fun email ->
let message = String.concat Email_parse.crlf [postmark ; email] in
append t2 message message_metadata
let commit t =
return ()
let uid_to_seq t uid =
fetch_uidlist t >>= fun uids ->
get_file t (`UID uid) uids >>= function
| `Ok (seq,_,_,_) -> return (Some seq)
| _ -> return None
let create_account t =
let path = subscribe_path t.config.mail_path t.user in
Utils.exists path Unix.S_REG >>= fun res ->
if res then
return `Exists
else (
let open Unix in
Lwt_unix.openfile path [O_NONBLOCK;O_WRONLY;O_CREAT] 0o664 >>= fun fd ->
Lwt_unix.close fd >>
write_subscribe path [] >>
return `Ok
)
let delete_account t =
let path = subscribe_path t.config.mail_path t.user in
Lwt_unix.system ("rm -rf " ^ path) >>= fun _ ->
return ()
end
|
27624946515b503d90bdcb4346b54b6316e31b6247a9356571676ba2e696211b | charJe/cl-yxorp | threads.lisp | (in-package #:yxorp)
(defvar *threads*-lock (bt:make-lock))
(defvar *threads* (list))
(defun track-thread (thread)
(bt:with-lock-held (*threads*-lock)
(push (tg:make-weak-pointer thread)
*threads*)))
(defun map-threads (function)
(declare (type function function))
(bt:with-lock-held (*threads*-lock)
(setq *threads* (delete-if-not 'tg:weak-pointer-value
*threads*))
(setq *threads* (delete-if-not
(lambda (pointer)
(-> pointer
tg:weak-pointer-value
bt:thread-alive-p))
*threads*))
(map 'list
(lambda (weak-pointer)
(funcall function (tg:weak-pointer-value weak-pointer)))
*threads*)))
| null | https://raw.githubusercontent.com/charJe/cl-yxorp/d2e8f9304549e47ae5c7fa35a6b114804603eac9/threads.lisp | lisp | (in-package #:yxorp)
(defvar *threads*-lock (bt:make-lock))
(defvar *threads* (list))
(defun track-thread (thread)
(bt:with-lock-held (*threads*-lock)
(push (tg:make-weak-pointer thread)
*threads*)))
(defun map-threads (function)
(declare (type function function))
(bt:with-lock-held (*threads*-lock)
(setq *threads* (delete-if-not 'tg:weak-pointer-value
*threads*))
(setq *threads* (delete-if-not
(lambda (pointer)
(-> pointer
tg:weak-pointer-value
bt:thread-alive-p))
*threads*))
(map 'list
(lambda (weak-pointer)
(funcall function (tg:weak-pointer-value weak-pointer)))
*threads*)))
| |
a4df91899b6c1c88b5ba50e0557db38e16f652a7409316d8500a5cb07fc35ebb | TikhonJelvis/Simple-Prolog | Main.hs | module Main where
import Control.Monad (foldM, when)
import Control.Applicative ((<$), (<$>), (<*))
import Data.List (intercalate)
import qualified System.Environment as Env
import System.IO (hFlush, stdout)
import Text.ParserCombinators.Parsec (ParseError, parse)
import Prolog.Interpreter
import Prolog.Parse
type Parsed = Either ParseError
showResult :: Predicate -> [MGU] -> [String]
showResult _ [] = ["No"]
showResult q res = showMgu . filter (contains (Pred q) . Var . fst) . simplify . reverse <$> res
where showMgu [] = "Yes"
showMgu mgu = intercalate " " $ map showBinding mgu
showBinding (n,v) = showName n ++ " = " ++ showVal v
showName (Name 0 n) = n
showName (Name i n) = n ++ "_" ++ show i
showVal (Atom atom) = atom
showVal (Var n) = showName n
showVal (Pred p) = showPred p
showPred list@(Predicate _ "cons" _) = "[" ++ showList list ++ "]"
showPred (Predicate _ n b) = n ++ "(" ++ intercalate ", " (showVal <$> b) ++ ")"
showList (Predicate _ _ [a, b]) = showVal a ++ rest b
where rest (Pred pr@(Predicate _ "cons" _)) = ", " ++ showList pr
rest (Atom "nil") = ""
rest term = "|" ++ showVal term
repl :: String -> (String -> IO ()) -> IO ()
repl prompt action = putStr prompt >> hFlush stdout >> getLine >>= go
where go "quit" = return ()
go inp = action inp >> repl prompt action
main :: IO ()
main = do args <- Env.getArgs
case args of
[] -> putStrLn "Please specify a file to run."
[file] -> run file
_ -> putStrLn "Please only specify one file!"
run :: FilePath -> IO ()
run file = do source <- readFile file
let program = parse rules file source
repl "?- " $ go . extractQuery program
where go (Left err) = putStrLn $ "Error: " ++ show err
go (Right (prog, q)) = printResults q $ resolve q prog
extractQuery :: Parsed [Rule] -> String -> Parsed ([Rule], Predicate)
extractQuery program input = do source <- program
queries <- parse query "<interactive>" input
let (q,r) = disjoin queries
return (r:source, q)
printResults :: Predicate -> [MGU] -> IO ()
printResults q a = go $ showResult q a
where go [] = return ()
go (r:rs) = putStr r >> hFlush stdout >> getLine >>= \ l -> when (';' `elem` l) $ go rs
| null | https://raw.githubusercontent.com/TikhonJelvis/Simple-Prolog/8dc7a23e41079155f747ffcb3f666fc38b390b4d/src/Main.hs | haskell | module Main where
import Control.Monad (foldM, when)
import Control.Applicative ((<$), (<$>), (<*))
import Data.List (intercalate)
import qualified System.Environment as Env
import System.IO (hFlush, stdout)
import Text.ParserCombinators.Parsec (ParseError, parse)
import Prolog.Interpreter
import Prolog.Parse
type Parsed = Either ParseError
showResult :: Predicate -> [MGU] -> [String]
showResult _ [] = ["No"]
showResult q res = showMgu . filter (contains (Pred q) . Var . fst) . simplify . reverse <$> res
where showMgu [] = "Yes"
showMgu mgu = intercalate " " $ map showBinding mgu
showBinding (n,v) = showName n ++ " = " ++ showVal v
showName (Name 0 n) = n
showName (Name i n) = n ++ "_" ++ show i
showVal (Atom atom) = atom
showVal (Var n) = showName n
showVal (Pred p) = showPred p
showPred list@(Predicate _ "cons" _) = "[" ++ showList list ++ "]"
showPred (Predicate _ n b) = n ++ "(" ++ intercalate ", " (showVal <$> b) ++ ")"
showList (Predicate _ _ [a, b]) = showVal a ++ rest b
where rest (Pred pr@(Predicate _ "cons" _)) = ", " ++ showList pr
rest (Atom "nil") = ""
rest term = "|" ++ showVal term
repl :: String -> (String -> IO ()) -> IO ()
repl prompt action = putStr prompt >> hFlush stdout >> getLine >>= go
where go "quit" = return ()
go inp = action inp >> repl prompt action
main :: IO ()
main = do args <- Env.getArgs
case args of
[] -> putStrLn "Please specify a file to run."
[file] -> run file
_ -> putStrLn "Please only specify one file!"
run :: FilePath -> IO ()
run file = do source <- readFile file
let program = parse rules file source
repl "?- " $ go . extractQuery program
where go (Left err) = putStrLn $ "Error: " ++ show err
go (Right (prog, q)) = printResults q $ resolve q prog
extractQuery :: Parsed [Rule] -> String -> Parsed ([Rule], Predicate)
extractQuery program input = do source <- program
queries <- parse query "<interactive>" input
let (q,r) = disjoin queries
return (r:source, q)
printResults :: Predicate -> [MGU] -> IO ()
printResults q a = go $ showResult q a
where go [] = return ()
go (r:rs) = putStr r >> hFlush stdout >> getLine >>= \ l -> when (';' `elem` l) $ go rs
| |
a72af871d1eecea416f0ff73d74ba0f89d6fff74aefb8a1d519f561eadbc37de | ktakashi/sagittarius-scheme | inline.scm | part of Sagittarius Scheme
(library (core inline)
(export define-inliner ;; to add inliner into existing procedures
define-inline ;; to define inliners *and* procedures.
;; not export this for now.
;;define-raw-inliner
)
(import (core)
(core errors)
(core base)
(core syntax)
(sagittarius)
(sagittarius compiler)
(sagittarius compiler procedure)
(sagittarius compiler util)
(sagittarius vm))
;; trick to get pass1 from compiler
(define pass1 (let ((lib (find-library '(sagittarius compiler) #f)))
(gloc-ref (find-binding lib 'pass1 #f))))
(define-syntax define-raw-inliner
(lambda (x)
(define (rename-it lib form)
(define k (make-global-identifier 'template
(find-library (syntax->datum lib) #f)))
(define seen (make-eq-hashtable))
(define (rename id)
(let ((i (datum->syntax k (syntax->datum id))))
(hashtable-set! seen id i)
i))
(let loop ((form form))
(syntax-case form ()
(() '())
((a . d) (cons (loop #'a) (loop #'d)))
(i (identifier? #'i) (or (hashtable-ref seen #'i) (rename #'i)))
(e #'e))))
(syntax-case x ()
((k name library where? ?inliner)
(with-syntax ((inline (if (and (eq? (syntax->datum #'where?) :origin)
;; library can be #f
#'library)
(rename-it #'library #'?inliner)
#'?inliner))
(debug-name (datum->syntax #'k
(string->symbol (format "inliner/~a"
(datum name))))))
#'(define dummy
(let* ((proc (find-procedure 'name
(if 'library
'library
(current-library))))
(orig (procedure-inliner proc))
(inliner inline)
(debug-name (lambda (form p1env)
(define (const-value expr)
(let ((iform (pass1 expr p1env)))
;; $CONST = #($CONST value)
(if (eqv? (vector-ref iform 0) $CONST)
(vector-ref iform 1)
(undefined))))
(let ((form2 (inliner form const-value)))
(if (undefined? form2)
(if orig
(orig form p1env)
;; return undefined so that
;; compiler just compiles to
;; $call
form2)
;; must return iform
(pass1 form2 p1env))))))
(when (integer? orig)
(error 'name "Can't overwrite insn inliner"))
(procedure-inliner-set! proc debug-name)))))
((k name library ?inliner)
#'(k name library #f ?inliner)))))
(define-syntax define-inliner
(lambda (x)
(define (parse patterns acc)
(syntax-case patterns ()
(((p f t) rest ...)
(parse (cdr patterns) (cons (list #'p #'f #'t) acc)))
(((p t) rest ...)
(parse (cdr patterns) (cons (list #'p #'#t #'t) acc)))
(() (reverse! acc))))
(syntax-case x ()
((_ name lib where? pattern* ...)
(memq (syntax->datum #'where?) '(#f :origin))
(with-syntax ((((pattern fender template) ...)
(parse #'(pattern* ...) '())))
#'(define-raw-inliner name lib where?
(lambda (form const-value)
(syntax-case form ()
(pattern fender (syntax template)) ...
(_ (undefined)))))))
((k name lib pattern* ...)
#'(k name lib #f pattern* ...)))))
;; for convenience
we define 2 things , one is a macro which is the real name
;; the other one is actual implementation. for debugging purpose
;; we use syntax-case to generate implementation name.
(define-syntax define-inline
(lambda (x)
(define (actual-name name)
(string->symbol (format "~~~a" (syntax->datum name))))
(syntax-case x ()
((me (name . formals) body ...)
(with-syntax ((%impl (datum->syntax #'me (actual-name #'name))))
#'(begin
#;(define-syntax name
(lambda (x)
(syntax-case x ()
((_ args (... ...))
;; compiler will inline this
#'((lambda formals body ...) args (... ...)))
(k (identifier? #'k) #'%impl))))
(define (name . formals) body ...)
;; do we need this?
(define-raw-inliner name #f
(lambda (form const-value)
(syntax-case form ()
((_ args (... ...))
#'((lambda formals body ...) args (... ...))))))))))))
)
| null | https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/bbdd71f01e8bfe8e25998f5239eb1a3b33b02ac1/lib/core/inline.scm | scheme | to add inliner into existing procedures
to define inliners *and* procedures.
not export this for now.
define-raw-inliner
trick to get pass1 from compiler
library can be #f
$CONST = #($CONST value)
return undefined so that
compiler just compiles to
$call
must return iform
for convenience
the other one is actual implementation. for debugging purpose
we use syntax-case to generate implementation name.
(define-syntax name
compiler will inline this
do we need this? | part of Sagittarius Scheme
(library (core inline)
)
(import (core)
(core errors)
(core base)
(core syntax)
(sagittarius)
(sagittarius compiler)
(sagittarius compiler procedure)
(sagittarius compiler util)
(sagittarius vm))
(define pass1 (let ((lib (find-library '(sagittarius compiler) #f)))
(gloc-ref (find-binding lib 'pass1 #f))))
(define-syntax define-raw-inliner
(lambda (x)
(define (rename-it lib form)
(define k (make-global-identifier 'template
(find-library (syntax->datum lib) #f)))
(define seen (make-eq-hashtable))
(define (rename id)
(let ((i (datum->syntax k (syntax->datum id))))
(hashtable-set! seen id i)
i))
(let loop ((form form))
(syntax-case form ()
(() '())
((a . d) (cons (loop #'a) (loop #'d)))
(i (identifier? #'i) (or (hashtable-ref seen #'i) (rename #'i)))
(e #'e))))
(syntax-case x ()
((k name library where? ?inliner)
(with-syntax ((inline (if (and (eq? (syntax->datum #'where?) :origin)
#'library)
(rename-it #'library #'?inliner)
#'?inliner))
(debug-name (datum->syntax #'k
(string->symbol (format "inliner/~a"
(datum name))))))
#'(define dummy
(let* ((proc (find-procedure 'name
(if 'library
'library
(current-library))))
(orig (procedure-inliner proc))
(inliner inline)
(debug-name (lambda (form p1env)
(define (const-value expr)
(let ((iform (pass1 expr p1env)))
(if (eqv? (vector-ref iform 0) $CONST)
(vector-ref iform 1)
(undefined))))
(let ((form2 (inliner form const-value)))
(if (undefined? form2)
(if orig
(orig form p1env)
form2)
(pass1 form2 p1env))))))
(when (integer? orig)
(error 'name "Can't overwrite insn inliner"))
(procedure-inliner-set! proc debug-name)))))
((k name library ?inliner)
#'(k name library #f ?inliner)))))
(define-syntax define-inliner
(lambda (x)
(define (parse patterns acc)
(syntax-case patterns ()
(((p f t) rest ...)
(parse (cdr patterns) (cons (list #'p #'f #'t) acc)))
(((p t) rest ...)
(parse (cdr patterns) (cons (list #'p #'#t #'t) acc)))
(() (reverse! acc))))
(syntax-case x ()
((_ name lib where? pattern* ...)
(memq (syntax->datum #'where?) '(#f :origin))
(with-syntax ((((pattern fender template) ...)
(parse #'(pattern* ...) '())))
#'(define-raw-inliner name lib where?
(lambda (form const-value)
(syntax-case form ()
(pattern fender (syntax template)) ...
(_ (undefined)))))))
((k name lib pattern* ...)
#'(k name lib #f pattern* ...)))))
we define 2 things , one is a macro which is the real name
(define-syntax define-inline
(lambda (x)
(define (actual-name name)
(string->symbol (format "~~~a" (syntax->datum name))))
(syntax-case x ()
((me (name . formals) body ...)
(with-syntax ((%impl (datum->syntax #'me (actual-name #'name))))
#'(begin
(lambda (x)
(syntax-case x ()
((_ args (... ...))
#'((lambda formals body ...) args (... ...)))
(k (identifier? #'k) #'%impl))))
(define (name . formals) body ...)
(define-raw-inliner name #f
(lambda (form const-value)
(syntax-case form ()
((_ args (... ...))
#'((lambda formals body ...) args (... ...))))))))))))
)
|
2b904192145b0da71d687d3517d8acc023594834dcfb25dbb9b3482d44835f73 | ghcjs/jsaddle-dom | MediaDevices.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.MediaDevices
(enumerateDevices, enumerateDevices_, getSupportedConstraints,
getSupportedConstraints_, getUserMedia, getUserMedia_,
devicechange, MediaDevices(..), gTypeMediaDevices)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/MediaDevices.enumerateDevices Mozilla MediaDevices.enumerateDevices documentation >
enumerateDevices ::
(MonadDOM m) => MediaDevices -> m [MediaDeviceInfo]
enumerateDevices self
= liftDOM
(((self ^. jsf "enumerateDevices" ()) >>= readPromise) >>=
fromJSArrayUnchecked)
| < -US/docs/Web/API/MediaDevices.enumerateDevices Mozilla MediaDevices.enumerateDevices documentation >
enumerateDevices_ :: (MonadDOM m) => MediaDevices -> m ()
enumerateDevices_ self
= liftDOM (void (self ^. jsf "enumerateDevices" ()))
| < -US/docs/Web/API/MediaDevices.getSupportedConstraints Mozilla MediaDevices.getSupportedConstraints documentation >
getSupportedConstraints ::
(MonadDOM m) => MediaDevices -> m MediaTrackSupportedConstraints
getSupportedConstraints self
= liftDOM
((self ^. jsf "getSupportedConstraints" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/MediaDevices.getSupportedConstraints Mozilla MediaDevices.getSupportedConstraints documentation >
getSupportedConstraints_ :: (MonadDOM m) => MediaDevices -> m ()
getSupportedConstraints_ self
= liftDOM (void (self ^. jsf "getSupportedConstraints" ()))
| < -US/docs/Web/API/MediaDevices.getUserMedia Mozilla MediaDevices.getUserMedia documentation >
getUserMedia ::
(MonadDOM m) =>
MediaDevices -> Maybe MediaStreamConstraints -> m MediaStream
getUserMedia self constraints
= liftDOM
(((self ^. jsf "getUserMedia" [toJSVal constraints]) >>=
readPromise)
>>= fromJSValUnchecked)
| < -US/docs/Web/API/MediaDevices.getUserMedia Mozilla MediaDevices.getUserMedia documentation >
getUserMedia_ ::
(MonadDOM m) =>
MediaDevices -> Maybe MediaStreamConstraints -> m ()
getUserMedia_ self constraints
= liftDOM (void (self ^. jsf "getUserMedia" [toJSVal constraints]))
-- | <-US/docs/Web/API/MediaDevices.ondevicechange Mozilla MediaDevices.ondevicechange documentation>
devicechange :: EventName MediaDevices ondevicechange
devicechange = unsafeEventName (toJSString "devicechange")
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/MediaDevices.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
| <-US/docs/Web/API/MediaDevices.ondevicechange Mozilla MediaDevices.ondevicechange documentation> | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.MediaDevices
(enumerateDevices, enumerateDevices_, getSupportedConstraints,
getSupportedConstraints_, getUserMedia, getUserMedia_,
devicechange, MediaDevices(..), gTypeMediaDevices)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/MediaDevices.enumerateDevices Mozilla MediaDevices.enumerateDevices documentation >
enumerateDevices ::
(MonadDOM m) => MediaDevices -> m [MediaDeviceInfo]
enumerateDevices self
= liftDOM
(((self ^. jsf "enumerateDevices" ()) >>= readPromise) >>=
fromJSArrayUnchecked)
| < -US/docs/Web/API/MediaDevices.enumerateDevices Mozilla MediaDevices.enumerateDevices documentation >
enumerateDevices_ :: (MonadDOM m) => MediaDevices -> m ()
enumerateDevices_ self
= liftDOM (void (self ^. jsf "enumerateDevices" ()))
| < -US/docs/Web/API/MediaDevices.getSupportedConstraints Mozilla MediaDevices.getSupportedConstraints documentation >
getSupportedConstraints ::
(MonadDOM m) => MediaDevices -> m MediaTrackSupportedConstraints
getSupportedConstraints self
= liftDOM
((self ^. jsf "getSupportedConstraints" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/MediaDevices.getSupportedConstraints Mozilla MediaDevices.getSupportedConstraints documentation >
getSupportedConstraints_ :: (MonadDOM m) => MediaDevices -> m ()
getSupportedConstraints_ self
= liftDOM (void (self ^. jsf "getSupportedConstraints" ()))
| < -US/docs/Web/API/MediaDevices.getUserMedia Mozilla MediaDevices.getUserMedia documentation >
getUserMedia ::
(MonadDOM m) =>
MediaDevices -> Maybe MediaStreamConstraints -> m MediaStream
getUserMedia self constraints
= liftDOM
(((self ^. jsf "getUserMedia" [toJSVal constraints]) >>=
readPromise)
>>= fromJSValUnchecked)
| < -US/docs/Web/API/MediaDevices.getUserMedia Mozilla MediaDevices.getUserMedia documentation >
getUserMedia_ ::
(MonadDOM m) =>
MediaDevices -> Maybe MediaStreamConstraints -> m ()
getUserMedia_ self constraints
= liftDOM (void (self ^. jsf "getUserMedia" [toJSVal constraints]))
devicechange :: EventName MediaDevices ondevicechange
devicechange = unsafeEventName (toJSString "devicechange")
|
27fb98a1d8c20eaef0e29087909eb3c4f832276e9259c4c8155e3130c435558f | Chris00/ocaml-gammu | discover.ml | module C = Configurator.V1
let error_sys sys =
C.die "System %S currently not supported. Please \
contact the OCaml gammu developers." sys
let cflags_default sys =
if sys = "linux" then
["-O3"; "-fPIC"; "-DPIC"; "-I/usr/include/gammu"]
else if sys = "mingw64" then
["-O3"; "-fPIC"; "-DPIC"; "-DHAVE_SSIZE_T"; "-IC:/Gammu/include/gammu"]
else if sys = "msvc" || sys = "win64" then
["/I"; "C:\\Gammu\\include\\gammu"]
else error_sys sys
let libs_default sys =
if sys = "linux" then ["-lGammu"; "-lm"]
else if sys = "msvc" || sys = "win64" then
["C:\\Gammu\\lib\\Gammu.lib"]
else if sys = "mingw64" then
["C:\\Gammu\\lib\\Gammu.lib"; "-verbose"]
else error_sys sys
let configure t =
let module P = C.Pkg_config in
let sys = C.ocaml_config_var_exn t "system"in
let pkg = match P.get t with
| Some pkg_config -> P.query pkg_config ~package:"gammu"
| None -> None in
let cflags = match Sys.getenv "OCAML_GAMMU_CFLAGS" with
| alt_cflags -> C.Flags.extract_blank_separated_words alt_cflags
| exception Not_found ->
match pkg with Some p -> p.P.cflags
| None -> cflags_default sys in
let libs = match Sys.getenv "OCAML_GAMMU_LIBS" with
| alt_libs -> C.Flags.extract_blank_separated_words alt_libs
| exception Not_found ->
match pkg with Some p -> p.P.libs
| None -> libs_default sys in
(* Check for debug environment variable *)
let debug = try ignore(Sys.getenv "OCAML_GAMMU_DEBUG"); true
with _ -> false in
let cflags =
if debug then
(if Sys.win32 then "/DCAML_GAMMU_DEBUG"
else "-DCAML_GAMMU_DEBUG") :: cflags
else cflags in
C.Flags.write_sexp "c_flags.sexp" cflags;
C.Flags.write_sexp "c_library_flags.sexp" libs
let () =
C.main ~name:"discover" configure
| null | https://raw.githubusercontent.com/Chris00/ocaml-gammu/ad38c6aff25bda8aa6da1db5fdfe61a224b00250/config/discover.ml | ocaml | Check for debug environment variable | module C = Configurator.V1
let error_sys sys =
C.die "System %S currently not supported. Please \
contact the OCaml gammu developers." sys
let cflags_default sys =
if sys = "linux" then
["-O3"; "-fPIC"; "-DPIC"; "-I/usr/include/gammu"]
else if sys = "mingw64" then
["-O3"; "-fPIC"; "-DPIC"; "-DHAVE_SSIZE_T"; "-IC:/Gammu/include/gammu"]
else if sys = "msvc" || sys = "win64" then
["/I"; "C:\\Gammu\\include\\gammu"]
else error_sys sys
let libs_default sys =
if sys = "linux" then ["-lGammu"; "-lm"]
else if sys = "msvc" || sys = "win64" then
["C:\\Gammu\\lib\\Gammu.lib"]
else if sys = "mingw64" then
["C:\\Gammu\\lib\\Gammu.lib"; "-verbose"]
else error_sys sys
let configure t =
let module P = C.Pkg_config in
let sys = C.ocaml_config_var_exn t "system"in
let pkg = match P.get t with
| Some pkg_config -> P.query pkg_config ~package:"gammu"
| None -> None in
let cflags = match Sys.getenv "OCAML_GAMMU_CFLAGS" with
| alt_cflags -> C.Flags.extract_blank_separated_words alt_cflags
| exception Not_found ->
match pkg with Some p -> p.P.cflags
| None -> cflags_default sys in
let libs = match Sys.getenv "OCAML_GAMMU_LIBS" with
| alt_libs -> C.Flags.extract_blank_separated_words alt_libs
| exception Not_found ->
match pkg with Some p -> p.P.libs
| None -> libs_default sys in
let debug = try ignore(Sys.getenv "OCAML_GAMMU_DEBUG"); true
with _ -> false in
let cflags =
if debug then
(if Sys.win32 then "/DCAML_GAMMU_DEBUG"
else "-DCAML_GAMMU_DEBUG") :: cflags
else cflags in
C.Flags.write_sexp "c_flags.sexp" cflags;
C.Flags.write_sexp "c_library_flags.sexp" libs
let () =
C.main ~name:"discover" configure
|
d4b600d069a14aee3c4856e791245c226a21c7b41c15b36ec539ca711b7a9f73 | lancelet/wgpu-hs | WGPUPresentMode.hs | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE PatternSynonyms #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE NoImplicitPrelude #
-- This file was generated by wgpu-raw-hs-codegen on:
2021 - 08 - 25T10:02:03.522705
-- Using wgpu-native git hash:
b10496e7eed9349f0fd541e6dfe5029cb436de74 wgpu - native ( )
module WGPU.Raw.Generated.Enum.WGPUPresentMode where
import Data.Word (Word32)
import Foreign (Storable)
import Prelude (Eq, Num, Show)
newtype WGPUPresentMode = WGPUPresentMode Word32
deriving (Eq, Show, Num, Storable)
pattern Immediate :: forall a. (Eq a, Num a) => a
pattern Immediate = 0x00000000
pattern Mailbox :: forall a. (Eq a, Num a) => a
pattern Mailbox = 0x00000001
pattern Fifo :: forall a. (Eq a, Num a) => a
pattern Fifo = 0x00000002
| null | https://raw.githubusercontent.com/lancelet/wgpu-hs/42d7931cdd793970bf4844906b382d908bbb196f/wgpu-raw-hs/src/WGPU/Raw/Generated/Enum/WGPUPresentMode.hs | haskell | This file was generated by wgpu-raw-hs-codegen on:
Using wgpu-native git hash: | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE PatternSynonyms #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE NoImplicitPrelude #
2021 - 08 - 25T10:02:03.522705
b10496e7eed9349f0fd541e6dfe5029cb436de74 wgpu - native ( )
module WGPU.Raw.Generated.Enum.WGPUPresentMode where
import Data.Word (Word32)
import Foreign (Storable)
import Prelude (Eq, Num, Show)
newtype WGPUPresentMode = WGPUPresentMode Word32
deriving (Eq, Show, Num, Storable)
pattern Immediate :: forall a. (Eq a, Num a) => a
pattern Immediate = 0x00000000
pattern Mailbox :: forall a. (Eq a, Num a) => a
pattern Mailbox = 0x00000001
pattern Fifo :: forall a. (Eq a, Num a) => a
pattern Fifo = 0x00000002
|
7b0e3e690190e7d58fbfacc3fd4b412f6739c695a0e06a0fbe6c8731a2e799ca | rtoy/ansi-cl-tests | map.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sat Aug 17 20:54:48 2002
;;;; Contains: Tests for the MAP function
(in-package :cl-test)
(deftest map-array.1
(map 'list #'1+ #(1 2 3 4))
(2 3 4 5))
(deftest map-array.2
(map 'vector #'+ #(1 2 3 4) #(6 6 6 6))
#(7 8 9 10))
(deftest map-array.3
(map 'vector #'+ #(1 2 3 4 5) #(6 6 6 6))
#(7 8 9 10))
(deftest map-array.4
(map 'vector #'+ #(1 2 3 4) #(6 6 6 6 6))
#(7 8 9 10))
(deftest map-array.5
(map '(vector *) #'+ #(1 2 3 4) #(6 6 6 6))
#(7 8 9 10))
(deftest map-array.6
(map '(vector * 4) #'+ #(1 2 3 4) #(6 6 6 6))
#(7 8 9 10))
;;; (deftest map-array.7
;;; (map 'array #'identity '(a b c d e f))
;;; #(a b c d e f))
;;; (deftest map-array.8
;;; (map 'simple-array #'identity '(a b c d e f))
;;; #(a b c d e f))
(deftest map-array.9
(map 'simple-vector #'identity '(a b c d e f))
#(a b c d e f))
(deftest map-array.10
(map 'simple-vector #'cons '(a b c d e f) #(1 2 3 4 5 6))
#((a . 1) (b . 2) (c . 3) (d . 4) (e . 5) (f . 6)))
(deftest map-array.11
(map 'vector #'identity '(#\a #\b #\c #\d #\e))
#(#\a #\b #\c #\d #\e))
(deftest map-array.12
(map 'vector #'identity "abcde")
#(#\a #\b #\c #\d #\e))
(deftest map-array.13
(map 'vector #'identity #*000001)
#(0 0 0 0 0 1))
(deftest map-array.14
(map 'list #'identity #*000001)
(0 0 0 0 0 1))
(deftest map-bit-vector.15
(map 'bit-vector #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.16
(map 'simple-bit-vector #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.17
(map '(vector bit) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.18
(map '(simple-vector *) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.19
(map '(bit-vector 6) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.20
(map '(bit-vector *) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.21
(map '(simple-bit-vector 6) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.22
(map '(simple-bit-vector *) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.23
(map '(vector bit 6) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.24
(map '(vector bit *) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.25
(map '(simple-vector 6) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-string.26
(map 'string #'identity '(#\a #\b #\c #\d #\e))
"abcde")
(deftest map-string.27
(map 'string #'identity "abcde")
"abcde")
(deftest map-string.28
(map '(vector character) #'identity '(#\a #\b #\c #\d #\e))
"abcde")
(deftest map-string.29
(map '(vector character 5) #'identity '(#\a #\b #\c #\d #\e))
"abcde")
(deftest map-string.30
(map '(simple-vector 5) #'identity '(#\a #\b #\c #\d #\e))
"abcde")
;;; Use a more elaborate form of the simple-array type specifier
;;; (deftest map-string.31
;;; (map '(simple-array character *) #'identity "abcde")
;;; "abcde")
;;; Use a more elaborate form of the simple-array type specifier
;;; (deftest map-string.32
( map ' ( simple - array character 5 ) # ' identity " abcde " )
;;; "abcde")
(deftest map-nil.33
(let ((a nil))
(values (map nil #'(lambda (x) (push x a)) "abcdef") a))
nil (#\f #\e #\d #\c #\b #\a))
(deftest map-nil.34
(let ((a nil))
(values (map nil #'(lambda (x) (push x a)) '(a b c d e)) a))
nil (e d c b a))
(deftest map-nil.35
(let ((a nil))
(values (map nil #'(lambda (x) (push x a)) #(a b c d e)) a))
nil (e d c b a))
(deftest map-nil.36
(let ((a nil))
(values (map nil #'(lambda (x) (push x a)) #*001011110) a))
nil (0 1 1 1 1 0 1 0 0))
(deftest map-null.1
(map 'null #'identity nil)
nil)
(deftest map-cons.1
(map 'cons #'identity '(a b c))
(a b c))
(deftest map.37
(map 'simple-string #'identity '(#\a #\b #\c))
"abc")
(deftest map.38
(map '(simple-string) #'identity '(#\a #\b #\c))
"abc")
(deftest map.39
(map '(simple-string *) #'identity '(#\a #\b #\c))
"abc")
(deftest map.40
(map '(simple-string 3) #'identity '(#\a #\b #\c))
"abc")
(deftest map.41
(map '(base-string) #'identity '(#\a #\b #\c))
"abc")
(deftest map.42
(map '(base-string *) #'identity '(#\a #\b #\c))
"abc")
(deftest map.43
(map '(base-string 3) #'identity '(#\a #\b #\c))
"abc")
(deftest map.44
(map 'simple-base-string #'identity '(#\a #\b #\c))
"abc")
(deftest map.45
(map '(simple-base-string) #'identity '(#\a #\b #\c))
"abc")
(deftest map.46
(map '(simple-base-string *) #'identity '(#\a #\b #\c))
"abc")
(deftest map.47
(map '(simple-base-string 3) #'identity '(#\a #\b #\c))
"abc")
(deftest map.48
:notes (:result-type-element-type-by-subtype)
(let ((type '(or (vector t 10) (vector t 5))))
(if (subtypep type '(vector t))
(equalpt (map type #'identity '(1 2 3 4 5)) #(1 2 3 4 5))
t))
t)
;;; Error tests
(deftest map.error.1
(signals-error-always (map 'symbol #'identity '(a b c)) type-error)
t t)
(deftest map.error.1a
(signals-error (map 'symbol #'identity '(a b c)) type-error)
t)
(deftest map.error.2
(signals-error (map '(vector * 8) #'identity '(a b c)) type-error)
t)
(deftest map.error.3
(signals-error (map 'list #'identity '(a b . c)) type-error)
t)
(deftest map.error.4
(signals-error (map) program-error)
t)
(deftest map.error.5
(signals-error (map 'list) program-error)
t)
(deftest map.error.6
(signals-error (map 'list #'null) program-error)
t)
(deftest map.error.7
(signals-error (map 'list #'cons '(a b c d)) program-error)
t)
(deftest map.error.8
(signals-error (map 'list #'cons '(a b c d) '(1 2 3 4) '(5 6 7 8))
program-error)
t)
(deftest map.error.9
(signals-error (map 'list #'car '(a b c d)) type-error)
t)
(deftest map.error.10
:notes (:result-type-element-type-by-subtype)
(let ((type '(or (vector bit) (vector t))))
(if (subtypep type 'vector)
(eval `(signals-error-always (map ',type #'identity '(1 0 1)) error))
(values t t)))
t t)
(deftest map.error.11
(let ((type '(or (vector t 5) (vector t 10))))
(if (subtypep type 'vector)
(eval `(signals-error (map ',type #'identity '(1 2 3 4 5 6)) type-error))
t))
t)
(deftest map.error.12
(check-type-error #'(lambda (x) (map 'list #'identity x)) #'sequencep)
nil)
(deftest map.error.13
(check-type-error #'(lambda (x) (map 'vector #'cons '(a b c d) x)) #'sequencep)
nil)
;;; Test mapping on arrays with fill pointers
(deftest map.fill.1
(let ((s1 (make-array '(10) :initial-contents '(a b c d e f g h i j)
:fill-pointer 8)))
(map 'list #'identity s1))
(a b c d e f g h))
(deftest map.fill.2
(let ((s1 (make-array '(10) :initial-contents '(a b c d e f g h i j)
:fill-pointer 8)))
(map 'list #'(lambda (x y) x) '(1 2 3 4 5 6 7 8 9 10) s1))
(1 2 3 4 5 6 7 8))
(deftest map.fill.3
(let ((s1 (make-array '(10) :initial-element #\a
:element-type 'character
:fill-pointer 8)))
(map 'string #'identity s1))
"aaaaaaaa")
(deftest map.fill.4
(let ((s1 (make-array '(10) :initial-element #\a
:element-type 'base-char
:fill-pointer 8)))
(map 'list #'(lambda (x y) x) '(1 2 3 4 5 6 7 8 9 10) s1))
(1 2 3 4 5 6 7 8))
(deftest map.fill.5
(let ((s1 (make-array '(10) :initial-element 0
:element-type 'bit
:fill-pointer 8)))
(map 'bit-vector #'identity s1))
#*00000000)
(deftest map.fill.6
(let ((s1 (make-array '(10) :initial-element 1
:element-type 'bit
:fill-pointer 8)))
(map 'list #'(lambda (x y) x) '(1 2 3 4 5 6 7 8 9 10) s1))
(1 2 3 4 5 6 7 8))
Specialized string tests
(deftest map.specialized-string.1
(do-special-strings
(s "abcde" nil)
(let ((s2 (map 'list #'identity s)))
(assert (equal s2 '(#\a #\b #\c #\d #\e)))))
nil)
(deftest map.specialized-string.2
(do-special-strings
(s "abcde" nil)
(let ((s2 (map 'list #'(lambda (x y) y) '(1 2 3 4 5) s)))
(assert (equal s2 '(#\a #\b #\c #\d #\e)))))
nil)
(deftest map.specialized-string.3
(let ((s (map 'base-string #'identity '(#\a #\b #\c))))
(assert (typep s 'base-string))
s)
"abc")
;;; FIXME: Add tests for building strings of other character types
;;; Special vector types
(deftest map.specialized-vector.1
(do-special-integer-vectors
(v #(0 1 1 0 0 1) nil)
(assert (equal (map 'list #'list v v) '((0 0) (1 1) (1 1) (0 0) (0 0) (1 1)))))
nil)
(deftest map.specialized-vector.2
(do-special-integer-vectors
(v #(1 2 3 4 5 6 7) nil)
(assert (equal (map 'list #'identity v) '(1 2 3 4 5 6 7))))
nil)
(deftest map.specialized-vector.3
(do-special-integer-vectors
(v #(-1 -2 -3 -4 -5 -6 -7) nil)
(assert (equal (map 'list #'- v) '(1 2 3 4 5 6 7))))
nil)
(deftest map.specialized-vector.4
(loop for i from 1 to 40
for type = `(unsigned-byte ,i)
for bound = (ash 1 i)
for len = 10
for vals = (loop repeat len collect (random i))
for result = (map `(vector ,type) #'identity vals)
unless (and (= (length result) len)
(every #'eql vals result))
collect (list i vals result))
nil)
(deftest map.specialized-vector.5
(loop for i from 1 to 40
for type = `(signed-byte ,i)
for bound = (ash 1 i)
for len = 10
for vals = (loop repeat len collect (- (random i) (/ bound 2)))
for result = (map `(vector ,type) #'identity vals)
unless (and (= (length result) len)
(every #'eql vals result))
collect (list i vals result))
nil)
(deftest map.specialized-vector.6
(loop for type in '(short-float single-float long-float double-float)
for len = 10
for vals = (loop for i from 1 to len collect (coerce i type))
for result = (map `(vector ,type) #'identity vals)
unless (and (= (length result) len)
(every #'eql vals result))
collect (list type vals result))
nil)
(deftest map.specialized-vector.7
(loop for etype in '(short-float single-float long-float double-float
integer rational)
for type = `(complex ,etype)
for len = 10
for vals = (loop for i from 1 to len collect (complex (coerce i etype)
(coerce (- i) etype)))
for result = (map `(vector ,type) #'identity vals)
unless (and (= (length result) len)
(every #'eql vals result))
collect (list type vals result))
nil)
;;; Order of evaluation tests
(deftest map.order.1
(let ((i 0) a b c d)
(values
(map (progn (setf a (incf i)) 'list)
(progn (setf b (incf i)) #'list)
(progn (setf c (incf i)) '(a b c))
(progn (setf d (incf i)) '(b c d)))
i a b c d))
((a b)(b c)(c d)) 4 1 2 3 4)
;;; Constant folding test
(def-fold-test map.fold.1 (map 'vector #'identity '(a b c)))
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/map.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests for the MAP function
(deftest map-array.7
(map 'array #'identity '(a b c d e f))
#(a b c d e f))
(deftest map-array.8
(map 'simple-array #'identity '(a b c d e f))
#(a b c d e f))
Use a more elaborate form of the simple-array type specifier
(deftest map-string.31
(map '(simple-array character *) #'identity "abcde")
"abcde")
Use a more elaborate form of the simple-array type specifier
(deftest map-string.32
"abcde")
Error tests
Test mapping on arrays with fill pointers
FIXME: Add tests for building strings of other character types
Special vector types
Order of evaluation tests
Constant folding test | Author :
Created : Sat Aug 17 20:54:48 2002
(in-package :cl-test)
(deftest map-array.1
(map 'list #'1+ #(1 2 3 4))
(2 3 4 5))
(deftest map-array.2
(map 'vector #'+ #(1 2 3 4) #(6 6 6 6))
#(7 8 9 10))
(deftest map-array.3
(map 'vector #'+ #(1 2 3 4 5) #(6 6 6 6))
#(7 8 9 10))
(deftest map-array.4
(map 'vector #'+ #(1 2 3 4) #(6 6 6 6 6))
#(7 8 9 10))
(deftest map-array.5
(map '(vector *) #'+ #(1 2 3 4) #(6 6 6 6))
#(7 8 9 10))
(deftest map-array.6
(map '(vector * 4) #'+ #(1 2 3 4) #(6 6 6 6))
#(7 8 9 10))
(deftest map-array.9
(map 'simple-vector #'identity '(a b c d e f))
#(a b c d e f))
(deftest map-array.10
(map 'simple-vector #'cons '(a b c d e f) #(1 2 3 4 5 6))
#((a . 1) (b . 2) (c . 3) (d . 4) (e . 5) (f . 6)))
(deftest map-array.11
(map 'vector #'identity '(#\a #\b #\c #\d #\e))
#(#\a #\b #\c #\d #\e))
(deftest map-array.12
(map 'vector #'identity "abcde")
#(#\a #\b #\c #\d #\e))
(deftest map-array.13
(map 'vector #'identity #*000001)
#(0 0 0 0 0 1))
(deftest map-array.14
(map 'list #'identity #*000001)
(0 0 0 0 0 1))
(deftest map-bit-vector.15
(map 'bit-vector #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.16
(map 'simple-bit-vector #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.17
(map '(vector bit) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.18
(map '(simple-vector *) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.19
(map '(bit-vector 6) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.20
(map '(bit-vector *) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.21
(map '(simple-bit-vector 6) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.22
(map '(simple-bit-vector *) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.23
(map '(vector bit 6) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.24
(map '(vector bit *) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-bit-vector.25
(map '(simple-vector 6) #'identity '(0 0 0 0 0 1))
#*000001)
(deftest map-string.26
(map 'string #'identity '(#\a #\b #\c #\d #\e))
"abcde")
(deftest map-string.27
(map 'string #'identity "abcde")
"abcde")
(deftest map-string.28
(map '(vector character) #'identity '(#\a #\b #\c #\d #\e))
"abcde")
(deftest map-string.29
(map '(vector character 5) #'identity '(#\a #\b #\c #\d #\e))
"abcde")
(deftest map-string.30
(map '(simple-vector 5) #'identity '(#\a #\b #\c #\d #\e))
"abcde")
( map ' ( simple - array character 5 ) # ' identity " abcde " )
(deftest map-nil.33
(let ((a nil))
(values (map nil #'(lambda (x) (push x a)) "abcdef") a))
nil (#\f #\e #\d #\c #\b #\a))
(deftest map-nil.34
(let ((a nil))
(values (map nil #'(lambda (x) (push x a)) '(a b c d e)) a))
nil (e d c b a))
(deftest map-nil.35
(let ((a nil))
(values (map nil #'(lambda (x) (push x a)) #(a b c d e)) a))
nil (e d c b a))
(deftest map-nil.36
(let ((a nil))
(values (map nil #'(lambda (x) (push x a)) #*001011110) a))
nil (0 1 1 1 1 0 1 0 0))
(deftest map-null.1
(map 'null #'identity nil)
nil)
(deftest map-cons.1
(map 'cons #'identity '(a b c))
(a b c))
(deftest map.37
(map 'simple-string #'identity '(#\a #\b #\c))
"abc")
(deftest map.38
(map '(simple-string) #'identity '(#\a #\b #\c))
"abc")
(deftest map.39
(map '(simple-string *) #'identity '(#\a #\b #\c))
"abc")
(deftest map.40
(map '(simple-string 3) #'identity '(#\a #\b #\c))
"abc")
(deftest map.41
(map '(base-string) #'identity '(#\a #\b #\c))
"abc")
(deftest map.42
(map '(base-string *) #'identity '(#\a #\b #\c))
"abc")
(deftest map.43
(map '(base-string 3) #'identity '(#\a #\b #\c))
"abc")
(deftest map.44
(map 'simple-base-string #'identity '(#\a #\b #\c))
"abc")
(deftest map.45
(map '(simple-base-string) #'identity '(#\a #\b #\c))
"abc")
(deftest map.46
(map '(simple-base-string *) #'identity '(#\a #\b #\c))
"abc")
(deftest map.47
(map '(simple-base-string 3) #'identity '(#\a #\b #\c))
"abc")
(deftest map.48
:notes (:result-type-element-type-by-subtype)
(let ((type '(or (vector t 10) (vector t 5))))
(if (subtypep type '(vector t))
(equalpt (map type #'identity '(1 2 3 4 5)) #(1 2 3 4 5))
t))
t)
(deftest map.error.1
(signals-error-always (map 'symbol #'identity '(a b c)) type-error)
t t)
(deftest map.error.1a
(signals-error (map 'symbol #'identity '(a b c)) type-error)
t)
(deftest map.error.2
(signals-error (map '(vector * 8) #'identity '(a b c)) type-error)
t)
(deftest map.error.3
(signals-error (map 'list #'identity '(a b . c)) type-error)
t)
(deftest map.error.4
(signals-error (map) program-error)
t)
(deftest map.error.5
(signals-error (map 'list) program-error)
t)
(deftest map.error.6
(signals-error (map 'list #'null) program-error)
t)
(deftest map.error.7
(signals-error (map 'list #'cons '(a b c d)) program-error)
t)
(deftest map.error.8
(signals-error (map 'list #'cons '(a b c d) '(1 2 3 4) '(5 6 7 8))
program-error)
t)
(deftest map.error.9
(signals-error (map 'list #'car '(a b c d)) type-error)
t)
(deftest map.error.10
:notes (:result-type-element-type-by-subtype)
(let ((type '(or (vector bit) (vector t))))
(if (subtypep type 'vector)
(eval `(signals-error-always (map ',type #'identity '(1 0 1)) error))
(values t t)))
t t)
(deftest map.error.11
(let ((type '(or (vector t 5) (vector t 10))))
(if (subtypep type 'vector)
(eval `(signals-error (map ',type #'identity '(1 2 3 4 5 6)) type-error))
t))
t)
(deftest map.error.12
(check-type-error #'(lambda (x) (map 'list #'identity x)) #'sequencep)
nil)
(deftest map.error.13
(check-type-error #'(lambda (x) (map 'vector #'cons '(a b c d) x)) #'sequencep)
nil)
(deftest map.fill.1
(let ((s1 (make-array '(10) :initial-contents '(a b c d e f g h i j)
:fill-pointer 8)))
(map 'list #'identity s1))
(a b c d e f g h))
(deftest map.fill.2
(let ((s1 (make-array '(10) :initial-contents '(a b c d e f g h i j)
:fill-pointer 8)))
(map 'list #'(lambda (x y) x) '(1 2 3 4 5 6 7 8 9 10) s1))
(1 2 3 4 5 6 7 8))
(deftest map.fill.3
(let ((s1 (make-array '(10) :initial-element #\a
:element-type 'character
:fill-pointer 8)))
(map 'string #'identity s1))
"aaaaaaaa")
(deftest map.fill.4
(let ((s1 (make-array '(10) :initial-element #\a
:element-type 'base-char
:fill-pointer 8)))
(map 'list #'(lambda (x y) x) '(1 2 3 4 5 6 7 8 9 10) s1))
(1 2 3 4 5 6 7 8))
(deftest map.fill.5
(let ((s1 (make-array '(10) :initial-element 0
:element-type 'bit
:fill-pointer 8)))
(map 'bit-vector #'identity s1))
#*00000000)
(deftest map.fill.6
(let ((s1 (make-array '(10) :initial-element 1
:element-type 'bit
:fill-pointer 8)))
(map 'list #'(lambda (x y) x) '(1 2 3 4 5 6 7 8 9 10) s1))
(1 2 3 4 5 6 7 8))
Specialized string tests
(deftest map.specialized-string.1
(do-special-strings
(s "abcde" nil)
(let ((s2 (map 'list #'identity s)))
(assert (equal s2 '(#\a #\b #\c #\d #\e)))))
nil)
(deftest map.specialized-string.2
(do-special-strings
(s "abcde" nil)
(let ((s2 (map 'list #'(lambda (x y) y) '(1 2 3 4 5) s)))
(assert (equal s2 '(#\a #\b #\c #\d #\e)))))
nil)
(deftest map.specialized-string.3
(let ((s (map 'base-string #'identity '(#\a #\b #\c))))
(assert (typep s 'base-string))
s)
"abc")
(deftest map.specialized-vector.1
(do-special-integer-vectors
(v #(0 1 1 0 0 1) nil)
(assert (equal (map 'list #'list v v) '((0 0) (1 1) (1 1) (0 0) (0 0) (1 1)))))
nil)
(deftest map.specialized-vector.2
(do-special-integer-vectors
(v #(1 2 3 4 5 6 7) nil)
(assert (equal (map 'list #'identity v) '(1 2 3 4 5 6 7))))
nil)
(deftest map.specialized-vector.3
(do-special-integer-vectors
(v #(-1 -2 -3 -4 -5 -6 -7) nil)
(assert (equal (map 'list #'- v) '(1 2 3 4 5 6 7))))
nil)
(deftest map.specialized-vector.4
(loop for i from 1 to 40
for type = `(unsigned-byte ,i)
for bound = (ash 1 i)
for len = 10
for vals = (loop repeat len collect (random i))
for result = (map `(vector ,type) #'identity vals)
unless (and (= (length result) len)
(every #'eql vals result))
collect (list i vals result))
nil)
(deftest map.specialized-vector.5
(loop for i from 1 to 40
for type = `(signed-byte ,i)
for bound = (ash 1 i)
for len = 10
for vals = (loop repeat len collect (- (random i) (/ bound 2)))
for result = (map `(vector ,type) #'identity vals)
unless (and (= (length result) len)
(every #'eql vals result))
collect (list i vals result))
nil)
(deftest map.specialized-vector.6
(loop for type in '(short-float single-float long-float double-float)
for len = 10
for vals = (loop for i from 1 to len collect (coerce i type))
for result = (map `(vector ,type) #'identity vals)
unless (and (= (length result) len)
(every #'eql vals result))
collect (list type vals result))
nil)
(deftest map.specialized-vector.7
(loop for etype in '(short-float single-float long-float double-float
integer rational)
for type = `(complex ,etype)
for len = 10
for vals = (loop for i from 1 to len collect (complex (coerce i etype)
(coerce (- i) etype)))
for result = (map `(vector ,type) #'identity vals)
unless (and (= (length result) len)
(every #'eql vals result))
collect (list type vals result))
nil)
(deftest map.order.1
(let ((i 0) a b c d)
(values
(map (progn (setf a (incf i)) 'list)
(progn (setf b (incf i)) #'list)
(progn (setf c (incf i)) '(a b c))
(progn (setf d (incf i)) '(b c d)))
i a b c d))
((a b)(b c)(c d)) 4 1 2 3 4)
(def-fold-test map.fold.1 (map 'vector #'identity '(a b c)))
|
ab68fd1e9b6c92d6cf37796fe76c1ea0c5a22e3881291cd33db8300ebf0cb7f3 | jonase/eastwood | utils.clj | Copyright ( c ) , Rich Hickey & contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns eastwood.copieddeps.dep1.clojure.tools.analyzer.utils
(:refer-clojure :exclude [record? boolean? update-keys update-vals])
(:require [eastwood.copieddeps.dep1.clojure.tools.analyzer.env :as env])
(:import (clojure.lang IRecord IType IObj
IReference Var)))
(defn into!
"Like into, but for transients"
[to from]
(reduce conj! to from))
(defn rseqv
"Same as (comp vec rseq)"
[v]
(vec (rseq v)))
(defn ctx
"Returns a copy of the passed environment with :context set to ctx"
[env ctx]
(assoc env :context ctx))
(defn dissoc-env
"Dissocs :env from the ast"
[ast]
(dissoc ast :env))
(defn butlast+last
"Returns same value as (juxt butlast last), but slightly more
efficient since it only traverses the input sequence s once, not
twice."
[s]
(loop [butlast (transient [])
s s]
(if-let [xs (next s)]
(recur (conj! butlast (first s)) xs)
[(seq (persistent! butlast)) (first s)])))
(defn update-vals
"Applies f to all the vals in the map"
[m f]
(reduce-kv (fn [m k v] (assoc m k (f v))) {} (or m {})))
(defn update-keys
"Applies f to all the keys in the map"
[m f]
(reduce-kv (fn [m k v] (assoc m (f k) v)) {} (or m {})))
(defn update-kv
"Applies f to all the keys and vals in the map"
[m f]
(reduce-kv (fn [m k v] (assoc m (f k) (f v))) {} (or m {})))
(defn record?
"Returns true if x is a record"
[x]
(instance? IRecord x))
(defn type?
"Returns true if x is a type"
[x]
(instance? IType x))
(defn obj?
"Returns true if x implements IObj"
[x]
(instance? IObj x))
(defn reference?
"Returns true if x implements IReference"
[x]
(instance? IReference x))
(defmacro compile-if
[exp then & else]
(if (try (eval exp)
(catch Exception _ false))
`(do ~then)
`(do ~@else)))
(defn regex?
"Returns true if x is a regex"
[x]
(instance? (compile-if (Class/forName "java.util.regex.Pattern")
java.util.regex.Pattern
System.Text.RegularExpressions.Regex)
x))
(defn boolean?
"Returns true if x is a boolean"
[x]
(or (true? x) (false? x)))
(defn classify
"Returns a keyword describing the form type"
[form]
(cond
(nil? form) :nil
(boolean? form) :bool
(keyword? form) :keyword
(symbol? form) :symbol
(string? form) :string
(number? form) :number
(type? form) :type
(record? form) :record
(map? form) :map
(vector? form) :vector
(set? form) :set
(seq? form) :seq
(char? form) :char
(regex? form) :regex
(class? form) :class
(var? form) :var
:else :unknown))
(defn private?
"Returns true if the var is private"
([var] (private? var nil))
([var m]
(:private (or m (meta var)))))
(defn macro?
"Returns true if the var maps to a macro"
([var] (macro? var nil))
([var m]
(:macro (or m (meta var)))))
(defn constant?
"Returns true if the var is a const"
([var] (constant? var nil))
([var m]
(:const (or m (meta var)))))
(defn dynamic?
"Returns true if the var is dynamic"
([var] (dynamic? var nil))
([var m]
(or (:dynamic (or m (meta var)))
workaround needed since Clojure does n't always propagate : dynamic
(.isDynamic ^Var var)))))
(defn protocol-node?
"Returns true if the var maps to a protocol function"
([var] (protocol-node? var nil))
([var m]
conveniently this is true in both clojure and clojurescript
(defn resolve-ns
"Resolves the ns mapped by the given sym in the global env"
[ns-sym {:keys [ns]}]
(when ns-sym
(let [namespaces (:namespaces (env/deref-env))]
(or (get-in namespaces [ns :aliases ns-sym])
(:ns (namespaces ns-sym))))))
(defn resolve-sym
"Resolves the value mapped by the given sym in the global env"
[sym {:keys [ns] :as env}]
(when (symbol? sym)
(let [sym-ns (when-let [ns (namespace sym)]
(symbol ns))
full-ns (resolve-ns sym-ns env)]
(when (or (not sym-ns) full-ns)
(let [name (if sym-ns (-> sym name symbol) sym)]
(-> (env/deref-env) :namespaces (get (or full-ns ns)) :mappings (get name)))))))
(defn arglist-for-arity
"Takes a fn node and an argc and returns the matching arglist"
[fn argc]
(let [arglists (->> fn :arglists (sort-by count))
arglist (->> arglists (filter #(= argc (count %))) first)
last-arglist (last arglists)]
(or arglist
(when (and (some '#{&} last-arglist)
(>= argc (- (count last-arglist) 2)))
last-arglist))))
(defn select-keys'
"Like clojure.core/select-keys, but uses transients and doesn't preserve meta"
[map keyseq]
(loop [ret (transient {}) keys (seq keyseq)]
(if keys
(let [entry (find map (first keys))]
(recur (if entry
(conj! ret entry)
ret)
(next keys)))
(persistent! ret))))
(defn merge'
"Like merge, but uses transients"
[m & mms]
(persistent! (reduce conj! (transient (or m {})) mms)))
(defn mapv'
"Like mapv, but short-circuits on reduced"
[f v]
(let [c (count v)]
(loop [ret (transient []) i 0]
(if (> c i)
(let [val (f (nth v i))]
(if (reduced? val)
(reduced (persistent! (reduce conj! (conj! ret @val) (subvec v (inc i)))))
(recur (conj! ret val) (inc i))))
(persistent! ret)))))
(defn source-info
"Returns the available source-info keys from a map"
[m]
(when (:line m)
(select-keys' m #{:file :line :column :end-line :end-column :source-span})))
(defn -source-info
"Returns the source-info of x"
[x env]
(merge' (source-info env)
(source-info (meta x))
(when-let [file (and (not= *file* "NO_SOURCE_FILE")
*file*)]
{:file file})))
(defn const-val
"Returns the value of a constant node (either :quote or :const)"
[{:keys [form val]}]
(or val form))
(def mmerge
"Same as (fn [m1 m2] (merge-with merge m2 m1))"
#(merge-with merge' %2 %1))
| null | https://raw.githubusercontent.com/jonase/eastwood/b6cf5e67dec600b7368db012c868103fe8a314ba/copied-deps/eastwood/copieddeps/dep1/clojure/tools/analyzer/utils.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) , Rich Hickey & contributors .
(ns eastwood.copieddeps.dep1.clojure.tools.analyzer.utils
(:refer-clojure :exclude [record? boolean? update-keys update-vals])
(:require [eastwood.copieddeps.dep1.clojure.tools.analyzer.env :as env])
(:import (clojure.lang IRecord IType IObj
IReference Var)))
(defn into!
"Like into, but for transients"
[to from]
(reduce conj! to from))
(defn rseqv
"Same as (comp vec rseq)"
[v]
(vec (rseq v)))
(defn ctx
"Returns a copy of the passed environment with :context set to ctx"
[env ctx]
(assoc env :context ctx))
(defn dissoc-env
"Dissocs :env from the ast"
[ast]
(dissoc ast :env))
(defn butlast+last
"Returns same value as (juxt butlast last), but slightly more
efficient since it only traverses the input sequence s once, not
twice."
[s]
(loop [butlast (transient [])
s s]
(if-let [xs (next s)]
(recur (conj! butlast (first s)) xs)
[(seq (persistent! butlast)) (first s)])))
(defn update-vals
"Applies f to all the vals in the map"
[m f]
(reduce-kv (fn [m k v] (assoc m k (f v))) {} (or m {})))
(defn update-keys
"Applies f to all the keys in the map"
[m f]
(reduce-kv (fn [m k v] (assoc m (f k) v)) {} (or m {})))
(defn update-kv
"Applies f to all the keys and vals in the map"
[m f]
(reduce-kv (fn [m k v] (assoc m (f k) (f v))) {} (or m {})))
(defn record?
"Returns true if x is a record"
[x]
(instance? IRecord x))
(defn type?
"Returns true if x is a type"
[x]
(instance? IType x))
(defn obj?
"Returns true if x implements IObj"
[x]
(instance? IObj x))
(defn reference?
"Returns true if x implements IReference"
[x]
(instance? IReference x))
(defmacro compile-if
[exp then & else]
(if (try (eval exp)
(catch Exception _ false))
`(do ~then)
`(do ~@else)))
(defn regex?
"Returns true if x is a regex"
[x]
(instance? (compile-if (Class/forName "java.util.regex.Pattern")
java.util.regex.Pattern
System.Text.RegularExpressions.Regex)
x))
(defn boolean?
"Returns true if x is a boolean"
[x]
(or (true? x) (false? x)))
(defn classify
"Returns a keyword describing the form type"
[form]
(cond
(nil? form) :nil
(boolean? form) :bool
(keyword? form) :keyword
(symbol? form) :symbol
(string? form) :string
(number? form) :number
(type? form) :type
(record? form) :record
(map? form) :map
(vector? form) :vector
(set? form) :set
(seq? form) :seq
(char? form) :char
(regex? form) :regex
(class? form) :class
(var? form) :var
:else :unknown))
(defn private?
"Returns true if the var is private"
([var] (private? var nil))
([var m]
(:private (or m (meta var)))))
(defn macro?
"Returns true if the var maps to a macro"
([var] (macro? var nil))
([var m]
(:macro (or m (meta var)))))
(defn constant?
"Returns true if the var is a const"
([var] (constant? var nil))
([var m]
(:const (or m (meta var)))))
(defn dynamic?
"Returns true if the var is dynamic"
([var] (dynamic? var nil))
([var m]
(or (:dynamic (or m (meta var)))
workaround needed since Clojure does n't always propagate : dynamic
(.isDynamic ^Var var)))))
(defn protocol-node?
"Returns true if the var maps to a protocol function"
([var] (protocol-node? var nil))
([var m]
conveniently this is true in both clojure and clojurescript
(defn resolve-ns
"Resolves the ns mapped by the given sym in the global env"
[ns-sym {:keys [ns]}]
(when ns-sym
(let [namespaces (:namespaces (env/deref-env))]
(or (get-in namespaces [ns :aliases ns-sym])
(:ns (namespaces ns-sym))))))
(defn resolve-sym
"Resolves the value mapped by the given sym in the global env"
[sym {:keys [ns] :as env}]
(when (symbol? sym)
(let [sym-ns (when-let [ns (namespace sym)]
(symbol ns))
full-ns (resolve-ns sym-ns env)]
(when (or (not sym-ns) full-ns)
(let [name (if sym-ns (-> sym name symbol) sym)]
(-> (env/deref-env) :namespaces (get (or full-ns ns)) :mappings (get name)))))))
(defn arglist-for-arity
"Takes a fn node and an argc and returns the matching arglist"
[fn argc]
(let [arglists (->> fn :arglists (sort-by count))
arglist (->> arglists (filter #(= argc (count %))) first)
last-arglist (last arglists)]
(or arglist
(when (and (some '#{&} last-arglist)
(>= argc (- (count last-arglist) 2)))
last-arglist))))
(defn select-keys'
"Like clojure.core/select-keys, but uses transients and doesn't preserve meta"
[map keyseq]
(loop [ret (transient {}) keys (seq keyseq)]
(if keys
(let [entry (find map (first keys))]
(recur (if entry
(conj! ret entry)
ret)
(next keys)))
(persistent! ret))))
(defn merge'
"Like merge, but uses transients"
[m & mms]
(persistent! (reduce conj! (transient (or m {})) mms)))
(defn mapv'
"Like mapv, but short-circuits on reduced"
[f v]
(let [c (count v)]
(loop [ret (transient []) i 0]
(if (> c i)
(let [val (f (nth v i))]
(if (reduced? val)
(reduced (persistent! (reduce conj! (conj! ret @val) (subvec v (inc i)))))
(recur (conj! ret val) (inc i))))
(persistent! ret)))))
(defn source-info
"Returns the available source-info keys from a map"
[m]
(when (:line m)
(select-keys' m #{:file :line :column :end-line :end-column :source-span})))
(defn -source-info
"Returns the source-info of x"
[x env]
(merge' (source-info env)
(source-info (meta x))
(when-let [file (and (not= *file* "NO_SOURCE_FILE")
*file*)]
{:file file})))
(defn const-val
"Returns the value of a constant node (either :quote or :const)"
[{:keys [form val]}]
(or val form))
(def mmerge
"Same as (fn [m1 m2] (merge-with merge m2 m1))"
#(merge-with merge' %2 %1))
|
e9b64563892dd96e3c1d8e9b5e1db405120d6ef0c323790b1f0e85d315836fdf | argp/bap | batRandom.ml |
* BatRandom - Additional randomization operations
* Copyright ( C ) 1996
* 2009 , LIFO , Universite d'Orleans
* 2009
*
* This library 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 ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library 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 .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* BatRandom - Additional randomization operations
* Copyright (C) 1996 Damien Doligez
* 2009 David Teller, LIFO, Universite d'Orleans
* 2009 Pierre Chambart
*
* This library 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; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
let init = Random.init
let full_init = Random.full_init
let self_init = Random.self_init
let bits = Random.bits
let int = Random.int
let int32 = Random.int32
let int64 = Random.int64
let nativeint = Random.nativeint
let float = Random.float
let bool = Random.bool
let char () = Char.chr (int 256)
let full_range_int =
need 31 - bits of entropy , bits ( ) gives 30
fun () -> if bool () then - (bits ())-1 else bits ()
64 - bit words
need 63 bits of entropy , bits + bits + bits land 0b11
let b = (bits ()) lor (bits () lsl 30) lor ((bits () land 0b11) lsl 60) in
if bool () then b else -b - 1
module State =
struct
include Random.State
let char t = Char.chr (int t 256)
(**A constructor for enumerations of random numbers. *)
let enum_bits state () = BatEnum.from (fun () -> bits state)
let enum_int state bound = BatEnum.from (fun () -> int state bound)
let enum_int32 state bound = BatEnum.from (fun () -> int32 state bound)
let enum_int64 state bound = BatEnum.from (fun () -> int64 state bound)
let enum_float state bound = BatEnum.from (fun () -> float state bound)
let enum_nativeint state bound =
BatEnum.from (fun () -> nativeint state bound)
let enum_bool state () = BatEnum.from (fun () -> bool state)
let enum_char state () = BatEnum.from (fun () -> char state)
end
let enum_bits () = BatEnum.from bits
let enum_int bound = BatEnum.from (fun () -> int bound)
let enum_int32 bound = BatEnum.from (fun () -> int32 bound)
let enum_int64 bound = BatEnum.from (fun () -> int64 bound)
let enum_float bound = BatEnum.from (fun () -> float bound)
let enum_nativeint bound = BatEnum.from (fun () -> nativeint bound)
let enum_bool () = BatEnum.from bool
let enum_char () = BatEnum.from char
let choice e = BatEnum.drop (int (BatEnum.count e)) e; BatEnum.get_exn e
Reservoir sampling algorithm ( see for instance
)
TODO : a more efficient algorithm when given enum length is known
)
TODO: a more efficient algorithm when given enum length is known *)
let multi_choice n e =
if BatEnum.is_empty e then
BatEnum.empty ()
else
let next e = BatOption.get (BatEnum.get e) in
Note : this assumes that Array.init will call the function for i
= 0 to n-1 in that order
= 0 to n-1 in that order *)
let chosen = Array.init n (fun i -> next e, i) in
BatEnum.iteri (fun i x ->
we 've already chosen the n first items
let r = Random.int i in
if r < n then chosen.(r) <- x, i) e ;
Array.sort (fun (_, i1) (_, i2) -> compare i1 i2) chosen ;
BatArray.enum (Array.map fst chosen)
$ T multi_choice
BatEnum.is_empty ( multi_choice 0 ( BatEnum.empty ( ) ) )
BatEnum.count ( multi_choice 3 ( BatList.enum [ 1;2;3;4;5 ] ) ) = 3
let l = [ 1;2;3;4;5 ] in let e = multi_choice 2 ( BatList.enum l ) in \
let a = BatOption.get ( BatEnum.get e ) in a < BatOption.get ( BatEnum.get e )
let x = BatEnum.repeat ~times:99 [ 0;1 ] /@ ( fun l - > \
multi_choice 1 ( BatList.enum l ) ) /@ \
BatEnum.get_exn | > \
reduce ( + ) in x > 0 & & x < 99
BatEnum.is_empty (multi_choice 0 (BatEnum.empty ()))
BatEnum.count (multi_choice 3 (BatList.enum [1;2;3;4;5])) = 3
let l = [1;2;3;4;5] in let e = multi_choice 2 (BatList.enum l) in \
let a = BatOption.get (BatEnum.get e) in a < BatOption.get (BatEnum.get e)
let x = BatEnum.repeat ~times:99 [0;1] /@ (fun l -> \
multi_choice 1 (BatList.enum l)) /@ \
BatEnum.get_exn |> \
reduce (+) in x > 0 && x < 99
*)
Note : this last test check that the first nor the last item is always chosen
let shuffle e =
let a = BatArray.of_enum e in
for n = Array.length a - 1 downto 1 do
let k = int ( n + 1 ) in
if k <> n then
let buf = Array.get a n in
Array.set a n (Array.get a k);
Array.set a k buf
done;
a
let get_state = Random.get_state
let set_state = Random.set_state
module Incubator = struct
module Private_state_enums = struct
module State = struct
include State (* the state we defined up above *)
let random_enum state next =
let rec aux state =
let next () = next state in
let count () = raise BatEnum.Infinite_enum in
let clone () = aux ( copy state ) in
BatEnum.make ~next ~count ~clone
in aux (copy state)
let enum_bits state () =
random_enum state bits
let enum_int state bound =
random_enum state (fun state -> int state bound)
let enum_int32 state bound =
random_enum state (fun state -> int32 state bound)
let enum_int64 state bound =
random_enum state (fun state -> int64 state bound)
let enum_float state bound =
random_enum state (fun state -> float state bound)
let enum_nativeint state bound =
random_enum state (fun state -> nativeint state bound)
let enum_bool state () =
random_enum state bool
let enum_char state () =
random_enum state char
type implementation = { st : int array; mutable idx : int };;
(* external t_of_impl: implementation -> t = "%identity" *)
external impl_of_t: t -> implementation = "%identity"
let perturb state =
let impl = impl_of_t state in
make (Array.append impl.st [|impl.idx|])
end
bumps the existing global RNG state ( reseeding on its current
array ) and returns the previous state
array) and returns the previous state *)
let perturb_global () =
let s_in = get_state () in
set_state (State.perturb s_in);
s_in
let enum_bits () = State.enum_bits (perturb_global ()) ()
let enum_bool () = State.enum_bool (perturb_global ()) ()
let enum_char () = State.enum_char (perturb_global ()) ()
let enum_int bound = State.enum_int (perturb_global ()) bound
let enum_int32 bound = State.enum_int32 (perturb_global ()) bound
let enum_int64 bound = State.enum_int64 (perturb_global ()) bound
let enum_float bound = State.enum_float (perturb_global ()) bound
let enum_nativeint bound = State.enum_nativeint (perturb_global ()) bound
end
end
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/src/batRandom.ml | ocaml | *A constructor for enumerations of random numbers.
the state we defined up above
external t_of_impl: implementation -> t = "%identity" |
* BatRandom - Additional randomization operations
* Copyright ( C ) 1996
* 2009 , LIFO , Universite d'Orleans
* 2009
*
* This library 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 ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library 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 .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* BatRandom - Additional randomization operations
* Copyright (C) 1996 Damien Doligez
* 2009 David Teller, LIFO, Universite d'Orleans
* 2009 Pierre Chambart
*
* This library 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; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
let init = Random.init
let full_init = Random.full_init
let self_init = Random.self_init
let bits = Random.bits
let int = Random.int
let int32 = Random.int32
let int64 = Random.int64
let nativeint = Random.nativeint
let float = Random.float
let bool = Random.bool
let char () = Char.chr (int 256)
let full_range_int =
need 31 - bits of entropy , bits ( ) gives 30
fun () -> if bool () then - (bits ())-1 else bits ()
64 - bit words
need 63 bits of entropy , bits + bits + bits land 0b11
let b = (bits ()) lor (bits () lsl 30) lor ((bits () land 0b11) lsl 60) in
if bool () then b else -b - 1
module State =
struct
include Random.State
let char t = Char.chr (int t 256)
let enum_bits state () = BatEnum.from (fun () -> bits state)
let enum_int state bound = BatEnum.from (fun () -> int state bound)
let enum_int32 state bound = BatEnum.from (fun () -> int32 state bound)
let enum_int64 state bound = BatEnum.from (fun () -> int64 state bound)
let enum_float state bound = BatEnum.from (fun () -> float state bound)
let enum_nativeint state bound =
BatEnum.from (fun () -> nativeint state bound)
let enum_bool state () = BatEnum.from (fun () -> bool state)
let enum_char state () = BatEnum.from (fun () -> char state)
end
let enum_bits () = BatEnum.from bits
let enum_int bound = BatEnum.from (fun () -> int bound)
let enum_int32 bound = BatEnum.from (fun () -> int32 bound)
let enum_int64 bound = BatEnum.from (fun () -> int64 bound)
let enum_float bound = BatEnum.from (fun () -> float bound)
let enum_nativeint bound = BatEnum.from (fun () -> nativeint bound)
let enum_bool () = BatEnum.from bool
let enum_char () = BatEnum.from char
let choice e = BatEnum.drop (int (BatEnum.count e)) e; BatEnum.get_exn e
Reservoir sampling algorithm ( see for instance
)
TODO : a more efficient algorithm when given enum length is known
)
TODO: a more efficient algorithm when given enum length is known *)
let multi_choice n e =
if BatEnum.is_empty e then
BatEnum.empty ()
else
let next e = BatOption.get (BatEnum.get e) in
Note : this assumes that Array.init will call the function for i
= 0 to n-1 in that order
= 0 to n-1 in that order *)
let chosen = Array.init n (fun i -> next e, i) in
BatEnum.iteri (fun i x ->
we 've already chosen the n first items
let r = Random.int i in
if r < n then chosen.(r) <- x, i) e ;
Array.sort (fun (_, i1) (_, i2) -> compare i1 i2) chosen ;
BatArray.enum (Array.map fst chosen)
$ T multi_choice
BatEnum.is_empty ( multi_choice 0 ( BatEnum.empty ( ) ) )
BatEnum.count ( multi_choice 3 ( BatList.enum [ 1;2;3;4;5 ] ) ) = 3
let l = [ 1;2;3;4;5 ] in let e = multi_choice 2 ( BatList.enum l ) in \
let a = BatOption.get ( BatEnum.get e ) in a < BatOption.get ( BatEnum.get e )
let x = BatEnum.repeat ~times:99 [ 0;1 ] /@ ( fun l - > \
multi_choice 1 ( BatList.enum l ) ) /@ \
BatEnum.get_exn | > \
reduce ( + ) in x > 0 & & x < 99
BatEnum.is_empty (multi_choice 0 (BatEnum.empty ()))
BatEnum.count (multi_choice 3 (BatList.enum [1;2;3;4;5])) = 3
let l = [1;2;3;4;5] in let e = multi_choice 2 (BatList.enum l) in \
let a = BatOption.get (BatEnum.get e) in a < BatOption.get (BatEnum.get e)
let x = BatEnum.repeat ~times:99 [0;1] /@ (fun l -> \
multi_choice 1 (BatList.enum l)) /@ \
BatEnum.get_exn |> \
reduce (+) in x > 0 && x < 99
*)
Note : this last test check that the first nor the last item is always chosen
let shuffle e =
let a = BatArray.of_enum e in
for n = Array.length a - 1 downto 1 do
let k = int ( n + 1 ) in
if k <> n then
let buf = Array.get a n in
Array.set a n (Array.get a k);
Array.set a k buf
done;
a
let get_state = Random.get_state
let set_state = Random.set_state
module Incubator = struct
module Private_state_enums = struct
module State = struct
let random_enum state next =
let rec aux state =
let next () = next state in
let count () = raise BatEnum.Infinite_enum in
let clone () = aux ( copy state ) in
BatEnum.make ~next ~count ~clone
in aux (copy state)
let enum_bits state () =
random_enum state bits
let enum_int state bound =
random_enum state (fun state -> int state bound)
let enum_int32 state bound =
random_enum state (fun state -> int32 state bound)
let enum_int64 state bound =
random_enum state (fun state -> int64 state bound)
let enum_float state bound =
random_enum state (fun state -> float state bound)
let enum_nativeint state bound =
random_enum state (fun state -> nativeint state bound)
let enum_bool state () =
random_enum state bool
let enum_char state () =
random_enum state char
type implementation = { st : int array; mutable idx : int };;
external impl_of_t: t -> implementation = "%identity"
let perturb state =
let impl = impl_of_t state in
make (Array.append impl.st [|impl.idx|])
end
bumps the existing global RNG state ( reseeding on its current
array ) and returns the previous state
array) and returns the previous state *)
let perturb_global () =
let s_in = get_state () in
set_state (State.perturb s_in);
s_in
let enum_bits () = State.enum_bits (perturb_global ()) ()
let enum_bool () = State.enum_bool (perturb_global ()) ()
let enum_char () = State.enum_char (perturb_global ()) ()
let enum_int bound = State.enum_int (perturb_global ()) bound
let enum_int32 bound = State.enum_int32 (perturb_global ()) bound
let enum_int64 bound = State.enum_int64 (perturb_global ()) bound
let enum_float bound = State.enum_float (perturb_global ()) bound
let enum_nativeint bound = State.enum_nativeint (perturb_global ()) bound
end
end
|
06584377e20bbdc418ce617792d61fa9536c7d71e92177b14aa46c8e601de542 | kitnil/dotfiles | tmux.scm | (define-module (home services tmux)
#:use-module (gnu home services)
#:use-module (gnu home services shepherd)
#:use-module (guix gexp)
#:use-module (guix records)
#:use-module (gnu services)
#:use-module (home config)
#:export (home-tmux-service
tmuxifier-service))
(define home-tmux-service
(simple-service 'tmux-config
home-files-service-type
(list `(".tmux.conf"
,(local-file (string-append %project-directory "/dot_tmux.conf"))))))
(define tmuxifier-service
(simple-service 'tmuxifier-config
home-files-service-type
(list `(".tmuxifier-layouts/backup.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/backup.session.sh")))
`(".tmuxifier-layouts/backup.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/backup.window.sh")))
`(".tmuxifier-layouts/blog.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/blog.session.sh")))
`(".tmuxifier-layouts/blog.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/blog.window.sh")))
`(".tmuxifier-layouts/guix-machines.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/guix-machines.window.sh")))
`(".tmuxifier-layouts/guix.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/guix.session.sh")))
`(".tmuxifier-layouts/guix.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/guix.window.sh")))
`(".tmuxifier-layouts/elk.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/elk.session.sh")))
;; TODO: `("web.session.sh.tmpl" ,(local-file "../../dot_tmuxifier-layouts/web.session.sh.tmpl"))
`(".tmuxifier-layouts/elk.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/elk.window.sh")))
`(".tmuxifier-layouts/kubernetes-cert-manager-logs.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-cert-manager-logs.window.sh")))
`(".tmuxifier-layouts/kubernetes-cilium.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-cilium.window.sh")))
`(".tmuxifier-layouts/kubernetes-flux-logs.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-flux-logs.window.sh")))
`(".tmuxifier-layouts/kubernetes-flux.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-flux.window.sh")))
`(".tmuxifier-layouts/kubernetes-kube-system.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-kube-system.window.sh")))
`(".tmuxifier-layouts/kubernetes-piraeus.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-piraeus.window.sh")))
`(".tmuxifier-layouts/kubernetes-opensearch.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-opensearch.window.sh")))
`(".tmuxifier-layouts/kubernetes-pdns.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-pdns.window.sh")))
`(".tmuxifier-layouts/kubernetes-harbor.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-harbor.window.sh")))
`(".tmuxifier-layouts/kubernetes.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes.session.sh"))))))
| null | https://raw.githubusercontent.com/kitnil/dotfiles/3083f773c5da0cdb8b715062cec7b4224515ff88/dotfiles/guixsd/modules/home/services/tmux.scm | scheme | TODO: `("web.session.sh.tmpl" ,(local-file "../../dot_tmuxifier-layouts/web.session.sh.tmpl")) | (define-module (home services tmux)
#:use-module (gnu home services)
#:use-module (gnu home services shepherd)
#:use-module (guix gexp)
#:use-module (guix records)
#:use-module (gnu services)
#:use-module (home config)
#:export (home-tmux-service
tmuxifier-service))
(define home-tmux-service
(simple-service 'tmux-config
home-files-service-type
(list `(".tmux.conf"
,(local-file (string-append %project-directory "/dot_tmux.conf"))))))
(define tmuxifier-service
(simple-service 'tmuxifier-config
home-files-service-type
(list `(".tmuxifier-layouts/backup.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/backup.session.sh")))
`(".tmuxifier-layouts/backup.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/backup.window.sh")))
`(".tmuxifier-layouts/blog.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/blog.session.sh")))
`(".tmuxifier-layouts/blog.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/blog.window.sh")))
`(".tmuxifier-layouts/guix-machines.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/guix-machines.window.sh")))
`(".tmuxifier-layouts/guix.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/guix.session.sh")))
`(".tmuxifier-layouts/guix.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/guix.window.sh")))
`(".tmuxifier-layouts/elk.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/elk.session.sh")))
`(".tmuxifier-layouts/elk.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/elk.window.sh")))
`(".tmuxifier-layouts/kubernetes-cert-manager-logs.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-cert-manager-logs.window.sh")))
`(".tmuxifier-layouts/kubernetes-cilium.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-cilium.window.sh")))
`(".tmuxifier-layouts/kubernetes-flux-logs.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-flux-logs.window.sh")))
`(".tmuxifier-layouts/kubernetes-flux.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-flux.window.sh")))
`(".tmuxifier-layouts/kubernetes-kube-system.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-kube-system.window.sh")))
`(".tmuxifier-layouts/kubernetes-piraeus.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-piraeus.window.sh")))
`(".tmuxifier-layouts/kubernetes-opensearch.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-opensearch.window.sh")))
`(".tmuxifier-layouts/kubernetes-pdns.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-pdns.window.sh")))
`(".tmuxifier-layouts/kubernetes-harbor.window.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes-harbor.window.sh")))
`(".tmuxifier-layouts/kubernetes.session.sh"
,(local-file (string-append %project-directory "/dot_tmuxifier-layouts/kubernetes.session.sh"))))))
|
e8e280f59aa636afe8ad60602936cf9f7963eb3afef5a811ebede145e3e28f6a | ocaml/Zarith | pi.ml | Pi digits computed with the streaming algorithm given on pages 4 , 6
& 7 of " Unbounded Spigot Algorithms for the Digits of Pi " , , August 2004 .
& 7 of "Unbounded Spigot Algorithms for the Digits of Pi", Jeremy
Gibbons, August 2004. *)
open Printf
let zero = Z.zero
and one = Z.one
and three = Z.of_int 3
and four = Z.of_int 4
and ten = Z.of_int 10
and neg_ten = Z.of_int (-10)
;;
Linear Fractional ( aka M = F6bius ) Transformations
module LFT = struct
let floor_ev (q, r, s, t) x =
Z.((q * x + r) / (s * x + t))
let unit = (one, zero, zero, one)
let comp (q, r, s, t) (q', r', s', t') =
Z.(q * q' + r * s', q * r' + r * t',
s * q' + t * s', s * r' + t * t')
end
let next z = LFT.floor_ev z three
let safe z n = (n = LFT.floor_ev z four)
let prod z n = LFT.comp (ten, Z.(neg_ten * n), zero, one) z
let cons z k =
let den = 2 * k + 1 in
LFT.comp z (Z.of_int k, Z.of_int (2 * den), zero, Z.of_int den)
let rec digit k z n row col =
if n > 0 then
let y = next z in
if safe z y then
if col = 10 then (
let row = row + 10 in
printf "\t:%i\n%a" row Z.output y;
digit k (prod z y) (n - 1) row 1
)
else (
printf "%a" Z.output y;
digit k (prod z y) (n - 1) row (col + 1)
)
else digit (k + 1) (cons z k) n row col
else
printf "%*s\t:%i\n" (10 - col) "" (row + col)
let digits n = digit 1 LFT.unit n 0 0
let usage () =
prerr_endline "Usage: pi <number of digits to compute for pi>";
exit 2
let _ =
let args = Sys.argv in
if Array.length args <> 2 then usage () else
digits (int_of_string Sys.argv.(1))
| null | https://raw.githubusercontent.com/ocaml/Zarith/39df015463f2797256dfb12440ed8f6c2dfd59cc/tests/pi.ml | ocaml | Pi digits computed with the streaming algorithm given on pages 4 , 6
& 7 of " Unbounded Spigot Algorithms for the Digits of Pi " , , August 2004 .
& 7 of "Unbounded Spigot Algorithms for the Digits of Pi", Jeremy
Gibbons, August 2004. *)
open Printf
let zero = Z.zero
and one = Z.one
and three = Z.of_int 3
and four = Z.of_int 4
and ten = Z.of_int 10
and neg_ten = Z.of_int (-10)
;;
Linear Fractional ( aka M = F6bius ) Transformations
module LFT = struct
let floor_ev (q, r, s, t) x =
Z.((q * x + r) / (s * x + t))
let unit = (one, zero, zero, one)
let comp (q, r, s, t) (q', r', s', t') =
Z.(q * q' + r * s', q * r' + r * t',
s * q' + t * s', s * r' + t * t')
end
let next z = LFT.floor_ev z three
let safe z n = (n = LFT.floor_ev z four)
let prod z n = LFT.comp (ten, Z.(neg_ten * n), zero, one) z
let cons z k =
let den = 2 * k + 1 in
LFT.comp z (Z.of_int k, Z.of_int (2 * den), zero, Z.of_int den)
let rec digit k z n row col =
if n > 0 then
let y = next z in
if safe z y then
if col = 10 then (
let row = row + 10 in
printf "\t:%i\n%a" row Z.output y;
digit k (prod z y) (n - 1) row 1
)
else (
printf "%a" Z.output y;
digit k (prod z y) (n - 1) row (col + 1)
)
else digit (k + 1) (cons z k) n row col
else
printf "%*s\t:%i\n" (10 - col) "" (row + col)
let digits n = digit 1 LFT.unit n 0 0
let usage () =
prerr_endline "Usage: pi <number of digits to compute for pi>";
exit 2
let _ =
let args = Sys.argv in
if Array.length args <> 2 then usage () else
digits (int_of_string Sys.argv.(1))
| |
5f549f837517c66edb9aa099758d6ac7d22d68c735b91b88ada1699ba5dd301d | dmitryvk/sbcl-win32-threads | hash.impure.lisp | This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
While most of SBCL is derived from the CMU CL system , the test
;;;; files (like this one) were written from scratch after the fork
from CMU CL .
;;;;
;;;; This software is in the public domain and is provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for
;;;; more information.
(in-package :cl-user)
(use-package :test-util)
(use-package :assertoid)
(defstruct foo)
(defstruct bar x y)
SXHASH and PSXHASH should distribute hash values well over the
;;; space of possible values, so that collisions between the hash
;;; values of unequal objects should be very uncommon. (Except of
course the hash values must collide when the objects are EQUAL or
EQUALP respectively ! )
(locally
;; In order to better test not-EQ-but-EQUAL and not-EQ-but-EQUALP,
;; we'd like to suppress some optimizations.
(declare (notinline complex float coerce + - expt))
(flet ((make-sxhash-subtests ()
(list (cons 0 1)
(list 0 1)
(cons 1 0)
(cons (cons 1 0) (cons 0 0))
(cons (list 1 0) (list 0 0))
(list (cons 1 0) (list 0 0))
(list (cons 0 1) (list 0 0))
(list (cons 0 0) (cons 1 0))
(list (cons 0 0) (cons 0 1))
44 (float 44) (coerce 44 'double-float)
-44 (float -44) (coerce -44 'double-float)
0 (float 0) (coerce 0 'double-float)
-0 (- (float 0)) (- (coerce 0 'double-float))
-121 (float -121) (coerce -121 'double-float)
3/4 (float 3/4) (coerce 3/4 'double-float)
-3/4 (float -3/4) (coerce -3/4 'double-float)
45 (float 45) (coerce 45 'double-float)
441/10 (float 441/10) (coerce (float 441/10) 'double-float)
(expt 2 33) (expt 2.0 33) (expt 2.0d0 33)
(- (expt 1/2 50)) (- (expt 0.5 50)) (- (expt 0.5d0 50))
(+ (expt 1/2 50)) (+ (expt 0.5 50)) (+ (expt 0.5d0 50))
(complex 1.0 2.0) (complex 1.0d0 2.0)
(complex 1.5 -3/2) (complex 1.5 -1.5d0)
#\x #\X #\*
(copy-seq "foo") (copy-seq "foobar") (copy-seq "foobarbaz")
(copy-seq #*)
(copy-seq #*0) (copy-seq #*1)
(copy-seq #*00) (copy-seq #*10)
(copy-seq #*01) (copy-seq #*11)
(copy-seq #*10010) (copy-seq #*100101) (bit-not #*01101)
(make-array 6 :fill-pointer 6
:element-type 'bit :initial-contents #*100101)
#'allocate-instance #'no-applicable-method))
(make-psxhash-extra-subtests ()
(list (copy-seq "")
(copy-seq #*)
(copy-seq #())
(copy-seq ())
(copy-seq '(()))
(copy-seq #(()))
(copy-seq '(#()))
(make-array 3 :fill-pointer 0)
(make-array 7 :fill-pointer 0 :element-type 'bit)
(make-array 8 :fill-pointer 0 :element-type 'character)
(vector (cons 1 0) (cons 0 0))
(vector (cons 0 1) (cons 0 0))
(vector (cons 0 0) (cons 1 0))
(vector (cons 0 0) (cons 0 1))
(vector (cons 1 0) (cons 0 0))
(vector (cons 0 1) (cons 0 0))
(vector (list 0 0) (cons 1 0))
(vector (list 0 0) (list 0 1))
(vector (vector 1 0) (list 0 0))
(vector (vector 0 1) (list 0 0))
(vector (vector 0 0) (list 1 0))
(vector (vector 0 0) (list 0 1))
(vector #*00 #*10)
(vector (vector 0 0) (list 0 1.0d0))
(vector (vector -0.0d0 0) (list 1.0 0))
(vector 1 0 1 0)
(vector 0 0 0)
(copy-seq #*1010)
(copy-seq #*000)
(replace (make-array 101
:element-type 'bit
:fill-pointer 4)
#*1010)
(replace (make-array 14
:element-type '(unsigned-byte 8)
:fill-pointer 3)
#*000)
(replace (make-array 14
:element-type t
:fill-pointer 3)
#*000)
(copy-seq "abc")
(copy-seq "ABC")
(copy-seq "aBc")
(copy-seq "abcc")
(copy-seq "1001")
'abc
(vector #\a #\b #\c)
(vector 'a 'b 'c)
(vector "A" 'b 'c)
(replace (make-array 14
:element-type 'character
:fill-pointer 3)
"aBc")
(replace (make-array 11
:element-type 'character
:fill-pointer 4)
"1001")
(replace (make-array 12
:element-type 'bit
:fill-pointer 4)
#*1001)
(replace (make-array 13
:element-type t
:fill-pointer 4)
"1001")
(replace (make-array 13
:element-type t
:fill-pointer 4)
#*1001)
;; FIXME: What about multi-dimensional arrays, hmm?
(make-hash-table)
(make-hash-table :test 'equal)
(make-foo)
(make-bar)
(make-bar :x (list 1))
(make-bar :y (list 1))))
(t->boolean (x) (if x t nil)))
(let* (;; Note:
* The noise here is to help more strenuously test
;; not-EQ-but-EQUAL and not-EQ-but-EQUALP cases.
* It seems not to be worth the hassle testing SXHASH on
values whose structure is n't understood by EQUAL , since
;; we get too many false positives "SXHASHes are equal even
though values are n't EQUAL , what a crummy hash function ! "
;; FIXME: Or am I misunderstanding the intent of the
the SXHASH specification ? Perhaps SXHASH is supposed to
descend into the structure of objects even when EQUAL
;; doesn't, in order to avoid hashing together things which
are guaranteed not to be EQUAL ? The definition of SXHASH
;; seems to leave this completely unspecified: should
" well - distributed " depend on substructure that EQUAL
;; ignores? For our internal hash tables, the stricter
;; descend-into-the-structure behavior might improve
performance even though it 's not specified by ANSI . But
;; is it reasonable for users to expect it? Hmm..
(sxhash-tests (append (make-sxhash-subtests)
(make-sxhash-subtests)))
(psxhash-tests (append sxhash-tests
(make-psxhash-extra-subtests)
(make-psxhash-extra-subtests))))
Check that SXHASH compiler transforms give the same results
as the out - of - line version of SXHASH .
(let* ((fundef `(lambda ()
(list ,@(mapcar (lambda (value)
`(sxhash ',value))
sxhash-tests))))
(fun (compile nil fundef)))
(assert (equal (funcall fun)
(mapcar #'sxhash sxhash-tests))))
Note : The tests for SXHASH - equality iff EQUAL and
;; PSXHASH-equality iff EQUALP could fail because of an unlucky
;; random collision. That's not very likely (since there are
( EXPT 2 29 ) possible hash values and only on the order of 100
;; test cases, so even with the birthday paradox a collision has
;; probability only (/ (EXPT 100 2) (EXPT 2 29)), but it's
;; probably worth checking if you are getting a mystifying error
from this test . ( SXHASH values and PSXHASH values do n't
;; change from run to run, so the random chance of bogus failure
;; happens once every time the code is changed in such a way
that the SXHASH distribution changes , not once every time the
;; tests are run.)
(dolist (i sxhash-tests)
(declare (notinline funcall))
(unless (typep (funcall #'sxhash i) '(and fixnum unsigned-byte))
(error "bad SXHASH behavior for ~S" i))
(dolist (j sxhash-tests)
(unless (or (eq (t->boolean (equal i j))
(t->boolean (= (sxhash i) (sxhash j))))
(and (typep i 'number)
(typep j 'number)
(= i j)
(subtypep (type-of i) (type-of j))
(subtypep (type-of j) (type-of i))))
;; (If you get a surprising failure here, maybe you were
;; just very unlucky; see the notes above.)
(error "bad SXHASH behavior for ~S ~S" i j))))
(dolist (i psxhash-tests)
(unless (typep (sb-int:psxhash i) '(and fixnum unsigned-byte))
(error "bad PSXHASH behavior for ~S" i))
(dolist (j psxhash-tests)
(unless (eq (t->boolean (equalp i j))
(t->boolean (= (sb-int:psxhash i) (sb-int:psxhash j))))
;; (If you get a surprising failure here, maybe you were
;; just very unlucky; see the notes above.)
(error "bad PSXHASH behavior for ~S ~S" i j))))
)))
As of sbcl-0.6.12.10 , writing hash tables readably should work .
This is n't required by the ANSI standard , but it should be , since
it 's well - defined useful behavior which ANSI prohibits the users
from implementing themselves . ( ANSI says the users ca n't define
;;; their own their own PRINT-OBJECT (HASH-TABLE T) methods, and they
;;; can't even wiggle out of it by subclassing HASH-TABLE or STREAM.)
(let ((original-ht (make-hash-table :test 'equal :size 111))
(original-keys '(1 10 11 400030002 -100000000)))
(dolist (key original-keys)
(setf (gethash key original-ht)
(expt key 4)))
(let* ((written-ht (with-output-to-string (s)
(write original-ht :stream s :readably t)))
(read-ht (with-input-from-string (s written-ht)
(read s))))
(assert (= (hash-table-count read-ht)
(hash-table-count original-ht)
(length original-keys)))
(assert (eql (hash-table-test original-ht) (hash-table-test read-ht)))
(assert (eql (hash-table-size original-ht) (hash-table-size read-ht)))
(dolist (key original-keys)
(assert (eql (gethash key read-ht)
(gethash key original-ht))))))
NIL is both SYMBOL and LIST
(dolist (fun '(sxhash sb-impl::psxhash))
(assert (= (eval `(,fun nil))
(funcall fun nil)
(funcall (compile nil `(lambda (x)
(declare (symbol x))
(,fun x)))
nil)
(funcall (compile nil `(lambda (x)
(declare (list x))
(,fun x)))
nil)
(funcall (compile nil `(lambda (x)
(declare (null x))
(,fun x)))
nil))))
;;; This test works reliably on non-conservative platforms and
;;; somewhat reliably on conservative platforms with threads.
#+(or (not (or x86 x86-64)) sb-thread)
(progn
(defparameter *ht* nil)
(defvar *cons-here*)
(declaim (notinline args))
(defun take (&rest args)
(declare (ignore args)))
(defmacro alloc (&body body)
"Execute BODY and try to reduce the chance of leaking a conservative root."
#-sb-thread
`(multiple-value-prog1
(progn ,@body)
(loop repeat 20000 do (setq *cons-here* (cons nil nil)))
: Clean the argument passing regs .
(apply #'take (loop repeat 36 collect #'cons)))
#+sb-thread
(let ((values (gensym))
(sem (gensym)))
`(let ((,sem (sb-thread::make-semaphore))
,values)
(sb-thread:make-thread (lambda ()
(setq ,values
(multiple-value-list (progn ,@body)))
(sb-thread::signal-semaphore ,sem)))
(sb-thread::wait-on-semaphore ,sem)
(values-list ,values))))
(with-test (:name (:hash-table :weakness :eql :numbers))
(flet ((random-number ()
(random 1000)))
(loop for weakness in '(nil :key :value :key-and-value :key-or-value) do
(let* ((ht (make-hash-table :weakness weakness))
(n (alloc (loop repeat 1000
count (let ((key (random-number)))
(if (gethash key ht)
(setf (gethash key ht)
(random-number))))))))
(gc :full t)
(gc :full t)
(assert (= n (hash-table-count ht)))))))
(defun add-removable-stuff (ht &key (n 100) (size 10))
(flet ((unique-object ()
(make-array size :fill-pointer 0)))
(loop for i below n do
(multiple-value-bind (key value)
(ecase (hash-table-weakness ht)
((:key) (values (unique-object) i))
((:value) (values i (unique-object)))
((:key-and-value)
(if (zerop (random 2))
(values (unique-object) i)
(values i (unique-object))))
((:key-or-value)
(values (unique-object) (unique-object))))
(setf (gethash key ht) value)))
(values)))
(defun print-ht (ht &optional (stream t))
(format stream "Weakness: ~S~%" (sb-impl::hash-table-weakness ht))
(format stream "Table: ~S~%" (sb-impl::hash-table-table ht))
(format stream "Next: ~S~%" (sb-impl::hash-table-next-vector ht))
(format stream "Index: ~S~%" (sb-impl::hash-table-index-vector ht))
(format stream "Hash: ~S~%" (sb-impl::hash-table-hash-vector ht))
(force-output stream))
(with-test (:name (:hash-table :weakness :removal))
(loop for test in '(eq eql equal equalp) do
(format t "test: ~A~%" test)
(loop for weakness in '(:key :value :key-and-value :key-or-value)
do
(format t "weakness: ~A~%" weakness)
(let ((ht (make-hash-table :test 'equal :weakness weakness)))
(alloc (add-removable-stuff ht :n 117 :size 1))
(loop for i upfrom 0
do (format t "~A. count: ~A~%" i (hash-table-count ht))
(force-output)
until (zerop (hash-table-count ht))
do
(when (= i 10)
(print-ht ht)
#-(or x86 x86-64)
(assert nil)
;; With conservative gc the test may not be
;; bullet-proof so it's not an outright
;; failure but a warning.
#+(or x86 x86-64)
(progn
(warn "Weak hash removal test failed for weakness ~A"
weakness)
(return)))
(gc :full t))))))
(with-test (:name (:hash-table :weakness :string-interning))
(let ((ht (make-hash-table :test 'equal :weakness :key))
(s "a"))
(setf (gethash s ht) s)
(assert (eq (gethash s ht) s))
(assert (eq (gethash (copy-seq s) ht) s))))
;;; see if hash_vector is not written when there is none ...
(with-test (:name (:hash-table :weakness :eq))
(loop repeat 10 do
(let ((index (random 2000)))
(let ((first (+ most-positive-fixnum (mod (* index 31) 9)))
(n 50000))
(let ((hash-table (make-hash-table :weakness :key :test 'eq)))
(dotimes (i n)
(setf (gethash (+ first i) hash-table) i))
hash-table)))))
;; used to crash in gc
(with-test (:name (:hash-table :weakness :keep))
(loop repeat 2 do
(let ((h1 (make-hash-table :weakness :key :test #'equal))
(keep ()))
(loop for i from 0 to 1000
for key = i
for value = (make-array 10000 :fill-pointer 0)
do
(push value keep)
(setf (gethash key h1) value))
(sb-ext:gc :full t))))
)
;;; DEFINE-HASH-TABLE-TEST
(defstruct custom-hash-key name)
(defun custom-hash-test (x y)
(equal (custom-hash-key-name x)
(custom-hash-key-name y)))
(defun custom-hash-hash (x)
(sxhash (custom-hash-key-name x)))
(define-hash-table-test custom-hash-test custom-hash-hash)
(with-test (:name define-hash-table-test.1)
(let ((table (make-hash-table :test 'custom-hash-test)))
(setf (gethash (make-custom-hash-key :name "foo") table) :foo)
(setf (gethash (make-custom-hash-key :name "bar") table) :bar)
(assert (eq :foo (gethash (make-custom-hash-key :name "foo") table)))
(assert (eq :bar (gethash (make-custom-hash-key :name "bar") table)))
(assert (eq 'custom-hash-test (hash-table-test table))))
(let ((table (make-hash-table :test #'custom-hash-test)))
(setf (gethash (make-custom-hash-key :name "foo") table) :foo)
(setf (gethash (make-custom-hash-key :name "bar") table) :bar)
(assert (eq :foo (gethash (make-custom-hash-key :name "foo") table)))
(assert (eq :bar (gethash (make-custom-hash-key :name "bar") table)))
(assert (eq 'custom-hash-test (hash-table-test table)))))
(defun head-eql (x y)
(every #'eql (subseq x 0 3) (subseq y 0 3)))
(define-hash-table-test head-eql
(lambda (x)
(logand most-positive-fixnum
(reduce #'+ (map 'list #'sxhash (subseq x 0 3))))))
(with-test (:name define-hash-table-test.2)
(let ((table (make-hash-table :test 'head-eql)))
(setf (gethash #(1 2 3 4) table) :|123|)
(setf (gethash '(2 3 4 7) table) :|234|)
(setf (gethash "foobar" table) :foo)
(assert (eq :|123| (gethash '(1 2 3 ! 6) table)))
(assert (eq :|234| (gethash #(2 3 4 0 2 1 a) table)))
(assert (eq :foo (gethash '(#\f #\o #\o 1 2 3) table)))
(assert (eq 'head-eql (hash-table-test table))))
(let ((table (make-hash-table :test #'head-eql)))
(setf (gethash #(1 2 3 4) table) :|123|)
(setf (gethash '(2 3 4 7) table) :|234|)
(setf (gethash "foobar" table) :foo)
(assert (eq :|123| (gethash '(1 2 3 ! 6) table)))
(assert (eq :|234| (gethash #(2 3 4 0 2 1 a) table)))
(assert (eq :foo (gethash '(#\f #\o #\o 1 2 3) table)))
(assert (eq 'head-eql (hash-table-test table)))))
(with-test (:name make-hash-table/hash-fun)
(let ((table (make-hash-table
:test #'=
:hash-function (lambda (x)
(sxhash (coerce (abs x) 'double-float))))))
(incf (gethash 1 table 0))
(incf (gethash 1.0f0 table))
(incf (gethash 1.0d0 table))
(incf (gethash (complex 1.0f0 0.0f0) table))
(incf (gethash (complex 1.0d0 0.0d0) table))
(assert (= 5 (gethash 1 table)))
(assert (eq '= (hash-table-test table)))))
;;; success
| null | https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/tests/hash.impure.lisp | lisp | more information.
files (like this one) were written from scratch after the fork
This software is in the public domain and is provided with
absolutely no warranty. See the COPYING and CREDITS files for
more information.
space of possible values, so that collisions between the hash
values of unequal objects should be very uncommon. (Except of
In order to better test not-EQ-but-EQUAL and not-EQ-but-EQUALP,
we'd like to suppress some optimizations.
FIXME: What about multi-dimensional arrays, hmm?
Note:
not-EQ-but-EQUAL and not-EQ-but-EQUALP cases.
we get too many false positives "SXHASHes are equal even
FIXME: Or am I misunderstanding the intent of the
doesn't, in order to avoid hashing together things which
seems to leave this completely unspecified: should
ignores? For our internal hash tables, the stricter
descend-into-the-structure behavior might improve
is it reasonable for users to expect it? Hmm..
PSXHASH-equality iff EQUALP could fail because of an unlucky
random collision. That's not very likely (since there are
test cases, so even with the birthday paradox a collision has
probability only (/ (EXPT 100 2) (EXPT 2 29)), but it's
probably worth checking if you are getting a mystifying error
change from run to run, so the random chance of bogus failure
happens once every time the code is changed in such a way
tests are run.)
(If you get a surprising failure here, maybe you were
just very unlucky; see the notes above.)
(If you get a surprising failure here, maybe you were
just very unlucky; see the notes above.)
their own their own PRINT-OBJECT (HASH-TABLE T) methods, and they
can't even wiggle out of it by subclassing HASH-TABLE or STREAM.)
This test works reliably on non-conservative platforms and
somewhat reliably on conservative platforms with threads.
With conservative gc the test may not be
bullet-proof so it's not an outright
failure but a warning.
see if hash_vector is not written when there is none ...
used to crash in gc
DEFINE-HASH-TABLE-TEST
success | This software is part of the SBCL system . See the README file for
While most of SBCL is derived from the CMU CL system , the test
from CMU CL .
(in-package :cl-user)
(use-package :test-util)
(use-package :assertoid)
(defstruct foo)
(defstruct bar x y)
SXHASH and PSXHASH should distribute hash values well over the
course the hash values must collide when the objects are EQUAL or
EQUALP respectively ! )
(locally
(declare (notinline complex float coerce + - expt))
(flet ((make-sxhash-subtests ()
(list (cons 0 1)
(list 0 1)
(cons 1 0)
(cons (cons 1 0) (cons 0 0))
(cons (list 1 0) (list 0 0))
(list (cons 1 0) (list 0 0))
(list (cons 0 1) (list 0 0))
(list (cons 0 0) (cons 1 0))
(list (cons 0 0) (cons 0 1))
44 (float 44) (coerce 44 'double-float)
-44 (float -44) (coerce -44 'double-float)
0 (float 0) (coerce 0 'double-float)
-0 (- (float 0)) (- (coerce 0 'double-float))
-121 (float -121) (coerce -121 'double-float)
3/4 (float 3/4) (coerce 3/4 'double-float)
-3/4 (float -3/4) (coerce -3/4 'double-float)
45 (float 45) (coerce 45 'double-float)
441/10 (float 441/10) (coerce (float 441/10) 'double-float)
(expt 2 33) (expt 2.0 33) (expt 2.0d0 33)
(- (expt 1/2 50)) (- (expt 0.5 50)) (- (expt 0.5d0 50))
(+ (expt 1/2 50)) (+ (expt 0.5 50)) (+ (expt 0.5d0 50))
(complex 1.0 2.0) (complex 1.0d0 2.0)
(complex 1.5 -3/2) (complex 1.5 -1.5d0)
#\x #\X #\*
(copy-seq "foo") (copy-seq "foobar") (copy-seq "foobarbaz")
(copy-seq #*)
(copy-seq #*0) (copy-seq #*1)
(copy-seq #*00) (copy-seq #*10)
(copy-seq #*01) (copy-seq #*11)
(copy-seq #*10010) (copy-seq #*100101) (bit-not #*01101)
(make-array 6 :fill-pointer 6
:element-type 'bit :initial-contents #*100101)
#'allocate-instance #'no-applicable-method))
(make-psxhash-extra-subtests ()
(list (copy-seq "")
(copy-seq #*)
(copy-seq #())
(copy-seq ())
(copy-seq '(()))
(copy-seq #(()))
(copy-seq '(#()))
(make-array 3 :fill-pointer 0)
(make-array 7 :fill-pointer 0 :element-type 'bit)
(make-array 8 :fill-pointer 0 :element-type 'character)
(vector (cons 1 0) (cons 0 0))
(vector (cons 0 1) (cons 0 0))
(vector (cons 0 0) (cons 1 0))
(vector (cons 0 0) (cons 0 1))
(vector (cons 1 0) (cons 0 0))
(vector (cons 0 1) (cons 0 0))
(vector (list 0 0) (cons 1 0))
(vector (list 0 0) (list 0 1))
(vector (vector 1 0) (list 0 0))
(vector (vector 0 1) (list 0 0))
(vector (vector 0 0) (list 1 0))
(vector (vector 0 0) (list 0 1))
(vector #*00 #*10)
(vector (vector 0 0) (list 0 1.0d0))
(vector (vector -0.0d0 0) (list 1.0 0))
(vector 1 0 1 0)
(vector 0 0 0)
(copy-seq #*1010)
(copy-seq #*000)
(replace (make-array 101
:element-type 'bit
:fill-pointer 4)
#*1010)
(replace (make-array 14
:element-type '(unsigned-byte 8)
:fill-pointer 3)
#*000)
(replace (make-array 14
:element-type t
:fill-pointer 3)
#*000)
(copy-seq "abc")
(copy-seq "ABC")
(copy-seq "aBc")
(copy-seq "abcc")
(copy-seq "1001")
'abc
(vector #\a #\b #\c)
(vector 'a 'b 'c)
(vector "A" 'b 'c)
(replace (make-array 14
:element-type 'character
:fill-pointer 3)
"aBc")
(replace (make-array 11
:element-type 'character
:fill-pointer 4)
"1001")
(replace (make-array 12
:element-type 'bit
:fill-pointer 4)
#*1001)
(replace (make-array 13
:element-type t
:fill-pointer 4)
"1001")
(replace (make-array 13
:element-type t
:fill-pointer 4)
#*1001)
(make-hash-table)
(make-hash-table :test 'equal)
(make-foo)
(make-bar)
(make-bar :x (list 1))
(make-bar :y (list 1))))
(t->boolean (x) (if x t nil)))
* The noise here is to help more strenuously test
* It seems not to be worth the hassle testing SXHASH on
values whose structure is n't understood by EQUAL , since
though values are n't EQUAL , what a crummy hash function ! "
the SXHASH specification ? Perhaps SXHASH is supposed to
descend into the structure of objects even when EQUAL
are guaranteed not to be EQUAL ? The definition of SXHASH
" well - distributed " depend on substructure that EQUAL
performance even though it 's not specified by ANSI . But
(sxhash-tests (append (make-sxhash-subtests)
(make-sxhash-subtests)))
(psxhash-tests (append sxhash-tests
(make-psxhash-extra-subtests)
(make-psxhash-extra-subtests))))
Check that SXHASH compiler transforms give the same results
as the out - of - line version of SXHASH .
(let* ((fundef `(lambda ()
(list ,@(mapcar (lambda (value)
`(sxhash ',value))
sxhash-tests))))
(fun (compile nil fundef)))
(assert (equal (funcall fun)
(mapcar #'sxhash sxhash-tests))))
Note : The tests for SXHASH - equality iff EQUAL and
( EXPT 2 29 ) possible hash values and only on the order of 100
from this test . ( SXHASH values and PSXHASH values do n't
that the SXHASH distribution changes , not once every time the
(dolist (i sxhash-tests)
(declare (notinline funcall))
(unless (typep (funcall #'sxhash i) '(and fixnum unsigned-byte))
(error "bad SXHASH behavior for ~S" i))
(dolist (j sxhash-tests)
(unless (or (eq (t->boolean (equal i j))
(t->boolean (= (sxhash i) (sxhash j))))
(and (typep i 'number)
(typep j 'number)
(= i j)
(subtypep (type-of i) (type-of j))
(subtypep (type-of j) (type-of i))))
(error "bad SXHASH behavior for ~S ~S" i j))))
(dolist (i psxhash-tests)
(unless (typep (sb-int:psxhash i) '(and fixnum unsigned-byte))
(error "bad PSXHASH behavior for ~S" i))
(dolist (j psxhash-tests)
(unless (eq (t->boolean (equalp i j))
(t->boolean (= (sb-int:psxhash i) (sb-int:psxhash j))))
(error "bad PSXHASH behavior for ~S ~S" i j))))
)))
As of sbcl-0.6.12.10 , writing hash tables readably should work .
This is n't required by the ANSI standard , but it should be , since
it 's well - defined useful behavior which ANSI prohibits the users
from implementing themselves . ( ANSI says the users ca n't define
(let ((original-ht (make-hash-table :test 'equal :size 111))
(original-keys '(1 10 11 400030002 -100000000)))
(dolist (key original-keys)
(setf (gethash key original-ht)
(expt key 4)))
(let* ((written-ht (with-output-to-string (s)
(write original-ht :stream s :readably t)))
(read-ht (with-input-from-string (s written-ht)
(read s))))
(assert (= (hash-table-count read-ht)
(hash-table-count original-ht)
(length original-keys)))
(assert (eql (hash-table-test original-ht) (hash-table-test read-ht)))
(assert (eql (hash-table-size original-ht) (hash-table-size read-ht)))
(dolist (key original-keys)
(assert (eql (gethash key read-ht)
(gethash key original-ht))))))
NIL is both SYMBOL and LIST
(dolist (fun '(sxhash sb-impl::psxhash))
(assert (= (eval `(,fun nil))
(funcall fun nil)
(funcall (compile nil `(lambda (x)
(declare (symbol x))
(,fun x)))
nil)
(funcall (compile nil `(lambda (x)
(declare (list x))
(,fun x)))
nil)
(funcall (compile nil `(lambda (x)
(declare (null x))
(,fun x)))
nil))))
#+(or (not (or x86 x86-64)) sb-thread)
(progn
(defparameter *ht* nil)
(defvar *cons-here*)
(declaim (notinline args))
(defun take (&rest args)
(declare (ignore args)))
(defmacro alloc (&body body)
"Execute BODY and try to reduce the chance of leaking a conservative root."
#-sb-thread
`(multiple-value-prog1
(progn ,@body)
(loop repeat 20000 do (setq *cons-here* (cons nil nil)))
: Clean the argument passing regs .
(apply #'take (loop repeat 36 collect #'cons)))
#+sb-thread
(let ((values (gensym))
(sem (gensym)))
`(let ((,sem (sb-thread::make-semaphore))
,values)
(sb-thread:make-thread (lambda ()
(setq ,values
(multiple-value-list (progn ,@body)))
(sb-thread::signal-semaphore ,sem)))
(sb-thread::wait-on-semaphore ,sem)
(values-list ,values))))
(with-test (:name (:hash-table :weakness :eql :numbers))
(flet ((random-number ()
(random 1000)))
(loop for weakness in '(nil :key :value :key-and-value :key-or-value) do
(let* ((ht (make-hash-table :weakness weakness))
(n (alloc (loop repeat 1000
count (let ((key (random-number)))
(if (gethash key ht)
(setf (gethash key ht)
(random-number))))))))
(gc :full t)
(gc :full t)
(assert (= n (hash-table-count ht)))))))
(defun add-removable-stuff (ht &key (n 100) (size 10))
(flet ((unique-object ()
(make-array size :fill-pointer 0)))
(loop for i below n do
(multiple-value-bind (key value)
(ecase (hash-table-weakness ht)
((:key) (values (unique-object) i))
((:value) (values i (unique-object)))
((:key-and-value)
(if (zerop (random 2))
(values (unique-object) i)
(values i (unique-object))))
((:key-or-value)
(values (unique-object) (unique-object))))
(setf (gethash key ht) value)))
(values)))
(defun print-ht (ht &optional (stream t))
(format stream "Weakness: ~S~%" (sb-impl::hash-table-weakness ht))
(format stream "Table: ~S~%" (sb-impl::hash-table-table ht))
(format stream "Next: ~S~%" (sb-impl::hash-table-next-vector ht))
(format stream "Index: ~S~%" (sb-impl::hash-table-index-vector ht))
(format stream "Hash: ~S~%" (sb-impl::hash-table-hash-vector ht))
(force-output stream))
(with-test (:name (:hash-table :weakness :removal))
(loop for test in '(eq eql equal equalp) do
(format t "test: ~A~%" test)
(loop for weakness in '(:key :value :key-and-value :key-or-value)
do
(format t "weakness: ~A~%" weakness)
(let ((ht (make-hash-table :test 'equal :weakness weakness)))
(alloc (add-removable-stuff ht :n 117 :size 1))
(loop for i upfrom 0
do (format t "~A. count: ~A~%" i (hash-table-count ht))
(force-output)
until (zerop (hash-table-count ht))
do
(when (= i 10)
(print-ht ht)
#-(or x86 x86-64)
(assert nil)
#+(or x86 x86-64)
(progn
(warn "Weak hash removal test failed for weakness ~A"
weakness)
(return)))
(gc :full t))))))
(with-test (:name (:hash-table :weakness :string-interning))
(let ((ht (make-hash-table :test 'equal :weakness :key))
(s "a"))
(setf (gethash s ht) s)
(assert (eq (gethash s ht) s))
(assert (eq (gethash (copy-seq s) ht) s))))
(with-test (:name (:hash-table :weakness :eq))
(loop repeat 10 do
(let ((index (random 2000)))
(let ((first (+ most-positive-fixnum (mod (* index 31) 9)))
(n 50000))
(let ((hash-table (make-hash-table :weakness :key :test 'eq)))
(dotimes (i n)
(setf (gethash (+ first i) hash-table) i))
hash-table)))))
(with-test (:name (:hash-table :weakness :keep))
(loop repeat 2 do
(let ((h1 (make-hash-table :weakness :key :test #'equal))
(keep ()))
(loop for i from 0 to 1000
for key = i
for value = (make-array 10000 :fill-pointer 0)
do
(push value keep)
(setf (gethash key h1) value))
(sb-ext:gc :full t))))
)
(defstruct custom-hash-key name)
(defun custom-hash-test (x y)
(equal (custom-hash-key-name x)
(custom-hash-key-name y)))
(defun custom-hash-hash (x)
(sxhash (custom-hash-key-name x)))
(define-hash-table-test custom-hash-test custom-hash-hash)
(with-test (:name define-hash-table-test.1)
(let ((table (make-hash-table :test 'custom-hash-test)))
(setf (gethash (make-custom-hash-key :name "foo") table) :foo)
(setf (gethash (make-custom-hash-key :name "bar") table) :bar)
(assert (eq :foo (gethash (make-custom-hash-key :name "foo") table)))
(assert (eq :bar (gethash (make-custom-hash-key :name "bar") table)))
(assert (eq 'custom-hash-test (hash-table-test table))))
(let ((table (make-hash-table :test #'custom-hash-test)))
(setf (gethash (make-custom-hash-key :name "foo") table) :foo)
(setf (gethash (make-custom-hash-key :name "bar") table) :bar)
(assert (eq :foo (gethash (make-custom-hash-key :name "foo") table)))
(assert (eq :bar (gethash (make-custom-hash-key :name "bar") table)))
(assert (eq 'custom-hash-test (hash-table-test table)))))
(defun head-eql (x y)
(every #'eql (subseq x 0 3) (subseq y 0 3)))
(define-hash-table-test head-eql
(lambda (x)
(logand most-positive-fixnum
(reduce #'+ (map 'list #'sxhash (subseq x 0 3))))))
(with-test (:name define-hash-table-test.2)
(let ((table (make-hash-table :test 'head-eql)))
(setf (gethash #(1 2 3 4) table) :|123|)
(setf (gethash '(2 3 4 7) table) :|234|)
(setf (gethash "foobar" table) :foo)
(assert (eq :|123| (gethash '(1 2 3 ! 6) table)))
(assert (eq :|234| (gethash #(2 3 4 0 2 1 a) table)))
(assert (eq :foo (gethash '(#\f #\o #\o 1 2 3) table)))
(assert (eq 'head-eql (hash-table-test table))))
(let ((table (make-hash-table :test #'head-eql)))
(setf (gethash #(1 2 3 4) table) :|123|)
(setf (gethash '(2 3 4 7) table) :|234|)
(setf (gethash "foobar" table) :foo)
(assert (eq :|123| (gethash '(1 2 3 ! 6) table)))
(assert (eq :|234| (gethash #(2 3 4 0 2 1 a) table)))
(assert (eq :foo (gethash '(#\f #\o #\o 1 2 3) table)))
(assert (eq 'head-eql (hash-table-test table)))))
(with-test (:name make-hash-table/hash-fun)
(let ((table (make-hash-table
:test #'=
:hash-function (lambda (x)
(sxhash (coerce (abs x) 'double-float))))))
(incf (gethash 1 table 0))
(incf (gethash 1.0f0 table))
(incf (gethash 1.0d0 table))
(incf (gethash (complex 1.0f0 0.0f0) table))
(incf (gethash (complex 1.0d0 0.0d0) table))
(assert (= 5 (gethash 1 table)))
(assert (eq '= (hash-table-test table)))))
|
3931ccd674e8577767c38dacb51ba607bb36fcb34f81b8b344d4bf3b9422ff79 | graninas/Hydra | Language.hs | module Hydra.Core.ControlFlow.Language where
import Hydra.Prelude
import Hydra.Core.ControlFlow.Class
data ControlFlowF next where
-- | Freeze the current thread on time (in microseconds).
Delay :: Int -> (() -> next) -> ControlFlowF next
instance Functor ControlFlowF where
fmap g (Delay i next) = Delay i (g . next)
type ControlFlowL = Free ControlFlowF
instance ControlFlow (Free ControlFlowF) where
delay i = liftF $ Delay i id
| null | https://raw.githubusercontent.com/graninas/Hydra/60d591b1300528f5ffd93efa205012eebdd0286c/lib/hydra-free/src/Hydra/Core/ControlFlow/Language.hs | haskell | | Freeze the current thread on time (in microseconds). | module Hydra.Core.ControlFlow.Language where
import Hydra.Prelude
import Hydra.Core.ControlFlow.Class
data ControlFlowF next where
Delay :: Int -> (() -> next) -> ControlFlowF next
instance Functor ControlFlowF where
fmap g (Delay i next) = Delay i (g . next)
type ControlFlowL = Free ControlFlowF
instance ControlFlow (Free ControlFlowF) where
delay i = liftF $ Delay i id
|
aba5034122895e5d66388a1cbe555505f89157ce307a0c850186c76edb023d33 | c089/haskell-craft3e | Base.hs | -------------------------------------------------------------------------
--
Haskell : The Craft of Functional Programming , 3e
( c ) Addison - Wesley , 1996 - 2011 .
--
-- The basis of the simulation package.
--
-------------------------------------------------------------------------
module Base where
-- The type of input messages.
data Inmess = No | Yes Arrival Service
deriving (Eq,Show)
type Arrival = Int
type Service = Int
-- The type of output messages.
data Outmess = None | Discharge Arrival Wait Service
deriving (Eq,Show)
type Wait = Int
| null | https://raw.githubusercontent.com/c089/haskell-craft3e/869e382601cab50559c4473dfa9c7480f1acba58/Simulation/Base.hs | haskell | -----------------------------------------------------------------------
The basis of the simulation package.
-----------------------------------------------------------------------
The type of input messages.
The type of output messages. | Haskell : The Craft of Functional Programming , 3e
( c ) Addison - Wesley , 1996 - 2011 .
module Base where
data Inmess = No | Yes Arrival Service
deriving (Eq,Show)
type Arrival = Int
type Service = Int
data Outmess = None | Discharge Arrival Wait Service
deriving (Eq,Show)
type Wait = Int
|
89783c66f43db0b343bb37d854f5a0961a19a082975f47622429ff59e47057ea | HaskellZhangSong/Introduction_to_Haskell_2ed_source | TypeFamily3.hs | # LANGUAGE TypeFamilies #
import Data.Vector
import Data.Sequence
data family Array a
data instance Array Int = MkArrayInt (Vector Int)
data instance Array Char = MkArrayChar (Seq Char) | null | https://raw.githubusercontent.com/HaskellZhangSong/Introduction_to_Haskell_2ed_source/140c50fdccfe608fe499ecf2d8a3732f531173f5/C16/TypeFamily3.hs | haskell | # LANGUAGE TypeFamilies #
import Data.Vector
import Data.Sequence
data family Array a
data instance Array Int = MkArrayInt (Vector Int)
data instance Array Char = MkArrayChar (Seq Char) | |
36a2e5f243214371dfc963fcb3977644056015db0d27c334a82fdd9a983ea2e1 | alexanderwasey/stupid-computer | Sumif.hs | module Sumif where
sum' :: Num a => [a] -> a
sum' xs = if (not (null xs)) then (head xs) + sum' (tail xs) else 0
demo = sum' [1,2,3] | null | https://raw.githubusercontent.com/alexanderwasey/stupid-computer/a485d2f33a4b8d58128a74b9003b9eadffe42702/examples/Sumif.hs | haskell | module Sumif where
sum' :: Num a => [a] -> a
sum' xs = if (not (null xs)) then (head xs) + sum' (tail xs) else 0
demo = sum' [1,2,3] | |
76d79fb9a0f456d6199ec33547ccc87914c61d4a30e6c2dc7bd3bef88ef66282 | awslabs/s2n-bignum | bignum_deamont_p521.ml |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
(* ========================================================================= *)
(* Mapping out of almost-Montgomery representation modulo p_521. *)
(* ========================================================================= *)
* * * print_literal_from_elf " x86 / p521 / " ; ;
* * *
****)
let bignum_deamont_p521_mc =
define_assert_from_elf "bignum_deamont_p521_mc" "x86/p521/bignum_deamont_p521.o"
[
0x53; (* PUSH (% rbx) *)
0x41; 0x54; (* PUSH (% r12) *)
0x41; 0x55; (* PUSH (% r13) *)
0x55; (* PUSH (% rbp) *)
MOV ( % rdx ) ( ( % % ( rsi,0 ) ) )
MOV ( % rax ) ( % rdx )
SHL ( % rax ) ( Imm8 ( word 9 ) )
MOV ( % rcx ) ( ( % % ( rsi,8 ) ) )
0x48; 0x0f; 0xac; 0xca; 0x37;
SHRD ( % rdx ) ( % rcx ) ( Imm8 ( word 55 ) )
MOV ( % r8 ) ( ( % % ( rsi,16 ) ) )
0x4c; 0x0f; 0xac; 0xc1; 0x37;
SHRD ( % rcx ) ( % r8 ) ( Imm8 ( word 55 ) )
MOV ( % r9 ) ( ( % % ( rsi,24 ) ) )
0x4d; 0x0f; 0xac; 0xc8; 0x37;
SHRD ( % r8 ) ( % r9 ) ( Imm8 ( word 55 ) )
MOV ( % r10 ) ( ( % % ( ) ) )
0x4d; 0x0f; 0xac; 0xd1; 0x37;
SHRD ( % r9 ) ( % r10 ) ( Imm8 ( word 55 ) )
MOV ( % r11 ) ( ( % % ( rsi,40 ) ) )
0x4d; 0x0f; 0xac; 0xda; 0x37;
SHRD ( % r10 ) ( % r11 ) ( Imm8 ( word 55 ) )
MOV ( % r12 ) ( ( % % ( rsi,48 ) ) )
0x4d; 0x0f; 0xac; 0xe3; 0x37;
SHRD ( % r11 ) ( % r12 ) ( Imm8 ( word 55 ) )
MOV ( % r13 ) ( ( % % ( ) ) )
0x4d; 0x0f; 0xac; 0xec; 0x37;
SHRD ( % r12 ) ( % r13 ) ( Imm8 ( word 55 ) )
MOV ( % rbp ) ( ( % % ( rsi,64 ) ) )
0x49; 0x0f; 0xac; 0xed; 0x37;
SHRD ( % r13 ) ( % rbp ) ( Imm8 ( word 55 ) )
SHR ( % rbp ) ( Imm8 ( word 55 ) )
MOV ( % rbx ) ( % rax )
SHR ( % rax ) ( Imm8 ( word 55 ) )
SHL ( % rbx ) ( Imm8 ( word 9 ) )
0x48; 0x81; 0xcd; 0x00; 0xfe; 0xff; 0xff;
OR ( % rbp ) ( Imm32 ( word 4294966784 ) )
ADD ( % rdx ) ( Imm8 ( word 1 ) )
0x48; 0x83; 0xd1; 0x00; (* ADC (% rcx) (Imm8 (word 0)) *)
0x49; 0x83; 0xd0; 0x00; (* ADC (% r8) (Imm8 (word 0)) *)
0x49; 0x83; 0xd1; 0x00; (* ADC (% r9) (Imm8 (word 0)) *)
0x49; 0x83; 0xd2; 0x00; (* ADC (% r10) (Imm8 (word 0)) *)
0x49; 0x83; 0xd3; 0x00; (* ADC (% r11) (Imm8 (word 0)) *)
0x49; 0x83; 0xd4; 0x00; (* ADC (% r12) (Imm8 (word 0)) *)
0x49; 0x11; 0xdd; (* ADC (% r13) (% rbx) *)
0x48; 0x11; 0xc5; (* ADC (% rbp) (% rax) *)
CMC
SBB ( % rdx ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,0 ) ) ) ( % rdx )
SBB ( % rcx ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,8 ) ) ) ( % rcx )
SBB ( % r8 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,16 ) ) ) ( % r8 )
SBB ( % r9 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( ) ) ) ( % r9 )
SBB ( % r10 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,32 ) ) ) ( % r10 )
SBB ( % r11 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,40 ) ) ) ( % r11 )
SBB ( % r12 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,48 ) ) ) ( % r12 )
SBB ( % r13 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( ) ) ) ( % r13 )
SBB ( % rbp ) ( Imm8 ( word 0 ) )
0x48; 0x81; 0xe5; 0xff; 0x01; 0x00; 0x00;
AND ( % rbp ) ( Imm32 ( word 511 ) )
MOV ( ( % % ( rdi,64 ) ) ) ( % rbp )
0x5d; (* POP (% rbp) *)
0x41; 0x5d; (* POP (% r13) *)
0x41; 0x5c; (* POP (% r12) *)
0x5b; (* POP (% rbx) *)
RET
];;
let BIGNUM_DEAMONT_P521_EXEC = X86_MK_CORE_EXEC_RULE bignum_deamont_p521_mc;;
(* ------------------------------------------------------------------------- *)
(* Proof. *)
(* ------------------------------------------------------------------------- *)
let p_521 = new_definition `p_521 = 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151`;;
let BIGNUM_DEAMONT_P521_CORRECT = time prove
(`!z x a pc.
nonoverlapping (word pc,0xe6) (z,8 * 9)
==> ensures x86
(\s. bytes_loaded s (word pc) (BUTLAST bignum_deamont_p521_mc) /\
read RIP s = word(pc + 0x06) /\
C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,9) s = a)
(\s. read RIP s = word (pc + 0xdf) /\
bignum_from_memory (z,9) s =
(inverse_mod p_521 (2 EXP 576) * a) MOD p_521)
(MAYCHANGE [RIP; RAX; RCX; RDX;
R8; R9; R10; R11; RBX; RBP; R12; R13] ,,
MAYCHANGE [memory :> bytes(z,8 * 9)] ,,
MAYCHANGE SOME_FLAGS)`,
MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `n:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
* * Digitize and break the input into n = 2 * 55 * h + l * *
ENSURES_INIT_TAC "s0" THEN
BIGNUM_LDIGITIZE_TAC "x_" `bignum_from_memory (x,9) s0` THEN
MAP_EVERY ABBREV_TAC [`h = n DIV 2 EXP 55`; `l = n MOD 2 EXP 55`] THEN
SUBGOAL_THEN `l < 2 EXP 55` ASSUME_TAC THENL
[EXPAND_TAC "l" THEN ARITH_TAC; ALL_TAC] THEN
SUBGOAL_THEN `h < 2 EXP 521` ASSUME_TAC THENL
[EXPAND_TAC "h" THEN REWRITE_TAC[ARITH_RULE
`n DIV 2 EXP 55 < 2 EXP 521 <=> n < 2 EXP (64 * 9)`] THEN
EXPAND_TAC "n" THEN MATCH_MP_TAC BIGNUM_OF_WORDLIST_BOUND THEN
REWRITE_TAC[LENGTH] THEN ARITH_TAC;
ALL_TAC] THEN
SUBGOAL_THEN
`(inverse_mod p_521 (2 EXP 576) * n) MOD p_521 =
(h + 2 EXP 466 * l) MOD p_521`
SUBST1_TAC THENL
[SUBST1_TAC(ARITH_RULE
`n = 2 EXP 55 * n DIV 2 EXP 55 + n MOD 2 EXP 55`) THEN
ASM_REWRITE_TAC[GSYM CONG] THEN
MATCH_MP_TAC(NUMBER_RULE
`!e. (e * i == 1) (mod n) /\ (e * hl == a) (mod n)
==> (i * a == hl) (mod n)`) THEN
EXISTS_TAC `2 EXP 576` THEN
REWRITE_TAC[GSYM(NUM_REDUCE_CONV `2 EXP 576`); INVERSE_MOD_RMUL_EQ] THEN
REWRITE_TAC[COPRIME_REXP; COPRIME_2; p_521] THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[REAL_CONGRUENCE] THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REAL_INTEGER_TAC;
ALL_TAC] THEN
(*** The actual computations of h and l ***)
X86_STEPS_TAC BIGNUM_DEAMONT_P521_EXEC (1--20) THEN
MAP_EVERY ABBREV_TAC
[`d0:int64 =
word_subword ((word_join:int64->int64->int128) x_1 x_0) (55,64)`;
`d1:int64 =
word_subword ((word_join:int64->int64->int128) x_2 x_1) (55,64)`;
`d2:int64 =
word_subword ((word_join:int64->int64->int128) x_3 x_2) (55,64)`;
`d3:int64 =
word_subword ((word_join:int64->int64->int128) x_4 x_3) (55,64)`;
`d4:int64 =
word_subword ((word_join:int64->int64->int128) x_5 x_4) (55,64)`;
`d5:int64 =
word_subword ((word_join:int64->int64->int128) x_6 x_5) (55,64)`;
`d6:int64 =
word_subword ((word_join:int64->int64->int128) x_7 x_6) (55,64)`;
`d7:int64 =
word_subword ((word_join:int64->int64->int128) x_8 x_7) (55,64)`;
`d8:int64 = word_ushr x_8 55`] THEN
SUBGOAL_THEN `word_shl (x_0:int64) 9 = word(2 EXP 9 * l)` SUBST_ALL_TAC THENL
[MAP_EVERY EXPAND_TAC ["l"; "n"] THEN REWRITE_TAC[word_shl; WORD_EQ] THEN
REWRITE_TAC[BIGNUM_OF_WORDLIST_SPLIT_RULE(1,8)] THEN
REWRITE_TAC[DIMINDEX_64; ARITH_RULE `64 = 55 + 9`; EXP_ADD] THEN
REWRITE_TAC[GSYM MULT_ASSOC; MOD_MULT_ADD] THEN
MATCH_MP_TAC(NUMBER_RULE
`(a:num == b) (mod n) ==> (a * e == e * b) (mod (n * e))`) THEN
REWRITE_TAC[CONG; BIGNUM_OF_WORDLIST_SING] THEN CONV_TAC MOD_DOWN_CONV THEN
REFL_TAC;
ALL_TAC] THEN
SUBGOAL_THEN
`n DIV 2 EXP 55 = bignum_of_wordlist[d0;d1;d2;d3;d4;d5;d6;d7;d8]`
SUBST_ALL_TAC THENL
[MATCH_MP_TAC DIV_UNIQ THEN
EXISTS_TAC `val(x_0:int64) MOD 2 EXP 55` THEN
REWRITE_TAC[ARITH_RULE `x MOD 2 EXP 55 < 2 EXP 55`] THEN
REWRITE_TAC[GSYM VAL_WORD_AND_MASK_WORD] THEN EXPAND_TAC "n" THEN
MAP_EVERY EXPAND_TAC
["d0"; "d1"; "d2"; "d3"; "d4"; "d5"; "d6"; "d7"; "d8"] THEN
REWRITE_TAC[val_def; DIMINDEX_64; bignum_of_wordlist] THEN
REWRITE_TAC[ARITH_RULE `i < 64 <=> 0 <= i /\ i <= 63`] THEN
REWRITE_TAC[GSYM IN_NUMSEG; IN_GSPEC] THEN
REWRITE_TAC[BIT_WORD_SUBWORD; BIT_WORD_JOIN; BIT_WORD_AND;
BIT_WORD_USHR; DIMINDEX_64; DIMINDEX_128] THEN
CONV_TAC NUM_REDUCE_CONV THEN
CONV_TAC(ONCE_DEPTH_CONV EXPAND_NSUM_CONV) THEN
CONV_TAC NUM_REDUCE_CONV THEN ONCE_REWRITE_TAC[BIT_GUARD] THEN
REWRITE_TAC[DIMINDEX_64] THEN
CONV_TAC(DEPTH_CONV(NUM_RED_CONV ORELSEC WORD_RED_CONV ORELSEC
GEN_REWRITE_CONV I [BITVAL_CLAUSES])) THEN
CONV_TAC NUM_RING;
ALL_TAC] THEN
(*** The comparison ***)
SUBGOAL_THEN
`&(val(word_or d8 (word 18446744073709551104):int64)):real =
&2 pow 9 * (&2 pow 55 - &1) + &(val d8)`
ASSUME_TAC THENL
[ONCE_REWRITE_TAC[WORD_BITWISE_RULE
`word_or a b = word_or b (word_and a (word_not b))`] THEN
SIMP_TAC[VAL_WORD_OR_DISJOINT; WORD_BITWISE_RULE
`word_and x (word_and y (word_not x)) = word 0`] THEN
CONV_TAC WORD_REDUCE_CONV THEN CONV_TAC REAL_RAT_REDUCE_CONV THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES; EQ_ADD_LCANCEL] THEN
AP_TERM_TAC THEN REWRITE_TAC[WORD_EQ_BITS_ALT; DIMINDEX_64] THEN
EXPAND_TAC "d8" THEN
REWRITE_TAC[BIT_WORD_AND; BIT_WORD_USHR; DIMINDEX_64] THEN
ONCE_REWRITE_TAC[BIT_GUARD] THEN REWRITE_TAC[DIMINDEX_64] THEN
CONV_TAC EXPAND_CASES_CONV THEN
CONV_TAC(DEPTH_CONV(NUM_RED_CONV ORELSEC WORD_RED_CONV));
ALL_TAC] THEN
SUBGOAL_THEN
`bignum_of_wordlist
[word_shl (word (512 * l)) 9; word_ushr (word (512 * l)) 55] =
2 EXP 18 * l`
ASSUME_TAC THENL
[REWRITE_TAC[bignum_of_wordlist; VAL_WORD_SHL; VAL_WORD_USHR] THEN
REWRITE_TAC[DIMINDEX_64; EXP_ADD; ARITH_RULE `64 = 9 + 55`] THEN
REWRITE_TAC[MOD_MULT2; GSYM MULT_ASSOC; GSYM LEFT_ADD_DISTRIB] THEN
REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES] THEN MATCH_MP_TAC(ARITH_RULE
`x = 512 * l
==> 2 EXP 9 * (x MOD 2 EXP 55 + 2 EXP 55 * x DIV 2 EXP 55) =
2 EXP 18 * l`) THEN
MATCH_MP_TAC VAL_WORD_EQ THEN EXPAND_TAC "l" THEN
REWRITE_TAC[DIMINDEX_64] THEN ARITH_TAC;
ALL_TAC] THEN
X86_ACCSTEPS_TAC BIGNUM_DEAMONT_P521_EXEC (25--33) (21--33) THEN
SUBGOAL_THEN `carry_s33 <=> p_521 <= h + 2 EXP 466 * l` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `576` THEN
SUBGOAL_THEN
`2 EXP 466 * l =
2 EXP 448 * bignum_of_wordlist
[word_shl (word (512 * l)) 9; word_ushr (word (512 * l)) 55]`
SUBST1_TAC THENL [ASM_REWRITE_TAC[] THEN ARITH_TAC; ALL_TAC] THEN
EXPAND_TAC "h" THEN
REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
ASM_REWRITE_TAC[p_521] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
ALL_TAC] THEN
(*** The final correction ***)
ABBREV_TAC `hl = h + 2 EXP 466 * l` THEN
X86_ACCSTEPS_TAC BIGNUM_DEAMONT_P521_EXEC (34--53) (34--53) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONV_TAC(LAND_CONV BIGNUM_LEXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN
MAP_EVERY EXISTS_TAC
[`521`;
`if h + 2 EXP 466 * l < p_521
then &(h + 2 EXP 466 * l)
else &(h + 2 EXP 466 * l) - &p_521`] THEN
REPEAT CONJ_TAC THENL
[BOUNDER_TAC[];
REWRITE_TAC[p_521] THEN ARITH_TAC;
REWRITE_TAC[p_521] THEN ARITH_TAC;
ALL_TAC;
SIMP_TAC[GSYM NOT_LE; COND_SWAP; REAL_OF_NUM_SUB] THEN
REWRITE_TAC[GSYM COND_RAND] THEN AP_TERM_TAC THEN EXPAND_TAC "hl" THEN
REWRITE_TAC[GSYM NOT_LT; COND_SWAP] THEN MATCH_MP_TAC MOD_CASES THEN
MAP_EVERY UNDISCH_TAC [`h < 2 EXP 521`; `l < 2 EXP 55`] THEN
REWRITE_TAC[p_521] THEN ARITH_TAC] THEN
ASM_REWRITE_TAC[] THEN
ABBREV_TAC `bb <=> hl < p_521` THEN MAP_EVERY EXPAND_TAC ["hl"; "h"] THEN
SUBGOAL_THEN
`2 EXP 466 * l =
2 EXP 448 * bignum_of_wordlist
[word_shl (word (512 * l)) 9; word_ushr (word (512 * l)) 55]`
SUBST1_TAC THENL [ASM_REWRITE_TAC[] THEN ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[SYM(NUM_REDUCE_CONV `2 EXP 9 - 1`)] THEN
REWRITE_TAC[VAL_WORD_AND_MASK_WORD; bignum_of_wordlist] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; REAL_OF_NUM_MOD; p_521] THEN
CONV_TAC NUM_REDUCE_CONV THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_INTEGER_TAC);;
let BIGNUM_DEAMONT_P521_SUBROUTINE_CORRECT = time prove
(`!z x a pc stackpointer returnaddress.
nonoverlapping (z,8 * 9) (word_sub stackpointer (word 32),40) /\
ALL (nonoverlapping (word_sub stackpointer (word 32),32))
[(word pc,0xe6); (x,8 * 9)] /\
nonoverlapping (word pc,0xe6) (z,8 * 9)
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_deamont_p521_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,9) s = a)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
bignum_from_memory (z,9) s =
(inverse_mod p_521 (2 EXP 576) * a) MOD p_521)
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 9);
memory :> bytes(word_sub stackpointer (word 32),32)] ,,
MAYCHANGE SOME_FLAGS)`,
X86_PROMOTE_RETURN_STACK_TAC
bignum_deamont_p521_mc BIGNUM_DEAMONT_P521_CORRECT
`[RBX; R12; R13; RBP]` 32);;
(* ------------------------------------------------------------------------- *)
(* Correctness of Windows ABI version. *)
(* ------------------------------------------------------------------------- *)
let windows_bignum_deamont_p521_mc = define_from_elf
"windows_bignum_deamont_p521_mc" "x86/p521/bignum_deamont_p521.obj";;
let WINDOWS_BIGNUM_DEAMONT_P521_SUBROUTINE_CORRECT = time prove
(`!z x a pc stackpointer returnaddress.
nonoverlapping (z,8 * 9) (word_sub stackpointer (word 48),56) /\
ALL (nonoverlapping (word_sub stackpointer (word 48),48))
[(word pc,0xf0); (x,8 * 9)] /\
nonoverlapping (word pc,0xf0) (z,8 * 9)
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_deamont_p521_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,9) s = a)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
bignum_from_memory (z,9) s =
(inverse_mod p_521 (2 EXP 576) * a) MOD p_521)
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 9);
memory :> bytes(word_sub stackpointer (word 48),48)] ,,
MAYCHANGE SOME_FLAGS)`,
WINDOWS_X86_WRAP_STACK_TAC
windows_bignum_deamont_p521_mc bignum_deamont_p521_mc
BIGNUM_DEAMONT_P521_CORRECT `[RBX; R12; R13; RBP]` 32);;
| null | https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/x86/proofs/bignum_deamont_p521.ml | ocaml | =========================================================================
Mapping out of almost-Montgomery representation modulo p_521.
=========================================================================
PUSH (% rbx)
PUSH (% r12)
PUSH (% r13)
PUSH (% rbp)
ADC (% rcx) (Imm8 (word 0))
ADC (% r8) (Imm8 (word 0))
ADC (% r9) (Imm8 (word 0))
ADC (% r10) (Imm8 (word 0))
ADC (% r11) (Imm8 (word 0))
ADC (% r12) (Imm8 (word 0))
ADC (% r13) (% rbx)
ADC (% rbp) (% rax)
POP (% rbp)
POP (% r13)
POP (% r12)
POP (% rbx)
-------------------------------------------------------------------------
Proof.
-------------------------------------------------------------------------
** The actual computations of h and l **
** The comparison **
** The final correction **
-------------------------------------------------------------------------
Correctness of Windows ABI version.
------------------------------------------------------------------------- |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
* * * print_literal_from_elf " x86 / p521 / " ; ;
* * *
****)
let bignum_deamont_p521_mc =
define_assert_from_elf "bignum_deamont_p521_mc" "x86/p521/bignum_deamont_p521.o"
[
MOV ( % rdx ) ( ( % % ( rsi,0 ) ) )
MOV ( % rax ) ( % rdx )
SHL ( % rax ) ( Imm8 ( word 9 ) )
MOV ( % rcx ) ( ( % % ( rsi,8 ) ) )
0x48; 0x0f; 0xac; 0xca; 0x37;
SHRD ( % rdx ) ( % rcx ) ( Imm8 ( word 55 ) )
MOV ( % r8 ) ( ( % % ( rsi,16 ) ) )
0x4c; 0x0f; 0xac; 0xc1; 0x37;
SHRD ( % rcx ) ( % r8 ) ( Imm8 ( word 55 ) )
MOV ( % r9 ) ( ( % % ( rsi,24 ) ) )
0x4d; 0x0f; 0xac; 0xc8; 0x37;
SHRD ( % r8 ) ( % r9 ) ( Imm8 ( word 55 ) )
MOV ( % r10 ) ( ( % % ( ) ) )
0x4d; 0x0f; 0xac; 0xd1; 0x37;
SHRD ( % r9 ) ( % r10 ) ( Imm8 ( word 55 ) )
MOV ( % r11 ) ( ( % % ( rsi,40 ) ) )
0x4d; 0x0f; 0xac; 0xda; 0x37;
SHRD ( % r10 ) ( % r11 ) ( Imm8 ( word 55 ) )
MOV ( % r12 ) ( ( % % ( rsi,48 ) ) )
0x4d; 0x0f; 0xac; 0xe3; 0x37;
SHRD ( % r11 ) ( % r12 ) ( Imm8 ( word 55 ) )
MOV ( % r13 ) ( ( % % ( ) ) )
0x4d; 0x0f; 0xac; 0xec; 0x37;
SHRD ( % r12 ) ( % r13 ) ( Imm8 ( word 55 ) )
MOV ( % rbp ) ( ( % % ( rsi,64 ) ) )
0x49; 0x0f; 0xac; 0xed; 0x37;
SHRD ( % r13 ) ( % rbp ) ( Imm8 ( word 55 ) )
SHR ( % rbp ) ( Imm8 ( word 55 ) )
MOV ( % rbx ) ( % rax )
SHR ( % rax ) ( Imm8 ( word 55 ) )
SHL ( % rbx ) ( Imm8 ( word 9 ) )
0x48; 0x81; 0xcd; 0x00; 0xfe; 0xff; 0xff;
OR ( % rbp ) ( Imm32 ( word 4294966784 ) )
ADD ( % rdx ) ( Imm8 ( word 1 ) )
CMC
SBB ( % rdx ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,0 ) ) ) ( % rdx )
SBB ( % rcx ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,8 ) ) ) ( % rcx )
SBB ( % r8 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,16 ) ) ) ( % r8 )
SBB ( % r9 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( ) ) ) ( % r9 )
SBB ( % r10 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,32 ) ) ) ( % r10 )
SBB ( % r11 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,40 ) ) ) ( % r11 )
SBB ( % r12 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( rdi,48 ) ) ) ( % r12 )
SBB ( % r13 ) ( Imm8 ( word 0 ) )
MOV ( ( % % ( ) ) ) ( % r13 )
SBB ( % rbp ) ( Imm8 ( word 0 ) )
0x48; 0x81; 0xe5; 0xff; 0x01; 0x00; 0x00;
AND ( % rbp ) ( Imm32 ( word 511 ) )
MOV ( ( % % ( rdi,64 ) ) ) ( % rbp )
RET
];;
let BIGNUM_DEAMONT_P521_EXEC = X86_MK_CORE_EXEC_RULE bignum_deamont_p521_mc;;
let p_521 = new_definition `p_521 = 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151`;;
let BIGNUM_DEAMONT_P521_CORRECT = time prove
(`!z x a pc.
nonoverlapping (word pc,0xe6) (z,8 * 9)
==> ensures x86
(\s. bytes_loaded s (word pc) (BUTLAST bignum_deamont_p521_mc) /\
read RIP s = word(pc + 0x06) /\
C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,9) s = a)
(\s. read RIP s = word (pc + 0xdf) /\
bignum_from_memory (z,9) s =
(inverse_mod p_521 (2 EXP 576) * a) MOD p_521)
(MAYCHANGE [RIP; RAX; RCX; RDX;
R8; R9; R10; R11; RBX; RBP; R12; R13] ,,
MAYCHANGE [memory :> bytes(z,8 * 9)] ,,
MAYCHANGE SOME_FLAGS)`,
MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `n:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
* * Digitize and break the input into n = 2 * 55 * h + l * *
ENSURES_INIT_TAC "s0" THEN
BIGNUM_LDIGITIZE_TAC "x_" `bignum_from_memory (x,9) s0` THEN
MAP_EVERY ABBREV_TAC [`h = n DIV 2 EXP 55`; `l = n MOD 2 EXP 55`] THEN
SUBGOAL_THEN `l < 2 EXP 55` ASSUME_TAC THENL
[EXPAND_TAC "l" THEN ARITH_TAC; ALL_TAC] THEN
SUBGOAL_THEN `h < 2 EXP 521` ASSUME_TAC THENL
[EXPAND_TAC "h" THEN REWRITE_TAC[ARITH_RULE
`n DIV 2 EXP 55 < 2 EXP 521 <=> n < 2 EXP (64 * 9)`] THEN
EXPAND_TAC "n" THEN MATCH_MP_TAC BIGNUM_OF_WORDLIST_BOUND THEN
REWRITE_TAC[LENGTH] THEN ARITH_TAC;
ALL_TAC] THEN
SUBGOAL_THEN
`(inverse_mod p_521 (2 EXP 576) * n) MOD p_521 =
(h + 2 EXP 466 * l) MOD p_521`
SUBST1_TAC THENL
[SUBST1_TAC(ARITH_RULE
`n = 2 EXP 55 * n DIV 2 EXP 55 + n MOD 2 EXP 55`) THEN
ASM_REWRITE_TAC[GSYM CONG] THEN
MATCH_MP_TAC(NUMBER_RULE
`!e. (e * i == 1) (mod n) /\ (e * hl == a) (mod n)
==> (i * a == hl) (mod n)`) THEN
EXISTS_TAC `2 EXP 576` THEN
REWRITE_TAC[GSYM(NUM_REDUCE_CONV `2 EXP 576`); INVERSE_MOD_RMUL_EQ] THEN
REWRITE_TAC[COPRIME_REXP; COPRIME_2; p_521] THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[REAL_CONGRUENCE] THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
REAL_INTEGER_TAC;
ALL_TAC] THEN
X86_STEPS_TAC BIGNUM_DEAMONT_P521_EXEC (1--20) THEN
MAP_EVERY ABBREV_TAC
[`d0:int64 =
word_subword ((word_join:int64->int64->int128) x_1 x_0) (55,64)`;
`d1:int64 =
word_subword ((word_join:int64->int64->int128) x_2 x_1) (55,64)`;
`d2:int64 =
word_subword ((word_join:int64->int64->int128) x_3 x_2) (55,64)`;
`d3:int64 =
word_subword ((word_join:int64->int64->int128) x_4 x_3) (55,64)`;
`d4:int64 =
word_subword ((word_join:int64->int64->int128) x_5 x_4) (55,64)`;
`d5:int64 =
word_subword ((word_join:int64->int64->int128) x_6 x_5) (55,64)`;
`d6:int64 =
word_subword ((word_join:int64->int64->int128) x_7 x_6) (55,64)`;
`d7:int64 =
word_subword ((word_join:int64->int64->int128) x_8 x_7) (55,64)`;
`d8:int64 = word_ushr x_8 55`] THEN
SUBGOAL_THEN `word_shl (x_0:int64) 9 = word(2 EXP 9 * l)` SUBST_ALL_TAC THENL
[MAP_EVERY EXPAND_TAC ["l"; "n"] THEN REWRITE_TAC[word_shl; WORD_EQ] THEN
REWRITE_TAC[BIGNUM_OF_WORDLIST_SPLIT_RULE(1,8)] THEN
REWRITE_TAC[DIMINDEX_64; ARITH_RULE `64 = 55 + 9`; EXP_ADD] THEN
REWRITE_TAC[GSYM MULT_ASSOC; MOD_MULT_ADD] THEN
MATCH_MP_TAC(NUMBER_RULE
`(a:num == b) (mod n) ==> (a * e == e * b) (mod (n * e))`) THEN
REWRITE_TAC[CONG; BIGNUM_OF_WORDLIST_SING] THEN CONV_TAC MOD_DOWN_CONV THEN
REFL_TAC;
ALL_TAC] THEN
SUBGOAL_THEN
`n DIV 2 EXP 55 = bignum_of_wordlist[d0;d1;d2;d3;d4;d5;d6;d7;d8]`
SUBST_ALL_TAC THENL
[MATCH_MP_TAC DIV_UNIQ THEN
EXISTS_TAC `val(x_0:int64) MOD 2 EXP 55` THEN
REWRITE_TAC[ARITH_RULE `x MOD 2 EXP 55 < 2 EXP 55`] THEN
REWRITE_TAC[GSYM VAL_WORD_AND_MASK_WORD] THEN EXPAND_TAC "n" THEN
MAP_EVERY EXPAND_TAC
["d0"; "d1"; "d2"; "d3"; "d4"; "d5"; "d6"; "d7"; "d8"] THEN
REWRITE_TAC[val_def; DIMINDEX_64; bignum_of_wordlist] THEN
REWRITE_TAC[ARITH_RULE `i < 64 <=> 0 <= i /\ i <= 63`] THEN
REWRITE_TAC[GSYM IN_NUMSEG; IN_GSPEC] THEN
REWRITE_TAC[BIT_WORD_SUBWORD; BIT_WORD_JOIN; BIT_WORD_AND;
BIT_WORD_USHR; DIMINDEX_64; DIMINDEX_128] THEN
CONV_TAC NUM_REDUCE_CONV THEN
CONV_TAC(ONCE_DEPTH_CONV EXPAND_NSUM_CONV) THEN
CONV_TAC NUM_REDUCE_CONV THEN ONCE_REWRITE_TAC[BIT_GUARD] THEN
REWRITE_TAC[DIMINDEX_64] THEN
CONV_TAC(DEPTH_CONV(NUM_RED_CONV ORELSEC WORD_RED_CONV ORELSEC
GEN_REWRITE_CONV I [BITVAL_CLAUSES])) THEN
CONV_TAC NUM_RING;
ALL_TAC] THEN
SUBGOAL_THEN
`&(val(word_or d8 (word 18446744073709551104):int64)):real =
&2 pow 9 * (&2 pow 55 - &1) + &(val d8)`
ASSUME_TAC THENL
[ONCE_REWRITE_TAC[WORD_BITWISE_RULE
`word_or a b = word_or b (word_and a (word_not b))`] THEN
SIMP_TAC[VAL_WORD_OR_DISJOINT; WORD_BITWISE_RULE
`word_and x (word_and y (word_not x)) = word 0`] THEN
CONV_TAC WORD_REDUCE_CONV THEN CONV_TAC REAL_RAT_REDUCE_CONV THEN
REWRITE_TAC[REAL_OF_NUM_CLAUSES; EQ_ADD_LCANCEL] THEN
AP_TERM_TAC THEN REWRITE_TAC[WORD_EQ_BITS_ALT; DIMINDEX_64] THEN
EXPAND_TAC "d8" THEN
REWRITE_TAC[BIT_WORD_AND; BIT_WORD_USHR; DIMINDEX_64] THEN
ONCE_REWRITE_TAC[BIT_GUARD] THEN REWRITE_TAC[DIMINDEX_64] THEN
CONV_TAC EXPAND_CASES_CONV THEN
CONV_TAC(DEPTH_CONV(NUM_RED_CONV ORELSEC WORD_RED_CONV));
ALL_TAC] THEN
SUBGOAL_THEN
`bignum_of_wordlist
[word_shl (word (512 * l)) 9; word_ushr (word (512 * l)) 55] =
2 EXP 18 * l`
ASSUME_TAC THENL
[REWRITE_TAC[bignum_of_wordlist; VAL_WORD_SHL; VAL_WORD_USHR] THEN
REWRITE_TAC[DIMINDEX_64; EXP_ADD; ARITH_RULE `64 = 9 + 55`] THEN
REWRITE_TAC[MOD_MULT2; GSYM MULT_ASSOC; GSYM LEFT_ADD_DISTRIB] THEN
REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES] THEN MATCH_MP_TAC(ARITH_RULE
`x = 512 * l
==> 2 EXP 9 * (x MOD 2 EXP 55 + 2 EXP 55 * x DIV 2 EXP 55) =
2 EXP 18 * l`) THEN
MATCH_MP_TAC VAL_WORD_EQ THEN EXPAND_TAC "l" THEN
REWRITE_TAC[DIMINDEX_64] THEN ARITH_TAC;
ALL_TAC] THEN
X86_ACCSTEPS_TAC BIGNUM_DEAMONT_P521_EXEC (25--33) (21--33) THEN
SUBGOAL_THEN `carry_s33 <=> p_521 <= h + 2 EXP 466 * l` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LE THEN EXISTS_TAC `576` THEN
SUBGOAL_THEN
`2 EXP 466 * l =
2 EXP 448 * bignum_of_wordlist
[word_shl (word (512 * l)) 9; word_ushr (word (512 * l)) 55]`
SUBST1_TAC THENL [ASM_REWRITE_TAC[] THEN ARITH_TAC; ALL_TAC] THEN
EXPAND_TAC "h" THEN
REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
ASM_REWRITE_TAC[p_521] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
ALL_TAC] THEN
ABBREV_TAC `hl = h + 2 EXP 466 * l` THEN
X86_ACCSTEPS_TAC BIGNUM_DEAMONT_P521_EXEC (34--53) (34--53) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
CONV_TAC(LAND_CONV BIGNUM_LEXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN
MAP_EVERY EXISTS_TAC
[`521`;
`if h + 2 EXP 466 * l < p_521
then &(h + 2 EXP 466 * l)
else &(h + 2 EXP 466 * l) - &p_521`] THEN
REPEAT CONJ_TAC THENL
[BOUNDER_TAC[];
REWRITE_TAC[p_521] THEN ARITH_TAC;
REWRITE_TAC[p_521] THEN ARITH_TAC;
ALL_TAC;
SIMP_TAC[GSYM NOT_LE; COND_SWAP; REAL_OF_NUM_SUB] THEN
REWRITE_TAC[GSYM COND_RAND] THEN AP_TERM_TAC THEN EXPAND_TAC "hl" THEN
REWRITE_TAC[GSYM NOT_LT; COND_SWAP] THEN MATCH_MP_TAC MOD_CASES THEN
MAP_EVERY UNDISCH_TAC [`h < 2 EXP 521`; `l < 2 EXP 55`] THEN
REWRITE_TAC[p_521] THEN ARITH_TAC] THEN
ASM_REWRITE_TAC[] THEN
ABBREV_TAC `bb <=> hl < p_521` THEN MAP_EVERY EXPAND_TAC ["hl"; "h"] THEN
SUBGOAL_THEN
`2 EXP 466 * l =
2 EXP 448 * bignum_of_wordlist
[word_shl (word (512 * l)) 9; word_ushr (word (512 * l)) 55]`
SUBST1_TAC THENL [ASM_REWRITE_TAC[] THEN ARITH_TAC; ALL_TAC] THEN
REWRITE_TAC[SYM(NUM_REDUCE_CONV `2 EXP 9 - 1`)] THEN
REWRITE_TAC[VAL_WORD_AND_MASK_WORD; bignum_of_wordlist] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES; REAL_OF_NUM_MOD; p_521] THEN
CONV_TAC NUM_REDUCE_CONV THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_INTEGER_TAC);;
let BIGNUM_DEAMONT_P521_SUBROUTINE_CORRECT = time prove
(`!z x a pc stackpointer returnaddress.
nonoverlapping (z,8 * 9) (word_sub stackpointer (word 32),40) /\
ALL (nonoverlapping (word_sub stackpointer (word 32),32))
[(word pc,0xe6); (x,8 * 9)] /\
nonoverlapping (word pc,0xe6) (z,8 * 9)
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_deamont_p521_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,9) s = a)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
bignum_from_memory (z,9) s =
(inverse_mod p_521 (2 EXP 576) * a) MOD p_521)
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 9);
memory :> bytes(word_sub stackpointer (word 32),32)] ,,
MAYCHANGE SOME_FLAGS)`,
X86_PROMOTE_RETURN_STACK_TAC
bignum_deamont_p521_mc BIGNUM_DEAMONT_P521_CORRECT
`[RBX; R12; R13; RBP]` 32);;
let windows_bignum_deamont_p521_mc = define_from_elf
"windows_bignum_deamont_p521_mc" "x86/p521/bignum_deamont_p521.obj";;
let WINDOWS_BIGNUM_DEAMONT_P521_SUBROUTINE_CORRECT = time prove
(`!z x a pc stackpointer returnaddress.
nonoverlapping (z,8 * 9) (word_sub stackpointer (word 48),56) /\
ALL (nonoverlapping (word_sub stackpointer (word 48),48))
[(word pc,0xf0); (x,8 * 9)] /\
nonoverlapping (word pc,0xf0) (z,8 * 9)
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_deamont_p521_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,9) s = a)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
bignum_from_memory (z,9) s =
(inverse_mod p_521 (2 EXP 576) * a) MOD p_521)
(MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,,
MAYCHANGE [memory :> bytes(z,8 * 9);
memory :> bytes(word_sub stackpointer (word 48),48)] ,,
MAYCHANGE SOME_FLAGS)`,
WINDOWS_X86_WRAP_STACK_TAC
windows_bignum_deamont_p521_mc bignum_deamont_p521_mc
BIGNUM_DEAMONT_P521_CORRECT `[RBX; R12; R13; RBP]` 32);;
|
7aec1fe36685557e7caddc4e8816b2d8eb2992d37b5c0be9b98cc2a28f42f14c | apache/couchdb-couch-replicator | couch_replicator_large_atts_tests.erl | 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(couch_replicator_large_atts_tests).
-include_lib("couch/include/couch_eunit.hrl").
-include_lib("couch/include/couch_db.hrl").
-import(couch_replicator_test_helper, [
db_url/1,
replicate/2,
compare_dbs/2
]).
-define(ATT_SIZE_1, 2 * 1024 * 1024).
-define(ATT_SIZE_2, round(6.6 * 1024 * 1024)).
-define(DOCS_COUNT, 11).
-define(TIMEOUT_EUNIT, 30).
setup() ->
DbName = ?tempdb(),
{ok, Db} = couch_db:create(DbName, [?ADMIN_CTX]),
ok = couch_db:close(Db),
DbName.
setup(local) ->
setup();
setup(remote) ->
{remote, setup()};
setup({A, B}) ->
Ctx = test_util:start_couch([couch_replicator]),
config:set("attachments", "compressible_types", "text/*", false),
Source = setup(A),
Target = setup(B),
{Ctx, {Source, Target}}.
teardown({remote, DbName}) ->
teardown(DbName);
teardown(DbName) ->
ok = couch_server:delete(DbName, [?ADMIN_CTX]),
ok.
teardown(_, {Ctx, {Source, Target}}) ->
teardown(Source),
teardown(Target),
ok = application:stop(couch_replicator),
ok = test_util:stop_couch(Ctx).
large_atts_test_() ->
Pairs = [{local, local}, {local, remote},
{remote, local}, {remote, remote}],
{
"Replicate docs with large attachments",
{
foreachx,
fun setup/1, fun teardown/2,
[{Pair, fun should_populate_replicate_compact/2}
|| Pair <- Pairs]
}
}.
should_populate_replicate_compact({From, To}, {_Ctx, {Source, Target}}) ->
{lists:flatten(io_lib:format("~p -> ~p", [From, To])),
{inorder, [should_populate_source(Source),
should_replicate(Source, Target),
should_compare_databases(Source, Target)]}}.
should_populate_source({remote, Source}) ->
should_populate_source(Source);
should_populate_source(Source) ->
{timeout, ?TIMEOUT_EUNIT, ?_test(populate_db(Source, ?DOCS_COUNT))}.
should_replicate({remote, Source}, Target) ->
should_replicate(db_url(Source), Target);
should_replicate(Source, {remote, Target}) ->
should_replicate(Source, db_url(Target));
should_replicate(Source, Target) ->
{timeout, ?TIMEOUT_EUNIT, ?_test(replicate(Source, Target))}.
should_compare_databases({remote, Source}, Target) ->
should_compare_databases(Source, Target);
should_compare_databases(Source, {remote, Target}) ->
should_compare_databases(Source, Target);
should_compare_databases(Source, Target) ->
{timeout, ?TIMEOUT_EUNIT, ?_test(compare_dbs(Source, Target))}.
populate_db(DbName, DocCount) ->
{ok, Db} = couch_db:open_int(DbName, []),
Docs = lists:foldl(
fun(DocIdCounter, Acc) ->
Doc = #doc{
id = iolist_to_binary(["doc", integer_to_list(DocIdCounter)]),
body = {[]},
atts = [
att(<<"att1">>, ?ATT_SIZE_1, <<"text/plain">>),
att(<<"att2">>, ?ATT_SIZE_2, <<"app/binary">>)
]
},
[Doc | Acc]
end,
[], lists:seq(1, DocCount)),
{ok, _} = couch_db:update_docs(Db, Docs, []),
couch_db:close(Db).
att(Name, Size, Type) ->
couch_att:new([
{name, Name},
{type, Type},
{att_len, Size},
{data, fun(Count) -> crypto:rand_bytes(Count) end}
]).
| null | https://raw.githubusercontent.com/apache/couchdb-couch-replicator/d00b981445c03622497088eb872059ab4f48b298/test/couch_replicator_large_atts_tests.erl | erlang | 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
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License. | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(couch_replicator_large_atts_tests).
-include_lib("couch/include/couch_eunit.hrl").
-include_lib("couch/include/couch_db.hrl").
-import(couch_replicator_test_helper, [
db_url/1,
replicate/2,
compare_dbs/2
]).
-define(ATT_SIZE_1, 2 * 1024 * 1024).
-define(ATT_SIZE_2, round(6.6 * 1024 * 1024)).
-define(DOCS_COUNT, 11).
-define(TIMEOUT_EUNIT, 30).
setup() ->
DbName = ?tempdb(),
{ok, Db} = couch_db:create(DbName, [?ADMIN_CTX]),
ok = couch_db:close(Db),
DbName.
setup(local) ->
setup();
setup(remote) ->
{remote, setup()};
setup({A, B}) ->
Ctx = test_util:start_couch([couch_replicator]),
config:set("attachments", "compressible_types", "text/*", false),
Source = setup(A),
Target = setup(B),
{Ctx, {Source, Target}}.
teardown({remote, DbName}) ->
teardown(DbName);
teardown(DbName) ->
ok = couch_server:delete(DbName, [?ADMIN_CTX]),
ok.
teardown(_, {Ctx, {Source, Target}}) ->
teardown(Source),
teardown(Target),
ok = application:stop(couch_replicator),
ok = test_util:stop_couch(Ctx).
large_atts_test_() ->
Pairs = [{local, local}, {local, remote},
{remote, local}, {remote, remote}],
{
"Replicate docs with large attachments",
{
foreachx,
fun setup/1, fun teardown/2,
[{Pair, fun should_populate_replicate_compact/2}
|| Pair <- Pairs]
}
}.
should_populate_replicate_compact({From, To}, {_Ctx, {Source, Target}}) ->
{lists:flatten(io_lib:format("~p -> ~p", [From, To])),
{inorder, [should_populate_source(Source),
should_replicate(Source, Target),
should_compare_databases(Source, Target)]}}.
should_populate_source({remote, Source}) ->
should_populate_source(Source);
should_populate_source(Source) ->
{timeout, ?TIMEOUT_EUNIT, ?_test(populate_db(Source, ?DOCS_COUNT))}.
should_replicate({remote, Source}, Target) ->
should_replicate(db_url(Source), Target);
should_replicate(Source, {remote, Target}) ->
should_replicate(Source, db_url(Target));
should_replicate(Source, Target) ->
{timeout, ?TIMEOUT_EUNIT, ?_test(replicate(Source, Target))}.
should_compare_databases({remote, Source}, Target) ->
should_compare_databases(Source, Target);
should_compare_databases(Source, {remote, Target}) ->
should_compare_databases(Source, Target);
should_compare_databases(Source, Target) ->
{timeout, ?TIMEOUT_EUNIT, ?_test(compare_dbs(Source, Target))}.
populate_db(DbName, DocCount) ->
{ok, Db} = couch_db:open_int(DbName, []),
Docs = lists:foldl(
fun(DocIdCounter, Acc) ->
Doc = #doc{
id = iolist_to_binary(["doc", integer_to_list(DocIdCounter)]),
body = {[]},
atts = [
att(<<"att1">>, ?ATT_SIZE_1, <<"text/plain">>),
att(<<"att2">>, ?ATT_SIZE_2, <<"app/binary">>)
]
},
[Doc | Acc]
end,
[], lists:seq(1, DocCount)),
{ok, _} = couch_db:update_docs(Db, Docs, []),
couch_db:close(Db).
att(Name, Size, Type) ->
couch_att:new([
{name, Name},
{type, Type},
{att_len, Size},
{data, fun(Count) -> crypto:rand_bytes(Count) end}
]).
|
c38b41112a69cd40dbccebaa7821bc27cb5be89733d9137af908071791832012 | skanev/playground | 33-tests.scm | (require rackunit rackunit/text-ui)
(load "../33.scm")
(define sicp-1.33-tests
(test-suite
"Tests for SICP exercise 1.33"
(check-equal? (sum-of-prime-squares 2 10) 87)
(check-equal? (sum-of-prime-squares 10 15) 290)
(check-equal? (product-of-relative-primes-to 10) 189)
(check-equal? (product-of-relative-primes-to 12) 385)
))
(run-tests sicp-1.33-tests)
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/01/tests/33-tests.scm | scheme | (require rackunit rackunit/text-ui)
(load "../33.scm")
(define sicp-1.33-tests
(test-suite
"Tests for SICP exercise 1.33"
(check-equal? (sum-of-prime-squares 2 10) 87)
(check-equal? (sum-of-prime-squares 10 15) 290)
(check-equal? (product-of-relative-primes-to 10) 189)
(check-equal? (product-of-relative-primes-to 12) 385)
))
(run-tests sicp-1.33-tests)
| |
14db958396e817642cf2b041c6bdf42b273f4bef845defaba75f1f9d9a412ed1 | pfdietz/ansi-test | random-type-prop-tests-02.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Mar 6 20:37:57 2005
Contains : Tests that invoke the random type prop infrastructure , part 2
(in-package :cl-test)
(def-type-prop-test =.1 '= '(number number) 2)
(def-type-prop-test =.2 '= '(number number number) 3)
(def-type-prop-test =.3 '= nil 4 :maxargs 10 :rest-type 'number)
(def-type-prop-test =.4 '= '(integer integer) 2)
(def-type-prop-test =.5 '= (list 'number #'(lambda (x) (if (coin) 'number
`(eql ,x)))) 2)
(def-type-prop-test =.6 '= (list 'number 'number
#'(lambda (x y) (rcase
(2 'number)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test /=.1 '/= '(number number) 2)
(def-type-prop-test /=.2 '/= '(number number number) 3)
(def-type-prop-test /=.3 '/= nil 4 :maxargs 10 :rest-type 'number)
(def-type-prop-test /=.4 '/= '(integer integer) 2)
(def-type-prop-test /=.5 '/= (list 'number #'(lambda (x) (if (coin) 'number
`(eql ,x)))) 2)
(def-type-prop-test /=.6 '/= (list 'number 'number
#'(lambda (x y) (rcase
(2 'number)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test <.1 '< '(real real) 2)
(def-type-prop-test <.2 '< '(real real real) 3)
(def-type-prop-test <.3 '< nil 4 :maxargs 10 :rest-type 'real)
(def-type-prop-test <.4 '< '(integer integer) 2)
(def-type-prop-test <.5 '< (list 'real #'(lambda (x) (if (coin) 'real
`(eql ,x)))) 2)
(def-type-prop-test <.6 '< (list 'real 'real
#'(lambda (x y) (rcase
(2 'real)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test >.1 '> '(real real) 2)
(def-type-prop-test >.2 '> '(real real real) 3)
(def-type-prop-test >.3 '> nil 4 :maxargs 10 :rest-type 'real)
(def-type-prop-test >.4 '> '(integer integer) 2)
(def-type-prop-test >.5 '> (list 'real #'(lambda (x) (if (coin) 'real
`(eql ,x)))) 2)
(def-type-prop-test >.6 '> (list 'real 'real
#'(lambda (x y) (rcase
(2 'real)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test <=.1 '<= '(real real) 2)
(def-type-prop-test <=.2 '<= '(real real real) 3)
(def-type-prop-test <=.3 '<= nil 4 :maxargs 10 :rest-type 'real)
(def-type-prop-test <=.4 '<= '(integer integer) 2)
(def-type-prop-test <=.5 '<= (list 'real #'(lambda (x) (if (coin) 'real
`(eql ,x)))) 2)
(def-type-prop-test <=.6 '<= (list 'real 'real
#'(lambda (x y) (rcase
(2 'real)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test >=.1 '>= '(real real) 2)
(def-type-prop-test >=.2 '>= '(real real real) 3)
(def-type-prop-test >=.3 '>= nil 4 :maxargs 10 :rest-type 'real)
(def-type-prop-test >=.4 '>= '(integer integer) 2)
(def-type-prop-test >=.5 '>= (list 'real #'(lambda (x) (if (coin) 'real
`(eql ,x)))) 2)
(def-type-prop-test >=.6 '>= (list 'real 'real
#'(lambda (x y) (rcase
(2 'real)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test comparisons.1 '(lambda (c x y) (funcall c x y))
(list '(member = /= < > <= >=)
'integer
#'(lambda (c x)
(declare (ignore c))
(rcase (10 'integer)
(1 `(eql ,(1- x)))
(1 `(eql ,x))
(1 `(eql ,(1+ x))))))
3)
(def-type-prop-test comparisons.2 '(lambda (c x y) (when (funcall c x y) (- x y)))
(list '(member = /= < > <= >=)
'integer
#'(lambda (c x)
(declare (ignore c))
(rcase (10 'integer)
(1 `(eql ,(1- x)))
(1 `(eql ,x))
(1 `(eql ,(1+ x))))))
3)
(def-type-prop-test min.1 'min nil 2 :maxargs 6 :rest-type 'integer)
(def-type-prop-test min.2 'min nil 2 :maxargs 6 :rest-type 'rational)
(def-type-prop-test min.3 'min nil 2 :maxargs 6 :rest-type 'real)
(def-type-prop-test max.1 'max nil 2 :maxargs 6 :rest-type 'integer)
(def-type-prop-test max.2 'max nil 2 :maxargs 6 :rest-type 'rational)
(def-type-prop-test max.3 'max nil 2 :maxargs 6 :rest-type 'real)
(def-type-prop-test minusp 'minusp '(real) 1)
(def-type-prop-test plusp 'plusp '(real) 1)
(def-type-prop-test zerop 'zerop '(number) 1)
(def-type-prop-test floor.1 'floor '(real) 1)
(def-type-prop-test floor.2 'floor '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor.3 'floor '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test ffloor.1 'ffloor '(real) 1)
(def-type-prop-test ffloor.2 'ffloor '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test ffloor.3 'ffloor '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test ceiling.1 'ceiling '(real) 1)
(def-type-prop-test ceiling.2 'ceiling '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test ceiling.3 'ceiling '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test fceiling.1 'fceiling '(real) 1)
(def-type-prop-test fceiling.2 'fceiling '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test fceiling.3 'fceiling '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test truncate.1 'truncate '(real) 1)
(def-type-prop-test truncate.2 'truncate '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate.3 'truncate '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test ftruncate.1 'ftruncate '(real) 1)
(def-type-prop-test ftruncate.2 'ftruncate '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test ftruncate.3 'ftruncate '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test round.1 'round '(real) 1)
(def-type-prop-test round.2 'round '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test round.3 'round '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test fround.1 'fround '(real) 1)
(def-type-prop-test fround.2 'fround '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test fround.3 'fround '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test floor/first-value.1 '(lambda (x y) (values (floor x y))) '(integer (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor/first-value.2 '(lambda (x y) (values (floor x y))) '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor/first-value.3 '(lambda (x y) (values (floor x y))) '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test floor/second-value.1 '(lambda (x y) (nth-value 1 (floor x y))) '(integer (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor/second-value.2 '(lambda (x y) (nth-value 1 (floor x y))) '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor/second-value.3 '(lambda (x y) (nth-value 1 (floor x y))) '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/first-value.1 '(lambda (x y) (values (truncate x y))) '(integer (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/first-value.2 '(lambda (x y) (values (truncate x y))) '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/first-value.3 '(lambda (x y) (values (truncate x y))) '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/second-value.1 '(lambda (x y) (nth-value 1 (truncate x y))) '(integer (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/second-value.2 '(lambda (x y) (nth-value 1 (truncate x y))) '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/second-value.3 '(lambda (x y) (nth-value 1 (truncate x y))) '(real (and real (not (satisfies zerop)))) 2)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/random/random-type-prop-tests-02.lsp | lisp | -*- Mode: Lisp -*- | Author :
Created : Sun Mar 6 20:37:57 2005
Contains : Tests that invoke the random type prop infrastructure , part 2
(in-package :cl-test)
(def-type-prop-test =.1 '= '(number number) 2)
(def-type-prop-test =.2 '= '(number number number) 3)
(def-type-prop-test =.3 '= nil 4 :maxargs 10 :rest-type 'number)
(def-type-prop-test =.4 '= '(integer integer) 2)
(def-type-prop-test =.5 '= (list 'number #'(lambda (x) (if (coin) 'number
`(eql ,x)))) 2)
(def-type-prop-test =.6 '= (list 'number 'number
#'(lambda (x y) (rcase
(2 'number)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test /=.1 '/= '(number number) 2)
(def-type-prop-test /=.2 '/= '(number number number) 3)
(def-type-prop-test /=.3 '/= nil 4 :maxargs 10 :rest-type 'number)
(def-type-prop-test /=.4 '/= '(integer integer) 2)
(def-type-prop-test /=.5 '/= (list 'number #'(lambda (x) (if (coin) 'number
`(eql ,x)))) 2)
(def-type-prop-test /=.6 '/= (list 'number 'number
#'(lambda (x y) (rcase
(2 'number)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test <.1 '< '(real real) 2)
(def-type-prop-test <.2 '< '(real real real) 3)
(def-type-prop-test <.3 '< nil 4 :maxargs 10 :rest-type 'real)
(def-type-prop-test <.4 '< '(integer integer) 2)
(def-type-prop-test <.5 '< (list 'real #'(lambda (x) (if (coin) 'real
`(eql ,x)))) 2)
(def-type-prop-test <.6 '< (list 'real 'real
#'(lambda (x y) (rcase
(2 'real)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test >.1 '> '(real real) 2)
(def-type-prop-test >.2 '> '(real real real) 3)
(def-type-prop-test >.3 '> nil 4 :maxargs 10 :rest-type 'real)
(def-type-prop-test >.4 '> '(integer integer) 2)
(def-type-prop-test >.5 '> (list 'real #'(lambda (x) (if (coin) 'real
`(eql ,x)))) 2)
(def-type-prop-test >.6 '> (list 'real 'real
#'(lambda (x y) (rcase
(2 'real)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test <=.1 '<= '(real real) 2)
(def-type-prop-test <=.2 '<= '(real real real) 3)
(def-type-prop-test <=.3 '<= nil 4 :maxargs 10 :rest-type 'real)
(def-type-prop-test <=.4 '<= '(integer integer) 2)
(def-type-prop-test <=.5 '<= (list 'real #'(lambda (x) (if (coin) 'real
`(eql ,x)))) 2)
(def-type-prop-test <=.6 '<= (list 'real 'real
#'(lambda (x y) (rcase
(2 'real)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test >=.1 '>= '(real real) 2)
(def-type-prop-test >=.2 '>= '(real real real) 3)
(def-type-prop-test >=.3 '>= nil 4 :maxargs 10 :rest-type 'real)
(def-type-prop-test >=.4 '>= '(integer integer) 2)
(def-type-prop-test >=.5 '>= (list 'real #'(lambda (x) (if (coin) 'real
`(eql ,x)))) 2)
(def-type-prop-test >=.6 '>= (list 'real 'real
#'(lambda (x y) (rcase
(2 'real)
(1 `(eql ,x))
(1 `(eql ,y)))))
3)
(def-type-prop-test comparisons.1 '(lambda (c x y) (funcall c x y))
(list '(member = /= < > <= >=)
'integer
#'(lambda (c x)
(declare (ignore c))
(rcase (10 'integer)
(1 `(eql ,(1- x)))
(1 `(eql ,x))
(1 `(eql ,(1+ x))))))
3)
(def-type-prop-test comparisons.2 '(lambda (c x y) (when (funcall c x y) (- x y)))
(list '(member = /= < > <= >=)
'integer
#'(lambda (c x)
(declare (ignore c))
(rcase (10 'integer)
(1 `(eql ,(1- x)))
(1 `(eql ,x))
(1 `(eql ,(1+ x))))))
3)
(def-type-prop-test min.1 'min nil 2 :maxargs 6 :rest-type 'integer)
(def-type-prop-test min.2 'min nil 2 :maxargs 6 :rest-type 'rational)
(def-type-prop-test min.3 'min nil 2 :maxargs 6 :rest-type 'real)
(def-type-prop-test max.1 'max nil 2 :maxargs 6 :rest-type 'integer)
(def-type-prop-test max.2 'max nil 2 :maxargs 6 :rest-type 'rational)
(def-type-prop-test max.3 'max nil 2 :maxargs 6 :rest-type 'real)
(def-type-prop-test minusp 'minusp '(real) 1)
(def-type-prop-test plusp 'plusp '(real) 1)
(def-type-prop-test zerop 'zerop '(number) 1)
(def-type-prop-test floor.1 'floor '(real) 1)
(def-type-prop-test floor.2 'floor '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor.3 'floor '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test ffloor.1 'ffloor '(real) 1)
(def-type-prop-test ffloor.2 'ffloor '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test ffloor.3 'ffloor '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test ceiling.1 'ceiling '(real) 1)
(def-type-prop-test ceiling.2 'ceiling '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test ceiling.3 'ceiling '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test fceiling.1 'fceiling '(real) 1)
(def-type-prop-test fceiling.2 'fceiling '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test fceiling.3 'fceiling '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test truncate.1 'truncate '(real) 1)
(def-type-prop-test truncate.2 'truncate '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate.3 'truncate '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test ftruncate.1 'ftruncate '(real) 1)
(def-type-prop-test ftruncate.2 'ftruncate '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test ftruncate.3 'ftruncate '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test round.1 'round '(real) 1)
(def-type-prop-test round.2 'round '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test round.3 'round '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test fround.1 'fround '(real) 1)
(def-type-prop-test fround.2 'fround '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test fround.3 'fround '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test floor/first-value.1 '(lambda (x y) (values (floor x y))) '(integer (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor/first-value.2 '(lambda (x y) (values (floor x y))) '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor/first-value.3 '(lambda (x y) (values (floor x y))) '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test floor/second-value.1 '(lambda (x y) (nth-value 1 (floor x y))) '(integer (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor/second-value.2 '(lambda (x y) (nth-value 1 (floor x y))) '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test floor/second-value.3 '(lambda (x y) (nth-value 1 (floor x y))) '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/first-value.1 '(lambda (x y) (values (truncate x y))) '(integer (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/first-value.2 '(lambda (x y) (values (truncate x y))) '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/first-value.3 '(lambda (x y) (values (truncate x y))) '(real (and real (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/second-value.1 '(lambda (x y) (nth-value 1 (truncate x y))) '(integer (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/second-value.2 '(lambda (x y) (nth-value 1 (truncate x y))) '(real (and integer (not (satisfies zerop)))) 2)
(def-type-prop-test truncate/second-value.3 '(lambda (x y) (nth-value 1 (truncate x y))) '(real (and real (not (satisfies zerop)))) 2)
|
1d8972508b1c19bef142a12d0fb7841246fec31caeec07ba8ce082eed03f4312 | FranklinChen/hugs98-plus-Sep2006 | ForeignPtr.hs | # OPTIONS_GHC -fno - implicit - prelude #
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.ForeignPtr
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- The 'ForeignPtr' type and operations. This module is part of the
Foreign Function Interface ( FFI ) and will usually be imported via
-- the "Foreign" module.
--
-----------------------------------------------------------------------------
module Foreign.ForeignPtr
(
-- * Finalised data pointers
ForeignPtr
, FinalizerPtr
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, FinalizerEnvPtr
#endif
-- ** Basic operations
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
#endif
, withForeignPtr
#ifdef __GLASGOW_HASKELL__
, finalizeForeignPtr
#endif
-- ** Low-level operations
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
-- ** Allocating managed memory
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
)
where
import Foreign.Ptr
#ifdef __NHC__
import NHC.FFI
( ForeignPtr
, FinalizerPtr
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
, withForeignPtr
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, Storable(sizeOf)
, malloc, mallocBytes, finalizerFree
)
#endif
#ifdef __HUGS__
import Hugs.ForeignPtr
#endif
#ifndef __NHC__
import Foreign.Storable ( Storable(sizeOf) )
#endif
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.IOBase
import GHC.Num
import GHC.Err ( undefined )
import GHC.ForeignPtr
#endif
#if !defined(__NHC__) && !defined(__GLASGOW_HASKELL__)
import Foreign.Marshal.Alloc ( malloc, mallocBytes, finalizerFree )
instance Eq (ForeignPtr a) where
p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
instance Ord (ForeignPtr a) where
compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
instance Show (ForeignPtr a) where
showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
#endif
#ifndef __NHC__
newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)
-- ^Turns a plain memory reference into a foreign pointer, and
-- associates a finaliser with the reference. The finaliser will be executed
-- after the last reference to the foreign object is dropped. Note that there
-- is no guarantee on how soon the finaliser is executed after the last
reference was dropped ; this depends on the details of the storage
-- manager. The only guarantee is that the finaliser runs before the program
-- terminates.
newForeignPtr finalizer p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizer finalizer fObj
return fObj
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
-- ^This is a way to look at the pointer living inside a
-- foreign object. This function takes a function which is
-- applied to that pointer. The resulting 'IO' action is then
-- executed. The foreign object is kept alive at least during
-- the whole action, even if it is not used directly
-- inside. Note that it is not safe to return the pointer from
-- the action and use it after the action completes. All uses
-- of the pointer should be inside the
-- 'withForeignPtr' bracket. The reason for
-- this unsafeness is the same as for
-- 'unsafeForeignPtrToPtr' below: the finalizer
-- may run earlier than expected, because the compiler can only
-- track usage of the 'ForeignPtr' object, not
-- a 'Ptr' object made from it.
--
-- This function is normally used for marshalling data to
-- or from the object pointed to by the
-- 'ForeignPtr', using the operations from the
-- 'Storable' class.
withForeignPtr fo io
= do r <- io (unsafeForeignPtrToPtr fo)
touchForeignPtr fo
return r
#endif /* ! __NHC__ */
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
| This variant of ' newForeignPtr ' adds a finalizer that expects an
-- environment in addition to the finalized pointer. The environment
that will be passed to the finalizer is fixed by the second argument to
-- 'newForeignPtrEnv'.
newForeignPtrEnv ::
FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)
newForeignPtrEnv finalizer env p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizerEnv finalizer env fObj
return fObj
#endif /* __HUGS__ */
#ifdef __GLASGOW_HASKELL__
type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())
-- | like 'addForeignPtrFinalizerEnv' but allows the finalizer to be
-- passed an additional environment parameter to be passed to the
-- finalizer. The environment passed to the finalizer is fixed by the
second argument to ' addForeignPtrFinalizerEnv '
addForeignPtrFinalizerEnv ::
FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()
addForeignPtrFinalizerEnv finalizer env fptr =
addForeignPtrConcFinalizer fptr
(mkFinalizerEnv finalizer env (unsafeForeignPtrToPtr fptr))
foreign import ccall "dynamic"
mkFinalizerEnv :: FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO ()
#endif
#ifndef __GLASGOW_HASKELL__
mallocForeignPtr :: Storable a => IO (ForeignPtr a)
mallocForeignPtr = do
r <- malloc
newForeignPtr finalizerFree r
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
mallocForeignPtrBytes n = do
r <- mallocBytes n
newForeignPtr finalizerFree r
#endif /* !__GLASGOW_HASKELL__ */
| This function is similar to ' Foreign . Marshal . Array.mallocArray ' ,
-- but yields a memory area that has a finalizer attached that releases
-- the memory area. As with 'mallocForeignPtr', it is not guaranteed that
-- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray = doMalloc undefined
where
doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b)
doMalloc dummy size = mallocForeignPtrBytes (size * sizeOf dummy)
-- | This function is similar to 'Foreign.Marshal.Array.mallocArray0',
-- but yields a memory area that has a finalizer attached that releases
-- the memory area. As with 'mallocForeignPtr', it is not guaranteed that
-- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray0 size = mallocForeignPtrArray (size + 1)
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/base/Foreign/ForeignPtr.hs | haskell | ---------------------------------------------------------------------------
|
Module : Foreign.ForeignPtr
License : BSD-style (see the file libraries/base/LICENSE)
Stability : provisional
Portability : portable
The 'ForeignPtr' type and operations. This module is part of the
the "Foreign" module.
---------------------------------------------------------------------------
* Finalised data pointers
** Basic operations
** Low-level operations
** Allocating managed memory
^Turns a plain memory reference into a foreign pointer, and
associates a finaliser with the reference. The finaliser will be executed
after the last reference to the foreign object is dropped. Note that there
is no guarantee on how soon the finaliser is executed after the last
manager. The only guarantee is that the finaliser runs before the program
terminates.
^This is a way to look at the pointer living inside a
foreign object. This function takes a function which is
applied to that pointer. The resulting 'IO' action is then
executed. The foreign object is kept alive at least during
the whole action, even if it is not used directly
inside. Note that it is not safe to return the pointer from
the action and use it after the action completes. All uses
of the pointer should be inside the
'withForeignPtr' bracket. The reason for
this unsafeness is the same as for
'unsafeForeignPtrToPtr' below: the finalizer
may run earlier than expected, because the compiler can only
track usage of the 'ForeignPtr' object, not
a 'Ptr' object made from it.
This function is normally used for marshalling data to
or from the object pointed to by the
'ForeignPtr', using the operations from the
'Storable' class.
environment in addition to the finalized pointer. The environment
'newForeignPtrEnv'.
| like 'addForeignPtrFinalizerEnv' but allows the finalizer to be
passed an additional environment parameter to be passed to the
finalizer. The environment passed to the finalizer is fixed by the
but yields a memory area that has a finalizer attached that releases
the memory area. As with 'mallocForeignPtr', it is not guaranteed that
the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
| This function is similar to 'Foreign.Marshal.Array.mallocArray0',
but yields a memory area that has a finalizer attached that releases
the memory area. As with 'mallocForeignPtr', it is not guaranteed that
the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'. | # OPTIONS_GHC -fno - implicit - prelude #
Copyright : ( c ) The University of Glasgow 2001
Maintainer :
Foreign Function Interface ( FFI ) and will usually be imported via
module Foreign.ForeignPtr
(
ForeignPtr
, FinalizerPtr
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, FinalizerEnvPtr
#endif
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
#endif
, withForeignPtr
#ifdef __GLASGOW_HASKELL__
, finalizeForeignPtr
#endif
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
)
where
import Foreign.Ptr
#ifdef __NHC__
import NHC.FFI
( ForeignPtr
, FinalizerPtr
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
, withForeignPtr
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, Storable(sizeOf)
, malloc, mallocBytes, finalizerFree
)
#endif
#ifdef __HUGS__
import Hugs.ForeignPtr
#endif
#ifndef __NHC__
import Foreign.Storable ( Storable(sizeOf) )
#endif
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.IOBase
import GHC.Num
import GHC.Err ( undefined )
import GHC.ForeignPtr
#endif
#if !defined(__NHC__) && !defined(__GLASGOW_HASKELL__)
import Foreign.Marshal.Alloc ( malloc, mallocBytes, finalizerFree )
instance Eq (ForeignPtr a) where
p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
instance Ord (ForeignPtr a) where
compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
instance Show (ForeignPtr a) where
showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
#endif
#ifndef __NHC__
newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)
reference was dropped ; this depends on the details of the storage
newForeignPtr finalizer p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizer finalizer fObj
return fObj
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
withForeignPtr fo io
= do r <- io (unsafeForeignPtrToPtr fo)
touchForeignPtr fo
return r
#endif /* ! __NHC__ */
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
| This variant of ' newForeignPtr ' adds a finalizer that expects an
that will be passed to the finalizer is fixed by the second argument to
newForeignPtrEnv ::
FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)
newForeignPtrEnv finalizer env p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizerEnv finalizer env fObj
return fObj
#endif /* __HUGS__ */
#ifdef __GLASGOW_HASKELL__
type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())
second argument to ' addForeignPtrFinalizerEnv '
addForeignPtrFinalizerEnv ::
FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()
addForeignPtrFinalizerEnv finalizer env fptr =
addForeignPtrConcFinalizer fptr
(mkFinalizerEnv finalizer env (unsafeForeignPtrToPtr fptr))
foreign import ccall "dynamic"
mkFinalizerEnv :: FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO ()
#endif
#ifndef __GLASGOW_HASKELL__
mallocForeignPtr :: Storable a => IO (ForeignPtr a)
mallocForeignPtr = do
r <- malloc
newForeignPtr finalizerFree r
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
mallocForeignPtrBytes n = do
r <- mallocBytes n
newForeignPtr finalizerFree r
#endif /* !__GLASGOW_HASKELL__ */
| This function is similar to ' Foreign . Marshal . Array.mallocArray ' ,
mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray = doMalloc undefined
where
doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b)
doMalloc dummy size = mallocForeignPtrBytes (size * sizeOf dummy)
mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray0 size = mallocForeignPtrArray (size + 1)
|
6ed1e57243e7d01167bfe69de5a9bc427f7c29b1aa78713fe1da7e760eae55b5 | aeolus-project/zephyrus | json_v0_j.mli | (* Auto-generated from "json_v0.atd" *)
(** Type definitions for naming. *)
type component_type_name = Json_v0_t.component_type_name
type port_name = Json_v0_t.port_name
type component_name = Json_v0_t.component_name
type package_name = Json_v0_t.package_name
type repository_name = Json_v0_t.repository_name
type location_name = Json_v0_t.location_name
(** Type definitions for Component Type. *)
type resource_name = Json_v0_t.resource_name
type provide_arity = Json_v0_t.provide_arity =
InfiniteProvide
| FiniteProvide of int
type require_arity = Json_v0_t.require_arity
type resource_consumption = Json_v0_t.resource_consumption
type resource_provide_arity = Json_v0_t.resource_provide_arity
type component_type = Json_v0_t.component_type = {
atd name
atd provide
atd require
component_type_conflict (*atd conflict *): port_name list;
atd consume
(resource_name * resource_consumption) list
}
* Type definitions for Universe .
type component_types = Json_v0_t.component_types
type package = Json_v0_t.package = {
atd name
atd depend
package_conflict (*atd conflict *): package_name list;
atd consume
(resource_name * resource_consumption) list
}
type packages = Json_v0_t.packages
type repository = Json_v0_t.repository = {
atd name
atd packages
}
type repositories = Json_v0_t.repositories
type package_names = Json_v0_t.package_names
(** Type definitions for Configuration. *)
type universe = Json_v0_t.universe = {
atd component_types
universe_implementation (*atd implementation *):
(component_type_name * package_names) list;
universe_repositories (*atd repositories *): repositories
}
type resources_provided = Json_v0_t.resources_provided
type location_cost = Json_v0_t.location_cost
type location = Json_v0_t.location = {
atd name
location_provide_resources (*atd provide_resources *): resources_provided;
atd repository
location_packages_installed (*atd packages_installed *): package_name list;
location_cost (*atd cost *): location_cost
}
type component = Json_v0_t.component = {
component_name: component_name;
component_type: component_type_name;
component_location: location_name
}
type binding = Json_v0_t.binding = {
atd port
binding_requirer (*atd requirer *): component_name;
binding_provider (*atd provider *): component_name
}
type configuration = Json_v0_t.configuration = {
configuration_locations (*atd locations *): location list;
atd components
configuration_bindings (*atd bindings *): binding list
}
val write_component_type_name :
Bi_outbuf.t -> component_type_name -> unit
(** Output a JSON value of type {!component_type_name}. *)
val string_of_component_type_name :
?len:int -> component_type_name -> string
* Serialize a value of type { ! component_type_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component_type_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component_type_name
(** Input JSON data of type {!component_type_name}. *)
val component_type_name_of_string :
string -> component_type_name
* JSON data of type { ! component_type_name } .
val write_port_name :
Bi_outbuf.t -> port_name -> unit
(** Output a JSON value of type {!port_name}. *)
val string_of_port_name :
?len:int -> port_name -> string
* Serialize a value of type { ! port_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_port_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> port_name
(** Input JSON data of type {!port_name}. *)
val port_name_of_string :
string -> port_name
* JSON data of type { ! port_name } .
val write_component_name :
Bi_outbuf.t -> component_name -> unit
(** Output a JSON value of type {!component_name}. *)
val string_of_component_name :
?len:int -> component_name -> string
* Serialize a value of type { ! component_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component_name
(** Input JSON data of type {!component_name}. *)
val component_name_of_string :
string -> component_name
* JSON data of type { ! component_name } .
val write_package_name :
Bi_outbuf.t -> package_name -> unit
(** Output a JSON value of type {!package_name}. *)
val string_of_package_name :
?len:int -> package_name -> string
* Serialize a value of type { ! package_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_package_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> package_name
(** Input JSON data of type {!package_name}. *)
val package_name_of_string :
string -> package_name
* JSON data of type { ! package_name } .
val write_repository_name :
Bi_outbuf.t -> repository_name -> unit
(** Output a JSON value of type {!repository_name}. *)
val string_of_repository_name :
?len:int -> repository_name -> string
* Serialize a value of type { ! repository_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_repository_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> repository_name
(** Input JSON data of type {!repository_name}. *)
val repository_name_of_string :
string -> repository_name
* JSON data of type { ! repository_name } .
val write_location_name :
Bi_outbuf.t -> location_name -> unit
(** Output a JSON value of type {!location_name}. *)
val string_of_location_name :
?len:int -> location_name -> string
* Serialize a value of type { ! location_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_location_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> location_name
(** Input JSON data of type {!location_name}. *)
val location_name_of_string :
string -> location_name
* JSON data of type { ! location_name } .
val write_resource_name :
Bi_outbuf.t -> resource_name -> unit
(** Output a JSON value of type {!resource_name}. *)
val string_of_resource_name :
?len:int -> resource_name -> string
* Serialize a value of type { ! resource_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_resource_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> resource_name
(** Input JSON data of type {!resource_name}. *)
val resource_name_of_string :
string -> resource_name
* JSON data of type { ! resource_name } .
val write_provide_arity :
Bi_outbuf.t -> provide_arity -> unit
(** Output a JSON value of type {!provide_arity}. *)
val string_of_provide_arity :
?len:int -> provide_arity -> string
* Serialize a value of type { ! provide_arity }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_provide_arity :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> provide_arity
(** Input JSON data of type {!provide_arity}. *)
val provide_arity_of_string :
string -> provide_arity
* JSON data of type { ! provide_arity } .
val write_require_arity :
Bi_outbuf.t -> require_arity -> unit
(** Output a JSON value of type {!require_arity}. *)
val string_of_require_arity :
?len:int -> require_arity -> string
* Serialize a value of type { ! require_arity }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_require_arity :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> require_arity
(** Input JSON data of type {!require_arity}. *)
val require_arity_of_string :
string -> require_arity
* JSON data of type { ! require_arity } .
val write_resource_consumption :
Bi_outbuf.t -> resource_consumption -> unit
* Output a JSON value of type { ! .
val string_of_resource_consumption :
?len:int -> resource_consumption -> string
* Serialize a value of type { ! resource_consumption }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_resource_consumption :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> resource_consumption
* Input JSON data of type { ! .
val resource_consumption_of_string :
string -> resource_consumption
* JSON data of type { ! .
val write_resource_provide_arity :
Bi_outbuf.t -> resource_provide_arity -> unit
(** Output a JSON value of type {!resource_provide_arity}. *)
val string_of_resource_provide_arity :
?len:int -> resource_provide_arity -> string
* Serialize a value of type { ! resource_provide_arity }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_resource_provide_arity :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> resource_provide_arity
(** Input JSON data of type {!resource_provide_arity}. *)
val resource_provide_arity_of_string :
string -> resource_provide_arity
* JSON data of type { ! resource_provide_arity } .
val write_component_type :
Bi_outbuf.t -> component_type -> unit
(** Output a JSON value of type {!component_type}. *)
val string_of_component_type :
?len:int -> component_type -> string
* Serialize a value of type { ! component_type }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component_type :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component_type
(** Input JSON data of type {!component_type}. *)
val component_type_of_string :
string -> component_type
* JSON data of type { ! component_type } .
val write_component_types :
Bi_outbuf.t -> component_types -> unit
(** Output a JSON value of type {!component_types}. *)
val string_of_component_types :
?len:int -> component_types -> string
* Serialize a value of type { ! component_types }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component_types :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component_types
(** Input JSON data of type {!component_types}. *)
val component_types_of_string :
string -> component_types
* JSON data of type { ! component_types } .
val write_package :
Bi_outbuf.t -> package -> unit
(** Output a JSON value of type {!package}. *)
val string_of_package :
?len:int -> package -> string
* Serialize a value of type { ! package }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_package :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> package
(** Input JSON data of type {!package}. *)
val package_of_string :
string -> package
* JSON data of type { ! package } .
val write_packages :
Bi_outbuf.t -> packages -> unit
(** Output a JSON value of type {!packages}. *)
val string_of_packages :
?len:int -> packages -> string
* Serialize a value of type { ! packages }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_packages :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> packages
(** Input JSON data of type {!packages}. *)
val packages_of_string :
string -> packages
* JSON data of type { ! packages } .
val write_repository :
Bi_outbuf.t -> repository -> unit
(** Output a JSON value of type {!repository}. *)
val string_of_repository :
?len:int -> repository -> string
* Serialize a value of type { ! repository }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_repository :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> repository
(** Input JSON data of type {!repository}. *)
val repository_of_string :
string -> repository
* JSON data of type { ! repository } .
val write_repositories :
Bi_outbuf.t -> repositories -> unit
(** Output a JSON value of type {!repositories}. *)
val string_of_repositories :
?len:int -> repositories -> string
* Serialize a value of type { ! repositories }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_repositories :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> repositories
(** Input JSON data of type {!repositories}. *)
val repositories_of_string :
string -> repositories
* JSON data of type { ! repositories } .
val write_package_names :
Bi_outbuf.t -> package_names -> unit
(** Output a JSON value of type {!package_names}. *)
val string_of_package_names :
?len:int -> package_names -> string
* Serialize a value of type { ! package_names }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_package_names :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> package_names
(** Input JSON data of type {!package_names}. *)
val package_names_of_string :
string -> package_names
* JSON data of type { ! package_names } .
val write_universe :
Bi_outbuf.t -> universe -> unit
(** Output a JSON value of type {!universe}. *)
val string_of_universe :
?len:int -> universe -> string
* Serialize a value of type { ! universe }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_universe :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> universe
(** Input JSON data of type {!universe}. *)
val universe_of_string :
string -> universe
* JSON data of type { ! universe } .
val write_resources_provided :
Bi_outbuf.t -> resources_provided -> unit
(** Output a JSON value of type {!resources_provided}. *)
val string_of_resources_provided :
?len:int -> resources_provided -> string
* Serialize a value of type { ! resources_provided }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_resources_provided :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> resources_provided
(** Input JSON data of type {!resources_provided}. *)
val resources_provided_of_string :
string -> resources_provided
* JSON data of type { ! resources_provided } .
val write_location_cost :
Bi_outbuf.t -> location_cost -> unit
(** Output a JSON value of type {!location_cost}. *)
val string_of_location_cost :
?len:int -> location_cost -> string
* Serialize a value of type { ! location_cost }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_location_cost :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> location_cost
(** Input JSON data of type {!location_cost}. *)
val location_cost_of_string :
string -> location_cost
* JSON data of type { ! location_cost } .
val write_location :
Bi_outbuf.t -> location -> unit
(** Output a JSON value of type {!location}. *)
val string_of_location :
?len:int -> location -> string
* Serialize a value of type { ! location }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_location :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> location
(** Input JSON data of type {!location}. *)
val location_of_string :
string -> location
* JSON data of type { ! location } .
val write_component :
Bi_outbuf.t -> component -> unit
(** Output a JSON value of type {!component}. *)
val string_of_component :
?len:int -> component -> string
* Serialize a value of type { ! component }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component
(** Input JSON data of type {!component}. *)
val component_of_string :
string -> component
* JSON data of type { ! component } .
val write_binding :
Bi_outbuf.t -> binding -> unit
(** Output a JSON value of type {!binding}. *)
val string_of_binding :
?len:int -> binding -> string
* Serialize a value of type { ! binding }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_binding :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> binding
(** Input JSON data of type {!binding}. *)
val binding_of_string :
string -> binding
* JSON data of type { ! binding } .
val write_configuration :
Bi_outbuf.t -> configuration -> unit
(** Output a JSON value of type {!configuration}. *)
val string_of_configuration :
?len:int -> configuration -> string
* Serialize a value of type { ! configuration }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_configuration :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> configuration
(** Input JSON data of type {!configuration}. *)
val configuration_of_string :
string -> configuration
* JSON data of type { ! configuration } .
| null | https://raw.githubusercontent.com/aeolus-project/zephyrus/0b52de4038bbab724e6a9628430165a7f09f77ae/src/atd/json_v0_j.mli | ocaml | Auto-generated from "json_v0.atd"
* Type definitions for naming.
* Type definitions for Component Type.
atd conflict
atd conflict
* Type definitions for Configuration.
atd implementation
atd repositories
atd provide_resources
atd packages_installed
atd cost
atd requirer
atd provider
atd locations
atd bindings
* Output a JSON value of type {!component_type_name}.
* Input JSON data of type {!component_type_name}.
* Output a JSON value of type {!port_name}.
* Input JSON data of type {!port_name}.
* Output a JSON value of type {!component_name}.
* Input JSON data of type {!component_name}.
* Output a JSON value of type {!package_name}.
* Input JSON data of type {!package_name}.
* Output a JSON value of type {!repository_name}.
* Input JSON data of type {!repository_name}.
* Output a JSON value of type {!location_name}.
* Input JSON data of type {!location_name}.
* Output a JSON value of type {!resource_name}.
* Input JSON data of type {!resource_name}.
* Output a JSON value of type {!provide_arity}.
* Input JSON data of type {!provide_arity}.
* Output a JSON value of type {!require_arity}.
* Input JSON data of type {!require_arity}.
* Output a JSON value of type {!resource_provide_arity}.
* Input JSON data of type {!resource_provide_arity}.
* Output a JSON value of type {!component_type}.
* Input JSON data of type {!component_type}.
* Output a JSON value of type {!component_types}.
* Input JSON data of type {!component_types}.
* Output a JSON value of type {!package}.
* Input JSON data of type {!package}.
* Output a JSON value of type {!packages}.
* Input JSON data of type {!packages}.
* Output a JSON value of type {!repository}.
* Input JSON data of type {!repository}.
* Output a JSON value of type {!repositories}.
* Input JSON data of type {!repositories}.
* Output a JSON value of type {!package_names}.
* Input JSON data of type {!package_names}.
* Output a JSON value of type {!universe}.
* Input JSON data of type {!universe}.
* Output a JSON value of type {!resources_provided}.
* Input JSON data of type {!resources_provided}.
* Output a JSON value of type {!location_cost}.
* Input JSON data of type {!location_cost}.
* Output a JSON value of type {!location}.
* Input JSON data of type {!location}.
* Output a JSON value of type {!component}.
* Input JSON data of type {!component}.
* Output a JSON value of type {!binding}.
* Input JSON data of type {!binding}.
* Output a JSON value of type {!configuration}.
* Input JSON data of type {!configuration}. |
type component_type_name = Json_v0_t.component_type_name
type port_name = Json_v0_t.port_name
type component_name = Json_v0_t.component_name
type package_name = Json_v0_t.package_name
type repository_name = Json_v0_t.repository_name
type location_name = Json_v0_t.location_name
type resource_name = Json_v0_t.resource_name
type provide_arity = Json_v0_t.provide_arity =
InfiniteProvide
| FiniteProvide of int
type require_arity = Json_v0_t.require_arity
type resource_consumption = Json_v0_t.resource_consumption
type resource_provide_arity = Json_v0_t.resource_provide_arity
type component_type = Json_v0_t.component_type = {
atd name
atd provide
atd require
atd consume
(resource_name * resource_consumption) list
}
* Type definitions for Universe .
type component_types = Json_v0_t.component_types
type package = Json_v0_t.package = {
atd name
atd depend
atd consume
(resource_name * resource_consumption) list
}
type packages = Json_v0_t.packages
type repository = Json_v0_t.repository = {
atd name
atd packages
}
type repositories = Json_v0_t.repositories
type package_names = Json_v0_t.package_names
type universe = Json_v0_t.universe = {
atd component_types
(component_type_name * package_names) list;
}
type resources_provided = Json_v0_t.resources_provided
type location_cost = Json_v0_t.location_cost
type location = Json_v0_t.location = {
atd name
atd repository
}
type component = Json_v0_t.component = {
component_name: component_name;
component_type: component_type_name;
component_location: location_name
}
type binding = Json_v0_t.binding = {
atd port
}
type configuration = Json_v0_t.configuration = {
atd components
}
val write_component_type_name :
Bi_outbuf.t -> component_type_name -> unit
val string_of_component_type_name :
?len:int -> component_type_name -> string
* Serialize a value of type { ! component_type_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component_type_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component_type_name
val component_type_name_of_string :
string -> component_type_name
* JSON data of type { ! component_type_name } .
val write_port_name :
Bi_outbuf.t -> port_name -> unit
val string_of_port_name :
?len:int -> port_name -> string
* Serialize a value of type { ! port_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_port_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> port_name
val port_name_of_string :
string -> port_name
* JSON data of type { ! port_name } .
val write_component_name :
Bi_outbuf.t -> component_name -> unit
val string_of_component_name :
?len:int -> component_name -> string
* Serialize a value of type { ! component_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component_name
val component_name_of_string :
string -> component_name
* JSON data of type { ! component_name } .
val write_package_name :
Bi_outbuf.t -> package_name -> unit
val string_of_package_name :
?len:int -> package_name -> string
* Serialize a value of type { ! package_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_package_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> package_name
val package_name_of_string :
string -> package_name
* JSON data of type { ! package_name } .
val write_repository_name :
Bi_outbuf.t -> repository_name -> unit
val string_of_repository_name :
?len:int -> repository_name -> string
* Serialize a value of type { ! repository_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_repository_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> repository_name
val repository_name_of_string :
string -> repository_name
* JSON data of type { ! repository_name } .
val write_location_name :
Bi_outbuf.t -> location_name -> unit
val string_of_location_name :
?len:int -> location_name -> string
* Serialize a value of type { ! location_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_location_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> location_name
val location_name_of_string :
string -> location_name
* JSON data of type { ! location_name } .
val write_resource_name :
Bi_outbuf.t -> resource_name -> unit
val string_of_resource_name :
?len:int -> resource_name -> string
* Serialize a value of type { ! resource_name }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_resource_name :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> resource_name
val resource_name_of_string :
string -> resource_name
* JSON data of type { ! resource_name } .
val write_provide_arity :
Bi_outbuf.t -> provide_arity -> unit
val string_of_provide_arity :
?len:int -> provide_arity -> string
* Serialize a value of type { ! provide_arity }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_provide_arity :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> provide_arity
val provide_arity_of_string :
string -> provide_arity
* JSON data of type { ! provide_arity } .
val write_require_arity :
Bi_outbuf.t -> require_arity -> unit
val string_of_require_arity :
?len:int -> require_arity -> string
* Serialize a value of type { ! require_arity }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_require_arity :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> require_arity
val require_arity_of_string :
string -> require_arity
* JSON data of type { ! require_arity } .
val write_resource_consumption :
Bi_outbuf.t -> resource_consumption -> unit
* Output a JSON value of type { ! .
val string_of_resource_consumption :
?len:int -> resource_consumption -> string
* Serialize a value of type { ! resource_consumption }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_resource_consumption :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> resource_consumption
* Input JSON data of type { ! .
val resource_consumption_of_string :
string -> resource_consumption
* JSON data of type { ! .
val write_resource_provide_arity :
Bi_outbuf.t -> resource_provide_arity -> unit
val string_of_resource_provide_arity :
?len:int -> resource_provide_arity -> string
* Serialize a value of type { ! resource_provide_arity }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_resource_provide_arity :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> resource_provide_arity
val resource_provide_arity_of_string :
string -> resource_provide_arity
* JSON data of type { ! resource_provide_arity } .
val write_component_type :
Bi_outbuf.t -> component_type -> unit
val string_of_component_type :
?len:int -> component_type -> string
* Serialize a value of type { ! component_type }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component_type :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component_type
val component_type_of_string :
string -> component_type
* JSON data of type { ! component_type } .
val write_component_types :
Bi_outbuf.t -> component_types -> unit
val string_of_component_types :
?len:int -> component_types -> string
* Serialize a value of type { ! component_types }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component_types :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component_types
val component_types_of_string :
string -> component_types
* JSON data of type { ! component_types } .
val write_package :
Bi_outbuf.t -> package -> unit
val string_of_package :
?len:int -> package -> string
* Serialize a value of type { ! package }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_package :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> package
val package_of_string :
string -> package
* JSON data of type { ! package } .
val write_packages :
Bi_outbuf.t -> packages -> unit
val string_of_packages :
?len:int -> packages -> string
* Serialize a value of type { ! packages }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_packages :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> packages
val packages_of_string :
string -> packages
* JSON data of type { ! packages } .
val write_repository :
Bi_outbuf.t -> repository -> unit
val string_of_repository :
?len:int -> repository -> string
* Serialize a value of type { ! repository }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_repository :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> repository
val repository_of_string :
string -> repository
* JSON data of type { ! repository } .
val write_repositories :
Bi_outbuf.t -> repositories -> unit
val string_of_repositories :
?len:int -> repositories -> string
* Serialize a value of type { ! repositories }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_repositories :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> repositories
val repositories_of_string :
string -> repositories
* JSON data of type { ! repositories } .
val write_package_names :
Bi_outbuf.t -> package_names -> unit
val string_of_package_names :
?len:int -> package_names -> string
* Serialize a value of type { ! package_names }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_package_names :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> package_names
val package_names_of_string :
string -> package_names
* JSON data of type { ! package_names } .
val write_universe :
Bi_outbuf.t -> universe -> unit
val string_of_universe :
?len:int -> universe -> string
* Serialize a value of type { ! universe }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_universe :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> universe
val universe_of_string :
string -> universe
* JSON data of type { ! universe } .
val write_resources_provided :
Bi_outbuf.t -> resources_provided -> unit
val string_of_resources_provided :
?len:int -> resources_provided -> string
* Serialize a value of type { ! resources_provided }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_resources_provided :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> resources_provided
val resources_provided_of_string :
string -> resources_provided
* JSON data of type { ! resources_provided } .
val write_location_cost :
Bi_outbuf.t -> location_cost -> unit
val string_of_location_cost :
?len:int -> location_cost -> string
* Serialize a value of type { ! location_cost }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_location_cost :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> location_cost
val location_cost_of_string :
string -> location_cost
* JSON data of type { ! location_cost } .
val write_location :
Bi_outbuf.t -> location -> unit
val string_of_location :
?len:int -> location -> string
* Serialize a value of type { ! location }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_location :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> location
val location_of_string :
string -> location
* JSON data of type { ! location } .
val write_component :
Bi_outbuf.t -> component -> unit
val string_of_component :
?len:int -> component -> string
* Serialize a value of type { ! component }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_component :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> component
val component_of_string :
string -> component
* JSON data of type { ! component } .
val write_binding :
Bi_outbuf.t -> binding -> unit
val string_of_binding :
?len:int -> binding -> string
* Serialize a value of type { ! binding }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_binding :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> binding
val binding_of_string :
string -> binding
* JSON data of type { ! binding } .
val write_configuration :
Bi_outbuf.t -> configuration -> unit
val string_of_configuration :
?len:int -> configuration -> string
* Serialize a value of type { ! configuration }
into a JSON string .
@param len specifies the initial length
of the buffer used internally .
Default : 1024 .
into a JSON string.
@param len specifies the initial length
of the buffer used internally.
Default: 1024. *)
val read_configuration :
Yojson.Safe.lexer_state -> Lexing.lexbuf -> configuration
val configuration_of_string :
string -> configuration
* JSON data of type { ! configuration } .
|
f1409cace3e21eb881750e8053c1b8208259bfdd78438ac9cdc47ccb4ef20ebd | mitchellwrosen/planet-mitchell | Benchmark.hs | module Benchmark
( -- * Running benchmarks
defaultMain
-- * Constructing benchmarks
-- ** Benchmark
, Benchmark
, bench
, bgroup
, env
, envWithCleanup
-- ** Benchmarkable
, Benchmarkable
, nfIO
, whnfIO
, nf
, whnf
, perBatchEnv
, perBatchEnvWithCleanup
, perRunEnv
, perRunEnvWithCleanup
) where
import Gauge
| null | https://raw.githubusercontent.com/mitchellwrosen/planet-mitchell/18dd83204e70fffcd23fe12dd3a80f70b7fa409b/planet-mitchell-test/src/Benchmark.hs | haskell | * Running benchmarks
* Constructing benchmarks
** Benchmark
** Benchmarkable | module Benchmark
defaultMain
, Benchmark
, bench
, bgroup
, env
, envWithCleanup
, Benchmarkable
, nfIO
, whnfIO
, nf
, whnf
, perBatchEnv
, perBatchEnvWithCleanup
, perRunEnv
, perRunEnvWithCleanup
) where
import Gauge
|
27b9a72fc06e8b763f885ab4bb518fe95a6bdf4efc2a995ec6ffe1649ee3c73b | matterhorn-chat/matterhorn | test_messages.hs | {-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
module Main where
import Control.Exception
import Data.Function (on)
import Data.List (sortBy)
import qualified Data.List.UniqueUnsorted as U
import qualified Data.Map as Map
import Data.Maybe (fromJust)
import qualified Data.Sequence as Seq
import qualified Data.Text as T
import Data.Time.Calendar (Day(..))
import Data.Time.Clock (UTCTime(..), getCurrentTime
, secondsToDiffTime)
import System.Exit
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
import Test.QuickCheck.Checkers
import Network.Mattermost.Types
import Message_QCA
import Matterhorn.Types.DirectionalSeq
import Matterhorn.Types.Core
import Matterhorn.Types.Messages
import Matterhorn.Types.Posts
import Matterhorn.Prelude
import Matterhorn.TimeUtils
main :: IO ()
main = defaultMain tests `catch` (\e -> do
if e == ExitSuccess
then putStrLn "Passed"
else do putStrLn "FAILED"
throwIO e)
tests :: TestTree
tests = testGroup "Messages Tests"
[ createTests
, lookupTests
, movementTests
, reversalTests
, splitTests
, removeTests
, instanceTests
]
test_m1 :: IO Message
test_m1 = do t1 <- ServerTime <$> getCurrentTime
return $ makeMsg t1 Nothing
test_m2 :: IO Message
test_m2 = do t2 <- ServerTime <$> getCurrentTime
return $ (makeMsg t2 (Just $ MessagePostId $ fromId $ Id "m2")) { _mType = CP Emote }
test_m3 :: IO Message
test_m3 = do t3 <- ServerTime <$> getCurrentTime
return $ makeMsg t3 (Just $ MessagePostId $ fromId $ Id "m3")
setDateOrderMessages :: [Message] -> [Message]
setDateOrderMessages = snd . foldl setTimeAndInsert (startTime, [])
where setTimeAndInsert (t, ml) m = let t2 = tick t
in (t2, ml ++ [m {_mDate = t2}])
startTime = ServerTime $ UTCTime (ModifiedJulianDay 100) (secondsToDiffTime 0)
tick (ServerTime (UTCTime d t)) = ServerTime $ UTCTime d $ succ t
makeMsg :: ServerTime -> Maybe MessageId -> Message
makeMsg t mId = Message mempty mempty NoUser t (CP NormalPost) False False Seq.empty NotAReply
mId Map.empty Nothing False False Nothing
makeMsgs :: [Message] -> Messages
makeMsgs = foldr addMessage noMessages
idlist :: Foldable t => t Message -> [Maybe MessageId]
idlist = foldr (\m s -> m^.mMessageId : s) []
postids :: (Foldable t) => String -> t Message -> String
postids names msgs = let zipf = (\(n,z) m -> if null n
then ("", ('?', m) : z)
else (init n, (last n, m) : z))
zipped = snd $ foldr (flip zipf) (names, []) msgs
pid (n, m) = show n <> ".mPostID=" <> show (m^.mMessageId)
in intercalate ", " $ map pid zipped
uniqueIds :: Foldable t => t Message -> Bool
uniqueIds msgs =
let ids = idlist msgs
in length ids == length (U.unique ids)
validIds :: Foldable t => t Message -> Bool
validIds = null . filter isNothing . idlist
tastyBatch :: TestBatch -> TestTree
tastyBatch b = testGroup (fst b) $ tastyTests (snd b)
where tastyTests = map tastyTest
tastyTest = uncurry testProperty
createTests :: TestTree
createTests = testGroup "Create"
[ testCase "no messages"
$ 0 @=? length noMessages
, testProperty "has messages"
$ \x -> not (null (x :: Messages)) ==> 0 /= length x
, testProperty "add to empty"
$ \x -> 1 == (length $ addMessage x noMessages)
, testProperty "add to add to empty"
$ \(x, y) -> 2 == (length $ makeMsgs [x, y])
, testProperty "join to empty"
$ \(x, y) ->
let m1 = makeMsgs [x, y]
m2 = noMessages
in (2 == (length $ m1 `appendDirSeq` m2) &&
2 == (length $ m2 `appendDirSeq` m1))
, testProperty "join one to many"
$ \(x, y, z) ->
let l1 = setDateOrderMessages [x, y]
m1 = makeMsgs l1
m2 = addMessage z noMessages
j2 = m2 `appendDirSeq` m1
in idlist [z, x, y] === idlist j2
, testProperty "join many to one"
$ \(x, y, z) ->
let l1 = setDateOrderMessages [x, y]
m1 = makeMsgs l1
m2 = addMessage z noMessages
j1 = m1 `appendDirSeq` m2
in idlist [x, y, z] === idlist j1
, testProperty "join to many"
$ \(w, x, y, z) ->
let l1 = setDateOrderMessages [x, y]
l2 = setDateOrderMessages [w, z]
m1 = makeMsgs l1
m2 = makeMsgs l2
-- note that mappend is literal: there is
-- no date relationship between the
-- members l1 and l2 and mappend doesn't
-- enforce one.
j1 = m1 `appendDirSeq` m2
j2 = m2 `appendDirSeq` m1
in (4 == (length j1) &&
4 == (length j2) &&
idlist (l1 <> l2) == idlist j1 &&
idlist (l2 <> l1) == idlist j2)
, testProperty "natural ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
in idlist l === idlist (makeMsgs l)
, testProperty "reverse ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
in idlist l === idlist (makeMsgs $ reverse l)
, testProperty "mirrored ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs [y', z', w', x'])
, testProperty "ordering 1 of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
[w', x', y', z'] = l
in
idlist l === idlist (makeMsgs [y', w', z', x'])
, testProperty "ordering 2 of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs [x', z', w', y'])
, testProperty "duplicated last addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ map postMsg [w, x, y, z]
in uniqueIds l ==>
idlist l === idlist (makeMsgs $ [last l] <> l)
, testProperty "duplicated natural ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ map postMsg [w, x, y, z]
in idlist l === idlist (makeMsgs $ l <> l)
, testProperty "duplicated reverse ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ map postMsg [w, x, y, z]
in idlist l === idlist (makeMsgs $ reverse l <> l)
, testProperty "duplicated mirrored ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ map postMsg [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs $ [y', z', w', x'] <> l)
, testProperty "duplicated ordering 1 of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ postMsg <$> [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs $ [y', w', z', x'] <> l)
, testProperty "duplicated ordering 2 of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ postMsg <$> [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs $ [x', z', w', y'] <> l)
, testProperty "non-posted are not duplicate removed"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
[w', x', y', z'] = l
l' = [x', z', w', y']
ex = sortBy (\a b -> compare (a^.mDate) (b^.mDate))
([e | e <- l', isNothing (messagePostId e) ] <> l)
in idlist ex === idlist (makeMsgs $ l' <> l)
, testProperty "duplicate dates different IDs in posted order"
$ \(w, x, y, z) ->
let d = ServerTime $ UTCTime
(ModifiedJulianDay 1234)
(secondsToDiffTime 9876)
l = foldl (setTime d) [] $ postMsg <$> [w, x, y, z]
setTime t ml m = ml ++ [m {_mDate = t}]
[w', x', y', z'] = l
l' = [x', z', w', y']
ex = l
in uniqueIds l ==>
idlist ex === idlist (makeMsgs $ l' <> l)
]
movementTests :: TestTree
movementTests = testGroup "Movement"
[ moveUpTestEmpty
, moveUpTestSingle
, moveUpTestMultipleStart
, moveUpTestMultipleEnd
, moveUpTestMultipleSkipDeleted
, moveUpTestMultipleSkipDeletedAll
, moveDownTestEmpty
, moveDownTestMultipleStart
, moveDownTestSingle
, moveDownTestMultipleEnd
, moveDownTestMultipleSkipDeleted
, moveDownTestMultipleSkipDeletedAll
]
moveDownTestEmpty :: TestTree
moveDownTestEmpty = testProperty "Move up in empty messages" $
\x -> Nothing == getNextPostId x noMessages
moveUpTestEmpty :: TestTree
moveUpTestEmpty = testProperty "Move down in empty messages" $
\x -> Nothing == getPrevPostId x noMessages
moveDownTestSingle :: TestTree
moveDownTestSingle = testProperty "Move up from single message" $
\x -> let msgs = addMessage x noMessages
in Nothing == (getNextPostId (messagePostId x) msgs)
moveUpTestSingle :: TestTree
moveUpTestSingle = testProperty "Move down from single message" $
\x -> let msgs = addMessage x noMessages
in Nothing == (getPrevPostId (messagePostId x) msgs)
moveDownTestMultipleStart :: TestTree
moveDownTestMultipleStart =
testProperty "Move down in multiple messages from the start" $
\(x', y', z') ->
let [x, y, z] = setDateOrderMessages
[ postMsg x'
, postMsg y'
, postMsg z'
]
msgs = makeMsgs [x, y, z]
msgid = getNextMessageId (x^.mMessageId) msgs
-- for useful info on failure:
idents = postids "xyz" msgs
info = idents <> " against " <> show msgid
in counterexample info $
y^.mMessageId == msgid
moveUpTestMultipleStart :: TestTree
moveUpTestMultipleStart =
testProperty "Move up in multiple messages from the start" $
\(x', y', z') ->
let [x, y, z] = setDateOrderMessages
[ postMsg x', postMsg y', postMsg z']
msgs = makeMsgs [x, y, z]
msgid = getPrevPostId (messagePostId x) msgs
-- for useful info on failure:
idents = postids "xyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ Nothing == msgid
moveDownTestMultipleEnd :: TestTree
moveDownTestMultipleEnd =
testProperty "Move down in multiple messages from the end" $
\(x', y', z') ->
let [x, y, z] = setDateOrderMessages
[ postMsg x', postMsg y', postMsg z']
msgs = makeMsgs [x, y, z]
msgid = getNextPostId (messagePostId z) msgs
-- for useful info on failure:
idents = postids "xyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ Nothing == msgid
moveUpTestMultipleEnd :: TestTree
moveUpTestMultipleEnd =
testProperty "Move up in multiple messages from the end" $
\(x', y', z') ->
let [x, y, z] = setDateOrderMessages
[ postMsg x', postMsg y', postMsg z']
msgs = makeMsgs [x, y, z]
msgid = getPrevPostId (messagePostId z) msgs
-- for useful info on failure:
idents = postids "xyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ (messagePostId y) == msgid
moveDownTestMultipleSkipDeleted :: TestTree
moveDownTestMultipleSkipDeleted =
testProperty "Move down in multiple messages skipping deleteds" $
\(w', x', y', z') ->
let [w, x, y, z] = setDateOrderMessages
[ postMsg w'
, delMsg x'
, delMsg y'
, postMsg z']
msgs = makeMsgs [w, x, y, z]
msgid = getNextPostId (messagePostId w) msgs
-- for useful info on failure:
idents = postids "wxyz" msgs
info = idents <> " against " <> show msgid
in counterexample info $ (messagePostId z) == msgid
moveUpTestMultipleSkipDeleted :: TestTree
moveUpTestMultipleSkipDeleted =
testProperty "Move one up in multiple messages skipping deleteds" $
\(w', x', y', z') ->
let [w, x, y, z] = setDateOrderMessages
[ postMsg w'
, delMsg x'
, delMsg y'
, postMsg z']
msgs = makeMsgs [w, x, y, z]
msgid = getPrevPostId (messagePostId z) msgs
-- for useful info on failure:
idents = postids "wxyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ (messagePostId w) == msgid
moveDownTestMultipleSkipDeletedAll :: TestTree
moveDownTestMultipleSkipDeletedAll =
testProperty "Move one down in multiple deleted messages skipping deleteds" $
\(w', x', y', z') ->
-- n.b. current selected is also deleted,
-- which can happen due to multi-user async
-- server changes.
let [w, x, y, z] = setDateOrderMessages
[ delMsg w'
, delMsg x'
, delMsg y'
, delMsg z']
msgs = makeMsgs [w, x, y, z]
msgid = getNextPostId (messagePostId w) msgs
-- for useful info on failure:
idents = postids "wxyz" msgs
info = idents <> " against " <> show msgid
in counterexample info $ Nothing == msgid
moveUpTestMultipleSkipDeletedAll :: TestTree
moveUpTestMultipleSkipDeletedAll =
testProperty "Move one up in multiple deleted messages skipping deleteds" $
\(w', x', y', z') ->
-- n.b. current selected is also deleted,
-- which can happen due to multi-user async
-- server changes.
let [w, x, y, z] = setDateOrderMessages
[ delMsg w'
, delMsg x'
, delMsg y'
, delMsg z']
msgs = makeMsgs [w, x, y, z]
msgid = getPrevPostId (messagePostId z) msgs
-- for useful info on failure:
idents = postids "wxyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ Nothing == msgid
reversalTests :: TestTree
reversalTests = testGroup "Reversal"
[ testProperty "round trip" $
\l -> let rr = unreverseMessages (reverseMessages l)
in idlist l === idlist rr
, testProperty "getLatestMessage finds same in either dir" $
KWQ : just one reverse , not two
in (messagePostId <$> getLatestPostMsg l) ===
(messagePostId <$> getLatestPostMsg rr)
, testCase "reverse nothing" $
(null $ unreverseMessages $ reverseMessages noMessages) @?
"reverse of empty Messages"
, testProperty "reverse order" $
\l -> let r = reverseMessages l
in idlist l === reverse (idlist r)
]
lookupTests :: TestTree
lookupTests = testGroup "Lookup"
[ testProperty "getEarliestPostMsg" $ \(m1, m2, m3, m4, m5) ->
let mlist = m1 : m2 : m3 : m4 : m5 : []
msgs = makeMsgs mlist
postIds = fmap messagePostId
$ sortBy (compare `on` (^.mDate))
$ filter (\m -> isJust (messagePostId m) && (not $ m^.mDeleted)) mlist
firstPostId = messagePostId <$> getEarliestPostMsg msgs
in if null postIds
then Nothing === firstPostId
else Just (head postIds) === firstPostId
, testProperty "getLatestPostMsg" $ \(m1, m2, m3, m4, m5) ->
let mlist = m1 : m2 : m3 : m4 : m5 : []
msgs = makeMsgs mlist
postIds = fmap messagePostId
$ sortBy (compare `on` (^.mDate))
$ filter (\m -> isJust (messagePostId m) && (not $ m^.mDeleted)) mlist
lastPostId = messagePostId <$> getLatestPostMsg msgs
in counterexample ("ids: " <> show (idlist msgs)
<> "\n dates: " <> (show $ fmap show $ foldr (\m l -> m^.mDate : l) [] msgs)
<> "\n deleted: " <> (show $ fmap show $ foldr (\m l -> m^.mDeleted : l) [] msgs)
<> "\n postIds:" <> show postIds) (
if null postIds
then Nothing === lastPostId
else Just (last postIds) === lastPostId)
, testProperty "findLatestUserMessage" $ \(m1, m2, m3, m4, m5) ->
let mlist = m1 : m2 : m3 : m4 : m5 : []
msgs = makeMsgs mlist
postIds = fmap messagePostId
$ sortBy (compare `on` (^.mDate))
$ filter (\m -> isJust (messagePostId m) && (not $ m^.mDeleted)) mlist
lastPostId = messagePostId <$> findLatestUserMessage (const True) msgs
firstPostId = messagePostId <$> findLatestUserMessage (\m -> messagePostId m == head postIds) msgs
in counterexample ("ids: " <> show (idlist msgs)
<> "\n dates: " <> (show $ fmap show $ foldr (\m l -> m^.mDate : l) [] msgs)
<> "\n deleted: " <> (show $ fmap show $ foldr (\m l -> m^.mDeleted : l) [] msgs)
<> "\n postIds:" <> show postIds) (
if null postIds
then Nothing === lastPostId
else Just (last postIds) === lastPostId .&&. Just (head postIds) === firstPostId)
]
splitTests :: TestTree
splitTests = testGroup "Split"
[ testCase "split nothing on empty" $
let (m, _) = splitDirSeqOn (const False) noMessages
in isNothing m @? "must be nothing"
, testProperty "split just on empty" $ \x ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == x) noMessages
in isNothing m
, testProperty "split nothing on list" $ \(x::Messages) ->
let (m, _) = splitDirSeqOn (const False) x
in isNothing m
, testProperty "split nothing on not found" $ \(w', x', y', z') ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
msgs = makeMsgs [x, y, z]
idents = postids "wxyz" msgs
info = idents <> " against " <> show (messagePostId (fromJust m))
in uniqueIds [w, x, y, z] ==>
counterexample info $ isNothing m
, testProperty "all before reversed on split nothing"
$ \(w, x, y, z) ->
let (_, (before, _)) = splitDirSeqOn (const False) msgs
msgs = makeMsgs inpl
inpl = setDateOrderMessages [w, x, y, z]
control = idlist (reverse inpl)
result = idlist before
info = show control <> " /= " <> show result
in counterexample info $ control == result
, testProperty "all before reversed on not found"
$ \(w', x', y', z') ->
let (_, (before, _)) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
in uniqueIds [w, x, y, z] ==>
idlist (reverse inpl) == idlist before
, testProperty "found at first position"
$ \(w', x', y', z') ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
in validIds inpl && uniqueIds inpl ==>
messagePostId w == messagePostId (fromJust m)
, testProperty "no before when found at first position"
$ \(w', x', y', z') ->
let (_, (before, _)) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist before)
in validIds inpl && uniqueIds inpl ==>
counterexample info $ null $ unreverseMessages before
, testProperty "remaining after when found at first position"
$ \(w', x', y', z') ->
let (_, (_, afterMsgs)) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist afterMsgs)
in validIds inpl && uniqueIds inpl ==>
counterexample info $
idlist (tail inpl) == idlist afterMsgs
, testProperty "found at last position"
$ \(w', x', y', z') ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == z^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
in validIds inpl && uniqueIds inpl ==>
messagePostId z == messagePostId (fromJust m)
, testProperty "reversed before when found at last position"
$ \(w', x', y', z') ->
let (_, (before, _)) = splitDirSeqOn (\m2 -> m2^.mMessageId == z^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist before)
in validIds inpl && uniqueIds inpl ==>
counterexample info $
idlist (reverse $ init inpl) == idlist before
, testProperty "no after when found at last position"
$ \(w', x', y', z') ->
let (_, (_, afterMsgs)) = splitDirSeqOn (\m2 -> m2^.mMessageId == z^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist afterMsgs)
in validIds inpl && uniqueIds inpl ==>
counterexample info $ null afterMsgs
, testProperty "found at midpoint position"
$ \(v', w', x', y', z') ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == x^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [v, w, x, y, z]
[v, w, x, y, z] = setDateOrderMessages
[v', w', x', y', z']
in validIds inpl && uniqueIds inpl ==>
messagePostId x == messagePostId (fromJust m)
, testProperty "reversed before when found at midpoint position"
$ \(v', w', x', y', z') ->
let (_, (before, _)) = splitDirSeqOn (\m2 -> m2^.mMessageId == x^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [v, w, x, y, z]
[v, w, x, y, z] = setDateOrderMessages
[v', w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist before)
in validIds inpl && uniqueIds inpl ==>
counterexample info $
idlist [w, v] == idlist before
, testProperty "after when found at midpoint position"
$ \(v', w', x', y', z') ->
let (_, (_, afterMsgs)) = splitDirSeqOn (\m2 -> m2^.mMessageId == x^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [v, w, x, y, z]
[v, w, x, y, z] = setDateOrderMessages
[v', w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist afterMsgs)
in validIds inpl && uniqueIds inpl ==>
counterexample info $
idlist [y, z] == idlist afterMsgs
]
removeTests :: TestTree
removeTests = adjustOption (\(QuickCheckMaxRatio n) -> QuickCheckMaxRatio (n*10)) $
testGroup "Remove"
[ testProperty "remove on empty" $ \(id1, id2) ->
let (remaining, removed) = removeMatchesFromSubset (const True) id1 id2 noMessages
in counterexample "got something from nothing" $ null remaining && null removed
, testProperty "remove range not found (C9)" $ \(id1, id2, msglist) ->
let msgs = makeMsgs msglist
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) (Just id1) (Just id2) msgs
in (not $ Just id1 `elem` ids || Just id2 `elem` ids) ==>
counterexample "got something from invalid range" $
null removed && length remaining == length ids
, testProperty "remove first in range (C6)" $ \(id1, id2, msglist) ->
let msgs = makeMsgs msglist
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) (Just id1) (Just id2) msgs
in Just id1 `elem` ids && (not $ Just id2 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
" remove id1=" <> show id1 <>
" should be in " <> show (idlist removed) <>
" but not id2=" <> show id2 <>
" and remaining=" <> show (idlist remaining)) $
(not $ null removed) &&
(length remaining /= length ids) &&
Just id1 `elem` idlist removed &&
(not $ Just id1 `elem` idlist remaining)
, testProperty "remove nothing first in range" $ \(id1, id2, msglist) ->
let msgs = makeMsgs msglist
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const False) (Just id1) (Just id2) msgs
in Just id1 `elem` ids && (not $ Just id2 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
" remove id1=" <> show id1 <>
" should be in " <> show (idlist removed) <>
" but not id2=" <> show id2 <>
" and remaining=" <> show (idlist remaining)) $
(idlist remaining == ids && null removed)
, testCase "remove only as last" $
let (remaining, removed) = removeMatchesFromSubset (const True) (Just id1) (Just id2) msgs
id1 = MessagePostId $ fromId $ Id "id1"
id2 = MessagePostId $ fromId $ Id "id2"
msgs = makeMsgs [makeMsg (ServerTime originTime) (Just id2)]
in null remaining && length removed == 1 @? "removed"
, testProperty "remove last in range (C8)" $ \(idx2, msg, msglist) ->
let msgs = makeMsgs $ msg : msglist
ids = idlist msgs
id2 = ids !! idx2'
id1 = MessagePostId $ PI $ Id $ T.intercalate "-" $ map (unId . unPI) $
catMaybes ((\i -> i >>= messageIdPostId) <$> ids)
idx2' = abs idx2 `mod` length ids
(remaining, removed) = removeMatchesFromSubset (const True) (Just id1) id2 msgs
in (isJust id2) && uniqueIds msgs ==>
counterexample ("with idlist " <> show ids <>
" remove id2=" <> show id2 <>
" should be in " <> show (idlist removed) <>
" but not id1=" <> show id1 <>
" and remaining=" <> show (idlist remaining)
) $
(not $ null removed) &&
(length remaining /= length ids) &&
id2 `elem` idlist removed &&
(not $ id2 `elem` idlist remaining)
, testProperty "remove sub range (C5)" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', postIds) = splitAt (idx2' + 1) ids
(preIds, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
(remaining, removed) = removeMatchesFromSubset (const True) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining) <>
"\n from " <> show preIds <> " and " <> show postIds
) $
(idlist remaining == (preIds <> postIds) &&
idlist removed == matchIds)
, testProperty "remove nothing sub range" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', postIds) = splitAt (idx2' + 1) ids
(preIds, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
(remaining, removed) = removeMatchesFromSubset (const False) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining) <>
"\n from " <> show preIds <> " and " <> show postIds
) $
(idlist remaining == ids && null removed)
, testProperty "remove first in sub range (C5)" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', _) = splitAt (idx2' + 1) ids
(_, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
(remaining, removed) = removeMatchesFromSubset (\m -> m^.mMessageId == id1) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == (filter (/= id1) ids) &&
idlist removed == [id1])
, testProperty "remove last in sub range (C5)" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', _) = splitAt (idx2' + 1) ids
(_, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
(remaining, removed) = removeMatchesFromSubset (\m -> m^.mMessageId == id2) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == (filter (/= id2) ids) &&
idlist removed == [id2])
, testProperty "remove some in sub range (C5)" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', _) = splitAt (idx2' + 1) ids
(_, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
rmvIds = map snd $ filter (odd . fst) $ zip [(0::Int)..] matchIds
(remaining, removed) = removeMatchesFromSubset (\m -> m^.mMessageId `elem` rmvIds) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n matching=" <> show matchIds <>
"\n removing=" <> show rmvIds <>
"\n extracts=" <> show (idlist removed) <>
"\n and leaves remaining=" <> show (idlist remaining) <>
"\n from " <> show (filter (not . flip elem rmvIds) ids)
) $
(idlist remaining == (filter (not . flip elem rmvIds) ids) &&
idlist removed == rmvIds)
, testProperty "remove from start last Nothing (C4)" $ \(m1, m2, m3, m4, m5, idx1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(leftIds, matchIds) = splitAt idx1' ids
id1 = head matchIds
idx1' = abs idx1 `mod` 5
(remaining, removed) = removeMatchesFromSubset (const True) id1 Nothing msgs
in uniqueIds msgs && isJust id1 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == leftIds &&
idlist removed == matchIds)
, testProperty "remove from Nothing to offset (C2)" $ \(m1, m2, m3, m4, m5, idx1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(matchIds, leftIds) = splitAt (idx1' + 1) ids
id1 = last matchIds
idx1' = abs idx1 `mod` 4
(remaining, removed) = removeMatchesFromSubset (const True) Nothing id1 msgs
in uniqueIds msgs && isJust id1 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == leftIds &&
idlist removed == matchIds)
, testProperty "remove from start not found last Nothing (C7)" $ \(m1, m2, m3, m4, m5, id1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) id1 Nothing msgs
in uniqueIds msgs && isJust id1 && (not $ id1 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
"\n extracts=" <> show (idlist removed) <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == ids &&
null removed)
, testProperty "remove from Nothing to end not found (C3)" $ \(m1, m2, m3, m4, m5, id1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) Nothing id1 msgs
in uniqueIds msgs && isJust id1 && (not $ id1 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
"\n extracts=" <> show (idlist removed) <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == ids &&
null removed)
, testProperty "remove from Nothing to Nothing (C1)" $ \(m1, m2, m3, m4, m5, id1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) Nothing Nothing msgs
in uniqueIds msgs && isJust id1 && (not $ id1 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
"\n extracts=" <> show (idlist removed) <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist removed == ids &&
null remaining)
]
monoid' :: (Show t, Arbitrary t, EqProp t) => t -> (t -> t -> t) -> TestBatch
monoid' mempty' mappend' =
( "monoid"
, [ ("left identity", leftId mappend' mempty')
, ("right identity", rightId mappend' mempty')
, ("associativity" , isAssoc mappend')
]
)
instanceTests :: TestTree
instanceTests = testGroup "Messages Instances"
$ map tastyBatch
[ (monoid' (emptyDirSeq :: Messages) appendDirSeq)
, (monoid' (emptyDirSeq :: RetrogradeMessages) appendDirSeq)
]
instance EqProp Messages where
a =-= b = idlist a =-= idlist b
instance EqProp RetrogradeMessages where
a =-= b = idlist a =-= idlist b
instance EqProp PostId where
a =-= b = (show $ idString a) =-= (show $ idString b)
instance EqProp MessageId where
(MessagePostId a) =-= (MessagePostId b) = (show $ idString a) =-= (show $ idString b)
(MessageUUID a) =-= (MessageUUID b) = (show a) =-= (show b)
_ =-= _ = eq True False
| null | https://raw.githubusercontent.com/matterhorn-chat/matterhorn/19a73ce833a8a8de3616cf884c03e9f08a4db0a7/test/test_messages.hs | haskell | # LANGUAGE TypeSynonymInstances #
note that mappend is literal: there is
no date relationship between the
members l1 and l2 and mappend doesn't
enforce one.
for useful info on failure:
for useful info on failure:
for useful info on failure:
for useful info on failure:
for useful info on failure:
for useful info on failure:
n.b. current selected is also deleted,
which can happen due to multi-user async
server changes.
for useful info on failure:
n.b. current selected is also deleted,
which can happen due to multi-user async
server changes.
for useful info on failure: | # LANGUAGE FlexibleInstances #
module Main where
import Control.Exception
import Data.Function (on)
import Data.List (sortBy)
import qualified Data.List.UniqueUnsorted as U
import qualified Data.Map as Map
import Data.Maybe (fromJust)
import qualified Data.Sequence as Seq
import qualified Data.Text as T
import Data.Time.Calendar (Day(..))
import Data.Time.Clock (UTCTime(..), getCurrentTime
, secondsToDiffTime)
import System.Exit
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
import Test.QuickCheck.Checkers
import Network.Mattermost.Types
import Message_QCA
import Matterhorn.Types.DirectionalSeq
import Matterhorn.Types.Core
import Matterhorn.Types.Messages
import Matterhorn.Types.Posts
import Matterhorn.Prelude
import Matterhorn.TimeUtils
main :: IO ()
main = defaultMain tests `catch` (\e -> do
if e == ExitSuccess
then putStrLn "Passed"
else do putStrLn "FAILED"
throwIO e)
tests :: TestTree
tests = testGroup "Messages Tests"
[ createTests
, lookupTests
, movementTests
, reversalTests
, splitTests
, removeTests
, instanceTests
]
test_m1 :: IO Message
test_m1 = do t1 <- ServerTime <$> getCurrentTime
return $ makeMsg t1 Nothing
test_m2 :: IO Message
test_m2 = do t2 <- ServerTime <$> getCurrentTime
return $ (makeMsg t2 (Just $ MessagePostId $ fromId $ Id "m2")) { _mType = CP Emote }
test_m3 :: IO Message
test_m3 = do t3 <- ServerTime <$> getCurrentTime
return $ makeMsg t3 (Just $ MessagePostId $ fromId $ Id "m3")
setDateOrderMessages :: [Message] -> [Message]
setDateOrderMessages = snd . foldl setTimeAndInsert (startTime, [])
where setTimeAndInsert (t, ml) m = let t2 = tick t
in (t2, ml ++ [m {_mDate = t2}])
startTime = ServerTime $ UTCTime (ModifiedJulianDay 100) (secondsToDiffTime 0)
tick (ServerTime (UTCTime d t)) = ServerTime $ UTCTime d $ succ t
makeMsg :: ServerTime -> Maybe MessageId -> Message
makeMsg t mId = Message mempty mempty NoUser t (CP NormalPost) False False Seq.empty NotAReply
mId Map.empty Nothing False False Nothing
makeMsgs :: [Message] -> Messages
makeMsgs = foldr addMessage noMessages
idlist :: Foldable t => t Message -> [Maybe MessageId]
idlist = foldr (\m s -> m^.mMessageId : s) []
postids :: (Foldable t) => String -> t Message -> String
postids names msgs = let zipf = (\(n,z) m -> if null n
then ("", ('?', m) : z)
else (init n, (last n, m) : z))
zipped = snd $ foldr (flip zipf) (names, []) msgs
pid (n, m) = show n <> ".mPostID=" <> show (m^.mMessageId)
in intercalate ", " $ map pid zipped
uniqueIds :: Foldable t => t Message -> Bool
uniqueIds msgs =
let ids = idlist msgs
in length ids == length (U.unique ids)
validIds :: Foldable t => t Message -> Bool
validIds = null . filter isNothing . idlist
tastyBatch :: TestBatch -> TestTree
tastyBatch b = testGroup (fst b) $ tastyTests (snd b)
where tastyTests = map tastyTest
tastyTest = uncurry testProperty
createTests :: TestTree
createTests = testGroup "Create"
[ testCase "no messages"
$ 0 @=? length noMessages
, testProperty "has messages"
$ \x -> not (null (x :: Messages)) ==> 0 /= length x
, testProperty "add to empty"
$ \x -> 1 == (length $ addMessage x noMessages)
, testProperty "add to add to empty"
$ \(x, y) -> 2 == (length $ makeMsgs [x, y])
, testProperty "join to empty"
$ \(x, y) ->
let m1 = makeMsgs [x, y]
m2 = noMessages
in (2 == (length $ m1 `appendDirSeq` m2) &&
2 == (length $ m2 `appendDirSeq` m1))
, testProperty "join one to many"
$ \(x, y, z) ->
let l1 = setDateOrderMessages [x, y]
m1 = makeMsgs l1
m2 = addMessage z noMessages
j2 = m2 `appendDirSeq` m1
in idlist [z, x, y] === idlist j2
, testProperty "join many to one"
$ \(x, y, z) ->
let l1 = setDateOrderMessages [x, y]
m1 = makeMsgs l1
m2 = addMessage z noMessages
j1 = m1 `appendDirSeq` m2
in idlist [x, y, z] === idlist j1
, testProperty "join to many"
$ \(w, x, y, z) ->
let l1 = setDateOrderMessages [x, y]
l2 = setDateOrderMessages [w, z]
m1 = makeMsgs l1
m2 = makeMsgs l2
j1 = m1 `appendDirSeq` m2
j2 = m2 `appendDirSeq` m1
in (4 == (length j1) &&
4 == (length j2) &&
idlist (l1 <> l2) == idlist j1 &&
idlist (l2 <> l1) == idlist j2)
, testProperty "natural ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
in idlist l === idlist (makeMsgs l)
, testProperty "reverse ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
in idlist l === idlist (makeMsgs $ reverse l)
, testProperty "mirrored ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs [y', z', w', x'])
, testProperty "ordering 1 of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
[w', x', y', z'] = l
in
idlist l === idlist (makeMsgs [y', w', z', x'])
, testProperty "ordering 2 of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs [x', z', w', y'])
, testProperty "duplicated last addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ map postMsg [w, x, y, z]
in uniqueIds l ==>
idlist l === idlist (makeMsgs $ [last l] <> l)
, testProperty "duplicated natural ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ map postMsg [w, x, y, z]
in idlist l === idlist (makeMsgs $ l <> l)
, testProperty "duplicated reverse ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ map postMsg [w, x, y, z]
in idlist l === idlist (makeMsgs $ reverse l <> l)
, testProperty "duplicated mirrored ordering of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ map postMsg [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs $ [y', z', w', x'] <> l)
, testProperty "duplicated ordering 1 of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ postMsg <$> [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs $ [y', w', z', x'] <> l)
, testProperty "duplicated ordering 2 of addMessage"
$ \(w, x, y, z) ->
let l = setDateOrderMessages $ postMsg <$> [w, x, y, z]
[w', x', y', z'] = l
in idlist l === idlist (makeMsgs $ [x', z', w', y'] <> l)
, testProperty "non-posted are not duplicate removed"
$ \(w, x, y, z) ->
let l = setDateOrderMessages [w, x, y, z]
[w', x', y', z'] = l
l' = [x', z', w', y']
ex = sortBy (\a b -> compare (a^.mDate) (b^.mDate))
([e | e <- l', isNothing (messagePostId e) ] <> l)
in idlist ex === idlist (makeMsgs $ l' <> l)
, testProperty "duplicate dates different IDs in posted order"
$ \(w, x, y, z) ->
let d = ServerTime $ UTCTime
(ModifiedJulianDay 1234)
(secondsToDiffTime 9876)
l = foldl (setTime d) [] $ postMsg <$> [w, x, y, z]
setTime t ml m = ml ++ [m {_mDate = t}]
[w', x', y', z'] = l
l' = [x', z', w', y']
ex = l
in uniqueIds l ==>
idlist ex === idlist (makeMsgs $ l' <> l)
]
movementTests :: TestTree
movementTests = testGroup "Movement"
[ moveUpTestEmpty
, moveUpTestSingle
, moveUpTestMultipleStart
, moveUpTestMultipleEnd
, moveUpTestMultipleSkipDeleted
, moveUpTestMultipleSkipDeletedAll
, moveDownTestEmpty
, moveDownTestMultipleStart
, moveDownTestSingle
, moveDownTestMultipleEnd
, moveDownTestMultipleSkipDeleted
, moveDownTestMultipleSkipDeletedAll
]
moveDownTestEmpty :: TestTree
moveDownTestEmpty = testProperty "Move up in empty messages" $
\x -> Nothing == getNextPostId x noMessages
moveUpTestEmpty :: TestTree
moveUpTestEmpty = testProperty "Move down in empty messages" $
\x -> Nothing == getPrevPostId x noMessages
moveDownTestSingle :: TestTree
moveDownTestSingle = testProperty "Move up from single message" $
\x -> let msgs = addMessage x noMessages
in Nothing == (getNextPostId (messagePostId x) msgs)
moveUpTestSingle :: TestTree
moveUpTestSingle = testProperty "Move down from single message" $
\x -> let msgs = addMessage x noMessages
in Nothing == (getPrevPostId (messagePostId x) msgs)
moveDownTestMultipleStart :: TestTree
moveDownTestMultipleStart =
testProperty "Move down in multiple messages from the start" $
\(x', y', z') ->
let [x, y, z] = setDateOrderMessages
[ postMsg x'
, postMsg y'
, postMsg z'
]
msgs = makeMsgs [x, y, z]
msgid = getNextMessageId (x^.mMessageId) msgs
idents = postids "xyz" msgs
info = idents <> " against " <> show msgid
in counterexample info $
y^.mMessageId == msgid
moveUpTestMultipleStart :: TestTree
moveUpTestMultipleStart =
testProperty "Move up in multiple messages from the start" $
\(x', y', z') ->
let [x, y, z] = setDateOrderMessages
[ postMsg x', postMsg y', postMsg z']
msgs = makeMsgs [x, y, z]
msgid = getPrevPostId (messagePostId x) msgs
idents = postids "xyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ Nothing == msgid
moveDownTestMultipleEnd :: TestTree
moveDownTestMultipleEnd =
testProperty "Move down in multiple messages from the end" $
\(x', y', z') ->
let [x, y, z] = setDateOrderMessages
[ postMsg x', postMsg y', postMsg z']
msgs = makeMsgs [x, y, z]
msgid = getNextPostId (messagePostId z) msgs
idents = postids "xyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ Nothing == msgid
moveUpTestMultipleEnd :: TestTree
moveUpTestMultipleEnd =
testProperty "Move up in multiple messages from the end" $
\(x', y', z') ->
let [x, y, z] = setDateOrderMessages
[ postMsg x', postMsg y', postMsg z']
msgs = makeMsgs [x, y, z]
msgid = getPrevPostId (messagePostId z) msgs
idents = postids "xyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ (messagePostId y) == msgid
moveDownTestMultipleSkipDeleted :: TestTree
moveDownTestMultipleSkipDeleted =
testProperty "Move down in multiple messages skipping deleteds" $
\(w', x', y', z') ->
let [w, x, y, z] = setDateOrderMessages
[ postMsg w'
, delMsg x'
, delMsg y'
, postMsg z']
msgs = makeMsgs [w, x, y, z]
msgid = getNextPostId (messagePostId w) msgs
idents = postids "wxyz" msgs
info = idents <> " against " <> show msgid
in counterexample info $ (messagePostId z) == msgid
moveUpTestMultipleSkipDeleted :: TestTree
moveUpTestMultipleSkipDeleted =
testProperty "Move one up in multiple messages skipping deleteds" $
\(w', x', y', z') ->
let [w, x, y, z] = setDateOrderMessages
[ postMsg w'
, delMsg x'
, delMsg y'
, postMsg z']
msgs = makeMsgs [w, x, y, z]
msgid = getPrevPostId (messagePostId z) msgs
idents = postids "wxyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ (messagePostId w) == msgid
moveDownTestMultipleSkipDeletedAll :: TestTree
moveDownTestMultipleSkipDeletedAll =
testProperty "Move one down in multiple deleted messages skipping deleteds" $
\(w', x', y', z') ->
let [w, x, y, z] = setDateOrderMessages
[ delMsg w'
, delMsg x'
, delMsg y'
, delMsg z']
msgs = makeMsgs [w, x, y, z]
msgid = getNextPostId (messagePostId w) msgs
idents = postids "wxyz" msgs
info = idents <> " against " <> show msgid
in counterexample info $ Nothing == msgid
moveUpTestMultipleSkipDeletedAll :: TestTree
moveUpTestMultipleSkipDeletedAll =
testProperty "Move one up in multiple deleted messages skipping deleteds" $
\(w', x', y', z') ->
let [w, x, y, z] = setDateOrderMessages
[ delMsg w'
, delMsg x'
, delMsg y'
, delMsg z']
msgs = makeMsgs [w, x, y, z]
msgid = getPrevPostId (messagePostId z) msgs
idents = postids "wxyz" msgs
info = idents <> " against " <> show msgid
in uniqueIds msgs ==>
counterexample info $ Nothing == msgid
reversalTests :: TestTree
reversalTests = testGroup "Reversal"
[ testProperty "round trip" $
\l -> let rr = unreverseMessages (reverseMessages l)
in idlist l === idlist rr
, testProperty "getLatestMessage finds same in either dir" $
KWQ : just one reverse , not two
in (messagePostId <$> getLatestPostMsg l) ===
(messagePostId <$> getLatestPostMsg rr)
, testCase "reverse nothing" $
(null $ unreverseMessages $ reverseMessages noMessages) @?
"reverse of empty Messages"
, testProperty "reverse order" $
\l -> let r = reverseMessages l
in idlist l === reverse (idlist r)
]
lookupTests :: TestTree
lookupTests = testGroup "Lookup"
[ testProperty "getEarliestPostMsg" $ \(m1, m2, m3, m4, m5) ->
let mlist = m1 : m2 : m3 : m4 : m5 : []
msgs = makeMsgs mlist
postIds = fmap messagePostId
$ sortBy (compare `on` (^.mDate))
$ filter (\m -> isJust (messagePostId m) && (not $ m^.mDeleted)) mlist
firstPostId = messagePostId <$> getEarliestPostMsg msgs
in if null postIds
then Nothing === firstPostId
else Just (head postIds) === firstPostId
, testProperty "getLatestPostMsg" $ \(m1, m2, m3, m4, m5) ->
let mlist = m1 : m2 : m3 : m4 : m5 : []
msgs = makeMsgs mlist
postIds = fmap messagePostId
$ sortBy (compare `on` (^.mDate))
$ filter (\m -> isJust (messagePostId m) && (not $ m^.mDeleted)) mlist
lastPostId = messagePostId <$> getLatestPostMsg msgs
in counterexample ("ids: " <> show (idlist msgs)
<> "\n dates: " <> (show $ fmap show $ foldr (\m l -> m^.mDate : l) [] msgs)
<> "\n deleted: " <> (show $ fmap show $ foldr (\m l -> m^.mDeleted : l) [] msgs)
<> "\n postIds:" <> show postIds) (
if null postIds
then Nothing === lastPostId
else Just (last postIds) === lastPostId)
, testProperty "findLatestUserMessage" $ \(m1, m2, m3, m4, m5) ->
let mlist = m1 : m2 : m3 : m4 : m5 : []
msgs = makeMsgs mlist
postIds = fmap messagePostId
$ sortBy (compare `on` (^.mDate))
$ filter (\m -> isJust (messagePostId m) && (not $ m^.mDeleted)) mlist
lastPostId = messagePostId <$> findLatestUserMessage (const True) msgs
firstPostId = messagePostId <$> findLatestUserMessage (\m -> messagePostId m == head postIds) msgs
in counterexample ("ids: " <> show (idlist msgs)
<> "\n dates: " <> (show $ fmap show $ foldr (\m l -> m^.mDate : l) [] msgs)
<> "\n deleted: " <> (show $ fmap show $ foldr (\m l -> m^.mDeleted : l) [] msgs)
<> "\n postIds:" <> show postIds) (
if null postIds
then Nothing === lastPostId
else Just (last postIds) === lastPostId .&&. Just (head postIds) === firstPostId)
]
splitTests :: TestTree
splitTests = testGroup "Split"
[ testCase "split nothing on empty" $
let (m, _) = splitDirSeqOn (const False) noMessages
in isNothing m @? "must be nothing"
, testProperty "split just on empty" $ \x ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == x) noMessages
in isNothing m
, testProperty "split nothing on list" $ \(x::Messages) ->
let (m, _) = splitDirSeqOn (const False) x
in isNothing m
, testProperty "split nothing on not found" $ \(w', x', y', z') ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
msgs = makeMsgs [x, y, z]
idents = postids "wxyz" msgs
info = idents <> " against " <> show (messagePostId (fromJust m))
in uniqueIds [w, x, y, z] ==>
counterexample info $ isNothing m
, testProperty "all before reversed on split nothing"
$ \(w, x, y, z) ->
let (_, (before, _)) = splitDirSeqOn (const False) msgs
msgs = makeMsgs inpl
inpl = setDateOrderMessages [w, x, y, z]
control = idlist (reverse inpl)
result = idlist before
info = show control <> " /= " <> show result
in counterexample info $ control == result
, testProperty "all before reversed on not found"
$ \(w', x', y', z') ->
let (_, (before, _)) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
in uniqueIds [w, x, y, z] ==>
idlist (reverse inpl) == idlist before
, testProperty "found at first position"
$ \(w', x', y', z') ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
in validIds inpl && uniqueIds inpl ==>
messagePostId w == messagePostId (fromJust m)
, testProperty "no before when found at first position"
$ \(w', x', y', z') ->
let (_, (before, _)) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist before)
in validIds inpl && uniqueIds inpl ==>
counterexample info $ null $ unreverseMessages before
, testProperty "remaining after when found at first position"
$ \(w', x', y', z') ->
let (_, (_, afterMsgs)) = splitDirSeqOn (\m2 -> m2^.mMessageId == w^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist afterMsgs)
in validIds inpl && uniqueIds inpl ==>
counterexample info $
idlist (tail inpl) == idlist afterMsgs
, testProperty "found at last position"
$ \(w', x', y', z') ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == z^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
in validIds inpl && uniqueIds inpl ==>
messagePostId z == messagePostId (fromJust m)
, testProperty "reversed before when found at last position"
$ \(w', x', y', z') ->
let (_, (before, _)) = splitDirSeqOn (\m2 -> m2^.mMessageId == z^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist before)
in validIds inpl && uniqueIds inpl ==>
counterexample info $
idlist (reverse $ init inpl) == idlist before
, testProperty "no after when found at last position"
$ \(w', x', y', z') ->
let (_, (_, afterMsgs)) = splitDirSeqOn (\m2 -> m2^.mMessageId == z^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [w, x, y, z]
[w, x, y, z] = setDateOrderMessages [w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist afterMsgs)
in validIds inpl && uniqueIds inpl ==>
counterexample info $ null afterMsgs
, testProperty "found at midpoint position"
$ \(v', w', x', y', z') ->
let (m, _) = splitDirSeqOn (\m2 -> m2^.mMessageId == x^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [v, w, x, y, z]
[v, w, x, y, z] = setDateOrderMessages
[v', w', x', y', z']
in validIds inpl && uniqueIds inpl ==>
messagePostId x == messagePostId (fromJust m)
, testProperty "reversed before when found at midpoint position"
$ \(v', w', x', y', z') ->
let (_, (before, _)) = splitDirSeqOn (\m2 -> m2^.mMessageId == x^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [v, w, x, y, z]
[v, w, x, y, z] = setDateOrderMessages
[v', w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist before)
in validIds inpl && uniqueIds inpl ==>
counterexample info $
idlist [w, v] == idlist before
, testProperty "after when found at midpoint position"
$ \(v', w', x', y', z') ->
let (_, (_, afterMsgs)) = splitDirSeqOn (\m2 -> m2^.mMessageId == x^.mMessageId) msgs
msgs = makeMsgs inpl
inpl = [v, w, x, y, z]
[v, w, x, y, z] = setDateOrderMessages
[v', w', x', y', z']
info = show (idlist inpl) <> " ==> " <> (show $ idlist afterMsgs)
in validIds inpl && uniqueIds inpl ==>
counterexample info $
idlist [y, z] == idlist afterMsgs
]
removeTests :: TestTree
removeTests = adjustOption (\(QuickCheckMaxRatio n) -> QuickCheckMaxRatio (n*10)) $
testGroup "Remove"
[ testProperty "remove on empty" $ \(id1, id2) ->
let (remaining, removed) = removeMatchesFromSubset (const True) id1 id2 noMessages
in counterexample "got something from nothing" $ null remaining && null removed
, testProperty "remove range not found (C9)" $ \(id1, id2, msglist) ->
let msgs = makeMsgs msglist
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) (Just id1) (Just id2) msgs
in (not $ Just id1 `elem` ids || Just id2 `elem` ids) ==>
counterexample "got something from invalid range" $
null removed && length remaining == length ids
, testProperty "remove first in range (C6)" $ \(id1, id2, msglist) ->
let msgs = makeMsgs msglist
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) (Just id1) (Just id2) msgs
in Just id1 `elem` ids && (not $ Just id2 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
" remove id1=" <> show id1 <>
" should be in " <> show (idlist removed) <>
" but not id2=" <> show id2 <>
" and remaining=" <> show (idlist remaining)) $
(not $ null removed) &&
(length remaining /= length ids) &&
Just id1 `elem` idlist removed &&
(not $ Just id1 `elem` idlist remaining)
, testProperty "remove nothing first in range" $ \(id1, id2, msglist) ->
let msgs = makeMsgs msglist
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const False) (Just id1) (Just id2) msgs
in Just id1 `elem` ids && (not $ Just id2 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
" remove id1=" <> show id1 <>
" should be in " <> show (idlist removed) <>
" but not id2=" <> show id2 <>
" and remaining=" <> show (idlist remaining)) $
(idlist remaining == ids && null removed)
, testCase "remove only as last" $
let (remaining, removed) = removeMatchesFromSubset (const True) (Just id1) (Just id2) msgs
id1 = MessagePostId $ fromId $ Id "id1"
id2 = MessagePostId $ fromId $ Id "id2"
msgs = makeMsgs [makeMsg (ServerTime originTime) (Just id2)]
in null remaining && length removed == 1 @? "removed"
, testProperty "remove last in range (C8)" $ \(idx2, msg, msglist) ->
let msgs = makeMsgs $ msg : msglist
ids = idlist msgs
id2 = ids !! idx2'
id1 = MessagePostId $ PI $ Id $ T.intercalate "-" $ map (unId . unPI) $
catMaybes ((\i -> i >>= messageIdPostId) <$> ids)
idx2' = abs idx2 `mod` length ids
(remaining, removed) = removeMatchesFromSubset (const True) (Just id1) id2 msgs
in (isJust id2) && uniqueIds msgs ==>
counterexample ("with idlist " <> show ids <>
" remove id2=" <> show id2 <>
" should be in " <> show (idlist removed) <>
" but not id1=" <> show id1 <>
" and remaining=" <> show (idlist remaining)
) $
(not $ null removed) &&
(length remaining /= length ids) &&
id2 `elem` idlist removed &&
(not $ id2 `elem` idlist remaining)
, testProperty "remove sub range (C5)" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', postIds) = splitAt (idx2' + 1) ids
(preIds, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
(remaining, removed) = removeMatchesFromSubset (const True) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining) <>
"\n from " <> show preIds <> " and " <> show postIds
) $
(idlist remaining == (preIds <> postIds) &&
idlist removed == matchIds)
, testProperty "remove nothing sub range" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', postIds) = splitAt (idx2' + 1) ids
(preIds, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
(remaining, removed) = removeMatchesFromSubset (const False) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining) <>
"\n from " <> show preIds <> " and " <> show postIds
) $
(idlist remaining == ids && null removed)
, testProperty "remove first in sub range (C5)" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', _) = splitAt (idx2' + 1) ids
(_, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
(remaining, removed) = removeMatchesFromSubset (\m -> m^.mMessageId == id1) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == (filter (/= id1) ids) &&
idlist removed == [id1])
, testProperty "remove last in sub range (C5)" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', _) = splitAt (idx2' + 1) ids
(_, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
(remaining, removed) = removeMatchesFromSubset (\m -> m^.mMessageId == id2) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == (filter (/= id2) ids) &&
idlist removed == [id2])
, testProperty "remove some in sub range (C5)" $ \(m1, m2, m3, m4, m5, idx1, idx2) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(ids', _) = splitAt (idx2' + 1) ids
(_, matchIds) = splitAt idx1' ids'
id1 = head matchIds
id2 = last matchIds
idxl = sort $ map (\v -> abs v `mod` 5) [idx1, idx2]
idx1' = head idxl
idx2' = last idxl
rmvIds = map snd $ filter (odd . fst) $ zip [(0::Int)..] matchIds
(remaining, removed) = removeMatchesFromSubset (\m -> m^.mMessageId `elem` rmvIds) id1 id2 msgs
in uniqueIds msgs && isJust id1 && isJust id2 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n idx2=" <> show idx2' <>
"\n matching=" <> show matchIds <>
"\n removing=" <> show rmvIds <>
"\n extracts=" <> show (idlist removed) <>
"\n and leaves remaining=" <> show (idlist remaining) <>
"\n from " <> show (filter (not . flip elem rmvIds) ids)
) $
(idlist remaining == (filter (not . flip elem rmvIds) ids) &&
idlist removed == rmvIds)
, testProperty "remove from start last Nothing (C4)" $ \(m1, m2, m3, m4, m5, idx1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(leftIds, matchIds) = splitAt idx1' ids
id1 = head matchIds
idx1' = abs idx1 `mod` 5
(remaining, removed) = removeMatchesFromSubset (const True) id1 Nothing msgs
in uniqueIds msgs && isJust id1 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == leftIds &&
idlist removed == matchIds)
, testProperty "remove from Nothing to offset (C2)" $ \(m1, m2, m3, m4, m5, idx1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(matchIds, leftIds) = splitAt (idx1' + 1) ids
id1 = last matchIds
idx1' = abs idx1 `mod` 4
(remaining, removed) = removeMatchesFromSubset (const True) Nothing id1 msgs
in uniqueIds msgs && isJust id1 ==>
counterexample ("with idlist " <> show (idlist msgs) <>
"\n idx1=" <> show idx1' <>
"\n extracts=" <> show (idlist removed) <>
"\n matching=" <> show matchIds <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == leftIds &&
idlist removed == matchIds)
, testProperty "remove from start not found last Nothing (C7)" $ \(m1, m2, m3, m4, m5, id1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) id1 Nothing msgs
in uniqueIds msgs && isJust id1 && (not $ id1 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
"\n extracts=" <> show (idlist removed) <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == ids &&
null removed)
, testProperty "remove from Nothing to end not found (C3)" $ \(m1, m2, m3, m4, m5, id1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) Nothing id1 msgs
in uniqueIds msgs && isJust id1 && (not $ id1 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
"\n extracts=" <> show (idlist removed) <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist remaining == ids &&
null removed)
, testProperty "remove from Nothing to Nothing (C1)" $ \(m1, m2, m3, m4, m5, id1) ->
let msgs = makeMsgs $ m1 : m2 : m3 : m4 : m5 : []
ids = idlist msgs
(remaining, removed) = removeMatchesFromSubset (const True) Nothing Nothing msgs
in uniqueIds msgs && isJust id1 && (not $ id1 `elem` ids) ==>
counterexample ("with idlist " <> show ids <>
"\n extracts=" <> show (idlist removed) <>
"\n and leaves remaining=" <> show (idlist remaining)
) $
(idlist removed == ids &&
null remaining)
]
monoid' :: (Show t, Arbitrary t, EqProp t) => t -> (t -> t -> t) -> TestBatch
monoid' mempty' mappend' =
( "monoid"
, [ ("left identity", leftId mappend' mempty')
, ("right identity", rightId mappend' mempty')
, ("associativity" , isAssoc mappend')
]
)
instanceTests :: TestTree
instanceTests = testGroup "Messages Instances"
$ map tastyBatch
[ (monoid' (emptyDirSeq :: Messages) appendDirSeq)
, (monoid' (emptyDirSeq :: RetrogradeMessages) appendDirSeq)
]
instance EqProp Messages where
a =-= b = idlist a =-= idlist b
instance EqProp RetrogradeMessages where
a =-= b = idlist a =-= idlist b
instance EqProp PostId where
a =-= b = (show $ idString a) =-= (show $ idString b)
instance EqProp MessageId where
(MessagePostId a) =-= (MessagePostId b) = (show $ idString a) =-= (show $ idString b)
(MessageUUID a) =-= (MessageUUID b) = (show a) =-= (show b)
_ =-= _ = eq True False
|
5da334b1fe3e5bca71ae40537424475434911f9597fb24833ba9179c905020da | mneedham/ranking-algorithms | ranking.clj | (ns ranking-algorithms.ranking
(:require [clojure.math.numeric-tower :as math]))
(defn initial-rankings [teams]
(apply array-map (mapcat (fn [x] [x {:points 1200.00}]) teams)))
(defn expected [my-ranking opponent-ranking]
(/ 1.0
(+ 1
(math/expt 10 (/ (- opponent-ranking my-ranking) 400)))))
(defn ranking-after-game
[{ ranking :ranking
opponent-ranking :opponent-ranking
importance :importance
score :score}]
(+ ranking
(* importance
(- score (expected ranking opponent-ranking) ))))
(defn ranking-after-loss [args]
(ranking-after-game (merge args {:score 0})))
(defn ranking-after-win [args]
(ranking-after-game (merge args {:score 1})))
(defn ranking-after-draw [args]
(ranking-after-game (merge args {:score 0.5})))
(def round-value
{"First qualifying round" 2
"Second qualifying round" 3
"Third qualifying round" 5
"Play-offs" 7
"Group stage" 12
"Round of 16" 15
"Quarter-finals" 18
"Semi-finals" 25
"Final" 32 })
(defn process-match [ts match]
(let [{:keys [home away home_score away_score round]} match]
(cond
(> home_score away_score)
(-> ts
(update-in [home :points] #(ranking-after-win {:ranking %
:opponent-ranking (:points (get ts away))
:importance (get round-value round 32)}))
(update-in [away :points] #(ranking-after-loss {:ranking %
:opponent-ranking (:points (get ts home))
:importance (get round-value round 32)})))
(> away_score home_score)
(-> ts
(update-in [home :points] #(ranking-after-loss {:ranking %
:opponent-ranking (:points (get ts away))
:importance (get round-value round 32)}))
(update-in [away :points] #(ranking-after-win {:ranking %
:opponent-ranking (:points (get ts home))
:importance (get round-value round 32)})))
(= home_score away_score)
(-> ts
(update-in [home :points] #(ranking-after-draw {:ranking %
:opponent-ranking (:points (get ts away))
:importance (get round-value round 32)}))
(update-in [away :points] #(ranking-after-draw {:ranking %
:opponent-ranking (:points (get ts home))
:importance (get round-value round 32)}))))))
(comment (def round-value
{"First Qualifying Round" 4
"Second qualifying round" 6
"Third qualifying round" 8
"First group-match stage" 12
"Second group-match stage" 15
"Quarter Finals" 18
"Semi-finals" 25
"Final" 32}))
| null | https://raw.githubusercontent.com/mneedham/ranking-algorithms/30d300170f60f24663c3d377ce68565427a42cb4/src/ranking_algorithms/ranking.clj | clojure | (ns ranking-algorithms.ranking
(:require [clojure.math.numeric-tower :as math]))
(defn initial-rankings [teams]
(apply array-map (mapcat (fn [x] [x {:points 1200.00}]) teams)))
(defn expected [my-ranking opponent-ranking]
(/ 1.0
(+ 1
(math/expt 10 (/ (- opponent-ranking my-ranking) 400)))))
(defn ranking-after-game
[{ ranking :ranking
opponent-ranking :opponent-ranking
importance :importance
score :score}]
(+ ranking
(* importance
(- score (expected ranking opponent-ranking) ))))
(defn ranking-after-loss [args]
(ranking-after-game (merge args {:score 0})))
(defn ranking-after-win [args]
(ranking-after-game (merge args {:score 1})))
(defn ranking-after-draw [args]
(ranking-after-game (merge args {:score 0.5})))
(def round-value
{"First qualifying round" 2
"Second qualifying round" 3
"Third qualifying round" 5
"Play-offs" 7
"Group stage" 12
"Round of 16" 15
"Quarter-finals" 18
"Semi-finals" 25
"Final" 32 })
(defn process-match [ts match]
(let [{:keys [home away home_score away_score round]} match]
(cond
(> home_score away_score)
(-> ts
(update-in [home :points] #(ranking-after-win {:ranking %
:opponent-ranking (:points (get ts away))
:importance (get round-value round 32)}))
(update-in [away :points] #(ranking-after-loss {:ranking %
:opponent-ranking (:points (get ts home))
:importance (get round-value round 32)})))
(> away_score home_score)
(-> ts
(update-in [home :points] #(ranking-after-loss {:ranking %
:opponent-ranking (:points (get ts away))
:importance (get round-value round 32)}))
(update-in [away :points] #(ranking-after-win {:ranking %
:opponent-ranking (:points (get ts home))
:importance (get round-value round 32)})))
(= home_score away_score)
(-> ts
(update-in [home :points] #(ranking-after-draw {:ranking %
:opponent-ranking (:points (get ts away))
:importance (get round-value round 32)}))
(update-in [away :points] #(ranking-after-draw {:ranking %
:opponent-ranking (:points (get ts home))
:importance (get round-value round 32)}))))))
(comment (def round-value
{"First Qualifying Round" 4
"Second qualifying round" 6
"Third qualifying round" 8
"First group-match stage" 12
"Second group-match stage" 15
"Quarter Finals" 18
"Semi-finals" 25
"Final" 32}))
| |
7dd291687cf026ab4afb51971dfb3992774f1e3fa22f092bfae63467177dc717 | hipsleek/hipsleek | ccl.mli |
*
* 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,
* Jeremy Condit <>
* George C. Necula <>
* 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.
*
*)
val verifiedExps: Cil.exp list ref
val verifiedArgs: Cil.exp list ref
val feature: Cil.featureDescr
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/cil/src/ext/ccl.mli | ocaml |
*
* 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,
* Jeremy Condit <>
* George C. Necula <>
* 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.
*
*)
val verifiedExps: Cil.exp list ref
val verifiedArgs: Cil.exp list ref
val feature: Cil.featureDescr
| |
ec4b5d1ea108b1a9a505c1bad01c380ff066da004973f55c992baf3ef5d41a33 | quernd/tea-chess | Nag.ml | exception Nag_error of string
type t = int
let pgn_of_nag = fun nag ->
Printf.sprintf "$%i" nag
let nag_of_string = function
| "!" -> 1
| "?" -> 2
| "!!" -> 3
| "??" -> 4
| "!?" -> 5
| "?!" -> 6
| a -> raise (Nag_error a)
let string_of_nag = function
| 0 -> ""
| 1 -> "!"
| 2 -> "?"
| 3 -> "!!" (* alternative: {js|\u203c|js} *)
| 4 -> "??" (* alternative: {js|\u2047|js} *)
| 5 -> "!?" (* alternative: {js|\u2049|js} *)
alternative : { }
| 7 -> {js|\u25a1|js} (* forced move *)
8 , 9
drawish position or even
11 , 12
| 13 -> {js|\u221e|js} (* unclear position *)
| 14 -> {js|\u2a72|js} (* White has a slight advantage *)
| 15 -> {js|\u2a71|js} (* Black has a slight advantage *)
| 16 -> {js|\u00b1|js} (* White has a moderate advantage *)
| 17 -> {js|\u2213|js} (* Black has a moderate advantage *)
| 18 -> "+-" (* White has a decisive advantage *)
| 19 -> "-+" (* Black has a decisive advantage *)
20 , 21
| 22 | 23 -> {js|\u2a00|js} (* zugzwang *)
24 - 31
| 32 | 33 -> {js|\u27f3|js} (* development advantage *)
34 , 35
| 36 | 37 -> {js|\u2192|js} (* initiative *)
38 , 39
| 40 | 41 -> {js|\u2191|js} (* attack *)
42 - 131
| 132 | 133 -> {js|\u21c6|js} (* counterplay *)
134 - 137
| 138 | 139 -> {js|\u2a01|js} (* zeitnot *)
| _ -> ""
| null | https://raw.githubusercontent.com/quernd/tea-chess/7dc929f406eeada5a72117b1c748fa0edda4c48c/src/Nag.ml | ocaml | alternative: {js|\u203c|js}
alternative: {js|\u2047|js}
alternative: {js|\u2049|js}
forced move
unclear position
White has a slight advantage
Black has a slight advantage
White has a moderate advantage
Black has a moderate advantage
White has a decisive advantage
Black has a decisive advantage
zugzwang
development advantage
initiative
attack
counterplay
zeitnot | exception Nag_error of string
type t = int
let pgn_of_nag = fun nag ->
Printf.sprintf "$%i" nag
let nag_of_string = function
| "!" -> 1
| "?" -> 2
| "!!" -> 3
| "??" -> 4
| "!?" -> 5
| "?!" -> 6
| a -> raise (Nag_error a)
let string_of_nag = function
| 0 -> ""
| 1 -> "!"
| 2 -> "?"
alternative : { }
8 , 9
drawish position or even
11 , 12
20 , 21
24 - 31
34 , 35
38 , 39
42 - 131
134 - 137
| _ -> ""
|
8fbe97404ebf9f27d334c7c077c4dd6f22bf25d97e7b9ce70d47552cb180a60a | codereport/SICP-2020 | conor_hoekstra_solutions.rkt | Exercise 3.12 ( page 345 - 6 )
Response from ) after append
'(b)
Response from ) after append !
'(b c d) ; equivalent of passing something by reference and then modifying
Exercise 3.14 ( page 347 )
;; mystery reverses a list
Exercise 3.16 ( 350 - 1 )
- > 3
(define x (cons 1 '()))
(define y (cons x x))
(define z (cons y '()))
- > 4
(define x (cons 1 '()))
(define y (cons x x))
(define z (cons y y))
- > 7
;; for box and pointer diagrams, see conor_hoekstra_solutions.md
Exercise 3.17 ( page 351 )
(define seen '())
(define (count-pairs x)
(if (not (pair? x))
0
(+ (count-pairs (car x))
(count-pairs (cdr x))
(if (memq x seen)
0
(begin (set! seen (cons x seen)) 1)))))
(require rackunit)
(check-equal? (count-pairs '(1 2 3)) 3)
(define x (cons 1 '()))
(define y (cons x x))
(define z (cons y '()))
(check-equal? (count-pairs z) 3)
(set! seen '())
(define a (cons 1 '()))
(define b (cons a a))
(define c (cons b b))
(check-equal? (count-pairs c) 3)
from book ( note use # sicp -- aka MIT Scheme -- for set - car!/set - cdr ! ; Racket and Scheme do n't have it )
(define (front-ptr queue) (car queue))
(define (rear-ptr queue) (cdr queue))
(define (set-front-ptr! queue item) (set-car! queue item))
(define (set-rear-ptr! queue item) (set-cdr! queue item))
(define (make-queue) (cons '() '()))
(define (empty-queue? queue) (null? (front-ptr queue)))
(define (front-queue queue)
(if (empty-queue? queue)
(error "FRONT called with an empty queue" queue)
(car (front-ptr queue))))
(define (insert-queue! queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue)
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
queue))))
(define (delete-queue! queue)
(cond ((empty-queue? queue)
(error "DELETE! called with an empty queue" queue))
(else (set-front-ptr! queue (cdr (front-ptr queue)))
queue)))
Exercise 3.21 ( page 359 )
(define q1 (make-queue))
(insert-queue! q1 'a) ;((a) a)
(insert-queue! q1 'b) ;((a b) b)
(insert-queue! q1 'c) ;((a b c) c)
(delete-queue! q1) ;((b c) c)
(delete-queue! q1) ;((c) c)
;; front-ptr essentially grows as a list to represent the queue, back-ptr is
;; just for inserting. print should just print front-ptr
(define (print-queue queue) (front-ptr queue))
;; then just update insert and delete
(define (insert-queue! queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
(print-queue queue))
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
(print-queue queue)))))
(define (delete-queue! queue)
(cond ((empty-queue? queue)
(error "DELETE! called with an empty queue" queue))
(else (set-front-ptr! queue (cdr (front-ptr queue)))
(print-queue queue))))
Exercise 3.23 ( page 360 ) this is an incorrect solution as I did n't use a doubly - linked list
;; meaning that the big-O of pop-back-deque is O(n)
(define (front-ptr deque) (car deque))
(define (rear-ptr deque) (cdr deque))
(define (set-front-ptr! deque item) (set-car! deque item))
(define (set-rear-ptr! deque item) (set-cdr! deque item))
(define (make-deque) (cons '() '()))
(define (empty-deque? deque) (null? (front-ptr deque)))
(define (front-deque deque)
(if (empty-deque? deque)
(error "FRONT called with an empty deque" deque)
(car (front-ptr deque))))
(define (back-deque deque)
(if (empty-deque? deque)
(error "BACK called with an empty deque" deque)
(car (rear-ptr deque))))
(define (print-deque deque)
(if (empty-deque? deque)
"EMPTY"
(front-ptr deque)))
(define (push-back-deque! deque item)
(let ((new-pair (cons item '())))
(cond ((empty-deque? deque)
(set-front-ptr! deque new-pair)
(set-rear-ptr! deque new-pair)
(print-deque deque))
(else
(set-cdr! (rear-ptr deque) new-pair)
(set-rear-ptr! deque new-pair)
(print-deque deque)))))
(define (push-front-deque! deque item)
(let ((new-pair (cons item '())))
(cond ((empty-deque? deque)
(set-front-ptr! deque new-pair)
(set-rear-ptr! deque new-pair)
(print-deque deque))
(else
(set-cdr! new-pair (front-ptr deque))
(set-front-ptr! deque new-pair)
(print-deque deque)))))
(define (pop-front-deque! deque)
(cond ((empty-deque? deque)
(error "POP-FRONT! called with an empty deque" deque))
(else (set-front-ptr! deque (cdr (front-ptr deque)))
(print-deque deque))))
(define (get-second-last-pair lst)
(if (null? (cdr (cdr lst)))
lst
(get-second-last-pair (cdr lst))))
(define (pop-back-deque! deque)
(cond ((empty-deque? deque)
(error "POP-BACK! called with an empty deque" deque))
((= (length (front-ptr deque)) 1) (set! deque (cons '() '()))
(print-deque deque))
(else (set-rear-ptr! deque (get-second-last-pair (front-ptr deque)))
(set-cdr! (get-second-last-pair (front-ptr deque)) '())
(print-deque deque))))
(define q (make-deque))
(push-back-deque! q 'a) ; (a)
(push-back-deque! q 'b) ; (a b)
(push-back-deque! q 'c) ; (a b c)
(front-deque q) ; 'a
(back-deque q) ; 'c
(pop-front-deque! q) ; (b c)
(pop-front-deque! q) ; (c)
(push-front-deque! q 'a) ; (a c)
(push-front-deque! q 'b) ; (b a c)
(pop-back-deque! q) ; (b a)
(pop-back-deque! q) ; (b)
(pop-back-deque! q) ; ()
(push-back-deque! q 'a) ; (b a) <- fails
;; 1D Table from book
(define (lookup key table)
(let ((record (assoc key (cdr table))))
(if record
(cdr record)
false)))
(define (assoc key records)
(cond ((null? records) false)
((equal? key (caar records)) (car records))
(else (assoc key (cdr records)))))
(define (insert! key value table)
(let ((record (assoc key (cdr table))))
(if record
(set-cdr! record value)
(set-cdr! table
(cons (cons key value)
(cdr table)))))
'ok)
(define (make-table)
(list '*table*))
(define t (make-table))
(insert! 'a 1 t) ; ok
(insert! 'b 2 t) ; ok
(insert! 'c 3 t) ; ok
(insert! 'd 4 t) ; ok
( * table * ( d . 4 ) ( c . 3 ) ( b . 2 ) ( a . 1 ) )
;; 2D Table from book (non-message passing style)
(define (lookup key-1 key-2 table)
(let ((subtable
(assoc key-1 (cdr table))))
(if subtable
(let ((record
(assoc key-2 (cdr subtable))))
(if record
(cdr record)
false))
false)))
(define (insert! key-1 key-2 value table)
(let ((subtable (assoc key-1 (cdr table))))
(if subtable
(let ((record (assoc key-2 (cdr subtable))))
(if record
(set-cdr! record value)
(set-cdr! subtable
(cons (cons key-2 value)
(cdr subtable)))))
(set-cdr! table
(cons (list key-1
(cons key-2 value))
(cdr table)))))
'ok)
(define (make-table)
(list '*table*))
(define t (make-table))
(insert! 'a 'a 1 t) ; ok
(insert! 'a 'b 2 t) ; ok
(lookup 'a '1 t) ; #f
1
;; 2D Table from book (message passing style)
(define (make-table)
(let ((local-table (list '*table*)))
(define (lookup key-1 key-2)
(let ((subtable
(assoc key-1 (cdr local-table))))
(if subtable
(let ((record
(assoc key-2 (cdr subtable))))
(if record (cdr record) false))
false)))
(define (insert! key-1 key-2 value)
(let ((subtable
(assoc key-1 (cdr local-table))))
(if subtable
(let ((record
(assoc key-2 (cdr subtable))))
(if record
(set-cdr! record value)
(set-cdr! subtable
(cons (cons key-2 value)
(cdr subtable)))))
(set-cdr! local-table
(cons (list key-1 (cons key-2 value))
(cdr local-table)))))
'ok)
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation: TABLE" m))))
dispatch))
(define t (make-table))
((t 'insert-proc!) 'a 'a 1) ; ok
((t 'insert-proc!) 'a 'b 2) ; ok
((t 'lookup-proc) 'a '1) ; #f
1
Exercise 3.25 ( page 367 )
(define (lookup keys table)
(let ((record (assoc keys (cdr table))))
(if record
(cdr record)
false)))
(define (insert! keys value table)
(let ((record (assoc keys (cdr table))))
(if record
(set-cdr! record value)
(set-cdr! table
(cons (cons keys value)
(cdr table)))))
'ok)
(define (make-table)
(list '*table*))
(define t (make-table))
(insert! '(a b c) 1 t) ; ok
(insert! '(a b) 2 t) ; ok
(lookup '(a 1) t) ; #f
2
| null | https://raw.githubusercontent.com/codereport/SICP-2020/2d1e60048db89678830d93fcc558a846b7f57b76/Chapter%203.3%20Solutions/conor_hoekstra_solutions.rkt | racket | equivalent of passing something by reference and then modifying
mystery reverses a list
for box and pointer diagrams, see conor_hoekstra_solutions.md
Racket and Scheme do n't have it )
((a) a)
((a b) b)
((a b c) c)
((b c) c)
((c) c)
front-ptr essentially grows as a list to represent the queue, back-ptr is
just for inserting. print should just print front-ptr
then just update insert and delete
meaning that the big-O of pop-back-deque is O(n)
(a)
(a b)
(a b c)
'a
'c
(b c)
(c)
(a c)
(b a c)
(b a)
(b)
()
(b a) <- fails
1D Table from book
ok
ok
ok
ok
2D Table from book (non-message passing style)
ok
ok
#f
2D Table from book (message passing style)
ok
ok
#f
ok
ok
#f | Exercise 3.12 ( page 345 - 6 )
Response from ) after append
'(b)
Response from ) after append !
Exercise 3.14 ( page 347 )
Exercise 3.16 ( 350 - 1 )
- > 3
(define x (cons 1 '()))
(define y (cons x x))
(define z (cons y '()))
- > 4
(define x (cons 1 '()))
(define y (cons x x))
(define z (cons y y))
- > 7
Exercise 3.17 ( page 351 )
(define seen '())
(define (count-pairs x)
(if (not (pair? x))
0
(+ (count-pairs (car x))
(count-pairs (cdr x))
(if (memq x seen)
0
(begin (set! seen (cons x seen)) 1)))))
(require rackunit)
(check-equal? (count-pairs '(1 2 3)) 3)
(define x (cons 1 '()))
(define y (cons x x))
(define z (cons y '()))
(check-equal? (count-pairs z) 3)
(set! seen '())
(define a (cons 1 '()))
(define b (cons a a))
(define c (cons b b))
(check-equal? (count-pairs c) 3)
(define (front-ptr queue) (car queue))
(define (rear-ptr queue) (cdr queue))
(define (set-front-ptr! queue item) (set-car! queue item))
(define (set-rear-ptr! queue item) (set-cdr! queue item))
(define (make-queue) (cons '() '()))
(define (empty-queue? queue) (null? (front-ptr queue)))
(define (front-queue queue)
(if (empty-queue? queue)
(error "FRONT called with an empty queue" queue)
(car (front-ptr queue))))
(define (insert-queue! queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue)
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
queue))))
(define (delete-queue! queue)
(cond ((empty-queue? queue)
(error "DELETE! called with an empty queue" queue))
(else (set-front-ptr! queue (cdr (front-ptr queue)))
queue)))
Exercise 3.21 ( page 359 )
(define q1 (make-queue))
(define (print-queue queue) (front-ptr queue))
(define (insert-queue! queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
(print-queue queue))
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
(print-queue queue)))))
(define (delete-queue! queue)
(cond ((empty-queue? queue)
(error "DELETE! called with an empty queue" queue))
(else (set-front-ptr! queue (cdr (front-ptr queue)))
(print-queue queue))))
Exercise 3.23 ( page 360 ) this is an incorrect solution as I did n't use a doubly - linked list
(define (front-ptr deque) (car deque))
(define (rear-ptr deque) (cdr deque))
(define (set-front-ptr! deque item) (set-car! deque item))
(define (set-rear-ptr! deque item) (set-cdr! deque item))
(define (make-deque) (cons '() '()))
(define (empty-deque? deque) (null? (front-ptr deque)))
(define (front-deque deque)
(if (empty-deque? deque)
(error "FRONT called with an empty deque" deque)
(car (front-ptr deque))))
(define (back-deque deque)
(if (empty-deque? deque)
(error "BACK called with an empty deque" deque)
(car (rear-ptr deque))))
(define (print-deque deque)
(if (empty-deque? deque)
"EMPTY"
(front-ptr deque)))
(define (push-back-deque! deque item)
(let ((new-pair (cons item '())))
(cond ((empty-deque? deque)
(set-front-ptr! deque new-pair)
(set-rear-ptr! deque new-pair)
(print-deque deque))
(else
(set-cdr! (rear-ptr deque) new-pair)
(set-rear-ptr! deque new-pair)
(print-deque deque)))))
(define (push-front-deque! deque item)
(let ((new-pair (cons item '())))
(cond ((empty-deque? deque)
(set-front-ptr! deque new-pair)
(set-rear-ptr! deque new-pair)
(print-deque deque))
(else
(set-cdr! new-pair (front-ptr deque))
(set-front-ptr! deque new-pair)
(print-deque deque)))))
(define (pop-front-deque! deque)
(cond ((empty-deque? deque)
(error "POP-FRONT! called with an empty deque" deque))
(else (set-front-ptr! deque (cdr (front-ptr deque)))
(print-deque deque))))
(define (get-second-last-pair lst)
(if (null? (cdr (cdr lst)))
lst
(get-second-last-pair (cdr lst))))
(define (pop-back-deque! deque)
(cond ((empty-deque? deque)
(error "POP-BACK! called with an empty deque" deque))
((= (length (front-ptr deque)) 1) (set! deque (cons '() '()))
(print-deque deque))
(else (set-rear-ptr! deque (get-second-last-pair (front-ptr deque)))
(set-cdr! (get-second-last-pair (front-ptr deque)) '())
(print-deque deque))))
(define q (make-deque))
(define (lookup key table)
(let ((record (assoc key (cdr table))))
(if record
(cdr record)
false)))
(define (assoc key records)
(cond ((null? records) false)
((equal? key (caar records)) (car records))
(else (assoc key (cdr records)))))
(define (insert! key value table)
(let ((record (assoc key (cdr table))))
(if record
(set-cdr! record value)
(set-cdr! table
(cons (cons key value)
(cdr table)))))
'ok)
(define (make-table)
(list '*table*))
(define t (make-table))
( * table * ( d . 4 ) ( c . 3 ) ( b . 2 ) ( a . 1 ) )
(define (lookup key-1 key-2 table)
(let ((subtable
(assoc key-1 (cdr table))))
(if subtable
(let ((record
(assoc key-2 (cdr subtable))))
(if record
(cdr record)
false))
false)))
(define (insert! key-1 key-2 value table)
(let ((subtable (assoc key-1 (cdr table))))
(if subtable
(let ((record (assoc key-2 (cdr subtable))))
(if record
(set-cdr! record value)
(set-cdr! subtable
(cons (cons key-2 value)
(cdr subtable)))))
(set-cdr! table
(cons (list key-1
(cons key-2 value))
(cdr table)))))
'ok)
(define (make-table)
(list '*table*))
(define t (make-table))
1
(define (make-table)
(let ((local-table (list '*table*)))
(define (lookup key-1 key-2)
(let ((subtable
(assoc key-1 (cdr local-table))))
(if subtable
(let ((record
(assoc key-2 (cdr subtable))))
(if record (cdr record) false))
false)))
(define (insert! key-1 key-2 value)
(let ((subtable
(assoc key-1 (cdr local-table))))
(if subtable
(let ((record
(assoc key-2 (cdr subtable))))
(if record
(set-cdr! record value)
(set-cdr! subtable
(cons (cons key-2 value)
(cdr subtable)))))
(set-cdr! local-table
(cons (list key-1 (cons key-2 value))
(cdr local-table)))))
'ok)
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation: TABLE" m))))
dispatch))
(define t (make-table))
1
Exercise 3.25 ( page 367 )
(define (lookup keys table)
(let ((record (assoc keys (cdr table))))
(if record
(cdr record)
false)))
(define (insert! keys value table)
(let ((record (assoc keys (cdr table))))
(if record
(set-cdr! record value)
(set-cdr! table
(cons (cons keys value)
(cdr table)))))
'ok)
(define (make-table)
(list '*table*))
(define t (make-table))
2
|
698ebd35bc428f7366722acd368987121d81dee0c625afbae753bddddf8675a1 | richhickey/clojure-contrib | test_util.clj | Copyright ( c ) . All rights reserved . The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; test-util.clj
;;
A Clojure implementation of Datalog -- Utilities Tests
;;
straszheimjeffrey ( gmail )
Created 11 Feburary 2009
(ns clojure.contrib.datalog.tests.test-util
(:use clojure.test
clojure.contrib.datalog.util)
(:use [clojure.contrib.except :only (throwf)]))
(deftest test-is-var?
(is (is-var? '?x))
(is (is-var? '?))
(is (not (is-var? '??x)))
(is (not (is-var? '??)))
(is (not (is-var? 'x)))
(is (not (is-var? "fred")))
(is (not (is-var? :q))))
(deftest test-map-values
(let [map {:fred 1 :sally 2}]
(is (= (map-values #(* 2 %) map) {:fred 2 :sally 4}))
(is (= (map-values identity {}) {}))))
(deftest test-keys-to-vals
(let [map {:fred 1 :sally 2 :joey 3}]
(is (= (set (keys-to-vals map [:fred :sally])) #{1 2}))
(is (= (set (keys-to-vals map [:fred :sally :becky])) #{1 2}))
(is (empty? (keys-to-vals map [])))
(is (empty? (keys-to-vals {} [:fred])))))
(deftest test-reverse-map
(let [map {:fred 1 :sally 2 :joey 3}
map-1 (assoc map :mary 3)]
(is (= (reverse-map map) {1 :fred 2 :sally 3 :joey}))
(is (or (= (reverse-map map-1) {1 :fred 2 :sally 3 :joey})
(= (reverse-map map-1) {1 :fred 2 :sally 3 :mary})))))
(def some-maps
[
{ :a 1 :b 2 }
{ :c 3 :b 3 }
{ :d 4 :a 1 }
{ :g 4 :b 4 }
{ :a 2 :b 1 }
{ :e 1 :f 1 }
])
(def reduced (preduce + some-maps))
(def merged (apply merge-with + some-maps))
(deftest test-preduce
(is (= reduced merged)))
(comment
(run-tests)
)
; End of file
| null | https://raw.githubusercontent.com/richhickey/clojure-contrib/40b960bba41ba02811ef0e2c632d721eb199649f/src/test/clojure/clojure/contrib/datalog/tests/test_util.clj | clojure | distribution terms for this software are covered by the Eclipse Public
License 1.0 (-1.0.php) which can
be found in the file epl-v10.html at the root of this distribution. By
using this software in any fashion, you are agreeing to be bound by the
terms of this license. You must not remove this notice, or any other,
from this software.
test-util.clj
End of file | Copyright ( c ) . All rights reserved . The use and
A Clojure implementation of Datalog -- Utilities Tests
straszheimjeffrey ( gmail )
Created 11 Feburary 2009
(ns clojure.contrib.datalog.tests.test-util
(:use clojure.test
clojure.contrib.datalog.util)
(:use [clojure.contrib.except :only (throwf)]))
(deftest test-is-var?
(is (is-var? '?x))
(is (is-var? '?))
(is (not (is-var? '??x)))
(is (not (is-var? '??)))
(is (not (is-var? 'x)))
(is (not (is-var? "fred")))
(is (not (is-var? :q))))
(deftest test-map-values
(let [map {:fred 1 :sally 2}]
(is (= (map-values #(* 2 %) map) {:fred 2 :sally 4}))
(is (= (map-values identity {}) {}))))
(deftest test-keys-to-vals
(let [map {:fred 1 :sally 2 :joey 3}]
(is (= (set (keys-to-vals map [:fred :sally])) #{1 2}))
(is (= (set (keys-to-vals map [:fred :sally :becky])) #{1 2}))
(is (empty? (keys-to-vals map [])))
(is (empty? (keys-to-vals {} [:fred])))))
(deftest test-reverse-map
(let [map {:fred 1 :sally 2 :joey 3}
map-1 (assoc map :mary 3)]
(is (= (reverse-map map) {1 :fred 2 :sally 3 :joey}))
(is (or (= (reverse-map map-1) {1 :fred 2 :sally 3 :joey})
(= (reverse-map map-1) {1 :fred 2 :sally 3 :mary})))))
(def some-maps
[
{ :a 1 :b 2 }
{ :c 3 :b 3 }
{ :d 4 :a 1 }
{ :g 4 :b 4 }
{ :a 2 :b 1 }
{ :e 1 :f 1 }
])
(def reduced (preduce + some-maps))
(def merged (apply merge-with + some-maps))
(deftest test-preduce
(is (= reduced merged)))
(comment
(run-tests)
)
|
dd0f0efc1a8ad3e092a77e646e69d9c96fbc5b83ea8562fd8bb9aa190f90191e | triclops200/quickapp | argument-parsing.lisp | (in-package :quickapp)
(defmacro loop-rec (bindings &body body)
"Similar to the clojure loop macro"
(let ((names (mapcar #'car bindings))
(init-vals (mapcar #'cadr bindings)))
`(labels ((rec ,names
,@body))
(rec ,@init-vals))))
(defun reduce-full (f &rest args)
"A reducer that allows f to control the iteration as well as the
accumulator"
(if (= (length args) 1)
(reduce-full f (caar args) (cdar args))
(loop-rec ((acc (list (car args) (cadr args))))
(if (cadr acc)
(rec (multiple-value-list (apply f acc)))
(car acc)))))
(defmacro with-string-stream (stream &body body)
"A macro to allow one to write to a variable string stream and get
the body result out"
(let ((st-name (gensym))
(res-name (gensym)))
`(let ((,st-name (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t)))
(let ((,res-name (with-output-to-string (,stream ,st-name)
,@body)))
(values ,st-name ,res-name)))))
(defun subseq-rel (seq fst &optional (l 0 l-p))
"A relative subsequence function"
(if l-p
(subseq seq fst (+ fst l))
(subseq seq fst)))
(defun split-string-first (seperator str &optional (default-value ""))
"Returns a value pair representing the first split in the string
matching the seperator string"
(let ((l (length seperator))
(el (length str)))
(with-string-stream st
Loop over indicies
(cond ((> (+ i l) el) ;; If we have hit the end
(write-string (subseq-rel str i (1- l)) st)
; Write the rest of the string
; to the stream
default-value)
; There is nothing to seperate, return
an empty string for the second half
((string= seperator (subseq-rel str i l))
; We have found the seperator
(subseq str (+ i l)))
; Return the rest of the
string as the second half
(t (progn
; We need to keep going
(write-char (char str i) st)
; Copy the current char to the
; stream
(rec (1+ i))))))))) ; Iterate to the next string
(defun split-string (seperator str)
"Fully split a string by seperator."
(loop-rec ((acc nil)
(str str))
(if (not str)
(nreverse acc)
(multiple-value-bind (fst snd) (split-string-first seperator str nil)
(rec (cons fst acc) snd)))))
(defun parse-arg (acc arg-list)
"Parses one argument/argument pair into the named/unnamed lists
appropriately"
(destructuring-bind (unnamed named) acc ;; keep track of the unnamed and named args
let x be the first argument
(l (length x))) ;; let l be the next argument
(cond
((and (>= l 2) (string= "--" (subseq x 0 2))) ;; If we have a fully-named arg
(multiple-value-bind (fst snd) (split-string-first "=" x) ;; split the arg on "="
(values
(list unnamed (cons (cons (subseq fst 2) snd) named)) ;;add to the named list
(cdr arg-list))))
((string= "-" (subseq x 0 1)) ;; if we have an abbreviated arg
(cond
((= l 2) ;; The form '-a'
(values
(list unnamed (cons (cons (subseq x 1) (cadr arg-list)) named)) ;; add to the named list
(cddr arg-list)))
((= l 1) ;; The form '-'
(values
(list (cons "-" unnamed) named) ;; Add "-" to the unnamed list
(cdr arg-list)))
(t ;; The form '-m"This is a commit message"'
(values
(list unnamed (cons (cons (subseq-rel x 1 1) (subseq x 2)) named)) ;;add to the named list
(cdr arg-list)))))
(t ;;otherwise, this is an unnamed argument
(values
(list (cons x unnamed) named)
(cdr arg-list)))))))
(defun parse-unfixed-args (args)
"Parse an argument list into the appropriate list"
(destructuring-bind (unnamed named) (reduce-full #'parse-arg (list nil nil) args)
(list (nreverse unnamed) named)))
(defun fix-named-arg (arg-names arg)
"This unifies the named arguments to use the long form."
(let ((x (assoc (first arg) arg-names :test #'string=)))
(if x
(cons (second x) (cdr arg))
arg)))
(defun fix-named-args (arg-names args)
"Fix all of the named args to use the long form"
(let ((named-args (cadr args)))
(list (first args)
(mapcar (lambda (arg) (fix-named-arg arg-names arg)) named-args))))
(defun fill-string (str fill-char n)
"Fill a string with a character until it is at least as long as n
specifies"
(with-string-stream st
(write-string str st)
(loop-rec ((n (- n (length str))))
(unless (<= n 0)
(write-char fill-char st)
(rec (1- n))))))
(defun fix-argdef (argdef)
"This is a formatter for an argdef to display properly"
(if (> (length argdef) 3) ;; If we have an assignment type
(list (if (> (length (first argdef)) 0)
(concatenate 'string " -" (first argdef))
" ")
(concatenate 'string "--" (second argdef) "=" (third argdef))
; Use the name given as a =
(nth 3 argdef))
(list (if (> (length (first argdef)) 0)
; otherwise, we have a boolean
; flag
(concatenate 'string " -" (first argdef))
" ")
(concatenate 'string "--" (second argdef))
(nth 2 argdef))))
(defun generate-flag-string (arg-defs)
"Generate the part of the help string that documents the options
from the arg definition"
(let ((l (loop for x in arg-defs
maximizing (length (second (fix-argdef x))) into l
finally (return l))))
; Get the maximum length of
; the argdef longform names
(format nil "~{~a~%~}"
; Combine the argdef strings
(mapcar (lambda (argdef)
(apply #'concatenate 'string
(list
(fill-string (first argdef) #\Space 6)
Two spaces before , two in
length , two spaces after
(fill-string (second argdef) #\Space (+ 2 l))
l is the , so we
get 2 spaces at least
(car (last argdef)))))
; car (last argdef) is the
; description
(mapcar #'fix-argdef arg-defs)))))
(defun parse-args (arg-defs args)
"Actually calls all the functions to parse the args into the correct
form."
(let ((parsed-args (parse-unfixed-args args)))
(fix-named-args arg-defs parsed-args)))
| null | https://raw.githubusercontent.com/triclops200/quickapp/20e004d90b971201cb7df3020a05ccebc38763eb/argument-parsing.lisp | lisp | If we have hit the end
Write the rest of the string
to the stream
There is nothing to seperate, return
We have found the seperator
Return the rest of the
We need to keep going
Copy the current char to the
stream
Iterate to the next string
keep track of the unnamed and named args
let l be the next argument
If we have a fully-named arg
split the arg on "="
add to the named list
if we have an abbreviated arg
The form '-a'
add to the named list
The form '-'
Add "-" to the unnamed list
The form '-m"This is a commit message"'
add to the named list
otherwise, this is an unnamed argument
If we have an assignment type
Use the name given as a =
otherwise, we have a boolean
flag
Get the maximum length of
the argdef longform names
Combine the argdef strings
car (last argdef) is the
description | (in-package :quickapp)
(defmacro loop-rec (bindings &body body)
"Similar to the clojure loop macro"
(let ((names (mapcar #'car bindings))
(init-vals (mapcar #'cadr bindings)))
`(labels ((rec ,names
,@body))
(rec ,@init-vals))))
(defun reduce-full (f &rest args)
"A reducer that allows f to control the iteration as well as the
accumulator"
(if (= (length args) 1)
(reduce-full f (caar args) (cdar args))
(loop-rec ((acc (list (car args) (cadr args))))
(if (cadr acc)
(rec (multiple-value-list (apply f acc)))
(car acc)))))
(defmacro with-string-stream (stream &body body)
"A macro to allow one to write to a variable string stream and get
the body result out"
(let ((st-name (gensym))
(res-name (gensym)))
`(let ((,st-name (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t)))
(let ((,res-name (with-output-to-string (,stream ,st-name)
,@body)))
(values ,st-name ,res-name)))))
(defun subseq-rel (seq fst &optional (l 0 l-p))
"A relative subsequence function"
(if l-p
(subseq seq fst (+ fst l))
(subseq seq fst)))
(defun split-string-first (seperator str &optional (default-value ""))
"Returns a value pair representing the first split in the string
matching the seperator string"
(let ((l (length seperator))
(el (length str)))
(with-string-stream st
Loop over indicies
(write-string (subseq-rel str i (1- l)) st)
default-value)
an empty string for the second half
((string= seperator (subseq-rel str i l))
(subseq str (+ i l)))
string as the second half
(t (progn
(write-char (char str i) st)
(defun split-string (seperator str)
"Fully split a string by seperator."
(loop-rec ((acc nil)
(str str))
(if (not str)
(nreverse acc)
(multiple-value-bind (fst snd) (split-string-first seperator str nil)
(rec (cons fst acc) snd)))))
(defun parse-arg (acc arg-list)
"Parses one argument/argument pair into the named/unnamed lists
appropriately"
let x be the first argument
(cond
(values
(cdr arg-list))))
(cond
(values
(cddr arg-list)))
(values
(cdr arg-list)))
(values
(cdr arg-list)))))
(values
(list (cons x unnamed) named)
(cdr arg-list)))))))
(defun parse-unfixed-args (args)
"Parse an argument list into the appropriate list"
(destructuring-bind (unnamed named) (reduce-full #'parse-arg (list nil nil) args)
(list (nreverse unnamed) named)))
(defun fix-named-arg (arg-names arg)
"This unifies the named arguments to use the long form."
(let ((x (assoc (first arg) arg-names :test #'string=)))
(if x
(cons (second x) (cdr arg))
arg)))
(defun fix-named-args (arg-names args)
"Fix all of the named args to use the long form"
(let ((named-args (cadr args)))
(list (first args)
(mapcar (lambda (arg) (fix-named-arg arg-names arg)) named-args))))
(defun fill-string (str fill-char n)
"Fill a string with a character until it is at least as long as n
specifies"
(with-string-stream st
(write-string str st)
(loop-rec ((n (- n (length str))))
(unless (<= n 0)
(write-char fill-char st)
(rec (1- n))))))
(defun fix-argdef (argdef)
"This is a formatter for an argdef to display properly"
(list (if (> (length (first argdef)) 0)
(concatenate 'string " -" (first argdef))
" ")
(concatenate 'string "--" (second argdef) "=" (third argdef))
(nth 3 argdef))
(list (if (> (length (first argdef)) 0)
(concatenate 'string " -" (first argdef))
" ")
(concatenate 'string "--" (second argdef))
(nth 2 argdef))))
(defun generate-flag-string (arg-defs)
"Generate the part of the help string that documents the options
from the arg definition"
(let ((l (loop for x in arg-defs
maximizing (length (second (fix-argdef x))) into l
finally (return l))))
(format nil "~{~a~%~}"
(mapcar (lambda (argdef)
(apply #'concatenate 'string
(list
(fill-string (first argdef) #\Space 6)
Two spaces before , two in
length , two spaces after
(fill-string (second argdef) #\Space (+ 2 l))
l is the , so we
get 2 spaces at least
(car (last argdef)))))
(mapcar #'fix-argdef arg-defs)))))
(defun parse-args (arg-defs args)
"Actually calls all the functions to parse the args into the correct
form."
(let ((parsed-args (parse-unfixed-args args)))
(fix-named-args arg-defs parsed-args)))
|
500c881183abde3155e1432279fd245a0a3350ef91b9048d415a29575006819a | clash-lang/clash-prelude | File.hs | |
Copyright : ( C ) 2015 - 2016 , University of Twente ,
2017 , Myrtle Software Ltd , Google Inc.
License : BSD2 ( see the file LICENSE )
Maintainer : < >
= Initialising a BlockRAM with a data file # usingramfiles #
BlockRAM primitives that can be initialised with a data file . The BNF grammar
for this data file is simple :
@
FILE = LINE+
LINE = BIT+
BIT = ' 0 '
| ' 1 '
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example , a data file @memory.bin@ containing the 9 - bit unsigned number
@7@ to @13@ looks like :
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
We can instantiate a BlockRAM using the content of the above file like so :
@
f : : HiddenClock domain - > Signal domain ( Unsigned 3 ) - > Signal domain ( Unsigned 9 )
f rd = ' Clash.Class.BitPack.unpack ' ' < $ > ' exposeClock ' blockRamFile ' clk d7 \"memory.bin\ " rd ( signal Nothing )
@
In the example above , we basically treat the BlockRAM as an synchronous ROM .
We can see that it works as expected :
@
_ _ > > > import qualified Data . List as L _ _
_ _ > > > L.tail $ sampleN 4 $ f ( fromList [ 3 .. 5 ] ) _ _
[ 10,11,12 ]
@
However , we can also interpret the same data as a tuple of a 6 - bit unsigned
number , and a 3 - bit signed number :
@
g : : HiddenClock domain - > Signal domain ( Unsigned 3 ) - > Signal domain ( Unsigned 6,Signed 3 )
g clk rd = ' Clash.Class.BitPack.unpack ' ' < $ > ' exposeClock ' blockRamFile ' clk d7 \"memory.bin\ " rd ( signal Nothing )
@
And then we would see :
@
_ _ > > > import qualified Data . List as L _ _
_ _ > > > L.tail $ sampleN 4 $ g ( fromList [ 3 .. 5 ] ) _ _
[ ( 1,2),(1,3)(1,-4 ) ]
@
Copyright : (C) 2015-2016, University of Twente,
2017 , Myrtle Software Ltd, Google Inc.
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <>
= Initialising a BlockRAM with a data file #usingramfiles#
BlockRAM primitives that can be initialised with a data file. The BNF grammar
for this data file is simple:
@
FILE = LINE+
LINE = BIT+
BIT = '0'
| '1'
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example, a data file @memory.bin@ containing the 9-bit unsigned number
@7@ to @13@ looks like:
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
We can instantiate a BlockRAM using the content of the above file like so:
@
f :: HiddenClock domain -> Signal domain (Unsigned 3) -> Signal domain (Unsigned 9)
f rd = 'Clash.Class.BitPack.unpack' '<$>' exposeClock 'blockRamFile' clk d7 \"memory.bin\" rd (signal Nothing)
@
In the example above, we basically treat the BlockRAM as an synchronous ROM.
We can see that it works as expected:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ f (fromList [3..5])__
[10,11,12]
@
However, we can also interpret the same data as a tuple of a 6-bit unsigned
number, and a 3-bit signed number:
@
g :: HiddenClock domain -> Signal domain (Unsigned 3) -> Signal domain (Unsigned 6,Signed 3)
g clk rd = 'Clash.Class.BitPack.unpack' '<$>' exposeClock 'blockRamFile' clk d7 \"memory.bin\" rd (signal Nothing)
@
And then we would see:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ g (fromList [3..5])__
[(1,2),(1,3)(1,-4)]
@
-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE GADTs #
# LANGUAGE MagicHash #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeOperators #-}
# LANGUAGE Unsafe #
{-# OPTIONS_HADDOCK show-extensions #-}
module Clash.Prelude.BlockRam.File
( -- * BlockRAM synchronised to an arbitrary clock
blockRamFile
, blockRamFilePow2
)
where
import GHC.TypeLits (KnownNat)
import GHC.Stack (HasCallStack, withFrozenCallStack)
import qualified Clash.Explicit.BlockRam.File as E
import Clash.Promoted.Nat (SNat)
import Clash.Signal (HiddenClock, Signal, hideClock)
import Clash.Sized.BitVector (BitVector)
import Clash.Sized.Unsigned (Unsigned)
| Create a blockRAM with space for 2^@n@ elements
--
* _ _ NB _ _ : Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
Altera / Quartus | Broken | Works | Works |
Xilinx / ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "Clash.Prelude.BlockRam#usingrams" for more information on how to use a
-- Block RAM.
* Use the adapter ' readNew '' for obtaining write - before - read semantics like this : @readNew ' clk ( blockRamFilePow2 ' clk file ) rd wrM@.
* See " Clash . Prelude . BlockRam . File#usingramfiles " for more information on how
-- to instantiate a Block RAM with the contents of a data file.
-- * See "Clash.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
blockRamFilePow2
:: forall domain gated n m
. (KnownNat m, KnownNat n, HiddenClock domain gated, HasCallStack)
=> FilePath
-- ^ File describing the initial content of the blockRAM
-> Signal domain (Unsigned n)
-- ^ Read address @r@
-> Signal domain (Maybe (Unsigned n, BitVector m))
-- ^ (write address @w@, value to write)
-> Signal domain (BitVector m)
^ Value of the @blockRAM@ at address @r@ from the previous
-- clock cycle
blockRamFilePow2 = \fp rd wrM -> withFrozenCallStack
(hideClock E.blockRamFilePow2 fp rd wrM)
# INLINE blockRamFilePow2 #
| Create a blockRAM with space for @n@ elements
--
* _ _ NB _ _ : Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
Altera / Quartus | Broken | Works | Works |
Xilinx / ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "Clash.Prelude.BlockRam#usingrams" for more information on how to use a
-- Block RAM.
* Use the adapter ' readNew '' for obtaining write - before - read semantics like this : @readNew ' clk ( blockRamFile ' clk size file ) rd wrM@.
* See " Clash . Prelude . BlockRam . File#usingramfiles " for more information on how
-- to instantiate a Block RAM with the contents of a data file.
-- * See "Clash.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
blockRamFile
:: (KnownNat m, Enum addr, HiddenClock domain gated, HasCallStack)
=> SNat n
-- ^ Size of the blockRAM
-> FilePath
-- ^ File describing the initial content of the blockRAM
-> Signal domain addr
-- ^ Read address @r@
-> Signal domain (Maybe (addr, BitVector m))
-- ^ (write address @w@, value to write)
-> Signal domain (BitVector m)
^ Value of the @blockRAM@ at address @r@ from the previous
-- clock cycle
blockRamFile = \sz fp rd wrM -> withFrozenCallStack
(hideClock E.blockRamFile sz fp rd wrM)
# INLINE blockRamFile #
| null | https://raw.githubusercontent.com/clash-lang/clash-prelude/5645d8417ab495696cf4e0293796133c7fe2a9a7/src/Clash/Prelude/BlockRam/File.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
# OPTIONS_HADDOCK show-extensions #
* BlockRAM synchronised to an arbitrary clock
* __NB__: Initial output value is 'undefined'
* __NB__: This function might not work for specific combinations of
code-generation backends and hardware targets. Please check the support table
below:
@
| VHDL | Verilog | SystemVerilog |
===============+==========+==========+===============+
ASIC | Untested | Untested | Untested |
===============+==========+==========+===============+
@
Additional helpful information:
* See "Clash.Prelude.BlockRam#usingrams" for more information on how to use a
Block RAM.
to instantiate a Block RAM with the contents of a data file.
* See "Clash.Sized.Fixed#creatingdatafiles" for ideas on how to create your
own data files.
^ File describing the initial content of the blockRAM
^ Read address @r@
^ (write address @w@, value to write)
clock cycle
* __NB__: Initial output value is 'undefined'
* __NB__: This function might not work for specific combinations of
code-generation backends and hardware targets. Please check the support table
below:
@
| VHDL | Verilog | SystemVerilog |
===============+==========+==========+===============+
ASIC | Untested | Untested | Untested |
===============+==========+==========+===============+
@
Additional helpful information:
* See "Clash.Prelude.BlockRam#usingrams" for more information on how to use a
Block RAM.
to instantiate a Block RAM with the contents of a data file.
* See "Clash.Sized.Fixed#creatingdatafiles" for ideas on how to create your
own data files.
^ Size of the blockRAM
^ File describing the initial content of the blockRAM
^ Read address @r@
^ (write address @w@, value to write)
clock cycle | |
Copyright : ( C ) 2015 - 2016 , University of Twente ,
2017 , Myrtle Software Ltd , Google Inc.
License : BSD2 ( see the file LICENSE )
Maintainer : < >
= Initialising a BlockRAM with a data file # usingramfiles #
BlockRAM primitives that can be initialised with a data file . The BNF grammar
for this data file is simple :
@
FILE = LINE+
LINE = BIT+
BIT = ' 0 '
| ' 1 '
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example , a data file @memory.bin@ containing the 9 - bit unsigned number
@7@ to @13@ looks like :
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
We can instantiate a BlockRAM using the content of the above file like so :
@
f : : HiddenClock domain - > Signal domain ( Unsigned 3 ) - > Signal domain ( Unsigned 9 )
f rd = ' Clash.Class.BitPack.unpack ' ' < $ > ' exposeClock ' blockRamFile ' clk d7 \"memory.bin\ " rd ( signal Nothing )
@
In the example above , we basically treat the BlockRAM as an synchronous ROM .
We can see that it works as expected :
@
_ _ > > > import qualified Data . List as L _ _
_ _ > > > L.tail $ sampleN 4 $ f ( fromList [ 3 .. 5 ] ) _ _
[ 10,11,12 ]
@
However , we can also interpret the same data as a tuple of a 6 - bit unsigned
number , and a 3 - bit signed number :
@
g : : HiddenClock domain - > Signal domain ( Unsigned 3 ) - > Signal domain ( Unsigned 6,Signed 3 )
g clk rd = ' Clash.Class.BitPack.unpack ' ' < $ > ' exposeClock ' blockRamFile ' clk d7 \"memory.bin\ " rd ( signal Nothing )
@
And then we would see :
@
_ _ > > > import qualified Data . List as L _ _
_ _ > > > L.tail $ sampleN 4 $ g ( fromList [ 3 .. 5 ] ) _ _
[ ( 1,2),(1,3)(1,-4 ) ]
@
Copyright : (C) 2015-2016, University of Twente,
2017 , Myrtle Software Ltd, Google Inc.
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <>
= Initialising a BlockRAM with a data file #usingramfiles#
BlockRAM primitives that can be initialised with a data file. The BNF grammar
for this data file is simple:
@
FILE = LINE+
LINE = BIT+
BIT = '0'
| '1'
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example, a data file @memory.bin@ containing the 9-bit unsigned number
@7@ to @13@ looks like:
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
We can instantiate a BlockRAM using the content of the above file like so:
@
f :: HiddenClock domain -> Signal domain (Unsigned 3) -> Signal domain (Unsigned 9)
f rd = 'Clash.Class.BitPack.unpack' '<$>' exposeClock 'blockRamFile' clk d7 \"memory.bin\" rd (signal Nothing)
@
In the example above, we basically treat the BlockRAM as an synchronous ROM.
We can see that it works as expected:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ f (fromList [3..5])__
[10,11,12]
@
However, we can also interpret the same data as a tuple of a 6-bit unsigned
number, and a 3-bit signed number:
@
g :: HiddenClock domain -> Signal domain (Unsigned 3) -> Signal domain (Unsigned 6,Signed 3)
g clk rd = 'Clash.Class.BitPack.unpack' '<$>' exposeClock 'blockRamFile' clk d7 \"memory.bin\" rd (signal Nothing)
@
And then we would see:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ g (fromList [3..5])__
[(1,2),(1,3)(1,-4)]
@
-}
# LANGUAGE GADTs #
# LANGUAGE MagicHash #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE Unsafe #
module Clash.Prelude.BlockRam.File
blockRamFile
, blockRamFilePow2
)
where
import GHC.TypeLits (KnownNat)
import GHC.Stack (HasCallStack, withFrozenCallStack)
import qualified Clash.Explicit.BlockRam.File as E
import Clash.Promoted.Nat (SNat)
import Clash.Signal (HiddenClock, Signal, hideClock)
import Clash.Sized.BitVector (BitVector)
import Clash.Sized.Unsigned (Unsigned)
| Create a blockRAM with space for 2^@n@ elements
* _ _ NB _ _ : Read value is delayed by 1 cycle
Altera / Quartus | Broken | Works | Works |
Xilinx / ISE | Works | Works | Works |
* Use the adapter ' readNew '' for obtaining write - before - read semantics like this : @readNew ' clk ( blockRamFilePow2 ' clk file ) rd wrM@.
* See " Clash . Prelude . BlockRam . File#usingramfiles " for more information on how
blockRamFilePow2
:: forall domain gated n m
. (KnownNat m, KnownNat n, HiddenClock domain gated, HasCallStack)
=> FilePath
-> Signal domain (Unsigned n)
-> Signal domain (Maybe (Unsigned n, BitVector m))
-> Signal domain (BitVector m)
^ Value of the @blockRAM@ at address @r@ from the previous
blockRamFilePow2 = \fp rd wrM -> withFrozenCallStack
(hideClock E.blockRamFilePow2 fp rd wrM)
# INLINE blockRamFilePow2 #
| Create a blockRAM with space for @n@ elements
* _ _ NB _ _ : Read value is delayed by 1 cycle
Altera / Quartus | Broken | Works | Works |
Xilinx / ISE | Works | Works | Works |
* Use the adapter ' readNew '' for obtaining write - before - read semantics like this : @readNew ' clk ( blockRamFile ' clk size file ) rd wrM@.
* See " Clash . Prelude . BlockRam . File#usingramfiles " for more information on how
blockRamFile
:: (KnownNat m, Enum addr, HiddenClock domain gated, HasCallStack)
=> SNat n
-> FilePath
-> Signal domain addr
-> Signal domain (Maybe (addr, BitVector m))
-> Signal domain (BitVector m)
^ Value of the @blockRAM@ at address @r@ from the previous
blockRamFile = \sz fp rd wrM -> withFrozenCallStack
(hideClock E.blockRamFile sz fp rd wrM)
# INLINE blockRamFile #
|
297def51ca116198cf614ef1a0c586b9f411c5368013ccbde5ede0d7d801ffff | tgass/macbeth | ChatRegistry.hs | module Macbeth.Wx.ChatRegistry (
wxChatRegistry
) where
import Control.Concurrent.Chan
import Control.Monad
import Macbeth.Fics.Message
import Macbeth.Fics.Api.Api
import Macbeth.Fics.Api.Player
import Macbeth.Wx.Chat
import Macbeth.Wx.RuntimeEnv
wxChatRegistry :: RuntimeEnv -> Chan Message -> IO (Message -> IO ())
wxChatRegistry env chan = return $ \case
Says (UserHandle username _) Nothing msg -> openIfUntracked (UserChat username) $ Receiving username msg
Tells (UserHandle username _) Nothing msg -> openIfUntracked (UserChat username) $ Receiving username msg
Tells (UserHandle username _) (Just channelId) msg -> openIfUntracked (ChannelChat channelId) $ Receiving username msg
Says (UserHandle username _) (Just gameId) msg -> openIfUntracked (GameChat gameId) $ Receiving username msg
Whispers (UserHandle username _) _ gameId msg -> openIfUntracked (GameChat gameId) $ Receiving username msg
Kibitzes (UserHandle username _) _ gameId msg -> openIfUntracked (GameChat gameId) $ Receiving username msg
_ -> return ()
where
openIfUntracked :: ChatId -> Receiving -> IO ()
openIfUntracked chatId msg = do
isTracked <- isTrackedChat env chatId
unless isTracked $ do
env `trackChat` chatId
dupChan chan >>= wxChat env chatId (Just msg)
| null | https://raw.githubusercontent.com/tgass/macbeth/c64b3cc9b641444688b14a2838ee554932f0e9e6/macbeth-wx/src/Macbeth/Wx/ChatRegistry.hs | haskell | module Macbeth.Wx.ChatRegistry (
wxChatRegistry
) where
import Control.Concurrent.Chan
import Control.Monad
import Macbeth.Fics.Message
import Macbeth.Fics.Api.Api
import Macbeth.Fics.Api.Player
import Macbeth.Wx.Chat
import Macbeth.Wx.RuntimeEnv
wxChatRegistry :: RuntimeEnv -> Chan Message -> IO (Message -> IO ())
wxChatRegistry env chan = return $ \case
Says (UserHandle username _) Nothing msg -> openIfUntracked (UserChat username) $ Receiving username msg
Tells (UserHandle username _) Nothing msg -> openIfUntracked (UserChat username) $ Receiving username msg
Tells (UserHandle username _) (Just channelId) msg -> openIfUntracked (ChannelChat channelId) $ Receiving username msg
Says (UserHandle username _) (Just gameId) msg -> openIfUntracked (GameChat gameId) $ Receiving username msg
Whispers (UserHandle username _) _ gameId msg -> openIfUntracked (GameChat gameId) $ Receiving username msg
Kibitzes (UserHandle username _) _ gameId msg -> openIfUntracked (GameChat gameId) $ Receiving username msg
_ -> return ()
where
openIfUntracked :: ChatId -> Receiving -> IO ()
openIfUntracked chatId msg = do
isTracked <- isTrackedChat env chatId
unless isTracked $ do
env `trackChat` chatId
dupChan chan >>= wxChat env chatId (Just msg)
| |
52dc9d5082aafdb2a936c1b3aafab6b47f4be65d0f870d421db8fc941abd9b9b | dselsam/arc | Goal.hs | Copyright ( c ) 2020 Microsoft Corporation . All rights reserved .
Released under Apache 2.0 license as described in the file LICENSE .
Authors : , , .
{-# LANGUAGE StrictData #-}
module Solver.Tactics.Blast.Goal where
import Util.Imports
import Data.List hiding (partition)
import qualified Data.Map as Map
import Synth1.Basic
import Synth.Ex (Ex(..), ForTrain, ForTest)
import qualified Synth.Ex as Ex
import Lib.Grid (Grid)
import Lib.Color (Color)
TODO : make ( doubly ) polymorphic in Color ?
data Goal = Goal {
inputs :: Ex (Grid Color),
outputs :: ForTrain (Grid Color),
reconstructs :: Ex (Grid (Maybe Color))
}
| null | https://raw.githubusercontent.com/dselsam/arc/7e68a7ed9508bf26926b0f68336db05505f4e765/src/Solver/Tactics/Blast/Goal.hs | haskell | # LANGUAGE StrictData # | Copyright ( c ) 2020 Microsoft Corporation . All rights reserved .
Released under Apache 2.0 license as described in the file LICENSE .
Authors : , , .
module Solver.Tactics.Blast.Goal where
import Util.Imports
import Data.List hiding (partition)
import qualified Data.Map as Map
import Synth1.Basic
import Synth.Ex (Ex(..), ForTrain, ForTest)
import qualified Synth.Ex as Ex
import Lib.Grid (Grid)
import Lib.Color (Color)
TODO : make ( doubly ) polymorphic in Color ?
data Goal = Goal {
inputs :: Ex (Grid Color),
outputs :: ForTrain (Grid Color),
reconstructs :: Ex (Grid (Maybe Color))
}
|
2602afda14f3d2b3657cac9841533899a6379d05e861bfdc2cbf266041d85442 | comby-tools/comby | patdiff_core_intf.ml | open! Core_kernel
open! Import
module type S = sig
* [ diff ~context ~keep_ws ~prev ~next ] uses [ Patience_diff . String ] to get a list of
hunks describing the comparison between [ prev ] and [ next ] .
hunks describing the comparison between [prev] and [next]. *)
val diff
: context:int
-> line_big_enough:int
-> keep_ws:bool
-> prev:string array
-> next:string array
-> Hunks.t
(** [refine hunks] maps each [Range.Replace (prev, next)] in [hunks] to a diff of [prev]
against [next]. *)
val refine
: rules:Format.Rules.t
-> produce_unified_lines:bool
-> output:Output.t
-> keep_ws:bool
-> split_long_lines:bool
-> interleave:bool
-> word_big_enough:int
-> Hunks.t
-> Hunks.t
val explode
: string array
-> keep_ws:bool
-> [ `Newline of int * string option | `Word of string ] array
(** Print a hunk list, usually from [diff] or [refine] *)
val print
: file_names:File_name.t * File_name.t
-> rules:Format.Rules.t
-> output:Output.t
-> location_style:Format.Location_style.t
-> Hunks.t
-> unit
(** Output a hunk list, usually from [diff] or [refine], to a string *)
val output_to_string
: ?print_global_header:bool
-> file_names:File_name.t * File_name.t
-> rules:Format.Rules.t
-> output:Output.t
-> location_style:Format.Location_style.t
-> Hunks.t
-> string
(** Iter along the lines of the diff and the breaks between hunks. Offers more flexibility
regarding what the caller wants to do with the lines *)
val iter_ansi
: rules:Format.Rules.t
-> f_hunk_break:(int * int -> int * int -> unit)
-> f_line:(string -> unit)
-> Hunks.t
-> unit
* Runs the equivalent of the command line version of on two given contents
[ prev ] and [ next ] . Uses [ Patience_diff . String ] .
[prev] and [next]. Uses [Patience_diff.String]. *)
val patdiff
: ?context:int
-> ?keep_ws:bool
-> ?rules:Format.Rules.t
-> ?output:Output.t
-> ?produce_unified_lines:bool
-> ?split_long_lines:bool
-> ?print_global_header:bool
-> ?location_style:Format.Location_style.t
-> ?interleave:bool
-> ?line_big_enough:int
-> ?word_big_enough:int
-> prev:Diff_input.t
-> next:Diff_input.t
-> unit
-> string
end
module type Output_impls = sig
val implementation : Output.t -> (module Output.S)
val console_width : unit -> int Or_error.t
end
module type Patdiff_core = sig
module type S = S
val default_context : int
val default_line_big_enough : int
val default_word_big_enough : int
* [ ] calls String.strip and replaces whitespace with " "
val remove_ws : string -> string
module Private : sig
module Make (Output_impls : Output_impls) : S
end
module Without_unix : S
end
| null | https://raw.githubusercontent.com/comby-tools/comby/fa71ea540855ba5bd48d948dd8c8ff034714348d/lib/app/vendored/patdiff/kernel/src/patdiff_core_intf.ml | ocaml | * [refine hunks] maps each [Range.Replace (prev, next)] in [hunks] to a diff of [prev]
against [next].
* Print a hunk list, usually from [diff] or [refine]
* Output a hunk list, usually from [diff] or [refine], to a string
* Iter along the lines of the diff and the breaks between hunks. Offers more flexibility
regarding what the caller wants to do with the lines | open! Core_kernel
open! Import
module type S = sig
* [ diff ~context ~keep_ws ~prev ~next ] uses [ Patience_diff . String ] to get a list of
hunks describing the comparison between [ prev ] and [ next ] .
hunks describing the comparison between [prev] and [next]. *)
val diff
: context:int
-> line_big_enough:int
-> keep_ws:bool
-> prev:string array
-> next:string array
-> Hunks.t
val refine
: rules:Format.Rules.t
-> produce_unified_lines:bool
-> output:Output.t
-> keep_ws:bool
-> split_long_lines:bool
-> interleave:bool
-> word_big_enough:int
-> Hunks.t
-> Hunks.t
val explode
: string array
-> keep_ws:bool
-> [ `Newline of int * string option | `Word of string ] array
val print
: file_names:File_name.t * File_name.t
-> rules:Format.Rules.t
-> output:Output.t
-> location_style:Format.Location_style.t
-> Hunks.t
-> unit
val output_to_string
: ?print_global_header:bool
-> file_names:File_name.t * File_name.t
-> rules:Format.Rules.t
-> output:Output.t
-> location_style:Format.Location_style.t
-> Hunks.t
-> string
val iter_ansi
: rules:Format.Rules.t
-> f_hunk_break:(int * int -> int * int -> unit)
-> f_line:(string -> unit)
-> Hunks.t
-> unit
* Runs the equivalent of the command line version of on two given contents
[ prev ] and [ next ] . Uses [ Patience_diff . String ] .
[prev] and [next]. Uses [Patience_diff.String]. *)
val patdiff
: ?context:int
-> ?keep_ws:bool
-> ?rules:Format.Rules.t
-> ?output:Output.t
-> ?produce_unified_lines:bool
-> ?split_long_lines:bool
-> ?print_global_header:bool
-> ?location_style:Format.Location_style.t
-> ?interleave:bool
-> ?line_big_enough:int
-> ?word_big_enough:int
-> prev:Diff_input.t
-> next:Diff_input.t
-> unit
-> string
end
module type Output_impls = sig
val implementation : Output.t -> (module Output.S)
val console_width : unit -> int Or_error.t
end
module type Patdiff_core = sig
module type S = S
val default_context : int
val default_line_big_enough : int
val default_word_big_enough : int
* [ ] calls String.strip and replaces whitespace with " "
val remove_ws : string -> string
module Private : sig
module Make (Output_impls : Output_impls) : S
end
module Without_unix : S
end
|
7252b3ba7e13c2a44cd825224249ad832327f37e8fa59e29b7c65928af5aa2e2 | number571/Haskell | calculator.hs | module Main where
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' _ x [] = x
foldl' f x (y:ys) = foldl' f (f x y) ys
head' :: [a] -> a
head' [] = undefined
head' (x:xs) = x
drop' :: Int -> [a] -> [a]
drop' _ [] = []
drop' x (y:ys)
| x /= 0 = drop' (x-1) ys
| otherwise = y:ys
length' :: [a] -> Int
length' [] = 0
length' (x:xs) = 1 + length' xs
isSpace :: Char -> Bool
isSpace x = if x == ' ' || x == '\t' || x == '\n'
then True else False
accumulate :: String -> String
accumulate [] = []
accumulate (x:xs)
| isSpace x = []
| otherwise = x : accumulate xs
words' :: String -> [String]
words' [] = []
words' (x:xs)
| isSpace x = words' xs
| otherwise = accumulate (x:xs) : words'
(drop' (length' (accumulate (x:xs))) xs)
calc :: String -> Float
calc s = head' . foldl' f [] $ words' s
where
f :: [Float] -> String -> [Float]
f (x:y:zs) "+" = (y + x):zs
f (x:y:zs) "-" = (y - x):zs
f (x:y:zs) "*" = (y * x):zs
f (x:y:zs) "/" = (y / x):zs
f xs y = read y : xs
main :: IO()
main = print . calc $ "2 5 + 3 *"
| null | https://raw.githubusercontent.com/number571/Haskell/7da2676c2604706d43791dc89c0ca8c9842aea48/Templates/calculator.hs | haskell | module Main where
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' _ x [] = x
foldl' f x (y:ys) = foldl' f (f x y) ys
head' :: [a] -> a
head' [] = undefined
head' (x:xs) = x
drop' :: Int -> [a] -> [a]
drop' _ [] = []
drop' x (y:ys)
| x /= 0 = drop' (x-1) ys
| otherwise = y:ys
length' :: [a] -> Int
length' [] = 0
length' (x:xs) = 1 + length' xs
isSpace :: Char -> Bool
isSpace x = if x == ' ' || x == '\t' || x == '\n'
then True else False
accumulate :: String -> String
accumulate [] = []
accumulate (x:xs)
| isSpace x = []
| otherwise = x : accumulate xs
words' :: String -> [String]
words' [] = []
words' (x:xs)
| isSpace x = words' xs
| otherwise = accumulate (x:xs) : words'
(drop' (length' (accumulate (x:xs))) xs)
calc :: String -> Float
calc s = head' . foldl' f [] $ words' s
where
f :: [Float] -> String -> [Float]
f (x:y:zs) "+" = (y + x):zs
f (x:y:zs) "-" = (y - x):zs
f (x:y:zs) "*" = (y * x):zs
f (x:y:zs) "/" = (y / x):zs
f xs y = read y : xs
main :: IO()
main = print . calc $ "2 5 + 3 *"
| |
838702b237e9ae564da1e586ff922ab1b880bb8054145096c5804e4d4b01e6d2 | ijvcms/chuanqi_dev | mmake.erl | %% 多进程编译,修改自otp/lib/tools/src/make.erl
解析Emakefile , 根据获取{mods , options}列表 ,
%% 按照次序编译每项(解决编译顺序的问题)
其中mods也可以包含多个模块 , 当大于1个时 ,
可以启动多个process进行编译 , 从而提高编译速度 .
-module(mmake).
-export([all/1, all/2, files/2, files/3]).
-include_lib("kernel/include/file.hrl").
-define(MakeOpts, [noexec, load, netload, noload]).
all(Worker) when is_integer(Worker) ->
all(Worker, []).
all(Worker, Options) when is_integer(Worker) ->
{MakeOpts, CompileOpts} = sort_options(Options, [], []),
case read_emakefile('Emakefile', CompileOpts) of
Files when is_list(Files) ->
do_make_files(Worker, Files, MakeOpts);
error ->
error
end.
files(Worker, Fs) ->
files(Worker, Fs, []).
files(Worker, Fs0, Options) ->
Fs = [filename:rootname(F, ".erl") || F <- Fs0],
{MakeOpts, CompileOpts} = sort_options(Options, [], []),
case get_opts_from_emakefile(Fs, 'Emakefile', CompileOpts) of
Files when is_list(Files) ->
do_make_files(Worker, Files, MakeOpts);
error -> error
end.
do_make_files(Worker, Fs, Opts) ->
io : format("worker:~p ~ " , [ Worker , Fs , Opts ] ) ,
process(Fs, Worker, lists:member(noexec, Opts), load_opt(Opts)).
sort_options([H | T], Make, Comp) ->
case lists:member(H, ?MakeOpts) of
true ->
sort_options(T, [H | Make], Comp);
false ->
sort_options(T, Make, [H | Comp])
end;
sort_options([], Make, Comp) ->
{Make, lists:reverse(Comp)}.
Reads the given Emakefile and returns a list of tuples : { Mods , Opts }
%%% Mods is a list of module names (strings)
Opts is a list of options to be used when compiling Mods
%%%
Emakefile can contain elements like this :
%%% Mod.
{ Mod , } .
%%% Mod is a module name which might include '*' as wildcard
%%% or a list of such module names
%%%
These elements are converted to [ { ModList , OptList } , ... ]
ModList is a list of modulenames ( strings )
read_emakefile(Emakefile, Opts) ->
case file:consult(Emakefile) of
{ok, Emake} ->
transform(Emake, Opts, [], []);
{error, enoent} ->
No Emakefile found - return all modules in current
%% directory and the options given at command line
Mods = [filename:rootname(F) || F <- filelib:wildcard("*.erl")],
[{Mods, Opts}];
{error, Other} ->
io:format("make: Trouble reading 'Emakefile':~n~p~n", [Other]),
error
end.
transform([{Mod, ModOpts} | Emake], Opts, Files, Already) ->
case expand(Mod, Already) of
[] ->
transform(Emake, Opts, Files, Already);
Mods ->
transform(Emake, Opts, [{Mods, ModOpts ++ Opts} | Files], Mods ++ Already)
end;
transform([Mod | Emake], Opts, Files, Already) ->
case expand(Mod, Already) of
[] ->
transform(Emake, Opts, Files, Already);
Mods ->
transform(Emake, Opts, [{Mods, Opts} | Files], Mods ++ Already)
end;
transform([], _Opts, Files, _Already) ->
lists:reverse(Files).
expand(Mod, Already) when is_atom(Mod) ->
expand(atom_to_list(Mod), Already);
expand(Mods, Already) when is_list(Mods), not is_integer(hd(Mods)) ->
lists:concat([expand(Mod, Already) || Mod <- Mods]);
expand(Mod, Already) ->
case lists:member($*, Mod) of
true ->
Fun = fun(F, Acc) ->
M = filename:rootname(F),
case lists:member(M, Already) of
true -> Acc;
false -> [M | Acc]
end
end,
lists:foldl(Fun, [], filelib:wildcard(Mod ++ ".erl"));
false ->
Mod2 = filename:rootname(Mod, ".erl"),
case lists:member(Mod2, Already) of
true -> [];
false -> [Mod2]
end
end.
Reads the given Emakefile to see if there are any specific compile
%%% options given for the modules.
get_opts_from_emakefile(Mods, Emakefile, Opts) ->
case file:consult(Emakefile) of
{ok, Emake} ->
Modsandopts = transform(Emake, Opts, [], []),
ModStrings = [coerce_2_list(M) || M <- Mods],
get_opts_from_emakefile2(Modsandopts, ModStrings, Opts, []);
{error, enoent} ->
[{Mods, Opts}];
{error, Other} ->
io:format("make: Trouble reading 'Emakefile':~n~p~n", [Other]),
error
end.
get_opts_from_emakefile2([{MakefileMods, O} | Rest], Mods, Opts, Result) ->
case members(Mods, MakefileMods, [], Mods) of
{[], _} ->
get_opts_from_emakefile2(Rest, Mods, Opts, Result);
{I, RestOfMods} ->
get_opts_from_emakefile2(Rest, RestOfMods, Opts, [{I, O} | Result])
end;
get_opts_from_emakefile2([], [], _Opts, Result) ->
Result;
get_opts_from_emakefile2([], RestOfMods, Opts, Result) ->
[{RestOfMods, Opts} | Result].
members([H | T], MakefileMods, I, Rest) ->
case lists:member(H, MakefileMods) of
true ->
members(T, MakefileMods, [H | I], lists:delete(H, Rest));
false ->
members(T, MakefileMods, I, Rest)
end;
members([], _MakefileMods, I, Rest) ->
{I, Rest}.
%% Any flags that are not recognixed as make flags are passed directly
%% to the compiler.
%% So for example make:all([load,debug_info]) will make everything
%% with the debug_info flag and load it.
load_opt(Opts) ->
case lists:member(netload, Opts) of
true ->
netload;
false ->
case lists:member(load, Opts) of
true ->
load;
_ ->
noload
end
end.
%% 处理
process([{[], _Opts} | Rest], Worker, NoExec, Load) ->
process(Rest, Worker, NoExec, Load);
process([{L, Opts} | Rest], Worker, NoExec, Load) ->
Len = length(L),
Worker2 = erlang:min(Len, Worker),
case catch do_worker(L, Opts, NoExec, Load, Worker2) of
error ->
error;
ok ->
process(Rest, Worker, NoExec, Load)
end;
process([], _Worker, _NoExec, _Load) ->
up_to_date.
worker进行编译
do_worker(L, Opts, NoExec, Load, Worker) ->
WorkerList = do_split_list(L, Worker),
io : format("worker:~p worker " , [ Worker , length(WorkerList ) ] ) ,
% 启动进程
Ref = make_ref(),
Pids =
[begin
start_worker(E, Opts, NoExec, Load, self(), Ref)
end || E <- WorkerList],
do_wait_worker(length(Pids), Ref).
%% 等待结果
do_wait_worker(0, _Ref) ->
ok;
do_wait_worker(N, Ref) ->
receive
{ack, Ref} ->
do_wait_worker(N - 1, Ref);
{error, Ref} ->
throw(error);
{'EXIT', _P, _Reason} ->
do_wait_worker(N, Ref);
_Other ->
io:format("receive unknown msg:~p~n", [_Other]),
do_wait_worker(N, Ref)
end.
%% 将L分割成最多包含N个子列表的列表
do_split_list(L, N) ->
Len = length(L),
每个列表的元素数
LLen = (Len + N - 1) div N,
do_split_list(L, LLen, []).
do_split_list([], _N, Acc) ->
lists:reverse(Acc);
do_split_list(L, N, Acc) ->
{L2, L3} = lists:split(erlang:min(length(L), N), L),
do_split_list(L3, N, [L2 | Acc]).
%% 启动worker进程
start_worker(L, Opts, NoExec, Load, Parent, Ref) ->
Fun =
fun() ->
[begin
case recompilep(coerce_2_list(F), NoExec, Load, Opts) of
error ->
Parent ! {error, Ref},
exit(error);
_ ->
ok
end
end || F <- L],
Parent ! {ack, Ref}
end,
spawn_link(Fun).
recompilep(File, NoExec, Load, Opts) ->
ObjName = lists:append(filename:basename(File),
code:objfile_extension()),
ObjFile = case lists:keysearch(outdir, 1, Opts) of
{value, {outdir, OutDir}} ->
filename:join(coerce_2_list(OutDir), ObjName);
false ->
ObjName
end,
case exists(ObjFile) of
true ->
recompilep1(File, NoExec, Load, Opts, ObjFile);
false ->
recompile(File, NoExec, Load, Opts)
end.
recompilep1(File, NoExec, Load, Opts, ObjFile) ->
{ok, Erl} = file:read_file_info(lists:append(File, ".erl")),
{ok, Obj} = file:read_file_info(ObjFile),
recompilep1(Erl, Obj, File, NoExec, Load, Opts).
recompilep1(#file_info{mtime = Te},
#file_info{mtime = To}, File, NoExec, Load, Opts) when Te > To ->
recompile(File, NoExec, Load, Opts);
recompilep1(_Erl, #file_info{mtime = To}, File, NoExec, Load, Opts) ->
recompile2(To, File, NoExec, Load, Opts).
recompile2(ObjMTime , File , NoExec , Load , Opts )
Check if file is of a later date than include files .
recompile2(ObjMTime, File, NoExec, Load, Opts) ->
IncludePath = include_opt(Opts),
case check_includes(lists:append(File, ".erl"), IncludePath, ObjMTime) of
true ->
recompile(File, NoExec, Load, Opts);
false ->
false
end.
include_opt([{i, Path} | Rest]) ->
[Path | include_opt(Rest)];
include_opt([_First | Rest]) ->
include_opt(Rest);
include_opt([]) ->
[].
recompile(File , NoExec , Load , Opts )
%% Actually recompile and load the file, depending on the flags.
Where load can be netload | load | noload
recompile(File, true, _Load, _Opts) ->
io:format("Out of date: ~s\n", [File]);
recompile(File, false, noload, Opts) ->
io:format("Recompile: ~s\n", [File]),
compile:file(File, [report_errors, report_warnings, error_summary | Opts]);
recompile(File, false, load, Opts) ->
io:format("Recompile: ~s\n", [File]),
c:c(File, Opts);
recompile(File, false, netload, Opts) ->
io:format("Recompile: ~s\n", [File]),
c:nc(File, Opts).
exists(File) ->
case file:read_file_info(File) of
{ok, _} ->
true;
_ ->
false
end.
coerce_2_list(X) when is_atom(X) ->
atom_to_list(X);
coerce_2_list(X) ->
X.
%%% If you an include file is found with a modification
%%% time larger than the modification time of the object
%%% file, return true. Otherwise return false.
check_includes(File, IncludePath, ObjMTime) ->
Path = [filename:dirname(File) | IncludePath],
case epp:open(File, Path, []) of
{ok, Epp} ->
check_includes2(Epp, File, ObjMTime);
_Error ->
false
end.
check_includes2(Epp, File, ObjMTime) ->
case epp:parse_erl_form(Epp) of
{ok, {attribute, 1, file, {File, 1}}} ->
check_includes2(Epp, File, ObjMTime);
{ok, {attribute, 1, file, {IncFile, 1}}} ->
case file:read_file_info(IncFile) of
{ok, #file_info{mtime = MTime}} when MTime > ObjMTime ->
epp:close(Epp),
true;
_ ->
check_includes2(Epp, File, ObjMTime)
end;
{ok, _} ->
check_includes2(Epp, File, ObjMTime);
{eof, _} ->
epp:close(Epp),
false;
{error, _Error} ->
check_includes2(Epp, File, ObjMTime)
end.
| null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/tool/misc/mmake.erl | erlang | 多进程编译,修改自otp/lib/tools/src/make.erl
按照次序编译每项(解决编译顺序的问题)
Mods is a list of module names (strings)
Mod.
Mod is a module name which might include '*' as wildcard
or a list of such module names
directory and the options given at command line
options given for the modules.
Any flags that are not recognixed as make flags are passed directly
to the compiler.
So for example make:all([load,debug_info]) will make everything
with the debug_info flag and load it.
处理
启动进程
等待结果
将L分割成最多包含N个子列表的列表
启动worker进程
Actually recompile and load the file, depending on the flags.
If you an include file is found with a modification
time larger than the modification time of the object
file, return true. Otherwise return false. | 解析Emakefile , 根据获取{mods , options}列表 ,
其中mods也可以包含多个模块 , 当大于1个时 ,
可以启动多个process进行编译 , 从而提高编译速度 .
-module(mmake).
-export([all/1, all/2, files/2, files/3]).
-include_lib("kernel/include/file.hrl").
-define(MakeOpts, [noexec, load, netload, noload]).
all(Worker) when is_integer(Worker) ->
all(Worker, []).
all(Worker, Options) when is_integer(Worker) ->
{MakeOpts, CompileOpts} = sort_options(Options, [], []),
case read_emakefile('Emakefile', CompileOpts) of
Files when is_list(Files) ->
do_make_files(Worker, Files, MakeOpts);
error ->
error
end.
files(Worker, Fs) ->
files(Worker, Fs, []).
files(Worker, Fs0, Options) ->
Fs = [filename:rootname(F, ".erl") || F <- Fs0],
{MakeOpts, CompileOpts} = sort_options(Options, [], []),
case get_opts_from_emakefile(Fs, 'Emakefile', CompileOpts) of
Files when is_list(Files) ->
do_make_files(Worker, Files, MakeOpts);
error -> error
end.
do_make_files(Worker, Fs, Opts) ->
io : format("worker:~p ~ " , [ Worker , Fs , Opts ] ) ,
process(Fs, Worker, lists:member(noexec, Opts), load_opt(Opts)).
sort_options([H | T], Make, Comp) ->
case lists:member(H, ?MakeOpts) of
true ->
sort_options(T, [H | Make], Comp);
false ->
sort_options(T, Make, [H | Comp])
end;
sort_options([], Make, Comp) ->
{Make, lists:reverse(Comp)}.
Reads the given Emakefile and returns a list of tuples : { Mods , Opts }
Opts is a list of options to be used when compiling Mods
Emakefile can contain elements like this :
{ Mod , } .
These elements are converted to [ { ModList , OptList } , ... ]
ModList is a list of modulenames ( strings )
read_emakefile(Emakefile, Opts) ->
case file:consult(Emakefile) of
{ok, Emake} ->
transform(Emake, Opts, [], []);
{error, enoent} ->
No Emakefile found - return all modules in current
Mods = [filename:rootname(F) || F <- filelib:wildcard("*.erl")],
[{Mods, Opts}];
{error, Other} ->
io:format("make: Trouble reading 'Emakefile':~n~p~n", [Other]),
error
end.
transform([{Mod, ModOpts} | Emake], Opts, Files, Already) ->
case expand(Mod, Already) of
[] ->
transform(Emake, Opts, Files, Already);
Mods ->
transform(Emake, Opts, [{Mods, ModOpts ++ Opts} | Files], Mods ++ Already)
end;
transform([Mod | Emake], Opts, Files, Already) ->
case expand(Mod, Already) of
[] ->
transform(Emake, Opts, Files, Already);
Mods ->
transform(Emake, Opts, [{Mods, Opts} | Files], Mods ++ Already)
end;
transform([], _Opts, Files, _Already) ->
lists:reverse(Files).
expand(Mod, Already) when is_atom(Mod) ->
expand(atom_to_list(Mod), Already);
expand(Mods, Already) when is_list(Mods), not is_integer(hd(Mods)) ->
lists:concat([expand(Mod, Already) || Mod <- Mods]);
expand(Mod, Already) ->
case lists:member($*, Mod) of
true ->
Fun = fun(F, Acc) ->
M = filename:rootname(F),
case lists:member(M, Already) of
true -> Acc;
false -> [M | Acc]
end
end,
lists:foldl(Fun, [], filelib:wildcard(Mod ++ ".erl"));
false ->
Mod2 = filename:rootname(Mod, ".erl"),
case lists:member(Mod2, Already) of
true -> [];
false -> [Mod2]
end
end.
Reads the given Emakefile to see if there are any specific compile
get_opts_from_emakefile(Mods, Emakefile, Opts) ->
case file:consult(Emakefile) of
{ok, Emake} ->
Modsandopts = transform(Emake, Opts, [], []),
ModStrings = [coerce_2_list(M) || M <- Mods],
get_opts_from_emakefile2(Modsandopts, ModStrings, Opts, []);
{error, enoent} ->
[{Mods, Opts}];
{error, Other} ->
io:format("make: Trouble reading 'Emakefile':~n~p~n", [Other]),
error
end.
get_opts_from_emakefile2([{MakefileMods, O} | Rest], Mods, Opts, Result) ->
case members(Mods, MakefileMods, [], Mods) of
{[], _} ->
get_opts_from_emakefile2(Rest, Mods, Opts, Result);
{I, RestOfMods} ->
get_opts_from_emakefile2(Rest, RestOfMods, Opts, [{I, O} | Result])
end;
get_opts_from_emakefile2([], [], _Opts, Result) ->
Result;
get_opts_from_emakefile2([], RestOfMods, Opts, Result) ->
[{RestOfMods, Opts} | Result].
members([H | T], MakefileMods, I, Rest) ->
case lists:member(H, MakefileMods) of
true ->
members(T, MakefileMods, [H | I], lists:delete(H, Rest));
false ->
members(T, MakefileMods, I, Rest)
end;
members([], _MakefileMods, I, Rest) ->
{I, Rest}.
load_opt(Opts) ->
case lists:member(netload, Opts) of
true ->
netload;
false ->
case lists:member(load, Opts) of
true ->
load;
_ ->
noload
end
end.
process([{[], _Opts} | Rest], Worker, NoExec, Load) ->
process(Rest, Worker, NoExec, Load);
process([{L, Opts} | Rest], Worker, NoExec, Load) ->
Len = length(L),
Worker2 = erlang:min(Len, Worker),
case catch do_worker(L, Opts, NoExec, Load, Worker2) of
error ->
error;
ok ->
process(Rest, Worker, NoExec, Load)
end;
process([], _Worker, _NoExec, _Load) ->
up_to_date.
worker进行编译
do_worker(L, Opts, NoExec, Load, Worker) ->
WorkerList = do_split_list(L, Worker),
io : format("worker:~p worker " , [ Worker , length(WorkerList ) ] ) ,
Ref = make_ref(),
Pids =
[begin
start_worker(E, Opts, NoExec, Load, self(), Ref)
end || E <- WorkerList],
do_wait_worker(length(Pids), Ref).
do_wait_worker(0, _Ref) ->
ok;
do_wait_worker(N, Ref) ->
receive
{ack, Ref} ->
do_wait_worker(N - 1, Ref);
{error, Ref} ->
throw(error);
{'EXIT', _P, _Reason} ->
do_wait_worker(N, Ref);
_Other ->
io:format("receive unknown msg:~p~n", [_Other]),
do_wait_worker(N, Ref)
end.
do_split_list(L, N) ->
Len = length(L),
每个列表的元素数
LLen = (Len + N - 1) div N,
do_split_list(L, LLen, []).
do_split_list([], _N, Acc) ->
lists:reverse(Acc);
do_split_list(L, N, Acc) ->
{L2, L3} = lists:split(erlang:min(length(L), N), L),
do_split_list(L3, N, [L2 | Acc]).
start_worker(L, Opts, NoExec, Load, Parent, Ref) ->
Fun =
fun() ->
[begin
case recompilep(coerce_2_list(F), NoExec, Load, Opts) of
error ->
Parent ! {error, Ref},
exit(error);
_ ->
ok
end
end || F <- L],
Parent ! {ack, Ref}
end,
spawn_link(Fun).
recompilep(File, NoExec, Load, Opts) ->
ObjName = lists:append(filename:basename(File),
code:objfile_extension()),
ObjFile = case lists:keysearch(outdir, 1, Opts) of
{value, {outdir, OutDir}} ->
filename:join(coerce_2_list(OutDir), ObjName);
false ->
ObjName
end,
case exists(ObjFile) of
true ->
recompilep1(File, NoExec, Load, Opts, ObjFile);
false ->
recompile(File, NoExec, Load, Opts)
end.
recompilep1(File, NoExec, Load, Opts, ObjFile) ->
{ok, Erl} = file:read_file_info(lists:append(File, ".erl")),
{ok, Obj} = file:read_file_info(ObjFile),
recompilep1(Erl, Obj, File, NoExec, Load, Opts).
recompilep1(#file_info{mtime = Te},
#file_info{mtime = To}, File, NoExec, Load, Opts) when Te > To ->
recompile(File, NoExec, Load, Opts);
recompilep1(_Erl, #file_info{mtime = To}, File, NoExec, Load, Opts) ->
recompile2(To, File, NoExec, Load, Opts).
recompile2(ObjMTime , File , NoExec , Load , Opts )
Check if file is of a later date than include files .
recompile2(ObjMTime, File, NoExec, Load, Opts) ->
IncludePath = include_opt(Opts),
case check_includes(lists:append(File, ".erl"), IncludePath, ObjMTime) of
true ->
recompile(File, NoExec, Load, Opts);
false ->
false
end.
include_opt([{i, Path} | Rest]) ->
[Path | include_opt(Rest)];
include_opt([_First | Rest]) ->
include_opt(Rest);
include_opt([]) ->
[].
recompile(File , NoExec , Load , Opts )
Where load can be netload | load | noload
recompile(File, true, _Load, _Opts) ->
io:format("Out of date: ~s\n", [File]);
recompile(File, false, noload, Opts) ->
io:format("Recompile: ~s\n", [File]),
compile:file(File, [report_errors, report_warnings, error_summary | Opts]);
recompile(File, false, load, Opts) ->
io:format("Recompile: ~s\n", [File]),
c:c(File, Opts);
recompile(File, false, netload, Opts) ->
io:format("Recompile: ~s\n", [File]),
c:nc(File, Opts).
exists(File) ->
case file:read_file_info(File) of
{ok, _} ->
true;
_ ->
false
end.
coerce_2_list(X) when is_atom(X) ->
atom_to_list(X);
coerce_2_list(X) ->
X.
check_includes(File, IncludePath, ObjMTime) ->
Path = [filename:dirname(File) | IncludePath],
case epp:open(File, Path, []) of
{ok, Epp} ->
check_includes2(Epp, File, ObjMTime);
_Error ->
false
end.
check_includes2(Epp, File, ObjMTime) ->
case epp:parse_erl_form(Epp) of
{ok, {attribute, 1, file, {File, 1}}} ->
check_includes2(Epp, File, ObjMTime);
{ok, {attribute, 1, file, {IncFile, 1}}} ->
case file:read_file_info(IncFile) of
{ok, #file_info{mtime = MTime}} when MTime > ObjMTime ->
epp:close(Epp),
true;
_ ->
check_includes2(Epp, File, ObjMTime)
end;
{ok, _} ->
check_includes2(Epp, File, ObjMTime);
{eof, _} ->
epp:close(Epp),
false;
{error, _Error} ->
check_includes2(Epp, File, ObjMTime)
end.
|
2c398c99233c1b2658b35ae5b46ebb5d60775f49b81fd34de3a9129750551355 | larcenists/larceny | quicksort.scm | This is probably from MS thesis .
The quick-1 benchmark . ( Figure 35 , page 132 . )
(import (scheme base)
(scheme read)
(scheme write)
(scheme time))
(define (quick-1 v less?)
(define (helper left right)
(if (< left right)
(let ((median (partition v left right less?)))
(if (< (- median left) (- right median))
(begin (helper left (- median 1))
(helper (+ median 1) right))
(begin (helper (+ median 1) right)
(helper left (- median 1)))))
v))
(helper 0 (- (vector-length v) 1)))
(define (partition v left right less?)
(let ((mid (vector-ref v right)))
(define (uploop i)
(let ((i (+ i 1)))
(if (and (< i right) (less? (vector-ref v i) mid))
(uploop i)
i)))
(define (downloop j)
(let ((j (- j 1)))
(if (and (> j left) (less? mid (vector-ref v j)))
(downloop j)
j)))
(define (ploop i j)
(let* ((i (uploop i))
(j (downloop j)))
(let ((tmp (vector-ref v i)))
(vector-set! v i (vector-ref v j))
(vector-set! v j tmp)
(if (< i j)
(ploop i j)
(begin (vector-set! v j (vector-ref v i))
(vector-set! v i (vector-ref v right))
(vector-set! v right tmp)
i)))))
(ploop (- left 1) right)))
Hansen 's original code for this benchmark used Larceny 's
predefined random procedure . When modified
Hansen 's benchmark for the Gambit benchmark suite , however ,
;;; he added a specific random number generator taken from an
article in CACM . Feeley 's generator used bignums , and was
;;; extremely slow, causing the Gambit version of this benchmark
;;; to spend nearly all of its time generating the random numbers.
;;; For a benchmark called quicksort to become a bignum benchmark
was very misleading , so left Feeley 's version of this
benchmark out of the Larceny benchmark suite .
;;;
;;; The following random number generator is much better and
;;; faster than the one used in the Gambit benchmark. See
;;;
;;; -27/mail-archive/msg00000.html
;;; /~lucier/random/random.scm
A uniform [ 0,1 ] random number generator ; is
generator from his paper
;;; "Good parameters and implementations for combined multiple
;;; recursive random number generators"
available at his web site /~lecuyer
(define seed-set! #f)
(define seed-ref #f)
(define random-flonum #f)
(let ((norm 2.328306549295728e-10)
(m1 4294967087.0)
(m2 4294944443.0)
(a12 1403580.0)
(a13n 810728.0)
(a21 527612.0)
(a23n 1370589.0)
(seed (vector 1.0 0.0 0.0 1.0 0.0 0.0))) ; will be mutated
; uses no conversions between flonums and fixnums.
(set! random-flonum
(lambda ()
(let ((seed seed)) ; make it local
(let ((p1 (- (* a12 (vector-ref seed 1))
(* a13n (vector-ref seed 0))))
(p2 (- (* a21 (vector-ref seed 5))
(* a23n (vector-ref seed 3)))))
(let ((k1 (truncate (/ p1 m1)))
(k2 (truncate (/ p2 m2)))
(ignore1 (vector-set! seed 0 (vector-ref seed 1)))
(ignore3 (vector-set! seed 3 (vector-ref seed 4))))
(let ((p1 (- p1 (* k1 m1)))
(p2 (- p2 (* k2 m2)))
(ignore2 (vector-set! seed 1 (vector-ref seed 2)))
(ignore4 (vector-set! seed 4 (vector-ref seed 5))))
(let ((p1 (if (< p1 0.0) (+ p1 m1) p1))
(p2 (if (< p2 0.0) (+ p2 m2) p2)))
(vector-set! seed 2 p1)
(vector-set! seed 5 p2)
(if (<= p1 p2)
(* norm (+ (- p1 p2) m1))
(* norm (- p1 p2))))))))))
(set! seed-ref (lambda () (vector->list seed)))
(set! seed-set! (lambda l (set! seed (list->vector l)))))
(define (random n)
(exact (truncate (* (inexact n) (random-flonum)))))
;;; Even with the improved random number generator,
;;; this benchmark still spends almost all of its time
;;; generating the random vector. To make this a true
;;; quicksort benchmark, we generate a relatively small
;;; random vector and then sort many copies of it.
(define (main)
(let* ((count (read))
(input1 (read))
(input2 (read))
(output (read))
(s3 (number->string count))
(s2 (number->string input2))
(s1 (number->string input1))
(name "quicksort")
(n (hide count input1))
(r (hide count input2))
(less? (hide count (lambda (x y) (< x y))))
(v (make-vector n)))
(do ((i 0 (+ i 1)))
((= i n))
(vector-set! v i (random r)))
(run-r7rs-benchmark
(string-append name ":" s1 ":" s3)
count
(lambda () (quick-1 (vector-map values v) less?))
(lambda (v)
(call-with-current-continuation
(lambda (return)
(do ((i 1 (+ i 1)))
((= i (vector-length v))
#t)
(if (not (<= (vector-ref v (- i 1))
(vector-ref v i)))
(return #f)))))))))
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/Benchmarking/R7RS/src/quicksort.scm | scheme | he added a specific random number generator taken from an
extremely slow, causing the Gambit version of this benchmark
to spend nearly all of its time generating the random numbers.
For a benchmark called quicksort to become a bignum benchmark
The following random number generator is much better and
faster than the one used in the Gambit benchmark. See
-27/mail-archive/msg00000.html
/~lucier/random/random.scm
is
"Good parameters and implementations for combined multiple
recursive random number generators"
will be mutated
uses no conversions between flonums and fixnums.
make it local
Even with the improved random number generator,
this benchmark still spends almost all of its time
generating the random vector. To make this a true
quicksort benchmark, we generate a relatively small
random vector and then sort many copies of it. | This is probably from MS thesis .
The quick-1 benchmark . ( Figure 35 , page 132 . )
(import (scheme base)
(scheme read)
(scheme write)
(scheme time))
(define (quick-1 v less?)
(define (helper left right)
(if (< left right)
(let ((median (partition v left right less?)))
(if (< (- median left) (- right median))
(begin (helper left (- median 1))
(helper (+ median 1) right))
(begin (helper (+ median 1) right)
(helper left (- median 1)))))
v))
(helper 0 (- (vector-length v) 1)))
(define (partition v left right less?)
(let ((mid (vector-ref v right)))
(define (uploop i)
(let ((i (+ i 1)))
(if (and (< i right) (less? (vector-ref v i) mid))
(uploop i)
i)))
(define (downloop j)
(let ((j (- j 1)))
(if (and (> j left) (less? mid (vector-ref v j)))
(downloop j)
j)))
(define (ploop i j)
(let* ((i (uploop i))
(j (downloop j)))
(let ((tmp (vector-ref v i)))
(vector-set! v i (vector-ref v j))
(vector-set! v j tmp)
(if (< i j)
(ploop i j)
(begin (vector-set! v j (vector-ref v i))
(vector-set! v i (vector-ref v right))
(vector-set! v right tmp)
i)))))
(ploop (- left 1) right)))
Hansen 's original code for this benchmark used Larceny 's
predefined random procedure . When modified
Hansen 's benchmark for the Gambit benchmark suite , however ,
article in CACM . Feeley 's generator used bignums , and was
was very misleading , so left Feeley 's version of this
benchmark out of the Larceny benchmark suite .
generator from his paper
available at his web site /~lecuyer
(define seed-set! #f)
(define seed-ref #f)
(define random-flonum #f)
(let ((norm 2.328306549295728e-10)
(m1 4294967087.0)
(m2 4294944443.0)
(a12 1403580.0)
(a13n 810728.0)
(a21 527612.0)
(a23n 1370589.0)
(set! random-flonum
(lambda ()
(let ((p1 (- (* a12 (vector-ref seed 1))
(* a13n (vector-ref seed 0))))
(p2 (- (* a21 (vector-ref seed 5))
(* a23n (vector-ref seed 3)))))
(let ((k1 (truncate (/ p1 m1)))
(k2 (truncate (/ p2 m2)))
(ignore1 (vector-set! seed 0 (vector-ref seed 1)))
(ignore3 (vector-set! seed 3 (vector-ref seed 4))))
(let ((p1 (- p1 (* k1 m1)))
(p2 (- p2 (* k2 m2)))
(ignore2 (vector-set! seed 1 (vector-ref seed 2)))
(ignore4 (vector-set! seed 4 (vector-ref seed 5))))
(let ((p1 (if (< p1 0.0) (+ p1 m1) p1))
(p2 (if (< p2 0.0) (+ p2 m2) p2)))
(vector-set! seed 2 p1)
(vector-set! seed 5 p2)
(if (<= p1 p2)
(* norm (+ (- p1 p2) m1))
(* norm (- p1 p2))))))))))
(set! seed-ref (lambda () (vector->list seed)))
(set! seed-set! (lambda l (set! seed (list->vector l)))))
(define (random n)
(exact (truncate (* (inexact n) (random-flonum)))))
(define (main)
(let* ((count (read))
(input1 (read))
(input2 (read))
(output (read))
(s3 (number->string count))
(s2 (number->string input2))
(s1 (number->string input1))
(name "quicksort")
(n (hide count input1))
(r (hide count input2))
(less? (hide count (lambda (x y) (< x y))))
(v (make-vector n)))
(do ((i 0 (+ i 1)))
((= i n))
(vector-set! v i (random r)))
(run-r7rs-benchmark
(string-append name ":" s1 ":" s3)
count
(lambda () (quick-1 (vector-map values v) less?))
(lambda (v)
(call-with-current-continuation
(lambda (return)
(do ((i 1 (+ i 1)))
((= i (vector-length v))
#t)
(if (not (<= (vector-ref v (- i 1))
(vector-ref v i)))
(return #f)))))))))
|
c772990b1d133cff695ffb40f63b18a067f73611b21cd5fa4708350c86655556 | pascal-knodel/haskell-craft | E'12'26.hs | --
--
--
------------------
Exercise 12.26 .
------------------
--
--
--
module E'12'26 where
| null | https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/_/links/E'12'26.hs | haskell |
----------------
----------------
| Exercise 12.26 .
module E'12'26 where
|
4fe77bc9c54501dcd30e2b69251e6ee20c3250051a37a03735b83078b2de8b65 | flipstone/orville | Delete.hs | # LANGUAGE GeneralizedNewtypeDeriving #
module Orville.PostgreSQL.Internal.Expr.Delete
( DeleteExpr,
deleteExpr,
)
where
import Data.Maybe (catMaybes)
import Orville.PostgreSQL.Internal.Expr.Name (Qualified, TableName)
import Orville.PostgreSQL.Internal.Expr.ReturningExpr (ReturningExpr)
import Orville.PostgreSQL.Internal.Expr.Where (WhereClause)
import qualified Orville.PostgreSQL.Internal.RawSql as RawSql
newtype DeleteExpr
= DeleteExpr RawSql.RawSql
deriving (RawSql.SqlExpression)
deleteExpr ::
Qualified TableName ->
Maybe WhereClause ->
Maybe ReturningExpr ->
DeleteExpr
deleteExpr tableName maybeWhereClause maybeReturningExpr =
DeleteExpr $
RawSql.intercalate RawSql.space $
catMaybes
[ Just $ RawSql.fromString "DELETE FROM"
, Just $ RawSql.toRawSql tableName
, fmap RawSql.toRawSql maybeWhereClause
, fmap RawSql.toRawSql maybeReturningExpr
]
| null | https://raw.githubusercontent.com/flipstone/orville/a018288c5d3fe8c567b156b980d9f8aab2d06b28/orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/Expr/Delete.hs | haskell | # LANGUAGE GeneralizedNewtypeDeriving #
module Orville.PostgreSQL.Internal.Expr.Delete
( DeleteExpr,
deleteExpr,
)
where
import Data.Maybe (catMaybes)
import Orville.PostgreSQL.Internal.Expr.Name (Qualified, TableName)
import Orville.PostgreSQL.Internal.Expr.ReturningExpr (ReturningExpr)
import Orville.PostgreSQL.Internal.Expr.Where (WhereClause)
import qualified Orville.PostgreSQL.Internal.RawSql as RawSql
newtype DeleteExpr
= DeleteExpr RawSql.RawSql
deriving (RawSql.SqlExpression)
deleteExpr ::
Qualified TableName ->
Maybe WhereClause ->
Maybe ReturningExpr ->
DeleteExpr
deleteExpr tableName maybeWhereClause maybeReturningExpr =
DeleteExpr $
RawSql.intercalate RawSql.space $
catMaybes
[ Just $ RawSql.fromString "DELETE FROM"
, Just $ RawSql.toRawSql tableName
, fmap RawSql.toRawSql maybeWhereClause
, fmap RawSql.toRawSql maybeReturningExpr
]
| |
e45734b1c31687be0fb9934cf5708db86be8f0b660b38bcbbbdb166aa76cc0ab | chaw/r7rs-libs | json-test.sps | ;; Some test cases for the (rebottled json) library testing read/write of JSON format
;; -- this needs some more tests
(import (scheme base)
(rebottled json)
(srfi 64))
(define (test-write val res)
(test-equal res
(parameterize ((current-output-port (open-output-string)))
(json-write val)
(get-output-string (current-output-port)))))
(define (test-read val res)
(test-equal res
(json-read (open-input-string val))))
(test-begin "rebottled-json")
(for-each (lambda (res-val)
(test-write (car res-val) (cdr res-val))
(test-read (cdr res-val) (car res-val)))
(list ; Scheme value -> JSON string
(cons 3 "3")
(cons (list 1 2 3) "[1, 2, 3]")
(cons #f "false")
(cons #t "true")
(cons (vector (cons "a" 4) (cons "b" 5) (cons "c" 6)) "{\"a\": 4, \"b\": 5, \"c\": 6}")
))
(test-assert (and (symbol? (json-read (open-input-string "null")))
(eq? 'null (json-read (open-input-string "null")))))
(test-write 'null "\"null\"")
(parameterize ((current-output-port (open-output-string)))
(test-error (json-write (vector 4 5 6)))
(test-error (json-write (vector (list 4 'a))))
)
(test-end)
| null | https://raw.githubusercontent.com/chaw/r7rs-libs/b8b625c36b040ff3d4b723e4346629a8a0e8d6c2/rebottled-tests/json-test.sps | scheme | Some test cases for the (rebottled json) library testing read/write of JSON format
-- this needs some more tests
Scheme value -> JSON string |
(import (scheme base)
(rebottled json)
(srfi 64))
(define (test-write val res)
(test-equal res
(parameterize ((current-output-port (open-output-string)))
(json-write val)
(get-output-string (current-output-port)))))
(define (test-read val res)
(test-equal res
(json-read (open-input-string val))))
(test-begin "rebottled-json")
(for-each (lambda (res-val)
(test-write (car res-val) (cdr res-val))
(test-read (cdr res-val) (car res-val)))
(cons 3 "3")
(cons (list 1 2 3) "[1, 2, 3]")
(cons #f "false")
(cons #t "true")
(cons (vector (cons "a" 4) (cons "b" 5) (cons "c" 6)) "{\"a\": 4, \"b\": 5, \"c\": 6}")
))
(test-assert (and (symbol? (json-read (open-input-string "null")))
(eq? 'null (json-read (open-input-string "null")))))
(test-write 'null "\"null\"")
(parameterize ((current-output-port (open-output-string)))
(test-error (json-write (vector 4 5 6)))
(test-error (json-write (vector (list 4 'a))))
)
(test-end)
|
d5192c8b63d3ab1733dee4324d995de4a474c4a34c7aa63508f54a3dc6513f6c | AccelerateHS/accelerate-examples | Util.hs | -- |
-- Module: : Data.Array.Accelerate.Examples.Internal.Util
Copyright : [ 2014 .. 2020 ]
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
module Data.Array.Accelerate.Examples.Internal.Util
where
import Numeric
import Data.List
import Data.Array.Accelerate as A ( Z(..), Elt, Scalar, fromList )
import Prelude as P
infixr 9 $$
($$) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
($$) g f x y = g (f x y)
scalar :: Elt a => a -> Scalar a
scalar x = fromList Z [x]
-- | Show a floating point number in scientific notation with a specific base.
--
showFFloatSIBase :: P.RealFloat a => Maybe Int -> a -> a -> ShowS
showFFloatSIBase p b n
= showString
. nubBy (\x y -> x == ' ' && y == ' ')
$ showFFloat p n' [ ' ', si_unit ]
where
n' = n / (b P.^^ (pow-4))
pow = P.max 0 . P.min 8 . (+) 4 . P.floor $ P.logBase b n
si_unit = "pnµm kMGT" P.!! pow
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-examples/a973ee423b5eadda6ef2e2504d2383f625e49821/lib/Data/Array/Accelerate/Examples/Internal/Util.hs | haskell | |
Module: : Data.Array.Accelerate.Examples.Internal.Util
License : BSD3
Stability : experimental
| Show a floating point number in scientific notation with a specific base.
| Copyright : [ 2014 .. 2020 ]
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Data.Array.Accelerate.Examples.Internal.Util
where
import Numeric
import Data.List
import Data.Array.Accelerate as A ( Z(..), Elt, Scalar, fromList )
import Prelude as P
infixr 9 $$
($$) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
($$) g f x y = g (f x y)
scalar :: Elt a => a -> Scalar a
scalar x = fromList Z [x]
showFFloatSIBase :: P.RealFloat a => Maybe Int -> a -> a -> ShowS
showFFloatSIBase p b n
= showString
. nubBy (\x y -> x == ' ' && y == ' ')
$ showFFloat p n' [ ' ', si_unit ]
where
n' = n / (b P.^^ (pow-4))
pow = P.max 0 . P.min 8 . (+) 4 . P.floor $ P.logBase b n
si_unit = "pnµm kMGT" P.!! pow
|
ebabf4a19ef1ee22819481e01934ad7a189380196d133bf121d6dd0bdd23fecd | wavewave/hoodle | Attoparsec.hs | {-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - unused - do - bind #
module Text.Hoodlet.Parse.Attoparsec where
import Control.Applicative ((<|>))
import Data.Attoparsec.ByteString.Char8
( Parser,
char,
string,
try,
(<?>),
)
import qualified Data.ByteString.Char8 as B
import qualified Data.Hoodle.Simple as H
import Text.Hoodle.Parse.Attoparsec
( hoodleversion,
img,
link,
onestroke,
svgObj,
trim,
xmlheader,
)
-- |
hoodlet :: Parser H.Item
hoodlet = do
trim
xmlheader <?> "xmlheader"
trim
hoodletheader <?> "hoodletheader"
trim
itm <- try (H.ItemStroke <$> onestroke) <|> try img <|> try svgObj <|> link
trim
string "</hoodlet>"
return itm
hoodletheader :: Parser B.ByteString
hoodletheader = do
string "<hoodlet"
trim
v <- hoodleversion
trim
char '>'
return v
| null | https://raw.githubusercontent.com/wavewave/hoodle/fa7481d14a53733b2f6ae9debc95357d904a943c/parser/src/Text/Hoodlet/Parse/Attoparsec.hs | haskell | # LANGUAGE OverloadedStrings #
| | # OPTIONS_GHC -fno - warn - unused - do - bind #
module Text.Hoodlet.Parse.Attoparsec where
import Control.Applicative ((<|>))
import Data.Attoparsec.ByteString.Char8
( Parser,
char,
string,
try,
(<?>),
)
import qualified Data.ByteString.Char8 as B
import qualified Data.Hoodle.Simple as H
import Text.Hoodle.Parse.Attoparsec
( hoodleversion,
img,
link,
onestroke,
svgObj,
trim,
xmlheader,
)
hoodlet :: Parser H.Item
hoodlet = do
trim
xmlheader <?> "xmlheader"
trim
hoodletheader <?> "hoodletheader"
trim
itm <- try (H.ItemStroke <$> onestroke) <|> try img <|> try svgObj <|> link
trim
string "</hoodlet>"
return itm
hoodletheader :: Parser B.ByteString
hoodletheader = do
string "<hoodlet"
trim
v <- hoodleversion
trim
char '>'
return v
|
70d424674a7bc2fc176bf9efbad554da6e429c2af9f7fb0a50edbf7bfa68693a | mbutterick/beautiful-racket | test.rkt | #lang tacogram-demo
##$%#$%#$#$#$$##$%#$%#$#$#$$##$%#$#$#$%#$$##$#$#$%#$%%$#%#$%#$#$%%$##$#$%%#$%%$##$#$%%#$%%$#%%%%#$%%$##$#$#$#$#$%#$$#%%%#$%%%$#%%%%#$%%$##$%#$#$%%%$##$#$%%#$%%$##$#$%#$#$%%$##$%#$#$#$%#$$##$%#$%#$#$#$$##$#$#$%#$%#$$#%%#$%#$%#$$##$#$#$#$#$%#$$#%#$#$#$%%#$$##$#$#$#$#$%#$$##$#$#$%#$%#$$##$%#$%#$%#$$##$#$#$#$#$%#$$##$%#$#$%%#$$##$#$#$#$#$%#$$##$#$#$%#$%#$$#%#$%%#$%#$$##$#$#$#$#$%#$$##$#$#$%%%%$#%#$#$%#$%#$$#%#$#$%#$%#$$#%#$#$%#$%#$$ | null | https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/tacogram-demo/test.rkt | racket | #lang tacogram-demo
##$%#$%#$#$#$$##$%#$%#$#$#$$##$%#$#$#$%#$$##$#$#$%#$%%$#%#$%#$#$%%$##$#$%%#$%%$##$#$%%#$%%$#%%%%#$%%$##$#$#$#$#$%#$$#%%%#$%%%$#%%%%#$%%$##$%#$#$%%%$##$#$%%#$%%$##$#$%#$#$%%$##$%#$#$#$%#$$##$%#$%#$#$#$$##$#$#$%#$%#$$#%%#$%#$%#$$##$#$#$#$#$%#$$#%#$#$#$%%#$$##$#$#$#$#$%#$$##$#$#$%#$%#$$##$%#$%#$%#$$##$#$#$#$#$%#$$##$%#$#$%%#$$##$#$#$#$#$%#$$##$#$#$%#$%#$$#%#$%%#$%#$$##$#$#$#$#$%#$$##$#$#$%%%%$#%#$#$%#$%#$$#%#$#$%#$%#$$#%#$#$%#$%#$$ | |
9e05debdd34efd3176321d09cfec13b8b4e374116b5361c970dece7a9f109182 | shirok/Gauche | serializer.scm | SXML serializer into XML and HTML
;
; Partial conformance with
; [1] XSLT 2.0 and XQuery 1.0 Serialization
W3C Candidate Recommendation 3 November 2005
; -xslt-xquery-serialization-20051103/
;
; This software is in Public Domain.
IT IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND .
;
; Please send bug reports and comments to:
; Dmitry Lizorkin
Prefix for global identifiers in this module is ` srl : '
; short for "serialization"
; Requires: function `filter' from SRFI-1
; syntax `cond-expand' from SRFI-0
In particular , for PLT , ` filter ' can be acquired as follows :
;(require (lib "filter.ss" "srfi/1"))
;==========================================================================
; Basic
; `map' and `append' in a single pass:
( srl : map - append func lst ) = ( apply append ( map func lst ) )
; A simplified analogue of `map-union' from "sxpathlib.scm"
(define (srl:map-append func lst)
(if (null? lst)
lst
(append (func (car lst))
(srl:map-append func (cdr lst)))))
procedure srl : apply - string - append : : STR - LST - > STRING
str - lst : : = ( string )
Concatenates ` str - lst ' members into a single string
( srl : apply - string - append str - lst ) = ( apply string - append str - lst )
;; (cond-expand
;; (chicken
In Chicken , procedures are generally limited to 126 arguments
; -with-current-continuation.org/
Due to this Chicken limitation , we can not apply ` string - append ' directly
; for a potentially long `str-lst'
Similar to R5RS ' list - tail ' but returns the new list consisting of the
; first 'k' members of 'lst'
( define ( srl : list - head )
( if ( or ( null ? lst ) ( zero ? k ) )
;; '()
( cons ( car lst ) ( srl : list - head ( cdr lst ) ( - k 1 ) ) ) ) )
Because of Chicken 126 - argument limitation , I do not care of intermediate
; garbage produced in the following solution:
( define ( srl : apply - string - append str - lst )
;; (cond
;; ((null? str-lst) "")
( ( null ? ( ) ) ( car str - lst ) )
( else ; at least two members
( let ( ( middle ( inexact->exact ( round ( / ( length str - lst ) 2 ) ) ) ) )
;; (string-append
( srl : apply - string - append ( srl : list - head str - lst middle ) )
( srl : apply - string - append ( list - tail str - lst middle ) ) ) ) ) ) )
;; )
;; (else
(define (srl:apply-string-append str-lst)
(apply string-append str-lst))
;; ))
Analogue of ` assoc '
; However, search is performed by `cdr' of each alist member and `string=?' is
; used for comparison
(define (srl:assoc-cdr-string= item alist)
(cond
((null? alist) #f)
((string=? (cdar alist) item) (car alist))
(else (srl:assoc-cdr-string= item (cdr alist)))))
Analogue of ` member ' for strings that uses case insensitive comparison
(define (srl:member-ci str lst)
(cond
((null? lst) #f)
((string-ci=? str (car lst)) lst)
(else (srl:member-ci str (cdr lst)))))
Analogue of ` member '
The end of the ` lst ' is returned , from the first member that satisfies
; the `pred?'
(define (srl:mem-pred pred? lst)
(cond
((null? lst) #f)
((pred? (car lst)) lst)
(else (srl:mem-pred pred? (cdr lst)))))
;-------------------------------------------------
; Borrowed from "char-encoding.scm"
; The newline character
(cond-expand
((or scheme48 scsh)
(define srl:char-nl (ascii->char 10)))
(else
(define srl:char-nl (integer->char 10))))
; A string consisting of a single newline character
(define srl:newline (string srl:char-nl))
;-------------------------------------------------
; Borrowed from "sxpathlib.scm"
; A simplified implementation of `select-kids' is sufficienf for the serializer
(define (srl:select-kids test-pred?)
(lambda (node) ; node or node-set
(cond
((null? node) node)
((not (pair? node)) '()) ; No children
((symbol? (car node))
(filter test-pred? (cdr node)))
(else
(srl:map-append (srl:select-kids test-pred?) node)))))
;-------------------------------------------------
; Borrowed from "modif.scm"
Separates the list into two lists with respect to the predicate
Returns : ( values )
; res-lst1 - contains all members from the input lst that satisfy the pred?
res - lst2 - contains the remaining members of the input lst
(define (srl:separate-list pred? lst)
(let loop ((lst lst)
(satisfy '())
(rest '()))
(cond
((null? lst)
(values (reverse satisfy) (reverse rest)))
the first member satisfies the predicate
(loop (cdr lst)
(cons (car lst) satisfy) rest))
(else
(loop (cdr lst)
satisfy (cons (car lst) rest))))))
;-------------------------------------------------
; Borrowed from "fragments.scm"
; A simplified implementation of `sxml:clean-fragments'
(define (srl:clean-fragments fragments)
(reverse
(let loop ((fragments fragments) (result '()))
(cond
((null? fragments) result)
((null? (car fragments)) (loop (cdr fragments) result))
((pair? (car fragments))
(loop (cdr fragments)
(loop (car fragments) result)))
(else
(loop (cdr fragments)
(cons (car fragments) result)))))))
; A very much simplified analogue of `sxml:display-fragments' for fragments
that have no more than two levels of nesting
; fragments-level2 ::= (listof fragments-level1)
fragments - level1 : : = string | ( listof string )
(define (srl:display-fragments-2nesting fragments-level2 port)
(for-each
(lambda (level1)
(if (pair? level1)
(for-each (lambda (x) (display x port))
level1)
(display level1 port)))
fragments-level2))
;==========================================================================
; Helper SXML utilities
Splits an SXML ` name ' into namespace id / uri and local part
; Returns: (cons namespace-id local-part)
; local-part - string
; namespace-id - string or #f if the `name' does not have a prefix
(define (srl:split-name name)
(let* ((name-str (symbol->string name))
(lng (string-length name-str)))
(let iter ((i (- lng 1)))
(cond
((< i 0) ; name scanned, #\: not found
(cons #f name-str))
((char=? (string-ref name-str i) #\:)
(cons (substring name-str 0 i)
(substring name-str (+ i 1) lng)))
(else
(iter (- i 1)))))))
Converts SXML atomic object to a string . Keeps non - atomic object unchanged .
A simplified analogue of applying the XPath ` string ( . ) ' function to atomic
; object.
(define (srl:atomic->string obj)
(cond
((or (pair? obj) ; non-atomic type
(string? obj)) obj)
((number? obj)
(number->string obj))
((boolean? obj)
(if obj "true" "false"))
(else ; unexpected type
; ATTENTION: should probably raise an error here
obj)))
Whether an SXML element is empty
(define (srl:empty-elem? elem)
(or (null? (cdr elem)) ; just the name
(and (null? (cddr elem)) ; just the name and attributes
(pair? (cadr elem)) (eq? (caadr elem) '@))
name , attributes , and SXML 2.X aux - list
(null? (cdddr elem))
(pair? (caddr elem)) (eq? (caaddr elem) '@@))))
;-------------------------------------------------
Handling SXML namespaces
< namespace - assoc > is defined in the SXML specification as
; <namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
; Conventional namespace prefix referred to in XML-related specifications
; These prefixes are used for serializing the corresponding namespace URIs by
; default, unless a different prefix is supplied
(define srl:conventional-ns-prefixes
'((dc . "/")
(fo . "")
(rdf . "-rdf-syntax-ns#")
(rng . "")
(xlink . "")
(xqx . "")
(xsd . "")
(xsi . "-instance")
(xsl . "")))
Returns ( listof < namespace - assoc > ) for the given SXML element
(define (srl:namespace-assoc-for-elem elem)
((srl:select-kids (lambda (node) (pair? node)))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
(append
compatibility with SXML 3.0
(lambda (node) (and (pair? node) (eq? (car node) '@))))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '@))))
elem))
compatibility with SXML 2.X
(lambda (node) (and (pair? node) (eq? (car node) '@@))))
elem)))))
Returns ( listof < namespace - assoc > ) for the SXML document node
(define (srl:ns-assoc-for-top doc)
((srl:select-kids (lambda (node) (pair? node)))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
((srl:select-kids
(lambda (node)
After sequence normalization [ 1 ] , the SXML 3.0 aux - list is used
; at the top-level
(and (pair? node) (eq? (car node) '@))))
doc))))
; Extract original prefix-binding from `namespace-assoc-lst'
namespace - assoc - lst : : = ( listof < namespace - assoc > )
; <namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
Returns : ( listof ( cons original - prefix " URI " ) )
(define (srl:extract-original-prefix-binding namespace-assoc-lst)
(map
(lambda (triple) (cons (caddr triple) (cadr triple)))
(filter ; specifies original prefix
(lambda (memb) (= (length memb) 3))
namespace-assoc-lst)))
;-------------------------------------------------
; Handling xml:space attribute
; Returns the new value of `space-preserve?' in accordance with the value of
xml : space attribute probably presented for the given SXML element ` elem '
space - preserve ? : : = # t | # f - whether the SXML subtree inherits the
; xml:space attribute with the value "preserve"
(define (srl:update-space-specifier elem space-preserve?)
(let ((xml-space-val
((srl:select-kids string?)
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) 'xml:space))))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '@))))
elem)))))
(cond
((null? xml-space-val) ; no xml:space attribute
space-preserve?)
((string=? (car xml-space-val) "preserve")
#t)
((string=? (car xml-space-val) "default")
#f)
(else space-preserve?))))
;==========================================================================
; Sequence normalization
Sect . 2 in [ 1 ]
Performs sequence normalization in accordance with [ 1 ]
Returns the SXML document node
(define (srl:normalize-sequence node-or-sequence)
(letrec
((normaliz-step-1
; "If the sequence that is input to serialization is empty, create a
sequence S1 that consists of a zero - length string . Otherwise , copy
; each item in the sequence that is input to serialization to create
the new sequence S1 . " [ 1 ]
(lambda (node-or-seq)
(cond
((null? node-or-seq) ; empty sequence
'(""))
; Effect of `as-nodeset' from "sxpathlib.scm"
((or (not (pair? node-or-seq)) ; single item
(symbol? (car node-or-seq))) ; single node
(list node-or-seq))
(else
node-or-seq))))
(normaliz-step-2
; "For each item in S1, if the item is atomic, obtain the lexical
; representation of the item by casting it to an xs:string and copy
; the string representation to the new sequence; otherwise, copy the
; item, which will be a node, to the new sequence. The new sequence is
S2 . " [ 1 ]
(lambda (seq)
(map
(lambda (item) (srl:atomic->string item))
seq)))
(normaliz-step-3
; "For each subsequence of adjacent strings in S2, copy a single
; string to the new sequence equal to the values of the strings in the
; subsequence concatenated in order, each separated by a single space.
; Copy all other items to the new sequence. The new sequence is S3."
(lambda (seq)
(let loop ((src (reverse seq))
(res '()))
(cond
((null? src)
res)
((string? (car src))
(let adjacent ((src (cdr src))
(adj-strs (list (car src))))
(cond
((null? src) ; source sequence is over
(cons (srl:apply-string-append adj-strs) res))
((string? (car src))
(adjacent (cdr src)
(cons (car src) (cons " " adj-strs))))
(else
(loop (cdr src)
(cons (car src)
(cons (srl:apply-string-append adj-strs)
res)))))))
(else
(loop (cdr src)
(cons (car src) res)))))))
Step 4 from [ 1 ] is redundant for SXML , since SXML text nodes are not
; distinquished from strings
(normaliz-step-5
; "For each item in S4, if the item is a document node, copy its
; children to the new sequence; otherwise, copy the item to the new
sequence . The new sequence is S5 . " [ 1 ]
(lambda (seq)
(cond
((null? seq)
seq)
((and (pair? (car seq)) (eq? (caar seq) '*TOP*))
; Document node
(append (cdar seq) (normaliz-step-5 (cdr seq))))
(else
(cons (car seq) (normaliz-step-5 (cdr seq)))))))
(normaliz-step-6
; "For each subsequence of adjacent text nodes in S5, copy a single
; text node to the new sequence equal to the values of the text nodes
; in the subsequence concatenated in order. Any text nodes with values
of zero length are dropped . Copy all other items to the new sequence .
The new sequence is S6 . " [ 1 ]
Much like Step 3 ; however , a space between adjacent strings is not
inserted and the zero - length strings are removed
(lambda (seq)
(let loop ((src (reverse seq))
(res '()))
(cond
((null? src)
res)
((string? (car src))
(if
(string=? (car src) "") ; empty string
(loop (cdr src) res)
(let adjacent ((src (cdr src))
(adj-strs (list (car src))))
(cond
((null? src) ; source sequence is over
(cons (srl:apply-string-append adj-strs) res))
((string? (car src))
; If it is an empty string, the effect of its presense
; will be removed by string concatenation
(adjacent (cdr src)
(cons (car src) adj-strs)))
(else
(loop (cdr src)
(cons (car src)
(cons
(srl:apply-string-append adj-strs)
res))))))))
(else
(loop (cdr src)
(cons (car src) res)))))))
(normaliz-step-7
; "It is a serialization error [err:SENR0001] if an item in S6 is an
; attribute node or a namespace node. Otherwise, construct a new
; sequence, S7, that consists of a single document node and copy all
; the items in the sequence, which are all nodes, as children of that
document node . " [ 1 ]
On this step , we should take care of SXML aux - lists
; ATTENTION: should generally raise an error in the presense of
attribute nodes in a sequence . By nature of SXML 3.0 , however ,
; attribute nodes on the top level are treated as aux-nodes
(lambda (seq)
(call-with-values
(lambda ()
(srl:separate-list
(lambda (item)
(and (pair? item)
aux - list in SXML 2.X
aux - list in SXML 3.0
)))
seq))
(lambda (aux-lists body)
(if
(null? aux-lists)
`(*TOP* ,@body)
`(*TOP*
(@ ,@(srl:map-append cdr aux-lists))
,@body)))))))
TODO : According to [ 1 ] , if the normalized sequence does not have exactly
one element node node child or has text node children , then the
; serialized output should be an XML external general parsed entity.
; However, external parsed entities are not currently handled by SSAX
; parser. Should think of a compromise between conformance and practical
; usability.
(normaliz-step-7
(normaliz-step-6
(normaliz-step-5
(normaliz-step-3
(normaliz-step-2
(normaliz-step-1 node-or-sequence))))))))
;==========================================================================
; Character escaping during string serialization
Escaping in accordance with [ 1 ] and [ 2 ] :
;
[ 2 ] Extensible Markup Language ( XML ) 1.0 ( Third Edition )
W3C Recommendation 04 February 2004
-xml-20040204
;-------------------------------------------------
CDATA sections
Returns # f if a given character ` ch ' is in XML character range [ 2 ]
; Otherwise, returns a string representing the character reference for that
; character
(define (srl:xml-char-escaped ch)
(let ((code (char->integer ch)))
(if (or (= code 9) (= code 10) (= code 13)
(and (>= code 32) (<= code 55295))
(and (>= code 57344) (<= code 65533))
(>= code 65536))
#f
(string-append "&#" (number->string code) ";"
))))
Represents a given string ` str ' as a CDATA section
(define (srl:string->cdata-section str)
(let ((flush-buffer
If a ` buffer ' is non - empty , converts it to a CDATA string and
; cons'es this string to `res'. Returns a new res
(lambda (buffer res)
(if (null? buffer)
res
(cons
(string-append
"<![CDATA[" (list->string (reverse buffer)) "]]>")
res)))))
(let loop ((src (string->list str))
(buffer '())
(res '("")))
(cond
((null? src)
(srl:apply-string-append
(reverse (flush-buffer buffer res))))
((srl:xml-char-escaped (car src))
=> (lambda (charref)
(loop (cdr src)
'()
(cons charref (flush-buffer buffer res)))))
((and (char=? (car src) #\])
(not (null? buffer))
(char=? (car buffer) #\]))
(loop (cdr src)
'()
(cons (string (car buffer) (car src)) ;= "]]"
(flush-buffer (cdr buffer) res))))
(else ; any other character
(loop (cdr src)
(cons (car src) buffer)
res))))))
;-------------------------------------------------
; Character data and attribute values
Associative lists of characters to be escaped in XML character data and
attribute values respectively [ 2 ]
(define srl:escape-alist-char-data
'((#\& . "&") (#\< . "<") (#\> . ">")))
(define srl:escape-alist-att-value
(append `((#\' . "'") (#\" . """)
; Escaping the newline character in attribute value
(,srl:char-nl . " "))
srl:escape-alist-char-data))
(define srl:escape-alist-html-att
'((#\& . "&") (#\> . ">") (#\' . "'") (#\" . """)))
; Escape a string with the `srl:xml-char-escaped' and with the `escape-alist'
; supplied
escape - alist : : = ( listof ( cons char string ) )
; html-method? ::= #t | #f
; Returns the escaped string
(define (srl:string->escaped str escape-alist html-method?)
(let loop ((src (string->list str))
(adj-chars '())
(res '()))
(cond
((null? src)
(srl:apply-string-append
(reverse (cons (list->string (reverse adj-chars))
res))))
((assv (car src) escape-alist) ; current character matches the alist
=> (lambda (pair)
(if
Subsect . 7.2 in [ 1 ] :
; "The HTML output method MUST NOT escape a & character occurring
; in an attribute value immediately followed by a { character"
(and (char=? (car src) #\&)
html-method?
(not (null? (cdr src))) (char=? (cadr src) #\{))
(loop (cdr src)
(cons (car src) adj-chars)
res)
(loop (cdr src)
'()
(cons (cdr pair)
(cons (list->string (reverse adj-chars))
res))))))
((srl:xml-char-escaped (car src))
=> (lambda (esc)
(loop (cdr src)
'()
(cons esc
(cons (list->string (reverse adj-chars))
res)))))
(else
(loop (cdr src)
(cons (car src) adj-chars)
res)))))
(define (srl:string->char-data str)
(srl:string->escaped str srl:escape-alist-char-data #f))
(define (srl:string->att-value str)
(srl:string->escaped str srl:escape-alist-att-value #f))
(define (srl:string->html-att str)
(srl:string->escaped str srl:escape-alist-html-att #t))
;-------------------------------------------------
; Serializing entities produced by HtmlPrag
;
[ 3 ] .
HtmlPrag : Pragmatic Parsing and Emitting of HTML using SXML and SHTML
Version 0.16 , 2005 - 12 - 18 , /
; "..SHTML adds a special & syntax for non-ASCII (or non-Extended-ASCII)
characters . The syntax is ( & val ) , where is a symbol or string naming
; with the symbolic name of the character, or an integer with the numeric
value of the character . " [ 3 ]
; entity ::= `(& ,val)
: : = symbol | string | number
; Returns the string representation for the entity
(define (srl:shtml-entity->char-data entity)
; TODO: think of an appropriate error message for an ill-formed entity
(if
(= (length entity) 2)
(let ((val (cadr entity)))
(cond
((symbol? val) (string-append "&" (symbol->string val) ";")
)
((string? val) (string-append "&" val ";")
)
((and (number? val) (integer? val) (> val 0))
; to guarantee well-formedness of the result produced
(string-append "&#" (number->string val) ";")
)
(else ; should signal of an error
"")))
""))
;==========================================================================
; Serialization for markup
declared - ns - prefixes : : = ( listof ( cons prefix - string namespace - uri ) )
; prefix-string, namespace-uri - strings
; Returns the string representation for a QName
; prefix-string ::= string or #f if the name contains no prefix
; TODO: should check names for proper characters
(define (srl:qname->string prefix-string local-part)
(if prefix-string
(string-append prefix-string ":" local-part)
local-part))
;-------------------------------------------------
; Different types of nodes
; Returns the list of strings that constitute the serialized representation
; for the attribute. Inserts a whitespace symbol in the beginning
; method ::= 'xml | 'html
(define (srl:attribute->str-lst prefix-string local-part att-value method)
(let ((attval (srl:atomic->string att-value)))
(cond
(prefix-string
(list " " prefix-string ":" local-part "=\""
((if (eq? method 'html)
srl:string->html-att
srl:string->att-value) attval)
"\""))
((eq? method 'html)
(list " " local-part "=\"" (srl:string->html-att attval) "\""))
(else ; unprefixed attribute, XML output method
(list " " local-part "=\"" (srl:string->att-value attval) "\"")))))
; Returns the list of strings that constitute the serialized representation
; for the namespace declaration. Inserts a whitespace symbol in the beginning
ATTENTION : character escaping for namespace URI may be improper , study this
; issue
(define (srl:namespace-decl->str-lst prefix-string namespace-uri)
(list " xmlns:" prefix-string "=\""
(srl:string->att-value namespace-uri) "\""))
According to SXML specification ,
; <comment> ::= ( *COMMENT* "comment string" )
; ATTENTION: in the case of ill-formed comment, should probably report an error
; instead of recovering
(define (srl:comment->str-lst comment-node)
(let ((proper-string-in-comment?
; Whether a proper string occurs in the comment node. Thus,
; "For compatibility, the string '--' (double-hyphen) MUST NOT occur
; within comments. ... Note that the grammar does not allow a comment
ending in --- > . " [ 2 ]
(lambda (str)
(let ((lng (string-length str)))
(or
empty string allowed in comment [ 2 ]
(and
(not (char=? (string-ref str 0) #\-))
(let iter ((i 1)
(prev-hyphen? #f))
(cond
((>= i lng)
(not prev-hyphen?) ; string must not end with hyphen
)
((char=? (string-ref str i) #\-)
(if prev-hyphen?
#f
(iter (+ i 1) #t)))
(else
(iter (+ i 1) #f))))))))))
(if (and (= (length comment-node) 2)
(string? (cadr comment-node))
(proper-string-in-comment? (cadr comment-node)))
(list "<!--" (cadr comment-node) "-->")
(list "<!--" "-->") ; should probably report of an error
)))
According to SXML specification ,
; <PI> ::= ( *PI* pi-target
; <annotations>? "processing instruction content string" )
; method ::= 'xml | 'html
Subsect 7.3 in [ 1 ] : " The HTML output method MUST terminate processing
; instructions with > rather than ?>."
; ATTENTION: in the case of ill-formed PI content string, should probably
; report an error instead of recovering
(define (srl:processing-instruction->str-lst pi-node method)
(let ((string-not-contain-charlist?
; Whether `str' does not contain a sequence of characters from
; `char-lst' as its substring
(lambda (str char-lst)
(let ((lng (string-length str)))
(or
(zero? lng) ; empty string doesn't contain
(let iter ((i 0)
(pattern char-lst))
(cond
((>= i lng) #t)
((char=? (string-ref str i) (car pattern))
(if (null? (cdr pattern)) ; it is the last member
#f ; contains
(iter (+ i 1) (cdr pattern))))
(else
(iter (+ i 1) char-lst)))))))))
(if
(or (null? (cdr pi-node))
no target = > ill - formed PI
'() ; should probably raise an error
(let ((content (filter string? (cddr pi-node))))
(cond
((null? content) ; PI with no content - correct situation
(list "<?" (symbol->string (cadr pi-node))
(if (eq? method 'html) ">" "?>")))
Subsect . 7.3 in [ 1 ] : " It is a serialization error to use the HTML
; output method when > appears within a processing instruction in
; the data model instance being serialized."
((and (null? (cdr content)) ; only a single member
(string-not-contain-charlist?
(car content)
(if (eq? method 'html) '(#\>) '(#\? #\>))))
(list "<?" (symbol->string (cadr pi-node)) " " (car content)
(if (eq? method 'html) ">" "?>")))
(else ; should probably signal of an error
'()))))))
;-------------------------------------------------
SXML element
; Returns: (values
; prefix-string namespace-uri local-part declaration-required?)
; prefix-string - namespace prefix to be given to the serialized name: a string
; or #f if no prefix is required
namespace - uri - the namespace URI for the given ` name ' , # f if the name has no
namespace URI
; local-part - local part of the name
; declaration-required ::= #t | #f - whether `prefix' has to be declared
(define (srl:name->qname-components
name ns-prefix-assig namespace-assoc declared-ns-prefixes)
(let ((use-ns-id-or-generate-prefix
(lambda (ns-id)
(if
(and ns-id ; try to use namespace-id as a prefix
(not (assq (string->symbol ns-id) ns-prefix-assig))
(not (assoc ns-id declared-ns-prefixes)))
ns-id
; Otherwise - generate unique prefix
; Returns a prefix-string not presented in ns-prefix-assig and
; declared-ns-prefixes
(let loop ((i 1))
(let ((candidate (string-append "prfx" (number->string i))))
(if (or (assoc candidate declared-ns-prefixes)
(assq (string->symbol candidate) ns-prefix-assig))
(loop (+ i 1))
candidate))))))
(n-parts (srl:split-name name)))
(cond
((not (car n-parts)) ; no namespace-id => no namespace
(values #f #f (cdr n-parts) ; name as a string
#f))
((string-ci=? (car n-parts) "xml") ; reserved XML namespace
(values (car n-parts) ""
(cdr n-parts) #f))
(else
(call-with-values
(lambda ()
(cond
((assq (string->symbol (car n-parts)) ; suppose a namespace-id
namespace-assoc)
=> (lambda (lst)
(values (cadr lst) (car n-parts))))
first part of a name is a namespace URI
(values (car n-parts) #f))))
(lambda (namespace-uri ns-id)
(cond
((srl:assoc-cdr-string= namespace-uri declared-ns-prefixes)
=> (lambda (pair)
Prefix for that namespace URI already declared
(values (car pair) namespace-uri (cdr n-parts) #f)))
(else ; namespace undeclared
(values
(cond
((srl:assoc-cdr-string= namespace-uri ns-prefix-assig)
=> (lambda (pair)
; A candidate namespace prefix is supplied from the user
(let ((candidate (symbol->string (car pair))))
(if
(assoc candidate declared-ns-prefixes)
; The prefix already bound to a different namespace
; Avoid XML prefix re-declaration
(use-ns-id-or-generate-prefix ns-id)
candidate))))
(else
(use-ns-id-or-generate-prefix ns-id)))
namespace-uri
(cdr n-parts)
#t ; in any case, prefix declaration is required
)))))))))
(define srl:void-elements
'("area" "base" "basefont" "br" "col" "embed"
"frame" "hr" "img" "input" "isindex" "keygen"
"link" "meta" "param" "source" "track" "wbr"))
Constructs start and end tags for an SXML element ` elem '
; method ::= 'xml | 'html
; Returns: (values start-tag end-tag
; ns-prefix-assig namespace-assoc declared-ns-prefixes)
start - tag : : = ( string )
end - tag : : = ( string ) or # f for empty element
TODO : escape URI attributes for HTML
; TODO: indentation probably should be made between attribute declarations
(define (srl:construct-start-end-tags
elem method
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(let ((ns-assoc-here (srl:namespace-assoc-for-elem elem))
(empty? (srl:empty-elem? elem)))
(let ((ns-prefix-assig
(append
(srl:extract-original-prefix-binding ns-assoc-here)
ns-prefix-assig))
(namespace-assoc
(append ns-assoc-here namespace-assoc)))
(call-with-values
(lambda ()
(srl:name->qname-components ; element name
(car elem) ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (elem-prefix elem-uri elem-local elem-decl-required?)
(let loop ((attrs
(reverse
((srl:select-kids
not SXML 3.0 aux - list
(and (pair? node) (not (eq? (car node) '@)))))
((srl:select-kids
(lambda (node)
(and (pair? node) (eq? (car node) '@))))
elem))))
(start-tag
(if (eq? method 'xml)
(if empty? '("/>") '(">"))
(if (or (not empty?)
(and (not elem-prefix)
(srl:member-ci
elem-local
srl:void-elements)))
'(">")
(list "></" (srl:qname->string elem-prefix elem-local) ">"))))
(ns-prefix-assig ns-prefix-assig)
(namespace-assoc namespace-assoc)
(declared-ns-prefixes
; As if element namespace already declared
(if elem-decl-required?
(cons (cons elem-prefix elem-uri)
declared-ns-prefixes)
declared-ns-prefixes)))
(if
(null? attrs) ; attributes scanned
(let ((elem-name (srl:qname->string elem-prefix elem-local)))
(values
(cons "<"
(cons elem-name
(if
elem-decl-required?
(cons
(srl:namespace-decl->str-lst elem-prefix elem-uri)
start-tag)
start-tag)))
(if empty? #f
(list "</" elem-name ">"))
ns-prefix-assig
namespace-assoc
declared-ns-prefixes))
(call-with-values
(lambda ()
(srl:name->qname-components
(caar attrs) ; attribute name
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (attr-prefix attr-uri attr-local attr-decl-required?)
(let ((start-tag
(cons
(srl:attribute->str-lst
attr-prefix attr-local
; TODO: optimize for HTML output method
(if (null? (cdar attrs)) ; no attribute value
attr-local
(cadar attrs))
method)
start-tag)))
(loop
(cdr attrs)
(if attr-decl-required?
(cons (srl:namespace-decl->str-lst attr-prefix attr-uri)
start-tag)
start-tag)
ns-prefix-assig
namespace-assoc
(if attr-decl-required?
(cons (cons attr-prefix attr-uri) declared-ns-prefixes)
declared-ns-prefixes))))))))))))
;==========================================================================
Recursively walking the tree of SXML elements
indentation : : = ( string ) or # f - a list of whitespace strings
; depending on the node nesting or #f if no indent is required
; space-preserve? ::= #t | #f - whether the subtree inherits the xml:space
; attribute with the value "preserve"
cdata - section - elements : : = ( listof symbol ) - list of element names whose
child nodes are to be output with CDATA section
; text-node-handler :: string -> string - a function that performs a proper
; character escaping for the given node if it is a text node
; TODO: do not insert whitespaces adjacent to HTML %inline elements in HTML
; output method
(define (srl:node->nested-str-lst-recursive
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indentation space-preserve?
cdata-section-elements text-node-handler)
(if
(not (pair? node)) ; text node
(text-node-handler (srl:atomic->string node))
(case (car node) ; node name
((*COMMENT*)
(srl:comment->str-lst node))
((*PI*)
(srl:processing-instruction->str-lst node method))
((&)
(srl:shtml-entity->char-data node))
recovering for non - SXML nodes
'())
(else ; otherwise - an element node
(call-with-values
(lambda ()
(srl:construct-start-end-tags
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(if
(not end-tag) ; empty element => recursion stops
start-tag
(let ((space-preserve?
(srl:update-space-specifier node space-preserve?))
(text-node-handler
(cond
((memq (car node) cdata-section-elements)
srl:string->cdata-section)
((and (eq? method 'html)
(srl:member-ci (symbol->string (car node))
'("script" "style")))
; No escaping for strings inside these HTML elements
(lambda (str) str))
(else
srl:string->char-data)))
(content ((srl:select-kids
TODO : support SXML entities
(not (and (pair? node)
(memq (car node) '(@ @@ *ENTITY*))))))
node)))
(call-with-values
(lambda ()
(cond
((or (not indentation)
(and (eq? method 'html)
(srl:member-ci
(symbol->string (car node))
'("pre" "script" "style" "textarea"))))
; No indent - on this level and subsequent levels
(values #f #f))
((or space-preserve?
(srl:mem-pred ; at least a single text node
(lambda (node) (not (pair? node)))
content))
; No indent on this level, possible indent on nested levels
(values #f indentation))
(else
(values (cons srl:newline indentation)
(cons (car indentation) indentation)))))
(lambda (indent-here indent4recursive)
(if
indent-here
(append
start-tag
(map
(lambda (kid)
(list
indent-here
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
content)
(cons srl:newline
(cons (cdr indentation) end-tag)))
(append
start-tag
(map
(lambda (kid)
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler))
content)
end-tag))))))))))))
(define (srl:display-node-out-recursive
node port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indentation space-preserve?
cdata-section-elements text-node-handler)
(if
(not (pair? node)) ; text node
(display (text-node-handler (srl:atomic->string node)) port)
(case (car node) ; node name
((*COMMENT*)
(for-each
(lambda (x) (display x port))
(srl:comment->str-lst node)))
((*PI*)
(for-each
(lambda (x) (display x port))
(srl:processing-instruction->str-lst node method)))
((&)
(display (srl:shtml-entity->char-data node) port))
recovering for non - SXML nodes
#f)
(else ; otherwise - an element node
(call-with-values
(lambda ()
(srl:construct-start-end-tags
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(begin
(srl:display-fragments-2nesting start-tag port)
(if
end-tag ; there exists content
(let ((space-preserve?
(srl:update-space-specifier node space-preserve?))
(text-node-handler
(cond
((memq (car node) cdata-section-elements)
srl:string->cdata-section)
((and (eq? method 'html)
(srl:member-ci (symbol->string (car node))
'("script" "style")))
; No escaping for strings inside these HTML elements
(lambda (str) str))
(else
srl:string->char-data)))
(content ((srl:select-kids
TODO : support SXML entities
(not (and (pair? node)
(memq (car node) '(@ @@ *ENTITY*))))))
node)))
(call-with-values
(lambda ()
(cond
((or (not indentation)
(and (eq? method 'html)
(srl:member-ci
(symbol->string (car node))
'("pre" "script" "style" "textarea"))))
; No indent - on this level and subsequent levels
(values #f #f))
((or space-preserve?
(srl:mem-pred ; at least a single text node
(lambda (node) (not (pair? node)))
content))
; No indent on this level, possible indent on nested levels
(values #f indentation))
(else
(values (cons srl:newline indentation)
(cons (car indentation) indentation)))))
(lambda (indent-here indent4recursive)
(begin
(for-each ; display content
(if
indent-here
(lambda (kid)
(begin
(for-each
(lambda (x) (display x port))
indent-here)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
(lambda (kid)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
content)
(if indent-here
(begin
(display srl:newline port)
(for-each
(lambda (x) (display x port))
(cdr indentation))))
(for-each
(lambda (x) (display x port))
end-tag)))))))))))))
;-------------------------------------------------
; Serializing the document node - start of recursion
Creates the serialized representation for the XML declaration
; Returns: (listof string)
; version ::= string | number
; standalone ::= 'yes | 'no | 'omit
(define (srl:make-xml-decl version standalone)
(let ((version (if (number? version) (number->string version) version)))
(if (eq? standalone 'omit)
(list "<?xml version='" version "'?>")
(list "<?xml version='" version "' standalone='"
(symbol->string standalone) "'?>"))))
; omit-xml-declaration? ::= #t | #f
; standalone ::= 'yes | 'no | 'omit
; version ::= string | number
(define (srl:top->nested-str-lst doc
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(let* ((namespace-assoc (srl:ns-assoc-for-top doc))
(ns-prefix-assig
(append
(srl:extract-original-prefix-binding namespace-assoc)
ns-prefix-assig))
(serialized-content
(map
(if
indent ; => output each member from the newline
(let ((indentation (list indent))) ; for nested elements
(lambda (kid)
(list
srl:newline
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data))))
(lambda (kid)
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc '()
indent #f
cdata-section-elements srl:string->char-data)))
((srl:select-kids ; document node content
TODO : support SXML entities
(not (and
(pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
doc))))
(if (or (eq? method 'html) omit-xml-declaration?)
(if (and indent (not (null? serialized-content)))
; Remove the starting newline
; ATTENTION: beware of `Gambit cadar bug':
; -list/
; 2005-July/000315.html
(cons (cadar serialized-content) (cdr serialized-content))
serialized-content)
(list (srl:make-xml-decl version standalone) serialized-content))))
(define (srl:display-top-out doc port
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
no XML declaration was displayed ?
(if (not (or (eq? method 'html) omit-xml-declaration?))
(begin
(for-each ; display xml declaration
(lambda (x) (display x port))
(srl:make-xml-decl version standalone))
#f)
#t))
(content ; document node content
((srl:select-kids
TODO : support SXML entities
(not (and
(pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
doc))
(namespace-assoc (srl:ns-assoc-for-top doc)))
(let ((ns-prefix-assig
(append
(srl:extract-original-prefix-binding namespace-assoc)
ns-prefix-assig)))
(cond
((null? content) ; generally a rare practical situation
#t) ; nothing more to do
((and indent no-xml-decl?)
; We'll not display newline before (car content)
(let ((indentation (list indent))) ; for nested elements
(for-each
(lambda (kid put-newline?)
(begin
(if put-newline?
(display srl:newline port))
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data)))
content
; After sequence normalization, content does not contain #f
(cons #f (cdr content)))))
(else
(for-each
(if
indent ; => output each member from the newline
(let ((indentation (list indent))) ; for nested elements
(lambda (kid)
(begin
(display srl:newline port)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data))))
(lambda (kid)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indent #f
cdata-section-elements srl:string->char-data)))
content))))))
;==========================================================================
Interface
;-------------------------------------------------
; Calling the serializer with all the serialization parameters supported
; and with no overhead of parameters parsing.
; ATTENTION: As future versions of this library may provide support for
additional serialization parameters , the functions ` srl : sxml->string ' and
` srl : display - sxml ' specified in this subsections may have a different number
; of their arguments in the future versions of the library.
; Returns a string that contains the serialized representation for `sxml-obj'.
cdata - section - elements : : = ( - name )
; indent ::= #t | #f | whitespace-string
; method = 'xml | 'html
ns - prefix - assign : : = ( listof ( cons prefix - symbol namespace - uri - string ) )
; omit-xml-declaration? ::= #t | #f
; standalone ::= 'yes | 'no | 'omit
version : : = number | string
(define (srl:sxml->string sxml-obj
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(srl:apply-string-append
(srl:clean-fragments
(srl:top->nested-str-lst (srl:normalize-sequence sxml-obj)
cdata-section-elements
(if (and indent (not (string? indent)))
" " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version))))
; Writes the serialized representation of the `sxml-obj' to an output port
; `port'. The result returned by the function is unspecified.
(define (srl:display-sxml sxml-obj port-or-filename
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(if
(string? port-or-filename) ; a filename?
(let ((out (open-output-file port-or-filename)))
(begin
(srl:display-top-out (srl:normalize-sequence sxml-obj) out
cdata-section-elements
(if (and indent (not (string? indent)))
" " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version)
(display srl:newline out) ; newline at the end of file
(close-output-port out)))
(srl:display-top-out (srl:normalize-sequence sxml-obj) port-or-filename
cdata-section-elements
(if (and indent (not (string? indent))) " " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version)))
;-------------------------------------------------
; Generalized serialization procedure, parameterizable with all the
; serialization params supported by this implementation
procedure srl : parameterizable : : SXML - OBJ [ PORT ] { PARAM } * - >
; -> STRING|unspecified
sxml - obj - an SXML object to serialize
; param ::= (cons param-name param-value)
; param-name ::= symbol
;
1 . cdata - section - elements
value : : = ( - elem - name )
sxml - elem - name : : = symbol
;
2 . indent
; value ::= 'yes | #t | 'no | #f | whitespace-string
;
3 . method
; value ::= 'xml | 'html
;
4 . ns - prefix - assig
value : : = ( listof ( cons prefix namespace - uri ) )
; prefix ::= symbol
; namespace-uri ::= string
;
5 . omit - xml - declaration ?
; value ::= 'yes | #t | 'no | #f
;
6 . standalone
; value ::= 'yes | #t | 'no | #f | 'omit
;
7 . version
; value ::= string | number
;
; ATTENTION: If a parameter name is unexpected or a parameter value is
; ill-formed, the parameter is silently ignored. Probably, a warning message
; in such a case would be more appropriate.
;
; Example:
( srl : parameterizable
; '(tag (@ (attr "value")) (nested "text node") (empty))
; (current-output-port)
; '(method . xml) ; XML output method is used by default
; '(indent . "\t") ; use a single tabulation to indent nested elements
' ( omit - xml - declaration . # f ) ; add XML declaration
' ( standalone . yes ) ; denote a standalone XML document
' ( version . " 1.0 " ) ) ; XML version
(define (srl:parameterizable sxml-obj . port-or-filename+params)
(call-with-values
(lambda ()
(if (and (not (null? port-or-filename+params))
(or (output-port? (car port-or-filename+params))
(string? (car port-or-filename+params))))
(values (car port-or-filename+params) (cdr port-or-filename+params))
(values #f port-or-filename+params)))
(lambda (port-or-filename params)
(let loop ((params params)
(cdata-section-elements '())
(indent " ")
(method 'xml)
(ns-prefix-assig srl:conventional-ns-prefixes)
(omit-xml-declaration? #t)
(standalone 'omit)
(version "1.0"))
(cond
((null? params) ; all parameters parsed
(if port-or-filename
(srl:display-sxml sxml-obj port-or-filename
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(srl:sxml->string sxml-obj
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)))
((or (not (pair? (car params))) ; not a pair or has no param value
(null? (cdar params)))
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version))
(else
(let ((prm-value (cdar params)))
(case (caar params)
((cdata-section-elements)
(loop (cdr params)
(if (list? prm-value) prm-value cdata-section-elements)
indent method ns-prefix-assig
omit-xml-declaration? standalone version))
((indent)
(loop (cdr params)
cdata-section-elements
(cond
((boolean? prm-value)
(if prm-value " " prm-value))
((string? prm-value) prm-value)
((eq? prm-value 'yes) " ")
((eq? prm-value 'no) #f)
(else indent))
method ns-prefix-assig
omit-xml-declaration? standalone version))
((method)
(loop (cdr params)
cdata-section-elements indent
(if (or (eq? prm-value 'xml) (eq? prm-value 'html))
prm-value method)
ns-prefix-assig
omit-xml-declaration? standalone version))
((ns-prefix-assig)
(loop (cdr params)
cdata-section-elements indent method
(if (and (list? prm-value)
(not (srl:mem-pred ; no non-pair members
(lambda (x) (not (pair? x)))
prm-value)))
(append prm-value ns-prefix-assig)
ns-prefix-assig)
omit-xml-declaration? standalone version))
((omit-xml-declaration)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
(cond
((boolean? prm-value) prm-value)
((eq? prm-value 'yes) #t)
((eq? prm-value 'no) #f)
(else indent))
standalone version))
((standalone)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig omit-xml-declaration?
(cond
((memv prm-value '(yes no omit))
prm-value)
((boolean? prm-value)
(if prm-value 'yes 'no))
(else standalone))
version))
((version)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone
(if (or (string? prm-value) (number? prm-value))
prm-value version)))
(else
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version))))))))))
;-------------------------------------------------
; High-level functions for popular serialization use-cases
; These functions use only a subset of serializer functionality, however, this
; subset seems sufficient for most practical purposes.
procedure srl : sxml->xml : : SXML - OBJ [ PORT - OR - FILENAME ] - > STRING|unspecified
;
Serializes the ` sxml - obj ' into XML , with indentation to facilitate
; readability by a human.
;
sxml - obj - an SXML object ( a node or a nodeset ) to be serialized
; port-or-filename - an output port or an output file name, an optional
; argument
; If `port-or-filename' is not supplied, the functions return a string that
; contains the serialized representation of the `sxml-obj'.
; If `port-or-filename' is supplied and is a port, the functions write the
; serialized representation of `sxml-obj' to this port and return an
; unspecified result.
; If `port-or-filename' is supplied and is a string, this string is treated as
; an output filename, the serialized representation of `sxml-obj' is written to
; that filename and an unspecified result is returned. If a file with the given
; name already exists, the effect is unspecified.
(define (srl:sxml->xml sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #t 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")
(srl:display-sxml sxml-obj (car port-or-filename) '() #t 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")))
procedure srl : sxml->xml - noindent : : SXML - OBJ [ PORT - OR - FILENAME ] - >
; -> STRING|unspecified
;
Serializes the ` sxml - obj ' into XML , without indentation .
(define (srl:sxml->xml-noindent sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #f 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")
(srl:display-sxml sxml-obj (car port-or-filename) '() #f 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")))
procedure srl : sxml->html : : SXML - OBJ [ PORT - OR - FILENAME ] - > STRING|unspecified
;
Serializes the ` sxml - obj ' into HTML , with indentation to facilitate
; readability by a human.
;
sxml - obj - an SXML object ( a node or a nodeset ) to be serialized
; port-or-filename - an output port or an output file name, an optional
; argument
; If `port-or-filename' is not supplied, the functions return a string that
; contains the serialized representation of the `sxml-obj'.
; If `port-or-filename' is supplied and is a port, the functions write the
; serialized representation of `sxml-obj' to this port and return an
; unspecified result.
; If `port-or-filename' is supplied and is a string, this string is treated as
; an output filename, the serialized representation of `sxml-obj' is written to
; that filename and an unspecified result is returned. If a file with the given
; name already exists, the effect is unspecified.
(define (srl:sxml->html sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #t 'html '() #t 'omit "4.0")
(srl:display-sxml sxml-obj (car port-or-filename)
'() #t 'html '() #t 'omit "4.0")))
procedure srl : sxml->html - noindent : : SXML - OBJ [ PORT - OR - FILENAME ] - >
; -> STRING|unspecified
;
Serializes the ` sxml - obj ' into HTML , without indentation .
(define (srl:sxml->html-noindent sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #f 'html '() #t 'omit "4.0")
(srl:display-sxml sxml-obj (car port-or-filename)
'() #f 'html '() #t 'omit "4.0")))
| null | https://raw.githubusercontent.com/shirok/Gauche/ecaf82f72e2e946f62d99ed8febe0df8960d20c4/ext/sxml/src/serializer.scm | scheme |
Partial conformance with
[1] XSLT 2.0 and XQuery 1.0 Serialization
-xslt-xquery-serialization-20051103/
This software is in Public Domain.
Please send bug reports and comments to:
Dmitry Lizorkin
short for "serialization"
Requires: function `filter' from SRFI-1
syntax `cond-expand' from SRFI-0
(require (lib "filter.ss" "srfi/1"))
==========================================================================
Basic
`map' and `append' in a single pass:
A simplified analogue of `map-union' from "sxpathlib.scm"
(cond-expand
(chicken
-with-current-continuation.org/
for a potentially long `str-lst'
first 'k' members of 'lst'
'()
garbage produced in the following solution:
(cond
((null? str-lst) "")
at least two members
(string-append
)
(else
))
However, search is performed by `cdr' of each alist member and `string=?' is
used for comparison
the `pred?'
-------------------------------------------------
Borrowed from "char-encoding.scm"
The newline character
A string consisting of a single newline character
-------------------------------------------------
Borrowed from "sxpathlib.scm"
A simplified implementation of `select-kids' is sufficienf for the serializer
node or node-set
No children
-------------------------------------------------
Borrowed from "modif.scm"
res-lst1 - contains all members from the input lst that satisfy the pred?
-------------------------------------------------
Borrowed from "fragments.scm"
A simplified implementation of `sxml:clean-fragments'
A very much simplified analogue of `sxml:display-fragments' for fragments
fragments-level2 ::= (listof fragments-level1)
==========================================================================
Helper SXML utilities
Returns: (cons namespace-id local-part)
local-part - string
namespace-id - string or #f if the `name' does not have a prefix
name scanned, #\: not found
object.
non-atomic type
unexpected type
ATTENTION: should probably raise an error here
just the name
just the name and attributes
-------------------------------------------------
<namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
Conventional namespace prefix referred to in XML-related specifications
These prefixes are used for serializing the corresponding namespace URIs by
default, unless a different prefix is supplied
at the top-level
Extract original prefix-binding from `namespace-assoc-lst'
<namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
specifies original prefix
-------------------------------------------------
Handling xml:space attribute
Returns the new value of `space-preserve?' in accordance with the value of
xml:space attribute with the value "preserve"
no xml:space attribute
==========================================================================
Sequence normalization
"If the sequence that is input to serialization is empty, create a
each item in the sequence that is input to serialization to create
empty sequence
Effect of `as-nodeset' from "sxpathlib.scm"
single item
single node
"For each item in S1, if the item is atomic, obtain the lexical
representation of the item by casting it to an xs:string and copy
the string representation to the new sequence; otherwise, copy the
item, which will be a node, to the new sequence. The new sequence is
"For each subsequence of adjacent strings in S2, copy a single
string to the new sequence equal to the values of the strings in the
subsequence concatenated in order, each separated by a single space.
Copy all other items to the new sequence. The new sequence is S3."
source sequence is over
distinquished from strings
"For each item in S4, if the item is a document node, copy its
children to the new sequence; otherwise, copy the item to the new
Document node
"For each subsequence of adjacent text nodes in S5, copy a single
text node to the new sequence equal to the values of the text nodes
in the subsequence concatenated in order. Any text nodes with values
however , a space between adjacent strings is not
empty string
source sequence is over
If it is an empty string, the effect of its presense
will be removed by string concatenation
"It is a serialization error [err:SENR0001] if an item in S6 is an
attribute node or a namespace node. Otherwise, construct a new
sequence, S7, that consists of a single document node and copy all
the items in the sequence, which are all nodes, as children of that
ATTENTION: should generally raise an error in the presense of
attribute nodes on the top level are treated as aux-nodes
serialized output should be an XML external general parsed entity.
However, external parsed entities are not currently handled by SSAX
parser. Should think of a compromise between conformance and practical
usability.
==========================================================================
Character escaping during string serialization
-------------------------------------------------
Otherwise, returns a string representing the character reference for that
character
cons'es this string to `res'. Returns a new res
= "]]"
any other character
-------------------------------------------------
Character data and attribute values
")
Escaping the newline character in attribute value
")))
Escape a string with the `srl:xml-char-escaped' and with the `escape-alist'
supplied
html-method? ::= #t | #f
Returns the escaped string
current character matches the alist
"The HTML output method MUST NOT escape a & character occurring
in an attribute value immediately followed by a { character"
-------------------------------------------------
Serializing entities produced by HtmlPrag
"..SHTML adds a special & syntax for non-ASCII (or non-Extended-ASCII)
with the symbolic name of the character, or an integer with the numeric
entity ::= `(& ,val)
Returns the string representation for the entity
TODO: think of an appropriate error message for an ill-formed entity
to guarantee well-formedness of the result produced
should signal of an error
==========================================================================
Serialization for markup
prefix-string, namespace-uri - strings
Returns the string representation for a QName
prefix-string ::= string or #f if the name contains no prefix
TODO: should check names for proper characters
-------------------------------------------------
Different types of nodes
Returns the list of strings that constitute the serialized representation
for the attribute. Inserts a whitespace symbol in the beginning
method ::= 'xml | 'html
unprefixed attribute, XML output method
Returns the list of strings that constitute the serialized representation
for the namespace declaration. Inserts a whitespace symbol in the beginning
issue
<comment> ::= ( *COMMENT* "comment string" )
ATTENTION: in the case of ill-formed comment, should probably report an error
instead of recovering
Whether a proper string occurs in the comment node. Thus,
"For compatibility, the string '--' (double-hyphen) MUST NOT occur
within comments. ... Note that the grammar does not allow a comment
string must not end with hyphen
should probably report of an error
<PI> ::= ( *PI* pi-target
<annotations>? "processing instruction content string" )
method ::= 'xml | 'html
instructions with > rather than ?>."
ATTENTION: in the case of ill-formed PI content string, should probably
report an error instead of recovering
Whether `str' does not contain a sequence of characters from
`char-lst' as its substring
empty string doesn't contain
it is the last member
contains
should probably raise an error
PI with no content - correct situation
output method when > appears within a processing instruction in
the data model instance being serialized."
only a single member
should probably signal of an error
-------------------------------------------------
Returns: (values
prefix-string namespace-uri local-part declaration-required?)
prefix-string - namespace prefix to be given to the serialized name: a string
or #f if no prefix is required
local-part - local part of the name
declaration-required ::= #t | #f - whether `prefix' has to be declared
try to use namespace-id as a prefix
Otherwise - generate unique prefix
Returns a prefix-string not presented in ns-prefix-assig and
declared-ns-prefixes
no namespace-id => no namespace
name as a string
reserved XML namespace
suppose a namespace-id
namespace undeclared
A candidate namespace prefix is supplied from the user
The prefix already bound to a different namespace
Avoid XML prefix re-declaration
in any case, prefix declaration is required
method ::= 'xml | 'html
Returns: (values start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
TODO: indentation probably should be made between attribute declarations
element name
As if element namespace already declared
attributes scanned
attribute name
TODO: optimize for HTML output method
no attribute value
==========================================================================
depending on the node nesting or #f if no indent is required
space-preserve? ::= #t | #f - whether the subtree inherits the xml:space
attribute with the value "preserve"
text-node-handler :: string -> string - a function that performs a proper
character escaping for the given node if it is a text node
TODO: do not insert whitespaces adjacent to HTML %inline elements in HTML
output method
text node
node name
otherwise - an element node
empty element => recursion stops
No escaping for strings inside these HTML elements
No indent - on this level and subsequent levels
at least a single text node
No indent on this level, possible indent on nested levels
text node
node name
otherwise - an element node
there exists content
No escaping for strings inside these HTML elements
No indent - on this level and subsequent levels
at least a single text node
No indent on this level, possible indent on nested levels
display content
-------------------------------------------------
Serializing the document node - start of recursion
Returns: (listof string)
version ::= string | number
standalone ::= 'yes | 'no | 'omit
omit-xml-declaration? ::= #t | #f
standalone ::= 'yes | 'no | 'omit
version ::= string | number
=> output each member from the newline
for nested elements
document node content
Remove the starting newline
ATTENTION: beware of `Gambit cadar bug':
-list/
2005-July/000315.html
display xml declaration
document node content
generally a rare practical situation
nothing more to do
We'll not display newline before (car content)
for nested elements
After sequence normalization, content does not contain #f
=> output each member from the newline
for nested elements
==========================================================================
-------------------------------------------------
Calling the serializer with all the serialization parameters supported
and with no overhead of parameters parsing.
ATTENTION: As future versions of this library may provide support for
of their arguments in the future versions of the library.
Returns a string that contains the serialized representation for `sxml-obj'.
indent ::= #t | #f | whitespace-string
method = 'xml | 'html
omit-xml-declaration? ::= #t | #f
standalone ::= 'yes | 'no | 'omit
Writes the serialized representation of the `sxml-obj' to an output port
`port'. The result returned by the function is unspecified.
a filename?
newline at the end of file
-------------------------------------------------
Generalized serialization procedure, parameterizable with all the
serialization params supported by this implementation
-> STRING|unspecified
param ::= (cons param-name param-value)
param-name ::= symbol
value ::= 'yes | #t | 'no | #f | whitespace-string
value ::= 'xml | 'html
prefix ::= symbol
namespace-uri ::= string
value ::= 'yes | #t | 'no | #f
value ::= 'yes | #t | 'no | #f | 'omit
value ::= string | number
ATTENTION: If a parameter name is unexpected or a parameter value is
ill-formed, the parameter is silently ignored. Probably, a warning message
in such a case would be more appropriate.
Example:
'(tag (@ (attr "value")) (nested "text node") (empty))
(current-output-port)
'(method . xml) ; XML output method is used by default
'(indent . "\t") ; use a single tabulation to indent nested elements
add XML declaration
denote a standalone XML document
XML version
all parameters parsed
not a pair or has no param value
no non-pair members
-------------------------------------------------
High-level functions for popular serialization use-cases
These functions use only a subset of serializer functionality, however, this
subset seems sufficient for most practical purposes.
readability by a human.
port-or-filename - an output port or an output file name, an optional
argument
If `port-or-filename' is not supplied, the functions return a string that
contains the serialized representation of the `sxml-obj'.
If `port-or-filename' is supplied and is a port, the functions write the
serialized representation of `sxml-obj' to this port and return an
unspecified result.
If `port-or-filename' is supplied and is a string, this string is treated as
an output filename, the serialized representation of `sxml-obj' is written to
that filename and an unspecified result is returned. If a file with the given
name already exists, the effect is unspecified.
-> STRING|unspecified
readability by a human.
port-or-filename - an output port or an output file name, an optional
argument
If `port-or-filename' is not supplied, the functions return a string that
contains the serialized representation of the `sxml-obj'.
If `port-or-filename' is supplied and is a port, the functions write the
serialized representation of `sxml-obj' to this port and return an
unspecified result.
If `port-or-filename' is supplied and is a string, this string is treated as
an output filename, the serialized representation of `sxml-obj' is written to
that filename and an unspecified result is returned. If a file with the given
name already exists, the effect is unspecified.
-> STRING|unspecified
| SXML serializer into XML and HTML
W3C Candidate Recommendation 3 November 2005
IT IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND .
Prefix for global identifiers in this module is ` srl : '
In particular , for PLT , ` filter ' can be acquired as follows :
( srl : map - append func lst ) = ( apply append ( map func lst ) )
(define (srl:map-append func lst)
(if (null? lst)
lst
(append (func (car lst))
(srl:map-append func (cdr lst)))))
procedure srl : apply - string - append : : STR - LST - > STRING
str - lst : : = ( string )
Concatenates ` str - lst ' members into a single string
( srl : apply - string - append str - lst ) = ( apply string - append str - lst )
In Chicken , procedures are generally limited to 126 arguments
Due to this Chicken limitation , we can not apply ` string - append ' directly
Similar to R5RS ' list - tail ' but returns the new list consisting of the
( define ( srl : list - head )
( if ( or ( null ? lst ) ( zero ? k ) )
( cons ( car lst ) ( srl : list - head ( cdr lst ) ( - k 1 ) ) ) ) )
Because of Chicken 126 - argument limitation , I do not care of intermediate
( define ( srl : apply - string - append str - lst )
( ( null ? ( ) ) ( car str - lst ) )
( let ( ( middle ( inexact->exact ( round ( / ( length str - lst ) 2 ) ) ) ) )
( srl : apply - string - append ( srl : list - head str - lst middle ) )
( srl : apply - string - append ( list - tail str - lst middle ) ) ) ) ) ) )
(define (srl:apply-string-append str-lst)
(apply string-append str-lst))
Analogue of ` assoc '
(define (srl:assoc-cdr-string= item alist)
(cond
((null? alist) #f)
((string=? (cdar alist) item) (car alist))
(else (srl:assoc-cdr-string= item (cdr alist)))))
Analogue of ` member ' for strings that uses case insensitive comparison
(define (srl:member-ci str lst)
(cond
((null? lst) #f)
((string-ci=? str (car lst)) lst)
(else (srl:member-ci str (cdr lst)))))
Analogue of ` member '
The end of the ` lst ' is returned , from the first member that satisfies
(define (srl:mem-pred pred? lst)
(cond
((null? lst) #f)
((pred? (car lst)) lst)
(else (srl:mem-pred pred? (cdr lst)))))
(cond-expand
((or scheme48 scsh)
(define srl:char-nl (ascii->char 10)))
(else
(define srl:char-nl (integer->char 10))))
(define srl:newline (string srl:char-nl))
(define (srl:select-kids test-pred?)
(cond
((null? node) node)
((symbol? (car node))
(filter test-pred? (cdr node)))
(else
(srl:map-append (srl:select-kids test-pred?) node)))))
Separates the list into two lists with respect to the predicate
Returns : ( values )
res - lst2 - contains the remaining members of the input lst
(define (srl:separate-list pred? lst)
(let loop ((lst lst)
(satisfy '())
(rest '()))
(cond
((null? lst)
(values (reverse satisfy) (reverse rest)))
the first member satisfies the predicate
(loop (cdr lst)
(cons (car lst) satisfy) rest))
(else
(loop (cdr lst)
satisfy (cons (car lst) rest))))))
(define (srl:clean-fragments fragments)
(reverse
(let loop ((fragments fragments) (result '()))
(cond
((null? fragments) result)
((null? (car fragments)) (loop (cdr fragments) result))
((pair? (car fragments))
(loop (cdr fragments)
(loop (car fragments) result)))
(else
(loop (cdr fragments)
(cons (car fragments) result)))))))
that have no more than two levels of nesting
fragments - level1 : : = string | ( listof string )
(define (srl:display-fragments-2nesting fragments-level2 port)
(for-each
(lambda (level1)
(if (pair? level1)
(for-each (lambda (x) (display x port))
level1)
(display level1 port)))
fragments-level2))
Splits an SXML ` name ' into namespace id / uri and local part
(define (srl:split-name name)
(let* ((name-str (symbol->string name))
(lng (string-length name-str)))
(let iter ((i (- lng 1)))
(cond
(cons #f name-str))
((char=? (string-ref name-str i) #\:)
(cons (substring name-str 0 i)
(substring name-str (+ i 1) lng)))
(else
(iter (- i 1)))))))
Converts SXML atomic object to a string . Keeps non - atomic object unchanged .
A simplified analogue of applying the XPath ` string ( . ) ' function to atomic
(define (srl:atomic->string obj)
(cond
(string? obj)) obj)
((number? obj)
(number->string obj))
((boolean? obj)
(if obj "true" "false"))
obj)))
Whether an SXML element is empty
(define (srl:empty-elem? elem)
(pair? (cadr elem)) (eq? (caadr elem) '@))
name , attributes , and SXML 2.X aux - list
(null? (cdddr elem))
(pair? (caddr elem)) (eq? (caaddr elem) '@@))))
Handling SXML namespaces
< namespace - assoc > is defined in the SXML specification as
(define srl:conventional-ns-prefixes
'((dc . "/")
(fo . "")
(rdf . "-rdf-syntax-ns#")
(rng . "")
(xlink . "")
(xqx . "")
(xsd . "")
(xsi . "-instance")
(xsl . "")))
Returns ( listof < namespace - assoc > ) for the given SXML element
(define (srl:namespace-assoc-for-elem elem)
((srl:select-kids (lambda (node) (pair? node)))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
(append
compatibility with SXML 3.0
(lambda (node) (and (pair? node) (eq? (car node) '@))))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '@))))
elem))
compatibility with SXML 2.X
(lambda (node) (and (pair? node) (eq? (car node) '@@))))
elem)))))
Returns ( listof < namespace - assoc > ) for the SXML document node
(define (srl:ns-assoc-for-top doc)
((srl:select-kids (lambda (node) (pair? node)))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
((srl:select-kids
(lambda (node)
After sequence normalization [ 1 ] , the SXML 3.0 aux - list is used
(and (pair? node) (eq? (car node) '@))))
doc))))
namespace - assoc - lst : : = ( listof < namespace - assoc > )
Returns : ( listof ( cons original - prefix " URI " ) )
(define (srl:extract-original-prefix-binding namespace-assoc-lst)
(map
(lambda (triple) (cons (caddr triple) (cadr triple)))
(lambda (memb) (= (length memb) 3))
namespace-assoc-lst)))
xml : space attribute probably presented for the given SXML element ` elem '
space - preserve ? : : = # t | # f - whether the SXML subtree inherits the
(define (srl:update-space-specifier elem space-preserve?)
(let ((xml-space-val
((srl:select-kids string?)
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) 'xml:space))))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '@))))
elem)))))
(cond
space-preserve?)
((string=? (car xml-space-val) "preserve")
#t)
((string=? (car xml-space-val) "default")
#f)
(else space-preserve?))))
Sect . 2 in [ 1 ]
Performs sequence normalization in accordance with [ 1 ]
Returns the SXML document node
(define (srl:normalize-sequence node-or-sequence)
(letrec
((normaliz-step-1
sequence S1 that consists of a zero - length string . Otherwise , copy
the new sequence S1 . " [ 1 ]
(lambda (node-or-seq)
(cond
'(""))
(list node-or-seq))
(else
node-or-seq))))
(normaliz-step-2
S2 . " [ 1 ]
(lambda (seq)
(map
(lambda (item) (srl:atomic->string item))
seq)))
(normaliz-step-3
(lambda (seq)
(let loop ((src (reverse seq))
(res '()))
(cond
((null? src)
res)
((string? (car src))
(let adjacent ((src (cdr src))
(adj-strs (list (car src))))
(cond
(cons (srl:apply-string-append adj-strs) res))
((string? (car src))
(adjacent (cdr src)
(cons (car src) (cons " " adj-strs))))
(else
(loop (cdr src)
(cons (car src)
(cons (srl:apply-string-append adj-strs)
res)))))))
(else
(loop (cdr src)
(cons (car src) res)))))))
Step 4 from [ 1 ] is redundant for SXML , since SXML text nodes are not
(normaliz-step-5
sequence . The new sequence is S5 . " [ 1 ]
(lambda (seq)
(cond
((null? seq)
seq)
((and (pair? (car seq)) (eq? (caar seq) '*TOP*))
(append (cdar seq) (normaliz-step-5 (cdr seq))))
(else
(cons (car seq) (normaliz-step-5 (cdr seq)))))))
(normaliz-step-6
of zero length are dropped . Copy all other items to the new sequence .
The new sequence is S6 . " [ 1 ]
inserted and the zero - length strings are removed
(lambda (seq)
(let loop ((src (reverse seq))
(res '()))
(cond
((null? src)
res)
((string? (car src))
(if
(loop (cdr src) res)
(let adjacent ((src (cdr src))
(adj-strs (list (car src))))
(cond
(cons (srl:apply-string-append adj-strs) res))
((string? (car src))
(adjacent (cdr src)
(cons (car src) adj-strs)))
(else
(loop (cdr src)
(cons (car src)
(cons
(srl:apply-string-append adj-strs)
res))))))))
(else
(loop (cdr src)
(cons (car src) res)))))))
(normaliz-step-7
document node . " [ 1 ]
On this step , we should take care of SXML aux - lists
attribute nodes in a sequence . By nature of SXML 3.0 , however ,
(lambda (seq)
(call-with-values
(lambda ()
(srl:separate-list
(lambda (item)
(and (pair? item)
aux - list in SXML 2.X
aux - list in SXML 3.0
)))
seq))
(lambda (aux-lists body)
(if
(null? aux-lists)
`(*TOP* ,@body)
`(*TOP*
(@ ,@(srl:map-append cdr aux-lists))
,@body)))))))
TODO : According to [ 1 ] , if the normalized sequence does not have exactly
one element node node child or has text node children , then the
(normaliz-step-7
(normaliz-step-6
(normaliz-step-5
(normaliz-step-3
(normaliz-step-2
(normaliz-step-1 node-or-sequence))))))))
Escaping in accordance with [ 1 ] and [ 2 ] :
[ 2 ] Extensible Markup Language ( XML ) 1.0 ( Third Edition )
W3C Recommendation 04 February 2004
-xml-20040204
CDATA sections
Returns # f if a given character ` ch ' is in XML character range [ 2 ]
(define (srl:xml-char-escaped ch)
(let ((code (char->integer ch)))
(if (or (= code 9) (= code 10) (= code 13)
(and (>= code 32) (<= code 55295))
(and (>= code 57344) (<= code 65533))
(>= code 65536))
#f
(string-append "&#" (number->string code) ";"
))))
Represents a given string ` str ' as a CDATA section
(define (srl:string->cdata-section str)
(let ((flush-buffer
If a ` buffer ' is non - empty , converts it to a CDATA string and
(lambda (buffer res)
(if (null? buffer)
res
(cons
(string-append
"<![CDATA[" (list->string (reverse buffer)) "]]>")
res)))))
(let loop ((src (string->list str))
(buffer '())
(res '("")))
(cond
((null? src)
(srl:apply-string-append
(reverse (flush-buffer buffer res))))
((srl:xml-char-escaped (car src))
=> (lambda (charref)
(loop (cdr src)
'()
(cons charref (flush-buffer buffer res)))))
((and (char=? (car src) #\])
(not (null? buffer))
(char=? (car buffer) #\]))
(loop (cdr src)
'()
(flush-buffer (cdr buffer) res))))
(loop (cdr src)
(cons (car src) buffer)
res))))))
Associative lists of characters to be escaped in XML character data and
attribute values respectively [ 2 ]
(define srl:escape-alist-char-data
'((#\& . "&") (#\< . "<") (#\> . ">")))
(define srl:escape-alist-att-value
(,srl:char-nl . " "))
srl:escape-alist-char-data))
(define srl:escape-alist-html-att
escape - alist : : = ( listof ( cons char string ) )
(define (srl:string->escaped str escape-alist html-method?)
(let loop ((src (string->list str))
(adj-chars '())
(res '()))
(cond
((null? src)
(srl:apply-string-append
(reverse (cons (list->string (reverse adj-chars))
res))))
=> (lambda (pair)
(if
Subsect . 7.2 in [ 1 ] :
(and (char=? (car src) #\&)
html-method?
(not (null? (cdr src))) (char=? (cadr src) #\{))
(loop (cdr src)
(cons (car src) adj-chars)
res)
(loop (cdr src)
'()
(cons (cdr pair)
(cons (list->string (reverse adj-chars))
res))))))
((srl:xml-char-escaped (car src))
=> (lambda (esc)
(loop (cdr src)
'()
(cons esc
(cons (list->string (reverse adj-chars))
res)))))
(else
(loop (cdr src)
(cons (car src) adj-chars)
res)))))
(define (srl:string->char-data str)
(srl:string->escaped str srl:escape-alist-char-data #f))
(define (srl:string->att-value str)
(srl:string->escaped str srl:escape-alist-att-value #f))
(define (srl:string->html-att str)
(srl:string->escaped str srl:escape-alist-html-att #t))
[ 3 ] .
HtmlPrag : Pragmatic Parsing and Emitting of HTML using SXML and SHTML
Version 0.16 , 2005 - 12 - 18 , /
characters . The syntax is ( & val ) , where is a symbol or string naming
value of the character . " [ 3 ]
: : = symbol | string | number
(define (srl:shtml-entity->char-data entity)
(if
(= (length entity) 2)
(let ((val (cadr entity)))
(cond
((symbol? val) (string-append "&" (symbol->string val) ";")
)
((string? val) (string-append "&" val ";")
)
((and (number? val) (integer? val) (> val 0))
(string-append "&#" (number->string val) ";")
)
"")))
""))
declared - ns - prefixes : : = ( listof ( cons prefix - string namespace - uri ) )
(define (srl:qname->string prefix-string local-part)
(if prefix-string
(string-append prefix-string ":" local-part)
local-part))
(define (srl:attribute->str-lst prefix-string local-part att-value method)
(let ((attval (srl:atomic->string att-value)))
(cond
(prefix-string
(list " " prefix-string ":" local-part "=\""
((if (eq? method 'html)
srl:string->html-att
srl:string->att-value) attval)
"\""))
((eq? method 'html)
(list " " local-part "=\"" (srl:string->html-att attval) "\""))
(list " " local-part "=\"" (srl:string->att-value attval) "\"")))))
ATTENTION : character escaping for namespace URI may be improper , study this
(define (srl:namespace-decl->str-lst prefix-string namespace-uri)
(list " xmlns:" prefix-string "=\""
(srl:string->att-value namespace-uri) "\""))
According to SXML specification ,
(define (srl:comment->str-lst comment-node)
(let ((proper-string-in-comment?
ending in --- > . " [ 2 ]
(lambda (str)
(let ((lng (string-length str)))
(or
empty string allowed in comment [ 2 ]
(and
(not (char=? (string-ref str 0) #\-))
(let iter ((i 1)
(prev-hyphen? #f))
(cond
((>= i lng)
)
((char=? (string-ref str i) #\-)
(if prev-hyphen?
#f
(iter (+ i 1) #t)))
(else
(iter (+ i 1) #f))))))))))
(if (and (= (length comment-node) 2)
(string? (cadr comment-node))
(proper-string-in-comment? (cadr comment-node)))
(list "<!--" (cadr comment-node) "-->")
)))
According to SXML specification ,
Subsect 7.3 in [ 1 ] : " The HTML output method MUST terminate processing
(define (srl:processing-instruction->str-lst pi-node method)
(let ((string-not-contain-charlist?
(lambda (str char-lst)
(let ((lng (string-length str)))
(or
(let iter ((i 0)
(pattern char-lst))
(cond
((>= i lng) #t)
((char=? (string-ref str i) (car pattern))
(iter (+ i 1) (cdr pattern))))
(else
(iter (+ i 1) char-lst)))))))))
(if
(or (null? (cdr pi-node))
no target = > ill - formed PI
(let ((content (filter string? (cddr pi-node))))
(cond
(list "<?" (symbol->string (cadr pi-node))
(if (eq? method 'html) ">" "?>")))
Subsect . 7.3 in [ 1 ] : " It is a serialization error to use the HTML
(string-not-contain-charlist?
(car content)
(if (eq? method 'html) '(#\>) '(#\? #\>))))
(list "<?" (symbol->string (cadr pi-node)) " " (car content)
(if (eq? method 'html) ">" "?>")))
'()))))))
SXML element
namespace - uri - the namespace URI for the given ` name ' , # f if the name has no
namespace URI
(define (srl:name->qname-components
name ns-prefix-assig namespace-assoc declared-ns-prefixes)
(let ((use-ns-id-or-generate-prefix
(lambda (ns-id)
(if
(not (assq (string->symbol ns-id) ns-prefix-assig))
(not (assoc ns-id declared-ns-prefixes)))
ns-id
(let loop ((i 1))
(let ((candidate (string-append "prfx" (number->string i))))
(if (or (assoc candidate declared-ns-prefixes)
(assq (string->symbol candidate) ns-prefix-assig))
(loop (+ i 1))
candidate))))))
(n-parts (srl:split-name name)))
(cond
#f))
(values (car n-parts) ""
(cdr n-parts) #f))
(else
(call-with-values
(lambda ()
(cond
namespace-assoc)
=> (lambda (lst)
(values (cadr lst) (car n-parts))))
first part of a name is a namespace URI
(values (car n-parts) #f))))
(lambda (namespace-uri ns-id)
(cond
((srl:assoc-cdr-string= namespace-uri declared-ns-prefixes)
=> (lambda (pair)
Prefix for that namespace URI already declared
(values (car pair) namespace-uri (cdr n-parts) #f)))
(values
(cond
((srl:assoc-cdr-string= namespace-uri ns-prefix-assig)
=> (lambda (pair)
(let ((candidate (symbol->string (car pair))))
(if
(assoc candidate declared-ns-prefixes)
(use-ns-id-or-generate-prefix ns-id)
candidate))))
(else
(use-ns-id-or-generate-prefix ns-id)))
namespace-uri
(cdr n-parts)
)))))))))
(define srl:void-elements
'("area" "base" "basefont" "br" "col" "embed"
"frame" "hr" "img" "input" "isindex" "keygen"
"link" "meta" "param" "source" "track" "wbr"))
Constructs start and end tags for an SXML element ` elem '
start - tag : : = ( string )
end - tag : : = ( string ) or # f for empty element
TODO : escape URI attributes for HTML
(define (srl:construct-start-end-tags
elem method
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(let ((ns-assoc-here (srl:namespace-assoc-for-elem elem))
(empty? (srl:empty-elem? elem)))
(let ((ns-prefix-assig
(append
(srl:extract-original-prefix-binding ns-assoc-here)
ns-prefix-assig))
(namespace-assoc
(append ns-assoc-here namespace-assoc)))
(call-with-values
(lambda ()
(car elem) ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (elem-prefix elem-uri elem-local elem-decl-required?)
(let loop ((attrs
(reverse
((srl:select-kids
not SXML 3.0 aux - list
(and (pair? node) (not (eq? (car node) '@)))))
((srl:select-kids
(lambda (node)
(and (pair? node) (eq? (car node) '@))))
elem))))
(start-tag
(if (eq? method 'xml)
(if empty? '("/>") '(">"))
(if (or (not empty?)
(and (not elem-prefix)
(srl:member-ci
elem-local
srl:void-elements)))
'(">")
(list "></" (srl:qname->string elem-prefix elem-local) ">"))))
(ns-prefix-assig ns-prefix-assig)
(namespace-assoc namespace-assoc)
(declared-ns-prefixes
(if elem-decl-required?
(cons (cons elem-prefix elem-uri)
declared-ns-prefixes)
declared-ns-prefixes)))
(if
(let ((elem-name (srl:qname->string elem-prefix elem-local)))
(values
(cons "<"
(cons elem-name
(if
elem-decl-required?
(cons
(srl:namespace-decl->str-lst elem-prefix elem-uri)
start-tag)
start-tag)))
(if empty? #f
(list "</" elem-name ">"))
ns-prefix-assig
namespace-assoc
declared-ns-prefixes))
(call-with-values
(lambda ()
(srl:name->qname-components
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (attr-prefix attr-uri attr-local attr-decl-required?)
(let ((start-tag
(cons
(srl:attribute->str-lst
attr-prefix attr-local
attr-local
(cadar attrs))
method)
start-tag)))
(loop
(cdr attrs)
(if attr-decl-required?
(cons (srl:namespace-decl->str-lst attr-prefix attr-uri)
start-tag)
start-tag)
ns-prefix-assig
namespace-assoc
(if attr-decl-required?
(cons (cons attr-prefix attr-uri) declared-ns-prefixes)
declared-ns-prefixes))))))))))))
Recursively walking the tree of SXML elements
indentation : : = ( string ) or # f - a list of whitespace strings
cdata - section - elements : : = ( listof symbol ) - list of element names whose
child nodes are to be output with CDATA section
(define (srl:node->nested-str-lst-recursive
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indentation space-preserve?
cdata-section-elements text-node-handler)
(if
(text-node-handler (srl:atomic->string node))
((*COMMENT*)
(srl:comment->str-lst node))
((*PI*)
(srl:processing-instruction->str-lst node method))
((&)
(srl:shtml-entity->char-data node))
recovering for non - SXML nodes
'())
(call-with-values
(lambda ()
(srl:construct-start-end-tags
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(if
start-tag
(let ((space-preserve?
(srl:update-space-specifier node space-preserve?))
(text-node-handler
(cond
((memq (car node) cdata-section-elements)
srl:string->cdata-section)
((and (eq? method 'html)
(srl:member-ci (symbol->string (car node))
'("script" "style")))
(lambda (str) str))
(else
srl:string->char-data)))
(content ((srl:select-kids
TODO : support SXML entities
(not (and (pair? node)
(memq (car node) '(@ @@ *ENTITY*))))))
node)))
(call-with-values
(lambda ()
(cond
((or (not indentation)
(and (eq? method 'html)
(srl:member-ci
(symbol->string (car node))
'("pre" "script" "style" "textarea"))))
(values #f #f))
((or space-preserve?
(lambda (node) (not (pair? node)))
content))
(values #f indentation))
(else
(values (cons srl:newline indentation)
(cons (car indentation) indentation)))))
(lambda (indent-here indent4recursive)
(if
indent-here
(append
start-tag
(map
(lambda (kid)
(list
indent-here
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
content)
(cons srl:newline
(cons (cdr indentation) end-tag)))
(append
start-tag
(map
(lambda (kid)
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler))
content)
end-tag))))))))))))
(define (srl:display-node-out-recursive
node port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indentation space-preserve?
cdata-section-elements text-node-handler)
(if
(display (text-node-handler (srl:atomic->string node)) port)
((*COMMENT*)
(for-each
(lambda (x) (display x port))
(srl:comment->str-lst node)))
((*PI*)
(for-each
(lambda (x) (display x port))
(srl:processing-instruction->str-lst node method)))
((&)
(display (srl:shtml-entity->char-data node) port))
recovering for non - SXML nodes
#f)
(call-with-values
(lambda ()
(srl:construct-start-end-tags
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(begin
(srl:display-fragments-2nesting start-tag port)
(if
(let ((space-preserve?
(srl:update-space-specifier node space-preserve?))
(text-node-handler
(cond
((memq (car node) cdata-section-elements)
srl:string->cdata-section)
((and (eq? method 'html)
(srl:member-ci (symbol->string (car node))
'("script" "style")))
(lambda (str) str))
(else
srl:string->char-data)))
(content ((srl:select-kids
TODO : support SXML entities
(not (and (pair? node)
(memq (car node) '(@ @@ *ENTITY*))))))
node)))
(call-with-values
(lambda ()
(cond
((or (not indentation)
(and (eq? method 'html)
(srl:member-ci
(symbol->string (car node))
'("pre" "script" "style" "textarea"))))
(values #f #f))
((or space-preserve?
(lambda (node) (not (pair? node)))
content))
(values #f indentation))
(else
(values (cons srl:newline indentation)
(cons (car indentation) indentation)))))
(lambda (indent-here indent4recursive)
(begin
(if
indent-here
(lambda (kid)
(begin
(for-each
(lambda (x) (display x port))
indent-here)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
(lambda (kid)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
content)
(if indent-here
(begin
(display srl:newline port)
(for-each
(lambda (x) (display x port))
(cdr indentation))))
(for-each
(lambda (x) (display x port))
end-tag)))))))))))))
Creates the serialized representation for the XML declaration
(define (srl:make-xml-decl version standalone)
(let ((version (if (number? version) (number->string version) version)))
(if (eq? standalone 'omit)
(list "<?xml version='" version "'?>")
(list "<?xml version='" version "' standalone='"
(symbol->string standalone) "'?>"))))
(define (srl:top->nested-str-lst doc
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(let* ((namespace-assoc (srl:ns-assoc-for-top doc))
(ns-prefix-assig
(append
(srl:extract-original-prefix-binding namespace-assoc)
ns-prefix-assig))
(serialized-content
(map
(if
(lambda (kid)
(list
srl:newline
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data))))
(lambda (kid)
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc '()
indent #f
cdata-section-elements srl:string->char-data)))
TODO : support SXML entities
(not (and
(pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
doc))))
(if (or (eq? method 'html) omit-xml-declaration?)
(if (and indent (not (null? serialized-content)))
(cons (cadar serialized-content) (cdr serialized-content))
serialized-content)
(list (srl:make-xml-decl version standalone) serialized-content))))
(define (srl:display-top-out doc port
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
no XML declaration was displayed ?
(if (not (or (eq? method 'html) omit-xml-declaration?))
(begin
(lambda (x) (display x port))
(srl:make-xml-decl version standalone))
#f)
#t))
((srl:select-kids
TODO : support SXML entities
(not (and
(pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
doc))
(namespace-assoc (srl:ns-assoc-for-top doc)))
(let ((ns-prefix-assig
(append
(srl:extract-original-prefix-binding namespace-assoc)
ns-prefix-assig)))
(cond
((and indent no-xml-decl?)
(for-each
(lambda (kid put-newline?)
(begin
(if put-newline?
(display srl:newline port))
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data)))
content
(cons #f (cdr content)))))
(else
(for-each
(if
(lambda (kid)
(begin
(display srl:newline port)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data))))
(lambda (kid)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indent #f
cdata-section-elements srl:string->char-data)))
content))))))
Interface
additional serialization parameters , the functions ` srl : sxml->string ' and
` srl : display - sxml ' specified in this subsections may have a different number
cdata - section - elements : : = ( - name )
ns - prefix - assign : : = ( listof ( cons prefix - symbol namespace - uri - string ) )
version : : = number | string
(define (srl:sxml->string sxml-obj
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(srl:apply-string-append
(srl:clean-fragments
(srl:top->nested-str-lst (srl:normalize-sequence sxml-obj)
cdata-section-elements
(if (and indent (not (string? indent)))
" " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version))))
(define (srl:display-sxml sxml-obj port-or-filename
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(if
(let ((out (open-output-file port-or-filename)))
(begin
(srl:display-top-out (srl:normalize-sequence sxml-obj) out
cdata-section-elements
(if (and indent (not (string? indent)))
" " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version)
(close-output-port out)))
(srl:display-top-out (srl:normalize-sequence sxml-obj) port-or-filename
cdata-section-elements
(if (and indent (not (string? indent))) " " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version)))
procedure srl : parameterizable : : SXML - OBJ [ PORT ] { PARAM } * - >
sxml - obj - an SXML object to serialize
1 . cdata - section - elements
value : : = ( - elem - name )
sxml - elem - name : : = symbol
2 . indent
3 . method
4 . ns - prefix - assig
value : : = ( listof ( cons prefix namespace - uri ) )
5 . omit - xml - declaration ?
6 . standalone
7 . version
( srl : parameterizable
(define (srl:parameterizable sxml-obj . port-or-filename+params)
(call-with-values
(lambda ()
(if (and (not (null? port-or-filename+params))
(or (output-port? (car port-or-filename+params))
(string? (car port-or-filename+params))))
(values (car port-or-filename+params) (cdr port-or-filename+params))
(values #f port-or-filename+params)))
(lambda (port-or-filename params)
(let loop ((params params)
(cdata-section-elements '())
(indent " ")
(method 'xml)
(ns-prefix-assig srl:conventional-ns-prefixes)
(omit-xml-declaration? #t)
(standalone 'omit)
(version "1.0"))
(cond
(if port-or-filename
(srl:display-sxml sxml-obj port-or-filename
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(srl:sxml->string sxml-obj
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)))
(null? (cdar params)))
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version))
(else
(let ((prm-value (cdar params)))
(case (caar params)
((cdata-section-elements)
(loop (cdr params)
(if (list? prm-value) prm-value cdata-section-elements)
indent method ns-prefix-assig
omit-xml-declaration? standalone version))
((indent)
(loop (cdr params)
cdata-section-elements
(cond
((boolean? prm-value)
(if prm-value " " prm-value))
((string? prm-value) prm-value)
((eq? prm-value 'yes) " ")
((eq? prm-value 'no) #f)
(else indent))
method ns-prefix-assig
omit-xml-declaration? standalone version))
((method)
(loop (cdr params)
cdata-section-elements indent
(if (or (eq? prm-value 'xml) (eq? prm-value 'html))
prm-value method)
ns-prefix-assig
omit-xml-declaration? standalone version))
((ns-prefix-assig)
(loop (cdr params)
cdata-section-elements indent method
(if (and (list? prm-value)
(lambda (x) (not (pair? x)))
prm-value)))
(append prm-value ns-prefix-assig)
ns-prefix-assig)
omit-xml-declaration? standalone version))
((omit-xml-declaration)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
(cond
((boolean? prm-value) prm-value)
((eq? prm-value 'yes) #t)
((eq? prm-value 'no) #f)
(else indent))
standalone version))
((standalone)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig omit-xml-declaration?
(cond
((memv prm-value '(yes no omit))
prm-value)
((boolean? prm-value)
(if prm-value 'yes 'no))
(else standalone))
version))
((version)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone
(if (or (string? prm-value) (number? prm-value))
prm-value version)))
(else
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version))))))))))
procedure srl : sxml->xml : : SXML - OBJ [ PORT - OR - FILENAME ] - > STRING|unspecified
Serializes the ` sxml - obj ' into XML , with indentation to facilitate
sxml - obj - an SXML object ( a node or a nodeset ) to be serialized
(define (srl:sxml->xml sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #t 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")
(srl:display-sxml sxml-obj (car port-or-filename) '() #t 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")))
procedure srl : sxml->xml - noindent : : SXML - OBJ [ PORT - OR - FILENAME ] - >
Serializes the ` sxml - obj ' into XML , without indentation .
(define (srl:sxml->xml-noindent sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #f 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")
(srl:display-sxml sxml-obj (car port-or-filename) '() #f 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")))
procedure srl : sxml->html : : SXML - OBJ [ PORT - OR - FILENAME ] - > STRING|unspecified
Serializes the ` sxml - obj ' into HTML , with indentation to facilitate
sxml - obj - an SXML object ( a node or a nodeset ) to be serialized
(define (srl:sxml->html sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #t 'html '() #t 'omit "4.0")
(srl:display-sxml sxml-obj (car port-or-filename)
'() #t 'html '() #t 'omit "4.0")))
procedure srl : sxml->html - noindent : : SXML - OBJ [ PORT - OR - FILENAME ] - >
Serializes the ` sxml - obj ' into HTML , without indentation .
(define (srl:sxml->html-noindent sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #f 'html '() #t 'omit "4.0")
(srl:display-sxml sxml-obj (car port-or-filename)
'() #f 'html '() #t 'omit "4.0")))
|
66eff8cab48cd30364964a9aabcf064aa2b824c35276958d96d8a18858ccb711 | yrashk/erlang | ex_radioBox.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online 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.
%%
%% %CopyrightEnd%
-module(ex_radioBox).
-behavoiur(wx_object).
-export([start/1, init/1, terminate/2, code_change/3,
handle_info/2, handle_call/3, handle_event/2]).
-include_lib("wx/include/wx.hrl").
-record(state,
{
parent,
config,
radio_box
}).
start(Config) ->
wx_object:start_link(?MODULE, Config, []).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init(Config) ->
wx:batch(fun() -> do_init(Config) end).
do_init(Config) ->
Parent = proplists:get_value(parent, Config),
Panel = wxPanel:new(Parent, []),
%% Setup sizers
MainSizer = wxBoxSizer:new(?wxVERTICAL),
Choices = ["Item " ++ integer_to_list(Int) || Int <- lists:seq(1,12)],
RadioBox = wxRadioBox:new(Panel, 1, "wxRadioBox Horizontal",
?wxDefaultPosition,
?wxDefaultSize,
Choices,
[{majorDim, 3},
{style, ?wxHORIZONTAL}]),
wxRadioBox:connect(RadioBox, command_radiobox_selected),
RadioButtonSizer = create_radio_buttons(Panel),
CheckSizer = create_checkboxes(Panel),
%% Add to sizers
Sizer = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(Sizer, RadioButtonSizer),
wxSizer:addSpacer(Sizer, 20),
wxSizer:add(Sizer, CheckSizer),
wxSizer:add(MainSizer, RadioBox),
wxSizer:addSpacer(MainSizer, 20),
wxSizer:add(MainSizer, Sizer),
wxPanel:setSizer(Panel, MainSizer),
{Panel, #state{parent=Panel, config=Config,
radio_box = RadioBox}}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Callbacks handled as normal gen_server callbacks
handle_info(Msg, State) ->
demo:format(State#state.config, "Got Info ~p\n",[Msg]),
{noreply, State}.
handle_call(Msg, _From, State) ->
demo:format(State#state.config,"Got Call ~p\n",[Msg]),
{reply, {error, nyi}, State}.
%% Async Events are handled in handle_event as in handle_info
handle_event(#wx{event = #wxCommand{type = command_radiobox_selected,
cmdString = Item}},
State = #state{}) ->
demo:format(State#state.config,"wxRadioBox selected ~p\n",[Item]),
{noreply, State};
handle_event(#wx{obj = Checkbox,
event = #wxCommand{type = command_checkbox_clicked,
commandInt = Int}},
State = #state{config = Config}) ->
Label = wxCheckBox:getLabel(Checkbox),
case Int of
0 -> demo:format(Config,"wxCheckBox deselected ~p\n",[Label]);
1 -> demo:format(Config,"wxCheckBox selected ~p \n",[Label]);
2 -> demo:format(Config,"wxCheckBox middle-state ~p\n",[Label])
end,
{noreply, State};
handle_event(#wx{obj = RadioButton,
event = #wxCommand{type = command_radiobutton_selected}},
State = #state{}) ->
Label = wxRadioButton:getLabel(RadioButton),
demo:format(State#state.config,"wxRadioButton selected ~p\n",[Label]),
{noreply, State};
handle_event(Ev = #wx{}, State = #state{}) ->
demo:format(State#state.config,"Got Event ~p\n",[Ev]),
{noreply, State}.
code_change(_, _, State) ->
{stop, ignore, State}.
terminate(_Reason, _State) ->
ok.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Local functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
create_checkboxes(Panel) ->
CheckSizer = wxStaticBoxSizer:new(?wxVERTICAL, Panel,
[{label, "wxCheckBox"}]),
CheckBoxes =
[wxCheckBox:new(Panel, ?wxID_ANY, "Label1", []),
wxCheckBox:new(Panel, ?wxID_ANY, "Label2", []),
wxCheckBox:new(Panel, ?wxID_ANY, "Label3", []),
wxCheckBox:new(Panel, ?wxID_ANY, "3-state checkbox",
[{style, ?wxCHK_3STATE bor
?wxCHK_ALLOW_3RD_STATE_FOR_USER}]),
wxCheckBox:new(Panel, ?wxID_ANY, "Right aligned",
[{style, ?wxALIGN_RIGHT}])],
Fun =
fun(Item) ->
wxCheckBox:connect(Item, command_checkbox_clicked),
wxSizer:add(CheckSizer, Item)
end,
wx:foreach(Fun, CheckBoxes),
CheckSizer.
create_radio_buttons(Panel) ->
RadioButtonSizer = wxStaticBoxSizer:new(?wxVERTICAL, Panel,
[{label, "wxRadioButton"}]),
Buttons =
[wxRadioButton:new(Panel, ?wxID_ANY, "Group1 Radio1",
[{style, ?wxRB_GROUP}]),
wxRadioButton:new(Panel, ?wxID_ANY, "Group1 Radio2", []),
wxRadioButton:new(Panel, ?wxID_ANY, "Group1 Radio3", []),
wxRadioButton:new(Panel, ?wxID_ANY, "Group2 Radio1",
[{style, ?wxRB_GROUP}]),
wxRadioButton:new(Panel, ?wxID_ANY, "Group2 Radio2", []),
wxRadioButton:new(Panel, ?wxID_ANY, "Group2 Radio3", [])],
Fun =
fun(Item) ->
wxRadioButton:connect(Item, command_radiobutton_selected),
wxSizer:add(RadioButtonSizer, Item)
end,
wx:foreach(Fun, Buttons),
RadioButtonSizer.
| null | https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/wx/examples/demo/ex_radioBox.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online 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.
%CopyrightEnd%
Setup sizers
Add to sizers
Callbacks handled as normal gen_server callbacks
Async Events are handled in handle_event as in handle_info
Local functions
| Copyright Ericsson AB 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(ex_radioBox).
-behavoiur(wx_object).
-export([start/1, init/1, terminate/2, code_change/3,
handle_info/2, handle_call/3, handle_event/2]).
-include_lib("wx/include/wx.hrl").
-record(state,
{
parent,
config,
radio_box
}).
start(Config) ->
wx_object:start_link(?MODULE, Config, []).
init(Config) ->
wx:batch(fun() -> do_init(Config) end).
do_init(Config) ->
Parent = proplists:get_value(parent, Config),
Panel = wxPanel:new(Parent, []),
MainSizer = wxBoxSizer:new(?wxVERTICAL),
Choices = ["Item " ++ integer_to_list(Int) || Int <- lists:seq(1,12)],
RadioBox = wxRadioBox:new(Panel, 1, "wxRadioBox Horizontal",
?wxDefaultPosition,
?wxDefaultSize,
Choices,
[{majorDim, 3},
{style, ?wxHORIZONTAL}]),
wxRadioBox:connect(RadioBox, command_radiobox_selected),
RadioButtonSizer = create_radio_buttons(Panel),
CheckSizer = create_checkboxes(Panel),
Sizer = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(Sizer, RadioButtonSizer),
wxSizer:addSpacer(Sizer, 20),
wxSizer:add(Sizer, CheckSizer),
wxSizer:add(MainSizer, RadioBox),
wxSizer:addSpacer(MainSizer, 20),
wxSizer:add(MainSizer, Sizer),
wxPanel:setSizer(Panel, MainSizer),
{Panel, #state{parent=Panel, config=Config,
radio_box = RadioBox}}.
handle_info(Msg, State) ->
demo:format(State#state.config, "Got Info ~p\n",[Msg]),
{noreply, State}.
handle_call(Msg, _From, State) ->
demo:format(State#state.config,"Got Call ~p\n",[Msg]),
{reply, {error, nyi}, State}.
handle_event(#wx{event = #wxCommand{type = command_radiobox_selected,
cmdString = Item}},
State = #state{}) ->
demo:format(State#state.config,"wxRadioBox selected ~p\n",[Item]),
{noreply, State};
handle_event(#wx{obj = Checkbox,
event = #wxCommand{type = command_checkbox_clicked,
commandInt = Int}},
State = #state{config = Config}) ->
Label = wxCheckBox:getLabel(Checkbox),
case Int of
0 -> demo:format(Config,"wxCheckBox deselected ~p\n",[Label]);
1 -> demo:format(Config,"wxCheckBox selected ~p \n",[Label]);
2 -> demo:format(Config,"wxCheckBox middle-state ~p\n",[Label])
end,
{noreply, State};
handle_event(#wx{obj = RadioButton,
event = #wxCommand{type = command_radiobutton_selected}},
State = #state{}) ->
Label = wxRadioButton:getLabel(RadioButton),
demo:format(State#state.config,"wxRadioButton selected ~p\n",[Label]),
{noreply, State};
handle_event(Ev = #wx{}, State = #state{}) ->
demo:format(State#state.config,"Got Event ~p\n",[Ev]),
{noreply, State}.
code_change(_, _, State) ->
{stop, ignore, State}.
terminate(_Reason, _State) ->
ok.
create_checkboxes(Panel) ->
CheckSizer = wxStaticBoxSizer:new(?wxVERTICAL, Panel,
[{label, "wxCheckBox"}]),
CheckBoxes =
[wxCheckBox:new(Panel, ?wxID_ANY, "Label1", []),
wxCheckBox:new(Panel, ?wxID_ANY, "Label2", []),
wxCheckBox:new(Panel, ?wxID_ANY, "Label3", []),
wxCheckBox:new(Panel, ?wxID_ANY, "3-state checkbox",
[{style, ?wxCHK_3STATE bor
?wxCHK_ALLOW_3RD_STATE_FOR_USER}]),
wxCheckBox:new(Panel, ?wxID_ANY, "Right aligned",
[{style, ?wxALIGN_RIGHT}])],
Fun =
fun(Item) ->
wxCheckBox:connect(Item, command_checkbox_clicked),
wxSizer:add(CheckSizer, Item)
end,
wx:foreach(Fun, CheckBoxes),
CheckSizer.
create_radio_buttons(Panel) ->
RadioButtonSizer = wxStaticBoxSizer:new(?wxVERTICAL, Panel,
[{label, "wxRadioButton"}]),
Buttons =
[wxRadioButton:new(Panel, ?wxID_ANY, "Group1 Radio1",
[{style, ?wxRB_GROUP}]),
wxRadioButton:new(Panel, ?wxID_ANY, "Group1 Radio2", []),
wxRadioButton:new(Panel, ?wxID_ANY, "Group1 Radio3", []),
wxRadioButton:new(Panel, ?wxID_ANY, "Group2 Radio1",
[{style, ?wxRB_GROUP}]),
wxRadioButton:new(Panel, ?wxID_ANY, "Group2 Radio2", []),
wxRadioButton:new(Panel, ?wxID_ANY, "Group2 Radio3", [])],
Fun =
fun(Item) ->
wxRadioButton:connect(Item, command_radiobutton_selected),
wxSizer:add(RadioButtonSizer, Item)
end,
wx:foreach(Fun, Buttons),
RadioButtonSizer.
|
9d1343936351c88907f6fa36caab9de62e543c98618d244cc1f0f6f4adb52a77 | gar1t/erlang-czmq | czmq_poller.erl | %% ===================================================================
@author < >
2014
%%
%% @doc Polling process for socket messages.
%%
As is implemented as an external port , it uses all .
%% non blocking operations. Message devliery must be performed by
%% routinely polling a socket.
%%
%% @end
%% ===================================================================
-module(czmq_poller).
-behavior(gen_server).
-export([start/2, start_link/2, stop/1]).
-export([init/1, handle_info/2, handle_cast/2, handle_call/3,
terminate/2, code_change/3]).
-record(state, {socket, dispatch, interval, start}).
-define(DEFAULT_POLL_INTERVAL, 1000).
%%%===================================================================
%%% Start / init
%%%===================================================================
start(Socket, Options) ->
gen_server:start(?MODULE, [Socket, Options, self()], []).
start_link(Socket, Options) ->
gen_server:start_link(?MODULE, [Socket, Options, self()], []).
init([Socket, Options, Parent]) ->
DispatchOption = dispatch_option(Options),
Target = maybe_target(DispatchOption, Options, Parent),
maybe_monitor(Target),
DispatchFun = dispatch_fun(DispatchOption, Target),
Interval = poll_interval_option(Options),
Start = timestamp(),
State = #state{
socket=Socket,
dispatch=DispatchFun,
interval=Interval,
start=Start},
{ok, State, 0}.
dispatch_option(Options) ->
proplists:get_value(dispatch, Options).
maybe_target(undefined, Options, Parent) ->
proplists:get_value(target, Options, Parent);
maybe_target(_Dispatch, _Options, _Parent) ->
undefined.
maybe_monitor(undefined) -> ok;
maybe_monitor(Pid) -> erlang:monitor(process, Pid).
dispatch_fun(undefined, Target) ->
fun(Msg) -> erlang:send(Target, {self(), Msg}) end;
dispatch_fun(Dispatch, _Target) ->
Dispatch.
poll_interval_option(Options) ->
proplists:get_value(poll_interval, Options, ?DEFAULT_POLL_INTERVAL).
timestamp() ->
{M, S, U} = erlang:timestamp(),
M * 1000000000 + S * 1000 + U div 1000.
%%%===================================================================
%%% API
%%%===================================================================
stop(Poller) ->
gen_server:call(Poller, stop).
%%%===================================================================
%%% Message dispatch
%%%===================================================================
handle_info(timeout, State) ->
handle_poll(State);
handle_info({'DOWN', _Ref, process, _Proc, _Reason}, State) ->
{stop, normal, State}.
%%%===================================================================
%%% Poll for / dispatch messages
%%%===================================================================
handle_poll(State) ->
dispatch_messages(State),
schedule_next(State),
{noreply, State}.
dispatch_messages(State) ->
handle_recv_msg(recv_msg(State, []), State).
recv_msg(State, FramesAcc) ->
handle_recv_frame(recv_frame(State), State, FramesAcc).
recv_frame(#state{socket=Socket}) ->
czmq:zframe_recv_nowait(Socket).
handle_recv_frame({ok, {Data, More}}, State, FramesAcc) ->
handle_frame_more(More, State, [Data|FramesAcc]);
handle_recv_frame(error, _State, _FramesAcc) ->
error.
handle_frame_more(true, State, FramesAcc) ->
handle_recv_frame(recv_frame(State), State, FramesAcc);
handle_frame_more(false, _State, FramesAcc) ->
{ok, lists:reverse(FramesAcc)}.
handle_recv_msg({ok, Msg}, State) ->
dispatch_msg(Msg, State),
dispatch_messages(State);
handle_recv_msg(error, _State) ->
ok.
dispatch_msg(Msg, #state{dispatch=Dispatch}) ->
Dispatch(Msg).
schedule_next(State) ->
erlang:send_after(next_delay(State), self(), timeout).
next_delay(#state{start=Start, interval=Interval}) ->
Now = timestamp(),
((Now - Start) div Interval + 1) * Interval + Start - Now.
%%%===================================================================
%%% Handle stop
%%%===================================================================
handle_call(stop, _From, State) ->
{stop, normal, ok, State}.
%%%===================================================================
%%% gen_server boilderplate
%%%===================================================================
handle_cast(_Msg, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
| null | https://raw.githubusercontent.com/gar1t/erlang-czmq/530c976ee4d0892294ac0468e366ad65c70e6a50/src/czmq_poller.erl | erlang | ===================================================================
@doc Polling process for socket messages.
non blocking operations. Message devliery must be performed by
routinely polling a socket.
@end
===================================================================
===================================================================
Start / init
===================================================================
===================================================================
API
===================================================================
===================================================================
Message dispatch
===================================================================
===================================================================
Poll for / dispatch messages
===================================================================
===================================================================
Handle stop
===================================================================
===================================================================
gen_server boilderplate
=================================================================== | @author < >
2014
As is implemented as an external port , it uses all .
-module(czmq_poller).
-behavior(gen_server).
-export([start/2, start_link/2, stop/1]).
-export([init/1, handle_info/2, handle_cast/2, handle_call/3,
terminate/2, code_change/3]).
-record(state, {socket, dispatch, interval, start}).
-define(DEFAULT_POLL_INTERVAL, 1000).
start(Socket, Options) ->
gen_server:start(?MODULE, [Socket, Options, self()], []).
start_link(Socket, Options) ->
gen_server:start_link(?MODULE, [Socket, Options, self()], []).
init([Socket, Options, Parent]) ->
DispatchOption = dispatch_option(Options),
Target = maybe_target(DispatchOption, Options, Parent),
maybe_monitor(Target),
DispatchFun = dispatch_fun(DispatchOption, Target),
Interval = poll_interval_option(Options),
Start = timestamp(),
State = #state{
socket=Socket,
dispatch=DispatchFun,
interval=Interval,
start=Start},
{ok, State, 0}.
dispatch_option(Options) ->
proplists:get_value(dispatch, Options).
maybe_target(undefined, Options, Parent) ->
proplists:get_value(target, Options, Parent);
maybe_target(_Dispatch, _Options, _Parent) ->
undefined.
maybe_monitor(undefined) -> ok;
maybe_monitor(Pid) -> erlang:monitor(process, Pid).
dispatch_fun(undefined, Target) ->
fun(Msg) -> erlang:send(Target, {self(), Msg}) end;
dispatch_fun(Dispatch, _Target) ->
Dispatch.
poll_interval_option(Options) ->
proplists:get_value(poll_interval, Options, ?DEFAULT_POLL_INTERVAL).
timestamp() ->
{M, S, U} = erlang:timestamp(),
M * 1000000000 + S * 1000 + U div 1000.
stop(Poller) ->
gen_server:call(Poller, stop).
handle_info(timeout, State) ->
handle_poll(State);
handle_info({'DOWN', _Ref, process, _Proc, _Reason}, State) ->
{stop, normal, State}.
handle_poll(State) ->
dispatch_messages(State),
schedule_next(State),
{noreply, State}.
dispatch_messages(State) ->
handle_recv_msg(recv_msg(State, []), State).
recv_msg(State, FramesAcc) ->
handle_recv_frame(recv_frame(State), State, FramesAcc).
recv_frame(#state{socket=Socket}) ->
czmq:zframe_recv_nowait(Socket).
handle_recv_frame({ok, {Data, More}}, State, FramesAcc) ->
handle_frame_more(More, State, [Data|FramesAcc]);
handle_recv_frame(error, _State, _FramesAcc) ->
error.
handle_frame_more(true, State, FramesAcc) ->
handle_recv_frame(recv_frame(State), State, FramesAcc);
handle_frame_more(false, _State, FramesAcc) ->
{ok, lists:reverse(FramesAcc)}.
handle_recv_msg({ok, Msg}, State) ->
dispatch_msg(Msg, State),
dispatch_messages(State);
handle_recv_msg(error, _State) ->
ok.
dispatch_msg(Msg, #state{dispatch=Dispatch}) ->
Dispatch(Msg).
schedule_next(State) ->
erlang:send_after(next_delay(State), self(), timeout).
next_delay(#state{start=Start, interval=Interval}) ->
Now = timestamp(),
((Now - Start) div Interval + 1) * Interval + Start - Now.
handle_call(stop, _From, State) ->
{stop, normal, ok, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
74e71b2f8b3d835140eef511e85be8b20e3a1e38b1d9e1663478d8b333ae4018 | purcell/adventofcode2016 | Day12.hs | module Main where
import AdventOfCode
import Control.Monad.State
import Control.Monad.Reader
import Data.Maybe (fromMaybe)
import Data.Map (Map)
import qualified Data.Map as M
data Reg =
Reg Char
deriving (Show)
data Value
= LitVal Int
| RegVal Reg
deriving (Show)
data Instr
= Copy Value
Reg
| JumpNotZero Value
Int
| Inc Reg
| Dec Reg
deriving (Show)
parseInstr :: Parser Instr
parseInstr =
(Dec <$> (string "dec " *> reg)) <|> (Inc <$> (string "inc " *> reg)) <|>
(JumpNotZero <$> (string "jnz " *> val) <*> (string " " *> step)) <|>
(Copy <$> (string "cpy " *> val) <*> (string " " *> reg))
where
reg = Reg <$> letter
val = (RegVal <$> reg) <|> (LitVal <$> num)
step = num
num = do
sign <- option '+' (char '-')
digits <- many1 digit
return $
(if sign == '-'
then -1
else 1) *
read digits
data SimState = SimState
{ stPos :: Int
, stRegs :: (Map Char Int)
}
type Sim = ReaderT [Instr] (State SimState)
run :: Sim ()
run = do
pos <- gets stPos
instrs <- ask
when (pos >= 0 && pos < length instrs) $
do step <- lift $ runInstr (instrs !! pos)
modify
(\st ->
st
{ stPos = stPos st + step
})
run
modifyReg :: Reg -> (Int -> Int) -> State SimState ()
modifyReg r@(Reg n) f = do
prev <- getReg r
modify
(\st ->
let regs = stRegs st
in st
{ stRegs = M.insert n (f prev) regs
})
getReg :: Reg -> State SimState Int
getReg (Reg n) = (fromMaybe 0 . M.lookup n) <$> gets stRegs
getVal :: Value -> State SimState Int
getVal (LitVal v) = return v
getVal (RegVal r) = getReg r
runInstr :: Instr -> State SimState Int
runInstr (Copy val reg) = (getVal val >>= modifyReg reg . const) >> return 1
runInstr (JumpNotZero val step) = do
v <- getVal val
return $
if v /= 0
then step
else 1
runInstr (Inc reg) = modifyReg reg (+ 1) >> return 1
runInstr (Dec reg) = modifyReg reg (\i -> i - 1) >> return 1
finalA :: Map Char Int -> [Instr] -> Int
finalA regs =
(M.! 'a') . stRegs . flip execState (SimState 0 regs) . runReaderT run
partA = finalA M.empty
partB = finalA (M.singleton 'c' 1)
main =
runDay $
Day
12
(many (parseInstr <* newline))
(return . show . partA)
(return . show . partB)
| null | https://raw.githubusercontent.com/purcell/adventofcode2016/081f30de4ea6b939e6c3736d83836f4dd72ab9a2/src/Day12.hs | haskell | module Main where
import AdventOfCode
import Control.Monad.State
import Control.Monad.Reader
import Data.Maybe (fromMaybe)
import Data.Map (Map)
import qualified Data.Map as M
data Reg =
Reg Char
deriving (Show)
data Value
= LitVal Int
| RegVal Reg
deriving (Show)
data Instr
= Copy Value
Reg
| JumpNotZero Value
Int
| Inc Reg
| Dec Reg
deriving (Show)
parseInstr :: Parser Instr
parseInstr =
(Dec <$> (string "dec " *> reg)) <|> (Inc <$> (string "inc " *> reg)) <|>
(JumpNotZero <$> (string "jnz " *> val) <*> (string " " *> step)) <|>
(Copy <$> (string "cpy " *> val) <*> (string " " *> reg))
where
reg = Reg <$> letter
val = (RegVal <$> reg) <|> (LitVal <$> num)
step = num
num = do
sign <- option '+' (char '-')
digits <- many1 digit
return $
(if sign == '-'
then -1
else 1) *
read digits
data SimState = SimState
{ stPos :: Int
, stRegs :: (Map Char Int)
}
type Sim = ReaderT [Instr] (State SimState)
run :: Sim ()
run = do
pos <- gets stPos
instrs <- ask
when (pos >= 0 && pos < length instrs) $
do step <- lift $ runInstr (instrs !! pos)
modify
(\st ->
st
{ stPos = stPos st + step
})
run
modifyReg :: Reg -> (Int -> Int) -> State SimState ()
modifyReg r@(Reg n) f = do
prev <- getReg r
modify
(\st ->
let regs = stRegs st
in st
{ stRegs = M.insert n (f prev) regs
})
getReg :: Reg -> State SimState Int
getReg (Reg n) = (fromMaybe 0 . M.lookup n) <$> gets stRegs
getVal :: Value -> State SimState Int
getVal (LitVal v) = return v
getVal (RegVal r) = getReg r
runInstr :: Instr -> State SimState Int
runInstr (Copy val reg) = (getVal val >>= modifyReg reg . const) >> return 1
runInstr (JumpNotZero val step) = do
v <- getVal val
return $
if v /= 0
then step
else 1
runInstr (Inc reg) = modifyReg reg (+ 1) >> return 1
runInstr (Dec reg) = modifyReg reg (\i -> i - 1) >> return 1
finalA :: Map Char Int -> [Instr] -> Int
finalA regs =
(M.! 'a') . stRegs . flip execState (SimState 0 regs) . runReaderT run
partA = finalA M.empty
partB = finalA (M.singleton 'c' 1)
main =
runDay $
Day
12
(many (parseInstr <* newline))
(return . show . partA)
(return . show . partB)
| |
6c13030452ec793e901b9fa0ef5b216f59476db0f8c3288677a735428566f04d | danx0r/festival | ogi_span_mx_phrasing.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<--CSLU-->;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
Center for Spoken Language Understanding ; ;
Oregon Graduate Institute of Science & Technology ; ;
Portland , OR USA ; ;
Copyright ( c ) 1999 ; ;
;; ;;
This module is not part of the CSTR / University of Edinburgh ; ;
;; release of the Festival TTS system. ;;
;; ;;
;; In addition to any conditions disclaimers below, please see the file ;;
" license_cslu_tts.txt " distributed with this software for information ; ;
;; on usage and redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<--CSLU-->;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Phrase breaks
;;; use punctuation only
(set! span_mx_phrase_cart_tree
'
((R:Token.parent.punc in ("?" "." ":"))
((B))
((R:Token.parent.punc in ("'" "\"" "," ";"))
((B))
((R:Token.parent.n.name in ("y"))
((B))
((n.name is 0) ;; end of utterance
((B))
((NB))
)
)
)
)
)
(provide 'cslu_span_mx_phrasing)
| null | https://raw.githubusercontent.com/danx0r/festival/6701715566aee6519a8b7949b567f2fdad1e2772/lib/ogi/ogi_spanish/ogi_span_mx_phrasing.scm | scheme | <--CSLU-->;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;
;
;
;
;;
;
release of the Festival TTS system. ;;
;;
In addition to any conditions disclaimers below, please see the file ;;
;
on usage and redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ;;
;;
<--CSLU-->;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Phrase breaks
use punctuation only
"))
end of utterance
|
(set! span_mx_phrase_cart_tree
'
((R:Token.parent.punc in ("?" "." ":"))
((B))
((B))
((R:Token.parent.n.name in ("y"))
((B))
((B))
((NB))
)
)
)
)
)
(provide 'cslu_span_mx_phrasing)
|
0243bcf12008e9e954c03d8bc7593797791921746d25738f8b534835645b8bf8 | janestreet/krb | server_key_source.mli | open! Core
open! Async
* Kerberos clients send encrypted tickets for servers . One of the central underpinning
of Kerberos is that only the KDC and the target server know this secret encryption
key .
A [ Server_key_source.t ] represents which key is used to encrypt service tickets . The
[ Keytab ] variant should be used for as - users . The [ Tgt ] variant should be used for
human users . [ default ( ) ] will make this choice for you based on the currently running
user .
See [ .. /doc / index.mkd ] for more information on how Kerberos works .
of Kerberos is that only the KDC and the target server know this secret encryption
key.
A [Server_key_source.t] represents which key is used to encrypt service tickets. The
[Keytab] variant should be used for as-users. The [Tgt] variant should be used for
human users. [default ()] will make this choice for you based on the currently running
user.
See [../doc/index.mkd] for more information on how Kerberos works.
*)
type t =
| Tgt
* Use the session key associated with the server 's ticket granting ticket ( TGT ) . The
user must have a valid TGT in its cred cache . This is the recommended setup for
human users that do n't have keytabs .
user must have a valid TGT in its cred cache. This is the recommended setup for
human users that don't have keytabs. *)
| Keytab of Principal.Name.t * Keytab.Path.t
* Use the password - derived key for the specified principal that is stored in the
specified keytab .
specified keytab. *)
[@@deriving compare, hash, sexp_of]
* Make a best effort attempt to validate [ t ] . This can be used as a way to fail early
after getting a [ t ] from the command line . It is automatically called with
[ ~refresh_tgt :() ] before all and Rpc client connections .
[ refresh_tgt ] will start a background job to refresh credentials in the [ Keytab ] case .
Note : it is still possible for this function to return a success but a later call
that uses [ t ] to fail . This might be because a ticket has expired or because some
other process has been mucking around with the credential cache .
after getting a [t] from the command line. It is automatically called with
[~refresh_tgt:()] before all Tcp and Rpc client connections.
[refresh_tgt] will start a background job to refresh credentials in the [Keytab] case.
Note: it is still possible for this function to return a success but a later call
that uses [t] to fail. This might be because a ticket has expired or because some
other process has been mucking around with the credential cache. *)
val best_effort_validate
: ?refresh_tgt:unit
-> cred_cache:Cred_cache.t
-> t
-> unit Deferred.Or_error.t
* [ principal t ] returns the [ Principal.t ] that will be used
to start kerberized services
to start kerberized services *)
val principal : t -> Principal.t Deferred.Or_error.t
module Stable : sig
module V2 : Stable_without_comparator with type t = t
end
| null | https://raw.githubusercontent.com/janestreet/krb/1105ba1e8b836f80f09e663bc1b4233cf2607e7b/src/server_key_source.mli | ocaml | open! Core
open! Async
* Kerberos clients send encrypted tickets for servers . One of the central underpinning
of Kerberos is that only the KDC and the target server know this secret encryption
key .
A [ Server_key_source.t ] represents which key is used to encrypt service tickets . The
[ Keytab ] variant should be used for as - users . The [ Tgt ] variant should be used for
human users . [ default ( ) ] will make this choice for you based on the currently running
user .
See [ .. /doc / index.mkd ] for more information on how Kerberos works .
of Kerberos is that only the KDC and the target server know this secret encryption
key.
A [Server_key_source.t] represents which key is used to encrypt service tickets. The
[Keytab] variant should be used for as-users. The [Tgt] variant should be used for
human users. [default ()] will make this choice for you based on the currently running
user.
See [../doc/index.mkd] for more information on how Kerberos works.
*)
type t =
| Tgt
* Use the session key associated with the server 's ticket granting ticket ( TGT ) . The
user must have a valid TGT in its cred cache . This is the recommended setup for
human users that do n't have keytabs .
user must have a valid TGT in its cred cache. This is the recommended setup for
human users that don't have keytabs. *)
| Keytab of Principal.Name.t * Keytab.Path.t
* Use the password - derived key for the specified principal that is stored in the
specified keytab .
specified keytab. *)
[@@deriving compare, hash, sexp_of]
* Make a best effort attempt to validate [ t ] . This can be used as a way to fail early
after getting a [ t ] from the command line . It is automatically called with
[ ~refresh_tgt :() ] before all and Rpc client connections .
[ refresh_tgt ] will start a background job to refresh credentials in the [ Keytab ] case .
Note : it is still possible for this function to return a success but a later call
that uses [ t ] to fail . This might be because a ticket has expired or because some
other process has been mucking around with the credential cache .
after getting a [t] from the command line. It is automatically called with
[~refresh_tgt:()] before all Tcp and Rpc client connections.
[refresh_tgt] will start a background job to refresh credentials in the [Keytab] case.
Note: it is still possible for this function to return a success but a later call
that uses [t] to fail. This might be because a ticket has expired or because some
other process has been mucking around with the credential cache. *)
val best_effort_validate
: ?refresh_tgt:unit
-> cred_cache:Cred_cache.t
-> t
-> unit Deferred.Or_error.t
* [ principal t ] returns the [ Principal.t ] that will be used
to start kerberized services
to start kerberized services *)
val principal : t -> Principal.t Deferred.Or_error.t
module Stable : sig
module V2 : Stable_without_comparator with type t = t
end
| |
870a38fc29f113db67edb3b03c0ee73365644ea42be04f102960bfda2fe3ae5c | ekmett/hyphenation | Pattern.hs | # LANGUAGE CPP #
-----------------------------------------------------------------------------
-- |
-- Module : Text.Hyphenation.Pattern
Copyright : ( C ) 2012 - 2019
-- License : BSD-style (see the file LICENSE)
--
Maintainer : < >
-- Stability : provisional
-- Portability : portable
--
----------------------------------------------------------------------------
module Text.Hyphenation.Pattern
(
-- * Pattern file support
Patterns
, insertPattern
, lookupPattern
, scorePattern
, parsePatterns
) where
import qualified Data.IntMap as IM
import Prelude hiding (lookup)
import Data.Char (digitToInt, isDigit)
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid (Monoid(..))
#endif
#if !(MIN_VERSION_base(4,11,0))
import Data.Semigroup (Semigroup(..))
#endif
| Hyphenation patterns
data Patterns = Patterns [Int] (IM.IntMap Patterns)
deriving Show
instance Semigroup Patterns where
Patterns ps m <> Patterns qs n = Patterns (zipMax ps qs) (IM.unionWith mappend m n)
instance Monoid Patterns where
mempty = Patterns [] IM.empty
#if !(MIN_VERSION_base(4,11,0))
mappend = (<>)
#endif
-- | Tallies the hyphenation scores for a word considering all tails.
lookupPattern :: String -> Patterns -> [Int]
lookupPattern xs0 = init . tail . go ('.' : xs0 ++ ".") where
go [] (Patterns ys _) = ys
go xxs@(_:xs) t = zipMax (go1 xxs t) (0:go xs t)
go1 [] (Patterns ys _) = ys
go1 (x:xs) (Patterns ys m) = case IM.lookup (fromEnum x) m of
Just t' -> zipMax ys (go1 xs t')
Nothing -> ys
| Insert a Knuth - Liang hyphenation pattern into the trie
--
1 . @.@ denotes the start or end of the input
--
2 . @0 - 9@ are used to denote hyphenation or dehyphenation depending on whether or not they are even ( no hyphen ) or odd ( hyphen allowed ) .
--
-- Patterns are overlaid and the maximum value at each location is used.
-- this allows you to implement a finite number of precedences between hyphenation rules
--
( e.g. @3foo.@ indicates that the suffix ' -foo ' should be hyphenated with precedence 3 . )
insertPattern :: String -> Patterns -> Patterns
insertPattern s0 = go (chars s0) where
pts = scorePattern s0
go [] (Patterns _ m) = Patterns pts m
go (x:xs) (Patterns n m) = Patterns n (IM.insertWith (\_ -> go xs) (fromEnum x) (mk xs) m)
mk [] = Patterns pts IM.empty
mk (x:xs) = Patterns [] (IM.singleton (fromEnum x) (mk xs))
| Parse one pattern per line from an input string
--
@hyph - utf8@ supplies these files UTF-8 encoded in the @txt@ folder with a @.pat.txt@ extension
parsePatterns :: String -> Patterns
parsePatterns = foldr insertPattern mempty . lines
chars :: String -> String
chars = filter (\x -> x < '0' || x > '9')
-- | Convert a Pattern string to a Score
scorePattern :: String -> [Int]
scorePattern [] = [0]
scorePattern (x:ys)
| isDigit x = digitToInt x : if null ys then [] else scorePattern (tail ys)
| otherwise = 0 : scorePattern ys
| Zip two scores .
zipMax :: [Int] -> [Int] -> [Int]
zipMax (x:xs) (y:ys) = max x y : zipMax xs ys
zipMax [] ys = ys
zipMax xs [] = xs
| null | https://raw.githubusercontent.com/ekmett/hyphenation/7fc0923f613fca64e3a294ec19f1db46d42c56bc/src/Text/Hyphenation/Pattern.hs | haskell | ---------------------------------------------------------------------------
|
Module : Text.Hyphenation.Pattern
License : BSD-style (see the file LICENSE)
Stability : provisional
Portability : portable
--------------------------------------------------------------------------
* Pattern file support
| Tallies the hyphenation scores for a word considering all tails.
Patterns are overlaid and the maximum value at each location is used.
this allows you to implement a finite number of precedences between hyphenation rules
| Convert a Pattern string to a Score | # LANGUAGE CPP #
Copyright : ( C ) 2012 - 2019
Maintainer : < >
module Text.Hyphenation.Pattern
(
Patterns
, insertPattern
, lookupPattern
, scorePattern
, parsePatterns
) where
import qualified Data.IntMap as IM
import Prelude hiding (lookup)
import Data.Char (digitToInt, isDigit)
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid (Monoid(..))
#endif
#if !(MIN_VERSION_base(4,11,0))
import Data.Semigroup (Semigroup(..))
#endif
| Hyphenation patterns
data Patterns = Patterns [Int] (IM.IntMap Patterns)
deriving Show
instance Semigroup Patterns where
Patterns ps m <> Patterns qs n = Patterns (zipMax ps qs) (IM.unionWith mappend m n)
instance Monoid Patterns where
mempty = Patterns [] IM.empty
#if !(MIN_VERSION_base(4,11,0))
mappend = (<>)
#endif
lookupPattern :: String -> Patterns -> [Int]
lookupPattern xs0 = init . tail . go ('.' : xs0 ++ ".") where
go [] (Patterns ys _) = ys
go xxs@(_:xs) t = zipMax (go1 xxs t) (0:go xs t)
go1 [] (Patterns ys _) = ys
go1 (x:xs) (Patterns ys m) = case IM.lookup (fromEnum x) m of
Just t' -> zipMax ys (go1 xs t')
Nothing -> ys
| Insert a Knuth - Liang hyphenation pattern into the trie
1 . @.@ denotes the start or end of the input
2 . @0 - 9@ are used to denote hyphenation or dehyphenation depending on whether or not they are even ( no hyphen ) or odd ( hyphen allowed ) .
( e.g. @3foo.@ indicates that the suffix ' -foo ' should be hyphenated with precedence 3 . )
insertPattern :: String -> Patterns -> Patterns
insertPattern s0 = go (chars s0) where
pts = scorePattern s0
go [] (Patterns _ m) = Patterns pts m
go (x:xs) (Patterns n m) = Patterns n (IM.insertWith (\_ -> go xs) (fromEnum x) (mk xs) m)
mk [] = Patterns pts IM.empty
mk (x:xs) = Patterns [] (IM.singleton (fromEnum x) (mk xs))
| Parse one pattern per line from an input string
@hyph - utf8@ supplies these files UTF-8 encoded in the @txt@ folder with a @.pat.txt@ extension
parsePatterns :: String -> Patterns
parsePatterns = foldr insertPattern mempty . lines
chars :: String -> String
chars = filter (\x -> x < '0' || x > '9')
scorePattern :: String -> [Int]
scorePattern [] = [0]
scorePattern (x:ys)
| isDigit x = digitToInt x : if null ys then [] else scorePattern (tail ys)
| otherwise = 0 : scorePattern ys
| Zip two scores .
zipMax :: [Int] -> [Int] -> [Int]
zipMax (x:xs) (y:ys) = max x y : zipMax xs ys
zipMax [] ys = ys
zipMax xs [] = xs
|
4bd1e4ffa688fbeaeb377ffda54332d09e56aed65fff50a4a3f2ba7ec95531cb | scheme-live/live | output.scm | #("\\a") | null | https://raw.githubusercontent.com/scheme-live/live/4c7c9d80f2fcf80692614e10935fa66be69e3708/live/json/data/y-string-double-escape-a/output.scm | scheme | #("\\a") | |
45f4536e21f05c88e499e79fba88e7ffd1e26d1586e50e4c025d155f97f9795d | BinRoot/Haskell-Data-Analysis-Cookbook | Main.hs | import Data.Graph
-- Defining a graphical network
myGraph :: Graph
myGraph = buildG bounds edges
where bounds = (1,4)
edges = [ (1,3), (1,4)
, (2,3), (2,4)
, (3,4) ]
main = do
putStrLn $ "The edges are " ++ (show.edges) myGraph
putStrLn $ "The vertices are " ++ (show.vertices) myGraph
| null | https://raw.githubusercontent.com/BinRoot/Haskell-Data-Analysis-Cookbook/f8c46987d78f4a6c1828b353c5f906b9314c2ef9/Ch06/Code01_graph1/Main.hs | haskell | Defining a graphical network | import Data.Graph
myGraph :: Graph
myGraph = buildG bounds edges
where bounds = (1,4)
edges = [ (1,3), (1,4)
, (2,3), (2,4)
, (3,4) ]
main = do
putStrLn $ "The edges are " ++ (show.edges) myGraph
putStrLn $ "The vertices are " ++ (show.vertices) myGraph
|
446446bd07de80b312b450bb65b649bb3741a992497ef5bf2d3a922629886111 | pokepay/trivial-battery | linux.lisp | (defpackage #:trivial-battery/os/linux
(:use #:cl)
(:import-from #:split-sequence
#:split-sequence)
(:import-from #:uiop)
(:export #:battery-info))
(in-package #:trivial-battery/os/linux)
(defun batteries ()
(let ((supplies
(with-output-to-string (s)
(uiop:run-program '("ls" "/sys/class/power_supply/")
:output s
:ignore-error-status t))))
(remove-if-not (lambda (supply)
(and (< 3 (length supply))
(string= supply "BAT" :end1 3)))
(split-sequence #\Newline supplies :remove-empty-subseqs t))))
(defun slurp-line (pathname)
(with-open-file (s pathname)
(read-line s)))
(defun try-int (value)
(handler-case
(values (parse-integer value))
(error (e) (declare (ignore e)) value)))
(defun battery-percentage (battery)
(values
(parse-integer
(slurp-line (format nil "/sys/class/power_supply/~A/capacity" battery)))))
(defun battery-charging-p (battery)
(not (string=
"Discharging"
(slurp-line (format nil "/sys/class/power_supply/~A/status" battery)))))
(defun battery-details (battery)
(cons
(cons "name" battery)
(loop for f in (uiop:directory-files (format nil "/sys/class/power_supply/~A/" battery))
for name = (file-namestring f)
unless (string= "uevent" name)
collect (cons name (try-int (slurp-line f))))))
(defun battery-info ()
(mapcar
(lambda (battery)
`(("percentage" . ,(battery-percentage battery))
("charging" . ,(battery-charging-p battery))
("name" . ,battery)))
(batteries)))
| null | https://raw.githubusercontent.com/pokepay/trivial-battery/318c9da88b4d11d3f33062e0fd09be660a383404/os/linux.lisp | lisp | (defpackage #:trivial-battery/os/linux
(:use #:cl)
(:import-from #:split-sequence
#:split-sequence)
(:import-from #:uiop)
(:export #:battery-info))
(in-package #:trivial-battery/os/linux)
(defun batteries ()
(let ((supplies
(with-output-to-string (s)
(uiop:run-program '("ls" "/sys/class/power_supply/")
:output s
:ignore-error-status t))))
(remove-if-not (lambda (supply)
(and (< 3 (length supply))
(string= supply "BAT" :end1 3)))
(split-sequence #\Newline supplies :remove-empty-subseqs t))))
(defun slurp-line (pathname)
(with-open-file (s pathname)
(read-line s)))
(defun try-int (value)
(handler-case
(values (parse-integer value))
(error (e) (declare (ignore e)) value)))
(defun battery-percentage (battery)
(values
(parse-integer
(slurp-line (format nil "/sys/class/power_supply/~A/capacity" battery)))))
(defun battery-charging-p (battery)
(not (string=
"Discharging"
(slurp-line (format nil "/sys/class/power_supply/~A/status" battery)))))
(defun battery-details (battery)
(cons
(cons "name" battery)
(loop for f in (uiop:directory-files (format nil "/sys/class/power_supply/~A/" battery))
for name = (file-namestring f)
unless (string= "uevent" name)
collect (cons name (try-int (slurp-line f))))))
(defun battery-info ()
(mapcar
(lambda (battery)
`(("percentage" . ,(battery-percentage battery))
("charging" . ,(battery-charging-p battery))
("name" . ,battery)))
(batteries)))
| |
c9a551488e9ab58693813f48bb153e69ea745542869fc875c9bd26e3504768ce | distrap/gcodehs | Pipes.hs | {-# LANGUAGE OverloadedStrings #-}
module Data.GCode.Pipes where
import Control.Monad
import Control.Monad.Trans.State.Strict
import Data.ByteString (ByteString)
import System.IO (Handle)
import Data.GCode.Types
import Data.GCode.Canon
import Data.GCode.Eval
import Data.GCode.Line
import Data.GCode.Parse
import Data.GCode.Pretty
import qualified Data.GCode.Canon.Convert
import Pipes
import Pipes.Attoparsec (ParsingError)
import Pipes.Safe (SafeT)
import qualified Data.ByteString.Char8
import qualified Data.Map.Strict
import qualified Pipes.Attoparsec
import qualified Pipes.ByteString
import qualified Pipes.Prelude
import qualified Pipes.Safe
import qualified System.IO
-- something fishy about this type
parseProducer :: Handle -> Producer Code (SafeT IO) (Either (ParsingError, Producer ByteString (SafeT IO) ()) ())
parseProducer = parseProducer' 1024
parseProducer' :: MonadIO m
=> Int
-> Handle
-> Producer Code m (Either (ParsingError, Producer ByteString m ()) ())
parseProducer' bufSize handle = Pipes.Attoparsec.parsed
parseGCodeLine (Pipes.ByteString.hGetSome bufSize handle)
withFile :: FilePath -> (Handle -> (SafeT IO) r) -> IO r
withFile filepath job =
System.IO.withFile filepath System.IO.ReadMode $ \handle ->
Pipes.Safe.runSafeT $ job handle
pipeToList :: FilePath -> Proxy () Code () a (SafeT IO) () -> IO [a]
pipeToList filepath pipeTail = withFile filepath $ \h ->
Pipes.Prelude.toListM
$ (() <$ parseProducer h)
>-> pipeTail
gcodeToCanonList :: FilePath -> IO [Canon]
gcodeToCanonList filepath = pipeToList filepath $ evalP >-> evalCanonP
gcodeToLines :: FilePath -> IO [Line]
gcodeToLines filepath = pipeToList filepath $ evalP >-> evalCanonLinesP
gcodePipe :: FilePath -> (Consumer Code (SafeT IO) ()) -> IO ()
gcodePipe filepath pipeTail =
System.IO.withFile filepath System.IO.ReadMode $ \handle ->
Pipes.Safe.runSafeT . runEffect $
(() <$ parseProducer handle)
>-> pipeTail
-- needs better name
runPipe :: FilePath
-> Maybe FilePath
-> (Pipe Code ByteString (SafeT IO) ())
-> IO ()
runPipe input Nothing pipeMiddle = gcodePipe input (pipeMiddle >-> Pipes.ByteString.stdout)
runPipe input (Just output) pipeMiddle =
System.IO.withFile output System.IO.WriteMode $ \outhandle ->
gcodePipe input (pipeMiddle >-> Pipes.ByteString.toHandle outhandle)
foldedPipe :: FilePath
-> (Producer Code (Pipes.Safe.SafeT IO) () -> Effect (Pipes.Safe.SafeT IO) r)
-> IO r
foldedPipe filepath fold =
System.IO.withFile filepath System.IO.ReadMode $ \handle ->
Pipes.Safe.runSafeT . runEffect $
fold (() <$ parseProducer handle)
-- evaluators
totalizeP :: Pipe Code Code (SafeT IO) ()
totalizeP = flip evalStateT Data.Map.Strict.empty $ forever $ do
x <- lift await
inEffect <- get
let updatedCode = updateFromCurrentModals inEffect x
updatedModals = updateModals inEffect updatedCode
put updatedModals
lift $ yield updatedCode
evalP :: Pipe Code Code (SafeT IO) ()
evalP = flip evalStateT newState $ forever $ do
x <- lift await
st <- get
let (result, steppedState, _rest) = step st [x]
XXX : add pretty printer for IPState
--liftIO $ print steppedState
put steppedState
case result of
Just r -> lift $ yield r
Nothing -> return ()
evalCanonP :: Pipe Code Canon (SafeT IO) ()
evalCanonP = flip evalStateT initCanonState $ forever $ do
x <- lift await
st <- get
forM_ (Data.GCode.Canon.Convert.toCanon x) $ \c -> do
let steppedState = stepCanon st c
put steppedState
lift $ yield c
evalCanonLinesP :: Pipe Code Line (SafeT IO) ()
evalCanonLinesP = flip evalStateT initCanonState $ forever $ do
x <- lift await
st <- get
forM_ (Data.GCode.Canon.Convert.toCanon x) $ \c -> do
let steppedState = stepCanon st c
put steppedState
forM_ (toLines st steppedState c) $ lift . yield
-- mmaped experiment, requires pipes-bytestring-mmap
import qualified Pipes . ByteString .
--main' = do
-- file <- fmap Prelude.head getArgs
Pipes . Safe.runSafeT . Pipes . Safe.runEffect $
-- (() <$ Pipes.Attoparsec.parsed parseGCodeLine (Pipes.ByteString.MMap.unsafeMMapFile file) )
-- >-> Pipes.Prelude.map ppGCodeLine
-- >-> Pipes.Prelude.stdoutLn
-- pretty print
prettySinkWith :: (a -> ByteString) -> Pipe a ByteString (SafeT IO) ()
prettySinkWith fn =
Pipes.Prelude.map fn
prettySink :: Pipe Code ByteString (SafeT IO) ()
prettySink =
Pipes.Prelude.map ppGCodeLine
>-> Pipes.Prelude.map (Data.ByteString.Char8.pack . (++"\n"))
compactSink :: Pipe Code ByteString (SafeT IO) ()
compactSink =
Pipes.Prelude.map ppGCodeLineCompact
>-> Pipes.Prelude.map (Data.ByteString.Char8.pack . (++"\n"))
-- Helpers
addNewLine :: ByteString -> ByteString
addNewLine to = Data.ByteString.Char8.append to "\n"
wrapPrinter :: (a -> String) -> a -> ByteString
wrapPrinter p = addNewLine . Data.ByteString.Char8.pack . p
| null | https://raw.githubusercontent.com/distrap/gcodehs/8a8dbc66445cff4ce832bb56f42ef03b3215e235/src/Data/GCode/Pipes.hs | haskell | # LANGUAGE OverloadedStrings #
something fishy about this type
needs better name
evaluators
liftIO $ print steppedState
mmaped experiment, requires pipes-bytestring-mmap
main' = do
file <- fmap Prelude.head getArgs
(() <$ Pipes.Attoparsec.parsed parseGCodeLine (Pipes.ByteString.MMap.unsafeMMapFile file) )
>-> Pipes.Prelude.map ppGCodeLine
>-> Pipes.Prelude.stdoutLn
pretty print
Helpers | module Data.GCode.Pipes where
import Control.Monad
import Control.Monad.Trans.State.Strict
import Data.ByteString (ByteString)
import System.IO (Handle)
import Data.GCode.Types
import Data.GCode.Canon
import Data.GCode.Eval
import Data.GCode.Line
import Data.GCode.Parse
import Data.GCode.Pretty
import qualified Data.GCode.Canon.Convert
import Pipes
import Pipes.Attoparsec (ParsingError)
import Pipes.Safe (SafeT)
import qualified Data.ByteString.Char8
import qualified Data.Map.Strict
import qualified Pipes.Attoparsec
import qualified Pipes.ByteString
import qualified Pipes.Prelude
import qualified Pipes.Safe
import qualified System.IO
parseProducer :: Handle -> Producer Code (SafeT IO) (Either (ParsingError, Producer ByteString (SafeT IO) ()) ())
parseProducer = parseProducer' 1024
parseProducer' :: MonadIO m
=> Int
-> Handle
-> Producer Code m (Either (ParsingError, Producer ByteString m ()) ())
parseProducer' bufSize handle = Pipes.Attoparsec.parsed
parseGCodeLine (Pipes.ByteString.hGetSome bufSize handle)
withFile :: FilePath -> (Handle -> (SafeT IO) r) -> IO r
withFile filepath job =
System.IO.withFile filepath System.IO.ReadMode $ \handle ->
Pipes.Safe.runSafeT $ job handle
pipeToList :: FilePath -> Proxy () Code () a (SafeT IO) () -> IO [a]
pipeToList filepath pipeTail = withFile filepath $ \h ->
Pipes.Prelude.toListM
$ (() <$ parseProducer h)
>-> pipeTail
gcodeToCanonList :: FilePath -> IO [Canon]
gcodeToCanonList filepath = pipeToList filepath $ evalP >-> evalCanonP
gcodeToLines :: FilePath -> IO [Line]
gcodeToLines filepath = pipeToList filepath $ evalP >-> evalCanonLinesP
gcodePipe :: FilePath -> (Consumer Code (SafeT IO) ()) -> IO ()
gcodePipe filepath pipeTail =
System.IO.withFile filepath System.IO.ReadMode $ \handle ->
Pipes.Safe.runSafeT . runEffect $
(() <$ parseProducer handle)
>-> pipeTail
runPipe :: FilePath
-> Maybe FilePath
-> (Pipe Code ByteString (SafeT IO) ())
-> IO ()
runPipe input Nothing pipeMiddle = gcodePipe input (pipeMiddle >-> Pipes.ByteString.stdout)
runPipe input (Just output) pipeMiddle =
System.IO.withFile output System.IO.WriteMode $ \outhandle ->
gcodePipe input (pipeMiddle >-> Pipes.ByteString.toHandle outhandle)
foldedPipe :: FilePath
-> (Producer Code (Pipes.Safe.SafeT IO) () -> Effect (Pipes.Safe.SafeT IO) r)
-> IO r
foldedPipe filepath fold =
System.IO.withFile filepath System.IO.ReadMode $ \handle ->
Pipes.Safe.runSafeT . runEffect $
fold (() <$ parseProducer handle)
totalizeP :: Pipe Code Code (SafeT IO) ()
totalizeP = flip evalStateT Data.Map.Strict.empty $ forever $ do
x <- lift await
inEffect <- get
let updatedCode = updateFromCurrentModals inEffect x
updatedModals = updateModals inEffect updatedCode
put updatedModals
lift $ yield updatedCode
evalP :: Pipe Code Code (SafeT IO) ()
evalP = flip evalStateT newState $ forever $ do
x <- lift await
st <- get
let (result, steppedState, _rest) = step st [x]
XXX : add pretty printer for IPState
put steppedState
case result of
Just r -> lift $ yield r
Nothing -> return ()
evalCanonP :: Pipe Code Canon (SafeT IO) ()
evalCanonP = flip evalStateT initCanonState $ forever $ do
x <- lift await
st <- get
forM_ (Data.GCode.Canon.Convert.toCanon x) $ \c -> do
let steppedState = stepCanon st c
put steppedState
lift $ yield c
evalCanonLinesP :: Pipe Code Line (SafeT IO) ()
evalCanonLinesP = flip evalStateT initCanonState $ forever $ do
x <- lift await
st <- get
forM_ (Data.GCode.Canon.Convert.toCanon x) $ \c -> do
let steppedState = stepCanon st c
put steppedState
forM_ (toLines st steppedState c) $ lift . yield
import qualified Pipes . ByteString .
Pipes . Safe.runSafeT . Pipes . Safe.runEffect $
prettySinkWith :: (a -> ByteString) -> Pipe a ByteString (SafeT IO) ()
prettySinkWith fn =
Pipes.Prelude.map fn
prettySink :: Pipe Code ByteString (SafeT IO) ()
prettySink =
Pipes.Prelude.map ppGCodeLine
>-> Pipes.Prelude.map (Data.ByteString.Char8.pack . (++"\n"))
compactSink :: Pipe Code ByteString (SafeT IO) ()
compactSink =
Pipes.Prelude.map ppGCodeLineCompact
>-> Pipes.Prelude.map (Data.ByteString.Char8.pack . (++"\n"))
addNewLine :: ByteString -> ByteString
addNewLine to = Data.ByteString.Char8.append to "\n"
wrapPrinter :: (a -> String) -> a -> ByteString
wrapPrinter p = addNewLine . Data.ByteString.Char8.pack . p
|
c1a304a5c9bbe8caa202df5c141b29cbc971eff4724acc3b511d6858d0d9df97 | mfoemmel/erlang-otp | wxDialog.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online 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.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
%% @doc See external documentation: <a href="">wxDialog</a>.
%% <p>This class is derived (and can use functions) from:
%% <br />{@link wxTopLevelWindow}
%% <br />{@link wxWindow}
%% <br />{@link wxEvtHandler}
%% </p>
%% @type wxDialog(). An object reference, The representation is internal
%% and can be changed without notice. It can't be used for comparsion
%% stored on disc or distributed for use on other nodes.
-module(wxDialog).
-include("wxe.hrl").
-export([create/4,create/5,createButtonSizer/2,createStdDialogButtonSizer/2,
destroy/1,endModal/2,getAffirmativeId/1,getReturnCode/1,isModal/1,
new/0,new/3,new/4,setAffirmativeId/2,setReturnCode/2,show/1,show/2,showModal/1]).
%% inherited exports
-export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1,
centerOnParent/2,centerOnScreen/1,centerOnScreen/2,centre/1,centre/2,
centreOnParent/1,centreOnParent/2,centreOnScreen/1,centreOnScreen/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,
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,
getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getIcon/1,getIcons/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,getTitle/1,getToolTip/1,getUpdateRegion/1,
getVirtualSize/1,getWindowStyleFlag/1,getWindowVariant/1,hasCapture/1,
hasScrollbar/2,hasTransparentBackground/1,hide/1,iconize/1,iconize/2,
inheritAttributes/1,initDialog/1,invalidateBestSize/1,isActive/1,
isEnabled/1,isExposed/2,isExposed/3,isExposed/5,isFullScreen/1,isIconized/1,
isMaximized/1,isRetained/1,isShown/1,isTopLevel/1,layout/1,lineDown/1,
lineUp/1,lower/1,makeModal/1,makeModal/2,maximize/1,maximize/2,move/2,
move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1,
navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2,
popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2,
refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,requestUserAttention/1,
requestUserAttention/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,
setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2,
setForegroundColour/2,setHelpText/2,setIcon/2,setIcons/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,setShape/2,setSize/2,setSize/3,setSize/5,
setSize/6,setSizeHints/2,setSizeHints/3,setSizeHints/4,setSizer/2,
setSizer/3,setSizerAndFit/2,setSizerAndFit/3,setThemeEnabled/2,setTitle/2,
setToolTip/2,setVirtualSize/2,setVirtualSize/3,setVirtualSizeHints/2,
setVirtualSizeHints/3,setVirtualSizeHints/4,setWindowStyle/2,setWindowStyleFlag/2,
setWindowVariant/2,shouldInheritColours/1,showFullScreen/2,showFullScreen/3,
thaw/1,transferDataFromWindow/1,transferDataToWindow/1,update/1,updateWindowUI/1,
updateWindowUI/2,validate/1,warpPointer/3]).
%% @hidden
parent_class(wxTopLevelWindow) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
( ) - > wxDialog ( )
%% @doc See <a href="#wxdialogwxdialog">external documentation</a>.
new() ->
wxe_util:construct(?wxDialog_new_0,
<<>>).
( Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , Title::string ( ) ) - > wxDialog ( )
@equiv new(Parent , Id , Title , [ ] )
new(Parent,Id,Title)
when is_record(Parent, wx_ref),is_integer(Id),is_list(Title) ->
new(Parent,Id,Title, []).
( Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , Title::string ( ) , [ Option ] ) - > wxDialog ( )
%% Option = {pos, {X::integer(),Y::integer()}} | {size, {W::integer(),H::integer()}} | {style, integer()}
%% @doc See <a href="#wxdialogwxdialog">external documentation</a>.
new(#wx_ref{type=ParentT,ref=ParentRef},Id,Title, Options)
when is_integer(Id),is_list(Title),is_list(Options) ->
?CLASS(ParentT,wxWindow),
Title_UC = unicode:characters_to_binary([Title,0]),
MOpts = fun({pos, {PosX,PosY}}, Acc) -> [<<1:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<2:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<3:32/?UI,Style:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxDialog_new_4,
<<ParentRef:32/?UI,Id:32/?UI,(byte_size(Title_UC)):32/?UI,(Title_UC)/binary, 0:(((8- ((4+byte_size(Title_UC)) band 16#7)) band 16#7))/unit:8, BinOpt/binary>>).
@spec ( This::wxDialog ( ) , Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , Title::string ( ) ) - > bool ( )
%% @equiv create(This,Parent,Id,Title, [])
create(This,Parent,Id,Title)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id),is_list(Title) ->
create(This,Parent,Id,Title, []).
@spec ( This::wxDialog ( ) , Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , Title::string ( ) , [ Option ] ) - > bool ( )
%% Option = {pos, {X::integer(),Y::integer()}} | {size, {W::integer(),H::integer()}} | {style, integer()}
%% @doc See <a href="#wxdialogcreate">external documentation</a>.
create(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},Id,Title, Options)
when is_integer(Id),is_list(Title),is_list(Options) ->
?CLASS(ThisT,wxDialog),
?CLASS(ParentT,wxWindow),
Title_UC = unicode:characters_to_binary([Title,0]),
MOpts = fun({pos, {PosX,PosY}}, Acc) -> [<<1:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<2:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<3:32/?UI,Style:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxDialog_Create,
<<ThisRef:32/?UI,ParentRef:32/?UI,Id:32/?UI,(byte_size(Title_UC)):32/?UI,(Title_UC)/binary, 0:(((8- ((0+byte_size(Title_UC)) band 16#7)) band 16#7))/unit:8, BinOpt/binary>>).
@spec ( This::wxDialog ( ) , Flags::integer ( ) ) - > wxSizer : wxSizer ( )
%% @doc See <a href="#wxdialogcreatebuttonsizer">external documentation</a>.
createButtonSizer(#wx_ref{type=ThisT,ref=ThisRef},Flags)
when is_integer(Flags) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_CreateButtonSizer,
<<ThisRef:32/?UI,Flags:32/?UI>>).
@spec ( This::wxDialog ( ) , Flags::integer ( ) ) - > wxStdDialogButtonSizer : ( )
%% @doc See <a href="#wxdialogcreatestddialogbuttonsizer">external documentation</a>.
createStdDialogButtonSizer(#wx_ref{type=ThisT,ref=ThisRef},Flags)
when is_integer(Flags) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_CreateStdDialogButtonSizer,
<<ThisRef:32/?UI,Flags:32/?UI>>).
%% @spec (This::wxDialog(), RetCode::integer()) -> ok
%% @doc See <a href="#wxdialogendmodal">external documentation</a>.
endModal(#wx_ref{type=ThisT,ref=ThisRef},RetCode)
when is_integer(RetCode) ->
?CLASS(ThisT,wxDialog),
wxe_util:cast(?wxDialog_EndModal,
<<ThisRef:32/?UI,RetCode:32/?UI>>).
%% @spec (This::wxDialog()) -> integer()
%% @doc See <a href="#wxdialoggetaffirmativeid">external documentation</a>.
getAffirmativeId(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_GetAffirmativeId,
<<ThisRef:32/?UI>>).
%% @spec (This::wxDialog()) -> integer()
%% @doc See <a href="#wxdialoggetreturncode">external documentation</a>.
getReturnCode(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_GetReturnCode,
<<ThisRef:32/?UI>>).
%% @spec (This::wxDialog()) -> bool()
%% @doc See <a href="#wxdialogismodal">external documentation</a>.
isModal(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_IsModal,
<<ThisRef:32/?UI>>).
%% @spec (This::wxDialog(), AffirmativeId::integer()) -> ok
%% @doc See <a href="#wxdialogsetaffirmativeid">external documentation</a>.
setAffirmativeId(#wx_ref{type=ThisT,ref=ThisRef},AffirmativeId)
when is_integer(AffirmativeId) ->
?CLASS(ThisT,wxDialog),
wxe_util:cast(?wxDialog_SetAffirmativeId,
<<ThisRef:32/?UI,AffirmativeId:32/?UI>>).
%% @spec (This::wxDialog(), ReturnCode::integer()) -> ok
%% @doc See <a href="#wxdialogsetreturncode">external documentation</a>.
setReturnCode(#wx_ref{type=ThisT,ref=ThisRef},ReturnCode)
when is_integer(ReturnCode) ->
?CLASS(ThisT,wxDialog),
wxe_util:cast(?wxDialog_SetReturnCode,
<<ThisRef:32/?UI,ReturnCode:32/?UI>>).
%% @spec (This::wxDialog()) -> bool()
%% @equiv show(This, [])
show(This)
when is_record(This, wx_ref) ->
show(This, []).
%% @spec (This::wxDialog(), [Option]) -> bool()
%% Option = {show, bool()}
%% @doc See <a href="#wxdialogshow">external documentation</a>.
show(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxDialog),
MOpts = fun({show, Show}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Show)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxDialog_Show,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
%% @spec (This::wxDialog()) -> integer()
%% @doc See <a href="#wxdialogshowmodal">external documentation</a>.
showModal(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_ShowModal,
<<ThisRef:32/?UI>>).
%% @spec (This::wxDialog()) -> ok
%% @doc Destroys this object, do not use object again
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxDialog),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
From wxTopLevelWindow
%% @hidden
showFullScreen(This,Show, Options) -> wxTopLevelWindow:showFullScreen(This,Show, Options).
%% @hidden
showFullScreen(This,Show) -> wxTopLevelWindow:showFullScreen(This,Show).
%% @hidden
setTitle(This,Title) -> wxTopLevelWindow:setTitle(This,Title).
%% @hidden
setShape(This,Region) -> wxTopLevelWindow:setShape(This,Region).
%% @hidden
centreOnScreen(This, Options) -> wxTopLevelWindow:centreOnScreen(This, Options).
%% @hidden
centreOnScreen(This) -> wxTopLevelWindow:centreOnScreen(This).
%% @hidden
centerOnScreen(This, Options) -> wxTopLevelWindow:centerOnScreen(This, Options).
%% @hidden
centerOnScreen(This) -> wxTopLevelWindow:centerOnScreen(This).
%% @hidden
setIcons(This,Icons) -> wxTopLevelWindow:setIcons(This,Icons).
%% @hidden
setIcon(This,Icon) -> wxTopLevelWindow:setIcon(This,Icon).
%% @hidden
requestUserAttention(This, Options) -> wxTopLevelWindow:requestUserAttention(This, Options).
%% @hidden
requestUserAttention(This) -> wxTopLevelWindow:requestUserAttention(This).
%% @hidden
maximize(This, Options) -> wxTopLevelWindow:maximize(This, Options).
%% @hidden
maximize(This) -> wxTopLevelWindow:maximize(This).
%% @hidden
isMaximized(This) -> wxTopLevelWindow:isMaximized(This).
%% @hidden
isIconized(This) -> wxTopLevelWindow:isIconized(This).
%% @hidden
isFullScreen(This) -> wxTopLevelWindow:isFullScreen(This).
%% @hidden
iconize(This, Options) -> wxTopLevelWindow:iconize(This, Options).
%% @hidden
iconize(This) -> wxTopLevelWindow:iconize(This).
%% @hidden
isActive(This) -> wxTopLevelWindow:isActive(This).
%% @hidden
getTitle(This) -> wxTopLevelWindow:getTitle(This).
%% @hidden
getIcons(This) -> wxTopLevelWindow:getIcons(This).
%% @hidden
getIcon(This) -> wxTopLevelWindow:getIcon(This).
%% From wxWindow
%% @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
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
setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options).
%% @hidden
setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH).
%% @hidden
setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize).
%% @hidden
setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y).
%% @hidden
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
%% @hidden
setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip).
%% @hidden
setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme).
%% @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,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options).
%% @hidden
setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos).
%% @hidden
setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options).
%% @hidden
setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range).
%% @hidden
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
%% @hidden
setName(This,Name) -> wxWindow:setName(This,Name).
%% @hidden
setLabel(This,Label) -> wxWindow:setLabel(This,Label).
%% @hidden
setId(This,Winid) -> wxWindow:setId(This,Winid).
%% @hidden
setHelpText(This,Text) -> wxWindow:setHelpText(This,Text).
%% @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,DropTarget) -> wxWindow:setDropTarget(This,DropTarget).
%% @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,MinSize) -> wxWindow:setMinSize(This,MinSize).
%% @hidden
setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize).
%% @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
popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options).
%% @hidden
popEventHandler(This) -> wxWindow:popEventHandler(This).
%% @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
makeModal(This, Options) -> wxWindow:makeModal(This, Options).
%% @hidden
makeModal(This) -> wxWindow:makeModal(This).
%% @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
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
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
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,Orient) -> wxWindow:getScrollThumb(This,Orient).
%% @hidden
getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient).
%% @hidden
getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient).
%% @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
getLabel(This) -> wxWindow:getLabel(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
getEventHandler(This) -> wxWindow:getEventHandler(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,Winid) -> wxWindow:findWindow(This,Winid).
%% @hidden
enable(This, Options) -> wxWindow:enable(This, Options).
%% @hidden
enable(This) -> wxWindow:enable(This).
%% @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
centreOnParent(This) -> wxWindow:centreOnParent(This).
%% @hidden
centre(This, Options) -> wxWindow:centre(This, Options).
%% @hidden
centre(This) -> wxWindow:centre(This).
%% @hidden
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
%% @hidden
centerOnParent(This) -> wxWindow:centerOnParent(This).
%% @hidden
center(This, Options) -> wxWindow:center(This, Options).
%% @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/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/src/gen/wxDialog.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online 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.
%CopyrightEnd%
This file is generated DO NOT EDIT
@doc See external documentation: <a href="">wxDialog</a>.
<p>This class is derived (and can use functions) from:
<br />{@link wxTopLevelWindow}
<br />{@link wxWindow}
<br />{@link wxEvtHandler}
</p>
@type wxDialog(). An object reference, The representation is internal
and can be changed without notice. It can't be used for comparsion
stored on disc or distributed for use on other nodes.
inherited exports
@hidden
@doc See <a href="#wxdialogwxdialog">external documentation</a>.
Option = {pos, {X::integer(),Y::integer()}} | {size, {W::integer(),H::integer()}} | {style, integer()}
@doc See <a href="#wxdialogwxdialog">external documentation</a>.
@equiv create(This,Parent,Id,Title, [])
Option = {pos, {X::integer(),Y::integer()}} | {size, {W::integer(),H::integer()}} | {style, integer()}
@doc See <a href="#wxdialogcreate">external documentation</a>.
@doc See <a href="#wxdialogcreatebuttonsizer">external documentation</a>.
@doc See <a href="#wxdialogcreatestddialogbuttonsizer">external documentation</a>.
@spec (This::wxDialog(), RetCode::integer()) -> ok
@doc See <a href="#wxdialogendmodal">external documentation</a>.
@spec (This::wxDialog()) -> integer()
@doc See <a href="#wxdialoggetaffirmativeid">external documentation</a>.
@spec (This::wxDialog()) -> integer()
@doc See <a href="#wxdialoggetreturncode">external documentation</a>.
@spec (This::wxDialog()) -> bool()
@doc See <a href="#wxdialogismodal">external documentation</a>.
@spec (This::wxDialog(), AffirmativeId::integer()) -> ok
@doc See <a href="#wxdialogsetaffirmativeid">external documentation</a>.
@spec (This::wxDialog(), ReturnCode::integer()) -> ok
@doc See <a href="#wxdialogsetreturncode">external documentation</a>.
@spec (This::wxDialog()) -> bool()
@equiv show(This, [])
@spec (This::wxDialog(), [Option]) -> bool()
Option = {show, bool()}
@doc See <a href="#wxdialogshow">external documentation</a>.
@spec (This::wxDialog()) -> integer()
@doc See <a href="#wxdialogshowmodal">external documentation</a>.
@spec (This::wxDialog()) -> ok
@doc Destroys this object, do not use object again
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@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
From wxEvtHandler
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(wxDialog).
-include("wxe.hrl").
-export([create/4,create/5,createButtonSizer/2,createStdDialogButtonSizer/2,
destroy/1,endModal/2,getAffirmativeId/1,getReturnCode/1,isModal/1,
new/0,new/3,new/4,setAffirmativeId/2,setReturnCode/2,show/1,show/2,showModal/1]).
-export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1,
centerOnParent/2,centerOnScreen/1,centerOnScreen/2,centre/1,centre/2,
centreOnParent/1,centreOnParent/2,centreOnScreen/1,centreOnScreen/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,
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,
getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getIcon/1,getIcons/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,getTitle/1,getToolTip/1,getUpdateRegion/1,
getVirtualSize/1,getWindowStyleFlag/1,getWindowVariant/1,hasCapture/1,
hasScrollbar/2,hasTransparentBackground/1,hide/1,iconize/1,iconize/2,
inheritAttributes/1,initDialog/1,invalidateBestSize/1,isActive/1,
isEnabled/1,isExposed/2,isExposed/3,isExposed/5,isFullScreen/1,isIconized/1,
isMaximized/1,isRetained/1,isShown/1,isTopLevel/1,layout/1,lineDown/1,
lineUp/1,lower/1,makeModal/1,makeModal/2,maximize/1,maximize/2,move/2,
move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1,
navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2,
popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2,
refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,requestUserAttention/1,
requestUserAttention/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,
setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2,
setForegroundColour/2,setHelpText/2,setIcon/2,setIcons/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,setShape/2,setSize/2,setSize/3,setSize/5,
setSize/6,setSizeHints/2,setSizeHints/3,setSizeHints/4,setSizer/2,
setSizer/3,setSizerAndFit/2,setSizerAndFit/3,setThemeEnabled/2,setTitle/2,
setToolTip/2,setVirtualSize/2,setVirtualSize/3,setVirtualSizeHints/2,
setVirtualSizeHints/3,setVirtualSizeHints/4,setWindowStyle/2,setWindowStyleFlag/2,
setWindowVariant/2,shouldInheritColours/1,showFullScreen/2,showFullScreen/3,
thaw/1,transferDataFromWindow/1,transferDataToWindow/1,update/1,updateWindowUI/1,
updateWindowUI/2,validate/1,warpPointer/3]).
parent_class(wxTopLevelWindow) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
( ) - > wxDialog ( )
new() ->
wxe_util:construct(?wxDialog_new_0,
<<>>).
( Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , Title::string ( ) ) - > wxDialog ( )
@equiv new(Parent , Id , Title , [ ] )
new(Parent,Id,Title)
when is_record(Parent, wx_ref),is_integer(Id),is_list(Title) ->
new(Parent,Id,Title, []).
( Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , Title::string ( ) , [ Option ] ) - > wxDialog ( )
new(#wx_ref{type=ParentT,ref=ParentRef},Id,Title, Options)
when is_integer(Id),is_list(Title),is_list(Options) ->
?CLASS(ParentT,wxWindow),
Title_UC = unicode:characters_to_binary([Title,0]),
MOpts = fun({pos, {PosX,PosY}}, Acc) -> [<<1:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<2:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<3:32/?UI,Style:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxDialog_new_4,
<<ParentRef:32/?UI,Id:32/?UI,(byte_size(Title_UC)):32/?UI,(Title_UC)/binary, 0:(((8- ((4+byte_size(Title_UC)) band 16#7)) band 16#7))/unit:8, BinOpt/binary>>).
@spec ( This::wxDialog ( ) , Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , Title::string ( ) ) - > bool ( )
create(This,Parent,Id,Title)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id),is_list(Title) ->
create(This,Parent,Id,Title, []).
@spec ( This::wxDialog ( ) , Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , Title::string ( ) , [ Option ] ) - > bool ( )
create(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},Id,Title, Options)
when is_integer(Id),is_list(Title),is_list(Options) ->
?CLASS(ThisT,wxDialog),
?CLASS(ParentT,wxWindow),
Title_UC = unicode:characters_to_binary([Title,0]),
MOpts = fun({pos, {PosX,PosY}}, Acc) -> [<<1:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<2:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<3:32/?UI,Style:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxDialog_Create,
<<ThisRef:32/?UI,ParentRef:32/?UI,Id:32/?UI,(byte_size(Title_UC)):32/?UI,(Title_UC)/binary, 0:(((8- ((0+byte_size(Title_UC)) band 16#7)) band 16#7))/unit:8, BinOpt/binary>>).
@spec ( This::wxDialog ( ) , Flags::integer ( ) ) - > wxSizer : wxSizer ( )
createButtonSizer(#wx_ref{type=ThisT,ref=ThisRef},Flags)
when is_integer(Flags) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_CreateButtonSizer,
<<ThisRef:32/?UI,Flags:32/?UI>>).
@spec ( This::wxDialog ( ) , Flags::integer ( ) ) - > wxStdDialogButtonSizer : ( )
createStdDialogButtonSizer(#wx_ref{type=ThisT,ref=ThisRef},Flags)
when is_integer(Flags) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_CreateStdDialogButtonSizer,
<<ThisRef:32/?UI,Flags:32/?UI>>).
endModal(#wx_ref{type=ThisT,ref=ThisRef},RetCode)
when is_integer(RetCode) ->
?CLASS(ThisT,wxDialog),
wxe_util:cast(?wxDialog_EndModal,
<<ThisRef:32/?UI,RetCode:32/?UI>>).
getAffirmativeId(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_GetAffirmativeId,
<<ThisRef:32/?UI>>).
getReturnCode(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_GetReturnCode,
<<ThisRef:32/?UI>>).
isModal(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_IsModal,
<<ThisRef:32/?UI>>).
setAffirmativeId(#wx_ref{type=ThisT,ref=ThisRef},AffirmativeId)
when is_integer(AffirmativeId) ->
?CLASS(ThisT,wxDialog),
wxe_util:cast(?wxDialog_SetAffirmativeId,
<<ThisRef:32/?UI,AffirmativeId:32/?UI>>).
setReturnCode(#wx_ref{type=ThisT,ref=ThisRef},ReturnCode)
when is_integer(ReturnCode) ->
?CLASS(ThisT,wxDialog),
wxe_util:cast(?wxDialog_SetReturnCode,
<<ThisRef:32/?UI,ReturnCode:32/?UI>>).
show(This)
when is_record(This, wx_ref) ->
show(This, []).
show(#wx_ref{type=ThisT,ref=ThisRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxDialog),
MOpts = fun({show, Show}, Acc) -> [<<1:32/?UI,(wxe_util:from_bool(Show)):32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxDialog_Show,
<<ThisRef:32/?UI, 0:32,BinOpt/binary>>).
showModal(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxDialog),
wxe_util:call(?wxDialog_ShowModal,
<<ThisRef:32/?UI>>).
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxDialog),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
From wxTopLevelWindow
showFullScreen(This,Show, Options) -> wxTopLevelWindow:showFullScreen(This,Show, Options).
showFullScreen(This,Show) -> wxTopLevelWindow:showFullScreen(This,Show).
setTitle(This,Title) -> wxTopLevelWindow:setTitle(This,Title).
setShape(This,Region) -> wxTopLevelWindow:setShape(This,Region).
centreOnScreen(This, Options) -> wxTopLevelWindow:centreOnScreen(This, Options).
centreOnScreen(This) -> wxTopLevelWindow:centreOnScreen(This).
centerOnScreen(This, Options) -> wxTopLevelWindow:centerOnScreen(This, Options).
centerOnScreen(This) -> wxTopLevelWindow:centerOnScreen(This).
setIcons(This,Icons) -> wxTopLevelWindow:setIcons(This,Icons).
setIcon(This,Icon) -> wxTopLevelWindow:setIcon(This,Icon).
requestUserAttention(This, Options) -> wxTopLevelWindow:requestUserAttention(This, Options).
requestUserAttention(This) -> wxTopLevelWindow:requestUserAttention(This).
maximize(This, Options) -> wxTopLevelWindow:maximize(This, Options).
maximize(This) -> wxTopLevelWindow:maximize(This).
isMaximized(This) -> wxTopLevelWindow:isMaximized(This).
isIconized(This) -> wxTopLevelWindow:isIconized(This).
isFullScreen(This) -> wxTopLevelWindow:isFullScreen(This).
iconize(This, Options) -> wxTopLevelWindow:iconize(This, Options).
iconize(This) -> wxTopLevelWindow:iconize(This).
isActive(This) -> wxTopLevelWindow:isActive(This).
getTitle(This) -> wxTopLevelWindow:getTitle(This).
getIcons(This) -> wxTopLevelWindow:getIcons(This).
getIcon(This) -> wxTopLevelWindow:getIcon(This).
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).
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).
setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options).
setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH).
setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize).
setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y).
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip).
setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme).
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,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options).
setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos).
setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options).
setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range).
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
setName(This,Name) -> wxWindow:setName(This,Name).
setLabel(This,Label) -> wxWindow:setLabel(This,Label).
setId(This,Winid) -> wxWindow:setId(This,Winid).
setHelpText(This,Text) -> wxWindow:setHelpText(This,Text).
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,DropTarget) -> wxWindow:setDropTarget(This,DropTarget).
setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour).
setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font).
setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour).
setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize).
setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize).
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).
popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options).
popEventHandler(This) -> wxWindow:popEventHandler(This).
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).
makeModal(This, Options) -> wxWindow:makeModal(This, Options).
makeModal(This) -> wxWindow:makeModal(This).
lower(This) -> wxWindow:lower(This).
lineUp(This) -> wxWindow:lineUp(This).
lineDown(This) -> wxWindow:lineDown(This).
layout(This) -> wxWindow:layout(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).
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).
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,Orient) -> wxWindow:getScrollThumb(This,Orient).
getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient).
getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient).
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).
getLabel(This) -> wxWindow:getLabel(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).
getEventHandler(This) -> wxWindow:getEventHandler(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,Winid) -> wxWindow:findWindow(This,Winid).
enable(This, Options) -> wxWindow:enable(This, Options).
enable(This) -> wxWindow:enable(This).
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).
centreOnParent(This) -> wxWindow:centreOnParent(This).
centre(This, Options) -> wxWindow:centre(This, Options).
centre(This) -> wxWindow:centre(This).
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
centerOnParent(This) -> wxWindow:centerOnParent(This).
center(This, Options) -> wxWindow:center(This, Options).
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).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.