_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
|
---|---|---|---|---|---|---|---|---|
c5ba22d41b663ca0e2cf2bd52b36eb5ef9f08b2423ff1b94809d9d2bf3b72bbf | mark-watson/loving-common-lisp | web-hunchentoot-example.lisp | (ql:quickload :hunchentoot)
(ql:quickload :cl-who)
(in-package :cl-user)
(defpackage hdemo
(:use :cl
:cl-who
:hunchentoot))
(in-package :hdemo)
(defvar *h* (make-instance 'easy-acceptor :port 3000))
;; define a handler with the arbitrary name my-greetings:
(define-easy-handler (my-greetings :uri "/hello") (name)
(setf (hunchentoot:content-type*) "text/html")
(with-html-output-to-string (*standard-output* nil :prologue t)
(:html
(:head (:title "hunchentoot test"))
(:body
(:h1 "hunchentoot form demo")
(:form
:method :post
(:input :type :text
:name "name"
:value name)
(:input :type :submit :value "Submit your name"))
(:p "Hello " (str name))))))
(hunchentoot:start *h*)
| null | https://raw.githubusercontent.com/mark-watson/loving-common-lisp/32f6abf3d2e500baeffd15c085a502b03399a074/src/hunchentoot_examples/web-hunchentoot-example.lisp | lisp | define a handler with the arbitrary name my-greetings: | (ql:quickload :hunchentoot)
(ql:quickload :cl-who)
(in-package :cl-user)
(defpackage hdemo
(:use :cl
:cl-who
:hunchentoot))
(in-package :hdemo)
(defvar *h* (make-instance 'easy-acceptor :port 3000))
(define-easy-handler (my-greetings :uri "/hello") (name)
(setf (hunchentoot:content-type*) "text/html")
(with-html-output-to-string (*standard-output* nil :prologue t)
(:html
(:head (:title "hunchentoot test"))
(:body
(:h1 "hunchentoot form demo")
(:form
:method :post
(:input :type :text
:name "name"
:value name)
(:input :type :submit :value "Submit your name"))
(:p "Hello " (str name))))))
(hunchentoot:start *h*)
|
a583423976320f65fa302e731f16e6f65bb63a6b197977b08b9c79e2eb02f113 | theodormoroianu/SecondYearCourses | LambdaChurch_20210415170220.hs | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
-- alpha-equivalence
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
-- subst u x t defines [u/x]t, i.e., substituting u for x in t
for example [ 3 / x](x + x ) = = 3 + 3
-- This substitution avoids variable captures so it is safe to be used when
-- reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
subst
:: Term -- ^ substitution term
-> Variable -- ^ variable to be substitutes
-> Term -- ^ term in which the substitution occurs
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
-- Normal order reduction
-- - like call by name
-- - but also reduce under lambda abstractions if no application is possible
-- - guarantees reaching a normal form if it exists
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
-- alpha-beta equivalence (for strongly normalizing terms) is obtained by
-- fully evaluating the terms using beta-reduction, then checking their
-- alpha-equivalence.
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
-- Church Encodings in Lambda
------------
--BOOLEANS--
------------
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
--If is not really needed because we can use the booleans themselves, but...
cIf :: Term
cIf = undefined
--The boolean negation switches the alternatives
cNot :: Term
cNot = undefined
--The boolean conjunction can be built as a conditional
cAnd :: Term
cAnd = undefined
--The boolean disjunction can be built as a conditional
cOr :: Term
cOr = undefined
---------
PAIRS--
---------
-- a pair with components of type a and b is a way to compute something based
-- on the values contained within the pair (a -> b -> c) -> c
builds a pair out of two values as an object which , when given
--a function to be applied on the values, it will apply it on them.
cPair :: Term
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = undefined
second projection
cSnd :: Term
cSnd = undefined
-------------------
--NATURAL NUMBERS--
-------------------
-- A natural number is any way to iterate a function s a number of times
-- over an initial value z ( (t -> t) -> t -> t )
--0 will iterate the function s 0 times over z, producing z
c0 :: Term
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: Term
c1 = undefined
--Successor n either
- applies s one more time in addition to what n does
-- - iterates s n times over (s z)
cS :: Term
cS = undefined
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) -> Term
cNat = undefined
--Addition of m and n can be done by composing n s with m s
cPlus :: Term
cPlus = undefined
--Multiplication of m and n can be done by composing n and m
cMul :: Term
cMul = undefined
--Exponentiation of m and n can be done by applying n to m
cPow :: Term
cPow = undefined
--Testing whether a value is 0 can be done through iteration
-- using a function constantly false and an initial value true
cIs0 :: Term
cIs0 = undefined
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: Term
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
-- of the predeccesor function
cSub :: Term
cSub = undefined
-- m is less than (or equal to) n if when substracting n from m we get 0
cLte :: Term
cLte = undefined
cGte :: Term
cGte = undefined
cLt :: Term
cLt = undefined
cGt :: Term
cGt = undefined
-- equality on naturals can be defined my means of comparisons
cEq :: Term
cEq = undefined
cFactorial :: Term
cFactorial = lam "n" (cSnd $$
(v "n"
$$ lam "p"
(cPair
$$ (cS $$ (cFst $$ v "p"))
$$ (cMul $$ (cFst $$ v "p") $$ (cSnd $$ v "p"))
)
$$ (cPair $$ c1 $$ c1)
))
cFibonacci :: Term
cFibonacci = lam "n" (cFst $$
(v "n"
$$ lam "p"
(cPair
$$ (cSnd $$ v "p")
$$ (cPlus $$ (cFst $$ v "p") $$ (cSnd $$ v "p"))
)
$$ (cPair $$ c0 $$ c1)
))
cDivMod :: Term
cDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(cIf
$$ (cLte $$ v "n" $$ (cSnd $$ v "pair"))
$$ (cPair
$$ (cS $$ (cFst $$ v "pair"))
$$ (cSub
$$ (cSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (cPair $$ c0 $$ v "m")
)
cNil :: Term
cNil = lams ["agg", "init"] (v "init")
cCons :: Term
cCons = lams ["x","l","agg", "init"]
(v "agg"
$$ v "x"
$$ (v "l" $$ v "agg" $$ v "init")
)
cList :: [Term] -> Term
cList = foldr (\x l -> cCons $$ x $$ l) cNil
cNatList :: [Integer] -> Term
cNatList = cList . map cNat
cSum :: Term
cSum = lam "l" (v "l" $$ cPlus $$ c0)
cIsNil :: Term
cIsNil = lam "l" (v "l" $$ lams ["x", "a"] cFalse $$ cTrue)
cHead :: Term
cHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cTail :: Term
cTail = lam "l" (cFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (cPair $$ v "t" $$ (cCons $$ v "x" $$ v "t"))
$$ (cSnd $$ v "p"))
$$ (cPair $$ cNil $$ cNil)
))
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
cDivMod' :: Term
cDivMod' = lams ["m", "n"]
(cIs0 $$ v "n"
$$ (cPair $$ c0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(cIs0 $$ v "x"
$$ (cLte $$ v "n" $$ (cSnd $$ v "p")
$$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0)
$$ v "p"
)
$$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x"))
)
$$ (cSub $$ (cSnd $$ v "p") $$ v "n")
)
$$ (cPair $$ c0 $$ v "m")
)
)
cSudan :: Term
cSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(cIs0 $$ v "n"
$$ (cPlus $$ v "x" $$ v "y")
$$ (cIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (cPred $$ v "n")
$$ v "fnpy"
$$ (cPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y"))
)
)
))
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415170220.hs | haskell | alpha-equivalence
subst u x t defines [u/x]t, i.e., substituting u for x in t
This substitution avoids variable captures so it is safe to be used when
reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
^ substitution term
^ variable to be substitutes
^ term in which the substitution occurs
Normal order reduction
- like call by name
- but also reduce under lambda abstractions if no application is possible
- guarantees reaching a normal form if it exists
alpha-beta equivalence (for strongly normalizing terms) is obtained by
fully evaluating the terms using beta-reduction, then checking their
alpha-equivalence.
Church Encodings in Lambda
----------
BOOLEANS--
----------
If is not really needed because we can use the booleans themselves, but...
The boolean negation switches the alternatives
The boolean conjunction can be built as a conditional
The boolean disjunction can be built as a conditional
-------
-------
a pair with components of type a and b is a way to compute something based
on the values contained within the pair (a -> b -> c) -> c
a function to be applied on the values, it will apply it on them.
-----------------
NATURAL NUMBERS--
-----------------
A natural number is any way to iterate a function s a number of times
over an initial value z ( (t -> t) -> t -> t )
0 will iterate the function s 0 times over z, producing z
Successor n either
- iterates s n times over (s z)
Addition of m and n can be done by composing n s with m s
Multiplication of m and n can be done by composing n and m
Exponentiation of m and n can be done by applying n to m
Testing whether a value is 0 can be done through iteration
using a function constantly false and an initial value true
of the predeccesor function
m is less than (or equal to) n if when substracting n from m we get 0
equality on naturals can be defined my means of comparisons | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
for example [ 3 / x](x + x ) = = 3 + 3
subst
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
cIf :: Term
cIf = undefined
cNot :: Term
cNot = undefined
cAnd :: Term
cAnd = undefined
cOr :: Term
cOr = undefined
builds a pair out of two values as an object which , when given
cPair :: Term
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = undefined
second projection
cSnd :: Term
cSnd = undefined
c0 :: Term
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: Term
c1 = undefined
- applies s one more time in addition to what n does
cS :: Term
cS = undefined
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) -> Term
cNat = undefined
cPlus :: Term
cPlus = undefined
cMul :: Term
cMul = undefined
cPow :: Term
cPow = undefined
cIs0 :: Term
cIs0 = undefined
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: Term
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
cSub :: Term
cSub = undefined
cLte :: Term
cLte = undefined
cGte :: Term
cGte = undefined
cLt :: Term
cLt = undefined
cGt :: Term
cGt = undefined
cEq :: Term
cEq = undefined
cFactorial :: Term
cFactorial = lam "n" (cSnd $$
(v "n"
$$ lam "p"
(cPair
$$ (cS $$ (cFst $$ v "p"))
$$ (cMul $$ (cFst $$ v "p") $$ (cSnd $$ v "p"))
)
$$ (cPair $$ c1 $$ c1)
))
cFibonacci :: Term
cFibonacci = lam "n" (cFst $$
(v "n"
$$ lam "p"
(cPair
$$ (cSnd $$ v "p")
$$ (cPlus $$ (cFst $$ v "p") $$ (cSnd $$ v "p"))
)
$$ (cPair $$ c0 $$ c1)
))
cDivMod :: Term
cDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(cIf
$$ (cLte $$ v "n" $$ (cSnd $$ v "pair"))
$$ (cPair
$$ (cS $$ (cFst $$ v "pair"))
$$ (cSub
$$ (cSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (cPair $$ c0 $$ v "m")
)
cNil :: Term
cNil = lams ["agg", "init"] (v "init")
cCons :: Term
cCons = lams ["x","l","agg", "init"]
(v "agg"
$$ v "x"
$$ (v "l" $$ v "agg" $$ v "init")
)
cList :: [Term] -> Term
cList = foldr (\x l -> cCons $$ x $$ l) cNil
cNatList :: [Integer] -> Term
cNatList = cList . map cNat
cSum :: Term
cSum = lam "l" (v "l" $$ cPlus $$ c0)
cIsNil :: Term
cIsNil = lam "l" (v "l" $$ lams ["x", "a"] cFalse $$ cTrue)
cHead :: Term
cHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cTail :: Term
cTail = lam "l" (cFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (cPair $$ v "t" $$ (cCons $$ v "x" $$ v "t"))
$$ (cSnd $$ v "p"))
$$ (cPair $$ cNil $$ cNil)
))
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
cDivMod' :: Term
cDivMod' = lams ["m", "n"]
(cIs0 $$ v "n"
$$ (cPair $$ c0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(cIs0 $$ v "x"
$$ (cLte $$ v "n" $$ (cSnd $$ v "p")
$$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0)
$$ v "p"
)
$$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x"))
)
$$ (cSub $$ (cSnd $$ v "p") $$ v "n")
)
$$ (cPair $$ c0 $$ v "m")
)
)
cSudan :: Term
cSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(cIs0 $$ v "n"
$$ (cPlus $$ v "x" $$ v "y")
$$ (cIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (cPred $$ v "n")
$$ v "fnpy"
$$ (cPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y"))
)
)
))
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
|
c110efd091f201eeeac1939bcecdad138366c8cf76860689c910c300bf85c095 | magicant/flesh | LexSpec.hs |
Copyright ( C ) 2017 WATANABE >
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program . If not , see < / > .
Copyright (C) 2017 WATANABE Yuki <>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see </>.
-}
module Flesh.Language.Parser.LexSpec (spec) where
import Data.List (isPrefixOf)
import Flesh.Language.Parser.Error
import Flesh.Language.Parser.Lex
import Flesh.Language.Parser.TestUtil
import Flesh.Source.Position
import Test.Hspec (Spec, context, describe, parallel)
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck ((===), (==>))
spec :: Spec
spec = parallel $ do
describe "blank" $ do
context "does not accept newline" $ do
expectFailure "\n" blank Soft UnknownReason 0
describe "comment" $ do
prop "fails if input does not start with #" $ \s ->
not ("#" `isPrefixOf` s) && not ("\\\n" `isPrefixOf` s) ==>
let p = dummyPosition s
s' = spread p s
in runFullInputTester comment s' ===
Left (Soft, Error UnknownReason p)
prop "parses up to newline" $ \s s' ->
notElem '\n' s ==>
let input = '#' : s ++ '\n' : s'
p = dummyPosition input
input' = spread p input
e = runOverrunTester comment input'
out = unposition $ spread (next p) s
in e === Just (Right (out, dropP (length s + 1) input'))
prop "parses up to end-of-file" $ \s ->
notElem '\n' s ==>
let input = '#' : s
p = dummyPosition input
input' = spread p input
e = runFullInputTester comment input'
out = unposition $ spread (next p) s
in e === Right (out, dropP (length s + 1) input')
context "skips preceding line continuations" $ do
expectSuccessEof "\\\n\\\n#" "" comment []
context "ignores line continuations in comment body" $ do
expectSuccess "#\\" "\n" (fmap (fmap snd) comment) "\\"
describe "whites" $ do
context "does not skip newline" $ do
expectSuccess "" "\n" ("" <$ whites) ""
describe "anyOperator" $ do
context "parses control operator" $ do
expectSuccessEof ";" "" (snd <$> anyOperator) ";"
expectSuccess ";" "&" (snd <$> anyOperator) ";"
expectSuccess ";;" "" (snd <$> anyOperator) ";;"
expectSuccessEof "|" "" (snd <$> anyOperator) "|"
expectSuccessEof "|" "&" (snd <$> anyOperator) "|"
expectSuccess "||" "" (snd <$> anyOperator) "||"
expectSuccessEof "&" "" (snd <$> anyOperator) "&"
expectSuccess "&" "|" (snd <$> anyOperator) "&"
expectSuccess "&&" "" (snd <$> anyOperator) "&&"
expectSuccess "(" "" (snd <$> anyOperator) "("
expectSuccess ")" "" (snd <$> anyOperator) ")"
context "parses redirection operator" $ do
expectSuccessEof "<" "" (snd <$> anyOperator) "<"
expectSuccess "<" "-" (snd <$> anyOperator) "<"
expectSuccess "<" "|" (snd <$> anyOperator) "<"
expectSuccessEof "<<" "" (snd <$> anyOperator) "<<"
expectSuccess "<<" "|" (snd <$> anyOperator) "<<"
expectSuccess "<<-" "" (snd <$> anyOperator) "<<-"
expectSuccess "<>" "" (snd <$> anyOperator) "<>"
expectSuccess "<&" "" (snd <$> anyOperator) "<&"
expectSuccessEof ">" "" (snd <$> anyOperator) ">"
expectSuccess ">" "-" (snd <$> anyOperator) ">"
expectSuccess ">>" "" (snd <$> anyOperator) ">>"
expectSuccess ">|" "" (snd <$> anyOperator) ">|"
expectSuccess ">&" "" (snd <$> anyOperator) ">&"
context "skips line continuations" $ do
expectSuccess "\\\n&\\\n\\\n&" "\\\n" (snd <$> anyOperator) "&&"
expectSuccess "\\\n<\\\n<\\\n-" "\\\n" (snd <$> anyOperator) "<<-"
describe "operator" $ do
context "parses argument control operator" $ do
expectSuccessEof ";" "" (snd <$> operator ";") ";"
expectSuccess ";" "&" (snd <$> operator ";") ";"
expectSuccess ";;" "" (snd <$> operator ";;") ";;"
expectSuccessEof "|" "" (snd <$> operator "|") "|"
expectSuccess "|" "&" (snd <$> operator "|") "|"
expectSuccess "||" "" (snd <$> operator "||") "||"
expectSuccessEof "&" "" (snd <$> operator "&") "&"
expectSuccess "&" "|" (snd <$> operator "&") "&"
expectSuccess "&&" "" (snd <$> operator "&&") "&&"
expectSuccess "(" "" (snd <$> operator "(") "("
expectSuccess ")" "" (snd <$> operator ")") ")"
context "parses argument redirection operator" $ do
expectSuccessEof "<" "" (snd <$> operator "<") "<"
expectSuccess "<" "-" (snd <$> operator "<") "<"
expectSuccess "<" "|" (snd <$> operator "<") "<"
expectSuccessEof "<<" "" (snd <$> operator "<<") "<<"
expectSuccess "<<" "|" (snd <$> operator "<<") "<<"
expectSuccess "<<-" "" (snd <$> operator "<<-") "<<-"
expectSuccess "<>" "" (snd <$> operator "<>") "<>"
expectSuccess "<&" "" (snd <$> operator "<&") "<&"
expectSuccessEof ">" "" (snd <$> operator ">") ">"
expectSuccess ">" "-" (snd <$> operator ">") ">"
expectSuccess ">>" "" (snd <$> operator ">>") ">>"
expectSuccess ">|" "" (snd <$> operator ">|") ">|"
expectSuccess ">&" "" (snd <$> operator ">&") ">&"
context "rejects operator other than argument" $ do
expectFailure ";;" (operator ";") Soft UnknownReason 0
expectFailure "&&" (operator "&") Soft UnknownReason 0
expectFailure "||" (operator "|") Soft UnknownReason 0
expectFailureEof "<<" (operator "<") Soft UnknownReason 0
expectFailure "<<-" (operator "<") Soft UnknownReason 0
expectFailure "<<-" (operator "<<") Soft UnknownReason 0
expectFailure "<>" (operator "<<") Soft UnknownReason 0
expectFailure ">>" (operator ">") Soft UnknownReason 0
expectFailure ">|" (operator ">") Soft UnknownReason 0
expectFailure ">&" (operator ">") Soft UnknownReason 0
expectFailure "\\\n>&" (operator ">") Soft UnknownReason 2
describe "ioNumber" $ do
context "parses digits followed by < or >" $ do
expectSuccess "1" "<" ioNumber 1
expectSuccess "20" ">" ioNumber 20
expectSuccess "123" ">" ioNumber 123
context "rejects non-digits" $ do
expectFailure "<" ioNumber Soft UnknownReason 0
expectFailure "a" ioNumber Soft UnknownReason 0
expectFailure " " ioNumber Soft UnknownReason 0
context "rejects digits not followed by < or >" $ do
expectFailureEof "0" ioNumber Soft UnknownReason 1
expectFailure "1-" ioNumber Soft UnknownReason 1
expectFailure "23 " ioNumber Soft UnknownReason 2
context "skips line continuations" $ do
expectSuccess "\\\n\\\n1" "<" ioNumber 1
expectSuccess "1" "\\\n\\\n<" ioNumber 1
expectFailure "1\\\n-" ioNumber Soft UnknownReason 3
-- vim: set et sw=2 sts=2 tw=78:
| null | https://raw.githubusercontent.com/magicant/flesh/0e76312d291aae8f890ba55d8131ade78600d7e8/hspec-src/Flesh/Language/Parser/LexSpec.hs | haskell | vim: set et sw=2 sts=2 tw=78: |
Copyright ( C ) 2017 WATANABE >
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program . If not , see < / > .
Copyright (C) 2017 WATANABE Yuki <>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see </>.
-}
module Flesh.Language.Parser.LexSpec (spec) where
import Data.List (isPrefixOf)
import Flesh.Language.Parser.Error
import Flesh.Language.Parser.Lex
import Flesh.Language.Parser.TestUtil
import Flesh.Source.Position
import Test.Hspec (Spec, context, describe, parallel)
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck ((===), (==>))
spec :: Spec
spec = parallel $ do
describe "blank" $ do
context "does not accept newline" $ do
expectFailure "\n" blank Soft UnknownReason 0
describe "comment" $ do
prop "fails if input does not start with #" $ \s ->
not ("#" `isPrefixOf` s) && not ("\\\n" `isPrefixOf` s) ==>
let p = dummyPosition s
s' = spread p s
in runFullInputTester comment s' ===
Left (Soft, Error UnknownReason p)
prop "parses up to newline" $ \s s' ->
notElem '\n' s ==>
let input = '#' : s ++ '\n' : s'
p = dummyPosition input
input' = spread p input
e = runOverrunTester comment input'
out = unposition $ spread (next p) s
in e === Just (Right (out, dropP (length s + 1) input'))
prop "parses up to end-of-file" $ \s ->
notElem '\n' s ==>
let input = '#' : s
p = dummyPosition input
input' = spread p input
e = runFullInputTester comment input'
out = unposition $ spread (next p) s
in e === Right (out, dropP (length s + 1) input')
context "skips preceding line continuations" $ do
expectSuccessEof "\\\n\\\n#" "" comment []
context "ignores line continuations in comment body" $ do
expectSuccess "#\\" "\n" (fmap (fmap snd) comment) "\\"
describe "whites" $ do
context "does not skip newline" $ do
expectSuccess "" "\n" ("" <$ whites) ""
describe "anyOperator" $ do
context "parses control operator" $ do
expectSuccessEof ";" "" (snd <$> anyOperator) ";"
expectSuccess ";" "&" (snd <$> anyOperator) ";"
expectSuccess ";;" "" (snd <$> anyOperator) ";;"
expectSuccessEof "|" "" (snd <$> anyOperator) "|"
expectSuccessEof "|" "&" (snd <$> anyOperator) "|"
expectSuccess "||" "" (snd <$> anyOperator) "||"
expectSuccessEof "&" "" (snd <$> anyOperator) "&"
expectSuccess "&" "|" (snd <$> anyOperator) "&"
expectSuccess "&&" "" (snd <$> anyOperator) "&&"
expectSuccess "(" "" (snd <$> anyOperator) "("
expectSuccess ")" "" (snd <$> anyOperator) ")"
context "parses redirection operator" $ do
expectSuccessEof "<" "" (snd <$> anyOperator) "<"
expectSuccess "<" "-" (snd <$> anyOperator) "<"
expectSuccess "<" "|" (snd <$> anyOperator) "<"
expectSuccessEof "<<" "" (snd <$> anyOperator) "<<"
expectSuccess "<<" "|" (snd <$> anyOperator) "<<"
expectSuccess "<<-" "" (snd <$> anyOperator) "<<-"
expectSuccess "<>" "" (snd <$> anyOperator) "<>"
expectSuccess "<&" "" (snd <$> anyOperator) "<&"
expectSuccessEof ">" "" (snd <$> anyOperator) ">"
expectSuccess ">" "-" (snd <$> anyOperator) ">"
expectSuccess ">>" "" (snd <$> anyOperator) ">>"
expectSuccess ">|" "" (snd <$> anyOperator) ">|"
expectSuccess ">&" "" (snd <$> anyOperator) ">&"
context "skips line continuations" $ do
expectSuccess "\\\n&\\\n\\\n&" "\\\n" (snd <$> anyOperator) "&&"
expectSuccess "\\\n<\\\n<\\\n-" "\\\n" (snd <$> anyOperator) "<<-"
describe "operator" $ do
context "parses argument control operator" $ do
expectSuccessEof ";" "" (snd <$> operator ";") ";"
expectSuccess ";" "&" (snd <$> operator ";") ";"
expectSuccess ";;" "" (snd <$> operator ";;") ";;"
expectSuccessEof "|" "" (snd <$> operator "|") "|"
expectSuccess "|" "&" (snd <$> operator "|") "|"
expectSuccess "||" "" (snd <$> operator "||") "||"
expectSuccessEof "&" "" (snd <$> operator "&") "&"
expectSuccess "&" "|" (snd <$> operator "&") "&"
expectSuccess "&&" "" (snd <$> operator "&&") "&&"
expectSuccess "(" "" (snd <$> operator "(") "("
expectSuccess ")" "" (snd <$> operator ")") ")"
context "parses argument redirection operator" $ do
expectSuccessEof "<" "" (snd <$> operator "<") "<"
expectSuccess "<" "-" (snd <$> operator "<") "<"
expectSuccess "<" "|" (snd <$> operator "<") "<"
expectSuccessEof "<<" "" (snd <$> operator "<<") "<<"
expectSuccess "<<" "|" (snd <$> operator "<<") "<<"
expectSuccess "<<-" "" (snd <$> operator "<<-") "<<-"
expectSuccess "<>" "" (snd <$> operator "<>") "<>"
expectSuccess "<&" "" (snd <$> operator "<&") "<&"
expectSuccessEof ">" "" (snd <$> operator ">") ">"
expectSuccess ">" "-" (snd <$> operator ">") ">"
expectSuccess ">>" "" (snd <$> operator ">>") ">>"
expectSuccess ">|" "" (snd <$> operator ">|") ">|"
expectSuccess ">&" "" (snd <$> operator ">&") ">&"
context "rejects operator other than argument" $ do
expectFailure ";;" (operator ";") Soft UnknownReason 0
expectFailure "&&" (operator "&") Soft UnknownReason 0
expectFailure "||" (operator "|") Soft UnknownReason 0
expectFailureEof "<<" (operator "<") Soft UnknownReason 0
expectFailure "<<-" (operator "<") Soft UnknownReason 0
expectFailure "<<-" (operator "<<") Soft UnknownReason 0
expectFailure "<>" (operator "<<") Soft UnknownReason 0
expectFailure ">>" (operator ">") Soft UnknownReason 0
expectFailure ">|" (operator ">") Soft UnknownReason 0
expectFailure ">&" (operator ">") Soft UnknownReason 0
expectFailure "\\\n>&" (operator ">") Soft UnknownReason 2
describe "ioNumber" $ do
context "parses digits followed by < or >" $ do
expectSuccess "1" "<" ioNumber 1
expectSuccess "20" ">" ioNumber 20
expectSuccess "123" ">" ioNumber 123
context "rejects non-digits" $ do
expectFailure "<" ioNumber Soft UnknownReason 0
expectFailure "a" ioNumber Soft UnknownReason 0
expectFailure " " ioNumber Soft UnknownReason 0
context "rejects digits not followed by < or >" $ do
expectFailureEof "0" ioNumber Soft UnknownReason 1
expectFailure "1-" ioNumber Soft UnknownReason 1
expectFailure "23 " ioNumber Soft UnknownReason 2
context "skips line continuations" $ do
expectSuccess "\\\n\\\n1" "<" ioNumber 1
expectSuccess "1" "\\\n\\\n<" ioNumber 1
expectFailure "1\\\n-" ioNumber Soft UnknownReason 3
|
dbfb5e2bf10eaf49f007e779ab1f6bc3113d78f1403fccf92f6c7f5d72204437 | jimcrayne/jhc | TrueSet.hs | module Util.TrueSet(
TrueSet,
fromList,
member,
empty,
full,
singleton,
insert,
delete,
unions,
union,
intersection,
intersects,
difference,
(\\)
) where
import qualified Data.Set as Set
infixl 9 \\
data TrueSet a = TrueSet (Set.Set a) Bool
False `xor` y = y
True `xor` y = not y
fromList xs = TrueSet (Set.fromList xs) False
member x (TrueSet s inv) = inv `xor` (Set.member x s)
invert (TrueSet x y) = TrueSet x (not y)
empty = TrueSet Set.empty False
full = TrueSet Set.empty False
singleton x = TrueSet (Set.singleton x) False
insert x (TrueSet s False) = TrueSet (Set.insert x s) False
insert x (TrueSet s True) = TrueSet (Set.delete x s) True
delete x (TrueSet s False) = TrueSet (Set.delete x s) False
delete x (TrueSet s True) = TrueSet (Set.insert x s) True
unions xs = foldlStrict union empty xs
intersects xs = foldlStrict intersection full xs
foldlStrict f z xs
= case xs of
[] -> z
(x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
difference x y = x `intersection` invert y
m1 \\ m2 = difference m1 m2
(TrueSet x True) `intersection` (TrueSet y True) = TrueSet (x `Set.union` y) True
(TrueSet x False) `intersection` (TrueSet y False) = TrueSet (x `Set.intersection` y) False
(TrueSet x True) `intersection` (TrueSet y False) = TrueSet (y Set.\\ x) False
(TrueSet x False) `intersection` (TrueSet y True) = TrueSet (x Set.\\ y) False
(TrueSet x True) `union` (TrueSet y True) = TrueSet (x `Set.intersection` y) True
(TrueSet x False) `union` (TrueSet y False) = TrueSet (x `Set.union` y) False
(TrueSet x True) `union` (TrueSet y False) = TrueSet (x Set.\\ y) True
(TrueSet x False) `union` (TrueSet y True) = TrueSet (y Set.\\ x) True
| null | https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/src/Util/TrueSet.hs | haskell | module Util.TrueSet(
TrueSet,
fromList,
member,
empty,
full,
singleton,
insert,
delete,
unions,
union,
intersection,
intersects,
difference,
(\\)
) where
import qualified Data.Set as Set
infixl 9 \\
data TrueSet a = TrueSet (Set.Set a) Bool
False `xor` y = y
True `xor` y = not y
fromList xs = TrueSet (Set.fromList xs) False
member x (TrueSet s inv) = inv `xor` (Set.member x s)
invert (TrueSet x y) = TrueSet x (not y)
empty = TrueSet Set.empty False
full = TrueSet Set.empty False
singleton x = TrueSet (Set.singleton x) False
insert x (TrueSet s False) = TrueSet (Set.insert x s) False
insert x (TrueSet s True) = TrueSet (Set.delete x s) True
delete x (TrueSet s False) = TrueSet (Set.delete x s) False
delete x (TrueSet s True) = TrueSet (Set.insert x s) True
unions xs = foldlStrict union empty xs
intersects xs = foldlStrict intersection full xs
foldlStrict f z xs
= case xs of
[] -> z
(x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
difference x y = x `intersection` invert y
m1 \\ m2 = difference m1 m2
(TrueSet x True) `intersection` (TrueSet y True) = TrueSet (x `Set.union` y) True
(TrueSet x False) `intersection` (TrueSet y False) = TrueSet (x `Set.intersection` y) False
(TrueSet x True) `intersection` (TrueSet y False) = TrueSet (y Set.\\ x) False
(TrueSet x False) `intersection` (TrueSet y True) = TrueSet (x Set.\\ y) False
(TrueSet x True) `union` (TrueSet y True) = TrueSet (x `Set.intersection` y) True
(TrueSet x False) `union` (TrueSet y False) = TrueSet (x `Set.union` y) False
(TrueSet x True) `union` (TrueSet y False) = TrueSet (x Set.\\ y) True
(TrueSet x False) `union` (TrueSet y True) = TrueSet (y Set.\\ x) True
|
|
652068965235f245f2034c420aa332c81183dec60afd1ef3e9d88f51d8cf8005 | mirage/irmin-watcher | irmin_watcher.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2016 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2016 Thomas Gazagnaire. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
let v = Lazy.force Backend.v
let mode = (Backend.mode :> [ `FSEvents | `Inotify | `Polling ])
let hook = Core.hook v
type stats = { watchdogs : int; dispatches : int }
let stats () =
let w = Core.watchdog v in
let d = Core.Watchdog.dispatch w in
{ watchdogs = Core.Watchdog.length w; dispatches = Core.Dispatch.length d }
let set_polling_time f =
match mode with `Polling -> Core.default_polling_time := f | _ -> ()
---------------------------------------------------------------------------
Copyright ( c ) 2016
Permission to use , copy , modify , and/or 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
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) 2016 Thomas Gazagnaire
Permission to use, copy, modify, and/or 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.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/mirage/irmin-watcher/753084ba383ca5d1ea30b3bf89c8757a782d213c/src/irmin_watcher.ml | ocaml | ---------------------------------------------------------------------------
Copyright ( c ) 2016 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2016 Thomas Gazagnaire. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
let v = Lazy.force Backend.v
let mode = (Backend.mode :> [ `FSEvents | `Inotify | `Polling ])
let hook = Core.hook v
type stats = { watchdogs : int; dispatches : int }
let stats () =
let w = Core.watchdog v in
let d = Core.Watchdog.dispatch w in
{ watchdogs = Core.Watchdog.length w; dispatches = Core.Dispatch.length d }
let set_polling_time f =
match mode with `Polling -> Core.default_polling_time := f | _ -> ()
---------------------------------------------------------------------------
Copyright ( c ) 2016
Permission to use , copy , modify , and/or 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
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) 2016 Thomas Gazagnaire
Permission to use, copy, modify, and/or 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.
---------------------------------------------------------------------------*)
|
|
e169fb5e540c1d0b7a44a5bb2f11348b3a9fdf7c383cc2dc20b083a341c217c3 | fakedata-haskell/fakedata | FrCaTextSpec.hs | # LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
module FrCaTextSpec where
import Data.Text (Text)
import qualified Data.Text as T
import Faker hiding (defaultFakerSettings)
import qualified Faker.Address as FA
import Faker.Combinators (listOf)
import qualified Faker.Company as CO
import qualified Faker.Internet as IN
import qualified Faker.Name as NA
import qualified Faker.PhoneNumber as PH
import qualified Faker.Book as BO
import qualified Faker.Lorem as LO
import qualified Faker.Game.Pokemon as PO
import Test.Hspec
import TestImport
isText :: Text -> Bool
isText x = T.length x >= 1
isTexts :: [Text] -> Bool
isTexts xs = and $ map isText xs
locale :: Text
locale = "fr-CA"
fakerSettings :: FakerSettings
fakerSettings = setLocale locale defaultFakerSettings
verifyDistributeFakes :: [Fake Text] -> IO [Bool]
verifyDistributeFakes funs = do
let fs :: [IO [Text]] =
map (generateWithSettings fakerSettings) $ map (listOf 100) funs
gs :: [IO Bool] = map (\f -> isTexts <$> f) fs
sequence gs
spec :: Spec
spec = do
describe "TextSpec" $ do
it "validates fr-CA locale" $ do
let functions :: [Fake Text] =
[ NA.lastName
, NA.firstName
, NA.prefix
, NA.name
, NA.nameWithMiddle
, BO.title
, BO.author
, BO.publisher
, PO.names
, PO.locations
, PO.moves
, PH.formats
, PH.cellPhoneFormat
, PH.countryCode
, FA.state
, FA.stateAbbr
, FA.countryCode
, FA.buildingNumber
, FA.streetSuffix
, FA.streetName
, FA.streetAddress
, FA.postcode
, IN.freeEmail
, IN.domainSuffix
, CO.suffix
, CO.name
, CO.buzzword
, CO.bs
, LO.words
, LO.supplemental
]
bools <- verifyDistributeFakes functions
(and bools) `shouldBe` True
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/e6fbc16cfa27b2d17aa449ea8140788196ca135b/test/FrCaTextSpec.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE ScopedTypeVariables #
module FrCaTextSpec where
import Data.Text (Text)
import qualified Data.Text as T
import Faker hiding (defaultFakerSettings)
import qualified Faker.Address as FA
import Faker.Combinators (listOf)
import qualified Faker.Company as CO
import qualified Faker.Internet as IN
import qualified Faker.Name as NA
import qualified Faker.PhoneNumber as PH
import qualified Faker.Book as BO
import qualified Faker.Lorem as LO
import qualified Faker.Game.Pokemon as PO
import Test.Hspec
import TestImport
isText :: Text -> Bool
isText x = T.length x >= 1
isTexts :: [Text] -> Bool
isTexts xs = and $ map isText xs
locale :: Text
locale = "fr-CA"
fakerSettings :: FakerSettings
fakerSettings = setLocale locale defaultFakerSettings
verifyDistributeFakes :: [Fake Text] -> IO [Bool]
verifyDistributeFakes funs = do
let fs :: [IO [Text]] =
map (generateWithSettings fakerSettings) $ map (listOf 100) funs
gs :: [IO Bool] = map (\f -> isTexts <$> f) fs
sequence gs
spec :: Spec
spec = do
describe "TextSpec" $ do
it "validates fr-CA locale" $ do
let functions :: [Fake Text] =
[ NA.lastName
, NA.firstName
, NA.prefix
, NA.name
, NA.nameWithMiddle
, BO.title
, BO.author
, BO.publisher
, PO.names
, PO.locations
, PO.moves
, PH.formats
, PH.cellPhoneFormat
, PH.countryCode
, FA.state
, FA.stateAbbr
, FA.countryCode
, FA.buildingNumber
, FA.streetSuffix
, FA.streetName
, FA.streetAddress
, FA.postcode
, IN.freeEmail
, IN.domainSuffix
, CO.suffix
, CO.name
, CO.buzzword
, CO.bs
, LO.words
, LO.supplemental
]
bools <- verifyDistributeFakes functions
(and bools) `shouldBe` True
|
0a7e583b90143fe315ca2e7003882ba8014fb33c92184ac096686fcb547cc6c2 | fragnix/fragnix | Text.Appar.Input.hs | # LANGUAGE Haskell98 #
{-# LINE 1 "Text/Appar/Input.hs" #-}
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module Text.Appar.Input where
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
----------------------------------------------------------------
{-|
The class for parser input.
-}
class Eq inp => Input inp where
-- | The head function for input
car :: inp -> Char
-- | The tail function for input
cdr :: inp -> inp
-- | The end of input
nil :: inp
-- | The function to check the end of input
isNil :: inp -> Bool
instance Input S.ByteString where
car = S.head
cdr = S.tail
nil = S.empty
isNil = S.null
instance Input L.ByteString where
car = L.head
cdr = L.tail
nil = L.empty
isNil = L.null
instance Input String where
car = head
cdr = tail
isNil = null
nil = ""
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/scotty/Text.Appar.Input.hs | haskell | # LINE 1 "Text/Appar/Input.hs" #
# LANGUAGE TypeSynonymInstances, FlexibleInstances #
--------------------------------------------------------------
|
The class for parser input.
| The head function for input
| The tail function for input
| The end of input
| The function to check the end of input | # LANGUAGE Haskell98 #
module Text.Appar.Input where
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
class Eq inp => Input inp where
car :: inp -> Char
cdr :: inp -> inp
nil :: inp
isNil :: inp -> Bool
instance Input S.ByteString where
car = S.head
cdr = S.tail
nil = S.empty
isNil = S.null
instance Input L.ByteString where
car = L.head
cdr = L.tail
nil = L.empty
isNil = L.null
instance Input String where
car = head
cdr = tail
isNil = null
nil = ""
|
74531a2eeefe8cd93bb0333fc2e1a9134d6520e527363c1eececcbed82f127ec | Practical-Formal-Methods/adiff | SemRep.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE StandaloneDeriving #
-----------------------------------------------------------------------------
-- |
-- Module : Language.C.Analysis.Syntax
Copyright : ( c ) 2008
-- License : BSD-style
-- Maintainer :
-- Stability : alpha
Portability : ghc
--
-- This module contains definitions for representing C translation units.
In contrast to ' Language . C.Syntax . AST ' , the representation tries to express the semantics of
-- of a translation unit.
---------------------------------------------------------------------------------------------------
module Language.C.Analysis.SemRep(
-- * Sums of tags and identifiers
TagDef(..),typeOfTagDef,
Declaration(..),declIdent,declName,declType,declAttrs,
IdentDecl(..),objKindDescr, splitIdentDecls,
-- * Global definitions
GlobalDecls(..),emptyGlobalDecls,filterGlobalDecls,mergeGlobalDecls,
-- * Events for visitors
DeclEvent(..),
-- * Declarations and definitions
Decl(..),
ObjDef(..),isTentative,
FunDef(..),
ParamDecl(..),MemberDecl(..),
TypeDef(..),identOfTypeDef,
VarDecl(..),
-- * Declaration attributes
DeclAttrs(..),isExtDecl,
FunctionAttrs(..), functionAttrs, noFunctionAttrs,
Storage(..),declStorage,ThreadLocal,Register,
Linkage(..),hasLinkage,declLinkage,
-- * Types
Type(..),
FunType(..),
ArraySize(..),
TypeDefRef(..),
TypeName(..),BuiltinType(..),
IntType(..),FloatType(..),
HasSUERef(..),HasCompTyKind(..),
CompTypeRef(..),CompType(..),typeOfCompDef,CompTyKind(..),
EnumTypeRef(..),EnumType(..),typeOfEnumDef,
Enumerator(..),
TypeQuals(..),noTypeQuals,mergeTypeQuals,
-- * Variable names
VarName(..),identOfVarName,isNoName,AsmName,
* Attributes ( STUB , not yet analyzed )
Attr(..),Attributes,noAttributes,mergeAttributes,
* Statements and Expressions ( STUB , aliases to Syntax )
Expr,Stmt,Initializer,AsmBlock,
)
where
import Data.Generics
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Language.C.Data
import Language.C.Syntax
import Data.Generics hiding (Generic)
-- | accessor class : struct\/union\/enum names
class HasSUERef a where
sueRef :: a -> SUERef
-- | accessor class : composite type tags (struct or union)
class HasCompTyKind a where
compTag :: a -> CompTyKind
-- | Composite type definitions (tags)
data TagDef = CompDef CompType --composite definition
| EnumDef EnumType --enum definition
! , !
instance HasSUERef TagDef where
sueRef (CompDef ct) = sueRef ct
sueRef (EnumDef et) = sueRef et
-- | return the type corresponding to a tag definition
typeOfTagDef :: TagDef -> TypeName
typeOfTagDef (CompDef comptype) = typeOfCompDef comptype
typeOfTagDef (EnumDef enumtype) = typeOfEnumDef enumtype
-- | All datatypes aggregating a declaration are instances of @Declaration@
class Declaration n where
-- | get the name, type and declaration attributes of a declaration or definition
getVarDecl :: n -> VarDecl
-- | get the declaration corresponding to a definition
declOfDef :: (Declaration n, CNode n) => n -> Decl
declOfDef def = let vd = getVarDecl def in Decl vd (nodeInfo def)
-- | get the variable identifier of a declaration (only safe if the
-- the declaration is known to have a name)
declIdent :: (Declaration n) => n -> Ident
declIdent = identOfVarName . declName
-- | get the variable name of a @Declaration@
declName :: (Declaration n) => n -> VarName
declName = (\(VarDecl n _ _) -> n) . getVarDecl
-- | get the type of a @Declaration@
declType :: (Declaration n) => n -> Type
declType = (\(VarDecl _ _ ty) -> ty) . getVarDecl
-- | get the declaration attributes of a @Declaration@
declAttrs :: (Declaration n) => n -> DeclAttrs
declAttrs = (\(VarDecl _ specs _) -> specs) . getVarDecl
instance (Declaration a, Declaration b) => Declaration (Either a b) where
getVarDecl = either getVarDecl getVarDecl
-- | identifiers, typedefs and enumeration constants (namespace sum)
data IdentDecl = Declaration Decl -- ^ object or function declaration
| ObjectDef ObjDef -- ^ object definition
| FunctionDef FunDef -- ^ function definition
| EnumeratorDef Enumerator -- ^ definition of an enumerator
! , !
instance Declaration IdentDecl where
getVarDecl (Declaration decl) = getVarDecl decl
getVarDecl (ObjectDef def) = getVarDecl def
getVarDecl (FunctionDef def) = getVarDecl def
getVarDecl (EnumeratorDef def) = getVarDecl def
-- | textual description of the kind of an object
objKindDescr :: IdentDecl -> String
objKindDescr (Declaration _ ) = "declaration"
objKindDescr (ObjectDef _) = "object definition"
objKindDescr (FunctionDef _) = "function definition"
objKindDescr (EnumeratorDef _) = "enumerator definition"
| @splitIdentDecls includeAllDecls@ splits a map of object , function and enumerator declarations and definitions into one map
holding declarations , and three maps for object definitions , enumerator definitions and function definitions .
If @includeAllDecls@ is all declarations are present in the first map , otherwise only those where no corresponding definition
-- is available.
splitIdentDecls :: Bool -> Map Ident IdentDecl -> (Map Ident Decl,
( Map Ident Enumerator,
Map Ident ObjDef,
Map Ident FunDef ) )
splitIdentDecls include_all = Map.foldWithKey (if include_all then deal else deal') (Map.empty,(Map.empty,Map.empty,Map.empty))
where
deal ident entry (decls,defs) = (Map.insert ident (declOfDef entry) decls, addDef ident entry defs)
deal' ident (Declaration d) (decls,defs) = (Map.insert ident d decls,defs)
deal' ident def (decls,defs) = (decls, addDef ident def defs)
addDef ident entry (es,os,fs) =
case entry of
Declaration _ -> (es,os,fs)
EnumeratorDef e -> (Map.insert ident e es,os,fs)
ObjectDef o -> (es,Map.insert ident o os,fs)
FunctionDef f -> (es, os,Map.insert ident f fs)
-- | global declaration\/definition table returned by the analysis
data GlobalDecls = GlobalDecls {
gObjs :: Map Ident IdentDecl,
gTags :: Map SUERef TagDef,
gTypeDefs :: Map Ident TypeDef
}
-- | empty global declaration table
emptyGlobalDecls :: GlobalDecls
emptyGlobalDecls = GlobalDecls Map.empty Map.empty Map.empty
-- | filter global declarations
filterGlobalDecls :: (DeclEvent -> Bool) -> GlobalDecls -> GlobalDecls
filterGlobalDecls decl_filter gmap = GlobalDecls
{
gObjs = Map.filter (decl_filter . DeclEvent) (gObjs gmap),
gTags = Map.filter (decl_filter . TagEvent) (gTags gmap),
gTypeDefs = Map.filter (decl_filter . TypeDefEvent) (gTypeDefs gmap)
}
-- | merge global declarations
mergeGlobalDecls :: GlobalDecls -> GlobalDecls -> GlobalDecls
mergeGlobalDecls gmap1 gmap2 = GlobalDecls
{
gObjs = Map.union (gObjs gmap1) (gObjs gmap2),
gTags = Map.union (gTags gmap1) (gTags gmap2),
gTypeDefs = Map.union (gTypeDefs gmap1) (gTypeDefs gmap2)
}
-- * Events
-- | Declaration events
--
-- Those events are reported to callbacks, which are executed during the traversal.
data DeclEvent =
TagEvent TagDef
-- ^ file-scope struct\/union\/enum event
| DeclEvent IdentDecl
-- ^ file-scope declaration or definition
| ParamEvent ParamDecl
-- ^ parameter declaration
| LocalEvent IdentDecl
-- ^ local variable declaration or definition
| TypeDefEvent TypeDef
-- ^ a type definition
| AsmEvent AsmBlock
-- ^ assembler block
! !
-- * Declarations and definitions
-- | Declarations, which aren't definitions
data Decl = Decl VarDecl NodeInfo
! , !
instance Declaration Decl where
getVarDecl (Decl vd _) = vd
-- | Object Definitions
--
-- An object definition is a declaration together with an initializer.
--
-- If the initializer is missing, it is a tentative definition, i.e. a
-- definition which might be overriden later on.
data ObjDef = ObjDef VarDecl (Maybe Initializer) NodeInfo
! , !
instance Declaration ObjDef where
getVarDecl (ObjDef vd _ _) = vd
-- | Returns @True@ if the given object definition is tentative.
isTentative :: ObjDef -> Bool
isTentative (ObjDef decl init_opt _) | isExtDecl decl = isNothing init_opt
| otherwise = False
-- | Function definitions
--
-- A function definition is a declaration together with a statement (the function body).
data FunDef = FunDef VarDecl Stmt NodeInfo
! , !
instance Declaration FunDef where
getVarDecl (FunDef vd _ _) = vd
-- | Parameter declaration
data ParamDecl = ParamDecl VarDecl NodeInfo
| AbstractParamDecl VarDecl NodeInfo
! , !
instance Declaration ParamDecl where
getVarDecl (ParamDecl vd _) = vd
getVarDecl (AbstractParamDecl vd _) = vd
-- | Struct\/Union member declaration
data MemberDecl = MemberDecl VarDecl (Maybe Expr) NodeInfo
^ @MemberDecl vardecl bitfieldsize node@
| AnonBitField Type Expr NodeInfo
^ size@
! , !
instance Declaration MemberDecl where
getVarDecl (MemberDecl vd _ _) = vd
getVarDecl (AnonBitField ty _ _) = VarDecl NoName (DeclAttrs noFunctionAttrs NoStorage []) ty
-- | @typedef@ definitions.
--
-- The identifier is a new name for the given type.
data TypeDef = TypeDef Ident Type Attributes NodeInfo
! , !
-- | return the idenitifier of a @typedef@
identOfTypeDef :: TypeDef -> Ident
identOfTypeDef (TypeDef ide _ _ _) = ide
-- | Generic variable declarations
data VarDecl = VarDecl VarName DeclAttrs Type
deriving (Eq, Ord, Show, Typeable, Data)
instance Declaration VarDecl where
getVarDecl = id
-- @isExtDecl d@ returns true if the declaration has /linkage/
isExtDecl :: (Declaration n) => n -> Bool
isExtDecl = hasLinkage . declStorage
| Declaration attributes of the form isInlineFunction storage linkage attrs@
--
-- They specify the storage and linkage of a declared object.
data DeclAttrs = DeclAttrs FunctionAttrs Storage Attributes
^ fspecs storage attrs@
deriving (Eq, Ord, Show, Typeable, Data)
-- | get the 'Storage' of a declaration
declStorage :: (Declaration d) => d -> Storage
declStorage d = case declAttrs d of (DeclAttrs _ st _) -> st
-- | get the `function attributes' of a declaration
functionAttrs :: (Declaration d) => d -> FunctionAttrs
functionAttrs d = case declAttrs d of (DeclAttrs fa _ _) -> fa
-- Function attributes (inline, noreturn)
data FunctionAttrs = FunctionAttrs { isInline :: Bool, isNoreturn :: Bool }
deriving (Show, Eq, Ord, Typeable, Data)
noFunctionAttrs :: FunctionAttrs
noFunctionAttrs = FunctionAttrs { isInline = False, isNoreturn = False }
-- In C we have
-- Identifiers can either have internal, external or no linkage
-- (same object everywhere, same object within the translation unit, unique).
-- * top-level identifiers
-- static : internal linkage (objects and function defs)
-- extern : linkage of prior declaration (if specified), external linkage otherwise
-- no-spec: external linkage
-- * storage duration
-- * static storage duration: objects with external or internal linkage, or local ones with the static keyword
-- * automatic storage duration: otherwise (register)
See , Table 8.1 , 8.2
-- | Storage duration and linkage of a variable
data Storage = NoStorage -- ^ no storage
| Auto Register -- ^ automatic storage (optional: register)
^ static storage , linkage spec and thread local specifier ( gnu c )
| FunLinkage Linkage -- ^ function, either internal or external linkage
deriving (Typeable, Data, Show, Eq, Ord)
type ThreadLocal = Bool
type Register = Bool
-- | Linkage: Either no linkage, internal to the translation unit or external
data Linkage = NoLinkage | InternalLinkage | ExternalLinkage
deriving (Typeable, Data, Show, Eq, Ord)
| return @True@ if the object has linkage
hasLinkage :: Storage -> Bool
hasLinkage (Auto _) = False
hasLinkage (Static NoLinkage _) = False
hasLinkage _ = True
-- | Get the linkage of a definition
declLinkage :: (Declaration d) => d -> Linkage
declLinkage decl =
case declStorage decl of
NoStorage -> undefined
Auto _ -> NoLinkage
Static linkage _ -> linkage
FunLinkage linkage -> linkage
-- * types
-- | types of C objects
data Type =
DirectType TypeName TypeQuals Attributes
-- ^ a non-derived type
| PtrType Type TypeQuals Attributes
-- ^ pointer type
| ArrayType Type ArraySize TypeQuals Attributes
-- ^ array type
| FunctionType FunType Attributes
-- ^ function type
| TypeDefType TypeDefRef TypeQuals Attributes
-- ^ a defined type
deriving (Eq, Ord, Show, Typeable, Data)
| Function types are of the form @FunType return - type
--
-- If the parameter types aren't yet known, the function has type @FunTypeIncomplete type attrs@.
data FunType = FunType Type [ParamDecl] Bool
| FunTypeIncomplete Type
deriving (Eq, Ord, Show, Typeable, Data)
-- | An array type may either have unknown size or a specified array size, the latter either variable or constant.
-- Furthermore, when used as a function parameters, the size may be qualified as /static/.
-- In a function prototype, the size may be `Unspecified variable size' (@[*]@).
data ArraySize = UnknownArraySize Bool
-- ^ @UnknownArraySize is-starred@
| ArraySize Bool Expr
-- ^ @FixedSizeArray is-static size-expr@
deriving (Eq, Ord, Typeable, Data)
instance Show ArraySize where
show arrSize = "ArraySize"
-- | normalized type representation
data TypeName =
TyVoid
| TyIntegral IntType
| TyFloating FloatType
| TyComplex FloatType
| TyComp CompTypeRef
| TyEnum EnumTypeRef
| TyBuiltin BuiltinType
deriving (Eq, Ord, Show, Typeable, Data)
| Builtin type ( va_list , anything )
data BuiltinType = TyVaList
| TyAny
deriving (Eq, Ord, Show, Typeable, Data)
-- | typdef references
-- If the actual type is known, it is attached for convenience
data TypeDefRef = TypeDefRef Ident Type NodeInfo
! , !
| integral types ( C99 6.7.2.2 )
data IntType =
TyBool
| TyChar
| TySChar
| TyUChar
| TyShort
| TyUShort
| TyInt
| TyUInt
| TyInt128
| TyUInt128
| TyLong
| TyULong
| TyLLong
| TyULLong
deriving (Typeable, Data, Eq, Ord)
instance Show IntType where
show TyBool = "_Bool"
show TyChar = "char"
show TySChar = "signed char"
show TyUChar = "unsigned char"
show TyShort = "short"
show TyUShort = "unsigned short"
show TyInt = "int"
show TyUInt = "unsigned int"
show TyInt128 = "__int128"
show TyUInt128 = "unsigned __int128"
show TyLong = "long"
show TyULong = "unsigned long"
show TyLLong = "long long"
show TyULLong = "unsigned long long"
| floating point type ( C99 6.7.2.2 )
data FloatType =
TyFloat
| TyDouble
| TyLDouble
| TyFloat128
deriving (Typeable, Data, Eq, Ord)
instance Show FloatType where
show TyFloat = "float"
show TyDouble = "double"
show TyLDouble = "long double"
show TyFloat128 = "__float128"
-- | composite type declarations
data CompTypeRef = CompTypeRef SUERef CompTyKind NodeInfo
! , !
instance HasSUERef CompTypeRef where sueRef (CompTypeRef ref _ _) = ref
instance HasCompTyKind CompTypeRef where compTag (CompTypeRef _ tag _) = tag
data EnumTypeRef = EnumTypeRef SUERef NodeInfo
! , !
instance HasSUERef EnumTypeRef where sueRef (EnumTypeRef ref _) = ref
-- | Composite type (struct or union).
data CompType = CompType SUERef CompTyKind [MemberDecl] Attributes NodeInfo
! , !
instance HasSUERef CompType where sueRef (CompType ref _ _ _ _) = ref
instance HasCompTyKind CompType where compTag (CompType _ tag _ _ _) = tag
-- | return the type of a composite type definition
typeOfCompDef :: CompType -> TypeName
typeOfCompDef (CompType ref tag _ _ _) = TyComp (CompTypeRef ref tag undefNode)
-- | a tag to determine wheter we refer to a @struct@ or @union@, see 'CompType'.
data CompTyKind = StructTag
| UnionTag
deriving (Eq,Ord,Typeable,Data)
instance Show CompTyKind where
show StructTag = "struct"
show UnionTag = "union"
-- | Representation of C enumeration types
data EnumType = EnumType SUERef [Enumerator] Attributes NodeInfo
^ @EnumType name enumeration - constants attrs node@
! , !
instance HasSUERef EnumType where sueRef (EnumType ref _ _ _) = ref
-- | return the type of an enum definition
typeOfEnumDef :: EnumType -> TypeName
typeOfEnumDef (EnumType ref _ _ _) = TyEnum (EnumTypeRef ref undefNode)
-- | An Enumerator consists of an identifier, a constant expressions and the link to its type
data Enumerator = Enumerator Ident Expr EnumType NodeInfo
! , !
instance Declaration Enumerator where
getVarDecl (Enumerator ide _ enumty _) =
VarDecl
(VarName ide Nothing)
(DeclAttrs noFunctionAttrs NoStorage [])
(DirectType (typeOfEnumDef enumty) noTypeQuals noAttributes)
-- | Type qualifiers: constant, volatile and restrict
data TypeQuals = TypeQuals { constant :: Bool, volatile :: Bool,
restrict :: Bool, atomic :: Bool,
nullable :: Bool, nonnull :: Bool }
deriving (Show, Typeable, Data)
instance Eq TypeQuals where
(==) (TypeQuals c1 v1 r1 a1 n1 nn1) (TypeQuals c2 v2 r2 a2 n2 nn2) =
c1 == c2 && v1 == v2 && r1 == r2 && a1 == a2 && n1 == n2 && nn1 == nn2
instance Ord TypeQuals where
(<=) (TypeQuals c1 v1 r1 a1 n1 nn1) (TypeQuals c2 v2 r2 a2 n2 nn2) =
c1 <= c2 && v1 <= v2 && r1 <= r2 && a1 <= a2 && n1 <= n2 && nn1 <= nn2
-- | no type qualifiers
noTypeQuals :: TypeQuals
noTypeQuals = TypeQuals False False False False False False
| merge ( /&&/ ) two type qualifier sets
mergeTypeQuals :: TypeQuals -> TypeQuals -> TypeQuals
mergeTypeQuals (TypeQuals c1 v1 r1 a1 n1 nn1) (TypeQuals c2 v2 r2 a2 n2 nn2) =
TypeQuals (c1 && c2) (v1 && v2) (r1 && r2) (a1 && a2) (n1 && n2) (nn1 && nn2)
-- * initializers
| ' Initializer ' is currently an alias for ' CInit ' .
--
-- We're planning a normalized representation, but this depends on the implementation of
-- constant expression evaluation
type Initializer = CInit
-- | Normalized C Initializers
-- * If the expression has scalar type, the initializer is an expression
-- * If the expression has struct type, the initializer is a map from designators to initializers
-- * If the expression has array type, the initializer is a list of values
-- Not implemented yet, as it depends on constant expression evaluation
-- * names and attributes
-- | @VarName name assembler-name@ is a name of an declared object
data VarName = VarName Ident (Maybe AsmName)
| NoName
deriving (Eq, Ord, Show, Typeable, Data)
identOfVarName :: VarName -> Ident
identOfVarName NoName = error "identOfVarName: NoName"
identOfVarName (VarName ident _) = ident
isNoName :: VarName -> Bool
isNoName NoName = True
isNoName _ = False
| Top level assembler block ( alias for )
type AsmBlock = CStrLit
| Assembler name ( alias for )
type AsmName = CStrLit
-- | @__attribute__@ annotations
--
-- Those are of the form @Attr attribute-name attribute-parameters@,
-- and serve as generic properties of some syntax tree elements.
--
-- Some examples:
--
-- * labels can be attributed with /unused/ to indicate that their not used
--
-- * struct definitions can be attributed with /packed/ to tell the compiler to use the most compact representation
--
-- * declarations can be attributed with /deprecated/
--
-- * function declarations can be attributes with /noreturn/ to tell the compiler that the function will never return,
--
-- * or with /const/ to indicate that it is a pure function
--
-- /TODO/: ultimatively, we want to parse attributes and represent them in a typed way
data Attr = Attr Ident [Expr] NodeInfo
! , !
instance Show Attr where
show (Attr i _ ni) = "Attribute " ++ show i ++ " [] " ++ show ni
type Attributes = [Attr]
-- |Empty attribute list
noAttributes :: Attributes
noAttributes = []
-- |Merge attribute lists
-- /TODO/: currently does not remove duplicates
mergeAttributes :: Attributes -> Attributes -> Attributes
mergeAttributes = (++)
-- * statements and expressions (Type aliases)
| ' Stmt ' is an alias for ' CStat ' ( Syntax )
type Stmt = CStat
| ' ' is currently an alias for ' CExpr ' ( Syntax )
type Expr = CExpr
deriving instance Data GlobalDecls
deriving instance Data TypeDef
deriving instance Data TagDef
deriving instance Data CompType
deriving instance Data MemberDecl
deriving instance Data EnumType
deriving instance Data Enumerator
deriving instance Data IdentDecl
deriving instance Data Decl
deriving instance Data ObjDef
deriving instance Data FunDef
-- GENERATED START
instance CNode TagDef where
nodeInfo (CompDef d) = nodeInfo d
nodeInfo (EnumDef d) = nodeInfo d
instance Pos TagDef where
posOf x = posOf (nodeInfo x)
instance CNode IdentDecl where
nodeInfo (Declaration d) = nodeInfo d
nodeInfo (ObjectDef d) = nodeInfo d
nodeInfo (FunctionDef d) = nodeInfo d
nodeInfo (EnumeratorDef d) = nodeInfo d
instance Pos IdentDecl where
posOf x = posOf (nodeInfo x)
instance CNode DeclEvent where
nodeInfo (TagEvent d) = nodeInfo d
nodeInfo (DeclEvent d) = nodeInfo d
nodeInfo (ParamEvent d) = nodeInfo d
nodeInfo (LocalEvent d) = nodeInfo d
nodeInfo (TypeDefEvent d) = nodeInfo d
nodeInfo (AsmEvent d) = nodeInfo d
instance Pos DeclEvent where
posOf x = posOf (nodeInfo x)
instance CNode Decl where
nodeInfo (Decl _ n) = n
instance Pos Decl where
posOf x = posOf (nodeInfo x)
instance CNode ObjDef where
nodeInfo (ObjDef _ _ n) = n
instance Pos ObjDef where
posOf x = posOf (nodeInfo x)
instance CNode FunDef where
nodeInfo (FunDef _ _ n) = n
instance Pos FunDef where
posOf x = posOf (nodeInfo x)
instance CNode ParamDecl where
nodeInfo (ParamDecl _ n) = n
nodeInfo (AbstractParamDecl _ n) = n
instance Pos ParamDecl where
posOf x = posOf (nodeInfo x)
instance CNode MemberDecl where
nodeInfo (MemberDecl _ _ n) = n
nodeInfo (AnonBitField _ _ n) = n
instance Pos MemberDecl where
posOf x = posOf (nodeInfo x)
instance CNode TypeDef where
nodeInfo (TypeDef _ _ _ n) = n
instance Pos TypeDef where
posOf x = posOf (nodeInfo x)
instance CNode TypeDefRef where
nodeInfo (TypeDefRef _ _ n) = n
instance Pos TypeDefRef where
posOf x = posOf (nodeInfo x)
instance CNode CompTypeRef where
nodeInfo (CompTypeRef _ _ n) = n
instance Pos CompTypeRef where
posOf x = posOf (nodeInfo x)
instance CNode EnumTypeRef where
nodeInfo (EnumTypeRef _ n) = n
instance Pos EnumTypeRef where
posOf x = posOf (nodeInfo x)
instance CNode CompType where
nodeInfo (CompType _ _ _ _ n) = n
instance Pos CompType where
posOf x = posOf (nodeInfo x)
instance CNode EnumType where
nodeInfo (EnumType _ _ _ n) = n
instance Pos EnumType where
posOf x = posOf (nodeInfo x)
instance CNode Enumerator where
nodeInfo (Enumerator _ _ _ n) = n
instance Pos Enumerator where
posOf x = posOf (nodeInfo x)
instance CNode Attr where
nodeInfo (Attr _ _ n) = n
instance Pos Attr where
posOf x = posOf (nodeInfo x)
-- GENERATED STOP
| null | https://raw.githubusercontent.com/Practical-Formal-Methods/adiff/c18872faf3e31572437686d766f9972e00274588/language-c-extensible/src/Language/C/Analysis/SemRep.hs | haskell | # LANGUAGE DeriveDataTypeable #
---------------------------------------------------------------------------
|
Module : Language.C.Analysis.Syntax
License : BSD-style
Maintainer :
Stability : alpha
This module contains definitions for representing C translation units.
of a translation unit.
-------------------------------------------------------------------------------------------------
* Sums of tags and identifiers
* Global definitions
* Events for visitors
* Declarations and definitions
* Declaration attributes
* Types
* Variable names
| accessor class : struct\/union\/enum names
| accessor class : composite type tags (struct or union)
| Composite type definitions (tags)
composite definition
enum definition
| return the type corresponding to a tag definition
| All datatypes aggregating a declaration are instances of @Declaration@
| get the name, type and declaration attributes of a declaration or definition
| get the declaration corresponding to a definition
| get the variable identifier of a declaration (only safe if the
the declaration is known to have a name)
| get the variable name of a @Declaration@
| get the type of a @Declaration@
| get the declaration attributes of a @Declaration@
| identifiers, typedefs and enumeration constants (namespace sum)
^ object or function declaration
^ object definition
^ function definition
^ definition of an enumerator
| textual description of the kind of an object
is available.
| global declaration\/definition table returned by the analysis
| empty global declaration table
| filter global declarations
| merge global declarations
* Events
| Declaration events
Those events are reported to callbacks, which are executed during the traversal.
^ file-scope struct\/union\/enum event
^ file-scope declaration or definition
^ parameter declaration
^ local variable declaration or definition
^ a type definition
^ assembler block
* Declarations and definitions
| Declarations, which aren't definitions
| Object Definitions
An object definition is a declaration together with an initializer.
If the initializer is missing, it is a tentative definition, i.e. a
definition which might be overriden later on.
| Returns @True@ if the given object definition is tentative.
| Function definitions
A function definition is a declaration together with a statement (the function body).
| Parameter declaration
| Struct\/Union member declaration
| @typedef@ definitions.
The identifier is a new name for the given type.
| return the idenitifier of a @typedef@
| Generic variable declarations
@isExtDecl d@ returns true if the declaration has /linkage/
They specify the storage and linkage of a declared object.
| get the 'Storage' of a declaration
| get the `function attributes' of a declaration
Function attributes (inline, noreturn)
In C we have
Identifiers can either have internal, external or no linkage
(same object everywhere, same object within the translation unit, unique).
* top-level identifiers
static : internal linkage (objects and function defs)
extern : linkage of prior declaration (if specified), external linkage otherwise
no-spec: external linkage
* storage duration
* static storage duration: objects with external or internal linkage, or local ones with the static keyword
* automatic storage duration: otherwise (register)
| Storage duration and linkage of a variable
^ no storage
^ automatic storage (optional: register)
^ function, either internal or external linkage
| Linkage: Either no linkage, internal to the translation unit or external
| Get the linkage of a definition
* types
| types of C objects
^ a non-derived type
^ pointer type
^ array type
^ function type
^ a defined type
If the parameter types aren't yet known, the function has type @FunTypeIncomplete type attrs@.
| An array type may either have unknown size or a specified array size, the latter either variable or constant.
Furthermore, when used as a function parameters, the size may be qualified as /static/.
In a function prototype, the size may be `Unspecified variable size' (@[*]@).
^ @UnknownArraySize is-starred@
^ @FixedSizeArray is-static size-expr@
| normalized type representation
| typdef references
If the actual type is known, it is attached for convenience
| composite type declarations
| Composite type (struct or union).
| return the type of a composite type definition
| a tag to determine wheter we refer to a @struct@ or @union@, see 'CompType'.
| Representation of C enumeration types
| return the type of an enum definition
| An Enumerator consists of an identifier, a constant expressions and the link to its type
| Type qualifiers: constant, volatile and restrict
| no type qualifiers
* initializers
We're planning a normalized representation, but this depends on the implementation of
constant expression evaluation
| Normalized C Initializers
* If the expression has scalar type, the initializer is an expression
* If the expression has struct type, the initializer is a map from designators to initializers
* If the expression has array type, the initializer is a list of values
Not implemented yet, as it depends on constant expression evaluation
* names and attributes
| @VarName name assembler-name@ is a name of an declared object
| @__attribute__@ annotations
Those are of the form @Attr attribute-name attribute-parameters@,
and serve as generic properties of some syntax tree elements.
Some examples:
* labels can be attributed with /unused/ to indicate that their not used
* struct definitions can be attributed with /packed/ to tell the compiler to use the most compact representation
* declarations can be attributed with /deprecated/
* function declarations can be attributes with /noreturn/ to tell the compiler that the function will never return,
* or with /const/ to indicate that it is a pure function
/TODO/: ultimatively, we want to parse attributes and represent them in a typed way
|Empty attribute list
|Merge attribute lists
/TODO/: currently does not remove duplicates
* statements and expressions (Type aliases)
GENERATED START
GENERATED STOP | # LANGUAGE StandaloneDeriving #
Copyright : ( c ) 2008
Portability : ghc
In contrast to ' Language . C.Syntax . AST ' , the representation tries to express the semantics of
module Language.C.Analysis.SemRep(
TagDef(..),typeOfTagDef,
Declaration(..),declIdent,declName,declType,declAttrs,
IdentDecl(..),objKindDescr, splitIdentDecls,
GlobalDecls(..),emptyGlobalDecls,filterGlobalDecls,mergeGlobalDecls,
DeclEvent(..),
Decl(..),
ObjDef(..),isTentative,
FunDef(..),
ParamDecl(..),MemberDecl(..),
TypeDef(..),identOfTypeDef,
VarDecl(..),
DeclAttrs(..),isExtDecl,
FunctionAttrs(..), functionAttrs, noFunctionAttrs,
Storage(..),declStorage,ThreadLocal,Register,
Linkage(..),hasLinkage,declLinkage,
Type(..),
FunType(..),
ArraySize(..),
TypeDefRef(..),
TypeName(..),BuiltinType(..),
IntType(..),FloatType(..),
HasSUERef(..),HasCompTyKind(..),
CompTypeRef(..),CompType(..),typeOfCompDef,CompTyKind(..),
EnumTypeRef(..),EnumType(..),typeOfEnumDef,
Enumerator(..),
TypeQuals(..),noTypeQuals,mergeTypeQuals,
VarName(..),identOfVarName,isNoName,AsmName,
* Attributes ( STUB , not yet analyzed )
Attr(..),Attributes,noAttributes,mergeAttributes,
* Statements and Expressions ( STUB , aliases to Syntax )
Expr,Stmt,Initializer,AsmBlock,
)
where
import Data.Generics
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Language.C.Data
import Language.C.Syntax
import Data.Generics hiding (Generic)
class HasSUERef a where
sueRef :: a -> SUERef
class HasCompTyKind a where
compTag :: a -> CompTyKind
! , !
instance HasSUERef TagDef where
sueRef (CompDef ct) = sueRef ct
sueRef (EnumDef et) = sueRef et
typeOfTagDef :: TagDef -> TypeName
typeOfTagDef (CompDef comptype) = typeOfCompDef comptype
typeOfTagDef (EnumDef enumtype) = typeOfEnumDef enumtype
class Declaration n where
getVarDecl :: n -> VarDecl
declOfDef :: (Declaration n, CNode n) => n -> Decl
declOfDef def = let vd = getVarDecl def in Decl vd (nodeInfo def)
declIdent :: (Declaration n) => n -> Ident
declIdent = identOfVarName . declName
declName :: (Declaration n) => n -> VarName
declName = (\(VarDecl n _ _) -> n) . getVarDecl
declType :: (Declaration n) => n -> Type
declType = (\(VarDecl _ _ ty) -> ty) . getVarDecl
declAttrs :: (Declaration n) => n -> DeclAttrs
declAttrs = (\(VarDecl _ specs _) -> specs) . getVarDecl
instance (Declaration a, Declaration b) => Declaration (Either a b) where
getVarDecl = either getVarDecl getVarDecl
! , !
instance Declaration IdentDecl where
getVarDecl (Declaration decl) = getVarDecl decl
getVarDecl (ObjectDef def) = getVarDecl def
getVarDecl (FunctionDef def) = getVarDecl def
getVarDecl (EnumeratorDef def) = getVarDecl def
objKindDescr :: IdentDecl -> String
objKindDescr (Declaration _ ) = "declaration"
objKindDescr (ObjectDef _) = "object definition"
objKindDescr (FunctionDef _) = "function definition"
objKindDescr (EnumeratorDef _) = "enumerator definition"
| @splitIdentDecls includeAllDecls@ splits a map of object , function and enumerator declarations and definitions into one map
holding declarations , and three maps for object definitions , enumerator definitions and function definitions .
If @includeAllDecls@ is all declarations are present in the first map , otherwise only those where no corresponding definition
splitIdentDecls :: Bool -> Map Ident IdentDecl -> (Map Ident Decl,
( Map Ident Enumerator,
Map Ident ObjDef,
Map Ident FunDef ) )
splitIdentDecls include_all = Map.foldWithKey (if include_all then deal else deal') (Map.empty,(Map.empty,Map.empty,Map.empty))
where
deal ident entry (decls,defs) = (Map.insert ident (declOfDef entry) decls, addDef ident entry defs)
deal' ident (Declaration d) (decls,defs) = (Map.insert ident d decls,defs)
deal' ident def (decls,defs) = (decls, addDef ident def defs)
addDef ident entry (es,os,fs) =
case entry of
Declaration _ -> (es,os,fs)
EnumeratorDef e -> (Map.insert ident e es,os,fs)
ObjectDef o -> (es,Map.insert ident o os,fs)
FunctionDef f -> (es, os,Map.insert ident f fs)
data GlobalDecls = GlobalDecls {
gObjs :: Map Ident IdentDecl,
gTags :: Map SUERef TagDef,
gTypeDefs :: Map Ident TypeDef
}
emptyGlobalDecls :: GlobalDecls
emptyGlobalDecls = GlobalDecls Map.empty Map.empty Map.empty
filterGlobalDecls :: (DeclEvent -> Bool) -> GlobalDecls -> GlobalDecls
filterGlobalDecls decl_filter gmap = GlobalDecls
{
gObjs = Map.filter (decl_filter . DeclEvent) (gObjs gmap),
gTags = Map.filter (decl_filter . TagEvent) (gTags gmap),
gTypeDefs = Map.filter (decl_filter . TypeDefEvent) (gTypeDefs gmap)
}
mergeGlobalDecls :: GlobalDecls -> GlobalDecls -> GlobalDecls
mergeGlobalDecls gmap1 gmap2 = GlobalDecls
{
gObjs = Map.union (gObjs gmap1) (gObjs gmap2),
gTags = Map.union (gTags gmap1) (gTags gmap2),
gTypeDefs = Map.union (gTypeDefs gmap1) (gTypeDefs gmap2)
}
data DeclEvent =
TagEvent TagDef
| DeclEvent IdentDecl
| ParamEvent ParamDecl
| LocalEvent IdentDecl
| TypeDefEvent TypeDef
| AsmEvent AsmBlock
! !
data Decl = Decl VarDecl NodeInfo
! , !
instance Declaration Decl where
getVarDecl (Decl vd _) = vd
data ObjDef = ObjDef VarDecl (Maybe Initializer) NodeInfo
! , !
instance Declaration ObjDef where
getVarDecl (ObjDef vd _ _) = vd
isTentative :: ObjDef -> Bool
isTentative (ObjDef decl init_opt _) | isExtDecl decl = isNothing init_opt
| otherwise = False
data FunDef = FunDef VarDecl Stmt NodeInfo
! , !
instance Declaration FunDef where
getVarDecl (FunDef vd _ _) = vd
data ParamDecl = ParamDecl VarDecl NodeInfo
| AbstractParamDecl VarDecl NodeInfo
! , !
instance Declaration ParamDecl where
getVarDecl (ParamDecl vd _) = vd
getVarDecl (AbstractParamDecl vd _) = vd
data MemberDecl = MemberDecl VarDecl (Maybe Expr) NodeInfo
^ @MemberDecl vardecl bitfieldsize node@
| AnonBitField Type Expr NodeInfo
^ size@
! , !
instance Declaration MemberDecl where
getVarDecl (MemberDecl vd _ _) = vd
getVarDecl (AnonBitField ty _ _) = VarDecl NoName (DeclAttrs noFunctionAttrs NoStorage []) ty
data TypeDef = TypeDef Ident Type Attributes NodeInfo
! , !
identOfTypeDef :: TypeDef -> Ident
identOfTypeDef (TypeDef ide _ _ _) = ide
data VarDecl = VarDecl VarName DeclAttrs Type
deriving (Eq, Ord, Show, Typeable, Data)
instance Declaration VarDecl where
getVarDecl = id
isExtDecl :: (Declaration n) => n -> Bool
isExtDecl = hasLinkage . declStorage
| Declaration attributes of the form isInlineFunction storage linkage attrs@
data DeclAttrs = DeclAttrs FunctionAttrs Storage Attributes
^ fspecs storage attrs@
deriving (Eq, Ord, Show, Typeable, Data)
declStorage :: (Declaration d) => d -> Storage
declStorage d = case declAttrs d of (DeclAttrs _ st _) -> st
functionAttrs :: (Declaration d) => d -> FunctionAttrs
functionAttrs d = case declAttrs d of (DeclAttrs fa _ _) -> fa
data FunctionAttrs = FunctionAttrs { isInline :: Bool, isNoreturn :: Bool }
deriving (Show, Eq, Ord, Typeable, Data)
noFunctionAttrs :: FunctionAttrs
noFunctionAttrs = FunctionAttrs { isInline = False, isNoreturn = False }
See , Table 8.1 , 8.2
^ static storage , linkage spec and thread local specifier ( gnu c )
deriving (Typeable, Data, Show, Eq, Ord)
type ThreadLocal = Bool
type Register = Bool
data Linkage = NoLinkage | InternalLinkage | ExternalLinkage
deriving (Typeable, Data, Show, Eq, Ord)
| return @True@ if the object has linkage
hasLinkage :: Storage -> Bool
hasLinkage (Auto _) = False
hasLinkage (Static NoLinkage _) = False
hasLinkage _ = True
declLinkage :: (Declaration d) => d -> Linkage
declLinkage decl =
case declStorage decl of
NoStorage -> undefined
Auto _ -> NoLinkage
Static linkage _ -> linkage
FunLinkage linkage -> linkage
data Type =
DirectType TypeName TypeQuals Attributes
| PtrType Type TypeQuals Attributes
| ArrayType Type ArraySize TypeQuals Attributes
| FunctionType FunType Attributes
| TypeDefType TypeDefRef TypeQuals Attributes
deriving (Eq, Ord, Show, Typeable, Data)
| Function types are of the form @FunType return - type
data FunType = FunType Type [ParamDecl] Bool
| FunTypeIncomplete Type
deriving (Eq, Ord, Show, Typeable, Data)
data ArraySize = UnknownArraySize Bool
| ArraySize Bool Expr
deriving (Eq, Ord, Typeable, Data)
instance Show ArraySize where
show arrSize = "ArraySize"
data TypeName =
TyVoid
| TyIntegral IntType
| TyFloating FloatType
| TyComplex FloatType
| TyComp CompTypeRef
| TyEnum EnumTypeRef
| TyBuiltin BuiltinType
deriving (Eq, Ord, Show, Typeable, Data)
| Builtin type ( va_list , anything )
data BuiltinType = TyVaList
| TyAny
deriving (Eq, Ord, Show, Typeable, Data)
data TypeDefRef = TypeDefRef Ident Type NodeInfo
! , !
| integral types ( C99 6.7.2.2 )
data IntType =
TyBool
| TyChar
| TySChar
| TyUChar
| TyShort
| TyUShort
| TyInt
| TyUInt
| TyInt128
| TyUInt128
| TyLong
| TyULong
| TyLLong
| TyULLong
deriving (Typeable, Data, Eq, Ord)
instance Show IntType where
show TyBool = "_Bool"
show TyChar = "char"
show TySChar = "signed char"
show TyUChar = "unsigned char"
show TyShort = "short"
show TyUShort = "unsigned short"
show TyInt = "int"
show TyUInt = "unsigned int"
show TyInt128 = "__int128"
show TyUInt128 = "unsigned __int128"
show TyLong = "long"
show TyULong = "unsigned long"
show TyLLong = "long long"
show TyULLong = "unsigned long long"
| floating point type ( C99 6.7.2.2 )
data FloatType =
TyFloat
| TyDouble
| TyLDouble
| TyFloat128
deriving (Typeable, Data, Eq, Ord)
instance Show FloatType where
show TyFloat = "float"
show TyDouble = "double"
show TyLDouble = "long double"
show TyFloat128 = "__float128"
data CompTypeRef = CompTypeRef SUERef CompTyKind NodeInfo
! , !
instance HasSUERef CompTypeRef where sueRef (CompTypeRef ref _ _) = ref
instance HasCompTyKind CompTypeRef where compTag (CompTypeRef _ tag _) = tag
data EnumTypeRef = EnumTypeRef SUERef NodeInfo
! , !
instance HasSUERef EnumTypeRef where sueRef (EnumTypeRef ref _) = ref
data CompType = CompType SUERef CompTyKind [MemberDecl] Attributes NodeInfo
! , !
instance HasSUERef CompType where sueRef (CompType ref _ _ _ _) = ref
instance HasCompTyKind CompType where compTag (CompType _ tag _ _ _) = tag
typeOfCompDef :: CompType -> TypeName
typeOfCompDef (CompType ref tag _ _ _) = TyComp (CompTypeRef ref tag undefNode)
data CompTyKind = StructTag
| UnionTag
deriving (Eq,Ord,Typeable,Data)
instance Show CompTyKind where
show StructTag = "struct"
show UnionTag = "union"
data EnumType = EnumType SUERef [Enumerator] Attributes NodeInfo
^ @EnumType name enumeration - constants attrs node@
! , !
instance HasSUERef EnumType where sueRef (EnumType ref _ _ _) = ref
typeOfEnumDef :: EnumType -> TypeName
typeOfEnumDef (EnumType ref _ _ _) = TyEnum (EnumTypeRef ref undefNode)
data Enumerator = Enumerator Ident Expr EnumType NodeInfo
! , !
instance Declaration Enumerator where
getVarDecl (Enumerator ide _ enumty _) =
VarDecl
(VarName ide Nothing)
(DeclAttrs noFunctionAttrs NoStorage [])
(DirectType (typeOfEnumDef enumty) noTypeQuals noAttributes)
data TypeQuals = TypeQuals { constant :: Bool, volatile :: Bool,
restrict :: Bool, atomic :: Bool,
nullable :: Bool, nonnull :: Bool }
deriving (Show, Typeable, Data)
instance Eq TypeQuals where
(==) (TypeQuals c1 v1 r1 a1 n1 nn1) (TypeQuals c2 v2 r2 a2 n2 nn2) =
c1 == c2 && v1 == v2 && r1 == r2 && a1 == a2 && n1 == n2 && nn1 == nn2
instance Ord TypeQuals where
(<=) (TypeQuals c1 v1 r1 a1 n1 nn1) (TypeQuals c2 v2 r2 a2 n2 nn2) =
c1 <= c2 && v1 <= v2 && r1 <= r2 && a1 <= a2 && n1 <= n2 && nn1 <= nn2
noTypeQuals :: TypeQuals
noTypeQuals = TypeQuals False False False False False False
| merge ( /&&/ ) two type qualifier sets
mergeTypeQuals :: TypeQuals -> TypeQuals -> TypeQuals
mergeTypeQuals (TypeQuals c1 v1 r1 a1 n1 nn1) (TypeQuals c2 v2 r2 a2 n2 nn2) =
TypeQuals (c1 && c2) (v1 && v2) (r1 && r2) (a1 && a2) (n1 && n2) (nn1 && nn2)
| ' Initializer ' is currently an alias for ' CInit ' .
type Initializer = CInit
data VarName = VarName Ident (Maybe AsmName)
| NoName
deriving (Eq, Ord, Show, Typeable, Data)
identOfVarName :: VarName -> Ident
identOfVarName NoName = error "identOfVarName: NoName"
identOfVarName (VarName ident _) = ident
isNoName :: VarName -> Bool
isNoName NoName = True
isNoName _ = False
| Top level assembler block ( alias for )
type AsmBlock = CStrLit
| Assembler name ( alias for )
type AsmName = CStrLit
data Attr = Attr Ident [Expr] NodeInfo
! , !
instance Show Attr where
show (Attr i _ ni) = "Attribute " ++ show i ++ " [] " ++ show ni
type Attributes = [Attr]
noAttributes :: Attributes
noAttributes = []
mergeAttributes :: Attributes -> Attributes -> Attributes
mergeAttributes = (++)
| ' Stmt ' is an alias for ' CStat ' ( Syntax )
type Stmt = CStat
| ' ' is currently an alias for ' CExpr ' ( Syntax )
type Expr = CExpr
deriving instance Data GlobalDecls
deriving instance Data TypeDef
deriving instance Data TagDef
deriving instance Data CompType
deriving instance Data MemberDecl
deriving instance Data EnumType
deriving instance Data Enumerator
deriving instance Data IdentDecl
deriving instance Data Decl
deriving instance Data ObjDef
deriving instance Data FunDef
instance CNode TagDef where
nodeInfo (CompDef d) = nodeInfo d
nodeInfo (EnumDef d) = nodeInfo d
instance Pos TagDef where
posOf x = posOf (nodeInfo x)
instance CNode IdentDecl where
nodeInfo (Declaration d) = nodeInfo d
nodeInfo (ObjectDef d) = nodeInfo d
nodeInfo (FunctionDef d) = nodeInfo d
nodeInfo (EnumeratorDef d) = nodeInfo d
instance Pos IdentDecl where
posOf x = posOf (nodeInfo x)
instance CNode DeclEvent where
nodeInfo (TagEvent d) = nodeInfo d
nodeInfo (DeclEvent d) = nodeInfo d
nodeInfo (ParamEvent d) = nodeInfo d
nodeInfo (LocalEvent d) = nodeInfo d
nodeInfo (TypeDefEvent d) = nodeInfo d
nodeInfo (AsmEvent d) = nodeInfo d
instance Pos DeclEvent where
posOf x = posOf (nodeInfo x)
instance CNode Decl where
nodeInfo (Decl _ n) = n
instance Pos Decl where
posOf x = posOf (nodeInfo x)
instance CNode ObjDef where
nodeInfo (ObjDef _ _ n) = n
instance Pos ObjDef where
posOf x = posOf (nodeInfo x)
instance CNode FunDef where
nodeInfo (FunDef _ _ n) = n
instance Pos FunDef where
posOf x = posOf (nodeInfo x)
instance CNode ParamDecl where
nodeInfo (ParamDecl _ n) = n
nodeInfo (AbstractParamDecl _ n) = n
instance Pos ParamDecl where
posOf x = posOf (nodeInfo x)
instance CNode MemberDecl where
nodeInfo (MemberDecl _ _ n) = n
nodeInfo (AnonBitField _ _ n) = n
instance Pos MemberDecl where
posOf x = posOf (nodeInfo x)
instance CNode TypeDef where
nodeInfo (TypeDef _ _ _ n) = n
instance Pos TypeDef where
posOf x = posOf (nodeInfo x)
instance CNode TypeDefRef where
nodeInfo (TypeDefRef _ _ n) = n
instance Pos TypeDefRef where
posOf x = posOf (nodeInfo x)
instance CNode CompTypeRef where
nodeInfo (CompTypeRef _ _ n) = n
instance Pos CompTypeRef where
posOf x = posOf (nodeInfo x)
instance CNode EnumTypeRef where
nodeInfo (EnumTypeRef _ n) = n
instance Pos EnumTypeRef where
posOf x = posOf (nodeInfo x)
instance CNode CompType where
nodeInfo (CompType _ _ _ _ n) = n
instance Pos CompType where
posOf x = posOf (nodeInfo x)
instance CNode EnumType where
nodeInfo (EnumType _ _ _ n) = n
instance Pos EnumType where
posOf x = posOf (nodeInfo x)
instance CNode Enumerator where
nodeInfo (Enumerator _ _ _ n) = n
instance Pos Enumerator where
posOf x = posOf (nodeInfo x)
instance CNode Attr where
nodeInfo (Attr _ _ n) = n
instance Pos Attr where
posOf x = posOf (nodeInfo x)
|
1aa84d49b279fa1d40bf2912118d6c068bcc53923abc8060a98e37795b03132e | bwo/macroparser | project.clj | (defproject bwo/macroparser "0.0.7c"
:license {:name "Eclipse Public License - v 1.0"
:url "-v10.html"
:distribution :repo
:comments "same as Clojure"}
:description "Tools for simplifying the writing of complex macros"
:url ""
:dependencies [[expectations "1.4.18"]
[org.clojure/clojure "1.4.0"]
[the/parsatron "0.0.4"]])
| null | https://raw.githubusercontent.com/bwo/macroparser/f03135fe1108959ea06c91cf6984bfb9a0fa9cd6/project.clj | clojure | (defproject bwo/macroparser "0.0.7c"
:license {:name "Eclipse Public License - v 1.0"
:url "-v10.html"
:distribution :repo
:comments "same as Clojure"}
:description "Tools for simplifying the writing of complex macros"
:url ""
:dependencies [[expectations "1.4.18"]
[org.clojure/clojure "1.4.0"]
[the/parsatron "0.0.4"]])
|
|
b755fd95ba1846dc344fe00a70ec3a73b91425edf77a51202ab19e90b555b4cd | oakmac/atom-parinfer | util.cljs | (ns atom-parinfer.util
(:require
[goog.dom :as gdom]
[oops.core :refer [ocall]]))
;; -----------------------------------------------------------------------------
;; Logging
(defn js-log
"Logs a JavaScript thing."
[js-thing]
(ocall js/console "log" js-thing))
(defn log
"Logs a Clojure thing."
[clj-thing]
(js-log (pr-str clj-thing)))
(defn log-atom-changes [_atm _kwd old-value new-value]
(log old-value)
(log new-value)
(js-log "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"))
(defn warn
([msg]
(ocall js/console "warn" msg))
([msg1 msg2]
(ocall js/console "warn" msg1 msg2)))
;; -----------------------------------------------------------------------------
DOM
(defn by-id [id]
(ocall js/document "getElementById" id))
(defn qs [selector]
(ocall js/document "querySelector" selector))
(defn remove-el! [el]
(gdom/removeNode el))
;; -----------------------------------------------------------------------------
;; String
(defn split-lines
"Same as clojure.string/split-lines, except it doesn't remove empty lines at
the end of the text."
[text]
(vec (.split text #"\r?\n")))
(defn lines-diff
"Returns a map {:diff X, :same Y} of the difference in lines between two texts.
NOTE: this is probably a reinvention of clojure.data/diff"
[text-a text-b]
(let [vec-a (split-lines text-a)
vec-b (split-lines text-b)
v-both (map vector vec-a vec-b)
initial-count {:diff 0, :same 0}]
(reduce (fn [running-count [line-a line-b]]
(if (= line-a line-b)
(update-in running-count [:same] inc)
(update-in running-count [:diff] inc)))
initial-count
v-both)))
;; -----------------------------------------------------------------------------
;; Misc
(defn one? [x]
(= 1 x))
(def always-nil (constantly nil))
| null | https://raw.githubusercontent.com/oakmac/atom-parinfer/3e12b9722466e163a0b536ec71c7c3e4a34a0e53/src-cljs/atom_parinfer/util.cljs | clojure | -----------------------------------------------------------------------------
Logging
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
String
-----------------------------------------------------------------------------
Misc | (ns atom-parinfer.util
(:require
[goog.dom :as gdom]
[oops.core :refer [ocall]]))
(defn js-log
"Logs a JavaScript thing."
[js-thing]
(ocall js/console "log" js-thing))
(defn log
"Logs a Clojure thing."
[clj-thing]
(js-log (pr-str clj-thing)))
(defn log-atom-changes [_atm _kwd old-value new-value]
(log old-value)
(log new-value)
(js-log "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"))
(defn warn
([msg]
(ocall js/console "warn" msg))
([msg1 msg2]
(ocall js/console "warn" msg1 msg2)))
DOM
(defn by-id [id]
(ocall js/document "getElementById" id))
(defn qs [selector]
(ocall js/document "querySelector" selector))
(defn remove-el! [el]
(gdom/removeNode el))
(defn split-lines
"Same as clojure.string/split-lines, except it doesn't remove empty lines at
the end of the text."
[text]
(vec (.split text #"\r?\n")))
(defn lines-diff
"Returns a map {:diff X, :same Y} of the difference in lines between two texts.
NOTE: this is probably a reinvention of clojure.data/diff"
[text-a text-b]
(let [vec-a (split-lines text-a)
vec-b (split-lines text-b)
v-both (map vector vec-a vec-b)
initial-count {:diff 0, :same 0}]
(reduce (fn [running-count [line-a line-b]]
(if (= line-a line-b)
(update-in running-count [:same] inc)
(update-in running-count [:diff] inc)))
initial-count
v-both)))
(defn one? [x]
(= 1 x))
(def always-nil (constantly nil))
|
6bd0a2bbbe30d6862c25aeecdc92d9c1be0d304ceee8be067e1685a743d95101 | mrkkrp/req | Req.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE DataKinds #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveLift #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE RoleAnnotations #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
{-# LANGUAGE TemplateHaskellQuotes #-}
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
-- |
Module : Network . HTTP.Req
Copyright : © 2016 – present
License : BSD 3 clause
--
Maintainer : < >
-- Stability : experimental
-- Portability : portable
--
-- The documentation below is structured in such a way that the most
important information is presented first : you learn how to do HTTP
-- requests, how to embed them in the monad you have, and then it gives you
-- details about less-common things you may want to know about. The
-- documentation is written with sufficient coverage of details and
-- examples, and it's designed to be a complete tutorial on its own.
--
-- === About the library
--
-- Req is an HTTP client library that attempts to be easy-to-use, type-safe,
-- and expandable.
--
-- “Easy-to-use” means that the library is designed to be beginner-friendly
-- so it's simple to add to your monad stack, intuitive to work with,
-- well-documented, and does not get in your way. Doing HTTP requests is a
common task and a library for this should be approachable and
clear to beginners , thus certain compromises were made . For example , one
-- cannot currently modify 'L.ManagerSettings' of the default manager
-- because the library always uses the same implicit global manager for
-- simplicity and maximal connection sharing. There is a way to use your own
-- manager with different settings, but it requires more typing.
--
-- “Type-safe” means that the library tries to eliminate certain classes of
-- errors. For example, we have correct-by-construction URLs; it is
-- guaranteed that the user does not send the request body when using
-- methods like GET or OPTIONS, and the amount of implicit assumptions is
-- minimized by making the user specify their intentions in an explicit
-- form. For example, it's not possible to avoid specifying the body or the
-- method of a request. Authentication methods that assume HTTPS force the
-- user to use HTTPS at the type level.
--
-- “Expandable” refers to the ability to create new components without
-- having to resort to hacking. For example, it's possible to define your
-- own HTTP methods, create new ways to construct the body of a request,
-- create new authorization options, perform a request in a different way,
-- and create your own methods to parse a response.
--
-- === Using with other libraries
--
* You wo n't need the low - level interface of @http - client@ most of the
-- time, but when you do, it's better to do a qualified import,
because @http - client@ has naming conflicts with @req@.
-- * For streaming of large request bodies see the companion package
-- @req-conduit@: <-conduit>.
--
-- === Lightweight, no risk solution
--
-- The library uses the following mature packages under the hood to
-- guarantee you the best experience:
--
-- * <-client>—low level HTTP
client used everywhere in Haskell .
-- * <-client-tls>—TLS (HTTPS)
support for @http - client@.
--
-- It's important to note that since we leverage well-known libraries that
the whole Haskell ecosystem uses , there is no risk in using @req@. The
machinery for performing requests is the same as with @http - conduit@ and
-- @wreq@. The only difference is the API.
module Network.HTTP.Req
( -- * Making a request
-- $making-a-request
req,
reqBr,
reqCb,
req',
withReqManager,
-- * Embedding requests in your monad
-- $embedding-requests
MonadHttp (..),
HttpConfig (..),
defaultHttpConfig,
Req,
runReq,
-- * Request
-- ** Method
-- $method
GET (..),
POST (..),
HEAD (..),
PUT (..),
DELETE (..),
TRACE (..),
CONNECT (..),
OPTIONS (..),
PATCH (..),
HttpMethod (..),
-- ** URL
-- $url
Url,
http,
https,
(/~),
(/:),
useHttpURI,
useHttpsURI,
useURI,
urlQ,
renderUrl,
-- ** Body
-- $body
NoReqBody (..),
ReqBodyJson (..),
ReqBodyFile (..),
ReqBodyBs (..),
ReqBodyLbs (..),
ReqBodyUrlEnc (..),
FormUrlEncodedParam,
ReqBodyMultipart,
reqBodyMultipart,
HttpBody (..),
ProvidesBody,
HttpBodyAllowed,
-- ** Optional parameters
-- $optional-parameters
Option,
-- *** Query parameters
-- $query-parameters
(=:),
queryFlag,
formToQuery,
QueryParam (..),
-- *** Headers
header,
attachHeader,
headerRedacted,
-- *** Cookies
-- $cookies
cookieJar,
-- *** Authentication
-- $authentication
basicAuth,
basicAuthUnsafe,
basicProxyAuth,
oAuth1,
oAuth2Bearer,
oAuth2Token,
customAuth,
-- *** Other
port,
decompress,
responseTimeout,
httpVersion,
-- * Response
-- ** Response interpretations
IgnoreResponse,
ignoreResponse,
JsonResponse,
jsonResponse,
BsResponse,
bsResponse,
LbsResponse,
lbsResponse,
-- ** Inspecting a response
responseBody,
responseStatusCode,
responseStatusMessage,
responseHeader,
responseCookieJar,
-- ** Defining your own interpretation
-- $new-response-interpretation
HttpResponse (..),
-- * Other
HttpException (..),
isStatusCodeException,
CanHaveBody (..),
Scheme (..),
)
where
import qualified Blaze.ByteString.Builder as BB
import Control.Applicative
import Control.Arrow (first, second)
import Control.Exception hiding (Handler (..), TypeError)
import Control.Monad (guard, void, (>=>))
import Control.Monad.Base
import Control.Monad.Catch (Handler (..), MonadCatch, MonadMask, MonadThrow)
import Control.Monad.IO.Class
import Control.Monad.IO.Unlift
import Control.Monad.Reader (ReaderT (ReaderT), ask, lift, runReaderT)
import Control.Monad.Trans.Accum (AccumT)
import Control.Monad.Trans.Cont (ContT)
import Control.Monad.Trans.Control
import Control.Monad.Trans.Except (ExceptT)
import Control.Monad.Trans.Identity (IdentityT)
import Control.Monad.Trans.Maybe (MaybeT)
import qualified Control.Monad.Trans.RWS.CPS as RWS.CPS
import qualified Control.Monad.Trans.RWS.Lazy as RWS.Lazy
import qualified Control.Monad.Trans.RWS.Strict as RWS.Strict
import Control.Monad.Trans.Select (SelectT)
import qualified Control.Monad.Trans.State.Lazy as State.Lazy
import qualified Control.Monad.Trans.State.Strict as State.Strict
import qualified Control.Monad.Trans.Writer.CPS as Writer.CPS
import qualified Control.Monad.Trans.Writer.Lazy as Writer.Lazy
import qualified Control.Monad.Trans.Writer.Strict as Writer.Strict
import Control.Retry
import Data.Aeson (FromJSON (..), ToJSON (..))
import qualified Data.Aeson as A
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.CaseInsensitive as CI
import Data.Data (Data)
import Data.Function (on)
import Data.IORef
import Data.Kind (Constraint, Type)
import Data.List (foldl', nubBy)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
import Data.Maybe (fromMaybe)
import Data.Proxy
import Data.Semigroup (Endo (..))
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Typeable (Typeable, cast)
import GHC.Generics
import GHC.TypeLits
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Quote as TH
import qualified Language.Haskell.TH.Syntax as TH
import qualified Network.Connection as NC
import qualified Network.HTTP.Client as L
import qualified Network.HTTP.Client.Internal as LI
import qualified Network.HTTP.Client.MultipartFormData as LM
import qualified Network.HTTP.Client.TLS as L
import qualified Network.HTTP.Types as Y
import System.IO.Unsafe (unsafePerformIO)
import Text.URI (URI)
import qualified Text.URI as URI
import qualified Text.URI.QQ as QQ
import qualified Web.Authenticate.OAuth as OAuth
import Web.FormUrlEncoded (FromForm (..), ToForm (..))
import qualified Web.FormUrlEncoded as Form
import Web.HttpApiData (ToHttpApiData (..))
----------------------------------------------------------------------------
-- Making a request
-- $making-a-request
--
To make an HTTP request you normally need only one function : ' req ' .
| Make an HTTP request . The function takes 5 arguments , 4 of which
-- specify required parameters and the final 'Option' argument is a
-- collection of optional parameters.
--
Let 's go through all the arguments first : @req method url body response
-- options@.
--
-- @method@ is an HTTP method such as 'GET' or 'POST'. The documentation has
-- a dedicated section about HTTP methods below.
--
-- @url@ is a 'Url' that describes location of resource you want to interact
-- with.
--
@body@ is a body option such as ' NoReqBody ' or ' ReqBodyJson ' . The
-- tutorial has a section about HTTP bodies, but usage is very
-- straightforward and should be clear from the examples.
--
-- @response@ is a type hint how to make and interpret response of an HTTP
-- request. Out-of-the-box it can be the following:
--
-- * 'ignoreResponse'
-- * 'jsonResponse'
* ' bsResponse ' ( to get a strict ' ByteString ' )
-- * 'lbsResponse' (to get a lazy 'BL.ByteString')
--
-- Finally, @options@ is a 'Monoid' that holds a composite 'Option' for all
-- other optional settings like query parameters, headers, non-standard port
-- number, etc. There are quite a few things you can put there, see the
-- corresponding section in the documentation. If you don't need anything at
all , pass ' ' .
--
-- __Note__ that if you use 'req' to do all your requests, connection
-- sharing and reuse is done for you automatically.
--
-- See the examples below to get on the speed quickly.
--
-- ==== __Examples__
--
First , this is a piece of boilerplate that should be in place before you
-- try the examples:
--
> { - # LANGUAGE DeriveGeneric # - }
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > module Main (main) where
-- >
> import Control . Monad
> import Control . Monad . IO.Class
-- > import Data.Aeson
-- > import Data.Maybe (fromJust)
> import Data . Monoid ( ( < > ) )
-- > import Data.Text (Text)
> import
> import Network . HTTP.Req
> import qualified Data . ByteString . Char8 as B
> import qualified Text . URI as URI
--
-- We will be making requests against the <> service.
--
Make a GET request , grab 5 random bytes :
--
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
-- > let n :: Int
> n = 5
> bs < - req GET ( https " httpbin.org " / : " bytes " /~ n ) NoReqBody bsResponse mempty
-- > liftIO $ B.putStrLn (responseBody bs)
--
-- The same, but now we use a query parameter named @\"seed\"@ to control
-- seed of the generator:
--
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
-- > let n, seed :: Int
> n = 5
> seed = 100
> bs < - req GET ( https " httpbin.org " / : " bytes " /~ n ) NoReqBody bsResponse $
-- > "seed" =: seed
-- > liftIO $ B.putStrLn (responseBody bs)
--
-- POST JSON data and get some info about the POST request:
--
> data
-- > { size :: Int
-- > , color :: Text
-- > } deriving (Show, Generic)
-- >
> instance ToJSON MyData
> instance FromJSON MyData
-- >
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
> let
> { size = 6
-- > , color = "Green" }
> v < - req POST ( https " httpbin.org " / : " post " ) ( )
-- > liftIO $ print (responseBody v :: Value)
--
-- Sending URL-encoded body:
--
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
-- > let params =
-- > "foo" =: ("bar" :: Text) <>
-- > queryFlag "baz"
> response < - req POST ( https " httpbin.org " / : " post " ) ( ReqBodyUrlEnc params )
-- > liftIO $ print (responseBody response :: Value)
--
-- Using various optional parameters and URL that is not known in advance:
--
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
-- > -- This is an example of what to do when URL is given dynamically. Of
-- > -- course in a real application you may not want to use 'fromJust'.
> uri < - URI.mkURI " "
-- > let (url, options) = fromJust (useHttpsURI uri)
> response < - req GET url NoReqBody jsonResponse $
> " from " = : ( 15 : : Int ) < >
> " to " = : ( 67 : : Int ) < >
-- > basicAuth "username" "password" <>
-- > options <> -- contains the ?foo=bar part
> port 443 -- here you can put any port of course
-- > liftIO $ print (responseBody response :: Value)
req ::
( MonadHttp m,
HttpMethod method,
HttpBody body,
HttpResponse response,
HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
) =>
-- | HTTP method
method ->
-- | 'Url'—location of resource
Url scheme ->
-- | Body of the request
body ->
-- | A hint how to interpret response
Proxy response ->
-- | Collection of optional parameters
Option scheme ->
-- | Response
m response
req method url body responseProxy options =
reqCb method url body responseProxy options pure
-- | A version of 'req' that does not use one of the predefined instances of
' HttpResponse ' but instead allows the user to consume @'L.Response '
-- 'L.BodyReader'@ manually, in a custom way.
--
-- @since 1.0.0
reqBr ::
( MonadHttp m,
HttpMethod method,
HttpBody body,
HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
) =>
-- | HTTP method
method ->
-- | 'Url'—location of resource
Url scheme ->
-- | Body of the request
body ->
-- | Collection of optional parameters
Option scheme ->
-- | How to consume response
(L.Response L.BodyReader -> IO a) ->
-- | Result
m a
reqBr method url body options consume =
req' method url body options (reqHandler consume)
| A version of ' req ' that takes a callback to modify the ' L.Request ' , but
-- otherwise performs the request identically.
--
@since 3.7.0
reqCb ::
( MonadHttp m,
HttpMethod method,
HttpBody body,
HttpResponse response,
HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
) =>
-- | HTTP method
method ->
-- | 'Url'—location of resource
Url scheme ->
-- | Body of the request
body ->
-- | A hint how to interpret response
Proxy response ->
-- | Collection of optional parameters
Option scheme ->
-- | Callback to modify the request
(L.Request -> m L.Request) ->
-- | Response
m response
reqCb method url body responseProxy options adjustRequest =
req' method url body (options <> extraOptions) $ \request manager -> do
request' <- adjustRequest request
reqHandler getHttpResponse request' manager
where
extraOptions =
case acceptHeader responseProxy of
Nothing -> mempty
Just accept -> header "Accept" accept
-- | The default handler function that the higher-level request functions
-- pass to 'req''. Internal function.
--
@since 3.7.0
reqHandler ::
(MonadHttp m) =>
-- | How to get final result from a 'L.Response'
(L.Response L.BodyReader -> IO b) ->
| ' L.Request ' to perform
L.Request ->
-- | 'L.Manager' to use
L.Manager ->
m b
reqHandler consume request manager = do
HttpConfig {..} <- getHttpConfig
let wrapVanilla = handle (throwIO . VanillaHttpException)
wrapExc = handle (throwIO . LI.toHttpException request)
withRRef =
bracket
(newIORef Nothing)
(readIORef >=> mapM_ L.responseClose)
(liftIO . try . wrapVanilla . wrapExc)
( withRRef $ \rref -> do
let openResponse = mask_ $ do
r <- readIORef rref
mapM_ L.responseClose r
r' <- L.responseOpen request manager
writeIORef rref (Just r')
return r'
exceptionRetryPolicies =
skipAsyncExceptions
++ [ \retryStatus -> Handler $ \e ->
return $ httpConfigRetryJudgeException retryStatus e
]
r <-
retrying
httpConfigRetryPolicy
(\retryStatus r -> return $ httpConfigRetryJudge retryStatus r)
( const
( recovering
httpConfigRetryPolicy
exceptionRetryPolicies
(const openResponse)
)
)
(preview, r') <- grabPreview httpConfigBodyPreviewLength r
mapM_ LI.throwHttp (httpConfigCheckResponse request r' preview)
consume r'
)
>>= either handleHttpException return
-- | Mostly like 'req' with respect to its arguments, but accepts a callback
-- that allows to perform a request in arbitrary fashion.
--
-- This function /does not/ perform handling\/wrapping exceptions, checking
-- response (with 'httpConfigCheckResponse'), and retrying. It only prepares
' L.Request ' and allows you to use it .
--
-- @since 0.3.0
req' ::
forall m method body scheme a.
( MonadHttp m,
HttpMethod method,
HttpBody body,
HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
) =>
-- | HTTP method
method ->
-- | 'Url'—location of resource
Url scheme ->
-- | Body of the request
body ->
-- | Collection of optional parameters
Option scheme ->
-- | How to perform request
(L.Request -> L.Manager -> m a) ->
-- | Result
m a
req' method url body options m = do
config <- getHttpConfig
NOTE First appearance of any given header wins . This allows to
-- “overwrite” headers when we construct a request by cons-ing.
nubHeaders = Endo $ \x ->
x {L.requestHeaders = nubBy ((==) `on` fst) (L.requestHeaders x)}
request' =
flip appEndo L.defaultRequest $
-- NOTE The order of 'mappend's matters, here method is overwritten
-- first and 'options' take effect last. In particular, this means
-- that 'options' can overwrite things set by other request
-- components, which is useful for setting port number,
" Content - Type " header , etc .
nubHeaders
<> getRequestMod options
<> getRequestMod config
<> getRequestMod (Tagged body :: Tagged "body" body)
<> getRequestMod url
<> getRequestMod (Tagged method :: Tagged "method" method)
request <- finalizeRequest options request'
withReqManager (m request)
-- | Perform an action using the global implicit 'L.Manager' that the rest
-- of the library uses. This allows to reuse connections that the
-- 'L.Manager' controls.
withReqManager :: (MonadIO m) => (L.Manager -> m a) -> m a
withReqManager m = liftIO (readIORef globalManager) >>= m
-- | The global 'L.Manager' that 'req' uses. Here we just go with the
-- default settings, so users don't need to deal with this manager stuff at
all , but when we create a request , instance ' HttpConfig ' can affect the
-- default settings via 'getHttpConfig'.
--
-- A note about safety, in case 'unsafePerformIO' looks suspicious to you.
-- The value of 'globalManager' is named and lives on top level. This means
it will be shared , i.e. computed only once on the first use of the
-- manager. From that moment on the 'IORef' will be just reused—exactly the
behavior we want here in order to maximize connection sharing . GHC could
-- spoil the plan by inlining the definition, hence the @NOINLINE@ pragma.
globalManager :: IORef L.Manager
globalManager = unsafePerformIO $ do
context <- NC.initConnectionContext
let settings =
L.mkManagerSettingsContext
(Just context)
(NC.TLSSettingsSimple False False False)
Nothing
manager <- L.newManager settings
newIORef manager
# NOINLINE globalManager #
----------------------------------------------------------------------------
-- Embedding requests in your monad
-- $embedding-requests
--
-- To use 'req' in your monad, all you need to do is to make the monad an
instance of the ' MonadHttp ' type class .
--
-- When writing a library, keep your API polymorphic in terms of
' ' , only define instance of ' ' in final application .
Another option is to use a @newtype@-wrapped monad stack and define
' ' for it . As of the version /0.4.0/ , the ' Req ' monad that
-- follows this strategy is provided out-of-the-box (see below).
-- | A type class for monads that support performing HTTP requests.
-- Typically, you only need to define the 'handleHttpException' method
unless you want to tweak ' HttpConfig ' .
class (MonadIO m) => MonadHttp m where
| This method describes how to deal with ' HttpException ' that was
caught by the library . One option is to re - throw it if you are OK with
-- exceptions, but if you prefer working with something like
' Control . . Except . ' , this is the right place to pass it to
' Control . Monad . Except.throwError ' .
handleHttpException :: HttpException -> m a
| Return the ' HttpConfig ' to be used when performing HTTP requests .
-- Default implementation returns its 'def' value, which is described in
-- the documentation for the type. Common usage pattern with manually
-- defined 'getHttpConfig' is to return some hard-coded value, or a value
extracted from ' Control . . Reader . MonadReader ' if a more flexible
-- approach to configuration is desirable.
getHttpConfig :: m HttpConfig
getHttpConfig = return defaultHttpConfig
| ' HttpConfig ' contains settings to be used when making HTTP requests .
data HttpConfig = HttpConfig
{ -- | Proxy to use. By default values of @HTTP_PROXY@ and @HTTPS_PROXY@
-- environment variables are respected, this setting overwrites them.
-- Default value: 'Nothing'.
httpConfigProxy :: Maybe L.Proxy,
-- | How many redirects to follow when getting a resource. Default
value : 10 .
httpConfigRedirectCount :: Int,
-- | Alternative 'L.Manager' to use. 'Nothing' (default value) means
-- that the default implicit manager will be used (that's what you want
in 99 % of cases ) .
httpConfigAltManager :: Maybe L.Manager,
-- | Function to check the response immediately after receiving the
status and headers , before streaming of response body . The third
argument is the beginning of response body ( typically first 1024
-- bytes). This is used for throwing exceptions on non-success status
-- codes by default (set to @\\_ _ _ -> Nothing@ if this behavior is not
-- desirable).
--
-- When the value this function returns is 'Nothing', nothing will
-- happen. When it there is 'L.HttpExceptionContent' inside 'Just', it
-- will be thrown.
--
-- Throwing is better then just returning a request with non-2xx status
-- code because in that case something is wrong and we need a way to
short - cut execution ( also remember that Req retries automatically on
-- request timeouts and such, so when your request fails, it's certainly
-- something exceptional). The thrown exception is caught by the library
-- though and is available in 'handleHttpException'.
--
-- __Note__: signature of this function was changed in the version
-- /1.0.0/.
--
-- @since 0.3.0
httpConfigCheckResponse ::
forall b.
L.Request ->
L.Response b ->
ByteString ->
Maybe L.HttpExceptionContent,
-- | The retry policy to use for request retrying. By default 'def' is
-- used (see 'RetryPolicyM').
--
-- __Note__: signature of this function was changed to disallow 'IO' in
-- version /1.0.0/ and then changed back to its current form in /3.1.0/.
--
-- @since 0.3.0
httpConfigRetryPolicy :: RetryPolicyM IO,
-- | The function is used to decide whether to retry a request. 'True'
-- means that the request should be retried.
--
-- __Note__: signature of this function was changed in the version
-- /1.0.0/.
--
-- @since 0.3.0
httpConfigRetryJudge :: forall b. RetryStatus -> L.Response b -> Bool,
-- | Similar to 'httpConfigRetryJudge', but is used to decide when to
-- retry requests that resulted in an exception. By default it retries
-- on response timeout and connection timeout (changed in version
-- /3.8.0/).
--
@since 3.4.0
httpConfigRetryJudgeException :: RetryStatus -> SomeException -> Bool,
| length of preview fragment of response body .
--
@since 3.6.0
httpConfigBodyPreviewLength :: forall a. (Num a) => a
}
deriving (Typeable)
| The default value of ' HttpConfig ' .
--
-- @since 2.0.0
defaultHttpConfig :: HttpConfig
defaultHttpConfig =
HttpConfig
{ httpConfigProxy = Nothing,
httpConfigRedirectCount = 10,
httpConfigAltManager = Nothing,
httpConfigCheckResponse = \_ response preview ->
let scode = statusCode response
in if 200 <= scode && scode < 300
then Nothing
else Just (L.StatusCodeException (void response) preview),
httpConfigRetryPolicy = retryPolicyDefault,
httpConfigRetryJudge = \_ response ->
statusCode response
`elem` [ 408, -- Request timeout
Gateway timeout
524, -- A timeout occurred
598, -- (Informal convention) Network read timeout error
599 -- (Informal convention) Network connect timeout error
],
httpConfigRetryJudgeException = \_ e ->
case fromException e of
Just (L.HttpExceptionRequest _ c) ->
case c of
L.ResponseTimeout -> True
L.ConnectionTimeout -> True
_ -> False
_ -> False,
httpConfigBodyPreviewLength = 1024
}
where
statusCode = Y.statusCode . L.responseStatus
instance RequestComponent HttpConfig where
getRequestMod HttpConfig {..} = Endo $ \x ->
x
{ L.proxy = httpConfigProxy,
L.redirectCount = httpConfigRedirectCount,
LI.requestManagerOverride = httpConfigAltManager
}
-- | A monad that allows us to run 'req' in any 'IO'-enabled monad without
-- having to define new instances.
--
@since 0.4.0
newtype Req a = Req (ReaderT HttpConfig IO a)
deriving
( Functor,
Applicative,
Monad,
MonadIO,
MonadUnliftIO
)
| @since 3.7.0
deriving instance MonadThrow Req
| @since 3.7.0
deriving instance MonadCatch Req
| @since 3.7.0
deriving instance MonadMask Req
instance MonadBase IO Req where
liftBase = liftIO
instance MonadBaseControl IO Req where
type StM Req a = a
liftBaseWith f = Req . ReaderT $ \r -> f (runReq r)
# INLINEABLE liftBaseWith #
restoreM = Req . ReaderT . const . return
# INLINEABLE restoreM #
instance MonadHttp Req where
handleHttpException = Req . lift . throwIO
getHttpConfig = Req ask
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (AccumT w m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (ContT r m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (ExceptT e m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (IdentityT m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (MaybeT m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (ReaderT r m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (RWS.CPS.RWST r w s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (RWS.Lazy.RWST r w s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (RWS.Strict.RWST r w s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (SelectT r m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (State.Lazy.StateT s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (State.Strict.StateT s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (Writer.CPS.WriterT w m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (Writer.Lazy.WriterT w m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (Writer.Strict.WriterT w m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| Run a computation in the ' Req ' monad with the given ' HttpConfig ' . In
the case of an exceptional situation an ' HttpException ' will be thrown .
--
@since 0.4.0
runReq ::
(MonadIO m) =>
| ' HttpConfig ' to use
HttpConfig ->
-- | Computation to run
Req a ->
m a
runReq config (Req m) = liftIO (runReaderT m config)
----------------------------------------------------------------------------
-- Request—Method
-- $method
--
-- The package supports all methods as defined by RFC 2616, and 'PATCH'
which is defined by RFC 5789 — that should be enough to talk to RESTful
-- APIs. In some cases, however, you may want to add more methods (e.g. you
work with WebDAV < > ) ; no need to
compromise on type safety and hack , it only takes a couple of seconds to
define a new method that will works seamlessly , see ' HttpMethod ' .
-- | 'GET' method.
data GET = GET
instance HttpMethod GET where
type AllowsBody GET = 'NoBody
httpMethodName Proxy = Y.methodGet
-- | 'POST' method.
data POST = POST
instance HttpMethod POST where
type AllowsBody POST = 'CanHaveBody
httpMethodName Proxy = Y.methodPost
-- | 'HEAD' method.
data HEAD = HEAD
instance HttpMethod HEAD where
type AllowsBody HEAD = 'NoBody
httpMethodName Proxy = Y.methodHead
-- | 'PUT' method.
data PUT = PUT
instance HttpMethod PUT where
type AllowsBody PUT = 'CanHaveBody
httpMethodName Proxy = Y.methodPut
-- | 'DELETE' method. RFC 7231 allows a payload in DELETE but without
-- semantics.
--
-- __Note__: before version /3.4.0/ this method did not allow request
-- bodies.
data DELETE = DELETE
instance HttpMethod DELETE where
type AllowsBody DELETE = 'CanHaveBody
httpMethodName Proxy = Y.methodDelete
-- | 'TRACE' method.
data TRACE = TRACE
instance HttpMethod TRACE where
type AllowsBody TRACE = 'CanHaveBody
httpMethodName Proxy = Y.methodTrace
-- | 'CONNECT' method.
data CONNECT = CONNECT
instance HttpMethod CONNECT where
type AllowsBody CONNECT = 'CanHaveBody
httpMethodName Proxy = Y.methodConnect
-- | 'OPTIONS' method.
data OPTIONS = OPTIONS
instance HttpMethod OPTIONS where
type AllowsBody OPTIONS = 'NoBody
httpMethodName Proxy = Y.methodOptions
-- | 'PATCH' method.
data PATCH = PATCH
instance HttpMethod PATCH where
type AllowsBody PATCH = 'CanHaveBody
httpMethodName Proxy = Y.methodPatch
-- | A type class for types that can be used as an HTTP method. To define a
-- non-standard method, follow this example that defines @COPY@:
--
> data COPY = COPY
-- >
> instance HttpMethod COPY where
> type AllowsBody COPY = ' CanHaveBody
-- > httpMethodName Proxy = "COPY"
class HttpMethod a where
| Type function ' AllowsBody ' returns a type of kind ' CanHaveBody ' which
-- tells the rest of the library whether the method can have body or not.
-- We use the special type 'CanHaveBody' lifted to the kind level instead
of ' ' to get more user - friendly compiler messages .
type AllowsBody a :: CanHaveBody
-- | Return name of the method as a 'ByteString'.
httpMethodName :: Proxy a -> ByteString
instance (HttpMethod method) => RequestComponent (Tagged "method" method) where
getRequestMod _ = Endo $ \x ->
x {L.method = httpMethodName (Proxy :: Proxy method)}
----------------------------------------------------------------------------
-- Request—URL
-- $url
--
-- We use 'Url's which are correct by construction, see 'Url'. To build a
-- 'Url' from a 'URI', use 'useHttpURI', 'useHttpsURI', or generic 'useURI'.
-- | Request's 'Url'. Start constructing your 'Url' with 'http' or 'https'
specifying the scheme and host at the same time . Then use the @('/~')@
and @('/:')@ operators to grow the path one piece at a time . Every single
piece of path will be url(percent)-encoded , so using @('/~')@ and
@('/:')@ is the only way to have forward slashes between path segments .
-- This approach makes working with dynamic path segments easy and safe. See
-- examples below how to represent various 'Url's (make sure the
language extension is enabled ) .
--
-- ==== __Examples__
--
-- > http "httpbin.org"
-- > --
--
-- > https "httpbin.org"
-- > --
--
> https " httpbin.org " / : " encoding " / : " utf8 "
-- > --
--
-- > https "httpbin.org" /: "foo" /: "bar/baz"
-- > --
--
> https " httpbin.org " / : " bytes " /~ ( 10 : : Int )
-- > --
--
-- > https "юникод.рф"
-- > --
data Url (scheme :: Scheme) = Url Scheme (NonEmpty Text)
NOTE The second value is the path segments in reversed order .
deriving (Eq, Ord, Show, Data, Typeable, Generic)
type role Url nominal
With template - haskell > = 2.15 and text > = 1.2.4 Lift can be derived , however
-- the derived lift forgets the type of the scheme.
instance (Typeable scheme) => TH.Lift (Url scheme) where
lift url =
TH.dataToExpQ (fmap liftText . cast) url `TH.sigE` case url of
Url Http _ -> [t|Url 'Http|]
Url Https _ -> [t|Url 'Https|]
where
liftText t = TH.AppE (TH.VarE 'T.pack) <$> TH.lift (T.unpack t)
liftTyped = TH.Code . TH.unsafeTExpCoerce . TH.lift
-- | Given host name, produce a 'Url' which has “http” as its scheme and
-- empty path. This also sets port to @80@.
http :: Text -> Url 'Http
http = Url Http . pure
-- | Given host name, produce a 'Url' which has “https” as its scheme and
-- empty path. This also sets port to @443@.
https :: Text -> Url 'Https
https = Url Https . pure
-- | Grow a given 'Url' appending a single path segment to it. Note that the
-- path segment can be of any type that is an instance of 'ToHttpApiData'.
infixl 5 /~
(/~) :: (ToHttpApiData a) => Url scheme -> a -> Url scheme
Url secure path /~ segment = Url secure (NE.cons (toUrlPiece segment) path)
| A type - constrained version of @('/~')@ to remove ambiguity in the cases
-- when next URL piece is a 'Data.Text.Text' literal.
infixl 5 /:
(/:) :: Url scheme -> Text -> Url scheme
(/:) = (/~)
-- | Render a 'Url' as 'Text'.
--
@since 3.4.0
renderUrl :: Url scheme -> Text
renderUrl = \case
Url Https parts ->
"https://" <> renderParts parts
Url Http parts ->
"http://" <> renderParts parts
where
renderParts parts =
T.intercalate "/" (reverse $ NE.toList parts)
-- | The 'useHttpURI' function provides an alternative method to get 'Url'
-- (possibly with some 'Option's) from a 'URI'. This is useful when you are
-- given a URL to query dynamically and don't know it beforehand.
--
-- This function expects the scheme to be “http” and host to be present.
--
-- @since 3.0.0
useHttpURI :: URI -> Maybe (Url 'Http, Option scheme)
useHttpURI uri = do
guard (URI.uriScheme uri == Just [QQ.scheme|http|])
urlHead <- http <$> uriHost uri
let url = case URI.uriPath uri of
Nothing -> urlHead
Just uriPath -> uriPathToUrl uriPath urlHead
return (url, uriOptions uri)
-- | Just like 'useHttpURI', but expects the “https” scheme.
--
-- @since 3.0.0
useHttpsURI :: URI -> Maybe (Url 'Https, Option scheme)
useHttpsURI uri = do
guard (URI.uriScheme uri == Just [QQ.scheme|https|])
urlHead <- https <$> uriHost uri
let url = case URI.uriPath uri of
Nothing -> urlHead
Just uriPath -> uriPathToUrl uriPath urlHead
return (url, uriOptions uri)
-- | Convert URI path to a 'Url'. Internal.
--
-- @since 3.9.0
uriPathToUrl ::
(Bool, NonEmpty (URI.RText 'URI.PathPiece)) ->
Url scheme ->
Url scheme
uriPathToUrl (trailingSlash, xs) urlHead =
if trailingSlash then path /: T.empty else path
where
path = foldl' (/:) urlHead (URI.unRText <$> NE.toList xs)
-- | A combination of 'useHttpURI' and 'useHttpsURI' for cases when scheme
-- is not known in advance.
--
-- @since 3.0.0
useURI ::
URI ->
Maybe
( Either
(Url 'Http, Option scheme0)
(Url 'Https, Option scheme1)
)
useURI uri =
(Left <$> useHttpURI uri) <|> (Right <$> useHttpsURI uri)
-- | An internal helper function to extract host from a 'URI'.
uriHost :: URI -> Maybe Text
uriHost uri = case URI.uriAuthority uri of
Left _ -> Nothing
Right URI.Authority {..} ->
Just (URI.unRText authHost)
-- | A quasiquoter to build an 'Url' and 'Option' tuple. The type of the
generated expression is @('Url ' scheme0 , ' Option ' scheme1)@ with
@scheme0@ being either ' Http ' or ' Https ' depending on the input .
--
-- @since 3.2.0
urlQ :: TH.QuasiQuoter
urlQ =
TH.QuasiQuoter
{ quoteExp = \str ->
case URI.mkURI (T.pack str) of
Left err -> fail (displayException err)
Right uri -> case useURI uri of
Nothing -> fail "Not a HTTP or HTTPS URL"
Just eurl ->
TH.tupE
[ either (TH.lift . fst) (TH.lift . fst) eurl,
[|uriOptions uri|]
],
quotePat = error "This usage is not supported",
quoteType = error "This usage is not supported",
quoteDec = error "This usage is not supported"
}
-- | An internal helper function to extract 'Option's from a 'URI'.
uriOptions :: forall scheme. URI -> Option scheme
uriOptions uri =
mconcat
[ auth,
query,
port'
-- , fragment'
]
where
(auth, port') =
case URI.uriAuthority uri of
Left _ -> (mempty, mempty)
Right URI.Authority {..} ->
let auth0 = case authUserInfo of
Nothing -> mempty
Just URI.UserInfo {..} ->
let username = T.encodeUtf8 (URI.unRText uiUsername)
password = maybe "" (T.encodeUtf8 . URI.unRText) uiPassword
in basicAuthUnsafe username password
port0 = case authPort of
Nothing -> mempty
Just port'' -> port (fromIntegral port'')
in (auth0, port0)
query =
let liftQueryParam = \case
URI.QueryFlag t -> queryFlag (URI.unRText t)
URI.QueryParam k v -> URI.unRText k =: URI.unRText v
in mconcat (liftQueryParam <$> URI.uriQuery uri)
TODO Blocked on upstream : -client/issues/424
-- fragment' =
-- case URI.uriFragment uri of
Nothing - >
Just fragment '' - > fragment ( URI.unRText fragment '' )
instance RequestComponent (Url scheme) where
getRequestMod (Url scheme segments) = Endo $ \x ->
let (host :| path) = NE.reverse segments
in x
{ L.secure = case scheme of
Http -> False
Https -> True,
L.port = case scheme of
Http -> 80
Https -> 443,
L.host = Y.urlEncode False (T.encodeUtf8 host),
L.path =
(BL.toStrict . BB.toLazyByteString . Y.encodePathSegments) path
}
----------------------------------------------------------------------------
-- Request—Body
-- $body
--
-- A number of options for request bodies are available. The @Content-Type@
-- header is set for you automatically according to the body option you use
-- (it's always specified in the documentation for a given body option). To
-- add your own way to represent request body, define an instance of
-- 'HttpBody'.
-- | This data type represents empty body of an HTTP request. This is the
data type to use with ' HttpMethod 's that can not have a body , as it 's the
only type for which ' ProvidesBody ' returns ' NoBody ' .
--
-- Using of this body option does not set the @Content-Type@ header.
data NoReqBody = NoReqBody
instance HttpBody NoReqBody where
getRequestBody NoReqBody = L.RequestBodyBS B.empty
-- | This body option allows us to use a JSON object as the request
-- body—probably the most popular format right now. Just wrap a data type
that is an instance of ' ToJSON ' type class and you are done : it will be
-- converted to JSON and inserted as request body.
--
-- This body option sets the @Content-Type@ header to @\"application/json;
-- charset=utf-8\"@ value.
newtype ReqBodyJson a = ReqBodyJson a
instance (ToJSON a) => HttpBody (ReqBodyJson a) where
getRequestBody (ReqBodyJson a) = L.RequestBodyLBS (A.encode a)
getRequestContentType _ = pure "application/json; charset=utf-8"
-- | This body option streams request body from a file. It is expected that
-- the file size does not change during streaming.
--
-- Using of this body option does not set the @Content-Type@ header.
newtype ReqBodyFile = ReqBodyFile FilePath
instance HttpBody ReqBodyFile where
getRequestBody (ReqBodyFile path) =
LI.RequestBodyIO (L.streamFile path)
| HTTP request body represented by a strict ' ByteString ' .
--
-- Using of this body option does not set the @Content-Type@ header.
newtype ReqBodyBs = ReqBodyBs ByteString
instance HttpBody ReqBodyBs where
getRequestBody (ReqBodyBs bs) = L.RequestBodyBS bs
-- | HTTP request body represented by a lazy 'BL.ByteString'.
--
-- Using of this body option does not set the @Content-Type@ header.
newtype ReqBodyLbs = ReqBodyLbs BL.ByteString
instance HttpBody ReqBodyLbs where
getRequestBody (ReqBodyLbs bs) = L.RequestBodyLBS bs
-- | URL-encoded body. This can hold a collection of parameters which are
-- encoded similarly to query parameters at the end of query string, with
-- the only difference that they are stored in request body. The similarity
-- is reflected in the API as well, as you can use the same combinators you
would use to add query parameters : @('=:')@ and ' ' .
--
-- This body option sets the @Content-Type@ header to
-- @\"application/x-www-form-urlencoded\"@ value.
newtype ReqBodyUrlEnc = ReqBodyUrlEnc FormUrlEncodedParam
instance HttpBody ReqBodyUrlEnc where
getRequestBody (ReqBodyUrlEnc (FormUrlEncodedParam params)) =
(L.RequestBodyLBS . BB.toLazyByteString) (Y.renderQueryText False params)
getRequestContentType _ = pure "application/x-www-form-urlencoded"
-- | An opaque monoidal value that allows to collect URL-encoded parameters
-- to be wrapped in 'ReqBodyUrlEnc'.
newtype FormUrlEncodedParam = FormUrlEncodedParam [(Text, Maybe Text)]
deriving (Semigroup, Monoid)
instance QueryParam FormUrlEncodedParam where
queryParam name mvalue =
FormUrlEncodedParam [(name, toQueryParam <$> mvalue)]
queryParamToList (FormUrlEncodedParam p) = p
-- | Use 'formToQuery'.
--
@since 3.11.0
instance FromForm FormUrlEncodedParam where
fromForm = Right . formToQuery
-- | Multipart form data. Please consult the
" Network . HTTP.Client . MultipartFormData " module for how to construct
-- parts, then use 'reqBodyMultipart' to create actual request body from the
-- parts. 'reqBodyMultipart' is the only way to get a value of the type
-- 'ReqBodyMultipart', as its constructor is not exported on purpose.
--
-- @since 0.2.0
--
-- ==== __Examples__
--
> import Control . Monad . IO.Class
-- > import Data.Default.Class
> import Network . HTTP.Req
> import qualified Network . HTTP.Client . MultipartFormData as LM
-- >
-- > main :: IO ()
-- > main = runReq def $ do
-- > body <-
-- > reqBodyMultipart
> [ LM.partBS " title " " My Image "
> , LM.partFileSource " file1 " " /tmp / image.jpg "
-- > ]
-- > response <-
> req POST ( http " example.com " / : " post " )
-- > body
-- > bsResponse
>
-- > liftIO $ print (responseBody response)
data ReqBodyMultipart = ReqBodyMultipart ByteString LI.RequestBody
instance HttpBody ReqBodyMultipart where
getRequestBody (ReqBodyMultipart _ body) = body
getRequestContentType (ReqBodyMultipart boundary _) =
pure ("multipart/form-data; boundary=" <> boundary)
| Create ' ReqBodyMultipart ' request body from a collection of ' LM.Part 's .
--
-- @since 0.2.0
reqBodyMultipart :: (MonadIO m) => [LM.Part] -> m ReqBodyMultipart
reqBodyMultipart parts = liftIO $ do
boundary <- LM.webkitBoundary
body <- LM.renderParts boundary parts
return (ReqBodyMultipart boundary body)
-- | A type class for things that can be interpreted as an HTTP
-- 'L.RequestBody'.
class HttpBody body where
-- | How to get actual 'L.RequestBody'.
getRequestBody :: body -> L.RequestBody
-- | This method allows us to optionally specify the value of
-- @Content-Type@ header that should be used with particular body option.
-- By default it returns 'Nothing' and so @Content-Type@ is not set.
getRequestContentType :: body -> Maybe ByteString
getRequestContentType = const Nothing
| The type function recognizes ' NoReqBody ' as having ' NoBody ' , while any
-- other body option 'CanHaveBody'. This forces the user to use 'NoReqBody'
-- with 'GET' method and other methods that should not have body.
type family ProvidesBody body :: CanHaveBody where
ProvidesBody NoReqBody = 'NoBody
ProvidesBody body = 'CanHaveBody
-- | This type function allows any HTTP body if method says it
' CanHaveBody ' . When the method says it should have ' NoBody ' , the only
body option to use is ' NoReqBody ' .
type family
HttpBodyAllowed
(allowsBody :: CanHaveBody)
(providesBody :: CanHaveBody) ::
Constraint
where
HttpBodyAllowed 'NoBody 'NoBody = ()
HttpBodyAllowed 'CanHaveBody body = ()
HttpBodyAllowed 'NoBody 'CanHaveBody =
TypeError
('Text "This HTTP method does not allow attaching a request body.")
instance (HttpBody body) => RequestComponent (Tagged "body" body) where
getRequestMod (Tagged body) = Endo $ \x ->
x
{ L.requestBody = getRequestBody body,
L.requestHeaders =
let old = L.requestHeaders x
in case getRequestContentType body of
Nothing -> old
Just contentType ->
(Y.hContentType, contentType) : old
}
----------------------------------------------------------------------------
-- Request—Optional parameters
-- $optional-parameters
--
-- Optional parameters of request include things like query parameters,
-- headers, port number, etc. All optional parameters have the type
-- 'Option', which is a 'Monoid'. This means that you can use 'mempty' as
-- the last argument of 'req' to specify no optional parameters, or combine
-- 'Option's using 'mappend' or @('<>')@ to have several of them at once.
-- | The opaque 'Option' type is a 'Monoid' you can use to pack collection
-- of optional parameters like query parameters and headers. See sections
-- below to learn which 'Option' primitives are available.
data Option (scheme :: Scheme)
= Option (Endo (Y.QueryText, L.Request)) (Maybe (L.Request -> IO L.Request))
NOTE ' QueryText ' is just [ ( Text , Maybe Text ) ] , we keep it along with
-- Request to avoid appending to an existing query string in request every
time new parameter is added . The additional Maybe ( L.Request - > IO
L.Request ) is a finalizer that will be applied after all other
-- transformations. This is for authentication methods that sign requests
-- based on data in Request.
instance Semigroup (Option scheme) where
Option er0 mr0 <> Option er1 mr1 =
Option
(er0 <> er1)
(mr0 <|> mr1)
instance Monoid (Option scheme) where
mempty = Option mempty Nothing
mappend = (<>)
-- | Use 'formToQuery'.
--
@since 3.11.0
instance FromForm (Option scheme) where
fromForm = Right . formToQuery
-- | A helper to create an 'Option' that modifies only collection of query
-- parameters. This helper is not a part of the public API.
withQueryParams :: (Y.QueryText -> Y.QueryText) -> Option scheme
withQueryParams f = Option (Endo (first f)) Nothing
| A helper to create an ' Option ' that modifies only ' L.Request ' . This
-- helper is not a part of public API.
withRequest :: (L.Request -> L.Request) -> Option scheme
withRequest f = Option (Endo (second f)) Nothing
instance RequestComponent (Option scheme) where
getRequestMod (Option f _) = Endo $ \x ->
let (qparams, x') = appEndo f ([], x)
query = Y.renderQuery True (Y.queryTextToQuery qparams)
in x' {L.queryString = query}
| Finalize given ' L.Request ' by applying a finalizer from the given
-- 'Option' (if it has any).
finalizeRequest :: (MonadIO m) => Option scheme -> L.Request -> m L.Request
finalizeRequest (Option _ mfinalizer) = liftIO . fromMaybe pure mfinalizer
----------------------------------------------------------------------------
-- Request—Optional parameters—Query Parameters
-- $query-parameters
--
-- This section describes a polymorphic interface that can be used to
-- construct query parameters (of the type 'Option') and form URL-encoded
-- bodies (of the type 'FormUrlEncodedParam').
-- | This operator builds a query parameter that will be included in URL of
your request after the question sign @?@. This is the same syntax you use
-- with form URL encoded request bodies.
--
-- This operator is defined in terms of 'queryParam':
--
> name = : value = queryParam name ( pure value )
infix 7 =:
(=:) :: (QueryParam param, ToHttpApiData a) => Text -> a -> param
name =: value = queryParam name (pure value)
-- | Construct a flag, that is, a valueless query parameter. For example, in
the following URL @\"a\"@ is a flag , while is a query parameter
-- with a value:
--
-- >
--
-- This operator is defined in terms of 'queryParam':
--
> queryFlag name = queryParam name ( Nothing : : Maybe ( ) )
queryFlag :: (QueryParam param) => Text -> param
queryFlag name = queryParam name (Nothing :: Maybe ())
| Construct query parameters from a ' ToForm ' instance . This function
-- produces the same query params as 'Form.urlEncodeAsFormStable'.
--
-- Note that 'Form.Form' doesn't have the concept of parameters with the
-- empty value (i.e. what you can get by @key =: ""@). If the value is
-- empty, it will be encoded as a valueless parameter (i.e. what you can get
by @queryFlag key@ ) .
--
@since 3.11.0
formToQuery :: (QueryParam param, Monoid param, ToForm f) => f -> param
formToQuery f = mconcat . fmap toParam . Form.toListStable $ toForm f
where
toParam (key, val) =
queryParam key $
if val == ""
then Nothing
else Just val
-- | A type class for query-parameter-like things. The reason to have an
overloaded ' queryParam ' is to be able to use it as an ' Option ' and as a
-- 'FormUrlEncodedParam' when constructing form URL encoded request bodies.
-- Having the same syntax for these cases seems natural and user-friendly.
class QueryParam param where
-- | Create a query parameter with given name and value. If value is
-- 'Nothing', it won't be included at all (i.e. you create a flag this
way ) . It 's recommended to use @('=:')@ and ' ' instead of this
-- method, because they are easier to read.
queryParam :: (ToHttpApiData a) => Text -> Maybe a -> param
| Get the query parameter names and values set by ' queryParam ' .
--
@since 3.11.0
queryParamToList :: param -> [(Text, Maybe Text)]
instance QueryParam (Option scheme) where
queryParam name mvalue =
withQueryParams ((:) (name, toQueryParam <$> mvalue))
queryParamToList (Option f _) = fst $ appEndo f ([], L.defaultRequest)
----------------------------------------------------------------------------
-- Request—Optional parameters—Headers
-- | Create an 'Option' that adds a header. Note that if you 'mappend' two
-- headers with the same names the leftmost header will win. This means, in
-- particular, that you cannot create a request with several headers of the
-- same name.
header ::
-- | Header name
ByteString ->
-- | Header value
ByteString ->
Option scheme
header name value = withRequest (attachHeader name value)
| Attach a header with given name and content to a ' L.Request ' .
--
-- @since 1.1.0
attachHeader :: ByteString -> ByteString -> L.Request -> L.Request
attachHeader name value x =
x {L.requestHeaders = (CI.mk name, value) : L.requestHeaders x}
-- | Same as 'header', but with redacted values on print.
--
@since 3.13.0
headerRedacted :: ByteString -> ByteString -> Option scheme
headerRedacted name value = withRequest $ \x ->
let y = attachHeader name value x
in y {L.redactHeaders = CI.mk name `S.insert` L.redactHeaders y}
----------------------------------------------------------------------------
-- Request—Optional parameters—Cookies
-- $cookies
--
-- Support for cookies is quite minimalistic at the moment. It's possible to
-- specify which cookies to send using 'cookieJar' and inspect 'L.Response'
to extract ' ' from it ( see ' responseCookieJar ' ) .
| Use the given ' ' . A ' L.CookieJar ' can be obtained from a
-- 'L.Response' record.
cookieJar :: L.CookieJar -> Option scheme
cookieJar jar = withRequest $ \x ->
x {L.cookieJar = Just jar}
----------------------------------------------------------------------------
-- Request—Optional parameters—Authentication
-- $authentication
--
-- This section provides the common authentication helpers in the form of
-- 'Option's. You should always prefer the provided authentication 'Option's
-- to manual construction of headers because it ensures that you only use
one authentication method at a time ( they overwrite each other ) and
-- provides additional type safety that prevents leaking of credentials in
-- the cases when authentication relies on HTTPS for encrypting sensitive
-- data.
-- | The 'Option' adds basic authentication.
--
-- See also: <>.
basicAuth ::
-- | Username
ByteString ->
-- | Password
ByteString ->
-- | Auth 'Option'
Option 'Https
basicAuth = basicAuthUnsafe
-- | An alternative to 'basicAuth' which works for any scheme. Note that
using basic access authentication without SSL\/TLS is vulnerable to
-- attacks. Use 'basicAuth' instead unless you know what you are doing.
--
@since 0.3.1
basicAuthUnsafe ::
-- | Username
ByteString ->
-- | Password
ByteString ->
-- | Auth 'Option'
Option scheme
basicAuthUnsafe username password =
customAuth
(pure . L.applyBasicAuth username password)
-- | The 'Option' set basic proxy authentication header.
--
-- @since 1.1.0
basicProxyAuth ::
-- | Username
ByteString ->
-- | Password
ByteString ->
-- | Auth 'Option'
Option scheme
basicProxyAuth username password =
withRequest (L.applyBasicProxyAuth username password)
| The ' Option ' adds authentication .
--
-- @since 0.2.0
oAuth1 ::
-- | Consumer token
ByteString ->
-- | Consumer secret
ByteString ->
-- | OAuth token
ByteString ->
-- | OAuth token secret
ByteString ->
-- | Auth 'Option'
Option scheme
oAuth1 consumerToken consumerSecret token tokenSecret =
customAuth (OAuth.signOAuth app creds)
where
app =
OAuth.newOAuth
{ OAuth.oauthConsumerKey = consumerToken,
OAuth.oauthConsumerSecret = consumerSecret
}
creds = OAuth.newCredential token tokenSecret
-- | The 'Option' adds an OAuth2 bearer token. This is treated by many
-- services as the equivalent of a username and password.
--
-- The 'Option' is defined as:
--
> oAuth2Bearer token = header " Authorization " ( " Bearer " < > token )
--
-- See also: <>.
oAuth2Bearer ::
-- | Token
ByteString ->
-- | Auth 'Option'
Option 'Https
oAuth2Bearer token =
customAuth
(pure . attachHeader "Authorization" ("Bearer " <> token))
-- | The 'Option' adds a not-quite-standard OAuth2 bearer token (that seems
to be used only by GitHub ) . This will be treated by whatever services
-- accept it as the equivalent of a username and password.
--
-- The 'Option' is defined as:
--
-- > oAuth2Token token = header "Authorization" ("token" <> token)
--
-- See also: <#3-use-the-access-token-to-access-the-api>.
oAuth2Token ::
-- | Token
ByteString ->
-- | Auth 'Option'
Option 'Https
oAuth2Token token =
customAuth
(pure . attachHeader "Authorization" ("token " <> token))
-- | A helper to create custom authentication 'Option's. The given
-- 'IO'-enabled request transformation is applied after all other
-- modifications when constructing a request. Use wisely.
--
-- @since 1.1.0
customAuth :: (L.Request -> IO L.Request) -> Option scheme
customAuth = Option mempty . pure
----------------------------------------------------------------------------
-- Request—Optional parameters—Other
-- | Specify the port to connect to explicitly. Normally, 'Url' you use
-- determines the default port: @80@ for HTTP and @443@ for HTTPS. This
-- 'Option' allows us to choose an arbitrary port overwriting the defaults.
port :: Int -> Option scheme
port n = withRequest $ \x ->
x {L.port = n}
-- | This 'Option' controls whether gzipped data should be decompressed on
-- the fly. By default everything except for @\"application\/x-tar\"@ is
-- decompressed, i.e. we have:
--
-- > decompress (/= "application/x-tar")
--
-- You can also choose to decompress everything like this:
--
-- > decompress (const True)
decompress ::
-- | Predicate that is given MIME type, it returns 'True' when content
-- should be decompressed on the fly.
(ByteString -> Bool) ->
Option scheme
decompress f = withRequest $ \x ->
x {L.decompress = f}
-- | Specify the number of microseconds to wait for response. The default
value is 30 seconds ( defined in ' L.ManagerSettings ' of connection
-- 'L.Manager').
responseTimeout ::
-- | Number of microseconds to wait
Int ->
Option scheme
responseTimeout n = withRequest $ \x ->
x {L.responseTimeout = LI.ResponseTimeoutMicro n}
| HTTP version to send to the server , the default is HTTP 1.1 .
httpVersion ::
-- | Major version number
Int ->
-- | Minor version number
Int ->
Option scheme
httpVersion major minor = withRequest $ \x ->
x {L.requestVersion = Y.HttpVersion major minor}
----------------------------------------------------------------------------
-- Response interpretations
-- | Make a request and ignore the body of the response.
newtype IgnoreResponse = IgnoreResponse (L.Response ())
deriving (Show)
instance HttpResponse IgnoreResponse where
type HttpResponseBody IgnoreResponse = ()
toVanillaResponse (IgnoreResponse r) = r
getHttpResponse r = return $ IgnoreResponse (void r)
| Use this as the fourth argument of ' req ' to specify that you want it to
-- ignore the response body.
ignoreResponse :: Proxy IgnoreResponse
ignoreResponse = Proxy
-- | Make a request and interpret the body of the response as JSON. The
' handleHttpException ' method of ' MonadHttp ' instance corresponding to
-- monad in which you use 'req' will determine what to do in the case when
-- parsing fails (the 'JsonHttpException' constructor will be used).
newtype JsonResponse a = JsonResponse (L.Response a)
deriving (Show)
instance (FromJSON a) => HttpResponse (JsonResponse a) where
type HttpResponseBody (JsonResponse a) = a
toVanillaResponse (JsonResponse r) = r
getHttpResponse r = do
chunks <- L.brConsume (L.responseBody r)
case A.eitherDecode (BL.fromChunks chunks) of
Left e -> throwIO (JsonHttpException e)
Right x -> return $ JsonResponse (x <$ r)
acceptHeader Proxy = Just "application/json"
| Use this as the fourth argument of ' req ' to specify that you want it to
return the ' JsonResponse ' interpretation .
jsonResponse :: Proxy (JsonResponse a)
jsonResponse = Proxy
-- | Make a request and interpret the body of the response as a strict
' ByteString ' .
newtype BsResponse = BsResponse (L.Response ByteString)
deriving (Show)
instance HttpResponse BsResponse where
type HttpResponseBody BsResponse = ByteString
toVanillaResponse (BsResponse r) = r
getHttpResponse r = do
chunks <- L.brConsume (L.responseBody r)
return $ BsResponse (B.concat chunks <$ r)
| Use this as the fourth argument of ' req ' to specify that you want to
interpret the response body as a strict ' ByteString ' .
bsResponse :: Proxy BsResponse
bsResponse = Proxy
-- | Make a request and interpret the body of the response as a lazy
-- 'BL.ByteString'.
newtype LbsResponse = LbsResponse (L.Response BL.ByteString)
deriving (Show)
instance HttpResponse LbsResponse where
type HttpResponseBody LbsResponse = BL.ByteString
toVanillaResponse (LbsResponse r) = r
getHttpResponse r = do
chunks <- L.brConsume (L.responseBody r)
return $ LbsResponse (BL.fromChunks chunks <$ r)
| Use this as the fourth argument of ' req ' to specify that you want to
-- interpret the response body as a lazy 'BL.ByteString'.
lbsResponse :: Proxy LbsResponse
lbsResponse = Proxy
----------------------------------------------------------------------------
-- Helpers for response interpretations
-- | Fetch beginning of the response and return it together with a new
@'L.Response ' ' L.BodyReader'@ that can be passed to ' ' and
-- such.
grabPreview ::
-- | How many bytes to fetch
Int ->
-- | Response with body reader inside
L.Response L.BodyReader ->
-- | Preview 'ByteString' and new response with body reader inside
IO (ByteString, L.Response L.BodyReader)
grabPreview nbytes r = do
let br = L.responseBody r
(target, leftover, done) <- brReadN br nbytes
nref <- newIORef (0 :: Int)
let br' = do
n <- readIORef nref
let incn = modifyIORef' nref (+ 1)
case n of
0 -> do
incn
if B.null target
then br'
else return target
1 -> do
incn
if B.null leftover
then br'
else return leftover
_ ->
if done
then return B.empty
else br
return (target, r {L.responseBody = br'})
-- | Consume N bytes from 'L.BodyReader', return the target chunk, the
-- leftover (may be empty), and whether we're done consuming the body.
brReadN ::
-- | Body reader to stream from
L.BodyReader ->
-- | How many bytes to consume
Int ->
-- | Target chunk, the leftover, whether we're done
IO (ByteString, ByteString, Bool)
brReadN br n = go 0 id id
where
go !tlen t l = do
chunk <- br
if B.null chunk
then return (r t, r l, True)
else do
let (target, leftover) = B.splitAt (n - tlen) chunk
tlen' = B.length target
t' = t . (target :)
l' = l . (leftover :)
if tlen + tlen' < n
then go (tlen + tlen') t' l'
else return (r t', r l', False)
r f = B.concat (f [])
----------------------------------------------------------------------------
-- Inspecting a response
-- | Get the response body.
responseBody ::
(HttpResponse response) =>
response ->
HttpResponseBody response
responseBody = L.responseBody . toVanillaResponse
-- | Get the response status code.
responseStatusCode ::
(HttpResponse response) =>
response ->
Int
responseStatusCode =
Y.statusCode . L.responseStatus . toVanillaResponse
-- | Get the response status message.
responseStatusMessage ::
(HttpResponse response) =>
response ->
ByteString
responseStatusMessage =
Y.statusMessage . L.responseStatus . toVanillaResponse
-- | Lookup a particular header from a response.
responseHeader ::
(HttpResponse response) =>
-- | Response interpretation
response ->
-- | Header to lookup
ByteString ->
-- | Header value if found
Maybe ByteString
responseHeader r h =
(lookup (CI.mk h) . L.responseHeaders . toVanillaResponse) r
| Get the response ' ' .
responseCookieJar ::
(HttpResponse response) =>
response ->
L.CookieJar
responseCookieJar = L.responseCookieJar . toVanillaResponse
----------------------------------------------------------------------------
-- Response—Defining your own interpretation
-- $new-response-interpretation
--
-- To create a new response interpretation you just need to make your data
type an instance of the ' HttpResponse ' type class .
-- | A type class for response interpretations. It allows us to describe how
-- to consume the response from a @'L.Response' 'L.BodyReader'@ and produce
-- the final result that is to be returned to the user.
class HttpResponse response where
-- | The associated type is the type of body that can be extracted from an
instance of ' HttpResponse ' .
type HttpResponseBody response :: Type
-- | The method describes how to get the underlying 'L.Response' record.
toVanillaResponse :: response -> L.Response (HttpResponseBody response)
-- | This method describes how to consume response body and, more
generally , obtain @response@ value from @'L.Response ' ' L.BodyReader'@.
--
-- __Note__: 'L.BodyReader' is nothing but @'IO' 'ByteString'@. You should
call this action repeatedly until it yields the empty ' ByteString ' . In
-- that case streaming of response is finished (which apparently leads to
-- closing of the connection, so don't call the reader after it has
returned the empty ' ByteString ' once ) and you can concatenate the
-- chunks to obtain the final result. (Of course you could as well stream
-- the contents to a file or do whatever you want.)
--
-- __Note__: signature of this function was changed in the version
-- /1.0.0/.
getHttpResponse ::
-- | Response with body reader inside
L.Response L.BodyReader ->
-- | The final result
IO response
-- | The value of @\"Accept\"@ header. This is useful, for example, if a
-- website supports both @XML@ and @JSON@ responses, and decides what to
-- reply with based on what @Accept@ headers you have sent.
--
-- __Note__: manually specified 'Options' that set the @\"Accept\"@ header
-- will take precedence.
--
@since 2.1.0
acceptHeader :: Proxy response -> Maybe ByteString
acceptHeader Proxy = Nothing
-- | This instance has been added to make it easier to inspect 'L.Response'
using Req 's functions like ' responseStatusCode ' , ' responseStatusMessage ' ,
-- etc.
--
@since 3.12.0
instance HttpResponse (L.Response ()) where
type HttpResponseBody (L.Response ()) = ()
toVanillaResponse = id
getHttpResponse = return . void
----------------------------------------------------------------------------
-- Other
| The main class for things that are “ parts ” of ' L.Request ' in the sense
that if we have a ' L.Request ' , then we know how to apply an instance of
-- 'RequestComponent' changing\/overwriting something in it. 'Endo' is a
-- monoid of endomorphisms under composition, it's used to chain different
request components easier using @('<>')@.
--
-- __Note__: this type class is not a part of the public API.
class RequestComponent a where
| Get a function that takes a ' L.Request ' and changes it somehow
returning another ' L.Request ' . For example , the ' HttpMethod ' instance
-- of 'RequestComponent' just overwrites method. The function is wrapped
-- in 'Endo' so it's easier to chain such “modifying applications”
-- together building bigger and bigger 'RequestComponent's.
getRequestMod :: a -> Endo L.Request
-- | This wrapper is only used to attach a type-level tag to a given type.
-- This is necessary to define instances of 'RequestComponent' for any thing
that implements ' HttpMethod ' or ' HttpBody ' . Without the tag , GHC ca n't
-- see the difference between @'HttpMethod' method => 'RequestComponent'
method@ and ' body = > ' RequestComponent ' body@ when it decides
-- which instance to use (i.e. the constraints are taken into account later,
-- when instance is already chosen).
newtype Tagged (tag :: Symbol) a = Tagged a
-- | Exceptions that this library throws.
data HttpException
| A wrapper with an ' L.HttpException ' from " Network . HTTP.Client "
VanillaHttpException L.HttpException
| A wrapper with Aeson - produced ' String ' describing why decoding
-- failed
JsonHttpException String
deriving (Show, Typeable, Generic)
instance Exception HttpException
| Return ' Just ' if the given ' HttpException ' is wrapping a http - client 's
-- 'L.StatusCodeException'. Otherwise, return 'Nothing'.
--
@since 3.12.0
isStatusCodeException :: HttpException -> Maybe (L.Response ())
isStatusCodeException
( VanillaHttpException
( L.HttpExceptionRequest
_
(L.StatusCodeException r _)
)
) = Just r
isStatusCodeException _ = Nothing
| A simple type isomorphic to ' ' that we only have for better error
-- messages. We use it as a kind and its data constructors as type-level
-- tags.
--
See also : ' HttpMethod ' and ' HttpBody ' .
data CanHaveBody
= -- | Indeed can have a body
CanHaveBody
| -- | Should not have a body
NoBody
-- | A type-level tag that specifies URL scheme used (and thus if HTTPS is
enabled ) . This is used to force TLS requirement for some authentication
-- 'Option's.
data Scheme
= -- | HTTP
Http
| -- | HTTPS
Https
deriving (Eq, Ord, Show, Data, Typeable, Generic, TH.Lift)
| null | https://raw.githubusercontent.com/mrkkrp/req/4ec1f7bf87ce70ddb2f88126e9e817d3b05c994f/Network/HTTP/Req.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveLift #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
# LANGUAGE TemplateHaskellQuotes #
|
Stability : experimental
Portability : portable
The documentation below is structured in such a way that the most
requests, how to embed them in the monad you have, and then it gives you
details about less-common things you may want to know about. The
documentation is written with sufficient coverage of details and
examples, and it's designed to be a complete tutorial on its own.
=== About the library
Req is an HTTP client library that attempts to be easy-to-use, type-safe,
and expandable.
“Easy-to-use” means that the library is designed to be beginner-friendly
so it's simple to add to your monad stack, intuitive to work with,
well-documented, and does not get in your way. Doing HTTP requests is a
cannot currently modify 'L.ManagerSettings' of the default manager
because the library always uses the same implicit global manager for
simplicity and maximal connection sharing. There is a way to use your own
manager with different settings, but it requires more typing.
“Type-safe” means that the library tries to eliminate certain classes of
errors. For example, we have correct-by-construction URLs; it is
guaranteed that the user does not send the request body when using
methods like GET or OPTIONS, and the amount of implicit assumptions is
minimized by making the user specify their intentions in an explicit
form. For example, it's not possible to avoid specifying the body or the
method of a request. Authentication methods that assume HTTPS force the
user to use HTTPS at the type level.
“Expandable” refers to the ability to create new components without
having to resort to hacking. For example, it's possible to define your
own HTTP methods, create new ways to construct the body of a request,
create new authorization options, perform a request in a different way,
and create your own methods to parse a response.
=== Using with other libraries
time, but when you do, it's better to do a qualified import,
* For streaming of large request bodies see the companion package
@req-conduit@: <-conduit>.
=== Lightweight, no risk solution
The library uses the following mature packages under the hood to
guarantee you the best experience:
* <-client>—low level HTTP
* <-client-tls>—TLS (HTTPS)
It's important to note that since we leverage well-known libraries that
@wreq@. The only difference is the API.
* Making a request
$making-a-request
* Embedding requests in your monad
$embedding-requests
* Request
** Method
$method
** URL
$url
** Body
$body
** Optional parameters
$optional-parameters
*** Query parameters
$query-parameters
*** Headers
*** Cookies
$cookies
*** Authentication
$authentication
*** Other
* Response
** Response interpretations
** Inspecting a response
** Defining your own interpretation
$new-response-interpretation
* Other
--------------------------------------------------------------------------
Making a request
$making-a-request
specify required parameters and the final 'Option' argument is a
collection of optional parameters.
options@.
@method@ is an HTTP method such as 'GET' or 'POST'. The documentation has
a dedicated section about HTTP methods below.
@url@ is a 'Url' that describes location of resource you want to interact
with.
tutorial has a section about HTTP bodies, but usage is very
straightforward and should be clear from the examples.
@response@ is a type hint how to make and interpret response of an HTTP
request. Out-of-the-box it can be the following:
* 'ignoreResponse'
* 'jsonResponse'
* 'lbsResponse' (to get a lazy 'BL.ByteString')
Finally, @options@ is a 'Monoid' that holds a composite 'Option' for all
other optional settings like query parameters, headers, non-standard port
number, etc. There are quite a few things you can put there, see the
corresponding section in the documentation. If you don't need anything at
__Note__ that if you use 'req' to do all your requests, connection
sharing and reuse is done for you automatically.
See the examples below to get on the speed quickly.
==== __Examples__
try the examples:
> {-# LANGUAGE OverloadedStrings #-}
>
> module Main (main) where
>
> import Data.Aeson
> import Data.Maybe (fromJust)
> import Data.Text (Text)
We will be making requests against the <> service.
> main :: IO ()
> main = runReq defaultHttpConfig $ do
> let n :: Int
> liftIO $ B.putStrLn (responseBody bs)
The same, but now we use a query parameter named @\"seed\"@ to control
seed of the generator:
> main :: IO ()
> main = runReq defaultHttpConfig $ do
> let n, seed :: Int
> "seed" =: seed
> liftIO $ B.putStrLn (responseBody bs)
POST JSON data and get some info about the POST request:
> { size :: Int
> , color :: Text
> } deriving (Show, Generic)
>
>
> main :: IO ()
> main = runReq defaultHttpConfig $ do
> , color = "Green" }
> liftIO $ print (responseBody v :: Value)
Sending URL-encoded body:
> main :: IO ()
> main = runReq defaultHttpConfig $ do
> let params =
> "foo" =: ("bar" :: Text) <>
> queryFlag "baz"
> liftIO $ print (responseBody response :: Value)
Using various optional parameters and URL that is not known in advance:
> main :: IO ()
> main = runReq defaultHttpConfig $ do
> -- This is an example of what to do when URL is given dynamically. Of
> -- course in a real application you may not want to use 'fromJust'.
> let (url, options) = fromJust (useHttpsURI uri)
> basicAuth "username" "password" <>
> options <> -- contains the ?foo=bar part
here you can put any port of course
> liftIO $ print (responseBody response :: Value)
| HTTP method
| 'Url'—location of resource
| Body of the request
| A hint how to interpret response
| Collection of optional parameters
| Response
| A version of 'req' that does not use one of the predefined instances of
'L.BodyReader'@ manually, in a custom way.
@since 1.0.0
| HTTP method
| 'Url'—location of resource
| Body of the request
| Collection of optional parameters
| How to consume response
| Result
otherwise performs the request identically.
| HTTP method
| 'Url'—location of resource
| Body of the request
| A hint how to interpret response
| Collection of optional parameters
| Callback to modify the request
| Response
| The default handler function that the higher-level request functions
pass to 'req''. Internal function.
| How to get final result from a 'L.Response'
| 'L.Manager' to use
| Mostly like 'req' with respect to its arguments, but accepts a callback
that allows to perform a request in arbitrary fashion.
This function /does not/ perform handling\/wrapping exceptions, checking
response (with 'httpConfigCheckResponse'), and retrying. It only prepares
@since 0.3.0
| HTTP method
| 'Url'—location of resource
| Body of the request
| Collection of optional parameters
| How to perform request
| Result
“overwrite” headers when we construct a request by cons-ing.
NOTE The order of 'mappend's matters, here method is overwritten
first and 'options' take effect last. In particular, this means
that 'options' can overwrite things set by other request
components, which is useful for setting port number,
| Perform an action using the global implicit 'L.Manager' that the rest
of the library uses. This allows to reuse connections that the
'L.Manager' controls.
| The global 'L.Manager' that 'req' uses. Here we just go with the
default settings, so users don't need to deal with this manager stuff at
default settings via 'getHttpConfig'.
A note about safety, in case 'unsafePerformIO' looks suspicious to you.
The value of 'globalManager' is named and lives on top level. This means
manager. From that moment on the 'IORef' will be just reused—exactly the
spoil the plan by inlining the definition, hence the @NOINLINE@ pragma.
--------------------------------------------------------------------------
Embedding requests in your monad
$embedding-requests
To use 'req' in your monad, all you need to do is to make the monad an
When writing a library, keep your API polymorphic in terms of
follows this strategy is provided out-of-the-box (see below).
| A type class for monads that support performing HTTP requests.
Typically, you only need to define the 'handleHttpException' method
exceptions, but if you prefer working with something like
Default implementation returns its 'def' value, which is described in
the documentation for the type. Common usage pattern with manually
defined 'getHttpConfig' is to return some hard-coded value, or a value
approach to configuration is desirable.
| Proxy to use. By default values of @HTTP_PROXY@ and @HTTPS_PROXY@
environment variables are respected, this setting overwrites them.
Default value: 'Nothing'.
| How many redirects to follow when getting a resource. Default
| Alternative 'L.Manager' to use. 'Nothing' (default value) means
that the default implicit manager will be used (that's what you want
| Function to check the response immediately after receiving the
bytes). This is used for throwing exceptions on non-success status
codes by default (set to @\\_ _ _ -> Nothing@ if this behavior is not
desirable).
When the value this function returns is 'Nothing', nothing will
happen. When it there is 'L.HttpExceptionContent' inside 'Just', it
will be thrown.
Throwing is better then just returning a request with non-2xx status
code because in that case something is wrong and we need a way to
request timeouts and such, so when your request fails, it's certainly
something exceptional). The thrown exception is caught by the library
though and is available in 'handleHttpException'.
__Note__: signature of this function was changed in the version
/1.0.0/.
@since 0.3.0
| The retry policy to use for request retrying. By default 'def' is
used (see 'RetryPolicyM').
__Note__: signature of this function was changed to disallow 'IO' in
version /1.0.0/ and then changed back to its current form in /3.1.0/.
@since 0.3.0
| The function is used to decide whether to retry a request. 'True'
means that the request should be retried.
__Note__: signature of this function was changed in the version
/1.0.0/.
@since 0.3.0
| Similar to 'httpConfigRetryJudge', but is used to decide when to
retry requests that resulted in an exception. By default it retries
on response timeout and connection timeout (changed in version
/3.8.0/).
@since 2.0.0
Request timeout
A timeout occurred
(Informal convention) Network read timeout error
(Informal convention) Network connect timeout error
| A monad that allows us to run 'req' in any 'IO'-enabled monad without
having to define new instances.
| Computation to run
--------------------------------------------------------------------------
Request—Method
$method
The package supports all methods as defined by RFC 2616, and 'PATCH'
APIs. In some cases, however, you may want to add more methods (e.g. you
| 'GET' method.
| 'POST' method.
| 'HEAD' method.
| 'PUT' method.
| 'DELETE' method. RFC 7231 allows a payload in DELETE but without
semantics.
__Note__: before version /3.4.0/ this method did not allow request
bodies.
| 'TRACE' method.
| 'CONNECT' method.
| 'OPTIONS' method.
| 'PATCH' method.
| A type class for types that can be used as an HTTP method. To define a
non-standard method, follow this example that defines @COPY@:
>
> httpMethodName Proxy = "COPY"
tells the rest of the library whether the method can have body or not.
We use the special type 'CanHaveBody' lifted to the kind level instead
| Return name of the method as a 'ByteString'.
--------------------------------------------------------------------------
Request—URL
$url
We use 'Url's which are correct by construction, see 'Url'. To build a
'Url' from a 'URI', use 'useHttpURI', 'useHttpsURI', or generic 'useURI'.
| Request's 'Url'. Start constructing your 'Url' with 'http' or 'https'
This approach makes working with dynamic path segments easy and safe. See
examples below how to represent various 'Url's (make sure the
==== __Examples__
> http "httpbin.org"
> --
> https "httpbin.org"
> --
> --
> https "httpbin.org" /: "foo" /: "bar/baz"
> --
> --
> https "юникод.рф"
> --
the derived lift forgets the type of the scheme.
| Given host name, produce a 'Url' which has “http” as its scheme and
empty path. This also sets port to @80@.
| Given host name, produce a 'Url' which has “https” as its scheme and
empty path. This also sets port to @443@.
| Grow a given 'Url' appending a single path segment to it. Note that the
path segment can be of any type that is an instance of 'ToHttpApiData'.
when next URL piece is a 'Data.Text.Text' literal.
| Render a 'Url' as 'Text'.
| The 'useHttpURI' function provides an alternative method to get 'Url'
(possibly with some 'Option's) from a 'URI'. This is useful when you are
given a URL to query dynamically and don't know it beforehand.
This function expects the scheme to be “http” and host to be present.
@since 3.0.0
| Just like 'useHttpURI', but expects the “https” scheme.
@since 3.0.0
| Convert URI path to a 'Url'. Internal.
@since 3.9.0
| A combination of 'useHttpURI' and 'useHttpsURI' for cases when scheme
is not known in advance.
@since 3.0.0
| An internal helper function to extract host from a 'URI'.
| A quasiquoter to build an 'Url' and 'Option' tuple. The type of the
@since 3.2.0
| An internal helper function to extract 'Option's from a 'URI'.
, fragment'
fragment' =
case URI.uriFragment uri of
--------------------------------------------------------------------------
Request—Body
$body
A number of options for request bodies are available. The @Content-Type@
header is set for you automatically according to the body option you use
(it's always specified in the documentation for a given body option). To
add your own way to represent request body, define an instance of
'HttpBody'.
| This data type represents empty body of an HTTP request. This is the
Using of this body option does not set the @Content-Type@ header.
| This body option allows us to use a JSON object as the request
body—probably the most popular format right now. Just wrap a data type
converted to JSON and inserted as request body.
This body option sets the @Content-Type@ header to @\"application/json;
charset=utf-8\"@ value.
| This body option streams request body from a file. It is expected that
the file size does not change during streaming.
Using of this body option does not set the @Content-Type@ header.
Using of this body option does not set the @Content-Type@ header.
| HTTP request body represented by a lazy 'BL.ByteString'.
Using of this body option does not set the @Content-Type@ header.
| URL-encoded body. This can hold a collection of parameters which are
encoded similarly to query parameters at the end of query string, with
the only difference that they are stored in request body. The similarity
is reflected in the API as well, as you can use the same combinators you
This body option sets the @Content-Type@ header to
@\"application/x-www-form-urlencoded\"@ value.
| An opaque monoidal value that allows to collect URL-encoded parameters
to be wrapped in 'ReqBodyUrlEnc'.
| Use 'formToQuery'.
| Multipart form data. Please consult the
parts, then use 'reqBodyMultipart' to create actual request body from the
parts. 'reqBodyMultipart' is the only way to get a value of the type
'ReqBodyMultipart', as its constructor is not exported on purpose.
@since 0.2.0
==== __Examples__
> import Data.Default.Class
>
> main :: IO ()
> main = runReq def $ do
> body <-
> reqBodyMultipart
> ]
> response <-
> body
> bsResponse
> liftIO $ print (responseBody response)
@since 0.2.0
| A type class for things that can be interpreted as an HTTP
'L.RequestBody'.
| How to get actual 'L.RequestBody'.
| This method allows us to optionally specify the value of
@Content-Type@ header that should be used with particular body option.
By default it returns 'Nothing' and so @Content-Type@ is not set.
other body option 'CanHaveBody'. This forces the user to use 'NoReqBody'
with 'GET' method and other methods that should not have body.
| This type function allows any HTTP body if method says it
--------------------------------------------------------------------------
Request—Optional parameters
$optional-parameters
Optional parameters of request include things like query parameters,
headers, port number, etc. All optional parameters have the type
'Option', which is a 'Monoid'. This means that you can use 'mempty' as
the last argument of 'req' to specify no optional parameters, or combine
'Option's using 'mappend' or @('<>')@ to have several of them at once.
| The opaque 'Option' type is a 'Monoid' you can use to pack collection
of optional parameters like query parameters and headers. See sections
below to learn which 'Option' primitives are available.
Request to avoid appending to an existing query string in request every
transformations. This is for authentication methods that sign requests
based on data in Request.
| Use 'formToQuery'.
| A helper to create an 'Option' that modifies only collection of query
parameters. This helper is not a part of the public API.
helper is not a part of public API.
'Option' (if it has any).
--------------------------------------------------------------------------
Request—Optional parameters—Query Parameters
$query-parameters
This section describes a polymorphic interface that can be used to
construct query parameters (of the type 'Option') and form URL-encoded
bodies (of the type 'FormUrlEncodedParam').
| This operator builds a query parameter that will be included in URL of
with form URL encoded request bodies.
This operator is defined in terms of 'queryParam':
| Construct a flag, that is, a valueless query parameter. For example, in
with a value:
>
This operator is defined in terms of 'queryParam':
produces the same query params as 'Form.urlEncodeAsFormStable'.
Note that 'Form.Form' doesn't have the concept of parameters with the
empty value (i.e. what you can get by @key =: ""@). If the value is
empty, it will be encoded as a valueless parameter (i.e. what you can get
| A type class for query-parameter-like things. The reason to have an
'FormUrlEncodedParam' when constructing form URL encoded request bodies.
Having the same syntax for these cases seems natural and user-friendly.
| Create a query parameter with given name and value. If value is
'Nothing', it won't be included at all (i.e. you create a flag this
method, because they are easier to read.
--------------------------------------------------------------------------
Request—Optional parameters—Headers
| Create an 'Option' that adds a header. Note that if you 'mappend' two
headers with the same names the leftmost header will win. This means, in
particular, that you cannot create a request with several headers of the
same name.
| Header name
| Header value
@since 1.1.0
| Same as 'header', but with redacted values on print.
--------------------------------------------------------------------------
Request—Optional parameters—Cookies
$cookies
Support for cookies is quite minimalistic at the moment. It's possible to
specify which cookies to send using 'cookieJar' and inspect 'L.Response'
'L.Response' record.
--------------------------------------------------------------------------
Request—Optional parameters—Authentication
$authentication
This section provides the common authentication helpers in the form of
'Option's. You should always prefer the provided authentication 'Option's
to manual construction of headers because it ensures that you only use
provides additional type safety that prevents leaking of credentials in
the cases when authentication relies on HTTPS for encrypting sensitive
data.
| The 'Option' adds basic authentication.
See also: <>.
| Username
| Password
| Auth 'Option'
| An alternative to 'basicAuth' which works for any scheme. Note that
attacks. Use 'basicAuth' instead unless you know what you are doing.
| Username
| Password
| Auth 'Option'
| The 'Option' set basic proxy authentication header.
@since 1.1.0
| Username
| Password
| Auth 'Option'
@since 0.2.0
| Consumer token
| Consumer secret
| OAuth token
| OAuth token secret
| Auth 'Option'
| The 'Option' adds an OAuth2 bearer token. This is treated by many
services as the equivalent of a username and password.
The 'Option' is defined as:
See also: <>.
| Token
| Auth 'Option'
| The 'Option' adds a not-quite-standard OAuth2 bearer token (that seems
accept it as the equivalent of a username and password.
The 'Option' is defined as:
> oAuth2Token token = header "Authorization" ("token" <> token)
See also: <#3-use-the-access-token-to-access-the-api>.
| Token
| Auth 'Option'
| A helper to create custom authentication 'Option's. The given
'IO'-enabled request transformation is applied after all other
modifications when constructing a request. Use wisely.
@since 1.1.0
--------------------------------------------------------------------------
Request—Optional parameters—Other
| Specify the port to connect to explicitly. Normally, 'Url' you use
determines the default port: @80@ for HTTP and @443@ for HTTPS. This
'Option' allows us to choose an arbitrary port overwriting the defaults.
| This 'Option' controls whether gzipped data should be decompressed on
the fly. By default everything except for @\"application\/x-tar\"@ is
decompressed, i.e. we have:
> decompress (/= "application/x-tar")
You can also choose to decompress everything like this:
> decompress (const True)
| Predicate that is given MIME type, it returns 'True' when content
should be decompressed on the fly.
| Specify the number of microseconds to wait for response. The default
'L.Manager').
| Number of microseconds to wait
| Major version number
| Minor version number
--------------------------------------------------------------------------
Response interpretations
| Make a request and ignore the body of the response.
ignore the response body.
| Make a request and interpret the body of the response as JSON. The
monad in which you use 'req' will determine what to do in the case when
parsing fails (the 'JsonHttpException' constructor will be used).
| Make a request and interpret the body of the response as a strict
| Make a request and interpret the body of the response as a lazy
'BL.ByteString'.
interpret the response body as a lazy 'BL.ByteString'.
--------------------------------------------------------------------------
Helpers for response interpretations
| Fetch beginning of the response and return it together with a new
such.
| How many bytes to fetch
| Response with body reader inside
| Preview 'ByteString' and new response with body reader inside
| Consume N bytes from 'L.BodyReader', return the target chunk, the
leftover (may be empty), and whether we're done consuming the body.
| Body reader to stream from
| How many bytes to consume
| Target chunk, the leftover, whether we're done
--------------------------------------------------------------------------
Inspecting a response
| Get the response body.
| Get the response status code.
| Get the response status message.
| Lookup a particular header from a response.
| Response interpretation
| Header to lookup
| Header value if found
--------------------------------------------------------------------------
Response—Defining your own interpretation
$new-response-interpretation
To create a new response interpretation you just need to make your data
| A type class for response interpretations. It allows us to describe how
to consume the response from a @'L.Response' 'L.BodyReader'@ and produce
the final result that is to be returned to the user.
| The associated type is the type of body that can be extracted from an
| The method describes how to get the underlying 'L.Response' record.
| This method describes how to consume response body and, more
__Note__: 'L.BodyReader' is nothing but @'IO' 'ByteString'@. You should
that case streaming of response is finished (which apparently leads to
closing of the connection, so don't call the reader after it has
chunks to obtain the final result. (Of course you could as well stream
the contents to a file or do whatever you want.)
__Note__: signature of this function was changed in the version
/1.0.0/.
| Response with body reader inside
| The final result
| The value of @\"Accept\"@ header. This is useful, for example, if a
website supports both @XML@ and @JSON@ responses, and decides what to
reply with based on what @Accept@ headers you have sent.
__Note__: manually specified 'Options' that set the @\"Accept\"@ header
will take precedence.
| This instance has been added to make it easier to inspect 'L.Response'
etc.
--------------------------------------------------------------------------
Other
'RequestComponent' changing\/overwriting something in it. 'Endo' is a
monoid of endomorphisms under composition, it's used to chain different
__Note__: this type class is not a part of the public API.
of 'RequestComponent' just overwrites method. The function is wrapped
in 'Endo' so it's easier to chain such “modifying applications”
together building bigger and bigger 'RequestComponent's.
| This wrapper is only used to attach a type-level tag to a given type.
This is necessary to define instances of 'RequestComponent' for any thing
see the difference between @'HttpMethod' method => 'RequestComponent'
which instance to use (i.e. the constraints are taken into account later,
when instance is already chosen).
| Exceptions that this library throws.
failed
'L.StatusCodeException'. Otherwise, return 'Nothing'.
messages. We use it as a kind and its data constructors as type-level
tags.
| Indeed can have a body
| Should not have a body
| A type-level tag that specifies URL scheme used (and thus if HTTPS is
'Option's.
| HTTP
| HTTPS | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuasiQuotes #
# LANGUAGE RecordWildCards #
# LANGUAGE RoleAnnotations #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
Module : Network . HTTP.Req
Copyright : © 2016 – present
License : BSD 3 clause
Maintainer : < >
important information is presented first : you learn how to do HTTP
common task and a library for this should be approachable and
clear to beginners , thus certain compromises were made . For example , one
* You wo n't need the low - level interface of @http - client@ most of the
because @http - client@ has naming conflicts with @req@.
client used everywhere in Haskell .
support for @http - client@.
the whole Haskell ecosystem uses , there is no risk in using @req@. The
machinery for performing requests is the same as with @http - conduit@ and
module Network.HTTP.Req
req,
reqBr,
reqCb,
req',
withReqManager,
MonadHttp (..),
HttpConfig (..),
defaultHttpConfig,
Req,
runReq,
GET (..),
POST (..),
HEAD (..),
PUT (..),
DELETE (..),
TRACE (..),
CONNECT (..),
OPTIONS (..),
PATCH (..),
HttpMethod (..),
Url,
http,
https,
(/~),
(/:),
useHttpURI,
useHttpsURI,
useURI,
urlQ,
renderUrl,
NoReqBody (..),
ReqBodyJson (..),
ReqBodyFile (..),
ReqBodyBs (..),
ReqBodyLbs (..),
ReqBodyUrlEnc (..),
FormUrlEncodedParam,
ReqBodyMultipart,
reqBodyMultipart,
HttpBody (..),
ProvidesBody,
HttpBodyAllowed,
Option,
(=:),
queryFlag,
formToQuery,
QueryParam (..),
header,
attachHeader,
headerRedacted,
cookieJar,
basicAuth,
basicAuthUnsafe,
basicProxyAuth,
oAuth1,
oAuth2Bearer,
oAuth2Token,
customAuth,
port,
decompress,
responseTimeout,
httpVersion,
IgnoreResponse,
ignoreResponse,
JsonResponse,
jsonResponse,
BsResponse,
bsResponse,
LbsResponse,
lbsResponse,
responseBody,
responseStatusCode,
responseStatusMessage,
responseHeader,
responseCookieJar,
HttpResponse (..),
HttpException (..),
isStatusCodeException,
CanHaveBody (..),
Scheme (..),
)
where
import qualified Blaze.ByteString.Builder as BB
import Control.Applicative
import Control.Arrow (first, second)
import Control.Exception hiding (Handler (..), TypeError)
import Control.Monad (guard, void, (>=>))
import Control.Monad.Base
import Control.Monad.Catch (Handler (..), MonadCatch, MonadMask, MonadThrow)
import Control.Monad.IO.Class
import Control.Monad.IO.Unlift
import Control.Monad.Reader (ReaderT (ReaderT), ask, lift, runReaderT)
import Control.Monad.Trans.Accum (AccumT)
import Control.Monad.Trans.Cont (ContT)
import Control.Monad.Trans.Control
import Control.Monad.Trans.Except (ExceptT)
import Control.Monad.Trans.Identity (IdentityT)
import Control.Monad.Trans.Maybe (MaybeT)
import qualified Control.Monad.Trans.RWS.CPS as RWS.CPS
import qualified Control.Monad.Trans.RWS.Lazy as RWS.Lazy
import qualified Control.Monad.Trans.RWS.Strict as RWS.Strict
import Control.Monad.Trans.Select (SelectT)
import qualified Control.Monad.Trans.State.Lazy as State.Lazy
import qualified Control.Monad.Trans.State.Strict as State.Strict
import qualified Control.Monad.Trans.Writer.CPS as Writer.CPS
import qualified Control.Monad.Trans.Writer.Lazy as Writer.Lazy
import qualified Control.Monad.Trans.Writer.Strict as Writer.Strict
import Control.Retry
import Data.Aeson (FromJSON (..), ToJSON (..))
import qualified Data.Aeson as A
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.CaseInsensitive as CI
import Data.Data (Data)
import Data.Function (on)
import Data.IORef
import Data.Kind (Constraint, Type)
import Data.List (foldl', nubBy)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
import Data.Maybe (fromMaybe)
import Data.Proxy
import Data.Semigroup (Endo (..))
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Typeable (Typeable, cast)
import GHC.Generics
import GHC.TypeLits
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Quote as TH
import qualified Language.Haskell.TH.Syntax as TH
import qualified Network.Connection as NC
import qualified Network.HTTP.Client as L
import qualified Network.HTTP.Client.Internal as LI
import qualified Network.HTTP.Client.MultipartFormData as LM
import qualified Network.HTTP.Client.TLS as L
import qualified Network.HTTP.Types as Y
import System.IO.Unsafe (unsafePerformIO)
import Text.URI (URI)
import qualified Text.URI as URI
import qualified Text.URI.QQ as QQ
import qualified Web.Authenticate.OAuth as OAuth
import Web.FormUrlEncoded (FromForm (..), ToForm (..))
import qualified Web.FormUrlEncoded as Form
import Web.HttpApiData (ToHttpApiData (..))
To make an HTTP request you normally need only one function : ' req ' .
| Make an HTTP request . The function takes 5 arguments , 4 of which
Let 's go through all the arguments first : @req method url body response
@body@ is a body option such as ' NoReqBody ' or ' ReqBodyJson ' . The
* ' bsResponse ' ( to get a strict ' ByteString ' )
all , pass ' ' .
First , this is a piece of boilerplate that should be in place before you
> { - # LANGUAGE DeriveGeneric # - }
> import Control . Monad
> import Control . Monad . IO.Class
> import Data . Monoid ( ( < > ) )
> import
> import Network . HTTP.Req
> import qualified Data . ByteString . Char8 as B
> import qualified Text . URI as URI
Make a GET request , grab 5 random bytes :
> n = 5
> bs < - req GET ( https " httpbin.org " / : " bytes " /~ n ) NoReqBody bsResponse mempty
> n = 5
> seed = 100
> bs < - req GET ( https " httpbin.org " / : " bytes " /~ n ) NoReqBody bsResponse $
> data
> instance ToJSON MyData
> instance FromJSON MyData
> let
> { size = 6
> v < - req POST ( https " httpbin.org " / : " post " ) ( )
> response < - req POST ( https " httpbin.org " / : " post " ) ( ReqBodyUrlEnc params )
> uri < - URI.mkURI " "
> response < - req GET url NoReqBody jsonResponse $
> " from " = : ( 15 : : Int ) < >
> " to " = : ( 67 : : Int ) < >
req ::
( MonadHttp m,
HttpMethod method,
HttpBody body,
HttpResponse response,
HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
) =>
method ->
Url scheme ->
body ->
Proxy response ->
Option scheme ->
m response
req method url body responseProxy options =
reqCb method url body responseProxy options pure
' HttpResponse ' but instead allows the user to consume @'L.Response '
reqBr ::
( MonadHttp m,
HttpMethod method,
HttpBody body,
HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
) =>
method ->
Url scheme ->
body ->
Option scheme ->
(L.Response L.BodyReader -> IO a) ->
m a
reqBr method url body options consume =
req' method url body options (reqHandler consume)
| A version of ' req ' that takes a callback to modify the ' L.Request ' , but
@since 3.7.0
reqCb ::
( MonadHttp m,
HttpMethod method,
HttpBody body,
HttpResponse response,
HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
) =>
method ->
Url scheme ->
body ->
Proxy response ->
Option scheme ->
(L.Request -> m L.Request) ->
m response
reqCb method url body responseProxy options adjustRequest =
req' method url body (options <> extraOptions) $ \request manager -> do
request' <- adjustRequest request
reqHandler getHttpResponse request' manager
where
extraOptions =
case acceptHeader responseProxy of
Nothing -> mempty
Just accept -> header "Accept" accept
@since 3.7.0
reqHandler ::
(MonadHttp m) =>
(L.Response L.BodyReader -> IO b) ->
| ' L.Request ' to perform
L.Request ->
L.Manager ->
m b
reqHandler consume request manager = do
HttpConfig {..} <- getHttpConfig
let wrapVanilla = handle (throwIO . VanillaHttpException)
wrapExc = handle (throwIO . LI.toHttpException request)
withRRef =
bracket
(newIORef Nothing)
(readIORef >=> mapM_ L.responseClose)
(liftIO . try . wrapVanilla . wrapExc)
( withRRef $ \rref -> do
let openResponse = mask_ $ do
r <- readIORef rref
mapM_ L.responseClose r
r' <- L.responseOpen request manager
writeIORef rref (Just r')
return r'
exceptionRetryPolicies =
skipAsyncExceptions
++ [ \retryStatus -> Handler $ \e ->
return $ httpConfigRetryJudgeException retryStatus e
]
r <-
retrying
httpConfigRetryPolicy
(\retryStatus r -> return $ httpConfigRetryJudge retryStatus r)
( const
( recovering
httpConfigRetryPolicy
exceptionRetryPolicies
(const openResponse)
)
)
(preview, r') <- grabPreview httpConfigBodyPreviewLength r
mapM_ LI.throwHttp (httpConfigCheckResponse request r' preview)
consume r'
)
>>= either handleHttpException return
' L.Request ' and allows you to use it .
req' ::
forall m method body scheme a.
( MonadHttp m,
HttpMethod method,
HttpBody body,
HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
) =>
method ->
Url scheme ->
body ->
Option scheme ->
(L.Request -> L.Manager -> m a) ->
m a
req' method url body options m = do
config <- getHttpConfig
NOTE First appearance of any given header wins . This allows to
nubHeaders = Endo $ \x ->
x {L.requestHeaders = nubBy ((==) `on` fst) (L.requestHeaders x)}
request' =
flip appEndo L.defaultRequest $
" Content - Type " header , etc .
nubHeaders
<> getRequestMod options
<> getRequestMod config
<> getRequestMod (Tagged body :: Tagged "body" body)
<> getRequestMod url
<> getRequestMod (Tagged method :: Tagged "method" method)
request <- finalizeRequest options request'
withReqManager (m request)
withReqManager :: (MonadIO m) => (L.Manager -> m a) -> m a
withReqManager m = liftIO (readIORef globalManager) >>= m
all , but when we create a request , instance ' HttpConfig ' can affect the
it will be shared , i.e. computed only once on the first use of the
behavior we want here in order to maximize connection sharing . GHC could
globalManager :: IORef L.Manager
globalManager = unsafePerformIO $ do
context <- NC.initConnectionContext
let settings =
L.mkManagerSettingsContext
(Just context)
(NC.TLSSettingsSimple False False False)
Nothing
manager <- L.newManager settings
newIORef manager
# NOINLINE globalManager #
instance of the ' MonadHttp ' type class .
' ' , only define instance of ' ' in final application .
Another option is to use a @newtype@-wrapped monad stack and define
' ' for it . As of the version /0.4.0/ , the ' Req ' monad that
unless you want to tweak ' HttpConfig ' .
class (MonadIO m) => MonadHttp m where
| This method describes how to deal with ' HttpException ' that was
caught by the library . One option is to re - throw it if you are OK with
' Control . . Except . ' , this is the right place to pass it to
' Control . Monad . Except.throwError ' .
handleHttpException :: HttpException -> m a
| Return the ' HttpConfig ' to be used when performing HTTP requests .
extracted from ' Control . . Reader . MonadReader ' if a more flexible
getHttpConfig :: m HttpConfig
getHttpConfig = return defaultHttpConfig
| ' HttpConfig ' contains settings to be used when making HTTP requests .
data HttpConfig = HttpConfig
httpConfigProxy :: Maybe L.Proxy,
value : 10 .
httpConfigRedirectCount :: Int,
in 99 % of cases ) .
httpConfigAltManager :: Maybe L.Manager,
status and headers , before streaming of response body . The third
argument is the beginning of response body ( typically first 1024
short - cut execution ( also remember that Req retries automatically on
httpConfigCheckResponse ::
forall b.
L.Request ->
L.Response b ->
ByteString ->
Maybe L.HttpExceptionContent,
httpConfigRetryPolicy :: RetryPolicyM IO,
httpConfigRetryJudge :: forall b. RetryStatus -> L.Response b -> Bool,
@since 3.4.0
httpConfigRetryJudgeException :: RetryStatus -> SomeException -> Bool,
| length of preview fragment of response body .
@since 3.6.0
httpConfigBodyPreviewLength :: forall a. (Num a) => a
}
deriving (Typeable)
| The default value of ' HttpConfig ' .
defaultHttpConfig :: HttpConfig
defaultHttpConfig =
HttpConfig
{ httpConfigProxy = Nothing,
httpConfigRedirectCount = 10,
httpConfigAltManager = Nothing,
httpConfigCheckResponse = \_ response preview ->
let scode = statusCode response
in if 200 <= scode && scode < 300
then Nothing
else Just (L.StatusCodeException (void response) preview),
httpConfigRetryPolicy = retryPolicyDefault,
httpConfigRetryJudge = \_ response ->
statusCode response
Gateway timeout
],
httpConfigRetryJudgeException = \_ e ->
case fromException e of
Just (L.HttpExceptionRequest _ c) ->
case c of
L.ResponseTimeout -> True
L.ConnectionTimeout -> True
_ -> False
_ -> False,
httpConfigBodyPreviewLength = 1024
}
where
statusCode = Y.statusCode . L.responseStatus
instance RequestComponent HttpConfig where
getRequestMod HttpConfig {..} = Endo $ \x ->
x
{ L.proxy = httpConfigProxy,
L.redirectCount = httpConfigRedirectCount,
LI.requestManagerOverride = httpConfigAltManager
}
@since 0.4.0
newtype Req a = Req (ReaderT HttpConfig IO a)
deriving
( Functor,
Applicative,
Monad,
MonadIO,
MonadUnliftIO
)
| @since 3.7.0
deriving instance MonadThrow Req
| @since 3.7.0
deriving instance MonadCatch Req
| @since 3.7.0
deriving instance MonadMask Req
instance MonadBase IO Req where
liftBase = liftIO
instance MonadBaseControl IO Req where
type StM Req a = a
liftBaseWith f = Req . ReaderT $ \r -> f (runReq r)
# INLINEABLE liftBaseWith #
restoreM = Req . ReaderT . const . return
# INLINEABLE restoreM #
instance MonadHttp Req where
handleHttpException = Req . lift . throwIO
getHttpConfig = Req ask
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (AccumT w m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (ContT r m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (ExceptT e m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (IdentityT m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (MaybeT m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (ReaderT r m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (RWS.CPS.RWST r w s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (RWS.Lazy.RWST r w s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (RWS.Strict.RWST r w s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (SelectT r m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (State.Lazy.StateT s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m) => MonadHttp (State.Strict.StateT s m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (Writer.CPS.WriterT w m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (Writer.Lazy.WriterT w m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (Writer.Strict.WriterT w m) where
handleHttpException = lift . handleHttpException
getHttpConfig = lift getHttpConfig
| Run a computation in the ' Req ' monad with the given ' HttpConfig ' . In
the case of an exceptional situation an ' HttpException ' will be thrown .
@since 0.4.0
runReq ::
(MonadIO m) =>
| ' HttpConfig ' to use
HttpConfig ->
Req a ->
m a
runReq config (Req m) = liftIO (runReaderT m config)
which is defined by RFC 5789 — that should be enough to talk to RESTful
work with WebDAV < > ) ; no need to
compromise on type safety and hack , it only takes a couple of seconds to
define a new method that will works seamlessly , see ' HttpMethod ' .
data GET = GET
instance HttpMethod GET where
type AllowsBody GET = 'NoBody
httpMethodName Proxy = Y.methodGet
data POST = POST
instance HttpMethod POST where
type AllowsBody POST = 'CanHaveBody
httpMethodName Proxy = Y.methodPost
data HEAD = HEAD
instance HttpMethod HEAD where
type AllowsBody HEAD = 'NoBody
httpMethodName Proxy = Y.methodHead
data PUT = PUT
instance HttpMethod PUT where
type AllowsBody PUT = 'CanHaveBody
httpMethodName Proxy = Y.methodPut
data DELETE = DELETE
instance HttpMethod DELETE where
type AllowsBody DELETE = 'CanHaveBody
httpMethodName Proxy = Y.methodDelete
data TRACE = TRACE
instance HttpMethod TRACE where
type AllowsBody TRACE = 'CanHaveBody
httpMethodName Proxy = Y.methodTrace
data CONNECT = CONNECT
instance HttpMethod CONNECT where
type AllowsBody CONNECT = 'CanHaveBody
httpMethodName Proxy = Y.methodConnect
data OPTIONS = OPTIONS
instance HttpMethod OPTIONS where
type AllowsBody OPTIONS = 'NoBody
httpMethodName Proxy = Y.methodOptions
data PATCH = PATCH
instance HttpMethod PATCH where
type AllowsBody PATCH = 'CanHaveBody
httpMethodName Proxy = Y.methodPatch
> data COPY = COPY
> instance HttpMethod COPY where
> type AllowsBody COPY = ' CanHaveBody
class HttpMethod a where
| Type function ' AllowsBody ' returns a type of kind ' CanHaveBody ' which
of ' ' to get more user - friendly compiler messages .
type AllowsBody a :: CanHaveBody
httpMethodName :: Proxy a -> ByteString
instance (HttpMethod method) => RequestComponent (Tagged "method" method) where
getRequestMod _ = Endo $ \x ->
x {L.method = httpMethodName (Proxy :: Proxy method)}
specifying the scheme and host at the same time . Then use the @('/~')@
and @('/:')@ operators to grow the path one piece at a time . Every single
piece of path will be url(percent)-encoded , so using @('/~')@ and
@('/:')@ is the only way to have forward slashes between path segments .
language extension is enabled ) .
> https " httpbin.org " / : " encoding " / : " utf8 "
> https " httpbin.org " / : " bytes " /~ ( 10 : : Int )
data Url (scheme :: Scheme) = Url Scheme (NonEmpty Text)
NOTE The second value is the path segments in reversed order .
deriving (Eq, Ord, Show, Data, Typeable, Generic)
type role Url nominal
With template - haskell > = 2.15 and text > = 1.2.4 Lift can be derived , however
instance (Typeable scheme) => TH.Lift (Url scheme) where
lift url =
TH.dataToExpQ (fmap liftText . cast) url `TH.sigE` case url of
Url Http _ -> [t|Url 'Http|]
Url Https _ -> [t|Url 'Https|]
where
liftText t = TH.AppE (TH.VarE 'T.pack) <$> TH.lift (T.unpack t)
liftTyped = TH.Code . TH.unsafeTExpCoerce . TH.lift
http :: Text -> Url 'Http
http = Url Http . pure
https :: Text -> Url 'Https
https = Url Https . pure
infixl 5 /~
(/~) :: (ToHttpApiData a) => Url scheme -> a -> Url scheme
Url secure path /~ segment = Url secure (NE.cons (toUrlPiece segment) path)
| A type - constrained version of @('/~')@ to remove ambiguity in the cases
infixl 5 /:
(/:) :: Url scheme -> Text -> Url scheme
(/:) = (/~)
@since 3.4.0
renderUrl :: Url scheme -> Text
renderUrl = \case
Url Https parts ->
"https://" <> renderParts parts
Url Http parts ->
"http://" <> renderParts parts
where
renderParts parts =
T.intercalate "/" (reverse $ NE.toList parts)
useHttpURI :: URI -> Maybe (Url 'Http, Option scheme)
useHttpURI uri = do
guard (URI.uriScheme uri == Just [QQ.scheme|http|])
urlHead <- http <$> uriHost uri
let url = case URI.uriPath uri of
Nothing -> urlHead
Just uriPath -> uriPathToUrl uriPath urlHead
return (url, uriOptions uri)
useHttpsURI :: URI -> Maybe (Url 'Https, Option scheme)
useHttpsURI uri = do
guard (URI.uriScheme uri == Just [QQ.scheme|https|])
urlHead <- https <$> uriHost uri
let url = case URI.uriPath uri of
Nothing -> urlHead
Just uriPath -> uriPathToUrl uriPath urlHead
return (url, uriOptions uri)
uriPathToUrl ::
(Bool, NonEmpty (URI.RText 'URI.PathPiece)) ->
Url scheme ->
Url scheme
uriPathToUrl (trailingSlash, xs) urlHead =
if trailingSlash then path /: T.empty else path
where
path = foldl' (/:) urlHead (URI.unRText <$> NE.toList xs)
useURI ::
URI ->
Maybe
( Either
(Url 'Http, Option scheme0)
(Url 'Https, Option scheme1)
)
useURI uri =
(Left <$> useHttpURI uri) <|> (Right <$> useHttpsURI uri)
uriHost :: URI -> Maybe Text
uriHost uri = case URI.uriAuthority uri of
Left _ -> Nothing
Right URI.Authority {..} ->
Just (URI.unRText authHost)
generated expression is @('Url ' scheme0 , ' Option ' scheme1)@ with
@scheme0@ being either ' Http ' or ' Https ' depending on the input .
urlQ :: TH.QuasiQuoter
urlQ =
TH.QuasiQuoter
{ quoteExp = \str ->
case URI.mkURI (T.pack str) of
Left err -> fail (displayException err)
Right uri -> case useURI uri of
Nothing -> fail "Not a HTTP or HTTPS URL"
Just eurl ->
TH.tupE
[ either (TH.lift . fst) (TH.lift . fst) eurl,
[|uriOptions uri|]
],
quotePat = error "This usage is not supported",
quoteType = error "This usage is not supported",
quoteDec = error "This usage is not supported"
}
uriOptions :: forall scheme. URI -> Option scheme
uriOptions uri =
mconcat
[ auth,
query,
port'
]
where
(auth, port') =
case URI.uriAuthority uri of
Left _ -> (mempty, mempty)
Right URI.Authority {..} ->
let auth0 = case authUserInfo of
Nothing -> mempty
Just URI.UserInfo {..} ->
let username = T.encodeUtf8 (URI.unRText uiUsername)
password = maybe "" (T.encodeUtf8 . URI.unRText) uiPassword
in basicAuthUnsafe username password
port0 = case authPort of
Nothing -> mempty
Just port'' -> port (fromIntegral port'')
in (auth0, port0)
query =
let liftQueryParam = \case
URI.QueryFlag t -> queryFlag (URI.unRText t)
URI.QueryParam k v -> URI.unRText k =: URI.unRText v
in mconcat (liftQueryParam <$> URI.uriQuery uri)
TODO Blocked on upstream : -client/issues/424
Nothing - >
Just fragment '' - > fragment ( URI.unRText fragment '' )
instance RequestComponent (Url scheme) where
getRequestMod (Url scheme segments) = Endo $ \x ->
let (host :| path) = NE.reverse segments
in x
{ L.secure = case scheme of
Http -> False
Https -> True,
L.port = case scheme of
Http -> 80
Https -> 443,
L.host = Y.urlEncode False (T.encodeUtf8 host),
L.path =
(BL.toStrict . BB.toLazyByteString . Y.encodePathSegments) path
}
data type to use with ' HttpMethod 's that can not have a body , as it 's the
only type for which ' ProvidesBody ' returns ' NoBody ' .
data NoReqBody = NoReqBody
instance HttpBody NoReqBody where
getRequestBody NoReqBody = L.RequestBodyBS B.empty
that is an instance of ' ToJSON ' type class and you are done : it will be
newtype ReqBodyJson a = ReqBodyJson a
instance (ToJSON a) => HttpBody (ReqBodyJson a) where
getRequestBody (ReqBodyJson a) = L.RequestBodyLBS (A.encode a)
getRequestContentType _ = pure "application/json; charset=utf-8"
newtype ReqBodyFile = ReqBodyFile FilePath
instance HttpBody ReqBodyFile where
getRequestBody (ReqBodyFile path) =
LI.RequestBodyIO (L.streamFile path)
| HTTP request body represented by a strict ' ByteString ' .
newtype ReqBodyBs = ReqBodyBs ByteString
instance HttpBody ReqBodyBs where
getRequestBody (ReqBodyBs bs) = L.RequestBodyBS bs
newtype ReqBodyLbs = ReqBodyLbs BL.ByteString
instance HttpBody ReqBodyLbs where
getRequestBody (ReqBodyLbs bs) = L.RequestBodyLBS bs
would use to add query parameters : @('=:')@ and ' ' .
newtype ReqBodyUrlEnc = ReqBodyUrlEnc FormUrlEncodedParam
instance HttpBody ReqBodyUrlEnc where
getRequestBody (ReqBodyUrlEnc (FormUrlEncodedParam params)) =
(L.RequestBodyLBS . BB.toLazyByteString) (Y.renderQueryText False params)
getRequestContentType _ = pure "application/x-www-form-urlencoded"
newtype FormUrlEncodedParam = FormUrlEncodedParam [(Text, Maybe Text)]
deriving (Semigroup, Monoid)
instance QueryParam FormUrlEncodedParam where
queryParam name mvalue =
FormUrlEncodedParam [(name, toQueryParam <$> mvalue)]
queryParamToList (FormUrlEncodedParam p) = p
@since 3.11.0
instance FromForm FormUrlEncodedParam where
fromForm = Right . formToQuery
" Network . HTTP.Client . MultipartFormData " module for how to construct
> import Control . Monad . IO.Class
> import Network . HTTP.Req
> import qualified Network . HTTP.Client . MultipartFormData as LM
> [ LM.partBS " title " " My Image "
> , LM.partFileSource " file1 " " /tmp / image.jpg "
> req POST ( http " example.com " / : " post " )
>
data ReqBodyMultipart = ReqBodyMultipart ByteString LI.RequestBody
instance HttpBody ReqBodyMultipart where
getRequestBody (ReqBodyMultipart _ body) = body
getRequestContentType (ReqBodyMultipart boundary _) =
pure ("multipart/form-data; boundary=" <> boundary)
| Create ' ReqBodyMultipart ' request body from a collection of ' LM.Part 's .
reqBodyMultipart :: (MonadIO m) => [LM.Part] -> m ReqBodyMultipart
reqBodyMultipart parts = liftIO $ do
boundary <- LM.webkitBoundary
body <- LM.renderParts boundary parts
return (ReqBodyMultipart boundary body)
class HttpBody body where
getRequestBody :: body -> L.RequestBody
getRequestContentType :: body -> Maybe ByteString
getRequestContentType = const Nothing
| The type function recognizes ' NoReqBody ' as having ' NoBody ' , while any
type family ProvidesBody body :: CanHaveBody where
ProvidesBody NoReqBody = 'NoBody
ProvidesBody body = 'CanHaveBody
' CanHaveBody ' . When the method says it should have ' NoBody ' , the only
body option to use is ' NoReqBody ' .
type family
HttpBodyAllowed
(allowsBody :: CanHaveBody)
(providesBody :: CanHaveBody) ::
Constraint
where
HttpBodyAllowed 'NoBody 'NoBody = ()
HttpBodyAllowed 'CanHaveBody body = ()
HttpBodyAllowed 'NoBody 'CanHaveBody =
TypeError
('Text "This HTTP method does not allow attaching a request body.")
instance (HttpBody body) => RequestComponent (Tagged "body" body) where
getRequestMod (Tagged body) = Endo $ \x ->
x
{ L.requestBody = getRequestBody body,
L.requestHeaders =
let old = L.requestHeaders x
in case getRequestContentType body of
Nothing -> old
Just contentType ->
(Y.hContentType, contentType) : old
}
data Option (scheme :: Scheme)
= Option (Endo (Y.QueryText, L.Request)) (Maybe (L.Request -> IO L.Request))
NOTE ' QueryText ' is just [ ( Text , Maybe Text ) ] , we keep it along with
time new parameter is added . The additional Maybe ( L.Request - > IO
L.Request ) is a finalizer that will be applied after all other
instance Semigroup (Option scheme) where
Option er0 mr0 <> Option er1 mr1 =
Option
(er0 <> er1)
(mr0 <|> mr1)
instance Monoid (Option scheme) where
mempty = Option mempty Nothing
mappend = (<>)
@since 3.11.0
instance FromForm (Option scheme) where
fromForm = Right . formToQuery
withQueryParams :: (Y.QueryText -> Y.QueryText) -> Option scheme
withQueryParams f = Option (Endo (first f)) Nothing
| A helper to create an ' Option ' that modifies only ' L.Request ' . This
withRequest :: (L.Request -> L.Request) -> Option scheme
withRequest f = Option (Endo (second f)) Nothing
instance RequestComponent (Option scheme) where
getRequestMod (Option f _) = Endo $ \x ->
let (qparams, x') = appEndo f ([], x)
query = Y.renderQuery True (Y.queryTextToQuery qparams)
in x' {L.queryString = query}
| Finalize given ' L.Request ' by applying a finalizer from the given
finalizeRequest :: (MonadIO m) => Option scheme -> L.Request -> m L.Request
finalizeRequest (Option _ mfinalizer) = liftIO . fromMaybe pure mfinalizer
your request after the question sign @?@. This is the same syntax you use
> name = : value = queryParam name ( pure value )
infix 7 =:
(=:) :: (QueryParam param, ToHttpApiData a) => Text -> a -> param
name =: value = queryParam name (pure value)
the following URL @\"a\"@ is a flag , while is a query parameter
> queryFlag name = queryParam name ( Nothing : : Maybe ( ) )
queryFlag :: (QueryParam param) => Text -> param
queryFlag name = queryParam name (Nothing :: Maybe ())
| Construct query parameters from a ' ToForm ' instance . This function
by @queryFlag key@ ) .
@since 3.11.0
formToQuery :: (QueryParam param, Monoid param, ToForm f) => f -> param
formToQuery f = mconcat . fmap toParam . Form.toListStable $ toForm f
where
toParam (key, val) =
queryParam key $
if val == ""
then Nothing
else Just val
overloaded ' queryParam ' is to be able to use it as an ' Option ' and as a
class QueryParam param where
way ) . It 's recommended to use @('=:')@ and ' ' instead of this
queryParam :: (ToHttpApiData a) => Text -> Maybe a -> param
| Get the query parameter names and values set by ' queryParam ' .
@since 3.11.0
queryParamToList :: param -> [(Text, Maybe Text)]
instance QueryParam (Option scheme) where
queryParam name mvalue =
withQueryParams ((:) (name, toQueryParam <$> mvalue))
queryParamToList (Option f _) = fst $ appEndo f ([], L.defaultRequest)
header ::
ByteString ->
ByteString ->
Option scheme
header name value = withRequest (attachHeader name value)
| Attach a header with given name and content to a ' L.Request ' .
attachHeader :: ByteString -> ByteString -> L.Request -> L.Request
attachHeader name value x =
x {L.requestHeaders = (CI.mk name, value) : L.requestHeaders x}
@since 3.13.0
headerRedacted :: ByteString -> ByteString -> Option scheme
headerRedacted name value = withRequest $ \x ->
let y = attachHeader name value x
in y {L.redactHeaders = CI.mk name `S.insert` L.redactHeaders y}
to extract ' ' from it ( see ' responseCookieJar ' ) .
| Use the given ' ' . A ' L.CookieJar ' can be obtained from a
cookieJar :: L.CookieJar -> Option scheme
cookieJar jar = withRequest $ \x ->
x {L.cookieJar = Just jar}
one authentication method at a time ( they overwrite each other ) and
basicAuth ::
ByteString ->
ByteString ->
Option 'Https
basicAuth = basicAuthUnsafe
using basic access authentication without SSL\/TLS is vulnerable to
@since 0.3.1
basicAuthUnsafe ::
ByteString ->
ByteString ->
Option scheme
basicAuthUnsafe username password =
customAuth
(pure . L.applyBasicAuth username password)
basicProxyAuth ::
ByteString ->
ByteString ->
Option scheme
basicProxyAuth username password =
withRequest (L.applyBasicProxyAuth username password)
| The ' Option ' adds authentication .
oAuth1 ::
ByteString ->
ByteString ->
ByteString ->
ByteString ->
Option scheme
oAuth1 consumerToken consumerSecret token tokenSecret =
customAuth (OAuth.signOAuth app creds)
where
app =
OAuth.newOAuth
{ OAuth.oauthConsumerKey = consumerToken,
OAuth.oauthConsumerSecret = consumerSecret
}
creds = OAuth.newCredential token tokenSecret
> oAuth2Bearer token = header " Authorization " ( " Bearer " < > token )
oAuth2Bearer ::
ByteString ->
Option 'Https
oAuth2Bearer token =
customAuth
(pure . attachHeader "Authorization" ("Bearer " <> token))
to be used only by GitHub ) . This will be treated by whatever services
oAuth2Token ::
ByteString ->
Option 'Https
oAuth2Token token =
customAuth
(pure . attachHeader "Authorization" ("token " <> token))
customAuth :: (L.Request -> IO L.Request) -> Option scheme
customAuth = Option mempty . pure
port :: Int -> Option scheme
port n = withRequest $ \x ->
x {L.port = n}
decompress ::
(ByteString -> Bool) ->
Option scheme
decompress f = withRequest $ \x ->
x {L.decompress = f}
value is 30 seconds ( defined in ' L.ManagerSettings ' of connection
responseTimeout ::
Int ->
Option scheme
responseTimeout n = withRequest $ \x ->
x {L.responseTimeout = LI.ResponseTimeoutMicro n}
| HTTP version to send to the server , the default is HTTP 1.1 .
httpVersion ::
Int ->
Int ->
Option scheme
httpVersion major minor = withRequest $ \x ->
x {L.requestVersion = Y.HttpVersion major minor}
newtype IgnoreResponse = IgnoreResponse (L.Response ())
deriving (Show)
instance HttpResponse IgnoreResponse where
type HttpResponseBody IgnoreResponse = ()
toVanillaResponse (IgnoreResponse r) = r
getHttpResponse r = return $ IgnoreResponse (void r)
| Use this as the fourth argument of ' req ' to specify that you want it to
ignoreResponse :: Proxy IgnoreResponse
ignoreResponse = Proxy
' handleHttpException ' method of ' MonadHttp ' instance corresponding to
newtype JsonResponse a = JsonResponse (L.Response a)
deriving (Show)
instance (FromJSON a) => HttpResponse (JsonResponse a) where
type HttpResponseBody (JsonResponse a) = a
toVanillaResponse (JsonResponse r) = r
getHttpResponse r = do
chunks <- L.brConsume (L.responseBody r)
case A.eitherDecode (BL.fromChunks chunks) of
Left e -> throwIO (JsonHttpException e)
Right x -> return $ JsonResponse (x <$ r)
acceptHeader Proxy = Just "application/json"
| Use this as the fourth argument of ' req ' to specify that you want it to
return the ' JsonResponse ' interpretation .
jsonResponse :: Proxy (JsonResponse a)
jsonResponse = Proxy
' ByteString ' .
newtype BsResponse = BsResponse (L.Response ByteString)
deriving (Show)
instance HttpResponse BsResponse where
type HttpResponseBody BsResponse = ByteString
toVanillaResponse (BsResponse r) = r
getHttpResponse r = do
chunks <- L.brConsume (L.responseBody r)
return $ BsResponse (B.concat chunks <$ r)
| Use this as the fourth argument of ' req ' to specify that you want to
interpret the response body as a strict ' ByteString ' .
bsResponse :: Proxy BsResponse
bsResponse = Proxy
newtype LbsResponse = LbsResponse (L.Response BL.ByteString)
deriving (Show)
instance HttpResponse LbsResponse where
type HttpResponseBody LbsResponse = BL.ByteString
toVanillaResponse (LbsResponse r) = r
getHttpResponse r = do
chunks <- L.brConsume (L.responseBody r)
return $ LbsResponse (BL.fromChunks chunks <$ r)
| Use this as the fourth argument of ' req ' to specify that you want to
lbsResponse :: Proxy LbsResponse
lbsResponse = Proxy
@'L.Response ' ' L.BodyReader'@ that can be passed to ' ' and
grabPreview ::
Int ->
L.Response L.BodyReader ->
IO (ByteString, L.Response L.BodyReader)
grabPreview nbytes r = do
let br = L.responseBody r
(target, leftover, done) <- brReadN br nbytes
nref <- newIORef (0 :: Int)
let br' = do
n <- readIORef nref
let incn = modifyIORef' nref (+ 1)
case n of
0 -> do
incn
if B.null target
then br'
else return target
1 -> do
incn
if B.null leftover
then br'
else return leftover
_ ->
if done
then return B.empty
else br
return (target, r {L.responseBody = br'})
brReadN ::
L.BodyReader ->
Int ->
IO (ByteString, ByteString, Bool)
brReadN br n = go 0 id id
where
go !tlen t l = do
chunk <- br
if B.null chunk
then return (r t, r l, True)
else do
let (target, leftover) = B.splitAt (n - tlen) chunk
tlen' = B.length target
t' = t . (target :)
l' = l . (leftover :)
if tlen + tlen' < n
then go (tlen + tlen') t' l'
else return (r t', r l', False)
r f = B.concat (f [])
responseBody ::
(HttpResponse response) =>
response ->
HttpResponseBody response
responseBody = L.responseBody . toVanillaResponse
responseStatusCode ::
(HttpResponse response) =>
response ->
Int
responseStatusCode =
Y.statusCode . L.responseStatus . toVanillaResponse
responseStatusMessage ::
(HttpResponse response) =>
response ->
ByteString
responseStatusMessage =
Y.statusMessage . L.responseStatus . toVanillaResponse
responseHeader ::
(HttpResponse response) =>
response ->
ByteString ->
Maybe ByteString
responseHeader r h =
(lookup (CI.mk h) . L.responseHeaders . toVanillaResponse) r
| Get the response ' ' .
responseCookieJar ::
(HttpResponse response) =>
response ->
L.CookieJar
responseCookieJar = L.responseCookieJar . toVanillaResponse
type an instance of the ' HttpResponse ' type class .
class HttpResponse response where
instance of ' HttpResponse ' .
type HttpResponseBody response :: Type
toVanillaResponse :: response -> L.Response (HttpResponseBody response)
generally , obtain @response@ value from @'L.Response ' ' L.BodyReader'@.
call this action repeatedly until it yields the empty ' ByteString ' . In
returned the empty ' ByteString ' once ) and you can concatenate the
getHttpResponse ::
L.Response L.BodyReader ->
IO response
@since 2.1.0
acceptHeader :: Proxy response -> Maybe ByteString
acceptHeader Proxy = Nothing
using Req 's functions like ' responseStatusCode ' , ' responseStatusMessage ' ,
@since 3.12.0
instance HttpResponse (L.Response ()) where
type HttpResponseBody (L.Response ()) = ()
toVanillaResponse = id
getHttpResponse = return . void
| The main class for things that are “ parts ” of ' L.Request ' in the sense
that if we have a ' L.Request ' , then we know how to apply an instance of
request components easier using @('<>')@.
class RequestComponent a where
| Get a function that takes a ' L.Request ' and changes it somehow
returning another ' L.Request ' . For example , the ' HttpMethod ' instance
getRequestMod :: a -> Endo L.Request
that implements ' HttpMethod ' or ' HttpBody ' . Without the tag , GHC ca n't
method@ and ' body = > ' RequestComponent ' body@ when it decides
newtype Tagged (tag :: Symbol) a = Tagged a
data HttpException
| A wrapper with an ' L.HttpException ' from " Network . HTTP.Client "
VanillaHttpException L.HttpException
| A wrapper with Aeson - produced ' String ' describing why decoding
JsonHttpException String
deriving (Show, Typeable, Generic)
instance Exception HttpException
| Return ' Just ' if the given ' HttpException ' is wrapping a http - client 's
@since 3.12.0
isStatusCodeException :: HttpException -> Maybe (L.Response ())
isStatusCodeException
( VanillaHttpException
( L.HttpExceptionRequest
_
(L.StatusCodeException r _)
)
) = Just r
isStatusCodeException _ = Nothing
| A simple type isomorphic to ' ' that we only have for better error
See also : ' HttpMethod ' and ' HttpBody ' .
data CanHaveBody
CanHaveBody
NoBody
enabled ) . This is used to force TLS requirement for some authentication
data Scheme
Http
Https
deriving (Eq, Ord, Show, Data, Typeable, Generic, TH.Lift)
|
80753ccc93b58bf17be632fea289ce4236a609bdeb6b9400447e1048495daaa5 | valderman/haste-compiler | TestDriver.hs | # LANGUAGE CPP #
module Main where
#ifdef __HASTE__
import Haste
#endif
import Tests.TEST_MODULE (runTest)
main = do
res <- runTest
putStrLn $ show res
| null | https://raw.githubusercontent.com/valderman/haste-compiler/47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8/TestDriver.hs | haskell | # LANGUAGE CPP #
module Main where
#ifdef __HASTE__
import Haste
#endif
import Tests.TEST_MODULE (runTest)
main = do
res <- runTest
putStrLn $ show res
|
|
9470e2203c93f8c231e1607313e38413acc8911518e48eca6874742a96fa628d | WorksHub/client | subs.cljc | (ns wh.components.navbar.subs
(:require [re-frame.core :refer [reg-sub]]
[wh.common.search :as search]
[wh.common.user :as user-common]
[wh.components.navbar.db :as db]
[wh.job.db :as job]))
(reg-sub
::profile-image
:<- [:user/sub-db]
(fn [{:keys [wh.user.db/type wh.user.db/image-url wh.user.db/company] :as _user} _]
(if (user-common/company-type? type) (get company :logo) image-url)))
(reg-sub
::company-slug
:<- [:user/sub-db]
(fn [user _]
(get-in user [:wh.user.db/company :slug])))
(reg-sub
::search-value
(fn [db _]
(or (::db/search-value db)
(search/->search-term (:wh.db/page-params db) (:wh.db/query-params db)))))
(reg-sub
::can-publish-jobs?
(fn [db _]
(job/can-publish-jobs? db)))
(reg-sub
::can-create-jobs?
(fn [db _]
(job/can-create-jobs? db)))
| null | https://raw.githubusercontent.com/WorksHub/client/77e4212a69dad049a9e784143915058acd918982/common/src/wh/components/navbar/subs.cljc | clojure | (ns wh.components.navbar.subs
(:require [re-frame.core :refer [reg-sub]]
[wh.common.search :as search]
[wh.common.user :as user-common]
[wh.components.navbar.db :as db]
[wh.job.db :as job]))
(reg-sub
::profile-image
:<- [:user/sub-db]
(fn [{:keys [wh.user.db/type wh.user.db/image-url wh.user.db/company] :as _user} _]
(if (user-common/company-type? type) (get company :logo) image-url)))
(reg-sub
::company-slug
:<- [:user/sub-db]
(fn [user _]
(get-in user [:wh.user.db/company :slug])))
(reg-sub
::search-value
(fn [db _]
(or (::db/search-value db)
(search/->search-term (:wh.db/page-params db) (:wh.db/query-params db)))))
(reg-sub
::can-publish-jobs?
(fn [db _]
(job/can-publish-jobs? db)))
(reg-sub
::can-create-jobs?
(fn [db _]
(job/can-create-jobs? db)))
|
|
451b478d40de13b0599ece0217f18fec69a3bc8007e80bc6c3a23b250255e514 | theam/haskell-do | View.hs |
- Copyright ( c ) 2017 The Agile Monkeys S.L. < >
-
- 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 .
- Copyright (c) 2017 The Agile Monkeys S.L. <>
-
- 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 HaskellDo.View where
import Prelude hiding (id, div)
import GHCJS.HPlay.View
import Transient.Internals ((**>))
import qualified Ulmus
import HaskellDo.Types
import qualified HaskellDo.Materialize.View as Materialize
import qualified HaskellDo.CodeMirror.View as CodeMirror
import qualified HaskellDo.Compilation.View as Compilation
import qualified HaskellDo.Toolbar.View as Toolbar
import qualified HaskellDo.Toolbar.Types as Toolbar
import qualified HaskellDo.Toolbar.FileSystemTree as FileSystemTree
view :: AppState -> Widget Action
view appState = Ulmus.withWidgets (widgets appState) $
div ! atr "class" "editor-container" $ do
Materialize.row $ do
Materialize.col "s" 6 $
Ulmus.widgetPlaceholder "editor"
Materialize.col "s" 6 ! id "outputdiv" $ do
Ulmus.widgetPlaceholder "outputDisplay"
loaderOverlay
Materialize.row $
Materialize.col "s" 12 $ div ! atr "class" "error-placeholder" $ noHtml
Ulmus.widgetPlaceholder "errorDisplay"
loaderOverlay :: Perch
loaderOverlay =
div ! atr "class" "dimmedBackground" $
div ! atr "class" "loader-align center-align" $
div ! atr "class" "loader-align-inner" $ do
div ! atr "class" "preloader-wrapper big active" $
div ! atr "class" "spinner-layer spinner-blue-only" $ do
div ! atr "class" "circle-clipper left" $
div ! atr "class" "circle" $ noHtml
div ! atr "class" "gap-patch" $
div ! atr "class" "circle" $ noHtml
div ! atr "class" "circle-clipper right" $
div ! atr "class" "circle" $ noHtml
p ! atr "class" "grey-text center-align" ! atr "id" "dependencyMessage" $ ("Downloading dependencies" :: String)
widgets :: AppState -> Widget Action
widgets state = do
Toolbar.toolbar
Toolbar.creationDisplay (toolbarState state)
showDisplays state
codeMirrorWidget
**> packageTextAreaWidget
**> openProjectButtonWidget
**> packageEditorButtonWidget
**> toggleEditorButtonWidget
**> toggleErrorButtonWidget
**> compileButtonWidget
**> pathInputWidget
**> closeModalButtonWidget
**> closePackageEditorButtonWidget
**> cancelPackageEditorButtonWidget
**> fsTreeWidget
**> modalPrompt "newDirectoryModal" Toolbar.NewDirectory Toolbar.CreateNewDirectory
where
modalPrompt id' inputAction buttonAction = Ulmus.mapAction ToolbarAction $
Toolbar.modalPrompt id' inputAction buttonAction (toolbarState state)
codeMirrorWidget = Ulmus.newWidget "editor" $
Ulmus.mapAction CodeMirrorAction $
CodeMirror.view $ codeMirrorState state
openProjectButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.openProjectButton (toolbarState state)
packageEditorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.packageEditorButton (toolbarState state)
compileButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.compileButton (toolbarState state)
toggleEditorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.toggleEditorButton (toolbarState state)
toggleErrorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.toggleErrorButton (toolbarState state)
pathInputWidget = Ulmus.mapAction ToolbarAction $
Toolbar.pathInput (toolbarState state)
packageTextAreaWidget = Ulmus.mapAction ToolbarAction $
Toolbar.packageTextArea (toolbarState state)
fsTreeWidget = Ulmus.mapAction ToolbarAction $
FileSystemTree.widget (toolbarState state)
closeModalButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.closeModalButton (toolbarState state)
closePackageEditorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.closePackageEditorButton (toolbarState state)
cancelPackageEditorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.cancelPackageEditorButton (toolbarState state)
showDisplays :: AppState -> Widget ()
showDisplays state = do
Ulmus.newWidget "outputDisplay" $ Compilation.outputDisplay (compilationState state)
Ulmus.newWidget "errorDisplay" $ Compilation.errorDisplay (compilationState state)
updateDisplays :: AppState -> Widget Action
updateDisplays state = do
Compilation.updateDisplays (compilationState state)
Ulmus.mapAction ToolbarAction $
Toolbar.updateDisplays (toolbarState state)
| null | https://raw.githubusercontent.com/theam/haskell-do/f339e57859d308437a72800bda08f96d0de12982/src/common/HaskellDo/View.hs | haskell |
- Copyright ( c ) 2017 The Agile Monkeys S.L. < >
-
- 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 .
- Copyright (c) 2017 The Agile Monkeys S.L. <>
-
- 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 HaskellDo.View where
import Prelude hiding (id, div)
import GHCJS.HPlay.View
import Transient.Internals ((**>))
import qualified Ulmus
import HaskellDo.Types
import qualified HaskellDo.Materialize.View as Materialize
import qualified HaskellDo.CodeMirror.View as CodeMirror
import qualified HaskellDo.Compilation.View as Compilation
import qualified HaskellDo.Toolbar.View as Toolbar
import qualified HaskellDo.Toolbar.Types as Toolbar
import qualified HaskellDo.Toolbar.FileSystemTree as FileSystemTree
view :: AppState -> Widget Action
view appState = Ulmus.withWidgets (widgets appState) $
div ! atr "class" "editor-container" $ do
Materialize.row $ do
Materialize.col "s" 6 $
Ulmus.widgetPlaceholder "editor"
Materialize.col "s" 6 ! id "outputdiv" $ do
Ulmus.widgetPlaceholder "outputDisplay"
loaderOverlay
Materialize.row $
Materialize.col "s" 12 $ div ! atr "class" "error-placeholder" $ noHtml
Ulmus.widgetPlaceholder "errorDisplay"
loaderOverlay :: Perch
loaderOverlay =
div ! atr "class" "dimmedBackground" $
div ! atr "class" "loader-align center-align" $
div ! atr "class" "loader-align-inner" $ do
div ! atr "class" "preloader-wrapper big active" $
div ! atr "class" "spinner-layer spinner-blue-only" $ do
div ! atr "class" "circle-clipper left" $
div ! atr "class" "circle" $ noHtml
div ! atr "class" "gap-patch" $
div ! atr "class" "circle" $ noHtml
div ! atr "class" "circle-clipper right" $
div ! atr "class" "circle" $ noHtml
p ! atr "class" "grey-text center-align" ! atr "id" "dependencyMessage" $ ("Downloading dependencies" :: String)
widgets :: AppState -> Widget Action
widgets state = do
Toolbar.toolbar
Toolbar.creationDisplay (toolbarState state)
showDisplays state
codeMirrorWidget
**> packageTextAreaWidget
**> openProjectButtonWidget
**> packageEditorButtonWidget
**> toggleEditorButtonWidget
**> toggleErrorButtonWidget
**> compileButtonWidget
**> pathInputWidget
**> closeModalButtonWidget
**> closePackageEditorButtonWidget
**> cancelPackageEditorButtonWidget
**> fsTreeWidget
**> modalPrompt "newDirectoryModal" Toolbar.NewDirectory Toolbar.CreateNewDirectory
where
modalPrompt id' inputAction buttonAction = Ulmus.mapAction ToolbarAction $
Toolbar.modalPrompt id' inputAction buttonAction (toolbarState state)
codeMirrorWidget = Ulmus.newWidget "editor" $
Ulmus.mapAction CodeMirrorAction $
CodeMirror.view $ codeMirrorState state
openProjectButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.openProjectButton (toolbarState state)
packageEditorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.packageEditorButton (toolbarState state)
compileButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.compileButton (toolbarState state)
toggleEditorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.toggleEditorButton (toolbarState state)
toggleErrorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.toggleErrorButton (toolbarState state)
pathInputWidget = Ulmus.mapAction ToolbarAction $
Toolbar.pathInput (toolbarState state)
packageTextAreaWidget = Ulmus.mapAction ToolbarAction $
Toolbar.packageTextArea (toolbarState state)
fsTreeWidget = Ulmus.mapAction ToolbarAction $
FileSystemTree.widget (toolbarState state)
closeModalButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.closeModalButton (toolbarState state)
closePackageEditorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.closePackageEditorButton (toolbarState state)
cancelPackageEditorButtonWidget = Ulmus.mapAction ToolbarAction $
Toolbar.cancelPackageEditorButton (toolbarState state)
showDisplays :: AppState -> Widget ()
showDisplays state = do
Ulmus.newWidget "outputDisplay" $ Compilation.outputDisplay (compilationState state)
Ulmus.newWidget "errorDisplay" $ Compilation.errorDisplay (compilationState state)
updateDisplays :: AppState -> Widget Action
updateDisplays state = do
Compilation.updateDisplays (compilationState state)
Ulmus.mapAction ToolbarAction $
Toolbar.updateDisplays (toolbarState state)
|
|
39e2768c4d8bde613322df104e571463cd46bb0107f0ff95fcbe67f2ae17bd2f | docopt/docopt.clj | optionsblock.clj | (ns docopt.optionsblock
(:require [clojure.string :as s])
(:use docopt.util))
(defn tokenize-option
"Generates a sequence of tokens for an option specification string."
[string]
(tokenize string [[#"\s{2,}(?s).*\[(?i)default(?-i):\s*([^\]]+).*" :default]
[#"\s{2,}(?s).*"]
[#"(?:^|\s+),?\s*-([^-,])" :short]
[#"(?:^|\s+),?\s*--([^ \t=,]+)" :long]
[(re-pattern re-arg-str) :arg]
[#"\s*[=,]?\s*"]]))
(defn parse-option
"Parses option description line into associative map."
[option-line]
(let [tokens (tokenize-option option-line)]
(err (seq (filter string? tokens)) :syntax
"Badly-formed option definition: '" (s/replace option-line #"\s\s.*" "") "'.")
(let [{:keys [short long arg default]} (reduce conj {} tokens)
[value & more-values] (filter seq (s/split (or default "") #"\s+"))]
(into (if arg
{:takes-arg true :default-value (if (seq more-values) (into [value] more-values) value)}
{:takes-arg false})
(filter val {:short short :long long})))))
(defn parse [options-lines]
"Parses options lines."
(let [options (map parse-option options-lines)]
(err (not (and (distinct? (filter identity (map :long options)))
(distinct? (filter identity (map :short options)))))
:syntax "In options descriptions, at least one option defined more than once.")
(into #{} options)))
| null | https://raw.githubusercontent.com/docopt/docopt.clj/0ae9b2eeb60d5e99388176ab4e9571238c964627/src/docopt/optionsblock.clj | clojure | (ns docopt.optionsblock
(:require [clojure.string :as s])
(:use docopt.util))
(defn tokenize-option
"Generates a sequence of tokens for an option specification string."
[string]
(tokenize string [[#"\s{2,}(?s).*\[(?i)default(?-i):\s*([^\]]+).*" :default]
[#"\s{2,}(?s).*"]
[#"(?:^|\s+),?\s*-([^-,])" :short]
[#"(?:^|\s+),?\s*--([^ \t=,]+)" :long]
[(re-pattern re-arg-str) :arg]
[#"\s*[=,]?\s*"]]))
(defn parse-option
"Parses option description line into associative map."
[option-line]
(let [tokens (tokenize-option option-line)]
(err (seq (filter string? tokens)) :syntax
"Badly-formed option definition: '" (s/replace option-line #"\s\s.*" "") "'.")
(let [{:keys [short long arg default]} (reduce conj {} tokens)
[value & more-values] (filter seq (s/split (or default "") #"\s+"))]
(into (if arg
{:takes-arg true :default-value (if (seq more-values) (into [value] more-values) value)}
{:takes-arg false})
(filter val {:short short :long long})))))
(defn parse [options-lines]
"Parses options lines."
(let [options (map parse-option options-lines)]
(err (not (and (distinct? (filter identity (map :long options)))
(distinct? (filter identity (map :short options)))))
:syntax "In options descriptions, at least one option defined more than once.")
(into #{} options)))
|
|
2227b15a782c76c697bc893e2c9fe2e041ec31bac09e375bd13f41a4843fa3d0 | IndianRoboticsOrganization/ArimaTTS | INST_uk_VOX_other.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
Carnegie Mellon University ; ; ;
and and ; ; ;
Copyright ( c ) 1998 - 2000 ; ; ;
All Rights Reserved . ; ; ;
;;; ;;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;;
;;; this software and its documentation without restriction, including ;;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;;
;;; permit persons to whom this work is furnished to do so, subject to ;;;
;;; the following conditions: ;;;
1 . The code must retain the above copyright notice , this list of ; ; ;
;;; conditions and the following disclaimer. ;;;
2 . Any modifications must be clearly marked as such . ; ; ;
3 . Original authors ' names are not deleted . ; ; ;
4 . The authors ' names are not used to endorse or promote products ; ; ;
;;; derived from this software without specific prior written ;;;
;;; permission. ;;;
;;; ;;;
CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ; ; ;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
;;; THIS SOFTWARE. ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Something else
;;;
;;; Load any necessary files here
(define (INST_uk_VOX::select_other)
"(INST_uk_VOX::select_other)
Set up the anything esle for the voice."
;; something else
)
(define (INST_uk_VOX::reset_other)
"(INST_uk_VOX::reset_other)
Reset other information."
t
)
(provide 'INST_uk_VOX_other)
| null | https://raw.githubusercontent.com/IndianRoboticsOrganization/ArimaTTS/7377dca466306e2e6b90a063427273142cd50616/festvox/src/vox_files/uk/INST_uk_VOX_other.scm | scheme |
;;;
; ;
; ;
; ;
; ;
;;;
Permission is hereby granted, free of charge, to use and distribute ;;;
this software and its documentation without restriction, including ;;;
without limitation the rights to use, copy, modify, merge, publish, ;;;
distribute, sublicense, and/or sell copies of this work, and to ;;;
permit persons to whom this work is furnished to do so, subject to ;;;
the following conditions: ;;;
; ;
conditions and the following disclaimer. ;;;
; ;
; ;
; ;
derived from this software without specific prior written ;;;
permission. ;;;
;;;
; ;
DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
; ;
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
; ;
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
THIS SOFTWARE. ;;;
;;;
Something else
Load any necessary files here
something else |
(define (INST_uk_VOX::select_other)
"(INST_uk_VOX::select_other)
Set up the anything esle for the voice."
)
(define (INST_uk_VOX::reset_other)
"(INST_uk_VOX::reset_other)
Reset other information."
t
)
(provide 'INST_uk_VOX_other)
|
d96f7c522785ca7c9e31c7d26dee3f7500eb7e4a0245f0f0194a879968c6b728 | arttuka/reagent-material-ui | step_button.cljs | (ns reagent-mui.material.step-button
"Imports @mui/material/StepButton as a Reagent component.
Original documentation is at -ui/api/step-button/ ."
(:require [reagent.core :as r]
["@mui/material/StepButton" :as MuiStepButton]))
(def step-button (r/adapt-react-class (.-default MuiStepButton)))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/core/reagent_mui/material/step_button.cljs | clojure | (ns reagent-mui.material.step-button
"Imports @mui/material/StepButton as a Reagent component.
Original documentation is at -ui/api/step-button/ ."
(:require [reagent.core :as r]
["@mui/material/StepButton" :as MuiStepButton]))
(def step-button (r/adapt-react-class (.-default MuiStepButton)))
|
|
b3b4b0f51c5e48183866be7b265c39535e0470cb10fd62b4f4fbd1b1ed0e80a0 | BekaValentine/SimpleFP | TypeChecking.hs | {-# OPTIONS -Wall #-}
# LANGUAGE TypeFamilies #
module Poly.Unification.TypeChecking where
import Control.Applicative ((<$>))
import Control.Monad.Except
import Control.Monad.State
import Data.List (intercalate,nubBy,find)
import Scope
import TypeChecker
import Poly.Core.Term
import Poly.Core.Type
-- Signatures
-- argnum, Params -> ([Arg],Ret)
data ConSig = ConSig Int (Scope Type ([Type],Type))
instance Show ConSig where
show (ConSig n sc)
= let (as,r) = instantiate sc (zipWith (\x i -> TyVar (TyGenerated x i)) (names sc) [0..n])
in "(" ++ intercalate "," (map show as) ++ ")" ++ show r
data TyConSig = TyConSig Int
instance Show TyConSig where
show (TyConSig 0) = "*"
show (TyConSig n) = "(" ++ intercalate "," (replicate n "*") ++ ") -> *"
data Signature = Signature [(String,TyConSig)] [(String,ConSig)]
instance Show Signature where
show (Signature tyconsigs consigs)
= "Types:\n" ++
unlines [ " " ++ c ++ " :: " ++ show tyconsig
| (c,tyconsig) <- tyconsigs
] ++
"Constructors:\n" ++
unlines [ " " ++ c ++ " :: " ++ show consig
| (c,consig) <- consigs
]
lookupSignature :: String -> Signature -> Maybe ConSig
lookupSignature c (Signature _ consigs) = lookup c consigs
-- Definitions
type Definitions = [(String,Term,Type)]
-- Contexts
type Context = [(Int,String,Type)]
type TyVarContext = [Int]
-- Unifying Type Checkers
data Equation = Equation Type Type
type MetaVar = Int
type Substitution = [(MetaVar,Type)]
data TCState
= TCState
{ tcSig :: Signature
, tcDefs :: Definitions
, tcCtx :: Context
, tcTyVarCtx :: TyVarContext
, tcNextName :: Int
, tcNextMeta :: MetaVar
, tcSubs :: Substitution
}
instance TypeCheckerState TCState where
type Sig TCState = Signature
type Defs TCState = Definitions
type Ctx TCState = Context
typeCheckerSig = tcSig
putTypeCheckerSig s sig = s { tcSig = sig }
typeCheckerDefs = tcDefs
putTypeCheckerDefs s defs = s { tcDefs = defs }
addTypeCheckerDefs s edefs = s { tcDefs = edefs ++ tcDefs s }
typeCheckerCtx = tcCtx
putTypeCheckerCtx s ctx = s { tcCtx = ctx }
addTypeCheckerCtx s ectx = s { tcCtx = ectx ++ tcCtx s }
typeCheckerNextName = tcNextName
putTypeCheckerNextName s n = s { tcNextName = n }
instance TypeCheckerMetas TCState where
type Subs TCState = Substitution
typeCheckerNextMeta = tcNextMeta
putTypeCheckerNextMeta s n = s { tcNextMeta = n }
typeCheckerSubs = tcSubs
putTypeCheckerSubs s subs = s { tcSubs = subs }
type TypeChecker a = StateT TCState (Either String) a
runTypeChecker :: TypeChecker a -> Signature -> Definitions -> Context -> Int -> Either String (a,TCState)
runTypeChecker checker sig defs ctx i
= runStateT checker (TCState sig defs ctx [] i 0 [])
tyVarContext :: TypeChecker TyVarContext
tyVarContext = tcTyVarCtx <$> get
putTyVarContext :: TyVarContext -> TypeChecker ()
putTyVarContext tyVarCtx = do s <- get
put (s { tcTyVarCtx = tyVarCtx })
extendTyVarContext :: TyVarContext -> TypeChecker a -> TypeChecker a
extendTyVarContext etyVarCtx tc = do tyVarCtx <- tyVarContext
putTyVarContext (etyVarCtx ++ tyVarCtx)
x <- tc
putTyVarContext tyVarCtx
return x
occurs :: MetaVar -> Type -> Bool
occurs x (TyCon _ args) = any (occurs x) args
occurs x (Fun a b) = occurs x a || occurs x b
occurs x (Meta y) = x == y
occurs _ (TyVar _) = False
occurs x (Forall sc) = occurs x (descope (TyVar . TyName) sc)
solve :: [Equation] -> TypeChecker Substitution
solve eqs0 = go eqs0 []
where
go :: [Equation] -> Substitution -> TypeChecker Substitution
go [] subs' = return subs'
go (Equation (Meta x) (Meta y) : eqs) subs'
| x == y
= go eqs subs'
| otherwise
= go eqs ((x,Meta y):subs')
go (Equation (Meta x) t2 : eqs) subs'
= do unless (not (occurs x t2))
$ throwError $ "Cannot unify because " ++ show (Meta x)
++ " occurs in " ++ show t2
go eqs ((x,t2):subs')
go (Equation t1 (Meta y) : eqs) subs'
= do unless (not (occurs y t1))
$ throwError $ "Cannot unify because " ++ show (Meta y)
++ " occurs in " ++ show t1
go eqs ((y,t1):subs')
go (Equation (TyCon tycon1 args1) (TyCon tycon2 args2) : eqs) subs'
= do unless (tycon1 == tycon2)
$ throwError $ "Mismatching type constructors " ++ tycon1 ++ " and " ++ tycon2
let largs1 = length args1
largs2 = length args2
unless (largs1 == largs2)
$ throwError $ "Mismatching type constructor arg lengths between "
++ show (TyCon tycon1 args1) ++ " and "
++ show (TyCon tycon2 args2)
go (zipWith Equation args1 args2 ++ eqs) subs'
go (Equation (Fun a1 b1) (Fun a2 b2) : eqs) subs'
= go (Equation a1 a2 : Equation b1 b2 : eqs) subs'
go (Equation (TyVar x) (TyVar y) : eqs) subs'
= do unless (x == y)
$ throwError $ "Cannot unify type variables " ++ show (TyVar x)
++ " and " ++ show (TyVar y)
go eqs subs'
go (Equation (Forall sc) (Forall sc') : eqs) subs'
= do i <- newName
let b = instantiate sc [TyVar (TyGenerated (head (names sc)) i)]
b' = instantiate sc' [TyVar (TyGenerated (head (names sc')) i)]
go (Equation b b' : eqs) subs'
go (Equation l r : _) _
= throwError $ "Cannot unify " ++ show l ++ " with " ++ show r
addSubstitutions :: Substitution -> TypeChecker ()
addSubstitutions subs0
= do completeSubstitution subs0
substituteContext
where
completeSubstitution subs'
= do subs <- substitution
let subs2 = subs' ++ subs
subs2' = nubBy (\(a,_) (b,_) -> a == b) (map (\(k,v) -> (k, instantiateMetas subs2 v)) subs2)
putSubstitution subs2'
substituteContext
= do ctx <- context
subs2 <- substitution
putContext (map (\(i,x,t) -> (i,x,instantiateMetas subs2 t)) ctx)
unify :: Type -> Type -> TypeChecker ()
unify p q = do subs' <- solve [Equation p q]
addSubstitutions subs'
instantiateMetas :: Substitution -> Type -> Type
instantiateMetas subs (TyCon tycon args)
= TyCon tycon (map (instantiateMetas subs) args)
instantiateMetas subs (Fun a b)
= Fun (instantiateMetas subs a) (instantiateMetas subs b)
instantiateMetas subs (Meta i)
= case lookup i subs of
Nothing -> Meta i
Just t -> instantiateMetas subs t
instantiateMetas _ (TyVar x)
= TyVar x
instantiateMetas subs (Forall sc)
= Forall (instantiateMetas subs <$> sc)
typeInContext :: Int -> TypeChecker Type
typeInContext i
= do ctx <- context
case find (\(j,_,_) -> j == i) ctx of
Nothing -> throwError "Unbound automatically generated variable."
Just (_,_,t) -> return t
typeInDefinitions :: String -> TypeChecker Type
typeInDefinitions n
= do defs <- definitions
case find (\(n',_,_) -> n' == n) defs of
Nothing -> throwError $ "Unknown constant/defined term: " ++ n
Just (_,_,t) -> return t
typeInSignature :: String -> TypeChecker ConSig
typeInSignature n
= do Signature _ consigs <- signature
case lookup n consigs of
Nothing -> throwError $ "Unknown constructor: " ++ n
Just t -> return t
tyconExists :: String -> TypeChecker Int
tyconExists n
= do Signature tyconsigs _ <- signature
let matches = filter (\(tycon,_) -> n == tycon) tyconsigs
case matches of
[(_,TyConSig arity)] -> return arity
_ -> throwError $ "Unknown type constructor: " ++ n
-- Type well-formedness
isType :: Type -> TypeChecker ()
isType (Meta _) = return ()
isType (TyCon c as) = do n <- tyconExists c
let las = length as
unless (n == las)
$ throwError $ c ++ " expects " ++ show n ++ " "
++ (if n == 1 then "arg" else "args")
++ " but was given " ++ show las
mapM_ isType as
isType (Fun a b) = isType a >> isType b
isType (TyVar _) = return ()
isType (Forall sc) = do i <- newName
isType (instantiate sc [TyVar (TyGenerated (head (names sc)) i)])
-- Inserting param variables into con data
instantiateParams :: Int -> Scope Type ([Type],Type) -> TypeChecker ([Type],Type)
instantiateParams n sc
= do ms <- replicateM n (fmap Meta newMetaVar)
return $ instantiate sc ms
-- Instantiating quantified values until there are no more initial quantifiers
instantiateQuantifiers :: Type -> TypeChecker Type
instantiateQuantifiers (Forall sc)
= do meta <- newMetaVar
let m = Meta meta
instantiateQuantifiers (instantiate sc [m])
instantiateQuantifiers t = return t
-- Type Inference
inferify :: Term -> TypeChecker Type
inferify (Var (Name x))
= typeInDefinitions x
inferify (Var (Generated _ i))
= typeInContext i
inferify (Ann m t)
= do isType t
checkify m t
subs <- substitution
return $ instantiateMetas subs t
inferify (Lam sc)
= do i <- newName
meta <- newMetaVar
let arg = Meta meta
ret <- extendContext [(i, head (names sc), arg)]
$ inferify (instantiate sc [Var (Generated (head (names sc)) i)])
subs <- substitution
return $ Fun (instantiateMetas subs arg) ret
inferify (App f a)
= do t <- inferify f
Fun arg ret <- instantiateQuantifiers t
checkify a arg
subs <- substitution
return $ instantiateMetas subs ret
inferify (Con c as)
= do ConSig n sc <- typeInSignature c
(args',ret') <- instantiateParams n sc
let las = length as
largs' = length args'
unless (las == largs')
$ throwError $ c ++ " expects " ++ show largs' ++ " "
++ (if largs' == 1 then "arg" else "args")
++ " but was given " ++ show las
checkifyMulti as args'
subs <- substitution
return $ instantiateMetas subs ret'
where
checkifyMulti :: [Term] -> [Type] -> TypeChecker ()
checkifyMulti [] [] = return ()
checkifyMulti (m:ms) (t:ts) = do subs <- substitution
checkify m (instantiateMetas subs t)
checkifyMulti ms ts
checkifyMulti _ _ = throwError "Mismatched constructor signature lengths."
inferify (Case ms cs)
= do ts <- mapM inferify ms
inferifyClauses ts cs
inferifyClause :: [Type] -> Clause -> TypeChecker Type
inferifyClause patTys (Clause psc sc)
= do let lps = length (descope Name psc)
unless (length patTys == lps)
$ throwError $ "Mismatching number of patterns. Expected " ++ show (length patTys)
++ " but found " ++ show lps
ctx' <- forM (names psc) $ \x -> do
i <- newName
m <- newMetaVar
return (i, x, Meta m)
let is = [ i | (i,_,_) <- ctx' ]
xs1 = zipWith Generated (names psc) is
xs2 = map Var (removeByDummies (names psc) xs1)
extendContext ctx' $ do
zipWithM_ checkifyPattern (instantiate psc xs1) patTys
inferify (instantiate sc xs2)
inferifyClauses :: [Type] -> [Clause] -> TypeChecker Type
inferifyClauses patTys cs
= do ts <- mapM (inferifyClause patTys) cs
case ts of
[] -> throwError "Empty clauses."
t:ts' -> do
catchError (mapM_ (unify t) ts') $ \e ->
throwError $ "Clauses do not all return the same type:\n"
++ unlines (map show ts) ++ "\n"
++ "Unification failed with error: " ++ e
subs <- substitution
return (instantiateMetas subs t)
-- Type Checking
checkify :: Term -> Type -> TypeChecker ()
checkify m (Forall sc)
= do i <- newName
extendTyVarContext [i]
$ checkify m (instantiate sc [TyVar (TyGenerated (head (names sc)) i)])
checkify (Var x) t
= do t' <- inferify (Var x)
equivQuantifiers t' t
checkify (Lam sc) (Fun arg ret)
= do i <- newName
extendContext [(i, head (names sc), arg)]
$ checkify (instantiate sc [Var (Generated (head (names sc)) i)]) ret
checkify (Lam sc) t
= throwError $ "Cannot check term: " ++ show (Lam sc) ++ "\n"
++ "Against non-function type: " ++ show t
checkify m t
= do t' <- inferify m
catchError (unify t t') $ \e ->
throwError $ "Expected term: " ++ show m ++ "\n"
++ "To have type: " ++ show t ++ "\n"
++ "Instead found type: " ++ show t' ++ "\n"
++ "Unification failed with error: " ++ e
equivQuantifiers :: Type -> Type -> TypeChecker ()
equivQuantifiers t (Forall sc')
= do i <- newName
equivQuantifiers t (instantiate sc' [TyVar (TyGenerated (head (names sc')) i)])
equivQuantifiers (Forall sc) t'
= do meta <- newMetaVar
let x2 = Meta meta
equivQuantifiers (instantiate sc [x2]) t'
equivQuantifiers (Fun arg ret) (Fun arg' ret')
= do --unify arg arg'
equivQuantifiers arg' arg
equivQuantifiers ret ret'
equivQuantifiers t t'
= unify t t'
checkifyPattern :: Pattern -> Type -> TypeChecker ()
checkifyPattern (VarPat (Name _)) _
= return ()
checkifyPattern (VarPat (Generated _ i)) t
= do t' <- typeInContext i
unify t t'
checkifyPattern (ConPat c ps) t
= do ConSig n sc <- typeInSignature c
(args',ret') <- instantiateParams n sc
let lps = length ps
largs' = length args'
unless (lps == largs')
$ throwError $ c ++ " expects " ++ show largs' ++ " "
++ (if largs' == 1 then "arg" else "args")
++ " but was given " ++ show lps
unify t ret'
subs <- substitution
zipWithM_ checkifyPattern ps (map (instantiateMetas subs) args')
-- type checking succees exactly when checkification succeeds
-- and there is a substitution for every meta-variable
metasSolved :: TypeChecker ()
metasSolved = do s <- get
unless (tcNextMeta s == length (tcSubs s))
$ throwError "Not all metavariables have been solved."
check :: Term -> Type -> TypeChecker ()
check m t = do checkify m t
metasSolved
infer :: Term -> TypeChecker Type
infer m = do t <- inferify m
metasSolved
subs <- substitution
return $ instantiateMetas subs t | null | https://raw.githubusercontent.com/BekaValentine/SimpleFP/3cff456be9f0b99509e5cbe809be1055009b32df/src/Poly/Unification/TypeChecking.hs | haskell | # OPTIONS -Wall #
Signatures
argnum, Params -> ([Arg],Ret)
Definitions
Contexts
Unifying Type Checkers
Type well-formedness
Inserting param variables into con data
Instantiating quantified values until there are no more initial quantifiers
Type Inference
Type Checking
unify arg arg'
type checking succees exactly when checkification succeeds
and there is a substitution for every meta-variable | # LANGUAGE TypeFamilies #
module Poly.Unification.TypeChecking where
import Control.Applicative ((<$>))
import Control.Monad.Except
import Control.Monad.State
import Data.List (intercalate,nubBy,find)
import Scope
import TypeChecker
import Poly.Core.Term
import Poly.Core.Type
data ConSig = ConSig Int (Scope Type ([Type],Type))
instance Show ConSig where
show (ConSig n sc)
= let (as,r) = instantiate sc (zipWith (\x i -> TyVar (TyGenerated x i)) (names sc) [0..n])
in "(" ++ intercalate "," (map show as) ++ ")" ++ show r
data TyConSig = TyConSig Int
instance Show TyConSig where
show (TyConSig 0) = "*"
show (TyConSig n) = "(" ++ intercalate "," (replicate n "*") ++ ") -> *"
data Signature = Signature [(String,TyConSig)] [(String,ConSig)]
instance Show Signature where
show (Signature tyconsigs consigs)
= "Types:\n" ++
unlines [ " " ++ c ++ " :: " ++ show tyconsig
| (c,tyconsig) <- tyconsigs
] ++
"Constructors:\n" ++
unlines [ " " ++ c ++ " :: " ++ show consig
| (c,consig) <- consigs
]
lookupSignature :: String -> Signature -> Maybe ConSig
lookupSignature c (Signature _ consigs) = lookup c consigs
type Definitions = [(String,Term,Type)]
type Context = [(Int,String,Type)]
type TyVarContext = [Int]
data Equation = Equation Type Type
type MetaVar = Int
type Substitution = [(MetaVar,Type)]
data TCState
= TCState
{ tcSig :: Signature
, tcDefs :: Definitions
, tcCtx :: Context
, tcTyVarCtx :: TyVarContext
, tcNextName :: Int
, tcNextMeta :: MetaVar
, tcSubs :: Substitution
}
instance TypeCheckerState TCState where
type Sig TCState = Signature
type Defs TCState = Definitions
type Ctx TCState = Context
typeCheckerSig = tcSig
putTypeCheckerSig s sig = s { tcSig = sig }
typeCheckerDefs = tcDefs
putTypeCheckerDefs s defs = s { tcDefs = defs }
addTypeCheckerDefs s edefs = s { tcDefs = edefs ++ tcDefs s }
typeCheckerCtx = tcCtx
putTypeCheckerCtx s ctx = s { tcCtx = ctx }
addTypeCheckerCtx s ectx = s { tcCtx = ectx ++ tcCtx s }
typeCheckerNextName = tcNextName
putTypeCheckerNextName s n = s { tcNextName = n }
instance TypeCheckerMetas TCState where
type Subs TCState = Substitution
typeCheckerNextMeta = tcNextMeta
putTypeCheckerNextMeta s n = s { tcNextMeta = n }
typeCheckerSubs = tcSubs
putTypeCheckerSubs s subs = s { tcSubs = subs }
type TypeChecker a = StateT TCState (Either String) a
runTypeChecker :: TypeChecker a -> Signature -> Definitions -> Context -> Int -> Either String (a,TCState)
runTypeChecker checker sig defs ctx i
= runStateT checker (TCState sig defs ctx [] i 0 [])
tyVarContext :: TypeChecker TyVarContext
tyVarContext = tcTyVarCtx <$> get
putTyVarContext :: TyVarContext -> TypeChecker ()
putTyVarContext tyVarCtx = do s <- get
put (s { tcTyVarCtx = tyVarCtx })
extendTyVarContext :: TyVarContext -> TypeChecker a -> TypeChecker a
extendTyVarContext etyVarCtx tc = do tyVarCtx <- tyVarContext
putTyVarContext (etyVarCtx ++ tyVarCtx)
x <- tc
putTyVarContext tyVarCtx
return x
occurs :: MetaVar -> Type -> Bool
occurs x (TyCon _ args) = any (occurs x) args
occurs x (Fun a b) = occurs x a || occurs x b
occurs x (Meta y) = x == y
occurs _ (TyVar _) = False
occurs x (Forall sc) = occurs x (descope (TyVar . TyName) sc)
solve :: [Equation] -> TypeChecker Substitution
solve eqs0 = go eqs0 []
where
go :: [Equation] -> Substitution -> TypeChecker Substitution
go [] subs' = return subs'
go (Equation (Meta x) (Meta y) : eqs) subs'
| x == y
= go eqs subs'
| otherwise
= go eqs ((x,Meta y):subs')
go (Equation (Meta x) t2 : eqs) subs'
= do unless (not (occurs x t2))
$ throwError $ "Cannot unify because " ++ show (Meta x)
++ " occurs in " ++ show t2
go eqs ((x,t2):subs')
go (Equation t1 (Meta y) : eqs) subs'
= do unless (not (occurs y t1))
$ throwError $ "Cannot unify because " ++ show (Meta y)
++ " occurs in " ++ show t1
go eqs ((y,t1):subs')
go (Equation (TyCon tycon1 args1) (TyCon tycon2 args2) : eqs) subs'
= do unless (tycon1 == tycon2)
$ throwError $ "Mismatching type constructors " ++ tycon1 ++ " and " ++ tycon2
let largs1 = length args1
largs2 = length args2
unless (largs1 == largs2)
$ throwError $ "Mismatching type constructor arg lengths between "
++ show (TyCon tycon1 args1) ++ " and "
++ show (TyCon tycon2 args2)
go (zipWith Equation args1 args2 ++ eqs) subs'
go (Equation (Fun a1 b1) (Fun a2 b2) : eqs) subs'
= go (Equation a1 a2 : Equation b1 b2 : eqs) subs'
go (Equation (TyVar x) (TyVar y) : eqs) subs'
= do unless (x == y)
$ throwError $ "Cannot unify type variables " ++ show (TyVar x)
++ " and " ++ show (TyVar y)
go eqs subs'
go (Equation (Forall sc) (Forall sc') : eqs) subs'
= do i <- newName
let b = instantiate sc [TyVar (TyGenerated (head (names sc)) i)]
b' = instantiate sc' [TyVar (TyGenerated (head (names sc')) i)]
go (Equation b b' : eqs) subs'
go (Equation l r : _) _
= throwError $ "Cannot unify " ++ show l ++ " with " ++ show r
addSubstitutions :: Substitution -> TypeChecker ()
addSubstitutions subs0
= do completeSubstitution subs0
substituteContext
where
completeSubstitution subs'
= do subs <- substitution
let subs2 = subs' ++ subs
subs2' = nubBy (\(a,_) (b,_) -> a == b) (map (\(k,v) -> (k, instantiateMetas subs2 v)) subs2)
putSubstitution subs2'
substituteContext
= do ctx <- context
subs2 <- substitution
putContext (map (\(i,x,t) -> (i,x,instantiateMetas subs2 t)) ctx)
unify :: Type -> Type -> TypeChecker ()
unify p q = do subs' <- solve [Equation p q]
addSubstitutions subs'
instantiateMetas :: Substitution -> Type -> Type
instantiateMetas subs (TyCon tycon args)
= TyCon tycon (map (instantiateMetas subs) args)
instantiateMetas subs (Fun a b)
= Fun (instantiateMetas subs a) (instantiateMetas subs b)
instantiateMetas subs (Meta i)
= case lookup i subs of
Nothing -> Meta i
Just t -> instantiateMetas subs t
instantiateMetas _ (TyVar x)
= TyVar x
instantiateMetas subs (Forall sc)
= Forall (instantiateMetas subs <$> sc)
typeInContext :: Int -> TypeChecker Type
typeInContext i
= do ctx <- context
case find (\(j,_,_) -> j == i) ctx of
Nothing -> throwError "Unbound automatically generated variable."
Just (_,_,t) -> return t
typeInDefinitions :: String -> TypeChecker Type
typeInDefinitions n
= do defs <- definitions
case find (\(n',_,_) -> n' == n) defs of
Nothing -> throwError $ "Unknown constant/defined term: " ++ n
Just (_,_,t) -> return t
typeInSignature :: String -> TypeChecker ConSig
typeInSignature n
= do Signature _ consigs <- signature
case lookup n consigs of
Nothing -> throwError $ "Unknown constructor: " ++ n
Just t -> return t
tyconExists :: String -> TypeChecker Int
tyconExists n
= do Signature tyconsigs _ <- signature
let matches = filter (\(tycon,_) -> n == tycon) tyconsigs
case matches of
[(_,TyConSig arity)] -> return arity
_ -> throwError $ "Unknown type constructor: " ++ n
isType :: Type -> TypeChecker ()
isType (Meta _) = return ()
isType (TyCon c as) = do n <- tyconExists c
let las = length as
unless (n == las)
$ throwError $ c ++ " expects " ++ show n ++ " "
++ (if n == 1 then "arg" else "args")
++ " but was given " ++ show las
mapM_ isType as
isType (Fun a b) = isType a >> isType b
isType (TyVar _) = return ()
isType (Forall sc) = do i <- newName
isType (instantiate sc [TyVar (TyGenerated (head (names sc)) i)])
instantiateParams :: Int -> Scope Type ([Type],Type) -> TypeChecker ([Type],Type)
instantiateParams n sc
= do ms <- replicateM n (fmap Meta newMetaVar)
return $ instantiate sc ms
instantiateQuantifiers :: Type -> TypeChecker Type
instantiateQuantifiers (Forall sc)
= do meta <- newMetaVar
let m = Meta meta
instantiateQuantifiers (instantiate sc [m])
instantiateQuantifiers t = return t
inferify :: Term -> TypeChecker Type
inferify (Var (Name x))
= typeInDefinitions x
inferify (Var (Generated _ i))
= typeInContext i
inferify (Ann m t)
= do isType t
checkify m t
subs <- substitution
return $ instantiateMetas subs t
inferify (Lam sc)
= do i <- newName
meta <- newMetaVar
let arg = Meta meta
ret <- extendContext [(i, head (names sc), arg)]
$ inferify (instantiate sc [Var (Generated (head (names sc)) i)])
subs <- substitution
return $ Fun (instantiateMetas subs arg) ret
inferify (App f a)
= do t <- inferify f
Fun arg ret <- instantiateQuantifiers t
checkify a arg
subs <- substitution
return $ instantiateMetas subs ret
inferify (Con c as)
= do ConSig n sc <- typeInSignature c
(args',ret') <- instantiateParams n sc
let las = length as
largs' = length args'
unless (las == largs')
$ throwError $ c ++ " expects " ++ show largs' ++ " "
++ (if largs' == 1 then "arg" else "args")
++ " but was given " ++ show las
checkifyMulti as args'
subs <- substitution
return $ instantiateMetas subs ret'
where
checkifyMulti :: [Term] -> [Type] -> TypeChecker ()
checkifyMulti [] [] = return ()
checkifyMulti (m:ms) (t:ts) = do subs <- substitution
checkify m (instantiateMetas subs t)
checkifyMulti ms ts
checkifyMulti _ _ = throwError "Mismatched constructor signature lengths."
inferify (Case ms cs)
= do ts <- mapM inferify ms
inferifyClauses ts cs
inferifyClause :: [Type] -> Clause -> TypeChecker Type
inferifyClause patTys (Clause psc sc)
= do let lps = length (descope Name psc)
unless (length patTys == lps)
$ throwError $ "Mismatching number of patterns. Expected " ++ show (length patTys)
++ " but found " ++ show lps
ctx' <- forM (names psc) $ \x -> do
i <- newName
m <- newMetaVar
return (i, x, Meta m)
let is = [ i | (i,_,_) <- ctx' ]
xs1 = zipWith Generated (names psc) is
xs2 = map Var (removeByDummies (names psc) xs1)
extendContext ctx' $ do
zipWithM_ checkifyPattern (instantiate psc xs1) patTys
inferify (instantiate sc xs2)
inferifyClauses :: [Type] -> [Clause] -> TypeChecker Type
inferifyClauses patTys cs
= do ts <- mapM (inferifyClause patTys) cs
case ts of
[] -> throwError "Empty clauses."
t:ts' -> do
catchError (mapM_ (unify t) ts') $ \e ->
throwError $ "Clauses do not all return the same type:\n"
++ unlines (map show ts) ++ "\n"
++ "Unification failed with error: " ++ e
subs <- substitution
return (instantiateMetas subs t)
checkify :: Term -> Type -> TypeChecker ()
checkify m (Forall sc)
= do i <- newName
extendTyVarContext [i]
$ checkify m (instantiate sc [TyVar (TyGenerated (head (names sc)) i)])
checkify (Var x) t
= do t' <- inferify (Var x)
equivQuantifiers t' t
checkify (Lam sc) (Fun arg ret)
= do i <- newName
extendContext [(i, head (names sc), arg)]
$ checkify (instantiate sc [Var (Generated (head (names sc)) i)]) ret
checkify (Lam sc) t
= throwError $ "Cannot check term: " ++ show (Lam sc) ++ "\n"
++ "Against non-function type: " ++ show t
checkify m t
= do t' <- inferify m
catchError (unify t t') $ \e ->
throwError $ "Expected term: " ++ show m ++ "\n"
++ "To have type: " ++ show t ++ "\n"
++ "Instead found type: " ++ show t' ++ "\n"
++ "Unification failed with error: " ++ e
equivQuantifiers :: Type -> Type -> TypeChecker ()
equivQuantifiers t (Forall sc')
= do i <- newName
equivQuantifiers t (instantiate sc' [TyVar (TyGenerated (head (names sc')) i)])
equivQuantifiers (Forall sc) t'
= do meta <- newMetaVar
let x2 = Meta meta
equivQuantifiers (instantiate sc [x2]) t'
equivQuantifiers (Fun arg ret) (Fun arg' ret')
equivQuantifiers arg' arg
equivQuantifiers ret ret'
equivQuantifiers t t'
= unify t t'
checkifyPattern :: Pattern -> Type -> TypeChecker ()
checkifyPattern (VarPat (Name _)) _
= return ()
checkifyPattern (VarPat (Generated _ i)) t
= do t' <- typeInContext i
unify t t'
checkifyPattern (ConPat c ps) t
= do ConSig n sc <- typeInSignature c
(args',ret') <- instantiateParams n sc
let lps = length ps
largs' = length args'
unless (lps == largs')
$ throwError $ c ++ " expects " ++ show largs' ++ " "
++ (if largs' == 1 then "arg" else "args")
++ " but was given " ++ show lps
unify t ret'
subs <- substitution
zipWithM_ checkifyPattern ps (map (instantiateMetas subs) args')
metasSolved :: TypeChecker ()
metasSolved = do s <- get
unless (tcNextMeta s == length (tcSubs s))
$ throwError "Not all metavariables have been solved."
check :: Term -> Type -> TypeChecker ()
check m t = do checkify m t
metasSolved
infer :: Term -> TypeChecker Type
infer m = do t <- inferify m
metasSolved
subs <- substitution
return $ instantiateMetas subs t |
7450cc3611be4119f8985a5a8c8210a7a59f644259f9f131b79a3046d6bc1f46 | borodust/claw-legacy | dynamic.lisp | (cl:in-package :claw.cffi.c)
(defgeneric initialize-adapter (library-name))
(defclass dynamic-adapter (adapter) ())
(defun make-dynamic-adapter (wrapper path)
(make-instance 'dynamic-adapter :wrapper wrapper :path path))
(defun load-dynamic-adapter-template ()
(alexandria:read-file-into-string
(asdf:system-relative-pathname :claw/cffi "src/cffi/c/adapter/template/dynamic.c")))
(defun library-loader-name (library-name)
(let* ((library-string (symbol-name library-name))
(c-name (ppcre:regex-replace-all "[^_\\w]+" library-string "_"))
(hex (claw-sha1:sha1-hex
(concatenate 'string
(if-let ((package (symbol-package library-name)))
(package-name package)
"")
(symbol-name library-name)))))
(subseq (format nil "~A~(~A~)_loader_~A" +adapted-function-prefix+ c-name hex) 0 64)))
(defun preprocess-dynamic-adapter-template (includes
loader-name
function-types
function-pointers
function-pointers-init
function-definitions)
(preprocess-template (load-dynamic-adapter-template)
"timestamp" (get-timestamp)
"includes" includes
"loader-name" loader-name
"function-types" function-types
"function-pointers" function-pointers
"function-pointers-init" function-pointers-init
"function-definitions" function-definitions))
(defmethod generate-adapter-file ((this dynamic-adapter))
(when (%adapter-needs-rebuilding-p this)
(ensure-directories-exist (uiop:pathname-directory-pathname (adapter-file-of this)))
(with-output-to-file (output (adapter-file-of this) :if-exists :supersede)
(let* ((functions (functions-of this))
(definitions
(%generate-adapted-function-definitions functions
+adapted-variable-prefix+)))
(flet ((function-types ()
(with-output-to-string (out)
(loop for function in functions
do (format out "~&")
(%generate-function-type function out))))
(function-variables ()
(with-output-to-string (out)
(loop for function in functions
do (format out "~&")
(%generate-function-variable function out))))
(function-variable-inits ()
(with-output-to-string (out)
(loop for function in functions
do (format out "~&")
(%generate-function-variable-init function out))))
(header-files ()
(format nil "~{#include \"~A\"~^~%~}" (headers-of this))))
(format output "~A"
(preprocess-dynamic-adapter-template
(header-files)
(library-loader-name (wrapper-name-of this))
(function-types)
(function-variables)
(function-variable-inits)
definitions)))))))
(defun build-dynamic-adapter (standard adapter-file includes target-file &key pedantic)
(uiop:run-program (append (list "gcc" "-shared" (namestring adapter-file))
(when standard
(list (format nil "-std=~A" standard)))
(when pedantic
(list "-pedantic"))
(list "-O3" "-fPIC")
(loop for directory in includes
collect (format nil "-I~A"
(namestring directory)))
(list "-o" (namestring target-file)))
:output *standard-output*
:error-output *debug-io*))
(defun %verify-adapter-initialization (result)
(unless (zerop result)
(error "Failed to initialize adapater")))
(defun shared-extension-name ()
#+(and unix (not darwin))
"so"
#+windows
"dll"
#+darwin
"dylib"
#-(or windows unix darwin)
(error "Unrecognized system"))
(defun default-shared-adapter-library-name ()
(format nil "adapter.~A" (shared-extension-name)))
(defmethod expand-adapter-routines ((this dynamic-adapter) wrapper)
(let ((name (wrapper-name-of this))
(shared-library-name (default-shared-adapter-library-name)))
`((defmethod build-adapter ((wrapper-name (eql ',name)) &optional target)
(declare (ignore wrapper-name))
(build-dynamic-adapter ,(standard-of this)
,(adapter-file-of this)
(list ,@(includes-of this))
(merge-pathnames (or target ,shared-library-name)
,(claw.wrapper:merge-wrapper-pathname
"" wrapper))))
(defmethod initialize-adapter ((wrapper-name (eql ',name)))
(declare (ignore wrapper-name))
(%verify-adapter-initialization
(cffi:foreign-funcall ,(library-loader-name name) :int))))))
| null | https://raw.githubusercontent.com/borodust/claw-legacy/3cd4a96fca95eb9e8d5d069426694669f81b2250/src/cffi/c/adapter/dynamic.lisp | lisp | (cl:in-package :claw.cffi.c)
(defgeneric initialize-adapter (library-name))
(defclass dynamic-adapter (adapter) ())
(defun make-dynamic-adapter (wrapper path)
(make-instance 'dynamic-adapter :wrapper wrapper :path path))
(defun load-dynamic-adapter-template ()
(alexandria:read-file-into-string
(asdf:system-relative-pathname :claw/cffi "src/cffi/c/adapter/template/dynamic.c")))
(defun library-loader-name (library-name)
(let* ((library-string (symbol-name library-name))
(c-name (ppcre:regex-replace-all "[^_\\w]+" library-string "_"))
(hex (claw-sha1:sha1-hex
(concatenate 'string
(if-let ((package (symbol-package library-name)))
(package-name package)
"")
(symbol-name library-name)))))
(subseq (format nil "~A~(~A~)_loader_~A" +adapted-function-prefix+ c-name hex) 0 64)))
(defun preprocess-dynamic-adapter-template (includes
loader-name
function-types
function-pointers
function-pointers-init
function-definitions)
(preprocess-template (load-dynamic-adapter-template)
"timestamp" (get-timestamp)
"includes" includes
"loader-name" loader-name
"function-types" function-types
"function-pointers" function-pointers
"function-pointers-init" function-pointers-init
"function-definitions" function-definitions))
(defmethod generate-adapter-file ((this dynamic-adapter))
(when (%adapter-needs-rebuilding-p this)
(ensure-directories-exist (uiop:pathname-directory-pathname (adapter-file-of this)))
(with-output-to-file (output (adapter-file-of this) :if-exists :supersede)
(let* ((functions (functions-of this))
(definitions
(%generate-adapted-function-definitions functions
+adapted-variable-prefix+)))
(flet ((function-types ()
(with-output-to-string (out)
(loop for function in functions
do (format out "~&")
(%generate-function-type function out))))
(function-variables ()
(with-output-to-string (out)
(loop for function in functions
do (format out "~&")
(%generate-function-variable function out))))
(function-variable-inits ()
(with-output-to-string (out)
(loop for function in functions
do (format out "~&")
(%generate-function-variable-init function out))))
(header-files ()
(format nil "~{#include \"~A\"~^~%~}" (headers-of this))))
(format output "~A"
(preprocess-dynamic-adapter-template
(header-files)
(library-loader-name (wrapper-name-of this))
(function-types)
(function-variables)
(function-variable-inits)
definitions)))))))
(defun build-dynamic-adapter (standard adapter-file includes target-file &key pedantic)
(uiop:run-program (append (list "gcc" "-shared" (namestring adapter-file))
(when standard
(list (format nil "-std=~A" standard)))
(when pedantic
(list "-pedantic"))
(list "-O3" "-fPIC")
(loop for directory in includes
collect (format nil "-I~A"
(namestring directory)))
(list "-o" (namestring target-file)))
:output *standard-output*
:error-output *debug-io*))
(defun %verify-adapter-initialization (result)
(unless (zerop result)
(error "Failed to initialize adapater")))
(defun shared-extension-name ()
#+(and unix (not darwin))
"so"
#+windows
"dll"
#+darwin
"dylib"
#-(or windows unix darwin)
(error "Unrecognized system"))
(defun default-shared-adapter-library-name ()
(format nil "adapter.~A" (shared-extension-name)))
(defmethod expand-adapter-routines ((this dynamic-adapter) wrapper)
(let ((name (wrapper-name-of this))
(shared-library-name (default-shared-adapter-library-name)))
`((defmethod build-adapter ((wrapper-name (eql ',name)) &optional target)
(declare (ignore wrapper-name))
(build-dynamic-adapter ,(standard-of this)
,(adapter-file-of this)
(list ,@(includes-of this))
(merge-pathnames (or target ,shared-library-name)
,(claw.wrapper:merge-wrapper-pathname
"" wrapper))))
(defmethod initialize-adapter ((wrapper-name (eql ',name)))
(declare (ignore wrapper-name))
(%verify-adapter-initialization
(cffi:foreign-funcall ,(library-loader-name name) :int))))))
|
|
52488a7d2af2a248a03fecf37669da6c1c530be8fa2de5094e87e7c6a9914d4f | 8c6794b6/guile-tjit | program.scm | ;;; Guile VM program functions
Copyright ( C ) 2001 , 2009 , 2010 , 2013 , 2014 Free Software Foundation , Inc.
;;;
;;; 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 3 of the License , or ( at your option ) any later version .
;;;
;;; 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. , 51 Franklin Street , Fifth Floor , Boston , USA
;;; Code:
(define-module (system vm program)
#:use-module (ice-9 match)
#:use-module (system vm debug)
#:use-module (rnrs bytevectors)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:export (source:addr source:line source:column source:file
source:line-for-user
program-sources program-sources-pre-retire program-source
program-address-range
program-arities program-arity arity:start arity:end
arity:nreq arity:nopt arity:rest? arity:kw arity:allow-other-keys?
program-arguments-alist program-arguments-alists
program-lambda-list
program? program-code
program-free-variables
program-num-free-variables
program-free-variable-ref program-free-variable-set!
print-program
primitive-code?))
(load-extension (string-append "libguile-" (effective-version))
"scm_init_programs")
;; These procedures are called by programs.c.
(define (program-name program)
(and=> (find-program-debug-info (program-code program))
program-debug-info-name))
(define (program-documentation program)
(find-program-docstring (program-code program)))
(define (program-minimum-arity program)
(find-program-minimum-arity (program-code program)))
(define (program-properties program)
(find-program-properties (program-code program)))
(define (source:addr source)
(car source))
(define (source:file source)
(cadr source))
(define (source:line source)
(caddr source))
(define (source:column source)
(cdddr source))
Lines are zero - indexed inside , but users expect them to be
one - indexed . Columns , on the other hand , are zero - indexed to both . Go
;; figure.
(define (source:line-for-user source)
(1+ (source:line source)))
(define (source-for-addr addr)
(and=> (find-source-for-addr addr)
(lambda (source)
;; FIXME: absolute or relative address?
(cons* 0
(source-file source)
(source-line source)
(source-column source)))))
(define (program-sources proc)
(map (lambda (source)
(cons* (- (source-post-pc source) (program-code proc))
(source-file source)
(source-line source)
(source-column source)))
(find-program-sources (program-code proc))))
(define* (program-source proc ip #:optional (sources (program-sources proc)))
(let lp ((source #f) (sources sources))
(match sources
(() source)
(((and s (pc . _)) . sources)
(if (<= pc ip)
(lp s sources)
source)))))
(define (program-address-range program)
"Return the start and end addresses of @var{program}'s code, as a pair
of integers."
(let ((pdi (find-program-debug-info (program-code program))))
(and pdi
(cons (program-debug-info-addr pdi)
(+ (program-debug-info-addr pdi)
(program-debug-info-size pdi))))))
;; Source information could in theory be correlated with the ip of the
instruction , or the ip just after the instruction is retired .
;; does the latter, to make backtraces easy -- an error produced while
;; running an opcode always happens after it has retired its arguments.
;;
;; But for breakpoints and such, we need the ip before the instruction
;; is retired -- before it has had a chance to do anything. So here we
;; change from the post-retire addresses given by program-sources to
;; pre-retire addresses.
;;
(define (program-sources-pre-retire proc)
(map (lambda (source)
(cons* (- (source-pre-pc source) (program-code proc))
(source-file source)
(source-line source)
(source-column source)))
(find-program-sources (program-code proc))))
(define (arity:start a)
(match a ((start end . _) start) (_ (error "bad arity" a))))
(define (arity:end a)
(match a ((start end . _) end) (_ (error "bad arity" a))))
(define (arity:nreq a)
(match a ((_ _ nreq . _) nreq) (_ 0)))
(define (arity:nopt a)
(match a ((_ _ nreq nopt . _) nopt) (_ 0)))
(define (arity:rest? a)
(match a ((_ _ nreq nopt rest? . _) rest?) (_ #f)))
(define (arity:kw a)
(match a ((_ _ nreq nopt rest? (_ . kw)) kw) (_ '())))
(define (arity:allow-other-keys? a)
(match a ((_ _ nreq nopt rest? (aok . kw)) aok) (_ #f)))
(define (program-arity prog ip)
(let ((arities (program-arities prog)))
(and arities
(let lp ((arities arities))
(cond ((null? arities) #f)
take the first one
((and (< (arity:start (car arities)) ip)
(<= ip (arity:end (car arities))))
(car arities))
(else (lp (cdr arities))))))))
(define (arglist->arguments-alist arglist)
(match arglist
((req opt keyword allow-other-keys? rest . extents)
`((required . ,req)
(optional . ,opt)
(keyword . ,keyword)
(allow-other-keys? . ,allow-other-keys?)
(rest . ,rest)
(extents . ,extents)))
(_ #f)))
(define* (arity->arguments-alist prog arity
#:optional
(make-placeholder
(lambda (i) (string->symbol "_"))))
(let lp ((nreq (arity:nreq arity)) (req '())
(nopt (arity:nopt arity)) (opt '())
(rest? (arity:rest? arity)) (rest #f)
(n 0))
(cond
((< 0 nreq)
(lp (1- nreq) (cons (make-placeholder n) req)
nopt opt rest? rest (1+ n)))
((< 0 nopt)
(lp nreq req
(1- nopt) (cons (make-placeholder n) opt)
rest? rest (1+ n)))
(rest?
(lp nreq req nopt opt
#f (make-placeholder (+ n (length (arity:kw arity))))
(1+ n)))
(else
`((required . ,(reverse req))
(optional . ,(reverse opt))
(keyword . ,(arity:kw arity))
(allow-other-keys? . ,(arity:allow-other-keys? arity))
(rest . ,rest))))))
;; the name "program-arguments" is taken by features.c...
(define* (program-arguments-alist prog #:optional ip)
"Returns the signature of the given procedure in the form of an association list."
(let ((code (program-code prog)))
(cond
((primitive-code? code)
(match (procedure-minimum-arity prog)
(#f #f)
((nreq nopt rest?)
(let ((start (primitive-call-ip prog)))
;; Assume that there is only one IP for the call.
(and (or (not ip) (= start ip))
(arity->arguments-alist
prog
(list 0 0 nreq nopt rest? '(#f . ()))))))))
(else
(or-map (lambda (arity)
(and (or (not ip)
(and (<= (arity-low-pc arity) ip)
(< ip (arity-high-pc arity))))
(arity-arguments-alist arity)))
(or (find-program-arities code) '()))))))
(define* (program-lambda-list prog #:optional ip)
"Returns the signature of the given procedure in the form of an argument list."
(and=> (program-arguments-alist prog ip) arguments-alist->lambda-list))
(define (arguments-alist->lambda-list arguments-alist)
(let ((req (or (assq-ref arguments-alist 'required) '()))
(opt (or (assq-ref arguments-alist 'optional) '()))
(key (map keyword->symbol
(map car (or (assq-ref arguments-alist 'keyword) '()))))
(rest (or (assq-ref arguments-alist 'rest) '())))
`(,@req
,@(if (pair? opt) (cons #:optional opt) '())
,@(if (pair? key) (cons #:key key) '())
. ,rest)))
(define (program-free-variables prog)
"Return the list of free variables of PROG."
(let ((count (program-num-free-variables prog)))
(unfold (lambda (i) (>= i count))
(cut program-free-variable-ref prog <>)
1+
0)))
(define (program-arguments-alists prog)
"Returns all arities of the given procedure, as a list of association
lists."
(define (fallback)
(match (procedure-minimum-arity prog)
(#f '())
((nreq nopt rest?)
(list
(arity->arguments-alist
prog
(list 0 0 nreq nopt rest? '(#f . ())))))))
(let* ((code (program-code prog))
(arities (and (not (primitive-code? code))
(find-program-arities code))))
(if arities
(map arity-arguments-alist arities)
(fallback))))
(define* (print-program #:optional program (port (current-output-port))
#:key (addr (program-code program))
(always-print-addr? #f) (never-print-addr? #f)
(always-print-source? #f) (never-print-source? #f)
(name-only? #f) (print-formals? #t))
(let* ((pdi (find-program-debug-info addr))
;; It could be the procedure had its name property set via the
;; procedure property interface.
(name (or (and program (procedure-name program))
(program-debug-info-name pdi)))
(source (match (find-program-sources addr)
(() #f)
((source . _) source)))
(formals (if program
(program-arguments-alists program)
(let ((arities (find-program-arities addr)))
(if arities
(map arity-arguments-alist arities)
'())))))
(define (hex n)
(number->string n 16))
(cond
((and name-only? name)
(format port "~a" name))
(else
(format port "#<procedure")
(format port " ~a"
(or name
(and program (hex (object-address program)))
(if never-print-addr?
""
(string-append "@" (hex addr)))))
(when (and always-print-addr? (not never-print-addr?))
(unless (and (not name) (not program))
(format port " @~a" (hex addr))))
(when (and source (not never-print-source?)
(or always-print-source? (not name)))
(format port " at ~a:~a:~a"
(or (source-file source) "<unknown port>")
(source-line-for-user source)
(source-column source)))
(unless (or (null? formals) (not print-formals?))
(format port "~a"
(string-append
" " (string-join (map (lambda (a)
(object->string
(arguments-alist->lambda-list a)))
formals)
" | "))))
(format port ">")))))
(define (write-program prog port)
(print-program prog port))
| null | https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/system/vm/program.scm | scheme | Guile VM program functions
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
either
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.
License along with this library; if not, write to the Free Software
Code:
These procedures are called by programs.c.
figure.
FIXME: absolute or relative address?
Source information could in theory be correlated with the ip of the
does the latter, to make backtraces easy -- an error produced while
running an opcode always happens after it has retired its arguments.
But for breakpoints and such, we need the ip before the instruction
is retired -- before it has had a chance to do anything. So here we
change from the post-retire addresses given by program-sources to
pre-retire addresses.
the name "program-arguments" is taken by features.c...
Assume that there is only one IP for the call.
It could be the procedure had its name property set via the
procedure property interface. |
Copyright ( C ) 2001 , 2009 , 2010 , 2013 , 2014 Free Software Foundation , Inc.
version 3 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
(define-module (system vm program)
#:use-module (ice-9 match)
#:use-module (system vm debug)
#:use-module (rnrs bytevectors)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:export (source:addr source:line source:column source:file
source:line-for-user
program-sources program-sources-pre-retire program-source
program-address-range
program-arities program-arity arity:start arity:end
arity:nreq arity:nopt arity:rest? arity:kw arity:allow-other-keys?
program-arguments-alist program-arguments-alists
program-lambda-list
program? program-code
program-free-variables
program-num-free-variables
program-free-variable-ref program-free-variable-set!
print-program
primitive-code?))
(load-extension (string-append "libguile-" (effective-version))
"scm_init_programs")
(define (program-name program)
(and=> (find-program-debug-info (program-code program))
program-debug-info-name))
(define (program-documentation program)
(find-program-docstring (program-code program)))
(define (program-minimum-arity program)
(find-program-minimum-arity (program-code program)))
(define (program-properties program)
(find-program-properties (program-code program)))
(define (source:addr source)
(car source))
(define (source:file source)
(cadr source))
(define (source:line source)
(caddr source))
(define (source:column source)
(cdddr source))
Lines are zero - indexed inside , but users expect them to be
one - indexed . Columns , on the other hand , are zero - indexed to both . Go
(define (source:line-for-user source)
(1+ (source:line source)))
(define (source-for-addr addr)
(and=> (find-source-for-addr addr)
(lambda (source)
(cons* 0
(source-file source)
(source-line source)
(source-column source)))))
(define (program-sources proc)
(map (lambda (source)
(cons* (- (source-post-pc source) (program-code proc))
(source-file source)
(source-line source)
(source-column source)))
(find-program-sources (program-code proc))))
(define* (program-source proc ip #:optional (sources (program-sources proc)))
(let lp ((source #f) (sources sources))
(match sources
(() source)
(((and s (pc . _)) . sources)
(if (<= pc ip)
(lp s sources)
source)))))
(define (program-address-range program)
"Return the start and end addresses of @var{program}'s code, as a pair
of integers."
(let ((pdi (find-program-debug-info (program-code program))))
(and pdi
(cons (program-debug-info-addr pdi)
(+ (program-debug-info-addr pdi)
(program-debug-info-size pdi))))))
instruction , or the ip just after the instruction is retired .
(define (program-sources-pre-retire proc)
(map (lambda (source)
(cons* (- (source-pre-pc source) (program-code proc))
(source-file source)
(source-line source)
(source-column source)))
(find-program-sources (program-code proc))))
(define (arity:start a)
(match a ((start end . _) start) (_ (error "bad arity" a))))
(define (arity:end a)
(match a ((start end . _) end) (_ (error "bad arity" a))))
(define (arity:nreq a)
(match a ((_ _ nreq . _) nreq) (_ 0)))
(define (arity:nopt a)
(match a ((_ _ nreq nopt . _) nopt) (_ 0)))
(define (arity:rest? a)
(match a ((_ _ nreq nopt rest? . _) rest?) (_ #f)))
(define (arity:kw a)
(match a ((_ _ nreq nopt rest? (_ . kw)) kw) (_ '())))
(define (arity:allow-other-keys? a)
(match a ((_ _ nreq nopt rest? (aok . kw)) aok) (_ #f)))
(define (program-arity prog ip)
(let ((arities (program-arities prog)))
(and arities
(let lp ((arities arities))
(cond ((null? arities) #f)
take the first one
((and (< (arity:start (car arities)) ip)
(<= ip (arity:end (car arities))))
(car arities))
(else (lp (cdr arities))))))))
(define (arglist->arguments-alist arglist)
(match arglist
((req opt keyword allow-other-keys? rest . extents)
`((required . ,req)
(optional . ,opt)
(keyword . ,keyword)
(allow-other-keys? . ,allow-other-keys?)
(rest . ,rest)
(extents . ,extents)))
(_ #f)))
(define* (arity->arguments-alist prog arity
#:optional
(make-placeholder
(lambda (i) (string->symbol "_"))))
(let lp ((nreq (arity:nreq arity)) (req '())
(nopt (arity:nopt arity)) (opt '())
(rest? (arity:rest? arity)) (rest #f)
(n 0))
(cond
((< 0 nreq)
(lp (1- nreq) (cons (make-placeholder n) req)
nopt opt rest? rest (1+ n)))
((< 0 nopt)
(lp nreq req
(1- nopt) (cons (make-placeholder n) opt)
rest? rest (1+ n)))
(rest?
(lp nreq req nopt opt
#f (make-placeholder (+ n (length (arity:kw arity))))
(1+ n)))
(else
`((required . ,(reverse req))
(optional . ,(reverse opt))
(keyword . ,(arity:kw arity))
(allow-other-keys? . ,(arity:allow-other-keys? arity))
(rest . ,rest))))))
(define* (program-arguments-alist prog #:optional ip)
"Returns the signature of the given procedure in the form of an association list."
(let ((code (program-code prog)))
(cond
((primitive-code? code)
(match (procedure-minimum-arity prog)
(#f #f)
((nreq nopt rest?)
(let ((start (primitive-call-ip prog)))
(and (or (not ip) (= start ip))
(arity->arguments-alist
prog
(list 0 0 nreq nopt rest? '(#f . ()))))))))
(else
(or-map (lambda (arity)
(and (or (not ip)
(and (<= (arity-low-pc arity) ip)
(< ip (arity-high-pc arity))))
(arity-arguments-alist arity)))
(or (find-program-arities code) '()))))))
(define* (program-lambda-list prog #:optional ip)
"Returns the signature of the given procedure in the form of an argument list."
(and=> (program-arguments-alist prog ip) arguments-alist->lambda-list))
(define (arguments-alist->lambda-list arguments-alist)
(let ((req (or (assq-ref arguments-alist 'required) '()))
(opt (or (assq-ref arguments-alist 'optional) '()))
(key (map keyword->symbol
(map car (or (assq-ref arguments-alist 'keyword) '()))))
(rest (or (assq-ref arguments-alist 'rest) '())))
`(,@req
,@(if (pair? opt) (cons #:optional opt) '())
,@(if (pair? key) (cons #:key key) '())
. ,rest)))
(define (program-free-variables prog)
"Return the list of free variables of PROG."
(let ((count (program-num-free-variables prog)))
(unfold (lambda (i) (>= i count))
(cut program-free-variable-ref prog <>)
1+
0)))
(define (program-arguments-alists prog)
"Returns all arities of the given procedure, as a list of association
lists."
(define (fallback)
(match (procedure-minimum-arity prog)
(#f '())
((nreq nopt rest?)
(list
(arity->arguments-alist
prog
(list 0 0 nreq nopt rest? '(#f . ())))))))
(let* ((code (program-code prog))
(arities (and (not (primitive-code? code))
(find-program-arities code))))
(if arities
(map arity-arguments-alist arities)
(fallback))))
(define* (print-program #:optional program (port (current-output-port))
#:key (addr (program-code program))
(always-print-addr? #f) (never-print-addr? #f)
(always-print-source? #f) (never-print-source? #f)
(name-only? #f) (print-formals? #t))
(let* ((pdi (find-program-debug-info addr))
(name (or (and program (procedure-name program))
(program-debug-info-name pdi)))
(source (match (find-program-sources addr)
(() #f)
((source . _) source)))
(formals (if program
(program-arguments-alists program)
(let ((arities (find-program-arities addr)))
(if arities
(map arity-arguments-alist arities)
'())))))
(define (hex n)
(number->string n 16))
(cond
((and name-only? name)
(format port "~a" name))
(else
(format port "#<procedure")
(format port " ~a"
(or name
(and program (hex (object-address program)))
(if never-print-addr?
""
(string-append "@" (hex addr)))))
(when (and always-print-addr? (not never-print-addr?))
(unless (and (not name) (not program))
(format port " @~a" (hex addr))))
(when (and source (not never-print-source?)
(or always-print-source? (not name)))
(format port " at ~a:~a:~a"
(or (source-file source) "<unknown port>")
(source-line-for-user source)
(source-column source)))
(unless (or (null? formals) (not print-formals?))
(format port "~a"
(string-append
" " (string-join (map (lambda (a)
(object->string
(arguments-alist->lambda-list a)))
formals)
" | "))))
(format port ">")))))
(define (write-program prog port)
(print-program prog port))
|
401db778c133c4e4776b5528548b31516fa88661424433e1ca86df273bfbc45c | LexiFi/csml | csml_iface.mli | This file is released under the terms of an MIT - like license .
(* See the attached LICENSE file. *)
Copyright 2016 by LexiFi .
(** Csml.*)
val csharp_available: bool ref
(** Is the .Net runtime available in the current process. *)
type cshandle
exception Csharp_exception of string * string * cshandle
(** A C# exception wrapped as an OCaml exception.
The arguments are: the exception's type name, the exception's message,
the exception value itself. *)
class csval: cshandle ->
object
method cshandle: cshandle
end
* Base class for ML objects that wraps C # values
val loadfile: string -> unit
(** Dynamically load a plugin. If the OCaml runtime is running in native code
then the extension of the filename is replaced by [.cmxs]. *)
* { 2 Internal use only }
val find_cs2ml_callback: int -> string -> string -> 'a -> 'b
val release_cs_value: Obj.t ref
val resolve_cs2ml: (int -> string -> Obj.t) ref
val ml2cs_register: string -> 'a -> unit
val ml2cs_registered: string -> 'a
val notify_ml_stub: string -> unit
val ml_stub_available: string -> bool
val csml_pop: Obj.t ref
| null | https://raw.githubusercontent.com/LexiFi/csml/1bdffc60b937b0cd23730589b191940cd1861640/src/csml_iface.mli | ocaml | See the attached LICENSE file.
* Csml.
* Is the .Net runtime available in the current process.
* A C# exception wrapped as an OCaml exception.
The arguments are: the exception's type name, the exception's message,
the exception value itself.
* Dynamically load a plugin. If the OCaml runtime is running in native code
then the extension of the filename is replaced by [.cmxs]. | This file is released under the terms of an MIT - like license .
Copyright 2016 by LexiFi .
val csharp_available: bool ref
type cshandle
exception Csharp_exception of string * string * cshandle
class csval: cshandle ->
object
method cshandle: cshandle
end
* Base class for ML objects that wraps C # values
val loadfile: string -> unit
* { 2 Internal use only }
val find_cs2ml_callback: int -> string -> string -> 'a -> 'b
val release_cs_value: Obj.t ref
val resolve_cs2ml: (int -> string -> Obj.t) ref
val ml2cs_register: string -> 'a -> unit
val ml2cs_registered: string -> 'a
val notify_ml_stub: string -> unit
val ml_stub_available: string -> bool
val csml_pop: Obj.t ref
|
dbf74f00470959614e9d173ca7bcd975482d69a0dfcd872b8f52a4d2143a09a2 | dparis/gen-phzr | quartic.cljs | (ns phzr.easing.quartic
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser]))
(defn in
"Quartic ease-in.
Parameters:
* quartic (Phaser.Easing.Quartic) - Targeted instance for method
* k (number) - The value to be tweened.
Returns: number - The tweened value."
([quartic k]
(phaser->clj
(.In quartic
(clj->phaser k)))))
(defn in-out
"Quartic ease-in/out.
Parameters:
* quartic (Phaser.Easing.Quartic) - Targeted instance for method
* k (number) - The value to be tweened.
Returns: number - The tweened value."
([quartic k]
(phaser->clj
(.InOut quartic
(clj->phaser k)))))
(defn out
"Quartic ease-out.
Parameters:
* quartic (Phaser.Easing.Quartic) - Targeted instance for method
* k (number) - The value to be tweened.
Returns: number - The tweened value."
([quartic k]
(phaser->clj
(.Out quartic
(clj->phaser k))))) | null | https://raw.githubusercontent.com/dparis/gen-phzr/e4c7b272e225ac343718dc15fc84f5f0dce68023/out/easing/quartic.cljs | clojure | (ns phzr.easing.quartic
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser]))
(defn in
"Quartic ease-in.
Parameters:
* quartic (Phaser.Easing.Quartic) - Targeted instance for method
* k (number) - The value to be tweened.
Returns: number - The tweened value."
([quartic k]
(phaser->clj
(.In quartic
(clj->phaser k)))))
(defn in-out
"Quartic ease-in/out.
Parameters:
* quartic (Phaser.Easing.Quartic) - Targeted instance for method
* k (number) - The value to be tweened.
Returns: number - The tweened value."
([quartic k]
(phaser->clj
(.InOut quartic
(clj->phaser k)))))
(defn out
"Quartic ease-out.
Parameters:
* quartic (Phaser.Easing.Quartic) - Targeted instance for method
* k (number) - The value to be tweened.
Returns: number - The tweened value."
([quartic k]
(phaser->clj
(.Out quartic
(clj->phaser k))))) |
|
7ae55bac6d4cbc81636a23c8a5b6162f9b71d98cedb36548c03ef17ad45018f9 | andrewthad/sockets | Indefinite.hs | # language BangPatterns #
# language LambdaCase #
{-# language MultiWayIf #-}
module Datagram.Send.Indefinite
( send
, attemptSend
) where
import Control.Concurrent.STM (TVar)
import Datagram.Send (Peer)
import Foreign.C.Error (Errno(..), eAGAIN, eWOULDBLOCK, eACCES, eMSGSIZE)
import Foreign.C.Error (eCONNREFUSED,eNOTCONN)
import Foreign.C.Types (CSize)
import Socket.Error (die)
import Socket.EventManager (Token)
import Socket.Datagram (SendException(..))
import Socket.Buffer (Buffer)
import Socket.Interrupt (Interrupt,Intr,wait,tokenToDatagramSendException)
import System.Posix.Types (Fd)
import qualified Foreign.C.Error.Describe as D
import qualified Socket.EventManager as EM
import qualified Socket.Buffer as Buffer
import qualified Datagram.Send as Send
-- Send the entirely of the buffer, making a single call to
-- POSIX @send@. This is used for datagram sockets. We cannot use a
-- Socket newtype here since destined and undestined sockets
-- use different newtypes.
send ::
Interrupt
-> Peer
-> Fd
-> Buffer
-> IO (Either (SendException Intr) ())
send !intr !dst !sock !buf = do
let !mngr = EM.manager
tv <- EM.writer mngr sock
token0 <- wait intr tv
case tokenToDatagramSendException token0 of
Left err -> pure (Left err)
Right _ -> sendLoop intr dst sock tv token0 buf
-- Never blocks.
attemptSend ::
Peer
-> Fd
-> Buffer
-> IO (Either (SendException Intr) Bool)
attemptSend !dst !sock !buf = Send.send dst sock buf >>= \case
Left e ->
if | e == eAGAIN || e == eWOULDBLOCK -> pure (Right False)
| e == eACCES -> pure (Left SendBroadcasted)
| e == eCONNREFUSED -> pure (Left SendConnectionRefused)
| e == eNOTCONN -> pure (Left SendConnectionRefused)
| e == eMSGSIZE -> pure (Left SendMessageSize)
| otherwise -> die ("Socket.Datagram.send: " ++ describeErrorCode e)
Right sz -> if csizeToInt sz == Buffer.length buf
then pure $! Right True
else pure $! Left $! SendTruncated $! csizeToInt sz
sendLoop ::
Interrupt -> Peer -> Fd -> TVar Token -> Token
-> Buffer -> IO (Either (SendException Intr) ())
sendLoop !intr !dst !sock !tv !old !buf =
Send.send dst sock buf >>= \case
Left e ->
if | e == eAGAIN || e == eWOULDBLOCK -> do
EM.unready old tv
new <- wait intr tv
case tokenToDatagramSendException new of
Left err -> pure (Left err)
Right _ -> sendLoop intr dst sock tv new buf
| e == eACCES -> pure (Left SendBroadcasted)
| e == eCONNREFUSED -> pure (Left SendConnectionRefused)
| e == eNOTCONN -> pure (Left SendConnectionRefused)
| e == eMSGSIZE -> pure (Left SendMessageSize)
| otherwise -> die ("Socket.Datagram.send: " ++ describeErrorCode e)
Right sz -> if csizeToInt sz == Buffer.length buf
then pure $! Right ()
else pure $! Left $! SendTruncated $! csizeToInt sz
csizeToInt :: CSize -> Int
csizeToInt = fromIntegral
describeErrorCode :: Errno -> String
describeErrorCode err@(Errno e) = "error code " ++ D.string err ++ " (" ++ show e ++ ")"
| null | https://raw.githubusercontent.com/andrewthad/sockets/90d314bd2ec71b248a90da6ad964c679f75cfcca/src-datagram-send/Datagram/Send/Indefinite.hs | haskell | # language MultiWayIf #
Send the entirely of the buffer, making a single call to
POSIX @send@. This is used for datagram sockets. We cannot use a
Socket newtype here since destined and undestined sockets
use different newtypes.
Never blocks. | # language BangPatterns #
# language LambdaCase #
module Datagram.Send.Indefinite
( send
, attemptSend
) where
import Control.Concurrent.STM (TVar)
import Datagram.Send (Peer)
import Foreign.C.Error (Errno(..), eAGAIN, eWOULDBLOCK, eACCES, eMSGSIZE)
import Foreign.C.Error (eCONNREFUSED,eNOTCONN)
import Foreign.C.Types (CSize)
import Socket.Error (die)
import Socket.EventManager (Token)
import Socket.Datagram (SendException(..))
import Socket.Buffer (Buffer)
import Socket.Interrupt (Interrupt,Intr,wait,tokenToDatagramSendException)
import System.Posix.Types (Fd)
import qualified Foreign.C.Error.Describe as D
import qualified Socket.EventManager as EM
import qualified Socket.Buffer as Buffer
import qualified Datagram.Send as Send
send ::
Interrupt
-> Peer
-> Fd
-> Buffer
-> IO (Either (SendException Intr) ())
send !intr !dst !sock !buf = do
let !mngr = EM.manager
tv <- EM.writer mngr sock
token0 <- wait intr tv
case tokenToDatagramSendException token0 of
Left err -> pure (Left err)
Right _ -> sendLoop intr dst sock tv token0 buf
attemptSend ::
Peer
-> Fd
-> Buffer
-> IO (Either (SendException Intr) Bool)
attemptSend !dst !sock !buf = Send.send dst sock buf >>= \case
Left e ->
if | e == eAGAIN || e == eWOULDBLOCK -> pure (Right False)
| e == eACCES -> pure (Left SendBroadcasted)
| e == eCONNREFUSED -> pure (Left SendConnectionRefused)
| e == eNOTCONN -> pure (Left SendConnectionRefused)
| e == eMSGSIZE -> pure (Left SendMessageSize)
| otherwise -> die ("Socket.Datagram.send: " ++ describeErrorCode e)
Right sz -> if csizeToInt sz == Buffer.length buf
then pure $! Right True
else pure $! Left $! SendTruncated $! csizeToInt sz
sendLoop ::
Interrupt -> Peer -> Fd -> TVar Token -> Token
-> Buffer -> IO (Either (SendException Intr) ())
sendLoop !intr !dst !sock !tv !old !buf =
Send.send dst sock buf >>= \case
Left e ->
if | e == eAGAIN || e == eWOULDBLOCK -> do
EM.unready old tv
new <- wait intr tv
case tokenToDatagramSendException new of
Left err -> pure (Left err)
Right _ -> sendLoop intr dst sock tv new buf
| e == eACCES -> pure (Left SendBroadcasted)
| e == eCONNREFUSED -> pure (Left SendConnectionRefused)
| e == eNOTCONN -> pure (Left SendConnectionRefused)
| e == eMSGSIZE -> pure (Left SendMessageSize)
| otherwise -> die ("Socket.Datagram.send: " ++ describeErrorCode e)
Right sz -> if csizeToInt sz == Buffer.length buf
then pure $! Right ()
else pure $! Left $! SendTruncated $! csizeToInt sz
csizeToInt :: CSize -> Int
csizeToInt = fromIntegral
describeErrorCode :: Errno -> String
describeErrorCode err@(Errno e) = "error code " ++ D.string err ++ " (" ++ show e ++ ")"
|
a43231fa2c90944de289fe3d0df99184cd19b3df1d06ce2cc6ddd477e557c69a | coq/coq | tok.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
* The type of token for the Coq lexer and parser
let string_equal (s1 : string) s2 = s1 = s2
type 'c p =
| PKEYWORD : string -> string p
| PPATTERNIDENT : string option -> string p
| PIDENT : string option -> string p
| PFIELD : string option -> string p
| PNUMBER : NumTok.Unsigned.t option -> NumTok.Unsigned.t p
| PSTRING : string option -> string p
| PLEFTQMARK : unit p
| PBULLET : string option -> string p
| PQUOTATION : string -> string p
| PEOI : unit p
let pattern_strings : type c. c p -> string * string option =
function
| PKEYWORD s -> "", Some s
| PPATTERNIDENT s -> "PATTERNIDENT", s
| PIDENT s -> "IDENT", s
| PFIELD s -> "FIELD", s
| PNUMBER None -> "NUMBER", None
| PNUMBER (Some n) -> "NUMBER", Some (NumTok.Unsigned.sprint n)
| PSTRING s -> "STRING", s
| PLEFTQMARK -> "LEFTQMARK", None
| PBULLET s -> "BULLET", s
| PQUOTATION lbl -> "QUOTATION", Some lbl
| PEOI -> "EOI", None
type t =
| KEYWORD of string
| PATTERNIDENT of string
| IDENT of string
| FIELD of string
| NUMBER of NumTok.Unsigned.t
| STRING of string
| LEFTQMARK
| BULLET of string
| QUOTATION of string * string
| EOI
let equal_p (type a b) (t1 : a p) (t2 : b p) : (a, b) Util.eq option =
let streq s1 s2 = match s1, s2 with None, None -> true
| Some s1, Some s2 -> string_equal s1 s2 | _ -> false in
match t1, t2 with
| PIDENT s1, PIDENT s2 when streq s1 s2 -> Some Util.Refl
| PKEYWORD s1, PKEYWORD s2 when string_equal s1 s2 -> Some Util.Refl
| PIDENT (Some s1), PKEYWORD s2 when string_equal s1 s2 -> Some Util.Refl
| PKEYWORD s1, PIDENT (Some s2) when string_equal s1 s2 -> Some Util.Refl
| PPATTERNIDENT s1, PPATTERNIDENT s2 when streq s1 s2 -> Some Util.Refl
| PFIELD s1, PFIELD s2 when streq s1 s2 -> Some Util.Refl
| PNUMBER None, PNUMBER None -> Some Util.Refl
| PNUMBER (Some n1), PNUMBER (Some n2) when NumTok.Unsigned.equal n1 n2 -> Some Util.Refl
| PSTRING s1, PSTRING s2 when streq s1 s2 -> Some Util.Refl
| PLEFTQMARK, PLEFTQMARK -> Some Util.Refl
| PBULLET s1, PBULLET s2 when streq s1 s2 -> Some Util.Refl
| PQUOTATION s1, PQUOTATION s2 when string_equal s1 s2 -> Some Util.Refl
| PEOI, PEOI -> Some Util.Refl
| _ -> None
let equal t1 t2 = match t1, t2 with
| IDENT s1, KEYWORD s2 -> string_equal s1 s2
| KEYWORD s1, KEYWORD s2 -> string_equal s1 s2
| PATTERNIDENT s1, PATTERNIDENT s2 -> string_equal s1 s2
| IDENT s1, IDENT s2 -> string_equal s1 s2
| FIELD s1, FIELD s2 -> string_equal s1 s2
| NUMBER n1, NUMBER n2 -> NumTok.Unsigned.equal n1 n2
| STRING s1, STRING s2 -> string_equal s1 s2
| LEFTQMARK, LEFTQMARK -> true
| BULLET s1, BULLET s2 -> string_equal s1 s2
| EOI, EOI -> true
| QUOTATION(s1,t1), QUOTATION(s2,t2) -> string_equal s1 s2 && string_equal t1 t2
| _ -> false
let token_text : type c. c p -> string = function
| PKEYWORD t -> "'" ^ t ^ "'"
| PIDENT None -> "identifier"
| PIDENT (Some t) -> "'" ^ t ^ "'"
| PNUMBER None -> "number"
| PNUMBER (Some n) -> "'" ^ NumTok.Unsigned.sprint n ^ "'"
| PSTRING None -> "string"
| PSTRING (Some s) -> "STRING \"" ^ s ^ "\""
| PLEFTQMARK -> "LEFTQMARK"
| PEOI -> "end of input"
| PPATTERNIDENT None -> "PATTERNIDENT"
| PPATTERNIDENT (Some s) -> "PATTERNIDENT \"" ^ s ^ "\""
| PFIELD None -> "FIELD"
| PFIELD (Some s) -> "FIELD \"" ^ s ^ "\""
| PBULLET None -> "BULLET"
| PBULLET (Some s) -> "BULLET \"" ^ s ^ "\""
| PQUOTATION lbl -> "QUOTATION \"" ^ lbl ^ "\""
let extract_string diff_mode = function
| KEYWORD s -> s
| IDENT s -> s
| STRING s ->
if diff_mode then
let escape_quotes s =
let len = String.length s in
let buf = Buffer.create len in
for i = 0 to len-1 do
let ch = String.get s i in
Buffer.add_char buf ch;
if ch = '"' then Buffer.add_char buf '"' else ()
done;
Buffer.contents buf
in
"\"" ^ (escape_quotes s) ^ "\""
else s
| PATTERNIDENT s -> s
| FIELD s -> if diff_mode then "." ^ s else s
| NUMBER n -> NumTok.Unsigned.sprint n
| LEFTQMARK -> "?"
| BULLET s -> s
| QUOTATION(_,s) -> s
| EOI -> ""
(* Invariant, txt is "ident" or a well parenthesized "{{....}}" *)
let trim_quotation txt =
let len = String.length txt in
if len = 0 then None, txt
else
let c = txt.[0] in
if c = '(' || c = '[' || c = '{' then
let rec aux n =
if n < len && txt.[n] = c then aux (n+1)
else Some c, String.sub txt n (len - (2*n))
in
aux 0
else None, txt
let match_pattern (type c) (p : c p) : t -> c =
let err () = raise Gramlib.Stream.Failure in
let seq = string_equal in
match p with
| PKEYWORD s -> (function KEYWORD s' when seq s s' -> s' | NUMBER n when seq s (NumTok.Unsigned.sprint n) -> s | _ -> err ())
| PIDENT None -> (function IDENT s' -> s' | _ -> err ())
| PIDENT (Some s) -> (function (IDENT s' | KEYWORD s') when seq s s' -> s' | _ -> err ())
| PPATTERNIDENT None -> (function PATTERNIDENT s -> s | _ -> err ())
| PPATTERNIDENT (Some s) -> (function PATTERNIDENT s' when seq s s' -> s' | _ -> err ())
| PFIELD None -> (function FIELD s -> s | _ -> err ())
| PFIELD (Some s) -> (function FIELD s' when seq s s' -> s' | _ -> err ())
| PNUMBER None -> (function NUMBER s -> s | _ -> err ())
| PNUMBER (Some n) -> let s = NumTok.Unsigned.sprint n in (function NUMBER n' when s = NumTok.Unsigned.sprint n' -> n' | _ -> err ())
| PSTRING None -> (function STRING s -> s | _ -> err ())
| PSTRING (Some s) -> (function STRING s' when seq s s' -> s' | _ -> err ())
| PLEFTQMARK -> (function LEFTQMARK -> () | _ -> err ())
| PBULLET None -> (function BULLET s -> s | _ -> err ())
| PBULLET (Some s) -> (function BULLET s' when seq s s' -> s' | _ -> err ())
| PQUOTATION lbl -> (function QUOTATION(lbl',s') when string_equal lbl lbl' -> s' | _ -> err ())
| PEOI -> (function EOI -> () | _ -> err ())
| null | https://raw.githubusercontent.com/coq/coq/0532b6cd6be0f1386492dda01d52db67a1608011/parsing/tok.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
Invariant, txt is "ident" or a well parenthesized "{{....}}" | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
* The type of token for the Coq lexer and parser
let string_equal (s1 : string) s2 = s1 = s2
type 'c p =
| PKEYWORD : string -> string p
| PPATTERNIDENT : string option -> string p
| PIDENT : string option -> string p
| PFIELD : string option -> string p
| PNUMBER : NumTok.Unsigned.t option -> NumTok.Unsigned.t p
| PSTRING : string option -> string p
| PLEFTQMARK : unit p
| PBULLET : string option -> string p
| PQUOTATION : string -> string p
| PEOI : unit p
let pattern_strings : type c. c p -> string * string option =
function
| PKEYWORD s -> "", Some s
| PPATTERNIDENT s -> "PATTERNIDENT", s
| PIDENT s -> "IDENT", s
| PFIELD s -> "FIELD", s
| PNUMBER None -> "NUMBER", None
| PNUMBER (Some n) -> "NUMBER", Some (NumTok.Unsigned.sprint n)
| PSTRING s -> "STRING", s
| PLEFTQMARK -> "LEFTQMARK", None
| PBULLET s -> "BULLET", s
| PQUOTATION lbl -> "QUOTATION", Some lbl
| PEOI -> "EOI", None
type t =
| KEYWORD of string
| PATTERNIDENT of string
| IDENT of string
| FIELD of string
| NUMBER of NumTok.Unsigned.t
| STRING of string
| LEFTQMARK
| BULLET of string
| QUOTATION of string * string
| EOI
let equal_p (type a b) (t1 : a p) (t2 : b p) : (a, b) Util.eq option =
let streq s1 s2 = match s1, s2 with None, None -> true
| Some s1, Some s2 -> string_equal s1 s2 | _ -> false in
match t1, t2 with
| PIDENT s1, PIDENT s2 when streq s1 s2 -> Some Util.Refl
| PKEYWORD s1, PKEYWORD s2 when string_equal s1 s2 -> Some Util.Refl
| PIDENT (Some s1), PKEYWORD s2 when string_equal s1 s2 -> Some Util.Refl
| PKEYWORD s1, PIDENT (Some s2) when string_equal s1 s2 -> Some Util.Refl
| PPATTERNIDENT s1, PPATTERNIDENT s2 when streq s1 s2 -> Some Util.Refl
| PFIELD s1, PFIELD s2 when streq s1 s2 -> Some Util.Refl
| PNUMBER None, PNUMBER None -> Some Util.Refl
| PNUMBER (Some n1), PNUMBER (Some n2) when NumTok.Unsigned.equal n1 n2 -> Some Util.Refl
| PSTRING s1, PSTRING s2 when streq s1 s2 -> Some Util.Refl
| PLEFTQMARK, PLEFTQMARK -> Some Util.Refl
| PBULLET s1, PBULLET s2 when streq s1 s2 -> Some Util.Refl
| PQUOTATION s1, PQUOTATION s2 when string_equal s1 s2 -> Some Util.Refl
| PEOI, PEOI -> Some Util.Refl
| _ -> None
let equal t1 t2 = match t1, t2 with
| IDENT s1, KEYWORD s2 -> string_equal s1 s2
| KEYWORD s1, KEYWORD s2 -> string_equal s1 s2
| PATTERNIDENT s1, PATTERNIDENT s2 -> string_equal s1 s2
| IDENT s1, IDENT s2 -> string_equal s1 s2
| FIELD s1, FIELD s2 -> string_equal s1 s2
| NUMBER n1, NUMBER n2 -> NumTok.Unsigned.equal n1 n2
| STRING s1, STRING s2 -> string_equal s1 s2
| LEFTQMARK, LEFTQMARK -> true
| BULLET s1, BULLET s2 -> string_equal s1 s2
| EOI, EOI -> true
| QUOTATION(s1,t1), QUOTATION(s2,t2) -> string_equal s1 s2 && string_equal t1 t2
| _ -> false
let token_text : type c. c p -> string = function
| PKEYWORD t -> "'" ^ t ^ "'"
| PIDENT None -> "identifier"
| PIDENT (Some t) -> "'" ^ t ^ "'"
| PNUMBER None -> "number"
| PNUMBER (Some n) -> "'" ^ NumTok.Unsigned.sprint n ^ "'"
| PSTRING None -> "string"
| PSTRING (Some s) -> "STRING \"" ^ s ^ "\""
| PLEFTQMARK -> "LEFTQMARK"
| PEOI -> "end of input"
| PPATTERNIDENT None -> "PATTERNIDENT"
| PPATTERNIDENT (Some s) -> "PATTERNIDENT \"" ^ s ^ "\""
| PFIELD None -> "FIELD"
| PFIELD (Some s) -> "FIELD \"" ^ s ^ "\""
| PBULLET None -> "BULLET"
| PBULLET (Some s) -> "BULLET \"" ^ s ^ "\""
| PQUOTATION lbl -> "QUOTATION \"" ^ lbl ^ "\""
let extract_string diff_mode = function
| KEYWORD s -> s
| IDENT s -> s
| STRING s ->
if diff_mode then
let escape_quotes s =
let len = String.length s in
let buf = Buffer.create len in
for i = 0 to len-1 do
let ch = String.get s i in
Buffer.add_char buf ch;
if ch = '"' then Buffer.add_char buf '"' else ()
done;
Buffer.contents buf
in
"\"" ^ (escape_quotes s) ^ "\""
else s
| PATTERNIDENT s -> s
| FIELD s -> if diff_mode then "." ^ s else s
| NUMBER n -> NumTok.Unsigned.sprint n
| LEFTQMARK -> "?"
| BULLET s -> s
| QUOTATION(_,s) -> s
| EOI -> ""
let trim_quotation txt =
let len = String.length txt in
if len = 0 then None, txt
else
let c = txt.[0] in
if c = '(' || c = '[' || c = '{' then
let rec aux n =
if n < len && txt.[n] = c then aux (n+1)
else Some c, String.sub txt n (len - (2*n))
in
aux 0
else None, txt
let match_pattern (type c) (p : c p) : t -> c =
let err () = raise Gramlib.Stream.Failure in
let seq = string_equal in
match p with
| PKEYWORD s -> (function KEYWORD s' when seq s s' -> s' | NUMBER n when seq s (NumTok.Unsigned.sprint n) -> s | _ -> err ())
| PIDENT None -> (function IDENT s' -> s' | _ -> err ())
| PIDENT (Some s) -> (function (IDENT s' | KEYWORD s') when seq s s' -> s' | _ -> err ())
| PPATTERNIDENT None -> (function PATTERNIDENT s -> s | _ -> err ())
| PPATTERNIDENT (Some s) -> (function PATTERNIDENT s' when seq s s' -> s' | _ -> err ())
| PFIELD None -> (function FIELD s -> s | _ -> err ())
| PFIELD (Some s) -> (function FIELD s' when seq s s' -> s' | _ -> err ())
| PNUMBER None -> (function NUMBER s -> s | _ -> err ())
| PNUMBER (Some n) -> let s = NumTok.Unsigned.sprint n in (function NUMBER n' when s = NumTok.Unsigned.sprint n' -> n' | _ -> err ())
| PSTRING None -> (function STRING s -> s | _ -> err ())
| PSTRING (Some s) -> (function STRING s' when seq s s' -> s' | _ -> err ())
| PLEFTQMARK -> (function LEFTQMARK -> () | _ -> err ())
| PBULLET None -> (function BULLET s -> s | _ -> err ())
| PBULLET (Some s) -> (function BULLET s' when seq s s' -> s' | _ -> err ())
| PQUOTATION lbl -> (function QUOTATION(lbl',s') when string_equal lbl lbl' -> s' | _ -> err ())
| PEOI -> (function EOI -> () | _ -> err ())
|
8929d4b123f339dd7971a784cfaddbe23f6ce31f23824c627778d8883607d697 | NorfairKing/cursor | Gen.hs | module Cursor.Simple.Map.KeyValue.Gen
(
)
where
import Cursor.Map.KeyValue.Gen ()
| null | https://raw.githubusercontent.com/NorfairKing/cursor/71ec3154809e229efbf35d500ac6d1a42ae5fdc0/cursor-gen/src/Cursor/Simple/Map/KeyValue/Gen.hs | haskell | module Cursor.Simple.Map.KeyValue.Gen
(
)
where
import Cursor.Map.KeyValue.Gen ()
|
|
7a7e39dbfce0bf2218313c96509bf8496f6933caee933d7f47fac3a29b239d73 | clash-lang/clash-compiler | ReduceOne.hs | module ReduceOne where
import Clash.Prelude
import Clash.Explicit.Testbench
topEntity
:: Clock System
-> Reset System
-> Enable System
-> Signal System (Signed 1)
-> Signal System (Bit, Bit, Bit)
topEntity clk rst en =
fmap (\a -> (reduceAnd a, reduceOr a, reduceXor a))
{-# NOINLINE topEntity #-}
testBench :: Signal System Bool
testBench = done
where
testInput = stimuliGenerator clk rst ((1 :: Signed 1) :> 0 :> Nil)
expectedOutput = outputVerifier' clk rst ((high, high, high) :> (low, low, low) :> Nil)
done = expectedOutput (topEntity clk rst enableGen testInput)
clk = tbSystemClockGen (not <$> done)
rst = systemResetGen
| null | https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/tests/shouldwork/BitVector/ReduceOne.hs | haskell | # NOINLINE topEntity # | module ReduceOne where
import Clash.Prelude
import Clash.Explicit.Testbench
topEntity
:: Clock System
-> Reset System
-> Enable System
-> Signal System (Signed 1)
-> Signal System (Bit, Bit, Bit)
topEntity clk rst en =
fmap (\a -> (reduceAnd a, reduceOr a, reduceXor a))
testBench :: Signal System Bool
testBench = done
where
testInput = stimuliGenerator clk rst ((1 :: Signed 1) :> 0 :> Nil)
expectedOutput = outputVerifier' clk rst ((high, high, high) :> (low, low, low) :> Nil)
done = expectedOutput (topEntity clk rst enableGen testInput)
clk = tbSystemClockGen (not <$> done)
rst = systemResetGen
|
50563c662edb5869b92716283382a7e18b24dc290632f208a9800956ea962580 | Yuppiechef/cqrs-server | simple_dynamo_test.clj | (ns cqrs-server.simple-dynamo-test
(:require
[schema.core :as s]
[clojure.core.async :as a]
[clojure.test :refer :all]
[clojure.tools.logging :as log]
[taoensso.faraday :as far]
[taoensso.nippy :as nippy]
[cqrs-server.cqrs :as cqrs]
[cqrs-server.simple :as simple]
[cqrs-server.async :as async]
[cqrs-server.dynamo :as dynamo]))
;; Simple testing module
(def users (atom {})) ;; Our super lightweight 'database'
(defn setup-aggregate-chan [chan]
(a/go-loop []
(when-let [msg (a/<! chan)]
(doseq [u msg]
(swap! users assoc (:name u) u))
(recur))))
(cqrs/install-commands
{:user/register {:name s/Str :age s/Int}})
;; :user/create
(defmethod cqrs/process-command :user/register [{:keys [data] :as c}]
(if (get @users (:name data))
(cqrs/events c 0 [[:user/register-failed data]])
(cqrs/events c 1 [[:user/registered data]])))
(defmethod cqrs/aggregate-event :user/registered [{:keys [data] :as e}]
[{:name (:name data)
:age (:age data)}])
;; Implementation
(def local-cred
{:access-key "aws-access-key"
:secret-key "aws-secret-key"
:endpoint ":8000"
:tablename :eventstore})
(def config
{:command-stream (atom nil)
:event-stream (atom nil)
:aggregator (atom nil)
:feedback-stream (atom nil)
:channels [:command-stream :event-stream :aggregator :feedback-stream]})
(def catalog-map
{:command/in-queue (async/stream :input (:command-stream config))
:event/out-queue (async/stream :output (:event-stream config))
:event/in-queue (async/stream :input (:event-stream config))
:event/store (dynamo/catalog local-cred)
:event/aggregator (async/stream :fn (:aggregator config))
:command/feedback (async/stream :output (:feedback-stream config))})
(defn setup-env []
(try
(far/delete-table local-cred (:tablename local-cred))
(catch Exception e nil))
(dynamo/table-setup local-cred)
(reset! users {})
(doseq [c (:channels config)]
(reset! (get config c) (a/chan 10)))
(setup-aggregate-chan @(:aggregator config))
(let [setup (cqrs/setup (java.util.UUID/randomUUID) catalog-map)]
{:simple (simple/start setup)}))
(defn stop-env [env]
(doseq [c (:channels config)]
(swap! (get config c) (fn [chan] (a/close! chan) nil)))
(try
(far/delete-table local-cred (:tablename local-cred))
(catch Exception e nil))
true)
(defn send-command [type data]
(a/>!! @(:command-stream config) (cqrs/command "123" 1 type data)))
;; Requires dynamo local
(defn run-test []
(let [env (setup-env)
feedback (delay (first (a/alts!! [@(:feedback-stream config) (a/timeout 2000)])))]
(try
(send-command :user/register {:name "Bob" :age 33})
(assert @feedback)
(assert (= {"Bob" {:name "Bob" :age 33}} @users))
(assert (= 1 (count (far/scan local-cred :eventstore))))
(assert (= {:age 33 :name "Bob"} (nippy/thaw (:data (first (far/scan local-cred :eventstore))))))
(finally
(stop-env env)))))
| null | https://raw.githubusercontent.com/Yuppiechef/cqrs-server/57621f52e8f4a9de9f2e06fff16b4b918a81228a/test/cqrs_server/simple_dynamo_test.clj | clojure | Simple testing module
Our super lightweight 'database'
:user/create
Implementation
Requires dynamo local | (ns cqrs-server.simple-dynamo-test
(:require
[schema.core :as s]
[clojure.core.async :as a]
[clojure.test :refer :all]
[clojure.tools.logging :as log]
[taoensso.faraday :as far]
[taoensso.nippy :as nippy]
[cqrs-server.cqrs :as cqrs]
[cqrs-server.simple :as simple]
[cqrs-server.async :as async]
[cqrs-server.dynamo :as dynamo]))
(defn setup-aggregate-chan [chan]
(a/go-loop []
(when-let [msg (a/<! chan)]
(doseq [u msg]
(swap! users assoc (:name u) u))
(recur))))
(cqrs/install-commands
{:user/register {:name s/Str :age s/Int}})
(defmethod cqrs/process-command :user/register [{:keys [data] :as c}]
(if (get @users (:name data))
(cqrs/events c 0 [[:user/register-failed data]])
(cqrs/events c 1 [[:user/registered data]])))
(defmethod cqrs/aggregate-event :user/registered [{:keys [data] :as e}]
[{:name (:name data)
:age (:age data)}])
(def local-cred
{:access-key "aws-access-key"
:secret-key "aws-secret-key"
:endpoint ":8000"
:tablename :eventstore})
(def config
{:command-stream (atom nil)
:event-stream (atom nil)
:aggregator (atom nil)
:feedback-stream (atom nil)
:channels [:command-stream :event-stream :aggregator :feedback-stream]})
(def catalog-map
{:command/in-queue (async/stream :input (:command-stream config))
:event/out-queue (async/stream :output (:event-stream config))
:event/in-queue (async/stream :input (:event-stream config))
:event/store (dynamo/catalog local-cred)
:event/aggregator (async/stream :fn (:aggregator config))
:command/feedback (async/stream :output (:feedback-stream config))})
(defn setup-env []
(try
(far/delete-table local-cred (:tablename local-cred))
(catch Exception e nil))
(dynamo/table-setup local-cred)
(reset! users {})
(doseq [c (:channels config)]
(reset! (get config c) (a/chan 10)))
(setup-aggregate-chan @(:aggregator config))
(let [setup (cqrs/setup (java.util.UUID/randomUUID) catalog-map)]
{:simple (simple/start setup)}))
(defn stop-env [env]
(doseq [c (:channels config)]
(swap! (get config c) (fn [chan] (a/close! chan) nil)))
(try
(far/delete-table local-cred (:tablename local-cred))
(catch Exception e nil))
true)
(defn send-command [type data]
(a/>!! @(:command-stream config) (cqrs/command "123" 1 type data)))
(defn run-test []
(let [env (setup-env)
feedback (delay (first (a/alts!! [@(:feedback-stream config) (a/timeout 2000)])))]
(try
(send-command :user/register {:name "Bob" :age 33})
(assert @feedback)
(assert (= {"Bob" {:name "Bob" :age 33}} @users))
(assert (= 1 (count (far/scan local-cred :eventstore))))
(assert (= {:age 33 :name "Bob"} (nippy/thaw (:data (first (far/scan local-cred :eventstore))))))
(finally
(stop-env env)))))
|
0a425d9d51145a84612c405ee97a825f5a46c147802bf4d86d1a37535cf5e8fb | mejgun/haskell-tdlib | SetUsername.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Query.SetUsername where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
-- |
-- Changes the editable username of the current user
data SetUsername = SetUsername
{ -- | The new value of the username. Use an empty string to remove the username. The username can't be completely removed if there is another active or disabled username
username :: Maybe String
}
deriving (Eq)
instance Show SetUsername where
show
SetUsername
{ username = username_
} =
"SetUsername"
++ U.cc
[ U.p "username" username_
]
instance T.ToJSON SetUsername where
toJSON
SetUsername
{ username = username_
} =
A.object
[ "@type" A..= T.String "setUsername",
"username" A..= username_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/dc380d18d49eaadc386a81dc98af2ce00f8797c2/src/TD/Query/SetUsername.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
Changes the editable username of the current user
| The new value of the username. Use an empty string to remove the username. The username can't be completely removed if there is another active or disabled username |
module TD.Query.SetUsername where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
data SetUsername = SetUsername
username :: Maybe String
}
deriving (Eq)
instance Show SetUsername where
show
SetUsername
{ username = username_
} =
"SetUsername"
++ U.cc
[ U.p "username" username_
]
instance T.ToJSON SetUsername where
toJSON
SetUsername
{ username = username_
} =
A.object
[ "@type" A..= T.String "setUsername",
"username" A..= username_
]
|
7eb6f7610bc29cb202e4a870fe88b391338b10c3ee0a83297d00b95a5f057259 | ocaml-multicore/tezos | michelson_v1_primitives.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
type error += (* `Permanent *) Unknown_primitive_name of string
type error += (* `Permanent *) Invalid_case of string
type error +=
| (* `Permanent *)
Invalid_primitive_name of
string Micheline.canonical * Micheline.canonical_location
* Types of nodes in 's AST . They fall into 4 categories :
- types ( prefixed with [ T _ ] ) ;
- constants ( prefixed with [ D _ ] ) ;
- instructions ( prefixed with [ I _ ] ) ;
- keywords ( prefixed with [ K _ ] ) .
Recall that is essentially just S - expressions with
a few extra atom types for strings and numbers . This variant
represents the values the [ Prim ] atoms in the subset
of Micheline . Other types ( such as [ ' a Micheline.canonical ] ) are
frequently parameterized by this type . This gives us a strongly - typed
subset of while keeping the set of primitives independent
from the definition of for easier changes .
- types (prefixed with [T_]);
- constants (prefixed with [D_]);
- instructions (prefixed with [I_]);
- keywords (prefixed with [K_]).
Recall that Micheline is essentially just S-expressions with
a few extra atom types for strings and numbers. This variant
represents the values the [Prim] atoms in the Michelson subset
of Micheline. Other types (such as ['a Micheline.canonical]) are
frequently parameterized by this type. This gives us a strongly-typed
subset of Micheline while keeping the set of primitives independent
from the definition of Micheline for easier changes.
*)
type prim =
| K_parameter
| K_storage
| K_code
| K_view
| D_False
| D_Elt
| D_Left
| D_None
| D_Pair
| D_Right
| D_Some
| D_True
| D_Unit
| I_PACK
| I_UNPACK
| I_BLAKE2B
| I_SHA256
| I_SHA512
| I_ABS
| I_ADD
| I_AMOUNT
| I_AND
| I_BALANCE
| I_CAR
| I_CDR
| I_CHAIN_ID
| I_CHECK_SIGNATURE
| I_COMPARE
| I_CONCAT
| I_CONS
| I_CREATE_ACCOUNT
| I_CREATE_CONTRACT
| I_IMPLICIT_ACCOUNT
| I_DIP
| I_DROP
| I_DUP
| I_VIEW
| I_EDIV
| I_EMPTY_BIG_MAP
| I_EMPTY_MAP
| I_EMPTY_SET
| I_EQ
| I_EXEC
| I_APPLY
| I_FAILWITH
| I_GE
| I_GET
| I_GET_AND_UPDATE
| I_GT
| I_HASH_KEY
| I_IF
| I_IF_CONS
| I_IF_LEFT
| I_IF_NONE
| I_INT
| I_LAMBDA
| I_LE
| I_LEFT
| I_LEVEL
| I_LOOP
| I_LSL
| I_LSR
| I_LT
| I_MAP
| I_MEM
| I_MUL
| I_NEG
| I_NEQ
| I_NIL
| I_NONE
| I_NOT
| I_NOW
| I_OR
| I_PAIR
| I_UNPAIR
| I_PUSH
| I_RIGHT
| I_SIZE
| I_SOME
| I_SOURCE
| I_SENDER
| I_SELF
| I_SELF_ADDRESS
| I_SLICE
| I_STEPS_TO_QUOTA
| I_SUB
| I_SUB_MUTEZ
| I_SWAP
| I_TRANSFER_TOKENS
| I_SET_DELEGATE
| I_UNIT
| I_UPDATE
| I_XOR
| I_ITER
| I_LOOP_LEFT
| I_ADDRESS
| I_CONTRACT
| I_ISNAT
| I_CAST
| I_RENAME
| I_SAPLING_EMPTY_STATE
| I_SAPLING_VERIFY_UPDATE
| I_DIG
| I_DUG
| I_NEVER
| I_VOTING_POWER
| I_TOTAL_VOTING_POWER
| I_KECCAK
| I_SHA3
| I_PAIRING_CHECK
| I_TICKET
| I_READ_TICKET
| I_SPLIT_TICKET
| I_JOIN_TICKETS
| I_OPEN_CHEST
| T_bool
| T_contract
| T_int
| T_key
| T_key_hash
| T_lambda
| T_list
| T_map
| T_big_map
| T_nat
| T_option
| T_or
| T_pair
| T_set
| T_signature
| T_string
| T_bytes
| T_mutez
| T_timestamp
| T_unit
| T_operation
| T_address
| T_sapling_transaction
| T_sapling_state
| T_chain_id
| T_never
| T_bls12_381_g1
| T_bls12_381_g2
| T_bls12_381_fr
| T_ticket
| T_chest_key
| T_chest
(* See the interface of [Global_constants_storage]. *)
| H_constant
(** Auxiliary types for error documentation.
All the prim constructor prefixes must match their namespace. *)
type namespace =
| (* prefix "T" *) Type_namespace
| (* prefix "D" *) Constant_namespace
| (* prefix "I" *) Instr_namespace
| (* prefix "K" *) Keyword_namespace
(* The Constant Hash namespace is a singleton reserved
for the constant keyword. Unlike other primitives,
constants have no representation in the typed IR,
being fully expanded away before typechecking. *)
| (* prefix "H" *) Constant_hash_namespace
val namespace : prim -> namespace
val prim_encoding : prim Data_encoding.encoding
val string_of_prim : prim -> string
val prim_of_string : string -> prim tzresult
val prims_of_strings :
string Micheline.canonical -> prim Micheline.canonical tzresult
val strings_of_prims : prim Micheline.canonical -> string Micheline.canonical
(** The string corresponds to the constructor prefix from the given namespace
(i.e. "T", "D", "I" or "K") *)
val string_of_namespace : namespace -> string
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_012_Psithaca/lib_protocol/michelson_v1_primitives.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
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.
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
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
`Permanent
`Permanent
`Permanent
See the interface of [Global_constants_storage].
* Auxiliary types for error documentation.
All the prim constructor prefixes must match their namespace.
prefix "T"
prefix "D"
prefix "I"
prefix "K"
The Constant Hash namespace is a singleton reserved
for the constant keyword. Unlike other primitives,
constants have no representation in the typed IR,
being fully expanded away before typechecking.
prefix "H"
* The string corresponds to the constructor prefix from the given namespace
(i.e. "T", "D", "I" or "K") | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
type error +=
Invalid_primitive_name of
string Micheline.canonical * Micheline.canonical_location
* Types of nodes in 's AST . They fall into 4 categories :
- types ( prefixed with [ T _ ] ) ;
- constants ( prefixed with [ D _ ] ) ;
- instructions ( prefixed with [ I _ ] ) ;
- keywords ( prefixed with [ K _ ] ) .
Recall that is essentially just S - expressions with
a few extra atom types for strings and numbers . This variant
represents the values the [ Prim ] atoms in the subset
of Micheline . Other types ( such as [ ' a Micheline.canonical ] ) are
frequently parameterized by this type . This gives us a strongly - typed
subset of while keeping the set of primitives independent
from the definition of for easier changes .
- types (prefixed with [T_]);
- constants (prefixed with [D_]);
- instructions (prefixed with [I_]);
- keywords (prefixed with [K_]).
Recall that Micheline is essentially just S-expressions with
a few extra atom types for strings and numbers. This variant
represents the values the [Prim] atoms in the Michelson subset
of Micheline. Other types (such as ['a Micheline.canonical]) are
frequently parameterized by this type. This gives us a strongly-typed
subset of Micheline while keeping the set of primitives independent
from the definition of Micheline for easier changes.
*)
type prim =
| K_parameter
| K_storage
| K_code
| K_view
| D_False
| D_Elt
| D_Left
| D_None
| D_Pair
| D_Right
| D_Some
| D_True
| D_Unit
| I_PACK
| I_UNPACK
| I_BLAKE2B
| I_SHA256
| I_SHA512
| I_ABS
| I_ADD
| I_AMOUNT
| I_AND
| I_BALANCE
| I_CAR
| I_CDR
| I_CHAIN_ID
| I_CHECK_SIGNATURE
| I_COMPARE
| I_CONCAT
| I_CONS
| I_CREATE_ACCOUNT
| I_CREATE_CONTRACT
| I_IMPLICIT_ACCOUNT
| I_DIP
| I_DROP
| I_DUP
| I_VIEW
| I_EDIV
| I_EMPTY_BIG_MAP
| I_EMPTY_MAP
| I_EMPTY_SET
| I_EQ
| I_EXEC
| I_APPLY
| I_FAILWITH
| I_GE
| I_GET
| I_GET_AND_UPDATE
| I_GT
| I_HASH_KEY
| I_IF
| I_IF_CONS
| I_IF_LEFT
| I_IF_NONE
| I_INT
| I_LAMBDA
| I_LE
| I_LEFT
| I_LEVEL
| I_LOOP
| I_LSL
| I_LSR
| I_LT
| I_MAP
| I_MEM
| I_MUL
| I_NEG
| I_NEQ
| I_NIL
| I_NONE
| I_NOT
| I_NOW
| I_OR
| I_PAIR
| I_UNPAIR
| I_PUSH
| I_RIGHT
| I_SIZE
| I_SOME
| I_SOURCE
| I_SENDER
| I_SELF
| I_SELF_ADDRESS
| I_SLICE
| I_STEPS_TO_QUOTA
| I_SUB
| I_SUB_MUTEZ
| I_SWAP
| I_TRANSFER_TOKENS
| I_SET_DELEGATE
| I_UNIT
| I_UPDATE
| I_XOR
| I_ITER
| I_LOOP_LEFT
| I_ADDRESS
| I_CONTRACT
| I_ISNAT
| I_CAST
| I_RENAME
| I_SAPLING_EMPTY_STATE
| I_SAPLING_VERIFY_UPDATE
| I_DIG
| I_DUG
| I_NEVER
| I_VOTING_POWER
| I_TOTAL_VOTING_POWER
| I_KECCAK
| I_SHA3
| I_PAIRING_CHECK
| I_TICKET
| I_READ_TICKET
| I_SPLIT_TICKET
| I_JOIN_TICKETS
| I_OPEN_CHEST
| T_bool
| T_contract
| T_int
| T_key
| T_key_hash
| T_lambda
| T_list
| T_map
| T_big_map
| T_nat
| T_option
| T_or
| T_pair
| T_set
| T_signature
| T_string
| T_bytes
| T_mutez
| T_timestamp
| T_unit
| T_operation
| T_address
| T_sapling_transaction
| T_sapling_state
| T_chain_id
| T_never
| T_bls12_381_g1
| T_bls12_381_g2
| T_bls12_381_fr
| T_ticket
| T_chest_key
| T_chest
| H_constant
type namespace =
val namespace : prim -> namespace
val prim_encoding : prim Data_encoding.encoding
val string_of_prim : prim -> string
val prim_of_string : string -> prim tzresult
val prims_of_strings :
string Micheline.canonical -> prim Micheline.canonical tzresult
val strings_of_prims : prim Micheline.canonical -> string Micheline.canonical
val string_of_namespace : namespace -> string
|
461c6eb3c263bf2de9b37f1147fe0ca2ff949fb0e911681e064e7b1ed64bda71 | imdea-software/leap | SMTTllQuery_reduced.ml |
(***********************************************************************)
(* *)
LEAP
(* *)
, IMDEA Software Institute
(* *)
(* *)
Copyright 2011 IMDEA Software Institute
(* *)
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. *)
(* *)
(***********************************************************************)
open TllQuery
open LeapLib
open LeapVerbose
module SMTTllQuery : TLL_QUERY =
struct
module Expr = TLLExpression
module VarIdSet = TLLExpression.VarIdSet
module B = Buffer
module GM = GenericModel
exception UnexpectedCellTerm of string
exception UnexpectedSetTerm of string
exception UnexpectedSetthTerm of string
exception UnexpectedSetelemTerm of string
let prog_lines = ref 0
let pc_prime_name : string = Conf.pc_name ^ "_prime"
let loc_str : string = "loc_"
let range_addr_str : string = "rg_addr_"
let range_tid_str : string = "rg_tid_"
let path_len_str : string = "p_len_"
let addr_prefix = "aa_"
let tid_prefix = "tt_"
let elem_prefix = "ee_"
(* Sort names *)
let bool_s : string = "Bool"
let int_s : string = "Int"
let addr_s : string = "Address"
let set_s : string = "Set"
let elem_s : string = "Elem"
let tid_s : string = "Tid"
let cell_s : string = "Cell"
let setth_s : string = "Setth"
let setelem_s : string = "SetElem"
let path_s : string = "Path"
let heap_s : string = "Heap"
let unk_s : string = "Unknown"
let loc_s : string = "Loc"
Lock - Unlock information table
(* We store calls to cell_lock and cell_unlock in the formula, in order to
add the necessary assertions once we have translated the formula *)
let cell_tbl = Hashtbl.create 10
let addr_tbl = Hashtbl.create 10
let elem_tbl = Hashtbl.create 10
let tid_tbl = Hashtbl.create 10
let getp_tbl = Hashtbl.create 10
let fstlock_tbl = Hashtbl.create 10
let clean_lists () : unit =
Hashtbl.clear cell_tbl;
Hashtbl.clear addr_tbl;
Hashtbl.clear elem_tbl;
Hashtbl.clear tid_tbl;
Hashtbl.clear getp_tbl;
Hashtbl.clear fstlock_tbl
(* Information storage *)
let sort_map : GM.sort_map_t = GM.new_sort_map()
let linenum_to_str (i:int) : string =
string_of_int i
let range_addr_to_str (i:int) : string =
string_of_int i
let range_tid_to_str (i:int) : string =
range_tid_str ^ string_of_int i
let path_len_to_str (i:int) : string =
string_of_int i
Program lines manipulation
let set_prog_lines (n:int) : unit =
prog_lines := n
(************************* Declarations **************************)
let data(expr:string) : string =
Hashtbl.add elem_tbl expr ();
("(data " ^expr^ ")")
let next(expr:string) : string =
Hashtbl.add addr_tbl expr ();
("(next " ^expr^ ")")
let lock(expr:string) : string =
Hashtbl.add tid_tbl expr ();
("(lock " ^expr^ ")")
(* (define-type address (scalar null aa_1 aa_2 aa_3 aa_4 aa_5)) *)
( define max_address::int 5 )
(* (define-type range_address (subrange 0 max_address)) *)
let smt_addr_preamble buf num_addr =
B.add_string buf ("(set-logic QF_AUFLIA)\n");
B.add_string buf ("(define-sort " ^addr_s^ " () " ^int_s^ ")\n");
GM.sm_decl_const sort_map "max_address" int_s ;
B.add_string buf
( "(define-fun max_address () " ^int_s^ " " ^(string_of_int num_addr)^ ")\n");
B.add_string buf
("(define-fun null () " ^addr_s^ " 0)\n");
for i = 1 to num_addr do
let i_str = string_of_int i in
let a_str = addr_prefix ^ i_str in
B.add_string buf ("(define-fun " ^a_str^ " () " ^addr_s^ " " ^i_str^ ")\n")
done;
B.add_string buf ("(define-fun isaddr ((x " ^addr_s^ ")) " ^bool_s^ " (and (<= 0 x) (<= x max_address)))\n");
B.add_string buf
( "(define-sort RangeAddress () " ^int_s^ ")\n" ^
"(define-fun is_valid_range_address ((i RangeAddress)) " ^bool_s^
" (and (<= 0 i) (<= i max_address)))\n")
(* (define-type tid (scalar notid t1 t2 t3)) *)
(* (define max_tid::int 3) *)
(* (define-type range_tid (subrange 0 max_tid)) *)
let smt_tid_preamble buf num_tids =
B.add_string buf ("(define-sort " ^tid_s^ " () " ^int_s^ ")\n");
GM.sm_decl_const sort_map "max_tid" int_s ;
B.add_string buf ("(define-fun max_tid () " ^int_s^ " " ^(string_of_int num_tids)^ ")\n");
B.add_string buf
("(define-fun notid () " ^tid_s^ " 0)\n");
for i = 1 to num_tids do
let i_str = string_of_int i in
let t_str = tid_prefix ^ i_str in
B.add_string buf ("(define-fun " ^t_str^ " () " ^tid_s^ " " ^i_str^ ")\n")
done;
B.add_string buf "; I need the line below to prevent an unknown constant error\n";
GM.sm_decl_const sort_map "tid_witness" tid_s ;
let witness_str = string_of_int (num_tids + 1) in
B.add_string buf ("(define-fun tid_witness () " ^tid_s^ " " ^witness_str^ ")\n");
B.add_string buf ("(define-fun istid ((x " ^tid_s^ ")) " ^bool_s^ " (and (<= 0 x) (<= x (+ max_tid 1))))\n")
(* (define-type element) *)
let smt_element_preamble buf num_elems =
B.add_string buf ("(define-sort " ^elem_s^ " () " ^int_s^ ")\n");
B.add_string buf ("(define-fun lowestElem () " ^elem_s^ " 0)\n");
B.add_string buf ("(define-fun highestElem () " ^elem_s^ " " ^(string_of_int (num_elems+1))^ ")\n");
for i = 1 to num_elems do
let i_str = string_of_int i in
let e_str = elem_prefix ^ i_str in
B.add_string buf ("(define-fun " ^e_str^ " () " ^elem_s^ " " ^i_str^ ")\n")
done;
B.add_string buf ("(define-fun iselem ((x " ^elem_s^ ")) " ^bool_s^ " (and (<= lowestElem x) (<= x highestElem)))\n")
(* (define-type cell (record data::element next::address lock::tid)) *)
(* (define next::(-> cell address) (lambda (c::cell) (select c next))) *)
( define data::(- > cell element ) ( lambda ( c::cell ) ( select c data ) ) )
(* (define lock::(-> cell tid) (lambda (c::cell) (select c lock))) *)
let smt_cell_preamble buf =
B.add_string buf
("(declare-sort " ^cell_s^ " 0)\n\
(declare-fun mkcell (" ^elem_s^ " " ^addr_s^ " " ^tid_s^ ") " ^cell_s^ ")\n\
(declare-fun data (" ^cell_s^ ") " ^elem_s^ ")\n\
(declare-fun next (" ^cell_s^ ") " ^addr_s^ ")\n\
(declare-fun lock (" ^cell_s^ ") " ^tid_s^ ")\n")
(* (define-type heap (-> address cell)) *)
let smt_heap_preamble buf =
B.add_string buf
("(define-sort " ^heap_s^ " () (Array " ^addr_s^ " " ^cell_s^ "))\n")
(* (define-type set (-> address bool)) *)
let smt_set_preamble buf =
B.add_string buf
("(define-sort " ^set_s^ " () (Array " ^addr_s^ " " ^bool_s^ "))\n")
( define - type setth ( - > tid bool ) )
let smt_setth_preamble buf =
B.add_string buf
("(define-sort " ^setth_s^ " () (Array " ^tid_s^ " " ^bool_s^ "))\n")
let smt_setelem_preamble buf =
B.add_string buf
("(define-sort " ^setelem_s^ " () (Array " ^elem_s^ " " ^bool_s^ "))\n")
(* (define pathat::(-> range_address address)) *)
(* (define pathwhere::(-> address range_address)) *)
(* (define-type path *)
(* (record length::range_address at::pathat where::pathwhere)) *)
( define eqpath_pos::(- > path path path_length bool )
( lambda ( p::path r::path_length i::range_address )
(* (=> (and (< i (select p length)) *)
(* (< i (select r length))) *)
(* (= ((select p at) i) ((select r at) i))))) *)
(* (define eqpath::(-> path path bool) *)
(* (lambda (p::path r::path) *)
(* (and (= (select p length) (select r length)) *)
( eqpath_pos p r 0 )
( eqpath_pos p r 1 )
( eqpath_pos p r 2 )
( eqpath_pos p r 3 ) ) ) )
let smt_path_preamble buf num_addr =
B.add_string buf
( "(define-sort PathLength () " ^int_s^ ")\n" ^
"(define-fun is_valid_path_length ((i PathLength)) " ^bool_s^
" (and (<= 0 i) (<= i (+ max_address 1))))\n");
B.add_string buf
( "(define-sort PathAt () (Array RangeAddress " ^addr_s^ "))\n" ^
"(define-sort PathWhere () (Array " ^addr_s^ " RangeAddress))\n");
B.add_string buf
( "(declare-sort " ^path_s^ " 0)\n" );
B.add_string buf
( "(declare-fun mkpath (PathLength PathAt PathWhere " ^set_s^ ") " ^path_s^ ")\n" );
B.add_string buf
( "(declare-fun length (" ^path_s^ ") PathLength)\n\
(declare-fun at (" ^path_s^ ") PathAt)\n\
(declare-fun where (" ^path_s^ ") PathWhere)\n\
(declare-fun addrs (" ^path_s^ ") " ^set_s^ ")\n" );
B.add_string buf
("(define-fun eqpath_pos ((p " ^path_s^ ") (r " ^path_s^
") (i RangeAddress)) " ^bool_s^ "\n" ^
" (=> (and (is_valid_range_address i) (< i (length p)) (< i (length r)))\n" ^
" (= (select (at p) i) (select (at r) i))))\n");
B.add_string buf
("(define-fun eqpath ((p " ^path_s^ ") (r " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (= (length p) (length r))\n");
for i=0 to num_addr do
B.add_string buf
(" (eqpath_pos p r "^ (path_len_to_str i) ^ ")\n");
done ;
B.add_string buf "))\n"
let smt_unknown_preamble buf =
B.add_string buf
("(declare-sort " ^unk_s^ " 0)\n")
let smt_pos_preamble buf =
B.add_string buf ("(define-sort " ^loc_s^ " () " ^int_s^ ")\n");
GM.sm_decl_fun sort_map Conf.pc_name [tid_s] [loc_s] ;
GM.sm_decl_fun sort_map pc_prime_name [tid_s] [loc_s] ;
B.add_string buf ("(declare-fun " ^Conf.pc_name^ " () (Array " ^tid_s^ " " ^loc_s^ "))\n");
B.add_string buf ("(declare-fun " ^pc_prime_name^ " () (Array " ^tid_s^ " " ^loc_s^ "))\n");
B.add_string buf ("(define-fun in_pos_range ((t " ^tid_s^ ")) " ^bool_s^ "\n" ^
" (and (<= 1 (select pc t))\n" ^
" (<= (select pc t) " ^string_of_int !prog_lines^ ")\n" ^
" (<= 1 (select pc_prime t))\n" ^
" (<= (select pc_prime t) " ^ string_of_int !prog_lines^ ")))\n")
( define )
(* (lambda (t::tid) (false)) *)
let smt_empth_def buf num_tids =
let _ = GM.sm_decl_const sort_map "emptyth" setth_s in
B.add_string buf
("(declare-fun emptyth () " ^setth_s^ ")\n");
B.add_string buf
("(assert (= (select emptyth notid) false))\n");
for i = 1 to num_tids do
B.add_string buf
("(assert (= (select emptyth " ^(tid_prefix ^ (string_of_int i))^ ") false))\n")
done;
B.add_string buf
("(assert (= (select emptyth tid_witness) false))\n")
( define singletonth::(- > tid setth )
(* (lambda (t::tid) *)
(* (lambda (r::tid) *)
(* (= t r)))) *)
let smt_singletonth_def buf =
B.add_string buf
("(define-fun singletonth ((t " ^tid_s^ ")) " ^setth_s^ "\n" ^
" (store emptyth t true))\n")
( define unionth::(- > setth )
(* (lambda (s::setth r::setth) *)
(* (lambda (t::tid) *)
(* (or (s t) (r t))))) *)
let smt_unionth_def buf num_tids =
let str = ref (" (store\n" ^
" (store emptyth notid (or (select s1 notid) (select s2 notid)))\n" ^
" tid_witness (or (select s1 tid_witness) (select s2 tid_witness)))") in
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^t_str^ " (or (select s1 " ^t_str^ ") (select s2 " ^t_str^ ")))"
done;
B.add_string buf
("(define-fun unionth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) " ^setth_s^ "\n" ^ (!str) ^ ")\n")
( define > setth )
(* (lambda (s::setth r::setth) *)
(* (lambda (t::tid) *)
(* (and (s t) (r t))))) *)
let smt_intersectionth_def buf num_tids =
let str = ref (" (store\n" ^
" (store emptyth notid (and (select s1 notid) (select s2 notid)))\n" ^
" tid_witness (and (select s1 tid_witness) (select s2 tid_witness)))") in
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^t_str^ " (and (select s1 " ^t_str^ ") (select s2 " ^t_str^ ")))"
done;
B.add_string buf
("(define-fun intersectionth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) " ^setth_s^ "\n" ^ (!str) ^ ")\n")
(* (define setdiffth::(-> set set set) *)
(* (lambda (s::setth r::setth) *)
(* (lambda (t::tid) *)
(* (and (s t) (not (r t)))))) *)
let smt_setdiffth_def buf num_tids =
let str = ref (" (store\n" ^
" (store emptyth notid (and (select s1 notid) (not (select s2 notid))))\n" ^
" tid_witness (and (select s1 tid_witness) (not (select s2 tid_witness))))") in
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^t_str^ " (and (select s1 " ^t_str^ ") (not (select s2 " ^t_str^ "))))"
done;
B.add_string buf
("(define-fun setdiffth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) " ^setth_s^ "\n" ^ (!str) ^ ")\n")
( define subseteqth::(- > setth setth bool )
(* (lambda (r::setth) (s::setth) *)
(* (and (if (r notid) (s notid)) *)
(* (if (r t1) (s t1)) *)
(* (if (r t2) (s t2)) *)
( if ( r t3 ) ( s t3 ) ) ) ) )
let smt_subseteqth_def buf num_tids =
B.add_string buf
("(define-fun subseteqth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) "^bool_s^ "\n" ^
" (and (=> (select s1 notid) (select s2 notid))\n" ^
" (=> (select s1 tid_witness) (select s2 tid_witness))\n");
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
B.add_string buf
(" (=> (select s1 " ^t_str^ ") (select s2 " ^t_str^ "))\n")
done;
B.add_string buf ("))\n")
( define eqsetth::(- > setth setth bool )
let smt_eqsetth_def buf num_tids =
B.add_string buf
("(define-fun eqsetth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) "^bool_s^ "\n" ^
" (and (= (select s1 notid) (select s2 notid))\n" ^
" (= (select s1 tid_witness) (select s2 tid_witness))\n");
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
B.add_string buf
(" (= (select s1 " ^t_str^ ") (select s2 " ^t_str^ "))\n")
done;
B.add_string buf ("))\n")
(* (define emptyelem::setelem) *)
(* (lambda (e::elem) (false)) *)
let smt_empelem_def buf num_elems =
let _ = GM.sm_decl_const sort_map "emptyelem" setelem_s in
B.add_string buf
("(declare-fun emptyelem () " ^setelem_s^ ")\n");
B.add_string buf
("(assert (= (select emptyelem lowestElem) false))\n");
B.add_string buf
("(assert (= (select emptyelem highestElem) false))\n");
for i = 1 to num_elems do
B.add_string buf
("(assert (= (select emptyelem " ^(elem_prefix ^ (string_of_int i))^ ") false))\n")
done
(* (define singletonelem::(-> elem setelem) *)
(* (lambda (e::elem) *)
(* (lambda (r::elem) *)
(* (= t r)))) *)
let smt_singletonelem_def buf =
B.add_string buf
("(define-fun singletonelem ((e " ^elem_s^ ")) " ^setelem_s^ "\n" ^
" (store emptyelem e true))\n")
(* (define unionelem::(-> setelem setelem setelem) *)
( lambda ( s::setelem r::setelem )
(* (lambda (e::elem) *)
(* (or (s e) (r e))))) *)
let smt_unionelem_def buf num_elems =
let str = ref (" (store\n" ^
" (store emptyelem lowestElem (or (select s1 lowestElem) (select s2 lowestElem)))\n" ^
" highestElem (or (select s1 highestElem) (select s2 highestElem)))") in
for i = 1 to num_elems do
let e_str = elem_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^e_str^ " (or (select s1 " ^e_str^ ") (select s2 " ^e_str^ ")))"
done;
B.add_string buf
("(define-fun unionelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) " ^setelem_s^ "\n" ^ (!str) ^ ")\n")
(* (define intersectionelem::(-> setelem setelem setelem) *)
( lambda ( s::setelem r::setelem )
(* (lambda (e::elem) *)
(* (and (s e) (r e))))) *)
let smt_intersectionelem_def buf num_elems =
let str = ref (" (store\n" ^
" (store emptyelem lowestElem (and (select s1 lowestElem) (select s2 lowestElem)))\n" ^
" highestElem (and (select s1 highestElem) (select s2 highestElem)))") in
for i = 1 to num_elems do
let e_str = elem_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^e_str^ " (and (select s1 " ^e_str^ ") (select s2 " ^e_str^ ")))"
done;
B.add_string buf
("(define-fun intersectionelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) " ^setelem_s^ "\n" ^ (!str) ^ ")\n")
(* (define setdiffelem::(-> setelem setelem setelem) *)
( lambda ( s::setelem r::setelem )
(* (lambda (e::elem) *)
(* (and (s e) (not (r e)))))) *)
let smt_setdiffelem_def buf num_elems =
let str = ref (" (store\n" ^
" (store emptyelem lowestElem (and (select s1 lowestElem) (not (select s2 lowestElem))))\n" ^
" highestElem (and (select s1 highestElem) (not (select s2 highestElem))))") in
for i = 1 to num_elems do
let e_str = elem_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^e_str^ " (and (select s1 " ^e_str^ ") (not (select s2 " ^e_str^ "))))"
done;
B.add_string buf
("(define-fun setdiffelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) " ^setelem_s^ "\n" ^ (!str) ^ ")\n")
( define subseteqelem::(- )
(* (lambda (r::setelem) (s::setelem) *)
(* (and (=> (r e1) (s e1)) *)
(* (=> (r e2) (s e2)) *)
(* (=> (r e3) (s e3))))) *)
let smt_subseteqelem_def buf num_elem =
B.add_string buf
("(define-fun subseteqelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) "^bool_s^ "\n" ^
" (and (=> (select s1 lowestElem) (select s2 lowestElem))\n" ^
" (=> (select s1 highestElem) (select s2 highestElem))\n");
for i = 1 to num_elem do
let e_str = elem_prefix ^ (string_of_int i) in
B.add_string buf
(" (=> (select s1 " ^e_str^ ") (select s2 " ^e_str^ "))\n")
done;
B.add_string buf ("))\n")
( define eqsetelem::(- )
let smt_eqsetelem_def buf num_elem =
B.add_string buf
("(define-fun eqsetelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) "^bool_s^ "\n" ^
" (and (= (select s1 lowestElem) (select s2 lowestElem))\n" ^
" (= (select s1 highestElem) (select s2 highestElem))\n");
for i = 1 to num_elem do
let e_str = elem_prefix ^ (string_of_int i) in
B.add_string buf
(" (= (select s1 " ^e_str^ ") (select s2 " ^e_str^ "))\n")
done;
B.add_string buf ("))\n")
(* (define empty::set) *)
(* (lambda (a::address) (false)) *)
let smt_emp_def buf num_addrs =
let _ = GM.sm_decl_const sort_map "empty" set_s in
B.add_string buf
("(declare-fun empty () " ^set_s^ ")\n");
B.add_string buf
("(assert (= (select empty null) false))\n");
for i = 1 to num_addrs do
B.add_string buf
("(assert (= (select empty " ^(addr_prefix ^ (string_of_int i))^ ") false))\n")
done
(* (define singleton::(-> address set) *)
(* (lambda (a::address) *)
(* (lambda (b::address) *)
(* (= a b)))) *)
let smt_singleton_def buf =
B.add_string buf
("(define-fun singleton ((a " ^addr_s^ ")) " ^set_s^ "\n" ^
" (store empty a true))\n")
(* (define setunion::(-> set set set) *)
(* (lambda (s::set r::set) *)
(* (lambda (a::address) *)
(* (or (s a) (r a))))) *)
let smt_union_def buf num_addrs =
let str = ref " (store empty null (or (select s1 null) (select s2 null)))" in
for i = 1 to num_addrs do
let a_str = addr_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^a_str^ " (or (select s1 " ^a_str^ ") (select s2 " ^a_str^ ")))"
done;
B.add_string buf
("(define-fun setunion ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) " ^set_s^ "\n" ^ (!str) ^ ")\n")
(* (define intersection::(-> set set set) *)
(* (lambda (s::set r::set) *)
(* (lambda (a::address) *)
(* (and (s a) (r a))))) *)
let smt_intersection_def buf num_addrs =
let str = ref " (store empty null (and (select s1 null) (select s2 null)))" in
for i = 1 to num_addrs do
let a_str = addr_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^a_str^ " (and (select s1 " ^a_str^ ") (select s2 " ^a_str^ ")))"
done;
B.add_string buf
("(define-fun intersection ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) " ^set_s^ "\n" ^ (!str) ^ ")\n")
(* (define setdiff::(-> set set set) *)
(* (lambda (s::set r::set) *)
(* (lambda (a::address) *)
(* (and (s a) (not (r a)))))) *)
let smt_setdiff_def buf num_addrs =
let str = ref " (store empty null (and (select s1 null) (not (select s2 null))))" in
for i = 1 to num_addrs do
let a_str = addr_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^a_str^ " (and (select s1 " ^a_str^ ") (not (select s2 " ^a_str^ "))))"
done;
B.add_string buf
("(define-fun setdiff ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) " ^set_s^ "\n" ^ (!str) ^ ")\n")
(* (define subseteq::(-> set set bool) *)
( lambda ( s1::set )
(* (and (if (s1 null) (s2 null)) *)
(* (if (s1 a1) (s2 a1)) *)
(* (if (s1 a1) (s2 a2)) *)
(* (if (s1 a3) (s2 a3)) *)
(* (if (s1 a4) (s2 a4)) *)
(* (if (s1 a5) (s2 a5))))) *)
let smt_subseteq_def buf num_addr =
B.add_string buf
("(define-fun subseteq ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) "^bool_s^ "\n" ^
" (and (=> (select s1 null) (select s2 null))\n");
for i = 1 to num_addr do
let a_str = addr_prefix ^ (string_of_int i) in
B.add_string buf
(" (=> (select s1 " ^a_str^ ") (select s2 " ^a_str^ "))\n")
done;
B.add_string buf ("))\n")
(* (define eqset::(-> set set bool) *)
let smt_eqset_def buf num_addr =
B.add_string buf
("(define-fun eqset ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) "^bool_s^ "\n" ^
" (and (= (select s1 null) (select s2 null))\n");
for i = 1 to num_addr do
let a_str = addr_prefix ^ (string_of_int i) in
B.add_string buf
(" (= (select s1 " ^a_str^ ") (select s2 " ^a_str^ "))\n")
done;
B.add_string buf ("))\n")
( define set2elem::(- > set )
(* (lambda (s::set m::mem) *)
(* (lambda (e::elem) *)
(* (or (and (= e (data (m null))) (s null)) *)
(* (and (= e (data (m aa_1))) (s aa_1)) *)
(* (and (= e (data (m aa_2))) (s aa_2)) *)
(* (and (= e (data (m aa_3))) (s aa_3)))))) *)
let smt_settoelems_def buf num_addrs =
let str = ref " (store emptyelem (data (select m null)) (select s null))\n" in
for i=1 to num_addrs do
let aa_i = addr_prefix ^ (string_of_int i) in
str := " (unionelem\n" ^ !str ^
" (store emptyelem (data (select m " ^aa_i^ ")) (select s " ^aa_i^ ")))\n"
done;
B.add_string buf
("(define-fun set2elem ((s " ^set_s^ ") (m " ^heap_s^ ")) " ^setelem_s^
"\n" ^ !str ^ ")\n")
( define > heap path range_address tid )
(* (lambda (h::heap p::path i::range_address)) *)
(* (lock (h ((select p at) i)))) *)
(* (define islockedpos::(-> heap path range_address bool) *)
(* (lambda (h::heap p::path i::range_address)) *)
(* (and (< i (select p length)) (/= notid (getlockat h p i)))) *)
(* (define firstlockfrom5::(-> heap path address) *)
(* (lambda (h::heap p::path)) *)
( if ( islockedpos h p 5 ) ( getlockat h p 5 ) null ) )
(* (define firstlockfrom4::(-> heap path address) *)
(* (lambda (h::heap p::path)) *)
( if ( islockedpos h p 4 ) ( getlockat h p 4 ) ( firstlockfrom5 h p ) ) )
(* (define firstlockfrom3::(-> heap path address) *)
(* (lambda (h::heap p::path)) *)
( if ( islockedpos h p 3 ) ( getlockat h p 3 ) ( firstlockfrom4 h p ) ) )
(* (define firstlockfrom2::(-> heap path address) *)
(* (lambda (h::heap p::path)) *)
( if ( islockedpos h p 2 ) ( getlockat h p 2 ) ( firstlockfrom3 h p ) ) )
( define firstlockfrom1::(- > heap path address )
(* (lambda (h::heap p::path)) *)
( if ( islockedpos h p 1 ) ( getlockat h p 1 ) ( firstlockfrom2 h p ) ) )
(* (define firstlock::(-> heap path address) *)
(* (lambda (h::heap p::path)) *)
( if ( islockedpos h p 0 ) ( getlockat h p 0 ) ( firstlockfrom1 h p ) ) )
let smt_firstlock_def buf num_addr =
let strlast = (string_of_int num_addr) in
B.add_string buf
("(define-fun getlockat ((h " ^heap_s^ ") (p " ^path_s^
") (i RangeAddress)) " ^tid_s^ "\n" ^
" (if (is_valid_range_address i) (lock (select h (select (at p) i))) notid))\n" ^
"(define-fun getaddrat ((p " ^path_s^ ") (i RangeAddress)) " ^addr_s^ "\n" ^
" (if (is_valid_range_address i) (select (at p) i) null))\n" ^
"(define-fun islockedpos ((h " ^heap_s^ ") (p " ^path_s^
") (i RangeAddress)) " ^bool_s^ "\n" ^
" (if (is_valid_range_address i) (and (< i (length p)) (not (= notid (getlockat h p i)))) false))\n");
B.add_string buf
("(define-fun firstlockfrom" ^ strlast ^ " ((h " ^heap_s^ ") (p " ^path_s^ ")) " ^addr_s^ "\n" ^
" (if (islockedpos h p " ^ strlast ^ ") (getaddrat p " ^ strlast ^ ") null))\n");
for i=(num_addr-1) downto 1 do
let stri = (string_of_int i) in
let strnext = (string_of_int (i+1)) in
B.add_string buf
("(define-fun firstlockfrom"^ stri ^" ((h " ^heap_s^ ") (p " ^path_s^ ")) " ^addr_s^ "\n" ^
" (if (islockedpos h p "^ stri ^") (getaddrat p "^ stri ^") (firstlockfrom"^ strnext ^" h p)))\n");
done ;
B.add_string buf
("(define-fun firstlock ((h " ^heap_s^ ") (p " ^path_s^ ") ) " ^addr_s^ "\n" ^
" (if (islockedpos h p 0) (getaddrat p 0) (firstlockfrom1 h p)))\n")
(* (define cell_lock::(-> cell tid cell) *)
(* (lambda (c::cell t::tid)) *)
(* (mkcell (next c) (data c) t)) *)
let smt_cell_lock buf =
B.add_string buf
("(declare-fun cell_lock (" ^cell_s^ " " ^tid_s^ ") " ^cell_s^ ")\n")
(* (define cell_unlock::(-> cell cell) *)
(* (lambda (c::cell)) *)
(* (mkcell (next c) (data c) notid)) *)
let smt_cell_unlock_def buf =
B.add_string buf
("(declare-fun cell_unlock (" ^cell_s^ ") " ^cell_s^ ")\n")
(* (define epsilonat::(-> range_address address) *)
(* (lambda r::range_address) null) *)
(* (define epsilonwhere::(-> address range_address) *)
(* (lambda a::address) 0) *)
(* (define epsilon::path *)
( mk - record length::0 at::epsilonat where::epsilonwhere ) )
let smt_epsilon_def buf num_addr =
let _ = GM.sm_decl_const sort_map "epsilon" path_s in
let mkpath_str = "mkpath 0 epsilonat epsilonwhere empty" in
B.add_string buf
("(declare-fun epsilonat () PathAt)\n");
for i = 0 to (num_addr + 1) do
B.add_string buf
("(assert (= (select epsilonat " ^(string_of_int i)^ ") null))\n")
done;
B.add_string buf
("(declare-fun epsilonwhere () PathWhere)\n" ^
"(assert (= (select epsilonwhere null) 0))\n");
for i = 1 to num_addr do
B.add_string buf
("(assert (= (select epsilonwhere " ^(addr_prefix ^ (string_of_int i))^ ") 0))\n")
done;
B.add_string buf
("(declare-fun epsilon () " ^path_s^ ")\n" ^
"(assert (= epsilon (" ^mkpath_str^ ")))\n");
B.add_string buf
("(assert (and (= (length (" ^mkpath_str^ ")) 0)\n\
(= (at (" ^mkpath_str^ ")) epsilonat)\n\
(= (where (" ^mkpath_str^ ")) epsilonwhere)\n\
(= (addrs (" ^mkpath_str^ ")) empty)))\n")
(* (define singletonat::(-> address range_address address) *)
(* (lambda (a::address) *)
( lambda ( r::range_address )
(* (if (= r 0) a null)))) *)
(* (define singletonwhere::(-> address address range_address) *)
(* (lambda (a::address) *)
(* (lambda (b::address) *)
( if (= a b ) 0 1 ) ) ) )
(* (define singlepath::(-> address path) *)
(* (lambda (a::address) *)
(* (mk-record length::1 at::(singletonat a) where::(singletonwhere a)))) *)
let smt_singletonpath_def buf num_addr =
let mkpath_str = "mkpath 1 (singletonat a) (singletonwhere a) (singleton a)" in
B.add_string buf
("(define-fun singletonat ((a " ^addr_s^ ")) PathAt\n" ^
" (store epsilonat 0 a))\n" ^
"(declare-fun singlewhere () PathWhere)\n" ^
"(assert (= (select singlewhere null) 1))\n");
for i = 1 to num_addr do
B.add_string buf
("(assert (= (select singlewhere " ^(addr_prefix ^ (string_of_int i))^ ") 1))\n")
done;
B.add_string buf
("(define-fun singletonwhere ((a " ^addr_s^ ")) PathWhere\n" ^
" (store singlewhere a 0))\n" ^
"(define-fun singlepath ((a " ^addr_s^ ")) " ^path_s^ "\n" ^
" (" ^mkpath_str^ "))\n");
B.add_string buf
("(assert (and (= (length (" ^mkpath_str^ ")) 1)\n\
(= (at (" ^mkpath_str^ ")) (singletonat a))\n\
(= (where (" ^mkpath_str^ ")) (singletonwhere a))\n\
(= (addrs (" ^mkpath_str^ ")) (singleton a))))\n")
(* (define check_position::(-> path range_address bool) *)
( lambda ( p::path i::range_address )
(= > ( < i ( select p length ) ) (= i ( ( select p where ) ( ( select p at ) i ) ) ) ) ) )
( define ispath::(- > path bool )
(* (lambda (p::path) *)
(* (and (check_position p 0) *)
(* (check_position p 1) *)
(* (check_position p 2) *)
(* (check_position p 3) *)
(* (check_position p 4) *)
(* (check_position p 5)))) *)
let smt_ispath_def buf num_addr =
B.add_string buf
("(define-fun check_position ((p " ^path_s^ ") (i RangeAddress)) " ^bool_s^ "\n" ^
" (=> (and (is_valid_range_address i)\n" ^
" (< i (length p)))\n" ^
" (and (= i (select (where p) (select (at p) i))) (isaddr (select (at p) i)))))\n");
B.add_string buf
("(define-fun ispath ((p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and");
for i=0 to num_addr do
B.add_string buf
("\n (check_position p " ^ (string_of_int i) ^ ")")
done ;
B.add_string buf "))\n"
(* (define rev_position::(-> path path range_address bool) *)
(* (lambda (p::path p_rev::path i::range_address) *)
(* (=> (< (i (select p length))) *)
(* (= ((select p at) i) ((select p_rev at) (- (select p length) i)))))) *)
(* (define rev::(-> path path bool) *)
(* (lambda (p::path p_rev::path) *)
(* (and (= (select p length) (select p_rev length)) *)
(* (rev_position p p_rev 0) *)
( rev_position p p_rev 1 )
( rev_position p p_rev 2 )
( rev_position p p_rev 3 )
( rev_position p p_rev 4 )
( rev_position p p_rev 5 ) ) ) )
let smt_rev_def buf num_addr =
B.add_string buf
("(define-fun rev_position ((p " ^path_s^ ") (p_rev " ^path_s^ ") (i RangeAddress)) " ^bool_s^ "\n" ^
" (=> (and (is_valid_range_address i)\n" ^
" (< i (length p)))\n" ^
" (= (select (at p) i) (select (at p_rev) (- (length p) i)))))\n");
B.add_string buf
("(define-fun rev ((p " ^path_s^ ") (p_rev " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (= (length p) (length p_rev))");
for i=0 to num_addr do
B.add_string buf
( "\n (rev_position p p_rev " ^ (string_of_int i) ^")" )
done ;
B.add_string buf "))\n"
( define path2set::(- > path set )
(* (lambda (p::path) *)
(* (lambda (a::address) *)
( < ( ( select p where ) a ) ( select p length ) ) ) ) )
let smt_path2set_def buf =
B.add_string buf
("(define-fun path2set ((p " ^path_s^ ")) " ^set_s^ " (addrs p))\n")
(* (define deref::(-> heap address cell) *)
(* (lambda (h::heap a::address) *)
(* (h a))) *)
let smt_dref_def buf =
B.add_string buf
("(define-fun deref ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^cell_s^ "\n" ^
" (select h a))\n")
let smt_elemorder_def buf =
B.add_string buf
("(define-fun lesselem ((x " ^elem_s^ ") (y " ^elem_s^ ")) " ^bool_s^ " (< x y))\n" ^
"(define-fun greaterelem ((x " ^elem_s^ ") (y " ^elem_s^ ")) " ^bool_s^ " (> x y))\n")
(* Ordered list predicate definition *)
let smt_orderlist_def buf num_addr =
let idlast = string_of_int num_addr in
B.add_string buf
("(define-fun orderlist" ^idlast^ " ((h " ^heap_s^ ") " ^
"(a " ^addr_s^ ") (b " ^addr_s^ ")) " ^bool_s^ " \n" ^
" true)\n");
for i = (num_addr-1) downto 1 do
let id = string_of_int i in
let idnext = string_of_int (i+1) in
B.add_string buf
("(define-fun orderlist" ^id^ " ((h " ^heap_s^ ") (a " ^addr_s^ ") ( b " ^addr_s^ ")) " ^bool_s^ "\n" ^
" (and (isaddr a)\n" ^
" (isaddr b)\n" ^
" (isaddr (next" ^id^ " h a))\n" ^
" (or (= (next" ^id^ " h a) b)\n" ^
" (and (lesselem (data (select h (next" ^id^ " h a)))\n" ^
" (data (select h (next" ^idnext^ " h a))))\n" ^
" (iselem (data (select h (next" ^id^ " h a))))\n" ^
" (iselem (data (select h (next" ^idnext^ " h a))))\n" ^
" (isaddr (next" ^idnext^ " h a))\n" ^
" (orderlist" ^idnext^ " h a b)))))\n")
done;
B.add_string buf
("(define-fun orderlist ((h " ^heap_s^ ") (a " ^addr_s^ ") (b " ^addr_s^ ")) " ^bool_s^ "\n" ^
" (and (isaddr a)\n" ^
" (isaddr b)\n" ^
" (or (= a b)\n" ^
" (and (lesselem (data (select h a))\n" ^
" (data (select h (next1 h a))))\n" ^
" (iselem (data (select h a)))\n" ^
" (iselem (data (select h (next1 h a))))\n" ^
" (isaddr (next1 h a))\n" ^
" (orderlist1 h a b)))))\n")
(* (define error::cell) *)
let smt_error_def buf=
let _ = GM.sm_decl_const sort_map "error" cell_s in
B.add_string buf
("(declare-fun error () " ^cell_s^ ")\n" ^
"(assert (= (lock error) notid))\n" ^
"(assert (= " ^next "error"^ " null))\n")
( define mkcell::(- > element address tid cell )
(* (lambda (h::heap e::element a::address k::tid) *)
( mk - record data::e next::a lock::k ) ) )
let smt_mkcell_def buf =
B.add_string buf
Unneeded
(* (define isheap::(-> heap bool) *)
(* (lambda (h::heap) *)
(* (= (deref h null) error))) *)
let smt_isheap_def buf =
B.add_string buf
("(define-fun isheap ((h " ^heap_s^ ")) " ^bool_s^ "\n" ^
" (= (select h null) error))\n")
(* (define next1::(-> heap address address) (lambda (h::heap a::address) (next h a))) *)
(* (define next2::(-> address address) (lambda (a::address) (next h (next1 h a)))) *)
( define next3::(- > address address ) ( lambda ( a::address ) ( next h ( next2 h a ) ) ) )
( define next4::(- > address address ) ( lambda ( a::address ) ( next h ( next3 h a ) ) ) )
( define next5::(- > address address ) ( lambda ( a::address ) ( next h ( next4 h a ) ) ) )
(* (define isreachable::(-> heap address address bool) *)
(* (lambda (h::heap from::address to::address) *)
(* (or (= from to) *)
(* (= (next from) to) *)
(* (= (next2 from) to) *)
(= ( next3 from ) to )
(= ( next4 from ) to ) ) ) )
let smt_nextiter_def buf num_addr =
if (num_addr >= 2) then
B.add_string buf
("(define-fun next0 ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^addr_s^ " a)\n");
B.add_string buf
("(define-fun next1 ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^addr_s^ "\n" ^
" (next (select h a)))\n");
for i=2 to num_addr do
B.add_string buf
("(define-fun next"^ (string_of_int i) ^" ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^addr_s^ "\n" ^
" (next (select h (next"^ (string_of_int (i-1)) ^" h a))))\n")
done
let smt_reachable_def buf num_addr =
B.add_string buf
("(define-fun isreachable ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^bool_s^ "\n" ^
" (and (isaddr from)\n" ^
" (isaddr to)\n" ^
" (isaddr (next0 h to))\n" ^
" (isaddr (next1 h to))\n");
for i = 2 to num_addr do
B.add_string buf
(" (isaddr (next" ^(string_of_int i)^ " h to))\n")
done;
B.add_string buf
(" (or (= from to)\n" ^
" (= (next (select h from)) to)\n");
for i=2 to num_addr do
B.add_string buf
( "\n (= (next" ^ (string_of_int i) ^ " h from) to)" )
done ;
B.add_string buf ")))\n"
(* (define address2set::(-> address set) *)
(* (lambda (from::address) *)
(* (lambda (to::address) *)
(* (isreachable from to)))) *)
let smt_address2set_def buf num_addr =
let join_sets s1 s2 = "\n (setunion "^ s1 ^" "^ s2 ^")" in
B.add_string buf
("(define-fun address2set ((h " ^heap_s^ ") (from " ^addr_s^ ")) " ^set_s^ "");
B.add_string buf
begin
match num_addr with
0 -> "\n (singleton from))\n"
| 1 -> "\n (setunion (singleton from) (singleton (next (select h from)))))\n"
| _ -> let basic = "\n (setunion (singleton from) (singleton (next (select h from))))" in
let addrs = LeapLib.rangeList 2 num_addr in
let str = List.fold_left (fun s i ->
join_sets ("(singleton (next"^ (string_of_int i) ^ " h from))") s
) basic addrs
in
str^")\n"
end
( define > address path bool )
(* (lambda (a::address p::path) *)
( and ( ispath p )
(= ( ( select p length ) 1 )
(* (= ((select p at) 0) a))))) *)
let smt_is_singlepath buf =
B.add_string buf
("(define-fun is_singlepath ((a " ^addr_s^ ") (p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (ispath p)\n" ^
" (= (length p) 1)\n" ^
" (= (select (at p) 0) a)))\n")
(* (define update_heap::(-> heap address cell heap) *)
(* (lambda (h::heap a::address c::cell) *)
(* (update h a c))) *)
let smt_update_heap_def buf =
B.add_string buf
("(define-fun update_heap ((h " ^heap_s^ ") (a " ^addr_s^ ") (c " ^cell_s^ ")) " ^heap_s^ "\n" ^
" (store h a c))\n")
(* (define update_pathat::(-> pathat range_address address pathat) *)
( lambda ( f::pathat i::range_address a::address )
(* (lambda (j::range_address) *)
(* (if (= i j) a (f j))))) *)
(* (define update_pathwhere::(-> pathwhere address range_address pathwhere) *)
(* (lambda (g::pathwhere a::address i::range_address) *)
(* (lambda (b::address) *)
(* (if (= b a) i (g b))))) *)
(* (define add_to_path::(-> path address path) *)
(* (lambda (p::path a::address) *)
( mk - record length::(+ 1 ( select p length ) )
at::(update_pathat ( select p at ) ( select p length ) a )
where::(update_pathwhere ( select p where ) a ( select p length ) ) ) ) )
(* (define path1::(-> heap address path) *)
(* (lambda (h::heap a::address) *)
(* (singlepath a))) *)
(* (define path2::(-> heap address path) *)
(* (lambda (h::heap a::address) *)
( add_to_path ( path1 h a ) ( next h a ) ) ) )
(* (define path3::(-> heap address path) *)
(* (lambda (h::heap a::address) *)
(* (add_to_path (path2 h a) (next2 h a)))) *)
(* (define path4::(-> heap address path) *)
(* (lambda (h::heap a::address) *)
( add_to_path ( path3 h a ) ( next3 h a ) ) ) )
(* (define getp4::(-> heap address address path) *)
(* (lambda (h::heap from::address to::address) *)
( if (= ( next3 h from ) to )
( path4 h from )
(* epsilon))) *)
(* (define getp3::(-> heap address address path) *)
(* (lambda (h::heap from::address to::address) *)
(* (if (= (next2 h from) to) *)
( h from )
( getp4 h from to ) ) ) )
(* (define getp2::(-> heap address address path) *)
(* (lambda (h::heap from::address to::address) *)
( if (= ( next h from ) to )
(* (path2 h from) *)
( h from to ) ) ) )
(* (define getp1::(-> heap address address path) *)
(* (lambda (h::heap from::address to::address) *)
(* (if (= from to) *)
( path1 h from )
( from to ) ) ) )
(* (define getp::(-> heap address address path) *)
(* (lambda (h::heap from::address to::address) *)
(* (getp1 h from to))) *)
let smt_getp_def buf num_addr =
B.add_string buf
("(define-fun update_pathat ((f PathAt) (i RangeAddress) (a " ^addr_s^ ")) PathAt\n" ^
" (if (is_valid_range_address i) (store f i a) f))\n" ^
"(define-fun update_pathwhere ((g PathWhere) (a " ^addr_s^ ") (i RangeAddress)) PathWhere\n" ^
" (if (is_valid_range_address i) (store g a i) g))\n");
" ( define - fun add_to_path ( ( p " ^path_s^ " ) ( a " ^addr_s^ " ) ) " ^path_s^ " \n " ^
" ( mkpath ( + 1 ( length p))\n " ^
" ( update_pathat ( at p ) ( length p ) a)\n " ^
" ( update_pathwhere ( where p ) a ( length p))\n " ^
" ( setunion ( addrs p ) ( singleton " ) ;
" (mkpath (+ 1 (length p))\n" ^
" (update_pathat (at p) (length p) a)\n" ^
" (update_pathwhere (where p) a (length p))\n" ^
" (setunion (addrs p) (singleton a))))\n");
*)
B.add_string buf
("(define-fun path1 ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^path_s^ "\n" ^
" (singlepath a))\n");
for i=2 to ( ) do
let stri= string_of_int i in
let strpre = string_of_int ( i-1 ) in
let p_str = " ( path"^ strpre ^ " h a ) " in
let next_str = " ( next"^ strpre ^ " h a ) " in
let arg1 = " ( + 1 ( length " ^p_str^ " ) ) " in
let = " ( update_pathat ( at " ^p_str^ " ) ( length " ^p_str^ " ) " ^next_str^ " ) " in
let arg3 = " ( update_pathwhere ( where " ^p_str^ " ) " ^next_str^ " ( length " ^p_str^ " ) ) " in
let arg4 = " ( setunion ( addrs " ^p_str^ " ) ( singleton " ^next_str^ " ) ) " in
let " mkpath " ^arg1^ " " ^
" " ^arg2^ " \n " ^
" " ^arg3^ " \n " ^
" " ^arg4 in
B.add_string buf
( " ( define - fun path"^ stri ^ " ( ( h " ^heap_s^ " ) ( a " ^addr_s^ " ) ) " ^path_s^ " \n " ^
" ( " ^mkpath_str^ " ) ) \n " ) ;
B.add_string buf
( " ( assert ( and (= ( length ( " ^mkpath_str^ " ) ) " ^arg1^ " ) \n\
(= ( at ( " ^mkpath_str^ " ) ) " ^arg2^ " ) \n\
(= ( where ( " ^mkpath_str^ " ) ) " ^arg3^ " ) \n\
(= ( ( " ^mkpath_str^ " ) ) " ^arg4^ " ) ) ) \n " )
done ;
for i=2 to (num_addr +1) do
let stri= string_of_int i in
let strpre = string_of_int (i-1) in
let p_str = "(path"^ strpre ^" h a)" in
let next_str = "(next"^ strpre ^" h a)" in
let arg1 = "(+ 1 (length " ^p_str^ "))" in
let arg2 = "(update_pathat (at " ^p_str^ ") (length " ^p_str^ ") " ^next_str^ ")" in
let arg3 = "(update_pathwhere (where " ^p_str^ ") " ^next_str^ " (length " ^p_str^ "))" in
let arg4 = "(setunion (addrs " ^p_str^ ") (singleton " ^next_str^ "))" in
let mkpath_str = " mkpath " ^arg1^ "\n" ^
" " ^arg2^ "\n" ^
" " ^arg3^ "\n" ^
" " ^arg4 in
B.add_string buf
("(define-fun path"^ stri ^" ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^path_s^ "\n" ^
" (" ^mkpath_str^ "))\n");
B.add_string buf
("(assert (and (= (length (" ^mkpath_str^ ")) " ^arg1^ ")\n\
(= (at (" ^mkpath_str^ ")) " ^arg2^ ")\n\
(= (where (" ^mkpath_str^ ")) " ^arg3^ ")\n\
(= (addrs (" ^mkpath_str^ ")) " ^arg4^ ")))\n")
done ;
*)
B.add_string buf
("(define-fun getp"^ (string_of_int (num_addr + 1)) ^" ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (if (= (next"^ (string_of_int num_addr) ^" h from) to)\n" ^
" (path"^ (string_of_int num_addr) ^" h from)\n" ^
" epsilon))\n");
for i=num_addr downto 1 do
let stri = string_of_int i in
let strpre = string_of_int (i-1) in
let strnext = string_of_int (i+1) in
B.add_string buf
("(define-fun getp"^ stri ^" ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (if (= (next"^ strpre ^" h from) to)\n" ^
" (path"^ stri ^" h from)\n" ^
" (getp"^ strnext ^" h from to)))\n")
done ;
B.add_string buf
("(define-fun getp ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (getp1 h from to))\n");
B.add_string buf
("(define-fun isgetp ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ") (p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (eqpath p (getp h from to)))\n")
let smt_getp_def buf num_addr =
B.add_string buf
("(define-fun getp"^ (string_of_int (num_addr + 1)) ^" ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (if (= (next"^ (string_of_int num_addr) ^" h from) to)\n" ^
" (path"^ (string_of_int num_addr) ^" h from)\n" ^
" epsilon))\n");
for i=num_addr downto 1 do
let stri = string_of_int i in
let strpred = string_of_int (i-1) in
let strsucc = string_of_int (i+1) in
B.add_string buf
("(define-fun getp"^ stri ^" ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (if (= (next"^ strpred ^" h from) to)\n" ^
" (path"^ stri ^" h from)\n" ^
" (getp"^ strsucc ^" h from to)))\n")
done ;
B.add_string buf
("(define-fun getp ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (getp1 h from to))\n");
B.add_string buf
("(define-fun isgetp ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ") (p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (eqpath p (getp h from to)))\n")
let smt_reach_def buf =
B.add_string buf
( "(define-fun reach ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ") (p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (ispath p) (eqpath (getp h from to) p) (not (eqpath p epsilon))))\n"
)
(* (define path_length::(-> path range_address) *)
(* (lambda (p1::path) *)
(* (select p1 length))) *)
let smt_path_length_def buf =
B.add_string buf
("(define-fun path_length ((p " ^path_s^ ")) RangeAddress (length p))\n")
(* (define at_path::(-> path range_address address) *)
( lambda ( p1::path i::range_address )
(* ((select p1 at) i))) *)
let smt_at_path_def buf =
B.add_string buf
("(define-fun at_path ((p " ^path_s^ ") (i RangeAddress)) " ^addr_s^ "\n" ^
" (if (is_valid_range_address i) (select (at p) i) null))\n")
( define > path range_address path range_address bool )
( lambda ( p1::path )
( ite ( < i ( path_length p1 ) )
(* (= (at_path p1 i) (at_path p2 j)) *)
(* true))) *)
let smt_equal_paths_at_def buf =
B.add_string buf
("(define-fun equal_paths_at ((p1 " ^path_s^ ") (i RangeAddress) (p2 " ^path_s^ ") (j RangeAddress)) " ^bool_s^ "\n" ^
" (if (< i (path_length p1))\n" ^
" (= (at_path p1 i) (at_path p2 j))\n" ^
" true))\n")
( define is_append::(- > path path path bool )
(* (lambda (p1::path p2::path p_res::path) *)
( and (= ( + ( path_length p1 ) ( path_length p2 ) ) ( path_length p_res ) )
( equal_paths_at p1 0 p_res 0 )
( equal_paths_at p1 1 p_res 1 )
( equal_paths_at p1 2 p_res 2 )
( equal_paths_at p1 3 p_res 3 )
( equal_paths_at p1 4 p_res 4 )
( equal_paths_at p1 5 p_res 5 )
( equal_paths_at p2 0 p_res ( + ( path_length p1 ) 0 ) )
( equal_paths_at p2 1 p_res ( + ( path_length p1 ) 1 ) )
( equal_paths_at p2 2 p_res ( + ( path_length p1 ) 2 ) )
( equal_paths_at p2 3 p_res ( + ( path_length p1 ) 3 ) )
( equal_paths_at p2 4 p_res ( + ( path_length p1 ) 4 ) )
( equal_paths_at p2 5 p_res ( + ( path_length p1 ) 5 ) ) ) ) )
let smt_is_append_def buf num_addr =
B.add_string buf
("(define-fun is_append ((p1 " ^path_s^ ") (p2 " ^path_s^ ") (p_res " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (= (+ (path_length p1) (path_length p2)) (path_length p_res))");
for i=0 to num_addr do
let str_i = (string_of_int i) in
B.add_string buf
( "\n (equal_paths_at p1 " ^ str_i ^ " p_res " ^ str_i ^ ")" )
done ;
for i=0 to num_addr do
let str_i = string_of_int i in
B.add_string buf
( "\n (equal_paths_at p2 " ^ str_i ^ " p_res (+ (path_length p1) " ^ str_i ^ "))" )
done ;
B.add_string buf "))\n"
(************************* Declarations **************************)
(********************* Preamble Declaration **********************)
let update_requirements (req_sorts:Expr.sort list)
(req_ops:Expr.special_op_t list)
: (Expr.sort list * Expr.special_op_t list) =
let (res_req_sorts, res_req_ops) = (ref req_sorts, ref req_ops) in
If " path " is a required sort , then we need to add " set " as required sort
since " set " is part of the definition of sort " path " ( required by " "
field )
since "set" is part of the definition of sort "path" (required by "addrs"
field) *)
if (List.mem Expr.Path req_sorts) then
res_req_sorts := Expr.Set :: !res_req_sorts ;
(!res_req_sorts, !res_req_ops)
let smt_preamble buf num_addr num_tid num_elem req_sorts =
if (List.exists (fun s ->
s=Expr.Addr || s=Expr.Cell || s=Expr.Path || s=Expr.Set || s=Expr.Mem
) req_sorts) then smt_addr_preamble buf num_addr ;
if (List.exists (fun s ->
s=Expr.Tid || s=Expr.Cell || s=Expr.SetTh
) req_sorts) then smt_tid_preamble buf num_tid ;
if (List.exists (fun s ->
s=Expr.Elem || s=Expr.Cell || s=Expr.Mem
) req_sorts) then smt_element_preamble buf num_elem ;
if List.mem Expr.Cell req_sorts || List.mem Expr.Mem req_sorts then
smt_cell_preamble buf ;
if List.mem Expr.Mem req_sorts then smt_heap_preamble buf ;
if List.mem Expr.Set req_sorts then smt_set_preamble buf ;
if List.mem Expr.SetTh req_sorts then smt_setth_preamble buf ;
if List.mem Expr.SetElem req_sorts then smt_setelem_preamble buf ;
if List.mem Expr.Path req_sorts then begin
smt_path_preamble buf num_addr ;
smt_ispath_def buf num_addr
end;
if List.mem Expr.Unknown req_sorts then smt_unknown_preamble buf ;
smt_pos_preamble buf
let smt_defs buf num_addr num_tid num_elem req_sorts req_ops =
(* Elements *)
if List.mem Expr.ElemOrder req_ops || List.mem Expr.OrderedList req_ops then
smt_elemorder_def buf ;
(* Cells and Heap *)
if List.mem Expr.Cell req_sorts || List.mem Expr.Mem req_sorts then
smt_error_def buf ;
(* Cell *)
if List.mem Expr.Cell req_sorts then
begin
smt_mkcell_def buf ;
smt_cell_lock buf ;
smt_cell_unlock_def buf
end;
Heap
if List.mem Expr.Mem req_sorts then
begin
smt_isheap_def buf ;
smt_dref_def buf ;
smt_update_heap_def buf
end;
(* Sets *)
if List.mem Expr.Set req_sorts then
begin
smt_emp_def buf num_addr ;
smt_singleton_def buf ;
smt_union_def buf num_addr ;
smt_intersection_def buf num_addr ;
smt_setdiff_def buf num_addr ;
smt_subseteq_def buf num_addr ;
smt_eqset_def buf num_addr
end;
(* Iterations over next *)
if List.mem Expr.Addr2Set req_ops
|| List.mem Expr.Reachable req_ops
|| List.mem Expr.OrderedList req_ops then
smt_nextiter_def buf num_addr ;
(* Address2set *)
if List.mem Expr.Addr2Set req_ops then
begin
smt_reachable_def buf num_addr ;
smt_address2set_def buf num_addr
end;
(* OrderedList *)
if List.mem Expr.OrderedList req_ops then smt_orderlist_def buf num_addr ;
(* Path2set *)
if List.mem Expr.Path2Set req_ops then smt_path2set_def buf ;
(* Sets of Threads *)
if List.mem Expr.SetTh req_sorts then
begin
smt_empth_def buf num_tid ;
smt_singletonth_def buf ;
smt_unionth_def buf num_tid ;
smt_intersectionth_def buf num_tid ;
smt_setdiffth_def buf num_tid ;
smt_subseteqth_def buf num_tid ;
smt_eqsetth_def buf num_tid
end;
(* Sets of Elements *)
if List.mem Expr.SetElem req_sorts then
begin
smt_empelem_def buf num_elem ;
smt_singletonelem_def buf ;
smt_unionelem_def buf num_elem ;
smt_intersectionelem_def buf num_elem ;
smt_setdiffelem_def buf num_elem ;
smt_subseteqelem_def buf num_elem ;
smt_eqsetelem_def buf num_elem
end;
(* Set2Elem *)
if List.mem Expr.Set2Elem req_ops then smt_settoelems_def buf num_addr ;
Firstlock
if List.mem Expr.FstLocked req_ops then smt_firstlock_def buf num_addr ;
(* Path *)
if List.mem Expr.Path req_sorts then
begin
smt_rev_def buf num_addr ;
smt_epsilon_def buf num_addr ;
smt_singletonpath_def buf num_addr ;
smt_is_singlepath buf ;
smt_path_length_def buf ;
smt_at_path_def buf ;
smt_equal_paths_at_def buf ;
smt_is_append_def buf num_addr
end;
if List.mem Expr.Getp req_ops ||
List.mem Expr.Reachable req_ops then smt_getp_def buf num_addr ;
Reachable
if List.mem Expr.Reachable req_ops then smt_reach_def buf
(********************* Preamble Declaration **********************)
let rec smt_define_var (buf:Buffer.t)
(tid_set:Expr.V.VarSet.t)
(num_tids:int)
(v:Expr.V.t) : unit =
let (id,s,pr,th,p) = v in
let sort_str asort = match asort with
Expr.Set -> set_s
| Expr.Elem -> elem_s
| Expr.Addr -> addr_s
| Expr.Tid -> tid_s
| Expr.Cell -> cell_s
| Expr.SetTh -> setth_s
| Expr.SetElem -> setelem_s
| Expr.Path -> path_s
| Expr.Mem -> heap_s
| Expr.Unknown -> unk_s in
let s_str = sort_str s in
let p_id = Option.map_default (fun str -> str ^ "_" ^ id) id p in
let name = p_id (* if pr then p_id ^ "_prime" else p_id *)
in
if Expr.V.is_global v then
begin
GM.sm_decl_const sort_map name
(GM.conv_sort (TLLInterface.sort_to_expr_sort s)) ;
B.add_string buf ( "(declare-fun " ^ name ^ " () " ^ s_str ^ ")\n" );
match s with
| Expr.Addr -> B.add_string buf ( "(assert (isaddr " ^name^ "))\n" )
| Expr.Elem -> B.add_string buf ( "(assert (iselem " ^name^ "))\n" )
| Expr.Path -> B.add_string buf ( "(assert (ispath " ^name^ "))\n" )
| Expr.Mem -> B.add_string buf ( "(assert (isheap " ^name^ "))\n" )
| Expr.Tid -> B.add_string buf ( "(assert (not (= " ^ name ^ " notid)))\n" );
B.add_string buf ( "(assert (istid " ^name^ "))\n" );
B.add_string buf ( "(assert (in_pos_range " ^ name ^ "))\n" )
| _ -> ()
end
else
begin
GM.sm_decl_fun sort_map name [tid_s] [s_str] ;
B.add_string buf ( "(declare-fun " ^ name ^ " () (Array " ^tid_s^ " " ^ s_str ^ "))\n" );
match s with
| Expr.Addr -> B.add_string buf ("(assert (isaddr (select " ^name^ " notid)))\n");
B.add_string buf ("(assert (isaddr (select " ^name^ " tid_witness)))\n");
for i = 1 to num_tids do
B.add_string buf ("(assert (isaddr (select " ^name^ " " ^tid_prefix ^ (string_of_int i)^ ")))\n")
done
| Expr.Elem -> B.add_string buf ("(assert (iselem (select " ^name^ " notid)))\n");
B.add_string buf ("(assert (iselem (select " ^name^ " tid_witness)))\n");
for i = 1 to num_tids do
B.add_string buf ("(assert (iselem (select " ^name^ " " ^tid_prefix ^ (string_of_int i)^ ")))\n")
done
| Expr.Path -> Expr.V.VarSet.iter (fun t ->
let v_str = variable_invocation_to_str
(Expr.V.set_param v (Expr.VarTh t)) in
B.add_string buf ( "(assert (ispath " ^ v_str ^ "))\n" )
) tid_set
| Expr.Mem -> Expr.V.VarSet.iter (fun t ->
let v_str = variable_invocation_to_str
(Expr.V.set_param v (Expr.VarTh t)) in
B.add_string buf ( "(assert (isheap " ^ v_str ^ "))\n" )
) tid_set
| Expr.Tid -> Expr.V.VarSet.iter (fun t ->
let v_str = variable_invocation_to_str
(Expr.V.set_param v (Expr.VarTh t)) in
B.add_string buf ( "(assert (not (= " ^ v_str ^ " notid)))\n" )
) tid_set;
B.add_string buf ("(assert (istid (select " ^name^ " notid)))\n");
B.add_string buf ("(assert (istid (select " ^name^ " tid_witness)))\n");
for i = 1 to num_tids do
B.add_string buf ("(assert (istid (select " ^name^ " " ^tid_prefix ^ (string_of_int i)^ ")))\n")
done
| _ -> ()
FIX : Add iterations for ispath and isheap on local variables
end
and define_variables (buf:Buffer.t) (num_tids:int) (vars:Expr.V.VarSet.t) : unit =
let varset = Expr.varset_of_sort vars Expr.Set in
let varelem = Expr.varset_of_sort vars Expr.Elem in
let varaddr = Expr.varset_of_sort vars Expr.Addr in
let vartid = Expr.varset_of_sort vars Expr.Tid in
let varcell = Expr.varset_of_sort vars Expr.Cell in
let varsetth = Expr.varset_of_sort vars Expr.SetTh in
let varsetelem = Expr.varset_of_sort vars Expr.SetElem in
let varpath = Expr.varset_of_sort vars Expr.Path in
let varmem = Expr.varset_of_sort vars Expr.Mem in
let varunk = Expr.varset_of_sort vars Expr.Unknown in
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varset;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varelem;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) vartid;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varaddr;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varcell;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varsetth;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varsetelem;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varpath;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varmem;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varunk
and variables_to_smt (buf:Buffer.t)
(num_tids:int)
(expr:Expr.conjunctive_formula) : unit =
let vars = Expr.get_varset_from_conj expr
in
define_variables buf num_tids vars
and variables_from_formula_to_smt (buf:Buffer.t)
(num_tids:int)
(phi:Expr.formula) : unit =
let vars = Expr.get_varset_from_formula phi
in
define_variables buf num_tids vars
and variable_invocation_to_str (v:Expr.V.t) : string =
let (id,s,pr,th,p) = v in
let th_str = Option.map_default tidterm_to_str "" th in
let p_str = Option.map_default (fun n -> Printf.sprintf "%s_" n) "" p in
let pr_str = "" (* if pr then "_prime" else "" *)
in
if th = None then
Printf.sprintf " %s%s%s%s" p_str id th_str pr_str
else
Printf.sprintf " (select %s%s%s %s)" p_str id pr_str th_str
and setterm_to_str (sa:Expr.set) : string =
match sa with
Expr.VarSet v -> variable_invocation_to_str v
| Expr.EmptySet -> "empty"
| Expr.Singl a -> Printf.sprintf "(singleton %s)" (addrterm_to_str a)
| Expr.Union(r,s) -> Printf.sprintf "(setunion %s %s)"
(setterm_to_str r)
(setterm_to_str s)
| Expr.Intr(r,s) -> Printf.sprintf "(intersection %s %s)"
(setterm_to_str r)
(setterm_to_str s)
| Expr.Setdiff(r,s) -> Printf.sprintf "(setdiff %s %s)"
(setterm_to_str r)
(setterm_to_str s)
| Expr.PathToSet p -> Printf.sprintf "(path2set %s)"
(pathterm_to_str p)
| Expr.AddrToSet(m,a) -> Printf.sprintf "(address2set %s %s)"
(memterm_to_str m)
(addrterm_to_str a)
and elemterm_to_str (e:Expr.elem) : string =
match e with
Expr.VarElem v -> variable_invocation_to_str v
| Expr.CellData c -> let c_str = cellterm_to_str c in
data c_str
| Expr.HavocListElem -> "" (* Don't need a representation for this *)
| Expr.LowestElem -> "lowestElem"
| Expr.HighestElem -> "highestElem"
and tidterm_to_str (th:Expr.tid) : string =
match th with
Expr.VarTh v -> variable_invocation_to_str v
| Expr.NoTid -> "notid"
| Expr.CellLockId c -> let c_str = cellterm_to_str c in
lock c_str
and addrterm_to_str (a:Expr.addr) : string =
match a with
Expr.VarAddr v -> variable_invocation_to_str v
| Expr.Null -> "null"
| Expr.Next c -> Printf.sprintf "(next %s)"
(cellterm_to_str c)
| Expr.FirstLocked(m,p) -> let m_str = memterm_to_str m in
let p_str = pathterm_to_str p in
Hashtbl.add fstlock_tbl (m_str, p_str) ();
Printf.sprintf "(firstlock %s %s)" m_str p_str
and cellterm_to_str (c:Expr.cell) : string =
match c with
Expr.VarCell v -> variable_invocation_to_str v
| Expr.Error -> "error"
| Expr.MkCell(e,a,th) -> Hashtbl.add cell_tbl c ();
Printf.sprintf "(mkcell %s %s %s)"
(elemterm_to_str e)
(addrterm_to_str a)
(tidterm_to_str th)
| Expr.CellLock(c,th) -> Hashtbl.add cell_tbl c ();
Printf.sprintf "(cell_lock %s %s)"
(cellterm_to_str c)
(tidterm_to_str th)
| Expr.CellUnlock c -> Hashtbl.add cell_tbl c ();
Printf.sprintf "(cell_unlock %s)"
(cellterm_to_str c)
| Expr.CellAt(m,a) -> Printf.sprintf "(select %s %s)"
(memterm_to_str m)
(addrterm_to_str a)
and setthterm_to_str (sth:Expr.setth) : string =
match sth with
Expr.VarSetTh v -> variable_invocation_to_str v
| Expr.EmptySetTh -> "emptyth"
| Expr.SinglTh th -> Printf.sprintf "(singletonth %s)"
(tidterm_to_str th)
| Expr.UnionTh(rt,st) -> Printf.sprintf "(unionth %s %s)"
(setthterm_to_str rt)
(setthterm_to_str st)
| Expr.IntrTh(rt,st) -> Printf.sprintf "(intersectionth %s %s)"
(setthterm_to_str rt)
(setthterm_to_str st)
| Expr.SetdiffTh(rt,st) -> Printf.sprintf "(setdiffth %s %s)"
(setthterm_to_str rt)
(setthterm_to_str st)
and setelemterm_to_str (se:Expr.setelem) : string =
match se with
Expr.VarSetElem v -> variable_invocation_to_str v
| Expr.EmptySetElem -> "emptyelem"
| Expr.SinglElem e -> Printf.sprintf "(singletonelem %s)"
(elemterm_to_str e)
| Expr.UnionElem(rt,st) -> Printf.sprintf "(unionelem %s %s)"
(setelemterm_to_str rt)
(setelemterm_to_str st)
| Expr.IntrElem(rt,st) -> Printf.sprintf "(intersectionelem %s %s)"
(setelemterm_to_str rt)
(setelemterm_to_str st)
| Expr.SetToElems(s,m) -> Printf.sprintf "(set2elem %s %s)"
(setterm_to_str s) (memterm_to_str m)
| Expr.SetdiffElem(rt,st) -> Printf.sprintf "(setdiffelem %s %s)"
(setelemterm_to_str rt)
(setelemterm_to_str st)
and pathterm_to_str (p:Expr.path) : string =
match p with
Expr.VarPath v -> variable_invocation_to_str v
| Expr.Epsilon -> "epsilon"
| Expr.SimplePath a -> Printf.sprintf "(singlepath %s)"
(addrterm_to_str a)
| Expr.GetPath(m,a1,a2)-> let m_str = memterm_to_str m in
let a1_str = addrterm_to_str a1 in
let a2_str = addrterm_to_str a2 in
Hashtbl.add getp_tbl (m_str, a1_str, a2_str) ();
Printf.sprintf "(getp %s %s %s)" m_str a1_str a2_str
and memterm_to_str (m:Expr.mem) : string =
match m with
Expr.VarMem v -> variable_invocation_to_str v
| Expr.Emp -> "emp"
| Expr.Update(m,a,c) -> Printf.sprintf "(update_heap %s %s %s)"
(memterm_to_str m)
(addrterm_to_str a)
(cellterm_to_str c)
let rec varupdate_to_str (v:Expr.V.t)
(th:Expr.tid)
(t:Expr.term) : string =
let v_str = variable_invocation_to_str v in
let th_str = tidterm_to_str th in
let t_str = term_to_str t
in
Printf.sprintf "(store %s %s %s)" v_str th_str t_str
and term_to_str (t:Expr.term) : string =
match t with
Expr.VarT v -> variable_invocation_to_str v
| Expr.SetT s -> setterm_to_str s
| Expr.ElemT e -> elemterm_to_str e
| Expr.TidT th -> tidterm_to_str th
| Expr.AddrT a -> addrterm_to_str a
| Expr.CellT c -> cellterm_to_str c
| Expr.SetThT sth -> setthterm_to_str sth
| Expr.SetElemT se -> setelemterm_to_str se
| Expr.PathT p -> pathterm_to_str p
| Expr.MemT m -> memterm_to_str m
| Expr.VarUpdate(v,th,t) -> varupdate_to_str v th t
let append_to_str (p1:Expr.path) (p2:Expr.path) (p3:Expr.path) : string =
Printf.sprintf "(is_append %s %s %s)" (pathterm_to_str p1)
(pathterm_to_str p2)
(pathterm_to_str p3)
let reach_to_str (m:Expr.mem) (a1:Expr.addr)
(a2:Expr.addr) (p:Expr.path) : string =
Printf.sprintf "(reach %s %s %s %s)"
(memterm_to_str m)
(addrterm_to_str a1)
(addrterm_to_str a2)
(pathterm_to_str p)
let orderlist_to_str (m:Expr.mem) (a1:Expr.addr) (a2:Expr.addr) : string =
Printf.sprintf ("(orderlist %s %s %s)")
(memterm_to_str m)
(addrterm_to_str a1)
(addrterm_to_str a2)
let in_to_str (a:Expr.addr) (s:Expr.set) : string =
Printf.sprintf "(select %s %s)" (setterm_to_str s) (addrterm_to_str a)
let subseteq_to_str (r:Expr.set) (s:Expr.set) : string =
Printf.sprintf "(subseteq %s %s)" (setterm_to_str r)
(setterm_to_str s)
let inth_to_str (t:Expr.tid) (sth:Expr.setth) : string =
Printf.sprintf "(select %s %s)" (setthterm_to_str sth)
(tidterm_to_str t)
let subseteqth_to_str (r:Expr.setth) (s:Expr.setth) : string =
Printf.sprintf "(subseteqth %s %s)" (setthterm_to_str r)
(setthterm_to_str s)
let inelem_to_str (e:Expr.elem) (se:Expr.setelem) : string =
Printf.sprintf "(select %s %s)" (setelemterm_to_str se)
(elemterm_to_str e)
let subseteqelem_to_str (r:Expr.setelem) (s:Expr.setelem) : string =
Printf.sprintf "(subseteqelem %s %s)" (setelemterm_to_str r)
(setelemterm_to_str s)
let lesselem_to_str (e1:Expr.elem) (e2:Expr.elem) : string =
Printf.sprintf "(lesselem %s %s)" (elemterm_to_str e1) (elemterm_to_str e2)
let greaterelem_to_str (e1:Expr.elem) (e2:Expr.elem) : string =
Printf.sprintf "(greaterelem %s %s)" (elemterm_to_str e1) (elemterm_to_str e2)
let eq_to_str (t1:Expr.term) (t2:Expr.term) : string =
let str_t1 = (term_to_str t1) in
let str_t2 = (term_to_str t2) in
match t1 with
| Expr.PathT _ -> Printf.sprintf "(eqpath %s %s)" str_t1 str_t2
| Expr.SetT _ -> Printf.sprintf "(eqset %s %s)" str_t1 str_t2
| Expr.SetThT _ -> Printf.sprintf "(eqsetth %s %s)" str_t1 str_t2
| Expr.SetElemT _ -> Printf.sprintf "(eqsetelem %s %s)" str_t1 str_t2
| _ -> Printf.sprintf "(= %s %s)" str_t1 str_t2
let ineq_to_str (t1:Expr.term) (t2:Expr.term) : string =
let str_t1 = (term_to_str t1) in
let str_t2 = (term_to_str t2) in
match t1 with
Expr.PathT _ -> Printf.sprintf "(not (eqpath %s %s))" str_t1 str_t2
| _ -> Printf.sprintf "(not (= %s %s))" str_t1 str_t2
let pc_to_str (pc:int) (th:Expr.tid option) (pr:bool) : string =
let pc_str = if pr then pc_prime_name else Conf.pc_name
in
Printf.sprintf "(= (select %s %s) %s)" pc_str
(Option.map_default tidterm_to_str "" th) (linenum_to_str pc)
let pcrange_to_str (pc1:int) (pc2:int)
(th:Expr.tid option) (pr:bool) : string =
let pc_str = if pr then pc_prime_name else Conf.pc_name in
let th_str = Option.map_default tidterm_to_str "" th
in
Printf.sprintf "(and (<= %s (select %s %s)) (<= (select %s %s) %s))"
(linenum_to_str pc1) pc_str th_str pc_str th_str (linenum_to_str pc2)
let pcupdate_to_str (pc:int) (th:Expr.tid) : string =
Printf.sprintf "(= %s (store %s %s %s))"
pc_prime_name Conf.pc_name (tidterm_to_str th) (linenum_to_str pc)
let smt_partition_assumptions (parts:'a Partition.t list) : string =
let _ = LeapDebug.debug "entering smt_partition_assumptions...\n" in
let parts_str =
List.fold_left (fun str p ->
let _ = LeapDebug.debug "." in
let counter = ref 0 in
let cs = Partition.to_list p in
let p_str = List.fold_left (fun str c ->
let is_null = List.mem (Expr.AddrT Expr.Null) c in
let id = if is_null then
"null"
else
begin
incr counter;
addr_prefix ^ (string_of_int (!counter))
end in
let elems_str = List.fold_left (fun str e ->
str ^ (Printf.sprintf "(= %s %s) "
(term_to_str e) id)
) "" c in
str ^ elems_str
) "" cs in
str ^ "(and " ^ p_str ^ ")\n"
) "" parts
in
("(assert (or " ^ parts_str ^ "))\n")
let atom_to_str (at:Expr.atom) : string =
match at with
Expr.Append(p1,p2,p3) -> append_to_str p1 p2 p3
| Expr.Reach(m,a1,a2,p) -> reach_to_str m a1 a2 p
| Expr.OrderList(m,a1,a2) -> orderlist_to_str m a1 a2
| Expr.In(a,s) -> in_to_str a s
| Expr.SubsetEq(r,s) -> subseteq_to_str r s
| Expr.InTh(t,st) -> inth_to_str t st
| Expr.SubsetEqTh(rt,st) -> subseteqth_to_str rt st
| Expr.InElem(e,se) -> inelem_to_str e se
| Expr.SubsetEqElem(re,se) -> subseteqelem_to_str re se
| Expr.LessElem(e1,e2) -> lesselem_to_str e1 e2
| Expr.GreaterElem(e1,e2) -> greaterelem_to_str e1 e2
| Expr.Eq(x,y) -> eq_to_str x y
| Expr.InEq(x,y) -> ineq_to_str x y
| Expr.PC(pc,t,pr) -> pc_to_str pc t pr
| Expr.PCUpdate(pc,t) -> pcupdate_to_str pc t
| Expr.PCRange(pc1,pc2,t,pr) -> pcrange_to_str pc1 pc2 t pr
let literal_to_str (lit:Expr.literal) : string =
match lit with
Expr.Atom(a) -> (atom_to_str a)
| Expr.NegAtom(a) -> ("(not " ^ (atom_to_str a) ^")")
let rec formula_to_str (phi:Expr.formula) : string =
let to_smt = formula_to_str in
match phi with
Expr.Literal l -> literal_to_str l
| Expr.True -> " true "
| Expr.False -> " false "
| Expr.And (f1,f2) -> Printf.sprintf "(and %s %s)" (to_smt f1)
(to_smt f2)
| Expr.Or (f1,f2) -> Printf.sprintf "(or %s %s)" (to_smt f1)
(to_smt f2)
| Expr.Not f -> Printf.sprintf "(not %s)" (to_smt f)
| Expr.Implies (f1,f2) -> Printf.sprintf "(=> %s %s)" (to_smt f1)
(to_smt f2)
| Expr.Iff (f1,f2) -> Printf.sprintf "(= %s %s)" (to_smt f1)
(to_smt f2)
let literal_to_smt (buf:Buffer.t) (lit:Expr.literal) : unit =
B.add_string buf (literal_to_str lit)
let process_addr (a_expr:string) : string =
("(assert (isaddr (next " ^a_expr^ ")))\n")
let process_tid (t_expr:string) : string =
("(assert (istid (lock " ^t_expr^ ")))\n")
let process_elem (e_expr:string) : string =
("(assert (iselem (data " ^e_expr^ ")))\n")
let process_cell (c:Expr.cell) : string =
match c with
| Expr.CellLock (c,t) ->
let c_str = cellterm_to_str c in
let t_str = tidterm_to_str t in
("(assert (and (= " ^data ("(cell_lock " ^c_str^ " " ^t_str^ ")")^ " " ^data c_str^ ")\n" ^
" (= " ^next ("(cell_lock " ^c_str^ " " ^t_str^ ")")^ " " ^next c_str^ ")\n" ^
" (= " ^lock ("(cell_lock " ^c_str^ " " ^t_str^ ")")^ " " ^t_str^ ")))\n")
| Expr.CellUnlock c ->
let c_str = cellterm_to_str c in
let notid_str = tidterm_to_str Expr.NoTid in
("(assert (and (= " ^data ("(cell_unlock " ^c_str^ ")")^ " " ^data c_str^ ")\n" ^
" (= " ^next ("(cell_unlock " ^c_str^ ")")^ " " ^next c_str^ ")\n" ^
" (= " ^lock ("(cell_unlock " ^c_str^ ")")^ " " ^notid_str^ ")))\n")
| Expr.MkCell (e,a,t) ->
let e_str = elemterm_to_str e in
let a_str = addrterm_to_str a in
let t_str = tidterm_to_str t in
let mkcell_str = "mkcell " ^e_str^ " " ^a_str^ " " ^t_str in
("(assert (and (= " ^data ("(" ^mkcell_str^ ")")^ " " ^e_str^ ")\n" ^
" (= " ^next ("(" ^mkcell_str^ ")")^ " " ^a_str^ ")\n" ^
" (= " ^lock ("(" ^mkcell_str^ ")")^ " " ^t_str^ ")))\n")
| _ -> raise(UnexpectedCellTerm(Expr.cell_to_str c))
let process_getp (max_addrs:int) ((m,a1,a2):string * string * string) : string =
let tmpbuf = B.create 1024 in
B.add_string tmpbuf ("(assert (ispath (path1 " ^m^ " " ^a1^ ")))\n");
for i = 2 to (max_addrs + 1) do
let str_i = string_of_int i in
let str_prev = string_of_int (i-1) in
B.add_string tmpbuf ("(assert (= (length (path" ^str_i^ " " ^m^ " " ^a1^ ")) (+ 1 (length (path" ^str_prev^ " " ^m^ " " ^a1^ ")))))\n");
B.add_string tmpbuf ("(assert (= (at (path" ^str_i^ " " ^m^ " " ^a1^ ")) (update_pathat (at (path" ^str_prev^ " " ^m^ " " ^a1^ ")) (length (path" ^str_prev^ " " ^m^ " " ^a1^ ")) (next" ^str_prev^ " " ^m^ " " ^a1^ "))))\n");
B.add_string tmpbuf ("(assert (= (where (path" ^str_i^ " " ^m^ " " ^a1^ ")) (update_pathwhere (where (path" ^str_prev^ " " ^m^ " " ^a1^ ")) (next" ^str_prev^ " " ^m^ " " ^a1^ ") (length (path" ^str_prev^ " " ^m^ " " ^a1^ ")))))\n");
B.add_string tmpbuf ("(assert (= (addrs (path" ^str_i^ " " ^m^ " " ^a1^ ")) (store (addrs (path" ^str_prev^ " " ^m^ " " ^a1^ ")) (next" ^str_prev^ " " ^m^ " " ^a1^ ") true)))\n");
B.add_string tmpbuf ("(assert (ispath (path" ^str_i^ " " ^m^ " " ^a1^ ")))\n")
done;
B.contents tmpbuf
let process_fstlock (max_addrs:int) ((m,p):string * string) : string =
let tmpbuf = B.create 1024 in
for i = 0 to max_addrs do
B.add_string tmpbuf ("(assert (istid (getlockat " ^m^ " " ^p^ " " ^string_of_int i^ ")))\n")
done;
B.contents tmpbuf
let post_process (buf:B.t) (num_addrs:int) (num_elems:int) (num_tids:int) : unit =
Hashtbl.iter (fun a _ -> B.add_string buf (process_addr a)) addr_tbl;
Hashtbl.iter (fun e _ -> B.add_string buf (process_elem e)) elem_tbl;
Hashtbl.iter (fun t _ -> B.add_string buf (process_tid t)) tid_tbl;
Hashtbl.iter (fun c _ -> B.add_string buf (process_cell c)) cell_tbl;
Hashtbl.iter (fun g _ -> B.add_string buf (process_getp num_addrs g)) getp_tbl;
Hashtbl.iter (fun f _ -> B.add_string buf (process_fstlock num_addrs f)) fstlock_tbl
let literal_list_to_str (ls:Expr.literal list) : string =
clean_lists();
let _ = GM.clear_sort_map sort_map in
let expr = Expr.Conj ls in
let c = SmpTll.cut_off_normalized expr in
let num_addr = c.SmpTll.num_addrs in
let num_tid = c.SmpTll.num_tids in
let num_elem = c.SmpTll.num_elems in
let (req_sorts, req_ops) =
List.fold_left (fun (ss,os) lit ->
let phi = Expr.Literal lit
in
(Expr.required_sorts phi @ ss, Expr.special_ops phi @ os)
) ([],[]) ls in
let (req_sorts, req_ops) = update_requirements req_sorts req_ops in
let buf = B.create 1024 in
smt_preamble buf num_addr num_tid num_elem req_sorts;
smt_defs buf num_addr num_tid num_elem req_sorts req_ops;
variables_to_smt buf num_tid expr ;
let add_and_literal l str =
"\n " ^ (literal_to_str l) ^ str
in
let formula_str = List.fold_right add_and_literal ls ""
in
post_process buf num_addr num_elem num_tid;
B.add_string buf "(assert\n (and";
B.add_string buf formula_str ;
B.add_string buf "))\n";
B.add_string buf "(check-sat)\n" ;
B.contents buf
let formula_to_str (stac:Tactics.solve_tactic option)
(co:Smp.cutoff_strategy_t)
(copt:Smp.cutoff_options_t)
(phi:Expr.formula) : string =
" Entering formula_to_str ... " LEVEL TRACE ;
let extra_info_str =
match stac with
| None -> ""
| Some Tactics.Cases ->
let (ante,(eq,ineq)) =
match phi with
| Expr.Not (Expr.Implies (ante,cons)) -> (ante, Expr.get_addrs_eqs ante)
| _ -> (phi, ([],[])) in
let temp_dom = Expr.TermSet.elements
(Expr.termset_of_sort
(Expr.get_termset_from_formula ante) Expr.Addr) in
(* We also filter primed variables *)
let term_dom = List.filter (fun t ->
match t with
| Expr.AddrT (Expr.VarAddr (id,s,pr,th,p)) -> th <> None || p = None
| _ -> true
) temp_dom in
let assumps = List.map (fun (x,y) -> Partition.Eq (Expr.AddrT x, Expr.AddrT y)) eq @
List.map (fun (x,y) -> Partition.Ineq (Expr.AddrT x, Expr.AddrT y)) ineq in
verbl _LONG_INFO "**** SMTTllQuery. Domain: %i\n" (List.length term_dom);
verbl _LONG_INFO "**** SMTTllQuery. Assumptions: %i\n" (List.length assumps);
let parts = Partition.gen_partitions term_dom assumps in
let _ = if LeapDebug.is_debug_enabled() then
List.iter (fun p ->
verbl _LONG_INFO "**** SMTTllQuery. Partitions:\n%s\n"
(Partition.to_str Expr.term_to_str p);
) parts in
verbl _LONG_INFO "**** SMTTllQuery. Number of cases: %i\n" (List.length parts);
verbl _LONG_INFO "**** SMTTllQuery. Computation done!!!\n";
smt_partition_assumptions parts in
clean_lists();
let _ = GM.clear_sort_map sort_map in
verbl _LONG_INFO "**** SMTTllQuery. Will compute the cutoff...\n";
let max_cut_off = SmpTll.cut_off co copt phi in
let num_addr = max_cut_off.SmpTll.num_addrs in
let num_tid = max_cut_off.SmpTll.num_tids in
let num_elem = max_cut_off.SmpTll.num_elems in
let req_sorts = Expr.required_sorts phi in
let req_ops = Expr.special_ops phi in
let formula_str = formula_to_str phi in
let (req_sorts, req_ops) = update_requirements req_sorts req_ops in
let buf = B.create 1024
in
smt_preamble buf num_addr num_tid num_elem req_sorts;
smt_defs buf num_addr num_tid num_elem req_sorts req_ops;
variables_from_formula_to_smt buf num_tid phi ;
(* We add extra information if needed *)
B.add_string buf extra_info_str ;
post_process buf num_addr num_elem num_tid;
B.add_string buf "(assert\n";
B.add_string buf formula_str ;
B.add_string buf ")\n";
B.add_string buf "(check-sat)\n" ;
B.contents buf
let conjformula_to_str (expr:Expr.conjunctive_formula) : string =
match expr with
Expr.TrueConj -> "(assert true)\n(check-sat)"
| Expr.FalseConj -> "(assert false)\n(check-sat)"
| Expr.Conj conjs -> literal_list_to_str conjs
let get_sort_map () : GM.sort_map_t =
GM.copy_sort_map sort_map
end
| null | https://raw.githubusercontent.com/imdea-software/leap/5f946163c0f80ff9162db605a75b7ce2e27926ef/src/solvers/backend/query/smtlib/SMTTllQuery_reduced.ml | ocaml | *********************************************************************
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
either express or implied.
See the License for the specific language governing permissions
and limitations under the License.
*********************************************************************
Sort names
We store calls to cell_lock and cell_unlock in the formula, in order to
add the necessary assertions once we have translated the formula
Information storage
************************ Declarations *************************
(define-type address (scalar null aa_1 aa_2 aa_3 aa_4 aa_5))
(define-type range_address (subrange 0 max_address))
(define-type tid (scalar notid t1 t2 t3))
(define max_tid::int 3)
(define-type range_tid (subrange 0 max_tid))
(define-type element)
(define-type cell (record data::element next::address lock::tid))
(define next::(-> cell address) (lambda (c::cell) (select c next)))
(define lock::(-> cell tid) (lambda (c::cell) (select c lock)))
(define-type heap (-> address cell))
(define-type set (-> address bool))
(define pathat::(-> range_address address))
(define pathwhere::(-> address range_address))
(define-type path
(record length::range_address at::pathat where::pathwhere))
(=> (and (< i (select p length))
(< i (select r length)))
(= ((select p at) i) ((select r at) i)))))
(define eqpath::(-> path path bool)
(lambda (p::path r::path)
(and (= (select p length) (select r length))
(lambda (t::tid) (false))
(lambda (t::tid)
(lambda (r::tid)
(= t r))))
(lambda (s::setth r::setth)
(lambda (t::tid)
(or (s t) (r t)))))
(lambda (s::setth r::setth)
(lambda (t::tid)
(and (s t) (r t)))))
(define setdiffth::(-> set set set)
(lambda (s::setth r::setth)
(lambda (t::tid)
(and (s t) (not (r t))))))
(lambda (r::setth) (s::setth)
(and (if (r notid) (s notid))
(if (r t1) (s t1))
(if (r t2) (s t2))
(define emptyelem::setelem)
(lambda (e::elem) (false))
(define singletonelem::(-> elem setelem)
(lambda (e::elem)
(lambda (r::elem)
(= t r))))
(define unionelem::(-> setelem setelem setelem)
(lambda (e::elem)
(or (s e) (r e)))))
(define intersectionelem::(-> setelem setelem setelem)
(lambda (e::elem)
(and (s e) (r e)))))
(define setdiffelem::(-> setelem setelem setelem)
(lambda (e::elem)
(and (s e) (not (r e))))))
(lambda (r::setelem) (s::setelem)
(and (=> (r e1) (s e1))
(=> (r e2) (s e2))
(=> (r e3) (s e3)))))
(define empty::set)
(lambda (a::address) (false))
(define singleton::(-> address set)
(lambda (a::address)
(lambda (b::address)
(= a b))))
(define setunion::(-> set set set)
(lambda (s::set r::set)
(lambda (a::address)
(or (s a) (r a)))))
(define intersection::(-> set set set)
(lambda (s::set r::set)
(lambda (a::address)
(and (s a) (r a)))))
(define setdiff::(-> set set set)
(lambda (s::set r::set)
(lambda (a::address)
(and (s a) (not (r a))))))
(define subseteq::(-> set set bool)
(and (if (s1 null) (s2 null))
(if (s1 a1) (s2 a1))
(if (s1 a1) (s2 a2))
(if (s1 a3) (s2 a3))
(if (s1 a4) (s2 a4))
(if (s1 a5) (s2 a5)))))
(define eqset::(-> set set bool)
(lambda (s::set m::mem)
(lambda (e::elem)
(or (and (= e (data (m null))) (s null))
(and (= e (data (m aa_1))) (s aa_1))
(and (= e (data (m aa_2))) (s aa_2))
(and (= e (data (m aa_3))) (s aa_3))))))
(lambda (h::heap p::path i::range_address))
(lock (h ((select p at) i))))
(define islockedpos::(-> heap path range_address bool)
(lambda (h::heap p::path i::range_address))
(and (< i (select p length)) (/= notid (getlockat h p i))))
(define firstlockfrom5::(-> heap path address)
(lambda (h::heap p::path))
(define firstlockfrom4::(-> heap path address)
(lambda (h::heap p::path))
(define firstlockfrom3::(-> heap path address)
(lambda (h::heap p::path))
(define firstlockfrom2::(-> heap path address)
(lambda (h::heap p::path))
(lambda (h::heap p::path))
(define firstlock::(-> heap path address)
(lambda (h::heap p::path))
(define cell_lock::(-> cell tid cell)
(lambda (c::cell t::tid))
(mkcell (next c) (data c) t))
(define cell_unlock::(-> cell cell)
(lambda (c::cell))
(mkcell (next c) (data c) notid))
(define epsilonat::(-> range_address address)
(lambda r::range_address) null)
(define epsilonwhere::(-> address range_address)
(lambda a::address) 0)
(define epsilon::path
(define singletonat::(-> address range_address address)
(lambda (a::address)
(if (= r 0) a null))))
(define singletonwhere::(-> address address range_address)
(lambda (a::address)
(lambda (b::address)
(define singlepath::(-> address path)
(lambda (a::address)
(mk-record length::1 at::(singletonat a) where::(singletonwhere a))))
(define check_position::(-> path range_address bool)
(lambda (p::path)
(and (check_position p 0)
(check_position p 1)
(check_position p 2)
(check_position p 3)
(check_position p 4)
(check_position p 5))))
(define rev_position::(-> path path range_address bool)
(lambda (p::path p_rev::path i::range_address)
(=> (< (i (select p length)))
(= ((select p at) i) ((select p_rev at) (- (select p length) i))))))
(define rev::(-> path path bool)
(lambda (p::path p_rev::path)
(and (= (select p length) (select p_rev length))
(rev_position p p_rev 0)
(lambda (p::path)
(lambda (a::address)
(define deref::(-> heap address cell)
(lambda (h::heap a::address)
(h a)))
Ordered list predicate definition
(define error::cell)
(lambda (h::heap e::element a::address k::tid)
(define isheap::(-> heap bool)
(lambda (h::heap)
(= (deref h null) error)))
(define next1::(-> heap address address) (lambda (h::heap a::address) (next h a)))
(define next2::(-> address address) (lambda (a::address) (next h (next1 h a))))
(define isreachable::(-> heap address address bool)
(lambda (h::heap from::address to::address)
(or (= from to)
(= (next from) to)
(= (next2 from) to)
(define address2set::(-> address set)
(lambda (from::address)
(lambda (to::address)
(isreachable from to))))
(lambda (a::address p::path)
(= ((select p at) 0) a)))))
(define update_heap::(-> heap address cell heap)
(lambda (h::heap a::address c::cell)
(update h a c)))
(define update_pathat::(-> pathat range_address address pathat)
(lambda (j::range_address)
(if (= i j) a (f j)))))
(define update_pathwhere::(-> pathwhere address range_address pathwhere)
(lambda (g::pathwhere a::address i::range_address)
(lambda (b::address)
(if (= b a) i (g b)))))
(define add_to_path::(-> path address path)
(lambda (p::path a::address)
(define path1::(-> heap address path)
(lambda (h::heap a::address)
(singlepath a)))
(define path2::(-> heap address path)
(lambda (h::heap a::address)
(define path3::(-> heap address path)
(lambda (h::heap a::address)
(add_to_path (path2 h a) (next2 h a))))
(define path4::(-> heap address path)
(lambda (h::heap a::address)
(define getp4::(-> heap address address path)
(lambda (h::heap from::address to::address)
epsilon)))
(define getp3::(-> heap address address path)
(lambda (h::heap from::address to::address)
(if (= (next2 h from) to)
(define getp2::(-> heap address address path)
(lambda (h::heap from::address to::address)
(path2 h from)
(define getp1::(-> heap address address path)
(lambda (h::heap from::address to::address)
(if (= from to)
(define getp::(-> heap address address path)
(lambda (h::heap from::address to::address)
(getp1 h from to)))
(define path_length::(-> path range_address)
(lambda (p1::path)
(select p1 length)))
(define at_path::(-> path range_address address)
((select p1 at) i)))
(= (at_path p1 i) (at_path p2 j))
true)))
(lambda (p1::path p2::path p_res::path)
************************ Declarations *************************
******************** Preamble Declaration *********************
Elements
Cells and Heap
Cell
Sets
Iterations over next
Address2set
OrderedList
Path2set
Sets of Threads
Sets of Elements
Set2Elem
Path
******************** Preamble Declaration *********************
if pr then p_id ^ "_prime" else p_id
if pr then "_prime" else ""
Don't need a representation for this
We also filter primed variables
We add extra information if needed |
LEAP
, IMDEA Software Institute
Copyright 2011 IMDEA Software Institute
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND ,
open TllQuery
open LeapLib
open LeapVerbose
module SMTTllQuery : TLL_QUERY =
struct
module Expr = TLLExpression
module VarIdSet = TLLExpression.VarIdSet
module B = Buffer
module GM = GenericModel
exception UnexpectedCellTerm of string
exception UnexpectedSetTerm of string
exception UnexpectedSetthTerm of string
exception UnexpectedSetelemTerm of string
let prog_lines = ref 0
let pc_prime_name : string = Conf.pc_name ^ "_prime"
let loc_str : string = "loc_"
let range_addr_str : string = "rg_addr_"
let range_tid_str : string = "rg_tid_"
let path_len_str : string = "p_len_"
let addr_prefix = "aa_"
let tid_prefix = "tt_"
let elem_prefix = "ee_"
let bool_s : string = "Bool"
let int_s : string = "Int"
let addr_s : string = "Address"
let set_s : string = "Set"
let elem_s : string = "Elem"
let tid_s : string = "Tid"
let cell_s : string = "Cell"
let setth_s : string = "Setth"
let setelem_s : string = "SetElem"
let path_s : string = "Path"
let heap_s : string = "Heap"
let unk_s : string = "Unknown"
let loc_s : string = "Loc"
Lock - Unlock information table
let cell_tbl = Hashtbl.create 10
let addr_tbl = Hashtbl.create 10
let elem_tbl = Hashtbl.create 10
let tid_tbl = Hashtbl.create 10
let getp_tbl = Hashtbl.create 10
let fstlock_tbl = Hashtbl.create 10
let clean_lists () : unit =
Hashtbl.clear cell_tbl;
Hashtbl.clear addr_tbl;
Hashtbl.clear elem_tbl;
Hashtbl.clear tid_tbl;
Hashtbl.clear getp_tbl;
Hashtbl.clear fstlock_tbl
let sort_map : GM.sort_map_t = GM.new_sort_map()
let linenum_to_str (i:int) : string =
string_of_int i
let range_addr_to_str (i:int) : string =
string_of_int i
let range_tid_to_str (i:int) : string =
range_tid_str ^ string_of_int i
let path_len_to_str (i:int) : string =
string_of_int i
Program lines manipulation
let set_prog_lines (n:int) : unit =
prog_lines := n
let data(expr:string) : string =
Hashtbl.add elem_tbl expr ();
("(data " ^expr^ ")")
let next(expr:string) : string =
Hashtbl.add addr_tbl expr ();
("(next " ^expr^ ")")
let lock(expr:string) : string =
Hashtbl.add tid_tbl expr ();
("(lock " ^expr^ ")")
( define max_address::int 5 )
let smt_addr_preamble buf num_addr =
B.add_string buf ("(set-logic QF_AUFLIA)\n");
B.add_string buf ("(define-sort " ^addr_s^ " () " ^int_s^ ")\n");
GM.sm_decl_const sort_map "max_address" int_s ;
B.add_string buf
( "(define-fun max_address () " ^int_s^ " " ^(string_of_int num_addr)^ ")\n");
B.add_string buf
("(define-fun null () " ^addr_s^ " 0)\n");
for i = 1 to num_addr do
let i_str = string_of_int i in
let a_str = addr_prefix ^ i_str in
B.add_string buf ("(define-fun " ^a_str^ " () " ^addr_s^ " " ^i_str^ ")\n")
done;
B.add_string buf ("(define-fun isaddr ((x " ^addr_s^ ")) " ^bool_s^ " (and (<= 0 x) (<= x max_address)))\n");
B.add_string buf
( "(define-sort RangeAddress () " ^int_s^ ")\n" ^
"(define-fun is_valid_range_address ((i RangeAddress)) " ^bool_s^
" (and (<= 0 i) (<= i max_address)))\n")
let smt_tid_preamble buf num_tids =
B.add_string buf ("(define-sort " ^tid_s^ " () " ^int_s^ ")\n");
GM.sm_decl_const sort_map "max_tid" int_s ;
B.add_string buf ("(define-fun max_tid () " ^int_s^ " " ^(string_of_int num_tids)^ ")\n");
B.add_string buf
("(define-fun notid () " ^tid_s^ " 0)\n");
for i = 1 to num_tids do
let i_str = string_of_int i in
let t_str = tid_prefix ^ i_str in
B.add_string buf ("(define-fun " ^t_str^ " () " ^tid_s^ " " ^i_str^ ")\n")
done;
B.add_string buf "; I need the line below to prevent an unknown constant error\n";
GM.sm_decl_const sort_map "tid_witness" tid_s ;
let witness_str = string_of_int (num_tids + 1) in
B.add_string buf ("(define-fun tid_witness () " ^tid_s^ " " ^witness_str^ ")\n");
B.add_string buf ("(define-fun istid ((x " ^tid_s^ ")) " ^bool_s^ " (and (<= 0 x) (<= x (+ max_tid 1))))\n")
let smt_element_preamble buf num_elems =
B.add_string buf ("(define-sort " ^elem_s^ " () " ^int_s^ ")\n");
B.add_string buf ("(define-fun lowestElem () " ^elem_s^ " 0)\n");
B.add_string buf ("(define-fun highestElem () " ^elem_s^ " " ^(string_of_int (num_elems+1))^ ")\n");
for i = 1 to num_elems do
let i_str = string_of_int i in
let e_str = elem_prefix ^ i_str in
B.add_string buf ("(define-fun " ^e_str^ " () " ^elem_s^ " " ^i_str^ ")\n")
done;
B.add_string buf ("(define-fun iselem ((x " ^elem_s^ ")) " ^bool_s^ " (and (<= lowestElem x) (<= x highestElem)))\n")
( define data::(- > cell element ) ( lambda ( c::cell ) ( select c data ) ) )
let smt_cell_preamble buf =
B.add_string buf
("(declare-sort " ^cell_s^ " 0)\n\
(declare-fun mkcell (" ^elem_s^ " " ^addr_s^ " " ^tid_s^ ") " ^cell_s^ ")\n\
(declare-fun data (" ^cell_s^ ") " ^elem_s^ ")\n\
(declare-fun next (" ^cell_s^ ") " ^addr_s^ ")\n\
(declare-fun lock (" ^cell_s^ ") " ^tid_s^ ")\n")
let smt_heap_preamble buf =
B.add_string buf
("(define-sort " ^heap_s^ " () (Array " ^addr_s^ " " ^cell_s^ "))\n")
let smt_set_preamble buf =
B.add_string buf
("(define-sort " ^set_s^ " () (Array " ^addr_s^ " " ^bool_s^ "))\n")
( define - type setth ( - > tid bool ) )
let smt_setth_preamble buf =
B.add_string buf
("(define-sort " ^setth_s^ " () (Array " ^tid_s^ " " ^bool_s^ "))\n")
let smt_setelem_preamble buf =
B.add_string buf
("(define-sort " ^setelem_s^ " () (Array " ^elem_s^ " " ^bool_s^ "))\n")
( define eqpath_pos::(- > path path path_length bool )
( lambda ( p::path r::path_length i::range_address )
( eqpath_pos p r 0 )
( eqpath_pos p r 1 )
( eqpath_pos p r 2 )
( eqpath_pos p r 3 ) ) ) )
let smt_path_preamble buf num_addr =
B.add_string buf
( "(define-sort PathLength () " ^int_s^ ")\n" ^
"(define-fun is_valid_path_length ((i PathLength)) " ^bool_s^
" (and (<= 0 i) (<= i (+ max_address 1))))\n");
B.add_string buf
( "(define-sort PathAt () (Array RangeAddress " ^addr_s^ "))\n" ^
"(define-sort PathWhere () (Array " ^addr_s^ " RangeAddress))\n");
B.add_string buf
( "(declare-sort " ^path_s^ " 0)\n" );
B.add_string buf
( "(declare-fun mkpath (PathLength PathAt PathWhere " ^set_s^ ") " ^path_s^ ")\n" );
B.add_string buf
( "(declare-fun length (" ^path_s^ ") PathLength)\n\
(declare-fun at (" ^path_s^ ") PathAt)\n\
(declare-fun where (" ^path_s^ ") PathWhere)\n\
(declare-fun addrs (" ^path_s^ ") " ^set_s^ ")\n" );
B.add_string buf
("(define-fun eqpath_pos ((p " ^path_s^ ") (r " ^path_s^
") (i RangeAddress)) " ^bool_s^ "\n" ^
" (=> (and (is_valid_range_address i) (< i (length p)) (< i (length r)))\n" ^
" (= (select (at p) i) (select (at r) i))))\n");
B.add_string buf
("(define-fun eqpath ((p " ^path_s^ ") (r " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (= (length p) (length r))\n");
for i=0 to num_addr do
B.add_string buf
(" (eqpath_pos p r "^ (path_len_to_str i) ^ ")\n");
done ;
B.add_string buf "))\n"
let smt_unknown_preamble buf =
B.add_string buf
("(declare-sort " ^unk_s^ " 0)\n")
let smt_pos_preamble buf =
B.add_string buf ("(define-sort " ^loc_s^ " () " ^int_s^ ")\n");
GM.sm_decl_fun sort_map Conf.pc_name [tid_s] [loc_s] ;
GM.sm_decl_fun sort_map pc_prime_name [tid_s] [loc_s] ;
B.add_string buf ("(declare-fun " ^Conf.pc_name^ " () (Array " ^tid_s^ " " ^loc_s^ "))\n");
B.add_string buf ("(declare-fun " ^pc_prime_name^ " () (Array " ^tid_s^ " " ^loc_s^ "))\n");
B.add_string buf ("(define-fun in_pos_range ((t " ^tid_s^ ")) " ^bool_s^ "\n" ^
" (and (<= 1 (select pc t))\n" ^
" (<= (select pc t) " ^string_of_int !prog_lines^ ")\n" ^
" (<= 1 (select pc_prime t))\n" ^
" (<= (select pc_prime t) " ^ string_of_int !prog_lines^ ")))\n")
( define )
let smt_empth_def buf num_tids =
let _ = GM.sm_decl_const sort_map "emptyth" setth_s in
B.add_string buf
("(declare-fun emptyth () " ^setth_s^ ")\n");
B.add_string buf
("(assert (= (select emptyth notid) false))\n");
for i = 1 to num_tids do
B.add_string buf
("(assert (= (select emptyth " ^(tid_prefix ^ (string_of_int i))^ ") false))\n")
done;
B.add_string buf
("(assert (= (select emptyth tid_witness) false))\n")
( define singletonth::(- > tid setth )
let smt_singletonth_def buf =
B.add_string buf
("(define-fun singletonth ((t " ^tid_s^ ")) " ^setth_s^ "\n" ^
" (store emptyth t true))\n")
( define unionth::(- > setth )
let smt_unionth_def buf num_tids =
let str = ref (" (store\n" ^
" (store emptyth notid (or (select s1 notid) (select s2 notid)))\n" ^
" tid_witness (or (select s1 tid_witness) (select s2 tid_witness)))") in
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^t_str^ " (or (select s1 " ^t_str^ ") (select s2 " ^t_str^ ")))"
done;
B.add_string buf
("(define-fun unionth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) " ^setth_s^ "\n" ^ (!str) ^ ")\n")
( define > setth )
let smt_intersectionth_def buf num_tids =
let str = ref (" (store\n" ^
" (store emptyth notid (and (select s1 notid) (select s2 notid)))\n" ^
" tid_witness (and (select s1 tid_witness) (select s2 tid_witness)))") in
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^t_str^ " (and (select s1 " ^t_str^ ") (select s2 " ^t_str^ ")))"
done;
B.add_string buf
("(define-fun intersectionth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) " ^setth_s^ "\n" ^ (!str) ^ ")\n")
let smt_setdiffth_def buf num_tids =
let str = ref (" (store\n" ^
" (store emptyth notid (and (select s1 notid) (not (select s2 notid))))\n" ^
" tid_witness (and (select s1 tid_witness) (not (select s2 tid_witness))))") in
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^t_str^ " (and (select s1 " ^t_str^ ") (not (select s2 " ^t_str^ "))))"
done;
B.add_string buf
("(define-fun setdiffth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) " ^setth_s^ "\n" ^ (!str) ^ ")\n")
( define subseteqth::(- > setth setth bool )
( if ( r t3 ) ( s t3 ) ) ) ) )
let smt_subseteqth_def buf num_tids =
B.add_string buf
("(define-fun subseteqth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) "^bool_s^ "\n" ^
" (and (=> (select s1 notid) (select s2 notid))\n" ^
" (=> (select s1 tid_witness) (select s2 tid_witness))\n");
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
B.add_string buf
(" (=> (select s1 " ^t_str^ ") (select s2 " ^t_str^ "))\n")
done;
B.add_string buf ("))\n")
( define eqsetth::(- > setth setth bool )
let smt_eqsetth_def buf num_tids =
B.add_string buf
("(define-fun eqsetth ((s1 " ^setth_s^ ") (s2 " ^setth_s^ ")) "^bool_s^ "\n" ^
" (and (= (select s1 notid) (select s2 notid))\n" ^
" (= (select s1 tid_witness) (select s2 tid_witness))\n");
for i = 1 to num_tids do
let t_str = tid_prefix ^ (string_of_int i) in
B.add_string buf
(" (= (select s1 " ^t_str^ ") (select s2 " ^t_str^ "))\n")
done;
B.add_string buf ("))\n")
let smt_empelem_def buf num_elems =
let _ = GM.sm_decl_const sort_map "emptyelem" setelem_s in
B.add_string buf
("(declare-fun emptyelem () " ^setelem_s^ ")\n");
B.add_string buf
("(assert (= (select emptyelem lowestElem) false))\n");
B.add_string buf
("(assert (= (select emptyelem highestElem) false))\n");
for i = 1 to num_elems do
B.add_string buf
("(assert (= (select emptyelem " ^(elem_prefix ^ (string_of_int i))^ ") false))\n")
done
let smt_singletonelem_def buf =
B.add_string buf
("(define-fun singletonelem ((e " ^elem_s^ ")) " ^setelem_s^ "\n" ^
" (store emptyelem e true))\n")
( lambda ( s::setelem r::setelem )
let smt_unionelem_def buf num_elems =
let str = ref (" (store\n" ^
" (store emptyelem lowestElem (or (select s1 lowestElem) (select s2 lowestElem)))\n" ^
" highestElem (or (select s1 highestElem) (select s2 highestElem)))") in
for i = 1 to num_elems do
let e_str = elem_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^e_str^ " (or (select s1 " ^e_str^ ") (select s2 " ^e_str^ ")))"
done;
B.add_string buf
("(define-fun unionelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) " ^setelem_s^ "\n" ^ (!str) ^ ")\n")
( lambda ( s::setelem r::setelem )
let smt_intersectionelem_def buf num_elems =
let str = ref (" (store\n" ^
" (store emptyelem lowestElem (and (select s1 lowestElem) (select s2 lowestElem)))\n" ^
" highestElem (and (select s1 highestElem) (select s2 highestElem)))") in
for i = 1 to num_elems do
let e_str = elem_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^e_str^ " (and (select s1 " ^e_str^ ") (select s2 " ^e_str^ ")))"
done;
B.add_string buf
("(define-fun intersectionelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) " ^setelem_s^ "\n" ^ (!str) ^ ")\n")
( lambda ( s::setelem r::setelem )
let smt_setdiffelem_def buf num_elems =
let str = ref (" (store\n" ^
" (store emptyelem lowestElem (and (select s1 lowestElem) (not (select s2 lowestElem))))\n" ^
" highestElem (and (select s1 highestElem) (not (select s2 highestElem))))") in
for i = 1 to num_elems do
let e_str = elem_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^e_str^ " (and (select s1 " ^e_str^ ") (not (select s2 " ^e_str^ "))))"
done;
B.add_string buf
("(define-fun setdiffelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) " ^setelem_s^ "\n" ^ (!str) ^ ")\n")
( define subseteqelem::(- )
let smt_subseteqelem_def buf num_elem =
B.add_string buf
("(define-fun subseteqelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) "^bool_s^ "\n" ^
" (and (=> (select s1 lowestElem) (select s2 lowestElem))\n" ^
" (=> (select s1 highestElem) (select s2 highestElem))\n");
for i = 1 to num_elem do
let e_str = elem_prefix ^ (string_of_int i) in
B.add_string buf
(" (=> (select s1 " ^e_str^ ") (select s2 " ^e_str^ "))\n")
done;
B.add_string buf ("))\n")
( define eqsetelem::(- )
let smt_eqsetelem_def buf num_elem =
B.add_string buf
("(define-fun eqsetelem ((s1 " ^setelem_s^ ") (s2 " ^setelem_s^ ")) "^bool_s^ "\n" ^
" (and (= (select s1 lowestElem) (select s2 lowestElem))\n" ^
" (= (select s1 highestElem) (select s2 highestElem))\n");
for i = 1 to num_elem do
let e_str = elem_prefix ^ (string_of_int i) in
B.add_string buf
(" (= (select s1 " ^e_str^ ") (select s2 " ^e_str^ "))\n")
done;
B.add_string buf ("))\n")
let smt_emp_def buf num_addrs =
let _ = GM.sm_decl_const sort_map "empty" set_s in
B.add_string buf
("(declare-fun empty () " ^set_s^ ")\n");
B.add_string buf
("(assert (= (select empty null) false))\n");
for i = 1 to num_addrs do
B.add_string buf
("(assert (= (select empty " ^(addr_prefix ^ (string_of_int i))^ ") false))\n")
done
let smt_singleton_def buf =
B.add_string buf
("(define-fun singleton ((a " ^addr_s^ ")) " ^set_s^ "\n" ^
" (store empty a true))\n")
let smt_union_def buf num_addrs =
let str = ref " (store empty null (or (select s1 null) (select s2 null)))" in
for i = 1 to num_addrs do
let a_str = addr_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^a_str^ " (or (select s1 " ^a_str^ ") (select s2 " ^a_str^ ")))"
done;
B.add_string buf
("(define-fun setunion ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) " ^set_s^ "\n" ^ (!str) ^ ")\n")
let smt_intersection_def buf num_addrs =
let str = ref " (store empty null (and (select s1 null) (select s2 null)))" in
for i = 1 to num_addrs do
let a_str = addr_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^a_str^ " (and (select s1 " ^a_str^ ") (select s2 " ^a_str^ ")))"
done;
B.add_string buf
("(define-fun intersection ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) " ^set_s^ "\n" ^ (!str) ^ ")\n")
let smt_setdiff_def buf num_addrs =
let str = ref " (store empty null (and (select s1 null) (not (select s2 null))))" in
for i = 1 to num_addrs do
let a_str = addr_prefix ^ (string_of_int i) in
str := " (store\n" ^ (!str) ^ "\n" ^
" " ^a_str^ " (and (select s1 " ^a_str^ ") (not (select s2 " ^a_str^ "))))"
done;
B.add_string buf
("(define-fun setdiff ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) " ^set_s^ "\n" ^ (!str) ^ ")\n")
( lambda ( s1::set )
let smt_subseteq_def buf num_addr =
B.add_string buf
("(define-fun subseteq ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) "^bool_s^ "\n" ^
" (and (=> (select s1 null) (select s2 null))\n");
for i = 1 to num_addr do
let a_str = addr_prefix ^ (string_of_int i) in
B.add_string buf
(" (=> (select s1 " ^a_str^ ") (select s2 " ^a_str^ "))\n")
done;
B.add_string buf ("))\n")
let smt_eqset_def buf num_addr =
B.add_string buf
("(define-fun eqset ((s1 " ^set_s^ ") (s2 " ^set_s^ ")) "^bool_s^ "\n" ^
" (and (= (select s1 null) (select s2 null))\n");
for i = 1 to num_addr do
let a_str = addr_prefix ^ (string_of_int i) in
B.add_string buf
(" (= (select s1 " ^a_str^ ") (select s2 " ^a_str^ "))\n")
done;
B.add_string buf ("))\n")
( define set2elem::(- > set )
let smt_settoelems_def buf num_addrs =
let str = ref " (store emptyelem (data (select m null)) (select s null))\n" in
for i=1 to num_addrs do
let aa_i = addr_prefix ^ (string_of_int i) in
str := " (unionelem\n" ^ !str ^
" (store emptyelem (data (select m " ^aa_i^ ")) (select s " ^aa_i^ ")))\n"
done;
B.add_string buf
("(define-fun set2elem ((s " ^set_s^ ") (m " ^heap_s^ ")) " ^setelem_s^
"\n" ^ !str ^ ")\n")
( define > heap path range_address tid )
( if ( islockedpos h p 5 ) ( getlockat h p 5 ) null ) )
( if ( islockedpos h p 4 ) ( getlockat h p 4 ) ( firstlockfrom5 h p ) ) )
( if ( islockedpos h p 3 ) ( getlockat h p 3 ) ( firstlockfrom4 h p ) ) )
( if ( islockedpos h p 2 ) ( getlockat h p 2 ) ( firstlockfrom3 h p ) ) )
( define firstlockfrom1::(- > heap path address )
( if ( islockedpos h p 1 ) ( getlockat h p 1 ) ( firstlockfrom2 h p ) ) )
( if ( islockedpos h p 0 ) ( getlockat h p 0 ) ( firstlockfrom1 h p ) ) )
let smt_firstlock_def buf num_addr =
let strlast = (string_of_int num_addr) in
B.add_string buf
("(define-fun getlockat ((h " ^heap_s^ ") (p " ^path_s^
") (i RangeAddress)) " ^tid_s^ "\n" ^
" (if (is_valid_range_address i) (lock (select h (select (at p) i))) notid))\n" ^
"(define-fun getaddrat ((p " ^path_s^ ") (i RangeAddress)) " ^addr_s^ "\n" ^
" (if (is_valid_range_address i) (select (at p) i) null))\n" ^
"(define-fun islockedpos ((h " ^heap_s^ ") (p " ^path_s^
") (i RangeAddress)) " ^bool_s^ "\n" ^
" (if (is_valid_range_address i) (and (< i (length p)) (not (= notid (getlockat h p i)))) false))\n");
B.add_string buf
("(define-fun firstlockfrom" ^ strlast ^ " ((h " ^heap_s^ ") (p " ^path_s^ ")) " ^addr_s^ "\n" ^
" (if (islockedpos h p " ^ strlast ^ ") (getaddrat p " ^ strlast ^ ") null))\n");
for i=(num_addr-1) downto 1 do
let stri = (string_of_int i) in
let strnext = (string_of_int (i+1)) in
B.add_string buf
("(define-fun firstlockfrom"^ stri ^" ((h " ^heap_s^ ") (p " ^path_s^ ")) " ^addr_s^ "\n" ^
" (if (islockedpos h p "^ stri ^") (getaddrat p "^ stri ^") (firstlockfrom"^ strnext ^" h p)))\n");
done ;
B.add_string buf
("(define-fun firstlock ((h " ^heap_s^ ") (p " ^path_s^ ") ) " ^addr_s^ "\n" ^
" (if (islockedpos h p 0) (getaddrat p 0) (firstlockfrom1 h p)))\n")
let smt_cell_lock buf =
B.add_string buf
("(declare-fun cell_lock (" ^cell_s^ " " ^tid_s^ ") " ^cell_s^ ")\n")
let smt_cell_unlock_def buf =
B.add_string buf
("(declare-fun cell_unlock (" ^cell_s^ ") " ^cell_s^ ")\n")
( mk - record length::0 at::epsilonat where::epsilonwhere ) )
let smt_epsilon_def buf num_addr =
let _ = GM.sm_decl_const sort_map "epsilon" path_s in
let mkpath_str = "mkpath 0 epsilonat epsilonwhere empty" in
B.add_string buf
("(declare-fun epsilonat () PathAt)\n");
for i = 0 to (num_addr + 1) do
B.add_string buf
("(assert (= (select epsilonat " ^(string_of_int i)^ ") null))\n")
done;
B.add_string buf
("(declare-fun epsilonwhere () PathWhere)\n" ^
"(assert (= (select epsilonwhere null) 0))\n");
for i = 1 to num_addr do
B.add_string buf
("(assert (= (select epsilonwhere " ^(addr_prefix ^ (string_of_int i))^ ") 0))\n")
done;
B.add_string buf
("(declare-fun epsilon () " ^path_s^ ")\n" ^
"(assert (= epsilon (" ^mkpath_str^ ")))\n");
B.add_string buf
("(assert (and (= (length (" ^mkpath_str^ ")) 0)\n\
(= (at (" ^mkpath_str^ ")) epsilonat)\n\
(= (where (" ^mkpath_str^ ")) epsilonwhere)\n\
(= (addrs (" ^mkpath_str^ ")) empty)))\n")
( lambda ( r::range_address )
( if (= a b ) 0 1 ) ) ) )
let smt_singletonpath_def buf num_addr =
let mkpath_str = "mkpath 1 (singletonat a) (singletonwhere a) (singleton a)" in
B.add_string buf
("(define-fun singletonat ((a " ^addr_s^ ")) PathAt\n" ^
" (store epsilonat 0 a))\n" ^
"(declare-fun singlewhere () PathWhere)\n" ^
"(assert (= (select singlewhere null) 1))\n");
for i = 1 to num_addr do
B.add_string buf
("(assert (= (select singlewhere " ^(addr_prefix ^ (string_of_int i))^ ") 1))\n")
done;
B.add_string buf
("(define-fun singletonwhere ((a " ^addr_s^ ")) PathWhere\n" ^
" (store singlewhere a 0))\n" ^
"(define-fun singlepath ((a " ^addr_s^ ")) " ^path_s^ "\n" ^
" (" ^mkpath_str^ "))\n");
B.add_string buf
("(assert (and (= (length (" ^mkpath_str^ ")) 1)\n\
(= (at (" ^mkpath_str^ ")) (singletonat a))\n\
(= (where (" ^mkpath_str^ ")) (singletonwhere a))\n\
(= (addrs (" ^mkpath_str^ ")) (singleton a))))\n")
( lambda ( p::path i::range_address )
(= > ( < i ( select p length ) ) (= i ( ( select p where ) ( ( select p at ) i ) ) ) ) ) )
( define ispath::(- > path bool )
let smt_ispath_def buf num_addr =
B.add_string buf
("(define-fun check_position ((p " ^path_s^ ") (i RangeAddress)) " ^bool_s^ "\n" ^
" (=> (and (is_valid_range_address i)\n" ^
" (< i (length p)))\n" ^
" (and (= i (select (where p) (select (at p) i))) (isaddr (select (at p) i)))))\n");
B.add_string buf
("(define-fun ispath ((p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and");
for i=0 to num_addr do
B.add_string buf
("\n (check_position p " ^ (string_of_int i) ^ ")")
done ;
B.add_string buf "))\n"
( rev_position p p_rev 1 )
( rev_position p p_rev 2 )
( rev_position p p_rev 3 )
( rev_position p p_rev 4 )
( rev_position p p_rev 5 ) ) ) )
let smt_rev_def buf num_addr =
B.add_string buf
("(define-fun rev_position ((p " ^path_s^ ") (p_rev " ^path_s^ ") (i RangeAddress)) " ^bool_s^ "\n" ^
" (=> (and (is_valid_range_address i)\n" ^
" (< i (length p)))\n" ^
" (= (select (at p) i) (select (at p_rev) (- (length p) i)))))\n");
B.add_string buf
("(define-fun rev ((p " ^path_s^ ") (p_rev " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (= (length p) (length p_rev))");
for i=0 to num_addr do
B.add_string buf
( "\n (rev_position p p_rev " ^ (string_of_int i) ^")" )
done ;
B.add_string buf "))\n"
( define path2set::(- > path set )
( < ( ( select p where ) a ) ( select p length ) ) ) ) )
let smt_path2set_def buf =
B.add_string buf
("(define-fun path2set ((p " ^path_s^ ")) " ^set_s^ " (addrs p))\n")
let smt_dref_def buf =
B.add_string buf
("(define-fun deref ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^cell_s^ "\n" ^
" (select h a))\n")
let smt_elemorder_def buf =
B.add_string buf
("(define-fun lesselem ((x " ^elem_s^ ") (y " ^elem_s^ ")) " ^bool_s^ " (< x y))\n" ^
"(define-fun greaterelem ((x " ^elem_s^ ") (y " ^elem_s^ ")) " ^bool_s^ " (> x y))\n")
let smt_orderlist_def buf num_addr =
let idlast = string_of_int num_addr in
B.add_string buf
("(define-fun orderlist" ^idlast^ " ((h " ^heap_s^ ") " ^
"(a " ^addr_s^ ") (b " ^addr_s^ ")) " ^bool_s^ " \n" ^
" true)\n");
for i = (num_addr-1) downto 1 do
let id = string_of_int i in
let idnext = string_of_int (i+1) in
B.add_string buf
("(define-fun orderlist" ^id^ " ((h " ^heap_s^ ") (a " ^addr_s^ ") ( b " ^addr_s^ ")) " ^bool_s^ "\n" ^
" (and (isaddr a)\n" ^
" (isaddr b)\n" ^
" (isaddr (next" ^id^ " h a))\n" ^
" (or (= (next" ^id^ " h a) b)\n" ^
" (and (lesselem (data (select h (next" ^id^ " h a)))\n" ^
" (data (select h (next" ^idnext^ " h a))))\n" ^
" (iselem (data (select h (next" ^id^ " h a))))\n" ^
" (iselem (data (select h (next" ^idnext^ " h a))))\n" ^
" (isaddr (next" ^idnext^ " h a))\n" ^
" (orderlist" ^idnext^ " h a b)))))\n")
done;
B.add_string buf
("(define-fun orderlist ((h " ^heap_s^ ") (a " ^addr_s^ ") (b " ^addr_s^ ")) " ^bool_s^ "\n" ^
" (and (isaddr a)\n" ^
" (isaddr b)\n" ^
" (or (= a b)\n" ^
" (and (lesselem (data (select h a))\n" ^
" (data (select h (next1 h a))))\n" ^
" (iselem (data (select h a)))\n" ^
" (iselem (data (select h (next1 h a))))\n" ^
" (isaddr (next1 h a))\n" ^
" (orderlist1 h a b)))))\n")
let smt_error_def buf=
let _ = GM.sm_decl_const sort_map "error" cell_s in
B.add_string buf
("(declare-fun error () " ^cell_s^ ")\n" ^
"(assert (= (lock error) notid))\n" ^
"(assert (= " ^next "error"^ " null))\n")
( define mkcell::(- > element address tid cell )
( mk - record data::e next::a lock::k ) ) )
let smt_mkcell_def buf =
B.add_string buf
Unneeded
let smt_isheap_def buf =
B.add_string buf
("(define-fun isheap ((h " ^heap_s^ ")) " ^bool_s^ "\n" ^
" (= (select h null) error))\n")
( define next3::(- > address address ) ( lambda ( a::address ) ( next h ( next2 h a ) ) ) )
( define next4::(- > address address ) ( lambda ( a::address ) ( next h ( next3 h a ) ) ) )
( define next5::(- > address address ) ( lambda ( a::address ) ( next h ( next4 h a ) ) ) )
(= ( next3 from ) to )
(= ( next4 from ) to ) ) ) )
let smt_nextiter_def buf num_addr =
if (num_addr >= 2) then
B.add_string buf
("(define-fun next0 ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^addr_s^ " a)\n");
B.add_string buf
("(define-fun next1 ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^addr_s^ "\n" ^
" (next (select h a)))\n");
for i=2 to num_addr do
B.add_string buf
("(define-fun next"^ (string_of_int i) ^" ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^addr_s^ "\n" ^
" (next (select h (next"^ (string_of_int (i-1)) ^" h a))))\n")
done
let smt_reachable_def buf num_addr =
B.add_string buf
("(define-fun isreachable ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^bool_s^ "\n" ^
" (and (isaddr from)\n" ^
" (isaddr to)\n" ^
" (isaddr (next0 h to))\n" ^
" (isaddr (next1 h to))\n");
for i = 2 to num_addr do
B.add_string buf
(" (isaddr (next" ^(string_of_int i)^ " h to))\n")
done;
B.add_string buf
(" (or (= from to)\n" ^
" (= (next (select h from)) to)\n");
for i=2 to num_addr do
B.add_string buf
( "\n (= (next" ^ (string_of_int i) ^ " h from) to)" )
done ;
B.add_string buf ")))\n"
let smt_address2set_def buf num_addr =
let join_sets s1 s2 = "\n (setunion "^ s1 ^" "^ s2 ^")" in
B.add_string buf
("(define-fun address2set ((h " ^heap_s^ ") (from " ^addr_s^ ")) " ^set_s^ "");
B.add_string buf
begin
match num_addr with
0 -> "\n (singleton from))\n"
| 1 -> "\n (setunion (singleton from) (singleton (next (select h from)))))\n"
| _ -> let basic = "\n (setunion (singleton from) (singleton (next (select h from))))" in
let addrs = LeapLib.rangeList 2 num_addr in
let str = List.fold_left (fun s i ->
join_sets ("(singleton (next"^ (string_of_int i) ^ " h from))") s
) basic addrs
in
str^")\n"
end
( define > address path bool )
( and ( ispath p )
(= ( ( select p length ) 1 )
let smt_is_singlepath buf =
B.add_string buf
("(define-fun is_singlepath ((a " ^addr_s^ ") (p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (ispath p)\n" ^
" (= (length p) 1)\n" ^
" (= (select (at p) 0) a)))\n")
let smt_update_heap_def buf =
B.add_string buf
("(define-fun update_heap ((h " ^heap_s^ ") (a " ^addr_s^ ") (c " ^cell_s^ ")) " ^heap_s^ "\n" ^
" (store h a c))\n")
( lambda ( f::pathat i::range_address a::address )
( mk - record length::(+ 1 ( select p length ) )
at::(update_pathat ( select p at ) ( select p length ) a )
where::(update_pathwhere ( select p where ) a ( select p length ) ) ) ) )
( add_to_path ( path1 h a ) ( next h a ) ) ) )
( add_to_path ( path3 h a ) ( next3 h a ) ) ) )
( if (= ( next3 h from ) to )
( path4 h from )
( h from )
( getp4 h from to ) ) ) )
( if (= ( next h from ) to )
( h from to ) ) ) )
( path1 h from )
( from to ) ) ) )
let smt_getp_def buf num_addr =
B.add_string buf
("(define-fun update_pathat ((f PathAt) (i RangeAddress) (a " ^addr_s^ ")) PathAt\n" ^
" (if (is_valid_range_address i) (store f i a) f))\n" ^
"(define-fun update_pathwhere ((g PathWhere) (a " ^addr_s^ ") (i RangeAddress)) PathWhere\n" ^
" (if (is_valid_range_address i) (store g a i) g))\n");
" ( define - fun add_to_path ( ( p " ^path_s^ " ) ( a " ^addr_s^ " ) ) " ^path_s^ " \n " ^
" ( mkpath ( + 1 ( length p))\n " ^
" ( update_pathat ( at p ) ( length p ) a)\n " ^
" ( update_pathwhere ( where p ) a ( length p))\n " ^
" ( setunion ( addrs p ) ( singleton " ) ;
" (mkpath (+ 1 (length p))\n" ^
" (update_pathat (at p) (length p) a)\n" ^
" (update_pathwhere (where p) a (length p))\n" ^
" (setunion (addrs p) (singleton a))))\n");
*)
B.add_string buf
("(define-fun path1 ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^path_s^ "\n" ^
" (singlepath a))\n");
for i=2 to ( ) do
let stri= string_of_int i in
let strpre = string_of_int ( i-1 ) in
let p_str = " ( path"^ strpre ^ " h a ) " in
let next_str = " ( next"^ strpre ^ " h a ) " in
let arg1 = " ( + 1 ( length " ^p_str^ " ) ) " in
let = " ( update_pathat ( at " ^p_str^ " ) ( length " ^p_str^ " ) " ^next_str^ " ) " in
let arg3 = " ( update_pathwhere ( where " ^p_str^ " ) " ^next_str^ " ( length " ^p_str^ " ) ) " in
let arg4 = " ( setunion ( addrs " ^p_str^ " ) ( singleton " ^next_str^ " ) ) " in
let " mkpath " ^arg1^ " " ^
" " ^arg2^ " \n " ^
" " ^arg3^ " \n " ^
" " ^arg4 in
B.add_string buf
( " ( define - fun path"^ stri ^ " ( ( h " ^heap_s^ " ) ( a " ^addr_s^ " ) ) " ^path_s^ " \n " ^
" ( " ^mkpath_str^ " ) ) \n " ) ;
B.add_string buf
( " ( assert ( and (= ( length ( " ^mkpath_str^ " ) ) " ^arg1^ " ) \n\
(= ( at ( " ^mkpath_str^ " ) ) " ^arg2^ " ) \n\
(= ( where ( " ^mkpath_str^ " ) ) " ^arg3^ " ) \n\
(= ( ( " ^mkpath_str^ " ) ) " ^arg4^ " ) ) ) \n " )
done ;
for i=2 to (num_addr +1) do
let stri= string_of_int i in
let strpre = string_of_int (i-1) in
let p_str = "(path"^ strpre ^" h a)" in
let next_str = "(next"^ strpre ^" h a)" in
let arg1 = "(+ 1 (length " ^p_str^ "))" in
let arg2 = "(update_pathat (at " ^p_str^ ") (length " ^p_str^ ") " ^next_str^ ")" in
let arg3 = "(update_pathwhere (where " ^p_str^ ") " ^next_str^ " (length " ^p_str^ "))" in
let arg4 = "(setunion (addrs " ^p_str^ ") (singleton " ^next_str^ "))" in
let mkpath_str = " mkpath " ^arg1^ "\n" ^
" " ^arg2^ "\n" ^
" " ^arg3^ "\n" ^
" " ^arg4 in
B.add_string buf
("(define-fun path"^ stri ^" ((h " ^heap_s^ ") (a " ^addr_s^ ")) " ^path_s^ "\n" ^
" (" ^mkpath_str^ "))\n");
B.add_string buf
("(assert (and (= (length (" ^mkpath_str^ ")) " ^arg1^ ")\n\
(= (at (" ^mkpath_str^ ")) " ^arg2^ ")\n\
(= (where (" ^mkpath_str^ ")) " ^arg3^ ")\n\
(= (addrs (" ^mkpath_str^ ")) " ^arg4^ ")))\n")
done ;
*)
B.add_string buf
("(define-fun getp"^ (string_of_int (num_addr + 1)) ^" ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (if (= (next"^ (string_of_int num_addr) ^" h from) to)\n" ^
" (path"^ (string_of_int num_addr) ^" h from)\n" ^
" epsilon))\n");
for i=num_addr downto 1 do
let stri = string_of_int i in
let strpre = string_of_int (i-1) in
let strnext = string_of_int (i+1) in
B.add_string buf
("(define-fun getp"^ stri ^" ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (if (= (next"^ strpre ^" h from) to)\n" ^
" (path"^ stri ^" h from)\n" ^
" (getp"^ strnext ^" h from to)))\n")
done ;
B.add_string buf
("(define-fun getp ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (getp1 h from to))\n");
B.add_string buf
("(define-fun isgetp ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ") (p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (eqpath p (getp h from to)))\n")
let smt_getp_def buf num_addr =
B.add_string buf
("(define-fun getp"^ (string_of_int (num_addr + 1)) ^" ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (if (= (next"^ (string_of_int num_addr) ^" h from) to)\n" ^
" (path"^ (string_of_int num_addr) ^" h from)\n" ^
" epsilon))\n");
for i=num_addr downto 1 do
let stri = string_of_int i in
let strpred = string_of_int (i-1) in
let strsucc = string_of_int (i+1) in
B.add_string buf
("(define-fun getp"^ stri ^" ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (if (= (next"^ strpred ^" h from) to)\n" ^
" (path"^ stri ^" h from)\n" ^
" (getp"^ strsucc ^" h from to)))\n")
done ;
B.add_string buf
("(define-fun getp ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ")) " ^path_s^ "\n" ^
" (getp1 h from to))\n");
B.add_string buf
("(define-fun isgetp ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ") (p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (eqpath p (getp h from to)))\n")
let smt_reach_def buf =
B.add_string buf
( "(define-fun reach ((h " ^heap_s^ ") (from " ^addr_s^ ") (to " ^addr_s^ ") (p " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (ispath p) (eqpath (getp h from to) p) (not (eqpath p epsilon))))\n"
)
let smt_path_length_def buf =
B.add_string buf
("(define-fun path_length ((p " ^path_s^ ")) RangeAddress (length p))\n")
( lambda ( p1::path i::range_address )
let smt_at_path_def buf =
B.add_string buf
("(define-fun at_path ((p " ^path_s^ ") (i RangeAddress)) " ^addr_s^ "\n" ^
" (if (is_valid_range_address i) (select (at p) i) null))\n")
( define > path range_address path range_address bool )
( lambda ( p1::path )
( ite ( < i ( path_length p1 ) )
let smt_equal_paths_at_def buf =
B.add_string buf
("(define-fun equal_paths_at ((p1 " ^path_s^ ") (i RangeAddress) (p2 " ^path_s^ ") (j RangeAddress)) " ^bool_s^ "\n" ^
" (if (< i (path_length p1))\n" ^
" (= (at_path p1 i) (at_path p2 j))\n" ^
" true))\n")
( define is_append::(- > path path path bool )
( and (= ( + ( path_length p1 ) ( path_length p2 ) ) ( path_length p_res ) )
( equal_paths_at p1 0 p_res 0 )
( equal_paths_at p1 1 p_res 1 )
( equal_paths_at p1 2 p_res 2 )
( equal_paths_at p1 3 p_res 3 )
( equal_paths_at p1 4 p_res 4 )
( equal_paths_at p1 5 p_res 5 )
( equal_paths_at p2 0 p_res ( + ( path_length p1 ) 0 ) )
( equal_paths_at p2 1 p_res ( + ( path_length p1 ) 1 ) )
( equal_paths_at p2 2 p_res ( + ( path_length p1 ) 2 ) )
( equal_paths_at p2 3 p_res ( + ( path_length p1 ) 3 ) )
( equal_paths_at p2 4 p_res ( + ( path_length p1 ) 4 ) )
( equal_paths_at p2 5 p_res ( + ( path_length p1 ) 5 ) ) ) ) )
let smt_is_append_def buf num_addr =
B.add_string buf
("(define-fun is_append ((p1 " ^path_s^ ") (p2 " ^path_s^ ") (p_res " ^path_s^ ")) " ^bool_s^ "\n" ^
" (and (= (+ (path_length p1) (path_length p2)) (path_length p_res))");
for i=0 to num_addr do
let str_i = (string_of_int i) in
B.add_string buf
( "\n (equal_paths_at p1 " ^ str_i ^ " p_res " ^ str_i ^ ")" )
done ;
for i=0 to num_addr do
let str_i = string_of_int i in
B.add_string buf
( "\n (equal_paths_at p2 " ^ str_i ^ " p_res (+ (path_length p1) " ^ str_i ^ "))" )
done ;
B.add_string buf "))\n"
let update_requirements (req_sorts:Expr.sort list)
(req_ops:Expr.special_op_t list)
: (Expr.sort list * Expr.special_op_t list) =
let (res_req_sorts, res_req_ops) = (ref req_sorts, ref req_ops) in
If " path " is a required sort , then we need to add " set " as required sort
since " set " is part of the definition of sort " path " ( required by " "
field )
since "set" is part of the definition of sort "path" (required by "addrs"
field) *)
if (List.mem Expr.Path req_sorts) then
res_req_sorts := Expr.Set :: !res_req_sorts ;
(!res_req_sorts, !res_req_ops)
let smt_preamble buf num_addr num_tid num_elem req_sorts =
if (List.exists (fun s ->
s=Expr.Addr || s=Expr.Cell || s=Expr.Path || s=Expr.Set || s=Expr.Mem
) req_sorts) then smt_addr_preamble buf num_addr ;
if (List.exists (fun s ->
s=Expr.Tid || s=Expr.Cell || s=Expr.SetTh
) req_sorts) then smt_tid_preamble buf num_tid ;
if (List.exists (fun s ->
s=Expr.Elem || s=Expr.Cell || s=Expr.Mem
) req_sorts) then smt_element_preamble buf num_elem ;
if List.mem Expr.Cell req_sorts || List.mem Expr.Mem req_sorts then
smt_cell_preamble buf ;
if List.mem Expr.Mem req_sorts then smt_heap_preamble buf ;
if List.mem Expr.Set req_sorts then smt_set_preamble buf ;
if List.mem Expr.SetTh req_sorts then smt_setth_preamble buf ;
if List.mem Expr.SetElem req_sorts then smt_setelem_preamble buf ;
if List.mem Expr.Path req_sorts then begin
smt_path_preamble buf num_addr ;
smt_ispath_def buf num_addr
end;
if List.mem Expr.Unknown req_sorts then smt_unknown_preamble buf ;
smt_pos_preamble buf
let smt_defs buf num_addr num_tid num_elem req_sorts req_ops =
if List.mem Expr.ElemOrder req_ops || List.mem Expr.OrderedList req_ops then
smt_elemorder_def buf ;
if List.mem Expr.Cell req_sorts || List.mem Expr.Mem req_sorts then
smt_error_def buf ;
if List.mem Expr.Cell req_sorts then
begin
smt_mkcell_def buf ;
smt_cell_lock buf ;
smt_cell_unlock_def buf
end;
Heap
if List.mem Expr.Mem req_sorts then
begin
smt_isheap_def buf ;
smt_dref_def buf ;
smt_update_heap_def buf
end;
if List.mem Expr.Set req_sorts then
begin
smt_emp_def buf num_addr ;
smt_singleton_def buf ;
smt_union_def buf num_addr ;
smt_intersection_def buf num_addr ;
smt_setdiff_def buf num_addr ;
smt_subseteq_def buf num_addr ;
smt_eqset_def buf num_addr
end;
if List.mem Expr.Addr2Set req_ops
|| List.mem Expr.Reachable req_ops
|| List.mem Expr.OrderedList req_ops then
smt_nextiter_def buf num_addr ;
if List.mem Expr.Addr2Set req_ops then
begin
smt_reachable_def buf num_addr ;
smt_address2set_def buf num_addr
end;
if List.mem Expr.OrderedList req_ops then smt_orderlist_def buf num_addr ;
if List.mem Expr.Path2Set req_ops then smt_path2set_def buf ;
if List.mem Expr.SetTh req_sorts then
begin
smt_empth_def buf num_tid ;
smt_singletonth_def buf ;
smt_unionth_def buf num_tid ;
smt_intersectionth_def buf num_tid ;
smt_setdiffth_def buf num_tid ;
smt_subseteqth_def buf num_tid ;
smt_eqsetth_def buf num_tid
end;
if List.mem Expr.SetElem req_sorts then
begin
smt_empelem_def buf num_elem ;
smt_singletonelem_def buf ;
smt_unionelem_def buf num_elem ;
smt_intersectionelem_def buf num_elem ;
smt_setdiffelem_def buf num_elem ;
smt_subseteqelem_def buf num_elem ;
smt_eqsetelem_def buf num_elem
end;
if List.mem Expr.Set2Elem req_ops then smt_settoelems_def buf num_addr ;
Firstlock
if List.mem Expr.FstLocked req_ops then smt_firstlock_def buf num_addr ;
if List.mem Expr.Path req_sorts then
begin
smt_rev_def buf num_addr ;
smt_epsilon_def buf num_addr ;
smt_singletonpath_def buf num_addr ;
smt_is_singlepath buf ;
smt_path_length_def buf ;
smt_at_path_def buf ;
smt_equal_paths_at_def buf ;
smt_is_append_def buf num_addr
end;
if List.mem Expr.Getp req_ops ||
List.mem Expr.Reachable req_ops then smt_getp_def buf num_addr ;
Reachable
if List.mem Expr.Reachable req_ops then smt_reach_def buf
let rec smt_define_var (buf:Buffer.t)
(tid_set:Expr.V.VarSet.t)
(num_tids:int)
(v:Expr.V.t) : unit =
let (id,s,pr,th,p) = v in
let sort_str asort = match asort with
Expr.Set -> set_s
| Expr.Elem -> elem_s
| Expr.Addr -> addr_s
| Expr.Tid -> tid_s
| Expr.Cell -> cell_s
| Expr.SetTh -> setth_s
| Expr.SetElem -> setelem_s
| Expr.Path -> path_s
| Expr.Mem -> heap_s
| Expr.Unknown -> unk_s in
let s_str = sort_str s in
let p_id = Option.map_default (fun str -> str ^ "_" ^ id) id p in
in
if Expr.V.is_global v then
begin
GM.sm_decl_const sort_map name
(GM.conv_sort (TLLInterface.sort_to_expr_sort s)) ;
B.add_string buf ( "(declare-fun " ^ name ^ " () " ^ s_str ^ ")\n" );
match s with
| Expr.Addr -> B.add_string buf ( "(assert (isaddr " ^name^ "))\n" )
| Expr.Elem -> B.add_string buf ( "(assert (iselem " ^name^ "))\n" )
| Expr.Path -> B.add_string buf ( "(assert (ispath " ^name^ "))\n" )
| Expr.Mem -> B.add_string buf ( "(assert (isheap " ^name^ "))\n" )
| Expr.Tid -> B.add_string buf ( "(assert (not (= " ^ name ^ " notid)))\n" );
B.add_string buf ( "(assert (istid " ^name^ "))\n" );
B.add_string buf ( "(assert (in_pos_range " ^ name ^ "))\n" )
| _ -> ()
end
else
begin
GM.sm_decl_fun sort_map name [tid_s] [s_str] ;
B.add_string buf ( "(declare-fun " ^ name ^ " () (Array " ^tid_s^ " " ^ s_str ^ "))\n" );
match s with
| Expr.Addr -> B.add_string buf ("(assert (isaddr (select " ^name^ " notid)))\n");
B.add_string buf ("(assert (isaddr (select " ^name^ " tid_witness)))\n");
for i = 1 to num_tids do
B.add_string buf ("(assert (isaddr (select " ^name^ " " ^tid_prefix ^ (string_of_int i)^ ")))\n")
done
| Expr.Elem -> B.add_string buf ("(assert (iselem (select " ^name^ " notid)))\n");
B.add_string buf ("(assert (iselem (select " ^name^ " tid_witness)))\n");
for i = 1 to num_tids do
B.add_string buf ("(assert (iselem (select " ^name^ " " ^tid_prefix ^ (string_of_int i)^ ")))\n")
done
| Expr.Path -> Expr.V.VarSet.iter (fun t ->
let v_str = variable_invocation_to_str
(Expr.V.set_param v (Expr.VarTh t)) in
B.add_string buf ( "(assert (ispath " ^ v_str ^ "))\n" )
) tid_set
| Expr.Mem -> Expr.V.VarSet.iter (fun t ->
let v_str = variable_invocation_to_str
(Expr.V.set_param v (Expr.VarTh t)) in
B.add_string buf ( "(assert (isheap " ^ v_str ^ "))\n" )
) tid_set
| Expr.Tid -> Expr.V.VarSet.iter (fun t ->
let v_str = variable_invocation_to_str
(Expr.V.set_param v (Expr.VarTh t)) in
B.add_string buf ( "(assert (not (= " ^ v_str ^ " notid)))\n" )
) tid_set;
B.add_string buf ("(assert (istid (select " ^name^ " notid)))\n");
B.add_string buf ("(assert (istid (select " ^name^ " tid_witness)))\n");
for i = 1 to num_tids do
B.add_string buf ("(assert (istid (select " ^name^ " " ^tid_prefix ^ (string_of_int i)^ ")))\n")
done
| _ -> ()
FIX : Add iterations for ispath and isheap on local variables
end
and define_variables (buf:Buffer.t) (num_tids:int) (vars:Expr.V.VarSet.t) : unit =
let varset = Expr.varset_of_sort vars Expr.Set in
let varelem = Expr.varset_of_sort vars Expr.Elem in
let varaddr = Expr.varset_of_sort vars Expr.Addr in
let vartid = Expr.varset_of_sort vars Expr.Tid in
let varcell = Expr.varset_of_sort vars Expr.Cell in
let varsetth = Expr.varset_of_sort vars Expr.SetTh in
let varsetelem = Expr.varset_of_sort vars Expr.SetElem in
let varpath = Expr.varset_of_sort vars Expr.Path in
let varmem = Expr.varset_of_sort vars Expr.Mem in
let varunk = Expr.varset_of_sort vars Expr.Unknown in
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varset;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varelem;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) vartid;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varaddr;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varcell;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varsetth;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varsetelem;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varpath;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varmem;
Expr.V.VarSet.iter (smt_define_var buf vartid num_tids) varunk
and variables_to_smt (buf:Buffer.t)
(num_tids:int)
(expr:Expr.conjunctive_formula) : unit =
let vars = Expr.get_varset_from_conj expr
in
define_variables buf num_tids vars
and variables_from_formula_to_smt (buf:Buffer.t)
(num_tids:int)
(phi:Expr.formula) : unit =
let vars = Expr.get_varset_from_formula phi
in
define_variables buf num_tids vars
and variable_invocation_to_str (v:Expr.V.t) : string =
let (id,s,pr,th,p) = v in
let th_str = Option.map_default tidterm_to_str "" th in
let p_str = Option.map_default (fun n -> Printf.sprintf "%s_" n) "" p in
in
if th = None then
Printf.sprintf " %s%s%s%s" p_str id th_str pr_str
else
Printf.sprintf " (select %s%s%s %s)" p_str id pr_str th_str
and setterm_to_str (sa:Expr.set) : string =
match sa with
Expr.VarSet v -> variable_invocation_to_str v
| Expr.EmptySet -> "empty"
| Expr.Singl a -> Printf.sprintf "(singleton %s)" (addrterm_to_str a)
| Expr.Union(r,s) -> Printf.sprintf "(setunion %s %s)"
(setterm_to_str r)
(setterm_to_str s)
| Expr.Intr(r,s) -> Printf.sprintf "(intersection %s %s)"
(setterm_to_str r)
(setterm_to_str s)
| Expr.Setdiff(r,s) -> Printf.sprintf "(setdiff %s %s)"
(setterm_to_str r)
(setterm_to_str s)
| Expr.PathToSet p -> Printf.sprintf "(path2set %s)"
(pathterm_to_str p)
| Expr.AddrToSet(m,a) -> Printf.sprintf "(address2set %s %s)"
(memterm_to_str m)
(addrterm_to_str a)
and elemterm_to_str (e:Expr.elem) : string =
match e with
Expr.VarElem v -> variable_invocation_to_str v
| Expr.CellData c -> let c_str = cellterm_to_str c in
data c_str
| Expr.LowestElem -> "lowestElem"
| Expr.HighestElem -> "highestElem"
and tidterm_to_str (th:Expr.tid) : string =
match th with
Expr.VarTh v -> variable_invocation_to_str v
| Expr.NoTid -> "notid"
| Expr.CellLockId c -> let c_str = cellterm_to_str c in
lock c_str
and addrterm_to_str (a:Expr.addr) : string =
match a with
Expr.VarAddr v -> variable_invocation_to_str v
| Expr.Null -> "null"
| Expr.Next c -> Printf.sprintf "(next %s)"
(cellterm_to_str c)
| Expr.FirstLocked(m,p) -> let m_str = memterm_to_str m in
let p_str = pathterm_to_str p in
Hashtbl.add fstlock_tbl (m_str, p_str) ();
Printf.sprintf "(firstlock %s %s)" m_str p_str
and cellterm_to_str (c:Expr.cell) : string =
match c with
Expr.VarCell v -> variable_invocation_to_str v
| Expr.Error -> "error"
| Expr.MkCell(e,a,th) -> Hashtbl.add cell_tbl c ();
Printf.sprintf "(mkcell %s %s %s)"
(elemterm_to_str e)
(addrterm_to_str a)
(tidterm_to_str th)
| Expr.CellLock(c,th) -> Hashtbl.add cell_tbl c ();
Printf.sprintf "(cell_lock %s %s)"
(cellterm_to_str c)
(tidterm_to_str th)
| Expr.CellUnlock c -> Hashtbl.add cell_tbl c ();
Printf.sprintf "(cell_unlock %s)"
(cellterm_to_str c)
| Expr.CellAt(m,a) -> Printf.sprintf "(select %s %s)"
(memterm_to_str m)
(addrterm_to_str a)
and setthterm_to_str (sth:Expr.setth) : string =
match sth with
Expr.VarSetTh v -> variable_invocation_to_str v
| Expr.EmptySetTh -> "emptyth"
| Expr.SinglTh th -> Printf.sprintf "(singletonth %s)"
(tidterm_to_str th)
| Expr.UnionTh(rt,st) -> Printf.sprintf "(unionth %s %s)"
(setthterm_to_str rt)
(setthterm_to_str st)
| Expr.IntrTh(rt,st) -> Printf.sprintf "(intersectionth %s %s)"
(setthterm_to_str rt)
(setthterm_to_str st)
| Expr.SetdiffTh(rt,st) -> Printf.sprintf "(setdiffth %s %s)"
(setthterm_to_str rt)
(setthterm_to_str st)
and setelemterm_to_str (se:Expr.setelem) : string =
match se with
Expr.VarSetElem v -> variable_invocation_to_str v
| Expr.EmptySetElem -> "emptyelem"
| Expr.SinglElem e -> Printf.sprintf "(singletonelem %s)"
(elemterm_to_str e)
| Expr.UnionElem(rt,st) -> Printf.sprintf "(unionelem %s %s)"
(setelemterm_to_str rt)
(setelemterm_to_str st)
| Expr.IntrElem(rt,st) -> Printf.sprintf "(intersectionelem %s %s)"
(setelemterm_to_str rt)
(setelemterm_to_str st)
| Expr.SetToElems(s,m) -> Printf.sprintf "(set2elem %s %s)"
(setterm_to_str s) (memterm_to_str m)
| Expr.SetdiffElem(rt,st) -> Printf.sprintf "(setdiffelem %s %s)"
(setelemterm_to_str rt)
(setelemterm_to_str st)
and pathterm_to_str (p:Expr.path) : string =
match p with
Expr.VarPath v -> variable_invocation_to_str v
| Expr.Epsilon -> "epsilon"
| Expr.SimplePath a -> Printf.sprintf "(singlepath %s)"
(addrterm_to_str a)
| Expr.GetPath(m,a1,a2)-> let m_str = memterm_to_str m in
let a1_str = addrterm_to_str a1 in
let a2_str = addrterm_to_str a2 in
Hashtbl.add getp_tbl (m_str, a1_str, a2_str) ();
Printf.sprintf "(getp %s %s %s)" m_str a1_str a2_str
and memterm_to_str (m:Expr.mem) : string =
match m with
Expr.VarMem v -> variable_invocation_to_str v
| Expr.Emp -> "emp"
| Expr.Update(m,a,c) -> Printf.sprintf "(update_heap %s %s %s)"
(memterm_to_str m)
(addrterm_to_str a)
(cellterm_to_str c)
let rec varupdate_to_str (v:Expr.V.t)
(th:Expr.tid)
(t:Expr.term) : string =
let v_str = variable_invocation_to_str v in
let th_str = tidterm_to_str th in
let t_str = term_to_str t
in
Printf.sprintf "(store %s %s %s)" v_str th_str t_str
and term_to_str (t:Expr.term) : string =
match t with
Expr.VarT v -> variable_invocation_to_str v
| Expr.SetT s -> setterm_to_str s
| Expr.ElemT e -> elemterm_to_str e
| Expr.TidT th -> tidterm_to_str th
| Expr.AddrT a -> addrterm_to_str a
| Expr.CellT c -> cellterm_to_str c
| Expr.SetThT sth -> setthterm_to_str sth
| Expr.SetElemT se -> setelemterm_to_str se
| Expr.PathT p -> pathterm_to_str p
| Expr.MemT m -> memterm_to_str m
| Expr.VarUpdate(v,th,t) -> varupdate_to_str v th t
let append_to_str (p1:Expr.path) (p2:Expr.path) (p3:Expr.path) : string =
Printf.sprintf "(is_append %s %s %s)" (pathterm_to_str p1)
(pathterm_to_str p2)
(pathterm_to_str p3)
let reach_to_str (m:Expr.mem) (a1:Expr.addr)
(a2:Expr.addr) (p:Expr.path) : string =
Printf.sprintf "(reach %s %s %s %s)"
(memterm_to_str m)
(addrterm_to_str a1)
(addrterm_to_str a2)
(pathterm_to_str p)
let orderlist_to_str (m:Expr.mem) (a1:Expr.addr) (a2:Expr.addr) : string =
Printf.sprintf ("(orderlist %s %s %s)")
(memterm_to_str m)
(addrterm_to_str a1)
(addrterm_to_str a2)
let in_to_str (a:Expr.addr) (s:Expr.set) : string =
Printf.sprintf "(select %s %s)" (setterm_to_str s) (addrterm_to_str a)
let subseteq_to_str (r:Expr.set) (s:Expr.set) : string =
Printf.sprintf "(subseteq %s %s)" (setterm_to_str r)
(setterm_to_str s)
let inth_to_str (t:Expr.tid) (sth:Expr.setth) : string =
Printf.sprintf "(select %s %s)" (setthterm_to_str sth)
(tidterm_to_str t)
let subseteqth_to_str (r:Expr.setth) (s:Expr.setth) : string =
Printf.sprintf "(subseteqth %s %s)" (setthterm_to_str r)
(setthterm_to_str s)
let inelem_to_str (e:Expr.elem) (se:Expr.setelem) : string =
Printf.sprintf "(select %s %s)" (setelemterm_to_str se)
(elemterm_to_str e)
let subseteqelem_to_str (r:Expr.setelem) (s:Expr.setelem) : string =
Printf.sprintf "(subseteqelem %s %s)" (setelemterm_to_str r)
(setelemterm_to_str s)
let lesselem_to_str (e1:Expr.elem) (e2:Expr.elem) : string =
Printf.sprintf "(lesselem %s %s)" (elemterm_to_str e1) (elemterm_to_str e2)
let greaterelem_to_str (e1:Expr.elem) (e2:Expr.elem) : string =
Printf.sprintf "(greaterelem %s %s)" (elemterm_to_str e1) (elemterm_to_str e2)
let eq_to_str (t1:Expr.term) (t2:Expr.term) : string =
let str_t1 = (term_to_str t1) in
let str_t2 = (term_to_str t2) in
match t1 with
| Expr.PathT _ -> Printf.sprintf "(eqpath %s %s)" str_t1 str_t2
| Expr.SetT _ -> Printf.sprintf "(eqset %s %s)" str_t1 str_t2
| Expr.SetThT _ -> Printf.sprintf "(eqsetth %s %s)" str_t1 str_t2
| Expr.SetElemT _ -> Printf.sprintf "(eqsetelem %s %s)" str_t1 str_t2
| _ -> Printf.sprintf "(= %s %s)" str_t1 str_t2
let ineq_to_str (t1:Expr.term) (t2:Expr.term) : string =
let str_t1 = (term_to_str t1) in
let str_t2 = (term_to_str t2) in
match t1 with
Expr.PathT _ -> Printf.sprintf "(not (eqpath %s %s))" str_t1 str_t2
| _ -> Printf.sprintf "(not (= %s %s))" str_t1 str_t2
let pc_to_str (pc:int) (th:Expr.tid option) (pr:bool) : string =
let pc_str = if pr then pc_prime_name else Conf.pc_name
in
Printf.sprintf "(= (select %s %s) %s)" pc_str
(Option.map_default tidterm_to_str "" th) (linenum_to_str pc)
let pcrange_to_str (pc1:int) (pc2:int)
(th:Expr.tid option) (pr:bool) : string =
let pc_str = if pr then pc_prime_name else Conf.pc_name in
let th_str = Option.map_default tidterm_to_str "" th
in
Printf.sprintf "(and (<= %s (select %s %s)) (<= (select %s %s) %s))"
(linenum_to_str pc1) pc_str th_str pc_str th_str (linenum_to_str pc2)
let pcupdate_to_str (pc:int) (th:Expr.tid) : string =
Printf.sprintf "(= %s (store %s %s %s))"
pc_prime_name Conf.pc_name (tidterm_to_str th) (linenum_to_str pc)
let smt_partition_assumptions (parts:'a Partition.t list) : string =
let _ = LeapDebug.debug "entering smt_partition_assumptions...\n" in
let parts_str =
List.fold_left (fun str p ->
let _ = LeapDebug.debug "." in
let counter = ref 0 in
let cs = Partition.to_list p in
let p_str = List.fold_left (fun str c ->
let is_null = List.mem (Expr.AddrT Expr.Null) c in
let id = if is_null then
"null"
else
begin
incr counter;
addr_prefix ^ (string_of_int (!counter))
end in
let elems_str = List.fold_left (fun str e ->
str ^ (Printf.sprintf "(= %s %s) "
(term_to_str e) id)
) "" c in
str ^ elems_str
) "" cs in
str ^ "(and " ^ p_str ^ ")\n"
) "" parts
in
("(assert (or " ^ parts_str ^ "))\n")
let atom_to_str (at:Expr.atom) : string =
match at with
Expr.Append(p1,p2,p3) -> append_to_str p1 p2 p3
| Expr.Reach(m,a1,a2,p) -> reach_to_str m a1 a2 p
| Expr.OrderList(m,a1,a2) -> orderlist_to_str m a1 a2
| Expr.In(a,s) -> in_to_str a s
| Expr.SubsetEq(r,s) -> subseteq_to_str r s
| Expr.InTh(t,st) -> inth_to_str t st
| Expr.SubsetEqTh(rt,st) -> subseteqth_to_str rt st
| Expr.InElem(e,se) -> inelem_to_str e se
| Expr.SubsetEqElem(re,se) -> subseteqelem_to_str re se
| Expr.LessElem(e1,e2) -> lesselem_to_str e1 e2
| Expr.GreaterElem(e1,e2) -> greaterelem_to_str e1 e2
| Expr.Eq(x,y) -> eq_to_str x y
| Expr.InEq(x,y) -> ineq_to_str x y
| Expr.PC(pc,t,pr) -> pc_to_str pc t pr
| Expr.PCUpdate(pc,t) -> pcupdate_to_str pc t
| Expr.PCRange(pc1,pc2,t,pr) -> pcrange_to_str pc1 pc2 t pr
let literal_to_str (lit:Expr.literal) : string =
match lit with
Expr.Atom(a) -> (atom_to_str a)
| Expr.NegAtom(a) -> ("(not " ^ (atom_to_str a) ^")")
let rec formula_to_str (phi:Expr.formula) : string =
let to_smt = formula_to_str in
match phi with
Expr.Literal l -> literal_to_str l
| Expr.True -> " true "
| Expr.False -> " false "
| Expr.And (f1,f2) -> Printf.sprintf "(and %s %s)" (to_smt f1)
(to_smt f2)
| Expr.Or (f1,f2) -> Printf.sprintf "(or %s %s)" (to_smt f1)
(to_smt f2)
| Expr.Not f -> Printf.sprintf "(not %s)" (to_smt f)
| Expr.Implies (f1,f2) -> Printf.sprintf "(=> %s %s)" (to_smt f1)
(to_smt f2)
| Expr.Iff (f1,f2) -> Printf.sprintf "(= %s %s)" (to_smt f1)
(to_smt f2)
let literal_to_smt (buf:Buffer.t) (lit:Expr.literal) : unit =
B.add_string buf (literal_to_str lit)
let process_addr (a_expr:string) : string =
("(assert (isaddr (next " ^a_expr^ ")))\n")
let process_tid (t_expr:string) : string =
("(assert (istid (lock " ^t_expr^ ")))\n")
let process_elem (e_expr:string) : string =
("(assert (iselem (data " ^e_expr^ ")))\n")
let process_cell (c:Expr.cell) : string =
match c with
| Expr.CellLock (c,t) ->
let c_str = cellterm_to_str c in
let t_str = tidterm_to_str t in
("(assert (and (= " ^data ("(cell_lock " ^c_str^ " " ^t_str^ ")")^ " " ^data c_str^ ")\n" ^
" (= " ^next ("(cell_lock " ^c_str^ " " ^t_str^ ")")^ " " ^next c_str^ ")\n" ^
" (= " ^lock ("(cell_lock " ^c_str^ " " ^t_str^ ")")^ " " ^t_str^ ")))\n")
| Expr.CellUnlock c ->
let c_str = cellterm_to_str c in
let notid_str = tidterm_to_str Expr.NoTid in
("(assert (and (= " ^data ("(cell_unlock " ^c_str^ ")")^ " " ^data c_str^ ")\n" ^
" (= " ^next ("(cell_unlock " ^c_str^ ")")^ " " ^next c_str^ ")\n" ^
" (= " ^lock ("(cell_unlock " ^c_str^ ")")^ " " ^notid_str^ ")))\n")
| Expr.MkCell (e,a,t) ->
let e_str = elemterm_to_str e in
let a_str = addrterm_to_str a in
let t_str = tidterm_to_str t in
let mkcell_str = "mkcell " ^e_str^ " " ^a_str^ " " ^t_str in
("(assert (and (= " ^data ("(" ^mkcell_str^ ")")^ " " ^e_str^ ")\n" ^
" (= " ^next ("(" ^mkcell_str^ ")")^ " " ^a_str^ ")\n" ^
" (= " ^lock ("(" ^mkcell_str^ ")")^ " " ^t_str^ ")))\n")
| _ -> raise(UnexpectedCellTerm(Expr.cell_to_str c))
let process_getp (max_addrs:int) ((m,a1,a2):string * string * string) : string =
let tmpbuf = B.create 1024 in
B.add_string tmpbuf ("(assert (ispath (path1 " ^m^ " " ^a1^ ")))\n");
for i = 2 to (max_addrs + 1) do
let str_i = string_of_int i in
let str_prev = string_of_int (i-1) in
B.add_string tmpbuf ("(assert (= (length (path" ^str_i^ " " ^m^ " " ^a1^ ")) (+ 1 (length (path" ^str_prev^ " " ^m^ " " ^a1^ ")))))\n");
B.add_string tmpbuf ("(assert (= (at (path" ^str_i^ " " ^m^ " " ^a1^ ")) (update_pathat (at (path" ^str_prev^ " " ^m^ " " ^a1^ ")) (length (path" ^str_prev^ " " ^m^ " " ^a1^ ")) (next" ^str_prev^ " " ^m^ " " ^a1^ "))))\n");
B.add_string tmpbuf ("(assert (= (where (path" ^str_i^ " " ^m^ " " ^a1^ ")) (update_pathwhere (where (path" ^str_prev^ " " ^m^ " " ^a1^ ")) (next" ^str_prev^ " " ^m^ " " ^a1^ ") (length (path" ^str_prev^ " " ^m^ " " ^a1^ ")))))\n");
B.add_string tmpbuf ("(assert (= (addrs (path" ^str_i^ " " ^m^ " " ^a1^ ")) (store (addrs (path" ^str_prev^ " " ^m^ " " ^a1^ ")) (next" ^str_prev^ " " ^m^ " " ^a1^ ") true)))\n");
B.add_string tmpbuf ("(assert (ispath (path" ^str_i^ " " ^m^ " " ^a1^ ")))\n")
done;
B.contents tmpbuf
let process_fstlock (max_addrs:int) ((m,p):string * string) : string =
let tmpbuf = B.create 1024 in
for i = 0 to max_addrs do
B.add_string tmpbuf ("(assert (istid (getlockat " ^m^ " " ^p^ " " ^string_of_int i^ ")))\n")
done;
B.contents tmpbuf
let post_process (buf:B.t) (num_addrs:int) (num_elems:int) (num_tids:int) : unit =
Hashtbl.iter (fun a _ -> B.add_string buf (process_addr a)) addr_tbl;
Hashtbl.iter (fun e _ -> B.add_string buf (process_elem e)) elem_tbl;
Hashtbl.iter (fun t _ -> B.add_string buf (process_tid t)) tid_tbl;
Hashtbl.iter (fun c _ -> B.add_string buf (process_cell c)) cell_tbl;
Hashtbl.iter (fun g _ -> B.add_string buf (process_getp num_addrs g)) getp_tbl;
Hashtbl.iter (fun f _ -> B.add_string buf (process_fstlock num_addrs f)) fstlock_tbl
let literal_list_to_str (ls:Expr.literal list) : string =
clean_lists();
let _ = GM.clear_sort_map sort_map in
let expr = Expr.Conj ls in
let c = SmpTll.cut_off_normalized expr in
let num_addr = c.SmpTll.num_addrs in
let num_tid = c.SmpTll.num_tids in
let num_elem = c.SmpTll.num_elems in
let (req_sorts, req_ops) =
List.fold_left (fun (ss,os) lit ->
let phi = Expr.Literal lit
in
(Expr.required_sorts phi @ ss, Expr.special_ops phi @ os)
) ([],[]) ls in
let (req_sorts, req_ops) = update_requirements req_sorts req_ops in
let buf = B.create 1024 in
smt_preamble buf num_addr num_tid num_elem req_sorts;
smt_defs buf num_addr num_tid num_elem req_sorts req_ops;
variables_to_smt buf num_tid expr ;
let add_and_literal l str =
"\n " ^ (literal_to_str l) ^ str
in
let formula_str = List.fold_right add_and_literal ls ""
in
post_process buf num_addr num_elem num_tid;
B.add_string buf "(assert\n (and";
B.add_string buf formula_str ;
B.add_string buf "))\n";
B.add_string buf "(check-sat)\n" ;
B.contents buf
let formula_to_str (stac:Tactics.solve_tactic option)
(co:Smp.cutoff_strategy_t)
(copt:Smp.cutoff_options_t)
(phi:Expr.formula) : string =
" Entering formula_to_str ... " LEVEL TRACE ;
let extra_info_str =
match stac with
| None -> ""
| Some Tactics.Cases ->
let (ante,(eq,ineq)) =
match phi with
| Expr.Not (Expr.Implies (ante,cons)) -> (ante, Expr.get_addrs_eqs ante)
| _ -> (phi, ([],[])) in
let temp_dom = Expr.TermSet.elements
(Expr.termset_of_sort
(Expr.get_termset_from_formula ante) Expr.Addr) in
let term_dom = List.filter (fun t ->
match t with
| Expr.AddrT (Expr.VarAddr (id,s,pr,th,p)) -> th <> None || p = None
| _ -> true
) temp_dom in
let assumps = List.map (fun (x,y) -> Partition.Eq (Expr.AddrT x, Expr.AddrT y)) eq @
List.map (fun (x,y) -> Partition.Ineq (Expr.AddrT x, Expr.AddrT y)) ineq in
verbl _LONG_INFO "**** SMTTllQuery. Domain: %i\n" (List.length term_dom);
verbl _LONG_INFO "**** SMTTllQuery. Assumptions: %i\n" (List.length assumps);
let parts = Partition.gen_partitions term_dom assumps in
let _ = if LeapDebug.is_debug_enabled() then
List.iter (fun p ->
verbl _LONG_INFO "**** SMTTllQuery. Partitions:\n%s\n"
(Partition.to_str Expr.term_to_str p);
) parts in
verbl _LONG_INFO "**** SMTTllQuery. Number of cases: %i\n" (List.length parts);
verbl _LONG_INFO "**** SMTTllQuery. Computation done!!!\n";
smt_partition_assumptions parts in
clean_lists();
let _ = GM.clear_sort_map sort_map in
verbl _LONG_INFO "**** SMTTllQuery. Will compute the cutoff...\n";
let max_cut_off = SmpTll.cut_off co copt phi in
let num_addr = max_cut_off.SmpTll.num_addrs in
let num_tid = max_cut_off.SmpTll.num_tids in
let num_elem = max_cut_off.SmpTll.num_elems in
let req_sorts = Expr.required_sorts phi in
let req_ops = Expr.special_ops phi in
let formula_str = formula_to_str phi in
let (req_sorts, req_ops) = update_requirements req_sorts req_ops in
let buf = B.create 1024
in
smt_preamble buf num_addr num_tid num_elem req_sorts;
smt_defs buf num_addr num_tid num_elem req_sorts req_ops;
variables_from_formula_to_smt buf num_tid phi ;
B.add_string buf extra_info_str ;
post_process buf num_addr num_elem num_tid;
B.add_string buf "(assert\n";
B.add_string buf formula_str ;
B.add_string buf ")\n";
B.add_string buf "(check-sat)\n" ;
B.contents buf
let conjformula_to_str (expr:Expr.conjunctive_formula) : string =
match expr with
Expr.TrueConj -> "(assert true)\n(check-sat)"
| Expr.FalseConj -> "(assert false)\n(check-sat)"
| Expr.Conj conjs -> literal_list_to_str conjs
let get_sort_map () : GM.sort_map_t =
GM.copy_sort_map sort_map
end
|
93fbb29ac3a0b7cee0ef399872f54a7d035dc2e0919ad05ada36eebdfd8b7c25 | ocaml/ocamlbuild | bb.ml | (***********************************************************************)
(* *)
(* ocamlbuild *)
(* *)
, , projet Gallium , INRIA Rocquencourt
(* *)
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
let foo = [2.2]
| null | https://raw.githubusercontent.com/ocaml/ocamlbuild/792b7c8abdbc712c98ed7e69469ed354b87e125b/test/test11/b/bb.ml | ocaml | *********************************************************************
ocamlbuild
the special exception on linking described in file ../LICENSE.
********************************************************************* | , , projet Gallium , INRIA Rocquencourt
Copyright 2007 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
let foo = [2.2]
|
48b5c14978f2f9fe63f2daedd6bc476e93461ae1d6f06bd7ccc7eb38642807d9 | saltysystems/overworld | ow_app.erl | %%%-------------------------------------------------------------------
%% @doc Overworld Public API
%% @end
%%%-------------------------------------------------------------------
-module(ow_app).
-behaviour(application).
-export([start/2, stop/1]).
% status information via JSON API
-export([status/0]).
-define(PEER_LIMIT, 64).
-define(CHANNEL_LIMIT, 4).
-define(ENET_PORT, 4484).
-define(ENET_DTLS_PORT, 4485).
-define(WS_PORT, 4434).
-define(WS_TLS_PORT, 4435).
start(_StartType, _StartArgs) ->
Dispatch = cowboy_router:compile([
{'_', [
{"/ws", ow_websocket, []},
{"/client/download", ow_dl_handler, []},
{"/client/manifest", ow_dl_manifest, []},
{"/stats", ow_stats, []}
TODO - See if this is needed , I think it 's old .
%{"/libow.gd", cowboy_static,
% {file, "apps/ow_core/static/libow.gd"}}
]}
]),
% Start WebSocket/CowBoy
{ok, _} = cowboy:start_clear(
http,
[
{port, ?WS_PORT},
{nodelay, true}
],
#{env => #{dispatch => Dispatch}}
),
% Start ENet
Options = [{peer_limit, ?PEER_LIMIT}, {channel_limit, ?CHANNEL_LIMIT}],
Handler = {ow_enet, start, []},
enet:start_host(?ENET_PORT, Handler, Options),
Start the OW supervisor
ow_sup:start_link().
stop(_State) ->
ok.
status() ->
{ok, Version} = application:get_key(overworld, vsn),
{ok, Description} = application:get_key(overworld, description),
#{
<<"name">> => <<"overworld">>,
<<"version">> => erlang:list_to_binary(Version),
<<"Description">> => erlang:list_to_binary(Description)
}.
| null | https://raw.githubusercontent.com/saltysystems/overworld/e5def9e4784fde42b27cc37abfec80de58b02c14/src/ow_app.erl | erlang | -------------------------------------------------------------------
@doc Overworld Public API
@end
-------------------------------------------------------------------
status information via JSON API
{"/libow.gd", cowboy_static,
{file, "apps/ow_core/static/libow.gd"}}
Start WebSocket/CowBoy
Start ENet |
-module(ow_app).
-behaviour(application).
-export([start/2, stop/1]).
-export([status/0]).
-define(PEER_LIMIT, 64).
-define(CHANNEL_LIMIT, 4).
-define(ENET_PORT, 4484).
-define(ENET_DTLS_PORT, 4485).
-define(WS_PORT, 4434).
-define(WS_TLS_PORT, 4435).
start(_StartType, _StartArgs) ->
Dispatch = cowboy_router:compile([
{'_', [
{"/ws", ow_websocket, []},
{"/client/download", ow_dl_handler, []},
{"/client/manifest", ow_dl_manifest, []},
{"/stats", ow_stats, []}
TODO - See if this is needed , I think it 's old .
]}
]),
{ok, _} = cowboy:start_clear(
http,
[
{port, ?WS_PORT},
{nodelay, true}
],
#{env => #{dispatch => Dispatch}}
),
Options = [{peer_limit, ?PEER_LIMIT}, {channel_limit, ?CHANNEL_LIMIT}],
Handler = {ow_enet, start, []},
enet:start_host(?ENET_PORT, Handler, Options),
Start the OW supervisor
ow_sup:start_link().
stop(_State) ->
ok.
status() ->
{ok, Version} = application:get_key(overworld, vsn),
{ok, Description} = application:get_key(overworld, description),
#{
<<"name">> => <<"overworld">>,
<<"version">> => erlang:list_to_binary(Version),
<<"Description">> => erlang:list_to_binary(Description)
}.
|
ee52f52adccea45e2ebc62c15fd02883c1fc289faf8397dfa8e6ce5ede0add17 | input-output-hk/cardano-rest | TxLast.hs | {-# LANGUAGE OverloadedStrings #-}
module Explorer.Web.Api.Legacy.TxLast
( getLastTxs
) where
import Cardano.Db
( EntityField (..), Tx, isJust )
import Control.Monad.IO.Class
( MonadIO )
import Data.ByteString.Char8
( ByteString )
import Data.Fixed
( Fixed (..), Uni )
import Data.Time.Clock
( UTCTime )
import Data.Time.Clock.POSIX
( utcTimeToPOSIXSeconds )
import Database.Esqueleto
( Entity
, InnerJoin (..)
, SqlExpr
, Value
, desc
, from
, limit
, on
, orderBy
, select
, subSelectUnsafe
, sum_
, unValue
, where_
, (==.)
, (^.)
)
import Database.Persist.Sql
( SqlPersistT )
import Explorer.Web.Api.Legacy.Util
import Explorer.Web.ClientTypes
( CHash (..), CTxEntry (..), CTxHash (..) )
import Explorer.Web.Error
( ExplorerError (..) )
getLastTxs :: MonadIO m => SqlPersistT m (Either ExplorerError [CTxEntry])
getLastTxs = Right <$> queryCTxEntry
queryCTxEntry :: MonadIO m => SqlPersistT m [CTxEntry]
queryCTxEntry = do
txRows <- select . from $ \ (blk `InnerJoin` tx) -> do
on (blk ^. BlockId ==. tx ^. TxBlockId)
where_ (isJust $ blk ^. BlockSlotNo)
orderBy [desc (blk ^. BlockSlotNo)]
limit 20
pure (blk ^. BlockTime, tx ^. TxHash, txOutValue tx)
pure $ map convert txRows
where
convert :: (Value UTCTime, Value ByteString, Value (Maybe Uni)) -> CTxEntry
convert (vtime, vhash, vtotal) =
CTxEntry
{ cteId = CTxHash . CHash $ bsBase16Encode (unValue vhash)
, cteTimeIssued = Just $ utcTimeToPOSIXSeconds (unValue vtime)
, cteAmount = unTotal vtotal
}
txOutValue :: SqlExpr (Entity Tx) -> SqlExpr (Value (Maybe Uni))
txOutValue tx =
-- This actually is safe.
subSelectUnsafe . from $ \ txOut -> do
where_ (txOut ^. TxOutTxId ==. tx ^. TxId)
pure $ sum_ (txOut ^. TxOutValue)
unTotal :: Num a => Value (Maybe Uni) -> a
unTotal mvi =
fromIntegral $
case unValue mvi of
Just (MkFixed x) -> x
_ -> 0
| null | https://raw.githubusercontent.com/input-output-hk/cardano-rest/040b123b45af06060aae04479d92fada68820f12/explorer-api/src/Explorer/Web/Api/Legacy/TxLast.hs | haskell | # LANGUAGE OverloadedStrings #
This actually is safe. |
module Explorer.Web.Api.Legacy.TxLast
( getLastTxs
) where
import Cardano.Db
( EntityField (..), Tx, isJust )
import Control.Monad.IO.Class
( MonadIO )
import Data.ByteString.Char8
( ByteString )
import Data.Fixed
( Fixed (..), Uni )
import Data.Time.Clock
( UTCTime )
import Data.Time.Clock.POSIX
( utcTimeToPOSIXSeconds )
import Database.Esqueleto
( Entity
, InnerJoin (..)
, SqlExpr
, Value
, desc
, from
, limit
, on
, orderBy
, select
, subSelectUnsafe
, sum_
, unValue
, where_
, (==.)
, (^.)
)
import Database.Persist.Sql
( SqlPersistT )
import Explorer.Web.Api.Legacy.Util
import Explorer.Web.ClientTypes
( CHash (..), CTxEntry (..), CTxHash (..) )
import Explorer.Web.Error
( ExplorerError (..) )
getLastTxs :: MonadIO m => SqlPersistT m (Either ExplorerError [CTxEntry])
getLastTxs = Right <$> queryCTxEntry
queryCTxEntry :: MonadIO m => SqlPersistT m [CTxEntry]
queryCTxEntry = do
txRows <- select . from $ \ (blk `InnerJoin` tx) -> do
on (blk ^. BlockId ==. tx ^. TxBlockId)
where_ (isJust $ blk ^. BlockSlotNo)
orderBy [desc (blk ^. BlockSlotNo)]
limit 20
pure (blk ^. BlockTime, tx ^. TxHash, txOutValue tx)
pure $ map convert txRows
where
convert :: (Value UTCTime, Value ByteString, Value (Maybe Uni)) -> CTxEntry
convert (vtime, vhash, vtotal) =
CTxEntry
{ cteId = CTxHash . CHash $ bsBase16Encode (unValue vhash)
, cteTimeIssued = Just $ utcTimeToPOSIXSeconds (unValue vtime)
, cteAmount = unTotal vtotal
}
txOutValue :: SqlExpr (Entity Tx) -> SqlExpr (Value (Maybe Uni))
txOutValue tx =
subSelectUnsafe . from $ \ txOut -> do
where_ (txOut ^. TxOutTxId ==. tx ^. TxId)
pure $ sum_ (txOut ^. TxOutValue)
unTotal :: Num a => Value (Maybe Uni) -> a
unTotal mvi =
fromIntegral $
case unValue mvi of
Just (MkFixed x) -> x
_ -> 0
|
9bf9c72b69f0712937c5347464bda06ecad143809135bcf1cb2a3de80289f9ef | haskell-compat/deriving-compat | Via.hs | # LANGUAGE CPP #
|
Module : Data . Deriving . Via
Copyright : ( C ) 2015 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Portability : Template Haskell
On @template - haskell-2.12@ or later ( i.e. , GHC 8.2 or later ) , this module
exports functionality which emulates the @GeneralizedNewtypeDeriving@ and
@DerivingVia@ GHC extensions ( the latter of which was introduced in GHC 8.6 ) .
On older versions of @template - haskell@/GHC , this module does not export
anything .
Module: Data.Deriving.Via
Copyright: (C) 2015-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Portability: Template Haskell
On @template-haskell-2.12@ or later (i.e., GHC 8.2 or later), this module
exports functionality which emulates the @GeneralizedNewtypeDeriving@ and
@DerivingVia@ GHC extensions (the latter of which was introduced in GHC 8.6).
On older versions of @template-haskell@/GHC, this module does not export
anything.
-}
module Data.Deriving.Via (
#if !(MIN_VERSION_template_haskell(2,12,0))
) where
#else
-- * @GeneralizedNewtypeDeriving@
deriveGND
* @DerivingVia@
, deriveVia
, Via
-- * Limitations
-- $constraints
) where
import Data.Deriving.Internal (Via)
import Data.Deriving.Via.Internal
$ constraints
Be aware of the following potential gotchas :
* Unlike every other module in this library , the functions exported by
" Data . Deriving . Via " only support GHC 8.2 and later , as they require
Template Haskell functionality not present in earlier GHCs .
* Additionally , using the functions in " Data . Deriving . Via " will likely
require you to enable some language extensions ( besides ) .
These may include :
* @ImpredicativeTypes@ ( if any class methods contain higher - rank types )
* @InstanceSigs@
* @KindSignatures@
* @RankNTypes@
* @ScopedTypeVariables@
* @TypeApplications@
* @TypeOperators@
* @UndecidableInstances@ ( if deriving an instance of a type class with
associated type families )
* The functions in " Data . Deriving . Via " are not terribly robust in the presence
of @PolyKinds@. Alas , Template Haskell does not make this easy to fix .
* The functions in " Data . Deriving . Via " make a best - effort attempt to derive
instances for classes with associated type families . This is known not to
work in all scenarios , however , especially when the last parameter to a type
class appears as a kind variable in an associated type family . ( See
< Trac # 14728 > . )
Be aware of the following potential gotchas:
* Unlike every other module in this library, the functions exported by
"Data.Deriving.Via" only support GHC 8.2 and later, as they require
Template Haskell functionality not present in earlier GHCs.
* Additionally, using the functions in "Data.Deriving.Via" will likely
require you to enable some language extensions (besides @TemplateHaskell@).
These may include:
* @ImpredicativeTypes@ (if any class methods contain higher-rank types)
* @InstanceSigs@
* @KindSignatures@
* @RankNTypes@
* @ScopedTypeVariables@
* @TypeApplications@
* @TypeOperators@
* @UndecidableInstances@ (if deriving an instance of a type class with
associated type families)
* The functions in "Data.Deriving.Via" are not terribly robust in the presence
of @PolyKinds@. Alas, Template Haskell does not make this easy to fix.
* The functions in "Data.Deriving.Via" make a best-effort attempt to derive
instances for classes with associated type families. This is known not to
work in all scenarios, however, especially when the last parameter to a type
class appears as a kind variable in an associated type family. (See
< Trac #14728>.)
-}
#endif
| null | https://raw.githubusercontent.com/haskell-compat/deriving-compat/23e62c003325258e925e6c2fe7e46fafdeaf199a/src/Data/Deriving/Via.hs | haskell | * @GeneralizedNewtypeDeriving@
* Limitations
$constraints | # LANGUAGE CPP #
|
Module : Data . Deriving . Via
Copyright : ( C ) 2015 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Portability : Template Haskell
On @template - haskell-2.12@ or later ( i.e. , GHC 8.2 or later ) , this module
exports functionality which emulates the @GeneralizedNewtypeDeriving@ and
@DerivingVia@ GHC extensions ( the latter of which was introduced in GHC 8.6 ) .
On older versions of @template - haskell@/GHC , this module does not export
anything .
Module: Data.Deriving.Via
Copyright: (C) 2015-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Portability: Template Haskell
On @template-haskell-2.12@ or later (i.e., GHC 8.2 or later), this module
exports functionality which emulates the @GeneralizedNewtypeDeriving@ and
@DerivingVia@ GHC extensions (the latter of which was introduced in GHC 8.6).
On older versions of @template-haskell@/GHC, this module does not export
anything.
-}
module Data.Deriving.Via (
#if !(MIN_VERSION_template_haskell(2,12,0))
) where
#else
deriveGND
* @DerivingVia@
, deriveVia
, Via
) where
import Data.Deriving.Internal (Via)
import Data.Deriving.Via.Internal
$ constraints
Be aware of the following potential gotchas :
* Unlike every other module in this library , the functions exported by
" Data . Deriving . Via " only support GHC 8.2 and later , as they require
Template Haskell functionality not present in earlier GHCs .
* Additionally , using the functions in " Data . Deriving . Via " will likely
require you to enable some language extensions ( besides ) .
These may include :
* @ImpredicativeTypes@ ( if any class methods contain higher - rank types )
* @InstanceSigs@
* @KindSignatures@
* @RankNTypes@
* @ScopedTypeVariables@
* @TypeApplications@
* @TypeOperators@
* @UndecidableInstances@ ( if deriving an instance of a type class with
associated type families )
* The functions in " Data . Deriving . Via " are not terribly robust in the presence
of @PolyKinds@. Alas , Template Haskell does not make this easy to fix .
* The functions in " Data . Deriving . Via " make a best - effort attempt to derive
instances for classes with associated type families . This is known not to
work in all scenarios , however , especially when the last parameter to a type
class appears as a kind variable in an associated type family . ( See
< Trac # 14728 > . )
Be aware of the following potential gotchas:
* Unlike every other module in this library, the functions exported by
"Data.Deriving.Via" only support GHC 8.2 and later, as they require
Template Haskell functionality not present in earlier GHCs.
* Additionally, using the functions in "Data.Deriving.Via" will likely
require you to enable some language extensions (besides @TemplateHaskell@).
These may include:
* @ImpredicativeTypes@ (if any class methods contain higher-rank types)
* @InstanceSigs@
* @KindSignatures@
* @RankNTypes@
* @ScopedTypeVariables@
* @TypeApplications@
* @TypeOperators@
* @UndecidableInstances@ (if deriving an instance of a type class with
associated type families)
* The functions in "Data.Deriving.Via" are not terribly robust in the presence
of @PolyKinds@. Alas, Template Haskell does not make this easy to fix.
* The functions in "Data.Deriving.Via" make a best-effort attempt to derive
instances for classes with associated type families. This is known not to
work in all scenarios, however, especially when the last parameter to a type
class appears as a kind variable in an associated type family. (See
< Trac #14728>.)
-}
#endif
|
bd94d095e1a8e85e2af7641ed13c15e69accf067f9782446270ba83180400311 | susisu/est-ocaml | value.mli | open Core
type t = Num of float
| Fun of (t -> t)
| Vec of t array
val equal : t -> t -> bool
val type_string_of : t -> string
val to_string : t -> string
| null | https://raw.githubusercontent.com/susisu/est-ocaml/e610d07b166a51e5763aa4f7b12449ec0438071c/src/value.mli | ocaml | open Core
type t = Num of float
| Fun of (t -> t)
| Vec of t array
val equal : t -> t -> bool
val type_string_of : t -> string
val to_string : t -> string
|
|
dbbd7748e56a6e271121808efb1f73a23a629a8b1020ac3c8193cdd2b5cfd45f | exoscale/pithos | keystore.clj | (ns io.pithos.keystore
"A keystore is a simple protocol which yields a map
of tenant details for a key id.
The basic implementation wants keys from the configuration
file, you'll likely want to use a custom implementation that
interacts with your user-base here.
")
(defn map-keystore [{:keys [keys]}]
"Wrap a map, translating looked-up keys to keywords."
(reify
clojure.lang.ILookup
(valAt [this id]
(get keys (keyword id)))))
| null | https://raw.githubusercontent.com/exoscale/pithos/54790f00fbfd330c6196d42e5408385028d5e029/src/io/pithos/keystore.clj | clojure | (ns io.pithos.keystore
"A keystore is a simple protocol which yields a map
of tenant details for a key id.
The basic implementation wants keys from the configuration
file, you'll likely want to use a custom implementation that
interacts with your user-base here.
")
(defn map-keystore [{:keys [keys]}]
"Wrap a map, translating looked-up keys to keywords."
(reify
clojure.lang.ILookup
(valAt [this id]
(get keys (keyword id)))))
|
|
5439783633eec778fcf4318ce29e5001b2ffd9ec375e5965ed5b19fd50170c91 | flyspeck/flyspeck | arith_float.mli | open Hol_core
open Num
val mk_num_exp : term -> term -> term
val dest_num_exp : term -> (term * term)
val dest_float : term -> (string * term * term)
val float_lt0 : term -> thm
val float_gt0 : term -> thm
val float_lt : term -> term -> thm
val float_le0 : term -> thm
val float_ge0 : term -> thm
val float_le : term -> term -> thm
val float_min : term -> term -> thm
val float_max : term -> term -> thm
val float_min_max : term -> term -> (thm * thm)
val float_mul_eq : term -> term -> thm
val float_mul_lo : int -> term -> term -> thm
val float_mul_hi : int -> term -> term -> thm
val float_div_lo : int -> term -> term -> thm
val float_div_hi : int -> term -> term -> thm
val float_add_lo : int -> term -> term -> thm
val float_add_hi : int -> term -> term -> thm
val float_sub_lo : int -> term -> term -> thm
val float_sub_hi : int -> term -> term -> thm
val float_sqrt_lo : int -> term -> thm
val float_sqrt_hi : int -> term -> thm
val float_prove_le : term -> term -> bool * thm
val float_prove_lt : term -> term -> bool * thm
val float_prove_le_interval : term -> thm -> bool * thm
val float_prove_ge_interval : term -> thm -> bool * thm
val float_prove_lt_interval : term -> thm -> bool * thm
val float_prove_gt_interval : term -> thm -> bool * thm
val float_compare_interval : term -> thm -> int * thm
val reset_stat : unit -> unit
val reset_cache : unit -> unit
val print_stat : unit -> unit
val dest_float_interval : term -> term * term * term
val mk_float_interval_small_num : int -> thm
val mk_float_interval_num : num -> thm
val float_lo : int -> term -> thm
val float_hi : int -> term -> thm
val float_interval_round : int -> thm -> thm
val float_interval_neg : thm -> thm
val float_interval_mul : int -> thm -> thm -> thm
val float_interval_div : int -> thm -> thm -> thm
val float_interval_add : int -> thm -> thm -> thm
val float_interval_sub : int -> thm -> thm -> thm
val float_interval_sqrt : int -> thm -> thm
val float_abs : term -> thm
val FLOAT_TO_NUM_CONV : term -> thm
| null | https://raw.githubusercontent.com/flyspeck/flyspeck/05bd66666b4b641f49e5131a37830f4881f39db9/azure/formal_ineqs-nat/arith/arith_float.mli | ocaml | open Hol_core
open Num
val mk_num_exp : term -> term -> term
val dest_num_exp : term -> (term * term)
val dest_float : term -> (string * term * term)
val float_lt0 : term -> thm
val float_gt0 : term -> thm
val float_lt : term -> term -> thm
val float_le0 : term -> thm
val float_ge0 : term -> thm
val float_le : term -> term -> thm
val float_min : term -> term -> thm
val float_max : term -> term -> thm
val float_min_max : term -> term -> (thm * thm)
val float_mul_eq : term -> term -> thm
val float_mul_lo : int -> term -> term -> thm
val float_mul_hi : int -> term -> term -> thm
val float_div_lo : int -> term -> term -> thm
val float_div_hi : int -> term -> term -> thm
val float_add_lo : int -> term -> term -> thm
val float_add_hi : int -> term -> term -> thm
val float_sub_lo : int -> term -> term -> thm
val float_sub_hi : int -> term -> term -> thm
val float_sqrt_lo : int -> term -> thm
val float_sqrt_hi : int -> term -> thm
val float_prove_le : term -> term -> bool * thm
val float_prove_lt : term -> term -> bool * thm
val float_prove_le_interval : term -> thm -> bool * thm
val float_prove_ge_interval : term -> thm -> bool * thm
val float_prove_lt_interval : term -> thm -> bool * thm
val float_prove_gt_interval : term -> thm -> bool * thm
val float_compare_interval : term -> thm -> int * thm
val reset_stat : unit -> unit
val reset_cache : unit -> unit
val print_stat : unit -> unit
val dest_float_interval : term -> term * term * term
val mk_float_interval_small_num : int -> thm
val mk_float_interval_num : num -> thm
val float_lo : int -> term -> thm
val float_hi : int -> term -> thm
val float_interval_round : int -> thm -> thm
val float_interval_neg : thm -> thm
val float_interval_mul : int -> thm -> thm -> thm
val float_interval_div : int -> thm -> thm -> thm
val float_interval_add : int -> thm -> thm -> thm
val float_interval_sub : int -> thm -> thm -> thm
val float_interval_sqrt : int -> thm -> thm
val float_abs : term -> thm
val FLOAT_TO_NUM_CONV : term -> thm
|
|
a999ad9e32bc96320e4cda096ffcf7e06c9b5fa25e3697b81c4915c6590af9f9 | CardanoSolutions/ogmios | WspSpec.hs | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
# LANGUAGE QuasiQuotes #
# LANGUAGE TypeApplications #
module Codec.Json.WspSpec
( spec,
)
where
import Prelude
import Data.Aeson
( FromJSON (..), Result (..), ToJSON (..), fromJSON )
import Data.Aeson.QQ.Simple
( aesonQQ )
import GHC.Generics
( Generic )
import Test.Hspec
( Spec, context, shouldBe, specify )
import qualified Codec.Json.Wsp as Wsp
import qualified Codec.Json.Wsp.Handler as Wsp
spec :: Spec
spec = context "gWSPFromJSON" $ do
specify "can parse WSP envelope" $ do
let
json = [aesonQQ|
{ "type": "jsonwsp/request"
, "version": "1.0"
, "servicename": "any"
, "methodname": "Foo"
, "args":
{ "foo": 14
, "bar": true
}
}
|]
in
fromJSON json `shouldBe` Success (Wsp.Request Nothing (Foo 14 True))
specify "can parse WSP envelope with mirror" $ do
let
json = [aesonQQ|
{ "type": "jsonwsp/request"
, "version": "1.0"
, "servicename": "any"
, "methodname": "Foo"
, "args":
{ "foo": 14
, "bar": true
}
, "mirror": "whatever"
}
|]
mirror = Just (toJSON ("whatever" :: String))
in
fromJSON json `shouldBe` Success (Wsp.Request mirror (Foo 14 True))
specify "fails when given a 'reflection' key" $ do
let
json = [aesonQQ|
{ "type": "jsonwsp/request"
, "version": "1.0"
, "servicename": "any"
, "methodname": "Foo"
, "args":
{ "foo": 14
, "bar": true
}
, "reflection": "whatever"
}
|]
in
fromJSON @(Wsp.Request Foo) json `shouldBe` Error "invalid key 'reflection'; should be 'mirror' on requests."
data Foo = Foo
{ foo :: Int
, bar :: Bool
} deriving (Eq, Show, Generic)
instance FromJSON (Wsp.Request Foo) where
parseJSON = Wsp.genericFromJSON Wsp.defaultOptions
| null | https://raw.githubusercontent.com/CardanoSolutions/ogmios/c52916ab99244a905556919c9e88bc47f3fbc250/server/modules/json-wsp/test/unit/Codec/Json/WspSpec.hs | haskell | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
# LANGUAGE QuasiQuotes #
# LANGUAGE TypeApplications #
module Codec.Json.WspSpec
( spec,
)
where
import Prelude
import Data.Aeson
( FromJSON (..), Result (..), ToJSON (..), fromJSON )
import Data.Aeson.QQ.Simple
( aesonQQ )
import GHC.Generics
( Generic )
import Test.Hspec
( Spec, context, shouldBe, specify )
import qualified Codec.Json.Wsp as Wsp
import qualified Codec.Json.Wsp.Handler as Wsp
spec :: Spec
spec = context "gWSPFromJSON" $ do
specify "can parse WSP envelope" $ do
let
json = [aesonQQ|
{ "type": "jsonwsp/request"
, "version": "1.0"
, "servicename": "any"
, "methodname": "Foo"
, "args":
{ "foo": 14
, "bar": true
}
}
|]
in
fromJSON json `shouldBe` Success (Wsp.Request Nothing (Foo 14 True))
specify "can parse WSP envelope with mirror" $ do
let
json = [aesonQQ|
{ "type": "jsonwsp/request"
, "version": "1.0"
, "servicename": "any"
, "methodname": "Foo"
, "args":
{ "foo": 14
, "bar": true
}
, "mirror": "whatever"
}
|]
mirror = Just (toJSON ("whatever" :: String))
in
fromJSON json `shouldBe` Success (Wsp.Request mirror (Foo 14 True))
specify "fails when given a 'reflection' key" $ do
let
json = [aesonQQ|
{ "type": "jsonwsp/request"
, "version": "1.0"
, "servicename": "any"
, "methodname": "Foo"
, "args":
{ "foo": 14
, "bar": true
}
, "reflection": "whatever"
}
|]
in
fromJSON @(Wsp.Request Foo) json `shouldBe` Error "invalid key 'reflection'; should be 'mirror' on requests."
data Foo = Foo
{ foo :: Int
, bar :: Bool
} deriving (Eq, Show, Generic)
instance FromJSON (Wsp.Request Foo) where
parseJSON = Wsp.genericFromJSON Wsp.defaultOptions
|
|
feebce48955883347e9355fe1bb4064b99a9a6a2a8bd804b8a64b1a47108f639 | sebhoss/bc-clj | key_generator.clj | ;
Copyright © 2013 < >
; This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License , Version 2 ,
as published by . See / for more details .
;
(ns bouncycastle.key-generator
"Wrapper around key-generators provided by Bouncy Castle."
(:import javax.crypto.KeyGenerator
(java.security KeyPairGenerator Provider SecureRandom)
org.bouncycastle.jce.provider.BouncyCastleProvider))
(defn- generate [create-generator initialize-strength initialize-random create-key
& {:keys [strength random]}]
(let [generator (create-generator (BouncyCastleProvider.))]
(cond
(and strength random) (initialize-random generator)
strength (initialize-strength generator))
(create-key generator)))
(defn generate-key [^String algorithm & {:keys [^int strength ^SecureRandom random]}]
(generate #(KeyGenerator/getInstance algorithm ^Provider %)
#(.init ^KeyGenerator % strength)
#(.init ^KeyGenerator % strength random)
#(.generateKey ^KeyGenerator %)
:strength strength
:random random))
(defn generate-keypair [^String algorithm & {:keys [^int strength ^SecureRandom random]}]
(generate #(KeyPairGenerator/getInstance algorithm ^Provider %)
#(.initialize ^KeyPairGenerator % strength)
#(.initialize ^KeyPairGenerator % strength random)
#(.generateKeyPair ^KeyPairGenerator %)
:strength strength
:random random))
| null | https://raw.githubusercontent.com/sebhoss/bc-clj/62a8fa69d729e7efee91574e0243c411c2172b0a/src/main/clojure/bouncycastle/key_generator.clj | clojure |
This work is free. You can redistribute it and/or modify it under the
| Copyright © 2013 < >
terms of the Do What The Fuck You Want To Public License , Version 2 ,
as published by . See / for more details .
(ns bouncycastle.key-generator
"Wrapper around key-generators provided by Bouncy Castle."
(:import javax.crypto.KeyGenerator
(java.security KeyPairGenerator Provider SecureRandom)
org.bouncycastle.jce.provider.BouncyCastleProvider))
(defn- generate [create-generator initialize-strength initialize-random create-key
& {:keys [strength random]}]
(let [generator (create-generator (BouncyCastleProvider.))]
(cond
(and strength random) (initialize-random generator)
strength (initialize-strength generator))
(create-key generator)))
(defn generate-key [^String algorithm & {:keys [^int strength ^SecureRandom random]}]
(generate #(KeyGenerator/getInstance algorithm ^Provider %)
#(.init ^KeyGenerator % strength)
#(.init ^KeyGenerator % strength random)
#(.generateKey ^KeyGenerator %)
:strength strength
:random random))
(defn generate-keypair [^String algorithm & {:keys [^int strength ^SecureRandom random]}]
(generate #(KeyPairGenerator/getInstance algorithm ^Provider %)
#(.initialize ^KeyPairGenerator % strength)
#(.initialize ^KeyPairGenerator % strength random)
#(.generateKeyPair ^KeyPairGenerator %)
:strength strength
:random random))
|
f47ad41b06e3cc4db848390de334992b35c2dcc563b7d9c2298f026dc8eff3b9 | oliyh/kamera | core_test.cljs | (ns example.core-test
(:require
[cljs.test :refer-macros [deftest is testing]]
[example.core :refer [hello-user]]
[devcards.core :refer-macros [defcard-rg]]))
(defcard-rg hello-user-test
[hello-user false])
| null | https://raw.githubusercontent.com/oliyh/kamera/8e9b3708a16c09ffbdc7ffa7894e3d023dcb7101/example/test/example/core_test.cljs | clojure | (ns example.core-test
(:require
[cljs.test :refer-macros [deftest is testing]]
[example.core :refer [hello-user]]
[devcards.core :refer-macros [defcard-rg]]))
(defcard-rg hello-user-test
[hello-user false])
|
|
e36724e073792b3eec19e98624310e98e2f15589ab9d349a89caae6c04729e28 | jacekschae/learn-datomic-course-files | handlers.clj | (ns cheffy.recipe.handlers
(:require [cheffy.recipe.db :as recipe-db]
[cheffy.responses :as responses]
[ring.util.response :as rr])
(:import (java.util UUID)))
(defn list-all-recipes
[{:keys [env claims] :as _request}]
(let [account-id (:sub claims)]
(recipe-db/find-all-recipes (:datomic env) {:account-id account-id})
))
(defn create-recipe!
[{:keys [env claims parameters] :as _request}]
(let [recipe-id (UUID/randomUUID)
account-id (:sub claims)
recipe (:body parameters)]
;; FIXME: recipe-db/transact-recipe
))
(defn retrieve-recipe
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
;; FIXME: recipe-db/find-recipe-by-id
recipe '(recipe-db/find-recipe-by-id)]
(if recipe
(rr/response recipe)
(rr/not-found {:type "recipe-not-found"
:message "Recipe not found"
:data (str "recipe-id " recipe-id)}))))
(defn update-recipe!
[{:keys [env claims parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
account-id (:sub claims)
recipe (:body parameters)]
;; FIXME: recipe-db/transact-recipe
))
(defn delete-recipe!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path)]
;; FIXME: recipe-db/retract-recipe
))
(defn create-step!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
step (:body parameters)
step-id (str (UUID/randomUUID))]
;; FIXME: recipe-db/transact-step
))
(defn update-step!
[{:keys [env parameters] :as _request}]
(let [step (:body parameters)
recipe-id (-> parameters :path :recipe-id)]
;; FIXME: recipe-db/transact-step
))
(defn delete-step!
[{:keys [env parameters] :as _request}]
(let [step (:body parameters)]
;; FIXME: recipe-db/retract-step
))
(defn create-ingredient!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
ingredient (:body parameters)
ingredient-id (str (UUID/randomUUID))]
;; FIXME: recipe-db/transact-ingredient
))
(defn update-ingredient!
[{:keys [env parameters] :as _request}]
(let [ingredient (:body parameters)
recipe-id (-> parameters :path :recipe-id)]
;; FIXME: recipe-db/transact-ingredient
))
(defn delete-ingredient!
[{:keys [env parameters] :as _request}]
(let [ingredient (:body parameters)]
;; FIXME: recipe-db/retract-ingredient
))
(defn favorite-recipe!
[{:keys [env claims parameters] :as _request}]
(let [account-id (:sub claims)
recipe-id (-> parameters :path :recipe-id)]
;; FIXME: recipe-db/favorite-recipe
))
(defn unfavorite-recipe!
[{:keys [env claims parameters] :as _request}]
(let [account-id (:sub claims)
recipe-id (-> parameters :path :recipe-id)]
;; FIXME: recipe-db/unfavorite-recipe
)) | null | https://raw.githubusercontent.com/jacekschae/learn-datomic-course-files/d27af218b89006497fd868d58b58b282e7c3e38c/increments/23-list-all-recipes-tests/src/main/cheffy/recipe/handlers.clj | clojure | FIXME: recipe-db/transact-recipe
FIXME: recipe-db/find-recipe-by-id
FIXME: recipe-db/transact-recipe
FIXME: recipe-db/retract-recipe
FIXME: recipe-db/transact-step
FIXME: recipe-db/transact-step
FIXME: recipe-db/retract-step
FIXME: recipe-db/transact-ingredient
FIXME: recipe-db/transact-ingredient
FIXME: recipe-db/retract-ingredient
FIXME: recipe-db/favorite-recipe
FIXME: recipe-db/unfavorite-recipe | (ns cheffy.recipe.handlers
(:require [cheffy.recipe.db :as recipe-db]
[cheffy.responses :as responses]
[ring.util.response :as rr])
(:import (java.util UUID)))
(defn list-all-recipes
[{:keys [env claims] :as _request}]
(let [account-id (:sub claims)]
(recipe-db/find-all-recipes (:datomic env) {:account-id account-id})
))
(defn create-recipe!
[{:keys [env claims parameters] :as _request}]
(let [recipe-id (UUID/randomUUID)
account-id (:sub claims)
recipe (:body parameters)]
))
(defn retrieve-recipe
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
recipe '(recipe-db/find-recipe-by-id)]
(if recipe
(rr/response recipe)
(rr/not-found {:type "recipe-not-found"
:message "Recipe not found"
:data (str "recipe-id " recipe-id)}))))
(defn update-recipe!
[{:keys [env claims parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
account-id (:sub claims)
recipe (:body parameters)]
))
(defn delete-recipe!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path)]
))
(defn create-step!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
step (:body parameters)
step-id (str (UUID/randomUUID))]
))
(defn update-step!
[{:keys [env parameters] :as _request}]
(let [step (:body parameters)
recipe-id (-> parameters :path :recipe-id)]
))
(defn delete-step!
[{:keys [env parameters] :as _request}]
(let [step (:body parameters)]
))
(defn create-ingredient!
[{:keys [env parameters] :as _request}]
(let [recipe-id (-> parameters :path :recipe-id)
ingredient (:body parameters)
ingredient-id (str (UUID/randomUUID))]
))
(defn update-ingredient!
[{:keys [env parameters] :as _request}]
(let [ingredient (:body parameters)
recipe-id (-> parameters :path :recipe-id)]
))
(defn delete-ingredient!
[{:keys [env parameters] :as _request}]
(let [ingredient (:body parameters)]
))
(defn favorite-recipe!
[{:keys [env claims parameters] :as _request}]
(let [account-id (:sub claims)
recipe-id (-> parameters :path :recipe-id)]
))
(defn unfavorite-recipe!
[{:keys [env claims parameters] :as _request}]
(let [account-id (:sub claims)
recipe-id (-> parameters :path :recipe-id)]
)) |
63f57edbe4c77dfddaba2d5f7c5d71ec975c155f5560c1541ce08f6dc25b1771 | Ericson2314/lighthouse | Parse.hs | Copyright ( c ) 2000 Galois Connections , Inc.
-- All rights reserved. This software is distributed as
-- free software under the license in the file "LICENSE",
-- which is included in the distribution.
module Parse where
import Char
import Text.ParserCombinators.Parsec hiding (token)
import Data
program :: Parser Code
program =
do { whiteSpace
; ts <- tokenList
; eof
; return ts
}
tokenList :: Parser Code
tokenList = many token <?> "list of tokens"
token :: Parser GMLToken
token =
do { ts <- braces tokenList ; return (TBody ts) }
<|> do { ts <- brackets tokenList ; return (TArray ts) }
<|> (do { s <- gmlString ; return (TString s) } <?> "string")
<|> (do { t <- pident False ; return t } <?> "identifier")
<|> (do { char '/' -- No whitespace after slash
; t <- pident True ; return t } <?> "binding identifier")
<|> (do { n <- number ; return n } <?> "number")
pident :: Bool -> Parser GMLToken
pident rebind =
do { id <- ident
; case (lookup id opTable) of
Nothing -> if rebind then return (TBind id) else return (TId id)
Just t -> if rebind then error ("Attempted rebinding of identifier " ++ id) else return t
}
ident :: Parser String
ident = lexeme $
do { l <- letter
; ls <- many (satisfy (\x -> isAlphaNum x || x == '-' || x == '_'))
; return (l:ls)
}
gmlString :: Parser String
gmlString = lexeme $ between (char '"') (char '"') (many (satisfy (\x -> isPrint x && x /= '"')))
-- Tests for numbers
-- Hugs breaks on big exponents (> ~40)
test_number = "1234 -1234 1 -0 0" ++
" 1234.5678 -1234.5678 1234.5678e12 1234.5678e-12 -1234.5678e-12" ++
" -1234.5678e12 -1234.5678E-12 -1234.5678E12" ++
" 1234e11 1234E33 -1234e33 1234e-33" ++
" 123e 123.4e 123ee 123.4ee 123E 123.4E 123EE 123.4EE"
-- Always int or real
number :: Parser GMLToken
number = lexeme $
do { s <- optSign
; n <- decimal
; do { string "."
; m <- decimal
; e <- option "" exponent'
; return (TReal (read (s ++ n ++ "." ++ m ++ e))) -- FIXME: Handle error conditions
}
<|> do { e <- exponent'
; return (TReal (read (s ++ n ++ ".0" ++ e)))
}
<|> do { return (TInt (read (s ++ n))) }
}
exponent' :: Parser String
exponent' = try $
do { e <- oneOf "eE"
; s <- optSign
; n <- decimal
; return (e:s ++ n)
}
decimal = many1 digit
optSign :: Parser String
optSign = option "" (string "-")
------------------------------------------------------
-- Library for tokenizing.
braces p = between (symbol "{") (symbol "}") p
brackets p = between (symbol "[") (symbol "]") p
symbol name = lexeme (string name)
lexeme p = do{ x <- p; whiteSpace; return x }
whiteSpace = skipMany (simpleSpace <|> oneLineComment <?> "")
where simpleSpace = skipMany1 (oneOf " \t\n\r\v")
oneLineComment =
do{ string "%"
; skipMany (noneOf "\n\r\v")
; return ()
}
------------------------------------------------------------------------------
rayParse :: String -> Code
rayParse is = case (parse program "<stdin>" is) of
Left err -> error (show err)
Right x -> x
rayParseF :: String -> IO Code
rayParseF file =
do { r <- parseFromFile program file
; case r of
Left err -> error (show err)
Right x -> return x
}
run :: String -> IO ()
run is = case (parse program "" is) of
Left err -> print err
Right x -> print x
runF :: IO ()
runF =
do { r <- parseFromFile program "simple.gml"
; case r of
Left err -> print err
Right x -> print x
}
| null | https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/hpc/tests/raytrace/Parse.hs | haskell | All rights reserved. This software is distributed as
free software under the license in the file "LICENSE",
which is included in the distribution.
No whitespace after slash
Tests for numbers
Hugs breaks on big exponents (> ~40)
Always int or real
FIXME: Handle error conditions
----------------------------------------------------
Library for tokenizing.
---------------------------------------------------------------------------- | Copyright ( c ) 2000 Galois Connections , Inc.
module Parse where
import Char
import Text.ParserCombinators.Parsec hiding (token)
import Data
program :: Parser Code
program =
do { whiteSpace
; ts <- tokenList
; eof
; return ts
}
tokenList :: Parser Code
tokenList = many token <?> "list of tokens"
token :: Parser GMLToken
token =
do { ts <- braces tokenList ; return (TBody ts) }
<|> do { ts <- brackets tokenList ; return (TArray ts) }
<|> (do { s <- gmlString ; return (TString s) } <?> "string")
<|> (do { t <- pident False ; return t } <?> "identifier")
; t <- pident True ; return t } <?> "binding identifier")
<|> (do { n <- number ; return n } <?> "number")
pident :: Bool -> Parser GMLToken
pident rebind =
do { id <- ident
; case (lookup id opTable) of
Nothing -> if rebind then return (TBind id) else return (TId id)
Just t -> if rebind then error ("Attempted rebinding of identifier " ++ id) else return t
}
ident :: Parser String
ident = lexeme $
do { l <- letter
; ls <- many (satisfy (\x -> isAlphaNum x || x == '-' || x == '_'))
; return (l:ls)
}
gmlString :: Parser String
gmlString = lexeme $ between (char '"') (char '"') (many (satisfy (\x -> isPrint x && x /= '"')))
test_number = "1234 -1234 1 -0 0" ++
" 1234.5678 -1234.5678 1234.5678e12 1234.5678e-12 -1234.5678e-12" ++
" -1234.5678e12 -1234.5678E-12 -1234.5678E12" ++
" 1234e11 1234E33 -1234e33 1234e-33" ++
" 123e 123.4e 123ee 123.4ee 123E 123.4E 123EE 123.4EE"
number :: Parser GMLToken
number = lexeme $
do { s <- optSign
; n <- decimal
; do { string "."
; m <- decimal
; e <- option "" exponent'
}
<|> do { e <- exponent'
; return (TReal (read (s ++ n ++ ".0" ++ e)))
}
<|> do { return (TInt (read (s ++ n))) }
}
exponent' :: Parser String
exponent' = try $
do { e <- oneOf "eE"
; s <- optSign
; n <- decimal
; return (e:s ++ n)
}
decimal = many1 digit
optSign :: Parser String
optSign = option "" (string "-")
braces p = between (symbol "{") (symbol "}") p
brackets p = between (symbol "[") (symbol "]") p
symbol name = lexeme (string name)
lexeme p = do{ x <- p; whiteSpace; return x }
whiteSpace = skipMany (simpleSpace <|> oneLineComment <?> "")
where simpleSpace = skipMany1 (oneOf " \t\n\r\v")
oneLineComment =
do{ string "%"
; skipMany (noneOf "\n\r\v")
; return ()
}
rayParse :: String -> Code
rayParse is = case (parse program "<stdin>" is) of
Left err -> error (show err)
Right x -> x
rayParseF :: String -> IO Code
rayParseF file =
do { r <- parseFromFile program file
; case r of
Left err -> error (show err)
Right x -> return x
}
run :: String -> IO ()
run is = case (parse program "" is) of
Left err -> print err
Right x -> print x
runF :: IO ()
runF =
do { r <- parseFromFile program "simple.gml"
; case r of
Left err -> print err
Right x -> print x
}
|
0926a3572fc96ada68389636a3998c4839207d0c60cfa37fec6958ba752d6637 | xapi-project/xen-api | xapi_vtpm.ml |
Copyright ( C ) Citrix Systems Inc.
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation ; version 2.1 only . with the special
exception on linking described in file LICENSE .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU Lesser General Public License for more details .
Copyright (C) Citrix Systems Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; version 2.1 only. with the special
exception on linking described in file LICENSE.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*)
* Do n't allow unless VTPM is enabled as an experimental feature
let assert_not_restricted ~__context =
let pool = Helpers.get_pool ~__context in
let restrictions = Db.Pool.get_restrictions ~__context ~self:pool in
let feature = "restrict_vtpm" in
match List.assoc_opt feature restrictions with
| Some "false" ->
()
| _ ->
raise Api_errors.(Server_error (feature_restricted, [feature]))
* The state in the backend is only up - to - date when the VMs are halted
let assert_no_fencing ~__context ~persistence_backend =
let pool = Helpers.get_pool ~__context in
let ha_enabled = Db.Pool.get_ha_enabled ~__context ~self:pool in
let clustering_enabled = Db.Cluster.get_all ~__context <> [] in
let may_fence = ha_enabled || clustering_enabled in
match (persistence_backend, may_fence) with
| `xapi, true ->
let message = "VTPM.create with HA or clustering enabled" in
Helpers.maybe_raise_vtpm_unimplemented __FUNCTION__ message
| _ ->
()
let assert_no_vtpm_associated ~__context vm =
match Db.VM.get_VTPMs ~__context ~self:vm with
| [] ->
()
| vtpms ->
let amount = List.length vtpms |> Int.to_string in
raise Api_errors.(Server_error (vtpm_max_amount_reached, [amount]))
let introduce ~__context ~vM ~persistence_backend ~contents ~is_unique =
let ref = Ref.make () in
let uuid = Uuidx.(to_string (make ())) in
let backend = Ref.null in
Db.VTPM.create ~__context ~ref ~uuid ~vM ~backend ~persistence_backend
~is_unique ~is_protected:false ~contents ;
ref
* Contents from unique vtpms can not be copied !
let get_contents ~__context ?from () =
let create () = Xapi_secret.create ~__context ~value:"" ~other_config:[] in
let copy ref =
let contents = Db.VTPM.get_contents ~__context ~self:ref in
Xapi_secret.copy ~__context ~secret:contents
in
let maybe_copy ref =
if Db.VTPM.get_is_unique ~__context ~self:ref then
create ()
else
copy ref
in
Option.fold ~none:(create ()) ~some:maybe_copy from
let create ~__context ~vM ~is_unique =
let persistence_backend = `xapi in
assert_not_restricted ~__context ;
assert_no_fencing ~__context ~persistence_backend ;
assert_no_vtpm_associated ~__context vM ;
Xapi_vm_lifecycle.assert_initial_power_state_is ~__context ~self:vM
~expected:`Halted ;
let contents = get_contents ~__context () in
introduce ~__context ~vM ~persistence_backend ~contents ~is_unique
let copy ~__context ~vM ref =
let vtpm = Db.VTPM.get_record ~__context ~self:ref in
let persistence_backend = vtpm.vTPM_persistence_backend in
let is_unique = vtpm.vTPM_is_unique in
let contents = get_contents ~__context ~from:ref () in
introduce ~__context ~vM ~persistence_backend ~contents ~is_unique
let destroy ~__context ~self =
let vm = Db.VTPM.get_VM ~__context ~self in
Xapi_vm_lifecycle.assert_initial_power_state_is ~__context ~self:vm
~expected:`Halted ;
let secret = Db.VTPM.get_contents ~__context ~self in
Db.Secret.destroy ~__context ~self:secret ;
Db.VTPM.destroy ~__context ~self
let get_contents ~__context ~self =
let secret = Db.VTPM.get_contents ~__context ~self in
Db.Secret.get_value ~__context ~self:secret
let set_contents ~__context ~self ~contents =
let previous_secret = Db.VTPM.get_contents ~__context ~self in
let _ =
(* verify contents to be already base64-encoded *)
try Base64.decode contents
with Invalid_argument err ->
raise Api_errors.(Server_error (internal_error, [err]))
in
let secret = Xapi_secret.create ~__context ~value:contents ~other_config:[] in
Db.VTPM.set_contents ~__context ~self ~value:secret ;
Db.Secret.destroy ~__context ~self:previous_secret
| null | https://raw.githubusercontent.com/xapi-project/xen-api/48cc1489fff0e344246ecf19fc1ebed6f09c7471/ocaml/xapi/xapi_vtpm.ml | ocaml | verify contents to be already base64-encoded |
Copyright ( C ) Citrix Systems Inc.
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation ; version 2.1 only . with the special
exception on linking described in file LICENSE .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU Lesser General Public License for more details .
Copyright (C) Citrix Systems Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; version 2.1 only. with the special
exception on linking described in file LICENSE.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
*)
* Do n't allow unless VTPM is enabled as an experimental feature
let assert_not_restricted ~__context =
let pool = Helpers.get_pool ~__context in
let restrictions = Db.Pool.get_restrictions ~__context ~self:pool in
let feature = "restrict_vtpm" in
match List.assoc_opt feature restrictions with
| Some "false" ->
()
| _ ->
raise Api_errors.(Server_error (feature_restricted, [feature]))
* The state in the backend is only up - to - date when the VMs are halted
let assert_no_fencing ~__context ~persistence_backend =
let pool = Helpers.get_pool ~__context in
let ha_enabled = Db.Pool.get_ha_enabled ~__context ~self:pool in
let clustering_enabled = Db.Cluster.get_all ~__context <> [] in
let may_fence = ha_enabled || clustering_enabled in
match (persistence_backend, may_fence) with
| `xapi, true ->
let message = "VTPM.create with HA or clustering enabled" in
Helpers.maybe_raise_vtpm_unimplemented __FUNCTION__ message
| _ ->
()
let assert_no_vtpm_associated ~__context vm =
match Db.VM.get_VTPMs ~__context ~self:vm with
| [] ->
()
| vtpms ->
let amount = List.length vtpms |> Int.to_string in
raise Api_errors.(Server_error (vtpm_max_amount_reached, [amount]))
let introduce ~__context ~vM ~persistence_backend ~contents ~is_unique =
let ref = Ref.make () in
let uuid = Uuidx.(to_string (make ())) in
let backend = Ref.null in
Db.VTPM.create ~__context ~ref ~uuid ~vM ~backend ~persistence_backend
~is_unique ~is_protected:false ~contents ;
ref
* Contents from unique vtpms can not be copied !
let get_contents ~__context ?from () =
let create () = Xapi_secret.create ~__context ~value:"" ~other_config:[] in
let copy ref =
let contents = Db.VTPM.get_contents ~__context ~self:ref in
Xapi_secret.copy ~__context ~secret:contents
in
let maybe_copy ref =
if Db.VTPM.get_is_unique ~__context ~self:ref then
create ()
else
copy ref
in
Option.fold ~none:(create ()) ~some:maybe_copy from
let create ~__context ~vM ~is_unique =
let persistence_backend = `xapi in
assert_not_restricted ~__context ;
assert_no_fencing ~__context ~persistence_backend ;
assert_no_vtpm_associated ~__context vM ;
Xapi_vm_lifecycle.assert_initial_power_state_is ~__context ~self:vM
~expected:`Halted ;
let contents = get_contents ~__context () in
introduce ~__context ~vM ~persistence_backend ~contents ~is_unique
let copy ~__context ~vM ref =
let vtpm = Db.VTPM.get_record ~__context ~self:ref in
let persistence_backend = vtpm.vTPM_persistence_backend in
let is_unique = vtpm.vTPM_is_unique in
let contents = get_contents ~__context ~from:ref () in
introduce ~__context ~vM ~persistence_backend ~contents ~is_unique
let destroy ~__context ~self =
let vm = Db.VTPM.get_VM ~__context ~self in
Xapi_vm_lifecycle.assert_initial_power_state_is ~__context ~self:vm
~expected:`Halted ;
let secret = Db.VTPM.get_contents ~__context ~self in
Db.Secret.destroy ~__context ~self:secret ;
Db.VTPM.destroy ~__context ~self
let get_contents ~__context ~self =
let secret = Db.VTPM.get_contents ~__context ~self in
Db.Secret.get_value ~__context ~self:secret
let set_contents ~__context ~self ~contents =
let previous_secret = Db.VTPM.get_contents ~__context ~self in
let _ =
try Base64.decode contents
with Invalid_argument err ->
raise Api_errors.(Server_error (internal_error, [err]))
in
let secret = Xapi_secret.create ~__context ~value:contents ~other_config:[] in
Db.VTPM.set_contents ~__context ~self ~value:secret ;
Db.Secret.destroy ~__context ~self:previous_secret
|
fcb93051106a6665cb02436dddbfbd00263657cdc8a04382eae1984adbcda90c | clojure/core.rrb-vector | test_utils.clj | (ns clojure.core.rrb-vector.test-utils
(:require [clojure.test :as test]
[clojure.string :as str]
[clojure.core.rrb-vector.rrbt :as rrbt]))
;; Parts of this file are nearly identical to
;; src/test/cljs/clojure/core/rrb_vector/test_utils.cljs, but also
significant parts are specific to each of the clj / cljs versions , so
while they could later be combined into a .cljc file , it may not
;; give much benefit to do so.
(def extra-checks? false)
(defn reset-optimizer-counts! []
(println "reset all optimizer counts to 0")
(reset! rrbt/peephole-optimization-count 0)
(reset! rrbt/fallback-to-slow-splice-count1 0)
(reset! rrbt/fallback-to-slow-splice-count2 0))
(defn print-optimizer-counts []
(println "optimizer counts: peephole=" @rrbt/peephole-optimization-count
"fallback1=" @rrbt/fallback-to-slow-splice-count1
"fallback2=" @rrbt/fallback-to-slow-splice-count2))
(defn now-msec []
(System/currentTimeMillis))
(def num-deftests-started (atom 0))
(def last-deftest-start-time (atom nil))
(defn print-jvm-classpath []
(let [cp-str (System/getProperty "java.class.path")
cp-strs (str/split cp-str #":")]
(println "java.class.path:")
(doseq [cp-str cp-strs]
(println " " cp-str))))
(defn print-test-env-info []
(try
(let [shift-var (resolve
'clojure.core.rrb-vector.parameters/shift-increment)]
(println "shift-increment=" @shift-var " (from parameters namespace)"))
(catch Exception e
(println "shift-increment=5 (assumed because no parameters namespace)")))
(println "extra-checks?=" extra-checks?)
(let [p (System/getProperties)]
(println "java.vm.name" (get p "java.vm.name"))
(println "java.vm.version" (get p "java.vm.version"))
(print-jvm-classpath)
(println "(clojure-version)" (clojure-version))))
(defmethod test/report :begin-test-var
[m]
(let [n (swap! num-deftests-started inc)]
(when (== n 1)
(print-test-env-info)))
(println)
(println "starting clj test" (:var m))
(reset! last-deftest-start-time (now-msec)))
(defmethod test/report :end-test-var
[m]
(println "elapsed time (sec)" (/ (- (now-msec) @last-deftest-start-time)
1000.0)))
Enable tests to be run on versions of Clojure before 1.10 , when
;; ex-message was added.
(defn ex-message-copy
"Returns the message attached to ex if ex is a Throwable.
Otherwise returns nil."
{:added "1.10"}
[ex]
(when (instance? Throwable ex)
(.getMessage ^Throwable ex)))
(defn ex-cause-copy
"Returns the cause of ex if ex is a Throwable.
Otherwise returns nil."
{:added "1.10"}
[ex]
(when (instance? Throwable ex)
(.getCause ^Throwable ex)))
| null | https://raw.githubusercontent.com/clojure/core.rrb-vector/88c2f814b47c0bbc4092dad82be2ec783ed2961f/src/test/clojure/clojure/core/rrb_vector/test_utils.clj | clojure | Parts of this file are nearly identical to
src/test/cljs/clojure/core/rrb_vector/test_utils.cljs, but also
give much benefit to do so.
ex-message was added. | (ns clojure.core.rrb-vector.test-utils
(:require [clojure.test :as test]
[clojure.string :as str]
[clojure.core.rrb-vector.rrbt :as rrbt]))
significant parts are specific to each of the clj / cljs versions , so
while they could later be combined into a .cljc file , it may not
(def extra-checks? false)
(defn reset-optimizer-counts! []
(println "reset all optimizer counts to 0")
(reset! rrbt/peephole-optimization-count 0)
(reset! rrbt/fallback-to-slow-splice-count1 0)
(reset! rrbt/fallback-to-slow-splice-count2 0))
(defn print-optimizer-counts []
(println "optimizer counts: peephole=" @rrbt/peephole-optimization-count
"fallback1=" @rrbt/fallback-to-slow-splice-count1
"fallback2=" @rrbt/fallback-to-slow-splice-count2))
(defn now-msec []
(System/currentTimeMillis))
(def num-deftests-started (atom 0))
(def last-deftest-start-time (atom nil))
(defn print-jvm-classpath []
(let [cp-str (System/getProperty "java.class.path")
cp-strs (str/split cp-str #":")]
(println "java.class.path:")
(doseq [cp-str cp-strs]
(println " " cp-str))))
(defn print-test-env-info []
(try
(let [shift-var (resolve
'clojure.core.rrb-vector.parameters/shift-increment)]
(println "shift-increment=" @shift-var " (from parameters namespace)"))
(catch Exception e
(println "shift-increment=5 (assumed because no parameters namespace)")))
(println "extra-checks?=" extra-checks?)
(let [p (System/getProperties)]
(println "java.vm.name" (get p "java.vm.name"))
(println "java.vm.version" (get p "java.vm.version"))
(print-jvm-classpath)
(println "(clojure-version)" (clojure-version))))
(defmethod test/report :begin-test-var
[m]
(let [n (swap! num-deftests-started inc)]
(when (== n 1)
(print-test-env-info)))
(println)
(println "starting clj test" (:var m))
(reset! last-deftest-start-time (now-msec)))
(defmethod test/report :end-test-var
[m]
(println "elapsed time (sec)" (/ (- (now-msec) @last-deftest-start-time)
1000.0)))
Enable tests to be run on versions of Clojure before 1.10 , when
(defn ex-message-copy
"Returns the message attached to ex if ex is a Throwable.
Otherwise returns nil."
{:added "1.10"}
[ex]
(when (instance? Throwable ex)
(.getMessage ^Throwable ex)))
(defn ex-cause-copy
"Returns the cause of ex if ex is a Throwable.
Otherwise returns nil."
{:added "1.10"}
[ex]
(when (instance? Throwable ex)
(.getCause ^Throwable ex)))
|
c6c8666273e7a08a14c28f21260caa7ecbe99b68780a558a53a62cc904e06031 | janestreet/base_quickcheck | test_generator.mli | include module type of Base_quickcheck.Generator
| null | https://raw.githubusercontent.com/janestreet/base_quickcheck/b3dc5bda5084253f62362293977e451a6c4257de/test/src/test_generator.mli | ocaml | include module type of Base_quickcheck.Generator
|
|
a664ea8d8ce8a13a73a4ee94c732ecfcbe7f968fc6a90a4766c9b47b7c78b6b8 | okuoku/nausicaa | test-mpf.sps | ;;;
Part of : / MP
Contents : tests for the MPF numbers
Date : Thu Nov 27 , 2008
;;;
;;;Abstract
;;;
;;;
;;;
Copyright ( c ) 2008 , 2009 < >
;;;
;;;This program is free software: you can redistribute it and/or modify
;;;it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or ( at
;;;your option) any later version.
;;;
;;;This program is distributed in the hope that it will be useful, but
;;;WITHOUT ANY WARRANTY; without even the implied warranty of
;;;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details .
;;;
You should have received a copy of the GNU General Public License
;;;along with this program. If not, see </>.
;;;
(import (nausicaa)
(compensations)
(checks)
(foreign memory)
(foreign cstrings)
(foreign math mp mpf)
(foreign math mp sizeof))
(check-set-mode! 'report-failed)
(display "*** testing mpf\n")
;;;; helpers
(define (mpf->string o)
(with-compensations
(letrec*
((l (malloc-small/c))
(str (compensate
(mpf_get_str pointer-null l 10 0 o)
(with
(primitive-free str))))
(s (cstring->string str))
(x (let ((x (pointer-ref-c-signed-long l 0)))
(if (char=? #\- (string-ref s 0))
(+ 1 x)
x)))
(i (substring s 0 x))
(f (substring s x (strlen str))))
(string-append i "." f))))
(parametrise ((check-test-name 'explicit-allocation))
(check
(let ((a (malloc sizeof-mpf_t))
(b (malloc sizeof-mpf_t))
(c (malloc sizeof-mpf_t)))
(mpf_init a)
(mpf_init b)
(mpf_init c)
(mpf_set_d a 10.4)
(mpf_set_si b 5)
(mpf_add c a b)
(mpf_clear a)
(mpf_clear b)
(primitive-free a)
(primitive-free b)
(begin0
(substring (mpf->string c) 0 5)
(primitive-free c)))
=> "15.40")
#t)
(parametrise ((check-test-name 'compensated-allocation))
(define (mpf/c)
(letrec ((p (compensate
(malloc sizeof-mpf_t)
(with
(mpf_clear p)
(primitive-free p)))))
(mpf_init p)
p))
(check
(with-compensations
(let ((c (mpf/c)))
(with-compensations
(let ((a (mpf/c))
(b (mpf/c)))
(mpf_set_d a 10.4)
(mpf_set_si b 5)
(mpf_add c a b)))
(substring (mpf->string c) 0 5)))
=> "15.40")
#t)
(parametrise ((check-test-name 'factory-allocation))
(define mpf-factory
(make-caching-object-factory mpf_init mpf_clear sizeof-mpf_t 10))
(define (mpf)
(letrec ((p (compensate
(mpf-factory)
(with
(mpf-factory p)))))
p))
(check
(with-compensations
(let ((c (mpf)))
(with-compensations
(let ((a (mpf))
(b (mpf)))
(mpf_set_d a 10.4)
(mpf_set_si b 5)
(mpf_add c a b)))
(substring (mpf->string c) 0 5)))
=> "15.40")
(check
(with-compensations
(let ((c (mpf)))
(with-compensations
(let ((a (mpf))
(b (mpf)))
(mpf_set_d a 10.4)
(mpf_set_si b -50)
(mpf_add c a b)))
(substring (mpf->string c) 0 8)))
=> "-39.5999")
(mpf-factory 'purge)
#t)
;;;; done
(check-report)
;;; end of file
| null | https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/mp/tests/test-mpf.sps | scheme |
Abstract
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
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
along with this program. If not, see </>.
helpers
done
end of file | Part of : / MP
Contents : tests for the MPF numbers
Date : Thu Nov 27 , 2008
Copyright ( c ) 2008 , 2009 < >
the Free Software Foundation , either version 3 of the License , or ( at
General Public License for more details .
You should have received a copy of the GNU General Public License
(import (nausicaa)
(compensations)
(checks)
(foreign memory)
(foreign cstrings)
(foreign math mp mpf)
(foreign math mp sizeof))
(check-set-mode! 'report-failed)
(display "*** testing mpf\n")
(define (mpf->string o)
(with-compensations
(letrec*
((l (malloc-small/c))
(str (compensate
(mpf_get_str pointer-null l 10 0 o)
(with
(primitive-free str))))
(s (cstring->string str))
(x (let ((x (pointer-ref-c-signed-long l 0)))
(if (char=? #\- (string-ref s 0))
(+ 1 x)
x)))
(i (substring s 0 x))
(f (substring s x (strlen str))))
(string-append i "." f))))
(parametrise ((check-test-name 'explicit-allocation))
(check
(let ((a (malloc sizeof-mpf_t))
(b (malloc sizeof-mpf_t))
(c (malloc sizeof-mpf_t)))
(mpf_init a)
(mpf_init b)
(mpf_init c)
(mpf_set_d a 10.4)
(mpf_set_si b 5)
(mpf_add c a b)
(mpf_clear a)
(mpf_clear b)
(primitive-free a)
(primitive-free b)
(begin0
(substring (mpf->string c) 0 5)
(primitive-free c)))
=> "15.40")
#t)
(parametrise ((check-test-name 'compensated-allocation))
(define (mpf/c)
(letrec ((p (compensate
(malloc sizeof-mpf_t)
(with
(mpf_clear p)
(primitive-free p)))))
(mpf_init p)
p))
(check
(with-compensations
(let ((c (mpf/c)))
(with-compensations
(let ((a (mpf/c))
(b (mpf/c)))
(mpf_set_d a 10.4)
(mpf_set_si b 5)
(mpf_add c a b)))
(substring (mpf->string c) 0 5)))
=> "15.40")
#t)
(parametrise ((check-test-name 'factory-allocation))
(define mpf-factory
(make-caching-object-factory mpf_init mpf_clear sizeof-mpf_t 10))
(define (mpf)
(letrec ((p (compensate
(mpf-factory)
(with
(mpf-factory p)))))
p))
(check
(with-compensations
(let ((c (mpf)))
(with-compensations
(let ((a (mpf))
(b (mpf)))
(mpf_set_d a 10.4)
(mpf_set_si b 5)
(mpf_add c a b)))
(substring (mpf->string c) 0 5)))
=> "15.40")
(check
(with-compensations
(let ((c (mpf)))
(with-compensations
(let ((a (mpf))
(b (mpf)))
(mpf_set_d a 10.4)
(mpf_set_si b -50)
(mpf_add c a b)))
(substring (mpf->string c) 0 8)))
=> "-39.5999")
(mpf-factory 'purge)
#t)
(check-report)
|
e8842ccc4d6016ed99b71c341db106cf47b8385138ad351d424e558957b8a6cc | nineties/Choco | Liveness.hs | -------------------------------------------------
Choco --
Chikadzume Oriented Compiler --
Copyright 2007 - 2008 by Basement fairy --
-------------------------------------------------
module Liveness (fundecl) where
{- liveness analysis -}
import Choco
import Mach
import Outputable
import Panic
import Proc
import Reg
import Control.Monad.State
import qualified Data.Set as S
isNormal r = case loc r of
Register r -> normalRegFirst <= r && r < normalRegEnd
_ -> True
normalArgs i = filter isNormal (args i)
liveness i@Inst{ idesc = Iend } finally
= (i{ live = finally }, finally)
liveness i@Inst{ idesc = Ireturn } finally
= (i, S.fromList (normalArgs i))
liveness i@Inst{ idesc = Iop Itailcall_ind } finally
= (i, S.fromList (normalArgs i))
liveness i@Inst{ idesc = Iop (Itailcall_imm _) } finally
= (i, S.fromList (normalArgs i))
liveness i@Inst{ idesc = Icond test ifso ifnot } finally
= let
(next', at_join) = liveness (next i) finally
(ifso', at_fork1) = liveness ifso at_join
(ifnot', at_fork2) = liveness ifnot at_join
at_fork = S.union at_fork1 at_fork2
in (
i{ idesc = Icond test ifso' ifnot', live = at_fork, next = next' },
S.union at_fork (S.fromList (normalArgs i))
)
liveness i@Inst{ idesc = Iloop body } finally
= let
(body', at_top) = walk body S.empty
in (
i{ idesc = Iloop body', live = at_top },
at_top
)
where
walk body set =
let (body', set') = liveness body set
newset = S.union set set'
in if newset == set
then (body', newset)
else walk body' newset
liveness i finally
= let (next', set) = liveness (next i) finally
across = set S.\\ (S.fromList $ result i)
in (i{ live = across, next = next' },
S.union across (S.fromList $ normalArgs i))
fundecl fun = do
let (body', initially_live) = liveness (fun_body fun) S.empty
{- Sanity check: only function parameters can be live at entrypoint -}
wrong_live = initially_live S.\\ (S.fromList (fun_args fun))
if not (S.null wrong_live)
then do
simpleError $ text "wrong live variables:" <+> hsep (map ppr (S.toList wrong_live))
else return fun{ fun_body = body' }
| null | https://raw.githubusercontent.com/nineties/Choco/0081351d0b556ff74f096accb65c9ab45d29ddfe/src/Liveness.hs | haskell | -----------------------------------------------
-----------------------------------------------
liveness analysis
Sanity check: only function parameters can be live at entrypoint | module Liveness (fundecl) where
import Choco
import Mach
import Outputable
import Panic
import Proc
import Reg
import Control.Monad.State
import qualified Data.Set as S
isNormal r = case loc r of
Register r -> normalRegFirst <= r && r < normalRegEnd
_ -> True
normalArgs i = filter isNormal (args i)
liveness i@Inst{ idesc = Iend } finally
= (i{ live = finally }, finally)
liveness i@Inst{ idesc = Ireturn } finally
= (i, S.fromList (normalArgs i))
liveness i@Inst{ idesc = Iop Itailcall_ind } finally
= (i, S.fromList (normalArgs i))
liveness i@Inst{ idesc = Iop (Itailcall_imm _) } finally
= (i, S.fromList (normalArgs i))
liveness i@Inst{ idesc = Icond test ifso ifnot } finally
= let
(next', at_join) = liveness (next i) finally
(ifso', at_fork1) = liveness ifso at_join
(ifnot', at_fork2) = liveness ifnot at_join
at_fork = S.union at_fork1 at_fork2
in (
i{ idesc = Icond test ifso' ifnot', live = at_fork, next = next' },
S.union at_fork (S.fromList (normalArgs i))
)
liveness i@Inst{ idesc = Iloop body } finally
= let
(body', at_top) = walk body S.empty
in (
i{ idesc = Iloop body', live = at_top },
at_top
)
where
walk body set =
let (body', set') = liveness body set
newset = S.union set set'
in if newset == set
then (body', newset)
else walk body' newset
liveness i finally
= let (next', set) = liveness (next i) finally
across = set S.\\ (S.fromList $ result i)
in (i{ live = across, next = next' },
S.union across (S.fromList $ normalArgs i))
fundecl fun = do
let (body', initially_live) = liveness (fun_body fun) S.empty
wrong_live = initially_live S.\\ (S.fromList (fun_args fun))
if not (S.null wrong_live)
then do
simpleError $ text "wrong live variables:" <+> hsep (map ppr (S.toList wrong_live))
else return fun{ fun_body = body' }
|
d7c1f331daaa3099384908f3324fde21f4564ad5dd7ac53d68df224f877e4bbd | qfpl/reflex-dom-storage | Example.hs | |
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE GADTs #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
module Storage.Example where
import Data.Functor.Identity (Identity(..))
import GHC.Generics
import Data.Dependent.Map (Some(..))
import Data.Dependent.Sum (ShowTag(..))
import Data.GADT.Show
import Data.GADT.Compare
import Data.Aeson (ToJSON(..), FromJSON(..))
import Data.GADT.Aeson
data Foo = Foo { bar :: Bool, baz :: String }
deriving (Eq, Ord, Show, Generic)
instance ToJSON Foo where
instance FromJSON Foo where
data ExampleTag a where
Tag1 :: ExampleTag Int
Tag2 :: ExampleTag Foo
instance GEq ExampleTag where
geq Tag1 Tag1 = Just Refl
geq Tag2 Tag2 = Just Refl
geq _ _ = Nothing
instance GCompare ExampleTag where
gcompare Tag1 Tag1 = GEQ
gcompare Tag1 _ = GLT
gcompare _ Tag1 = GGT
gcompare Tag2 Tag2 = GEQ
instance GShow ExampleTag where
gshowsPrec _p Tag1 = showString "Tag1"
gshowsPrec _p Tag2 = showString "Tag2"
instance ShowTag ExampleTag Identity where
showTaggedPrec Tag1 = showsPrec
showTaggedPrec Tag2 = showsPrec
instance GKey ExampleTag where
toKey (This Tag1) = "tag1"
toKey (This Tag2) = "tag2"
fromKey t =
case t of
"tag1" -> Just (This Tag1)
"tag2" -> Just (This Tag2)
_ -> Nothing
keys _ = [This Tag1, This Tag2]
instance ToJSONTag ExampleTag Identity where
toJSONTagged Tag1 (Identity x) = toJSON x
toJSONTagged Tag2 (Identity x) = toJSON x
instance FromJSONTag ExampleTag Identity where
parseJSONTagged Tag1 x = Identity <$> parseJSON x
parseJSONTagged Tag2 x = Identity <$> parseJSON x
| null | https://raw.githubusercontent.com/qfpl/reflex-dom-storage/2ffa13a48740681993dead6a10830c23d251d3a4/example/frontend/src/Storage/Example.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE OverloadedStrings # | |
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
# LANGUAGE DeriveGeneric #
# LANGUAGE MultiParamTypeClasses #
module Storage.Example where
import Data.Functor.Identity (Identity(..))
import GHC.Generics
import Data.Dependent.Map (Some(..))
import Data.Dependent.Sum (ShowTag(..))
import Data.GADT.Show
import Data.GADT.Compare
import Data.Aeson (ToJSON(..), FromJSON(..))
import Data.GADT.Aeson
data Foo = Foo { bar :: Bool, baz :: String }
deriving (Eq, Ord, Show, Generic)
instance ToJSON Foo where
instance FromJSON Foo where
data ExampleTag a where
Tag1 :: ExampleTag Int
Tag2 :: ExampleTag Foo
instance GEq ExampleTag where
geq Tag1 Tag1 = Just Refl
geq Tag2 Tag2 = Just Refl
geq _ _ = Nothing
instance GCompare ExampleTag where
gcompare Tag1 Tag1 = GEQ
gcompare Tag1 _ = GLT
gcompare _ Tag1 = GGT
gcompare Tag2 Tag2 = GEQ
instance GShow ExampleTag where
gshowsPrec _p Tag1 = showString "Tag1"
gshowsPrec _p Tag2 = showString "Tag2"
instance ShowTag ExampleTag Identity where
showTaggedPrec Tag1 = showsPrec
showTaggedPrec Tag2 = showsPrec
instance GKey ExampleTag where
toKey (This Tag1) = "tag1"
toKey (This Tag2) = "tag2"
fromKey t =
case t of
"tag1" -> Just (This Tag1)
"tag2" -> Just (This Tag2)
_ -> Nothing
keys _ = [This Tag1, This Tag2]
instance ToJSONTag ExampleTag Identity where
toJSONTagged Tag1 (Identity x) = toJSON x
toJSONTagged Tag2 (Identity x) = toJSON x
instance FromJSONTag ExampleTag Identity where
parseJSONTagged Tag1 x = Identity <$> parseJSON x
parseJSONTagged Tag2 x = Identity <$> parseJSON x
|
5b18b6440b89bb4ff62c6648e38e40d4a88a863ebff7882d5485733a2c4d8483 | haskellari/edit-distance | Benchmark.hs | # OPTIONS_GHC -fno - full - laziness #
module Main where
import Text.EditDistance.EditCosts
import Text.EditDistance.MonadUtilities
import qualified Text.EditDistance as BestEffort
import qualified Text.EditDistance.Bits as Bits
import qualified Text.EditDistance.STUArray as STUArray
import qualified Text.EditDistance.SquareSTUArray as SquareSTUArray
import Control.DeepSeq ( NFData, rnf )
import Control.Exception
import Control.Monad
import Criterion.Main
import Data.List
import Data.Time.Clock.POSIX (getPOSIXTime)
import System.Environment
import System.Exit
import System.Mem
import System.Process
import System.Random
sTRING_SIZE_STEP, mAX_STRING_SIZE :: Int
sTRING_SIZE_STEP = 3
mAX_STRING_SIZE = 108
getTime :: IO Double
getTime = realToFrac `fmap` getPOSIXTime
time :: IO a -> IO Double
time action = do
ts1 <- getTime
action
ts2 <- getTime
return $ ts2 - ts1
augment :: Monad m => (a -> m b) -> [a] -> m [(a, [b])]
augment fx xs = liftM (zip xs) $ mapM (liftM (\b -> [b]) . fx) xs
sample :: NFData a => (String -> String -> a) -> (Int, Int) -> IO Double
sample distance bounds@(i, j) = do
Generate two random strings of length i and j
gen <- newStdGen
let (string1, string2_long) = splitAt i (randoms gen)
string2 = take j string2_long
Force the two strings to be evaluated so they do n't meddle
-- with the benchmarking
evaluate (rnf string1)
evaluate (rnf string2)
Do n't want junk from previous runs causing a GC during the test
performGC
-- Our sample is the time taken to find the edit distance
putStrLn $ "Sampling " ++ show bounds
time $ loop (100000 `div` (1 + i + j)) $ evaluate (distance string1 string2) >> return ()
loop :: Monad m => Int -> m () -> m ()
loop n act = loopM_ 1 n (const act)
joinOnKey :: Eq a => [(a, [b])] -> [(a, [b])] -> [(a, [b])]
joinOnKey xs ys = [(x_a, (x_b ++ y_c)) | (x_a, x_b) <- xs, (y_a, y_c) <- ys, x_a == y_a]
gnuPlotScript :: [String] -> String
gnuPlotScript titles = "set term postscript eps enhanced color\n\
\set output \"data.ps\"\n\
\#unset key\n\
\set dgrid3d\n\
\set hidden3d\n\
\#set pm3d map\n\
\#splot \"data.plot\" using 1:2:3\n\
\splot " ++ splot_script ++ "\n\
\quit\n"
where
splot_script = " \"data.plot\ " using 1:2:3 title \"Bits\ " with lines , \"data.plot\ " using 1:2:4 title \"STUArray\ " with lines , \"data.plot\ " using 1:2:5 title \"SquareSTUArray\ " with lines "
splot_script = intercalate ", " ["\"data.plot\" using 1:2:" ++ show i ++ " title " ++ show title ++ " with lines" | (i, title) <- [3..] `zip` titles]
toGnuPlotFormat :: (Show a, Show b, Show c) => [((a, b), [c])] -> String
toGnuPlotFormat samples = unlines (header : map sampleToGnuPlotFormat samples)
where
first_cs = snd $ head samples
header = "#\tX\tY" ++ concat (replicate (length first_cs) "\tZ")
sampleToGnuPlotFormat ((a, b), cs) = concat $ intersperse "\t" $ [show a, show b] ++ map show cs
main :: IO ()
main = do
args <- getArgs
let sample_titles = ["Bits", "SquareSTUArray", "STUArray", "Best effort"]
sample_fns = [Bits.levenshteinDistance, SquareSTUArray.levenshteinDistance defaultEditCosts, STUArray.levenshteinDistance defaultEditCosts, BestEffort.levenshteinDistance defaultEditCosts]
case args of
["plot"] -> do
let sample_range = [(i, j) | i <- [0,sTRING_SIZE_STEP..mAX_STRING_SIZE]
, j <- [0,sTRING_SIZE_STEP..mAX_STRING_SIZE]]
sample_fns = [ Bits.restrictedDamerauLevenshteinDistance , , STUArray.restrictedDamerauLevenshteinDistance defaultEditCosts , BestEffort.restrictedDamerauLevenshteinDistance defaultEditCosts ]
sampless <- forM sample_fns $ \sample_fn -> augment (sample sample_fn) sample_range
let listified_samples = foldr1 joinOnKey sampless
writeFile "data.plot" (toGnuPlotFormat listified_samples)
writeFile "plot.script" (gnuPlotScript sample_titles)
(_inp, _outp, _err, gp_pid) <- runInteractiveCommand "(cat plot.script | gnuplot); RETCODE=$?; rm plot.script; exit $RETCODE"
gp_exit_code <- waitForProcess gp_pid
case gp_exit_code of
ExitSuccess -> putStrLn "Plotted at 'data.ps'"
ExitFailure err_no -> putStrLn $ "Failed! Error code " ++ show err_no
_ -> do
let mkBench n m name f = bench name $ whnf (uncurry f) (replicate n 'a', replicate m 'b')
defaultMain [ bgroup (show (n, m)) (zipWith (mkBench n m) sample_titles sample_fns)
| (n, m) <- [(32, 32), (32, mAX_STRING_SIZE), (mAX_STRING_SIZE, 32), (mAX_STRING_SIZE, mAX_STRING_SIZE)]]
| null | https://raw.githubusercontent.com/haskellari/edit-distance/5521afd4f4966a947499a16cfc7ce6d9e0a028ee/Text/EditDistance/Benchmark.hs | haskell | with the benchmarking
Our sample is the time taken to find the edit distance | # OPTIONS_GHC -fno - full - laziness #
module Main where
import Text.EditDistance.EditCosts
import Text.EditDistance.MonadUtilities
import qualified Text.EditDistance as BestEffort
import qualified Text.EditDistance.Bits as Bits
import qualified Text.EditDistance.STUArray as STUArray
import qualified Text.EditDistance.SquareSTUArray as SquareSTUArray
import Control.DeepSeq ( NFData, rnf )
import Control.Exception
import Control.Monad
import Criterion.Main
import Data.List
import Data.Time.Clock.POSIX (getPOSIXTime)
import System.Environment
import System.Exit
import System.Mem
import System.Process
import System.Random
sTRING_SIZE_STEP, mAX_STRING_SIZE :: Int
sTRING_SIZE_STEP = 3
mAX_STRING_SIZE = 108
getTime :: IO Double
getTime = realToFrac `fmap` getPOSIXTime
time :: IO a -> IO Double
time action = do
ts1 <- getTime
action
ts2 <- getTime
return $ ts2 - ts1
augment :: Monad m => (a -> m b) -> [a] -> m [(a, [b])]
augment fx xs = liftM (zip xs) $ mapM (liftM (\b -> [b]) . fx) xs
sample :: NFData a => (String -> String -> a) -> (Int, Int) -> IO Double
sample distance bounds@(i, j) = do
Generate two random strings of length i and j
gen <- newStdGen
let (string1, string2_long) = splitAt i (randoms gen)
string2 = take j string2_long
Force the two strings to be evaluated so they do n't meddle
evaluate (rnf string1)
evaluate (rnf string2)
Do n't want junk from previous runs causing a GC during the test
performGC
putStrLn $ "Sampling " ++ show bounds
time $ loop (100000 `div` (1 + i + j)) $ evaluate (distance string1 string2) >> return ()
loop :: Monad m => Int -> m () -> m ()
loop n act = loopM_ 1 n (const act)
joinOnKey :: Eq a => [(a, [b])] -> [(a, [b])] -> [(a, [b])]
joinOnKey xs ys = [(x_a, (x_b ++ y_c)) | (x_a, x_b) <- xs, (y_a, y_c) <- ys, x_a == y_a]
gnuPlotScript :: [String] -> String
gnuPlotScript titles = "set term postscript eps enhanced color\n\
\set output \"data.ps\"\n\
\#unset key\n\
\set dgrid3d\n\
\set hidden3d\n\
\#set pm3d map\n\
\#splot \"data.plot\" using 1:2:3\n\
\splot " ++ splot_script ++ "\n\
\quit\n"
where
splot_script = " \"data.plot\ " using 1:2:3 title \"Bits\ " with lines , \"data.plot\ " using 1:2:4 title \"STUArray\ " with lines , \"data.plot\ " using 1:2:5 title \"SquareSTUArray\ " with lines "
splot_script = intercalate ", " ["\"data.plot\" using 1:2:" ++ show i ++ " title " ++ show title ++ " with lines" | (i, title) <- [3..] `zip` titles]
toGnuPlotFormat :: (Show a, Show b, Show c) => [((a, b), [c])] -> String
toGnuPlotFormat samples = unlines (header : map sampleToGnuPlotFormat samples)
where
first_cs = snd $ head samples
header = "#\tX\tY" ++ concat (replicate (length first_cs) "\tZ")
sampleToGnuPlotFormat ((a, b), cs) = concat $ intersperse "\t" $ [show a, show b] ++ map show cs
main :: IO ()
main = do
args <- getArgs
let sample_titles = ["Bits", "SquareSTUArray", "STUArray", "Best effort"]
sample_fns = [Bits.levenshteinDistance, SquareSTUArray.levenshteinDistance defaultEditCosts, STUArray.levenshteinDistance defaultEditCosts, BestEffort.levenshteinDistance defaultEditCosts]
case args of
["plot"] -> do
let sample_range = [(i, j) | i <- [0,sTRING_SIZE_STEP..mAX_STRING_SIZE]
, j <- [0,sTRING_SIZE_STEP..mAX_STRING_SIZE]]
sample_fns = [ Bits.restrictedDamerauLevenshteinDistance , , STUArray.restrictedDamerauLevenshteinDistance defaultEditCosts , BestEffort.restrictedDamerauLevenshteinDistance defaultEditCosts ]
sampless <- forM sample_fns $ \sample_fn -> augment (sample sample_fn) sample_range
let listified_samples = foldr1 joinOnKey sampless
writeFile "data.plot" (toGnuPlotFormat listified_samples)
writeFile "plot.script" (gnuPlotScript sample_titles)
(_inp, _outp, _err, gp_pid) <- runInteractiveCommand "(cat plot.script | gnuplot); RETCODE=$?; rm plot.script; exit $RETCODE"
gp_exit_code <- waitForProcess gp_pid
case gp_exit_code of
ExitSuccess -> putStrLn "Plotted at 'data.ps'"
ExitFailure err_no -> putStrLn $ "Failed! Error code " ++ show err_no
_ -> do
let mkBench n m name f = bench name $ whnf (uncurry f) (replicate n 'a', replicate m 'b')
defaultMain [ bgroup (show (n, m)) (zipWith (mkBench n m) sample_titles sample_fns)
| (n, m) <- [(32, 32), (32, mAX_STRING_SIZE), (mAX_STRING_SIZE, 32), (mAX_STRING_SIZE, mAX_STRING_SIZE)]]
|
fd0ca10bfd3a2f7880e048717fe04d2184294bdff0b2e893242a02e1dcb87bc5 | pgujjula/list-utilities | Filter.hs | | Module : Data . List . Filter
Description : Special takes and drops on lists
Copyright : ( c ) , 2020
License : BSD3
Maintainer : pgujjula+
Stability : experimental
Special takes and drops on lists .
Description : Special takes and drops on lists
Copyright : (c) Preetham Gujjula, 2020
License : BSD3
Maintainer : pgujjula+
Stability : experimental
Special takes and drops on lists.
-}
module Data.List.Filter (
takeEvery
, dropEvery
, takeUntil
, dropUntil
) where
is a list of every @n@th element of @xs@.
_ _ Precondition : _ _ must be positive .
> > > takeEvery 3 [ 1 .. 10 ]
[ 3 , 6 , 9 ]
> > > takeEvery 1 [ 1 .. 10 ] = = [ 1 .. 10 ]
True
__Precondition:__ @n@ must be positive.
>>> takeEvery 3 [1..10]
[3, 6, 9]
>>> takeEvery 1 [1..10] == [1..10]
True
-}
takeEvery :: Int -> [a] -> [a]
takeEvery step xs = compute validated
where
compute ys = case drop (step - 1) ys of
[] -> []
y:ys' -> y : compute ys'
validated
| step > 0 = xs
| otherwise = error $ "Data.List.Transform.takeEvery: Step parameter "
++ "must be positive."
| @dropEvery n xs@ is a list of every @n@th element of @xs@.
_ _ Precondition : _ _ must be positive .
> > > dropEvery 3 [ 1 .. 10 ]
[ 1 , 2 , 4 , 5 , 7 , 8 , 10 ]
> > > dropEvery 1 [ 1 .. 10 ]
[ ]
__Precondition:__ @n@ must be positive.
>>> dropEvery 3 [1..10]
[1, 2, 4, 5, 7, 8, 10]
>>> dropEvery 1 [1..10]
[]
-}
dropEvery :: Int -> [a] -> [a]
dropEvery step xs = compute validated
where
compute ys = case splitAt (step - 1) ys of
(as, []) -> as
(as, _:bs) -> as ++ compute bs
validated
| step > 0 = xs
| otherwise = error $ "Data.List.Transform.dropEvery: Step parameter "
++ "must be positive."
| Take a list until a predicate is satisfied , and include the element
satisfying the predicate .
> > > takeUntil (= = 5 ) [ 1 .. ]
[ 1 , 2 , 3 , 4 , 5 ]
> > > takeUntil (= = 7 ) [ 3 , 2 , 1 ]
[ 3 , 2 , 1 ]
> > > takeUntil undefined [ ]
[ ]
Note that @takeUntil@ on a nonempty list must always yield the first
element , and the implementation is lazy enough to take advantage of this
fact .
> > > head ( takeUntil undefined [ 1 .. ] )
1
satisfying the predicate.
>>> takeUntil (== 5) [1..]
[1, 2, 3, 4, 5]
>>> takeUntil (== 7) [3, 2, 1]
[3, 2, 1]
>>> takeUntil undefined []
[]
Note that @takeUntil@ on a nonempty list must always yield the first
element, and the implementation is lazy enough to take advantage of this
fact.
>>> head (takeUntil undefined [1..])
1
-}
takeUntil :: (a -> Bool) -> [a] -> [a]
takeUntil _ [] = []
takeUntil _ [x] = [x]
takeUntil f (x:xs) = x : (if f x then [] else takeUntil f xs)
| Drop a list until a predicate is satisfied , and do n't include the element
satisfying the predicate .
> > > dropUntil (= = 5 ) [ 1 .. 10 ]
[ 6 , 7 , 8 , 9 , 10 ]
> > > dropUntil ( < 0 ) [ 1 , 2 , 3 ]
[ ]
> > > dropUntil undefined [ ]
[ ]
Note that @dropUntil@ on a nonempty list must always drop the first
element , and the implementation is lazy enough to take advantage of this
fact .
> > > dropUntil undefined [ undefined ]
[ ]
satisfying the predicate.
>>> dropUntil (== 5) [1..10]
[6, 7, 8, 9, 10]
>>> dropUntil (< 0) [1, 2, 3]
[]
>>> dropUntil undefined []
[]
Note that @dropUntil@ on a nonempty list must always drop the first
element, and the implementation is lazy enough to take advantage of this
fact.
>>> dropUntil undefined [undefined]
[]
-}
dropUntil :: (a -> Bool) -> [a] -> [a]
dropUntil _ [] = []
dropUntil _ [_] = []
dropUntil f (x:xs) = if f x then xs else dropUntil f xs
| null | https://raw.githubusercontent.com/pgujjula/list-utilities/03d26bb5a16fa0fb7ae5b112e1897fbf79d11c92/list-filter/src/Data/List/Filter.hs | haskell | | Module : Data . List . Filter
Description : Special takes and drops on lists
Copyright : ( c ) , 2020
License : BSD3
Maintainer : pgujjula+
Stability : experimental
Special takes and drops on lists .
Description : Special takes and drops on lists
Copyright : (c) Preetham Gujjula, 2020
License : BSD3
Maintainer : pgujjula+
Stability : experimental
Special takes and drops on lists.
-}
module Data.List.Filter (
takeEvery
, dropEvery
, takeUntil
, dropUntil
) where
is a list of every @n@th element of @xs@.
_ _ Precondition : _ _ must be positive .
> > > takeEvery 3 [ 1 .. 10 ]
[ 3 , 6 , 9 ]
> > > takeEvery 1 [ 1 .. 10 ] = = [ 1 .. 10 ]
True
__Precondition:__ @n@ must be positive.
>>> takeEvery 3 [1..10]
[3, 6, 9]
>>> takeEvery 1 [1..10] == [1..10]
True
-}
takeEvery :: Int -> [a] -> [a]
takeEvery step xs = compute validated
where
compute ys = case drop (step - 1) ys of
[] -> []
y:ys' -> y : compute ys'
validated
| step > 0 = xs
| otherwise = error $ "Data.List.Transform.takeEvery: Step parameter "
++ "must be positive."
| @dropEvery n xs@ is a list of every @n@th element of @xs@.
_ _ Precondition : _ _ must be positive .
> > > dropEvery 3 [ 1 .. 10 ]
[ 1 , 2 , 4 , 5 , 7 , 8 , 10 ]
> > > dropEvery 1 [ 1 .. 10 ]
[ ]
__Precondition:__ @n@ must be positive.
>>> dropEvery 3 [1..10]
[1, 2, 4, 5, 7, 8, 10]
>>> dropEvery 1 [1..10]
[]
-}
dropEvery :: Int -> [a] -> [a]
dropEvery step xs = compute validated
where
compute ys = case splitAt (step - 1) ys of
(as, []) -> as
(as, _:bs) -> as ++ compute bs
validated
| step > 0 = xs
| otherwise = error $ "Data.List.Transform.dropEvery: Step parameter "
++ "must be positive."
| Take a list until a predicate is satisfied , and include the element
satisfying the predicate .
> > > takeUntil (= = 5 ) [ 1 .. ]
[ 1 , 2 , 3 , 4 , 5 ]
> > > takeUntil (= = 7 ) [ 3 , 2 , 1 ]
[ 3 , 2 , 1 ]
> > > takeUntil undefined [ ]
[ ]
Note that @takeUntil@ on a nonempty list must always yield the first
element , and the implementation is lazy enough to take advantage of this
fact .
> > > head ( takeUntil undefined [ 1 .. ] )
1
satisfying the predicate.
>>> takeUntil (== 5) [1..]
[1, 2, 3, 4, 5]
>>> takeUntil (== 7) [3, 2, 1]
[3, 2, 1]
>>> takeUntil undefined []
[]
Note that @takeUntil@ on a nonempty list must always yield the first
element, and the implementation is lazy enough to take advantage of this
fact.
>>> head (takeUntil undefined [1..])
1
-}
takeUntil :: (a -> Bool) -> [a] -> [a]
takeUntil _ [] = []
takeUntil _ [x] = [x]
takeUntil f (x:xs) = x : (if f x then [] else takeUntil f xs)
| Drop a list until a predicate is satisfied , and do n't include the element
satisfying the predicate .
> > > dropUntil (= = 5 ) [ 1 .. 10 ]
[ 6 , 7 , 8 , 9 , 10 ]
> > > dropUntil ( < 0 ) [ 1 , 2 , 3 ]
[ ]
> > > dropUntil undefined [ ]
[ ]
Note that @dropUntil@ on a nonempty list must always drop the first
element , and the implementation is lazy enough to take advantage of this
fact .
> > > dropUntil undefined [ undefined ]
[ ]
satisfying the predicate.
>>> dropUntil (== 5) [1..10]
[6, 7, 8, 9, 10]
>>> dropUntil (< 0) [1, 2, 3]
[]
>>> dropUntil undefined []
[]
Note that @dropUntil@ on a nonempty list must always drop the first
element, and the implementation is lazy enough to take advantage of this
fact.
>>> dropUntil undefined [undefined]
[]
-}
dropUntil :: (a -> Bool) -> [a] -> [a]
dropUntil _ [] = []
dropUntil _ [_] = []
dropUntil f (x:xs) = if f x then xs else dropUntil f xs
|
|
c45cf867cf52be580fbc6abd77a42f4bc4feaaa3af743f83d76f4db0e2e49d88 | Mathieu-Desrochers/Schemings | jansson.scm | (declare (unit jansson))
(foreign-declare "
#include <jansson.h>
")
;; jansson types definition
(define-foreign-type json-t "json_t")
(define-foreign-type json-t* (c-pointer json-t))
(define-foreign-type json-error-t "json_error_t")
(define-foreign-type json-error-t* (c-pointer json-error-t))
;; returns a new jansson object
(define json-object (foreign-lambda json-t* "json_object"))
;; returns a new jansson array
(define json-array (foreign-lambda json-t* "json_array"))
;; returns a new jansson value
(define json-boolean (foreign-lambda json-t* "json_boolean" int))
(define json-integer (foreign-lambda json-t* "json_integer" int))
(define json-real (foreign-lambda json-t* "json_real" double))
(define json-string (foreign-lambda json-t* "json_string" c-string))
(define json-null (foreign-lambda json-t* "json_null"))
;; sets the value of key to value in object
(define json-object-set-new (foreign-lambda int "json_object_set_new" json-t* c-string json-t*))
;; appends a value to the end of array
(define json-array-append-new (foreign-lambda int "json_array_append_new" json-t* json-t*))
;; returns the jansson representation as a string
(define json-indent (foreign-value "JSON_INDENT(2)" int))
(define json-preserve-order (foreign-value "JSON_PRESERVE_ORDER" int))
(define json-dumps (foreign-lambda c-string* "json_dumps" json-t* int))
;; decodes the jansson string input
(define json-reject-duplicates (foreign-value "JSON_REJECT_DUPLICATES" int))
(define json-loads (foreign-lambda json-t* "json_loads" c-string unsigned-integer json-error-t*))
;; returns the type of the jansson value
(define json-type-object (foreign-value "JSON_OBJECT" int))
(define json-type-array (foreign-value "JSON_ARRAY" int))
(define json-type-string (foreign-value "JSON_STRING" int))
(define json-type-integer (foreign-value "JSON_INTEGER" int))
(define json-type-real (foreign-value "JSON_REAL" int))
(define json-type-true (foreign-value "JSON_TRUE" int))
(define json-type-false (foreign-value "JSON_FALSE" int))
(define json-type-null (foreign-value "JSON_NULL" int))
(define json-typeof (foreign-lambda int "json_typeof" json-t*))
;; returns the associated value
(define json-integer-value (foreign-lambda int "json_integer_value" json-t*))
(define json-real-value (foreign-lambda double "json_real_value" json-t*))
(define json-string-value (foreign-lambda c-string "json_string_value" json-t*))
;; gets a value corresponding to key from object
(define json-object-get (foreign-lambda json-t* "json_object_get" json-t* c-string))
;; returns the number of elements in array
(define json-array-size (foreign-lambda int "json_array_size" json-t*))
;; returns the element in array at position index
(define json-array-get (foreign-lambda json-t* "json_array_get" json-t* int))
;; decrements the reference count
(define json-decref (foreign-lambda void "json_decref" json-t*))
| null | https://raw.githubusercontent.com/Mathieu-Desrochers/Schemings/3df7c8f8589a1c9c4135a3ae4c1bab3244e6444c/sources/foreign-interfaces/jansson.scm | scheme | jansson types definition
returns a new jansson object
returns a new jansson array
returns a new jansson value
sets the value of key to value in object
appends a value to the end of array
returns the jansson representation as a string
decodes the jansson string input
returns the type of the jansson value
returns the associated value
gets a value corresponding to key from object
returns the number of elements in array
returns the element in array at position index
decrements the reference count | (declare (unit jansson))
(foreign-declare "
#include <jansson.h>
")
(define-foreign-type json-t "json_t")
(define-foreign-type json-t* (c-pointer json-t))
(define-foreign-type json-error-t "json_error_t")
(define-foreign-type json-error-t* (c-pointer json-error-t))
(define json-object (foreign-lambda json-t* "json_object"))
(define json-array (foreign-lambda json-t* "json_array"))
(define json-boolean (foreign-lambda json-t* "json_boolean" int))
(define json-integer (foreign-lambda json-t* "json_integer" int))
(define json-real (foreign-lambda json-t* "json_real" double))
(define json-string (foreign-lambda json-t* "json_string" c-string))
(define json-null (foreign-lambda json-t* "json_null"))
(define json-object-set-new (foreign-lambda int "json_object_set_new" json-t* c-string json-t*))
(define json-array-append-new (foreign-lambda int "json_array_append_new" json-t* json-t*))
(define json-indent (foreign-value "JSON_INDENT(2)" int))
(define json-preserve-order (foreign-value "JSON_PRESERVE_ORDER" int))
(define json-dumps (foreign-lambda c-string* "json_dumps" json-t* int))
(define json-reject-duplicates (foreign-value "JSON_REJECT_DUPLICATES" int))
(define json-loads (foreign-lambda json-t* "json_loads" c-string unsigned-integer json-error-t*))
(define json-type-object (foreign-value "JSON_OBJECT" int))
(define json-type-array (foreign-value "JSON_ARRAY" int))
(define json-type-string (foreign-value "JSON_STRING" int))
(define json-type-integer (foreign-value "JSON_INTEGER" int))
(define json-type-real (foreign-value "JSON_REAL" int))
(define json-type-true (foreign-value "JSON_TRUE" int))
(define json-type-false (foreign-value "JSON_FALSE" int))
(define json-type-null (foreign-value "JSON_NULL" int))
(define json-typeof (foreign-lambda int "json_typeof" json-t*))
(define json-integer-value (foreign-lambda int "json_integer_value" json-t*))
(define json-real-value (foreign-lambda double "json_real_value" json-t*))
(define json-string-value (foreign-lambda c-string "json_string_value" json-t*))
(define json-object-get (foreign-lambda json-t* "json_object_get" json-t* c-string))
(define json-array-size (foreign-lambda int "json_array_size" json-t*))
(define json-array-get (foreign-lambda json-t* "json_array_get" json-t* int))
(define json-decref (foreign-lambda void "json_decref" json-t*))
|
ca3fe47d9d570b2b14b9ddc24cf9b3778aeddb78c186c06a3cb49df6f26e5e30 | aiya000/haskell-examples | Main.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE OverloadedLabels #
# LANGUAGE TypeApplications #
import Data.Extensible (Associate, WriterEff, Eff, tellEff, leaveEff, runWriterEff)
context :: ( Associate "greet" (WriterEff [String]) xs
, Associate "message" (WriterEff [String]) xs
) => Eff xs ()
context = do
tellEff #greet ["hi"]
tellEff #message ["extensible, OverloadedLabels, and TypeApplications is great"]
tellEff #greet ["thanks !"]
main :: IO ()
main = print
. leaveEff
. runWriterEff @ "message"
. runWriterEff @ "greet"
$ context
| null | https://raw.githubusercontent.com/aiya000/haskell-examples/a337ba0e86be8bb1333e7eea852ba5fa1d177d8a/Data/Extensible/Effect/Main.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE OverloadedLabels #
# LANGUAGE TypeApplications #
import Data.Extensible (Associate, WriterEff, Eff, tellEff, leaveEff, runWriterEff)
context :: ( Associate "greet" (WriterEff [String]) xs
, Associate "message" (WriterEff [String]) xs
) => Eff xs ()
context = do
tellEff #greet ["hi"]
tellEff #message ["extensible, OverloadedLabels, and TypeApplications is great"]
tellEff #greet ["thanks !"]
main :: IO ()
main = print
. leaveEff
. runWriterEff @ "message"
. runWriterEff @ "greet"
$ context
|
|
dd3b217eeaf6129755c990267fbc1de707c62260584cabdeadff69c5fdfd2d4d | danr/hipspec | PropT20.hs | module PropT20 where
import Prelude(Bool(..))
import Zeno
-- Definitions
True && x = x
_ && _ = False
False || x = x
_ || _ = True
not True = False
not False = True
-- Nats
data Nat = S Nat | Z
(+) :: Nat -> Nat -> Nat
Z + y = y
(S x) + y = S (x + y)
(*) :: Nat -> Nat -> Nat
Z * _ = Z
(S x) * y = y + (x * y)
(==),(/=) :: Nat -> Nat -> Bool
Z == Z = True
Z == _ = False
S _ == Z = False
S x == S y = x == y
x /= y = not (x == y)
(<=) :: Nat -> Nat -> Bool
Z <= _ = True
_ <= Z = False
S x <= S y = x <= y
one, zero :: Nat
zero = Z
one = S Z
double :: Nat -> Nat
double Z = Z
double (S x) = S (S (double x))
even :: Nat -> Bool
even Z = True
even (S Z) = False
even (S (S x)) = even x
half :: Nat -> Nat
half Z = Z
half (S Z) = Z
half (S (S x)) = S (half x)
mult :: Nat -> Nat -> Nat -> Nat
mult Z _ acc = acc
mult (S x) y acc = mult x y (y + acc)
fac :: Nat -> Nat
fac Z = S Z
fac (S x) = S x * fac x
qfac :: Nat -> Nat -> Nat
qfac Z acc = acc
qfac (S x) acc = qfac x (S x * acc)
exp :: Nat -> Nat -> Nat
exp _ Z = S Z
exp x (S n) = x * exp x n
qexp :: Nat -> Nat -> Nat -> Nat
qexp x Z acc = acc
qexp x (S n) acc = qexp x n (x * acc)
-- Lists
length :: [a] -> Nat
length [] = Z
length (_:xs) = S (length xs)
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
drop :: Nat -> [a] -> [a]
drop Z xs = xs
drop _ [] = []
drop (S x) (_:xs) = drop x xs
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = rev xs ++ [x]
qrev :: [a] -> [a] -> [a]
qrev [] acc = acc
qrev (x:xs) acc = qrev xs (x:acc)
revflat :: [[a]] -> [a]
revflat [] = []
revflat ([]:xss) = revflat xss
revflat ((x:xs):xss) = revflat (xs:xss) ++ [x]
qrevflat :: [[a]] -> [a] -> [a]
qrevflat [] acc = acc
qrevflat ([]:xss) acc = qrevflat xss acc
qrevflat ((x:xs):xss) acc = qrevflat (xs:xss) (x:acc)
rotate :: Nat -> [a] -> [a]
rotate Z xs = xs
rotate _ [] = []
rotate (S n) (x:xs) = rotate n (xs ++ [x])
elem :: Nat -> [Nat] -> Bool
elem _ [] = False
elem n (x:xs) = n == x || elem n xs
subset :: [Nat] -> [Nat] -> Bool
subset [] ys = True
subset (x:xs) ys = x `elem` xs && subset xs ys
intersect,union :: [Nat] -> [Nat] -> [Nat]
(x:xs) `intersect` ys | x `elem` ys = x:(xs `intersect` ys)
| otherwise = xs `intersect` ys
[] `intersect` ys = []
union (x:xs) ys | x `elem` ys = union xs ys
| otherwise = x:(union xs ys)
union [] ys = ys
isort :: [Nat] -> [Nat]
isort [] = []
isort (x:xs) = insert x (isort xs)
insert :: Nat -> [Nat] -> [Nat]
insert n [] = [n]
insert n (x:xs) =
case n <= x of
True -> n : x : xs
False -> x : (insert n xs)
count :: Nat -> [Nat] -> Nat
count n (x:xs) | n == x = S (count n xs)
| otherwise = count n xs
count n [] = Z
sorted :: [Nat] -> Bool
sorted (x:y:xs) = x <= y && sorted (y:xs)
sorted _ = True
-- Theorem
prop_T20 :: [a] -> Prop
prop_T20 x = proveBool (even (length (x ++ x)))
| null | https://raw.githubusercontent.com/danr/hipspec/a114db84abd5fee8ce0b026abc5380da11147aa9/testsuite/prod/zeno_version/PropT20.hs | haskell | Definitions
Nats
Lists
Theorem | module PropT20 where
import Prelude(Bool(..))
import Zeno
True && x = x
_ && _ = False
False || x = x
_ || _ = True
not True = False
not False = True
data Nat = S Nat | Z
(+) :: Nat -> Nat -> Nat
Z + y = y
(S x) + y = S (x + y)
(*) :: Nat -> Nat -> Nat
Z * _ = Z
(S x) * y = y + (x * y)
(==),(/=) :: Nat -> Nat -> Bool
Z == Z = True
Z == _ = False
S _ == Z = False
S x == S y = x == y
x /= y = not (x == y)
(<=) :: Nat -> Nat -> Bool
Z <= _ = True
_ <= Z = False
S x <= S y = x <= y
one, zero :: Nat
zero = Z
one = S Z
double :: Nat -> Nat
double Z = Z
double (S x) = S (S (double x))
even :: Nat -> Bool
even Z = True
even (S Z) = False
even (S (S x)) = even x
half :: Nat -> Nat
half Z = Z
half (S Z) = Z
half (S (S x)) = S (half x)
mult :: Nat -> Nat -> Nat -> Nat
mult Z _ acc = acc
mult (S x) y acc = mult x y (y + acc)
fac :: Nat -> Nat
fac Z = S Z
fac (S x) = S x * fac x
qfac :: Nat -> Nat -> Nat
qfac Z acc = acc
qfac (S x) acc = qfac x (S x * acc)
exp :: Nat -> Nat -> Nat
exp _ Z = S Z
exp x (S n) = x * exp x n
qexp :: Nat -> Nat -> Nat -> Nat
qexp x Z acc = acc
qexp x (S n) acc = qexp x n (x * acc)
length :: [a] -> Nat
length [] = Z
length (_:xs) = S (length xs)
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
drop :: Nat -> [a] -> [a]
drop Z xs = xs
drop _ [] = []
drop (S x) (_:xs) = drop x xs
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = rev xs ++ [x]
qrev :: [a] -> [a] -> [a]
qrev [] acc = acc
qrev (x:xs) acc = qrev xs (x:acc)
revflat :: [[a]] -> [a]
revflat [] = []
revflat ([]:xss) = revflat xss
revflat ((x:xs):xss) = revflat (xs:xss) ++ [x]
qrevflat :: [[a]] -> [a] -> [a]
qrevflat [] acc = acc
qrevflat ([]:xss) acc = qrevflat xss acc
qrevflat ((x:xs):xss) acc = qrevflat (xs:xss) (x:acc)
rotate :: Nat -> [a] -> [a]
rotate Z xs = xs
rotate _ [] = []
rotate (S n) (x:xs) = rotate n (xs ++ [x])
elem :: Nat -> [Nat] -> Bool
elem _ [] = False
elem n (x:xs) = n == x || elem n xs
subset :: [Nat] -> [Nat] -> Bool
subset [] ys = True
subset (x:xs) ys = x `elem` xs && subset xs ys
intersect,union :: [Nat] -> [Nat] -> [Nat]
(x:xs) `intersect` ys | x `elem` ys = x:(xs `intersect` ys)
| otherwise = xs `intersect` ys
[] `intersect` ys = []
union (x:xs) ys | x `elem` ys = union xs ys
| otherwise = x:(union xs ys)
union [] ys = ys
isort :: [Nat] -> [Nat]
isort [] = []
isort (x:xs) = insert x (isort xs)
insert :: Nat -> [Nat] -> [Nat]
insert n [] = [n]
insert n (x:xs) =
case n <= x of
True -> n : x : xs
False -> x : (insert n xs)
count :: Nat -> [Nat] -> Nat
count n (x:xs) | n == x = S (count n xs)
| otherwise = count n xs
count n [] = Z
sorted :: [Nat] -> Bool
sorted (x:y:xs) = x <= y && sorted (y:xs)
sorted _ = True
prop_T20 :: [a] -> Prop
prop_T20 x = proveBool (even (length (x ++ x)))
|
a91de598d9ccb4eaa8440e4b7a2b37e547663662e88e8539829f81fd99442d20 | nmattia/niv | Cmd.hs | {-# LANGUAGE RankNTypes #-}
module Niv.Cmd where
import qualified Data.Aeson as Aeson
import qualified Data.Text as T
import Niv.Sources
import Niv.Update
import qualified Options.Applicative as Opts
-- TODO: add filter
data Cmd = Cmd
{ description :: forall a. Opts.InfoMod a,
parseCmdShortcut :: T.Text -> Maybe (PackageName, Aeson.Object),
parsePackageSpec :: Opts.Parser PackageSpec,
updateCmd :: Update () (),
name :: T.Text,
-- | Some notes to print
extraLogs :: Attrs -> [T.Text]
}
| null | https://raw.githubusercontent.com/nmattia/niv/94080ae8286024820c570a2a24ed7c36d7ad04a9/src/Niv/Cmd.hs | haskell | # LANGUAGE RankNTypes #
TODO: add filter
| Some notes to print |
module Niv.Cmd where
import qualified Data.Aeson as Aeson
import qualified Data.Text as T
import Niv.Sources
import Niv.Update
import qualified Options.Applicative as Opts
data Cmd = Cmd
{ description :: forall a. Opts.InfoMod a,
parseCmdShortcut :: T.Text -> Maybe (PackageName, Aeson.Object),
parsePackageSpec :: Opts.Parser PackageSpec,
updateCmd :: Update () (),
name :: T.Text,
extraLogs :: Attrs -> [T.Text]
}
|
78f30b6019d2c98fc17c828f1586613a804ee070ece0d954959579d534d850f0 | monadbobo/ocaml-core | crit_bit.mli | open Core.Std
type 'data t
val empty : 'data t
val find : 'data t -> string -> 'data option
val add : 'data t -> key:string -> data:'data -> 'data t
val remove : 'data t -> string -> 'data t
val iter : 'data t -> f:(key:string -> data:'data -> unit) -> unit
val map : 'data t -> f:('data -> 'b) -> 'b t
val fold : 'data t -> init:'b -> f:(key:string -> data:'data -> 'b -> 'b) -> 'b
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/extended/lib/crit_bit.mli | ocaml | open Core.Std
type 'data t
val empty : 'data t
val find : 'data t -> string -> 'data option
val add : 'data t -> key:string -> data:'data -> 'data t
val remove : 'data t -> string -> 'data t
val iter : 'data t -> f:(key:string -> data:'data -> unit) -> unit
val map : 'data t -> f:('data -> 'b) -> 'b t
val fold : 'data t -> init:'b -> f:(key:string -> data:'data -> 'b -> 'b) -> 'b
|
|
c6abf54deb5efaca46053d1a51588b886d69f82b426af0892e22362199cfbb97 | scalaris-team/scalaris | unittest_helper.erl | 2008 - 2018 Zuse Institute Berlin
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.
@author < >
%% @doc Helper functions for Unit tests
%% @end
%% @version $Id$
-module(unittest_helper).
-author('').
-vsn('$Id$').
%%-define(TRACE_RING_DATA(), print_ring_data()).
-define(TRACE_RING_DATA(), ok).
-export([get_scalaris_port/0, get_yaws_port/0,
make_ring_with_ids/1, make_ring_with_ids/2, make_ring/1, make_ring/2, make_ring_recover/1,
make_symmetric_ring/0, make_symmetric_ring/1,
stop_ring/0, stop_ring/1,
stop_pid_groups/0,
check_ring_size/1, check_ring_size_fully_joined/1,
wait_for_stable_ring/0, wait_for_stable_ring_deep/0,
start_process/1, start_process/2,
start_subprocess/1, start_subprocess/2,
get_processes/0, kill_new_processes/1, kill_new_processes/2,
create_ct_all/1, create_ct_groups/2,
init_per_group/2, end_per_group/2,
get_ring_data/1, print_ring_data/0,
print_proto_sched_stats/1, print_proto_sched_stats/2,
macro_equals/5, macro_compare/7,
macro_equals_failed/6,
expect_no_message_timeout/1,
prepare_config/1,
start_minimal_procs/3, stop_minimal_procs/1,
check_ring_load/1, check_ring_data/0, check_ring_data/2,
build_interval/2,
db_entry_not_null/1, scrub_data/1]).
-export_type([process_info/0, kv_opts/0, ring_data/1]).
-include("scalaris.hrl").
-include("client_types.hrl").
-include("unittest.hrl").
-dialyzer({no_match, get_processes/0}).
-type kv_opts() :: [{Key::atom(), Value::term()}].
-spec get_port(EnvName::string(), Default::pos_integer()) -> pos_integer().
get_port(EnvName, Default) ->
case os:getenv(EnvName) of
false -> Default;
X ->
try erlang:list_to_integer(X)
catch
_:_ -> Default
end
end.
-spec get_scalaris_port() -> pos_integer().
get_scalaris_port() ->
get_port("SCALARIS_UNITTEST_PORT", 14195).
-spec get_yaws_port() -> pos_integer().
get_yaws_port() ->
get_port("SCALARIS_UNITTEST_YAWS_PORT", 8000).
%% @doc Adds unittest-specific config parameters to the given key-value list.
%% The following parameters are added7changed:
%% - SCALARIS_UNITTEST_PORT environment variable to specify the port to
%% listen on
%% - SCALARIS_UNITTEST_YAWS_PORT environment variable to specify the port
%% yaws listens on
- adds only a single known_hosts node
%% - specifies the node to be empty
-spec add_my_config(ConfigKVList::[{atom(), term()}])
-> NewKVList::[{atom(), term()}].
add_my_config(KVList) ->
% add empty_node to the end (so it is not overwritten)
but add known_hosts to the beginning so it
% can be overwritten by the Options
ScalarisPort = get_scalaris_port(),
YawsPort = get_yaws_port(),
KVList1 = [{known_hosts, [{{127,0,0,1}, ScalarisPort, service_per_vm}]},
{mgmt_server, {{127,0,0,1}, ScalarisPort, mgmt_server}},
{port, ScalarisPort},
{yaws_port, YawsPort},
{start_type, first_nostart} | KVList],
lists:append(KVList1, [{start_mgmt_server, true}]).
%% @doc Adds unittest specific ports from the environment to the list of
%% options for the config process.
-spec prepare_config(Options::[{atom(), term()}]) -> NewOptions::[{atom(), term()}].
prepare_config(Options) ->
prepare_config_helper(Options, false).
-spec prepare_config_helper(Options, ConfigFound::boolean()) -> Options when is_subtype(Options, [{atom(), term()}]).
prepare_config_helper([], false) ->
[{config, add_my_config([])}];
prepare_config_helper([], true) ->
[];
prepare_config_helper([Option | Rest], OldConfigFound) ->
{NewOption, ConfigFound} =
case Option of
{config, KVList} -> {{config, add_my_config(KVList)}, true};
X -> {X, OldConfigFound}
end,
[NewOption | prepare_config_helper(Rest, ConfigFound)].
%% @doc Creates a symmetric ring.
-spec make_symmetric_ring() -> pid().
make_symmetric_ring() ->
make_symmetric_ring([]).
%% @doc Creates a symmetric ring.
-spec make_symmetric_ring(Options::kv_opts()) -> pid().
make_symmetric_ring(Options) ->
ct:pal("Trying to make a symmetric ring"),
NodeAddFun =
fun() ->
Ids = case lists:keyfind(scale_ring_size_by, 1, Options) of
{scale_ring_size_by, Scale} ->
api_rt:get_evenly_spaced_keys(
Scale * config:read(replication_factor));
false ->
api_rt:get_evenly_spaced_keys(
config:read(replication_factor))
end,
[admin:add_node([{first}, {{dht_node, id}, hd(Ids)}])
| [admin:add_node_at_id(Id) || Id <- tl(Ids)]]
end,
Pid = make_ring_generic(Options, NodeAddFun),
Size = case lists:keyfind(scale_ring_size_by, 1, Options) of
{scale_ring_size_by, Scale} ->
Scale * config:read(replication_factor);
false ->
config:read(replication_factor)
end,
check_ring_size(Size),
wait_for_stable_ring(),
check_ring_size(Size),
ct:pal("Scalaris booted with ~p node(s)...~n", [Size]),
TimeTrap = test_server:timetrap(3000 + Size * 1000),
test_server:timetrap_cancel(TimeTrap),
Pid.
%% @doc Creates a ring with the given IDs (or IDs returned by the IdFun).
-spec make_ring_with_ids([?RT:key()]) -> pid().
make_ring_with_ids(Ids) ->
make_ring_with_ids(Ids, []).
%% @doc Creates a ring with the given IDs (or IDs returned by the IdFun).
%% Passes Options to the supervisor, e.g. to set config variables, specify
%% a {config, [{Key, Value},...]} option.
-spec make_ring_with_ids([?RT:key(),...], Options::kv_opts()) -> pid().
make_ring_with_ids(Ids, Options) when is_list(Ids) ->
ct:pal("Trying to make ring with Ids, containing ~p nodes.",[erlang:length(Ids)]),
NodeAddFun =
fun() ->
[admin:add_node([{first}, {{dht_node, id}, hd(Ids)}])
| [admin:add_node_at_id(Id) || Id <- tl(Ids)]]
end,
Size = erlang:length(Ids),
TimeTrap = test_server:timetrap(3000 + Size * 1000),
Pid = make_ring_generic(Options, NodeAddFun),
check_ring_size(Size),
wait_for_stable_ring(),
check_ring_size(Size),
ct:pal("Scalaris booted with ~p node(s)...~n", [Size]),
test_server:timetrap_cancel(TimeTrap),
Pid.
-spec make_ring_recover(Options::kv_opts()) -> pid().
make_ring_recover(Options) ->
ct:pal("Trying to recover ring."),
TimeTrap = test_server:timetrap(60000),
Pid = make_ring_generic(Options, fun() -> [] end),
ct:pal("ring restored"),
test_server:timetrap_cancel(TimeTrap),
Pid.
%% @doc Creates a ring with Size random IDs.
-spec make_ring(Size::pos_integer()) -> pid().
make_ring(Size) ->
make_ring(Size, []).
@doc Creates a ring with Size rangom IDs .
%% Passes Options to the supervisor, e.g. to set config variables, specify
%% a {config, [{Key, Value},...]} option.
-spec make_ring(Size::pos_integer(), Options::kv_opts()) -> pid().
make_ring(Size, Options) ->
ct:pal("Trying to make ring with ~p nodes.",[Size]),
NodeAddFun =
fun() ->
First = admin:add_node([{first}]),
{RestSuc, RestFailed} = admin:add_nodes(Size - 1),
[First | RestSuc ++ RestFailed]
end,
TimeTrap = test_server:timetrap(3000 + Size * 1000),
Pid = make_ring_generic(Options, NodeAddFun),
check_ring_size(Size),
wait_for_stable_ring(),
check_ring_size(Size),
ct:pal("Scalaris booted with ~p node(s)...~n", [Size]),
test_server:timetrap_cancel(TimeTrap),
Pid.
-spec make_ring_generic(Options::kv_opts(),
NodeAddFun::fun(() -> [pid_groups:groupname() | {error, term()}]))
-> pid().
make_ring_generic(Options, NodeAddFun) ->
case ets:info(config_ets) of
undefined -> ok;
_ -> ct:fail("Trying to create a new ring although there is already one.")
end,
{Pid, StartRes} =
start_process(
fun() ->
erlang:register(ct_test_ring, self()),
randoms:start(),
{ok, _GroupsPid} = pid_groups:start_link(),
NewOptions = prepare_config(Options),
config:init(NewOptions),
tester:start_pseudo_proc(),
{ok, _} = sup_scalaris:start_link(NewOptions),
NodeAddFun()
end),
FailedNodes = [X || X = {error, _ } <- StartRes],
case FailedNodes of
[] -> ok;
[_|_] -> stop_ring(Pid),
?ct_fail("adding nodes failed: ~.0p", [FailedNodes])
end,
true = erlang:is_process_alive(Pid),
timer : sleep(1000 ) ,
% need to call IdsFun again (may require config process or others
% -> can not call it before starting the scalaris process)
?TRACE_RING_DATA(),
Pid.
@doc Stops a ring previously started with make_ring/1 or .
-spec stop_ring() -> ok.
stop_ring() ->
case erlang:whereis(ct_test_ring) of
undefined -> ok;
Pid -> stop_ring(Pid)
end.
@doc Stops a ring previously started with make_ring/1 or
%% when the process' pid is known.
-spec stop_ring(pid()) -> ok.
stop_ring(Pid) ->
LogLevel = config:read(log_level),
try
begin
ct:pal("unittest_helper:stop_ring start."),
log:set_log_level(none),
sup:sup_terminate(main_sup),
catch exit(Pid, kill),
util:wait_for_process_to_die(Pid),
stop_pid_groups(),
sup_scalaris:stop_first_services(),
log:set_log_level(LogLevel),
ct:pal("unittest_helper:stop_ring done."),
ok
end
catch
?CATCH_CLAUSE_WITH_STACKTRACE(Level, Reason, Stacktrace)
ct:pal("~s in stop_ring: ~p~n~.0p", [Level, Reason, Stacktrace]),
erlang:Level(Reason)
after
catch(unregister(ct_test_ring)),
log:set_log_level(LogLevel)
end.
-spec stop_pid_groups() -> ok.
stop_pid_groups() ->
case whereis(pid_groups) of
PidGroups when is_pid(PidGroups) ->
gen_component:kill(PidGroups),
util:wait_for_ets_table_to_disappear(PidGroups, pid_groups),
util:wait_for_ets_table_to_disappear(PidGroups, pid_groups_hidden),
catch unregister(pid_groups),
ok;
_ -> ok
end.
-spec wait_for_stable_ring() -> ok.
wait_for_stable_ring() ->
util:wait_for(fun() ->
R = admin:check_ring(),
%% ct:pal("CheckRing: ~p~n", [R]),
R =:= ok
end, 100).
-spec wait_for_stable_ring_deep() -> ok.
wait_for_stable_ring_deep() ->
util:wait_for(fun() ->
R = admin:check_ring_deep(),
ct:pal("CheckRingDeep: ~p~n", [R]),
R =:= ok
end, 100).
-spec check_ring_size(non_neg_integer(), CheckFun::fun((DhtNodeState::term()) -> boolean())) -> ok.
check_ring_size(Size, CheckFun) ->
util:wait_for(
fun() ->
% note: we use a single VM in unit tests, therefore no
% mgmt_server is needed - if one exists though, then check
% the correct size
BootSize =
try
mgmt_server:number_of_nodes(),
trace_mpath:thread_yield(),
receive ?SCALARIS_RECV({get_list_length_response, L}, L) end
catch _:_ -> Size
end,
BootSize =:= Size andalso
Size =:= erlang:length(
[P || P <- pid_groups:find_all(dht_node),
CheckFun(gen_component:get_state(P))])
end, 50).
-spec check_ring_size(Size::non_neg_integer()) -> ok.
check_ring_size(Size) ->
check_ring_size(Size, fun(State) ->
DhtModule = config:read(dht_node),
DhtModule:is_alive(State)
end).
@doc Checks whether nodes have fully joined the ring ( including
%% finished join-related slides).
-spec check_ring_size_fully_joined(Size::non_neg_integer()) -> ok.
check_ring_size_fully_joined(Size) ->
check_ring_size(Size, fun(State) ->
DhtModule = config:read(dht_node),
DhtModule:is_alive_no_slide(State)
end).
%% @doc Starts a process which executes the given function and then waits forever.
-spec start_process(StartFun::fun(() -> StartRes)) -> {pid(), StartRes}.
start_process(StartFun) ->
start_process(StartFun, fun() -> receive {done} -> ok end end).
-spec start_process(StartFun::fun(() -> StartRes), RunFun::fun(() -> any())) -> {pid(), StartRes}.
start_process(StartFun, RunFun) ->
start_process(StartFun, RunFun, false, spawn).
-spec start_process(StartFun::fun(() -> StartRes), RunFun::fun(() -> any()),
TrapExit::boolean(), Spawn::spawn | spawn_link)
-> {pid(), StartRes}.
start_process(StartFun, RunFun, TrapExit, Spawn) ->
process_flag(trap_exit, TrapExit),
Owner = self(),
Node = erlang:Spawn(
fun() ->
try Res = StartFun(),
Owner ! {started, self(), Res}
catch Level:Reason ->
Owner ! {killed},
erlang:Level(Reason)
end,
RunFun()
end),
receive
{started, Node, Res} -> {Node, Res};
{killed} -> ?ct_fail("start_process(~.0p, ~.0p, ~.0p, ~.0p) failed",
[StartFun, RunFun, TrapExit, Spawn])
end.
%% @doc Starts a sub-process which executes the given function and then waits forever.
-spec start_subprocess(StartFun::fun(() -> StartRes)) -> {pid(), StartRes}.
start_subprocess(StartFun) ->
start_subprocess(StartFun, fun() -> receive {done} -> ok end end).
-spec start_subprocess(StartFun::fun(() -> StartRes), RunFun::fun(() -> any())) -> {pid(), StartRes}.
start_subprocess(StartFun, RunFun) ->
start_process(StartFun, RunFun, true, spawn_link).
%% @doc Starts the minimal number of processes in order for non-ring unit tests
%% to be able to execute (pid_groups, config, log).
-spec start_minimal_procs(CTConfig, ConfigOptions::[{atom(), term()}],
StartCommServer::boolean()) -> CTConfig when is_subtype(CTConfig, list()).
start_minimal_procs(CTConfig, ConfigOptions, StartCommServer) ->
{Pid, _} =
start_process(
fun() ->
{ok, _GroupsPid} = pid_groups:start_link(),
{priv_dir, PrivDir} = lists:keyfind(priv_dir, 1, CTConfig),
ConfigOptions2 = prepare_config(
[{config, [{log_path, PrivDir} | ConfigOptions]}]),
config:init(ConfigOptions2),
tester:start_pseudo_proc(),
case StartCommServer of
true ->
{ok, _CommPid} = sup:sup_start(
{local, no_name},
sup_comm_layer, []),
Port = get_scalaris_port(),
comm_server:set_local_address({127,0,0,1}, Port);
false -> ok
end
end),
[{wrapper_pid, Pid} | CTConfig].
%% @doc Stops the processes started by start_minimal_procs/3 given the
%% ct config term.
-spec stop_minimal_procs(CTConfig) -> CTConfig when is_subtype(CTConfig, list()).
stop_minimal_procs(CTConfig) ->
case lists:keytake(wrapper_pid, 1, CTConfig) of
{value, {wrapper_pid, Pid}, CTConfig1} ->
LogLevel = config:read(log_level),
log:set_log_level(none),
exit(Pid, kill),
stop_pid_groups(),
log:set_log_level(LogLevel),
CTConfig1;
false -> CTConfig
end.
-type process_info() ::
{pid(), InitCall::mfa(), CurFun::mfa(),
{RegName::atom() | not_registered, Info::term() | failed | no_further_infos}}.
-spec get_processes() -> [process_info()].
get_processes() ->
[begin
InitCall =
case proc_lib:initial_call(X) of
false -> element(2, lists:keyfind(initial_call, 1, Data));
{Module, Function, Args} -> {Module, Function, length(Args)}
end,
CurFun = element(2, lists:keyfind(current_function, 1, Data)),
RegName = case lists:keyfind(registered_name, 1, Data) of
false -> not_registered;
RegNameTpl -> element(2, RegNameTpl)
end,
Info =
case {InitCall, CurFun} of
{{gen_component, _, _}, {gen_component, _, _}} ->
gen_component:get_component_state(X);
{_, {file_io_server, _, _}} ->
case file:pid2name(X) of
undefined -> {file, undefined};
{ok, FileName} -> {file, FileName};
case occuring in older Erlang versions :
FileName -> {file, FileName}
end;
{_, {gen_server, _, _}} ->
% may throw exit due to a killed process
try sys:get_status(X)
catch _:_ -> no_further_infos
end;
_ -> no_further_infos
end,
{X, InitCall, CurFun, {RegName, Info}}
end
|| X <- processes(),
Data <- [process_info(X, [current_function, initial_call, registered_name])],
Data =/= undefined].
-spec kill_new_processes(OldProcesses::[process_info()]) -> ok.
kill_new_processes(OldProcesses) ->
kill_new_processes(OldProcesses, []).
-spec kill_new_processes(OldProcesses::[process_info()], Options::list()) -> ok.
kill_new_processes(OldProcesses, Options) ->
NewProcesses = get_processes(),
{_OnlyOld, _Both, OnlyNew} =
util:split_unique(OldProcesses, NewProcesses,
fun(P1, P2) ->
element(1, P1) =< element(1, P2)
end, fun(_P1, P2) -> P2 end),
%% ct:pal("Proc-Old: ~.0p~n", [_OnlyOld]),
%% ct:pal("Proc-Both: ~.0p~n", [_Both]),
%% ct:pal("Proc-New: ~.0p~n", [OnlyNew]),
Killed = [begin
%% ct:pal("killing ~.0p~n", [Proc]),
Tabs = util:ets_tables_of(X),
try erlang:exit(X, kill) of
true ->
util:wait_for_process_to_die(X),
_ = [begin
%% ct:pal("waiting for table ~.0p to disappear~n~p",
%% [Tab, ets:info(Tab)]),
util:wait_for_ets_table_to_disappear(X, Tab)
end || Tab <- Tabs ],
{ok, Proc}
catch _:_ -> {fail, Proc}
end
end || {X, InitCall, CurFun, {RegName, _Info}} = Proc <- OnlyNew,
not (InitCall =:= {test_server_sup, timetrap, 3} andalso
CurFun =:= {test_server_sup, timetrap, 3}),
not (InitCall =:= {test_server_sup, timetrap, 2} andalso
CurFun =:= {test_server_sup, timetrap, 2}),
not (InitCall =:= {test_server_gl, init, 1}),
spawned by : put_chars/3
RegName =/= cover_server,
X =/= self(),
X =/= whereis(timer_server),
element(1, CurFun) =/= file_io_server],
case lists:member({?quiet}, Options) of
false ->
ct:pal("Killed processes: ~.0p~n", [Killed]);
true -> ok
end.
-type ct_group_props() ::
[parallel | sequence | shuffle | {shuffle, {integer(), integer(), integer()}} |
{repeat | repeat_until_all_ok | repeat_until_all_fail | repeat_until_any_ok | repeat_until_any_fail, integer() | forever}].
-spec testcase_to_groupname(TestCase::atom()) -> atom().
testcase_to_groupname(TestCase) ->
erlang:list_to_atom(erlang:atom_to_list(TestCase) ++ "_grp").
-spec create_ct_all(TestCases::[atom()]) -> [{group, atom()}].
create_ct_all(TestCases) ->
[{group, testcase_to_groupname(TestCase)} || TestCase <- TestCases].
-spec create_ct_groups(TestCases::[atom()], SpecialOptions::[{atom(), ct_group_props()}])
-> [{atom(), ct_group_props(), [atom()]}].
create_ct_groups(TestCases, SpecialOptions) ->
[begin
Options =
case lists:keyfind(TestCase, 1, SpecialOptions) of
false -> [sequence, {repeat, 1}];
{_, X} -> X
end,
{testcase_to_groupname(TestCase), Options, [TestCase]}
end || TestCase <- TestCases].
-spec init_per_group(atom(), Config) -> Config when is_subtype(Config, kv_opts()).
init_per_group(_Group, Config) -> Config.
-spec end_per_group(atom(), kv_opts()) -> {return_group_result, ok | failed}.
end_per_group(_Group, Config) ->
Status = test_server:lookup_config(tc_group_result, Config),
case proplists:get_value(failed, Status) of
[] -> % no failed cases
{return_group_result, ok};
one or more failed
{return_group_result, failed}
end.
-type ring_data(DBType) ::
[{pid(),
{intervals:left_bracket(), intervals:key(), intervals:key(), intervals:right_bracket()},
DBType,
{pred, comm:erl_local_pid_plain()},
{succ, comm:erl_local_pid_plain()},
ok | timeout}] |
{exception, Level::throw | error | exit, Reason::term(), Stacktrace::term()}.
-spec get_ring_data(full) -> ring_data(db_dht:db_as_list());
(kv) -> ring_data([{?RT:key(), client_version()}]).
get_ring_data(Type) ->
Self = self(),
erlang:spawn(
fun() ->
try
DHTNodes = pid_groups:find_all(dht_node),
Data =
lists:sort(
fun(E1, E2) ->
erlang:element(2, E1) =< erlang:element(2, E2)
end,
[begin
comm:send_local(DhtNode,
{unittest_get_bounds_and_data, comm:this(), Type}),
receive
{unittest_get_bounds_and_data_response, Bounds, Data, Pred, Succ} ->
{DhtNode, Bounds, Data,
{pred, comm:make_local(node:pidX(Pred))},
{succ, comm:make_local(node:pidX(Succ))}, ok}
% we are in a separate process, any message in the
% message box should not influence the calling process
after 750 -> {DhtNode, empty, [], {pred, null}, {succ, null}, timeout}
end
end || DhtNode <- DHTNodes]),
Self ! {data, Data}
catch
?CATCH_CLAUSE_WITH_STACKTRACE(Level, Reason, Stacktrace)
Result =
case erlang:whereis(ct_test_ring) of
undefined -> [];
_ -> {exception, Level, Reason, Stacktrace}
end,
Self ! {data, Result}
end
end),
receive {data, Data} -> Data
end.
-spec print_ring_data() -> ok.
print_ring_data() ->
DataAll = get_ring_data(full),
ct:pal("Scalaris ring data:~n~.0p~n", [DataAll]).
-spec print_proto_sched_stats(now | now_short | at_end_if_failed | at_end_if_failed_append) -> ok.
print_proto_sched_stats(When) ->
% NOTE: keep the default tag in sync!
print_proto_sched_stats(When, default).
-spec print_proto_sched_stats(now | now_short | at_end_if_failed | at_end_if_failed_append,
TraceId::term()) -> ok.
print_proto_sched_stats(now, TraceId) ->
ct:pal("Proto scheduler stats: ~.2p", [proto_sched:get_infos(TraceId)]);
print_proto_sched_stats(now_short, TraceId) ->
ct:pal("Proto scheduler stats: ~.2p",
[proto_sched:info_shorten_messages(proto_sched:get_infos(TraceId), 200)]);
print_proto_sched_stats(at_end_if_failed, TraceId) ->
unittest_global_state:insert(proto_sched_stats, proto_sched:get_infos(TraceId)),
ok;
print_proto_sched_stats(at_end_if_failed_append, TraceId) ->
Current = case unittest_global_state:lookup(proto_sched_stats) of
failed -> [];
X when is_list(X) -> X
end,
unittest_global_state:insert(proto_sched_stats,
Current ++ proto_sched:get_infos(TraceId)),
ok.
-spec macro_equals(Actual::any(), ExpectedVal::any(), ActualStr::string(),
ExpectedStr::string(), Note::term()) -> true | no_return().
macro_equals(Actual, ExpectedVal, ActualStr, ExpectedStr, Note) ->
macro_compare(fun erlang:'=:='/2, Actual, ExpectedVal, "=:=", ActualStr, ExpectedStr, Note).
-spec macro_compare(CompFun::fun((T, T) -> boolean()), Actual::any(), ExpectedVal::any(),
CompFunStr::string(), ActualStr::string(), ExpectedStr::string(),
Note::term()) -> true | no_return().
macro_compare(CompFun, Actual, ExpectedVal, CompFunStr, ActualStr, ExpectedStr, Note) ->
case CompFun(Actual, ExpectedVal) of
true -> true;
false -> macro_equals_failed(Actual, ExpectedVal, CompFunStr, ActualStr, ExpectedStr, Note)
end.
-spec macro_equals_failed(ActualVal::any(), ExpectedVal::any(), CompFunStr::string(),
ActualStr::string(), ExpectedStr::string(), Note::term())
-> no_return().
macro_equals_failed(ActualVal, ExpectedVal, CompFunStr, ActualStr, ExpectedStr, Note) ->
log:log(error, "Failed (in ~.0p)~n"
" Call: ~s~n"
" Returns: ~.0p~n"
" is not (~s)~n"
" Exp. term: ~s~n"
" Exp. return: ~.0p~n"
" Note: ~.0p~n"
" Stacktrace: ~p~n"
" Linetrace: ~p~n",
[self(), ActualStr, ActualVal, CompFunStr, ExpectedStr, ExpectedVal, Note,
util:get_stacktrace(), util:get_linetrace()]),
?ct_fail("~s returned ~.0p which is not ~s the expected ~s that returns ~.0p. Note: ~.0p",
[ActualStr, ActualVal, CompFunStr, ExpectedStr, ExpectedVal, Note]).
-spec expect_no_message_timeout(Timeout::pos_integer()) -> true | no_return().
expect_no_message_timeout(Timeout) ->
receive
ActualMessage ->
?ct_fail("expected no message but got \"~.0p\"~n", [ActualMessage])
after Timeout -> true
end.
-spec check_ring_load(ExpLoad::pos_integer()) -> true | no_return().
check_ring_load(ExpLoad) ->
Ring = statistics:get_ring_details(),
Load = statistics:get_total_load(load, Ring),
?equals(Load, ExpLoad).
-spec check_ring_data() -> boolean().
check_ring_data() ->
check_ring_data(250, 8).
-spec check_ring_data(Timeout::pos_integer(), Retries::non_neg_integer()) -> boolean().
check_ring_data(Timeout, Retries) ->
Data = lists:flatmap(
fun({_Pid, _Interval, Data, {pred, _PredPid}, {succc, _SuccPid}, _Result}) -> Data;
(_) -> []
end,
get_ring_data(full)),
case Retries < 1 of
true ->
check_ring_data_all(Data, true);
_ ->
case check_ring_data_all(Data, false) of
true -> true;
_ -> timer:sleep(Timeout),
check_ring_data(Timeout, Retries - 1)
end
end.
check_ring_data_all(Data, FailOnError) ->
check_ring_data_unique(Data, FailOnError) andalso
check_ring_data_repl_fac(Data, FailOnError) andalso
check_ring_data_lock_free(Data, FailOnError) andalso
check_ring_data_repl_exist(Data, FailOnError).
-spec check_ring_data_unique(Data::[db_entry:entry()], FailOnError::boolean()) -> boolean().
check_ring_data_unique(Data, FailOnError) ->
UniqueData = lists:usort(fun(A, B) ->
db_entry:get_key(A) =< db_entry:get_key(B)
end, Data),
DataDiff = lists:subtract(Data, UniqueData),
case FailOnError of
true ->
?equals_w_note(DataDiff, [], "duplicate elements detected"),
true;
_ when DataDiff =:= [] ->
true;
_ ->
ct:pal("check_ring_data: duplicate elements detected: ~p~n", [DataDiff]),
false
end.
-spec check_ring_data_repl_fac(Data::[db_entry:entry()], FailOnError::boolean()) -> boolean().
check_ring_data_repl_fac(Data, FailOnError) ->
ReplicaKeys0 = ?RT:get_replica_keys(?RT:hash_key("0")),
DataLen = length(Data),
ReplicaLen = length(ReplicaKeys0),
ReplicaRem = DataLen rem ReplicaLen,
case FailOnError of
true ->
?equals(ReplicaRem, 0);
_ when ReplicaRem =:= 0 ->
true;
_ ->
ct:pal("check_ring_data: length(Data) = ~p not multiple of ~p~n", [DataLen, ReplicaLen]),
false
end.
-spec check_ring_data_lock_free(Data::[db_entry:entry()], FailOnError::boolean()) -> boolean().
check_ring_data_lock_free(Data, FailOnError) ->
Locked = [E || E <- Data, db_entry:is_locked(E)],
case FailOnError of
true ->
?equals_w_note(Locked, [], "ring is not lock-free"),
true;
_ when Locked =:= [] ->
true;
_ ->
ct:pal("check_ring_data: locked elements found: ~p~n", [Locked]),
false
end.
-spec check_ring_data_repl_exist(Data::[db_entry:entry()], FailOnError::boolean()) -> boolean().
check_ring_data_repl_exist(Data, FailOnError) ->
ElementsNotAllReplicas =
[E || E <- Data, not data_contains_all_replicas(Data, db_entry:get_key(E))],
case FailOnError of
true ->
?equals_w_note(ElementsNotAllReplicas, [], "missing replicas found"),
true;
_ when ElementsNotAllReplicas =:= [] ->
true;
_ ->
ct:pal("check_ring_data: elements with missing replicas:", [ElementsNotAllReplicas]),
false
end.
data_contains_all_replicas(Data, Key) ->
Keys = ?RT:get_replica_keys(Key),
Replicas = [E || E <- Data, lists:member(db_entry:get_key(E), Keys)],
length(Keys) =:= length(Replicas).
% @doc returns only left-open intervals or intervals:all()
% rrepair relies on this
-spec build_interval(intervals:key(), intervals:key()) -> intervals:interval().
build_interval(?MINUS_INFINITY, ?PLUS_INFINITY) -> intervals:all();
build_interval(?PLUS_INFINITY, ?MINUS_INFINITY) -> intervals:all();
build_interval(A, A) -> intervals:all();
build_interval(A, B) when A < B -> intervals:new('(', A, B, ']');
build_interval(A, B) when A > B -> intervals:new('(', B, A, ']').
@doc can be used to filter empty entries out of a list of db_entries
-spec db_entry_not_null(db_entry:entry()) -> boolean().
db_entry_not_null(Entry) ->
not db_entry:is_null(Entry).
@doc removes duplicates and db_entries that are null
-spec scrub_data(db_dht:db_as_list()) -> db_dht:db_as_list().
scrub_data(Data) ->
lists:filter(
fun db_entry_not_null/1,
lists:usort(fun(A, B) ->
db_entry:get_key(A) =< db_entry:get_key(B)
end, lists:reverse(Data))).
| null | https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/test/unittest_helper.erl | erlang | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@doc Helper functions for Unit tests
@end
@version $Id$
-define(TRACE_RING_DATA(), print_ring_data()).
@doc Adds unittest-specific config parameters to the given key-value list.
The following parameters are added7changed:
- SCALARIS_UNITTEST_PORT environment variable to specify the port to
listen on
- SCALARIS_UNITTEST_YAWS_PORT environment variable to specify the port
yaws listens on
- specifies the node to be empty
add empty_node to the end (so it is not overwritten)
can be overwritten by the Options
@doc Adds unittest specific ports from the environment to the list of
options for the config process.
@doc Creates a symmetric ring.
@doc Creates a symmetric ring.
@doc Creates a ring with the given IDs (or IDs returned by the IdFun).
@doc Creates a ring with the given IDs (or IDs returned by the IdFun).
Passes Options to the supervisor, e.g. to set config variables, specify
a {config, [{Key, Value},...]} option.
@doc Creates a ring with Size random IDs.
Passes Options to the supervisor, e.g. to set config variables, specify
a {config, [{Key, Value},...]} option.
need to call IdsFun again (may require config process or others
-> can not call it before starting the scalaris process)
when the process' pid is known.
ct:pal("CheckRing: ~p~n", [R]),
note: we use a single VM in unit tests, therefore no
mgmt_server is needed - if one exists though, then check
the correct size
finished join-related slides).
@doc Starts a process which executes the given function and then waits forever.
@doc Starts a sub-process which executes the given function and then waits forever.
@doc Starts the minimal number of processes in order for non-ring unit tests
to be able to execute (pid_groups, config, log).
@doc Stops the processes started by start_minimal_procs/3 given the
ct config term.
may throw exit due to a killed process
ct:pal("Proc-Old: ~.0p~n", [_OnlyOld]),
ct:pal("Proc-Both: ~.0p~n", [_Both]),
ct:pal("Proc-New: ~.0p~n", [OnlyNew]),
ct:pal("killing ~.0p~n", [Proc]),
ct:pal("waiting for table ~.0p to disappear~n~p",
[Tab, ets:info(Tab)]),
no failed cases
we are in a separate process, any message in the
message box should not influence the calling process
NOTE: keep the default tag in sync!
@doc returns only left-open intervals or intervals:all()
rrepair relies on this | 2008 - 2018 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
-module(unittest_helper).
-author('').
-vsn('$Id$').
-define(TRACE_RING_DATA(), ok).
-export([get_scalaris_port/0, get_yaws_port/0,
make_ring_with_ids/1, make_ring_with_ids/2, make_ring/1, make_ring/2, make_ring_recover/1,
make_symmetric_ring/0, make_symmetric_ring/1,
stop_ring/0, stop_ring/1,
stop_pid_groups/0,
check_ring_size/1, check_ring_size_fully_joined/1,
wait_for_stable_ring/0, wait_for_stable_ring_deep/0,
start_process/1, start_process/2,
start_subprocess/1, start_subprocess/2,
get_processes/0, kill_new_processes/1, kill_new_processes/2,
create_ct_all/1, create_ct_groups/2,
init_per_group/2, end_per_group/2,
get_ring_data/1, print_ring_data/0,
print_proto_sched_stats/1, print_proto_sched_stats/2,
macro_equals/5, macro_compare/7,
macro_equals_failed/6,
expect_no_message_timeout/1,
prepare_config/1,
start_minimal_procs/3, stop_minimal_procs/1,
check_ring_load/1, check_ring_data/0, check_ring_data/2,
build_interval/2,
db_entry_not_null/1, scrub_data/1]).
-export_type([process_info/0, kv_opts/0, ring_data/1]).
-include("scalaris.hrl").
-include("client_types.hrl").
-include("unittest.hrl").
-dialyzer({no_match, get_processes/0}).
-type kv_opts() :: [{Key::atom(), Value::term()}].
-spec get_port(EnvName::string(), Default::pos_integer()) -> pos_integer().
get_port(EnvName, Default) ->
case os:getenv(EnvName) of
false -> Default;
X ->
try erlang:list_to_integer(X)
catch
_:_ -> Default
end
end.
-spec get_scalaris_port() -> pos_integer().
get_scalaris_port() ->
get_port("SCALARIS_UNITTEST_PORT", 14195).
-spec get_yaws_port() -> pos_integer().
get_yaws_port() ->
get_port("SCALARIS_UNITTEST_YAWS_PORT", 8000).
- adds only a single known_hosts node
-spec add_my_config(ConfigKVList::[{atom(), term()}])
-> NewKVList::[{atom(), term()}].
add_my_config(KVList) ->
but add known_hosts to the beginning so it
ScalarisPort = get_scalaris_port(),
YawsPort = get_yaws_port(),
KVList1 = [{known_hosts, [{{127,0,0,1}, ScalarisPort, service_per_vm}]},
{mgmt_server, {{127,0,0,1}, ScalarisPort, mgmt_server}},
{port, ScalarisPort},
{yaws_port, YawsPort},
{start_type, first_nostart} | KVList],
lists:append(KVList1, [{start_mgmt_server, true}]).
-spec prepare_config(Options::[{atom(), term()}]) -> NewOptions::[{atom(), term()}].
prepare_config(Options) ->
prepare_config_helper(Options, false).
-spec prepare_config_helper(Options, ConfigFound::boolean()) -> Options when is_subtype(Options, [{atom(), term()}]).
prepare_config_helper([], false) ->
[{config, add_my_config([])}];
prepare_config_helper([], true) ->
[];
prepare_config_helper([Option | Rest], OldConfigFound) ->
{NewOption, ConfigFound} =
case Option of
{config, KVList} -> {{config, add_my_config(KVList)}, true};
X -> {X, OldConfigFound}
end,
[NewOption | prepare_config_helper(Rest, ConfigFound)].
-spec make_symmetric_ring() -> pid().
make_symmetric_ring() ->
make_symmetric_ring([]).
-spec make_symmetric_ring(Options::kv_opts()) -> pid().
make_symmetric_ring(Options) ->
ct:pal("Trying to make a symmetric ring"),
NodeAddFun =
fun() ->
Ids = case lists:keyfind(scale_ring_size_by, 1, Options) of
{scale_ring_size_by, Scale} ->
api_rt:get_evenly_spaced_keys(
Scale * config:read(replication_factor));
false ->
api_rt:get_evenly_spaced_keys(
config:read(replication_factor))
end,
[admin:add_node([{first}, {{dht_node, id}, hd(Ids)}])
| [admin:add_node_at_id(Id) || Id <- tl(Ids)]]
end,
Pid = make_ring_generic(Options, NodeAddFun),
Size = case lists:keyfind(scale_ring_size_by, 1, Options) of
{scale_ring_size_by, Scale} ->
Scale * config:read(replication_factor);
false ->
config:read(replication_factor)
end,
check_ring_size(Size),
wait_for_stable_ring(),
check_ring_size(Size),
ct:pal("Scalaris booted with ~p node(s)...~n", [Size]),
TimeTrap = test_server:timetrap(3000 + Size * 1000),
test_server:timetrap_cancel(TimeTrap),
Pid.
-spec make_ring_with_ids([?RT:key()]) -> pid().
make_ring_with_ids(Ids) ->
make_ring_with_ids(Ids, []).
-spec make_ring_with_ids([?RT:key(),...], Options::kv_opts()) -> pid().
make_ring_with_ids(Ids, Options) when is_list(Ids) ->
ct:pal("Trying to make ring with Ids, containing ~p nodes.",[erlang:length(Ids)]),
NodeAddFun =
fun() ->
[admin:add_node([{first}, {{dht_node, id}, hd(Ids)}])
| [admin:add_node_at_id(Id) || Id <- tl(Ids)]]
end,
Size = erlang:length(Ids),
TimeTrap = test_server:timetrap(3000 + Size * 1000),
Pid = make_ring_generic(Options, NodeAddFun),
check_ring_size(Size),
wait_for_stable_ring(),
check_ring_size(Size),
ct:pal("Scalaris booted with ~p node(s)...~n", [Size]),
test_server:timetrap_cancel(TimeTrap),
Pid.
-spec make_ring_recover(Options::kv_opts()) -> pid().
make_ring_recover(Options) ->
ct:pal("Trying to recover ring."),
TimeTrap = test_server:timetrap(60000),
Pid = make_ring_generic(Options, fun() -> [] end),
ct:pal("ring restored"),
test_server:timetrap_cancel(TimeTrap),
Pid.
-spec make_ring(Size::pos_integer()) -> pid().
make_ring(Size) ->
make_ring(Size, []).
@doc Creates a ring with Size rangom IDs .
-spec make_ring(Size::pos_integer(), Options::kv_opts()) -> pid().
make_ring(Size, Options) ->
ct:pal("Trying to make ring with ~p nodes.",[Size]),
NodeAddFun =
fun() ->
First = admin:add_node([{first}]),
{RestSuc, RestFailed} = admin:add_nodes(Size - 1),
[First | RestSuc ++ RestFailed]
end,
TimeTrap = test_server:timetrap(3000 + Size * 1000),
Pid = make_ring_generic(Options, NodeAddFun),
check_ring_size(Size),
wait_for_stable_ring(),
check_ring_size(Size),
ct:pal("Scalaris booted with ~p node(s)...~n", [Size]),
test_server:timetrap_cancel(TimeTrap),
Pid.
-spec make_ring_generic(Options::kv_opts(),
NodeAddFun::fun(() -> [pid_groups:groupname() | {error, term()}]))
-> pid().
make_ring_generic(Options, NodeAddFun) ->
case ets:info(config_ets) of
undefined -> ok;
_ -> ct:fail("Trying to create a new ring although there is already one.")
end,
{Pid, StartRes} =
start_process(
fun() ->
erlang:register(ct_test_ring, self()),
randoms:start(),
{ok, _GroupsPid} = pid_groups:start_link(),
NewOptions = prepare_config(Options),
config:init(NewOptions),
tester:start_pseudo_proc(),
{ok, _} = sup_scalaris:start_link(NewOptions),
NodeAddFun()
end),
FailedNodes = [X || X = {error, _ } <- StartRes],
case FailedNodes of
[] -> ok;
[_|_] -> stop_ring(Pid),
?ct_fail("adding nodes failed: ~.0p", [FailedNodes])
end,
true = erlang:is_process_alive(Pid),
timer : sleep(1000 ) ,
?TRACE_RING_DATA(),
Pid.
@doc Stops a ring previously started with make_ring/1 or .
-spec stop_ring() -> ok.
stop_ring() ->
case erlang:whereis(ct_test_ring) of
undefined -> ok;
Pid -> stop_ring(Pid)
end.
@doc Stops a ring previously started with make_ring/1 or
-spec stop_ring(pid()) -> ok.
stop_ring(Pid) ->
LogLevel = config:read(log_level),
try
begin
ct:pal("unittest_helper:stop_ring start."),
log:set_log_level(none),
sup:sup_terminate(main_sup),
catch exit(Pid, kill),
util:wait_for_process_to_die(Pid),
stop_pid_groups(),
sup_scalaris:stop_first_services(),
log:set_log_level(LogLevel),
ct:pal("unittest_helper:stop_ring done."),
ok
end
catch
?CATCH_CLAUSE_WITH_STACKTRACE(Level, Reason, Stacktrace)
ct:pal("~s in stop_ring: ~p~n~.0p", [Level, Reason, Stacktrace]),
erlang:Level(Reason)
after
catch(unregister(ct_test_ring)),
log:set_log_level(LogLevel)
end.
-spec stop_pid_groups() -> ok.
stop_pid_groups() ->
case whereis(pid_groups) of
PidGroups when is_pid(PidGroups) ->
gen_component:kill(PidGroups),
util:wait_for_ets_table_to_disappear(PidGroups, pid_groups),
util:wait_for_ets_table_to_disappear(PidGroups, pid_groups_hidden),
catch unregister(pid_groups),
ok;
_ -> ok
end.
-spec wait_for_stable_ring() -> ok.
wait_for_stable_ring() ->
util:wait_for(fun() ->
R = admin:check_ring(),
R =:= ok
end, 100).
-spec wait_for_stable_ring_deep() -> ok.
wait_for_stable_ring_deep() ->
util:wait_for(fun() ->
R = admin:check_ring_deep(),
ct:pal("CheckRingDeep: ~p~n", [R]),
R =:= ok
end, 100).
-spec check_ring_size(non_neg_integer(), CheckFun::fun((DhtNodeState::term()) -> boolean())) -> ok.
check_ring_size(Size, CheckFun) ->
util:wait_for(
fun() ->
BootSize =
try
mgmt_server:number_of_nodes(),
trace_mpath:thread_yield(),
receive ?SCALARIS_RECV({get_list_length_response, L}, L) end
catch _:_ -> Size
end,
BootSize =:= Size andalso
Size =:= erlang:length(
[P || P <- pid_groups:find_all(dht_node),
CheckFun(gen_component:get_state(P))])
end, 50).
-spec check_ring_size(Size::non_neg_integer()) -> ok.
check_ring_size(Size) ->
check_ring_size(Size, fun(State) ->
DhtModule = config:read(dht_node),
DhtModule:is_alive(State)
end).
@doc Checks whether nodes have fully joined the ring ( including
-spec check_ring_size_fully_joined(Size::non_neg_integer()) -> ok.
check_ring_size_fully_joined(Size) ->
check_ring_size(Size, fun(State) ->
DhtModule = config:read(dht_node),
DhtModule:is_alive_no_slide(State)
end).
-spec start_process(StartFun::fun(() -> StartRes)) -> {pid(), StartRes}.
start_process(StartFun) ->
start_process(StartFun, fun() -> receive {done} -> ok end end).
-spec start_process(StartFun::fun(() -> StartRes), RunFun::fun(() -> any())) -> {pid(), StartRes}.
start_process(StartFun, RunFun) ->
start_process(StartFun, RunFun, false, spawn).
-spec start_process(StartFun::fun(() -> StartRes), RunFun::fun(() -> any()),
TrapExit::boolean(), Spawn::spawn | spawn_link)
-> {pid(), StartRes}.
start_process(StartFun, RunFun, TrapExit, Spawn) ->
process_flag(trap_exit, TrapExit),
Owner = self(),
Node = erlang:Spawn(
fun() ->
try Res = StartFun(),
Owner ! {started, self(), Res}
catch Level:Reason ->
Owner ! {killed},
erlang:Level(Reason)
end,
RunFun()
end),
receive
{started, Node, Res} -> {Node, Res};
{killed} -> ?ct_fail("start_process(~.0p, ~.0p, ~.0p, ~.0p) failed",
[StartFun, RunFun, TrapExit, Spawn])
end.
-spec start_subprocess(StartFun::fun(() -> StartRes)) -> {pid(), StartRes}.
start_subprocess(StartFun) ->
start_subprocess(StartFun, fun() -> receive {done} -> ok end end).
-spec start_subprocess(StartFun::fun(() -> StartRes), RunFun::fun(() -> any())) -> {pid(), StartRes}.
start_subprocess(StartFun, RunFun) ->
start_process(StartFun, RunFun, true, spawn_link).
-spec start_minimal_procs(CTConfig, ConfigOptions::[{atom(), term()}],
StartCommServer::boolean()) -> CTConfig when is_subtype(CTConfig, list()).
start_minimal_procs(CTConfig, ConfigOptions, StartCommServer) ->
{Pid, _} =
start_process(
fun() ->
{ok, _GroupsPid} = pid_groups:start_link(),
{priv_dir, PrivDir} = lists:keyfind(priv_dir, 1, CTConfig),
ConfigOptions2 = prepare_config(
[{config, [{log_path, PrivDir} | ConfigOptions]}]),
config:init(ConfigOptions2),
tester:start_pseudo_proc(),
case StartCommServer of
true ->
{ok, _CommPid} = sup:sup_start(
{local, no_name},
sup_comm_layer, []),
Port = get_scalaris_port(),
comm_server:set_local_address({127,0,0,1}, Port);
false -> ok
end
end),
[{wrapper_pid, Pid} | CTConfig].
-spec stop_minimal_procs(CTConfig) -> CTConfig when is_subtype(CTConfig, list()).
stop_minimal_procs(CTConfig) ->
case lists:keytake(wrapper_pid, 1, CTConfig) of
{value, {wrapper_pid, Pid}, CTConfig1} ->
LogLevel = config:read(log_level),
log:set_log_level(none),
exit(Pid, kill),
stop_pid_groups(),
log:set_log_level(LogLevel),
CTConfig1;
false -> CTConfig
end.
-type process_info() ::
{pid(), InitCall::mfa(), CurFun::mfa(),
{RegName::atom() | not_registered, Info::term() | failed | no_further_infos}}.
-spec get_processes() -> [process_info()].
get_processes() ->
[begin
InitCall =
case proc_lib:initial_call(X) of
false -> element(2, lists:keyfind(initial_call, 1, Data));
{Module, Function, Args} -> {Module, Function, length(Args)}
end,
CurFun = element(2, lists:keyfind(current_function, 1, Data)),
RegName = case lists:keyfind(registered_name, 1, Data) of
false -> not_registered;
RegNameTpl -> element(2, RegNameTpl)
end,
Info =
case {InitCall, CurFun} of
{{gen_component, _, _}, {gen_component, _, _}} ->
gen_component:get_component_state(X);
{_, {file_io_server, _, _}} ->
case file:pid2name(X) of
undefined -> {file, undefined};
{ok, FileName} -> {file, FileName};
case occuring in older Erlang versions :
FileName -> {file, FileName}
end;
{_, {gen_server, _, _}} ->
try sys:get_status(X)
catch _:_ -> no_further_infos
end;
_ -> no_further_infos
end,
{X, InitCall, CurFun, {RegName, Info}}
end
|| X <- processes(),
Data <- [process_info(X, [current_function, initial_call, registered_name])],
Data =/= undefined].
-spec kill_new_processes(OldProcesses::[process_info()]) -> ok.
kill_new_processes(OldProcesses) ->
kill_new_processes(OldProcesses, []).
-spec kill_new_processes(OldProcesses::[process_info()], Options::list()) -> ok.
kill_new_processes(OldProcesses, Options) ->
NewProcesses = get_processes(),
{_OnlyOld, _Both, OnlyNew} =
util:split_unique(OldProcesses, NewProcesses,
fun(P1, P2) ->
element(1, P1) =< element(1, P2)
end, fun(_P1, P2) -> P2 end),
Killed = [begin
Tabs = util:ets_tables_of(X),
try erlang:exit(X, kill) of
true ->
util:wait_for_process_to_die(X),
_ = [begin
util:wait_for_ets_table_to_disappear(X, Tab)
end || Tab <- Tabs ],
{ok, Proc}
catch _:_ -> {fail, Proc}
end
end || {X, InitCall, CurFun, {RegName, _Info}} = Proc <- OnlyNew,
not (InitCall =:= {test_server_sup, timetrap, 3} andalso
CurFun =:= {test_server_sup, timetrap, 3}),
not (InitCall =:= {test_server_sup, timetrap, 2} andalso
CurFun =:= {test_server_sup, timetrap, 2}),
not (InitCall =:= {test_server_gl, init, 1}),
spawned by : put_chars/3
RegName =/= cover_server,
X =/= self(),
X =/= whereis(timer_server),
element(1, CurFun) =/= file_io_server],
case lists:member({?quiet}, Options) of
false ->
ct:pal("Killed processes: ~.0p~n", [Killed]);
true -> ok
end.
-type ct_group_props() ::
[parallel | sequence | shuffle | {shuffle, {integer(), integer(), integer()}} |
{repeat | repeat_until_all_ok | repeat_until_all_fail | repeat_until_any_ok | repeat_until_any_fail, integer() | forever}].
-spec testcase_to_groupname(TestCase::atom()) -> atom().
testcase_to_groupname(TestCase) ->
erlang:list_to_atom(erlang:atom_to_list(TestCase) ++ "_grp").
-spec create_ct_all(TestCases::[atom()]) -> [{group, atom()}].
create_ct_all(TestCases) ->
[{group, testcase_to_groupname(TestCase)} || TestCase <- TestCases].
-spec create_ct_groups(TestCases::[atom()], SpecialOptions::[{atom(), ct_group_props()}])
-> [{atom(), ct_group_props(), [atom()]}].
create_ct_groups(TestCases, SpecialOptions) ->
[begin
Options =
case lists:keyfind(TestCase, 1, SpecialOptions) of
false -> [sequence, {repeat, 1}];
{_, X} -> X
end,
{testcase_to_groupname(TestCase), Options, [TestCase]}
end || TestCase <- TestCases].
-spec init_per_group(atom(), Config) -> Config when is_subtype(Config, kv_opts()).
init_per_group(_Group, Config) -> Config.
-spec end_per_group(atom(), kv_opts()) -> {return_group_result, ok | failed}.
end_per_group(_Group, Config) ->
Status = test_server:lookup_config(tc_group_result, Config),
case proplists:get_value(failed, Status) of
{return_group_result, ok};
one or more failed
{return_group_result, failed}
end.
-type ring_data(DBType) ::
[{pid(),
{intervals:left_bracket(), intervals:key(), intervals:key(), intervals:right_bracket()},
DBType,
{pred, comm:erl_local_pid_plain()},
{succ, comm:erl_local_pid_plain()},
ok | timeout}] |
{exception, Level::throw | error | exit, Reason::term(), Stacktrace::term()}.
-spec get_ring_data(full) -> ring_data(db_dht:db_as_list());
(kv) -> ring_data([{?RT:key(), client_version()}]).
get_ring_data(Type) ->
Self = self(),
erlang:spawn(
fun() ->
try
DHTNodes = pid_groups:find_all(dht_node),
Data =
lists:sort(
fun(E1, E2) ->
erlang:element(2, E1) =< erlang:element(2, E2)
end,
[begin
comm:send_local(DhtNode,
{unittest_get_bounds_and_data, comm:this(), Type}),
receive
{unittest_get_bounds_and_data_response, Bounds, Data, Pred, Succ} ->
{DhtNode, Bounds, Data,
{pred, comm:make_local(node:pidX(Pred))},
{succ, comm:make_local(node:pidX(Succ))}, ok}
after 750 -> {DhtNode, empty, [], {pred, null}, {succ, null}, timeout}
end
end || DhtNode <- DHTNodes]),
Self ! {data, Data}
catch
?CATCH_CLAUSE_WITH_STACKTRACE(Level, Reason, Stacktrace)
Result =
case erlang:whereis(ct_test_ring) of
undefined -> [];
_ -> {exception, Level, Reason, Stacktrace}
end,
Self ! {data, Result}
end
end),
receive {data, Data} -> Data
end.
-spec print_ring_data() -> ok.
print_ring_data() ->
DataAll = get_ring_data(full),
ct:pal("Scalaris ring data:~n~.0p~n", [DataAll]).
-spec print_proto_sched_stats(now | now_short | at_end_if_failed | at_end_if_failed_append) -> ok.
print_proto_sched_stats(When) ->
print_proto_sched_stats(When, default).
-spec print_proto_sched_stats(now | now_short | at_end_if_failed | at_end_if_failed_append,
TraceId::term()) -> ok.
print_proto_sched_stats(now, TraceId) ->
ct:pal("Proto scheduler stats: ~.2p", [proto_sched:get_infos(TraceId)]);
print_proto_sched_stats(now_short, TraceId) ->
ct:pal("Proto scheduler stats: ~.2p",
[proto_sched:info_shorten_messages(proto_sched:get_infos(TraceId), 200)]);
print_proto_sched_stats(at_end_if_failed, TraceId) ->
unittest_global_state:insert(proto_sched_stats, proto_sched:get_infos(TraceId)),
ok;
print_proto_sched_stats(at_end_if_failed_append, TraceId) ->
Current = case unittest_global_state:lookup(proto_sched_stats) of
failed -> [];
X when is_list(X) -> X
end,
unittest_global_state:insert(proto_sched_stats,
Current ++ proto_sched:get_infos(TraceId)),
ok.
-spec macro_equals(Actual::any(), ExpectedVal::any(), ActualStr::string(),
ExpectedStr::string(), Note::term()) -> true | no_return().
macro_equals(Actual, ExpectedVal, ActualStr, ExpectedStr, Note) ->
macro_compare(fun erlang:'=:='/2, Actual, ExpectedVal, "=:=", ActualStr, ExpectedStr, Note).
-spec macro_compare(CompFun::fun((T, T) -> boolean()), Actual::any(), ExpectedVal::any(),
CompFunStr::string(), ActualStr::string(), ExpectedStr::string(),
Note::term()) -> true | no_return().
macro_compare(CompFun, Actual, ExpectedVal, CompFunStr, ActualStr, ExpectedStr, Note) ->
case CompFun(Actual, ExpectedVal) of
true -> true;
false -> macro_equals_failed(Actual, ExpectedVal, CompFunStr, ActualStr, ExpectedStr, Note)
end.
-spec macro_equals_failed(ActualVal::any(), ExpectedVal::any(), CompFunStr::string(),
ActualStr::string(), ExpectedStr::string(), Note::term())
-> no_return().
macro_equals_failed(ActualVal, ExpectedVal, CompFunStr, ActualStr, ExpectedStr, Note) ->
log:log(error, "Failed (in ~.0p)~n"
" Call: ~s~n"
" Returns: ~.0p~n"
" is not (~s)~n"
" Exp. term: ~s~n"
" Exp. return: ~.0p~n"
" Note: ~.0p~n"
" Stacktrace: ~p~n"
" Linetrace: ~p~n",
[self(), ActualStr, ActualVal, CompFunStr, ExpectedStr, ExpectedVal, Note,
util:get_stacktrace(), util:get_linetrace()]),
?ct_fail("~s returned ~.0p which is not ~s the expected ~s that returns ~.0p. Note: ~.0p",
[ActualStr, ActualVal, CompFunStr, ExpectedStr, ExpectedVal, Note]).
-spec expect_no_message_timeout(Timeout::pos_integer()) -> true | no_return().
expect_no_message_timeout(Timeout) ->
receive
ActualMessage ->
?ct_fail("expected no message but got \"~.0p\"~n", [ActualMessage])
after Timeout -> true
end.
-spec check_ring_load(ExpLoad::pos_integer()) -> true | no_return().
check_ring_load(ExpLoad) ->
Ring = statistics:get_ring_details(),
Load = statistics:get_total_load(load, Ring),
?equals(Load, ExpLoad).
-spec check_ring_data() -> boolean().
check_ring_data() ->
check_ring_data(250, 8).
-spec check_ring_data(Timeout::pos_integer(), Retries::non_neg_integer()) -> boolean().
check_ring_data(Timeout, Retries) ->
Data = lists:flatmap(
fun({_Pid, _Interval, Data, {pred, _PredPid}, {succc, _SuccPid}, _Result}) -> Data;
(_) -> []
end,
get_ring_data(full)),
case Retries < 1 of
true ->
check_ring_data_all(Data, true);
_ ->
case check_ring_data_all(Data, false) of
true -> true;
_ -> timer:sleep(Timeout),
check_ring_data(Timeout, Retries - 1)
end
end.
check_ring_data_all(Data, FailOnError) ->
check_ring_data_unique(Data, FailOnError) andalso
check_ring_data_repl_fac(Data, FailOnError) andalso
check_ring_data_lock_free(Data, FailOnError) andalso
check_ring_data_repl_exist(Data, FailOnError).
-spec check_ring_data_unique(Data::[db_entry:entry()], FailOnError::boolean()) -> boolean().
check_ring_data_unique(Data, FailOnError) ->
UniqueData = lists:usort(fun(A, B) ->
db_entry:get_key(A) =< db_entry:get_key(B)
end, Data),
DataDiff = lists:subtract(Data, UniqueData),
case FailOnError of
true ->
?equals_w_note(DataDiff, [], "duplicate elements detected"),
true;
_ when DataDiff =:= [] ->
true;
_ ->
ct:pal("check_ring_data: duplicate elements detected: ~p~n", [DataDiff]),
false
end.
-spec check_ring_data_repl_fac(Data::[db_entry:entry()], FailOnError::boolean()) -> boolean().
check_ring_data_repl_fac(Data, FailOnError) ->
ReplicaKeys0 = ?RT:get_replica_keys(?RT:hash_key("0")),
DataLen = length(Data),
ReplicaLen = length(ReplicaKeys0),
ReplicaRem = DataLen rem ReplicaLen,
case FailOnError of
true ->
?equals(ReplicaRem, 0);
_ when ReplicaRem =:= 0 ->
true;
_ ->
ct:pal("check_ring_data: length(Data) = ~p not multiple of ~p~n", [DataLen, ReplicaLen]),
false
end.
-spec check_ring_data_lock_free(Data::[db_entry:entry()], FailOnError::boolean()) -> boolean().
check_ring_data_lock_free(Data, FailOnError) ->
Locked = [E || E <- Data, db_entry:is_locked(E)],
case FailOnError of
true ->
?equals_w_note(Locked, [], "ring is not lock-free"),
true;
_ when Locked =:= [] ->
true;
_ ->
ct:pal("check_ring_data: locked elements found: ~p~n", [Locked]),
false
end.
-spec check_ring_data_repl_exist(Data::[db_entry:entry()], FailOnError::boolean()) -> boolean().
check_ring_data_repl_exist(Data, FailOnError) ->
ElementsNotAllReplicas =
[E || E <- Data, not data_contains_all_replicas(Data, db_entry:get_key(E))],
case FailOnError of
true ->
?equals_w_note(ElementsNotAllReplicas, [], "missing replicas found"),
true;
_ when ElementsNotAllReplicas =:= [] ->
true;
_ ->
ct:pal("check_ring_data: elements with missing replicas:", [ElementsNotAllReplicas]),
false
end.
data_contains_all_replicas(Data, Key) ->
Keys = ?RT:get_replica_keys(Key),
Replicas = [E || E <- Data, lists:member(db_entry:get_key(E), Keys)],
length(Keys) =:= length(Replicas).
-spec build_interval(intervals:key(), intervals:key()) -> intervals:interval().
build_interval(?MINUS_INFINITY, ?PLUS_INFINITY) -> intervals:all();
build_interval(?PLUS_INFINITY, ?MINUS_INFINITY) -> intervals:all();
build_interval(A, A) -> intervals:all();
build_interval(A, B) when A < B -> intervals:new('(', A, B, ']');
build_interval(A, B) when A > B -> intervals:new('(', B, A, ']').
@doc can be used to filter empty entries out of a list of db_entries
-spec db_entry_not_null(db_entry:entry()) -> boolean().
db_entry_not_null(Entry) ->
not db_entry:is_null(Entry).
@doc removes duplicates and db_entries that are null
-spec scrub_data(db_dht:db_as_list()) -> db_dht:db_as_list().
scrub_data(Data) ->
lists:filter(
fun db_entry_not_null/1,
lists:usort(fun(A, B) ->
db_entry:get_key(A) =< db_entry:get_key(B)
end, lists:reverse(Data))).
|
38f680d6eab0ae456c15c7927a4f866daf7967c424e413c2539d632a1bf527cf | helium/router | console_callback.erl | -module(console_callback).
-behaviour(elli_handler).
-behaviour(elli_websocket_handler).
-include("console_test.hrl").
-export([
init/2,
handle/2,
handle_event/3
]).
-export([
websocket_init/2,
websocket_handle/3,
websocket_info/3,
websocket_handle_event/3
]).
init(Req, Args) ->
case elli_request:get_header(<<"Upgrade">>, Req) of
<<"websocket">> ->
init_ws(elli_request:path(Req), Req, Args);
_ ->
ignore
end.
handle(Req, _Args) ->
Method =
case elli_request:get_header(<<"Upgrade">>, Req) of
<<"websocket">> ->
websocket;
_ ->
elli_request:method(Req)
end,
handle(Method, elli_request:path(Req), Req, _Args).
%% Get All Devices
handle('GET', [<<"api">>, <<"router">>, <<"devices">>], _Req, Args) ->
Body = #{
<<"id">> => ?CONSOLE_DEVICE_ID,
<<"name">> => ?CONSOLE_DEVICE_NAME,
<<"app_key">> => lorawan_utils:binary_to_hex(maps:get(app_key, Args)),
<<"app_eui">> => lorawan_utils:binary_to_hex(maps:get(app_eui, Args)),
<<"dev_eui">> => lorawan_utils:binary_to_hex(maps:get(dev_eui, Args)),
<<"channels">> => [],
<<"labels">> => ?CONSOLE_LABELS,
<<"organization_id">> => ?CONSOLE_ORG_ID,
<<"active">> => true,
<<"multi_buy">> => 1
},
{200, [], jsx:encode([Body])};
%% Get Device
handle('GET', [<<"api">>, <<"router">>, <<"devices">>, DID], _Req, Args) ->
Tab = maps:get(ets, Args),
ChannelType =
case ets:lookup(Tab, channel_type) of
[] -> http;
[{channel_type, Type}] -> Type
end,
NoChannel =
case ets:lookup(Tab, no_channel) of
[] -> false;
[{no_channel, No}] -> No
end,
Channel =
case ChannelType of
http -> ?CONSOLE_HTTP_CHANNEL;
mqtt -> ?CONSOLE_MQTT_CHANNEL;
aws -> ?CONSOLE_AWS_CHANNEL;
decoder -> ?CONSOLE_DECODER_CHANNEL;
console -> ?CONSOLE_CONSOLE_CHANNEL;
template -> ?CONSOLE_TEMPLATE_CHANNEL
end,
Channels =
case NoChannel of
true ->
[];
false ->
case ets:lookup(Tab, channels) of
[] -> [Channel];
[{channels, C}] -> C
end
end,
DeviceID =
case ets:lookup(Tab, device_id) of
[] -> ?CONSOLE_DEVICE_ID;
[{device_id, ID}] -> ID
end,
NotFound =
case ets:lookup(Tab, device_not_found) of
[] -> false;
[{device_not_found, Bool}] -> Bool
end,
IsActive =
case ets:lookup(Tab, is_active) of
[] -> true;
[{is_active, IS}] -> IS
end,
Body = #{
<<"id">> => DeviceID,
<<"name">> => ?CONSOLE_DEVICE_NAME,
<<"app_key">> => lorawan_utils:binary_to_hex(maps:get(app_key, Args)),
<<"app_eui">> => lorawan_utils:binary_to_hex(maps:get(app_eui, Args)),
<<"dev_eui">> => lorawan_utils:binary_to_hex(maps:get(dev_eui, Args)),
<<"channels">> => Channels,
<<"labels">> => ?CONSOLE_LABELS,
<<"organization_id">> => ?CONSOLE_ORG_ID,
<<"active">> => IsActive,
<<"multi_buy">> => 1,
<<"adr_allowed">> => false
},
case NotFound of
true ->
{404, [], <<"Not Found">>};
false ->
case DID == <<"unknown">> of
true ->
{200, [], jsx:encode([Body])};
false ->
{200, [], jsx:encode(Body)}
end
end;
%% Get token
handle('POST', [<<"api">>, <<"router">>, <<"sessions">>], _Req, _Args) ->
Body = #{<<"jwt">> => <<"console_callback_token">>},
{201, [], jsx:encode(Body)};
%% Report status
handle(
'POST',
[
<<"api">>,
<<"router">>,
<<"devices">>,
_DID,
<<"event">>
],
Req,
Args
) ->
Pid = maps:get(forward, Args),
Body = elli_request:body(Req),
Data = jsx:decode(Body, [return_maps]),
Cat = maps:get(<<"category">>, Data, <<"unknown">>),
SubCat = maps:get(<<"sub_category">>, Data, <<"unknown">>),
ct:print("Console Event: ~p (~p)~n~n~p", [Cat, SubCat, Data]),
Pid ! {console_event, Cat, SubCat, Data},
{200, [], <<>>};
handle('POST', [<<"api">>, <<"router">>, <<"organizations">>, <<"burned">>], Req, Args) ->
Pid = maps:get(forward, Args),
Body = elli_request:body(Req),
try jsx:decode(Body, [return_maps]) of
Map ->
Pid ! {organizations_burned, Map},
{204, [], <<>>}
catch
_:_ ->
{400, [], <<"bad_body">>}
end;
%% POST to channel
handle('POST', [<<"channel">>], Req, Args) ->
Pid = maps:get(forward, Args),
Body = elli_request:body(Req),
Tab = maps:get(ets, Args),
Resp =
case ets:lookup(Tab, http_resp) of
[] -> <<"success">>;
[{http_resp, R}] -> R
end,
try jsx:decode(Body, [return_maps]) of
JSON ->
Pid ! {channel_data, JSON},
Reply = base64:encode(<<"reply">>),
case maps:find(<<"payload">>, JSON) of
{ok, Reply} ->
{200, [],
jsx:encode(#{
payload_raw => base64:encode(<<"ack">>),
port => 1,
confirmed => true
})};
_ ->
{200, [], Resp}
end
catch
_:_ ->
{400, [], <<"bad_body">>}
end;
handle('websocket', [<<"websocket">>], Req, Args) ->
%% Upgrade to a websocket connection.
elli_websocket:upgrade(Req, [
{handler, ?MODULE},
{handler_opts, Args}
]),
%% websocket is closed:
%% See RFC-6455 () for a list of
%% valid WS status codes than can be used on a close frame.
Note that the second element is the reason and is abitrary but should be meaningful
%% in regards to your server and sub-protocol.
{<<"1000">>, <<"Closed">>};
handle(_Method, _Path, _Req, _Args) ->
ct:pal("got unknown ~p req on ~p args=~p", [_Method, _Path, _Args]),
{404, [], <<"Not Found">>}.
handle_event(_Event, _Data, _Args) ->
ok.
websocket_init(Req, Opts) ->
lager:info("websocket_init ~p", [Req]),
lager:info("websocket_init ~p", [Opts]),
maps:get(forward, Opts) ! {websocket_init, self()},
{ok, [], Opts}.
websocket_handle(_Req, {text, Msg}, State) ->
{ok, Map} = router_console_ws_handler:decode_msg(Msg),
handle_message(Map, State);
websocket_handle(_Req, _Frame, State) ->
lager:info("websocket_handle ~p", [_Frame]),
{ok, State}.
websocket_info(_Req, clear_queue, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:clear_downlink_queue:devices">>,
#{<<"devices">> => [?CONSOLE_DEVICE_ID]}
),
{reply, {text, Data}, State};
websocket_info(_Req, {downlink, Payload}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:downlink:devices">>,
#{
<<"devices">> => [?CONSOLE_DEVICE_ID],
<<"payload">> => Payload,
<<"channel_name">> => ?CONSOLE_HTTP_CHANNEL_NAME
}
),
{reply, {text, Data}, State};
websocket_info(_Req, {device_update, Topic}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
Topic,
<<"device:all:refetch:devices">>,
#{<<"devices">> => [?CONSOLE_DEVICE_ID]}
),
{reply, {text, Data}, State};
websocket_info(_Req, {org_update, Topic}, State) ->
Payload = #{
<<"id">> => ?CONSOLE_ORG_ID,
<<"dc_balance_nonce">> => 0,
<<"dc_balance">> => 0
},
Data = router_console_ws_handler:encode_msg(
<<"0">>,
Topic,
<<"organization:all:refill:dc_balance">>,
Payload
),
{reply, {text, Data}, State};
websocket_info(_Req, {is_active, true}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:active:devices">>,
#{<<"devices">> => [?CONSOLE_DEVICE_ID]}
),
{reply, {text, Data}, State};
websocket_info(_Req, {is_active, false}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:inactive:devices">>,
#{<<"devices">> => [?CONSOLE_DEVICE_ID]}
),
{reply, {text, Data}, State};
websocket_info(_Req, get_router_address, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"router">>,
<<"router:get_address">>,
#{}
),
{reply, {text, Data}, State};
websocket_info(_Req, {label_fetch_queue, LabelID}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"label:all">>,
<<"label:all:downlink:fetch_queue">>,
#{
<<"label">> => LabelID,
<<"devices">> => [?CONSOLE_DEVICE_ID]
}
),
{reply, {text, Data}, State};
websocket_info(_Req, device_fetch_queue, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:downlink:fetch_queue">>,
#{
<<"device">> => ?CONSOLE_DEVICE_ID
}
),
{reply, {text, Data}, State};
websocket_info(_Req, _Msg, State) ->
lager:info("websocket_info ~p", [_Msg]),
{ok, State}.
websocket_handle_event(_Event, _Args, _State) ->
lager:info("websocket_handle_event ~p", [_Event]),
ok.
handle_message(#{ref := Ref, topic := <<"phoenix">>, event := <<"heartbeat">>}, State) ->
Data = router_console_ws_handler:encode_msg(Ref, <<"phoenix">>, <<"phx_reply">>, #{
<<"status">> => <<"ok">>
}),
{reply, {text, Data}, State};
handle_message(#{ref := Ref, topic := Topic, event := <<"phx_join">>}, State) ->
Data = router_console_ws_handler:encode_msg(
Ref,
Topic,
<<"phx_reply">>,
#{<<"status">> => <<"ok">>},
Ref
),
{reply, {text, Data}, State};
handle_message(Map, State) ->
lager:info("got unhandle message ~p ~p", [Map, lager:pr(State, ?MODULE)]),
Pid = maps:get(forward, State),
Pid ! {websocket_msg, Map},
{ok, State}.
init_ws([<<"websocket">>], _Req, _Args) ->
{ok, handover};
init_ws(_, _, _) ->
ignore.
| null | https://raw.githubusercontent.com/helium/router/8a103868831e99f72600ba34ef2f8ea2c3351e51/test/utils/console_callback.erl | erlang | Get All Devices
Get Device
Get token
Report status
POST to channel
Upgrade to a websocket connection.
websocket is closed:
See RFC-6455 () for a list of
valid WS status codes than can be used on a close frame.
in regards to your server and sub-protocol. | -module(console_callback).
-behaviour(elli_handler).
-behaviour(elli_websocket_handler).
-include("console_test.hrl").
-export([
init/2,
handle/2,
handle_event/3
]).
-export([
websocket_init/2,
websocket_handle/3,
websocket_info/3,
websocket_handle_event/3
]).
init(Req, Args) ->
case elli_request:get_header(<<"Upgrade">>, Req) of
<<"websocket">> ->
init_ws(elli_request:path(Req), Req, Args);
_ ->
ignore
end.
handle(Req, _Args) ->
Method =
case elli_request:get_header(<<"Upgrade">>, Req) of
<<"websocket">> ->
websocket;
_ ->
elli_request:method(Req)
end,
handle(Method, elli_request:path(Req), Req, _Args).
handle('GET', [<<"api">>, <<"router">>, <<"devices">>], _Req, Args) ->
Body = #{
<<"id">> => ?CONSOLE_DEVICE_ID,
<<"name">> => ?CONSOLE_DEVICE_NAME,
<<"app_key">> => lorawan_utils:binary_to_hex(maps:get(app_key, Args)),
<<"app_eui">> => lorawan_utils:binary_to_hex(maps:get(app_eui, Args)),
<<"dev_eui">> => lorawan_utils:binary_to_hex(maps:get(dev_eui, Args)),
<<"channels">> => [],
<<"labels">> => ?CONSOLE_LABELS,
<<"organization_id">> => ?CONSOLE_ORG_ID,
<<"active">> => true,
<<"multi_buy">> => 1
},
{200, [], jsx:encode([Body])};
handle('GET', [<<"api">>, <<"router">>, <<"devices">>, DID], _Req, Args) ->
Tab = maps:get(ets, Args),
ChannelType =
case ets:lookup(Tab, channel_type) of
[] -> http;
[{channel_type, Type}] -> Type
end,
NoChannel =
case ets:lookup(Tab, no_channel) of
[] -> false;
[{no_channel, No}] -> No
end,
Channel =
case ChannelType of
http -> ?CONSOLE_HTTP_CHANNEL;
mqtt -> ?CONSOLE_MQTT_CHANNEL;
aws -> ?CONSOLE_AWS_CHANNEL;
decoder -> ?CONSOLE_DECODER_CHANNEL;
console -> ?CONSOLE_CONSOLE_CHANNEL;
template -> ?CONSOLE_TEMPLATE_CHANNEL
end,
Channels =
case NoChannel of
true ->
[];
false ->
case ets:lookup(Tab, channels) of
[] -> [Channel];
[{channels, C}] -> C
end
end,
DeviceID =
case ets:lookup(Tab, device_id) of
[] -> ?CONSOLE_DEVICE_ID;
[{device_id, ID}] -> ID
end,
NotFound =
case ets:lookup(Tab, device_not_found) of
[] -> false;
[{device_not_found, Bool}] -> Bool
end,
IsActive =
case ets:lookup(Tab, is_active) of
[] -> true;
[{is_active, IS}] -> IS
end,
Body = #{
<<"id">> => DeviceID,
<<"name">> => ?CONSOLE_DEVICE_NAME,
<<"app_key">> => lorawan_utils:binary_to_hex(maps:get(app_key, Args)),
<<"app_eui">> => lorawan_utils:binary_to_hex(maps:get(app_eui, Args)),
<<"dev_eui">> => lorawan_utils:binary_to_hex(maps:get(dev_eui, Args)),
<<"channels">> => Channels,
<<"labels">> => ?CONSOLE_LABELS,
<<"organization_id">> => ?CONSOLE_ORG_ID,
<<"active">> => IsActive,
<<"multi_buy">> => 1,
<<"adr_allowed">> => false
},
case NotFound of
true ->
{404, [], <<"Not Found">>};
false ->
case DID == <<"unknown">> of
true ->
{200, [], jsx:encode([Body])};
false ->
{200, [], jsx:encode(Body)}
end
end;
handle('POST', [<<"api">>, <<"router">>, <<"sessions">>], _Req, _Args) ->
Body = #{<<"jwt">> => <<"console_callback_token">>},
{201, [], jsx:encode(Body)};
handle(
'POST',
[
<<"api">>,
<<"router">>,
<<"devices">>,
_DID,
<<"event">>
],
Req,
Args
) ->
Pid = maps:get(forward, Args),
Body = elli_request:body(Req),
Data = jsx:decode(Body, [return_maps]),
Cat = maps:get(<<"category">>, Data, <<"unknown">>),
SubCat = maps:get(<<"sub_category">>, Data, <<"unknown">>),
ct:print("Console Event: ~p (~p)~n~n~p", [Cat, SubCat, Data]),
Pid ! {console_event, Cat, SubCat, Data},
{200, [], <<>>};
handle('POST', [<<"api">>, <<"router">>, <<"organizations">>, <<"burned">>], Req, Args) ->
Pid = maps:get(forward, Args),
Body = elli_request:body(Req),
try jsx:decode(Body, [return_maps]) of
Map ->
Pid ! {organizations_burned, Map},
{204, [], <<>>}
catch
_:_ ->
{400, [], <<"bad_body">>}
end;
handle('POST', [<<"channel">>], Req, Args) ->
Pid = maps:get(forward, Args),
Body = elli_request:body(Req),
Tab = maps:get(ets, Args),
Resp =
case ets:lookup(Tab, http_resp) of
[] -> <<"success">>;
[{http_resp, R}] -> R
end,
try jsx:decode(Body, [return_maps]) of
JSON ->
Pid ! {channel_data, JSON},
Reply = base64:encode(<<"reply">>),
case maps:find(<<"payload">>, JSON) of
{ok, Reply} ->
{200, [],
jsx:encode(#{
payload_raw => base64:encode(<<"ack">>),
port => 1,
confirmed => true
})};
_ ->
{200, [], Resp}
end
catch
_:_ ->
{400, [], <<"bad_body">>}
end;
handle('websocket', [<<"websocket">>], Req, Args) ->
elli_websocket:upgrade(Req, [
{handler, ?MODULE},
{handler_opts, Args}
]),
Note that the second element is the reason and is abitrary but should be meaningful
{<<"1000">>, <<"Closed">>};
handle(_Method, _Path, _Req, _Args) ->
ct:pal("got unknown ~p req on ~p args=~p", [_Method, _Path, _Args]),
{404, [], <<"Not Found">>}.
handle_event(_Event, _Data, _Args) ->
ok.
websocket_init(Req, Opts) ->
lager:info("websocket_init ~p", [Req]),
lager:info("websocket_init ~p", [Opts]),
maps:get(forward, Opts) ! {websocket_init, self()},
{ok, [], Opts}.
websocket_handle(_Req, {text, Msg}, State) ->
{ok, Map} = router_console_ws_handler:decode_msg(Msg),
handle_message(Map, State);
websocket_handle(_Req, _Frame, State) ->
lager:info("websocket_handle ~p", [_Frame]),
{ok, State}.
websocket_info(_Req, clear_queue, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:clear_downlink_queue:devices">>,
#{<<"devices">> => [?CONSOLE_DEVICE_ID]}
),
{reply, {text, Data}, State};
websocket_info(_Req, {downlink, Payload}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:downlink:devices">>,
#{
<<"devices">> => [?CONSOLE_DEVICE_ID],
<<"payload">> => Payload,
<<"channel_name">> => ?CONSOLE_HTTP_CHANNEL_NAME
}
),
{reply, {text, Data}, State};
websocket_info(_Req, {device_update, Topic}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
Topic,
<<"device:all:refetch:devices">>,
#{<<"devices">> => [?CONSOLE_DEVICE_ID]}
),
{reply, {text, Data}, State};
websocket_info(_Req, {org_update, Topic}, State) ->
Payload = #{
<<"id">> => ?CONSOLE_ORG_ID,
<<"dc_balance_nonce">> => 0,
<<"dc_balance">> => 0
},
Data = router_console_ws_handler:encode_msg(
<<"0">>,
Topic,
<<"organization:all:refill:dc_balance">>,
Payload
),
{reply, {text, Data}, State};
websocket_info(_Req, {is_active, true}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:active:devices">>,
#{<<"devices">> => [?CONSOLE_DEVICE_ID]}
),
{reply, {text, Data}, State};
websocket_info(_Req, {is_active, false}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:inactive:devices">>,
#{<<"devices">> => [?CONSOLE_DEVICE_ID]}
),
{reply, {text, Data}, State};
websocket_info(_Req, get_router_address, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"router">>,
<<"router:get_address">>,
#{}
),
{reply, {text, Data}, State};
websocket_info(_Req, {label_fetch_queue, LabelID}, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"label:all">>,
<<"label:all:downlink:fetch_queue">>,
#{
<<"label">> => LabelID,
<<"devices">> => [?CONSOLE_DEVICE_ID]
}
),
{reply, {text, Data}, State};
websocket_info(_Req, device_fetch_queue, State) ->
Data = router_console_ws_handler:encode_msg(
<<"0">>,
<<"device:all">>,
<<"device:all:downlink:fetch_queue">>,
#{
<<"device">> => ?CONSOLE_DEVICE_ID
}
),
{reply, {text, Data}, State};
websocket_info(_Req, _Msg, State) ->
lager:info("websocket_info ~p", [_Msg]),
{ok, State}.
websocket_handle_event(_Event, _Args, _State) ->
lager:info("websocket_handle_event ~p", [_Event]),
ok.
handle_message(#{ref := Ref, topic := <<"phoenix">>, event := <<"heartbeat">>}, State) ->
Data = router_console_ws_handler:encode_msg(Ref, <<"phoenix">>, <<"phx_reply">>, #{
<<"status">> => <<"ok">>
}),
{reply, {text, Data}, State};
handle_message(#{ref := Ref, topic := Topic, event := <<"phx_join">>}, State) ->
Data = router_console_ws_handler:encode_msg(
Ref,
Topic,
<<"phx_reply">>,
#{<<"status">> => <<"ok">>},
Ref
),
{reply, {text, Data}, State};
handle_message(Map, State) ->
lager:info("got unhandle message ~p ~p", [Map, lager:pr(State, ?MODULE)]),
Pid = maps:get(forward, State),
Pid ! {websocket_msg, Map},
{ok, State}.
init_ws([<<"websocket">>], _Req, _Args) ->
{ok, handover};
init_ws(_, _, _) ->
ignore.
|
46090a612cd26f58c298b997f034dc849066ba88f2ac9a601a1adc400d8c2521 | sebsheep/elm2node | Magnitude.hs | module Elm.Magnitude
( Magnitude(..)
, toChars
)
where
-- MAGNITUDE
data Magnitude
= PATCH
| MINOR
| MAJOR
deriving (Eq, Ord)
toChars :: Magnitude -> String
toChars magnitude =
case magnitude of
PATCH -> "PATCH"
MINOR -> "MINOR"
MAJOR -> "MAJOR"
| null | https://raw.githubusercontent.com/sebsheep/elm2node/602a64f48e39edcdfa6d99793cc2827b677d650d/compiler/src/Elm/Magnitude.hs | haskell | MAGNITUDE | module Elm.Magnitude
( Magnitude(..)
, toChars
)
where
data Magnitude
= PATCH
| MINOR
| MAJOR
deriving (Eq, Ord)
toChars :: Magnitude -> String
toChars magnitude =
case magnitude of
PATCH -> "PATCH"
MINOR -> "MINOR"
MAJOR -> "MAJOR"
|
376ae1464d56efdcf85938975bf07d9484dcdb44e918945e22f5470b192b1e48 | ahrefs/monorobot | action.ml | open Devkit
open Base
open Slack
open Config_t
open Common
open Github_j
exception Action_error of string
let action_error msg = raise (Action_error msg)
let log = Log.from "action"
module Action (Github_api : Api.Github) (Slack_api : Api.Slack) = struct
let partition_push (cfg : Config_t.config) n =
let default = Option.to_list cfg.prefix_rules.default_channel in
let rules = cfg.prefix_rules.rules in
let branch = Github.commits_branch_of_ref n.ref in
let main_branch = if cfg.prefix_rules.filter_main_branch then cfg.main_branch_name else None in
let filter_by_branch = Rule.Prefix.filter_by_branch ~branch ~main_branch in
n.commits
|> List.filter ~f:(fun c ->
let skip = Github.is_merge_commit_to_ignore ~cfg ~branch c in
if skip then log#info "main branch merge, ignoring %s: %s" c.id (first_line c.message);
not skip
)
|> List.concat_map ~f:(fun commit ->
let rules = List.filter ~f:(filter_by_branch ~distinct:commit.distinct) rules in
let matched_channel_names =
Github.modified_files_of_commit commit
|> List.filter_map ~f:(Rule.Prefix.match_rules ~rules)
|> List.dedup_and_sort ~compare:String.compare
in
let channel_names =
if List.is_empty matched_channel_names && commit.distinct then default else matched_channel_names
in
List.map channel_names ~f:(fun n -> n, commit)
)
|> Map.of_alist_multi (module String)
|> Map.map ~f:(fun commits -> { n with commits })
|> Map.to_alist
let partition_label (cfg : Config_t.config) (labels : label list) =
let default = cfg.label_rules.default_channel in
let rules = cfg.label_rules.rules in
labels |> List.concat_map ~f:(Rule.Label.match_rules ~rules) |> List.dedup_and_sort ~compare:String.compare
|> fun channel_names -> if List.is_empty channel_names then Option.to_list default else channel_names
let partition_pr cfg (n : pr_notification) =
match n.action with
| (Opened | Closed | Reopened | Labeled | Ready_for_review) when not n.pull_request.draft ->
partition_label cfg n.pull_request.labels
| _ -> []
let partition_issue cfg (n : issue_notification) =
match n.action with
| Opened | Closed | Reopened | Labeled -> partition_label cfg n.issue.labels
| _ -> []
let partition_pr_review_comment cfg (n : pr_review_comment_notification) =
match n.action with
| Created -> partition_label cfg n.pull_request.labels
| _ -> []
let partition_issue_comment cfg (n : issue_comment_notification) =
match n.action with
| Created -> partition_label cfg n.issue.labels
| _ -> []
let partition_pr_review cfg (n : pr_review_notification) =
let { review; action; _ } = n in
match action, review.state, review.body with
| Submitted, "commented", (Some "" | None) -> []
the case ( action = Submitted , review.state = " commented " , review.body = " " ) happens when
a reviewer starts a review by commenting on particular sections of the code , which triggars a pull_request_review_comment event simultaneouly ,
and then submits the review without submitting any general feedback or explicit approval / changes .
the case ( action = Submitted , review.state = " commented " , review.body = null ) happens when
a reviewer adds a single comment on a particular section of the code , which triggars a pull_request_review_comment event simultaneouly .
in both cases , since pull_request_review_comment is already handled by another type of event , information in the pull_request_review payload
does not provide any insightful information and will thus be ignored .
a reviewer starts a review by commenting on particular sections of the code, which triggars a pull_request_review_comment event simultaneouly,
and then submits the review without submitting any general feedback or explicit approval/changes.
the case (action = Submitted, review.state = "commented", review.body = null) happens when
a reviewer adds a single comment on a particular section of the code, which triggars a pull_request_review_comment event simultaneouly.
in both cases, since pull_request_review_comment is already handled by another type of event, information in the pull_request_review payload
does not provide any insightful information and will thus be ignored. *)
| Submitted, _, _ -> partition_label cfg n.pull_request.labels
| _ -> []
let partition_commit (cfg : Config_t.config) files =
let default = Option.to_list cfg.prefix_rules.default_channel in
let rules = cfg.prefix_rules.rules in
let matched_channel_names =
List.map ~f:(fun f -> f.filename) files
|> List.filter_map ~f:(Rule.Prefix.match_rules ~rules)
|> List.dedup_and_sort ~compare:String.compare
in
if List.is_empty matched_channel_names then default else matched_channel_names
let partition_status (ctx : Context.t) (n : status_notification) =
let repo = n.repository in
let cfg = Context.find_repo_config_exn ctx repo.url in
let pipeline = n.context in
let current_status = n.state in
let rules = cfg.status_rules.rules in
let action_on_match (branches : branch list) =
let default = Option.to_list cfg.prefix_rules.default_channel in
let%lwt () = State.set_repo_pipeline_status ctx.state repo.url ~pipeline ~branches ~status:current_status in
match List.is_empty branches with
| true -> Lwt.return []
| false ->
match cfg.main_branch_name with
| None -> Lwt.return default
| Some main_branch_name ->
(* non-main branch build notifications go to default channel to reduce spam in topic channels *)
match List.exists branches ~f:(fun { name } -> String.equal name main_branch_name) with
| false -> Lwt.return default
| true ->
let sha = n.commit.sha in
( match%lwt Github_api.get_api_commit ~ctx ~repo ~sha with
| Error e -> action_error e
| Ok commit -> Lwt.return @@ partition_commit cfg commit.files
)
in
if Context.is_pipeline_allowed ctx repo.url ~pipeline then begin
let%lwt repo_state = State.find_or_add_repo ctx.state repo.url in
match Rule.Status.match_rules ~rules n with
| Some Ignore | None -> Lwt.return []
| Some Allow -> action_on_match n.branches
| Some Allow_once ->
match Map.find repo_state.pipeline_statuses pipeline with
| Some branch_statuses ->
let has_same_status_state_as_prev (branch : branch) =
match Map.find branch_statuses branch.name with
| None -> false
| Some state -> Poly.equal state current_status
in
let branches = List.filter n.branches ~f:(Fn.non @@ has_same_status_state_as_prev) in
action_on_match branches
| None -> action_on_match n.branches
end
else Lwt.return []
let partition_commit_comment (ctx : Context.t) n =
let cfg = Context.find_repo_config_exn ctx n.repository.url in
match n.comment.commit_id with
| None -> action_error "unable to find commit id for this commit comment event"
| Some sha ->
( match%lwt Github_api.get_api_commit ~ctx ~repo:n.repository ~sha with
| Error e -> action_error e
| Ok commit ->
let default = Option.to_list cfg.prefix_rules.default_channel in
let rules = cfg.prefix_rules.rules in
( match n.comment.path with
| None -> Lwt.return @@ (partition_commit cfg commit.files, commit)
| Some filename ->
match Rule.Prefix.match_rules filename ~rules with
| None -> Lwt.return (default, commit)
| Some chan -> Lwt.return ([ chan ], commit)
)
)
let ignore_notifications_from_user cfg req =
let sender_login =
match req with
| Github.Issue_comment n ->
Some n.sender.login
(*
| Github.Push n -> Some n.sender.login
| Pull_request n -> Some n.sender.login
| PR_review n -> Some n.sender.login
| PR_review_comment n -> Some n.sender.login
| Issue n -> Some n.sender.login
| Commit_comment n -> Some n.sender.login
*)
| _ -> None
in
match sender_login with
| Some sender_login -> List.exists cfg.ignored_users ~f:(String.equal sender_login)
| None -> false
let generate_notifications (ctx : Context.t) (req : Github.t) =
let repo = Github.repo_of_notification req in
let cfg = Context.find_repo_config_exn ctx repo.url in
match ignore_notifications_from_user cfg req with
| true -> Lwt.return []
| false ->
match req with
| Github.Push n ->
partition_push cfg n |> List.map ~f:(fun (channel, n) -> generate_push_notification n channel) |> Lwt.return
| Pull_request n -> partition_pr cfg n |> List.map ~f:(generate_pull_request_notification n) |> Lwt.return
| PR_review n -> partition_pr_review cfg n |> List.map ~f:(generate_pr_review_notification n) |> Lwt.return
| PR_review_comment n ->
partition_pr_review_comment cfg n |> List.map ~f:(generate_pr_review_comment_notification n) |> Lwt.return
| Issue n -> partition_issue cfg n |> List.map ~f:(generate_issue_notification n) |> Lwt.return
| Issue_comment n ->
partition_issue_comment cfg n |> List.map ~f:(generate_issue_comment_notification n) |> Lwt.return
| Commit_comment n ->
let%lwt channels, api_commit = partition_commit_comment ctx n in
let notifs = List.map ~f:(generate_commit_comment_notification api_commit n) channels in
Lwt.return notifs
| Status n ->
let%lwt channels = partition_status ctx n in
let notifs = List.map ~f:(generate_status_notification cfg n) channels in
Lwt.return notifs
| _ -> Lwt.return []
let send_notifications (ctx : Context.t) notifications =
let notify (msg : Slack_t.post_message_req) =
match%lwt Slack_api.send_notification ~ctx ~msg with
| Ok () -> Lwt.return_unit
| Error e -> action_error e
in
Lwt_list.iter_s notify notifications
(** [refresh_repo_config ctx n] fetches the latest repo config if it's
uninitialized, or if the incoming request [n] is a push
notification containing commits that touched the config file. *)
let refresh_repo_config (ctx : Context.t) notification =
let repo = Github.repo_of_notification notification in
let fetch_config () =
match%lwt Github_api.get_config ~ctx ~repo with
| Ok config ->
Context.set_repo_config ctx repo.url config;
Context.print_config ctx repo.url;
Lwt.return @@ Ok ()
| Error e -> action_error e
in
match Context.find_repo_config ctx repo.url with
| None -> fetch_config ()
| Some _ ->
match notification with
| Github.Push commit_pushed_notification ->
let commits = commit_pushed_notification.commits in
let modified_files = List.concat_map commits ~f:Github.modified_files_of_commit in
let config_was_modified = List.exists modified_files ~f:(String.equal ctx.config_filename) in
if config_was_modified then fetch_config () else Lwt.return @@ Ok ()
| _ -> Lwt.return @@ Ok ()
let do_github_tasks ctx (repo : repository) (req : Github.t) =
let cfg = Context.find_repo_config_exn ctx repo.url in
let project_owners (pull_request : pull_request) repository number =
match Github.get_project_owners pull_request cfg.project_owners with
| Some reviewers ->
( match%lwt Github_api.request_reviewers ~ctx ~repo:repository ~number ~reviewers with
| Ok () -> Lwt.return_unit
| Error e -> action_error e
)
| None -> Lwt.return_unit
in
match req with
| Github.Pull_request
{ action; pull_request = { draft = false; state = Open; _ } as pull_request; repository; number; _ } ->
begin
match action with
| Ready_for_review | Labeled -> project_owners pull_request repository number
| _ -> Lwt.return_unit
end
| _ -> Lwt.return_unit
let process_github_notification (ctx : Context.t) headers body =
let validate_signature secrets payload =
let repo = Github.repo_of_notification payload in
let signing_key = Context.gh_hook_token_of_secrets secrets repo.url in
Github.validate_signature ?signing_key ~headers body
in
let repo_is_supported secrets (repo : Github_t.repository) =
List.exists secrets.repos ~f:(fun r -> String.equal r.url repo.url)
in
try%lwt
let secrets = Context.get_secrets_exn ctx in
match Github.parse_exn headers body with
| exception exn -> Exn_lwt.fail ~exn "failed to parse payload"
| payload ->
match validate_signature secrets payload with
| Error e -> action_error e
| Ok () ->
let repo = Github.repo_of_notification payload in
( match repo_is_supported secrets repo with
| false -> action_error @@ Printf.sprintf "unsupported repository %s" repo.url
| true ->
( match%lwt refresh_repo_config ctx payload with
| Error e -> action_error e
| Ok () ->
let%lwt notifications = generate_notifications ctx payload in
let%lwt () = Lwt.join [ send_notifications ctx notifications; do_github_tasks ctx repo payload ] in
( match ctx.state_filepath with
| None -> Lwt.return_unit
| Some path ->
( match%lwt State.save ctx.state path with
| Ok () -> Lwt.return_unit
| Error e -> action_error e
)
)
)
)
with
| Yojson.Json_error msg ->
log#error "failed to parse file as valid JSON (%s)" msg;
Lwt.return_unit
| Action_error msg ->
log#error "%s" msg;
Lwt.return_unit
| Context.Context_error msg ->
log#error "%s" msg;
Lwt.return_unit
let process_link_shared_event (ctx : Context.t) (event : Slack_t.link_shared_event) =
let fetch_bot_user_id () =
match%lwt Slack_api.send_auth_test ~ctx () with
| Ok { user_id; _ } ->
State.set_bot_user_id ctx.state user_id;
let%lwt () =
Option.value_map ctx.state_filepath ~default:Lwt.return_unit ~f:(fun path ->
match%lwt State.save ctx.state path with
| Ok () -> Lwt.return_unit
| Error msg ->
log#warn "failed to save state file %s : %s" path msg;
Lwt.return_unit
)
in
Lwt.return_some user_id
| Error msg ->
log#warn "failed to query slack auth.test : %s" msg;
Lwt.return_none
in
let process link =
let with_gh_result_populate_slack (type a) ~(api_result : (a, string) Result.t)
~(populate : repository -> a -> Slack_t.message_attachment) ~repo
=
match api_result with
| Error _ -> Lwt.return_none
| Ok item -> Lwt.return_some @@ (link, populate repo item)
in
match Github.gh_link_of_string link with
| None -> Lwt.return_none
| Some gh_link ->
match gh_link with
| Pull_request (repo, number) ->
let%lwt result = Github_api.get_pull_request ~ctx ~repo ~number in
with_gh_result_populate_slack ~api_result:result ~populate:Slack_message.populate_pull_request ~repo
| Issue (repo, number) ->
let%lwt result = Github_api.get_issue ~ctx ~repo ~number in
with_gh_result_populate_slack ~api_result:result ~populate:Slack_message.populate_issue ~repo
| Commit (repo, sha) ->
let%lwt result = Github_api.get_api_commit ~ctx ~repo ~sha in
with_gh_result_populate_slack ~api_result:result ~populate:Slack_message.populate_commit ~repo
| Compare (repo, basehead) ->
let%lwt result = Github_api.get_compare ~ctx ~repo ~basehead in
with_gh_result_populate_slack ~api_result:result ~populate:Slack_message.populate_compare ~repo
in
let%lwt bot_user_id =
match State.get_bot_user_id ctx.state with
| Some id -> Lwt.return_some id
| None -> fetch_bot_user_id ()
in
if List.length event.links > 2 then Lwt.return "ignored: more than two links present"
else if Option.value_map bot_user_id ~default:false ~f:(String.equal event.user) then
Lwt.return "ignored: is bot user"
else begin
let links = List.map event.links ~f:(fun l -> l.url) in
let%lwt unfurls = List.map links ~f:process |> Lwt.all |> Lwt.map List.filter_opt |> Lwt.map StringMap.of_list in
if Map.is_empty unfurls then Lwt.return "ignored: no links to unfurl"
else begin
match%lwt Slack_api.send_chat_unfurl ~ctx ~channel:event.channel ~ts:event.message_ts ~unfurls () with
| Ok () -> Lwt.return "ok"
| Error e ->
log#error "%s" e;
Lwt.return "ignored: failed to unfurl links"
end
end
let process_slack_event (ctx : Context.t) headers body =
let secrets = Context.get_secrets_exn ctx in
match Slack_j.event_notification_of_string body with
| Url_verification payload -> Lwt.return payload.challenge
| Event_callback notification ->
match Slack.validate_signature ?signing_key:secrets.slack_signing_secret ~headers body with
| Error e -> action_error e
| Ok () ->
match notification.event with
| Link_shared event -> process_link_shared_event ctx event
(** debugging endpoint to return current in-memory repo config *)
let print_config (ctx : Context.t) repo_url =
log#info "finding config for repo_url: %s" repo_url;
match Context.find_repo_config ctx repo_url with
| None -> Lwt.return_error (`Not_found, Printf.sprintf "repo_url not found: %s" repo_url)
| Some config -> Lwt.return_ok (Config_j.string_of_config config)
end
| null | https://raw.githubusercontent.com/ahrefs/monorobot/93ccfca195f81d5e7534f0b0d0777e191f07e00e/lib/action.ml | ocaml | non-main branch build notifications go to default channel to reduce spam in topic channels
| Github.Push n -> Some n.sender.login
| Pull_request n -> Some n.sender.login
| PR_review n -> Some n.sender.login
| PR_review_comment n -> Some n.sender.login
| Issue n -> Some n.sender.login
| Commit_comment n -> Some n.sender.login
* [refresh_repo_config ctx n] fetches the latest repo config if it's
uninitialized, or if the incoming request [n] is a push
notification containing commits that touched the config file.
* debugging endpoint to return current in-memory repo config | open Devkit
open Base
open Slack
open Config_t
open Common
open Github_j
exception Action_error of string
let action_error msg = raise (Action_error msg)
let log = Log.from "action"
module Action (Github_api : Api.Github) (Slack_api : Api.Slack) = struct
let partition_push (cfg : Config_t.config) n =
let default = Option.to_list cfg.prefix_rules.default_channel in
let rules = cfg.prefix_rules.rules in
let branch = Github.commits_branch_of_ref n.ref in
let main_branch = if cfg.prefix_rules.filter_main_branch then cfg.main_branch_name else None in
let filter_by_branch = Rule.Prefix.filter_by_branch ~branch ~main_branch in
n.commits
|> List.filter ~f:(fun c ->
let skip = Github.is_merge_commit_to_ignore ~cfg ~branch c in
if skip then log#info "main branch merge, ignoring %s: %s" c.id (first_line c.message);
not skip
)
|> List.concat_map ~f:(fun commit ->
let rules = List.filter ~f:(filter_by_branch ~distinct:commit.distinct) rules in
let matched_channel_names =
Github.modified_files_of_commit commit
|> List.filter_map ~f:(Rule.Prefix.match_rules ~rules)
|> List.dedup_and_sort ~compare:String.compare
in
let channel_names =
if List.is_empty matched_channel_names && commit.distinct then default else matched_channel_names
in
List.map channel_names ~f:(fun n -> n, commit)
)
|> Map.of_alist_multi (module String)
|> Map.map ~f:(fun commits -> { n with commits })
|> Map.to_alist
let partition_label (cfg : Config_t.config) (labels : label list) =
let default = cfg.label_rules.default_channel in
let rules = cfg.label_rules.rules in
labels |> List.concat_map ~f:(Rule.Label.match_rules ~rules) |> List.dedup_and_sort ~compare:String.compare
|> fun channel_names -> if List.is_empty channel_names then Option.to_list default else channel_names
let partition_pr cfg (n : pr_notification) =
match n.action with
| (Opened | Closed | Reopened | Labeled | Ready_for_review) when not n.pull_request.draft ->
partition_label cfg n.pull_request.labels
| _ -> []
let partition_issue cfg (n : issue_notification) =
match n.action with
| Opened | Closed | Reopened | Labeled -> partition_label cfg n.issue.labels
| _ -> []
let partition_pr_review_comment cfg (n : pr_review_comment_notification) =
match n.action with
| Created -> partition_label cfg n.pull_request.labels
| _ -> []
let partition_issue_comment cfg (n : issue_comment_notification) =
match n.action with
| Created -> partition_label cfg n.issue.labels
| _ -> []
let partition_pr_review cfg (n : pr_review_notification) =
let { review; action; _ } = n in
match action, review.state, review.body with
| Submitted, "commented", (Some "" | None) -> []
the case ( action = Submitted , review.state = " commented " , review.body = " " ) happens when
a reviewer starts a review by commenting on particular sections of the code , which triggars a pull_request_review_comment event simultaneouly ,
and then submits the review without submitting any general feedback or explicit approval / changes .
the case ( action = Submitted , review.state = " commented " , review.body = null ) happens when
a reviewer adds a single comment on a particular section of the code , which triggars a pull_request_review_comment event simultaneouly .
in both cases , since pull_request_review_comment is already handled by another type of event , information in the pull_request_review payload
does not provide any insightful information and will thus be ignored .
a reviewer starts a review by commenting on particular sections of the code, which triggars a pull_request_review_comment event simultaneouly,
and then submits the review without submitting any general feedback or explicit approval/changes.
the case (action = Submitted, review.state = "commented", review.body = null) happens when
a reviewer adds a single comment on a particular section of the code, which triggars a pull_request_review_comment event simultaneouly.
in both cases, since pull_request_review_comment is already handled by another type of event, information in the pull_request_review payload
does not provide any insightful information and will thus be ignored. *)
| Submitted, _, _ -> partition_label cfg n.pull_request.labels
| _ -> []
let partition_commit (cfg : Config_t.config) files =
let default = Option.to_list cfg.prefix_rules.default_channel in
let rules = cfg.prefix_rules.rules in
let matched_channel_names =
List.map ~f:(fun f -> f.filename) files
|> List.filter_map ~f:(Rule.Prefix.match_rules ~rules)
|> List.dedup_and_sort ~compare:String.compare
in
if List.is_empty matched_channel_names then default else matched_channel_names
let partition_status (ctx : Context.t) (n : status_notification) =
let repo = n.repository in
let cfg = Context.find_repo_config_exn ctx repo.url in
let pipeline = n.context in
let current_status = n.state in
let rules = cfg.status_rules.rules in
let action_on_match (branches : branch list) =
let default = Option.to_list cfg.prefix_rules.default_channel in
let%lwt () = State.set_repo_pipeline_status ctx.state repo.url ~pipeline ~branches ~status:current_status in
match List.is_empty branches with
| true -> Lwt.return []
| false ->
match cfg.main_branch_name with
| None -> Lwt.return default
| Some main_branch_name ->
match List.exists branches ~f:(fun { name } -> String.equal name main_branch_name) with
| false -> Lwt.return default
| true ->
let sha = n.commit.sha in
( match%lwt Github_api.get_api_commit ~ctx ~repo ~sha with
| Error e -> action_error e
| Ok commit -> Lwt.return @@ partition_commit cfg commit.files
)
in
if Context.is_pipeline_allowed ctx repo.url ~pipeline then begin
let%lwt repo_state = State.find_or_add_repo ctx.state repo.url in
match Rule.Status.match_rules ~rules n with
| Some Ignore | None -> Lwt.return []
| Some Allow -> action_on_match n.branches
| Some Allow_once ->
match Map.find repo_state.pipeline_statuses pipeline with
| Some branch_statuses ->
let has_same_status_state_as_prev (branch : branch) =
match Map.find branch_statuses branch.name with
| None -> false
| Some state -> Poly.equal state current_status
in
let branches = List.filter n.branches ~f:(Fn.non @@ has_same_status_state_as_prev) in
action_on_match branches
| None -> action_on_match n.branches
end
else Lwt.return []
let partition_commit_comment (ctx : Context.t) n =
let cfg = Context.find_repo_config_exn ctx n.repository.url in
match n.comment.commit_id with
| None -> action_error "unable to find commit id for this commit comment event"
| Some sha ->
( match%lwt Github_api.get_api_commit ~ctx ~repo:n.repository ~sha with
| Error e -> action_error e
| Ok commit ->
let default = Option.to_list cfg.prefix_rules.default_channel in
let rules = cfg.prefix_rules.rules in
( match n.comment.path with
| None -> Lwt.return @@ (partition_commit cfg commit.files, commit)
| Some filename ->
match Rule.Prefix.match_rules filename ~rules with
| None -> Lwt.return (default, commit)
| Some chan -> Lwt.return ([ chan ], commit)
)
)
let ignore_notifications_from_user cfg req =
let sender_login =
match req with
| Github.Issue_comment n ->
Some n.sender.login
| _ -> None
in
match sender_login with
| Some sender_login -> List.exists cfg.ignored_users ~f:(String.equal sender_login)
| None -> false
let generate_notifications (ctx : Context.t) (req : Github.t) =
let repo = Github.repo_of_notification req in
let cfg = Context.find_repo_config_exn ctx repo.url in
match ignore_notifications_from_user cfg req with
| true -> Lwt.return []
| false ->
match req with
| Github.Push n ->
partition_push cfg n |> List.map ~f:(fun (channel, n) -> generate_push_notification n channel) |> Lwt.return
| Pull_request n -> partition_pr cfg n |> List.map ~f:(generate_pull_request_notification n) |> Lwt.return
| PR_review n -> partition_pr_review cfg n |> List.map ~f:(generate_pr_review_notification n) |> Lwt.return
| PR_review_comment n ->
partition_pr_review_comment cfg n |> List.map ~f:(generate_pr_review_comment_notification n) |> Lwt.return
| Issue n -> partition_issue cfg n |> List.map ~f:(generate_issue_notification n) |> Lwt.return
| Issue_comment n ->
partition_issue_comment cfg n |> List.map ~f:(generate_issue_comment_notification n) |> Lwt.return
| Commit_comment n ->
let%lwt channels, api_commit = partition_commit_comment ctx n in
let notifs = List.map ~f:(generate_commit_comment_notification api_commit n) channels in
Lwt.return notifs
| Status n ->
let%lwt channels = partition_status ctx n in
let notifs = List.map ~f:(generate_status_notification cfg n) channels in
Lwt.return notifs
| _ -> Lwt.return []
let send_notifications (ctx : Context.t) notifications =
let notify (msg : Slack_t.post_message_req) =
match%lwt Slack_api.send_notification ~ctx ~msg with
| Ok () -> Lwt.return_unit
| Error e -> action_error e
in
Lwt_list.iter_s notify notifications
let refresh_repo_config (ctx : Context.t) notification =
let repo = Github.repo_of_notification notification in
let fetch_config () =
match%lwt Github_api.get_config ~ctx ~repo with
| Ok config ->
Context.set_repo_config ctx repo.url config;
Context.print_config ctx repo.url;
Lwt.return @@ Ok ()
| Error e -> action_error e
in
match Context.find_repo_config ctx repo.url with
| None -> fetch_config ()
| Some _ ->
match notification with
| Github.Push commit_pushed_notification ->
let commits = commit_pushed_notification.commits in
let modified_files = List.concat_map commits ~f:Github.modified_files_of_commit in
let config_was_modified = List.exists modified_files ~f:(String.equal ctx.config_filename) in
if config_was_modified then fetch_config () else Lwt.return @@ Ok ()
| _ -> Lwt.return @@ Ok ()
let do_github_tasks ctx (repo : repository) (req : Github.t) =
let cfg = Context.find_repo_config_exn ctx repo.url in
let project_owners (pull_request : pull_request) repository number =
match Github.get_project_owners pull_request cfg.project_owners with
| Some reviewers ->
( match%lwt Github_api.request_reviewers ~ctx ~repo:repository ~number ~reviewers with
| Ok () -> Lwt.return_unit
| Error e -> action_error e
)
| None -> Lwt.return_unit
in
match req with
| Github.Pull_request
{ action; pull_request = { draft = false; state = Open; _ } as pull_request; repository; number; _ } ->
begin
match action with
| Ready_for_review | Labeled -> project_owners pull_request repository number
| _ -> Lwt.return_unit
end
| _ -> Lwt.return_unit
let process_github_notification (ctx : Context.t) headers body =
let validate_signature secrets payload =
let repo = Github.repo_of_notification payload in
let signing_key = Context.gh_hook_token_of_secrets secrets repo.url in
Github.validate_signature ?signing_key ~headers body
in
let repo_is_supported secrets (repo : Github_t.repository) =
List.exists secrets.repos ~f:(fun r -> String.equal r.url repo.url)
in
try%lwt
let secrets = Context.get_secrets_exn ctx in
match Github.parse_exn headers body with
| exception exn -> Exn_lwt.fail ~exn "failed to parse payload"
| payload ->
match validate_signature secrets payload with
| Error e -> action_error e
| Ok () ->
let repo = Github.repo_of_notification payload in
( match repo_is_supported secrets repo with
| false -> action_error @@ Printf.sprintf "unsupported repository %s" repo.url
| true ->
( match%lwt refresh_repo_config ctx payload with
| Error e -> action_error e
| Ok () ->
let%lwt notifications = generate_notifications ctx payload in
let%lwt () = Lwt.join [ send_notifications ctx notifications; do_github_tasks ctx repo payload ] in
( match ctx.state_filepath with
| None -> Lwt.return_unit
| Some path ->
( match%lwt State.save ctx.state path with
| Ok () -> Lwt.return_unit
| Error e -> action_error e
)
)
)
)
with
| Yojson.Json_error msg ->
log#error "failed to parse file as valid JSON (%s)" msg;
Lwt.return_unit
| Action_error msg ->
log#error "%s" msg;
Lwt.return_unit
| Context.Context_error msg ->
log#error "%s" msg;
Lwt.return_unit
let process_link_shared_event (ctx : Context.t) (event : Slack_t.link_shared_event) =
let fetch_bot_user_id () =
match%lwt Slack_api.send_auth_test ~ctx () with
| Ok { user_id; _ } ->
State.set_bot_user_id ctx.state user_id;
let%lwt () =
Option.value_map ctx.state_filepath ~default:Lwt.return_unit ~f:(fun path ->
match%lwt State.save ctx.state path with
| Ok () -> Lwt.return_unit
| Error msg ->
log#warn "failed to save state file %s : %s" path msg;
Lwt.return_unit
)
in
Lwt.return_some user_id
| Error msg ->
log#warn "failed to query slack auth.test : %s" msg;
Lwt.return_none
in
let process link =
let with_gh_result_populate_slack (type a) ~(api_result : (a, string) Result.t)
~(populate : repository -> a -> Slack_t.message_attachment) ~repo
=
match api_result with
| Error _ -> Lwt.return_none
| Ok item -> Lwt.return_some @@ (link, populate repo item)
in
match Github.gh_link_of_string link with
| None -> Lwt.return_none
| Some gh_link ->
match gh_link with
| Pull_request (repo, number) ->
let%lwt result = Github_api.get_pull_request ~ctx ~repo ~number in
with_gh_result_populate_slack ~api_result:result ~populate:Slack_message.populate_pull_request ~repo
| Issue (repo, number) ->
let%lwt result = Github_api.get_issue ~ctx ~repo ~number in
with_gh_result_populate_slack ~api_result:result ~populate:Slack_message.populate_issue ~repo
| Commit (repo, sha) ->
let%lwt result = Github_api.get_api_commit ~ctx ~repo ~sha in
with_gh_result_populate_slack ~api_result:result ~populate:Slack_message.populate_commit ~repo
| Compare (repo, basehead) ->
let%lwt result = Github_api.get_compare ~ctx ~repo ~basehead in
with_gh_result_populate_slack ~api_result:result ~populate:Slack_message.populate_compare ~repo
in
let%lwt bot_user_id =
match State.get_bot_user_id ctx.state with
| Some id -> Lwt.return_some id
| None -> fetch_bot_user_id ()
in
if List.length event.links > 2 then Lwt.return "ignored: more than two links present"
else if Option.value_map bot_user_id ~default:false ~f:(String.equal event.user) then
Lwt.return "ignored: is bot user"
else begin
let links = List.map event.links ~f:(fun l -> l.url) in
let%lwt unfurls = List.map links ~f:process |> Lwt.all |> Lwt.map List.filter_opt |> Lwt.map StringMap.of_list in
if Map.is_empty unfurls then Lwt.return "ignored: no links to unfurl"
else begin
match%lwt Slack_api.send_chat_unfurl ~ctx ~channel:event.channel ~ts:event.message_ts ~unfurls () with
| Ok () -> Lwt.return "ok"
| Error e ->
log#error "%s" e;
Lwt.return "ignored: failed to unfurl links"
end
end
let process_slack_event (ctx : Context.t) headers body =
let secrets = Context.get_secrets_exn ctx in
match Slack_j.event_notification_of_string body with
| Url_verification payload -> Lwt.return payload.challenge
| Event_callback notification ->
match Slack.validate_signature ?signing_key:secrets.slack_signing_secret ~headers body with
| Error e -> action_error e
| Ok () ->
match notification.event with
| Link_shared event -> process_link_shared_event ctx event
let print_config (ctx : Context.t) repo_url =
log#info "finding config for repo_url: %s" repo_url;
match Context.find_repo_config ctx repo_url with
| None -> Lwt.return_error (`Not_found, Printf.sprintf "repo_url not found: %s" repo_url)
| Some config -> Lwt.return_ok (Config_j.string_of_config config)
end
|
ac1130b98cb79e65a062996986f789a5be8b5771376ad99c583887a2c17345c3 | geophf/1HaskellADay | Exercise.hs | module Y2020.M09.D08.Exercise where
-
Yesterday * ...
-
Yesterday* ...
--}
import Y2020.M09.D01.Exercise
-
* time is so fluid for me , ... it being time , and all ... * rolleyes *
... we build this city ...
... wait : we built this ONTOLOGY of words to novels in the top 100 - read
books in gutenberg .
OR . DID . WE ?
I concluded that exercise with : " I noticed there are gutenberg - artefacts , so
I 'm removing words that occur in all 100 books . "
But was that a valid assertion ?
What other assertions can we make of these data we collected ?
Today 's Haskell Exercise : data analyses .
-
*time is so fluid for me, ... it being time, and all ... *rolleyes*
... we build this city ...
... wait: we built this ONTOLOGY of words to novels in the top 100-read
books in gutenberg.
OR. DID. WE?
I concluded that exercise with: "I noticed there are gutenberg-artefacts, so
I'm removing words that occur in all 100 books."
But was that a valid assertion?
What other assertions can we make of these data we collected?
Today's Haskell Exercise: data analyses.
--}
import Data.Map (Map)
import Data.Set (Set)
import Y2020.M08.D25.Solution (gutenbergIndex, workingDir, gutenbergTop100Index)
import Y2020.M08.D26.Solution (importLibrary)
import Y2020.M08.D31.Solution (stopwords, loadStopwords)
type WordOccurrences = Map String Int
-- A little helper-function to load the ontology
ont :: IO Ontology
ont = let nupes = loadStopwords stopwords
idx = gutenbergIndex (workingDir ++ gutenbergTop100Index)
lib = idx >>= importLibrary
in bookVec <$> nupes <*> lib
-
> > > ont
... zillions of entries later ...
> > > let mont = it
... ` mont ` stands for ` my ont(ology ) `
... now we need to get the WordOccurrences
> > > let wc = ontology mont
-
>>> ont
... zillions of entries later ...
>>> let mont = it
... `mont` stands for `my ont(ology)`
... now we need to get the WordOccurrences
>>> let wc = ontology mont
--}
-- 0. How many words are in all the books?
allWordsCount :: WordOccurrences -> Int
allWordsCount wordcounts = undefined
-
> > > allWordsCount wc
251429
That took a little while .
-
>>> allWordsCount wc
251429
That took a little while.
--}
1 . How many words , and what are the words that occur in all 100 books ?
inAllBooks :: WordOccurrences -> Set String
inAllBooks wordcounts = undefined
-
> > > let iab = inAllBooks wc
> > > iab
{ " body","ebook","ebooks","free","gutenberg","library " ,
" " }
> > > length iab
10
-
>>> let iab = inAllBooks wc
>>> iab
{"body","ebook","ebooks","free","gutenberg","library",
"page","project","search","start"}
>>> length iab
10
--}
2 . How many words , and what are the words , that occur only once ?
onlyOneOccurringWords :: WordOccurrences -> Set String
onlyOneOccurringWords wordcounts = undefined
-
Hm :
> > > let ooow = onlyOneOccurringWords wc
> > > ooow
lots of messy words , but then we also have words of this form :
... " liveries\226\128\157 " ...
It looks like we may need to clean up our clean - up algorithm , because :
> > > length ooow
195035
Is a lot of words . Some of those words may be useful in clustering ( later ) .
-
Hm:
>>> let ooow = onlyOneOccurringWords wc
>>> ooow
lots of messy words, but then we also have words of this form:
... "liveries\226\128\157" ...
It looks like we may need to clean up our clean-up algorithm, because:
>>> length ooow
195035
Is a lot of words. Some of those words may be useful in clustering (later).
--}
3 . Which words occur only once in a book ( any book ) ... even if those words
-- occur in multiple books, if they occur just once in any book, what are these
-- words?
oneWordInBook :: Ontology -> Set String
oneWordInBook bookswords = undefined
-
> > > let ooib = oneWordInBook mont
> > > ooib
... lots of words , again ...
> > > length ooib
205354
Good Heavens !
-
>>> let ooib = oneWordInBook mont
>>> ooib
... lots of words, again ...
>>> length ooib
205354
Good Heavens!
--}
4 . Okay . Remove all the one - word and all - books - words from out ontology .
removeInfreqs :: Set String -> Ontology -> Ontology
removeInfreqs infrequentWords ont = undefined
-
> > > let newOnt ( Set.unions [ iab , ooow , ooib ] ) mont
> > > length newOnt
100
... as expected , as there are still 100 books being codified , but ...
> > > let newWc = ontology newOnt
> > > allWordsCount newWc
2333
Wow ! Huge difference ! Good or bad ?
We will find that out on another , fine - problem - solving day !
-
>>> let newOnt = removeInfreqs (Set.unions [iab, ooow, ooib]) mont
>>> length newOnt
100
... as expected, as there are still 100 books being codified, but ...
>>> let newWc = ontology newOnt
>>> allWordsCount newWc
2333
Wow! Huge difference! Good or bad?
We will find that out on another, fine Haskell-problem-solving day!
--}
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2020/M09/D08/Exercise.hs | haskell | }
}
A little helper-function to load the ontology
}
0. How many words are in all the books?
}
}
}
occur in multiple books, if they occur just once in any book, what are these
words?
}
} | module Y2020.M09.D08.Exercise where
-
Yesterday * ...
-
Yesterday* ...
import Y2020.M09.D01.Exercise
-
* time is so fluid for me , ... it being time , and all ... * rolleyes *
... we build this city ...
... wait : we built this ONTOLOGY of words to novels in the top 100 - read
books in gutenberg .
OR . DID . WE ?
I concluded that exercise with : " I noticed there are gutenberg - artefacts , so
I 'm removing words that occur in all 100 books . "
But was that a valid assertion ?
What other assertions can we make of these data we collected ?
Today 's Haskell Exercise : data analyses .
-
*time is so fluid for me, ... it being time, and all ... *rolleyes*
... we build this city ...
... wait: we built this ONTOLOGY of words to novels in the top 100-read
books in gutenberg.
OR. DID. WE?
I concluded that exercise with: "I noticed there are gutenberg-artefacts, so
I'm removing words that occur in all 100 books."
But was that a valid assertion?
What other assertions can we make of these data we collected?
Today's Haskell Exercise: data analyses.
import Data.Map (Map)
import Data.Set (Set)
import Y2020.M08.D25.Solution (gutenbergIndex, workingDir, gutenbergTop100Index)
import Y2020.M08.D26.Solution (importLibrary)
import Y2020.M08.D31.Solution (stopwords, loadStopwords)
type WordOccurrences = Map String Int
ont :: IO Ontology
ont = let nupes = loadStopwords stopwords
idx = gutenbergIndex (workingDir ++ gutenbergTop100Index)
lib = idx >>= importLibrary
in bookVec <$> nupes <*> lib
-
> > > ont
... zillions of entries later ...
> > > let mont = it
... ` mont ` stands for ` my ont(ology ) `
... now we need to get the WordOccurrences
> > > let wc = ontology mont
-
>>> ont
... zillions of entries later ...
>>> let mont = it
... `mont` stands for `my ont(ology)`
... now we need to get the WordOccurrences
>>> let wc = ontology mont
allWordsCount :: WordOccurrences -> Int
allWordsCount wordcounts = undefined
-
> > > allWordsCount wc
251429
That took a little while .
-
>>> allWordsCount wc
251429
That took a little while.
1 . How many words , and what are the words that occur in all 100 books ?
inAllBooks :: WordOccurrences -> Set String
inAllBooks wordcounts = undefined
-
> > > let iab = inAllBooks wc
> > > iab
{ " body","ebook","ebooks","free","gutenberg","library " ,
" " }
> > > length iab
10
-
>>> let iab = inAllBooks wc
>>> iab
{"body","ebook","ebooks","free","gutenberg","library",
"page","project","search","start"}
>>> length iab
10
2 . How many words , and what are the words , that occur only once ?
onlyOneOccurringWords :: WordOccurrences -> Set String
onlyOneOccurringWords wordcounts = undefined
-
Hm :
> > > let ooow = onlyOneOccurringWords wc
> > > ooow
lots of messy words , but then we also have words of this form :
... " liveries\226\128\157 " ...
It looks like we may need to clean up our clean - up algorithm , because :
> > > length ooow
195035
Is a lot of words . Some of those words may be useful in clustering ( later ) .
-
Hm:
>>> let ooow = onlyOneOccurringWords wc
>>> ooow
lots of messy words, but then we also have words of this form:
... "liveries\226\128\157" ...
It looks like we may need to clean up our clean-up algorithm, because:
>>> length ooow
195035
Is a lot of words. Some of those words may be useful in clustering (later).
3 . Which words occur only once in a book ( any book ) ... even if those words
oneWordInBook :: Ontology -> Set String
oneWordInBook bookswords = undefined
-
> > > let ooib = oneWordInBook mont
> > > ooib
... lots of words , again ...
> > > length ooib
205354
Good Heavens !
-
>>> let ooib = oneWordInBook mont
>>> ooib
... lots of words, again ...
>>> length ooib
205354
Good Heavens!
4 . Okay . Remove all the one - word and all - books - words from out ontology .
removeInfreqs :: Set String -> Ontology -> Ontology
removeInfreqs infrequentWords ont = undefined
-
> > > let newOnt ( Set.unions [ iab , ooow , ooib ] ) mont
> > > length newOnt
100
... as expected , as there are still 100 books being codified , but ...
> > > let newWc = ontology newOnt
> > > allWordsCount newWc
2333
Wow ! Huge difference ! Good or bad ?
We will find that out on another , fine - problem - solving day !
-
>>> let newOnt = removeInfreqs (Set.unions [iab, ooow, ooib]) mont
>>> length newOnt
100
... as expected, as there are still 100 books being codified, but ...
>>> let newWc = ontology newOnt
>>> allWordsCount newWc
2333
Wow! Huge difference! Good or bad?
We will find that out on another, fine Haskell-problem-solving day!
|
26dfc1db17d14546167831ee18d1bcda6c4f552e1f6b60ab96438dd9fcf19928 | mirage/ocaml-openflow | flowvisor.ml |
* Copyright ( c ) 2011 < >
*
* 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) 2011 Charalampos Rotsos <>
*
* 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 Net
module OP = Openflow.Ofpacket
module OC = Openflow.Ofcontroller
module OE = Openflow.Ofcontroller.Event
module OSK = Openflow.Ofsocket
open OP
open OP.Flow
open OP.Flow_mod
open OP.Match
let sp = Printf.sprintf
let cp = OS.Console.log
let to_port = OP.Port.port_of_int
let of_port = OP.Port.int_of_port
exception Ofcontroller_error of int32 * OP.error_code * OP.t
exception Ofswitch_error of int64 * int32 * OP.error_code * OP.t
(* fake switch state to be exposed to controllers *)
type port = {
port_id: int;
port_name: string;
phy: OP.Port.phy;
origin_dpid: int64;
origin_port_id: int;
}
type cached_reply =
| Flows of OP.Flow.stats list
| Aggr of OP.Stats.aggregate
| Table of OP.Stats.table
| Port of OP.Port.stats list
| No_reply
type xid_state = {
xid : int32;
src : int64;
mutable dst : int64 list;
ts : float;
mutable cache : cached_reply;
}
type t = {
verbose : bool;
(* counters *)
mutable errornum : int32;
mutable portnum : int;
mutable xid_count : int32;
mutable buffer_id_count: int32;
(* controller and switch storage *)
mutable controllers : (int64 * OP.Match.t *Openflow.Ofsocket.conn_state ) list;
switches : (int64, OC.t) Hashtbl.t;
(* Mapping transients id values *)
xid_map : (int32, xid_state) Hashtbl.t;
port_map : (int, (int64 * int * OP.Port.phy)) Hashtbl.t;
buffer_id_map : (int32, (OP.Packet_in.t * int64)) Hashtbl.t;
(* topology managment module *)
flv_topo: Flowvisor_topology.t;
}
timeout pending queries after 3 minutes
let timeout = 180.
let supported_actions () =
OP.Switch.(
{output=true;set_vlan_id=true;set_vlan_pcp=true;strip_vlan=true;
set_dl_src=true; set_dl_dst=true; set_nw_src=true; set_nw_dst=true;
set_nw_tos=true; set_tp_src=true; set_tp_dst=true; enqueue=false;
vendor=false; })
let supported_capabilities () =
OP.Switch.({flow_stats=true;table_stats=true;port_stats=true;stp=false;
ip_reasm=false;queue_stats=false;arp_match_ip=true;})
let switch_features datapath_id ports =
OP.Switch.({datapath_id; n_buffers=0l; n_tables=(char_of_int 1);
capabilities=(supported_capabilities ());
actions=(supported_actions ()); ports;})
let init_flowvisor verbose flv_topo =
{verbose; errornum=0l; portnum=10; xid_count=0l;
port_map=(Hashtbl.create 64);
controllers=[]; buffer_id_map=(Hashtbl.create 64);
buffer_id_count=0l; xid_map=(Hashtbl.create 64);
switches=(Hashtbl.create 64); flv_topo; }
(* xid buffer controller functions *)
let match_dpid_buffer_id st dpid buffer_id =
try
let (_, dst_dpid) = Hashtbl.find st.buffer_id_map buffer_id in
(dpid = dst_dpid)
with Not_found -> false
let get_new_xid old_xid st src dst cache =
let xid = st.xid_count in
let _ = st.xid_count <- Int32.add st.xid_count 1l in
let r = {xid; src; dst; ts=(OS.Clock.time ()); cache;} in
let _ = Hashtbl.replace st.xid_map xid r in
xid
let handle_xid flv st xid_st =
match xid_st.cache with
| Flows flows ->
let stats = OP.Stats.({st_ty=FLOW; more=true;}) in
let (_, _, t) = List.find (
fun (dpid, _, _) -> dpid = xid_st.src )
flv.controllers in
lwt (_, flows) =
Lwt_list. fold_right_s (
fun fl (sz, flows) ->
let fl_sz = OP.Flow.flow_stats_len fl in
if (sz + fl_sz > 0xffff) then
let r = OP.Stats.Flow_resp(stats, flows) in
let h = OP.Header.create ~xid:(xid_st.xid) OP.Header.STATS_RESP 0 in
lwt _ = Openflow.Ofsocket.send_packet t (OP.Stats_resp (h, r)) in
return ((OP.Header.get_len + OP.Stats.get_resp_hdr_size + fl_sz), [fl])
else
return ((sz + fl_sz), (fl::flows)) )
flows ((OP.Header.get_len + OP.Stats.get_resp_hdr_size), []) in
let stats = OP.Stats.({st_ty=FLOW; more=false;}) in
let r = OP.Stats.Flow_resp(stats, flows) in
let h = OP.Header.create ~xid:xid_st.xid OP.Header.STATS_RESP 0 in
Openflow.Ofsocket.send_packet t (OP.Stats_resp (h, r))
| _ -> return ()
let timeout_xid flv st =
while_lwt true do
let time = OS.Clock.time () in
let xid =
Hashtbl.fold (
fun xid r ret ->
if (r.ts+.timeout>time) then
let _ = Hashtbl.remove st.xid_map xid in
r :: ret
else ret
) st.xid_map [] in
lwt _ = Lwt_list.iter_p (handle_xid flv st) xid in
OS.Time.sleep 600.
done
(* communication primitives *)
let switch_dpid flv = Hashtbl.fold (fun dpid _ r -> r@[dpid]) flv.switches []
let switch_chan_dpid flv = Hashtbl.fold (fun dpid ch r -> (dpid,ch)::r) flv.switches []
let dpid_of_port st inp =
try
let (in_dpid, _, _) = Hashtbl.find st.port_map (of_port inp) in
in_dpid
with Not_found -> 0L
let port_of_port st inp =
try
let (_, inp, _) = Hashtbl.find st.port_map (of_port inp) in
OP.Port.Port(inp)
with Not_found -> OP.Port.No_port
let dpid_port_of_port_exn st inp xid msg =
try
let (dpid, p, _) = Hashtbl.find st.port_map (of_port inp) in
(dpid, OP.Port.Port(p))
with Not_found ->
raise (Ofcontroller_error (xid, OP.ACTION_BAD_OUT_PORT, msg) )
let send_all_switches st msg =
Lwt_list.iter_p (
fun (dpid, ch) -> OC.send_data ch dpid msg)
(Hashtbl.fold (fun dpid ch c -> c @[(dpid, ch)]) st.switches [])
let send_switch st dpid msg =
try_lwt
let ch = Hashtbl.find st.switches dpid in
OC.send_data ch dpid msg
with Not_found -> return (cp (sp "[flowvisor] unregister dpid %Ld\n%!" dpid))
let send_controller t msg = OSK.send_packet t msg
let inform_controllers flv m msg =
(* find the controller that should handle the packet in *)
Lwt_list.iter_p
(fun (_, rule, t) ->
if (OP.Match.flow_match_compare rule m rule.OP.Match.wildcards) then
Openflow.Ofsocket.send_packet t msg
else return ()) flv.controllers
(*************************************************
* Switch OpenFlow control channel
*************************************************)
let packet_out_create st msg xid inp bid data actions =
let data =
match (bid) with
| -1l -> data
(* if no buffer id included, send the data section of the
* packet_out*)
| bid when (Hashtbl.mem st.buffer_id_map bid) ->
(* if we have a buffer id in cache, use those data *)
let (pkt, _ ) = Hashtbl.find st.buffer_id_map bid in
let _ = Hashtbl.remove st.buffer_id_map bid in
pkt.OP.Packet_in.data
| _ -> raise (Ofcontroller_error(xid, OP.REQUEST_BUFFER_UNKNOWN, msg) )
in
let in_port = port_of_port st inp in
let m = OP.Packet_out.create ~buffer_id:(-1l)
~actions ~in_port ~data () in
let h = OP.Header.(create ~xid PACKET_OUT 0) in
OP.Packet_out (h,m)
let rec pkt_out_process st xid inp bid data msg acts = function
| (OP.Flow.Output(OP.Port.All, len))::tail
| (OP.Flow.Output(OP.Port.Flood, len))::tail -> begin
let actions = acts @ [OP.Flow.Output(OP.Port.Flood, len)] in
OP.Port . None is not the appropriate way to handle this . Need to find the
* port that connects the two switches probably .
* port that connects the two switches probably. *)
let in_dpid = dpid_of_port st inp in
(* let _ = pp "sending packet from port %d to port %d\n%!"
* (OP.Port.int_of_port inp) (in_p) in *)
let msg = packet_out_create st msg xid OP.Port.No_port (-1l) data actions in
lwt _ =
Lwt_list.iter_p (
fun (dpid, ch) ->
if (dpid = in_dpid) then
OC.send_data ch dpid
(packet_out_create st msg xid inp (-1l) data actions)
else
OC.send_data ch dpid msg
) (Hashtbl.fold (fun dpid ch c -> c @[(dpid, ch)]) st.switches []) in
pkt_out_process st xid inp bid data msg acts tail
end
| (OP.Flow.Output(OP.Port.In_port, len))::tail -> begin
(* output packet to the last hop of the path *)
let (dpid, out_p) = dpid_port_of_port_exn st inp xid msg in
let actions = acts @ [OP.Flow.Output(OP.Port.In_port, len)] in
lwt _ = send_switch st dpid
(packet_out_create st msg xid out_p bid data actions) in
pkt_out_process st xid inp bid data msg acts tail
end
| (OP.Flow.Output(OP.Port.Port(p), len))::tail -> begin
(* output packet to the last hop of the path *)
let (dpid, out_p) = dpid_port_of_port_exn st (to_port p) xid msg in
let actions = acts @ [OP.Flow.Output(out_p, len)] in
let msg = packet_out_create st msg xid inp bid data actions in
lwt _ = send_switch st dpid
(packet_out_create st msg xid inp bid data actions) in
pkt_out_process st xid inp bid data msg acts tail
end
| (OP.Flow.Output(OP.Port.Controller, len))::tail
| (OP.Flow.Output(OP.Port.Table, len))::tail
| (OP.Flow.Output(OP.Port.Local, len))::tail
| (OP.Flow.Output(OP.Port.No_port, len))::tail
| (OP.Flow.Output(OP.Port.Normal, len))::tail ->
raise (Ofcontroller_error (xid, OP.REQUEST_BAD_STAT, msg) )
| a :: tail ->
(* for the non-output action, populate the new action list *)
pkt_out_process st xid inp bid data msg (acts @ [a]) tail
| [] -> return ()
let map_path flv in_dpid in_port out_dpid out_port =
(* let _ = pp "[flowvisor-switch] mapping a path between %Ld:%s - %Ld:%s\n%!"
in_dpid (OP.Port.string_of_port in_port)
out_dpid (OP.Port.string_of_port out_port) in *)
if (in_dpid = out_dpid) then [(out_dpid, in_port, out_port)]
else
Flowvisor_topology.find_dpid_path flv.flv_topo
in_dpid in_port out_dpid out_port
(* let path = List.rev path in *)
let _ =
List.iter (
fun ( dp , in_p , out_p ) - >
pp " % s:%Ld:%s - > "
( OP.Port.string_of_port in_p )
dp ( OP.Port.string_of_port out_p )
) path in
let _ = pp " \n% ! " in
path
List.iter (
fun (dp, in_p, out_p) ->
pp "%s:%Ld:%s -> "
(OP.Port.string_of_port in_p)
dp (OP.Port.string_of_port out_p)
) path in
let _ = pp "\n%!" in
path *)
TODO fixme ! ! ! !
let map_spanning_tree flv in_dpid in_port = []
let rec send_flow_mod_to_path st xid msg pkt len actions path =
let h = OP.Header.create ~xid OP.Header.FLOW_MOD 0 in
match path with
| [] -> return ()
| [(dpid, in_port, out_port)] -> begin
let actions = actions @ [OP.Flow.Output(out_port, len)] in
let _ = pkt.of_match.in_port <- in_port in
let fm = OP.Flow_mod.(
{pkt with buffer_id=(-1l);out_port=(OP.Port.No_port);actions;}) in
lwt _ = send_switch st dpid (OP.Flow_mod(h, fm)) in
match (pkt.buffer_id) with
| -1l -> return ()
| bid when (Hashtbl.mem st.buffer_id_map bid) ->
(* if we have a buffer id in cache, use those data *)
let (pkt, _ ) = Hashtbl.find st.buffer_id_map bid in
let msg = packet_out_create st msg xid (OP.Port.No_port)
(-1l) (pkt.OP.Packet_in.data) actions in
lwt _ = send_switch st dpid msg in
return ()
| _ ->
(* if buffer id is unknown, send error *)
raise (Ofcontroller_error(xid, OP.REQUEST_BUFFER_UNKNOWN, msg))
end
| ((dpid, in_port, out_port)::rest) -> begin
let _ = pkt.of_match.in_port <- in_port in
let fm = OP.Flow_mod.(
{pkt with buffer_id=(-1l);out_port=(OP.Port.No_port);
actions=( [OP.Flow.Output(out_port, len)] );}) in
lwt _ = send_switch st dpid (OP.Flow_mod(h, fm)) in
send_flow_mod_to_path st xid msg pkt len actions rest
end
let rec flow_mod_translate_inner st msg xid pkt in_dpid in_port acts = function
| (OP.Flow.Output(OP.Port.All, len))::tail
| (OP.Flow.Output(OP.Port.Flood, len))::tail ->
(* Need a spanning tree maybe for this? *)
lwt _ = send_flow_mod_to_path st xid msg pkt len acts
(map_spanning_tree st in_dpid in_port) in
flow_mod_translate_inner st msg xid pkt in_dpid in_port acts tail
| (OP.Flow.Output(OP.Port.In_port, len))::tail ->
lwt _ = send_flow_mod_to_path st xid msg pkt len acts
[(in_dpid, OP.Port.Port(in_port), OP.Port.In_port)] in
flow_mod_translate_inner st msg xid pkt in_dpid in_port acts tail
| (OP.Flow.Output(OP.Port.Controller, len))::tail ->
lwt _ = send_flow_mod_to_path st xid msg pkt len acts
[(in_dpid, OP.Port.Port(in_port), OP.Port.Controller)] in
flow_mod_translate_inner st msg xid pkt in_dpid in_port acts tail
| (OP.Flow.Output(OP.Port.Port(p), len))::tail ->
let (out_dpid, out_port) = dpid_port_of_port_exn st (to_port p) xid msg in
lwt _ = send_flow_mod_to_path st xid msg pkt len acts
(map_path st in_dpid (OP.Port.Port(in_port) )
out_dpid out_port) in
flow_mod_translate_inner st msg xid pkt in_dpid in_port acts tail
| (OP.Flow.Output(OP.Port.Table, _))::_
| (OP.Flow.Output(OP.Port.Local, _))::_
| (OP.Flow.Output(OP.Port.Normal, _))::_ ->
raise (Ofcontroller_error (xid, OP.REQUEST_BAD_STAT, msg) )
| a :: tail -> flow_mod_translate_inner st msg xid pkt in_dpid in_port (acts@[a]) tail
| [] -> return ()
let flow_mod_add_translate st msg xid pkt =
let (in_dpid, in_port) = dpid_port_of_port_exn st pkt.of_match.in_port xid msg in
flow_mod_translate_inner st msg xid pkt in_dpid (of_port in_port) [] pkt.actions
let flow_mod_del_translate st msg xid pkt =
match (pkt.of_match.OP.Match.wildcards.OP.Wildcards.in_port,
pkt.of_match.OP.Match.in_port, pkt.OP.Flow_mod.out_port) with
| (false, OP.Port.Local, OP.Port.No_port)
| (true, _, OP.Port.No_port) ->
let h = OP.Header.(create ~xid FLOW_MOD 0) in
send_all_switches st (OP.Flow_mod(h, pkt))
| (false, OP.Port.Port(p), OP.Port.No_port) ->
let (dpid, port) = dpid_port_of_port_exn st (to_port p) xid msg in
let _ = pkt.of_match.in_port <- port in
let h = OP.Header.(create ~xid FLOW_MOD 0) in
send_switch st dpid (OP.Flow_mod(h, pkt))
| (false, OP.Port.Port(in_p), OP.Port.Port(out_p)) ->
let (in_dpid, in_port) = dpid_port_of_port_exn st
pkt.of_match.OP.Match.in_port xid msg in
let (out_dpid, out_port) = dpid_port_of_port_exn st
pkt.OP.Flow_mod.out_port xid msg in
lwt _ = send_flow_mod_to_path st xid msg pkt 0 []
(map_path st in_dpid in_port out_dpid out_port) in
return ()
| _ -> raise (Ofcontroller_error (xid, OP.REQUEST_BAD_STAT, msg) )
let process_openflow st dpid t msg =
let _ = if st.verbose then cp (sp "[flowvisor-switch] %s\n%!" (OP.to_string msg)) in
match msg with
| OP.Hello (h) -> return ()
| OP.Echo_req (h) -> (* Reply to ECHO requests *)
let open OP.Header in
send_controller t (OP.Echo_resp (create ECHO_RESP ~xid:h.xid get_len))
| OP.Features_req (h) ->
let h = OP.Header.(create FEATURES_RESP ~xid:h.xid 0) in
let f = switch_features dpid
(Hashtbl.fold (fun _ (_, _, p) r -> p::r)
st.port_map []) in
send_controller t (OP.Features_resp(h, f))
| OP.Stats_req(h, req) -> begin
(* TODO Need to translate the xid here *)
match req with
| OP.Stats.Desc_req(req) ->
let open OP.Stats in
let desc = { imfr_desc="Mirage"; hw_desc="Mirage";
sw_desc="Mirage_flowvisor"; serial_num="0.1";
dp_desc="Mirage";} in
let resp_h = {st_ty=DESC;more=false;} in
send_controller t
(OP.Stats_resp(h, (Desc_resp(resp_h,desc))))
| OP.Stats.Flow_req(req_h, of_match, table_id, out_port) -> begin
TODO Need to consider the table_id and the out_port and
* split reply over multiple openflow packets if they do n't
* fit a single packet .
* split reply over multiple openflow packets if they don't
* fit a single packet. *)
match (of_match.OP.Match.wildcards.OP.Wildcards.in_port,
(of_match.OP.Match.in_port)) with
| (false, OP.Port.Port(p)) ->
let (dst_dpid, out_port) = dpid_port_of_port_exn st
of_match.OP.Match.in_port h.OP.Header.xid msg in
let xid = get_new_xid h.OP.Header.xid st dst_dpid [dpid] (Flows [])in
let h = OP.Header.(create STATS_RESP ~xid 0) in
let of_match = OP.Match.translate_port of_match out_port in
(* TODO out_port needs processing. if dpid are between
* different switches need to define the outport
* as the port of the interconnection link *)
let req = OP.Stats.(
Flow_req(req_h, of_match, table_id, out_port)) in
send_switch st dst_dpid (OP.Stats_req(h, req))
| (_, _) ->
let req = OP.Stats.(Flow_req(req_h, of_match,table_id, out_port)) in
let xid = get_new_xid h.OP.Header.xid st dpid (switch_dpid st) (Flows []) in
let h = OP.Header.(create STATS_RESP ~xid 0) in
send_all_switches st (OP.Stats_req(h, req))
end
| OP.Stats.Aggregate_req (req_h, of_match, table_id, out_port) ->
begin
let open OP.Stats in
let open OP.Header in
let cache = Aggr ({packet_count=0L; byte_count=0L;flow_count=0l;}) in
match OP.Match.(of_match.wildcards.OP.Wildcards.in_port,(of_match.in_port)) with
| (false, OP.Port.Port(p)) ->
let (dst_dpid, port) = dpid_port_of_port_exn st of_match.in_port h.xid msg in
let xid = get_new_xid h.xid st dpid [dst_dpid] cache in
let h = { h with xid;} in
let _ = of_match.in_port <- port in
(* TODO out_port needs processing. if dpid are between
* different switches need to define the outport as the
* port of the interconnection link *)
let m = Aggregate_req(req_h, of_match, table_id, out_port) in
send_switch st dst_dpid (OP.Stats_req(h, m))
| (_, _) ->
let open OP.Header in
let h = {h with xid=(get_new_xid h.xid st dpid
(switch_dpid st) cache);} in
send_all_switches st (OP.Stats_req(h, req))
end
| OP.Stats.Table_req(req_h) ->
let open OP.Header in
let cache = Table OP.Stats.(init_table_stats (OP.Stats.table_id_of_int 1)
"mirage" (OP.Wildcards.full_wildcard ()) ) in
let xid = get_new_xid h.xid st dpid (switch_dpid st) cache in
let h = {h with xid;} in
send_all_switches st (OP.Stats_req(h, req))
| OP.Stats.Port_req(req_h, port) -> begin
match port with
| OP.Port.No_port ->
let open OP.Header in
let xid = get_new_xid h.xid st dpid (switch_dpid st) (Port []) in
let h = ({h with xid;}) in
send_all_switches st (OP.Stats_req(h, req))
| OP.Port.Port(_) ->
let open OP.Header in
let (dst_dpid, port) = dpid_port_of_port_exn st port h.xid msg in
let xid = get_new_xid h.xid st dpid [dst_dpid] (Port []) in
let h = {h with xid;} in
let m = OP.Stats.(Port_req(req_h, port)) in
send_all_switches st (OP.Stats_req(h, m))
| _ ->
raise (Ofcontroller_error (h.OP.Header.xid, OP.QUEUE_OP_BAD_PORT, msg))
end
| _ ->
raise (Ofcontroller_error (h.OP.Header.xid, OP.REQUEST_BAD_STAT, msg))
end
| OP.Get_config_req(h) ->
TODO make a custom reply tothe query
let h = OP.Header.({h with ty=FEATURES_RESP}) in
send_controller t (OP.Get_config_resp(h, OP.Switch.init_switch_config))
| OP.Barrier_req(h) ->
(* TODO just reply for now. need to check this with all switches *)
(* let xid = get_new_xid dpid in *)
let _ = cp (sp "BARRIER_REQ: %s\n%!" (OP.Header.header_to_string h)) in
send_controller t (OP.Barrier_resp (OP.Header.({h with ty=BARRIER_RESP;})) )
| OP.Packet_out(h, pkt) -> begin
let _ = if st.verbose then cp (sp "[flowvisor-switch] PACKET_OUT: %s\n%!"
(OP.Packet_out.packet_out_to_string pkt)) in
(* Check if controller has the right to send traffic on the specific subnet *)
try_lwt
OP.Packet_out.(pkt_out_process st h.OP.Header.xid pkt.in_port
pkt.buffer_id pkt.data msg [] pkt.actions )
with exn ->
return (cp (sp "[flowvisor-switch] packet_out message error %s\n%!"
(Printexc.to_string exn)))
end
| OP.Flow_mod(h,fm) -> begin
let _ = if st.verbose then cp (sp "[flowvisor-switch] FLOW_MOD: %s\n%!"
(OP.Flow_mod.flow_mod_to_string fm)) in
let xid = get_new_xid h.OP.Header.xid st dpid (switch_dpid st) No_reply in
match (fm.OP.Flow_mod.command) with
| OP.Flow_mod.ADD
| OP.Flow_mod.MODIFY
| OP.Flow_mod.MODIFY_STRICT ->
flow_mod_add_translate st msg xid fm
| OP.Flow_mod.DELETE
| OP.Flow_mod.DELETE_STRICT ->
flow_mod_del_translate st msg xid fm
end
(*Unsupported switch actions *)
| OP.Port_mod (h, _)
| OP.Queue_get_config_resp (h, _, _)
| OP.Queue_get_config_req (h, _)
- >
send_controller t
( OP.marshal_error OP.REQUEST_BAD_TYPE bits h.OP.Header.xid )
send_controller t
(OP.marshal_error OP.REQUEST_BAD_TYPE bits h.OP.Header.xid) *)
(* Message that should not be received by a switch *)
| OP.Port_status (h, _)
| OP.Flow_removed (h, _)
| OP.Packet_in (h, _)
| OP.Get_config_resp (h, _)
| OP.Barrier_resp h
| OP.Stats_resp (h, _)
| OP.Features_resp (h, _)
| OP.Vendor (h, _)
| OP.Echo_resp (h)
| OP.Error (h, _, _) ->
let h = OP.Header.(create ~xid:h.xid OP.Header.ERROR 0) in
let bits = OP.marshal msg in
send_controller t (OP.Error(h, OP.REQUEST_BAD_TYPE, bits) )
let switch_channel st dpid of_m sock =
let h = OP.Header.(create ~xid:1l HELLO sizeof_ofp_header) in
lwt _ = Openflow.Ofsocket.send_packet sock (OP.Hello h) in
let _ = st.controllers <- (dpid, of_m, sock)::st.controllers in
let continue = ref true in
while_lwt !continue do
try_lwt
lwt ofp = Openflow.Ofsocket.read_packet sock in
process_openflow st dpid sock ofp
with
| Nettypes.Closed ->
let _ = continue := false in
return (cp (sp "[flowvisor-switch] control channel closed\n%!") )
| OP.Unparsed (m, bs) ->
return (cp (sp "[flowvisor-switch] # unparsed! m=%s\n %!" m))
| Ofcontroller_error (xid, error, msg)->
let h = OP.Header.create ~xid OP.Header.ERROR 0 in
send_switch st dpid (OP.Error(h, error, (OP.marshal msg)))
| exn -> return (cp (sp "[flowvisor-switch] ERROR:%s\n"
(Printexc.to_string exn)))
done
(*
* openflow controller threads
* *)
let add_flowvisor_port flv dpid port =
let port_id = flv.portnum in
let _ = flv.portnum <- flv.portnum + 1 in
let phy = OP.Port.translate_port_phy port port_id in
let _ = Hashtbl.add flv.port_map port_id
(dpid, port.OP.Port.port_no, phy) in
lwt _ = Flowvisor_topology.add_port flv.flv_topo dpid port.OP.Port.port_no
port.OP.Port.hw_addr in
let h = OP.Header.(create PORT_STATUS 0 ) in
let status = OP.Port_status(h, (OP.Port.({reason=OP.Port.ADD; desc=phy;}))) in
Lwt_list.iter_p
(fun (dpid, _, conn) ->
Openflow.Ofsocket.send_packet conn status ) flv.controllers
(*
* openflow controller threads
**)
let del_flowvisor_port flv desc =
let h = OP.Header.(create PORT_STATUS 0 ) in
let status = OP.Port_status(h, (OP.Port.({reason=OP.Port.ADD;desc;}))) in
Lwt_list.iter_p
(fun (dpid, _, conn) ->
Openflow.Ofsocket.send_packet conn status ) flv.controllers
let map_flv_port flv dpid port =
(* map the new port *)
let p =
Hashtbl.fold (
fun flv_port (sw_dpid, sw_port, _) r ->
if ((dpid = sw_dpid) &&
(sw_port = port)) then flv_port
else r ) flv.port_map (-1) in
if (p < 0) then OP.Port.Port(port)
else OP.Port.Port (p)
let translate_stat flv dpid f =
Translate match
let _ =
match (f.OP.Flow.of_match.OP.Match.wildcards.OP.Wildcards.in_port,
f.OP.Flow.of_match.OP.Match.in_port) with
| (false, OP.Port.Port(p) ) ->
f.OP.Flow.of_match.OP.Match.in_port <- map_flv_port flv dpid p
| _ -> ()
in
let _ =
f.OP.Flow.action <- List.map
(fun act ->
match act with
| OP.Flow.Output(OP.Port.Port(p), len ) ->
let p = map_flv_port flv dpid p in
OP.Flow.Output(p, len )
| _ -> act) f.OP.Flow.action in
Translate actions
f
let process_switch_channel flv st dpid e =
try_lwt
let _ = if (flv.verbose) then cp (sp "[flowvisor-ctrl] %s\n%!" (OE.string_of_event e)) in
match e with
| OE.Datapath_join(dpid, ports) ->
let _ = cp (sp "[flowvisor-ctrl]+ switch dpid:%Ld\n%!" dpid) in
let _ = Flowvisor_topology.add_channel flv.flv_topo dpid st in
(* Update local state *)
let _ = Hashtbl.replace flv.switches dpid st in
Lwt_list.iter_p (add_flowvisor_port flv dpid) ports
| OE.Datapath_leave(dpid) ->
let _ = (cp(sp "[flowvisor-ctrl]- switch dpid:%Ld\n%!" dpid)) in
let _ = Flowvisor_topology.remove_dpid flv.flv_topo dpid in
(* Need to remove ports and port mapping and disard any state
* pending for replies. *)
Lwt_list.iter_p (del_flowvisor_port flv)
( Hashtbl.fold (fun vp (dp, _, phy) r ->
if (dp = dpid) then
let _ = Hashtbl.remove flv.port_map vp in
phy::r else r) flv.port_map [])
| OE.Packet_in(in_port, reason, buffer_id, data, dpid) -> begin
let m = OP.Match.raw_packet_to_match in_port data in
match (in_port, m.OP.Match.dl_type) with
| (OP.Port.Port(p), 0x88cc) -> begin
match (Flowvisor_topology.process_lldp_packet
flv.flv_topo dpid p data) with
| true -> return ()
| false ->
let in_port = map_flv_port flv dpid p in
let h = OP.Header.(create PACKET_IN 0) in
let pkt = OP.Packet_in.({buffer_id=(-1l);in_port;reason;data;}) in
inform_controllers flv m (OP.Packet_in(h, pkt))
end
| (OP.Port.Port(p), _) when
not (Flowvisor_topology.is_transit_port flv.flv_topo dpid p) -> begin
(* translate the buffer id information *)
let buffer_id = flv.buffer_id_count in
flv.buffer_id_count <- Int32.succ flv.buffer_id_count;
(* generate packet bits *)
let in_port = map_flv_port flv dpid p in
let h = OP.Header.(create PACKET_IN 0) in
let pkt = OP.Packet_in.({buffer_id;in_port;reason;data;}) in
let _ = Hashtbl.add flv.buffer_id_map buffer_id (pkt, dpid) in
inform_controllers flv m (OP.Packet_in(h, pkt))
end
| (OP.Port.Port(p), _) -> return ()
| _ ->
let _ = cp (sp "[flowvisor-ctrl] Invalid port on Packet_in\n%!") in
let h = OP.Header.(create ERROR 0) in
inform_controllers flv m
(OP.Error(h, OP.REQUEST_BAD_STAT, (Cstruct.create 0)))
end
| OE.Flow_removed(of_match, r, dur_s, dur_ns, pkts, bytes, dpid) ->
(* translate packet *)
let new_in_p = map_flv_port flv dpid (of_port of_match.OP.Match.in_port) in
TODO need to pass cookie i d , idle , and priority
let _ = of_match.OP.Match.in_port <- new_in_p in
let pkt =
OP.Flow_removed.(
{of_match; cookie=0L;reason=r; priority=0;idle_timeout=0;
duration_sec=dur_s; duration_nsec=dur_ns; packet_count=pkts;
byte_count=bytes;}) in
let h = OP.Header.(create FLOW_REMOVED 0) in
inform_controllers flv of_match (OP.Flow_removed(h, pkt))
(* TODO: Need to write code to handle stats replies *)
| OE.Flow_stats_reply(xid, more, flows, dpid) -> begin
if Hashtbl.mem flv.xid_map xid then (
let xid_st = Hashtbl.find flv.xid_map xid in
match xid_st.cache with
| Flows fl ->
(* Group reply separation *)
xid_st.cache <- (Flows (fl @ flows));
let flows = List.map (translate_stat flv dpid) flows in
let _ =
if not more then
xid_st.dst <- List.filter (fun a -> a <> dpid) xid_st.dst
in
if (List.length xid_st.dst = 0 ) then
let _ = Hashtbl.remove flv.xid_map xid in
handle_xid flv st xid_st
else
return (Hashtbl.replace flv.xid_map xid xid_st)
| _ -> return ()
) else
return (cp (sp "[flowvisor-ctrl] Unknown stats reply xid\n%!"))
end
| OE.Aggr_flow_stats_reply(xid, pkts, bytes, flows, dpid) -> begin
if (Hashtbl.mem flv.xid_map xid) then (
let xid_st = Hashtbl.find flv.xid_map xid in
match xid_st.cache with
| Aggr aggr ->
(* Group reply separation *)
let aggr =
OP.Stats.({packet_count=(Int64.add pkts aggr.packet_count);
byte_count=(Int64.add bytes aggr.byte_count);
flow_count=(Int32.add flows aggr.flow_count);}) in
let _ = xid_st.cache <- (Aggr aggr) in
let _ =
xid_st.dst <- List.filter (fun a -> a <> dpid) xid_st.dst
in
if (List.length xid_st.dst = 0 ) then
let _ = Hashtbl.remove flv.xid_map xid in
handle_xid flv st xid_st
else
return (Hashtbl.replace flv.xid_map xid xid_st)
| _ -> return ()
) else return ()
end
| OE.Port_stats_reply(xid, more, ports, dpid) -> begin
if (Hashtbl.mem flv.xid_map xid) then (
let xid_st = Hashtbl.find flv.xid_map xid in
match xid_st.cache with
| Port p ->
(* Group reply separation *)
let ports = List.map (fun port ->
let port_id = map_flv_port flv dpid port.OP.Port.port_id in
OP.Port.({port with port_id=(OP.Port.int_of_port port_id);})) ports in
let _ = xid_st.cache <- (Port (p @ ports)) in
let _ = if not more then
xid_st.dst <- List.filter (fun a -> a <> dpid) xid_st.dst in
if (List.length xid_st.dst = 0 ) then
let _ = Hashtbl.remove flv.xid_map xid in
handle_xid flv st xid_st
else
let _ = Hashtbl.replace flv.xid_map xid xid_st in
return ()
| _ -> return ()
) else return ()
end
| OE.Table_stats_reply(xid, more, tables, dpid) ->
return ()
| OE.Port_status(reason, port, dpid) ->
(* TODO: send a port withdrawal to all controllers *)
add_flowvisor_port flv dpid port
| _ -> return (cp "[flowvisor-ctrl] Unsupported event\n%!")
with Not_found -> return (cp(sp "[flowvisor-ctrl] ignore pkt of non existing state\n%!"))
let init flv st =
(* register all the required handlers *)
let fn = process_switch_channel flv in
OC.register_cb st OE.DATAPATH_JOIN fn;
OC.register_cb st OE.DATAPATH_LEAVE fn;
OC.register_cb st OE.PACKET_IN fn;
OC.register_cb st OE.FLOW_REMOVED fn;
OC.register_cb st OE.FLOW_STATS_REPLY fn;
OC.register_cb st OE.AGGR_FLOW_STATS_REPLY fn;
OC.register_cb st OE.PORT_STATUS_CHANGE fn;
OC.register_cb st OE.TABLE_STATS_REPLY fn
let create_flowvisor ?(verbose=false) () =
let ret = init_flowvisor verbose (Flowvisor_topology.init_topology ()) in
let _ = ignore_result (Flowvisor_topology.discover ret.flv_topo) in
ret
let add_slice mgr flv of_m dst dpid =
ignore_result (
while_lwt true do
let switch_connect (addr, port) t =
let rs = Ipaddr.V4.to_string addr in
try_lwt
let _ = cp (sp "[flowvisor-switch]+ switch %s:%d\n%!" rs port) in
Trigger the dance between the 2 nodes
let sock = Openflow.Ofsocket.init_socket_conn_state t in
switch_channel flv dpid of_m sock
with exn ->
return (cp(sp "[flowvisorswitch]- switch %s:%d %s\n%!" rs port (Printexc.to_string exn)))
in
Net.Channel.connect mgr ( `TCPv4 (None, dst, (switch_connect dst) ) )
done)
let listen st mgr loc = OC.listen mgr loc (init st)
let local_listen st conn =
OC.local_connect (OC.init_controller (init st)) conn
let remove_slice _ _ = ()
let add_local_slice flv of_m conn dpid =
ignore_result ( switch_channel flv dpid of_m conn)
(* TODO Need to store thread for termination on remove_slice *)
| null | https://raw.githubusercontent.com/mirage/ocaml-openflow/dcda113745e8edc61b5508eb8ac2d1e864e1a2df/lib/flowvisor.ml | ocaml | fake switch state to be exposed to controllers
counters
controller and switch storage
Mapping transients id values
topology managment module
xid buffer controller functions
communication primitives
find the controller that should handle the packet in
************************************************
* Switch OpenFlow control channel
************************************************
if no buffer id included, send the data section of the
* packet_out
if we have a buffer id in cache, use those data
let _ = pp "sending packet from port %d to port %d\n%!"
* (OP.Port.int_of_port inp) (in_p) in
output packet to the last hop of the path
output packet to the last hop of the path
for the non-output action, populate the new action list
let _ = pp "[flowvisor-switch] mapping a path between %Ld:%s - %Ld:%s\n%!"
in_dpid (OP.Port.string_of_port in_port)
out_dpid (OP.Port.string_of_port out_port) in
let path = List.rev path in
if we have a buffer id in cache, use those data
if buffer id is unknown, send error
Need a spanning tree maybe for this?
Reply to ECHO requests
TODO Need to translate the xid here
TODO out_port needs processing. if dpid are between
* different switches need to define the outport
* as the port of the interconnection link
TODO out_port needs processing. if dpid are between
* different switches need to define the outport as the
* port of the interconnection link
TODO just reply for now. need to check this with all switches
let xid = get_new_xid dpid in
Check if controller has the right to send traffic on the specific subnet
Unsupported switch actions
Message that should not be received by a switch
* openflow controller threads
*
* openflow controller threads
*
map the new port
Update local state
Need to remove ports and port mapping and disard any state
* pending for replies.
translate the buffer id information
generate packet bits
translate packet
TODO: Need to write code to handle stats replies
Group reply separation
Group reply separation
Group reply separation
TODO: send a port withdrawal to all controllers
register all the required handlers
TODO Need to store thread for termination on remove_slice |
* Copyright ( c ) 2011 < >
*
* 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) 2011 Charalampos Rotsos <>
*
* 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 Net
module OP = Openflow.Ofpacket
module OC = Openflow.Ofcontroller
module OE = Openflow.Ofcontroller.Event
module OSK = Openflow.Ofsocket
open OP
open OP.Flow
open OP.Flow_mod
open OP.Match
let sp = Printf.sprintf
let cp = OS.Console.log
let to_port = OP.Port.port_of_int
let of_port = OP.Port.int_of_port
exception Ofcontroller_error of int32 * OP.error_code * OP.t
exception Ofswitch_error of int64 * int32 * OP.error_code * OP.t
type port = {
port_id: int;
port_name: string;
phy: OP.Port.phy;
origin_dpid: int64;
origin_port_id: int;
}
type cached_reply =
| Flows of OP.Flow.stats list
| Aggr of OP.Stats.aggregate
| Table of OP.Stats.table
| Port of OP.Port.stats list
| No_reply
type xid_state = {
xid : int32;
src : int64;
mutable dst : int64 list;
ts : float;
mutable cache : cached_reply;
}
type t = {
verbose : bool;
mutable errornum : int32;
mutable portnum : int;
mutable xid_count : int32;
mutable buffer_id_count: int32;
mutable controllers : (int64 * OP.Match.t *Openflow.Ofsocket.conn_state ) list;
switches : (int64, OC.t) Hashtbl.t;
xid_map : (int32, xid_state) Hashtbl.t;
port_map : (int, (int64 * int * OP.Port.phy)) Hashtbl.t;
buffer_id_map : (int32, (OP.Packet_in.t * int64)) Hashtbl.t;
flv_topo: Flowvisor_topology.t;
}
timeout pending queries after 3 minutes
let timeout = 180.
let supported_actions () =
OP.Switch.(
{output=true;set_vlan_id=true;set_vlan_pcp=true;strip_vlan=true;
set_dl_src=true; set_dl_dst=true; set_nw_src=true; set_nw_dst=true;
set_nw_tos=true; set_tp_src=true; set_tp_dst=true; enqueue=false;
vendor=false; })
let supported_capabilities () =
OP.Switch.({flow_stats=true;table_stats=true;port_stats=true;stp=false;
ip_reasm=false;queue_stats=false;arp_match_ip=true;})
let switch_features datapath_id ports =
OP.Switch.({datapath_id; n_buffers=0l; n_tables=(char_of_int 1);
capabilities=(supported_capabilities ());
actions=(supported_actions ()); ports;})
let init_flowvisor verbose flv_topo =
{verbose; errornum=0l; portnum=10; xid_count=0l;
port_map=(Hashtbl.create 64);
controllers=[]; buffer_id_map=(Hashtbl.create 64);
buffer_id_count=0l; xid_map=(Hashtbl.create 64);
switches=(Hashtbl.create 64); flv_topo; }
let match_dpid_buffer_id st dpid buffer_id =
try
let (_, dst_dpid) = Hashtbl.find st.buffer_id_map buffer_id in
(dpid = dst_dpid)
with Not_found -> false
let get_new_xid old_xid st src dst cache =
let xid = st.xid_count in
let _ = st.xid_count <- Int32.add st.xid_count 1l in
let r = {xid; src; dst; ts=(OS.Clock.time ()); cache;} in
let _ = Hashtbl.replace st.xid_map xid r in
xid
let handle_xid flv st xid_st =
match xid_st.cache with
| Flows flows ->
let stats = OP.Stats.({st_ty=FLOW; more=true;}) in
let (_, _, t) = List.find (
fun (dpid, _, _) -> dpid = xid_st.src )
flv.controllers in
lwt (_, flows) =
Lwt_list. fold_right_s (
fun fl (sz, flows) ->
let fl_sz = OP.Flow.flow_stats_len fl in
if (sz + fl_sz > 0xffff) then
let r = OP.Stats.Flow_resp(stats, flows) in
let h = OP.Header.create ~xid:(xid_st.xid) OP.Header.STATS_RESP 0 in
lwt _ = Openflow.Ofsocket.send_packet t (OP.Stats_resp (h, r)) in
return ((OP.Header.get_len + OP.Stats.get_resp_hdr_size + fl_sz), [fl])
else
return ((sz + fl_sz), (fl::flows)) )
flows ((OP.Header.get_len + OP.Stats.get_resp_hdr_size), []) in
let stats = OP.Stats.({st_ty=FLOW; more=false;}) in
let r = OP.Stats.Flow_resp(stats, flows) in
let h = OP.Header.create ~xid:xid_st.xid OP.Header.STATS_RESP 0 in
Openflow.Ofsocket.send_packet t (OP.Stats_resp (h, r))
| _ -> return ()
let timeout_xid flv st =
while_lwt true do
let time = OS.Clock.time () in
let xid =
Hashtbl.fold (
fun xid r ret ->
if (r.ts+.timeout>time) then
let _ = Hashtbl.remove st.xid_map xid in
r :: ret
else ret
) st.xid_map [] in
lwt _ = Lwt_list.iter_p (handle_xid flv st) xid in
OS.Time.sleep 600.
done
let switch_dpid flv = Hashtbl.fold (fun dpid _ r -> r@[dpid]) flv.switches []
let switch_chan_dpid flv = Hashtbl.fold (fun dpid ch r -> (dpid,ch)::r) flv.switches []
let dpid_of_port st inp =
try
let (in_dpid, _, _) = Hashtbl.find st.port_map (of_port inp) in
in_dpid
with Not_found -> 0L
let port_of_port st inp =
try
let (_, inp, _) = Hashtbl.find st.port_map (of_port inp) in
OP.Port.Port(inp)
with Not_found -> OP.Port.No_port
let dpid_port_of_port_exn st inp xid msg =
try
let (dpid, p, _) = Hashtbl.find st.port_map (of_port inp) in
(dpid, OP.Port.Port(p))
with Not_found ->
raise (Ofcontroller_error (xid, OP.ACTION_BAD_OUT_PORT, msg) )
let send_all_switches st msg =
Lwt_list.iter_p (
fun (dpid, ch) -> OC.send_data ch dpid msg)
(Hashtbl.fold (fun dpid ch c -> c @[(dpid, ch)]) st.switches [])
let send_switch st dpid msg =
try_lwt
let ch = Hashtbl.find st.switches dpid in
OC.send_data ch dpid msg
with Not_found -> return (cp (sp "[flowvisor] unregister dpid %Ld\n%!" dpid))
let send_controller t msg = OSK.send_packet t msg
let inform_controllers flv m msg =
Lwt_list.iter_p
(fun (_, rule, t) ->
if (OP.Match.flow_match_compare rule m rule.OP.Match.wildcards) then
Openflow.Ofsocket.send_packet t msg
else return ()) flv.controllers
let packet_out_create st msg xid inp bid data actions =
let data =
match (bid) with
| -1l -> data
| bid when (Hashtbl.mem st.buffer_id_map bid) ->
let (pkt, _ ) = Hashtbl.find st.buffer_id_map bid in
let _ = Hashtbl.remove st.buffer_id_map bid in
pkt.OP.Packet_in.data
| _ -> raise (Ofcontroller_error(xid, OP.REQUEST_BUFFER_UNKNOWN, msg) )
in
let in_port = port_of_port st inp in
let m = OP.Packet_out.create ~buffer_id:(-1l)
~actions ~in_port ~data () in
let h = OP.Header.(create ~xid PACKET_OUT 0) in
OP.Packet_out (h,m)
let rec pkt_out_process st xid inp bid data msg acts = function
| (OP.Flow.Output(OP.Port.All, len))::tail
| (OP.Flow.Output(OP.Port.Flood, len))::tail -> begin
let actions = acts @ [OP.Flow.Output(OP.Port.Flood, len)] in
OP.Port . None is not the appropriate way to handle this . Need to find the
* port that connects the two switches probably .
* port that connects the two switches probably. *)
let in_dpid = dpid_of_port st inp in
let msg = packet_out_create st msg xid OP.Port.No_port (-1l) data actions in
lwt _ =
Lwt_list.iter_p (
fun (dpid, ch) ->
if (dpid = in_dpid) then
OC.send_data ch dpid
(packet_out_create st msg xid inp (-1l) data actions)
else
OC.send_data ch dpid msg
) (Hashtbl.fold (fun dpid ch c -> c @[(dpid, ch)]) st.switches []) in
pkt_out_process st xid inp bid data msg acts tail
end
| (OP.Flow.Output(OP.Port.In_port, len))::tail -> begin
let (dpid, out_p) = dpid_port_of_port_exn st inp xid msg in
let actions = acts @ [OP.Flow.Output(OP.Port.In_port, len)] in
lwt _ = send_switch st dpid
(packet_out_create st msg xid out_p bid data actions) in
pkt_out_process st xid inp bid data msg acts tail
end
| (OP.Flow.Output(OP.Port.Port(p), len))::tail -> begin
let (dpid, out_p) = dpid_port_of_port_exn st (to_port p) xid msg in
let actions = acts @ [OP.Flow.Output(out_p, len)] in
let msg = packet_out_create st msg xid inp bid data actions in
lwt _ = send_switch st dpid
(packet_out_create st msg xid inp bid data actions) in
pkt_out_process st xid inp bid data msg acts tail
end
| (OP.Flow.Output(OP.Port.Controller, len))::tail
| (OP.Flow.Output(OP.Port.Table, len))::tail
| (OP.Flow.Output(OP.Port.Local, len))::tail
| (OP.Flow.Output(OP.Port.No_port, len))::tail
| (OP.Flow.Output(OP.Port.Normal, len))::tail ->
raise (Ofcontroller_error (xid, OP.REQUEST_BAD_STAT, msg) )
| a :: tail ->
pkt_out_process st xid inp bid data msg (acts @ [a]) tail
| [] -> return ()
let map_path flv in_dpid in_port out_dpid out_port =
if (in_dpid = out_dpid) then [(out_dpid, in_port, out_port)]
else
Flowvisor_topology.find_dpid_path flv.flv_topo
in_dpid in_port out_dpid out_port
let _ =
List.iter (
fun ( dp , in_p , out_p ) - >
pp " % s:%Ld:%s - > "
( OP.Port.string_of_port in_p )
dp ( OP.Port.string_of_port out_p )
) path in
let _ = pp " \n% ! " in
path
List.iter (
fun (dp, in_p, out_p) ->
pp "%s:%Ld:%s -> "
(OP.Port.string_of_port in_p)
dp (OP.Port.string_of_port out_p)
) path in
let _ = pp "\n%!" in
path *)
TODO fixme ! ! ! !
let map_spanning_tree flv in_dpid in_port = []
let rec send_flow_mod_to_path st xid msg pkt len actions path =
let h = OP.Header.create ~xid OP.Header.FLOW_MOD 0 in
match path with
| [] -> return ()
| [(dpid, in_port, out_port)] -> begin
let actions = actions @ [OP.Flow.Output(out_port, len)] in
let _ = pkt.of_match.in_port <- in_port in
let fm = OP.Flow_mod.(
{pkt with buffer_id=(-1l);out_port=(OP.Port.No_port);actions;}) in
lwt _ = send_switch st dpid (OP.Flow_mod(h, fm)) in
match (pkt.buffer_id) with
| -1l -> return ()
| bid when (Hashtbl.mem st.buffer_id_map bid) ->
let (pkt, _ ) = Hashtbl.find st.buffer_id_map bid in
let msg = packet_out_create st msg xid (OP.Port.No_port)
(-1l) (pkt.OP.Packet_in.data) actions in
lwt _ = send_switch st dpid msg in
return ()
| _ ->
raise (Ofcontroller_error(xid, OP.REQUEST_BUFFER_UNKNOWN, msg))
end
| ((dpid, in_port, out_port)::rest) -> begin
let _ = pkt.of_match.in_port <- in_port in
let fm = OP.Flow_mod.(
{pkt with buffer_id=(-1l);out_port=(OP.Port.No_port);
actions=( [OP.Flow.Output(out_port, len)] );}) in
lwt _ = send_switch st dpid (OP.Flow_mod(h, fm)) in
send_flow_mod_to_path st xid msg pkt len actions rest
end
let rec flow_mod_translate_inner st msg xid pkt in_dpid in_port acts = function
| (OP.Flow.Output(OP.Port.All, len))::tail
| (OP.Flow.Output(OP.Port.Flood, len))::tail ->
lwt _ = send_flow_mod_to_path st xid msg pkt len acts
(map_spanning_tree st in_dpid in_port) in
flow_mod_translate_inner st msg xid pkt in_dpid in_port acts tail
| (OP.Flow.Output(OP.Port.In_port, len))::tail ->
lwt _ = send_flow_mod_to_path st xid msg pkt len acts
[(in_dpid, OP.Port.Port(in_port), OP.Port.In_port)] in
flow_mod_translate_inner st msg xid pkt in_dpid in_port acts tail
| (OP.Flow.Output(OP.Port.Controller, len))::tail ->
lwt _ = send_flow_mod_to_path st xid msg pkt len acts
[(in_dpid, OP.Port.Port(in_port), OP.Port.Controller)] in
flow_mod_translate_inner st msg xid pkt in_dpid in_port acts tail
| (OP.Flow.Output(OP.Port.Port(p), len))::tail ->
let (out_dpid, out_port) = dpid_port_of_port_exn st (to_port p) xid msg in
lwt _ = send_flow_mod_to_path st xid msg pkt len acts
(map_path st in_dpid (OP.Port.Port(in_port) )
out_dpid out_port) in
flow_mod_translate_inner st msg xid pkt in_dpid in_port acts tail
| (OP.Flow.Output(OP.Port.Table, _))::_
| (OP.Flow.Output(OP.Port.Local, _))::_
| (OP.Flow.Output(OP.Port.Normal, _))::_ ->
raise (Ofcontroller_error (xid, OP.REQUEST_BAD_STAT, msg) )
| a :: tail -> flow_mod_translate_inner st msg xid pkt in_dpid in_port (acts@[a]) tail
| [] -> return ()
let flow_mod_add_translate st msg xid pkt =
let (in_dpid, in_port) = dpid_port_of_port_exn st pkt.of_match.in_port xid msg in
flow_mod_translate_inner st msg xid pkt in_dpid (of_port in_port) [] pkt.actions
let flow_mod_del_translate st msg xid pkt =
match (pkt.of_match.OP.Match.wildcards.OP.Wildcards.in_port,
pkt.of_match.OP.Match.in_port, pkt.OP.Flow_mod.out_port) with
| (false, OP.Port.Local, OP.Port.No_port)
| (true, _, OP.Port.No_port) ->
let h = OP.Header.(create ~xid FLOW_MOD 0) in
send_all_switches st (OP.Flow_mod(h, pkt))
| (false, OP.Port.Port(p), OP.Port.No_port) ->
let (dpid, port) = dpid_port_of_port_exn st (to_port p) xid msg in
let _ = pkt.of_match.in_port <- port in
let h = OP.Header.(create ~xid FLOW_MOD 0) in
send_switch st dpid (OP.Flow_mod(h, pkt))
| (false, OP.Port.Port(in_p), OP.Port.Port(out_p)) ->
let (in_dpid, in_port) = dpid_port_of_port_exn st
pkt.of_match.OP.Match.in_port xid msg in
let (out_dpid, out_port) = dpid_port_of_port_exn st
pkt.OP.Flow_mod.out_port xid msg in
lwt _ = send_flow_mod_to_path st xid msg pkt 0 []
(map_path st in_dpid in_port out_dpid out_port) in
return ()
| _ -> raise (Ofcontroller_error (xid, OP.REQUEST_BAD_STAT, msg) )
let process_openflow st dpid t msg =
let _ = if st.verbose then cp (sp "[flowvisor-switch] %s\n%!" (OP.to_string msg)) in
match msg with
| OP.Hello (h) -> return ()
let open OP.Header in
send_controller t (OP.Echo_resp (create ECHO_RESP ~xid:h.xid get_len))
| OP.Features_req (h) ->
let h = OP.Header.(create FEATURES_RESP ~xid:h.xid 0) in
let f = switch_features dpid
(Hashtbl.fold (fun _ (_, _, p) r -> p::r)
st.port_map []) in
send_controller t (OP.Features_resp(h, f))
| OP.Stats_req(h, req) -> begin
match req with
| OP.Stats.Desc_req(req) ->
let open OP.Stats in
let desc = { imfr_desc="Mirage"; hw_desc="Mirage";
sw_desc="Mirage_flowvisor"; serial_num="0.1";
dp_desc="Mirage";} in
let resp_h = {st_ty=DESC;more=false;} in
send_controller t
(OP.Stats_resp(h, (Desc_resp(resp_h,desc))))
| OP.Stats.Flow_req(req_h, of_match, table_id, out_port) -> begin
TODO Need to consider the table_id and the out_port and
* split reply over multiple openflow packets if they do n't
* fit a single packet .
* split reply over multiple openflow packets if they don't
* fit a single packet. *)
match (of_match.OP.Match.wildcards.OP.Wildcards.in_port,
(of_match.OP.Match.in_port)) with
| (false, OP.Port.Port(p)) ->
let (dst_dpid, out_port) = dpid_port_of_port_exn st
of_match.OP.Match.in_port h.OP.Header.xid msg in
let xid = get_new_xid h.OP.Header.xid st dst_dpid [dpid] (Flows [])in
let h = OP.Header.(create STATS_RESP ~xid 0) in
let of_match = OP.Match.translate_port of_match out_port in
let req = OP.Stats.(
Flow_req(req_h, of_match, table_id, out_port)) in
send_switch st dst_dpid (OP.Stats_req(h, req))
| (_, _) ->
let req = OP.Stats.(Flow_req(req_h, of_match,table_id, out_port)) in
let xid = get_new_xid h.OP.Header.xid st dpid (switch_dpid st) (Flows []) in
let h = OP.Header.(create STATS_RESP ~xid 0) in
send_all_switches st (OP.Stats_req(h, req))
end
| OP.Stats.Aggregate_req (req_h, of_match, table_id, out_port) ->
begin
let open OP.Stats in
let open OP.Header in
let cache = Aggr ({packet_count=0L; byte_count=0L;flow_count=0l;}) in
match OP.Match.(of_match.wildcards.OP.Wildcards.in_port,(of_match.in_port)) with
| (false, OP.Port.Port(p)) ->
let (dst_dpid, port) = dpid_port_of_port_exn st of_match.in_port h.xid msg in
let xid = get_new_xid h.xid st dpid [dst_dpid] cache in
let h = { h with xid;} in
let _ = of_match.in_port <- port in
let m = Aggregate_req(req_h, of_match, table_id, out_port) in
send_switch st dst_dpid (OP.Stats_req(h, m))
| (_, _) ->
let open OP.Header in
let h = {h with xid=(get_new_xid h.xid st dpid
(switch_dpid st) cache);} in
send_all_switches st (OP.Stats_req(h, req))
end
| OP.Stats.Table_req(req_h) ->
let open OP.Header in
let cache = Table OP.Stats.(init_table_stats (OP.Stats.table_id_of_int 1)
"mirage" (OP.Wildcards.full_wildcard ()) ) in
let xid = get_new_xid h.xid st dpid (switch_dpid st) cache in
let h = {h with xid;} in
send_all_switches st (OP.Stats_req(h, req))
| OP.Stats.Port_req(req_h, port) -> begin
match port with
| OP.Port.No_port ->
let open OP.Header in
let xid = get_new_xid h.xid st dpid (switch_dpid st) (Port []) in
let h = ({h with xid;}) in
send_all_switches st (OP.Stats_req(h, req))
| OP.Port.Port(_) ->
let open OP.Header in
let (dst_dpid, port) = dpid_port_of_port_exn st port h.xid msg in
let xid = get_new_xid h.xid st dpid [dst_dpid] (Port []) in
let h = {h with xid;} in
let m = OP.Stats.(Port_req(req_h, port)) in
send_all_switches st (OP.Stats_req(h, m))
| _ ->
raise (Ofcontroller_error (h.OP.Header.xid, OP.QUEUE_OP_BAD_PORT, msg))
end
| _ ->
raise (Ofcontroller_error (h.OP.Header.xid, OP.REQUEST_BAD_STAT, msg))
end
| OP.Get_config_req(h) ->
TODO make a custom reply tothe query
let h = OP.Header.({h with ty=FEATURES_RESP}) in
send_controller t (OP.Get_config_resp(h, OP.Switch.init_switch_config))
| OP.Barrier_req(h) ->
let _ = cp (sp "BARRIER_REQ: %s\n%!" (OP.Header.header_to_string h)) in
send_controller t (OP.Barrier_resp (OP.Header.({h with ty=BARRIER_RESP;})) )
| OP.Packet_out(h, pkt) -> begin
let _ = if st.verbose then cp (sp "[flowvisor-switch] PACKET_OUT: %s\n%!"
(OP.Packet_out.packet_out_to_string pkt)) in
try_lwt
OP.Packet_out.(pkt_out_process st h.OP.Header.xid pkt.in_port
pkt.buffer_id pkt.data msg [] pkt.actions )
with exn ->
return (cp (sp "[flowvisor-switch] packet_out message error %s\n%!"
(Printexc.to_string exn)))
end
| OP.Flow_mod(h,fm) -> begin
let _ = if st.verbose then cp (sp "[flowvisor-switch] FLOW_MOD: %s\n%!"
(OP.Flow_mod.flow_mod_to_string fm)) in
let xid = get_new_xid h.OP.Header.xid st dpid (switch_dpid st) No_reply in
match (fm.OP.Flow_mod.command) with
| OP.Flow_mod.ADD
| OP.Flow_mod.MODIFY
| OP.Flow_mod.MODIFY_STRICT ->
flow_mod_add_translate st msg xid fm
| OP.Flow_mod.DELETE
| OP.Flow_mod.DELETE_STRICT ->
flow_mod_del_translate st msg xid fm
end
| OP.Port_mod (h, _)
| OP.Queue_get_config_resp (h, _, _)
| OP.Queue_get_config_req (h, _)
- >
send_controller t
( OP.marshal_error OP.REQUEST_BAD_TYPE bits h.OP.Header.xid )
send_controller t
(OP.marshal_error OP.REQUEST_BAD_TYPE bits h.OP.Header.xid) *)
| OP.Port_status (h, _)
| OP.Flow_removed (h, _)
| OP.Packet_in (h, _)
| OP.Get_config_resp (h, _)
| OP.Barrier_resp h
| OP.Stats_resp (h, _)
| OP.Features_resp (h, _)
| OP.Vendor (h, _)
| OP.Echo_resp (h)
| OP.Error (h, _, _) ->
let h = OP.Header.(create ~xid:h.xid OP.Header.ERROR 0) in
let bits = OP.marshal msg in
send_controller t (OP.Error(h, OP.REQUEST_BAD_TYPE, bits) )
let switch_channel st dpid of_m sock =
let h = OP.Header.(create ~xid:1l HELLO sizeof_ofp_header) in
lwt _ = Openflow.Ofsocket.send_packet sock (OP.Hello h) in
let _ = st.controllers <- (dpid, of_m, sock)::st.controllers in
let continue = ref true in
while_lwt !continue do
try_lwt
lwt ofp = Openflow.Ofsocket.read_packet sock in
process_openflow st dpid sock ofp
with
| Nettypes.Closed ->
let _ = continue := false in
return (cp (sp "[flowvisor-switch] control channel closed\n%!") )
| OP.Unparsed (m, bs) ->
return (cp (sp "[flowvisor-switch] # unparsed! m=%s\n %!" m))
| Ofcontroller_error (xid, error, msg)->
let h = OP.Header.create ~xid OP.Header.ERROR 0 in
send_switch st dpid (OP.Error(h, error, (OP.marshal msg)))
| exn -> return (cp (sp "[flowvisor-switch] ERROR:%s\n"
(Printexc.to_string exn)))
done
let add_flowvisor_port flv dpid port =
let port_id = flv.portnum in
let _ = flv.portnum <- flv.portnum + 1 in
let phy = OP.Port.translate_port_phy port port_id in
let _ = Hashtbl.add flv.port_map port_id
(dpid, port.OP.Port.port_no, phy) in
lwt _ = Flowvisor_topology.add_port flv.flv_topo dpid port.OP.Port.port_no
port.OP.Port.hw_addr in
let h = OP.Header.(create PORT_STATUS 0 ) in
let status = OP.Port_status(h, (OP.Port.({reason=OP.Port.ADD; desc=phy;}))) in
Lwt_list.iter_p
(fun (dpid, _, conn) ->
Openflow.Ofsocket.send_packet conn status ) flv.controllers
let del_flowvisor_port flv desc =
let h = OP.Header.(create PORT_STATUS 0 ) in
let status = OP.Port_status(h, (OP.Port.({reason=OP.Port.ADD;desc;}))) in
Lwt_list.iter_p
(fun (dpid, _, conn) ->
Openflow.Ofsocket.send_packet conn status ) flv.controllers
let map_flv_port flv dpid port =
let p =
Hashtbl.fold (
fun flv_port (sw_dpid, sw_port, _) r ->
if ((dpid = sw_dpid) &&
(sw_port = port)) then flv_port
else r ) flv.port_map (-1) in
if (p < 0) then OP.Port.Port(port)
else OP.Port.Port (p)
let translate_stat flv dpid f =
Translate match
let _ =
match (f.OP.Flow.of_match.OP.Match.wildcards.OP.Wildcards.in_port,
f.OP.Flow.of_match.OP.Match.in_port) with
| (false, OP.Port.Port(p) ) ->
f.OP.Flow.of_match.OP.Match.in_port <- map_flv_port flv dpid p
| _ -> ()
in
let _ =
f.OP.Flow.action <- List.map
(fun act ->
match act with
| OP.Flow.Output(OP.Port.Port(p), len ) ->
let p = map_flv_port flv dpid p in
OP.Flow.Output(p, len )
| _ -> act) f.OP.Flow.action in
Translate actions
f
let process_switch_channel flv st dpid e =
try_lwt
let _ = if (flv.verbose) then cp (sp "[flowvisor-ctrl] %s\n%!" (OE.string_of_event e)) in
match e with
| OE.Datapath_join(dpid, ports) ->
let _ = cp (sp "[flowvisor-ctrl]+ switch dpid:%Ld\n%!" dpid) in
let _ = Flowvisor_topology.add_channel flv.flv_topo dpid st in
let _ = Hashtbl.replace flv.switches dpid st in
Lwt_list.iter_p (add_flowvisor_port flv dpid) ports
| OE.Datapath_leave(dpid) ->
let _ = (cp(sp "[flowvisor-ctrl]- switch dpid:%Ld\n%!" dpid)) in
let _ = Flowvisor_topology.remove_dpid flv.flv_topo dpid in
Lwt_list.iter_p (del_flowvisor_port flv)
( Hashtbl.fold (fun vp (dp, _, phy) r ->
if (dp = dpid) then
let _ = Hashtbl.remove flv.port_map vp in
phy::r else r) flv.port_map [])
| OE.Packet_in(in_port, reason, buffer_id, data, dpid) -> begin
let m = OP.Match.raw_packet_to_match in_port data in
match (in_port, m.OP.Match.dl_type) with
| (OP.Port.Port(p), 0x88cc) -> begin
match (Flowvisor_topology.process_lldp_packet
flv.flv_topo dpid p data) with
| true -> return ()
| false ->
let in_port = map_flv_port flv dpid p in
let h = OP.Header.(create PACKET_IN 0) in
let pkt = OP.Packet_in.({buffer_id=(-1l);in_port;reason;data;}) in
inform_controllers flv m (OP.Packet_in(h, pkt))
end
| (OP.Port.Port(p), _) when
not (Flowvisor_topology.is_transit_port flv.flv_topo dpid p) -> begin
let buffer_id = flv.buffer_id_count in
flv.buffer_id_count <- Int32.succ flv.buffer_id_count;
let in_port = map_flv_port flv dpid p in
let h = OP.Header.(create PACKET_IN 0) in
let pkt = OP.Packet_in.({buffer_id;in_port;reason;data;}) in
let _ = Hashtbl.add flv.buffer_id_map buffer_id (pkt, dpid) in
inform_controllers flv m (OP.Packet_in(h, pkt))
end
| (OP.Port.Port(p), _) -> return ()
| _ ->
let _ = cp (sp "[flowvisor-ctrl] Invalid port on Packet_in\n%!") in
let h = OP.Header.(create ERROR 0) in
inform_controllers flv m
(OP.Error(h, OP.REQUEST_BAD_STAT, (Cstruct.create 0)))
end
| OE.Flow_removed(of_match, r, dur_s, dur_ns, pkts, bytes, dpid) ->
let new_in_p = map_flv_port flv dpid (of_port of_match.OP.Match.in_port) in
TODO need to pass cookie i d , idle , and priority
let _ = of_match.OP.Match.in_port <- new_in_p in
let pkt =
OP.Flow_removed.(
{of_match; cookie=0L;reason=r; priority=0;idle_timeout=0;
duration_sec=dur_s; duration_nsec=dur_ns; packet_count=pkts;
byte_count=bytes;}) in
let h = OP.Header.(create FLOW_REMOVED 0) in
inform_controllers flv of_match (OP.Flow_removed(h, pkt))
| OE.Flow_stats_reply(xid, more, flows, dpid) -> begin
if Hashtbl.mem flv.xid_map xid then (
let xid_st = Hashtbl.find flv.xid_map xid in
match xid_st.cache with
| Flows fl ->
xid_st.cache <- (Flows (fl @ flows));
let flows = List.map (translate_stat flv dpid) flows in
let _ =
if not more then
xid_st.dst <- List.filter (fun a -> a <> dpid) xid_st.dst
in
if (List.length xid_st.dst = 0 ) then
let _ = Hashtbl.remove flv.xid_map xid in
handle_xid flv st xid_st
else
return (Hashtbl.replace flv.xid_map xid xid_st)
| _ -> return ()
) else
return (cp (sp "[flowvisor-ctrl] Unknown stats reply xid\n%!"))
end
| OE.Aggr_flow_stats_reply(xid, pkts, bytes, flows, dpid) -> begin
if (Hashtbl.mem flv.xid_map xid) then (
let xid_st = Hashtbl.find flv.xid_map xid in
match xid_st.cache with
| Aggr aggr ->
let aggr =
OP.Stats.({packet_count=(Int64.add pkts aggr.packet_count);
byte_count=(Int64.add bytes aggr.byte_count);
flow_count=(Int32.add flows aggr.flow_count);}) in
let _ = xid_st.cache <- (Aggr aggr) in
let _ =
xid_st.dst <- List.filter (fun a -> a <> dpid) xid_st.dst
in
if (List.length xid_st.dst = 0 ) then
let _ = Hashtbl.remove flv.xid_map xid in
handle_xid flv st xid_st
else
return (Hashtbl.replace flv.xid_map xid xid_st)
| _ -> return ()
) else return ()
end
| OE.Port_stats_reply(xid, more, ports, dpid) -> begin
if (Hashtbl.mem flv.xid_map xid) then (
let xid_st = Hashtbl.find flv.xid_map xid in
match xid_st.cache with
| Port p ->
let ports = List.map (fun port ->
let port_id = map_flv_port flv dpid port.OP.Port.port_id in
OP.Port.({port with port_id=(OP.Port.int_of_port port_id);})) ports in
let _ = xid_st.cache <- (Port (p @ ports)) in
let _ = if not more then
xid_st.dst <- List.filter (fun a -> a <> dpid) xid_st.dst in
if (List.length xid_st.dst = 0 ) then
let _ = Hashtbl.remove flv.xid_map xid in
handle_xid flv st xid_st
else
let _ = Hashtbl.replace flv.xid_map xid xid_st in
return ()
| _ -> return ()
) else return ()
end
| OE.Table_stats_reply(xid, more, tables, dpid) ->
return ()
| OE.Port_status(reason, port, dpid) ->
add_flowvisor_port flv dpid port
| _ -> return (cp "[flowvisor-ctrl] Unsupported event\n%!")
with Not_found -> return (cp(sp "[flowvisor-ctrl] ignore pkt of non existing state\n%!"))
let init flv st =
let fn = process_switch_channel flv in
OC.register_cb st OE.DATAPATH_JOIN fn;
OC.register_cb st OE.DATAPATH_LEAVE fn;
OC.register_cb st OE.PACKET_IN fn;
OC.register_cb st OE.FLOW_REMOVED fn;
OC.register_cb st OE.FLOW_STATS_REPLY fn;
OC.register_cb st OE.AGGR_FLOW_STATS_REPLY fn;
OC.register_cb st OE.PORT_STATUS_CHANGE fn;
OC.register_cb st OE.TABLE_STATS_REPLY fn
let create_flowvisor ?(verbose=false) () =
let ret = init_flowvisor verbose (Flowvisor_topology.init_topology ()) in
let _ = ignore_result (Flowvisor_topology.discover ret.flv_topo) in
ret
let add_slice mgr flv of_m dst dpid =
ignore_result (
while_lwt true do
let switch_connect (addr, port) t =
let rs = Ipaddr.V4.to_string addr in
try_lwt
let _ = cp (sp "[flowvisor-switch]+ switch %s:%d\n%!" rs port) in
Trigger the dance between the 2 nodes
let sock = Openflow.Ofsocket.init_socket_conn_state t in
switch_channel flv dpid of_m sock
with exn ->
return (cp(sp "[flowvisorswitch]- switch %s:%d %s\n%!" rs port (Printexc.to_string exn)))
in
Net.Channel.connect mgr ( `TCPv4 (None, dst, (switch_connect dst) ) )
done)
let listen st mgr loc = OC.listen mgr loc (init st)
let local_listen st conn =
OC.local_connect (OC.init_controller (init st)) conn
let remove_slice _ _ = ()
let add_local_slice flv of_m conn dpid =
ignore_result ( switch_channel flv dpid of_m conn)
|
bc475991b3e9c00f70b0f71c0f06e81aef1f93d8932f2ca02ea2b2be57d39287 | fragnix/fragnix | Data.ByteString.Base64.hs | # LANGUAGE Haskell98 #
# LINE 1 " Data / ByteString / Base64.hs " #
# LANGUAGE CPP #
# LANGUAGE Trustworthy #
-- |
-- Module : Data.ByteString.Base64
Copyright : ( c ) 2010
--
-- License : BSD-style
-- Maintainer :
-- Stability : experimental
Portability : GHC
--
-- Fast and efficient encoding and decoding of base64-encoded strings.
module Data.ByteString.Base64
(
encode
, decode
, decodeLenient
, joinWith
) where
import Data.ByteString.Base64.Internal
import qualified Data.ByteString as B
import Data.ByteString.Internal (ByteString(..))
import Data.Word (Word8)
import Foreign.ForeignPtr (ForeignPtr)
-- | Encode a string into base64 form. The result will always be a
multiple of 4 bytes in length .
encode :: ByteString -> ByteString
encode s = encodeWith (mkEncodeTable alphabet) s
-- | Decode a base64-encoded string. This function strictly follows
the specification in RFC 4648 ,
-- <>.
decode :: ByteString -> Either String ByteString
decode s = decodeWithTable decodeFP s
-- | Decode a base64-encoded string. This function is lenient in
following the specification from RFC 4648 ,
-- <>, and will not generate
-- parse errors no matter how poor its input.
decodeLenient :: ByteString -> ByteString
decodeLenient s = decodeLenientWithTable decodeFP s
alphabet :: ByteString
alphabet = B.pack $ [65..90] ++ [97..122] ++ [48..57] ++ [43,47]
# NOINLINE alphabet #
decodeFP :: ForeignPtr Word8
PS decodeFP _ _ = B.pack $
replicate 43 x ++ [62,x,x,x,63] ++ [52..61] ++ [x,x,x,done,x,x,x] ++
[0..25] ++ [x,x,x,x,x,x] ++ [26..51] ++ replicate 133 x
# NOINLINE decodeFP #
x :: Integral a => a
x = 255
# INLINE x #
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/scotty/Data.ByteString.Base64.hs | haskell | |
Module : Data.ByteString.Base64
License : BSD-style
Maintainer :
Stability : experimental
Fast and efficient encoding and decoding of base64-encoded strings.
| Encode a string into base64 form. The result will always be a
| Decode a base64-encoded string. This function strictly follows
<>.
| Decode a base64-encoded string. This function is lenient in
<>, and will not generate
parse errors no matter how poor its input. | # LANGUAGE Haskell98 #
# LINE 1 " Data / ByteString / Base64.hs " #
# LANGUAGE CPP #
# LANGUAGE Trustworthy #
Copyright : ( c ) 2010
Portability : GHC
module Data.ByteString.Base64
(
encode
, decode
, decodeLenient
, joinWith
) where
import Data.ByteString.Base64.Internal
import qualified Data.ByteString as B
import Data.ByteString.Internal (ByteString(..))
import Data.Word (Word8)
import Foreign.ForeignPtr (ForeignPtr)
multiple of 4 bytes in length .
encode :: ByteString -> ByteString
encode s = encodeWith (mkEncodeTable alphabet) s
the specification in RFC 4648 ,
decode :: ByteString -> Either String ByteString
decode s = decodeWithTable decodeFP s
following the specification from RFC 4648 ,
decodeLenient :: ByteString -> ByteString
decodeLenient s = decodeLenientWithTable decodeFP s
alphabet :: ByteString
alphabet = B.pack $ [65..90] ++ [97..122] ++ [48..57] ++ [43,47]
# NOINLINE alphabet #
decodeFP :: ForeignPtr Word8
PS decodeFP _ _ = B.pack $
replicate 43 x ++ [62,x,x,x,63] ++ [52..61] ++ [x,x,x,done,x,x,x] ++
[0..25] ++ [x,x,x,x,x,x] ++ [26..51] ++ replicate 133 x
# NOINLINE decodeFP #
x :: Integral a => a
x = 255
# INLINE x #
|
3d2b627e57f47dc2cb020fbe20023009e855a1ecaf8861823de634b6f814bf7a | mmontone/gestalt | transactions.lisp | (require :ele-bdb)
(require :hunchentoot)
(require :cl-who)
(defpackage tapp
(:use :cl :elephant :hunchentoot :cl-who))
(in-package :tapp)
(setf hunchentoot:*catch-errors-p* nil)
(setf hunchentoot:*HUNCHENTOOT-DEFAULT-EXTERNAL-FORMAT*
(flexi-streams:make-external-format :utf8 :eol-style :lf))
(start (make-instance 'acceptor :port 9090))
(setf elephant::*default-mvcc* t)
(defparameter *test-db-spec*
'(:BDB "/home/marian/tmp/tapp/"))
(defparameter *transactions* (make-hash-table))
(defparameter *transaction-id-seq* 1)
(open-store *test-db-spec*)
(define-easy-handler (root :uri "/") ()
(start-session)
(with-html-output-to-string (s)
(loop for person in (get-instances-by-class 'person)
do (htm (:a :href (format nil "/edit-person?id=~A" (id person))
(:b (str (title person))))
:br))))
(define-easy-handler (edit-person :uri "/edit-person") (id)
(start-session)
(let ((person (first (get-instances-by-value 'person 'id (parse-integer id)))))
(with-html-output-to-string (s)
(htm (:form :action "/save-person"
:method "post"
(:fieldset
(:input :type "hidden"
:name "id"
:value id)
(:table
(:tbody
(:tr
(:td
(:label (str "Name:")))
(:td
(:input :type "text"
:name "name"
:value (name person))))
(:tr
(:td
(:label (str "Lastname:")))
(:td
(:input :type "text"
:name "lastname"
:value (lastname person))))))
(:input :type "submit"
:value "submit")))))))
(define-easy-handler (save-person :uri "/save-person") (id name lastname)
(start-session)
(let* ((person (first (get-instances-by-value 'person 'id
(parse-integer id))))
(tx-id (incf *transaction-id-seq*))
(tx (controller-start-transaction *store-controller*))
(elephant::*current-transaction* (list *store-controller*
tx nil)))
(setf (gethash tx-id *transactions*)
elephant::*current-transaction*)
(setf (name person) name)
(setf (lastname person) lastname)
(with-html-output-to-string (s)
(htm
(:table
(:tbody
(:tr
(:td
(:label (str "Name:")))
(:td
(:label (str (name person)))))
(:tr
(:td
(:label (str "Lastname:")))
(:td
(:label (str (lastname person)))))
(:tr
(:td (:a :href (format nil "/commit?tid=~A" tx-id)
(str "Save")))
(:td (:a :href (format nil "/discard?tid=~A" tx-id)
(str "Cancel"))))))))))
(define-easy-handler (commit :uri "/commit") (tid)
(let ((tid (parse-integer tid)))
(with-html-output-to-string (s)
(let ((tx (gethash tid *transactions*)))
(controller-commit-transaction *store-controller* (second tx))
(htm (:b (str (format nil "Committing transaction ~A" tx)))
(:a :href "/" (:b (str "Go home"))))))))
(define-easy-handler (discard :uri "/discard") (tid)
(let ((tid (parse-integer tid)))
(with-html-output-to-string (s)
(let ((tx (gethash tid *transactions*)))
(controller-abort-transaction *store-controller* (second tx))
(htm (:b (str (format nil "Discarding transaction ~A" tx)))
(:a :href "/" (:b (str "Go home"))))))))
(defclass person ()
((id :initarg :id :initform (next-person-id)
:accessor id :index t)
(name :initarg :name :initform nil
:accessor name)
(lastname :initarg :lastname :initform nil
:accessor lastname)
(email :initarg :email :initform nil
:accessor email))
(:metaclass persistent-metaclass))
(defmethod title ((person person))
(format nil "~A ~A" (name person) (lastname person)))
(defun next-person-id ()
(prog1
(get-from-root :persons-id-seq)
(add-to-root :persons-id-seq (1+ (get-from-root :persons-id-seq)))))
(get-from-root :persons)
(add-to-root :persons (make-hash-table))
(add-to-root :persons-id-seq 1) | null | https://raw.githubusercontent.com/mmontone/gestalt/fd019c0ca03b4efc73b9ddd3db1e3ed211233428/examples/transactions.lisp | lisp | (require :ele-bdb)
(require :hunchentoot)
(require :cl-who)
(defpackage tapp
(:use :cl :elephant :hunchentoot :cl-who))
(in-package :tapp)
(setf hunchentoot:*catch-errors-p* nil)
(setf hunchentoot:*HUNCHENTOOT-DEFAULT-EXTERNAL-FORMAT*
(flexi-streams:make-external-format :utf8 :eol-style :lf))
(start (make-instance 'acceptor :port 9090))
(setf elephant::*default-mvcc* t)
(defparameter *test-db-spec*
'(:BDB "/home/marian/tmp/tapp/"))
(defparameter *transactions* (make-hash-table))
(defparameter *transaction-id-seq* 1)
(open-store *test-db-spec*)
(define-easy-handler (root :uri "/") ()
(start-session)
(with-html-output-to-string (s)
(loop for person in (get-instances-by-class 'person)
do (htm (:a :href (format nil "/edit-person?id=~A" (id person))
(:b (str (title person))))
:br))))
(define-easy-handler (edit-person :uri "/edit-person") (id)
(start-session)
(let ((person (first (get-instances-by-value 'person 'id (parse-integer id)))))
(with-html-output-to-string (s)
(htm (:form :action "/save-person"
:method "post"
(:fieldset
(:input :type "hidden"
:name "id"
:value id)
(:table
(:tbody
(:tr
(:td
(:label (str "Name:")))
(:td
(:input :type "text"
:name "name"
:value (name person))))
(:tr
(:td
(:label (str "Lastname:")))
(:td
(:input :type "text"
:name "lastname"
:value (lastname person))))))
(:input :type "submit"
:value "submit")))))))
(define-easy-handler (save-person :uri "/save-person") (id name lastname)
(start-session)
(let* ((person (first (get-instances-by-value 'person 'id
(parse-integer id))))
(tx-id (incf *transaction-id-seq*))
(tx (controller-start-transaction *store-controller*))
(elephant::*current-transaction* (list *store-controller*
tx nil)))
(setf (gethash tx-id *transactions*)
elephant::*current-transaction*)
(setf (name person) name)
(setf (lastname person) lastname)
(with-html-output-to-string (s)
(htm
(:table
(:tbody
(:tr
(:td
(:label (str "Name:")))
(:td
(:label (str (name person)))))
(:tr
(:td
(:label (str "Lastname:")))
(:td
(:label (str (lastname person)))))
(:tr
(:td (:a :href (format nil "/commit?tid=~A" tx-id)
(str "Save")))
(:td (:a :href (format nil "/discard?tid=~A" tx-id)
(str "Cancel"))))))))))
(define-easy-handler (commit :uri "/commit") (tid)
(let ((tid (parse-integer tid)))
(with-html-output-to-string (s)
(let ((tx (gethash tid *transactions*)))
(controller-commit-transaction *store-controller* (second tx))
(htm (:b (str (format nil "Committing transaction ~A" tx)))
(:a :href "/" (:b (str "Go home"))))))))
(define-easy-handler (discard :uri "/discard") (tid)
(let ((tid (parse-integer tid)))
(with-html-output-to-string (s)
(let ((tx (gethash tid *transactions*)))
(controller-abort-transaction *store-controller* (second tx))
(htm (:b (str (format nil "Discarding transaction ~A" tx)))
(:a :href "/" (:b (str "Go home"))))))))
(defclass person ()
((id :initarg :id :initform (next-person-id)
:accessor id :index t)
(name :initarg :name :initform nil
:accessor name)
(lastname :initarg :lastname :initform nil
:accessor lastname)
(email :initarg :email :initform nil
:accessor email))
(:metaclass persistent-metaclass))
(defmethod title ((person person))
(format nil "~A ~A" (name person) (lastname person)))
(defun next-person-id ()
(prog1
(get-from-root :persons-id-seq)
(add-to-root :persons-id-seq (1+ (get-from-root :persons-id-seq)))))
(get-from-root :persons)
(add-to-root :persons (make-hash-table))
(add-to-root :persons-id-seq 1) |
|
59ca105f51cd09a26f15cdcc260b76cdc5a28e6b5c2835dbffcbeb8fb68de6fb | UU-ComputerScience/js-asteroids | WX.hs | --------------------------------------------------------------------------------
| Module : WX
Copyright : ( c ) 2003
License : wxWindows
Maintainer :
Stability : provisional
Portability : portable
The WX module just re - exports functionality from helper modules and
defines the ' start ' function .
The WX library provides a /haskellized/ interface to the raw wxWindows
functionality provided by the " Graphics . UI.WXCore " library .
Copyright : (c) Daan Leijen 2003
License : wxWindows
Maintainer :
Stability : provisional
Portability : portable
The WX module just re-exports functionality from helper modules and
defines the 'start' function.
The WX library provides a /haskellized/ interface to the raw wxWindows
functionality provided by the "Graphics.UI.WXCore" library.
-}
--------------------------------------------------------------------------------
module Graphics.UI.WX
( -- * Functions
start
-- * Modules
, module Graphics.UI.WX.Types
, module Graphics.UI.WX.Attributes
, module Graphics.UI.WX.Classes
, module Graphics.UI.WX.Variable
--, module Graphics.UI.WX.Layout
, module Graphics.UI.WX.Events
, module Graphics.UI.WX.Window
--, module Graphics.UI.WX.Frame
, module Graphics.UI.WX.Timer
, module Graphics.UI.WX.Media
--, module Graphics.UI.WX.Menu
, module Graphics .
--, module Graphics.UI.WX.Dialogs
, module Graphics.UI.WX.Draw
) where
import Graphics.UI.WX.Types hiding (size)
import Graphics.UI.WX.Attributes
import Graphics.UI.WX.Classes
import Graphics.UI.WX.Variable
import Graphics . UI.WX.Layout
import Graphics.UI.WX.Events
import Graphics.UI.WX.Window
import Graphics . UI.WX.Frame
import Graphics.UI.WX.Timer
import Graphics.UI.WX.Media
import Graphics . UI.WX.Menu
import Graphics .
import Graphics . UI.WX.Dialogs
import Graphics.UI.WX.Draw
import Graphics.UI.WXCore (unitIO,run)
-- | 'start' runs the GUI.
start :: IO a -> IO ()
start io
= run (unitIO io) | null | https://raw.githubusercontent.com/UU-ComputerScience/js-asteroids/b7015d8ad4aa57ff30f2631e0945462f6e1ef47a/wxasteroids/src/Graphics/UI/WX.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
* Functions
* Modules
, module Graphics.UI.WX.Layout
, module Graphics.UI.WX.Frame
, module Graphics.UI.WX.Menu
, module Graphics.UI.WX.Dialogs
| 'start' runs the GUI. | | Module : WX
Copyright : ( c ) 2003
License : wxWindows
Maintainer :
Stability : provisional
Portability : portable
The WX module just re - exports functionality from helper modules and
defines the ' start ' function .
The WX library provides a /haskellized/ interface to the raw wxWindows
functionality provided by the " Graphics . UI.WXCore " library .
Copyright : (c) Daan Leijen 2003
License : wxWindows
Maintainer :
Stability : provisional
Portability : portable
The WX module just re-exports functionality from helper modules and
defines the 'start' function.
The WX library provides a /haskellized/ interface to the raw wxWindows
functionality provided by the "Graphics.UI.WXCore" library.
-}
module Graphics.UI.WX
start
, module Graphics.UI.WX.Types
, module Graphics.UI.WX.Attributes
, module Graphics.UI.WX.Classes
, module Graphics.UI.WX.Variable
, module Graphics.UI.WX.Events
, module Graphics.UI.WX.Window
, module Graphics.UI.WX.Timer
, module Graphics.UI.WX.Media
, module Graphics .
, module Graphics.UI.WX.Draw
) where
import Graphics.UI.WX.Types hiding (size)
import Graphics.UI.WX.Attributes
import Graphics.UI.WX.Classes
import Graphics.UI.WX.Variable
import Graphics . UI.WX.Layout
import Graphics.UI.WX.Events
import Graphics.UI.WX.Window
import Graphics . UI.WX.Frame
import Graphics.UI.WX.Timer
import Graphics.UI.WX.Media
import Graphics . UI.WX.Menu
import Graphics .
import Graphics . UI.WX.Dialogs
import Graphics.UI.WX.Draw
import Graphics.UI.WXCore (unitIO,run)
start :: IO a -> IO ()
start io
= run (unitIO io) |
29f9acb0951b4e509801c55e8933af703e8cb2cb38c31824959d5ff747e1d017 | haroldcarr/learn-haskell-coq-ml-etc | EntityTagCacheNoSigs.hs | # OPTIONS_GHC -fno - warn - missing - signatures -fno - warn - unused - binds #
{-# LANGUAGE OverloadedStrings #-}
module EntityTagCacheNoSigs where
import Control.Monad ((>=>))
import Data.List (isPrefixOf)
import Data.Map.Strict as M
import Data.Maybe as MB (mapMaybe)
import Prelude as P
import System.IO (IOMode (ReadMode), hGetContents, withFile)
import Test.HUnit (Counts, Test (TestList), runTestTT)
import qualified Test.HUnit.Util as U (t)
------------------------------------------------------------------------------
type MSI = Map String Int
type MIS = Map Int String
data Cache = Cache !(Map Int [Int]) -- entity id to tag numbers
!Int -- next tag number
!MSI -- tag to tag number
!MIS -- tag number to tag
mii (Cache r _ _ _) = r
next (Cache _ r _ _) = r
msi (Cache _ _ r _) = r
mis (Cache _ _ _ r) = r
------------------------------------------------------------------------------
-- Use cache
-- impure
getTagsIO :: Monad m => Int -> m Cache -> m (Maybe [String])
getTagsIO = fmap . getTags
updateTagsIO x ts = fmap (updateTags x ts)
-- pure
getTags x c = M.lookup x (mii c) >>= \r -> return $ MB.mapMaybe (`M.lookup` mis c) r
updateTags x ts c =
let (ks, next', msi', mis') = dedupTagIdTags (ts, next c, msi c, mis c)
in Cache (M.insert x ks (mii c)) next' msi' mis'
------------------------------------------------------------------------------
-- Populate cache
loadCacheFromFile filename =
withFile filename ReadMode (hGetContents >=> return . stringToCache)
stringToCache = dedupTags . collectTagIdAndTags
------------------------------------------------------------------------------
-- Internals
collectTagIdAndTags = P.map mkEntry . lines
where
mkEntry x = let (i:xs) = splitOn "," x in (read i, xs)
dedupTags = P.foldr level1 (Cache M.empty (-1) M.empty M.empty)
where
level1 (tag, ss) c =
let (ks, i, msi', mis') = dedupTagIdTags (ss, next c, msi c, mis c)
in Cache (M.insert tag ks (mii c)) i msi' mis'
dedupTagIdTags (ss, i0, msi0, mis0) = P.foldr level2 (mempty, i0, msi0, mis0) ss
where
level2 s (acc, i, msi', mis') = case M.lookup s msi' of
Just j -> (j:acc, i, msi', mis')
Nothing -> (i:acc, i+1, M.insert s i msi', M.insert i s mis')
------------------------------------------------------------------------------
-- Test
exCsv = "0,foo,bar\n1,abc,foo\n2\n3,xyz,bar"
cache = stringToCache exCsv
cToList c = (M.toList (mii c), next c, M.toList (msi c), M.toList (mis c))
tgt = U.t "tgt"
(P.map (`getTags` cache) [0..4])
[ Just ["foo","bar"]
, Just ["abc","foo"]
, Just []
, Just ["xyz","bar"]
, Nothing
]
tut = U.t "tut"
(cToList $ updateTags 2 ["new1","new2"] cache)
( [(0,[1,-1]), (1,[2,1]), (2,[4,3]), (3,[0,-1])]
, 5
, [("abc",2),("bar",-1),("foo",1),("new1",4),("new2",3),("xyz",0)]
, [(-1,"bar"),(0,"xyz"),(1,"foo"),(2,"abc"),(3,"new2"),(4,"new1")] )
tstc = U.t "tstc"
(cToList cache)
( [(0,[1,-1]), (1,[2,1]), (2,[]), (3,[0,-1])]
, 3
, [("abc",2),("bar",-1),("foo",1),("xyz",0)]
, [(-1,"bar"),(0,"xyz"),(1,"foo"),(2,"abc")] )
tct = U.t "tct"
(collectTagIdAndTags exCsv)
[(0,["foo","bar"]), (1,["abc","foo"]), (2,[]), (3,["xyz","bar"])]
tddt = U.t "tddt"
(let (i, acc, msi0, mis0) = dedupTagIdTags ( ["foo", "bar", "baz", "foo", "baz", "baz", "foo", "qux", "new"::String]
, -1, M.empty, M.empty)
in (i, acc, M.toList msi0, M.toList mis0))
( [ 1, 3, 2, 1, 2, 2, 1, 0, -1]
, 4::Int
, [("bar",3),("baz",2),("foo",1),("new",-1),("qux",0)]
, [(-1,"new"),(0,"qux"),(1,"foo"),(2,"baz"),(3,"bar")])
test :: IO Counts
test =
runTestTT $ TestList $ tgt ++ tut ++ tstc ++ tct ++ tddt
------------------------------------------------------------------------------
Utililties ( I ca n't find this in the libraries available on stackage )
splitOn :: Eq a => [a] -> [a] -> [[a]]
splitOn _ [] = []
splitOn delim str =
let (firstline, remainder) = breakList (isPrefixOf delim) str
in firstline : case remainder of
[] -> []
x -> if x == delim
then [[]]
else splitOn delim (drop (length delim) x)
breakList :: ([a] -> Bool) -> [a] -> ([a], [a])
breakList func = spanList (not . func)
spanList :: ([a] -> Bool) -> [a] -> ([a], [a])
spanList _ [] = ([],[])
spanList func list@(x:xs) = if func list then (x:ys,zs) else ([],list)
where (ys,zs) = spanList func xs
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/playpen/interview/api-catalog/src/EntityTagCacheNoSigs.hs | haskell | # LANGUAGE OverloadedStrings #
----------------------------------------------------------------------------
entity id to tag numbers
next tag number
tag to tag number
tag number to tag
----------------------------------------------------------------------------
Use cache
impure
pure
----------------------------------------------------------------------------
Populate cache
----------------------------------------------------------------------------
Internals
----------------------------------------------------------------------------
Test
---------------------------------------------------------------------------- | # OPTIONS_GHC -fno - warn - missing - signatures -fno - warn - unused - binds #
module EntityTagCacheNoSigs where
import Control.Monad ((>=>))
import Data.List (isPrefixOf)
import Data.Map.Strict as M
import Data.Maybe as MB (mapMaybe)
import Prelude as P
import System.IO (IOMode (ReadMode), hGetContents, withFile)
import Test.HUnit (Counts, Test (TestList), runTestTT)
import qualified Test.HUnit.Util as U (t)
type MSI = Map String Int
type MIS = Map Int String
mii (Cache r _ _ _) = r
next (Cache _ r _ _) = r
msi (Cache _ _ r _) = r
mis (Cache _ _ _ r) = r
getTagsIO :: Monad m => Int -> m Cache -> m (Maybe [String])
getTagsIO = fmap . getTags
updateTagsIO x ts = fmap (updateTags x ts)
getTags x c = M.lookup x (mii c) >>= \r -> return $ MB.mapMaybe (`M.lookup` mis c) r
updateTags x ts c =
let (ks, next', msi', mis') = dedupTagIdTags (ts, next c, msi c, mis c)
in Cache (M.insert x ks (mii c)) next' msi' mis'
loadCacheFromFile filename =
withFile filename ReadMode (hGetContents >=> return . stringToCache)
stringToCache = dedupTags . collectTagIdAndTags
collectTagIdAndTags = P.map mkEntry . lines
where
mkEntry x = let (i:xs) = splitOn "," x in (read i, xs)
dedupTags = P.foldr level1 (Cache M.empty (-1) M.empty M.empty)
where
level1 (tag, ss) c =
let (ks, i, msi', mis') = dedupTagIdTags (ss, next c, msi c, mis c)
in Cache (M.insert tag ks (mii c)) i msi' mis'
dedupTagIdTags (ss, i0, msi0, mis0) = P.foldr level2 (mempty, i0, msi0, mis0) ss
where
level2 s (acc, i, msi', mis') = case M.lookup s msi' of
Just j -> (j:acc, i, msi', mis')
Nothing -> (i:acc, i+1, M.insert s i msi', M.insert i s mis')
exCsv = "0,foo,bar\n1,abc,foo\n2\n3,xyz,bar"
cache = stringToCache exCsv
cToList c = (M.toList (mii c), next c, M.toList (msi c), M.toList (mis c))
tgt = U.t "tgt"
(P.map (`getTags` cache) [0..4])
[ Just ["foo","bar"]
, Just ["abc","foo"]
, Just []
, Just ["xyz","bar"]
, Nothing
]
tut = U.t "tut"
(cToList $ updateTags 2 ["new1","new2"] cache)
( [(0,[1,-1]), (1,[2,1]), (2,[4,3]), (3,[0,-1])]
, 5
, [("abc",2),("bar",-1),("foo",1),("new1",4),("new2",3),("xyz",0)]
, [(-1,"bar"),(0,"xyz"),(1,"foo"),(2,"abc"),(3,"new2"),(4,"new1")] )
tstc = U.t "tstc"
(cToList cache)
( [(0,[1,-1]), (1,[2,1]), (2,[]), (3,[0,-1])]
, 3
, [("abc",2),("bar",-1),("foo",1),("xyz",0)]
, [(-1,"bar"),(0,"xyz"),(1,"foo"),(2,"abc")] )
tct = U.t "tct"
(collectTagIdAndTags exCsv)
[(0,["foo","bar"]), (1,["abc","foo"]), (2,[]), (3,["xyz","bar"])]
tddt = U.t "tddt"
(let (i, acc, msi0, mis0) = dedupTagIdTags ( ["foo", "bar", "baz", "foo", "baz", "baz", "foo", "qux", "new"::String]
, -1, M.empty, M.empty)
in (i, acc, M.toList msi0, M.toList mis0))
( [ 1, 3, 2, 1, 2, 2, 1, 0, -1]
, 4::Int
, [("bar",3),("baz",2),("foo",1),("new",-1),("qux",0)]
, [(-1,"new"),(0,"qux"),(1,"foo"),(2,"baz"),(3,"bar")])
test :: IO Counts
test =
runTestTT $ TestList $ tgt ++ tut ++ tstc ++ tct ++ tddt
Utililties ( I ca n't find this in the libraries available on stackage )
splitOn :: Eq a => [a] -> [a] -> [[a]]
splitOn _ [] = []
splitOn delim str =
let (firstline, remainder) = breakList (isPrefixOf delim) str
in firstline : case remainder of
[] -> []
x -> if x == delim
then [[]]
else splitOn delim (drop (length delim) x)
breakList :: ([a] -> Bool) -> [a] -> ([a], [a])
breakList func = spanList (not . func)
spanList :: ([a] -> Bool) -> [a] -> ([a], [a])
spanList _ [] = ([],[])
spanList func list@(x:xs) = if func list then (x:ys,zs) else ([],list)
where (ys,zs) = spanList func xs
|
aa4eab5d2edfe18b4be62cdf874ad7b51b2c7c16e8659912a2e3198ec0c5eb32 | rizo/streams-bench | Config.ml | let length = ref (int_of_float (2.0 ** 10.0))
let limit = ref (!length / 2)
let main_ops = ref "all"
let configure () =
begin
try
main_ops := Sys.getenv "STREAMS_BENCHMARK";
length := int_of_string (Sys.getenv "STREAMS_LENGTH");
limit := int_of_string (Sys.getenv "STREAMS_LIMIT")
with Not_found ->
print_endline
"Missing environment variables for benchmark:\n\n\
\ - \
STREAMS_BENCHMARK=all|all_no_flat_map|all_no_take|fold|map|filter|flat_map|take\n\
\ - STREAMS_LENGTH=int (input length)\n\
\ - STREAMS_LIMIT=int (used for take)\n\n\
Using defaults."
end;
Printf.printf "benchmark=%s length=%d limit=%d\n" !main_ops !length !limit
| null | https://raw.githubusercontent.com/rizo/streams-bench/87baf838971c84613b801ab32b6473d397bcc23f/experiments/Config.ml | ocaml | let length = ref (int_of_float (2.0 ** 10.0))
let limit = ref (!length / 2)
let main_ops = ref "all"
let configure () =
begin
try
main_ops := Sys.getenv "STREAMS_BENCHMARK";
length := int_of_string (Sys.getenv "STREAMS_LENGTH");
limit := int_of_string (Sys.getenv "STREAMS_LIMIT")
with Not_found ->
print_endline
"Missing environment variables for benchmark:\n\n\
\ - \
STREAMS_BENCHMARK=all|all_no_flat_map|all_no_take|fold|map|filter|flat_map|take\n\
\ - STREAMS_LENGTH=int (input length)\n\
\ - STREAMS_LIMIT=int (used for take)\n\n\
Using defaults."
end;
Printf.printf "benchmark=%s length=%d limit=%d\n" !main_ops !length !limit
|
|
dedeb1e7e8139a0ecb04afee4612bebace0437f33437eb940ae3b68721cd2407 | blitz/stumpwm | primitives.lisp | Copyright ( C ) 2003 - 2008
;;
This file is part of stumpwm .
;;
stumpwm is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 , or ( at your option )
;; any later version.
stumpwm is distributed in the hope that it will be useful ,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
You should have received a copy of the GNU General Public License
;; along with this software; see the file COPYING. If not, write to
the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 ,
Boston , MA 02111 - 1307 USA
;; Commentary:
;;
;; This file contains primitive data structures and functions used
throughout stumpwm .
;;
;; Code:
(in-package :stumpwm)
(export '(*suppress-abort-messages*
*suppress-frame-indicator*
*timeout-wait*
*timeout-frame-indicator-wait*
*frame-indicator-text*
*frame-indicator-timer*
*message-window-timer*
*urgent-window-hook*
*new-window-hook*
*destroy-window-hook*
*focus-window-hook*
*place-window-hook*
*start-hook*
*internal-loop-hook*
*focus-frame-hook*
*new-frame-hook*
*message-hook*
*top-level-error-hook*
*focus-group-hook*
*key-press-hook*
*root-click-hook*
*mode-line-click-hook*
*display*
*shell-program*
*maxsize-border-width*
*transient-border-width*
*normal-border-width*
*text-color*
*window-events*
*window-parent-events*
*message-window-padding*
*message-window-gravity*
*editor-bindings*
*input-window-gravity*
*normal-gravity*
*maxsize-gravity*
*transient-gravity*
*top-level-error-action*
*window-name-source*
*frame-number-map*
*all-modifiers*
*modifiers*
*screen-list*
*initializing*
*processing-existing-windows*
*executing-stumpwm-command*
*debug-level*
*debug-expose-events*
*debug-stream*
*window-formatters*
*window-format*
*group-formatters*
*group-format*
*list-hidden-groups*
*x-selection*
*last-command*
*max-last-message-size*
*record-last-msg-override*
*suppress-echo-timeout*
*run-or-raise-all-groups*
*run-or-raise-all-screens*
*deny-map-request*
*deny-raise-request*
*suppress-deny-messages*
*honor-window-moves*
*resize-hides-windows*
*min-frame-width*
*min-frame-height*
*new-frame-action*
*new-window-preferred-frame*
*startup-message*
*default-package*
*window-placement-rules*
*mouse-focus-policy*
*root-click-focuses-frame*
*banish-pointer-to*
*xwin-to-window*
*resize-map*
*default-group-name*
*window-border-style*
*data-dir*
add-hook
clear-window-placement-rules
data-dir-file
dformat
define-frame-preference
redirect-all-output
remove-hook
run-hook
run-hook-with-args
split-string
with-restarts-menu
with-data-file
move-to-head))
;;; Message Timer
(defvar *suppress-abort-messages* nil
"Suppress abort message when non-nil.")
(defvar *timeout-wait* 5
"Specifies, in seconds, how long a message will appear for. This must
be an integer.")
(defvar *timeout-frame-indicator-wait* 1
"The amount of time a frame indicator timeout takes.")
(defvar *frame-indicator-timer* nil
"Keep track of the timer that hides the frame indicator.")
(defvar *frame-indicator-text* " Current Frame "
"What appears in the frame indicator window?")
(defvar *suppress-frame-indicator* nil
"Set this to T if you never want to see the frame indicator.")
(defvar *message-window-timer* nil
"Keep track of the timer that hides the message window.")
;;; Hooks
(defvar *urgent-window-hook* '()
"A hook called whenever a window sets the property indicating that
it demands the user's attention")
(defvar *map-window-hook* '()
"A hook called whenever a window is mapped.")
(defvar *unmap-window-hook* '()
"A hook called whenever a window is withdrawn.")
(defvar *new-window-hook* '()
"A hook called whenever a window is added to the window list. This
includes a genuinely new window as well as bringing a withdrawn window
back into the window list.")
(defvar *destroy-window-hook* '()
"A hook called whenever a window is destroyed or withdrawn.")
(defvar *focus-window-hook* '()
"A hook called when a window is given focus. It is called with 2
arguments: the current window and the last window (could be nil).")
(defvar *place-window-hook* '()
"A hook called whenever a window is placed by rule. Arguments are
window group and frame")
(defvar *start-hook* '()
"A hook called when stumpwm starts.")
(defvar *internal-loop-hook* '()
"A hook called inside stumpwm's inner loop.")
(defvar *focus-frame-hook* '()
"A hook called when a frame is given focus. The hook functions are
called with 2 arguments: the current frame and the last frame.")
(defvar *new-frame-hook* '()
"A hook called when a new frame is created. the hook is called with
the frame as an argument.")
(defvar *message-hook* '()
"A hook called whenever stumpwm displays a message. The hook
function is passed any number of arguments. Each argument is a
line of text.")
(defvar *top-level-error-hook* '()
"Called when a top level error occurs. Note that this hook is
run before the error is dealt with according to
*top-level-error-action*.")
(defvar *focus-group-hook* '()
"A hook called whenever stumpwm switches groups. It is called with 2 arguments: the current group and the last group.")
(defvar *key-press-hook* '()
"A hook called whenever a key under *top-map* is pressed.
It is called with 3 argument: the key, the (possibly incomplete) key
sequence it is a part of, and command value bound to the key.")
(defvar *root-click-hook* '()
"A hook called whenever there is a mouse click on the root
window. Called with 4 arguments, the screen containing the root
window, the button clicked, and the x and y of the pointer.")
(defvar *mode-line-click-hook* '()
"Called whenever the mode-line is clicked. It is called with 4 arguments,
the mode-line, the button clicked, and the x and y of the pointer.")
Data types and globals used by stumpwm
(defvar *display* nil
"The display for the X server")
(defvar *shell-program* "/bin/sh"
"The shell program used by @code{run-shell-command}.")
(defvar *maxsize-border-width* 1
"The width in pixels given to the borders of windows with maxsize or ratio hints.")
(defvar *transient-border-width* 1
"The width in pixels given to the borders of transient or pop-up windows.")
(defvar *normal-border-width* 1
"The width in pixels given to the borders of regular windows.")
(defvar *text-color* "white"
"The color of message text.")
(defparameter +netwm-supported+
'(:_NET_SUPPORTING_WM_CHECK
:_NET_NUMBER_OF_DESKTOPS
:_NET_DESKTOP_GEOMETRY
:_NET_DESKTOP_VIEWPORT
:_NET_CURRENT_DESKTOP
:_NET_WM_WINDOW_TYPE
:_NET_WM_STATE
:_NET_WM_STATE_MODAL
:_NET_WM_ALLOWED_ACTIONS
:_NET_WM_STATE_FULLSCREEN
:_NET_WM_STATE_HIDDEN
:_NET_WM_STATE_DEMANDS_ATTENTION
:_NET_WM_FULL_WINDOW_PLACEMENT
:_NET_CLOSE_WINDOW
:_NET_CLIENT_LIST
:_NET_CLIENT_LIST_STACKING
:_NET_ACTIVE_WINDOW
:_KDE_NET_SYSTEM_TRAY_WINDOW_FOR)
"Supported NETWM properties.
Window types are in +WINDOW-TYPES+.")
(defparameter +netwm-allowed-actions+
'(:_NET_WM_ACTION_CHANGE_DESKTOP
:_NET_WM_ACTION_FULLSCREEN
:_NET_WM_ACTION_CLOSE)
"Allowed NETWM actions for managed windows")
(defparameter +netwm-window-types+
'(
;; (:_NET_WM_WINDOW_TYPE_DESKTOP . :desktop)
(:_NET_WM_WINDOW_TYPE_DOCK . :dock)
;; (:_NET_WM_WINDOW_TYPE_TOOLBAR . :toolbar)
;; (:_NET_WM_WINDOW_TYPE_MENU . :menu)
;; (:_NET_WM_WINDOW_TYPE_UTILITY . :utility)
;; (:_NET_WM_WINDOW_TYPE_SPLASH . :splash)
(:_NET_WM_WINDOW_TYPE_DIALOG . :dialog)
(:_NET_WM_WINDOW_TYPE_NORMAL . :normal))
"Alist mapping NETWM window types to keywords.
Include only those we are ready to support.")
;; Window states
(defconstant +withdrawn-state+ 0)
(defconstant +normal-state+ 1)
(defconstant +iconic-state+ 3)
(defvar *window-events* '(:structure-notify
:property-change
:colormap-change
:focus-change
:enter-window)
"The events to listen for on managed windows.")
(defvar *window-parent-events* '(:substructure-notify
:substructure-redirect)
"The events to listen for on managed windows' parents.")
;; Message window variables
(defvar *message-window-padding* 5
"The number of pixels that pad the text in the message window.")
(defvar *message-window-gravity* :top-right
"This variable controls where the message window appears. The follow
are valid values.
@table @asis
@item :top-left
@item :top-right
@item :bottom-left
@item :bottom-right
@item :center
@end table")
;; line editor
(defvar *editor-bindings* nil
"A list of key-bindings for line editing.")
(defvar *input-window-gravity* :top-right
"This variable controls where the input window appears. The follow
are valid values.
@table @asis
@item :top-left
@item :top-right
@item :bottom-left
@item :bottom-right
@item :center
@end table")
;; default values. use the set-* functions to these attributes
(defparameter +default-foreground-color+ "White")
(defparameter +default-background-color+ "Black")
(defparameter +default-window-background-color+ "Black")
(defparameter +default-border-color+ "White")
(defparameter +default-font-name+ "9x15bold")
(defparameter +default-focus-color+ "White")
(defparameter +default-unfocus-color+ "Black")
(defparameter +default-frame-outline-width+ 2)
Do n't set these variables directly , use set-<var name > instead
(defvar *normal-gravity* :center)
(defvar *maxsize-gravity* :center)
(defvar *transient-gravity* :center)
(defvar *top-level-error-action* :abort
"If an error is encountered at the top level, in
STUMPWM-INTERNAL-LOOP, then this variable decides what action
shall be taken. By default it will print a message to the screen
and to *standard-output*.
Valid values are :message, :break, :abort. :break will break to the
debugger. This can be problematic because if the user hit's a
mapped key the ENTIRE keyboard will be frozen and you will have
to login remotely to regain control. :abort quits stumpmwm.")
(defvar *window-name-source* :title
"This variable controls what is used for the window's name. The default is @code{:title}.
@table @code
@item :title
Use the window's title given to it by its owner.
@item :class
Use the window's resource class.
@item :resource-name
Use the window's resource name.
@end table")
(defstruct frame
(number nil :type integer)
x
y
width
height
window)
(defstruct (head (:include frame))
;; point back to the screen this head belongs to
screen
;; a bar along the top or bottom that displays anything you want.
mode-line)
(defclass screen ()
((id :initform nil :accessor screen-id)
(host :initform nil :accessor screen-host)
(number :initform nil :accessor screen-number)
(heads :initform nil :accessor screen-heads :documentation
"heads of screen")
(groups :initform nil :accessor screen-groups :documentation
"the list of groups available on this screen")
(current-group :initform nil :accessor screen-current-group)
;; various colors (as returned by alloc-color)
(border-color :initform nil :accessor screen-border-color)
(fg-color :initform nil :accessor screen-fg-color)
(bg-color :initform nil :accessor screen-bg-color)
(win-bg-color :initform nil :accessor screen-win-bg-color)
(focus-color :initform nil :accessor screen-focus-color)
(unfocus-color :initform nil :accessor screen-unfocus-color)
(msg-border-width :initform nil :accessor screen-msg-border-width)
(frame-outline-width :initform nil :accessor screen-frame-outline-width)
(font :initform nil :accessor screen-font)
(mapped-windows :initform nil :accessor screen-mapped-windows :documentation
"A list of all mapped windows. These are the raw xlib:window's. window structures are stored in groups.")
(withdrawn-windows :initform nil :accessor screen-withdrawn-windows :documentation
"A list of withdrawn windows. These are of type stumpwm::window
and when they're mapped again they'll be put back in the group
they were in when they were unmapped unless that group doesn't
exist, in which case they go into the current group.")
(urgent-windows :initform nil :accessor screen-urgent-windows :documentation
"a list of windows for which (window-urgent-p) currently true.")
(input-window :initform nil :accessor screen-input-window)
(key-window :initform nil :accessor screen-key-window :documentation
"the window that accepts further keypresses after a toplevel key has been pressed.")
(focus-window :initform nil :accessor screen-focus-window :documentation
"The window that gets focus when no window has focus")
;;
(frame-window :initform nil :accessor screen-frame-window)
(frame-outline-gc :initform nil :accessor screen-frame-outline-gc)
;; color contexts
(message-cc :initform nil :accessor screen-message-cc)
(mode-line-cc :initform nil :accessor screen-mode-line-cc)
;; color maps
(color-map-normal :initform nil :accessor screen-color-map-normal)
(color-map-bright :initform nil :accessor screen-color-map-bright)
(ignore-msg-expose :initform nil :accessor screen-ignore-msg-expose :documentation
"used to ignore the first expose even when mapping the message window.")
;; the window that has focus
(focus :initform nil :accessor screen-focus)
(current-msg :initform nil :accessor screen-current-msg)
(current-msg-highlights :initform nil :accessor screen-current-msg-highlights)
(last-msg :initform nil :accessor screen-last-msg)
(last-msg-highlights :initform nil :accessor screen-last-msg-highlights)))
(defstruct ccontext
win
px
gc
default-fg
default-bright
default-bg)
(defun screen-message-window (screen)
(ccontext-win (screen-message-cc screen)))
(defun screen-message-pixmap (screen)
(ccontext-px (screen-message-cc screen)))
(defun screen-message-gc (screen)
(ccontext-gc (screen-message-cc screen)))
(defmethod print-object ((object frame) stream)
(format stream "#S(frame ~d ~a ~d ~d ~d ~d)"
(frame-number object) (frame-window object) (frame-x object) (frame-y object) (frame-width object) (frame-height object)))
(defvar *frame-number-map* "0123456789abcdefghijklmnopqrstuvxwyz"
"Set this to a string to remap the frame numbers to more convenient keys.
For instance,
\"hutenosa\"
would map frame 0 to 7 to be selectable by hitting the appropriate
homerow key on a dvorak keyboard. Currently, only single char keys are
supported. By default, the frame labels are the 36 (lower-case)
alphanumeric characters, starting with numbers 0-9.")
(defun get-frame-number-translation (frame)
"Given a frame return its number translation using *frame-number-map* as a char."
(let ((num (frame-number frame)))
(or (and (< num (length *frame-number-map*))
(char *frame-number-map* num))
translate the frame number to a char . FIXME : it loops after 9
(char (prin1-to-string num) 0))))
(defstruct modifiers
(meta nil)
(alt nil)
(hyper nil)
(super nil)
(altgr nil)
(numlock nil))
(defvar *all-modifiers* nil
"A list of all keycodes that are considered modifiers")
(defvar *modifiers* nil
"A mapping from modifier type to x11 modifier.")
(defmethod print-object ((object screen) stream)
(format stream "#S<screen ~s>" (screen-number object)))
(defvar *screen-list* '()
"The list of screens managed by stumpwm.")
(defvar *initializing* nil
"True when starting stumpwm. Use this variable in your rc file to
run code that should only be executed once, when stumpwm starts up and
loads the rc file.")
(defvar *processing-existing-windows* nil
"True when processing pre-existing windows at startup.")
(defvar *executing-stumpwm-command* nil
"True when executing external commands.")
(defvar *interactivep* nil
"True when a defcommand is executed from colon or a keybinding")
;;; The restarts menu macro
(defmacro with-restarts-menu (&body body)
"Execute BODY. If an error occurs allow the user to pick a
restart from a menu of possible restarts. If a restart is not
chosen, resignal the error."
(let ((c (gensym)))
`(handler-bind
((warning #'muffle-warning)
((or serious-condition error)
(lambda (,c)
(restarts-menu ,c)
(signal ,c))))
,@body)))
;;; Hook functionality
(defun run-hook-with-args (hook &rest args)
"Call each function in HOOK and pass args to it."
(handler-case
(with-simple-restart (abort-hooks "Abort running the remaining hooks.")
(with-restarts-menu
(dolist (fn hook)
(with-simple-restart (continue-hooks "Continue running the remaining hooks.")
(apply fn args)))))
(t (c) (message "^B^1*Error on hook ^b~S^B!~% ^n~A" hook c) (values nil c))))
(defun run-hook (hook)
"Call each function in HOOK."
(run-hook-with-args hook))
(defmacro add-hook (hook fn)
"Add @var{function} to the hook @var{hook-variable}. For example, to
display a message whenever you switch frames:
@example
\(defun my-rad-fn (to-frame from-frame)
(stumpwm:message \"Mustard!\"))
\(stumpmwm:add-hook stumpwm:*focus-frame-hook* 'my-rad-fn)
@end example"
`(setf ,hook (adjoin ,fn ,hook)))
(defmacro remove-hook (hook fn)
"Remove the specified function from the hook."
`(setf ,hook (remove ,fn ,hook)))
;; Misc. utility functions
(defun conc1 (list arg)
"Append arg to the end of list"
(nconc list (list arg)))
(defun sort1 (list sort-fn &rest keys &key &allow-other-keys)
"Return a sorted copy of list."
(let ((copy (copy-list list)))
(apply 'sort copy sort-fn keys)))
(defun mapcar-hash (fn hash)
"Just like maphash except it accumulates the result in a list."
(let ((accum nil))
(labels ((mapfn (key val)
(push (funcall fn key val) accum)))
(maphash #'mapfn hash))
accum))
(defun find-free-number (l &optional (min 0) dir)
"Return a number that is not in the list l. If dir is :negative then
look for a free number in the negative direction. anything else means
positive direction."
(let* ((dirfn (if (eq dir :negative) '> '<))
;; sort it and crop numbers below/above min depending on dir
(nums (sort (remove-if (lambda (n)
(funcall dirfn n min))
l) dirfn))
(max (car (last nums)))
(inc (if (eq dir :negative) -1 1))
(new-num (loop for n = min then (+ n inc)
for i in nums
when (/= n i)
do (return n))))
(dformat 3 "Free number: ~S~%" nums)
(if new-num
new-num
there was no space between the numbers , so use the
(if max
(+ inc max)
min))))
(defun remove-plist (plist &rest keys)
"Remove the keys from the plist.
Useful for re-using the &REST arg after removing some options."
(do (copy rest)
((null (setq rest (nth-value 2 (get-properties plist keys))))
(nreconc copy plist))
(do () ((eq plist rest))
(push (pop plist) copy)
(push (pop plist) copy))
(setq plist (cddr plist))))
(defun screen-display-string (screen &optional (assign t))
(format nil
(if assign "DISPLAY=~a:~d.~d" "~a:~d.~d")
(screen-host screen)
(xlib:display-display *display*)
(screen-id screen)))
(defun split-seq (seq separators &key test default-value)
"split a sequence into sub sequences given the list of seperators."
(let ((seps separators))
(labels ((sep (c)
(find c seps :test test)))
(or (loop for i = (position-if (complement #'sep) seq)
then (position-if (complement #'sep) seq :start j)
as j = (position-if #'sep seq :start (or i 0))
while i
collect (subseq seq i j)
while j)
the empty seq causes the above to return NIL , so help
;; it out a little.
default-value))))
(defun split-string (string &optional (separators "
"))
"Splits STRING into substrings where there are matches for SEPARATORS.
Each match for SEPARATORS is a splitting point.
The substrings between the splitting points are made into a list
which is returned.
***If SEPARATORS is absent, it defaults to \"[ \f\t\n\r\v]+\".
If there is match for SEPARATORS at the beginning of STRING, we do not
include a null substring for that. Likewise, if there is a match
at the end of STRING, we don't include a null substring for that.
Modifies the match data; use `save-match-data' if necessary."
(split-seq string separators :test #'char= :default-value '("")))
(defun insert-before (list item nth)
"Insert ITEM before the NTH element of LIST."
(declare (type (integer 0 *) nth))
(let* ((nth (min nth (length list)))
(pre (subseq list 0 nth))
(post (subseq list nth)))
(nconc pre (list item) post)))
(defvar *debug-level* 0
"Set this variable to a number > 0 to turn on debugging. The greater the number the more debugging output.")
(defvar *debug-expose-events* nil
"Set this variable for a visual indication of expose events on internal StumpWM windows.")
(defvar *debug-stream* *error-output*
"This is the stream debugging output is sent to. It defaults to
*error-output*. It may be more convenient for you to pipe debugging
output directly to a file.")
(defun dformat (level fmt &rest args)
(when (>= *debug-level* level)
(multiple-value-bind (sec m h) (decode-universal-time (get-universal-time))
(format *debug-stream* "~2,'0d:~2,'0d:~2,'0d " h m sec))
;; strip out non base-char chars quick-n-dirty like
(write-string (map 'string (lambda (ch)
(if (typep ch 'standard-char)
ch #\?))
(apply 'format nil fmt args))
*debug-stream*)))
(defvar *redirect-stream* nil
"This variable Keeps track of the stream all output is sent to when
`redirect-all-output' is called so if it changes we can close it
before reopening.")
(defun redirect-all-output (file)
"Elect to redirect all output to the specified file. For instance,
if you want everything to go to ~/stumpwm.d/debug-output.txt you would
do:
@example
(redirect-all-output (data-dir-file \"debug-output\" \"txt\"))
@end example
"
(when (typep *redirect-stream* 'file-stream)
(close *redirect-stream*))
(setf *redirect-stream* (open file :direction :output :if-exists :append :if-does-not-exist :create)
*error-output* *redirect-stream*
*standard-output* *redirect-stream*
*trace-output* *redirect-stream*
*debug-stream* *redirect-stream*))
;;;
;;; formatting routines
(defun format-expand (fmt-alist fmt &rest args)
(let* ((chars (coerce fmt 'list))
(output "")
(cur chars))
;; FIXME: this is horribly inneficient
(loop
(cond ((null cur)
(return-from format-expand output))
;; if % is the last char in the string then it's a literal.
((and (char= (car cur) #\%)
(cdr cur))
(setf cur (cdr cur))
(let* ((tmp (loop while (and cur (char<= #\0 (car cur) #\9))
collect (pop cur)))
(len (and tmp (parse-integer (coerce tmp 'string))))
So that eg " % 25^t " will trim from the left
(from-left-p (when (char= #\^ (car cur)) (pop cur))))
(if (null cur)
(format t "%~a~@[~a~]" len from-left-p)
(let* ((fmt (cadr (assoc (car cur) fmt-alist :test 'char=)))
(str (cond (fmt
;; it can return any type, not jut as string.
(format nil "~a" (apply fmt args)))
((char= (car cur) #\%)
(string #\%))
(t
(concatenate 'string (string #\%) (string (car cur)))))))
;; crop string if needed
(setf output (concatenate 'string output
(cond ((null len) str)
((not from-left-p) ; Default behavior
(subseq str 0 (min len (length str))))
;; New behavior -- trim from the left
(t (subseq str (max 0 (- (length str) len)))))))
(setf cur (cdr cur))))))
(t
(setf output (concatenate 'string output (string (car cur)))
cur (cdr cur)))))))
(defvar *window-formatters* '((#\n window-number)
(#\s fmt-window-status)
(#\t window-name)
(#\c window-class)
(#\i window-res)
(#\r window-role)
(#\m fmt-window-marked)
(#\h window-height)
(#\w window-width)
(#\g gravity-for-window))
"an alist containing format character format function pairs for formatting window lists.")
(defvar *window-format* "%m%n%s%50t"
"This variable decides how the window list is formatted. It is a string
with the following formatting options:
@table @asis
@item %n
Substitute the window number.
@item %s
Substitute the window's status. * means current window, + means last
window, and - means any other window.
@item %t
Substitute the window's name.
@item %c
Substitute the window's class.
@item %i
Substitute the window's resource ID.
@item %m
Draw a # if the window is marked.
@end table
Note, a prefix number can be used to crop the argument to a specified
size. For instance, @samp{%20t} crops the window's title to 20
characters.")
(defvar *window-info-format* "%wx%h %n (%t)"
"The format used in the info command. @xref{*window-format*} for formatting details.")
(defvar *group-formatters* '((#\n group-number)
(#\s fmt-group-status)
(#\t group-name))
"An alist of characters and formatter functions. The character can be
used as a format character in @var{*group-format*}. When the character
is encountered in the string, the corresponding function is called
with a group as an argument. The functions return value is inserted
into the string. If the return value isn't a string it is converted to
one using @code{prin1-to-string}.")
(defvar *group-format* "%n%s%t"
"The format string that decides what information will show up in the
group listing. The following format options are available:
@table @asis
@item %n
The group's number.
@item %s
The group's status. Similar to a window's status.
@item %t
The group's name.
@end table")
(defvar *list-hidden-groups* nil
"Controls whether hidden groups are displayed by 'groups' and 'vgroups' commands")
(defun font-height (font)
(+ (xlib:font-descent font)
(xlib:font-ascent font)))
(defvar *x-selection* nil
"This holds stumpwm's current selection. It is generally set
when killing text in the input bar.")
(defvar *last-command* nil
"Set to the last interactive command run.")
(defvar *max-last-message-size* 20
"how many previous messages to keep.")
(defvar *record-last-msg-override* nil
"assign this to T and messages won't be recorded. It is
recommended this is assigned using LET.")
(defvar *suppress-echo-timeout* nil
"Assign this T and messages will not time out. It is recommended this is assigned using LET.")
(defvar *ignore-echo-timeout* nil
"Assign this T and the message time out won't be touched. It is recommended this is assigned using LET.")
(defvar *run-or-raise-all-groups* t
"When this is @code{T} the @code{run-or-raise} function searches all groups for a
running instance. Set it to NIL to search only the current group.")
(defvar *run-or-raise-all-screens* nil
"When this is @code{T} the @code{run-or-raise} function searches all screens for a
running instance. Set it to @code{NIL} to search only the current screen. If
@var{*run-or-raise-all-groups*} is @code{NIL} this variable has no effect.")
(defvar *deny-map-request* nil
"A list of window properties that stumpwm should deny matching windows'
requests to become mapped for the first time.")
(defvar *deny-raise-request* nil
"Exactly the same as @var{*deny-map-request*} but for raise requests.
Note that no denial message is displayed if the window is already visible.")
(defvar *suppress-deny-messages* nil
"For complete focus on the task at hand, set this to @code{T} and no
raise/map denial messages will be seen.")
(defvar *honor-window-moves* t
"Allow windows to move between frames.")
(defvar *resize-hides-windows* nil
"Set to T to hide windows during interactive resize")
(defun deny-request-p (window deny-list)
(or (eq deny-list t)
(and
(listp deny-list)
(find-if (lambda (props)
(apply 'window-matches-properties-p window props))
deny-list)
t)))
(defun list-splice-replace (item list &rest replacements)
"splice REPLACEMENTS into LIST where ITEM is, removing
ITEM. Return the new list."
(let ((p (position item list)))
(if p
(nconc (subseq list 0 p) replacements (subseq list (1+ p)))
list)))
(defvar *min-frame-width* 50
"The minimum width a frame can be. A frame will not shrink below this
width. Splitting will not affect frames if the new frame widths are
less than this value.")
(defvar *min-frame-height* 50
"The minimum height a frame can be. A frame will not shrink below this
height. Splitting will not affect frames if the new frame heights are
less than this value.")
(defvar *new-frame-action* :last-window
"When a new frame is created, this variable controls what is put in the
new frame. Valid values are
@table @code
@item :empty
The frame is left empty
@item :last-window
The last focused window that is not currently visible is placed in the
frame. This is the default.
@end table")
(defvar *new-window-preferred-frame* '(:focused)
"This variable controls what frame a new window appears in. It is a
list of preferences. The first preference that is satisfied is
used. Valid list elements are as follows:
@table @code
@item :focused
Choose the focused frame.
@item :last
Choose the last focused frame.
@item :empty
Choose any empty frame.
@item :unfocused
Choose any unfocused frame.
@end table
Alternatively, it can be set to a function that takes one argument, the new
window, and returns the preferred frame or a list of the above preferences.")
(defun backtrace-string ()
"Similar to print-backtrace, but return the backtrace as a string."
(with-output-to-string (*standard-output*)
(print-backtrace)))
(defvar *startup-message* "^2*Welcome to The ^BStump^b ^BW^bindow ^BM^banager!
Press ^5*~a ?^2* for help."
"This is the message StumpWM displays when it starts. Set it to NIL to
suppress.")
(defvar *default-package* (find-package '#:stumpwm-user)
"This is the package eval reads and executes in. You might want to set
this to @code{:stumpwm} if you find yourself using a lot of internal
stumpwm symbols. Setting this variable anywhere but in your rc file
will have no effect.")
(defun concat (&rest strings)
(apply 'concatenate 'string strings))
(defvar *window-placement-rules* '()
"List of rules governing window placement. Use define-frame-preference to
add rules")
(defmacro define-frame-preference (target-group &rest frame-rules)
"Create a rule that matches windows and automatically places them in
a specified group and frame. Each frame rule is a lambda list:
@example
\(frame-number raise lock &key create restore dump-name class instance type role title)
@end example
@table @var
@item frame-number
The frame number to send matching windows to
@item raise
When non-nil, raise and focus the window in its frame
@item lock
When this is nil, this rule will only match when the current group
matches @var{target-group}. When non-nil, this rule matches regardless
of the group and the window is sent to @var{target-group}. If
@var{lock} and @var{raise} are both non-nil, then stumpwm will jump to
the specified group and focus the matched window.
@item create
When non-NIL the group is created and eventually restored when the value of
create is a group dump filename in *DATA-DIR*. Defaults to NIL.
@item restore
When non-NIL the group is restored even if it already exists. This arg should
be set to the dump filename to use for forced restore. Defaults to NIL
@item class
The window's class must match @var{class}.
@item instance
The window's instance/resource name must match @var{instance}.
@item type
The window's type must match @var{type}.
@item role
The window's role must match @var{role}.
@item title
The window's title must match @var{title}.
@end table"
(let ((x (gensym "X")))
`(dolist (,x ',frame-rules)
;; verify the correct structure
(destructuring-bind (frame-number raise lock
&rest keys
&key create restore class instance type role title) ,x
(declare (ignore create restore class instance type role title))
(push (list* ,target-group frame-number raise lock keys)
*window-placement-rules*)))))
(defun clear-window-placement-rules ()
"Clear all window placement rules."
(setf *window-placement-rules* nil))
(defvar *mouse-focus-policy* :ignore
"The mouse focus policy decides how the mouse affects input
focus. Possible values are :ignore, :sloppy, and :click. :ignore means
stumpwm ignores the mouse. :sloppy means input focus follows the
mouse; the window that the mouse is in gets the focus. :click means
input focus is transfered to the window you click on.")
(defvar *root-click-focuses-frame* t
"Set to NIL if you don't want clicking the root window to focus the frame
containing the pointer when *mouse-focus-policy* is :click.")
(defvar *banish-pointer-to* :head
"Where to put the pointer when no argument is given to (banish-pointer) or the banish
command. May be one of :screen :head :frame or :window")
(defvar *xwin-to-window* (make-hash-table)
"Hash table for looking up windows quickly.")
(defvar *resize-map* nil
"The keymap used for resizing a window")
(defvar *default-group-name* "Default"
"The name of the default group.")
(defmacro with-focus (xwin &body body)
"Set the focus to xwin, do body, then restore focus"
`(progn
(grab-keyboard ,xwin)
(unwind-protect
(progn ,@body)
(ungrab-keyboard))))
(defvar *last-unhandled-error* nil
"If an unrecoverable error occurs, this variable will contain the
condition and the backtrace.")
(defvar *show-command-backtrace* nil
"When this is T a backtrace is displayed with errors that occurred
within an interactive call to a command.")
(defvar *window-border-style* :thick
"This controls the appearance of the border around windows. valid
values are:
@table @var
@item :thick
All space within the frame not used by the window is dedicated to the
border.
@item :thin
Only the border width as controlled by *maxsize-border-width*
*normal-border-width* and *transient-border-width* is used as the
border. The rest is filled with the unfocus color.
@item :tight
The same as :thin but the border surrounds the window and the wasted
space within the frame is not obscured, revealing the background.
@item :none
Like :tight but no border is ever visible.
@end table
After changing this variable you may need to call
sync-all-frame-windows to see the change.")
(defvar *data-dir* (make-pathname :directory (append (pathname-directory (user-homedir-pathname))
(list ".stumpwm.d")))
"The directory used by stumpwm to store data between sessions.")
(defun data-dir-file (name &optional type)
"Return a pathname inside stumpwm's data dir with the specified name and type"
(ensure-directories-exist *data-dir*)
(make-pathname :name name :type type :defaults *data-dir*))
(defmacro with-data-file ((s file &rest keys &key (if-exists :supersede) &allow-other-keys) &body body)
"Open a file in StumpWM's data directory. keyword arguments are sent
directly to OPEN. Note that IF-EXISTS defaults to :supersede, instead
of :error."
(declare (ignorable if-exists))
`(progn
(ensure-directories-exist *data-dir*)
(with-open-file (,s ,(merge-pathnames *data-dir* file)
,@keys)
,@body)))
(defmacro move-to-head (list elt)
"Move the specified element in in LIST to the head of the list."
`(progn
(setf ,list (remove ,elt ,list))
(push ,elt ,list)))
(define-condition stumpwm-error (error)
() (:documentation "Any stumpwm specific error should inherit this."))
(defun intern1 (thing &optional (package *package*) (rt *readtable*))
"A DWIM intern."
(intern
(ecase (readtable-case rt)
(:upcase (string-upcase thing))
(:downcase (string-downcase thing))
Prooobably this is what they want ? It could make sense to
;; upcase them as well.
(:preserve thing)
(:invert (string-downcase thing)))
package))
| null | https://raw.githubusercontent.com/blitz/stumpwm/439180985920a628b18d4426f1a29b1c36576531/primitives.lisp | lisp |
you can redistribute it and/or modify
either version 2 , or ( at your option )
any later version.
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this software; see the file COPYING. If not, write to
Commentary:
This file contains primitive data structures and functions used
Code:
Message Timer
Hooks
(:_NET_WM_WINDOW_TYPE_DESKTOP . :desktop)
(:_NET_WM_WINDOW_TYPE_TOOLBAR . :toolbar)
(:_NET_WM_WINDOW_TYPE_MENU . :menu)
(:_NET_WM_WINDOW_TYPE_UTILITY . :utility)
(:_NET_WM_WINDOW_TYPE_SPLASH . :splash)
Window states
Message window variables
line editor
default values. use the set-* functions to these attributes
point back to the screen this head belongs to
a bar along the top or bottom that displays anything you want.
various colors (as returned by alloc-color)
color contexts
color maps
the window that has focus
The restarts menu macro
Hook functionality
Misc. utility functions
sort it and crop numbers below/above min depending on dir
it out a little.
use `save-match-data' if necessary."
strip out non base-char chars quick-n-dirty like
formatting routines
FIXME: this is horribly inneficient
if % is the last char in the string then it's a literal.
it can return any type, not jut as string.
crop string if needed
Default behavior
New behavior -- trim from the left
verify the correct structure
the window that the mouse is in gets the focus. :click means
upcase them as well. | Copyright ( C ) 2003 - 2008
This file is part of stumpwm .
it under the terms of the GNU General Public License as published by
stumpwm is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 ,
Boston , MA 02111 - 1307 USA
throughout stumpwm .
(in-package :stumpwm)
(export '(*suppress-abort-messages*
*suppress-frame-indicator*
*timeout-wait*
*timeout-frame-indicator-wait*
*frame-indicator-text*
*frame-indicator-timer*
*message-window-timer*
*urgent-window-hook*
*new-window-hook*
*destroy-window-hook*
*focus-window-hook*
*place-window-hook*
*start-hook*
*internal-loop-hook*
*focus-frame-hook*
*new-frame-hook*
*message-hook*
*top-level-error-hook*
*focus-group-hook*
*key-press-hook*
*root-click-hook*
*mode-line-click-hook*
*display*
*shell-program*
*maxsize-border-width*
*transient-border-width*
*normal-border-width*
*text-color*
*window-events*
*window-parent-events*
*message-window-padding*
*message-window-gravity*
*editor-bindings*
*input-window-gravity*
*normal-gravity*
*maxsize-gravity*
*transient-gravity*
*top-level-error-action*
*window-name-source*
*frame-number-map*
*all-modifiers*
*modifiers*
*screen-list*
*initializing*
*processing-existing-windows*
*executing-stumpwm-command*
*debug-level*
*debug-expose-events*
*debug-stream*
*window-formatters*
*window-format*
*group-formatters*
*group-format*
*list-hidden-groups*
*x-selection*
*last-command*
*max-last-message-size*
*record-last-msg-override*
*suppress-echo-timeout*
*run-or-raise-all-groups*
*run-or-raise-all-screens*
*deny-map-request*
*deny-raise-request*
*suppress-deny-messages*
*honor-window-moves*
*resize-hides-windows*
*min-frame-width*
*min-frame-height*
*new-frame-action*
*new-window-preferred-frame*
*startup-message*
*default-package*
*window-placement-rules*
*mouse-focus-policy*
*root-click-focuses-frame*
*banish-pointer-to*
*xwin-to-window*
*resize-map*
*default-group-name*
*window-border-style*
*data-dir*
add-hook
clear-window-placement-rules
data-dir-file
dformat
define-frame-preference
redirect-all-output
remove-hook
run-hook
run-hook-with-args
split-string
with-restarts-menu
with-data-file
move-to-head))
(defvar *suppress-abort-messages* nil
"Suppress abort message when non-nil.")
(defvar *timeout-wait* 5
"Specifies, in seconds, how long a message will appear for. This must
be an integer.")
(defvar *timeout-frame-indicator-wait* 1
"The amount of time a frame indicator timeout takes.")
(defvar *frame-indicator-timer* nil
"Keep track of the timer that hides the frame indicator.")
(defvar *frame-indicator-text* " Current Frame "
"What appears in the frame indicator window?")
(defvar *suppress-frame-indicator* nil
"Set this to T if you never want to see the frame indicator.")
(defvar *message-window-timer* nil
"Keep track of the timer that hides the message window.")
(defvar *urgent-window-hook* '()
"A hook called whenever a window sets the property indicating that
it demands the user's attention")
(defvar *map-window-hook* '()
"A hook called whenever a window is mapped.")
(defvar *unmap-window-hook* '()
"A hook called whenever a window is withdrawn.")
(defvar *new-window-hook* '()
"A hook called whenever a window is added to the window list. This
includes a genuinely new window as well as bringing a withdrawn window
back into the window list.")
(defvar *destroy-window-hook* '()
"A hook called whenever a window is destroyed or withdrawn.")
(defvar *focus-window-hook* '()
"A hook called when a window is given focus. It is called with 2
arguments: the current window and the last window (could be nil).")
(defvar *place-window-hook* '()
"A hook called whenever a window is placed by rule. Arguments are
window group and frame")
(defvar *start-hook* '()
"A hook called when stumpwm starts.")
(defvar *internal-loop-hook* '()
"A hook called inside stumpwm's inner loop.")
(defvar *focus-frame-hook* '()
"A hook called when a frame is given focus. The hook functions are
called with 2 arguments: the current frame and the last frame.")
(defvar *new-frame-hook* '()
"A hook called when a new frame is created. the hook is called with
the frame as an argument.")
(defvar *message-hook* '()
"A hook called whenever stumpwm displays a message. The hook
function is passed any number of arguments. Each argument is a
line of text.")
(defvar *top-level-error-hook* '()
"Called when a top level error occurs. Note that this hook is
run before the error is dealt with according to
*top-level-error-action*.")
(defvar *focus-group-hook* '()
"A hook called whenever stumpwm switches groups. It is called with 2 arguments: the current group and the last group.")
(defvar *key-press-hook* '()
"A hook called whenever a key under *top-map* is pressed.
It is called with 3 argument: the key, the (possibly incomplete) key
sequence it is a part of, and command value bound to the key.")
(defvar *root-click-hook* '()
"A hook called whenever there is a mouse click on the root
window. Called with 4 arguments, the screen containing the root
window, the button clicked, and the x and y of the pointer.")
(defvar *mode-line-click-hook* '()
"Called whenever the mode-line is clicked. It is called with 4 arguments,
the mode-line, the button clicked, and the x and y of the pointer.")
Data types and globals used by stumpwm
(defvar *display* nil
"The display for the X server")
(defvar *shell-program* "/bin/sh"
"The shell program used by @code{run-shell-command}.")
(defvar *maxsize-border-width* 1
"The width in pixels given to the borders of windows with maxsize or ratio hints.")
(defvar *transient-border-width* 1
"The width in pixels given to the borders of transient or pop-up windows.")
(defvar *normal-border-width* 1
"The width in pixels given to the borders of regular windows.")
(defvar *text-color* "white"
"The color of message text.")
(defparameter +netwm-supported+
'(:_NET_SUPPORTING_WM_CHECK
:_NET_NUMBER_OF_DESKTOPS
:_NET_DESKTOP_GEOMETRY
:_NET_DESKTOP_VIEWPORT
:_NET_CURRENT_DESKTOP
:_NET_WM_WINDOW_TYPE
:_NET_WM_STATE
:_NET_WM_STATE_MODAL
:_NET_WM_ALLOWED_ACTIONS
:_NET_WM_STATE_FULLSCREEN
:_NET_WM_STATE_HIDDEN
:_NET_WM_STATE_DEMANDS_ATTENTION
:_NET_WM_FULL_WINDOW_PLACEMENT
:_NET_CLOSE_WINDOW
:_NET_CLIENT_LIST
:_NET_CLIENT_LIST_STACKING
:_NET_ACTIVE_WINDOW
:_KDE_NET_SYSTEM_TRAY_WINDOW_FOR)
"Supported NETWM properties.
Window types are in +WINDOW-TYPES+.")
(defparameter +netwm-allowed-actions+
'(:_NET_WM_ACTION_CHANGE_DESKTOP
:_NET_WM_ACTION_FULLSCREEN
:_NET_WM_ACTION_CLOSE)
"Allowed NETWM actions for managed windows")
(defparameter +netwm-window-types+
'(
(:_NET_WM_WINDOW_TYPE_DOCK . :dock)
(:_NET_WM_WINDOW_TYPE_DIALOG . :dialog)
(:_NET_WM_WINDOW_TYPE_NORMAL . :normal))
"Alist mapping NETWM window types to keywords.
Include only those we are ready to support.")
(defconstant +withdrawn-state+ 0)
(defconstant +normal-state+ 1)
(defconstant +iconic-state+ 3)
(defvar *window-events* '(:structure-notify
:property-change
:colormap-change
:focus-change
:enter-window)
"The events to listen for on managed windows.")
(defvar *window-parent-events* '(:substructure-notify
:substructure-redirect)
"The events to listen for on managed windows' parents.")
(defvar *message-window-padding* 5
"The number of pixels that pad the text in the message window.")
(defvar *message-window-gravity* :top-right
"This variable controls where the message window appears. The follow
are valid values.
@table @asis
@item :top-left
@item :top-right
@item :bottom-left
@item :bottom-right
@item :center
@end table")
(defvar *editor-bindings* nil
"A list of key-bindings for line editing.")
(defvar *input-window-gravity* :top-right
"This variable controls where the input window appears. The follow
are valid values.
@table @asis
@item :top-left
@item :top-right
@item :bottom-left
@item :bottom-right
@item :center
@end table")
(defparameter +default-foreground-color+ "White")
(defparameter +default-background-color+ "Black")
(defparameter +default-window-background-color+ "Black")
(defparameter +default-border-color+ "White")
(defparameter +default-font-name+ "9x15bold")
(defparameter +default-focus-color+ "White")
(defparameter +default-unfocus-color+ "Black")
(defparameter +default-frame-outline-width+ 2)
Do n't set these variables directly , use set-<var name > instead
(defvar *normal-gravity* :center)
(defvar *maxsize-gravity* :center)
(defvar *transient-gravity* :center)
(defvar *top-level-error-action* :abort
"If an error is encountered at the top level, in
STUMPWM-INTERNAL-LOOP, then this variable decides what action
shall be taken. By default it will print a message to the screen
and to *standard-output*.
Valid values are :message, :break, :abort. :break will break to the
debugger. This can be problematic because if the user hit's a
mapped key the ENTIRE keyboard will be frozen and you will have
to login remotely to regain control. :abort quits stumpmwm.")
(defvar *window-name-source* :title
"This variable controls what is used for the window's name. The default is @code{:title}.
@table @code
@item :title
Use the window's title given to it by its owner.
@item :class
Use the window's resource class.
@item :resource-name
Use the window's resource name.
@end table")
(defstruct frame
(number nil :type integer)
x
y
width
height
window)
(defstruct (head (:include frame))
screen
mode-line)
(defclass screen ()
((id :initform nil :accessor screen-id)
(host :initform nil :accessor screen-host)
(number :initform nil :accessor screen-number)
(heads :initform nil :accessor screen-heads :documentation
"heads of screen")
(groups :initform nil :accessor screen-groups :documentation
"the list of groups available on this screen")
(current-group :initform nil :accessor screen-current-group)
(border-color :initform nil :accessor screen-border-color)
(fg-color :initform nil :accessor screen-fg-color)
(bg-color :initform nil :accessor screen-bg-color)
(win-bg-color :initform nil :accessor screen-win-bg-color)
(focus-color :initform nil :accessor screen-focus-color)
(unfocus-color :initform nil :accessor screen-unfocus-color)
(msg-border-width :initform nil :accessor screen-msg-border-width)
(frame-outline-width :initform nil :accessor screen-frame-outline-width)
(font :initform nil :accessor screen-font)
(mapped-windows :initform nil :accessor screen-mapped-windows :documentation
"A list of all mapped windows. These are the raw xlib:window's. window structures are stored in groups.")
(withdrawn-windows :initform nil :accessor screen-withdrawn-windows :documentation
"A list of withdrawn windows. These are of type stumpwm::window
and when they're mapped again they'll be put back in the group
they were in when they were unmapped unless that group doesn't
exist, in which case they go into the current group.")
(urgent-windows :initform nil :accessor screen-urgent-windows :documentation
"a list of windows for which (window-urgent-p) currently true.")
(input-window :initform nil :accessor screen-input-window)
(key-window :initform nil :accessor screen-key-window :documentation
"the window that accepts further keypresses after a toplevel key has been pressed.")
(focus-window :initform nil :accessor screen-focus-window :documentation
"The window that gets focus when no window has focus")
(frame-window :initform nil :accessor screen-frame-window)
(frame-outline-gc :initform nil :accessor screen-frame-outline-gc)
(message-cc :initform nil :accessor screen-message-cc)
(mode-line-cc :initform nil :accessor screen-mode-line-cc)
(color-map-normal :initform nil :accessor screen-color-map-normal)
(color-map-bright :initform nil :accessor screen-color-map-bright)
(ignore-msg-expose :initform nil :accessor screen-ignore-msg-expose :documentation
"used to ignore the first expose even when mapping the message window.")
(focus :initform nil :accessor screen-focus)
(current-msg :initform nil :accessor screen-current-msg)
(current-msg-highlights :initform nil :accessor screen-current-msg-highlights)
(last-msg :initform nil :accessor screen-last-msg)
(last-msg-highlights :initform nil :accessor screen-last-msg-highlights)))
(defstruct ccontext
win
px
gc
default-fg
default-bright
default-bg)
(defun screen-message-window (screen)
(ccontext-win (screen-message-cc screen)))
(defun screen-message-pixmap (screen)
(ccontext-px (screen-message-cc screen)))
(defun screen-message-gc (screen)
(ccontext-gc (screen-message-cc screen)))
(defmethod print-object ((object frame) stream)
(format stream "#S(frame ~d ~a ~d ~d ~d ~d)"
(frame-number object) (frame-window object) (frame-x object) (frame-y object) (frame-width object) (frame-height object)))
(defvar *frame-number-map* "0123456789abcdefghijklmnopqrstuvxwyz"
"Set this to a string to remap the frame numbers to more convenient keys.
For instance,
\"hutenosa\"
would map frame 0 to 7 to be selectable by hitting the appropriate
homerow key on a dvorak keyboard. Currently, only single char keys are
supported. By default, the frame labels are the 36 (lower-case)
alphanumeric characters, starting with numbers 0-9.")
(defun get-frame-number-translation (frame)
"Given a frame return its number translation using *frame-number-map* as a char."
(let ((num (frame-number frame)))
(or (and (< num (length *frame-number-map*))
(char *frame-number-map* num))
translate the frame number to a char . FIXME : it loops after 9
(char (prin1-to-string num) 0))))
(defstruct modifiers
(meta nil)
(alt nil)
(hyper nil)
(super nil)
(altgr nil)
(numlock nil))
(defvar *all-modifiers* nil
"A list of all keycodes that are considered modifiers")
(defvar *modifiers* nil
"A mapping from modifier type to x11 modifier.")
(defmethod print-object ((object screen) stream)
(format stream "#S<screen ~s>" (screen-number object)))
(defvar *screen-list* '()
"The list of screens managed by stumpwm.")
(defvar *initializing* nil
"True when starting stumpwm. Use this variable in your rc file to
run code that should only be executed once, when stumpwm starts up and
loads the rc file.")
(defvar *processing-existing-windows* nil
"True when processing pre-existing windows at startup.")
(defvar *executing-stumpwm-command* nil
"True when executing external commands.")
(defvar *interactivep* nil
"True when a defcommand is executed from colon or a keybinding")
(defmacro with-restarts-menu (&body body)
"Execute BODY. If an error occurs allow the user to pick a
restart from a menu of possible restarts. If a restart is not
chosen, resignal the error."
(let ((c (gensym)))
`(handler-bind
((warning #'muffle-warning)
((or serious-condition error)
(lambda (,c)
(restarts-menu ,c)
(signal ,c))))
,@body)))
(defun run-hook-with-args (hook &rest args)
"Call each function in HOOK and pass args to it."
(handler-case
(with-simple-restart (abort-hooks "Abort running the remaining hooks.")
(with-restarts-menu
(dolist (fn hook)
(with-simple-restart (continue-hooks "Continue running the remaining hooks.")
(apply fn args)))))
(t (c) (message "^B^1*Error on hook ^b~S^B!~% ^n~A" hook c) (values nil c))))
(defun run-hook (hook)
"Call each function in HOOK."
(run-hook-with-args hook))
(defmacro add-hook (hook fn)
"Add @var{function} to the hook @var{hook-variable}. For example, to
display a message whenever you switch frames:
@example
\(defun my-rad-fn (to-frame from-frame)
(stumpwm:message \"Mustard!\"))
\(stumpmwm:add-hook stumpwm:*focus-frame-hook* 'my-rad-fn)
@end example"
`(setf ,hook (adjoin ,fn ,hook)))
(defmacro remove-hook (hook fn)
"Remove the specified function from the hook."
`(setf ,hook (remove ,fn ,hook)))
(defun conc1 (list arg)
"Append arg to the end of list"
(nconc list (list arg)))
(defun sort1 (list sort-fn &rest keys &key &allow-other-keys)
"Return a sorted copy of list."
(let ((copy (copy-list list)))
(apply 'sort copy sort-fn keys)))
(defun mapcar-hash (fn hash)
"Just like maphash except it accumulates the result in a list."
(let ((accum nil))
(labels ((mapfn (key val)
(push (funcall fn key val) accum)))
(maphash #'mapfn hash))
accum))
(defun find-free-number (l &optional (min 0) dir)
"Return a number that is not in the list l. If dir is :negative then
look for a free number in the negative direction. anything else means
positive direction."
(let* ((dirfn (if (eq dir :negative) '> '<))
(nums (sort (remove-if (lambda (n)
(funcall dirfn n min))
l) dirfn))
(max (car (last nums)))
(inc (if (eq dir :negative) -1 1))
(new-num (loop for n = min then (+ n inc)
for i in nums
when (/= n i)
do (return n))))
(dformat 3 "Free number: ~S~%" nums)
(if new-num
new-num
there was no space between the numbers , so use the
(if max
(+ inc max)
min))))
(defun remove-plist (plist &rest keys)
"Remove the keys from the plist.
Useful for re-using the &REST arg after removing some options."
(do (copy rest)
((null (setq rest (nth-value 2 (get-properties plist keys))))
(nreconc copy plist))
(do () ((eq plist rest))
(push (pop plist) copy)
(push (pop plist) copy))
(setq plist (cddr plist))))
(defun screen-display-string (screen &optional (assign t))
(format nil
(if assign "DISPLAY=~a:~d.~d" "~a:~d.~d")
(screen-host screen)
(xlib:display-display *display*)
(screen-id screen)))
(defun split-seq (seq separators &key test default-value)
"split a sequence into sub sequences given the list of seperators."
(let ((seps separators))
(labels ((sep (c)
(find c seps :test test)))
(or (loop for i = (position-if (complement #'sep) seq)
then (position-if (complement #'sep) seq :start j)
as j = (position-if #'sep seq :start (or i 0))
while i
collect (subseq seq i j)
while j)
the empty seq causes the above to return NIL , so help
default-value))))
(defun split-string (string &optional (separators "
"))
"Splits STRING into substrings where there are matches for SEPARATORS.
Each match for SEPARATORS is a splitting point.
The substrings between the splitting points are made into a list
which is returned.
***If SEPARATORS is absent, it defaults to \"[ \f\t\n\r\v]+\".
If there is match for SEPARATORS at the beginning of STRING, we do not
include a null substring for that. Likewise, if there is a match
at the end of STRING, we don't include a null substring for that.
(split-seq string separators :test #'char= :default-value '("")))
(defun insert-before (list item nth)
"Insert ITEM before the NTH element of LIST."
(declare (type (integer 0 *) nth))
(let* ((nth (min nth (length list)))
(pre (subseq list 0 nth))
(post (subseq list nth)))
(nconc pre (list item) post)))
(defvar *debug-level* 0
"Set this variable to a number > 0 to turn on debugging. The greater the number the more debugging output.")
(defvar *debug-expose-events* nil
"Set this variable for a visual indication of expose events on internal StumpWM windows.")
(defvar *debug-stream* *error-output*
"This is the stream debugging output is sent to. It defaults to
*error-output*. It may be more convenient for you to pipe debugging
output directly to a file.")
(defun dformat (level fmt &rest args)
(when (>= *debug-level* level)
(multiple-value-bind (sec m h) (decode-universal-time (get-universal-time))
(format *debug-stream* "~2,'0d:~2,'0d:~2,'0d " h m sec))
(write-string (map 'string (lambda (ch)
(if (typep ch 'standard-char)
ch #\?))
(apply 'format nil fmt args))
*debug-stream*)))
(defvar *redirect-stream* nil
"This variable Keeps track of the stream all output is sent to when
`redirect-all-output' is called so if it changes we can close it
before reopening.")
(defun redirect-all-output (file)
"Elect to redirect all output to the specified file. For instance,
if you want everything to go to ~/stumpwm.d/debug-output.txt you would
do:
@example
(redirect-all-output (data-dir-file \"debug-output\" \"txt\"))
@end example
"
(when (typep *redirect-stream* 'file-stream)
(close *redirect-stream*))
(setf *redirect-stream* (open file :direction :output :if-exists :append :if-does-not-exist :create)
*error-output* *redirect-stream*
*standard-output* *redirect-stream*
*trace-output* *redirect-stream*
*debug-stream* *redirect-stream*))
(defun format-expand (fmt-alist fmt &rest args)
(let* ((chars (coerce fmt 'list))
(output "")
(cur chars))
(loop
(cond ((null cur)
(return-from format-expand output))
((and (char= (car cur) #\%)
(cdr cur))
(setf cur (cdr cur))
(let* ((tmp (loop while (and cur (char<= #\0 (car cur) #\9))
collect (pop cur)))
(len (and tmp (parse-integer (coerce tmp 'string))))
So that eg " % 25^t " will trim from the left
(from-left-p (when (char= #\^ (car cur)) (pop cur))))
(if (null cur)
(format t "%~a~@[~a~]" len from-left-p)
(let* ((fmt (cadr (assoc (car cur) fmt-alist :test 'char=)))
(str (cond (fmt
(format nil "~a" (apply fmt args)))
((char= (car cur) #\%)
(string #\%))
(t
(concatenate 'string (string #\%) (string (car cur)))))))
(setf output (concatenate 'string output
(cond ((null len) str)
(subseq str 0 (min len (length str))))
(t (subseq str (max 0 (- (length str) len)))))))
(setf cur (cdr cur))))))
(t
(setf output (concatenate 'string output (string (car cur)))
cur (cdr cur)))))))
(defvar *window-formatters* '((#\n window-number)
(#\s fmt-window-status)
(#\t window-name)
(#\c window-class)
(#\i window-res)
(#\r window-role)
(#\m fmt-window-marked)
(#\h window-height)
(#\w window-width)
(#\g gravity-for-window))
"an alist containing format character format function pairs for formatting window lists.")
(defvar *window-format* "%m%n%s%50t"
"This variable decides how the window list is formatted. It is a string
with the following formatting options:
@table @asis
@item %n
Substitute the window number.
@item %s
Substitute the window's status. * means current window, + means last
window, and - means any other window.
@item %t
Substitute the window's name.
@item %c
Substitute the window's class.
@item %i
Substitute the window's resource ID.
@item %m
Draw a # if the window is marked.
@end table
Note, a prefix number can be used to crop the argument to a specified
size. For instance, @samp{%20t} crops the window's title to 20
characters.")
(defvar *window-info-format* "%wx%h %n (%t)"
"The format used in the info command. @xref{*window-format*} for formatting details.")
(defvar *group-formatters* '((#\n group-number)
(#\s fmt-group-status)
(#\t group-name))
"An alist of characters and formatter functions. The character can be
used as a format character in @var{*group-format*}. When the character
is encountered in the string, the corresponding function is called
with a group as an argument. The functions return value is inserted
into the string. If the return value isn't a string it is converted to
one using @code{prin1-to-string}.")
(defvar *group-format* "%n%s%t"
"The format string that decides what information will show up in the
group listing. The following format options are available:
@table @asis
@item %n
The group's number.
@item %s
The group's status. Similar to a window's status.
@item %t
The group's name.
@end table")
(defvar *list-hidden-groups* nil
"Controls whether hidden groups are displayed by 'groups' and 'vgroups' commands")
(defun font-height (font)
(+ (xlib:font-descent font)
(xlib:font-ascent font)))
(defvar *x-selection* nil
"This holds stumpwm's current selection. It is generally set
when killing text in the input bar.")
(defvar *last-command* nil
"Set to the last interactive command run.")
(defvar *max-last-message-size* 20
"how many previous messages to keep.")
(defvar *record-last-msg-override* nil
"assign this to T and messages won't be recorded. It is
recommended this is assigned using LET.")
(defvar *suppress-echo-timeout* nil
"Assign this T and messages will not time out. It is recommended this is assigned using LET.")
(defvar *ignore-echo-timeout* nil
"Assign this T and the message time out won't be touched. It is recommended this is assigned using LET.")
(defvar *run-or-raise-all-groups* t
"When this is @code{T} the @code{run-or-raise} function searches all groups for a
running instance. Set it to NIL to search only the current group.")
(defvar *run-or-raise-all-screens* nil
"When this is @code{T} the @code{run-or-raise} function searches all screens for a
running instance. Set it to @code{NIL} to search only the current screen. If
@var{*run-or-raise-all-groups*} is @code{NIL} this variable has no effect.")
(defvar *deny-map-request* nil
"A list of window properties that stumpwm should deny matching windows'
requests to become mapped for the first time.")
(defvar *deny-raise-request* nil
"Exactly the same as @var{*deny-map-request*} but for raise requests.
Note that no denial message is displayed if the window is already visible.")
(defvar *suppress-deny-messages* nil
"For complete focus on the task at hand, set this to @code{T} and no
raise/map denial messages will be seen.")
(defvar *honor-window-moves* t
"Allow windows to move between frames.")
(defvar *resize-hides-windows* nil
"Set to T to hide windows during interactive resize")
(defun deny-request-p (window deny-list)
(or (eq deny-list t)
(and
(listp deny-list)
(find-if (lambda (props)
(apply 'window-matches-properties-p window props))
deny-list)
t)))
(defun list-splice-replace (item list &rest replacements)
"splice REPLACEMENTS into LIST where ITEM is, removing
ITEM. Return the new list."
(let ((p (position item list)))
(if p
(nconc (subseq list 0 p) replacements (subseq list (1+ p)))
list)))
(defvar *min-frame-width* 50
"The minimum width a frame can be. A frame will not shrink below this
width. Splitting will not affect frames if the new frame widths are
less than this value.")
(defvar *min-frame-height* 50
"The minimum height a frame can be. A frame will not shrink below this
height. Splitting will not affect frames if the new frame heights are
less than this value.")
(defvar *new-frame-action* :last-window
"When a new frame is created, this variable controls what is put in the
new frame. Valid values are
@table @code
@item :empty
The frame is left empty
@item :last-window
The last focused window that is not currently visible is placed in the
frame. This is the default.
@end table")
(defvar *new-window-preferred-frame* '(:focused)
"This variable controls what frame a new window appears in. It is a
list of preferences. The first preference that is satisfied is
used. Valid list elements are as follows:
@table @code
@item :focused
Choose the focused frame.
@item :last
Choose the last focused frame.
@item :empty
Choose any empty frame.
@item :unfocused
Choose any unfocused frame.
@end table
Alternatively, it can be set to a function that takes one argument, the new
window, and returns the preferred frame or a list of the above preferences.")
(defun backtrace-string ()
"Similar to print-backtrace, but return the backtrace as a string."
(with-output-to-string (*standard-output*)
(print-backtrace)))
(defvar *startup-message* "^2*Welcome to The ^BStump^b ^BW^bindow ^BM^banager!
Press ^5*~a ?^2* for help."
"This is the message StumpWM displays when it starts. Set it to NIL to
suppress.")
(defvar *default-package* (find-package '#:stumpwm-user)
"This is the package eval reads and executes in. You might want to set
this to @code{:stumpwm} if you find yourself using a lot of internal
stumpwm symbols. Setting this variable anywhere but in your rc file
will have no effect.")
(defun concat (&rest strings)
(apply 'concatenate 'string strings))
(defvar *window-placement-rules* '()
"List of rules governing window placement. Use define-frame-preference to
add rules")
(defmacro define-frame-preference (target-group &rest frame-rules)
"Create a rule that matches windows and automatically places them in
a specified group and frame. Each frame rule is a lambda list:
@example
\(frame-number raise lock &key create restore dump-name class instance type role title)
@end example
@table @var
@item frame-number
The frame number to send matching windows to
@item raise
When non-nil, raise and focus the window in its frame
@item lock
When this is nil, this rule will only match when the current group
matches @var{target-group}. When non-nil, this rule matches regardless
of the group and the window is sent to @var{target-group}. If
@var{lock} and @var{raise} are both non-nil, then stumpwm will jump to
the specified group and focus the matched window.
@item create
When non-NIL the group is created and eventually restored when the value of
create is a group dump filename in *DATA-DIR*. Defaults to NIL.
@item restore
When non-NIL the group is restored even if it already exists. This arg should
be set to the dump filename to use for forced restore. Defaults to NIL
@item class
The window's class must match @var{class}.
@item instance
The window's instance/resource name must match @var{instance}.
@item type
The window's type must match @var{type}.
@item role
The window's role must match @var{role}.
@item title
The window's title must match @var{title}.
@end table"
(let ((x (gensym "X")))
`(dolist (,x ',frame-rules)
(destructuring-bind (frame-number raise lock
&rest keys
&key create restore class instance type role title) ,x
(declare (ignore create restore class instance type role title))
(push (list* ,target-group frame-number raise lock keys)
*window-placement-rules*)))))
(defun clear-window-placement-rules ()
"Clear all window placement rules."
(setf *window-placement-rules* nil))
(defvar *mouse-focus-policy* :ignore
"The mouse focus policy decides how the mouse affects input
focus. Possible values are :ignore, :sloppy, and :click. :ignore means
stumpwm ignores the mouse. :sloppy means input focus follows the
input focus is transfered to the window you click on.")
(defvar *root-click-focuses-frame* t
"Set to NIL if you don't want clicking the root window to focus the frame
containing the pointer when *mouse-focus-policy* is :click.")
(defvar *banish-pointer-to* :head
"Where to put the pointer when no argument is given to (banish-pointer) or the banish
command. May be one of :screen :head :frame or :window")
(defvar *xwin-to-window* (make-hash-table)
"Hash table for looking up windows quickly.")
(defvar *resize-map* nil
"The keymap used for resizing a window")
(defvar *default-group-name* "Default"
"The name of the default group.")
(defmacro with-focus (xwin &body body)
"Set the focus to xwin, do body, then restore focus"
`(progn
(grab-keyboard ,xwin)
(unwind-protect
(progn ,@body)
(ungrab-keyboard))))
(defvar *last-unhandled-error* nil
"If an unrecoverable error occurs, this variable will contain the
condition and the backtrace.")
(defvar *show-command-backtrace* nil
"When this is T a backtrace is displayed with errors that occurred
within an interactive call to a command.")
(defvar *window-border-style* :thick
"This controls the appearance of the border around windows. valid
values are:
@table @var
@item :thick
All space within the frame not used by the window is dedicated to the
border.
@item :thin
Only the border width as controlled by *maxsize-border-width*
*normal-border-width* and *transient-border-width* is used as the
border. The rest is filled with the unfocus color.
@item :tight
The same as :thin but the border surrounds the window and the wasted
space within the frame is not obscured, revealing the background.
@item :none
Like :tight but no border is ever visible.
@end table
After changing this variable you may need to call
sync-all-frame-windows to see the change.")
(defvar *data-dir* (make-pathname :directory (append (pathname-directory (user-homedir-pathname))
(list ".stumpwm.d")))
"The directory used by stumpwm to store data between sessions.")
(defun data-dir-file (name &optional type)
"Return a pathname inside stumpwm's data dir with the specified name and type"
(ensure-directories-exist *data-dir*)
(make-pathname :name name :type type :defaults *data-dir*))
(defmacro with-data-file ((s file &rest keys &key (if-exists :supersede) &allow-other-keys) &body body)
"Open a file in StumpWM's data directory. keyword arguments are sent
directly to OPEN. Note that IF-EXISTS defaults to :supersede, instead
of :error."
(declare (ignorable if-exists))
`(progn
(ensure-directories-exist *data-dir*)
(with-open-file (,s ,(merge-pathnames *data-dir* file)
,@keys)
,@body)))
(defmacro move-to-head (list elt)
"Move the specified element in in LIST to the head of the list."
`(progn
(setf ,list (remove ,elt ,list))
(push ,elt ,list)))
(define-condition stumpwm-error (error)
() (:documentation "Any stumpwm specific error should inherit this."))
(defun intern1 (thing &optional (package *package*) (rt *readtable*))
"A DWIM intern."
(intern
(ecase (readtable-case rt)
(:upcase (string-upcase thing))
(:downcase (string-downcase thing))
Prooobably this is what they want ? It could make sense to
(:preserve thing)
(:invert (string-downcase thing)))
package))
|
4bdbb8ba7415409cd0690579fd3488669330096360aa11577eed87250b2262cc | simedw/Kandidat | Debugger.hs | # LANGUAGE NamedFieldPuns #
{-# LANGUAGE PackageImports #-}
# LANGUAGE PatternGuards #
# LANGUAGE RecordWildCards #
module Debugger where
import "mtl" Control.Monad.State
import Data.Function
import Data.List
import qualified Data.Map as M
import System( getArgs )
import System.Console.GetOpt
import System.Directory
import System.FilePath
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import Text.PrettyPrint.ANSI.Leijen(Doc)
import System.Console.Haskeline (InputT, outputStrLn, getInputLine)
import qualified System.Console.Haskeline as Hl
import Text.ParserCombinators.Parsec
import Parser.Diabetes
import qualified Parser.Locals as Locals
import Parser.Pretty.Pretty
import Parser.SugarParser
import Parser.STGParser
import Stg.AST
import Stg.GC
import Stg.Input
import Stg.Interpreter
import Shared.BoxPrimitives
import Stg.Rules
import Stg.Types hiding (settings)
import qualified Stg.Types as ST
import Stg.Heap (Heap,Location(..))
import qualified Stg.Heap as H
import Util
data Settings = Settings
{ steping :: Bool
, lset :: LoadSettings
, quiet :: Bool
, forceStg :: Bool
, toGC :: Bool
}
type Result = (Rule, StgState String)
data BreakPoint
= AtRule Rule
| AtCall String
deriving (Eq, Show)
evalBP :: BreakPoint -> Result -> Bool
evalBP bp (rule, _) = case bp of
AtRule r -> r == rule
i d - > case code of
ECall fid _ - > i d = = fid
stgState : : Bool - > Bool - > Bool - > StgState String - > String
stgState sc ss sh st@(StgState { code , stack , heap } ) =
showi sc " code " ( show ( prExpr PP.text code ) )
+ + showi ss ( " stack ( " + + show ( length stack ) + + " ) " ) ( show stack )
+ + showi sh ( " heap("++ show ( H.size heap ) + + " ) " ) ( concat [ show ( i d , prObj PP.text obj ) + + " \n\t "
| ( i d , obj ) < - H.toList heap ] )
where
showi : : Bool - > String - > String - > String
showi True s d = s + + " : " + + d + + " \n "
showi False s _ = s + + " \n "
stgState :: Bool -> Bool -> Bool -> StgState String -> String
stgState sc ss sh st@(StgState {code, stack, heap}) =
showi sc "code" (show (prExpr PP.text code))
++ showi ss ("stack(" ++ show (length stack) ++ ")") (show stack)
++ showi sh ("heap("++ show (H.size heap) ++")") (concat [ show (id, prObj PP.text obj) ++ "\n\t"
| (id, obj) <- H.toList heap])
where
showi :: Bool -> String -> String -> String
showi True s d = s ++ ": " ++ d ++ "\n"
showi False s _ = s ++ "\n"
-}
defaultSettings = Settings {
steping = True
, lset = LSettings "Prelude.hls" defaultInput False
, quiet = False
, forceStg = False
, toGC = True
}
noheapSettings = defaultSettings { showStgState = stgState True True False }
data InterpreterState = IS
{ settings :: Settings
, stgm :: StgMState String
, history :: ![Result]
, breakPoints :: ![BreakPoint]
, nrRules :: !Int
, saveHist :: !Bool
}
testInterpreter :: Settings -> FilePath -> IO ()
testInterpreter set file = do
fs <- loadFileSpecifyOutput True (lset set) file
let st = initialState fs
evalStateT (Hl.runInputT Hl.defaultSettings (loop st)) IS
{ settings = set
, stgm = initialStgMState
, history = []
, breakPoints = []
, nrRules = 0
, saveHist = not False
}
loop :: StgState String -> InputT (StateT InterpreterState IO) ()
loop originalState = do
minput <- getInputLine "% "
set <- lift $ gets settings
let st = (if toGC set then gc else id) originalState
case minput of
Nothing -> return ()
Just xs -> case words xs of
[] -> evalStep 1 st
[":q"] -> return ()
":v" : xs -> loopView st xs
":view" : xs -> loopView st xs
":bp" : xs -> addbp xs >> loop st
[":bpo"] -> addbp ["rule", "ROptimise"] >> evalStep 1000000000 st
[":bpd"] -> addbp ["rule", "ROpt", "ORDone"] >> evalStep 100000000 st
[":back", num] -> case reads num of
((x, "") : _) -> evalStep (negate x) st
_ -> loop st
[":step", num] -> case reads num of
((x, "") : _) -> evalStep x st
_ -> loop st
-- [":force!"] -> forcing st >> loop st
-- [":force", var] -> forceit st var >> loop st
[":h"] -> printHelp >> loop st
[":help"] -> printHelp >> loop st
[":popFrame"] -> loop st
input -> do
outputStrLn $ "oh hoi: " ++ unwords input
loop st
where
gc = mkGC ["$True", "$False"]
bp :: [BreakPoint] -> Result -> Maybe BreakPoint
bp [] _ = Nothing
bp (b : bs) r | evalBP b r = Just b
| otherwise = bp bs r
forcing st = do
stg < - lift $ gets stgm
outputStrLn . fst $ runState ( force st ) stg
forceit st var = do
stg < - lift $ gets stgm
case ( ) " " var of
Left r - > return ( )
Right x - > do
s < - liftIO $ catch ( return $ Just . fst $ runState ( force $ st { code = ( EAtom x ) } ) stg ) ( \ _ - > return $ Nothing )
case s of
Nothing - > outputStrLn " Something bad has happend "
Just x - > outputStrLn x
forcing st = do
stg <- lift $ gets stgm
outputStrLn . fst $ runState (force st) stg
forceit st var = do
stg <- lift $ gets stgm
case runParser Parser.STGParser.atom () "" var of
Left r -> return ()
Right x -> do
s <- liftIO $ catch (return $ Just . fst $ runState (force $ st {code = (EAtom x)} ) stg) (\_ -> return $ Nothing)
case s of
Nothing -> outputStrLn "Something bad has happend"
Just x -> outputStrLn x
-}
evalStep n s | n == 0 = printSummary s
| n < 0 = do
hist <- lift . gets $ history
case hist of
[] -> printSummary s
(_, s') : xs -> do
lift . modify $ \set -> set { history = xs, nrRules = nrRules set - 1}
evalStep (n + 1) s'
| otherwise = do
stg <- lift $ gets stgm
bps <- lift . gets $ breakPoints
case runStgM (step s) stg of
(Nothing, stg') -> do
outputStrLn "No Rule applied"
loop s
(Just res@(_, s'), stg')
| Just b <- bp bps res -> do
addHistory res
lift . modify $ \set -> set { stgm = stg' }
outputStrLn $ "BreakPoint! " ++ show b
printSummary s'
| otherwise -> do
addHistory res
lift . modify $ \set -> set { stgm = stg' }
evalStep (n - 1) s'
addHistory res = do
sv <- lift . gets $ saveHist
lift . modify $ \set -> set { history = if sv
then res : history set
else history set
, nrRules = nrRules set + 1}
addbp xs = case xs of
"rule": rs -> case reads (unwords rs) of
(r', "") : _ -> do
outputStrLn "ok"
lift . modify $ \set -> set { breakPoints = AtRule r' : breakPoints set }
_ -> outputStrLn "can't parse that rule"
["call", f] -> do
outputStrLn "ok"
lift . modify $ \set -> set { breakPoints = AtCall f : breakPoints set }
_ -> outputStrLn "Sirisly u want m3 too parse that?"
printSummary st = do
hist <- lift (gets history)
case st of
StgState {} -> return ()
OmegaState {} -> outputStrLn "Omega:"
PsiState {} -> outputStrLn "Psi:"
IrrState {} -> outputStrLn "Irr:"
case hist of
[] -> do
outputStrLn $ "Rule: " ++ show RInitial
printCode $ code st
printCStack True $ cstack st
outputStrLn $ "heap(" ++ show (M.size $ heap st) ++ ")"
loop st
(rule, st) : _ -> do
outputStrLn $ "Rule: " ++ show rule
printCode $ code st
printCStack True $ cstack st
outputStrLn $ "heap(" ++ show (M.size $ heap st) ++ ")"
outputStrLn $ "astack\n" ++ showDoc (prAStack PP.text $ astack st)
loop st
loopView st xs = do
case xs of
["h"] -> printHeap (heap st)
["heap"] -> printHeap (heap st)
"heap":fs -> mapM_ (printHeapLookup (heap st)) fs
"h":fs -> mapM_ (printHeapLookup (heap st)) fs
["set"] -> printSetting =<< lift (gets settings)
["settings"] -> printSetting =<< lift (gets settings)
["s"] -> printCStack False (cstack st)
["stack"] -> printCStack False (cstack st)
["c"] -> printCode (code st)
["code"] -> printCode (code st)
["rules"] -> printRules
["sum"] -> printSummary st
["bp"] -> do
bps <- lift (gets breakPoints)
outputStrLn $ show bps
_ -> outputStrLn "wouldn't we all?"
loop st
printSetting set = do
outputStrLn "Current Settings:"
mapM_ (outputStrLn . show)
[ "steping" ~> steping set
, "quiet" ~> quiet set
, "forceStg" ~> forceStg set
, "toGC" ~> toGC set
]
where
(~>) = (,)
printCode code = outputStrLn $ "code: " ++ show (prExpr PP.text code)
printCStack b cstack = do
outputStrLn $ "stack(" ++ show (length cstack) ++ "):"
outputStrLn $ show (prCStack PP.text (if b then take 5 cstack else id cstack))
if b && length cstack >= 5
then outputStrLn "..."
else return ()
printHeapLookup heap f = outputStrLn $ printHeapFunctions $ M.filterWithKey (\k _ -> k == f) heap
printHeap heap = outputStrLn $ "heap(" ++ show (M.size heap) ++ "): \n"
++ printHeapFunctions heap
printHeapFunctions :: Heap String -> String
printHeapFunctions heap = concat
[ padFunction (id ++ if loc == OnAbyss then "!" else ""
, show $ prObj PP.text obj)
| (id, (obj, loc)) <- H.toList heap]
where
padFunction :: (String, String) -> String
padFunction (id, obj) = unlines . map (" " ++) $ case lines obj of
[] -> []
x : xs -> (id ++ " = " ++ x)
: map (\y -> replicate (length id + 3) ' ' ++ y) xs
printRules = do
ruls <- lift $ gets history
nrR <- lift . gets $ nrRules
outputStrLn $ "number of rules: " ++ show (nrR)
outputStrLn $ "number of rules: " ++ show (length ruls)
outputStrLn . show . map (\ list -> (head list, length list))
. group . sort . map fst $ ruls
printHelp = do
mapM_ outputStrLn
[ "Oh hi! This is the Interpreter speaking"
, "Press the following to do the following"
, ":q - to quit"
, ":v or :view - to view something"
, " h or heap - the heap"
, " accepts a list of heap objects to be printed"
, " s or stack - the stack"
, " c or code - the code"
, " rules - the number of rules fired"
, " sum - a summary"
, " bp - the current breakpoints"
, ":bp - to add a new breakpoint"
, " rule <rule> - for that <rule>"
, " call <id> - when calling <id>"
, ":step <n> - step <n> steps :)"
, ":back <n> - step <-n> steps (history)"
, ":force! - forced evaulation"
, ""
, "Happy Hacking !!"
]
showDoc :: Doc -> String
showDoc x = PP.displayS (PP.renderPretty 0.8 80 x) ""
main :: IO ()
main = do
First argument is the filename
file:args <- getArgs
print $ args
case getOpt RequireOrder options args of
(flags, [], []) -> do
opts <- foldl (>>=) (return defaultSettings) flags
-- if forceStg opts
then loadFile opts file > > = forceInterpreter > > return ( )
else opts file
testInterpreter opts file
(_, nonOpts, []) -> error $ "unrecognized arguments: " ++ unwords nonOpts
(_, _, msgs) -> error $ concat msgs ++ usageInfo header options
data Flag = Version
options :: [OptDescr (Settings -> IO Settings)]
options =
[ Option ['S'] ["step"] (ReqArg setSteping "BOOL") "step through"
, Option ['F'] ["force"] (ReqArg setForce "Bool") "force evaluation"
, Option [ ' V ' ] [ " visible " ] ( ReqArg setVisible " \"BOOL BOOL BOOL\ " " ) " show code stack heap "
, Option ['i'] ["integer-input"]
(ReqArg setInputInteger "Integer")
"single integer input"
, Option ['d'] ["double-input"]
(ReqArg setInputDouble "Double")
"single double input"
, Option ['I'] ["list-integer-input"]
(ReqArg setInputIntegers "[Integer]")
"integer list input"
, Option ['D'] ["list-double-input"]
(ReqArg setInputDoubles "[Double]")
"double list input"
, Option ['s'] ["string-input"]
(ReqArg setInputString "String")
"string input"
]
setSteping :: String -> Settings -> IO Settings
setSteping arg s = return $ s { steping = read arg }
setVisible : : String- > Settings - > IO Settings
set = let ( arg : : arg3 : _ ) = words = read arg3
s = read c = read arg
in return $ set { showStgState = stgState c s h }
setVisible :: String-> Settings -> IO Settings
setVisible ind set = let (arg: arg2: arg3:_) = words ind
h = read arg3
s = read arg2
c = read arg
in return $ set { showStgState = stgState c s h }
-}
setForce :: String -> Settings -> IO Settings
setForce arg set = return $ set { forceStg = read arg }
setInputInteger :: String -> Settings -> IO Settings
setInputInteger arg s =
return $ s { lset = (lset s) {input = (input (lset s)) { inputInteger = Just (read arg) }}}
setInputIntegers :: String -> Settings -> IO Settings
setInputIntegers arg s =
return $ s { lset = (lset s) { input = (input (lset s)) { inputIntegers = Just (read arg) }}}
setInputDouble :: String -> Settings -> IO Settings
setInputDouble arg s =
return $ s { lset = (lset s) {input = (input (lset s)) { inputDouble = Just (read arg) }}}
setInputDoubles :: String -> Settings -> IO Settings
setInputDoubles arg s =
return $ s { lset = (lset s) { input = (input (lset s)) { inputDoubles = Just (read arg) }}}
setInputString :: String -> Settings -> IO Settings
setInputString arg s =
return $ s { lset = (lset s) { input = (input (lset s)) { inputString = Just arg }}}
header = "Usage: main [OPTION...]"
| null | https://raw.githubusercontent.com/simedw/Kandidat/fbf68edf5b003aba2ce13dac32ee1b94172d57d8/test/Debugger.hs | haskell | # LANGUAGE PackageImports #
[":force!"] -> forcing st >> loop st
[":force", var] -> forceit st var >> loop st
if forceStg opts | # LANGUAGE NamedFieldPuns #
# LANGUAGE PatternGuards #
# LANGUAGE RecordWildCards #
module Debugger where
import "mtl" Control.Monad.State
import Data.Function
import Data.List
import qualified Data.Map as M
import System( getArgs )
import System.Console.GetOpt
import System.Directory
import System.FilePath
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import Text.PrettyPrint.ANSI.Leijen(Doc)
import System.Console.Haskeline (InputT, outputStrLn, getInputLine)
import qualified System.Console.Haskeline as Hl
import Text.ParserCombinators.Parsec
import Parser.Diabetes
import qualified Parser.Locals as Locals
import Parser.Pretty.Pretty
import Parser.SugarParser
import Parser.STGParser
import Stg.AST
import Stg.GC
import Stg.Input
import Stg.Interpreter
import Shared.BoxPrimitives
import Stg.Rules
import Stg.Types hiding (settings)
import qualified Stg.Types as ST
import Stg.Heap (Heap,Location(..))
import qualified Stg.Heap as H
import Util
data Settings = Settings
{ steping :: Bool
, lset :: LoadSettings
, quiet :: Bool
, forceStg :: Bool
, toGC :: Bool
}
type Result = (Rule, StgState String)
data BreakPoint
= AtRule Rule
| AtCall String
deriving (Eq, Show)
evalBP :: BreakPoint -> Result -> Bool
evalBP bp (rule, _) = case bp of
AtRule r -> r == rule
i d - > case code of
ECall fid _ - > i d = = fid
stgState : : Bool - > Bool - > Bool - > StgState String - > String
stgState sc ss sh st@(StgState { code , stack , heap } ) =
showi sc " code " ( show ( prExpr PP.text code ) )
+ + showi ss ( " stack ( " + + show ( length stack ) + + " ) " ) ( show stack )
+ + showi sh ( " heap("++ show ( H.size heap ) + + " ) " ) ( concat [ show ( i d , prObj PP.text obj ) + + " \n\t "
| ( i d , obj ) < - H.toList heap ] )
where
showi : : Bool - > String - > String - > String
showi True s d = s + + " : " + + d + + " \n "
showi False s _ = s + + " \n "
stgState :: Bool -> Bool -> Bool -> StgState String -> String
stgState sc ss sh st@(StgState {code, stack, heap}) =
showi sc "code" (show (prExpr PP.text code))
++ showi ss ("stack(" ++ show (length stack) ++ ")") (show stack)
++ showi sh ("heap("++ show (H.size heap) ++")") (concat [ show (id, prObj PP.text obj) ++ "\n\t"
| (id, obj) <- H.toList heap])
where
showi :: Bool -> String -> String -> String
showi True s d = s ++ ": " ++ d ++ "\n"
showi False s _ = s ++ "\n"
-}
defaultSettings = Settings {
steping = True
, lset = LSettings "Prelude.hls" defaultInput False
, quiet = False
, forceStg = False
, toGC = True
}
noheapSettings = defaultSettings { showStgState = stgState True True False }
data InterpreterState = IS
{ settings :: Settings
, stgm :: StgMState String
, history :: ![Result]
, breakPoints :: ![BreakPoint]
, nrRules :: !Int
, saveHist :: !Bool
}
testInterpreter :: Settings -> FilePath -> IO ()
testInterpreter set file = do
fs <- loadFileSpecifyOutput True (lset set) file
let st = initialState fs
evalStateT (Hl.runInputT Hl.defaultSettings (loop st)) IS
{ settings = set
, stgm = initialStgMState
, history = []
, breakPoints = []
, nrRules = 0
, saveHist = not False
}
loop :: StgState String -> InputT (StateT InterpreterState IO) ()
loop originalState = do
minput <- getInputLine "% "
set <- lift $ gets settings
let st = (if toGC set then gc else id) originalState
case minput of
Nothing -> return ()
Just xs -> case words xs of
[] -> evalStep 1 st
[":q"] -> return ()
":v" : xs -> loopView st xs
":view" : xs -> loopView st xs
":bp" : xs -> addbp xs >> loop st
[":bpo"] -> addbp ["rule", "ROptimise"] >> evalStep 1000000000 st
[":bpd"] -> addbp ["rule", "ROpt", "ORDone"] >> evalStep 100000000 st
[":back", num] -> case reads num of
((x, "") : _) -> evalStep (negate x) st
_ -> loop st
[":step", num] -> case reads num of
((x, "") : _) -> evalStep x st
_ -> loop st
[":h"] -> printHelp >> loop st
[":help"] -> printHelp >> loop st
[":popFrame"] -> loop st
input -> do
outputStrLn $ "oh hoi: " ++ unwords input
loop st
where
gc = mkGC ["$True", "$False"]
bp :: [BreakPoint] -> Result -> Maybe BreakPoint
bp [] _ = Nothing
bp (b : bs) r | evalBP b r = Just b
| otherwise = bp bs r
forcing st = do
stg < - lift $ gets stgm
outputStrLn . fst $ runState ( force st ) stg
forceit st var = do
stg < - lift $ gets stgm
case ( ) " " var of
Left r - > return ( )
Right x - > do
s < - liftIO $ catch ( return $ Just . fst $ runState ( force $ st { code = ( EAtom x ) } ) stg ) ( \ _ - > return $ Nothing )
case s of
Nothing - > outputStrLn " Something bad has happend "
Just x - > outputStrLn x
forcing st = do
stg <- lift $ gets stgm
outputStrLn . fst $ runState (force st) stg
forceit st var = do
stg <- lift $ gets stgm
case runParser Parser.STGParser.atom () "" var of
Left r -> return ()
Right x -> do
s <- liftIO $ catch (return $ Just . fst $ runState (force $ st {code = (EAtom x)} ) stg) (\_ -> return $ Nothing)
case s of
Nothing -> outputStrLn "Something bad has happend"
Just x -> outputStrLn x
-}
evalStep n s | n == 0 = printSummary s
| n < 0 = do
hist <- lift . gets $ history
case hist of
[] -> printSummary s
(_, s') : xs -> do
lift . modify $ \set -> set { history = xs, nrRules = nrRules set - 1}
evalStep (n + 1) s'
| otherwise = do
stg <- lift $ gets stgm
bps <- lift . gets $ breakPoints
case runStgM (step s) stg of
(Nothing, stg') -> do
outputStrLn "No Rule applied"
loop s
(Just res@(_, s'), stg')
| Just b <- bp bps res -> do
addHistory res
lift . modify $ \set -> set { stgm = stg' }
outputStrLn $ "BreakPoint! " ++ show b
printSummary s'
| otherwise -> do
addHistory res
lift . modify $ \set -> set { stgm = stg' }
evalStep (n - 1) s'
addHistory res = do
sv <- lift . gets $ saveHist
lift . modify $ \set -> set { history = if sv
then res : history set
else history set
, nrRules = nrRules set + 1}
addbp xs = case xs of
"rule": rs -> case reads (unwords rs) of
(r', "") : _ -> do
outputStrLn "ok"
lift . modify $ \set -> set { breakPoints = AtRule r' : breakPoints set }
_ -> outputStrLn "can't parse that rule"
["call", f] -> do
outputStrLn "ok"
lift . modify $ \set -> set { breakPoints = AtCall f : breakPoints set }
_ -> outputStrLn "Sirisly u want m3 too parse that?"
printSummary st = do
hist <- lift (gets history)
case st of
StgState {} -> return ()
OmegaState {} -> outputStrLn "Omega:"
PsiState {} -> outputStrLn "Psi:"
IrrState {} -> outputStrLn "Irr:"
case hist of
[] -> do
outputStrLn $ "Rule: " ++ show RInitial
printCode $ code st
printCStack True $ cstack st
outputStrLn $ "heap(" ++ show (M.size $ heap st) ++ ")"
loop st
(rule, st) : _ -> do
outputStrLn $ "Rule: " ++ show rule
printCode $ code st
printCStack True $ cstack st
outputStrLn $ "heap(" ++ show (M.size $ heap st) ++ ")"
outputStrLn $ "astack\n" ++ showDoc (prAStack PP.text $ astack st)
loop st
loopView st xs = do
case xs of
["h"] -> printHeap (heap st)
["heap"] -> printHeap (heap st)
"heap":fs -> mapM_ (printHeapLookup (heap st)) fs
"h":fs -> mapM_ (printHeapLookup (heap st)) fs
["set"] -> printSetting =<< lift (gets settings)
["settings"] -> printSetting =<< lift (gets settings)
["s"] -> printCStack False (cstack st)
["stack"] -> printCStack False (cstack st)
["c"] -> printCode (code st)
["code"] -> printCode (code st)
["rules"] -> printRules
["sum"] -> printSummary st
["bp"] -> do
bps <- lift (gets breakPoints)
outputStrLn $ show bps
_ -> outputStrLn "wouldn't we all?"
loop st
printSetting set = do
outputStrLn "Current Settings:"
mapM_ (outputStrLn . show)
[ "steping" ~> steping set
, "quiet" ~> quiet set
, "forceStg" ~> forceStg set
, "toGC" ~> toGC set
]
where
(~>) = (,)
printCode code = outputStrLn $ "code: " ++ show (prExpr PP.text code)
printCStack b cstack = do
outputStrLn $ "stack(" ++ show (length cstack) ++ "):"
outputStrLn $ show (prCStack PP.text (if b then take 5 cstack else id cstack))
if b && length cstack >= 5
then outputStrLn "..."
else return ()
printHeapLookup heap f = outputStrLn $ printHeapFunctions $ M.filterWithKey (\k _ -> k == f) heap
printHeap heap = outputStrLn $ "heap(" ++ show (M.size heap) ++ "): \n"
++ printHeapFunctions heap
printHeapFunctions :: Heap String -> String
printHeapFunctions heap = concat
[ padFunction (id ++ if loc == OnAbyss then "!" else ""
, show $ prObj PP.text obj)
| (id, (obj, loc)) <- H.toList heap]
where
padFunction :: (String, String) -> String
padFunction (id, obj) = unlines . map (" " ++) $ case lines obj of
[] -> []
x : xs -> (id ++ " = " ++ x)
: map (\y -> replicate (length id + 3) ' ' ++ y) xs
printRules = do
ruls <- lift $ gets history
nrR <- lift . gets $ nrRules
outputStrLn $ "number of rules: " ++ show (nrR)
outputStrLn $ "number of rules: " ++ show (length ruls)
outputStrLn . show . map (\ list -> (head list, length list))
. group . sort . map fst $ ruls
printHelp = do
mapM_ outputStrLn
[ "Oh hi! This is the Interpreter speaking"
, "Press the following to do the following"
, ":q - to quit"
, ":v or :view - to view something"
, " h or heap - the heap"
, " accepts a list of heap objects to be printed"
, " s or stack - the stack"
, " c or code - the code"
, " rules - the number of rules fired"
, " sum - a summary"
, " bp - the current breakpoints"
, ":bp - to add a new breakpoint"
, " rule <rule> - for that <rule>"
, " call <id> - when calling <id>"
, ":step <n> - step <n> steps :)"
, ":back <n> - step <-n> steps (history)"
, ":force! - forced evaulation"
, ""
, "Happy Hacking !!"
]
showDoc :: Doc -> String
showDoc x = PP.displayS (PP.renderPretty 0.8 80 x) ""
main :: IO ()
main = do
First argument is the filename
file:args <- getArgs
print $ args
case getOpt RequireOrder options args of
(flags, [], []) -> do
opts <- foldl (>>=) (return defaultSettings) flags
then loadFile opts file > > = forceInterpreter > > return ( )
else opts file
testInterpreter opts file
(_, nonOpts, []) -> error $ "unrecognized arguments: " ++ unwords nonOpts
(_, _, msgs) -> error $ concat msgs ++ usageInfo header options
data Flag = Version
options :: [OptDescr (Settings -> IO Settings)]
options =
[ Option ['S'] ["step"] (ReqArg setSteping "BOOL") "step through"
, Option ['F'] ["force"] (ReqArg setForce "Bool") "force evaluation"
, Option [ ' V ' ] [ " visible " ] ( ReqArg setVisible " \"BOOL BOOL BOOL\ " " ) " show code stack heap "
, Option ['i'] ["integer-input"]
(ReqArg setInputInteger "Integer")
"single integer input"
, Option ['d'] ["double-input"]
(ReqArg setInputDouble "Double")
"single double input"
, Option ['I'] ["list-integer-input"]
(ReqArg setInputIntegers "[Integer]")
"integer list input"
, Option ['D'] ["list-double-input"]
(ReqArg setInputDoubles "[Double]")
"double list input"
, Option ['s'] ["string-input"]
(ReqArg setInputString "String")
"string input"
]
setSteping :: String -> Settings -> IO Settings
setSteping arg s = return $ s { steping = read arg }
setVisible : : String- > Settings - > IO Settings
set = let ( arg : : arg3 : _ ) = words = read arg3
s = read c = read arg
in return $ set { showStgState = stgState c s h }
setVisible :: String-> Settings -> IO Settings
setVisible ind set = let (arg: arg2: arg3:_) = words ind
h = read arg3
s = read arg2
c = read arg
in return $ set { showStgState = stgState c s h }
-}
setForce :: String -> Settings -> IO Settings
setForce arg set = return $ set { forceStg = read arg }
setInputInteger :: String -> Settings -> IO Settings
setInputInteger arg s =
return $ s { lset = (lset s) {input = (input (lset s)) { inputInteger = Just (read arg) }}}
setInputIntegers :: String -> Settings -> IO Settings
setInputIntegers arg s =
return $ s { lset = (lset s) { input = (input (lset s)) { inputIntegers = Just (read arg) }}}
setInputDouble :: String -> Settings -> IO Settings
setInputDouble arg s =
return $ s { lset = (lset s) {input = (input (lset s)) { inputDouble = Just (read arg) }}}
setInputDoubles :: String -> Settings -> IO Settings
setInputDoubles arg s =
return $ s { lset = (lset s) { input = (input (lset s)) { inputDoubles = Just (read arg) }}}
setInputString :: String -> Settings -> IO Settings
setInputString arg s =
return $ s { lset = (lset s) { input = (input (lset s)) { inputString = Just arg }}}
header = "Usage: main [OPTION...]"
|
cdb8260947fb19f99db3f4239e3406cbeb21d0ec22509e98e307968a427c8332 | tomsmalley/semantic-reflex | Dimmer.hs | # LANGUAGE RecursiveDo #
# LANGUAGE TemplateHaskell #
-- | Semantic UI dimmers. Pure reflex implementation is provided.
-- -ui.com/modules/dimmers.html
module Reflex.Dom.SemanticUI.Dimmer
(
dimmer, dimmer'
, DimmerConfig (..)
, dimmerConfig_inverted
, dimmerConfig_page
, dimmerConfig_dimmed
, dimmerConfig_transitionType
, dimmerConfig_duration
, dimmerConfig_closeOnClick
, dimmerConfig_elConfig
) where
import Control.Lens.TH (makeLensesWith, lensRules, simpleLenses)
import Control.Lens ((^.))
import Control.Monad ((<=<))
import Data.Default
import Data.Maybe (fromMaybe)
import Data.Semigroup ((<>))
import Reflex
import Reflex.Dom.Core
import Data.Time (NominalDiffTime)
import Reflex.Active
import Reflex.Dom.SemanticUI.Common
import Reflex.Dom.SemanticUI.Transition
data DimmerConfig t = DimmerConfig
{ _dimmerConfig_inverted :: Dynamic t Bool
-- ^ Dimmers can be inverted
, _dimmerConfig_page :: Bool
-- ^ Dimmers can dim the whole page
, _dimmerConfig_dimmed :: SetValue' t Direction (Maybe Direction)
-- ^ Dimmer state control
, _dimmerConfig_transitionType :: Dynamic t TransitionType
-- ^ Type of transition to use
, _dimmerConfig_duration :: Dynamic t NominalDiffTime
-- ^ Duration of transition
, _dimmerConfig_closeOnClick :: Dynamic t Bool
-- ^ User can click out of a dimmer
, _dimmerConfig_elConfig :: ActiveElConfig t
-- ^ Config
}
makeLensesWith (lensRules & simpleLenses .~ True) ''DimmerConfig
instance HasElConfig t (DimmerConfig t) where
elConfig = dimmerConfig_elConfig
instance Reflex t => Default (DimmerConfig t) where
def = DimmerConfig
{ _dimmerConfig_inverted = pure False
, _dimmerConfig_page = False
, _dimmerConfig_dimmed = SetValue Out Nothing
, _dimmerConfig_transitionType = pure Fade
, _dimmerConfig_duration = pure 0.5
, _dimmerConfig_closeOnClick = pure True
, _dimmerConfig_elConfig = def
}
-- | Make the dimmer div classes from the configuration
dimmerConfigClasses :: Reflex t => DimmerConfig t -> Dynamic t Classes
dimmerConfigClasses DimmerConfig {..} = dynClasses'
[ pure $ Just "ui active dimmer"
, boolClass "inverted" _dimmerConfig_inverted
, pure $ if _dimmerConfig_page then Just "page" else Nothing
]
-- | Dimmer UI Element.
dimmer'
:: forall t m a. UI t m => DimmerConfig t -> m a
-> m (Element EventResult (DomBuilderSpace m) t, a)
dimmer' config@DimmerConfig {..} content = mdo
let click = gate (current _dimmerConfig_closeOnClick) $ domEvent Click e
f Nothing d = flipDirection d
f (Just d) _ = d
dDir <- holdUniqDyn <=< foldDyn f (_dimmerConfig_dimmed ^. initial) $ leftmost
[ fromMaybe never $ _dimmerConfig_dimmed ^. event
, Just Out <$ click ]
(e, a) <- ui' "div" (mkElConfig $ updated dDir) content
pure (e, a)
where
mkElConfig eDir = _dimmerConfig_elConfig <> def
{ _classes = Dyn $ dimmerConfigClasses config
, _action = Just $ def
{ _action_initialDirection = _dimmerConfig_dimmed ^. initial
, _action_transition =
let f dur dir = Transition Fade (Just dir) $ def
{ _transitionConfig_cancelling = True
, _transitionConfig_duration = dur
}
in attachWith f (current _dimmerConfig_duration) eDir
}
}
-- | Dimmer UI Element.
dimmer :: UI t m => DimmerConfig t -> m a -> m a
dimmer c = fmap snd . dimmer' c
| null | https://raw.githubusercontent.com/tomsmalley/semantic-reflex/5a973390fae1facbc4351b75ea59210d6756b8e5/semantic-reflex/src/Reflex/Dom/SemanticUI/Dimmer.hs | haskell | | Semantic UI dimmers. Pure reflex implementation is provided.
-ui.com/modules/dimmers.html
^ Dimmers can be inverted
^ Dimmers can dim the whole page
^ Dimmer state control
^ Type of transition to use
^ Duration of transition
^ User can click out of a dimmer
^ Config
| Make the dimmer div classes from the configuration
| Dimmer UI Element.
| Dimmer UI Element. | # LANGUAGE RecursiveDo #
# LANGUAGE TemplateHaskell #
module Reflex.Dom.SemanticUI.Dimmer
(
dimmer, dimmer'
, DimmerConfig (..)
, dimmerConfig_inverted
, dimmerConfig_page
, dimmerConfig_dimmed
, dimmerConfig_transitionType
, dimmerConfig_duration
, dimmerConfig_closeOnClick
, dimmerConfig_elConfig
) where
import Control.Lens.TH (makeLensesWith, lensRules, simpleLenses)
import Control.Lens ((^.))
import Control.Monad ((<=<))
import Data.Default
import Data.Maybe (fromMaybe)
import Data.Semigroup ((<>))
import Reflex
import Reflex.Dom.Core
import Data.Time (NominalDiffTime)
import Reflex.Active
import Reflex.Dom.SemanticUI.Common
import Reflex.Dom.SemanticUI.Transition
data DimmerConfig t = DimmerConfig
{ _dimmerConfig_inverted :: Dynamic t Bool
, _dimmerConfig_page :: Bool
, _dimmerConfig_dimmed :: SetValue' t Direction (Maybe Direction)
, _dimmerConfig_transitionType :: Dynamic t TransitionType
, _dimmerConfig_duration :: Dynamic t NominalDiffTime
, _dimmerConfig_closeOnClick :: Dynamic t Bool
, _dimmerConfig_elConfig :: ActiveElConfig t
}
makeLensesWith (lensRules & simpleLenses .~ True) ''DimmerConfig
instance HasElConfig t (DimmerConfig t) where
elConfig = dimmerConfig_elConfig
instance Reflex t => Default (DimmerConfig t) where
def = DimmerConfig
{ _dimmerConfig_inverted = pure False
, _dimmerConfig_page = False
, _dimmerConfig_dimmed = SetValue Out Nothing
, _dimmerConfig_transitionType = pure Fade
, _dimmerConfig_duration = pure 0.5
, _dimmerConfig_closeOnClick = pure True
, _dimmerConfig_elConfig = def
}
dimmerConfigClasses :: Reflex t => DimmerConfig t -> Dynamic t Classes
dimmerConfigClasses DimmerConfig {..} = dynClasses'
[ pure $ Just "ui active dimmer"
, boolClass "inverted" _dimmerConfig_inverted
, pure $ if _dimmerConfig_page then Just "page" else Nothing
]
dimmer'
:: forall t m a. UI t m => DimmerConfig t -> m a
-> m (Element EventResult (DomBuilderSpace m) t, a)
dimmer' config@DimmerConfig {..} content = mdo
let click = gate (current _dimmerConfig_closeOnClick) $ domEvent Click e
f Nothing d = flipDirection d
f (Just d) _ = d
dDir <- holdUniqDyn <=< foldDyn f (_dimmerConfig_dimmed ^. initial) $ leftmost
[ fromMaybe never $ _dimmerConfig_dimmed ^. event
, Just Out <$ click ]
(e, a) <- ui' "div" (mkElConfig $ updated dDir) content
pure (e, a)
where
mkElConfig eDir = _dimmerConfig_elConfig <> def
{ _classes = Dyn $ dimmerConfigClasses config
, _action = Just $ def
{ _action_initialDirection = _dimmerConfig_dimmed ^. initial
, _action_transition =
let f dur dir = Transition Fade (Just dir) $ def
{ _transitionConfig_cancelling = True
, _transitionConfig_duration = dur
}
in attachWith f (current _dimmerConfig_duration) eDir
}
}
dimmer :: UI t m => DimmerConfig t -> m a -> m a
dimmer c = fmap snd . dimmer' c
|
b7565047f2bded1e0ba4f41ccf2fb9ede724e27e4c19ab8d2662ba63e7a68f69 | resttime/cl-liballegro | file-io.lisp | (in-package :cl-liballegro)
(defcenum seek
(:seek-set 0)
(:seek-cur)
(:seek-end))
| null | https://raw.githubusercontent.com/resttime/cl-liballegro/0f8a3a77d5c81fe14352d9a799cba20e1a3a90b4/src/constants/file-io.lisp | lisp | (in-package :cl-liballegro)
(defcenum seek
(:seek-set 0)
(:seek-cur)
(:seek-end))
|
|
6d33903c9b3adb42dfd923cba42c35fb072731f863323fd4bc6f8fcc2020b97b | avsm/ocaml-ssh | kex.mli |
* Copyright ( c ) 2004,2005 Anil Madhavapeddy < >
*
* 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) 2004,2005 Anil Madhavapeddy <>
*
* 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.
*
*)
exception Not_implemented
exception Key_too_short
module Methods : sig
type mpint = Mpl_stdlib.Mpl_mpint.t
type t =
| DiffieHellmanGexSHA1
| DiffieHellmanGroup1SHA1
| DiffieHellmanGroup14SHA1
module DHGroup : sig
type kex_hash = {
v_c : Version.t;
v_s : Version.t;
i_c : string;
i_s : string;
k_s : string;
e : mpint;
f : mpint;
k : mpint;
}
val marshal : kex_hash -> string
end
module DHGex : sig
type kex_hash = {
v_c : Version.t;
v_s : Version.t;
i_c : string;
i_s : string;
k_s : string;
min : int32;
n : int32;
max : int32;
p : mpint;
g : mpint;
e : mpint;
f : mpint;
k : mpint;
}
val marshal : kex_hash -> string
type moduli
val empty_moduli : unit -> moduli
val add_moduli : primes:moduli -> size:int32 -> prime:mpint -> generator:mpint -> unit
val choose : min:int32 -> want:int32 -> max:int32 -> moduli -> (mpint * mpint) option
end
exception Unknown of string
val to_string : t -> string
val from_string : string -> t
val public_parameters : t -> mpint * mpint
val algorithm_choice : kex:string * string -> enc_cs:string * string ->
enc_sc:string * string ->
mac_cs:string * string ->
mac_sc:string * string -> (string -> exn) ->
t * Algorithms.Cipher.t * Algorithms.Cipher.t * Algorithms.MAC.t * Algorithms.MAC.t
val compute_init : Cryptokit.Random.rng -> mpint -> mpint ->
mpint * Cryptokit.DH.private_secret
val compute_shared_secret : mpint -> mpint -> Cryptokit.DH.private_secret -> mpint -> mpint
val compute_reply : Cryptokit.Random.rng -> mpint -> mpint -> mpint -> mpint * mpint
val pad_rsa_signature : mpint -> string -> string
val derive_key : (unit -> Cryptokit.hash) -> mpint -> string -> string -> int -> char -> string
end
| null | https://raw.githubusercontent.com/avsm/ocaml-ssh/26577d1501e7a43e4b520239b08da114c542eda4/lib/kex.mli | ocaml |
* Copyright ( c ) 2004,2005 Anil Madhavapeddy < >
*
* 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) 2004,2005 Anil Madhavapeddy <>
*
* 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.
*
*)
exception Not_implemented
exception Key_too_short
module Methods : sig
type mpint = Mpl_stdlib.Mpl_mpint.t
type t =
| DiffieHellmanGexSHA1
| DiffieHellmanGroup1SHA1
| DiffieHellmanGroup14SHA1
module DHGroup : sig
type kex_hash = {
v_c : Version.t;
v_s : Version.t;
i_c : string;
i_s : string;
k_s : string;
e : mpint;
f : mpint;
k : mpint;
}
val marshal : kex_hash -> string
end
module DHGex : sig
type kex_hash = {
v_c : Version.t;
v_s : Version.t;
i_c : string;
i_s : string;
k_s : string;
min : int32;
n : int32;
max : int32;
p : mpint;
g : mpint;
e : mpint;
f : mpint;
k : mpint;
}
val marshal : kex_hash -> string
type moduli
val empty_moduli : unit -> moduli
val add_moduli : primes:moduli -> size:int32 -> prime:mpint -> generator:mpint -> unit
val choose : min:int32 -> want:int32 -> max:int32 -> moduli -> (mpint * mpint) option
end
exception Unknown of string
val to_string : t -> string
val from_string : string -> t
val public_parameters : t -> mpint * mpint
val algorithm_choice : kex:string * string -> enc_cs:string * string ->
enc_sc:string * string ->
mac_cs:string * string ->
mac_sc:string * string -> (string -> exn) ->
t * Algorithms.Cipher.t * Algorithms.Cipher.t * Algorithms.MAC.t * Algorithms.MAC.t
val compute_init : Cryptokit.Random.rng -> mpint -> mpint ->
mpint * Cryptokit.DH.private_secret
val compute_shared_secret : mpint -> mpint -> Cryptokit.DH.private_secret -> mpint -> mpint
val compute_reply : Cryptokit.Random.rng -> mpint -> mpint -> mpint -> mpint * mpint
val pad_rsa_signature : mpint -> string -> string
val derive_key : (unit -> Cryptokit.hash) -> mpint -> string -> string -> int -> char -> string
end
|
|
5638e1559fac037dbde7ab0471b412346a191c7089923fbfd5ec643e62f8671b | hypernumbers/hypernumbers | stdfuns_info.erl | %%% @doc Built-in information functions.
@author < >
@private
( C ) 2009 - 2014 , Hypernumbers Ltd.
%%%-------------------------------------------------------------------
%%%
%%% LICENSE
%%%
%%% 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 version 3
%%%
%%% 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(stdfuns_info).
fns that pass test
-export([
'error.type'/1,
isblank/1,
iserr/1,
iserror/1,
islogical/1,
isna/1,
isnontext/1,
isnumber/1,
istext/1,
n/1,
na/1,
type/1
]).
fns that fail test
-export([
cell/1
]).
fns without a c test suite
but with a d_gnumeric one
-export([
iseven/1,
isodd/1,
isref/1,
isnonblank/1, % (except me - no tests at all...)
info/1
]).
-export([rows/1,
columns/1]).
-include("typechecks.hrl").
-include("spriki.hrl").
-include("muin_records.hrl").
-define(ext, muin:external_eval_formula).
%% TODO: Range references (literal and from INDIRECT)
%% TODO: Other info types.
cell([V1, V2]) ->
InfoType = muin:external_eval_formula(V1),
muin_checks:ensure(?is_string(InfoType), ?ERRVAL_VAL),
R = case V2 of
[indirect, _] -> muin:external_eval(V2);
X when ?is_cellref(X) -> X;
%% TODO: X when ?is_rangeref(X) -> todo;
_ -> ?ERR_REF
end,
muin:do_cell(R#cellref.path, muin:row_index(R#cellref.row),
muin:col_index(R#cellref.col), finite, "__rawvalue", false),
Path = muin_util:walk_path(muin:context_setting(path), R#cellref.path),
RefX = #refX{site = muin:context_setting(site),
type = url,
path = Path,
obj = {cell, {muin:col_index(R#cellref.col),
muin:row_index(R#cellref.row)}}},
cell1(InfoType, RefX).
cell1("formula", RefX) ->
Ret = new_db_api:read_attribute(RefX, "formula"),
case Ret of
[{_, F}] ->
case string:substr(F, 1, 1) of
"=" -> string:substr(F, 2); % drop the equals sign "="
_ -> F
end;
_ ->
""
end;
cell1("address", RefX) ->
{cell, {Col, Row}} = RefX#refX.obj,
stdfuns_lookup_ref:address([Row, Col]);
cell1("col", RefX) ->
{cell, {Col, _Row}} = RefX#refX.obj,
Col;
cell1("row", RefX) ->
{cell, {_Col, Row}} = RefX#refX.obj,
Row;
cell1("contents", RefX) ->
Ret = new_db_api:read_attribute(RefX, "value"),
[{_, V}] = Ret,
case V of
blank -> 0;
Else -> Else
end;
cell1(_, _) ->
?ERR_VAL.
errornum(?ERRVAL_NULL) -> 1;
errornum(?ERRVAL_DIV) -> 2;
errornum(?ERRVAL_VAL) -> 3;
errornum(?ERRVAL_REF) -> 4;
errornum(?ERRVAL_NAME) -> 5;
errornum(?ERRVAL_NUM) -> 6;
errornum(?ERRVAL_NA) -> 7;
errornum(?ERRVAL_CIRCREF) -> 8;
errornum(?ERRVAL_AUTH) -> 9;
errornum(?ERRVAL_FORM) -> 10;
errornum(?ERRVAL_CANTINC) -> 11;
errornum(?ERRVAL_PAYONLY) -> 12;
errornum(?ERRVAL_NOTSETUP) -> 13.
%% THERE IS NO errornum FOR #MOCHIJSON! AS IT IS A BUG NOT A PROPER ERROR MESSAGE!
'error.type'([X]) when ?is_errval(X) -> errornum(X);
'error.type'([{array, [[X|_]|_]}]) when ?is_errval(X) -> errornum(X);
'error.type'(_) -> ?ERRVAL_NA.
%% Returns the logical value TRUE if value refers to any error value except
%% #N/A; otherwise it returns FALSE.
iserr([?ERRVAL_NA]) -> false;
iserr([X]) when ?is_errval(X) -> true;
iserr([{array, [[X|_]|_]}]) when ?is_errval(X) -> true;
iserr(_) -> false.
%% Returns true if argument is any error value.
iserror([X]) when ?is_errval(X) -> true;
iserror([{array, [[X|_]|_]}]) when ?is_errval(X) -> true;
iserror(_) -> false.
%% Returns TRUE if number is even, or FALSE if number is odd.
%% The number is truncated, so ISEVEN(2.5) is true.
@todo needs a test case written because it is not an Excel 97 function
iseven([V1]) ->
Num = muin_col_DEPR:collect_number(V1, [cast_strings, cast_bools, cast_dates]),
(trunc(Num) div 2) * 2 == trunc(Num).
@todo needs a test case written because it is not an Excel 97 function
isodd([Num]) -> not(iseven([Num])).
Returns true only for booleans or arrays where element ( 1,1 ) is a boolean .
%% (Returns false for ranges regardless of what's in them.)
islogical([B]) when is_boolean(B) -> true;
islogical([A]) when ?is_array(A) ->
{ok, Val} = area_util:at(1, 1, A),
is_boolean(Val);
islogical(_Else) ->
false.
isna([{errval, '#N/A'}]) -> true;
isna([X]) when ?is_array(X) ->
{ok, N} = area_util:at(1, 1, X),
N == {errval, '#N/A'};
isna(_X) ->
false.
isnumber([X]) when is_number(X) -> true;
isnumber([X]) when ?is_array(X) ->
{ok, N} = area_util:at(1, 1, X),
is_number(N);
isnumber([_]) -> false.
isnontext([X]) -> not istext([X]).
istext([X]) when ?is_string(X) -> true; %% complement(fun isnontext/1)
istext([X]) when ?is_array(X) ->
{ok, N} = area_util:at(1, 1, X),
?is_string(N);
istext([_]) -> false.
%% TODO: dates.
n([Num]) when is_number(Num) -> Num;
n([true]) -> 1;
n([false]) -> 0;
n([{errval, X}]) -> {errval, X};
n([{datetime, _Y, _D}=Date]) -> case muin_util:cast(Date, date, num) of
{error, _Err} -> ?ERR_VAL;
Else -> Else
end;
n([X]) when ?is_array(X) -> 1;
n(_X) -> 0.
na([]) -> {errval, '#N/A'}.
TYPE(INDIRECT("A1 " ) ) in Excel = 0 regardless of contents of A1 . In Hypernumbers it 's same as TYPE(A1 )
type([A]) when ?is_range(A) -> 16;
type([A]) when ?is_array(A) -> 64;
type([N]) when is_number(N) -> 1;
type([S]) when is_list(S) -> 2;
type([B]) when is_boolean(B) -> 4;
type([{errval, _X}]) -> 16;
type([blank]) -> 1;
type(_) -> 0.
Excel 's ISBLANK takes one argument . Ours will work with a list too .
isblank([B]) when ?is_blank(B) ->
true;
isblank(Vs) ->
Flatvs = muin_col_DEPR:flatten_areas(Vs),
lists:all(fun muin_collect:is_blank/1, Flatvs).
@todo needs a test case written because it is not an Excel 97 function
isnonblank(Vs) -> Flatvs = muin_col_DEPR:flatten_areas(Vs),
lists:all(fun(X) -> not(muin_collect:is_blank(X)) end, Flatvs).
info(["site"]) -> get(site);
info(["path"]) -> case "/" ++ string:join(get(path), "/") ++ "/" of
"//" -> "/";
V -> V
end.
isref([R]) when ?is_rangeref(R) orelse ?is_cellref(R) -> true;
isref(_R) ->
false.
rows([R]) when ?is_rangeref(R) -> R#rangeref.height;
rows([A]) when ?is_array(A) -> area_util:height(A);
rows([Expr]) when ?is_cellref(Expr) -> 1;
rows([Expr]) when ?is_namedexpr(Expr) -> ?ERRVAL_NAME;
rows([Expr]) when is_number(Expr) -> 1;
rows([Expr]) when ?is_errval(Expr) -> Expr;
rows([Expr]) when ?is_funcall(Expr) -> rows([?ext(Expr)]);
rows([_Expr]) -> ?ERRVAL_VAL.
columns([R]) when ?is_rangeref(R) -> R#rangeref.width;
columns([A]) when ?is_array(A) -> area_util:width(A);
columns([Expr]) when ?is_cellref(Expr) -> 1;
columns([Expr]) when ?is_namedexpr(Expr) -> ?ERRVAL_NAME;
columns([Expr]) when is_number(Expr) -> 1;
columns([Expr]) when ?is_errval(Expr) -> Expr;
columns([Expr]) when ?is_funcall(Expr) -> columns([?ext(Expr)]);
columns([_Expr]) -> ?ERRVAL_VAL.
| null | https://raw.githubusercontent.com/hypernumbers/hypernumbers/281319f60c0ac60fb009ee6d1e4826f4f2d51c4e/lib/formula_engine-1.0/src/stdfuns_info.erl | erlang | @doc Built-in information functions.
-------------------------------------------------------------------
LICENSE
This program is free software: you can redistribute it and/or modify
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.
along with this program. If not, see </>.
-------------------------------------------------------------------
(except me - no tests at all...)
TODO: Range references (literal and from INDIRECT)
TODO: Other info types.
TODO: X when ?is_rangeref(X) -> todo;
drop the equals sign "="
THERE IS NO errornum FOR #MOCHIJSON! AS IT IS A BUG NOT A PROPER ERROR MESSAGE!
Returns the logical value TRUE if value refers to any error value except
#N/A; otherwise it returns FALSE.
Returns true if argument is any error value.
Returns TRUE if number is even, or FALSE if number is odd.
The number is truncated, so ISEVEN(2.5) is true.
(Returns false for ranges regardless of what's in them.)
complement(fun isnontext/1)
TODO: dates. | @author < >
@private
( C ) 2009 - 2014 , Hypernumbers Ltd.
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3
You should have received a copy of the GNU Affero General Public License
-module(stdfuns_info).
fns that pass test
-export([
'error.type'/1,
isblank/1,
iserr/1,
iserror/1,
islogical/1,
isna/1,
isnontext/1,
isnumber/1,
istext/1,
n/1,
na/1,
type/1
]).
fns that fail test
-export([
cell/1
]).
fns without a c test suite
but with a d_gnumeric one
-export([
iseven/1,
isodd/1,
isref/1,
info/1
]).
-export([rows/1,
columns/1]).
-include("typechecks.hrl").
-include("spriki.hrl").
-include("muin_records.hrl").
-define(ext, muin:external_eval_formula).
cell([V1, V2]) ->
InfoType = muin:external_eval_formula(V1),
muin_checks:ensure(?is_string(InfoType), ?ERRVAL_VAL),
R = case V2 of
[indirect, _] -> muin:external_eval(V2);
X when ?is_cellref(X) -> X;
_ -> ?ERR_REF
end,
muin:do_cell(R#cellref.path, muin:row_index(R#cellref.row),
muin:col_index(R#cellref.col), finite, "__rawvalue", false),
Path = muin_util:walk_path(muin:context_setting(path), R#cellref.path),
RefX = #refX{site = muin:context_setting(site),
type = url,
path = Path,
obj = {cell, {muin:col_index(R#cellref.col),
muin:row_index(R#cellref.row)}}},
cell1(InfoType, RefX).
cell1("formula", RefX) ->
Ret = new_db_api:read_attribute(RefX, "formula"),
case Ret of
[{_, F}] ->
case string:substr(F, 1, 1) of
_ -> F
end;
_ ->
""
end;
cell1("address", RefX) ->
{cell, {Col, Row}} = RefX#refX.obj,
stdfuns_lookup_ref:address([Row, Col]);
cell1("col", RefX) ->
{cell, {Col, _Row}} = RefX#refX.obj,
Col;
cell1("row", RefX) ->
{cell, {_Col, Row}} = RefX#refX.obj,
Row;
cell1("contents", RefX) ->
Ret = new_db_api:read_attribute(RefX, "value"),
[{_, V}] = Ret,
case V of
blank -> 0;
Else -> Else
end;
cell1(_, _) ->
?ERR_VAL.
errornum(?ERRVAL_NULL) -> 1;
errornum(?ERRVAL_DIV) -> 2;
errornum(?ERRVAL_VAL) -> 3;
errornum(?ERRVAL_REF) -> 4;
errornum(?ERRVAL_NAME) -> 5;
errornum(?ERRVAL_NUM) -> 6;
errornum(?ERRVAL_NA) -> 7;
errornum(?ERRVAL_CIRCREF) -> 8;
errornum(?ERRVAL_AUTH) -> 9;
errornum(?ERRVAL_FORM) -> 10;
errornum(?ERRVAL_CANTINC) -> 11;
errornum(?ERRVAL_PAYONLY) -> 12;
errornum(?ERRVAL_NOTSETUP) -> 13.
'error.type'([X]) when ?is_errval(X) -> errornum(X);
'error.type'([{array, [[X|_]|_]}]) when ?is_errval(X) -> errornum(X);
'error.type'(_) -> ?ERRVAL_NA.
iserr([?ERRVAL_NA]) -> false;
iserr([X]) when ?is_errval(X) -> true;
iserr([{array, [[X|_]|_]}]) when ?is_errval(X) -> true;
iserr(_) -> false.
iserror([X]) when ?is_errval(X) -> true;
iserror([{array, [[X|_]|_]}]) when ?is_errval(X) -> true;
iserror(_) -> false.
@todo needs a test case written because it is not an Excel 97 function
iseven([V1]) ->
Num = muin_col_DEPR:collect_number(V1, [cast_strings, cast_bools, cast_dates]),
(trunc(Num) div 2) * 2 == trunc(Num).
@todo needs a test case written because it is not an Excel 97 function
isodd([Num]) -> not(iseven([Num])).
Returns true only for booleans or arrays where element ( 1,1 ) is a boolean .
islogical([B]) when is_boolean(B) -> true;
islogical([A]) when ?is_array(A) ->
{ok, Val} = area_util:at(1, 1, A),
is_boolean(Val);
islogical(_Else) ->
false.
isna([{errval, '#N/A'}]) -> true;
isna([X]) when ?is_array(X) ->
{ok, N} = area_util:at(1, 1, X),
N == {errval, '#N/A'};
isna(_X) ->
false.
isnumber([X]) when is_number(X) -> true;
isnumber([X]) when ?is_array(X) ->
{ok, N} = area_util:at(1, 1, X),
is_number(N);
isnumber([_]) -> false.
isnontext([X]) -> not istext([X]).
istext([X]) when ?is_array(X) ->
{ok, N} = area_util:at(1, 1, X),
?is_string(N);
istext([_]) -> false.
n([Num]) when is_number(Num) -> Num;
n([true]) -> 1;
n([false]) -> 0;
n([{errval, X}]) -> {errval, X};
n([{datetime, _Y, _D}=Date]) -> case muin_util:cast(Date, date, num) of
{error, _Err} -> ?ERR_VAL;
Else -> Else
end;
n([X]) when ?is_array(X) -> 1;
n(_X) -> 0.
na([]) -> {errval, '#N/A'}.
TYPE(INDIRECT("A1 " ) ) in Excel = 0 regardless of contents of A1 . In Hypernumbers it 's same as TYPE(A1 )
type([A]) when ?is_range(A) -> 16;
type([A]) when ?is_array(A) -> 64;
type([N]) when is_number(N) -> 1;
type([S]) when is_list(S) -> 2;
type([B]) when is_boolean(B) -> 4;
type([{errval, _X}]) -> 16;
type([blank]) -> 1;
type(_) -> 0.
Excel 's ISBLANK takes one argument . Ours will work with a list too .
isblank([B]) when ?is_blank(B) ->
true;
isblank(Vs) ->
Flatvs = muin_col_DEPR:flatten_areas(Vs),
lists:all(fun muin_collect:is_blank/1, Flatvs).
@todo needs a test case written because it is not an Excel 97 function
isnonblank(Vs) -> Flatvs = muin_col_DEPR:flatten_areas(Vs),
lists:all(fun(X) -> not(muin_collect:is_blank(X)) end, Flatvs).
info(["site"]) -> get(site);
info(["path"]) -> case "/" ++ string:join(get(path), "/") ++ "/" of
"//" -> "/";
V -> V
end.
isref([R]) when ?is_rangeref(R) orelse ?is_cellref(R) -> true;
isref(_R) ->
false.
rows([R]) when ?is_rangeref(R) -> R#rangeref.height;
rows([A]) when ?is_array(A) -> area_util:height(A);
rows([Expr]) when ?is_cellref(Expr) -> 1;
rows([Expr]) when ?is_namedexpr(Expr) -> ?ERRVAL_NAME;
rows([Expr]) when is_number(Expr) -> 1;
rows([Expr]) when ?is_errval(Expr) -> Expr;
rows([Expr]) when ?is_funcall(Expr) -> rows([?ext(Expr)]);
rows([_Expr]) -> ?ERRVAL_VAL.
columns([R]) when ?is_rangeref(R) -> R#rangeref.width;
columns([A]) when ?is_array(A) -> area_util:width(A);
columns([Expr]) when ?is_cellref(Expr) -> 1;
columns([Expr]) when ?is_namedexpr(Expr) -> ?ERRVAL_NAME;
columns([Expr]) when is_number(Expr) -> 1;
columns([Expr]) when ?is_errval(Expr) -> Expr;
columns([Expr]) when ?is_funcall(Expr) -> columns([?ext(Expr)]);
columns([_Expr]) -> ?ERRVAL_VAL.
|
a5afe38aa7b473cc1d23dd1ba0d2ec27dbec2aa5bafc65ef401698a6b5852847 | zmactep/hasbolt-sample-app | Routes.hs | {-# LANGUAGE OverloadedStrings #-}
module Routes where
import Control.Monad.Trans (lift, liftIO)
import Control.Monad.Trans.Reader (ask)
import Data.Pool (withResource)
import Data.Text.Lazy (Text, toStrict)
import Database.Bolt
import Web.Scotty.Trans (ActionT, file, param, json, rescue)
import Type
import Data
|Run BOLT action in scotty ' ActionT ' monad tansformer
runQ :: BoltActionT IO a -> ActionT Text WebM a
runQ act = do ss <- lift ask
liftIO $ withResource (pool ss) (`run` act)
-- |Main page route
mainR :: ActionT Text WebM ()
mainR = file "index.html"
-- |Graph response route
graphR :: ActionT Text WebM ()
graphR = do limit <- param "limit" `rescue` const (return 100)
graph <- runQ $ queryGraph limit
json graph
-- |Search response route
searchR :: ActionT Text WebM ()
searchR = do q <- param "q" :: ActionT Text WebM Text
results <- runQ $ querySearch (toStrict q)
json results
-- |Movie response route
movieR :: ActionT Text WebM ()
movieR = do t <- param "title" :: ActionT Text WebM Text
movieInfo <- runQ $ queryMovie (toStrict t)
json movieInfo
| null | https://raw.githubusercontent.com/zmactep/hasbolt-sample-app/bae5aae8ed21e6b8779fe8041a681b3fbb1e746d/src/Routes.hs | haskell | # LANGUAGE OverloadedStrings #
|Main page route
|Graph response route
|Search response route
|Movie response route |
module Routes where
import Control.Monad.Trans (lift, liftIO)
import Control.Monad.Trans.Reader (ask)
import Data.Pool (withResource)
import Data.Text.Lazy (Text, toStrict)
import Database.Bolt
import Web.Scotty.Trans (ActionT, file, param, json, rescue)
import Type
import Data
|Run BOLT action in scotty ' ActionT ' monad tansformer
runQ :: BoltActionT IO a -> ActionT Text WebM a
runQ act = do ss <- lift ask
liftIO $ withResource (pool ss) (`run` act)
mainR :: ActionT Text WebM ()
mainR = file "index.html"
graphR :: ActionT Text WebM ()
graphR = do limit <- param "limit" `rescue` const (return 100)
graph <- runQ $ queryGraph limit
json graph
searchR :: ActionT Text WebM ()
searchR = do q <- param "q" :: ActionT Text WebM Text
results <- runQ $ querySearch (toStrict q)
json results
movieR :: ActionT Text WebM ()
movieR = do t <- param "title" :: ActionT Text WebM Text
movieInfo <- runQ $ queryMovie (toStrict t)
json movieInfo
|
c9b79e2f89cff7d797aaa1da76da991fadb2db4d15dce6938a135e0088369ab3 | kowainik/tomland | Key.hs | # LANGUAGE PatternSynonyms #
|
Module : Toml . Type . Key
Copyright : ( c ) 2018 - 2022 Kowainik
SPDX - License - Identifier : MPL-2.0
Maintainer : < >
Stability : Stable
Portability : Portable
Implementation of key type . The type is used for key - value pairs and
table names .
@since 1.3.0.0
Module : Toml.Type.Key
Copyright : (c) 2018-2022 Kowainik
SPDX-License-Identifier : MPL-2.0
Maintainer : Kowainik <>
Stability : Stable
Portability : Portable
Implementation of key type. The type is used for key-value pairs and
table names.
@since 1.3.0.0
-}
module Toml.Type.Key
( -- * Core types
Key (..)
, Prefix
, Piece (..)
, pattern (:||)
, (<|)
-- * Key difference
, KeysDiff (..)
, keysDiff
) where
import Control.DeepSeq (NFData)
import Data.Coerce (coerce)
import Data.Hashable (Hashable)
import Data.List.NonEmpty (NonEmpty (..))
import Data.String (IsString (..))
import Data.Text (Text)
import GHC.Generics (Generic)
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Text as Text
| Represents the key piece of some layer .
@since 0.0.0
@since 0.0.0
-}
newtype Piece = Piece
{ unPiece :: Text
} deriving stock (Generic)
deriving newtype (Show, Eq, Ord, Hashable, IsString, NFData)
| Key of value in @key = val@ pair . Represents as non - empty list of key
components — ' 's . Key like
@
site . "google.com "
@
is represented like
@
Key ( Piece " site " :| [ Piece " \\"google.com\\ " " ] )
@
@since 0.0.0
components — 'Piece's. Key like
@
site."google.com"
@
is represented like
@
Key (Piece "site" :| [Piece "\\"google.com\\""])
@
@since 0.0.0
-}
newtype Key = Key
{ unKey :: NonEmpty Piece
} deriving stock (Generic)
deriving newtype (Show, Eq, Ord, Hashable, NFData, Semigroup)
| Type synonym for ' Key ' .
@since 0.0.0
@since 0.0.0
-}
type Prefix = Key
| Split a dot - separated string into ' Key ' . Empty string turns into a ' Key '
with single element — empty ' Piece ' .
This instance is not safe for now . Use carefully . If you try to use as a key
string like this @site.\"google.com\"@ you will have list of three components
instead of desired two .
@since 0.1.0
with single element — empty 'Piece'.
This instance is not safe for now. Use carefully. If you try to use as a key
string like this @site.\"google.com\"@ you will have list of three components
instead of desired two.
@since 0.1.0
-}
instance IsString Key where
fromString :: String -> Key
fromString = \case
"" -> Key ("" :| [])
s -> case Text.splitOn "." (fromString s) of
[] -> error "Text.splitOn returned empty string" -- can't happen
x:xs -> coerce @(NonEmpty Text) @Key (x :| xs)
{- | Bidirectional pattern synonym for constructing and deconstructing 'Key's.
-}
pattern (:||) :: Piece -> [Piece] -> Key
pattern x :|| xs <- Key (x :| xs)
where
x :|| xs = Key (x :| xs)
{-# COMPLETE (:||) #-}
| Prepends ' ' to the beginning of the ' Key ' .
(<|) :: Piece -> Key -> Key
(<|) p k = Key (p NonEmpty.<| unKey k)
{-# INLINE (<|) #-}
| Data represent difference between two keys .
@since 0.0.0
@since 0.0.0
-}
data KeysDiff
= Equal -- ^ Keys are equal
| NoPrefix -- ^ Keys don't have any common part.
^ The first key is the prefix of the second one .
^ Rest of the second key .
^ The second key is the prefix of the first one .
^ Rest of the first key .
| Diff -- ^ Key have a common prefix.
!Key -- ^ Common prefix.
^ Rest of the first key .
^ Rest of the second key .
deriving stock (Show, Eq)
| Find key difference between two keys .
@since 0.0.0
@since 0.0.0
-}
keysDiff :: Key -> Key -> KeysDiff
keysDiff (x :|| xs) (y :|| ys)
| x == y = listSame xs ys []
| otherwise = NoPrefix
where
listSame :: [Piece] -> [Piece] -> [Piece] -> KeysDiff
listSame [] [] _ = Equal
listSame [] (s:ss) _ = FstIsPref $ s :|| ss
listSame (f:fs) [] _ = SndIsPref $ f :|| fs
listSame (f:fs) (s:ss) pr =
if f == s
then listSame fs ss (pr ++ [f])
else Diff (x :|| pr) (f :|| fs) (s :|| ss)
| null | https://raw.githubusercontent.com/kowainik/tomland/561aefdbcf177498c06e6c6fcee2b3fe299b3af6/src/Toml/Type/Key.hs | haskell | * Core types
* Key difference
can't happen
| Bidirectional pattern synonym for constructing and deconstructing 'Key's.
# COMPLETE (:||) #
# INLINE (<|) #
^ Keys are equal
^ Keys don't have any common part.
^ Key have a common prefix.
^ Common prefix. | # LANGUAGE PatternSynonyms #
|
Module : Toml . Type . Key
Copyright : ( c ) 2018 - 2022 Kowainik
SPDX - License - Identifier : MPL-2.0
Maintainer : < >
Stability : Stable
Portability : Portable
Implementation of key type . The type is used for key - value pairs and
table names .
@since 1.3.0.0
Module : Toml.Type.Key
Copyright : (c) 2018-2022 Kowainik
SPDX-License-Identifier : MPL-2.0
Maintainer : Kowainik <>
Stability : Stable
Portability : Portable
Implementation of key type. The type is used for key-value pairs and
table names.
@since 1.3.0.0
-}
module Toml.Type.Key
Key (..)
, Prefix
, Piece (..)
, pattern (:||)
, (<|)
, KeysDiff (..)
, keysDiff
) where
import Control.DeepSeq (NFData)
import Data.Coerce (coerce)
import Data.Hashable (Hashable)
import Data.List.NonEmpty (NonEmpty (..))
import Data.String (IsString (..))
import Data.Text (Text)
import GHC.Generics (Generic)
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Text as Text
| Represents the key piece of some layer .
@since 0.0.0
@since 0.0.0
-}
newtype Piece = Piece
{ unPiece :: Text
} deriving stock (Generic)
deriving newtype (Show, Eq, Ord, Hashable, IsString, NFData)
| Key of value in @key = val@ pair . Represents as non - empty list of key
components — ' 's . Key like
@
site . "google.com "
@
is represented like
@
Key ( Piece " site " :| [ Piece " \\"google.com\\ " " ] )
@
@since 0.0.0
components — 'Piece's. Key like
@
site."google.com"
@
is represented like
@
Key (Piece "site" :| [Piece "\\"google.com\\""])
@
@since 0.0.0
-}
newtype Key = Key
{ unKey :: NonEmpty Piece
} deriving stock (Generic)
deriving newtype (Show, Eq, Ord, Hashable, NFData, Semigroup)
| Type synonym for ' Key ' .
@since 0.0.0
@since 0.0.0
-}
type Prefix = Key
| Split a dot - separated string into ' Key ' . Empty string turns into a ' Key '
with single element — empty ' Piece ' .
This instance is not safe for now . Use carefully . If you try to use as a key
string like this @site.\"google.com\"@ you will have list of three components
instead of desired two .
@since 0.1.0
with single element — empty 'Piece'.
This instance is not safe for now. Use carefully. If you try to use as a key
string like this @site.\"google.com\"@ you will have list of three components
instead of desired two.
@since 0.1.0
-}
instance IsString Key where
fromString :: String -> Key
fromString = \case
"" -> Key ("" :| [])
s -> case Text.splitOn "." (fromString s) of
x:xs -> coerce @(NonEmpty Text) @Key (x :| xs)
pattern (:||) :: Piece -> [Piece] -> Key
pattern x :|| xs <- Key (x :| xs)
where
x :|| xs = Key (x :| xs)
| Prepends ' ' to the beginning of the ' Key ' .
(<|) :: Piece -> Key -> Key
(<|) p k = Key (p NonEmpty.<| unKey k)
| Data represent difference between two keys .
@since 0.0.0
@since 0.0.0
-}
data KeysDiff
^ The first key is the prefix of the second one .
^ Rest of the second key .
^ The second key is the prefix of the first one .
^ Rest of the first key .
^ Rest of the first key .
^ Rest of the second key .
deriving stock (Show, Eq)
| Find key difference between two keys .
@since 0.0.0
@since 0.0.0
-}
keysDiff :: Key -> Key -> KeysDiff
keysDiff (x :|| xs) (y :|| ys)
| x == y = listSame xs ys []
| otherwise = NoPrefix
where
listSame :: [Piece] -> [Piece] -> [Piece] -> KeysDiff
listSame [] [] _ = Equal
listSame [] (s:ss) _ = FstIsPref $ s :|| ss
listSame (f:fs) [] _ = SndIsPref $ f :|| fs
listSame (f:fs) (s:ss) pr =
if f == s
then listSame fs ss (pr ++ [f])
else Diff (x :|| pr) (f :|| fs) (s :|| ss)
|
1ceb3a9a9c20f8b7cedd5492a2750d15cad56f2fb5b55beeacff5eac7c8fc270 | paurkedal/batyr | xmpp_inst.mli | Copyright ( C ) 2013 - -2019 < >
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
*)
(** XMPP based on erm-xmpp specialized for Lwt. *)
open Erm_xml
(** {2 Basic Session} *)
module JID : module type of JID with type t = JID.t
module Chat : sig
include XMPP.S with type 'a t = 'a Lwt.t
type chat = unit session_data
val ns_streams : string option
val ns_server : string option
val ns_client : string option
val ns_xmpp_tls : string option
val ns_xmpp_sasl : string option
val ns_xmpp_bind : string option
val ns_xmpp_session : string option
val register_iq_request_handler :
chat -> Xml.namespace ->
(iq_request -> string option -> string option -> string option ->
unit -> iq_response Lwt.t) ->
unit
val register_stanza_handler :
chat -> Xml.qname ->
(chat -> Xml.attribute list -> Xml.element list -> unit Lwt.t) ->
unit
val parse_message :
callback: (chat -> message_content stanza -> 'a) ->
callback_error: (chat -> ?id: string ->
?jid_from: JID.t -> ?jid_to: string -> ?lang: string ->
StanzaError.t -> 'a) ->
chat -> Xml.attribute list -> Xml.element list -> 'a
val close_stream : chat -> unit Lwt.t
end
type chat = unit Chat.session_data
module Chat_params : sig
type t = {
server : string;
port : int;
username : string;
password : string;
resource : string;
}
val make :
server: string -> ?port : int ->
username: string -> password: string -> ?resource : string ->
unit -> t
end
val with_chat : (chat -> unit Lwt.t) -> Chat_params.t -> unit Lwt.t
* { 2 Features }
module Chat_version : sig
type t = {
name : string;
version : string;
os : string;
}
val ns_version : Xml.namespace
val encode : t -> Xml.element
val decode : Xml.attribute list -> Xml.element list -> t option
val get : chat -> ?jid_from: JID.t -> ?jid_to: JID.t -> ?lang: string ->
?error_callback: (StanzaError.t -> unit Lwt.t) ->
(?jid_from: JID.t -> ?jid_to: JID.t -> ?lang: string ->
t option -> unit Lwt.t) ->
unit Lwt.t
val iq_request :
get: (?jid_from: JID.t -> ?jid_to: JID.t -> ?lang: string ->
unit -> t) ->
Chat.iq_request -> JID.t option -> JID.t option -> string option ->
unit -> Chat.iq_response
val register : ?name: string -> ?version: string -> ?os: string ->
Chat.chat -> unit
end
module Chat_disco : sig
val ns_disco_info : string option
val ns_disco_items : string option
val register_info : ?category: string -> ?type_: string -> ?name: string ->
?features: string list -> Chat.chat -> unit
end
module Chat_ping : sig
val ping : jid_from: JID.t -> jid_to: JID.t -> Chat.chat ->
StanzaError.t option Lwt.t
val ns_ping : string option
val register : Chat.chat -> unit
end
module Chat_muc : sig
val ns_muc : string option
val ns_muc_user : string option
val ns_muc_admin : string option
val ns_muc_owner : string option
val ns_muc_unique : string option
type role =
| RoleModerator
| RoleParticipant
| RoleVisitor
| RoleNone
type affiliation =
| AffiliationOwner
| AffiliationAdmin
| AffiliationMember
| AffiliationOutcast
| AffiliationNone
type muc_data = {
maxchars : int option;
maxstanzas : int option;
seconds : int option;
since : int option;
password : string option;
}
val encode_muc : ?maxchars: int -> ?maxstanzas: int -> ?seconds: int ->
?since: int -> ?password: string -> unit -> Xml.element
val decode_muc : Xml.element -> muc_data
module User : sig
type item = {
actor : JID.t option;
continue : string option;
reason : string option;
jid : JID.t option;
nick : string option;
affiliation : affiliation option;
role : role option;
}
type data = {
decline : (JID.t option * JID.t option * string option) option;
destroy : (JID.t option * string option) option;
invite : (JID.t option * JID.t option * string option) list;
item : item option;
password : string option;
status : int list;
}
val encode : data -> Xml.element
val decode : Xml.element -> data
end
module Admin : sig
type item = {
actor : JID.t option;
reason : string option;
jid : JID.t option;
nick : string option;
affiliation : affiliation option;
role : role option;
}
val encode : Xml.element list -> Xml.element
val encode_item : ?actor: JID.t -> ?reason: string ->
?affiliation: affiliation -> ?jid: string ->
?nick: string -> ?role: role -> unit -> Xml.element
val decode : Xml.element -> item list
end
module Owner : sig
val encode_destroy : ?jid: string -> ?password: string -> ?reason: string ->
unit -> Xml.element
val decode_destroy : Xml.element ->
string option * string option * string option
val encode_xdata : Xml.element -> Xml.element
val decode_xdata : Xml.element -> unit
end
val enter_room :
chat ->
?maxchars: int ->
?maxstanzas: int ->
?seconds: int ->
?since: int ->
?password: string ->
?nick: string ->
JID.t -> unit Lwt.t
val leave_room :
chat ->
?reason: string ->
nick: string ->
JID.t -> unit Lwt.t
end
| null | https://raw.githubusercontent.com/paurkedal/batyr/e7b290340afea5b80880f9ab96db769142438a77/batyr-on-xmpp/lib/xmpp_inst.mli | ocaml | * XMPP based on erm-xmpp specialized for Lwt.
* {2 Basic Session} | Copyright ( C ) 2013 - -2019 < >
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
*)
open Erm_xml
module JID : module type of JID with type t = JID.t
module Chat : sig
include XMPP.S with type 'a t = 'a Lwt.t
type chat = unit session_data
val ns_streams : string option
val ns_server : string option
val ns_client : string option
val ns_xmpp_tls : string option
val ns_xmpp_sasl : string option
val ns_xmpp_bind : string option
val ns_xmpp_session : string option
val register_iq_request_handler :
chat -> Xml.namespace ->
(iq_request -> string option -> string option -> string option ->
unit -> iq_response Lwt.t) ->
unit
val register_stanza_handler :
chat -> Xml.qname ->
(chat -> Xml.attribute list -> Xml.element list -> unit Lwt.t) ->
unit
val parse_message :
callback: (chat -> message_content stanza -> 'a) ->
callback_error: (chat -> ?id: string ->
?jid_from: JID.t -> ?jid_to: string -> ?lang: string ->
StanzaError.t -> 'a) ->
chat -> Xml.attribute list -> Xml.element list -> 'a
val close_stream : chat -> unit Lwt.t
end
type chat = unit Chat.session_data
module Chat_params : sig
type t = {
server : string;
port : int;
username : string;
password : string;
resource : string;
}
val make :
server: string -> ?port : int ->
username: string -> password: string -> ?resource : string ->
unit -> t
end
val with_chat : (chat -> unit Lwt.t) -> Chat_params.t -> unit Lwt.t
* { 2 Features }
module Chat_version : sig
type t = {
name : string;
version : string;
os : string;
}
val ns_version : Xml.namespace
val encode : t -> Xml.element
val decode : Xml.attribute list -> Xml.element list -> t option
val get : chat -> ?jid_from: JID.t -> ?jid_to: JID.t -> ?lang: string ->
?error_callback: (StanzaError.t -> unit Lwt.t) ->
(?jid_from: JID.t -> ?jid_to: JID.t -> ?lang: string ->
t option -> unit Lwt.t) ->
unit Lwt.t
val iq_request :
get: (?jid_from: JID.t -> ?jid_to: JID.t -> ?lang: string ->
unit -> t) ->
Chat.iq_request -> JID.t option -> JID.t option -> string option ->
unit -> Chat.iq_response
val register : ?name: string -> ?version: string -> ?os: string ->
Chat.chat -> unit
end
module Chat_disco : sig
val ns_disco_info : string option
val ns_disco_items : string option
val register_info : ?category: string -> ?type_: string -> ?name: string ->
?features: string list -> Chat.chat -> unit
end
module Chat_ping : sig
val ping : jid_from: JID.t -> jid_to: JID.t -> Chat.chat ->
StanzaError.t option Lwt.t
val ns_ping : string option
val register : Chat.chat -> unit
end
module Chat_muc : sig
val ns_muc : string option
val ns_muc_user : string option
val ns_muc_admin : string option
val ns_muc_owner : string option
val ns_muc_unique : string option
type role =
| RoleModerator
| RoleParticipant
| RoleVisitor
| RoleNone
type affiliation =
| AffiliationOwner
| AffiliationAdmin
| AffiliationMember
| AffiliationOutcast
| AffiliationNone
type muc_data = {
maxchars : int option;
maxstanzas : int option;
seconds : int option;
since : int option;
password : string option;
}
val encode_muc : ?maxchars: int -> ?maxstanzas: int -> ?seconds: int ->
?since: int -> ?password: string -> unit -> Xml.element
val decode_muc : Xml.element -> muc_data
module User : sig
type item = {
actor : JID.t option;
continue : string option;
reason : string option;
jid : JID.t option;
nick : string option;
affiliation : affiliation option;
role : role option;
}
type data = {
decline : (JID.t option * JID.t option * string option) option;
destroy : (JID.t option * string option) option;
invite : (JID.t option * JID.t option * string option) list;
item : item option;
password : string option;
status : int list;
}
val encode : data -> Xml.element
val decode : Xml.element -> data
end
module Admin : sig
type item = {
actor : JID.t option;
reason : string option;
jid : JID.t option;
nick : string option;
affiliation : affiliation option;
role : role option;
}
val encode : Xml.element list -> Xml.element
val encode_item : ?actor: JID.t -> ?reason: string ->
?affiliation: affiliation -> ?jid: string ->
?nick: string -> ?role: role -> unit -> Xml.element
val decode : Xml.element -> item list
end
module Owner : sig
val encode_destroy : ?jid: string -> ?password: string -> ?reason: string ->
unit -> Xml.element
val decode_destroy : Xml.element ->
string option * string option * string option
val encode_xdata : Xml.element -> Xml.element
val decode_xdata : Xml.element -> unit
end
val enter_room :
chat ->
?maxchars: int ->
?maxstanzas: int ->
?seconds: int ->
?since: int ->
?password: string ->
?nick: string ->
JID.t -> unit Lwt.t
val leave_room :
chat ->
?reason: string ->
nick: string ->
JID.t -> unit Lwt.t
end
|
dbe7e4550c67e854460fc592a3c52a6784100f44d575439f1469ee50f0b4d909 | ocamllabs/ocaml-modular-implicits | callback.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
(** Registering OCaml values with the C runtime.
This module allows OCaml values to be registered with the C runtime
under a symbolic name, so that C code can later call back registered
OCaml functions, or raise registered OCaml exceptions.
*)
val register : string -> 'a -> unit
(** [Callback.register n v] registers the value [v] under
the name [n]. C code can later retrieve a handle to [v]
by calling [caml_named_value(n)]. *)
val register_exception : string -> exn -> unit
* [ Callback.register_exception n exn ] registers the
exception contained in the exception value [ exn ]
under the name [ n ] . C code can later retrieve a handle to
the exception by calling [ caml_named_value(n ) ] . The exception
value thus obtained is suitable for passing as first argument
to [ raise_constant ] or [ raise_with_arg ] .
exception contained in the exception value [exn]
under the name [n]. C code can later retrieve a handle to
the exception by calling [caml_named_value(n)]. The exception
value thus obtained is suitable for passing as first argument
to [raise_constant] or [raise_with_arg]. *)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/stdlib/callback.mli | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* Registering OCaml values with the C runtime.
This module allows OCaml values to be registered with the C runtime
under a symbolic name, so that C code can later call back registered
OCaml functions, or raise registered OCaml exceptions.
* [Callback.register n v] registers the value [v] under
the name [n]. C code can later retrieve a handle to [v]
by calling [caml_named_value(n)]. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
val register : string -> 'a -> unit
val register_exception : string -> exn -> unit
* [ Callback.register_exception n exn ] registers the
exception contained in the exception value [ exn ]
under the name [ n ] . C code can later retrieve a handle to
the exception by calling [ caml_named_value(n ) ] . The exception
value thus obtained is suitable for passing as first argument
to [ raise_constant ] or [ raise_with_arg ] .
exception contained in the exception value [exn]
under the name [n]. C code can later retrieve a handle to
the exception by calling [caml_named_value(n)]. The exception
value thus obtained is suitable for passing as first argument
to [raise_constant] or [raise_with_arg]. *)
|
0b7dd064595571fcf70f400b1fa7de484336cbcb39c894d6329af17592760a7a | spacegangster/gcal-clj | specs_calendar.clj | (ns gcal-clj.specs-calendar
(:require [clojure.spec.alpha :as s]
[common.specs]
[common.specs.http]
[gcal-clj.specs-event]
[gcal-clj.specs-macros :as sm]))
(s/def :s.gcal.prop.calendar/kind #{"calendar#calendar"})
(sm/mapdef1 :s.gcal.prop/notification-settings
{:s.prop.gcal/notifications (s/coll-of :s.gcal.ent/reminder)})
(sm/mapdef1 :s.gcal.prop/conference-properties
{:s.prop.gcal/allowedConferenceSolutionTypes (s/coll-of string?)})
; Calendar List entry
#resource
(sm/def-map-props
{:s.gcal.prop.calendar-list-entry/kind #{"calendar#calendarListEntry"},
:s.prop.gcal/id :s.prop/id_goog})
(sm/def-map-props
; :opt-un for calendar list entry
{:s.prop.gcal/description string?
:s.prop.gcal/location string?
:s.prop.gcal/timeZone string?
:s.prop.gcal/summaryOverride string?
:s.prop.gcal/colorId string?
:s.prop.gcal/backgroundColor string?
:s.prop.gcal/foregroundColor string?
:s.prop.gcal/hidden boolean?
:s.prop.gcal/selected boolean?
:s.prop.gcal/accessRole string?
:s.prop.gcal/defaultReminders (s/coll-of :s.gcal.ent/reminder)
:s.prop.gcal/notificationSettings :s.gcal.prop/notification-settings
:s.prop.gcal/primary boolean?,
:s.prop.gcal/deleted boolean?,
:s.prop.gcal/conferenceProperties :s.gcal.prop/conference-properties})
(s/def :s.gcal.ent/calendar-list-entry
(s/keys :req-un
[:s.gcal.prop.calendar-list-entry/kind
:s.http/etag
:s.prop.gcal/id
:s.prop.gcal/summary]
:opt-un
[:s.prop.gcal/description
:s.prop.gcal/location
:s.prop.gcal/timeZone
:s.prop.gcal/summaryOverride
:s.prop.gcal/colorId
:s.prop.gcal/backgroundColor
:s.prop.gcal/foregroundColor
:s.prop.gcal/hidden
:s.prop.gcal/selected
:s.prop.gcal/accessRole
:s.prop.gcal/defaultReminders
:s.prop.gcal/notificationSettings
:s.prop.gcal/primary
:s.prop.gcal/deleted
:s.prop.gcal/conferenceProperties]))
; Calendar plain #resource
(s/def :s.gcal.ent/calendar
(s/keys
:req-un [:s.gcal.prop.calendar/kind
:s.http/etag
:s.prop.gcal/summary]
:opt-un [:s.prop.gcal/description
:s.prop.gcal/timeZone
:s.prop.gcal/nextSyncToken
:s.prop.gcal/updated
:s.prop.gcal/accessRole
:s.prop.gcal/defaultReminders
:s.prop.gcal/items]))
| null | https://raw.githubusercontent.com/spacegangster/gcal-clj/c7b14d6330f1099adb1b9ae6f5631dfebde0cbd3/src/gcal_clj/specs_calendar.clj | clojure | Calendar List entry
:opt-un for calendar list entry
Calendar plain #resource | (ns gcal-clj.specs-calendar
(:require [clojure.spec.alpha :as s]
[common.specs]
[common.specs.http]
[gcal-clj.specs-event]
[gcal-clj.specs-macros :as sm]))
(s/def :s.gcal.prop.calendar/kind #{"calendar#calendar"})
(sm/mapdef1 :s.gcal.prop/notification-settings
{:s.prop.gcal/notifications (s/coll-of :s.gcal.ent/reminder)})
(sm/mapdef1 :s.gcal.prop/conference-properties
{:s.prop.gcal/allowedConferenceSolutionTypes (s/coll-of string?)})
#resource
(sm/def-map-props
{:s.gcal.prop.calendar-list-entry/kind #{"calendar#calendarListEntry"},
:s.prop.gcal/id :s.prop/id_goog})
(sm/def-map-props
{:s.prop.gcal/description string?
:s.prop.gcal/location string?
:s.prop.gcal/timeZone string?
:s.prop.gcal/summaryOverride string?
:s.prop.gcal/colorId string?
:s.prop.gcal/backgroundColor string?
:s.prop.gcal/foregroundColor string?
:s.prop.gcal/hidden boolean?
:s.prop.gcal/selected boolean?
:s.prop.gcal/accessRole string?
:s.prop.gcal/defaultReminders (s/coll-of :s.gcal.ent/reminder)
:s.prop.gcal/notificationSettings :s.gcal.prop/notification-settings
:s.prop.gcal/primary boolean?,
:s.prop.gcal/deleted boolean?,
:s.prop.gcal/conferenceProperties :s.gcal.prop/conference-properties})
(s/def :s.gcal.ent/calendar-list-entry
(s/keys :req-un
[:s.gcal.prop.calendar-list-entry/kind
:s.http/etag
:s.prop.gcal/id
:s.prop.gcal/summary]
:opt-un
[:s.prop.gcal/description
:s.prop.gcal/location
:s.prop.gcal/timeZone
:s.prop.gcal/summaryOverride
:s.prop.gcal/colorId
:s.prop.gcal/backgroundColor
:s.prop.gcal/foregroundColor
:s.prop.gcal/hidden
:s.prop.gcal/selected
:s.prop.gcal/accessRole
:s.prop.gcal/defaultReminders
:s.prop.gcal/notificationSettings
:s.prop.gcal/primary
:s.prop.gcal/deleted
:s.prop.gcal/conferenceProperties]))
(s/def :s.gcal.ent/calendar
(s/keys
:req-un [:s.gcal.prop.calendar/kind
:s.http/etag
:s.prop.gcal/summary]
:opt-un [:s.prop.gcal/description
:s.prop.gcal/timeZone
:s.prop.gcal/nextSyncToken
:s.prop.gcal/updated
:s.prop.gcal/accessRole
:s.prop.gcal/defaultReminders
:s.prop.gcal/items]))
|
3ac69cd41033de53704a15e109b9bc2d2769d881fc3238f282e110d86fae13a3 | janestreet/merlin-jst | outcometree.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Module [Outcometree]: results displayed by the toplevel *)
These types represent messages that the toplevel displays as normal
results or errors . The real displaying is customisable using the hooks :
[ Toploop.print_out_value ]
[ Toploop.print_out_type ]
[ Toploop.print_out_sig_item ]
[ Toploop.print_out_phrase ]
results or errors. The real displaying is customisable using the hooks:
[Toploop.print_out_value]
[Toploop.print_out_type]
[Toploop.print_out_sig_item]
[Toploop.print_out_phrase] *)
(** An [out_name] is a string representation of an identifier which can be
rewritten on the fly to avoid name collisions *)
type out_name = { mutable printed_name: string }
type out_ident =
| Oide_apply of out_ident * out_ident
| Oide_dot of out_ident * string
| Oide_ident of out_name
type out_string =
| Ostr_string
| Ostr_bytes
type out_attribute =
{ oattr_name: string }
type out_value =
| Oval_array of out_value list
| Oval_char of char
| Oval_constr of out_ident * out_value list
| Oval_ellipsis
| Oval_float of float
| Oval_int of int
| Oval_int32 of int32
| Oval_int64 of int64
| Oval_nativeint of nativeint
| Oval_list of out_value list
| Oval_printer of (Format.formatter -> unit)
| Oval_record of (out_ident * out_value) list
| Oval_string of string * int * out_string (* string, size-to-print, kind *)
| Oval_stuff of string
| Oval_tuple of out_value list
| Oval_variant of string * out_value option
type out_type_param = string * (Asttypes.variance * Asttypes.injectivity)
type out_mutable_or_global =
| Ogom_mutable
| Ogom_global
| Ogom_nonlocal
| Ogom_immutable
type out_global =
| Ogf_global
| Ogf_nonlocal
| Ogf_unrestricted
type out_type =
| Otyp_abstract
| Otyp_open
| Otyp_alias of out_type * string
| Otyp_arrow of string * out_alloc_mode * out_type * out_alloc_mode * out_type
| Otyp_class of bool * out_ident * out_type list
| Otyp_constr of out_ident * out_type list
| Otyp_manifest of out_type * out_type
| Otyp_object of (string * out_type) list * bool option
| Otyp_record of (string * out_mutable_or_global * out_type) list
| Otyp_stuff of string
| Otyp_sum of out_constructor list
| Otyp_tuple of out_type list
| Otyp_var of bool * string
| Otyp_variant of
bool * out_variant * bool * (string list) option
| Otyp_poly of string list * out_type
| Otyp_module of out_ident * (string * out_type) list
| Otyp_attribute of out_type * out_attribute
and out_constructor = {
ocstr_name: string;
ocstr_args: (out_type * out_global) list;
ocstr_return_type: out_type option;
}
and out_variant =
| Ovar_fields of (string * bool * out_type list) list
| Ovar_typ of out_type
and out_alloc_mode =
| Oam_local
| Oam_global
| Oam_unknown
type out_class_type =
| Octy_constr of out_ident * out_type list
| Octy_arrow of string * out_type * out_class_type
| Octy_signature of out_type option * out_class_sig_item list
and out_class_sig_item =
| Ocsg_constraint of out_type * out_type
| Ocsg_method of string * bool * bool * out_type
| Ocsg_value of string * bool * bool * out_type
type out_module_type =
| Omty_abstract
| Omty_functor of (string option * out_module_type) option * out_module_type
| Omty_ident of out_ident
| Omty_signature of out_sig_item list
| Omty_alias of out_ident
and out_sig_item =
| Osig_class of
bool * string * out_type_param list * out_class_type *
out_rec_status
| Osig_class_type of
bool * string * out_type_param list * out_class_type *
out_rec_status
| Osig_typext of out_extension_constructor * out_ext_status
| Osig_modtype of string * out_module_type
| Osig_module of string * out_module_type * out_rec_status
| Osig_type of out_type_decl * out_rec_status
| Osig_value of out_val_decl
| Osig_ellipsis
and out_type_decl =
{ otype_name: string;
otype_params: out_type_param list;
otype_type: out_type;
otype_private: Asttypes.private_flag;
otype_immediate: Type_immediacy.t;
otype_unboxed: bool;
otype_cstrs: (out_type * out_type) list }
and out_extension_constructor =
{ oext_name: string;
oext_type_name: string;
oext_type_params: string list;
oext_args: (out_type * out_global) list;
oext_ret_type: out_type option;
oext_private: Asttypes.private_flag }
and out_type_extension =
{ otyext_name: string;
otyext_params: string list;
otyext_constructors: out_constructor list;
otyext_private: Asttypes.private_flag }
and out_val_decl =
{ oval_name: string;
oval_type: out_type;
oval_prims: string list;
oval_attributes: out_attribute list }
and out_rec_status =
| Orec_not
| Orec_first
| Orec_next
and out_ext_status =
| Oext_first
| Oext_next
| Oext_exception
type out_phrase =
| Ophr_eval of out_value * out_type
| Ophr_signature of (out_sig_item * out_value option) list
| Ophr_exception of (exn * out_value)
| null | https://raw.githubusercontent.com/janestreet/merlin-jst/980b574405617fa0dfb0b79a84a66536b46cd71b/upstream/ocaml_flambda/typing/outcometree.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Module [Outcometree]: results displayed by the toplevel
* An [out_name] is a string representation of an identifier which can be
rewritten on the fly to avoid name collisions
string, size-to-print, kind | , projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
These types represent messages that the toplevel displays as normal
results or errors . The real displaying is customisable using the hooks :
[ Toploop.print_out_value ]
[ Toploop.print_out_type ]
[ Toploop.print_out_sig_item ]
[ Toploop.print_out_phrase ]
results or errors. The real displaying is customisable using the hooks:
[Toploop.print_out_value]
[Toploop.print_out_type]
[Toploop.print_out_sig_item]
[Toploop.print_out_phrase] *)
type out_name = { mutable printed_name: string }
type out_ident =
| Oide_apply of out_ident * out_ident
| Oide_dot of out_ident * string
| Oide_ident of out_name
type out_string =
| Ostr_string
| Ostr_bytes
type out_attribute =
{ oattr_name: string }
type out_value =
| Oval_array of out_value list
| Oval_char of char
| Oval_constr of out_ident * out_value list
| Oval_ellipsis
| Oval_float of float
| Oval_int of int
| Oval_int32 of int32
| Oval_int64 of int64
| Oval_nativeint of nativeint
| Oval_list of out_value list
| Oval_printer of (Format.formatter -> unit)
| Oval_record of (out_ident * out_value) list
| Oval_stuff of string
| Oval_tuple of out_value list
| Oval_variant of string * out_value option
type out_type_param = string * (Asttypes.variance * Asttypes.injectivity)
type out_mutable_or_global =
| Ogom_mutable
| Ogom_global
| Ogom_nonlocal
| Ogom_immutable
type out_global =
| Ogf_global
| Ogf_nonlocal
| Ogf_unrestricted
type out_type =
| Otyp_abstract
| Otyp_open
| Otyp_alias of out_type * string
| Otyp_arrow of string * out_alloc_mode * out_type * out_alloc_mode * out_type
| Otyp_class of bool * out_ident * out_type list
| Otyp_constr of out_ident * out_type list
| Otyp_manifest of out_type * out_type
| Otyp_object of (string * out_type) list * bool option
| Otyp_record of (string * out_mutable_or_global * out_type) list
| Otyp_stuff of string
| Otyp_sum of out_constructor list
| Otyp_tuple of out_type list
| Otyp_var of bool * string
| Otyp_variant of
bool * out_variant * bool * (string list) option
| Otyp_poly of string list * out_type
| Otyp_module of out_ident * (string * out_type) list
| Otyp_attribute of out_type * out_attribute
and out_constructor = {
ocstr_name: string;
ocstr_args: (out_type * out_global) list;
ocstr_return_type: out_type option;
}
and out_variant =
| Ovar_fields of (string * bool * out_type list) list
| Ovar_typ of out_type
and out_alloc_mode =
| Oam_local
| Oam_global
| Oam_unknown
type out_class_type =
| Octy_constr of out_ident * out_type list
| Octy_arrow of string * out_type * out_class_type
| Octy_signature of out_type option * out_class_sig_item list
and out_class_sig_item =
| Ocsg_constraint of out_type * out_type
| Ocsg_method of string * bool * bool * out_type
| Ocsg_value of string * bool * bool * out_type
type out_module_type =
| Omty_abstract
| Omty_functor of (string option * out_module_type) option * out_module_type
| Omty_ident of out_ident
| Omty_signature of out_sig_item list
| Omty_alias of out_ident
and out_sig_item =
| Osig_class of
bool * string * out_type_param list * out_class_type *
out_rec_status
| Osig_class_type of
bool * string * out_type_param list * out_class_type *
out_rec_status
| Osig_typext of out_extension_constructor * out_ext_status
| Osig_modtype of string * out_module_type
| Osig_module of string * out_module_type * out_rec_status
| Osig_type of out_type_decl * out_rec_status
| Osig_value of out_val_decl
| Osig_ellipsis
and out_type_decl =
{ otype_name: string;
otype_params: out_type_param list;
otype_type: out_type;
otype_private: Asttypes.private_flag;
otype_immediate: Type_immediacy.t;
otype_unboxed: bool;
otype_cstrs: (out_type * out_type) list }
and out_extension_constructor =
{ oext_name: string;
oext_type_name: string;
oext_type_params: string list;
oext_args: (out_type * out_global) list;
oext_ret_type: out_type option;
oext_private: Asttypes.private_flag }
and out_type_extension =
{ otyext_name: string;
otyext_params: string list;
otyext_constructors: out_constructor list;
otyext_private: Asttypes.private_flag }
and out_val_decl =
{ oval_name: string;
oval_type: out_type;
oval_prims: string list;
oval_attributes: out_attribute list }
and out_rec_status =
| Orec_not
| Orec_first
| Orec_next
and out_ext_status =
| Oext_first
| Oext_next
| Oext_exception
type out_phrase =
| Ophr_eval of out_value * out_type
| Ophr_signature of (out_sig_item * out_value option) list
| Ophr_exception of (exn * out_value)
|
6e7b8ef312bcae590721f4e69e782731e252a430f8c84ca874f7a5f06e9a3a0a | maximk/spawnpool | redirect_handler.erl | -module(redirect_handler).
-export([init/3]).
-export([handle/2,terminate/3]).
-define(ZERGLING_IMAGE, <<"/home/mk/zergling/vmling">>).
-define(BRIDGE, <<"xenbr0">>).
-define(BASIC_EXTRA,
"-notify 10.0.0.1:8909 -shutdown_after 15000 "
" -home /zergling "
"-pz /zergling/ebin "
"-pz /zergling/deps/cowboy/ebin "
"-pz /zergling/deps/cowlib/ebin "
"-pz /zergling/deps/ranch/ebin "
"-pz /zergling/deps/erlydtl/ebin "
"-s zergling_app").
init({tcp,http}, Req, []) ->
{ok,Req,[]}.
handle(Req, St) ->
TsReqReceived = timestamp(),
{ok,DomName,{A0,B0,C0,D0}} = nominator:fresh(),
{RealIp,_} = cowboy_req:header(<<"x-real-ip">>, Req, undefined),
io:format("demo:~s:~s:", [real_host_name(RealIp),DomName]),
Extra = io_lib:format("-ipaddr ~w.~w.~w.~w "
"-netmask 255.0.0.0 "
"-gateway 10.0.0.1 "
"~s -ts_req_received ~w", [A0,B0,C0,D0,?BASIC_EXTRA,TsReqReceived]),
DomOpts = [{extra,list_to_binary(Extra)},
{memory,32},
{bridge,?BRIDGE}],
case egator:create(DomName, ?ZERGLING_IMAGE, DomOpts, []) of
ok ->
{ok,{A,B,C,D}} = nominator:wait_until_ready(DomName),
io:format("~w.~w.~w.~w\n", [A,B,C,D]),
{Path,_} = cowboy_req:path(Req),
RedirectTo = io_lib:format("/internal_redirect/~w.~w.~w.~w/8000~s",
[A,B,C,D,Path]),
Headers = [{<<"X-Accel-Redirect">>,list_to_binary(RedirectTo)}],
{ok,Reply} = cowboy_req:reply(200, Headers, Req),
{ok,Reply,St};
{error,Error} ->
{ok,Body} = error_page(Error),
{ok,Reply} = cowboy_req:reply(200, [], Body, Req),
{ok,Reply,St}
end.
terminate(_What, _Req, _St) ->
ok.
%%------------------------------------------------------------------------------
real_host_name(undefined) -> <<"not-set">>;
real_host_name(IpAddr) when is_binary(IpAddr) ->
case inet:gethostbyaddr(binary_to_list(IpAddr)) of
{error,_} -> IpAddr;
{ok,{hostent,undefined,_,_,_,_}} -> IpAddr;
{ok,{hostent,HostName,_,_,_,_}} -> list_to_binary(HostName) end.
error_page(Error) ->
Vars = [{error,io_lib:format("~p~n", [Error])}],
error_dtl:render(Vars).
timestamp() ->
{Mega,Secs,Micro} = now(),
Mega *1000000.0 + Secs + Micro / 1000000.0.
EOF
| null | https://raw.githubusercontent.com/maximk/spawnpool/f6a36a7634e0d08a6ab48d7bdaa5d2b548d96bcc/src/redirect_handler.erl | erlang | ------------------------------------------------------------------------------ | -module(redirect_handler).
-export([init/3]).
-export([handle/2,terminate/3]).
-define(ZERGLING_IMAGE, <<"/home/mk/zergling/vmling">>).
-define(BRIDGE, <<"xenbr0">>).
-define(BASIC_EXTRA,
"-notify 10.0.0.1:8909 -shutdown_after 15000 "
" -home /zergling "
"-pz /zergling/ebin "
"-pz /zergling/deps/cowboy/ebin "
"-pz /zergling/deps/cowlib/ebin "
"-pz /zergling/deps/ranch/ebin "
"-pz /zergling/deps/erlydtl/ebin "
"-s zergling_app").
init({tcp,http}, Req, []) ->
{ok,Req,[]}.
handle(Req, St) ->
TsReqReceived = timestamp(),
{ok,DomName,{A0,B0,C0,D0}} = nominator:fresh(),
{RealIp,_} = cowboy_req:header(<<"x-real-ip">>, Req, undefined),
io:format("demo:~s:~s:", [real_host_name(RealIp),DomName]),
Extra = io_lib:format("-ipaddr ~w.~w.~w.~w "
"-netmask 255.0.0.0 "
"-gateway 10.0.0.1 "
"~s -ts_req_received ~w", [A0,B0,C0,D0,?BASIC_EXTRA,TsReqReceived]),
DomOpts = [{extra,list_to_binary(Extra)},
{memory,32},
{bridge,?BRIDGE}],
case egator:create(DomName, ?ZERGLING_IMAGE, DomOpts, []) of
ok ->
{ok,{A,B,C,D}} = nominator:wait_until_ready(DomName),
io:format("~w.~w.~w.~w\n", [A,B,C,D]),
{Path,_} = cowboy_req:path(Req),
RedirectTo = io_lib:format("/internal_redirect/~w.~w.~w.~w/8000~s",
[A,B,C,D,Path]),
Headers = [{<<"X-Accel-Redirect">>,list_to_binary(RedirectTo)}],
{ok,Reply} = cowboy_req:reply(200, Headers, Req),
{ok,Reply,St};
{error,Error} ->
{ok,Body} = error_page(Error),
{ok,Reply} = cowboy_req:reply(200, [], Body, Req),
{ok,Reply,St}
end.
terminate(_What, _Req, _St) ->
ok.
real_host_name(undefined) -> <<"not-set">>;
real_host_name(IpAddr) when is_binary(IpAddr) ->
case inet:gethostbyaddr(binary_to_list(IpAddr)) of
{error,_} -> IpAddr;
{ok,{hostent,undefined,_,_,_,_}} -> IpAddr;
{ok,{hostent,HostName,_,_,_,_}} -> list_to_binary(HostName) end.
error_page(Error) ->
Vars = [{error,io_lib:format("~p~n", [Error])}],
error_dtl:render(Vars).
timestamp() ->
{Mega,Secs,Micro} = now(),
Mega *1000000.0 + Secs + Micro / 1000000.0.
EOF
|
b7863e28115f331660c3a32fc75144008ef0f9385fccae3567db63781547a311 | the-little-typer/pie | pretty.rkt | #lang racket/base
(require racket/function racket/list racket/match)
(require "resugar.rkt")
(provide pprint-pie pprint-message indented)
(define indentation (make-parameter 0))
(define-syntax indented
(syntax-rules ()
[(_ i e ...)
(parameterize ([indentation (+ i (indentation))])
(begin e ...))]))
(define (spaces n)
(for ([i (in-range n)])
(printf " ")))
(define (space) (spaces 1))
(define (indent)
(spaces (indentation)))
(define (start-line)
(indent))
(define (terpri)
(printf "\n")
(start-line))
(define (l)
(printf "("))
(define (r)
(printf ")"))
(define-syntax parens
(syntax-rules ()
((_ e ...)
(begin (l)
(indented 1 e ...)
(r)))))
(define (top-binder? sym)
(and (symbol? sym)
(or (eqv? sym '?)
(eqv? sym 'Pi)
(eqv? sym 'Π)
(eqv? sym 'Sigma)
(eqv? sym 'Σ))))
(define (ind? sym)
(and (symbol? sym)
(let ([str (symbol->string sym)])
(and (>= (string-length str) 4)
(string=? (substring str 0 4) "ind-")))))
(define (simple-elim? sym)
(and (symbol? sym)
(or (eqv? sym 'which-Nat)
(eqv? sym 'iter-Nat)
(let ([str (symbol->string sym)])
(and (>= (string-length str) 4)
(string=? (substring str 0 4) "rec-"))))))
(define (sep s op args)
(match args
['() (void)]
[(list b) (op b)]
[(cons b bs) (op b) (s) (sep s op bs)]))
(define (vsep op args)
(sep terpri op args))
(define (hsep op args)
(sep space op args))
(define (annots bindings)
(define (print-binding b)
(match b
[(list (app symbol->string x) ty)
(parens
(printf x)
(space)
(indented (+ (string-length x) 2)
(print-pie ty)))]))
(vsep print-binding bindings))
(define (atomic? x)
(match x
[(? symbol?) #t]
[(? number?) #t]
[(list 'quote _) #t]
[_ #f]))
Print a high - level expression
(define (print-pie expr)
;; Always display something, even if the print code is borked
(with-handlers ([exn:fail? (lambda (e)
(display expr))])
(match expr
[(list (? top-binder? (app symbol->string binder-string))
bindings
body)
(parens (printf binder-string)
(spaces 1)
(indented (add1 (string-length binder-string))
(parens (annots bindings)))
(terpri)
(print-pie body))]
[(list (or 'lambda 'λ) (list-rest args) body)
(parens
(display 'λ) (space) (parens (hsep display args))
(indented 1 (terpri) (print-pie body)))]
[(cons (or '-> '→) (app reverse (cons ret (app reverse args))))
(parens (display "→")
(if (andmap atomic? args)
(begin (space)
(hsep display args))
(indented 3
(space)
(vsep print-pie
args)))
(indented 1 (terpri) (print-pie ret)) )]
[(list 'quote x) (printf "'~a" x)]
[(cons (and op (? ind? (app symbol->string elim))) args)
(define target-count
(case op
[(ind-Vec trans) 2]
[else 1]))
(define-values (targets normal)
(split-at args target-count))
(parens
(display elim)
(space)
(hsep print-pie targets)
(match normal
[(list) (void)]
[(cons motive others)
(indented 2 (terpri) (vsep print-pie (cons motive others)))]))]
[(cons (and op (? simple-elim? (app symbol->string elim))) args)
(match-define (cons target normal) args)
(parens
(display elim)
(space)
(print-pie target)
(match normal
[(list) (void)]
[others
(indented 2
(terpri)
(vsep print-pie others))]))]
[(list-rest (? symbol? op) (? atomic? arg) args)
#:when (and (< (length args) 20)
(andmap atomic? args))
(parens
(hsep print-pie
(cons op (cons arg args))))]
[(list-rest (? symbol? op) arg args)
(parens (print-pie op) (space)
(indented (add1 (string-length (symbol->string op)))
(print-pie arg))
(indented 1
(when (pair? args)
(terpri)
(vsep print-pie
args))))]
[(list-rest op args)
(parens (print-pie op)
(indented 1
(terpri)
(vsep print-pie args)))]
[other (display other)])))
(define (pprint-pie expr (description ""))
(start-line)
(indented (string-length description)
(when (not (string=? description ""))
(display description))
(print-pie expr)))
(define (pprint-claim name ty)
(start-line)
(parens
(indented 1
(display 'claim) (space) (display name) (terpri)
(print-pie ty))))
(define (pprint-message msg)
(start-line)
(for ([part (in-list msg)])
(cond [(string? part)
(display part)]
[(symbol? part)
(space)
(display part)
(space)]
[else (indented 2 (terpri) (print-pie (resugar part))) (terpri)])))
| null | https://raw.githubusercontent.com/the-little-typer/pie/a698d4cacd6823b5161221596d34bd17ce5282b8/pretty.rkt | racket | Always display something, even if the print code is borked | #lang racket/base
(require racket/function racket/list racket/match)
(require "resugar.rkt")
(provide pprint-pie pprint-message indented)
(define indentation (make-parameter 0))
(define-syntax indented
(syntax-rules ()
[(_ i e ...)
(parameterize ([indentation (+ i (indentation))])
(begin e ...))]))
(define (spaces n)
(for ([i (in-range n)])
(printf " ")))
(define (space) (spaces 1))
(define (indent)
(spaces (indentation)))
(define (start-line)
(indent))
(define (terpri)
(printf "\n")
(start-line))
(define (l)
(printf "("))
(define (r)
(printf ")"))
(define-syntax parens
(syntax-rules ()
((_ e ...)
(begin (l)
(indented 1 e ...)
(r)))))
(define (top-binder? sym)
(and (symbol? sym)
(or (eqv? sym '?)
(eqv? sym 'Pi)
(eqv? sym 'Π)
(eqv? sym 'Sigma)
(eqv? sym 'Σ))))
(define (ind? sym)
(and (symbol? sym)
(let ([str (symbol->string sym)])
(and (>= (string-length str) 4)
(string=? (substring str 0 4) "ind-")))))
(define (simple-elim? sym)
(and (symbol? sym)
(or (eqv? sym 'which-Nat)
(eqv? sym 'iter-Nat)
(let ([str (symbol->string sym)])
(and (>= (string-length str) 4)
(string=? (substring str 0 4) "rec-"))))))
(define (sep s op args)
(match args
['() (void)]
[(list b) (op b)]
[(cons b bs) (op b) (s) (sep s op bs)]))
(define (vsep op args)
(sep terpri op args))
(define (hsep op args)
(sep space op args))
(define (annots bindings)
(define (print-binding b)
(match b
[(list (app symbol->string x) ty)
(parens
(printf x)
(space)
(indented (+ (string-length x) 2)
(print-pie ty)))]))
(vsep print-binding bindings))
(define (atomic? x)
(match x
[(? symbol?) #t]
[(? number?) #t]
[(list 'quote _) #t]
[_ #f]))
Print a high - level expression
(define (print-pie expr)
(with-handlers ([exn:fail? (lambda (e)
(display expr))])
(match expr
[(list (? top-binder? (app symbol->string binder-string))
bindings
body)
(parens (printf binder-string)
(spaces 1)
(indented (add1 (string-length binder-string))
(parens (annots bindings)))
(terpri)
(print-pie body))]
[(list (or 'lambda 'λ) (list-rest args) body)
(parens
(display 'λ) (space) (parens (hsep display args))
(indented 1 (terpri) (print-pie body)))]
[(cons (or '-> '→) (app reverse (cons ret (app reverse args))))
(parens (display "→")
(if (andmap atomic? args)
(begin (space)
(hsep display args))
(indented 3
(space)
(vsep print-pie
args)))
(indented 1 (terpri) (print-pie ret)) )]
[(list 'quote x) (printf "'~a" x)]
[(cons (and op (? ind? (app symbol->string elim))) args)
(define target-count
(case op
[(ind-Vec trans) 2]
[else 1]))
(define-values (targets normal)
(split-at args target-count))
(parens
(display elim)
(space)
(hsep print-pie targets)
(match normal
[(list) (void)]
[(cons motive others)
(indented 2 (terpri) (vsep print-pie (cons motive others)))]))]
[(cons (and op (? simple-elim? (app symbol->string elim))) args)
(match-define (cons target normal) args)
(parens
(display elim)
(space)
(print-pie target)
(match normal
[(list) (void)]
[others
(indented 2
(terpri)
(vsep print-pie others))]))]
[(list-rest (? symbol? op) (? atomic? arg) args)
#:when (and (< (length args) 20)
(andmap atomic? args))
(parens
(hsep print-pie
(cons op (cons arg args))))]
[(list-rest (? symbol? op) arg args)
(parens (print-pie op) (space)
(indented (add1 (string-length (symbol->string op)))
(print-pie arg))
(indented 1
(when (pair? args)
(terpri)
(vsep print-pie
args))))]
[(list-rest op args)
(parens (print-pie op)
(indented 1
(terpri)
(vsep print-pie args)))]
[other (display other)])))
(define (pprint-pie expr (description ""))
(start-line)
(indented (string-length description)
(when (not (string=? description ""))
(display description))
(print-pie expr)))
(define (pprint-claim name ty)
(start-line)
(parens
(indented 1
(display 'claim) (space) (display name) (terpri)
(print-pie ty))))
(define (pprint-message msg)
(start-line)
(for ([part (in-list msg)])
(cond [(string? part)
(display part)]
[(symbol? part)
(space)
(display part)
(space)]
[else (indented 2 (terpri) (print-pie (resugar part))) (terpri)])))
|
5db67de7ca45facc86bc9435adb10b430f7fa41d9e5ae0581c78fdd518e8ba23 | LPCIC/matita | grafiteDisambiguate.mli | Copyright ( C ) 2004 - 2005 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* HELM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /
*)
type db
class type g_status =
object
inherit Interpretations.g_status
method disambiguate_db: db
end
class virtual status :
object ('self)
inherit g_status
inherit Interpretations.status
method set_disambiguate_db: db -> 'self
method set_disambiguate_status: #g_status -> 'self
end
val eval_with_new_aliases:
#status as 'status -> ('status -> 'a) ->
(DisambiguateTypes.domain_item * GrafiteAst.alias_spec) list * 'a
val set_proof_aliases:
#status as 'status ->
implicit_aliases:bool -> (* implicit ones are made explicit *)
GrafiteAst.inclusion_mode ->
(DisambiguateTypes.domain_item * GrafiteAst.alias_spec) list -> 'status
val aliases_for_objs:
#NCic.status -> NUri.uri list ->
(DisambiguateTypes.domain_item * GrafiteAst.alias_spec) list
(* args: print function, message (may be empty), status *)
val dump_aliases: (string -> unit) -> string -> #status -> unit
exception BaseUriNotSetYet
val disambiguate_nterm :
#status as 'status ->
NCic.term NCicRefiner.expected_type -> NCic.context -> NCic.metasenv -> NCic.substitution ->
NotationPt.term Disambiguate.disambiguator_input ->
NCic.metasenv * NCic.substitution * 'status * NCic.term
val disambiguate_nobj :
#status as 'status -> ?baseuri:string ->
(NotationPt.term NotationPt.obj) Disambiguate.disambiguator_input ->
'status * NCic.obj
type pattern =
NotationPt.term Disambiguate.disambiguator_input option *
(string * NCic.term) list * NCic.term option
val disambiguate_npattern:
#NCic.status -> GrafiteAst.npattern Disambiguate.disambiguator_input -> pattern
val disambiguate_cic_appl_pattern:
#status ->
NotationPt.argument_pattern list ->
NotationPt.cic_appl_pattern -> NotationPt.cic_appl_pattern
| null | https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/ng_disambiguation/grafiteDisambiguate.mli | ocaml | implicit ones are made explicit
args: print function, message (may be empty), status | Copyright ( C ) 2004 - 2005 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* HELM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /
*)
type db
class type g_status =
object
inherit Interpretations.g_status
method disambiguate_db: db
end
class virtual status :
object ('self)
inherit g_status
inherit Interpretations.status
method set_disambiguate_db: db -> 'self
method set_disambiguate_status: #g_status -> 'self
end
val eval_with_new_aliases:
#status as 'status -> ('status -> 'a) ->
(DisambiguateTypes.domain_item * GrafiteAst.alias_spec) list * 'a
val set_proof_aliases:
#status as 'status ->
GrafiteAst.inclusion_mode ->
(DisambiguateTypes.domain_item * GrafiteAst.alias_spec) list -> 'status
val aliases_for_objs:
#NCic.status -> NUri.uri list ->
(DisambiguateTypes.domain_item * GrafiteAst.alias_spec) list
val dump_aliases: (string -> unit) -> string -> #status -> unit
exception BaseUriNotSetYet
val disambiguate_nterm :
#status as 'status ->
NCic.term NCicRefiner.expected_type -> NCic.context -> NCic.metasenv -> NCic.substitution ->
NotationPt.term Disambiguate.disambiguator_input ->
NCic.metasenv * NCic.substitution * 'status * NCic.term
val disambiguate_nobj :
#status as 'status -> ?baseuri:string ->
(NotationPt.term NotationPt.obj) Disambiguate.disambiguator_input ->
'status * NCic.obj
type pattern =
NotationPt.term Disambiguate.disambiguator_input option *
(string * NCic.term) list * NCic.term option
val disambiguate_npattern:
#NCic.status -> GrafiteAst.npattern Disambiguate.disambiguator_input -> pattern
val disambiguate_cic_appl_pattern:
#status ->
NotationPt.argument_pattern list ->
NotationPt.cic_appl_pattern -> NotationPt.cic_appl_pattern
|
b2eea17176e6fbe304fe3122dd6698a458636d3246174a2d5be2683c71843707 | ghcjs/ghcjs | t4136.hs | module Main where
data T = (:=:) {- | (:!=:) -} deriving (Show,Read)
main
= do putStrLn ("show (:=:) = " ++ show (:=:))
putStrLn ("read (show (:=:)) :: T = " ++
show (read (show (:=:)) :: T))
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/deriving/t4136.hs | haskell | | (:!=:) | module Main where
main
= do putStrLn ("show (:=:) = " ++ show (:=:))
putStrLn ("read (show (:=:)) :: T = " ++
show (read (show (:=:)) :: T))
|
11300a2928bcedcfb90153e431f6ab1e0259f5794f760c9680e240fbef2ec050 | a9032676/Codewars-Haskell | AdditionCommutes_Definitions.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module AdditionCommutes_Definitions where
-- | The natural numbers, encoded in types.
data Z
data S n
-- | Predicate describing natural numbers.
-- | This allows us to reason with `Nat`s.
data Natural :: * -> * where
NumZ :: Natural Z
NumS :: Natural n -> Natural (S n)
-- | Predicate describing equality of natural numbers.
data Equal :: * -> * -> * where
EqlZ :: Equal Z Z
EqlS :: Equal n m -> Equal (S n) (S m)
-- | Peano definition of addition.
type family (:+:) (n :: *) (m :: *) :: *
type instance Z :+: m = m
type instance S n :+: m = S (n :+: m)
-- These are some lemmas that may be helpful.
-- They will *not* be tested, so rename them
-- if you so desire. Good luck!
-- | For any n, n = n.
reflexive :: Natural n -> Equal n n
reflexive NumZ = EqlZ
reflexive (NumS n) = EqlS $ reflexive n
-- | if a = b, then b = a.
symmetric :: Equal a b -> Equal b a
symmetric EqlZ = EqlZ
symmetric (EqlS ab) = EqlS $ symmetric ab
-- | if a = b and b = c, then a = c.
transitive :: Equal a b -> Equal b c -> Equal a c
transitive EqlZ EqlZ = EqlZ
transitive (EqlS ab) (EqlS bc) = EqlS $ transitive ab bc | null | https://raw.githubusercontent.com/a9032676/Codewars-Haskell/6eccd81e9b6ae31b5c0a28ecc16b933f3abae1a5/src/AdditionCommutes_Definitions.hs | haskell | # LANGUAGE GADTs #
| The natural numbers, encoded in types.
| Predicate describing natural numbers.
| This allows us to reason with `Nat`s.
| Predicate describing equality of natural numbers.
| Peano definition of addition.
These are some lemmas that may be helpful.
They will *not* be tested, so rename them
if you so desire. Good luck!
| For any n, n = n.
| if a = b, then b = a.
| if a = b and b = c, then a = c. | # LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module AdditionCommutes_Definitions where
data Z
data S n
data Natural :: * -> * where
NumZ :: Natural Z
NumS :: Natural n -> Natural (S n)
data Equal :: * -> * -> * where
EqlZ :: Equal Z Z
EqlS :: Equal n m -> Equal (S n) (S m)
type family (:+:) (n :: *) (m :: *) :: *
type instance Z :+: m = m
type instance S n :+: m = S (n :+: m)
reflexive :: Natural n -> Equal n n
reflexive NumZ = EqlZ
reflexive (NumS n) = EqlS $ reflexive n
symmetric :: Equal a b -> Equal b a
symmetric EqlZ = EqlZ
symmetric (EqlS ab) = EqlS $ symmetric ab
transitive :: Equal a b -> Equal b c -> Equal a c
transitive EqlZ EqlZ = EqlZ
transitive (EqlS ab) (EqlS bc) = EqlS $ transitive ab bc |
4168dcc87f460833ba8bc0ff660258443ee0c340f0aec026d6b7b26a103c6d5e | pbv/codex | Limits.hs | {-# LANGUAGE OverloadedStrings #-}
{-
Limits for memory, cpu time, etc. under a "sandbox"
-}
module Codex.Tester.Limits (
Limits(..),
lookupLimits,
) where
import Data.Configurator.Types(Config)
import qualified Data.Configurator as Configurator
import Control.Monad (mplus)
-- | SafeExec limits
data Limits
= Limits { maxCpuTime :: !(Maybe Int) -- seconds
, maxClockTime :: !(Maybe Int) -- seconds
, maxMemory :: !(Maybe Int) -- KB
, maxStack :: !(Maybe Int) -- KB
, maxFSize :: !(Maybe Int) -- KB
, maxCore :: !(Maybe Int) -- KB
, numProc :: !(Maybe Int)
} deriving (Eq, Show, Read)
instance Monoid Limits where
-- | empty element; no limits set
mempty
= Limits { maxCpuTime = Nothing
, maxClockTime = Nothing
, maxMemory = Nothing
, maxStack = Nothing
, numProc = Nothing
, maxFSize = Nothing
, maxCore = Nothing
}
instance Semigroup Limits where
-- | combine limits; left-hand side overrriding right-hand side
l <> r
= Limits { maxCpuTime = maxCpuTime l `mplus` maxCpuTime r,
maxClockTime = maxClockTime l `mplus` maxClockTime r,
maxMemory = maxMemory l `mplus` maxMemory r,
maxStack = maxStack l `mplus` maxStack r,
maxFSize = maxFSize l `mplus` maxFSize r,
maxCore = maxCore l `mplus` maxCore r,
numProc = numProc l `mplus` numProc r
}
-- | lookup limits from a subconfig
lookupLimits :: Config -> IO Limits
lookupLimits cfg = do
cpu <- Configurator.lookup cfg "max_cpu"
clock<- Configurator.lookup cfg "max_clock"
mem <- Configurator.lookup cfg "max_memory"
stack <- Configurator.lookup cfg "max_stack"
nproc <- Configurator.lookup cfg "num_proc"
max_fsize <- Configurator.lookup cfg "max_fsize"
max_core <- Configurator.lookup cfg "max_core"
return Limits { maxCpuTime = cpu
, maxClockTime = clock
, maxMemory = mem
, maxStack = stack
, numProc = nproc
, maxFSize = max_fsize
, maxCore = max_core
}
| null | https://raw.githubusercontent.com/pbv/codex/1a5a81965b12f834b436e2165c07120360aded99/src/Codex/Tester/Limits.hs | haskell | # LANGUAGE OverloadedStrings #
Limits for memory, cpu time, etc. under a "sandbox"
| SafeExec limits
seconds
seconds
KB
KB
KB
KB
| empty element; no limits set
| combine limits; left-hand side overrriding right-hand side
| lookup limits from a subconfig | module Codex.Tester.Limits (
Limits(..),
lookupLimits,
) where
import Data.Configurator.Types(Config)
import qualified Data.Configurator as Configurator
import Control.Monad (mplus)
data Limits
, numProc :: !(Maybe Int)
} deriving (Eq, Show, Read)
instance Monoid Limits where
mempty
= Limits { maxCpuTime = Nothing
, maxClockTime = Nothing
, maxMemory = Nothing
, maxStack = Nothing
, numProc = Nothing
, maxFSize = Nothing
, maxCore = Nothing
}
instance Semigroup Limits where
l <> r
= Limits { maxCpuTime = maxCpuTime l `mplus` maxCpuTime r,
maxClockTime = maxClockTime l `mplus` maxClockTime r,
maxMemory = maxMemory l `mplus` maxMemory r,
maxStack = maxStack l `mplus` maxStack r,
maxFSize = maxFSize l `mplus` maxFSize r,
maxCore = maxCore l `mplus` maxCore r,
numProc = numProc l `mplus` numProc r
}
lookupLimits :: Config -> IO Limits
lookupLimits cfg = do
cpu <- Configurator.lookup cfg "max_cpu"
clock<- Configurator.lookup cfg "max_clock"
mem <- Configurator.lookup cfg "max_memory"
stack <- Configurator.lookup cfg "max_stack"
nproc <- Configurator.lookup cfg "num_proc"
max_fsize <- Configurator.lookup cfg "max_fsize"
max_core <- Configurator.lookup cfg "max_core"
return Limits { maxCpuTime = cpu
, maxClockTime = clock
, maxMemory = mem
, maxStack = stack
, numProc = nproc
, maxFSize = max_fsize
, maxCore = max_core
}
|
1e1d3c6f6c703ae0438ad1f862ec788317cc182427b10d5e8e1c0f1f69721c80 | schemedoc/implementation-metadata | airship.scm | (title "Airship Scheme")
(person "Michael Babich")
| null | https://raw.githubusercontent.com/schemedoc/implementation-metadata/6280d9c4c73833dc5bd1c9bef9b45be6ea5beb68/schemes/airship.scm | scheme | (title "Airship Scheme")
(person "Michael Babich")
|
|
ba30a45351ff605b16909585885c8b1f469eb0f268c1246babc183dd11e456ec | project-oak/hafnium-verification | exec.ml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(** Symbolic Execution *)
[@@@warning "+9"]
(** generic command: [∀xs. {foot ∧ sub} ms := - {post}] *)
type spec =
{xs: Var.Set.t; foot: Sh.t; sub: Var.Subst.t; ms: Var.Set.t; post: Sh.t}
type xseg = {us: Var.Set.t; xs: Var.Set.t; seg: Sh.seg}
let fresh_var nam us xs =
let var, us = Var.fresh nam ~wrt:us in
(Term.var var, us, Set.add xs var)
let fresh_seg ~loc ?bas ?len ?siz ?arr ?(xs = Var.Set.empty) us =
let freshen term nam us xs =
match term with
| Some term -> (term, us, xs)
| None -> fresh_var nam us xs
in
let bas, us, xs = freshen bas "b" us xs in
let len, us, xs = freshen len "m" us xs in
let siz, us, xs = freshen siz "n" us xs in
let arr, us, xs = freshen arr "a" us xs in
{us; xs; seg= {loc; bas; len; siz; arr}}
let null_eq ptr = Sh.pure (Term.eq Term.null ptr)
(* Overwritten variables renaming and remaining modified variables. [ws] are
the written variables; [rs] are the variables read or in the
precondition; [us] are the variables to which ghosts must be chosen
fresh. *)
let assign ~ws ~rs ~us =
let ovs = Set.inter ws rs in
let sub = Var.Subst.freshen ovs ~wrt:us in
let us = Set.union us (Var.Subst.range sub) in
let ms = Set.diff ws (Var.Subst.domain sub) in
(sub, ms, us)
(*
* Instruction small axioms
*)
{ emp }
* rs : = es
* { * ᵢ rᵢ=eᵢΘ }
* rs := es
* { *ᵢ rᵢ=eᵢΘ }
*)
let move_spec us reg_exps =
let xs = Var.Set.empty in
let foot = Sh.emp in
let ws, rs =
Vector.fold reg_exps ~init:(Var.Set.empty, Var.Set.empty)
~f:(fun (ws, rs) (reg, exp) ->
(Set.add ws reg, Set.union rs (Term.fv exp)) )
in
let sub, ms, _ = assign ~ws ~rs ~us in
let post =
Vector.fold reg_exps ~init:Sh.emp ~f:(fun post (reg, exp) ->
Sh.and_ (Term.eq (Term.var reg) (Term.rename sub exp)) post )
in
{xs; foot; sub; ms; post}
{ p-[b;m)->⟨l , α⟩ }
* load l r p
* { r = αΘ * ( p-[b;m)->⟨l , α⟩)Θ }
* load l r p
* { r=αΘ * (p-[b;m)->⟨l,α⟩)Θ }
*)
let load_spec us reg ptr len =
let {us; xs; seg} = fresh_seg ~loc:ptr ~siz:len us in
let foot = Sh.seg seg in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let post =
Sh.and_
(Term.eq (Term.var reg) (Term.rename sub seg.arr))
(Sh.rename sub foot)
in
{xs; foot; sub; ms; post}
{ p-[b;m)->⟨l , α⟩ }
* store l p e
* { p-[b;m)->⟨l , e⟩ }
* store l p e
* { p-[b;m)->⟨l,e⟩ }
*)
let store_spec us ptr exp len =
let {us= _; xs; seg} = fresh_seg ~loc:ptr ~siz:len us in
let foot = Sh.seg seg in
let post = Sh.seg {seg with arr= exp} in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
(* { d-[b;m)->⟨l,α⟩ }
* memset l d b
* { d-[b;m)->⟨l,b^⟩ }
*)
let memset_spec us dst byt len =
let {us= _; xs; seg} = fresh_seg ~loc:dst ~siz:len us in
let foot = Sh.seg seg in
let post = Sh.seg {seg with arr= Term.splat byt} in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
(* { d=s * l=0 * d-[b;m)->⟨l,α⟩ }
* memcpy l d s
* { d-[b;m)->⟨l,α⟩ }
*)
let memcpy_eq_spec us dst src len =
let {us= _; xs; seg} = fresh_seg ~loc:dst ~len us in
let dst_heap = Sh.seg seg in
let foot =
Sh.and_ (Term.eq dst src) (Sh.and_ (Term.eq len Term.zero) dst_heap)
in
let post = dst_heap in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ d-[b;m)->⟨l , α⟩ * s-[b';m')->⟨l , α'⟩ }
* memcpy l d s
* { d-[b;m)->⟨l , α'⟩ * s-[b';m')->⟨l , α'⟩ }
* memcpy l d s
* { d-[b;m)->⟨l,α'⟩ * s-[b';m')->⟨l,α'⟩ }
*)
let memcpy_dj_spec us dst src len =
let {us; xs; seg= dst_seg} = fresh_seg ~loc:dst ~siz:len us in
let dst_heap = Sh.seg dst_seg in
let {us= _; xs; seg= src_seg} = fresh_seg ~loc:src ~siz:len ~xs us in
let src_heap = Sh.seg src_seg in
let dst_seg' = {dst_seg with arr= src_seg.arr} in
let dst_heap' = Sh.seg dst_seg' in
let foot = Sh.star dst_heap src_heap in
let post = Sh.star dst_heap' src_heap in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
let memcpy_specs us dst src len =
[memcpy_eq_spec us dst src len; memcpy_dj_spec us dst src len]
{ d = s * d-[b;m)->⟨l , α⟩ }
* l d s
* { d-[b;m)->⟨l , α⟩ }
* memmov l d s
* { d-[b;m)->⟨l,α⟩ }
*)
let memmov_eq_spec us dst src len =
let {us= _; xs; seg= dst_seg} = fresh_seg ~loc:dst ~len us in
let dst_heap = Sh.seg dst_seg in
let foot = Sh.and_ (Term.eq dst src) dst_heap in
let post = dst_heap in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ d-[b;m)->⟨l , α⟩ * s-[b';m')->⟨l , α'⟩ }
* l d s
* { d-[b;m)->⟨l , α'⟩ * s-[b';m')->⟨l , α'⟩ }
* memmov l d s
* { d-[b;m)->⟨l,α'⟩ * s-[b';m')->⟨l,α'⟩ }
*)
let memmov_dj_spec = memcpy_dj_spec
(* memmov footprint for dst < src case *)
let memmov_foot us dst src len =
let xs = Var.Set.empty in
let bas, us, xs = fresh_var "b" us xs in
let siz, us, xs = fresh_var "m" us xs in
let arr_dst, us, xs = fresh_var "a" us xs in
let arr_mid, us, xs = fresh_var "a" us xs in
let arr_src, us, xs = fresh_var "a" us xs in
let src_dst = Term.sub src dst in
let mem_dst = (src_dst, arr_dst) in
let siz_mid = Term.sub len src_dst in
let mem_mid = (siz_mid, arr_mid) in
let mem_src = (src_dst, arr_src) in
let mem_dst_mid_src = [|mem_dst; mem_mid; mem_src|] in
let siz_dst_mid_src, us, xs = fresh_var "m" us xs in
let arr_dst_mid_src, _, xs = fresh_var "a" us xs in
let eq_mem_dst_mid_src =
Term.eq_concat (siz_dst_mid_src, arr_dst_mid_src) mem_dst_mid_src
in
let seg =
Sh.seg
{loc= dst; bas; len= siz; siz= siz_dst_mid_src; arr= arr_dst_mid_src}
in
let foot =
Sh.and_ eq_mem_dst_mid_src
(Sh.and_ (Term.lt dst src)
(Sh.and_ (Term.lt src (Term.add dst len)) seg))
in
(xs, bas, siz, mem_dst, mem_mid, mem_src, foot)
{ d < s * s < d+l * d-[b;m)->⟨s - d , α⟩^⟨l-(s - d),β⟩^⟨s - d , γ⟩ }
* l d s
* { d-[b;m)->⟨l-(s - d),β⟩^⟨s - d , γ⟩^⟨s - d , γ⟩ }
* memmov l d s
* { d-[b;m)->⟨l-(s-d),β⟩^⟨s-d,γ⟩^⟨s-d,γ⟩ }
*)
let memmov_dn_spec us dst src len =
let xs, bas, siz, _, mem_mid, mem_src, foot =
memmov_foot us dst src len
in
let mem_mid_src_src = [|mem_mid; mem_src; mem_src|] in
let siz_mid_src_src, us, xs = fresh_var "m" us xs in
let arr_mid_src_src, _, xs = fresh_var "a" us xs in
let eq_mem_mid_src_src =
Term.eq_concat (siz_mid_src_src, arr_mid_src_src) mem_mid_src_src
in
let post =
Sh.and_ eq_mem_mid_src_src
(Sh.seg
{ loc= dst
; bas
; len= siz
; siz= siz_mid_src_src
; arr= arr_mid_src_src })
in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ s < d * d < s+l * s-[b;m)->⟨d - s , α⟩^⟨l-(d - s),β⟩^⟨d - s , γ⟩ }
* l d s
* { s-[b;m)->⟨d - s , - s , α⟩^⟨l-(d - s),β⟩ }
* memmov l d s
* { s-[b;m)->⟨d-s,α⟩^⟨d-s,α⟩^⟨l-(d-s),β⟩ }
*)
let memmov_up_spec us dst src len =
let xs, bas, siz, mem_src, mem_mid, _, foot =
memmov_foot us src dst len
in
let mem_src_src_mid = [|mem_src; mem_src; mem_mid|] in
let siz_src_src_mid, us, xs = fresh_var "m" us xs in
let arr_src_src_mid, _, xs = fresh_var "a" us xs in
let eq_mem_src_src_mid =
Term.eq_concat (siz_src_src_mid, arr_src_src_mid) mem_src_src_mid
in
let post =
Sh.and_ eq_mem_src_src_mid
(Sh.seg
{ loc= src
; bas
; len= siz
; siz= siz_src_src_mid
; arr= arr_src_src_mid })
in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
let memmov_specs us dst src len =
[ memmov_eq_spec us dst src len; memmov_dj_spec us dst src len
; memmov_dn_spec us dst src len; memmov_up_spec us dst src len ]
{ emp }
* alloc r [ n × l ]
* { ∃α ' . r-[r;(n×l)Θ)->⟨(n×l)Θ , α'⟩ }
* alloc r [n × l]
* { ∃α'. r-[r;(n×l)Θ)->⟨(n×l)Θ,α'⟩ }
*)
let alloc_spec us reg num len =
let foot = Sh.emp in
let siz = Term.mul num len in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:(Term.fv siz) ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us= _; xs; seg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz us in
let post = Sh.seg seg in
{xs; foot; sub; ms; post}
(*
* Memory management - see e.g.
*)
{ ∨ p-[p;m)->⟨m , α⟩ }
* free p
* { emp }
* free p
* { emp }
*)
let free_spec us ptr =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us= _; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.or_ (null_eq ptr) (Sh.seg seg) in
let post = Sh.emp in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
(* { p-[p;m)->⟨m,α⟩ }
* dallocx p
* { emp }
*)
let dallocx_spec us ptr =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us= _; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.seg seg in
let post = Sh.emp in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ emp }
* malloc r s
* { r=0 ∨ ∃α ' . r-[r;sΘ)->⟨sΘ , α'⟩ }
* malloc r s
* { r=0 ∨ ∃α'. r-[r;sΘ)->⟨sΘ,α'⟩ }
*)
let malloc_spec us reg siz =
let foot = Sh.emp in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:(Term.fv siz) ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us= _; xs; seg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz us in
let post = Sh.or_ (null_eq (Term.var reg)) (Sh.seg seg) in
{xs; foot; sub; ms; post}
{ s≠0 }
* mallocx r s
* { r=0 ∨ ∃α ' . r-[r;sΘ)->⟨sΘ , α'⟩ }
* mallocx r s
* { r=0 ∨ ∃α'. r-[r;sΘ)->⟨sΘ,α'⟩ }
*)
let mallocx_spec us reg siz =
let foot = Sh.pure Term.(dq siz zero) in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:(Term.fv siz) ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us= _; xs; seg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz us in
let post = Sh.or_ (null_eq (Term.var reg)) (Sh.seg seg) in
{xs; foot; sub; ms; post}
(* { emp }
* calloc r [n × l]
* { r=0 ∨ r-[r;(n×l)Θ)->⟨(n×l)Θ,0^⟩ }
*)
let calloc_spec us reg num len =
let foot = Sh.emp in
let siz = Term.mul num len in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:(Term.fv siz) ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let arr = Term.splat Term.zero in
let {us= _; xs; seg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz ~arr us in
let post = Sh.or_ (null_eq (Term.var reg)) (Sh.seg seg) in
{xs; foot; sub; ms; post}
let size_of_ptr = Term.size_of Typ.ptr
{ p-[_;_)->⟨W,_⟩ }
* posix_memalign r p s
* { r = ENOMEM * ( p-[_;_)->⟨W,_⟩)Θ
* ∨ ∃α',q . r=0 * ( p-[_;_)->⟨W , q⟩ * , α'⟩)Θ }
* where W = sizeof void *
* posix_memalign r p s
* { r=ENOMEM * (p-[_;_)->⟨W,_⟩)Θ
* ∨ ∃α',q. r=0 * (p-[_;_)->⟨W,q⟩ * q-[q;s)->⟨s,α'⟩)Θ }
* where W = sizeof void*
*)
let posix_memalign_spec us reg ptr siz =
let {us; xs; seg= pseg} = fresh_seg ~loc:ptr ~siz:size_of_ptr us in
let foot = Sh.seg pseg in
let sub, ms, us =
assign ~ws:(Var.Set.of_ reg) ~rs:(Set.union foot.us (Term.fv siz)) ~us
in
let q, us, xs = fresh_var "q" us xs in
let pseg' = {pseg with arr= q} in
let {us= _; xs; seg= qseg} =
fresh_seg ~loc:q ~bas:q ~len:siz ~siz ~xs us
in
let eok = Term.zero in
let enomem = Term.integer (Z.of_int 12) in
let post =
Sh.or_
(Sh.and_ (Term.eq (Term.var reg) enomem) (Sh.rename sub foot))
(Sh.and_
(Term.eq (Term.var reg) eok)
(Sh.rename sub (Sh.star (Sh.seg pseg') (Sh.seg qseg))))
in
{xs; foot; sub; ms; post}
{ ∨ p-[p;m)->⟨m , α⟩ }
* realloc r p s
* { ( r=0 * ( pΘ=0 ∨ pΘ-[pΘ;m)->⟨m , α⟩ ) )
* ∨ ∃α',α '' . r-[r;sΘ)->⟨sΘ , α'⟩
* * ( m≤sΘ ? ⟨sΘ , , , α''⟩ : ⟨m , α⟩=⟨sΘ , α'⟩^⟨m - sΘ , α''⟩ ) }
* realloc r p s
* { (r=0 * (pΘ=0 ∨ pΘ-[pΘ;m)->⟨m,α⟩))
* ∨ ∃α',α'' . r-[r;sΘ)->⟨sΘ,α'⟩
* * (m≤sΘ ? ⟨sΘ,α'⟩=⟨m,α⟩^⟨sΘ-m,α''⟩ : ⟨m,α⟩=⟨sΘ,α'⟩^⟨m-sΘ,α''⟩) }
*)
let realloc_spec us reg ptr siz =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg= pseg} =
fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us
in
let foot = Sh.or_ (null_eq ptr) (Sh.seg pseg) in
let sub, ms, us =
assign ~ws:(Var.Set.of_ reg) ~rs:(Set.union foot.us (Term.fv siz)) ~us
in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us; xs; seg= rseg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz ~xs us in
let a0 = pseg.arr in
let a1 = rseg.arr in
let a2, _, xs = fresh_var "a" us xs in
let post =
Sh.or_
(Sh.and_ Term.(eq loc null) (Sh.rename sub foot))
(Sh.and_
Term.(
conditional ~cnd:(le len siz)
~thn:(eq_concat (siz, a1) [|(len, a0); (sub siz len, a2)|])
~els:(eq_concat (len, a0) [|(siz, a1); (sub len siz, a2)|]))
(Sh.seg rseg))
in
{xs; foot; sub; ms; post}
{ s≠0 * p-[p;m)->⟨m , α⟩ }
* rallocx r p s
* { ( r=0 * pΘ-[pΘ;m)->⟨m , α⟩ )
* ∨ ∃α',α '' . r-[r;sΘ)->⟨sΘ , α'⟩
* * ( m≤sΘ ? ⟨sΘ , , , α''⟩ : ⟨m , α⟩=⟨sΘ , α'⟩^⟨m - sΘ , α''⟩ ) }
* rallocx r p s
* { (r=0 * pΘ-[pΘ;m)->⟨m,α⟩)
* ∨ ∃α',α'' . r-[r;sΘ)->⟨sΘ,α'⟩
* * (m≤sΘ ? ⟨sΘ,α'⟩=⟨m,α⟩^⟨sΘ-m,α''⟩ : ⟨m,α⟩=⟨sΘ,α'⟩^⟨m-sΘ,α''⟩) }
*)
let rallocx_spec us reg ptr siz =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg= pseg} =
fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us
in
let pheap = Sh.seg pseg in
let foot = Sh.and_ Term.(dq siz zero) pheap in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us; xs; seg= rseg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz ~xs us in
let a0 = pseg.arr in
let a1 = rseg.arr in
let a2, _, xs = fresh_var "a" us xs in
let post =
Sh.or_
(Sh.and_ Term.(eq loc null) (Sh.rename sub pheap))
(Sh.and_
Term.(
conditional ~cnd:(le len siz)
~thn:(eq_concat (siz, a1) [|(len, a0); (sub siz len, a2)|])
~els:(eq_concat (len, a0) [|(siz, a1); (sub len siz, a2)|]))
(Sh.seg rseg))
in
{xs; foot; sub; ms; post}
{ s≠0 * p-[p;m)->⟨m , α⟩ }
* xallocx r p s e
* { ∃α',α '' . sΘ≤r≤(s+e)Θ * pΘ-[pΘ;r)->⟨r , α'⟩
* * ( m≤r ? ⟨r , , α⟩^⟨r - m , α''⟩ : ⟨m , α⟩=⟨r , α'⟩^⟨m - r , α''⟩ ) }
* xallocx r p s e
* { ∃α',α'' . sΘ≤r≤(s+e)Θ * pΘ-[pΘ;r)->⟨r,α'⟩
* * (m≤r ? ⟨r,α'⟩=⟨m,α⟩^⟨r-m,α''⟩ : ⟨m,α⟩=⟨r,α'⟩^⟨m-r,α''⟩) }
*)
let xallocx_spec us reg ptr siz ext =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.and_ Term.(dq siz zero) (Sh.seg seg) in
let sub, ms, us =
assign ~ws:(Var.Set.of_ reg)
~rs:Set.(union foot.us (union (Term.fv siz) (Term.fv ext)))
~us
in
let reg = Term.var reg in
let ptr = Term.rename sub ptr in
let siz = Term.rename sub siz in
let ext = Term.rename sub ext in
let {us; xs; seg= seg'} =
fresh_seg ~loc:ptr ~bas:ptr ~len:reg ~siz:reg ~xs us
in
let a0 = seg.arr in
let a1 = seg'.arr in
let a2, _, xs = fresh_var "a" us xs in
let post =
Sh.and_
Term.(
and_
(conditional ~cnd:(le len siz)
~thn:(eq_concat (siz, a1) [|(len, a0); (sub siz len, a2)|])
~els:(eq_concat (len, a0) [|(siz, a1); (sub len siz, a2)|]))
(and_ (le siz reg) (le reg (add siz ext))))
(Sh.seg seg')
in
{xs; foot; sub; ms; post}
(* { p-[p;m)->⟨m,α⟩ }
* sallocx r p
* { r=m * (p-[p;m)->⟨m,α⟩)Θ }
*)
let sallocx_spec us reg ptr =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.seg seg in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let post = Sh.and_ Term.(eq (var reg) len) (Sh.rename sub foot) in
{xs; foot; sub; ms; post}
(* { p-[p;m)->⟨m,α⟩ }
* malloc_usable_size r p
* { m≤r * (p-[p;m)->⟨m,α⟩)Θ }
*)
let malloc_usable_size_spec us reg ptr =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.seg seg in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let post = Sh.and_ Term.(le len (var reg)) (Sh.rename sub foot) in
{xs; foot; sub; ms; post}
(* { s≠0 }
* r = nallocx s
* { r=0 ∨ r=sΘ }
*)
let nallocx_spec us reg siz =
let xs = Var.Set.empty in
let foot = Sh.pure (Term.dq siz Term.zero) in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let post = Sh.or_ (null_eq loc) (Sh.pure (Term.eq loc siz)) in
{xs; foot; sub; ms; post}
let size_of_int_mul = Term.mul (Term.size_of Typ.siz)
(* { r-[_;_)->⟨m,_⟩ * i-[_;_)->⟨_,m⟩ * w=0 * n=0 }
* mallctl r i w n
* { ∃α'. r-[_;_)->⟨m,α'⟩ * i-[_;_)->⟨_,m⟩ }
*)
let mallctl_read_spec us r i w n =
let {us; xs; seg= iseg} = fresh_seg ~loc:i us in
let {us; xs; seg= rseg} = fresh_seg ~loc:r ~siz:iseg.arr ~xs us in
let a, _, xs = fresh_var "a" us xs in
let foot =
Sh.and_
Term.(eq w null)
(Sh.and_ Term.(eq n zero) (Sh.star (Sh.seg iseg) (Sh.seg rseg)))
in
let rseg' = {rseg with arr= a} in
let post = Sh.star (Sh.seg rseg') (Sh.seg iseg) in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ p-[_;_)->⟨W×l,_⟩ * r-[_;_)->⟨m,_⟩ * i-[_;_)->⟨_,m⟩ * w=0 * n=0 }
* mallctlbymib p l r i w n
* { ∃α ' . p-[_;_)->⟨W×l,_⟩ * r-[_;_)->⟨m , α'⟩ * i-[_;_)->⟨_,m⟩ }
* where W = sizeof int
* mallctlbymib p l r i w n
* { ∃α'. p-[_;_)->⟨W×l,_⟩ * r-[_;_)->⟨m,α'⟩ * i-[_;_)->⟨_,m⟩ }
* where W = sizeof int
*)
let mallctlbymib_read_spec us p l r i w n =
let wl = size_of_int_mul l in
let {us; xs; seg= pseg} = fresh_seg ~loc:p ~siz:wl us in
let {us; xs; seg= iseg} = fresh_seg ~loc:i ~xs us in
let m = iseg.arr in
let {us; xs; seg= rseg} = fresh_seg ~loc:r ~siz:m ~xs us in
let const = Sh.star (Sh.seg pseg) (Sh.seg iseg) in
let a, _, xs = fresh_var "a" us xs in
let foot =
Sh.and_
Term.(eq w null)
(Sh.and_ Term.(eq n zero) (Sh.star const (Sh.seg rseg)))
in
let rseg' = {rseg with arr= a} in
let post = Sh.star (Sh.seg rseg') const in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ r=0 * i=0 * }
* mallctl r i w n
* { w-[_;_)->⟨n,_⟩ }
* mallctl r i w n
* { w-[_;_)->⟨n,_⟩ }
*)
let mallctl_write_spec us r i w n =
let {us= _; xs; seg} = fresh_seg ~loc:w ~siz:n us in
let post = Sh.seg seg in
let foot = Sh.and_ Term.(eq r null) (Sh.and_ Term.(eq i zero) post) in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ p-[_;_)->⟨W×l,_⟩ * r=0 * i=0 * }
* mallctl r i w n
* { p-[_;_)->⟨W×l,_⟩ * }
* where W = sizeof int
* mallctl r i w n
* { p-[_;_)->⟨W×l,_⟩ * w-[_;_)->⟨n,_⟩ }
* where W = sizeof int
*)
let mallctlbymib_write_spec us p l r i w n =
let wl = size_of_int_mul l in
let {us; xs; seg= pseg} = fresh_seg ~loc:p ~siz:wl us in
let {us= _; xs; seg= wseg} = fresh_seg ~loc:w ~siz:n ~xs us in
let post = Sh.star (Sh.seg pseg) (Sh.seg wseg) in
let foot = Sh.and_ Term.(eq r null) (Sh.and_ Term.(eq i zero) post) in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
let mallctl_specs us r i w n =
[mallctl_read_spec us r i w n; mallctl_write_spec us r i w n]
let mallctlbymib_specs us p j r i w n =
[ mallctlbymib_read_spec us p j r i w n
; mallctlbymib_write_spec us p j r i w n ]
{ p-[_;_)->⟨W×n , α⟩ * o-[_;_)->⟨_,n⟩ }
* mallctlnametomib p o
* { ∃α ' .
* p-[_;_)->⟨W×n , α'⟩ * o-[_;_)->⟨_,n⟩ }
* where W = sizeof int
*
* Note : post is too strong , more accurate would be :
* { ∃α',α²,α³,n ' . ⟨W×n , - n'),α²⟩ *
* p-[_;_)->⟨W×n',α'⟩ * p+W×n'-[_;_)->⟨W×(n - n'),α²⟩ * o-[_;_)->⟨_,n'⟩ }
* mallctlnametomib p o
* { ∃α'.
* p-[_;_)->⟨W×n,α'⟩ * o-[_;_)->⟨_,n⟩ }
* where W = sizeof int
*
* Note: post is too strong, more accurate would be:
* { ∃α',α²,α³,n'. ⟨W×n,α⟩=⟨W×n',α³⟩^⟨W×(n-n'),α²⟩ *
* p-[_;_)->⟨W×n',α'⟩ * p+W×n'-[_;_)->⟨W×(n-n'),α²⟩ * o-[_;_)->⟨_,n'⟩ }
*)
let mallctlnametomib_spec us p o =
let {us; xs; seg= oseg} = fresh_seg ~loc:o us in
let n = oseg.arr in
let wn = size_of_int_mul n in
let {us; xs; seg= pseg} = fresh_seg ~loc:p ~siz:wn ~xs us in
let a, _, xs = fresh_var "a" us xs in
let foot = Sh.star (Sh.seg oseg) (Sh.seg pseg) in
let pseg' = {pseg with arr= a} in
let post = Sh.star (Sh.seg pseg') (Sh.seg oseg) in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
(*
* cstring - see e.g. /
*)
{ p-[b;m)->⟨l , α⟩ }
* r = strlen p
* { * ( p-[b;m)->⟨l , α⟩)Θ }
* r = strlen p
* { r=(b+m-p-1)Θ * (p-[b;m)->⟨l,α⟩)Θ }
*)
let strlen_spec us reg ptr =
let {us; xs; seg} = fresh_seg ~loc:ptr us in
let foot = Sh.seg seg in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let {Sh.loc= p; bas= b; len= m; _} = seg in
let ret = Term.sub (Term.sub (Term.add b m) p) Term.one in
let post =
Sh.and_
(Term.eq (Term.var reg) (Term.rename sub ret))
(Sh.rename sub foot)
in
{xs; foot; sub; ms; post}
(*
* Symbolic Execution
*)
let check_preserve_us (q0 : Sh.t) (q1 : Sh.t) =
let gain_us = Set.diff q1.us q0.us in
let lose_us = Set.diff q0.us q1.us in
(Set.is_empty gain_us || fail "gain us: %a" Var.Set.pp gain_us ())
&& (Set.is_empty lose_us || fail "lose us: %a" Var.Set.pp lose_us ())
(* execute a command with given spec from pre *)
let exec_spec pre0 {xs; foot; sub; ms; post} =
([%Trace.call fun {pf} ->
pf "@[%a@]@ @[<2>%a@,@[<hv>{%a %a}@;<1 -1>%a--@ {%a }@]@]" Sh.pp pre0
(Sh.pp_us ~pre:"@<2>∀ ")
xs Sh.pp foot
(fun fs sub ->
if not (Var.Subst.is_empty sub) then
Format.fprintf fs "∧ %a" Var.Subst.pp sub )
sub
(fun fs ms ->
if not (Set.is_empty ms) then
Format.fprintf fs "%a := " Var.Set.pp ms )
ms Sh.pp post ;
assert (
let vs = Set.diff (Set.diff foot.us xs) pre0.us in
Set.is_empty vs || fail "unbound foot: {%a}" Var.Set.pp vs () ) ;
assert (
let vs = Set.diff (Set.diff post.us xs) pre0.us in
Set.is_empty vs || fail "unbound post: {%a}" Var.Set.pp vs () )]
;
let foot = Sh.extend_us xs foot in
let zs, pre = Sh.bind_exists pre0 ~wrt:xs in
let+ frame = Solver.infer_frame pre xs foot in
Sh.exists (Set.union zs xs)
(Sh.star post (Sh.exists ms (Sh.rename sub frame))))
|>
[%Trace.retn fun {pf} r ->
pf "%a" (Option.pp "%a" Sh.pp) r ;
assert (Option.for_all ~f:(check_preserve_us pre0) r)]
(* execute a multiple-spec command, where the disjunction of the specs
preconditions are known to be tautologous *)
let rec exec_specs pre = function
| ({xs; foot; _} as spec) :: specs ->
let foot = Sh.extend_us xs foot in
let pre_pure = Sh.star (Sh.exists xs (Sh.pure_approx foot)) pre in
let* post = exec_spec pre_pure spec in
let+ posts = exec_specs pre specs in
Sh.or_ post posts
| [] -> Some (Sh.false_ pre.us)
let exec_specs pre specs =
[%Trace.call fun _ -> ()]
;
exec_specs pre specs
|>
[%Trace.retn fun _ r ->
assert (Option.for_all ~f:(check_preserve_us pre) r)]
(*
* Exposed interface
*)
let assume pre cnd =
let post = Sh.and_ cnd pre in
if Sh.is_false post then None else Some post
let kill pre reg =
let ms = Var.Set.of_ reg in
Sh.extend_us ms (Sh.exists ms pre)
let move pre reg_exps =
exec_spec pre (move_spec pre.us reg_exps)
|> function Some post -> post | _ -> fail "Exec.move failed" ()
let load pre ~reg ~ptr ~len = exec_spec pre (load_spec pre.us reg ptr len)
let store pre ~ptr ~exp ~len = exec_spec pre (store_spec pre.us ptr exp len)
let memset pre ~dst ~byt ~len =
exec_spec pre (memset_spec pre.us dst byt len)
let memcpy pre ~dst ~src ~len =
exec_specs pre (memcpy_specs pre.us dst src len)
let memmov pre ~dst ~src ~len =
exec_specs pre (memmov_specs pre.us dst src len)
let alloc pre ~reg ~num ~len = exec_spec pre (alloc_spec pre.us reg num len)
let free pre ~ptr = exec_spec pre (free_spec pre.us ptr)
let nondet pre = function Some reg -> kill pre reg | None -> pre
let abort _ = None
let intrinsic ~skip_throw :
Sh.t -> Var.t option -> Var.t -> Term.t list -> Sh.t option option =
fun pre areturn intrinsic actuals ->
let us = pre.us in
let name =
let n = Var.name intrinsic in
match String.index n '.' with None -> n | Some i -> String.prefix n i
in
let skip pre = Some (Some pre) in
( match (areturn, name, actuals) with
(*
* cstdlib - memory management
*)
void * malloc(size_t size )
| Some reg, "malloc", [size]
(* void* aligned_alloc(size_t alignment, size_t size) *)
|Some reg, "aligned_alloc", [size; _] ->
Some (exec_spec pre (malloc_spec us reg size))
(* void* calloc(size_t number, size_t size) *)
| Some reg, "calloc", [size; number] ->
Some (exec_spec pre (calloc_spec us reg number size))
(* int posix_memalign(void** ptr, size_t alignment, size_t size) *)
| Some reg, "posix_memalign", [size; _; ptr] ->
Some (exec_spec pre (posix_memalign_spec us reg ptr size))
(* void* realloc(void* ptr, size_t size) *)
| Some reg, "realloc", [size; ptr] ->
Some (exec_spec pre (realloc_spec us reg ptr size))
(*
* jemalloc - non-standard API
*)
void * mallocx(size_t size , int flags )
| Some reg, "mallocx", [_; size] ->
Some (exec_spec pre (mallocx_spec us reg size))
(* void* rallocx(void* ptr, size_t size, int flags) *)
| Some reg, "rallocx", [_; size; ptr] ->
Some (exec_spec pre (rallocx_spec us reg ptr size))
(* size_t xallocx(void* ptr, size_t size, size_t extra, int flags) *)
| Some reg, "xallocx", [_; extra; size; ptr] ->
Some (exec_spec pre (xallocx_spec us reg ptr size extra))
(* size_t sallocx(void* ptr, int flags) *)
| Some reg, "sallocx", [_; ptr] ->
Some (exec_spec pre (sallocx_spec us reg ptr))
(* void dallocx(void* ptr, int flags) *)
| None, "dallocx", [_; ptr]
(* void sdallocx(void* ptr, size_t size, int flags) *)
|None, "sdallocx", [_; _; ptr] ->
Some (exec_spec pre (dallocx_spec us ptr))
(* size_t nallocx(size_t size, int flags) *)
| Some reg, "nallocx", [_; size] ->
Some (exec_spec pre (nallocx_spec us reg size))
size_t malloc_usable_size(void * ptr )
| Some reg, "malloc_usable_size", [ptr] ->
Some (exec_spec pre (malloc_usable_size_spec us reg ptr))
int mallctl(const char * name , void * oldp , size_t * oldlenp , void * newp ,
size_t newlen )
size_t newlen) *)
| Some _, "mallctl", [newlen; newp; oldlenp; oldp; _] ->
Some (exec_specs pre (mallctl_specs us oldp oldlenp newp newlen))
int mallctlnametomib(const char * name , size_t * mibp , size_t * )
| Some _, "mallctlnametomib", [miblenp; mibp; _] ->
Some (exec_spec pre (mallctlnametomib_spec us mibp miblenp))
int mallctlbymib(const size_t * mib , size_t miblen , void * oldp , size_t *
oldlenp , void * newp , size_t newlen ) ;
oldlenp, void* newp, size_t newlen); *)
| Some _, "mallctlbymib", [newlen; newp; oldlenp; oldp; miblen; mib] ->
Some
(exec_specs pre
(mallctlbymib_specs us mib miblen oldp oldlenp newp newlen))
| _, "malloc_stats_print", _ -> skip pre
(*
* cstring
*)
(* size_t strlen (const char* ptr) *)
| Some reg, "strlen", [ptr] ->
Some (exec_spec pre (strlen_spec us reg ptr))
(*
* cxxabi
*)
| Some _, "__cxa_allocate_exception", [_] when skip_throw ->
skip (Sh.false_ pre.us)
(*
* folly
*)
(* bool folly::usingJEMalloc() *)
| Some _, "_ZN5folly13usingJEMallocEv", [] -> skip pre
| _ -> None )
$> function
| None -> ()
| Some _ ->
[%Trace.info
"@[<2>exec intrinsic@ @[%a%a(@[%a@])@] from@ @[{ %a@ }@]@]"
(Option.pp "%a := " Var.pp)
areturn Var.pp intrinsic (List.pp ",@ " Term.pp)
(List.rev actuals) Sh.pp pre]
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/sledge/src/symbheap/exec.ml | ocaml | * Symbolic Execution
* generic command: [∀xs. {foot ∧ sub} ms := - {post}]
Overwritten variables renaming and remaining modified variables. [ws] are
the written variables; [rs] are the variables read or in the
precondition; [us] are the variables to which ghosts must be chosen
fresh.
* Instruction small axioms
{ d-[b;m)->⟨l,α⟩ }
* memset l d b
* { d-[b;m)->⟨l,b^⟩ }
{ d=s * l=0 * d-[b;m)->⟨l,α⟩ }
* memcpy l d s
* { d-[b;m)->⟨l,α⟩ }
memmov footprint for dst < src case
* Memory management - see e.g.
{ p-[p;m)->⟨m,α⟩ }
* dallocx p
* { emp }
{ emp }
* calloc r [n × l]
* { r=0 ∨ r-[r;(n×l)Θ)->⟨(n×l)Θ,0^⟩ }
{ p-[p;m)->⟨m,α⟩ }
* sallocx r p
* { r=m * (p-[p;m)->⟨m,α⟩)Θ }
{ p-[p;m)->⟨m,α⟩ }
* malloc_usable_size r p
* { m≤r * (p-[p;m)->⟨m,α⟩)Θ }
{ s≠0 }
* r = nallocx s
* { r=0 ∨ r=sΘ }
{ r-[_;_)->⟨m,_⟩ * i-[_;_)->⟨_,m⟩ * w=0 * n=0 }
* mallctl r i w n
* { ∃α'. r-[_;_)->⟨m,α'⟩ * i-[_;_)->⟨_,m⟩ }
* cstring - see e.g. /
* Symbolic Execution
execute a command with given spec from pre
execute a multiple-spec command, where the disjunction of the specs
preconditions are known to be tautologous
* Exposed interface
* cstdlib - memory management
void* aligned_alloc(size_t alignment, size_t size)
void* calloc(size_t number, size_t size)
int posix_memalign(void** ptr, size_t alignment, size_t size)
void* realloc(void* ptr, size_t size)
* jemalloc - non-standard API
void* rallocx(void* ptr, size_t size, int flags)
size_t xallocx(void* ptr, size_t size, size_t extra, int flags)
size_t sallocx(void* ptr, int flags)
void dallocx(void* ptr, int flags)
void sdallocx(void* ptr, size_t size, int flags)
size_t nallocx(size_t size, int flags)
* cstring
size_t strlen (const char* ptr)
* cxxabi
* folly
bool folly::usingJEMalloc() |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
[@@@warning "+9"]
type spec =
{xs: Var.Set.t; foot: Sh.t; sub: Var.Subst.t; ms: Var.Set.t; post: Sh.t}
type xseg = {us: Var.Set.t; xs: Var.Set.t; seg: Sh.seg}
let fresh_var nam us xs =
let var, us = Var.fresh nam ~wrt:us in
(Term.var var, us, Set.add xs var)
let fresh_seg ~loc ?bas ?len ?siz ?arr ?(xs = Var.Set.empty) us =
let freshen term nam us xs =
match term with
| Some term -> (term, us, xs)
| None -> fresh_var nam us xs
in
let bas, us, xs = freshen bas "b" us xs in
let len, us, xs = freshen len "m" us xs in
let siz, us, xs = freshen siz "n" us xs in
let arr, us, xs = freshen arr "a" us xs in
{us; xs; seg= {loc; bas; len; siz; arr}}
let null_eq ptr = Sh.pure (Term.eq Term.null ptr)
let assign ~ws ~rs ~us =
let ovs = Set.inter ws rs in
let sub = Var.Subst.freshen ovs ~wrt:us in
let us = Set.union us (Var.Subst.range sub) in
let ms = Set.diff ws (Var.Subst.domain sub) in
(sub, ms, us)
{ emp }
* rs : = es
* { * ᵢ rᵢ=eᵢΘ }
* rs := es
* { *ᵢ rᵢ=eᵢΘ }
*)
let move_spec us reg_exps =
let xs = Var.Set.empty in
let foot = Sh.emp in
let ws, rs =
Vector.fold reg_exps ~init:(Var.Set.empty, Var.Set.empty)
~f:(fun (ws, rs) (reg, exp) ->
(Set.add ws reg, Set.union rs (Term.fv exp)) )
in
let sub, ms, _ = assign ~ws ~rs ~us in
let post =
Vector.fold reg_exps ~init:Sh.emp ~f:(fun post (reg, exp) ->
Sh.and_ (Term.eq (Term.var reg) (Term.rename sub exp)) post )
in
{xs; foot; sub; ms; post}
{ p-[b;m)->⟨l , α⟩ }
* load l r p
* { r = αΘ * ( p-[b;m)->⟨l , α⟩)Θ }
* load l r p
* { r=αΘ * (p-[b;m)->⟨l,α⟩)Θ }
*)
let load_spec us reg ptr len =
let {us; xs; seg} = fresh_seg ~loc:ptr ~siz:len us in
let foot = Sh.seg seg in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let post =
Sh.and_
(Term.eq (Term.var reg) (Term.rename sub seg.arr))
(Sh.rename sub foot)
in
{xs; foot; sub; ms; post}
{ p-[b;m)->⟨l , α⟩ }
* store l p e
* { p-[b;m)->⟨l , e⟩ }
* store l p e
* { p-[b;m)->⟨l,e⟩ }
*)
let store_spec us ptr exp len =
let {us= _; xs; seg} = fresh_seg ~loc:ptr ~siz:len us in
let foot = Sh.seg seg in
let post = Sh.seg {seg with arr= exp} in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
let memset_spec us dst byt len =
let {us= _; xs; seg} = fresh_seg ~loc:dst ~siz:len us in
let foot = Sh.seg seg in
let post = Sh.seg {seg with arr= Term.splat byt} in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
let memcpy_eq_spec us dst src len =
let {us= _; xs; seg} = fresh_seg ~loc:dst ~len us in
let dst_heap = Sh.seg seg in
let foot =
Sh.and_ (Term.eq dst src) (Sh.and_ (Term.eq len Term.zero) dst_heap)
in
let post = dst_heap in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ d-[b;m)->⟨l , α⟩ * s-[b';m')->⟨l , α'⟩ }
* memcpy l d s
* { d-[b;m)->⟨l , α'⟩ * s-[b';m')->⟨l , α'⟩ }
* memcpy l d s
* { d-[b;m)->⟨l,α'⟩ * s-[b';m')->⟨l,α'⟩ }
*)
let memcpy_dj_spec us dst src len =
let {us; xs; seg= dst_seg} = fresh_seg ~loc:dst ~siz:len us in
let dst_heap = Sh.seg dst_seg in
let {us= _; xs; seg= src_seg} = fresh_seg ~loc:src ~siz:len ~xs us in
let src_heap = Sh.seg src_seg in
let dst_seg' = {dst_seg with arr= src_seg.arr} in
let dst_heap' = Sh.seg dst_seg' in
let foot = Sh.star dst_heap src_heap in
let post = Sh.star dst_heap' src_heap in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
let memcpy_specs us dst src len =
[memcpy_eq_spec us dst src len; memcpy_dj_spec us dst src len]
{ d = s * d-[b;m)->⟨l , α⟩ }
* l d s
* { d-[b;m)->⟨l , α⟩ }
* memmov l d s
* { d-[b;m)->⟨l,α⟩ }
*)
let memmov_eq_spec us dst src len =
let {us= _; xs; seg= dst_seg} = fresh_seg ~loc:dst ~len us in
let dst_heap = Sh.seg dst_seg in
let foot = Sh.and_ (Term.eq dst src) dst_heap in
let post = dst_heap in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ d-[b;m)->⟨l , α⟩ * s-[b';m')->⟨l , α'⟩ }
* l d s
* { d-[b;m)->⟨l , α'⟩ * s-[b';m')->⟨l , α'⟩ }
* memmov l d s
* { d-[b;m)->⟨l,α'⟩ * s-[b';m')->⟨l,α'⟩ }
*)
let memmov_dj_spec = memcpy_dj_spec
let memmov_foot us dst src len =
let xs = Var.Set.empty in
let bas, us, xs = fresh_var "b" us xs in
let siz, us, xs = fresh_var "m" us xs in
let arr_dst, us, xs = fresh_var "a" us xs in
let arr_mid, us, xs = fresh_var "a" us xs in
let arr_src, us, xs = fresh_var "a" us xs in
let src_dst = Term.sub src dst in
let mem_dst = (src_dst, arr_dst) in
let siz_mid = Term.sub len src_dst in
let mem_mid = (siz_mid, arr_mid) in
let mem_src = (src_dst, arr_src) in
let mem_dst_mid_src = [|mem_dst; mem_mid; mem_src|] in
let siz_dst_mid_src, us, xs = fresh_var "m" us xs in
let arr_dst_mid_src, _, xs = fresh_var "a" us xs in
let eq_mem_dst_mid_src =
Term.eq_concat (siz_dst_mid_src, arr_dst_mid_src) mem_dst_mid_src
in
let seg =
Sh.seg
{loc= dst; bas; len= siz; siz= siz_dst_mid_src; arr= arr_dst_mid_src}
in
let foot =
Sh.and_ eq_mem_dst_mid_src
(Sh.and_ (Term.lt dst src)
(Sh.and_ (Term.lt src (Term.add dst len)) seg))
in
(xs, bas, siz, mem_dst, mem_mid, mem_src, foot)
{ d < s * s < d+l * d-[b;m)->⟨s - d , α⟩^⟨l-(s - d),β⟩^⟨s - d , γ⟩ }
* l d s
* { d-[b;m)->⟨l-(s - d),β⟩^⟨s - d , γ⟩^⟨s - d , γ⟩ }
* memmov l d s
* { d-[b;m)->⟨l-(s-d),β⟩^⟨s-d,γ⟩^⟨s-d,γ⟩ }
*)
let memmov_dn_spec us dst src len =
let xs, bas, siz, _, mem_mid, mem_src, foot =
memmov_foot us dst src len
in
let mem_mid_src_src = [|mem_mid; mem_src; mem_src|] in
let siz_mid_src_src, us, xs = fresh_var "m" us xs in
let arr_mid_src_src, _, xs = fresh_var "a" us xs in
let eq_mem_mid_src_src =
Term.eq_concat (siz_mid_src_src, arr_mid_src_src) mem_mid_src_src
in
let post =
Sh.and_ eq_mem_mid_src_src
(Sh.seg
{ loc= dst
; bas
; len= siz
; siz= siz_mid_src_src
; arr= arr_mid_src_src })
in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ s < d * d < s+l * s-[b;m)->⟨d - s , α⟩^⟨l-(d - s),β⟩^⟨d - s , γ⟩ }
* l d s
* { s-[b;m)->⟨d - s , - s , α⟩^⟨l-(d - s),β⟩ }
* memmov l d s
* { s-[b;m)->⟨d-s,α⟩^⟨d-s,α⟩^⟨l-(d-s),β⟩ }
*)
let memmov_up_spec us dst src len =
let xs, bas, siz, mem_src, mem_mid, _, foot =
memmov_foot us src dst len
in
let mem_src_src_mid = [|mem_src; mem_src; mem_mid|] in
let siz_src_src_mid, us, xs = fresh_var "m" us xs in
let arr_src_src_mid, _, xs = fresh_var "a" us xs in
let eq_mem_src_src_mid =
Term.eq_concat (siz_src_src_mid, arr_src_src_mid) mem_src_src_mid
in
let post =
Sh.and_ eq_mem_src_src_mid
(Sh.seg
{ loc= src
; bas
; len= siz
; siz= siz_src_src_mid
; arr= arr_src_src_mid })
in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
let memmov_specs us dst src len =
[ memmov_eq_spec us dst src len; memmov_dj_spec us dst src len
; memmov_dn_spec us dst src len; memmov_up_spec us dst src len ]
{ emp }
* alloc r [ n × l ]
* { ∃α ' . r-[r;(n×l)Θ)->⟨(n×l)Θ , α'⟩ }
* alloc r [n × l]
* { ∃α'. r-[r;(n×l)Θ)->⟨(n×l)Θ,α'⟩ }
*)
let alloc_spec us reg num len =
let foot = Sh.emp in
let siz = Term.mul num len in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:(Term.fv siz) ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us= _; xs; seg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz us in
let post = Sh.seg seg in
{xs; foot; sub; ms; post}
{ ∨ p-[p;m)->⟨m , α⟩ }
* free p
* { emp }
* free p
* { emp }
*)
let free_spec us ptr =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us= _; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.or_ (null_eq ptr) (Sh.seg seg) in
let post = Sh.emp in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
let dallocx_spec us ptr =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us= _; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.seg seg in
let post = Sh.emp in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ emp }
* malloc r s
* { r=0 ∨ ∃α ' . r-[r;sΘ)->⟨sΘ , α'⟩ }
* malloc r s
* { r=0 ∨ ∃α'. r-[r;sΘ)->⟨sΘ,α'⟩ }
*)
let malloc_spec us reg siz =
let foot = Sh.emp in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:(Term.fv siz) ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us= _; xs; seg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz us in
let post = Sh.or_ (null_eq (Term.var reg)) (Sh.seg seg) in
{xs; foot; sub; ms; post}
{ s≠0 }
* mallocx r s
* { r=0 ∨ ∃α ' . r-[r;sΘ)->⟨sΘ , α'⟩ }
* mallocx r s
* { r=0 ∨ ∃α'. r-[r;sΘ)->⟨sΘ,α'⟩ }
*)
let mallocx_spec us reg siz =
let foot = Sh.pure Term.(dq siz zero) in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:(Term.fv siz) ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us= _; xs; seg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz us in
let post = Sh.or_ (null_eq (Term.var reg)) (Sh.seg seg) in
{xs; foot; sub; ms; post}
let calloc_spec us reg num len =
let foot = Sh.emp in
let siz = Term.mul num len in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:(Term.fv siz) ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let arr = Term.splat Term.zero in
let {us= _; xs; seg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz ~arr us in
let post = Sh.or_ (null_eq (Term.var reg)) (Sh.seg seg) in
{xs; foot; sub; ms; post}
let size_of_ptr = Term.size_of Typ.ptr
{ p-[_;_)->⟨W,_⟩ }
* posix_memalign r p s
* { r = ENOMEM * ( p-[_;_)->⟨W,_⟩)Θ
* ∨ ∃α',q . r=0 * ( p-[_;_)->⟨W , q⟩ * , α'⟩)Θ }
* where W = sizeof void *
* posix_memalign r p s
* { r=ENOMEM * (p-[_;_)->⟨W,_⟩)Θ
* ∨ ∃α',q. r=0 * (p-[_;_)->⟨W,q⟩ * q-[q;s)->⟨s,α'⟩)Θ }
* where W = sizeof void*
*)
let posix_memalign_spec us reg ptr siz =
let {us; xs; seg= pseg} = fresh_seg ~loc:ptr ~siz:size_of_ptr us in
let foot = Sh.seg pseg in
let sub, ms, us =
assign ~ws:(Var.Set.of_ reg) ~rs:(Set.union foot.us (Term.fv siz)) ~us
in
let q, us, xs = fresh_var "q" us xs in
let pseg' = {pseg with arr= q} in
let {us= _; xs; seg= qseg} =
fresh_seg ~loc:q ~bas:q ~len:siz ~siz ~xs us
in
let eok = Term.zero in
let enomem = Term.integer (Z.of_int 12) in
let post =
Sh.or_
(Sh.and_ (Term.eq (Term.var reg) enomem) (Sh.rename sub foot))
(Sh.and_
(Term.eq (Term.var reg) eok)
(Sh.rename sub (Sh.star (Sh.seg pseg') (Sh.seg qseg))))
in
{xs; foot; sub; ms; post}
{ ∨ p-[p;m)->⟨m , α⟩ }
* realloc r p s
* { ( r=0 * ( pΘ=0 ∨ pΘ-[pΘ;m)->⟨m , α⟩ ) )
* ∨ ∃α',α '' . r-[r;sΘ)->⟨sΘ , α'⟩
* * ( m≤sΘ ? ⟨sΘ , , , α''⟩ : ⟨m , α⟩=⟨sΘ , α'⟩^⟨m - sΘ , α''⟩ ) }
* realloc r p s
* { (r=0 * (pΘ=0 ∨ pΘ-[pΘ;m)->⟨m,α⟩))
* ∨ ∃α',α'' . r-[r;sΘ)->⟨sΘ,α'⟩
* * (m≤sΘ ? ⟨sΘ,α'⟩=⟨m,α⟩^⟨sΘ-m,α''⟩ : ⟨m,α⟩=⟨sΘ,α'⟩^⟨m-sΘ,α''⟩) }
*)
let realloc_spec us reg ptr siz =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg= pseg} =
fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us
in
let foot = Sh.or_ (null_eq ptr) (Sh.seg pseg) in
let sub, ms, us =
assign ~ws:(Var.Set.of_ reg) ~rs:(Set.union foot.us (Term.fv siz)) ~us
in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us; xs; seg= rseg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz ~xs us in
let a0 = pseg.arr in
let a1 = rseg.arr in
let a2, _, xs = fresh_var "a" us xs in
let post =
Sh.or_
(Sh.and_ Term.(eq loc null) (Sh.rename sub foot))
(Sh.and_
Term.(
conditional ~cnd:(le len siz)
~thn:(eq_concat (siz, a1) [|(len, a0); (sub siz len, a2)|])
~els:(eq_concat (len, a0) [|(siz, a1); (sub len siz, a2)|]))
(Sh.seg rseg))
in
{xs; foot; sub; ms; post}
{ s≠0 * p-[p;m)->⟨m , α⟩ }
* rallocx r p s
* { ( r=0 * pΘ-[pΘ;m)->⟨m , α⟩ )
* ∨ ∃α',α '' . r-[r;sΘ)->⟨sΘ , α'⟩
* * ( m≤sΘ ? ⟨sΘ , , , α''⟩ : ⟨m , α⟩=⟨sΘ , α'⟩^⟨m - sΘ , α''⟩ ) }
* rallocx r p s
* { (r=0 * pΘ-[pΘ;m)->⟨m,α⟩)
* ∨ ∃α',α'' . r-[r;sΘ)->⟨sΘ,α'⟩
* * (m≤sΘ ? ⟨sΘ,α'⟩=⟨m,α⟩^⟨sΘ-m,α''⟩ : ⟨m,α⟩=⟨sΘ,α'⟩^⟨m-sΘ,α''⟩) }
*)
let rallocx_spec us reg ptr siz =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg= pseg} =
fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us
in
let pheap = Sh.seg pseg in
let foot = Sh.and_ Term.(dq siz zero) pheap in
let sub, ms, us = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let {us; xs; seg= rseg} = fresh_seg ~loc ~bas:loc ~len:siz ~siz ~xs us in
let a0 = pseg.arr in
let a1 = rseg.arr in
let a2, _, xs = fresh_var "a" us xs in
let post =
Sh.or_
(Sh.and_ Term.(eq loc null) (Sh.rename sub pheap))
(Sh.and_
Term.(
conditional ~cnd:(le len siz)
~thn:(eq_concat (siz, a1) [|(len, a0); (sub siz len, a2)|])
~els:(eq_concat (len, a0) [|(siz, a1); (sub len siz, a2)|]))
(Sh.seg rseg))
in
{xs; foot; sub; ms; post}
{ s≠0 * p-[p;m)->⟨m , α⟩ }
* xallocx r p s e
* { ∃α',α '' . sΘ≤r≤(s+e)Θ * pΘ-[pΘ;r)->⟨r , α'⟩
* * ( m≤r ? ⟨r , , α⟩^⟨r - m , α''⟩ : ⟨m , α⟩=⟨r , α'⟩^⟨m - r , α''⟩ ) }
* xallocx r p s e
* { ∃α',α'' . sΘ≤r≤(s+e)Θ * pΘ-[pΘ;r)->⟨r,α'⟩
* * (m≤r ? ⟨r,α'⟩=⟨m,α⟩^⟨r-m,α''⟩ : ⟨m,α⟩=⟨r,α'⟩^⟨m-r,α''⟩) }
*)
let xallocx_spec us reg ptr siz ext =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.and_ Term.(dq siz zero) (Sh.seg seg) in
let sub, ms, us =
assign ~ws:(Var.Set.of_ reg)
~rs:Set.(union foot.us (union (Term.fv siz) (Term.fv ext)))
~us
in
let reg = Term.var reg in
let ptr = Term.rename sub ptr in
let siz = Term.rename sub siz in
let ext = Term.rename sub ext in
let {us; xs; seg= seg'} =
fresh_seg ~loc:ptr ~bas:ptr ~len:reg ~siz:reg ~xs us
in
let a0 = seg.arr in
let a1 = seg'.arr in
let a2, _, xs = fresh_var "a" us xs in
let post =
Sh.and_
Term.(
and_
(conditional ~cnd:(le len siz)
~thn:(eq_concat (siz, a1) [|(len, a0); (sub siz len, a2)|])
~els:(eq_concat (len, a0) [|(siz, a1); (sub len siz, a2)|]))
(and_ (le siz reg) (le reg (add siz ext))))
(Sh.seg seg')
in
{xs; foot; sub; ms; post}
let sallocx_spec us reg ptr =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.seg seg in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let post = Sh.and_ Term.(eq (var reg) len) (Sh.rename sub foot) in
{xs; foot; sub; ms; post}
let malloc_usable_size_spec us reg ptr =
let len, us, xs = fresh_var "m" us Var.Set.empty in
let {us; xs; seg} = fresh_seg ~loc:ptr ~bas:ptr ~len ~siz:len ~xs us in
let foot = Sh.seg seg in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let post = Sh.and_ Term.(le len (var reg)) (Sh.rename sub foot) in
{xs; foot; sub; ms; post}
let nallocx_spec us reg siz =
let xs = Var.Set.empty in
let foot = Sh.pure (Term.dq siz Term.zero) in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let loc = Term.var reg in
let siz = Term.rename sub siz in
let post = Sh.or_ (null_eq loc) (Sh.pure (Term.eq loc siz)) in
{xs; foot; sub; ms; post}
let size_of_int_mul = Term.mul (Term.size_of Typ.siz)
let mallctl_read_spec us r i w n =
let {us; xs; seg= iseg} = fresh_seg ~loc:i us in
let {us; xs; seg= rseg} = fresh_seg ~loc:r ~siz:iseg.arr ~xs us in
let a, _, xs = fresh_var "a" us xs in
let foot =
Sh.and_
Term.(eq w null)
(Sh.and_ Term.(eq n zero) (Sh.star (Sh.seg iseg) (Sh.seg rseg)))
in
let rseg' = {rseg with arr= a} in
let post = Sh.star (Sh.seg rseg') (Sh.seg iseg) in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ p-[_;_)->⟨W×l,_⟩ * r-[_;_)->⟨m,_⟩ * i-[_;_)->⟨_,m⟩ * w=0 * n=0 }
* mallctlbymib p l r i w n
* { ∃α ' . p-[_;_)->⟨W×l,_⟩ * r-[_;_)->⟨m , α'⟩ * i-[_;_)->⟨_,m⟩ }
* where W = sizeof int
* mallctlbymib p l r i w n
* { ∃α'. p-[_;_)->⟨W×l,_⟩ * r-[_;_)->⟨m,α'⟩ * i-[_;_)->⟨_,m⟩ }
* where W = sizeof int
*)
let mallctlbymib_read_spec us p l r i w n =
let wl = size_of_int_mul l in
let {us; xs; seg= pseg} = fresh_seg ~loc:p ~siz:wl us in
let {us; xs; seg= iseg} = fresh_seg ~loc:i ~xs us in
let m = iseg.arr in
let {us; xs; seg= rseg} = fresh_seg ~loc:r ~siz:m ~xs us in
let const = Sh.star (Sh.seg pseg) (Sh.seg iseg) in
let a, _, xs = fresh_var "a" us xs in
let foot =
Sh.and_
Term.(eq w null)
(Sh.and_ Term.(eq n zero) (Sh.star const (Sh.seg rseg)))
in
let rseg' = {rseg with arr= a} in
let post = Sh.star (Sh.seg rseg') const in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ r=0 * i=0 * }
* mallctl r i w n
* { w-[_;_)->⟨n,_⟩ }
* mallctl r i w n
* { w-[_;_)->⟨n,_⟩ }
*)
let mallctl_write_spec us r i w n =
let {us= _; xs; seg} = fresh_seg ~loc:w ~siz:n us in
let post = Sh.seg seg in
let foot = Sh.and_ Term.(eq r null) (Sh.and_ Term.(eq i zero) post) in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ p-[_;_)->⟨W×l,_⟩ * r=0 * i=0 * }
* mallctl r i w n
* { p-[_;_)->⟨W×l,_⟩ * }
* where W = sizeof int
* mallctl r i w n
* { p-[_;_)->⟨W×l,_⟩ * w-[_;_)->⟨n,_⟩ }
* where W = sizeof int
*)
let mallctlbymib_write_spec us p l r i w n =
let wl = size_of_int_mul l in
let {us; xs; seg= pseg} = fresh_seg ~loc:p ~siz:wl us in
let {us= _; xs; seg= wseg} = fresh_seg ~loc:w ~siz:n ~xs us in
let post = Sh.star (Sh.seg pseg) (Sh.seg wseg) in
let foot = Sh.and_ Term.(eq r null) (Sh.and_ Term.(eq i zero) post) in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
let mallctl_specs us r i w n =
[mallctl_read_spec us r i w n; mallctl_write_spec us r i w n]
let mallctlbymib_specs us p j r i w n =
[ mallctlbymib_read_spec us p j r i w n
; mallctlbymib_write_spec us p j r i w n ]
{ p-[_;_)->⟨W×n , α⟩ * o-[_;_)->⟨_,n⟩ }
* mallctlnametomib p o
* { ∃α ' .
* p-[_;_)->⟨W×n , α'⟩ * o-[_;_)->⟨_,n⟩ }
* where W = sizeof int
*
* Note : post is too strong , more accurate would be :
* { ∃α',α²,α³,n ' . ⟨W×n , - n'),α²⟩ *
* p-[_;_)->⟨W×n',α'⟩ * p+W×n'-[_;_)->⟨W×(n - n'),α²⟩ * o-[_;_)->⟨_,n'⟩ }
* mallctlnametomib p o
* { ∃α'.
* p-[_;_)->⟨W×n,α'⟩ * o-[_;_)->⟨_,n⟩ }
* where W = sizeof int
*
* Note: post is too strong, more accurate would be:
* { ∃α',α²,α³,n'. ⟨W×n,α⟩=⟨W×n',α³⟩^⟨W×(n-n'),α²⟩ *
* p-[_;_)->⟨W×n',α'⟩ * p+W×n'-[_;_)->⟨W×(n-n'),α²⟩ * o-[_;_)->⟨_,n'⟩ }
*)
let mallctlnametomib_spec us p o =
let {us; xs; seg= oseg} = fresh_seg ~loc:o us in
let n = oseg.arr in
let wn = size_of_int_mul n in
let {us; xs; seg= pseg} = fresh_seg ~loc:p ~siz:wn ~xs us in
let a, _, xs = fresh_var "a" us xs in
let foot = Sh.star (Sh.seg oseg) (Sh.seg pseg) in
let pseg' = {pseg with arr= a} in
let post = Sh.star (Sh.seg pseg') (Sh.seg oseg) in
{xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post}
{ p-[b;m)->⟨l , α⟩ }
* r = strlen p
* { * ( p-[b;m)->⟨l , α⟩)Θ }
* r = strlen p
* { r=(b+m-p-1)Θ * (p-[b;m)->⟨l,α⟩)Θ }
*)
let strlen_spec us reg ptr =
let {us; xs; seg} = fresh_seg ~loc:ptr us in
let foot = Sh.seg seg in
let sub, ms, _ = assign ~ws:(Var.Set.of_ reg) ~rs:foot.us ~us in
let {Sh.loc= p; bas= b; len= m; _} = seg in
let ret = Term.sub (Term.sub (Term.add b m) p) Term.one in
let post =
Sh.and_
(Term.eq (Term.var reg) (Term.rename sub ret))
(Sh.rename sub foot)
in
{xs; foot; sub; ms; post}
let check_preserve_us (q0 : Sh.t) (q1 : Sh.t) =
let gain_us = Set.diff q1.us q0.us in
let lose_us = Set.diff q0.us q1.us in
(Set.is_empty gain_us || fail "gain us: %a" Var.Set.pp gain_us ())
&& (Set.is_empty lose_us || fail "lose us: %a" Var.Set.pp lose_us ())
let exec_spec pre0 {xs; foot; sub; ms; post} =
([%Trace.call fun {pf} ->
pf "@[%a@]@ @[<2>%a@,@[<hv>{%a %a}@;<1 -1>%a--@ {%a }@]@]" Sh.pp pre0
(Sh.pp_us ~pre:"@<2>∀ ")
xs Sh.pp foot
(fun fs sub ->
if not (Var.Subst.is_empty sub) then
Format.fprintf fs "∧ %a" Var.Subst.pp sub )
sub
(fun fs ms ->
if not (Set.is_empty ms) then
Format.fprintf fs "%a := " Var.Set.pp ms )
ms Sh.pp post ;
assert (
let vs = Set.diff (Set.diff foot.us xs) pre0.us in
Set.is_empty vs || fail "unbound foot: {%a}" Var.Set.pp vs () ) ;
assert (
let vs = Set.diff (Set.diff post.us xs) pre0.us in
Set.is_empty vs || fail "unbound post: {%a}" Var.Set.pp vs () )]
;
let foot = Sh.extend_us xs foot in
let zs, pre = Sh.bind_exists pre0 ~wrt:xs in
let+ frame = Solver.infer_frame pre xs foot in
Sh.exists (Set.union zs xs)
(Sh.star post (Sh.exists ms (Sh.rename sub frame))))
|>
[%Trace.retn fun {pf} r ->
pf "%a" (Option.pp "%a" Sh.pp) r ;
assert (Option.for_all ~f:(check_preserve_us pre0) r)]
let rec exec_specs pre = function
| ({xs; foot; _} as spec) :: specs ->
let foot = Sh.extend_us xs foot in
let pre_pure = Sh.star (Sh.exists xs (Sh.pure_approx foot)) pre in
let* post = exec_spec pre_pure spec in
let+ posts = exec_specs pre specs in
Sh.or_ post posts
| [] -> Some (Sh.false_ pre.us)
let exec_specs pre specs =
[%Trace.call fun _ -> ()]
;
exec_specs pre specs
|>
[%Trace.retn fun _ r ->
assert (Option.for_all ~f:(check_preserve_us pre) r)]
let assume pre cnd =
let post = Sh.and_ cnd pre in
if Sh.is_false post then None else Some post
let kill pre reg =
let ms = Var.Set.of_ reg in
Sh.extend_us ms (Sh.exists ms pre)
let move pre reg_exps =
exec_spec pre (move_spec pre.us reg_exps)
|> function Some post -> post | _ -> fail "Exec.move failed" ()
let load pre ~reg ~ptr ~len = exec_spec pre (load_spec pre.us reg ptr len)
let store pre ~ptr ~exp ~len = exec_spec pre (store_spec pre.us ptr exp len)
let memset pre ~dst ~byt ~len =
exec_spec pre (memset_spec pre.us dst byt len)
let memcpy pre ~dst ~src ~len =
exec_specs pre (memcpy_specs pre.us dst src len)
let memmov pre ~dst ~src ~len =
exec_specs pre (memmov_specs pre.us dst src len)
let alloc pre ~reg ~num ~len = exec_spec pre (alloc_spec pre.us reg num len)
let free pre ~ptr = exec_spec pre (free_spec pre.us ptr)
let nondet pre = function Some reg -> kill pre reg | None -> pre
let abort _ = None
let intrinsic ~skip_throw :
Sh.t -> Var.t option -> Var.t -> Term.t list -> Sh.t option option =
fun pre areturn intrinsic actuals ->
let us = pre.us in
let name =
let n = Var.name intrinsic in
match String.index n '.' with None -> n | Some i -> String.prefix n i
in
let skip pre = Some (Some pre) in
( match (areturn, name, actuals) with
void * malloc(size_t size )
| Some reg, "malloc", [size]
|Some reg, "aligned_alloc", [size; _] ->
Some (exec_spec pre (malloc_spec us reg size))
| Some reg, "calloc", [size; number] ->
Some (exec_spec pre (calloc_spec us reg number size))
| Some reg, "posix_memalign", [size; _; ptr] ->
Some (exec_spec pre (posix_memalign_spec us reg ptr size))
| Some reg, "realloc", [size; ptr] ->
Some (exec_spec pre (realloc_spec us reg ptr size))
void * mallocx(size_t size , int flags )
| Some reg, "mallocx", [_; size] ->
Some (exec_spec pre (mallocx_spec us reg size))
| Some reg, "rallocx", [_; size; ptr] ->
Some (exec_spec pre (rallocx_spec us reg ptr size))
| Some reg, "xallocx", [_; extra; size; ptr] ->
Some (exec_spec pre (xallocx_spec us reg ptr size extra))
| Some reg, "sallocx", [_; ptr] ->
Some (exec_spec pre (sallocx_spec us reg ptr))
| None, "dallocx", [_; ptr]
|None, "sdallocx", [_; _; ptr] ->
Some (exec_spec pre (dallocx_spec us ptr))
| Some reg, "nallocx", [_; size] ->
Some (exec_spec pre (nallocx_spec us reg size))
size_t malloc_usable_size(void * ptr )
| Some reg, "malloc_usable_size", [ptr] ->
Some (exec_spec pre (malloc_usable_size_spec us reg ptr))
int mallctl(const char * name , void * oldp , size_t * oldlenp , void * newp ,
size_t newlen )
size_t newlen) *)
| Some _, "mallctl", [newlen; newp; oldlenp; oldp; _] ->
Some (exec_specs pre (mallctl_specs us oldp oldlenp newp newlen))
int mallctlnametomib(const char * name , size_t * mibp , size_t * )
| Some _, "mallctlnametomib", [miblenp; mibp; _] ->
Some (exec_spec pre (mallctlnametomib_spec us mibp miblenp))
int mallctlbymib(const size_t * mib , size_t miblen , void * oldp , size_t *
oldlenp , void * newp , size_t newlen ) ;
oldlenp, void* newp, size_t newlen); *)
| Some _, "mallctlbymib", [newlen; newp; oldlenp; oldp; miblen; mib] ->
Some
(exec_specs pre
(mallctlbymib_specs us mib miblen oldp oldlenp newp newlen))
| _, "malloc_stats_print", _ -> skip pre
| Some reg, "strlen", [ptr] ->
Some (exec_spec pre (strlen_spec us reg ptr))
| Some _, "__cxa_allocate_exception", [_] when skip_throw ->
skip (Sh.false_ pre.us)
| Some _, "_ZN5folly13usingJEMallocEv", [] -> skip pre
| _ -> None )
$> function
| None -> ()
| Some _ ->
[%Trace.info
"@[<2>exec intrinsic@ @[%a%a(@[%a@])@] from@ @[{ %a@ }@]@]"
(Option.pp "%a := " Var.pp)
areturn Var.pp intrinsic (List.pp ",@ " Term.pp)
(List.rev actuals) Sh.pp pre]
|
cd602954912d62af488430adf948c382362d8270e89a5242ff89ef7ecdd532db | mcorbin/meuse | ring.clj | (ns meuse.interceptor.ring
(:require [ring.middleware.cookies :as cookies]
[ring.middleware.params :as params]
[ring.middleware.keyword-params :as keyword-params]))
(def keyword-params
{:name ::keyword-params
:enter (fn [ctx] (update ctx :request keyword-params/keyword-params-request))})
(def params
{:name ::params
:enter (fn [ctx] (update ctx :request params/params-request))})
(def cookies
{:name ::cookies
:enter (fn [ctx] (update ctx :request #(cookies/cookies-request % {})))
:leave (fn [ctx] (update ctx :response #(cookies/cookies-response % {})))})
| null | https://raw.githubusercontent.com/mcorbin/meuse/d2b74543fce37c8cde770ae6f6097cabb509a804/src/meuse/interceptor/ring.clj | clojure | (ns meuse.interceptor.ring
(:require [ring.middleware.cookies :as cookies]
[ring.middleware.params :as params]
[ring.middleware.keyword-params :as keyword-params]))
(def keyword-params
{:name ::keyword-params
:enter (fn [ctx] (update ctx :request keyword-params/keyword-params-request))})
(def params
{:name ::params
:enter (fn [ctx] (update ctx :request params/params-request))})
(def cookies
{:name ::cookies
:enter (fn [ctx] (update ctx :request #(cookies/cookies-request % {})))
:leave (fn [ctx] (update ctx :response #(cookies/cookies-response % {})))})
|
|
88b2a86c044cc9ad4c7584cbf6ffb9c154d2f2b3b8dedbde12ac4167b4caf4b7 | robert-strandh/SICL | segment.lisp | (cl:in-package #:sicl-elf)
(defparameter *segment-type*
'((0 . :unused-entry)
(1 . :loadable-segment)
(2 . :dynamic-link-tables)
(3 . :program-interpreter-path-name)
(4 . :note-sections)
5 is reserved
(6 . :program-header-table)))
(defparameter *segment-attribute*
'((#x1 . :execute-permission)
(#x2 . :write-permission)
(#x4 . :read-permission)))
(defclass segment ()
((%data-encoding
:initarg :data-encoding
:reader data-encoding)
(%segment-type
:initarg :segment-type
:reader segment-type)
(%segment-attributes
:initarg :segment-attributes
:reader segment-attributes)
(%virtual-address
:initarg :virtual-address
:reader virtual-address)
(%alignment
:initarg :alignment
:reader alignment)
(%contents
:initarg :contents
:reader contents)))
(defvar *segment-offsets*)
(defun segment-offset (segment)
(let ((result (gethash segment *segment-offsets*)))
(assert (not (null result)))
result))
(defun store-segment-header (segment pos)
(let ((encoding (data-encoding segment)))
(store-value (encode (segment-type segment) *segment-type*)
32 pos encoding)
(let ((coded-attributes
(loop for attribute in (segment-attributes segment)
sum (encode attribute *segment-attribute*))))
(store-value coded-attributes 32 pos encoding))
(store-value (segment-offset segment) 64 pos encoding)
(store-value (virtual-address segment) 64 pos encoding)
;; Physical address is reserved.
(store-value 0 64 pos encoding)
;; Size of segment in file. Maybe this value needs to be rounded up?
(store-value (length (contents segment)) 64 pos encoding)
;; Size of segment in memory. Maybe this value needs to be rounded up?
(store-value (length (contents segment)) 64 pos encoding)
(store-value (alignment segment) 64 pos encoding)))
(defun store-segment-contents (segment bytes)
(let ((offset (segment-offset segment)))
(replace bytes (contents segment) :start1 offset)))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/7ecf9978aba7e11744b58da60dbcb49cf1b81b0a/Code/ELF/segment.lisp | lisp | Physical address is reserved.
Size of segment in file. Maybe this value needs to be rounded up?
Size of segment in memory. Maybe this value needs to be rounded up? | (cl:in-package #:sicl-elf)
(defparameter *segment-type*
'((0 . :unused-entry)
(1 . :loadable-segment)
(2 . :dynamic-link-tables)
(3 . :program-interpreter-path-name)
(4 . :note-sections)
5 is reserved
(6 . :program-header-table)))
(defparameter *segment-attribute*
'((#x1 . :execute-permission)
(#x2 . :write-permission)
(#x4 . :read-permission)))
(defclass segment ()
((%data-encoding
:initarg :data-encoding
:reader data-encoding)
(%segment-type
:initarg :segment-type
:reader segment-type)
(%segment-attributes
:initarg :segment-attributes
:reader segment-attributes)
(%virtual-address
:initarg :virtual-address
:reader virtual-address)
(%alignment
:initarg :alignment
:reader alignment)
(%contents
:initarg :contents
:reader contents)))
(defvar *segment-offsets*)
(defun segment-offset (segment)
(let ((result (gethash segment *segment-offsets*)))
(assert (not (null result)))
result))
(defun store-segment-header (segment pos)
(let ((encoding (data-encoding segment)))
(store-value (encode (segment-type segment) *segment-type*)
32 pos encoding)
(let ((coded-attributes
(loop for attribute in (segment-attributes segment)
sum (encode attribute *segment-attribute*))))
(store-value coded-attributes 32 pos encoding))
(store-value (segment-offset segment) 64 pos encoding)
(store-value (virtual-address segment) 64 pos encoding)
(store-value 0 64 pos encoding)
(store-value (length (contents segment)) 64 pos encoding)
(store-value (length (contents segment)) 64 pos encoding)
(store-value (alignment segment) 64 pos encoding)))
(defun store-segment-contents (segment bytes)
(let ((offset (segment-offset segment)))
(replace bytes (contents segment) :start1 offset)))
|
f5461b4b2ac36d6da00492ce201c0069038a9dc8785e0674538a5633e6041910 | robert-strandh/Second-Climacs | view-name.lisp | (cl:in-package #:second-climacs-base)
(defgeneric view-name (view)
(:method (view) "Unknown"))
| null | https://raw.githubusercontent.com/robert-strandh/Second-Climacs/45f683249fcdec364991a28342b223469a3fb3ad/Code/Base/view-name.lisp | lisp | (cl:in-package #:second-climacs-base)
(defgeneric view-name (view)
(:method (view) "Unknown"))
|
|
285dd20f26361e02ee5f80d9d5cb3b4f654a5009a0a6762235065392e2438e2b | yitzchak/common-lisp-jupyter | select.lisp | (in-package #:jupyter/widgets)
(defwidget base-select (description-widget %options-labels-slot disabled-slot)
((rows
:initarg :rows
:initform 5
:accessor widget-rows
:documentation "The number of rows to display."
:trait :int)))
(defwidget select (base-select index-slot)
((options
:accessor widget-options
:initarg :options
:documentation "The option values that correspond to the labels"))
(:default-initargs
:%model-name "SelectModel"
:%view-name "SelectView")
(:documentation
"Listbox that only allows one item to be selected at any given time."))
; Simulate value property below
(defun select-value (instance index)
(when index
(nth index
(if (slot-boundp instance 'options)
(widget-options instance)
(widget-%options-labels instance)))))
(defun select-values (instance indices)
(mapcar (lambda (index)
(select-value instance index))
indices))
(defmethod widget-value ((instance select))
(select-value instance (widget-index instance)))
(defmethod (setf widget-value) (new-value (instance select))
(setf (widget-index instance)
(position new-value
(if (slot-boundp instance 'options)
(widget-options instance)
(widget-%options-labels instance))
:test #'equal)))
(defmethod on-trait-change :after ((instance select) type (name (eql :index)) old-value new-value source)
(jupyter::enqueue *trait-notifications*
(list instance :any :value (select-value instance old-value) (select-value instance new-value) source)))
(defmethod initialize-instance :after ((instance select) &rest initargs &key &allow-other-keys)
(let ((value (getf initargs :value)))
(when value
(setf (widget-value instance) value))))
(defwidget select-multiple (base-select)
((index
:initarg :index
:initform nil
:accessor widget-index
:documentation "Selected indicies"
:trait :int-list)
(options
:accessor widget-options
:initarg :options
:documentation "The option values that correspond to the labels"))
(:default-initargs
:%model-name "SelectMultipleModel"
:%view-name "SelectMultipleView")
(:documentation
"Listbox that allows many items to be selected at any given time."))
(defmethod widget-value ((instance select-multiple))
(select-values instance (widget-index instance)))
(defmethod (setf widget-value) (new-value (instance select-multiple))
(setf (widget-index instance)
(mapcar (lambda (value)
(position value
(if (slot-boundp instance 'options)
(widget-options instance)
(widget-%options-labels instance))
:test #'equal))
new-value)))
(defmethod on-trait-change :after ((instance select-multiple) type (name (eql :index)) old-value new-value source)
(jupyter::enqueue *trait-notifications*
(list instance :any :value (select-values instance old-value) (select-values instance new-value) source)))
(defmethod initialize-instance :after ((instance select-multiple) &rest initargs &key &allow-other-keys)
(let ((value (getf initargs :value)))
(when value
(setf (widget-value instance) value))))
(defwidget radio-buttons (select)
()
(:default-initargs
:%model-name "RadioButtonsModel"
:%view-name "RadioButtonsView")
(:documentation
"Group of radio buttons that represent an enumeration. Only one radio button can
be toggled at any point in time."))
(defwidget dropdown (select)
()
(:default-initargs
:%model-name "DropdownModel"
:%view-name "DropdownView")
(:documentation "Allows you to select a single item from a dropdown."))
| null | https://raw.githubusercontent.com/yitzchak/common-lisp-jupyter/a1dc775e4116ab61b34530fe33f3e27291d937f4/src/widgets/select.lisp | lisp | Simulate value property below | (in-package #:jupyter/widgets)
(defwidget base-select (description-widget %options-labels-slot disabled-slot)
((rows
:initarg :rows
:initform 5
:accessor widget-rows
:documentation "The number of rows to display."
:trait :int)))
(defwidget select (base-select index-slot)
((options
:accessor widget-options
:initarg :options
:documentation "The option values that correspond to the labels"))
(:default-initargs
:%model-name "SelectModel"
:%view-name "SelectView")
(:documentation
"Listbox that only allows one item to be selected at any given time."))
(defun select-value (instance index)
(when index
(nth index
(if (slot-boundp instance 'options)
(widget-options instance)
(widget-%options-labels instance)))))
(defun select-values (instance indices)
(mapcar (lambda (index)
(select-value instance index))
indices))
(defmethod widget-value ((instance select))
(select-value instance (widget-index instance)))
(defmethod (setf widget-value) (new-value (instance select))
(setf (widget-index instance)
(position new-value
(if (slot-boundp instance 'options)
(widget-options instance)
(widget-%options-labels instance))
:test #'equal)))
(defmethod on-trait-change :after ((instance select) type (name (eql :index)) old-value new-value source)
(jupyter::enqueue *trait-notifications*
(list instance :any :value (select-value instance old-value) (select-value instance new-value) source)))
(defmethod initialize-instance :after ((instance select) &rest initargs &key &allow-other-keys)
(let ((value (getf initargs :value)))
(when value
(setf (widget-value instance) value))))
(defwidget select-multiple (base-select)
((index
:initarg :index
:initform nil
:accessor widget-index
:documentation "Selected indicies"
:trait :int-list)
(options
:accessor widget-options
:initarg :options
:documentation "The option values that correspond to the labels"))
(:default-initargs
:%model-name "SelectMultipleModel"
:%view-name "SelectMultipleView")
(:documentation
"Listbox that allows many items to be selected at any given time."))
(defmethod widget-value ((instance select-multiple))
(select-values instance (widget-index instance)))
(defmethod (setf widget-value) (new-value (instance select-multiple))
(setf (widget-index instance)
(mapcar (lambda (value)
(position value
(if (slot-boundp instance 'options)
(widget-options instance)
(widget-%options-labels instance))
:test #'equal))
new-value)))
(defmethod on-trait-change :after ((instance select-multiple) type (name (eql :index)) old-value new-value source)
(jupyter::enqueue *trait-notifications*
(list instance :any :value (select-values instance old-value) (select-values instance new-value) source)))
(defmethod initialize-instance :after ((instance select-multiple) &rest initargs &key &allow-other-keys)
(let ((value (getf initargs :value)))
(when value
(setf (widget-value instance) value))))
(defwidget radio-buttons (select)
()
(:default-initargs
:%model-name "RadioButtonsModel"
:%view-name "RadioButtonsView")
(:documentation
"Group of radio buttons that represent an enumeration. Only one radio button can
be toggled at any point in time."))
(defwidget dropdown (select)
()
(:default-initargs
:%model-name "DropdownModel"
:%view-name "DropdownView")
(:documentation "Allows you to select a single item from a dropdown."))
|
3251eed8c5965db2e7e88cb696e2b47285c4977c4fbbfa609c67dd0de4eace29 | mhuebert/chia | routers.cljs | (ns chia.routing.routers
(:require [chia.db :as db]))
(def db-id :db/routers)
(defn get-router
([]
(db/entity db-id))
([k]
;; keep :routers here?
(db/get db-id k))) | null | https://raw.githubusercontent.com/mhuebert/chia/74ee3ee9f86efbdf81d8829ab4f0a44d619c73d3/routing/src/chia/routing/routers.cljs | clojure | keep :routers here? | (ns chia.routing.routers
(:require [chia.db :as db]))
(def db-id :db/routers)
(defn get-router
([]
(db/entity db-id))
([k]
(db/get db-id k))) |
0d357ceccb6965cd2f9f0980a3dc2e84d2199856ee483f2375e04e06852baf24 | haskell-repa/repa | Int.hs |
module Data.Array.Repa.Series.Prim.Int where
import Data.Array.Repa.Series.Rate
import Data.Array.Repa.Series.Prim.Utils
import Data.Array.Repa.Series.Vector as V
import Data.Array.Repa.Series.Series as S
import Data.Array.Repa.Series.Ref as Ref
import GHC.Exts
import GHC.Types
Ref ------------------------------------------------------------------------
repa_newRefInt :: Int# -> W -> (# W, Ref Int #)
repa_newRefInt x = unwrapIO' (Ref.new (I# x))
{-# INLINE [1] repa_newRefInt #-}
repa_readRefInt :: Ref Int -> W -> (# W, Int# #)
repa_readRefInt ref
= case Ref.read ref of
IO f -> \world
-> case f world of
(# world', I# i #) -> (# world', i #)
{-# INLINE [1] repa_readRefInt #-}
repa_writeRefInt :: Ref Int -> Int# -> W -> W
repa_writeRefInt ref val = unwrapIO_ (Ref.write ref (I# val))
{-# INLINE [1] repa_writeRefInt #-}
-- Vector ---------------------------------------------------------------------
repa_newVectorInt :: Word# -> W -> (# W, Vector Int #)
repa_newVectorInt len = unwrapIO' (V.new' len)
{-# INLINE [1] repa_newVectorInt #-}
repa_readVectorInt :: Vector Int -> Word# -> W -> (# W, Int# #)
repa_readVectorInt vec ix
= case V.read vec ix of
IO f -> \world
-> case f world of
(# world', I# i #) -> (# world', i #)
{-# INLINE [1] repa_readVectorInt #-}
repa_writeVectorInt :: Vector Int -> Word# -> Int# -> W -> W
repa_writeVectorInt vec ix val
= unwrapIO_ (V.write vec ix (I# val))
{-# INLINE [1] repa_writeVectorInt #-}
repa_truncVectorInt :: Word# -> Vector Int -> W -> W
repa_truncVectorInt len vec
= unwrapIO_ (V.trunc len vec)
{-# INLINE [1] repa_truncVectorInt #-}
Series ---------------------------------------------------------------------
repa_nextInt :: Series k Int -> Word# -> W -> (# W, Int# #)
repa_nextInt s ix world
= case S.index s ix of
I# i -> (# world, i #)
{-# INLINE [1] repa_nextInt #-}
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/icebox/abandoned/repa-series/Data/Array/Repa/Series/Prim/Int.hs | haskell | ----------------------------------------------------------------------
# INLINE [1] repa_newRefInt #
# INLINE [1] repa_readRefInt #
# INLINE [1] repa_writeRefInt #
Vector ---------------------------------------------------------------------
# INLINE [1] repa_newVectorInt #
# INLINE [1] repa_readVectorInt #
# INLINE [1] repa_writeVectorInt #
# INLINE [1] repa_truncVectorInt #
-------------------------------------------------------------------
# INLINE [1] repa_nextInt # |
module Data.Array.Repa.Series.Prim.Int where
import Data.Array.Repa.Series.Rate
import Data.Array.Repa.Series.Prim.Utils
import Data.Array.Repa.Series.Vector as V
import Data.Array.Repa.Series.Series as S
import Data.Array.Repa.Series.Ref as Ref
import GHC.Exts
import GHC.Types
repa_newRefInt :: Int# -> W -> (# W, Ref Int #)
repa_newRefInt x = unwrapIO' (Ref.new (I# x))
repa_readRefInt :: Ref Int -> W -> (# W, Int# #)
repa_readRefInt ref
= case Ref.read ref of
IO f -> \world
-> case f world of
(# world', I# i #) -> (# world', i #)
repa_writeRefInt :: Ref Int -> Int# -> W -> W
repa_writeRefInt ref val = unwrapIO_ (Ref.write ref (I# val))
repa_newVectorInt :: Word# -> W -> (# W, Vector Int #)
repa_newVectorInt len = unwrapIO' (V.new' len)
repa_readVectorInt :: Vector Int -> Word# -> W -> (# W, Int# #)
repa_readVectorInt vec ix
= case V.read vec ix of
IO f -> \world
-> case f world of
(# world', I# i #) -> (# world', i #)
repa_writeVectorInt :: Vector Int -> Word# -> Int# -> W -> W
repa_writeVectorInt vec ix val
= unwrapIO_ (V.write vec ix (I# val))
repa_truncVectorInt :: Word# -> Vector Int -> W -> W
repa_truncVectorInt len vec
= unwrapIO_ (V.trunc len vec)
repa_nextInt :: Series k Int -> Word# -> W -> (# W, Int# #)
repa_nextInt s ix world
= case S.index s ix of
I# i -> (# world, i #)
|
1c21e68db3922c97f39e0a8afd0742719626eea7083c63a532eb265c1286fb95 | ocaml/opam | opamProcess.mli | (**************************************************************************)
(* *)
Copyright 2012 - 2018 OCamlPro
Copyright 2012 INRIA
(* *)
(* 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. *)
(* *)
(**************************************************************************)
(** Process and job handling, with logs, termination status, etc. *)
(** The type of shell commands *)
type command
* Builds a shell command for later execution .
@param env environment for the command
@param verbose force verbosity
@param name title , used to name log files , etc .
@param metadata additional info to log
@param dir CWD for the command
@param allow_stdin whether to forward stdin
@param stdout redirect stdout to the given file instead of the logs
@param text Short text that may be displayed in the status - line
@param command The command itself
@param args Command - line arguments
@param env environment for the command
@param verbose force verbosity
@param name title, used to name log files, etc.
@param metadata additional info to log
@param dir CWD for the command
@param allow_stdin whether to forward stdin
@param stdout redirect stdout to the given file instead of the logs
@param text Short text that may be displayed in the status-line
@param command The command itself
@param args Command-line arguments *)
val command:
?env:string array ->
?verbose:bool ->
?name:string ->
?metadata:(string*string) list ->
?dir:string ->
?allow_stdin:bool ->
?stdout:string ->
?text:string ->
string ->
string list ->
command
val string_of_command: command -> string
val text_of_command: command -> string option
val is_verbose_command: command -> bool
* Returns a label suitable for printing the summary of running commands . First
string is the topic ( e.g. package ) , second the action ( e.g. command name ) .
Optional command arguments may be used for details ( e.g. make action ) .
string is the topic (e.g. package), second the action (e.g. command name).
Optional command arguments may be used for details (e.g. make action). *)
val make_command_text:
?color:OpamConsole.text_style -> string -> ?args:string list -> string ->
string
(** The type for processes *)
type t = {
p_name : string; (** Command name *)
p_args : string list; (** Command args *)
p_pid : int; (** Process PID *)
p_cwd : string; (** Process initial working directory *)
p_time : float; (** Process start time *)
p_stdout : string option; (** stdout dump file *)
p_stderr : string option; (** stderr dump file *)
p_env : string option; (** dump environment variables *)
p_info : string option; (** dump process info *)
p_metadata: (string * string) list; (** Metadata associated to the process *)
p_verbose: bool; (** whether output of the process should be
displayed *)
p_tmp_files: string list; (** temporary files that should be cleaned up upon
completion *)
}
(** Process results *)
type result = {
* Process exit code , or 256 on error
r_signal : int option; (** Signal received if the processed was killed *)
r_duration : float; (** Process duration *)
r_info : (string * string) list; (** Process info *)
r_stdout : string list; (** Content of stdout dump file *)
r_stderr : string list; (** Content of stderr dump file *)
r_cleanup : string list; (** List of files to clean-up *)
}
(** [run command] synchronously call the command [command.cmd] with
arguments [command.args]. It waits until the process is finished. The files
[name.info], [name.env], [name.out] and [name.err], with
[name = command.cmd_name] are
created, and contain the process main description, the environment
variables, the standard output and the standard error.
Don't forget to call [cleanup result] afterwards *)
val run : command -> result
(** Same as [run], but doesn't wait. Use wait_one to wait and collect
results;
Don't forget to call [cleanup result] afterwards *)
val run_background: command -> t
(** Similar to [run_background], except that no process is created, and a dummy
process (suitable for dry_wait_one) is returned. *)
val dry_run_background: command -> t
* [ wait p ] waits for the processus [ p ] to end and returns its results . Be
careful to handle . Break
careful to handle Sys.Break *)
val wait: t -> result
(** Like [wait], but returns None immediately if the process hasn't ended *)
val dontwait: t -> result option
* Wait for the first of the listed processes to terminate , and return its
termination status
termination status *)
val wait_one: t list -> t * result
(** Similar to [wait_one] for simulations, to be used with
[dry_run_background] *)
val dry_wait_one: t list -> t * result
* Send SIGINT to a process ( or SIGKILL on Windows )
val interrupt: t -> unit
(** Is the process result a success? *)
val is_success : result -> bool
(** Is the process result a failure? *)
val is_failure : result -> bool
(** Should be called after process termination, to cleanup temporary files.
Leaves artefacts in case OpamGlobals.debug is on and on failure, unless
force has been set. *)
val cleanup : ?force:bool -> result -> unit
(** Like [is_success], with an added cleanup side-effect (as [cleanup
~force:true]). Use this when not returning 0 is not an error case: since the
default behaviour is to cleanup only when the command returned 0, which is
not what is expected in that case. *)
val check_success_and_cleanup : result -> bool
* { 2 Misc }
(** Reads a text file and returns a list of lines *)
val read_lines: string -> string list
(** Detailed report on process outcome *)
val string_of_result: ?color:OpamConsole.text_style -> result -> string
(** Short report on process outcome *)
val result_summary: result -> string
(** Higher-level interface to allow parallelism *)
module Job: sig
(** Open type and add combinators. Meant to be opened *)
module Op: sig
type 'a job =
| Done of 'a
| Run of command * (result -> 'a job)
* Stage a shell command with its continuation , eg :
{ [
command " ls " [ " -a " ] @@ > fun result - >
if OpamProcess.is_success result then Done result.r_stdout
else failwith " ls "
] }
{[
command "ls" ["-a"] @@> fun result ->
if OpamProcess.is_success result then Done result.r_stdout
else failwith "ls"
]}
*)
val (@@>): command -> (result -> 'a job) -> 'a job
(** [job1 @@+ fun r -> job2] appends the computation of tasks in [job2] after
[job1] *)
val (@@+): 'a job -> ('a -> 'b job) -> 'b job
* [ job @@| f ] maps [ f ] on the results of [ job ] .
Equivalent to [ job @@+ fun r - > Done ( f r ) ]
Equivalent to [job @@+ fun r -> Done (f r)] *)
val (@@|): 'a job -> ('a -> 'b) -> 'b job
end
(** Sequential run of a job *)
val run: 'a Op.job -> 'a
(** Same as [run] but doesn't actually run any shell command,
and feed a dummy result to the cont. *)
val dry_run: 'a Op.job -> 'a
(** Catch exceptions raised within a job *)
val catch: (exn -> 'a Op.job) -> (unit -> 'a Op.job) -> 'a Op.job
(** Ignore all non-fatal exceptions raised by job and return default *)
val ignore_errors: default:'a -> ?message:string ->
(unit -> 'a Op.job) -> 'a Op.job
(** Register an exception-safe finaliser in a job.
[finally job fin] is equivalent to
[catch job (fun e -> fin (); raise e) @@+ fun r -> fin (); Done r] *)
val finally: (unit -> unit) -> (unit -> 'a Op.job) -> 'a Op.job
* Converts a list of commands into a job that returns None on success , or
the first failed command and its result .
Unless [ keep_going ] is true , stops on first error .
the first failed command and its result.
Unless [keep_going] is true, stops on first error. *)
val of_list: ?keep_going:bool -> command list ->
(command * result) option Op.job
(** As [of_list], but takes a list of functions that return the commands. The
functions will only be evaluated when the command needs to be run. *)
val of_fun_list: ?keep_going:bool -> (unit -> command) list ->
(command * result) option Op.job
(** Returns the job made of the given homogeneous jobs run sequentially *)
val seq: ('a -> 'a Op.job) list -> 'a -> 'a Op.job
(** Sequentially maps jobs on a list *)
val seq_map: ('a -> 'b Op.job) -> 'a list -> 'b list Op.job
(** Sets and overrides text of the underlying commands *)
val with_text: string -> 'a Op.job -> 'a Op.job
end
type 'a job = 'a Job.Op.job
(**/**)
val set_resolve_command :
(?env:string array -> ?dir:string -> string -> string option) -> unit
* Like Unix.create_process_env , but with correct escaping of arguments when
invoking a cygwin executable from a native Windows executable .
invoking a cygwin executable from a native Windows executable. *)
val create_process_env :
string -> string array -> string array ->
Unix.file_descr -> Unix.file_descr -> Unix.file_descr ->
int
| null | https://raw.githubusercontent.com/ocaml/opam/800dc5be9a51a14c3a1f35bfc08d914930ab866f/src/core/opamProcess.mli | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************
* Process and job handling, with logs, termination status, etc.
* The type of shell commands
* The type for processes
* Command name
* Command args
* Process PID
* Process initial working directory
* Process start time
* stdout dump file
* stderr dump file
* dump environment variables
* dump process info
* Metadata associated to the process
* whether output of the process should be
displayed
* temporary files that should be cleaned up upon
completion
* Process results
* Signal received if the processed was killed
* Process duration
* Process info
* Content of stdout dump file
* Content of stderr dump file
* List of files to clean-up
* [run command] synchronously call the command [command.cmd] with
arguments [command.args]. It waits until the process is finished. The files
[name.info], [name.env], [name.out] and [name.err], with
[name = command.cmd_name] are
created, and contain the process main description, the environment
variables, the standard output and the standard error.
Don't forget to call [cleanup result] afterwards
* Same as [run], but doesn't wait. Use wait_one to wait and collect
results;
Don't forget to call [cleanup result] afterwards
* Similar to [run_background], except that no process is created, and a dummy
process (suitable for dry_wait_one) is returned.
* Like [wait], but returns None immediately if the process hasn't ended
* Similar to [wait_one] for simulations, to be used with
[dry_run_background]
* Is the process result a success?
* Is the process result a failure?
* Should be called after process termination, to cleanup temporary files.
Leaves artefacts in case OpamGlobals.debug is on and on failure, unless
force has been set.
* Like [is_success], with an added cleanup side-effect (as [cleanup
~force:true]). Use this when not returning 0 is not an error case: since the
default behaviour is to cleanup only when the command returned 0, which is
not what is expected in that case.
* Reads a text file and returns a list of lines
* Detailed report on process outcome
* Short report on process outcome
* Higher-level interface to allow parallelism
* Open type and add combinators. Meant to be opened
* [job1 @@+ fun r -> job2] appends the computation of tasks in [job2] after
[job1]
* Sequential run of a job
* Same as [run] but doesn't actually run any shell command,
and feed a dummy result to the cont.
* Catch exceptions raised within a job
* Ignore all non-fatal exceptions raised by job and return default
* Register an exception-safe finaliser in a job.
[finally job fin] is equivalent to
[catch job (fun e -> fin (); raise e) @@+ fun r -> fin (); Done r]
* As [of_list], but takes a list of functions that return the commands. The
functions will only be evaluated when the command needs to be run.
* Returns the job made of the given homogeneous jobs run sequentially
* Sequentially maps jobs on a list
* Sets and overrides text of the underlying commands
*/* | Copyright 2012 - 2018 OCamlPro
Copyright 2012 INRIA
GNU Lesser General Public License version 2.1 , with the special
type command
* Builds a shell command for later execution .
@param env environment for the command
@param verbose force verbosity
@param name title , used to name log files , etc .
@param metadata additional info to log
@param dir CWD for the command
@param allow_stdin whether to forward stdin
@param stdout redirect stdout to the given file instead of the logs
@param text Short text that may be displayed in the status - line
@param command The command itself
@param args Command - line arguments
@param env environment for the command
@param verbose force verbosity
@param name title, used to name log files, etc.
@param metadata additional info to log
@param dir CWD for the command
@param allow_stdin whether to forward stdin
@param stdout redirect stdout to the given file instead of the logs
@param text Short text that may be displayed in the status-line
@param command The command itself
@param args Command-line arguments *)
val command:
?env:string array ->
?verbose:bool ->
?name:string ->
?metadata:(string*string) list ->
?dir:string ->
?allow_stdin:bool ->
?stdout:string ->
?text:string ->
string ->
string list ->
command
val string_of_command: command -> string
val text_of_command: command -> string option
val is_verbose_command: command -> bool
* Returns a label suitable for printing the summary of running commands . First
string is the topic ( e.g. package ) , second the action ( e.g. command name ) .
Optional command arguments may be used for details ( e.g. make action ) .
string is the topic (e.g. package), second the action (e.g. command name).
Optional command arguments may be used for details (e.g. make action). *)
val make_command_text:
?color:OpamConsole.text_style -> string -> ?args:string list -> string ->
string
type t = {
}
type result = {
* Process exit code , or 256 on error
}
val run : command -> result
val run_background: command -> t
val dry_run_background: command -> t
* [ wait p ] waits for the processus [ p ] to end and returns its results . Be
careful to handle . Break
careful to handle Sys.Break *)
val wait: t -> result
val dontwait: t -> result option
* Wait for the first of the listed processes to terminate , and return its
termination status
termination status *)
val wait_one: t list -> t * result
val dry_wait_one: t list -> t * result
* Send SIGINT to a process ( or SIGKILL on Windows )
val interrupt: t -> unit
val is_success : result -> bool
val is_failure : result -> bool
val cleanup : ?force:bool -> result -> unit
val check_success_and_cleanup : result -> bool
* { 2 Misc }
val read_lines: string -> string list
val string_of_result: ?color:OpamConsole.text_style -> result -> string
val result_summary: result -> string
module Job: sig
module Op: sig
type 'a job =
| Done of 'a
| Run of command * (result -> 'a job)
* Stage a shell command with its continuation , eg :
{ [
command " ls " [ " -a " ] @@ > fun result - >
if OpamProcess.is_success result then Done result.r_stdout
else failwith " ls "
] }
{[
command "ls" ["-a"] @@> fun result ->
if OpamProcess.is_success result then Done result.r_stdout
else failwith "ls"
]}
*)
val (@@>): command -> (result -> 'a job) -> 'a job
val (@@+): 'a job -> ('a -> 'b job) -> 'b job
* [ job @@| f ] maps [ f ] on the results of [ job ] .
Equivalent to [ job @@+ fun r - > Done ( f r ) ]
Equivalent to [job @@+ fun r -> Done (f r)] *)
val (@@|): 'a job -> ('a -> 'b) -> 'b job
end
val run: 'a Op.job -> 'a
val dry_run: 'a Op.job -> 'a
val catch: (exn -> 'a Op.job) -> (unit -> 'a Op.job) -> 'a Op.job
val ignore_errors: default:'a -> ?message:string ->
(unit -> 'a Op.job) -> 'a Op.job
val finally: (unit -> unit) -> (unit -> 'a Op.job) -> 'a Op.job
* Converts a list of commands into a job that returns None on success , or
the first failed command and its result .
Unless [ keep_going ] is true , stops on first error .
the first failed command and its result.
Unless [keep_going] is true, stops on first error. *)
val of_list: ?keep_going:bool -> command list ->
(command * result) option Op.job
val of_fun_list: ?keep_going:bool -> (unit -> command) list ->
(command * result) option Op.job
val seq: ('a -> 'a Op.job) list -> 'a -> 'a Op.job
val seq_map: ('a -> 'b Op.job) -> 'a list -> 'b list Op.job
val with_text: string -> 'a Op.job -> 'a Op.job
end
type 'a job = 'a Job.Op.job
val set_resolve_command :
(?env:string array -> ?dir:string -> string -> string option) -> unit
* Like Unix.create_process_env , but with correct escaping of arguments when
invoking a cygwin executable from a native Windows executable .
invoking a cygwin executable from a native Windows executable. *)
val create_process_env :
string -> string array -> string array ->
Unix.file_descr -> Unix.file_descr -> Unix.file_descr ->
int
|
7eaa1d08b418bc5c002a42833b152b42e3dd075bd0793b187f088153f3ce4f80 | ragkousism/Guix-on-Hurd | lout.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2012 , 2013 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages lout)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages ghostscript))
(define-public lout
This one is a bit tricky , because it does n't follow the GNU Build System
;; rules. Instead, it has a makefile that has to be patched to set the
;; prefix, etc., and it has no makefile rules to build its doc.
(let ((configure-phase
'(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(doc (assoc-ref outputs "doc")))
(substitute* "makefile"
(("^PREFIX[[:blank:]]*=.*$")
(string-append "PREFIX = " out "\n"))
(("^LOUTLIBDIR[[:blank:]]*=.*$")
(string-append "LOUTLIBDIR = " out "/lib/lout\n"))
(("^LOUTDOCDIR[[:blank:]]*=.*$")
(string-append "LOUTDOCDIR = " doc "/share/doc/lout\n"))
(("^MANDIR[[:blank:]]*=.*$")
(string-append "MANDIR = " out "/man\n")))
(mkdir out)
(mkdir (string-append out "/bin"))
(mkdir (string-append out "/lib"))
(mkdir (string-append out "/man"))
(mkdir-p (string-append doc "/share/doc/lout")))))
(install-man-phase
'(lambda* (#:key outputs #:allow-other-keys)
(zero? (system* "make" "installman"))))
(doc-phase
'(lambda* (#:key outputs #:allow-other-keys)
(define out
(assoc-ref outputs "doc"))
(setenv "PATH"
(string-append (assoc-ref outputs "out")
"/bin:" (getenv "PATH")))
(chdir "doc")
(every (lambda (doc)
(format #t "doc: building `~a'...~%" doc)
(with-directory-excursion doc
(let ((file (string-append out "/share/doc/lout/"
doc ".ps")))
(and (or (file-exists? "outfile.ps")
(zero? (system* "lout" "-r4" "-o"
"outfile.ps" "all")))
(begin
(copy-file "outfile.ps" file)
#t)
(zero? (system* "ps2pdf"
"-dPDFSETTINGS=/prepress"
"-sPAPERSIZE=a4"
file
(string-append out "/share/doc/lout/"
doc ".pdf")))))))
'("design" "expert" "slides" "user")))))
(package
(name "lout")
(version "3.40")
(source (origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"1gb8vb1wl7ikn269dd1c7ihqhkyrwk19jwx5kd0rdvbk6g7g25ix"))))
(build-system gnu-build-system) ; actually, just a makefile
(outputs '("out" "doc"))
(native-inputs
`(("ghostscript" ,ghostscript)))
(arguments `(#:modules ((guix build utils)
(guix build gnu-build-system)
(srfi srfi-1)) ; we need SRFI-1
#:tests? #f ; no "check" target
;; Customize the build phases.
#:phases (alist-replace
'configure ,configure-phase
(alist-cons-after
'install 'install-man-pages
,install-man-phase
(alist-cons-after
'install 'install-doc
,doc-phase
%standard-phases)))))
(synopsis "Document layout system")
(description
"The Lout document formatting system reads a high-level description of
a document similar in style to LaTeX and produces a PostScript or plain text
output file.
Lout offers an unprecedented range of advanced features, including optimal
paragraph and page breaking, automatic hyphenation, PostScript EPS file
inclusion and generation, equation formatting, tables, diagrams, rotation and
scaling, sorted indexes, bibliographic databases, running headers and
odd-even pages, automatic cross referencing, multilingual documents including
hyphenation (most European languages are supported), formatting of computer
programs, and much more, all ready to use. Furthermore, Lout is easily
extended with definitions which are very much easier to write than troff of
TeX macros because Lout is a high-level, purely functional language, the
outcome of an eight-year research project that went back to the
beginning.")
(license gpl3+)
(home-page "/"))))
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/lout.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
rules. Instead, it has a makefile that has to be patched to set the
prefix, etc., and it has no makefile rules to build its doc.
actually, just a makefile
we need SRFI-1
no "check" target
Customize the build phases. | Copyright © 2012 , 2013 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages lout)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages ghostscript))
(define-public lout
This one is a bit tricky , because it does n't follow the GNU Build System
(let ((configure-phase
'(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(doc (assoc-ref outputs "doc")))
(substitute* "makefile"
(("^PREFIX[[:blank:]]*=.*$")
(string-append "PREFIX = " out "\n"))
(("^LOUTLIBDIR[[:blank:]]*=.*$")
(string-append "LOUTLIBDIR = " out "/lib/lout\n"))
(("^LOUTDOCDIR[[:blank:]]*=.*$")
(string-append "LOUTDOCDIR = " doc "/share/doc/lout\n"))
(("^MANDIR[[:blank:]]*=.*$")
(string-append "MANDIR = " out "/man\n")))
(mkdir out)
(mkdir (string-append out "/bin"))
(mkdir (string-append out "/lib"))
(mkdir (string-append out "/man"))
(mkdir-p (string-append doc "/share/doc/lout")))))
(install-man-phase
'(lambda* (#:key outputs #:allow-other-keys)
(zero? (system* "make" "installman"))))
(doc-phase
'(lambda* (#:key outputs #:allow-other-keys)
(define out
(assoc-ref outputs "doc"))
(setenv "PATH"
(string-append (assoc-ref outputs "out")
"/bin:" (getenv "PATH")))
(chdir "doc")
(every (lambda (doc)
(format #t "doc: building `~a'...~%" doc)
(with-directory-excursion doc
(let ((file (string-append out "/share/doc/lout/"
doc ".ps")))
(and (or (file-exists? "outfile.ps")
(zero? (system* "lout" "-r4" "-o"
"outfile.ps" "all")))
(begin
(copy-file "outfile.ps" file)
#t)
(zero? (system* "ps2pdf"
"-dPDFSETTINGS=/prepress"
"-sPAPERSIZE=a4"
file
(string-append out "/share/doc/lout/"
doc ".pdf")))))))
'("design" "expert" "slides" "user")))))
(package
(name "lout")
(version "3.40")
(source (origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"1gb8vb1wl7ikn269dd1c7ihqhkyrwk19jwx5kd0rdvbk6g7g25ix"))))
(outputs '("out" "doc"))
(native-inputs
`(("ghostscript" ,ghostscript)))
(arguments `(#:modules ((guix build utils)
(guix build gnu-build-system)
#:phases (alist-replace
'configure ,configure-phase
(alist-cons-after
'install 'install-man-pages
,install-man-phase
(alist-cons-after
'install 'install-doc
,doc-phase
%standard-phases)))))
(synopsis "Document layout system")
(description
"The Lout document formatting system reads a high-level description of
a document similar in style to LaTeX and produces a PostScript or plain text
output file.
Lout offers an unprecedented range of advanced features, including optimal
paragraph and page breaking, automatic hyphenation, PostScript EPS file
inclusion and generation, equation formatting, tables, diagrams, rotation and
scaling, sorted indexes, bibliographic databases, running headers and
odd-even pages, automatic cross referencing, multilingual documents including
hyphenation (most European languages are supported), formatting of computer
programs, and much more, all ready to use. Furthermore, Lout is easily
extended with definitions which are very much easier to write than troff of
TeX macros because Lout is a high-level, purely functional language, the
outcome of an eight-year research project that went back to the
beginning.")
(license gpl3+)
(home-page "/"))))
|
a3f2475bbb7ea201401073c85281af6f1c280e50826576f1035caaf8ff0249d1 | Helium4Haskell/helium | MonadInstance1.hs |
main = do
x <- return 3
y <- Just "Hello"
let z = True
return (x, y, z) | null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeClasses/MonadInstance1.hs | haskell |
main = do
x <- return 3
y <- Just "Hello"
let z = True
return (x, y, z) |
|
df488fbf75f4fb7902ba7a416b5f86fcdcbd2e0d84ddb9023a5b8838037cf6a3 | avsm/platform | max_indent.ml | let () =
fooooo
|> List.iter (fun x ->
let x = x $ y in
fooooooooooo x)
let () =
fooooo
|> List.iter
(fun some_really_really_really_long_name_that_doesn't_fit_on_the_line ->
let x =
some_really_really_really_long_name_that_doesn't_fit_on_the_line $ y
in
fooooooooooo x)
| null | https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/ocamlformat.0.12/test/passing/max_indent.ml | ocaml | let () =
fooooo
|> List.iter (fun x ->
let x = x $ y in
fooooooooooo x)
let () =
fooooo
|> List.iter
(fun some_really_really_really_long_name_that_doesn't_fit_on_the_line ->
let x =
some_really_really_really_long_name_that_doesn't_fit_on_the_line $ y
in
fooooooooooo x)
|
|
89cce621e00db67e10a18fc18e44dd1632a22aa80a67187d2a6aa3f8ddb718b1 | Chris00/ocaml-rope | rope.ml | File : rope.ml
Copyright ( C ) 2007
email :
WWW : /
This library is free software ; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 2.1 or
later as published by the Free Software Foundation , with the special
exception on linking described in the 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 file
LICENSE for more details .
Copyright (C) 2007
Christophe Troestler
email:
WWW: /
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 2.1 or
later as published by the Free Software Foundation, with the special
exception on linking described in the 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 file
LICENSE for more details. *)
* Rope implementation inspired from :
, , , " Ropes : an alternative
to strings " , Software Practice and Experience 25 , vol . 12 ( 1995 ) ,
pp . 1315 - 1330 .
-95/spe/vol25/issue12/spe986.pdf
Hans Boehm, Russ Atkinson, Michael Plass, "Ropes: an alternative
to strings", Software Practice and Experience 25, vol. 12 (1995),
pp. 1315-1330.
-95/spe/vol25/issue12/spe986.pdf *)
TODO :
- Regexp ( maybe using regexp lib ?
/~vouillon/ )
- Camomille interop . ( with phantom types for encoding ? ? )
See also the OSR
- Regexp (maybe using Jérôme Vouillon regexp lib ?
/~vouillon/)
- Camomille interop. (with phantom types for encoding ??)
See also the OSR
*)
let min i j = if (i:int) < j then i else j
let max i j = if (i:int) > j then i else j
exception Out_of_bounds of string
(* One assumes throughout that the length is a representable
integer. Public functions that allow to construct larger ropes
must check this. *)
type t =
| Sub of string * int * int
( s , i0 , len ) where only s.[i0 .. i0+len-1 ] is used by the
rope . ] is forbidden , unless the rope has 0 length
( i.e. it is empty ) . Experiments show that this is faster
than [ Sub of string ] and does not really use more memory --
because splices share all nodes .
rope. [len = 0] is forbidden, unless the rope has 0 length
(i.e. it is empty). Experiments show that this is faster
than [Sub of string] and does not really use more memory --
because splices share all nodes. *)
| Concat of int * int * t * int * t
[ ( height , length , left , left_length , right ) ] . This asymmetry
between left and right was chosen because the full length and
the left length are more often needed that the right
length .
between left and right was chosen because the full length and
the left length are more often needed that the right
length. *)
type rope = t
let small_rope_length = 32
(** Use this as leaf when creating fresh leaves. Also sub-ropes of
length [<= small_rope_length] may be flattened by [concat2].
This value must be quite small, typically comparable to the size
of a [Concat] node. *)
let make_length_pow2 = 10
let make_length = 1 lsl make_length_pow2
let max_flatten_length = 1024
(** When deciding whether to flatten a rope, only those with length [<=
max_flatten_length] will be. *)
let extract_sub_length = small_rope_length / 2
(** When balancing, copy the substrings with this length or less (=>
release the original string). *)
let level_flatten = 12
(** When balancing, flatten the rope at level [level_flatten]. The
sum of [min_length.(n)], [0 <= n <= level_flatten] must be of te
same order as [max_flatten_length]. *)
Fibonacci numbers $ F_{n+2}$. By definition , a NON - EMPTY rope [ r ]
is balanced iff [ length r > = ) ] .
[ ] is the first height at which the fib . number overflow
the integer range .
is balanced iff [length r >= min_length.(height r)].
[max_height] is the first height at which the fib. number overflow
the integer range. *)
let min_length, max_height =
(* Since F_{n+2} >= ((1 + sqrt 5)/2)^n, we know F_{d+2} will overflow: *)
let d = (3 * Sys.word_size) / 2 in
let m = Array.make d max_int in
(* See [add_nonempty_to_forest] for the reason for [max_int] *)
let prev = ref 0
and last = ref 1
and i = ref 0 in
try
while !i < d - 1 do
let curr = !last + !prev in
if curr < !last (* overflow *) then raise Exit;
m.(!i) <- curr;
prev := !last;
last := curr;
incr i
done;
assert false
with Exit -> m, !i
let rebalancing_height = min (max_height - 1) 60
* Beyond this height , implicit balance will be done . This value
allows gross inefficiencies while not being too time consuming .
For example , explicit rebalancing did not really improve the
running time on the ICFP 2007 task .
allows gross inefficiencies while not being too time consuming.
For example, explicit rebalancing did not really improve the
running time on the ICFP 2007 task. *)
32 bits : = 42
let empty = Sub("", 0, 0)
let length = function
| Sub(_, _, len) -> len
| Concat(_,len,_,_,_) -> len
let height = function
| Sub(_,_,_) -> 0
| Concat(h,_,_,_,_) -> h
let is_empty = function
| Sub(_, _, len) -> len = 0
| _ -> false
let is_not_empty = function
| Sub(_, _, len) -> len <> 0
| _ -> true
(* For debugging purposes and judging the balancing *)
let print =
let rec map_left = function
| [] -> []
| [x] -> ["/" ^ x]
| x :: tl -> (" " ^ x) :: map_left tl in
let map_right = function
| [] -> []
| x :: tl -> ("\\" ^ x) :: List.map (fun r -> " " ^ r) tl in
let rec leaves_list = function
| Sub(s, i0, len) -> [String.sub s i0 len]
| Concat(_,_, l,_, r) ->
map_left(leaves_list l) @ map_right(leaves_list r) in
fun r -> List.iter print_endline (leaves_list r)
;;
let of_string s = Sub(s, 0, String.length s)
(* safe: string is now immutable *)
(* Since we will need to copy the string anyway, let us take this
opportunity to split it in small chunks for easier further
sharing. In order to minimize the height, we use a simple
bisection scheme. *)
let rec unsafe_of_substring s i len =
if len <= small_rope_length then Sub(String.sub s i len, 0, len)
else
let len' = len / 2 in
let i' = i + len' in
let left = unsafe_of_substring s i len'
and right = unsafe_of_substring s i' (len - len') in
let h = 1 + max (height left) (height right) in
let ll = length left in
Concat(h, ll + length right, left, ll, right)
let of_substring s i len =
let len_s = String.length s in
if i < 0 || len < 0 || i > len_s - len then invalid_arg "Rope.of_substring";
(* If only a small percentage of the string is not in the rope, do
not cut the string in small pieces. The case of small lengths is
managed by [unsafe_of_substring]. *)
if len >= len_s - (len / 10) then Sub(s, i, len)
else unsafe_of_substring s i len
let of_char c = Sub(String.make 1 c, 0, 1)
Construct a rope from [ n-1 ] copies of a call to [ gen ofs len ] of
length [ len = make_length ] and a last call with the remainder
length . So the tree has [ n ] leaves [ Sub ] . The strings returned by
[ ] may be longer than [ len ] of only the first [ len ]
chars will be used .
length [len = make_length] and a last call with the remainder
length. So the tree has [n] leaves [Sub]. The strings returned by
[gen ofs len] may be longer than [len] of only the first [len]
chars will be used. *)
let rec make_of_gen gen ofs len ~n =
if n <= 1 then
if len > 0 then Sub(gen ofs len, 0, len) else empty
else
let nl = n / 2 in
let ll = nl * max_flatten_length in
let l = make_of_gen gen ofs ll ~n:nl in
let r = make_of_gen gen (ofs + ll) (len - ll) ~n:(n - nl) in
Concat(1 + max (height l) (height r), len, l, ll, r)
let make_length_mask = make_length - 1
let make_n_chunks len =
if len land make_length_mask = 0 then len lsr make_length_pow2
else len lsr make_length_pow2 + 1
let make len c =
if len < 0 then failwith "Rope.make: len must be >= 0";
if len <= make_length then Sub(String.make len c, 0, len)
else
let base = String.make make_length c in
make_of_gen (fun _ _ -> base) 0 len ~n:(make_n_chunks len)
let init len f =
if len < 0 then failwith "Rope.init: len must be >= 0";
if len <= make_length then Sub(String.init len f, 0, len)
else
Do not use String.init to avoid creating a closure .
let gen ofs len =
let b = Bytes.create len in
for i = 0 to len - 1 do Bytes.set b i (f (ofs + i)) done;
Bytes.unsafe_to_string b in
make_of_gen gen 0 len ~n:(make_n_chunks len)
[ copy_to_subbytes t ofs r ] copy the rope [ r ] to the byte range
[ t.[ofs .. ofs+(length r)-1 ] ] . It is assumed that [ t ] is long enough .
( This function could be a one liner with [ iteri ] but we want to use
[ Bytes.blit_string ] for efficiency . )
[t.[ofs .. ofs+(length r)-1]]. It is assumed that [t] is long enough.
(This function could be a one liner with [iteri] but we want to use
[Bytes.blit_string] for efficiency.) *)
let rec copy_to_subbytes t ofs = function
| Sub(s, i0, len) ->
Bytes.blit_string s i0 t ofs len
| Concat(_, _, l,ll, r) ->
copy_to_subbytes t ofs l;
copy_to_subbytes t (ofs + ll) r
let to_string = function
| Sub(s, i0, len) ->
(* Optimize when the rope hold a single string. *)
if i0 = 0 && len = String.length s then s
else String.sub s i0 len
| r ->
let len = length r in
if len > Sys.max_string_length then
failwith "Rope.to_string: rope length > Sys.max_string_length";
let t = Bytes.create len in
copy_to_subbytes t 0 r;
Bytes.unsafe_to_string t
(* Similar to [copy_to_subbytes] do more work to allow specifying a
range of [src]. *)
let rec unsafe_blit src srcofs dst dstofs len =
match src with
| Sub(s, i0, _) ->
String.blit s (i0 + srcofs) dst dstofs len
| Concat(_, _, l, ll, r) ->
let rofs = srcofs - ll in
if rofs >= 0 then
unsafe_blit r rofs dst dstofs len
else
let llen = - rofs in (* # of chars after [srcofs] in the left rope *)
if len <= llen then
unsafe_blit l srcofs dst dstofs len
else (* len > llen *) (
unsafe_blit l srcofs dst dstofs llen;
unsafe_blit r 0 dst (dstofs + llen) (len - llen);
)
let blit src srcofs dst dstofs len =
if len < 0 then failwith "Rope.blit: len >= 0 required";
if srcofs < 0 || srcofs > length src - len then
failwith "Rope.blit: not a valid range of src";
if dstofs < 0 || dstofs > Bytes.length dst - len then
failwith "Rope.blit: not a valid range of dst";
unsafe_blit src srcofs dst dstofs len
(* Flatten a rope (avoids unecessary copying). *)
let flatten = function
| Sub(_,_,_) as r -> r
| r ->
let len = length r in
assert(len <= Sys.max_string_length);
let t = Bytes.create len in
copy_to_subbytes t 0 r;
Sub(Bytes.unsafe_to_string t, 0, len)
let rec get rope i = match rope with
| Sub(s, i0, len) ->
if i < 0 || i >= len then raise(Out_of_bounds "Rope.get")
else s.[i0 + i]
| Concat(_,_, l, left_len, r) ->
if i < left_len then get l i else get r (i - left_len)
let rec iter f = function
| Sub(s, i0, len) -> for i = i0 to i0 + len - 1 do f s.[i] done
| Concat(_, _, l,_, r) -> iter f l; iter f r
let rec iteri_rec f init = function
| Sub(s, i0, len) ->
let offset = init - i0 in
for i = i0 to i0 + len - 1 do f (i + offset) s.[i] done
| Concat(_, _, l,ll, r) ->
iteri_rec f init l;
iteri_rec f (init + ll) r
let iteri f r = ignore(iteri_rec f 0 r)
let rec map ~f = function
| Sub(s, i0, len) ->
let b = Bytes.create len in
for i = 0 to len - 1 do
Bytes.set b i (f (String.unsafe_get s (i0 + i)))
done;
Sub(Bytes.unsafe_to_string b, 0, len)
| Concat(h, len, l, ll, r) ->
let l = map ~f l in
let r = map ~f r in
Concat(h, len, l, ll, r)
let rec mapi_rec ~f idx0 = function
| Sub(s, i0, len) ->
let b = Bytes.create len in
for i = 0 to len - 1 do Bytes.set b i (f (idx0 + i) s.[i0 + i]) done;
Sub(Bytes.unsafe_to_string b, 0, len)
| Concat(h, len, l, ll, r) ->
let l = mapi_rec ~f idx0 l in
let r = mapi_rec ~f (idx0 + ll) r in
Concat(h, len, l, ll, r)
let mapi ~f r = mapi_rec ~f 0 r
(** Balancing
***********************************************************************)
(* Fast, no fuss, concatenation. *)
let balance_concat rope1 rope2 =
let len1 = length rope1
and len2 = length rope2 in
if len1 = 0 then rope2
else if len2 = 0 then rope1
else
let h = 1 + max (height rope1) (height rope2) in
Concat(h, len1 + len2, rope1, len1, rope2)
(* Invariants for [forest]:
1) The concatenation of the forest (in decreasing order) with the
unscanned part of the rope is equal to the rope being balanced.
2) All trees in the forest are balanced, i.e. [forest.(n)] is empty or
[length forest.(n) >= min_length.(n)].
3) [height forest.(n) <= n] *)
(* Add the rope [r] (usually a leaf) to the appropriate slot of
[forest] (according to [length r]) gathering ropes from lower
levels if necessary. Assume [r] is not empty. *)
let add_nonempty_to_forest forest r =
let len = length r in
let n = ref 0 in
let sum = ref empty in
forest.(n-1 ) ^ ... ^ ( forest.(2 ) ^ ( forest.(1 ) ^ forest.(0 ) ) )
with [ n ] s.t . [ min_length.(n ) < len < = ) ] . [ n ]
is at most [ max_height-1 ] because [ min_length.(max_height ) = max_int ]
with [n] s.t. [min_length.(n) < len <= min_length.(n+1)]. [n]
is at most [max_height-1] because [min_length.(max_height) = max_int] *)
while len > min_length.(!n + 1) do
if is_not_empty forest.(!n) then (
sum := balance_concat forest.(!n) !sum;
forest.(!n) <- empty;
);
if !n = level_flatten then sum := flatten !sum;
incr n
done;
(* Height of [sum] at most 1 greater than what would be required
for balance. *)
sum := balance_concat !sum r;
If [ height r < = ! n - 1 ] ( e.g. if [ r ] is a leaf ) , then [ ! sum ] is
now balanced -- distinguish whether forest.(!n - 1 ) is empty or
not ( see the cited paper pp . 1319 - 1320 ) . We now continue
concatenating ropes until the result fits into an empty slot of
the [ forest ] .
now balanced -- distinguish whether forest.(!n - 1) is empty or
not (see the cited paper pp. 1319-1320). We now continue
concatenating ropes until the result fits into an empty slot of
the [forest]. *)
let sum_len = ref(length !sum) in
while !n < max_height && !sum_len >= min_length.(!n) do
if is_not_empty forest.(!n) then (
sum := balance_concat forest.(!n) !sum;
sum_len := length forest.(!n) + !sum_len;
forest.(!n) <- empty;
);
if !n = level_flatten then sum := flatten !sum;
incr n
done;
decr n;
forest.(!n) <- !sum
let add_to_forest forest r =
if is_not_empty r then add_nonempty_to_forest forest r
(* Add a NON-EMPTY rope [r] to the forest *)
let rec balance_insert forest rope = match rope with
| Sub(s, i0, len) ->
(* If the length of the leaf is small w.r.t. the length of
[s], extract it to avoid keeping a ref the larger [s]. *)
if 25 * len <= String.length s then
add_nonempty_to_forest forest (Sub(String.sub s i0 len, 0, len))
else add_nonempty_to_forest forest rope
| Concat(h, len, l,_, r) ->
(* FIXME: when to rebalance subtrees *)
if h >= max_height || len < min_length.(h) then (
(* sub-rope needs rebalancing *)
balance_insert forest l;
balance_insert forest r;
)
else add_nonempty_to_forest forest rope
;;
let concat_forest forest =
let concat (n, sum) r =
let sum = balance_concat r sum in
(n+1, if n = level_flatten then flatten sum else sum) in
snd(Array.fold_left concat (0,empty) forest)
let balance = function
| Sub(s, i0, len) as r ->
if 0 < len && len <= extract_sub_length then
Sub(String.sub s i0 len, 0, len)
else r
| r ->
let forest = Array.make max_height empty in
balance_insert forest r;
concat_forest forest
(* Only rebalance on the height. Also doing it when [length r
< min_length.(height r)] ask for too many balancing and thus is slower. *)
let balance_if_needed r =
if height r >= rebalancing_height then balance r else r
(** "Fast" concat for ropes.
**********************************************************************
* Since concat is one of the few ways a rope can be constructed, it
* must be fast. Also, this means it is this concat which is
* responsible for the height of small ropes (until balance kicks in
* but the later the better).
*)
exception Relocation_failure (* Internal exception *)
Try to relocate the [ leaf ] at a position that will not increase the
height .
[ length(relocate_topright rope leaf _ ) = length rope + length leaf ]
[ height(relocate_topright rope leaf _ ) = height rope ]
height.
[length(relocate_topright rope leaf _)= length rope + length leaf]
[height(relocate_topright rope leaf _) = height rope] *)
let rec relocate_topright rope leaf len_leaf = match rope with
| Sub(_,_,_) -> raise Relocation_failure
| Concat(h, len, l,ll, r) ->
let hr = height r + 1 in
if hr < h then
Success , we can insert the leaf here without increasing the height
let lr = length r in
Concat(h, len + len_leaf, l,ll,
Concat(hr, lr + len_leaf, r, lr, leaf))
else
(* Try at the next level *)
Concat(h, len + len_leaf, l,ll, relocate_topright r leaf len_leaf)
let rec relocate_topleft leaf len_leaf rope = match rope with
| Sub(_,_,_) -> raise Relocation_failure
| Concat(h, len, l,ll, r) ->
let hl = height l + 1 in
if hl < h then
Success , we can insert the leaf here without increasing the height
let len_left = len_leaf + ll in
let left = Concat(hl, len_left, leaf, len_leaf, l) in
Concat(h, len_leaf + len, left, len_left, r)
else
(* Try at the next level *)
let left = relocate_topleft leaf len_leaf l in
Concat(h, len_leaf + len, left, len_leaf + ll, r)
(* We avoid copying too much -- as this may slow down access, even if
height is lower. *)
let concat2_nonempty rope1 rope2 =
match rope1, rope2 with
| Sub(s1,i1,len1), Sub(s2,i2,len2) ->
let len = len1 + len2 in
if len <= small_rope_length then
let s = Bytes.create len in
Bytes.blit_string s1 i1 s 0 len1;
Bytes.blit_string s2 i2 s len1 len2;
Sub(Bytes.unsafe_to_string s, 0, len)
else
Concat(1, len, rope1, len1, rope2)
| Concat(h1, len1, l1,ll1, (Sub(s1, i1, lens1) as leaf1)), _
when h1 > height rope2 ->
let len2 = length rope2 in
let len = len1 + len2
and lens = lens1 + len2 in
if lens <= small_rope_length then
let s = Bytes.create lens in
Bytes.blit_string s1 i1 s 0 lens1;
copy_to_subbytes s lens1 rope2;
Concat(h1, len, l1,ll1, Sub(Bytes.unsafe_to_string s, 0, lens))
else begin
try
let left = relocate_topright l1 leaf1 lens1 in
(* [h1 = height l1 + 1] since the right branch is a leaf
and [height l1 = height left]. *)
Concat(max h1 (1 + height rope2), len, left, len1, rope2)
with Relocation_failure ->
let h2plus1 = height rope2 + 1 in
(* if replacing [leaf1] will increase the height or if further
concat will have an opportunity to add to a (small) leaf *)
if (h1 = h2plus1 && len2 <= max_flatten_length)
|| len2 < small_rope_length then
Concat(h1 + 1, len, rope1, len1, flatten rope2)
else
(* [h1 > h2 + 1] *)
let right = Concat(h2plus1, lens, leaf1, lens1, rope2) in
Concat(h1, len, l1, ll1, right)
end
| _, Concat(h2, len2, (Sub(s2, i2, lens2) as leaf2),_, r2)
when height rope1 < h2 ->
let len1 = length rope1 in
let len = len1 + len2
and lens = len1 + lens2 in
if lens <= small_rope_length then
let s = Bytes.create lens in
copy_to_subbytes s 0 rope1;
Bytes.blit_string s2 i2 s len1 lens2;
Concat(h2, len, Sub(Bytes.unsafe_to_string s, 0, lens), lens, r2)
else begin
try
let right = relocate_topleft leaf2 lens2 r2 in
(* [h2 = height r2 + 1] since the left branch is a leaf
and [height r2 = height right]. *)
Concat(max (1 + height rope1) h2, len, rope1, len1, right)
with Relocation_failure ->
let h1plus1 = height rope1 + 1 in
if replacing [ ] will increase the height or if further
concat will have an opportunity to add to a ( small ) leaf
concat will have an opportunity to add to a (small) leaf *)
if (h1plus1 = h2 && len1 <= max_flatten_length)
|| len1 < small_rope_length then
Concat(h2 + 1, len, flatten rope1, len1, rope2)
else
(* [h1 + 1 < h2] *)
let left = Concat(h1plus1, lens, rope1, len1, leaf2) in
Concat(h2, len, left, lens, r2)
end
| _, _ ->
let len1 = length rope1
and len2 = length rope2 in
let len = len1 + len2 in
Small unbalanced ropes may happen if one concat left , then
right , then left , ... This costs a bit of time but is a good
defense .
right, then left,... This costs a bit of time but is a good
defense. *)
if len <= small_rope_length then
let s = Bytes.create len in
copy_to_subbytes s 0 rope1;
copy_to_subbytes s len1 rope2;
Sub(Bytes.unsafe_to_string s, 0, len)
else begin
let rope1 =
if len1 <= small_rope_length then flatten rope1 else rope1
and rope2 =
if len2 <= small_rope_length then flatten rope2 else rope2 in
let h = 1 + max (height rope1) (height rope2) in
Concat(h, len1 + len2, rope1, len1, rope2)
end
;;
let concat2 rope1 rope2 =
let len1 = length rope1
and len2 = length rope2 in
let len = len1 + len2 in
if len1 = 0 then rope2
else if len2 = 0 then rope1
else begin
if len < len1 (* overflow *) then
failwith "Rope.concat2: the length of the resulting rope exceeds max_int";
let h = 1 + max (height rope1) (height rope2) in
if h >= rebalancing_height then
(* We will need to rebalance anyway, so do a simple concat *)
balance (Concat(h, len, rope1, len1, rope2))
else
(* No automatic rebalancing -- experimentally lead to faster exec *)
concat2_nonempty rope1 rope2
end
;;
(** Subrope
***********************************************************************)
(** [sub_to_substring flat j i len r] copies the subrope of [r]
starting at character [i] and of length [len] to [flat.[j ..]]. *)
let rec sub_to_substring flat j i len = function
| Sub(s, i0, _) ->
Bytes.blit_string s (i0 + i) flat j len
| Concat(_, _, l, ll, r) ->
let ri = i - ll in
if ri >= 0 then (* only right branch *)
sub_to_substring flat j ri len r
ri < 0
let lenr = ri + len in
if lenr <= 0 then (* only left branch *)
sub_to_substring flat j i len l
at least one char from the left and right branches
sub_to_substring flat j i (-ri) l;
sub_to_substring flat (j - ri) 0 lenr r;
)
let flatten_subrope rope i len =
assert(len <= Sys.max_string_length);
let flat = Bytes.create len in
sub_to_substring flat 0 i len rope;
Sub(Bytes.unsafe_to_string flat, 0, len)
;;
(* Are lazy sub-rope nodes really needed? *)
(* This function assumes that [i], [len] define a valid sub-rope of
the last arg. *)
let rec sub_rec i len = function
| Sub(s, i0, lens) ->
assert(i >= 0 && i <= lens - len);
Sub(s, i0 + i, len)
| Concat(_, rope_len, l, ll, r) ->
let rl = rope_len - ll in
let ri = i - ll in
if ri >= 0 then
= > ri = 0 -- full right sub - rope
else sub_rec ri len r
else
let rlen = ri + len (* = i + len - ll *) in
if rlen <= 0 then (* right sub-rope empty *)
if len = ll then l (* => i = 0 -- full left sub-rope *)
else sub_rec i len l
else
at least one char from the left and right sub - ropes
let l' = if i = 0 then l else sub_rec i (-ri) l
and r' = if rlen = rl then r else sub_rec 0 rlen r in
let h = 1 + max (height l') (height r') in
(* FIXME: do we have to use this opportunity to flatten some
subtrees? In any case, the height of tree we get is no
worse than the initial tree (but the length may be much
smaller). *)
Concat(h, len, l', -ri, r')
let sub rope i len =
let len_rope = length rope in
if i < 0 || len < 0 || i > len_rope - len then invalid_arg "Rope.sub"
else if len = 0 then empty
else if len <= max_flatten_length && len_rope >= 32768 then
(* The benefit of flattening such subropes (and constants) has been
seen experimentally. It is not clear what the "exact" rule
should be. *)
flatten_subrope rope i len
else sub_rec i len rope
(** String alike functions
***********************************************************************)
let is_space = function
| ' ' | '\012' | '\n' | '\r' | '\t' -> true
| _ -> false
let rec trim_left = function
| Sub(s, i0, len) ->
let i = ref i0 in
let i_max = i0 + len in
while !i < i_max && is_space (String.unsafe_get s !i) do incr i done;
if !i = i_max then empty else Sub(s, !i, i_max - !i)
| Concat(_, _, l, _, r) ->
let l = trim_left l in
if is_empty l then trim_left r
else let ll = length l in
Concat(1 + max (height l) (height r), ll + length r, l, ll, r)
let rec trim_right = function
| Sub(s, i0, len) ->
let i = ref (i0 + len - 1) in
while !i >= i0 && is_space (String.unsafe_get s !i) do decr i done;
if !i < i0 then empty else Sub(s, i0, !i - i0 + 1)
| Concat(_, _, l, ll, r) ->
let r = trim_right r in
if is_empty r then trim_right l
else let lr = length r in
Concat(1 + max (height l) (height r), ll + lr, l, ll, r)
let trim r = trim_right(trim_left r)
(* Escape the range s.[i0 .. i0+len-1]. Modeled after Bytes.escaped *)
let escaped_sub s i0 len =
let n = ref 0 in
let i1 = i0 + len - 1 in
for i = i0 to i1 do
n := !n + (match String.unsafe_get s i with
| '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> 2
| ' ' .. '~' -> 1
| _ -> 4)
done;
if !n = len then Sub(s, i0, len) else (
let s' = Bytes.create !n in
n := 0;
for i = i0 to i1 do
(match String.unsafe_get s i with
| ('\"' | '\\') as c ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n c
| '\n' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'n'
| '\t' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 't'
| '\r' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'r'
| '\b' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'b'
| (' ' .. '~') as c -> Bytes.unsafe_set s' !n c
| c ->
let a = Char.code c in
Bytes.unsafe_set s' !n '\\';
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a / 100));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + (a / 10) mod 10));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a mod 10));
);
incr n
done;
Sub(Bytes.unsafe_to_string s', 0, !n)
)
let rec escaped = function
| Sub(s, i0, len) -> escaped_sub s i0 len
| Concat(h, _, l, _, r) ->
let l = escaped l in
let ll = length l in
let r = escaped r in
Concat(h, ll + length r, l, ll, r)
(* Return the index of [c] in [s.[i .. i1-1]] plus the [offset] or
[-1] if not found. *)
let rec index_string offset s i i1 c =
if i >= i1 then -1
else if s.[i] = c then offset + i
else index_string offset s (i+1) i1 c;;
(* Return the index of [c] from position [i] in the rope or a negative
value if not found *)
let rec unsafe_index offset i c = function
| Sub(s, i0, len) ->
index_string (offset - i0) s (i0 + i) (i0 + len) c
| Concat(_, _, l,ll, r) ->
if i >= ll then unsafe_index (offset + ll) (i - ll) c r
else
let li = unsafe_index offset i c l in
if li >= 0 then li else unsafe_index (offset + ll) 0 c r
let index_from r i c =
if i < 0 || i >= length r then invalid_arg "Rope.index_from" else
let j = unsafe_index 0 i c r in
if j >= 0 then j else raise Not_found
let index_from_opt r i c =
if i < 0 || i >= length r then invalid_arg "Rope.index_from_opt";
let j = unsafe_index 0 i c r in
if j >= 0 then Some j else None
let index r c =
let j = unsafe_index 0 0 c r in
if j >= 0 then j else raise Not_found
let index_opt r c =
let j = unsafe_index 0 0 c r in
if j >= 0 then Some j else None
let contains_from r i c =
if i < 0 || i >= length r then invalid_arg "Rope.contains_from"
else unsafe_index 0 i c r >= 0
let contains r c = unsafe_index 0 0 c r >= 0
(* Return the index of [c] in [s.[i0 .. i]] (starting from the
right) plus the [offset] or [-1] if not found. *)
let rec rindex_string offset s i0 i c =
if i < i0 then -1
else if s.[i] = c then offset + i
else rindex_string offset s i0 (i - 1) c
let rec unsafe_rindex offset i c = function
| Sub(s, i0, _) ->
rindex_string (offset - i0) s i0 (i0 + i) c
| Concat(_, _, l,ll, r) ->
if i < ll then unsafe_rindex offset i c l
else
let ri = unsafe_rindex (offset + ll) (i - ll) c r in
if ri >= 0 then ri else unsafe_rindex offset (ll - 1) c l
let rindex_from r i c =
if i < 0 || i > length r then invalid_arg "Rope.rindex_from" else
let j = unsafe_rindex 0 i c r in
if j >= 0 then j else raise Not_found
let rindex_from_opt r i c =
if i < 0 || i > length r then invalid_arg "Rope.rindex_from_opt";
let j = unsafe_rindex 0 i c r in
if j >= 0 then Some j else None
let rindex r c =
let j = unsafe_rindex 0 (length r - 1) c r in
if j >= 0 then j else raise Not_found
let rindex_opt r c =
let j = unsafe_rindex 0 (length r - 1) c r in
if j >= 0 then Some j else None
let rcontains_from r i c =
if i < 0 || i >= length r then invalid_arg "Rope.rcontains_from"
else unsafe_rindex 0 i c r >= 0
let lowercase_ascii r = map ~f:Char.lowercase_ascii r
let uppercase_ascii r = map ~f:Char.uppercase_ascii r
let lowercase = lowercase_ascii
let uppercase = uppercase_ascii
let rec map1 f = function
| Concat(h, len, l, ll, r) -> Concat(h, len, map1 f l, ll, r)
| Sub(s, i0, len) ->
if len = 0 then empty else begin
let s' = Bytes.create len in
Bytes.set s' 0 (f (String.unsafe_get s i0));
Bytes.blit_string s (i0 + 1) s' 1 (len - 1);
Sub(Bytes.unsafe_to_string s', 0, len)
end
let capitalize_ascii r = map1 Char.uppercase_ascii r
let uncapitalize_ascii r = map1 Char.lowercase_ascii r
let capitalize = capitalize_ascii
let uncapitalize = uncapitalize_ascii
(** Iterator
***********************************************************************)
module Iterator = struct
type t = {
rope: rope;
len: int; (* = length rope; avoids to recompute it again and again
for bound checks *)
mutable i: int; (* current position in the rope; it is always a
valid position of the rope or [-1]. *)
mutable path: (rope * int) list;
path to the current leaf with global range . First elements are
closer to the leaf , last element is the full rope .
closer to the leaf, last element is the full rope. *)
mutable current: string; (* local cache of current leaf *)
mutable current_g0: int;
(* global index of the beginning of current string.
i0 = current_g0 + offset *)
mutable current_g1: int;
(* global index of the char past the current string.
len = current_g1 - current_g0 *)
mutable current_offset: int; (* = i0 - current_g0 *)
}
(* [g0] is the global index (of [itr.rope]) of the beginning of the
node we are examining.
[i] is the _local_ index (of the current node) that we seek the leaf for *)
let rec set_current_for_index_rec itr g0 i = function
| Sub(s, i0, len) ->
assert(0 <= i && i < len);
itr.current <- s;
itr.current_g0 <- g0;
itr.current_g1 <- g0 + len;
itr.current_offset <- i0 - g0
| Concat(_, _, l,ll, r) ->
if i < ll then set_current_for_index_rec itr g0 i l
else set_current_for_index_rec itr (g0 + ll) (i - ll) r
let set_current_for_index itr =
set_current_for_index_rec itr 0 itr.i itr.rope
let rope itr = itr.rope
let make r i0 =
let len = length r in
let itr =
{ rope = balance_if_needed r;
len = len;
i = i0;
path = [(r, 0)]; (* the whole rope *)
current = ""; current_offset = 0;
current_g0 = 0; current_g1 = 0;
(* empty range, important if [current] not set! *)
} in
if i0 >= 0 && i0 < len then
set_current_for_index itr; (* force [current] to be set *)
itr
let peek itr i =
if i < 0 || i >= itr.len then raise(Out_of_bounds "Rope.Iterator.peek")
else (
if itr.current_g0 <= i && i < itr.current_g1 then
itr.current.[i + itr.current_offset]
else
get itr.rope i (* rope get *)
)
let get itr =
let i = itr.i in
if i < 0 || i >= itr.len then raise(Out_of_bounds "Rope.Iterator.get")
else (
if i < itr.current_g0 || i >= itr.current_g1 then
set_current_for_index itr; (* out of local bounds *)
itr.current.[i + itr.current_offset]
)
let pos itr = itr.i
let incr itr = itr.i <- itr.i + 1
let decr itr = itr.i <- itr.i - 1
let goto itr j = itr.i <- j
let move itr k = itr.i <- itr.i + k
end
(** (In)equality
***********************************************************************)
exception Less
exception Greater
let compare r1 r2 =
let len1 = length r1 and len2 = length r2 in
let i1 = Iterator.make r1 0
and i2 = Iterator.make r2 0 in
try
for _i = 1 to min len1 len2 do (* on the common portion of [r1] and [r2] *)
let c1 = Iterator.get i1 and c2 = Iterator.get i2 in
if c1 < c2 then raise Less;
if c1 > c2 then raise Greater;
Iterator.incr i1;
Iterator.incr i2;
done;
The strings are equal on their common portion , the shorter one
is the smaller .
is the smaller. *)
compare (len1: int) len2
with
| Less -> -1
| Greater -> 1
;;
(* Semantically equivalent to [compare r1 r2 = 0] but specialized
implementation for speed. *)
let equal r1 r2 =
let len1 = length r1 and len2 = length r2 in
if len1 <> len2 then false else (
let i1 = Iterator.make r1 0
and i2 = Iterator.make r2 0 in
try
for _i = 1 to len1 do (* len1 times *)
if Iterator.get i1 <> Iterator.get i2 then raise Exit;
Iterator.incr i1;
Iterator.incr i2;
done;
true
with Exit -> false
)
* KMP search algo
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
***********************************************************************)
let init_next p =
let m = String.length p in
let next = Array.make m 0 in
let i = ref 1 and j = ref 0 in
while !i < m - 1 do
if p.[!i] = p.[!j] then begin incr i; incr j; next.(!i) <- !j end
else if !j = 0 then begin incr i; next.(!i) <- 0 end else j := next.(!j)
done;
next
let search_forward_string p =
if String.length p > Sys.max_array_length then
failwith "Rope.search_forward: string to search too long";
let next = init_next p
and m = String.length p in
fun rope i0 ->
let i = Iterator.make rope i0
and j = ref 0 in
(try
(* The iterator will raise an exception of we go beyond the
length of the rope. *)
while !j < m do
if p.[!j] = Iterator.get i then begin Iterator.incr i; incr j end
else if !j = 0 then Iterator.incr i else j := next.(!j)
done;
with Out_of_bounds _ -> ());
if !j >= m then Iterator.pos i - m else raise Not_found
(** Buffer
***********************************************************************)
module Buffer = struct
The content of the buffer consists of the forest concatenated in
decreasing order plus ( at the end ) the part stored in [ buf ] :
[ forest.(max_height-1 ) ^ ... ^ forest.(1 ) ^ forest.(0 )
^ String.sub buf 0 pos ]
decreasing order plus (at the end) the part stored in [buf]:
[forest.(max_height-1) ^ ... ^ forest.(1) ^ forest.(0)
^ String.sub buf 0 pos]
*)
type t = {
mutable buf: Bytes.t;
= String.length buf ; must be > 0
mutable pos: int;
mutable length: int; (* the length of the rope contained in this buffer
-- including the part in the forest *)
forest: rope array; (* keeping the partial rope in a forest will
ensure it is balanced at the end. *)
}
(* We will not allocate big buffers, if we exceed the buffer length,
we will cut into small chunks and add it directly to the forest. *)
let create n =
let n =
if n < 1 then small_rope_length else
if n > Sys.max_string_length then Sys.max_string_length
else n in
{ buf = Bytes.create n;
buf_len = n;
pos = 0;
length = 0;
forest = Array.make max_height empty;
}
let clear b =
b.pos <- 0;
b.length <- 0;
Array.fill b.forest 0 max_height empty
(* [reset] is no different from [clear] because we do not grow the
buffer. *)
let reset b = clear b
let add_char b c =
if b.length = max_int then failwith "Rope.Buffer.add_char: \
buffer length will exceed the int range";
if b.pos >= b.buf_len then (
(* Buffer full, add it to the forest and allocate a new one: *)
add_nonempty_to_forest
b.forest (Sub(Bytes.unsafe_to_string b.buf, 0, b.buf_len));
b.buf <- Bytes.create b.buf_len;
Bytes.set b.buf 0 c;
b.pos <- 1;
)
else (
Bytes.set b.buf b.pos c;
b.pos <- b.pos + 1;
);
b.length <- b.length + 1
let unsafe_add_substring b s ofs len =
(* Beware of int overflow *)
if b.length > max_int - len then failwith "Rope.Buffer.add_substring: \
buffer length will exceed the int range";
let buf_left = b.buf_len - b.pos in
if len <= buf_left then (
Enough space in [ buf ] to hold the substring of [ s ] .
String.blit s ofs b.buf b.pos len;
b.pos <- b.pos + len;
)
else (
Complete [ buf ] and add it to the forest :
Bytes.blit_string s ofs b.buf b.pos buf_left;
add_nonempty_to_forest
b.forest (Sub(Bytes.unsafe_to_string b.buf, 0, b.buf_len));
b.buf <- Bytes.create b.buf_len;
b.pos <- 0;
(* Add the remaining of [s] to to forest (it is already
balanced by of_substring, so we add is as such): *)
let s = unsafe_of_substring s (ofs + buf_left) (len - buf_left) in
add_nonempty_to_forest b.forest s
);
b.length <- b.length + len
let add_substring b s ofs len =
if ofs < 0 || len < 0 || ofs > String.length s - len then
invalid_arg "Rope.Buffer.add_substring";
unsafe_add_substring b s ofs len
let add_string b s = unsafe_add_substring b s 0 (String.length s)
let add_rope b (r: rope) =
if is_not_empty r then (
let len = length r in
if b.length > max_int - len then failwith "Rope.Buffer.add_rope: \
buffer length will exceed the int range";
First add the part hold by [ buf ] :
add_to_forest b.forest (Sub(Bytes.sub_string b.buf 0 b.pos, 0, b.pos));
b.pos <- 0;
(* I thought [balance_insert b.forest r] was going to rebalance
[r] taking into account the content already in the buffer but
it does not seem faster. We take the decision to possibly
rebalance when the content is asked. *)
add_nonempty_to_forest b.forest r; (* [r] not empty *)
b.length <- b.length + len
)
;;
let add_buffer b b2 =
if b.length > max_int - b2.length then failwith "Rope.Buffer.add_buffer: \
buffer length will exceed the int range";
add_to_forest b.forest (Sub(Bytes.sub_string b.buf 0 b.pos, 0, b.pos));
b.pos <- 0;
let forest = b.forest in
let forest2 = b2.forest in
for i = Array.length b2.forest - 1 to 0 do
add_to_forest forest forest2.(i)
done;
b.length <- b.length + b2.length
;;
let add_channel b ic len =
if b.length > max_int - len then failwith "Rope.Buffer.add_channel: \
buffer length will exceed the int range";
let buf_left = b.buf_len - b.pos in
if len <= buf_left then (
Enough space in [ buf ] to hold the input from the channel .
really_input ic b.buf b.pos len;
b.pos <- b.pos + len;
)
else (
[ len > buf_left ] . Complete [ buf ] and add it to the forest :
really_input ic b.buf b.pos buf_left;
add_nonempty_to_forest
b.forest (Sub(Bytes.unsafe_to_string b.buf, 0, b.buf_len));
(* Read the remaining from the channel *)
let len = ref(len - buf_left) in
while !len >= b.buf_len do
let s = Bytes.create b.buf_len in
really_input ic s 0 b.buf_len;
add_nonempty_to_forest
b.forest (Sub(Bytes.unsafe_to_string s, 0, b.buf_len));
len := !len - b.buf_len;
done;
[ ! len < b.buf_len ] to read , put them into a new [ buf ] :
let s = Bytes.create b.buf_len in
really_input ic s 0 !len;
b.buf <- s;
b.pos <- !len;
);
b.length <- b.length + len
;;
(* Search for the nth element in [forest.(i ..)] of total length [len] *)
let rec nth_forest forest k i len =
assert(k <= Array.length forest);
let r = forest.(k) in (* possibly empty *)
let ofs = len - length r in (* offset of [r] in the full rope *)
if i >= ofs then get r (i - ofs)
else nth_forest forest (k + 1) i ofs
let nth b i =
if i < 0 || i >= b.length then raise(Out_of_bounds "Rope.Buffer.nth");
let forest_len = b.length - b.pos in
if i >= forest_len then Bytes.get b.buf (i - forest_len)
else nth_forest b.forest 0 i forest_len
;;
Return a rope , [ buf ] must be duplicated as it becomes part of the
rope , thus we duplicate it as ropes are immutable . What we do is
very close to [ add_nonempty_to_forest ] followed by
[ concat_forest ] except that we do not modify the forest and we
select a sub - rope . Assume [ len > 0 ] -- and [ i0 > = 0 ] .
rope, thus we duplicate it as ropes are immutable. What we do is
very close to [add_nonempty_to_forest] followed by
[concat_forest] except that we do not modify the forest and we
select a sub-rope. Assume [len > 0] -- and [i0 >= 0]. *)
let unsafe_sub (b: t) i0 len =
1 char past subrope
let forest_len = b.length - b.pos in
let buf_i1 = i1 - forest_len in
if buf_i1 >= len then
The subrope is entirely in [ buf ]
Sub(Bytes.sub_string b.buf (i0 - forest_len) len, 0, len)
else begin
let n = ref 0 in
let sum = ref empty in
if buf_i1 > 0 then (
At least one char in [ buf ] and at least one in the forest .
Concat the ropes of inferior length and append the part of [ buf ]
Concat the ropes of inferior length and append the part of [buf] *)
let rem_len = len - buf_i1 in
while buf_i1 > min_length.(!n + 1) && length !sum < rem_len do
sum := balance_concat b.forest.(!n) !sum;
if !n = level_flatten then sum := flatten !sum;
incr n
done;
sum := balance_concat
!sum (Sub(Bytes.sub_string b.buf 0 buf_i1, 0, buf_i1))
)
else (
(* Subrope in the forest. Skip the forest elements until
the last chunk of the sub-rope is found. Since [0 < len
<= forest_len], there exists a nonempty rope in the forest. *)
< = 0
while !j <= 0 do j := !j + length b.forest.(!n); incr n done;
sum := sub b.forest.(!n - 1) 0 !j (* init. with proper subrope *)
);
(* Add more forest elements until we get at least the desired length *)
while length !sum < len do
assert(!n < max_height);
sum := balance_concat b.forest.(!n) !sum;
FIXME : Check how this line may generate a 1Mb leaf :
(* if !n = level_flatten then sum := flatten !sum; *)
incr n
done;
let extra = length !sum - len in
if extra = 0 then !sum else sub !sum extra len
end
let sub b i len =
if i < 0 || len < 0 || i > b.length - len then
invalid_arg "Rope.Buffer.sub";
if len = 0 then empty
else (unsafe_sub b i len)
let contents b =
if b.length = 0 then empty
else (unsafe_sub b 0 b.length)
let length b = b.length
end
(* Using the Buffer module should be more efficient than sucessive
concatenations and ensures that the final rope is balanced. *)
let concat sep = function
| [] -> empty
| r0 :: tl ->
[ buf ] will not be used as we add ropes
Buffer.add_rope b r0;
List.iter (fun r -> Buffer.add_rope b sep; Buffer.add_rope b r) tl;
Buffer.contents b
(** Input/output -- modeled on Pervasive
***********************************************************************)
(* Imported from pervasives.ml: *)
external input_scan_line : in_channel -> int = "caml_ml_input_scan_line"
let input_line ?(leaf_length=128) chan =
let b = Buffer.create leaf_length in
let rec scan () =
let n = input_scan_line chan in
n = 0 : we are at EOF
if Buffer.length b = 0 then raise End_of_file
else Buffer.contents b
else if n > 0 then ( (* n > 0: newline found in buffer *)
Buffer.add_channel b chan (n-1);
ignore (input_char chan); (* skip the newline *)
Buffer.contents b
)
else ( (* n < 0: newline not found *)
Buffer.add_channel b chan (-n);
scan ()
)
in scan()
;;
let read_line () = flush stdout; input_line stdin
let rec output_string fh = function
| Sub(s, i0, len) -> output fh (Bytes.unsafe_of_string s) i0 len
| Concat(_, _, l,_, r) -> output_string fh l; output_string fh r
;;
let output_rope = output_string
let print_string rope = output_string stdout rope
let print_endline rope = output_string stdout rope; print_newline()
let prerr_string rope = output_string stderr rope
let prerr_endline rope = output_string stderr rope; prerr_newline()
(**/**)
let rec number_leaves = function
| Sub(_,_,_) -> 1
| Concat(_,_, l,_, r) -> number_leaves l + number_leaves r
let rec number_concat = function
| Sub(_,_,_) -> 0
| Concat(_,_, l,_, r) -> 1 + number_concat l + number_concat r
let rec length_leaves = function
| Sub(_,_, len) -> (len, len)
| Concat(_,_, l,_, r) ->
let (min1,max1) = length_leaves l
and (min2,max2) = length_leaves r in
(min min1 min2, max max1 max2)
module IMap = Map.Make(struct
type t = int
let compare = Stdlib.compare
end)
let distrib_leaves =
let rec add_leaves m = function
| Sub(_,_,len) ->
(try incr(IMap.find len !m)
with _ -> m := IMap.add len (ref 1) !m)
| Concat(_,_, l,_, r) -> add_leaves m l; add_leaves m r in
fun r ->
let m = ref(IMap.empty) in
add_leaves m r;
!m
(**/**)
* Toplevel
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
***********************************************************************)
module Rope_toploop = struct
open Format
let max_display_length = ref 400
(* When displaying, truncate strings that are longer than this. *)
let ellipsis = ref "..."
ellipsis for ropes longer than . User changeable .
(* Return [max_len - length r]. *)
let rec printer_lim max_len (fm:formatter) r =
if max_len > 0 then
match r with
| Concat(_,_, l,_, r) ->
let to_be_printed = printer_lim max_len fm l in
printer_lim to_be_printed fm r
| Sub(s, i0, len) ->
let l = if len < max_len then len else max_len in
(match escaped_sub s i0 l with
| Sub (s, i0, len) ->
if i0 = 0 && len = String.length s then pp_print_string fm s
else for i = i0 to i0 + len - 1 do
pp_print_char fm (String.unsafe_get s i)
done
| Concat _ -> assert false);
max_len - len
else max_len
let printer fm r =
pp_print_string fm "\"";
let to_be_printed = printer_lim !max_display_length fm r in
pp_print_string fm "\"";
if to_be_printed < 0 then pp_print_string fm !ellipsis
end
(** Regexp
***********************************************************************)
module Regexp = struct
FIXME : See also /~vouillon/ who is
writing a DFA - based regular expression library . Would be nice to
cooperate .
writing a DFA-based regular expression library. Would be nice to
cooperate. *)
end
;;
(* Local Variables: *)
compile - command : " make -C .. "
(* End: *)
| null | https://raw.githubusercontent.com/Chris00/ocaml-rope/be74c6069e407a40fc8c1f2cc41741e3224781fd/src/rope.ml | ocaml | One assumes throughout that the length is a representable
integer. Public functions that allow to construct larger ropes
must check this.
* Use this as leaf when creating fresh leaves. Also sub-ropes of
length [<= small_rope_length] may be flattened by [concat2].
This value must be quite small, typically comparable to the size
of a [Concat] node.
* When deciding whether to flatten a rope, only those with length [<=
max_flatten_length] will be.
* When balancing, copy the substrings with this length or less (=>
release the original string).
* When balancing, flatten the rope at level [level_flatten]. The
sum of [min_length.(n)], [0 <= n <= level_flatten] must be of te
same order as [max_flatten_length].
Since F_{n+2} >= ((1 + sqrt 5)/2)^n, we know F_{d+2} will overflow:
See [add_nonempty_to_forest] for the reason for [max_int]
overflow
For debugging purposes and judging the balancing
safe: string is now immutable
Since we will need to copy the string anyway, let us take this
opportunity to split it in small chunks for easier further
sharing. In order to minimize the height, we use a simple
bisection scheme.
If only a small percentage of the string is not in the rope, do
not cut the string in small pieces. The case of small lengths is
managed by [unsafe_of_substring].
Optimize when the rope hold a single string.
Similar to [copy_to_subbytes] do more work to allow specifying a
range of [src].
# of chars after [srcofs] in the left rope
len > llen
Flatten a rope (avoids unecessary copying).
* Balancing
**********************************************************************
Fast, no fuss, concatenation.
Invariants for [forest]:
1) The concatenation of the forest (in decreasing order) with the
unscanned part of the rope is equal to the rope being balanced.
2) All trees in the forest are balanced, i.e. [forest.(n)] is empty or
[length forest.(n) >= min_length.(n)].
3) [height forest.(n) <= n]
Add the rope [r] (usually a leaf) to the appropriate slot of
[forest] (according to [length r]) gathering ropes from lower
levels if necessary. Assume [r] is not empty.
Height of [sum] at most 1 greater than what would be required
for balance.
Add a NON-EMPTY rope [r] to the forest
If the length of the leaf is small w.r.t. the length of
[s], extract it to avoid keeping a ref the larger [s].
FIXME: when to rebalance subtrees
sub-rope needs rebalancing
Only rebalance on the height. Also doing it when [length r
< min_length.(height r)] ask for too many balancing and thus is slower.
* "Fast" concat for ropes.
**********************************************************************
* Since concat is one of the few ways a rope can be constructed, it
* must be fast. Also, this means it is this concat which is
* responsible for the height of small ropes (until balance kicks in
* but the later the better).
Internal exception
Try at the next level
Try at the next level
We avoid copying too much -- as this may slow down access, even if
height is lower.
[h1 = height l1 + 1] since the right branch is a leaf
and [height l1 = height left].
if replacing [leaf1] will increase the height or if further
concat will have an opportunity to add to a (small) leaf
[h1 > h2 + 1]
[h2 = height r2 + 1] since the left branch is a leaf
and [height r2 = height right].
[h1 + 1 < h2]
overflow
We will need to rebalance anyway, so do a simple concat
No automatic rebalancing -- experimentally lead to faster exec
* Subrope
**********************************************************************
* [sub_to_substring flat j i len r] copies the subrope of [r]
starting at character [i] and of length [len] to [flat.[j ..]].
only right branch
only left branch
Are lazy sub-rope nodes really needed?
This function assumes that [i], [len] define a valid sub-rope of
the last arg.
= i + len - ll
right sub-rope empty
=> i = 0 -- full left sub-rope
FIXME: do we have to use this opportunity to flatten some
subtrees? In any case, the height of tree we get is no
worse than the initial tree (but the length may be much
smaller).
The benefit of flattening such subropes (and constants) has been
seen experimentally. It is not clear what the "exact" rule
should be.
* String alike functions
**********************************************************************
Escape the range s.[i0 .. i0+len-1]. Modeled after Bytes.escaped
Return the index of [c] in [s.[i .. i1-1]] plus the [offset] or
[-1] if not found.
Return the index of [c] from position [i] in the rope or a negative
value if not found
Return the index of [c] in [s.[i0 .. i]] (starting from the
right) plus the [offset] or [-1] if not found.
* Iterator
**********************************************************************
= length rope; avoids to recompute it again and again
for bound checks
current position in the rope; it is always a
valid position of the rope or [-1].
local cache of current leaf
global index of the beginning of current string.
i0 = current_g0 + offset
global index of the char past the current string.
len = current_g1 - current_g0
= i0 - current_g0
[g0] is the global index (of [itr.rope]) of the beginning of the
node we are examining.
[i] is the _local_ index (of the current node) that we seek the leaf for
the whole rope
empty range, important if [current] not set!
force [current] to be set
rope get
out of local bounds
* (In)equality
**********************************************************************
on the common portion of [r1] and [r2]
Semantically equivalent to [compare r1 r2 = 0] but specialized
implementation for speed.
len1 times
The iterator will raise an exception of we go beyond the
length of the rope.
* Buffer
**********************************************************************
the length of the rope contained in this buffer
-- including the part in the forest
keeping the partial rope in a forest will
ensure it is balanced at the end.
We will not allocate big buffers, if we exceed the buffer length,
we will cut into small chunks and add it directly to the forest.
[reset] is no different from [clear] because we do not grow the
buffer.
Buffer full, add it to the forest and allocate a new one:
Beware of int overflow
Add the remaining of [s] to to forest (it is already
balanced by of_substring, so we add is as such):
I thought [balance_insert b.forest r] was going to rebalance
[r] taking into account the content already in the buffer but
it does not seem faster. We take the decision to possibly
rebalance when the content is asked.
[r] not empty
Read the remaining from the channel
Search for the nth element in [forest.(i ..)] of total length [len]
possibly empty
offset of [r] in the full rope
Subrope in the forest. Skip the forest elements until
the last chunk of the sub-rope is found. Since [0 < len
<= forest_len], there exists a nonempty rope in the forest.
init. with proper subrope
Add more forest elements until we get at least the desired length
if !n = level_flatten then sum := flatten !sum;
Using the Buffer module should be more efficient than sucessive
concatenations and ensures that the final rope is balanced.
* Input/output -- modeled on Pervasive
**********************************************************************
Imported from pervasives.ml:
n > 0: newline found in buffer
skip the newline
n < 0: newline not found
*/*
*/*
When displaying, truncate strings that are longer than this.
Return [max_len - length r].
* Regexp
**********************************************************************
Local Variables:
End: | File : rope.ml
Copyright ( C ) 2007
email :
WWW : /
This library is free software ; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 2.1 or
later as published by the Free Software Foundation , with the special
exception on linking described in the 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 file
LICENSE for more details .
Copyright (C) 2007
Christophe Troestler
email:
WWW: /
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 2.1 or
later as published by the Free Software Foundation, with the special
exception on linking described in the 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 file
LICENSE for more details. *)
* Rope implementation inspired from :
, , , " Ropes : an alternative
to strings " , Software Practice and Experience 25 , vol . 12 ( 1995 ) ,
pp . 1315 - 1330 .
-95/spe/vol25/issue12/spe986.pdf
Hans Boehm, Russ Atkinson, Michael Plass, "Ropes: an alternative
to strings", Software Practice and Experience 25, vol. 12 (1995),
pp. 1315-1330.
-95/spe/vol25/issue12/spe986.pdf *)
TODO :
- Regexp ( maybe using regexp lib ?
/~vouillon/ )
- Camomille interop . ( with phantom types for encoding ? ? )
See also the OSR
- Regexp (maybe using Jérôme Vouillon regexp lib ?
/~vouillon/)
- Camomille interop. (with phantom types for encoding ??)
See also the OSR
*)
let min i j = if (i:int) < j then i else j
let max i j = if (i:int) > j then i else j
exception Out_of_bounds of string
type t =
| Sub of string * int * int
( s , i0 , len ) where only s.[i0 .. i0+len-1 ] is used by the
rope . ] is forbidden , unless the rope has 0 length
( i.e. it is empty ) . Experiments show that this is faster
than [ Sub of string ] and does not really use more memory --
because splices share all nodes .
rope. [len = 0] is forbidden, unless the rope has 0 length
(i.e. it is empty). Experiments show that this is faster
than [Sub of string] and does not really use more memory --
because splices share all nodes. *)
| Concat of int * int * t * int * t
[ ( height , length , left , left_length , right ) ] . This asymmetry
between left and right was chosen because the full length and
the left length are more often needed that the right
length .
between left and right was chosen because the full length and
the left length are more often needed that the right
length. *)
type rope = t
let small_rope_length = 32
let make_length_pow2 = 10
let make_length = 1 lsl make_length_pow2
let max_flatten_length = 1024
let extract_sub_length = small_rope_length / 2
let level_flatten = 12
Fibonacci numbers $ F_{n+2}$. By definition , a NON - EMPTY rope [ r ]
is balanced iff [ length r > = ) ] .
[ ] is the first height at which the fib . number overflow
the integer range .
is balanced iff [length r >= min_length.(height r)].
[max_height] is the first height at which the fib. number overflow
the integer range. *)
let min_length, max_height =
let d = (3 * Sys.word_size) / 2 in
let m = Array.make d max_int in
let prev = ref 0
and last = ref 1
and i = ref 0 in
try
while !i < d - 1 do
let curr = !last + !prev in
m.(!i) <- curr;
prev := !last;
last := curr;
incr i
done;
assert false
with Exit -> m, !i
let rebalancing_height = min (max_height - 1) 60
* Beyond this height , implicit balance will be done . This value
allows gross inefficiencies while not being too time consuming .
For example , explicit rebalancing did not really improve the
running time on the ICFP 2007 task .
allows gross inefficiencies while not being too time consuming.
For example, explicit rebalancing did not really improve the
running time on the ICFP 2007 task. *)
32 bits : = 42
let empty = Sub("", 0, 0)
let length = function
| Sub(_, _, len) -> len
| Concat(_,len,_,_,_) -> len
let height = function
| Sub(_,_,_) -> 0
| Concat(h,_,_,_,_) -> h
let is_empty = function
| Sub(_, _, len) -> len = 0
| _ -> false
let is_not_empty = function
| Sub(_, _, len) -> len <> 0
| _ -> true
let print =
let rec map_left = function
| [] -> []
| [x] -> ["/" ^ x]
| x :: tl -> (" " ^ x) :: map_left tl in
let map_right = function
| [] -> []
| x :: tl -> ("\\" ^ x) :: List.map (fun r -> " " ^ r) tl in
let rec leaves_list = function
| Sub(s, i0, len) -> [String.sub s i0 len]
| Concat(_,_, l,_, r) ->
map_left(leaves_list l) @ map_right(leaves_list r) in
fun r -> List.iter print_endline (leaves_list r)
;;
let of_string s = Sub(s, 0, String.length s)
let rec unsafe_of_substring s i len =
if len <= small_rope_length then Sub(String.sub s i len, 0, len)
else
let len' = len / 2 in
let i' = i + len' in
let left = unsafe_of_substring s i len'
and right = unsafe_of_substring s i' (len - len') in
let h = 1 + max (height left) (height right) in
let ll = length left in
Concat(h, ll + length right, left, ll, right)
let of_substring s i len =
let len_s = String.length s in
if i < 0 || len < 0 || i > len_s - len then invalid_arg "Rope.of_substring";
if len >= len_s - (len / 10) then Sub(s, i, len)
else unsafe_of_substring s i len
let of_char c = Sub(String.make 1 c, 0, 1)
Construct a rope from [ n-1 ] copies of a call to [ gen ofs len ] of
length [ len = make_length ] and a last call with the remainder
length . So the tree has [ n ] leaves [ Sub ] . The strings returned by
[ ] may be longer than [ len ] of only the first [ len ]
chars will be used .
length [len = make_length] and a last call with the remainder
length. So the tree has [n] leaves [Sub]. The strings returned by
[gen ofs len] may be longer than [len] of only the first [len]
chars will be used. *)
let rec make_of_gen gen ofs len ~n =
if n <= 1 then
if len > 0 then Sub(gen ofs len, 0, len) else empty
else
let nl = n / 2 in
let ll = nl * max_flatten_length in
let l = make_of_gen gen ofs ll ~n:nl in
let r = make_of_gen gen (ofs + ll) (len - ll) ~n:(n - nl) in
Concat(1 + max (height l) (height r), len, l, ll, r)
let make_length_mask = make_length - 1
let make_n_chunks len =
if len land make_length_mask = 0 then len lsr make_length_pow2
else len lsr make_length_pow2 + 1
let make len c =
if len < 0 then failwith "Rope.make: len must be >= 0";
if len <= make_length then Sub(String.make len c, 0, len)
else
let base = String.make make_length c in
make_of_gen (fun _ _ -> base) 0 len ~n:(make_n_chunks len)
let init len f =
if len < 0 then failwith "Rope.init: len must be >= 0";
if len <= make_length then Sub(String.init len f, 0, len)
else
Do not use String.init to avoid creating a closure .
let gen ofs len =
let b = Bytes.create len in
for i = 0 to len - 1 do Bytes.set b i (f (ofs + i)) done;
Bytes.unsafe_to_string b in
make_of_gen gen 0 len ~n:(make_n_chunks len)
[ copy_to_subbytes t ofs r ] copy the rope [ r ] to the byte range
[ t.[ofs .. ofs+(length r)-1 ] ] . It is assumed that [ t ] is long enough .
( This function could be a one liner with [ iteri ] but we want to use
[ Bytes.blit_string ] for efficiency . )
[t.[ofs .. ofs+(length r)-1]]. It is assumed that [t] is long enough.
(This function could be a one liner with [iteri] but we want to use
[Bytes.blit_string] for efficiency.) *)
let rec copy_to_subbytes t ofs = function
| Sub(s, i0, len) ->
Bytes.blit_string s i0 t ofs len
| Concat(_, _, l,ll, r) ->
copy_to_subbytes t ofs l;
copy_to_subbytes t (ofs + ll) r
let to_string = function
| Sub(s, i0, len) ->
if i0 = 0 && len = String.length s then s
else String.sub s i0 len
| r ->
let len = length r in
if len > Sys.max_string_length then
failwith "Rope.to_string: rope length > Sys.max_string_length";
let t = Bytes.create len in
copy_to_subbytes t 0 r;
Bytes.unsafe_to_string t
let rec unsafe_blit src srcofs dst dstofs len =
match src with
| Sub(s, i0, _) ->
String.blit s (i0 + srcofs) dst dstofs len
| Concat(_, _, l, ll, r) ->
let rofs = srcofs - ll in
if rofs >= 0 then
unsafe_blit r rofs dst dstofs len
else
if len <= llen then
unsafe_blit l srcofs dst dstofs len
unsafe_blit l srcofs dst dstofs llen;
unsafe_blit r 0 dst (dstofs + llen) (len - llen);
)
let blit src srcofs dst dstofs len =
if len < 0 then failwith "Rope.blit: len >= 0 required";
if srcofs < 0 || srcofs > length src - len then
failwith "Rope.blit: not a valid range of src";
if dstofs < 0 || dstofs > Bytes.length dst - len then
failwith "Rope.blit: not a valid range of dst";
unsafe_blit src srcofs dst dstofs len
let flatten = function
| Sub(_,_,_) as r -> r
| r ->
let len = length r in
assert(len <= Sys.max_string_length);
let t = Bytes.create len in
copy_to_subbytes t 0 r;
Sub(Bytes.unsafe_to_string t, 0, len)
let rec get rope i = match rope with
| Sub(s, i0, len) ->
if i < 0 || i >= len then raise(Out_of_bounds "Rope.get")
else s.[i0 + i]
| Concat(_,_, l, left_len, r) ->
if i < left_len then get l i else get r (i - left_len)
let rec iter f = function
| Sub(s, i0, len) -> for i = i0 to i0 + len - 1 do f s.[i] done
| Concat(_, _, l,_, r) -> iter f l; iter f r
let rec iteri_rec f init = function
| Sub(s, i0, len) ->
let offset = init - i0 in
for i = i0 to i0 + len - 1 do f (i + offset) s.[i] done
| Concat(_, _, l,ll, r) ->
iteri_rec f init l;
iteri_rec f (init + ll) r
let iteri f r = ignore(iteri_rec f 0 r)
let rec map ~f = function
| Sub(s, i0, len) ->
let b = Bytes.create len in
for i = 0 to len - 1 do
Bytes.set b i (f (String.unsafe_get s (i0 + i)))
done;
Sub(Bytes.unsafe_to_string b, 0, len)
| Concat(h, len, l, ll, r) ->
let l = map ~f l in
let r = map ~f r in
Concat(h, len, l, ll, r)
let rec mapi_rec ~f idx0 = function
| Sub(s, i0, len) ->
let b = Bytes.create len in
for i = 0 to len - 1 do Bytes.set b i (f (idx0 + i) s.[i0 + i]) done;
Sub(Bytes.unsafe_to_string b, 0, len)
| Concat(h, len, l, ll, r) ->
let l = mapi_rec ~f idx0 l in
let r = mapi_rec ~f (idx0 + ll) r in
Concat(h, len, l, ll, r)
let mapi ~f r = mapi_rec ~f 0 r
let balance_concat rope1 rope2 =
let len1 = length rope1
and len2 = length rope2 in
if len1 = 0 then rope2
else if len2 = 0 then rope1
else
let h = 1 + max (height rope1) (height rope2) in
Concat(h, len1 + len2, rope1, len1, rope2)
let add_nonempty_to_forest forest r =
let len = length r in
let n = ref 0 in
let sum = ref empty in
forest.(n-1 ) ^ ... ^ ( forest.(2 ) ^ ( forest.(1 ) ^ forest.(0 ) ) )
with [ n ] s.t . [ min_length.(n ) < len < = ) ] . [ n ]
is at most [ max_height-1 ] because [ min_length.(max_height ) = max_int ]
with [n] s.t. [min_length.(n) < len <= min_length.(n+1)]. [n]
is at most [max_height-1] because [min_length.(max_height) = max_int] *)
while len > min_length.(!n + 1) do
if is_not_empty forest.(!n) then (
sum := balance_concat forest.(!n) !sum;
forest.(!n) <- empty;
);
if !n = level_flatten then sum := flatten !sum;
incr n
done;
sum := balance_concat !sum r;
If [ height r < = ! n - 1 ] ( e.g. if [ r ] is a leaf ) , then [ ! sum ] is
now balanced -- distinguish whether forest.(!n - 1 ) is empty or
not ( see the cited paper pp . 1319 - 1320 ) . We now continue
concatenating ropes until the result fits into an empty slot of
the [ forest ] .
now balanced -- distinguish whether forest.(!n - 1) is empty or
not (see the cited paper pp. 1319-1320). We now continue
concatenating ropes until the result fits into an empty slot of
the [forest]. *)
let sum_len = ref(length !sum) in
while !n < max_height && !sum_len >= min_length.(!n) do
if is_not_empty forest.(!n) then (
sum := balance_concat forest.(!n) !sum;
sum_len := length forest.(!n) + !sum_len;
forest.(!n) <- empty;
);
if !n = level_flatten then sum := flatten !sum;
incr n
done;
decr n;
forest.(!n) <- !sum
let add_to_forest forest r =
if is_not_empty r then add_nonempty_to_forest forest r
let rec balance_insert forest rope = match rope with
| Sub(s, i0, len) ->
if 25 * len <= String.length s then
add_nonempty_to_forest forest (Sub(String.sub s i0 len, 0, len))
else add_nonempty_to_forest forest rope
| Concat(h, len, l,_, r) ->
if h >= max_height || len < min_length.(h) then (
balance_insert forest l;
balance_insert forest r;
)
else add_nonempty_to_forest forest rope
;;
let concat_forest forest =
let concat (n, sum) r =
let sum = balance_concat r sum in
(n+1, if n = level_flatten then flatten sum else sum) in
snd(Array.fold_left concat (0,empty) forest)
let balance = function
| Sub(s, i0, len) as r ->
if 0 < len && len <= extract_sub_length then
Sub(String.sub s i0 len, 0, len)
else r
| r ->
let forest = Array.make max_height empty in
balance_insert forest r;
concat_forest forest
let balance_if_needed r =
if height r >= rebalancing_height then balance r else r
Try to relocate the [ leaf ] at a position that will not increase the
height .
[ length(relocate_topright rope leaf _ ) = length rope + length leaf ]
[ height(relocate_topright rope leaf _ ) = height rope ]
height.
[length(relocate_topright rope leaf _)= length rope + length leaf]
[height(relocate_topright rope leaf _) = height rope] *)
let rec relocate_topright rope leaf len_leaf = match rope with
| Sub(_,_,_) -> raise Relocation_failure
| Concat(h, len, l,ll, r) ->
let hr = height r + 1 in
if hr < h then
Success , we can insert the leaf here without increasing the height
let lr = length r in
Concat(h, len + len_leaf, l,ll,
Concat(hr, lr + len_leaf, r, lr, leaf))
else
Concat(h, len + len_leaf, l,ll, relocate_topright r leaf len_leaf)
let rec relocate_topleft leaf len_leaf rope = match rope with
| Sub(_,_,_) -> raise Relocation_failure
| Concat(h, len, l,ll, r) ->
let hl = height l + 1 in
if hl < h then
Success , we can insert the leaf here without increasing the height
let len_left = len_leaf + ll in
let left = Concat(hl, len_left, leaf, len_leaf, l) in
Concat(h, len_leaf + len, left, len_left, r)
else
let left = relocate_topleft leaf len_leaf l in
Concat(h, len_leaf + len, left, len_leaf + ll, r)
let concat2_nonempty rope1 rope2 =
match rope1, rope2 with
| Sub(s1,i1,len1), Sub(s2,i2,len2) ->
let len = len1 + len2 in
if len <= small_rope_length then
let s = Bytes.create len in
Bytes.blit_string s1 i1 s 0 len1;
Bytes.blit_string s2 i2 s len1 len2;
Sub(Bytes.unsafe_to_string s, 0, len)
else
Concat(1, len, rope1, len1, rope2)
| Concat(h1, len1, l1,ll1, (Sub(s1, i1, lens1) as leaf1)), _
when h1 > height rope2 ->
let len2 = length rope2 in
let len = len1 + len2
and lens = lens1 + len2 in
if lens <= small_rope_length then
let s = Bytes.create lens in
Bytes.blit_string s1 i1 s 0 lens1;
copy_to_subbytes s lens1 rope2;
Concat(h1, len, l1,ll1, Sub(Bytes.unsafe_to_string s, 0, lens))
else begin
try
let left = relocate_topright l1 leaf1 lens1 in
Concat(max h1 (1 + height rope2), len, left, len1, rope2)
with Relocation_failure ->
let h2plus1 = height rope2 + 1 in
if (h1 = h2plus1 && len2 <= max_flatten_length)
|| len2 < small_rope_length then
Concat(h1 + 1, len, rope1, len1, flatten rope2)
else
let right = Concat(h2plus1, lens, leaf1, lens1, rope2) in
Concat(h1, len, l1, ll1, right)
end
| _, Concat(h2, len2, (Sub(s2, i2, lens2) as leaf2),_, r2)
when height rope1 < h2 ->
let len1 = length rope1 in
let len = len1 + len2
and lens = len1 + lens2 in
if lens <= small_rope_length then
let s = Bytes.create lens in
copy_to_subbytes s 0 rope1;
Bytes.blit_string s2 i2 s len1 lens2;
Concat(h2, len, Sub(Bytes.unsafe_to_string s, 0, lens), lens, r2)
else begin
try
let right = relocate_topleft leaf2 lens2 r2 in
Concat(max (1 + height rope1) h2, len, rope1, len1, right)
with Relocation_failure ->
let h1plus1 = height rope1 + 1 in
if replacing [ ] will increase the height or if further
concat will have an opportunity to add to a ( small ) leaf
concat will have an opportunity to add to a (small) leaf *)
if (h1plus1 = h2 && len1 <= max_flatten_length)
|| len1 < small_rope_length then
Concat(h2 + 1, len, flatten rope1, len1, rope2)
else
let left = Concat(h1plus1, lens, rope1, len1, leaf2) in
Concat(h2, len, left, lens, r2)
end
| _, _ ->
let len1 = length rope1
and len2 = length rope2 in
let len = len1 + len2 in
Small unbalanced ropes may happen if one concat left , then
right , then left , ... This costs a bit of time but is a good
defense .
right, then left,... This costs a bit of time but is a good
defense. *)
if len <= small_rope_length then
let s = Bytes.create len in
copy_to_subbytes s 0 rope1;
copy_to_subbytes s len1 rope2;
Sub(Bytes.unsafe_to_string s, 0, len)
else begin
let rope1 =
if len1 <= small_rope_length then flatten rope1 else rope1
and rope2 =
if len2 <= small_rope_length then flatten rope2 else rope2 in
let h = 1 + max (height rope1) (height rope2) in
Concat(h, len1 + len2, rope1, len1, rope2)
end
;;
let concat2 rope1 rope2 =
let len1 = length rope1
and len2 = length rope2 in
let len = len1 + len2 in
if len1 = 0 then rope2
else if len2 = 0 then rope1
else begin
failwith "Rope.concat2: the length of the resulting rope exceeds max_int";
let h = 1 + max (height rope1) (height rope2) in
if h >= rebalancing_height then
balance (Concat(h, len, rope1, len1, rope2))
else
concat2_nonempty rope1 rope2
end
;;
let rec sub_to_substring flat j i len = function
| Sub(s, i0, _) ->
Bytes.blit_string s (i0 + i) flat j len
| Concat(_, _, l, ll, r) ->
let ri = i - ll in
sub_to_substring flat j ri len r
ri < 0
let lenr = ri + len in
sub_to_substring flat j i len l
at least one char from the left and right branches
sub_to_substring flat j i (-ri) l;
sub_to_substring flat (j - ri) 0 lenr r;
)
let flatten_subrope rope i len =
assert(len <= Sys.max_string_length);
let flat = Bytes.create len in
sub_to_substring flat 0 i len rope;
Sub(Bytes.unsafe_to_string flat, 0, len)
;;
let rec sub_rec i len = function
| Sub(s, i0, lens) ->
assert(i >= 0 && i <= lens - len);
Sub(s, i0 + i, len)
| Concat(_, rope_len, l, ll, r) ->
let rl = rope_len - ll in
let ri = i - ll in
if ri >= 0 then
= > ri = 0 -- full right sub - rope
else sub_rec ri len r
else
else sub_rec i len l
else
at least one char from the left and right sub - ropes
let l' = if i = 0 then l else sub_rec i (-ri) l
and r' = if rlen = rl then r else sub_rec 0 rlen r in
let h = 1 + max (height l') (height r') in
Concat(h, len, l', -ri, r')
let sub rope i len =
let len_rope = length rope in
if i < 0 || len < 0 || i > len_rope - len then invalid_arg "Rope.sub"
else if len = 0 then empty
else if len <= max_flatten_length && len_rope >= 32768 then
flatten_subrope rope i len
else sub_rec i len rope
let is_space = function
| ' ' | '\012' | '\n' | '\r' | '\t' -> true
| _ -> false
let rec trim_left = function
| Sub(s, i0, len) ->
let i = ref i0 in
let i_max = i0 + len in
while !i < i_max && is_space (String.unsafe_get s !i) do incr i done;
if !i = i_max then empty else Sub(s, !i, i_max - !i)
| Concat(_, _, l, _, r) ->
let l = trim_left l in
if is_empty l then trim_left r
else let ll = length l in
Concat(1 + max (height l) (height r), ll + length r, l, ll, r)
let rec trim_right = function
| Sub(s, i0, len) ->
let i = ref (i0 + len - 1) in
while !i >= i0 && is_space (String.unsafe_get s !i) do decr i done;
if !i < i0 then empty else Sub(s, i0, !i - i0 + 1)
| Concat(_, _, l, ll, r) ->
let r = trim_right r in
if is_empty r then trim_right l
else let lr = length r in
Concat(1 + max (height l) (height r), ll + lr, l, ll, r)
let trim r = trim_right(trim_left r)
let escaped_sub s i0 len =
let n = ref 0 in
let i1 = i0 + len - 1 in
for i = i0 to i1 do
n := !n + (match String.unsafe_get s i with
| '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> 2
| ' ' .. '~' -> 1
| _ -> 4)
done;
if !n = len then Sub(s, i0, len) else (
let s' = Bytes.create !n in
n := 0;
for i = i0 to i1 do
(match String.unsafe_get s i with
| ('\"' | '\\') as c ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n c
| '\n' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'n'
| '\t' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 't'
| '\r' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'r'
| '\b' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'b'
| (' ' .. '~') as c -> Bytes.unsafe_set s' !n c
| c ->
let a = Char.code c in
Bytes.unsafe_set s' !n '\\';
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a / 100));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + (a / 10) mod 10));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a mod 10));
);
incr n
done;
Sub(Bytes.unsafe_to_string s', 0, !n)
)
let rec escaped = function
| Sub(s, i0, len) -> escaped_sub s i0 len
| Concat(h, _, l, _, r) ->
let l = escaped l in
let ll = length l in
let r = escaped r in
Concat(h, ll + length r, l, ll, r)
let rec index_string offset s i i1 c =
if i >= i1 then -1
else if s.[i] = c then offset + i
else index_string offset s (i+1) i1 c;;
let rec unsafe_index offset i c = function
| Sub(s, i0, len) ->
index_string (offset - i0) s (i0 + i) (i0 + len) c
| Concat(_, _, l,ll, r) ->
if i >= ll then unsafe_index (offset + ll) (i - ll) c r
else
let li = unsafe_index offset i c l in
if li >= 0 then li else unsafe_index (offset + ll) 0 c r
let index_from r i c =
if i < 0 || i >= length r then invalid_arg "Rope.index_from" else
let j = unsafe_index 0 i c r in
if j >= 0 then j else raise Not_found
let index_from_opt r i c =
if i < 0 || i >= length r then invalid_arg "Rope.index_from_opt";
let j = unsafe_index 0 i c r in
if j >= 0 then Some j else None
let index r c =
let j = unsafe_index 0 0 c r in
if j >= 0 then j else raise Not_found
let index_opt r c =
let j = unsafe_index 0 0 c r in
if j >= 0 then Some j else None
let contains_from r i c =
if i < 0 || i >= length r then invalid_arg "Rope.contains_from"
else unsafe_index 0 i c r >= 0
let contains r c = unsafe_index 0 0 c r >= 0
let rec rindex_string offset s i0 i c =
if i < i0 then -1
else if s.[i] = c then offset + i
else rindex_string offset s i0 (i - 1) c
let rec unsafe_rindex offset i c = function
| Sub(s, i0, _) ->
rindex_string (offset - i0) s i0 (i0 + i) c
| Concat(_, _, l,ll, r) ->
if i < ll then unsafe_rindex offset i c l
else
let ri = unsafe_rindex (offset + ll) (i - ll) c r in
if ri >= 0 then ri else unsafe_rindex offset (ll - 1) c l
let rindex_from r i c =
if i < 0 || i > length r then invalid_arg "Rope.rindex_from" else
let j = unsafe_rindex 0 i c r in
if j >= 0 then j else raise Not_found
let rindex_from_opt r i c =
if i < 0 || i > length r then invalid_arg "Rope.rindex_from_opt";
let j = unsafe_rindex 0 i c r in
if j >= 0 then Some j else None
let rindex r c =
let j = unsafe_rindex 0 (length r - 1) c r in
if j >= 0 then j else raise Not_found
let rindex_opt r c =
let j = unsafe_rindex 0 (length r - 1) c r in
if j >= 0 then Some j else None
let rcontains_from r i c =
if i < 0 || i >= length r then invalid_arg "Rope.rcontains_from"
else unsafe_rindex 0 i c r >= 0
let lowercase_ascii r = map ~f:Char.lowercase_ascii r
let uppercase_ascii r = map ~f:Char.uppercase_ascii r
let lowercase = lowercase_ascii
let uppercase = uppercase_ascii
let rec map1 f = function
| Concat(h, len, l, ll, r) -> Concat(h, len, map1 f l, ll, r)
| Sub(s, i0, len) ->
if len = 0 then empty else begin
let s' = Bytes.create len in
Bytes.set s' 0 (f (String.unsafe_get s i0));
Bytes.blit_string s (i0 + 1) s' 1 (len - 1);
Sub(Bytes.unsafe_to_string s', 0, len)
end
let capitalize_ascii r = map1 Char.uppercase_ascii r
let uncapitalize_ascii r = map1 Char.lowercase_ascii r
let capitalize = capitalize_ascii
let uncapitalize = uncapitalize_ascii
module Iterator = struct
type t = {
rope: rope;
mutable path: (rope * int) list;
path to the current leaf with global range . First elements are
closer to the leaf , last element is the full rope .
closer to the leaf, last element is the full rope. *)
mutable current_g0: int;
mutable current_g1: int;
}
let rec set_current_for_index_rec itr g0 i = function
| Sub(s, i0, len) ->
assert(0 <= i && i < len);
itr.current <- s;
itr.current_g0 <- g0;
itr.current_g1 <- g0 + len;
itr.current_offset <- i0 - g0
| Concat(_, _, l,ll, r) ->
if i < ll then set_current_for_index_rec itr g0 i l
else set_current_for_index_rec itr (g0 + ll) (i - ll) r
let set_current_for_index itr =
set_current_for_index_rec itr 0 itr.i itr.rope
let rope itr = itr.rope
let make r i0 =
let len = length r in
let itr =
{ rope = balance_if_needed r;
len = len;
i = i0;
current = ""; current_offset = 0;
current_g0 = 0; current_g1 = 0;
} in
if i0 >= 0 && i0 < len then
itr
let peek itr i =
if i < 0 || i >= itr.len then raise(Out_of_bounds "Rope.Iterator.peek")
else (
if itr.current_g0 <= i && i < itr.current_g1 then
itr.current.[i + itr.current_offset]
else
)
let get itr =
let i = itr.i in
if i < 0 || i >= itr.len then raise(Out_of_bounds "Rope.Iterator.get")
else (
if i < itr.current_g0 || i >= itr.current_g1 then
itr.current.[i + itr.current_offset]
)
let pos itr = itr.i
let incr itr = itr.i <- itr.i + 1
let decr itr = itr.i <- itr.i - 1
let goto itr j = itr.i <- j
let move itr k = itr.i <- itr.i + k
end
exception Less
exception Greater
let compare r1 r2 =
let len1 = length r1 and len2 = length r2 in
let i1 = Iterator.make r1 0
and i2 = Iterator.make r2 0 in
try
let c1 = Iterator.get i1 and c2 = Iterator.get i2 in
if c1 < c2 then raise Less;
if c1 > c2 then raise Greater;
Iterator.incr i1;
Iterator.incr i2;
done;
The strings are equal on their common portion , the shorter one
is the smaller .
is the smaller. *)
compare (len1: int) len2
with
| Less -> -1
| Greater -> 1
;;
let equal r1 r2 =
let len1 = length r1 and len2 = length r2 in
if len1 <> len2 then false else (
let i1 = Iterator.make r1 0
and i2 = Iterator.make r2 0 in
try
if Iterator.get i1 <> Iterator.get i2 then raise Exit;
Iterator.incr i1;
Iterator.incr i2;
done;
true
with Exit -> false
)
* KMP search algo
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
***********************************************************************)
let init_next p =
let m = String.length p in
let next = Array.make m 0 in
let i = ref 1 and j = ref 0 in
while !i < m - 1 do
if p.[!i] = p.[!j] then begin incr i; incr j; next.(!i) <- !j end
else if !j = 0 then begin incr i; next.(!i) <- 0 end else j := next.(!j)
done;
next
let search_forward_string p =
if String.length p > Sys.max_array_length then
failwith "Rope.search_forward: string to search too long";
let next = init_next p
and m = String.length p in
fun rope i0 ->
let i = Iterator.make rope i0
and j = ref 0 in
(try
while !j < m do
if p.[!j] = Iterator.get i then begin Iterator.incr i; incr j end
else if !j = 0 then Iterator.incr i else j := next.(!j)
done;
with Out_of_bounds _ -> ());
if !j >= m then Iterator.pos i - m else raise Not_found
module Buffer = struct
The content of the buffer consists of the forest concatenated in
decreasing order plus ( at the end ) the part stored in [ buf ] :
[ forest.(max_height-1 ) ^ ... ^ forest.(1 ) ^ forest.(0 )
^ String.sub buf 0 pos ]
decreasing order plus (at the end) the part stored in [buf]:
[forest.(max_height-1) ^ ... ^ forest.(1) ^ forest.(0)
^ String.sub buf 0 pos]
*)
type t = {
mutable buf: Bytes.t;
= String.length buf ; must be > 0
mutable pos: int;
}
let create n =
let n =
if n < 1 then small_rope_length else
if n > Sys.max_string_length then Sys.max_string_length
else n in
{ buf = Bytes.create n;
buf_len = n;
pos = 0;
length = 0;
forest = Array.make max_height empty;
}
let clear b =
b.pos <- 0;
b.length <- 0;
Array.fill b.forest 0 max_height empty
let reset b = clear b
let add_char b c =
if b.length = max_int then failwith "Rope.Buffer.add_char: \
buffer length will exceed the int range";
if b.pos >= b.buf_len then (
add_nonempty_to_forest
b.forest (Sub(Bytes.unsafe_to_string b.buf, 0, b.buf_len));
b.buf <- Bytes.create b.buf_len;
Bytes.set b.buf 0 c;
b.pos <- 1;
)
else (
Bytes.set b.buf b.pos c;
b.pos <- b.pos + 1;
);
b.length <- b.length + 1
let unsafe_add_substring b s ofs len =
if b.length > max_int - len then failwith "Rope.Buffer.add_substring: \
buffer length will exceed the int range";
let buf_left = b.buf_len - b.pos in
if len <= buf_left then (
Enough space in [ buf ] to hold the substring of [ s ] .
String.blit s ofs b.buf b.pos len;
b.pos <- b.pos + len;
)
else (
Complete [ buf ] and add it to the forest :
Bytes.blit_string s ofs b.buf b.pos buf_left;
add_nonempty_to_forest
b.forest (Sub(Bytes.unsafe_to_string b.buf, 0, b.buf_len));
b.buf <- Bytes.create b.buf_len;
b.pos <- 0;
let s = unsafe_of_substring s (ofs + buf_left) (len - buf_left) in
add_nonempty_to_forest b.forest s
);
b.length <- b.length + len
let add_substring b s ofs len =
if ofs < 0 || len < 0 || ofs > String.length s - len then
invalid_arg "Rope.Buffer.add_substring";
unsafe_add_substring b s ofs len
let add_string b s = unsafe_add_substring b s 0 (String.length s)
let add_rope b (r: rope) =
if is_not_empty r then (
let len = length r in
if b.length > max_int - len then failwith "Rope.Buffer.add_rope: \
buffer length will exceed the int range";
First add the part hold by [ buf ] :
add_to_forest b.forest (Sub(Bytes.sub_string b.buf 0 b.pos, 0, b.pos));
b.pos <- 0;
b.length <- b.length + len
)
;;
let add_buffer b b2 =
if b.length > max_int - b2.length then failwith "Rope.Buffer.add_buffer: \
buffer length will exceed the int range";
add_to_forest b.forest (Sub(Bytes.sub_string b.buf 0 b.pos, 0, b.pos));
b.pos <- 0;
let forest = b.forest in
let forest2 = b2.forest in
for i = Array.length b2.forest - 1 to 0 do
add_to_forest forest forest2.(i)
done;
b.length <- b.length + b2.length
;;
let add_channel b ic len =
if b.length > max_int - len then failwith "Rope.Buffer.add_channel: \
buffer length will exceed the int range";
let buf_left = b.buf_len - b.pos in
if len <= buf_left then (
Enough space in [ buf ] to hold the input from the channel .
really_input ic b.buf b.pos len;
b.pos <- b.pos + len;
)
else (
[ len > buf_left ] . Complete [ buf ] and add it to the forest :
really_input ic b.buf b.pos buf_left;
add_nonempty_to_forest
b.forest (Sub(Bytes.unsafe_to_string b.buf, 0, b.buf_len));
let len = ref(len - buf_left) in
while !len >= b.buf_len do
let s = Bytes.create b.buf_len in
really_input ic s 0 b.buf_len;
add_nonempty_to_forest
b.forest (Sub(Bytes.unsafe_to_string s, 0, b.buf_len));
len := !len - b.buf_len;
done;
[ ! len < b.buf_len ] to read , put them into a new [ buf ] :
let s = Bytes.create b.buf_len in
really_input ic s 0 !len;
b.buf <- s;
b.pos <- !len;
);
b.length <- b.length + len
;;
let rec nth_forest forest k i len =
assert(k <= Array.length forest);
if i >= ofs then get r (i - ofs)
else nth_forest forest (k + 1) i ofs
let nth b i =
if i < 0 || i >= b.length then raise(Out_of_bounds "Rope.Buffer.nth");
let forest_len = b.length - b.pos in
if i >= forest_len then Bytes.get b.buf (i - forest_len)
else nth_forest b.forest 0 i forest_len
;;
Return a rope , [ buf ] must be duplicated as it becomes part of the
rope , thus we duplicate it as ropes are immutable . What we do is
very close to [ add_nonempty_to_forest ] followed by
[ concat_forest ] except that we do not modify the forest and we
select a sub - rope . Assume [ len > 0 ] -- and [ i0 > = 0 ] .
rope, thus we duplicate it as ropes are immutable. What we do is
very close to [add_nonempty_to_forest] followed by
[concat_forest] except that we do not modify the forest and we
select a sub-rope. Assume [len > 0] -- and [i0 >= 0]. *)
let unsafe_sub (b: t) i0 len =
1 char past subrope
let forest_len = b.length - b.pos in
let buf_i1 = i1 - forest_len in
if buf_i1 >= len then
The subrope is entirely in [ buf ]
Sub(Bytes.sub_string b.buf (i0 - forest_len) len, 0, len)
else begin
let n = ref 0 in
let sum = ref empty in
if buf_i1 > 0 then (
At least one char in [ buf ] and at least one in the forest .
Concat the ropes of inferior length and append the part of [ buf ]
Concat the ropes of inferior length and append the part of [buf] *)
let rem_len = len - buf_i1 in
while buf_i1 > min_length.(!n + 1) && length !sum < rem_len do
sum := balance_concat b.forest.(!n) !sum;
if !n = level_flatten then sum := flatten !sum;
incr n
done;
sum := balance_concat
!sum (Sub(Bytes.sub_string b.buf 0 buf_i1, 0, buf_i1))
)
else (
< = 0
while !j <= 0 do j := !j + length b.forest.(!n); incr n done;
);
while length !sum < len do
assert(!n < max_height);
sum := balance_concat b.forest.(!n) !sum;
FIXME : Check how this line may generate a 1Mb leaf :
incr n
done;
let extra = length !sum - len in
if extra = 0 then !sum else sub !sum extra len
end
let sub b i len =
if i < 0 || len < 0 || i > b.length - len then
invalid_arg "Rope.Buffer.sub";
if len = 0 then empty
else (unsafe_sub b i len)
let contents b =
if b.length = 0 then empty
else (unsafe_sub b 0 b.length)
let length b = b.length
end
let concat sep = function
| [] -> empty
| r0 :: tl ->
[ buf ] will not be used as we add ropes
Buffer.add_rope b r0;
List.iter (fun r -> Buffer.add_rope b sep; Buffer.add_rope b r) tl;
Buffer.contents b
external input_scan_line : in_channel -> int = "caml_ml_input_scan_line"
let input_line ?(leaf_length=128) chan =
let b = Buffer.create leaf_length in
let rec scan () =
let n = input_scan_line chan in
n = 0 : we are at EOF
if Buffer.length b = 0 then raise End_of_file
else Buffer.contents b
Buffer.add_channel b chan (n-1);
Buffer.contents b
)
Buffer.add_channel b chan (-n);
scan ()
)
in scan()
;;
let read_line () = flush stdout; input_line stdin
let rec output_string fh = function
| Sub(s, i0, len) -> output fh (Bytes.unsafe_of_string s) i0 len
| Concat(_, _, l,_, r) -> output_string fh l; output_string fh r
;;
let output_rope = output_string
let print_string rope = output_string stdout rope
let print_endline rope = output_string stdout rope; print_newline()
let prerr_string rope = output_string stderr rope
let prerr_endline rope = output_string stderr rope; prerr_newline()
let rec number_leaves = function
| Sub(_,_,_) -> 1
| Concat(_,_, l,_, r) -> number_leaves l + number_leaves r
let rec number_concat = function
| Sub(_,_,_) -> 0
| Concat(_,_, l,_, r) -> 1 + number_concat l + number_concat r
let rec length_leaves = function
| Sub(_,_, len) -> (len, len)
| Concat(_,_, l,_, r) ->
let (min1,max1) = length_leaves l
and (min2,max2) = length_leaves r in
(min min1 min2, max max1 max2)
module IMap = Map.Make(struct
type t = int
let compare = Stdlib.compare
end)
let distrib_leaves =
let rec add_leaves m = function
| Sub(_,_,len) ->
(try incr(IMap.find len !m)
with _ -> m := IMap.add len (ref 1) !m)
| Concat(_,_, l,_, r) -> add_leaves m l; add_leaves m r in
fun r ->
let m = ref(IMap.empty) in
add_leaves m r;
!m
* Toplevel
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
***********************************************************************)
module Rope_toploop = struct
open Format
let max_display_length = ref 400
let ellipsis = ref "..."
ellipsis for ropes longer than . User changeable .
let rec printer_lim max_len (fm:formatter) r =
if max_len > 0 then
match r with
| Concat(_,_, l,_, r) ->
let to_be_printed = printer_lim max_len fm l in
printer_lim to_be_printed fm r
| Sub(s, i0, len) ->
let l = if len < max_len then len else max_len in
(match escaped_sub s i0 l with
| Sub (s, i0, len) ->
if i0 = 0 && len = String.length s then pp_print_string fm s
else for i = i0 to i0 + len - 1 do
pp_print_char fm (String.unsafe_get s i)
done
| Concat _ -> assert false);
max_len - len
else max_len
let printer fm r =
pp_print_string fm "\"";
let to_be_printed = printer_lim !max_display_length fm r in
pp_print_string fm "\"";
if to_be_printed < 0 then pp_print_string fm !ellipsis
end
module Regexp = struct
FIXME : See also /~vouillon/ who is
writing a DFA - based regular expression library . Would be nice to
cooperate .
writing a DFA-based regular expression library. Would be nice to
cooperate. *)
end
;;
compile - command : " make -C .. "
|
108b9447b5cc918ef64e110ca7dc1dd2da658bb5b0b506176ca7a142b2c0701c | zenspider/schemers | exercise.1.28.scm | #lang racket/base
Exercise 1.28 :
One variant of the Fermat test that can not be fooled is called the
" - Rabin test " ( 1976 ; 1980 ) . This starts from an
alternate form of Fermat 's Little Theorem , which states that if n
;; is a prime number and a is any positive integer less than n, then a
raised to the ( n - 1)st power is congruent to 1 modulo n. To test
the primality of a number n by the - Rabin test , we pick a
;; random number a<n and raise a to the (n - 1)st power modulo n using
;; the `expmod' procedure. However, whenever we perform the squaring
;; step in `expmod', we check to see if we have discovered a
" nontrivial square root of 1 modulo n , " that is , a number not equal
to 1 or n - 1 whose square is equal to 1 modulo n. It is possible
to prove that if such a nontrivial square root of 1 exists , then n
;; is not prime. It is also possible to prove that if n is an odd
number that is not prime , then , for at least half the numbers a < n ,
;; computing a^(n-1) in this way will reveal a nontrivial square root
of 1 modulo n. ( This is why the - Rabin test can not be
;; fooled.) Modify the `expmod' procedure to signal if it discovers a
nontrivial square root of 1 , and use this to implement the
;; Miller-Rabin test with a procedure analogous to `fermat-test'.
;; Check your procedure by testing various known primes and
non - primes . Hint : One convenient way to make ` expmod ' signal is to
;; have it return 0.
;; I don't think I can muster the effort to care about this... for fuck's sake.
| null | https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_1/exercise.1.28.scm | scheme | 1980 ) . This starts from an
is a prime number and a is any positive integer less than n, then a
random number a<n and raise a to the (n - 1)st power modulo n using
the `expmod' procedure. However, whenever we perform the squaring
step in `expmod', we check to see if we have discovered a
is not prime. It is also possible to prove that if n is an odd
computing a^(n-1) in this way will reveal a nontrivial square root
fooled.) Modify the `expmod' procedure to signal if it discovers a
Miller-Rabin test with a procedure analogous to `fermat-test'.
Check your procedure by testing various known primes and
have it return 0.
I don't think I can muster the effort to care about this... for fuck's sake. | #lang racket/base
Exercise 1.28 :
One variant of the Fermat test that can not be fooled is called the
alternate form of Fermat 's Little Theorem , which states that if n
raised to the ( n - 1)st power is congruent to 1 modulo n. To test
the primality of a number n by the - Rabin test , we pick a
" nontrivial square root of 1 modulo n , " that is , a number not equal
to 1 or n - 1 whose square is equal to 1 modulo n. It is possible
to prove that if such a nontrivial square root of 1 exists , then n
number that is not prime , then , for at least half the numbers a < n ,
of 1 modulo n. ( This is why the - Rabin test can not be
nontrivial square root of 1 , and use this to implement the
non - primes . Hint : One convenient way to make ` expmod ' signal is to
|
0e7214797be3b776f1d993d22c32b386508c2166c3351a417a358e78f068aaae | grin-compiler/ghc-wpc-sample-programs | Common.hs | |
Module : . Package . Common
Description : Data structures common to all ` iPKG ` file formats .
License : : The Idris Community .
Module : Idris.Package.Common
Description : Data structures common to all `iPKG` file formats.
License : BSD3
Maintainer : The Idris Community.
-}
module Idris.Package.Common where
import Idris.Core.TT (Name)
import Idris.Imports
import Idris.Options (Opt(..))
| Description of an package .
data PkgDesc = PkgDesc {
pkgname :: PkgName -- ^ Name associated with a package.
, pkgdeps :: [PkgName] -- ^ List of packages this package depends on.
, pkgbrief :: Maybe String -- ^ Brief description of the package.
, pkgversion :: Maybe String -- ^ Version string to associate with the package.
, pkgreadme :: Maybe String -- ^ Location of the README file.
, pkglicense :: Maybe String -- ^ Description of the licensing information.
, pkgauthor :: Maybe String -- ^ Author information.
, pkgmaintainer :: Maybe String -- ^ Maintainer information.
, pkghomepage :: Maybe String -- ^ Website associated with the package.
, pkgsourceloc :: Maybe String -- ^ Location of the source files.
, pkgbugtracker :: Maybe String -- ^ Location of the project's bug tracker.
, libdeps :: [String] -- ^ External dependencies.
, objs :: [String] -- ^ Object files required by the package.
^ Makefile used to build external code . Used as part of the FFI process .
, idris_opts :: [Opt] -- ^ List of options to give the compiler.
^ Source directory for files .
, modules :: [Name] -- ^ Modules provided by the package.
^ If an executable in which module can the Main namespace and function be found .
, execout :: Maybe String -- ^ What to call the executable.
, idris_tests :: [Name] -- ^ Lists of tests to execute against the package.
} deriving (Show)
-- | Default settings for package descriptions.
defaultPkg :: PkgDesc
defaultPkg = PkgDesc unInitializedPkgName [] Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing
Nothing [] [] Nothing [] "" [] Nothing Nothing []
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/idris-1.3.3/src/Idris/Package/Common.hs | haskell | ^ Name associated with a package.
^ List of packages this package depends on.
^ Brief description of the package.
^ Version string to associate with the package.
^ Location of the README file.
^ Description of the licensing information.
^ Author information.
^ Maintainer information.
^ Website associated with the package.
^ Location of the source files.
^ Location of the project's bug tracker.
^ External dependencies.
^ Object files required by the package.
^ List of options to give the compiler.
^ Modules provided by the package.
^ What to call the executable.
^ Lists of tests to execute against the package.
| Default settings for package descriptions. | |
Module : . Package . Common
Description : Data structures common to all ` iPKG ` file formats .
License : : The Idris Community .
Module : Idris.Package.Common
Description : Data structures common to all `iPKG` file formats.
License : BSD3
Maintainer : The Idris Community.
-}
module Idris.Package.Common where
import Idris.Core.TT (Name)
import Idris.Imports
import Idris.Options (Opt(..))
| Description of an package .
data PkgDesc = PkgDesc {
^ Makefile used to build external code . Used as part of the FFI process .
^ Source directory for files .
^ If an executable in which module can the Main namespace and function be found .
} deriving (Show)
defaultPkg :: PkgDesc
defaultPkg = PkgDesc unInitializedPkgName [] Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing
Nothing [] [] Nothing [] "" [] Nothing Nothing []
|
f17c9ff22fe48bbdd06bf4bdbac10ae809ffbbece1dec3bd409416169b33bcd5 | dannypsnl/typed-nanopass | define-language.rkt | #lang typed/racket
(provide define-language)
(require syntax/parse/define
(for-syntax ee-lib
fancy-app
racket/syntax
syntax/stx))
(define-for-syntax (prefix-id prefix id)
(format-id id #:source id #:props id "~a:~a" prefix id))
(begin-for-syntax
(define-syntax-class ty-meta
; TODO: how to check this is a valid type in typed/racket?
(pattern (type (meta:id ...+))))
(define-syntax-class rule
(pattern (name:id (meta:id ...+)
#| TODO:
Currently, we have only simple rule-case
there should have a syntax
rule-case => rule-pretty-form
for example,
(bind ,x ,ty) => (,x : ,ty)
The bind structure will be printed as the right-hand side pretty form
|#
case*:rule-case ...+)))
(define-syntax-class rule-case
; syntax `,x`, which means `x` is a meta variable
(pattern (unquote meta:id)
#:attr intro-ty #f
#:attr as-field #`[#,(generate-temporary #'meta) : #,(lookup #'meta)])
; syntax `(+ ,e ,e)`, which means `+` should be a new structure, with fields `([e1 : T] [e2 : T])`
; the `T` here is fetching from the language definition
;
; TODO: The syntax that nested and with splicing `(let ([,x ,e] ...) ,e)`
(pattern (lead:id c*:rule-case ...+)
#:attr intro-ty #'lead
#:attr as-field (syntax-property #'(c*.as-field ...) 'field #t))
; TODO: please consider the syntax without leading id
; for example, we might like to write application just `(,fn ,arg)`
; rather than `(app ,fn ,arg) => (,fn ,arg)`
))
(begin-for-syntax
(define (meta-variable/bind stx)
(syntax-parse stx
[(type (meta:id ...))
(for-each (bind! _ #'#'type)
(syntax->list #'(meta ...)))]))
(define (rule-case/meta-type stx name)
(syntax-parse stx
; lookup a meta-variable associated type
[((~literal unquote) meta:id) (lookup #'meta)]
; build the struct name
[(lead:id c* ...) (prefix-id name #'lead)]))
(define (rule/bind stx name)
(syntax-parse stx [(meta:id ...) (stx-map (bind! _ #`#'#,name) #'(meta ...))]))
(define (rule/expand scoped-stx stx name)
(syntax-parse scoped-stx
[(scoped-c*:rule-case ...)
(with-syntax
([(ty ...) (stx-map (rule-case/meta-type _ name) #'(scoped-c* ...))]
[(case-struct ...) (syntax-parse stx
[(c*:rule-case ...)
(for/list ([struct-name (attribute c*.intro-ty)]
[fields (syntax->list #'(scoped-c*.as-field ...))]
#:when struct-name)
#`(struct #,(prefix-id name struct-name) #,fields #:transparent))])])
#`((define-type #,name (U ty ...)) case-struct ...))])))
(define-syntax-parser define-language
[(_ lang:id
(terminals t*:ty-meta ...)
rules:rule ...)
(define rule-names (stx-map (prefix-id #'lang _) #'(rules.name ...)))
(with-scope lang-scope
(stx-map meta-variable/bind (add-scope #'(t* ...) lang-scope))
(stx-map (rule/bind _ _)
(add-scope #'((rules.meta ...) ...) lang-scope)
rule-names)
(with-syntax
([((rule/define-types^ ...) ...)
(stx-map (rule/expand _ _ _)
(add-scope #'((rules.case* ...) ...) lang-scope)
#'((rules.case* ...) ...)
rule-names)])
#'(begin (define lang #'(language lang
(terminals t* ...)
rules ...))
rule/define-types^
... ...)))])
(module+ test
(require typed/rackunit)
(define-language surface
(terminals
(Integer (n)))
(Expr (e)
,n
(+ ,e ,e)))
(define a : surface:Expr (surface:Expr:+ 1 2))
(check-equal? a a))
| null | https://raw.githubusercontent.com/dannypsnl/typed-nanopass/4db0a30ab394b410f70cc988a528e8e056a2210c/define-language.rkt | racket | TODO: how to check this is a valid type in typed/racket?
TODO:
Currently, we have only simple rule-case
there should have a syntax
rule-case => rule-pretty-form
for example,
(bind ,x ,ty) => (,x : ,ty)
The bind structure will be printed as the right-hand side pretty form
syntax `,x`, which means `x` is a meta variable
syntax `(+ ,e ,e)`, which means `+` should be a new structure, with fields `([e1 : T] [e2 : T])`
the `T` here is fetching from the language definition
TODO: The syntax that nested and with splicing `(let ([,x ,e] ...) ,e)`
TODO: please consider the syntax without leading id
for example, we might like to write application just `(,fn ,arg)`
rather than `(app ,fn ,arg) => (,fn ,arg)`
lookup a meta-variable associated type
build the struct name | #lang typed/racket
(provide define-language)
(require syntax/parse/define
(for-syntax ee-lib
fancy-app
racket/syntax
syntax/stx))
(define-for-syntax (prefix-id prefix id)
(format-id id #:source id #:props id "~a:~a" prefix id))
(begin-for-syntax
(define-syntax-class ty-meta
(pattern (type (meta:id ...+))))
(define-syntax-class rule
(pattern (name:id (meta:id ...+)
case*:rule-case ...+)))
(define-syntax-class rule-case
(pattern (unquote meta:id)
#:attr intro-ty #f
#:attr as-field #`[#,(generate-temporary #'meta) : #,(lookup #'meta)])
(pattern (lead:id c*:rule-case ...+)
#:attr intro-ty #'lead
#:attr as-field (syntax-property #'(c*.as-field ...) 'field #t))
))
(begin-for-syntax
(define (meta-variable/bind stx)
(syntax-parse stx
[(type (meta:id ...))
(for-each (bind! _ #'#'type)
(syntax->list #'(meta ...)))]))
(define (rule-case/meta-type stx name)
(syntax-parse stx
[((~literal unquote) meta:id) (lookup #'meta)]
[(lead:id c* ...) (prefix-id name #'lead)]))
(define (rule/bind stx name)
(syntax-parse stx [(meta:id ...) (stx-map (bind! _ #`#'#,name) #'(meta ...))]))
(define (rule/expand scoped-stx stx name)
(syntax-parse scoped-stx
[(scoped-c*:rule-case ...)
(with-syntax
([(ty ...) (stx-map (rule-case/meta-type _ name) #'(scoped-c* ...))]
[(case-struct ...) (syntax-parse stx
[(c*:rule-case ...)
(for/list ([struct-name (attribute c*.intro-ty)]
[fields (syntax->list #'(scoped-c*.as-field ...))]
#:when struct-name)
#`(struct #,(prefix-id name struct-name) #,fields #:transparent))])])
#`((define-type #,name (U ty ...)) case-struct ...))])))
(define-syntax-parser define-language
[(_ lang:id
(terminals t*:ty-meta ...)
rules:rule ...)
(define rule-names (stx-map (prefix-id #'lang _) #'(rules.name ...)))
(with-scope lang-scope
(stx-map meta-variable/bind (add-scope #'(t* ...) lang-scope))
(stx-map (rule/bind _ _)
(add-scope #'((rules.meta ...) ...) lang-scope)
rule-names)
(with-syntax
([((rule/define-types^ ...) ...)
(stx-map (rule/expand _ _ _)
(add-scope #'((rules.case* ...) ...) lang-scope)
#'((rules.case* ...) ...)
rule-names)])
#'(begin (define lang #'(language lang
(terminals t* ...)
rules ...))
rule/define-types^
... ...)))])
(module+ test
(require typed/rackunit)
(define-language surface
(terminals
(Integer (n)))
(Expr (e)
,n
(+ ,e ,e)))
(define a : surface:Expr (surface:Expr:+ 1 2))
(check-equal? a a))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.