_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
|
---|---|---|---|---|---|---|---|---|
acc12aa0fd98cdc9857ba19650f2b846ca686037729c45d542ca0624e92812a1 | psg-mit/probzelus-haskell | Numeric.hs | module Util.Numeric where
import Control.Arrow (second)
import Numeric.Log
import Numeric.SpecFunctions (logGamma)
average :: Fractional a => [a] -> a
average = go 0 0 where
go n x [] = x / fromIntegral n
go n x (z : zs) = go (n + 1) (x + z) zs
shiftByMax :: (Precise d, RealFloat d, Ord d) => [(a, Log d)] -> [(a, Log d)]
shiftByMax xs = map (second (/ x')) xs
where x' = maximum $ map snd xs
exponentiateWeights :: (Precise d, RealFloat d, Ord d) => [(a, Log d)] -> [(a, d)]
exponentiateWeights = map (second (exp . ln)) . shiftByMax
weightedAverage :: Fractional a => [(a, a)] -> a
weightedAverage = go 0 0 where
go w x [] = x / w
go w x ((y, ll) : ys) = go (w + ll) (ll * y + x) ys
weightedAverageGeneric :: Fractional a => (a -> b -> b) -> b -> (b -> b -> b) -> [(b, a)] -> b
weightedAverageGeneric scale zero plus = go 0 zero where
go w x [] = scale (recip w) x
go w x ((y, ll) : ys) = go (w + ll) (scale ll y `plus` x) ys
logFact :: Int -> Double
logFact n = logGamma (fromIntegral (n + 1))
| null | https://raw.githubusercontent.com/psg-mit/probzelus-haskell/a4b66631451b6156938a9c5420cfff2999ecbbc6/haskell/src/Util/Numeric.hs | haskell | module Util.Numeric where
import Control.Arrow (second)
import Numeric.Log
import Numeric.SpecFunctions (logGamma)
average :: Fractional a => [a] -> a
average = go 0 0 where
go n x [] = x / fromIntegral n
go n x (z : zs) = go (n + 1) (x + z) zs
shiftByMax :: (Precise d, RealFloat d, Ord d) => [(a, Log d)] -> [(a, Log d)]
shiftByMax xs = map (second (/ x')) xs
where x' = maximum $ map snd xs
exponentiateWeights :: (Precise d, RealFloat d, Ord d) => [(a, Log d)] -> [(a, d)]
exponentiateWeights = map (second (exp . ln)) . shiftByMax
weightedAverage :: Fractional a => [(a, a)] -> a
weightedAverage = go 0 0 where
go w x [] = x / w
go w x ((y, ll) : ys) = go (w + ll) (ll * y + x) ys
weightedAverageGeneric :: Fractional a => (a -> b -> b) -> b -> (b -> b -> b) -> [(b, a)] -> b
weightedAverageGeneric scale zero plus = go 0 zero where
go w x [] = scale (recip w) x
go w x ((y, ll) : ys) = go (w + ll) (scale ll y `plus` x) ys
logFact :: Int -> Double
logFact n = logGamma (fromIntegral (n + 1))
|
|
d996f9fb709287d3ad84e9ae2f0ccc2a5beb3871cce796d3c168c26380985d43 | koka-lang/koka | Var.hs | ------------------------------------------------------------------------------
Copyright 2012 - 2021 , Microsoft Research , .
--
-- This is free software; you can redistribute it and/or modify it under the
terms of the Apache License , Version 2.0 . A copy of the License can be
-- found in the LICENSE file at the root of this distribution.
-----------------------------------------------------------------------------
Module that exports non - standardized ' MVar 's .
Module that exports non-standardized 'MVar's.
-}
-----------------------------------------------------------------------------
module Platform.Var( Var, newVar, takeVar, putVar
) where
newtype Var a = Var a
newVar :: a -> IO (Var a)
newVar x = return (Var x)
putVar :: Var a -> a -> IO ()
putVar v x = return ()
takeVar :: Var a -> IO a
takeVar v = error "haddock.Platform.Var.takeVar: undefined"
| null | https://raw.githubusercontent.com/koka-lang/koka/2909df715aebf57966fbdd4afdc7a477f55f239e/src/Platform/haddock/Platform/Var.hs | haskell | ----------------------------------------------------------------------------
This is free software; you can redistribute it and/or modify it under the
found in the LICENSE file at the root of this distribution.
---------------------------------------------------------------------------
--------------------------------------------------------------------------- | Copyright 2012 - 2021 , Microsoft Research , .
terms of the Apache License , Version 2.0 . A copy of the License can be
Module that exports non - standardized ' MVar 's .
Module that exports non-standardized 'MVar's.
-}
module Platform.Var( Var, newVar, takeVar, putVar
) where
newtype Var a = Var a
newVar :: a -> IO (Var a)
newVar x = return (Var x)
putVar :: Var a -> a -> IO ()
putVar v x = return ()
takeVar :: Var a -> IO a
takeVar v = error "haddock.Platform.Var.takeVar: undefined"
|
8f037827896fb6b8ac0f4f609dff23a2fdcbfd7829054d7b724053599ffe440c | evturn/haskellbook | fix-it.hs | module Sing where
1 .
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
2 .
sing =
if (x < y)
then fstString x
else sndString y
where x = "Singin"
y = "Somewhere"
3 .
main :: IO ()
main = do
print ((+) 1 2)
print 10
print (negate (-1))
print ((+) 0 blah)
where blah = negate 1
| null | https://raw.githubusercontent.com/evturn/haskellbook/3d310d0ddd4221ffc5b9fd7ec6476b2a0731274a/05/chapter-exercises/fix-it.hs | haskell | module Sing where
1 .
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
2 .
sing =
if (x < y)
then fstString x
else sndString y
where x = "Singin"
y = "Somewhere"
3 .
main :: IO ()
main = do
print ((+) 1 2)
print 10
print (negate (-1))
print ((+) 0 blah)
where blah = negate 1
|
|
de0e1b9ceb4827d7a58aaa22c2c58d774edf606be5400b5f12f3f4bb8a812e12 | felipeZ/Haskell-abinitio | BasisSet.hs |
module Science.QuantumChemistry.BasisSet where
import Science.QuantumChemistry.BasisSet.FetchBasis
import Science.QuantumChemistry.BasisSet.NormalizeBasis
import Science.QuantumChemistry.BasisSet.SerializeBasis
| null | https://raw.githubusercontent.com/felipeZ/Haskell-abinitio/c019bc37c8de78affddf97eb858c1ef18af76d83/Science/QuantumChemistry/BasisSet.hs | haskell |
module Science.QuantumChemistry.BasisSet where
import Science.QuantumChemistry.BasisSet.FetchBasis
import Science.QuantumChemistry.BasisSet.NormalizeBasis
import Science.QuantumChemistry.BasisSet.SerializeBasis
|
|
15123297b7cdcbd08f1498167af0579a3a1c2069ddf45f1e76412c0eb8738000 | haskell-game/sdl2 | Lesson02.hs | {-# LANGUAGE OverloadedStrings #-}
module Lazyfoo.Lesson02 (main) where
import Control.Concurrent (threadDelay)
import Control.Monad (void)
import Foreign.C.Types
import SDL.Vect
import qualified SDL
import Paths_sdl2 (getDataFileName)
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo]
window <- SDL.createWindow "SDL Tutorial" SDL.defaultWindow { SDL.windowInitialSize = V2 screenWidth screenHeight }
SDL.showWindow window
screenSurface <- SDL.getWindowSurface window
helloWorld <- getDataFileName "examples/lazyfoo/hello_world.bmp" >>= SDL.loadBMP
void $ SDL.surfaceBlit helloWorld Nothing screenSurface Nothing
SDL.updateWindowSurface window
threadDelay 2000000
SDL.destroyWindow window
SDL.freeSurface helloWorld
SDL.quit
| null | https://raw.githubusercontent.com/haskell-game/sdl2/569f4160b74ec1e17ad9f28368fbfa202840201f/examples/lazyfoo/Lesson02.hs | haskell | # LANGUAGE OverloadedStrings # | module Lazyfoo.Lesson02 (main) where
import Control.Concurrent (threadDelay)
import Control.Monad (void)
import Foreign.C.Types
import SDL.Vect
import qualified SDL
import Paths_sdl2 (getDataFileName)
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo]
window <- SDL.createWindow "SDL Tutorial" SDL.defaultWindow { SDL.windowInitialSize = V2 screenWidth screenHeight }
SDL.showWindow window
screenSurface <- SDL.getWindowSurface window
helloWorld <- getDataFileName "examples/lazyfoo/hello_world.bmp" >>= SDL.loadBMP
void $ SDL.surfaceBlit helloWorld Nothing screenSurface Nothing
SDL.updateWindowSurface window
threadDelay 2000000
SDL.destroyWindow window
SDL.freeSurface helloWorld
SDL.quit
|
a997af824d3240788679ba5302816c153bd367e4230969df2c1f1b8c60e0a45c | HaskellZhangSong/Introduction_to_Haskell_2ed_source | GADTs.hs | {-# LANGUAGE GADTs #-}
data Exp a where
ValInt :: Int -> Exp Int
ValBool :: Bool -> Exp Bool
Add :: Exp Int -> Exp Int -> Exp Int
Equa :: Exp Int -> Exp Int -> Exp Bool
eval :: Exp a -> a
eval (ValInt i) = i
eval (ValBool b) = b
eval (Add e1 e2) = eval e1 + eval e2
eval (Equa e1 e2) = eval e1 == eval e2
data Tree a where
Leaf :: a -> Tree Int
Branch :: Tree a -> Tree a -> Tree Int | null | https://raw.githubusercontent.com/HaskellZhangSong/Introduction_to_Haskell_2ed_source/140c50fdccfe608fe499ecf2d8a3732f531173f5/C08/GADTs.hs | haskell | # LANGUAGE GADTs # |
data Exp a where
ValInt :: Int -> Exp Int
ValBool :: Bool -> Exp Bool
Add :: Exp Int -> Exp Int -> Exp Int
Equa :: Exp Int -> Exp Int -> Exp Bool
eval :: Exp a -> a
eval (ValInt i) = i
eval (ValBool b) = b
eval (Add e1 e2) = eval e1 + eval e2
eval (Equa e1 e2) = eval e1 == eval e2
data Tree a where
Leaf :: a -> Tree Int
Branch :: Tree a -> Tree a -> Tree Int |
e3d9546f2327d41cd26ef9126a06fefec623df6b704c24244fb194a81197ec7c | bytekid/mkbtt | termx.ml | Copyright 2010
* GNU Lesser General Public License
*
* This file is part of MKBtt .
*
* 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 .
*
* 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 MKBtt . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of MKBtt.
*
* MKBtt 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.
*
* MKBtt 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 MKBtt. If not, see </>.
*)
* Auxiliary functions mainly related to terms
@author
@since 2008/01/16
@author Sarah Winkler
@since 2008/01/16 *)
(*** OPENS ********************************************************************)
open Util;;
(*** SUBMODULES **********************************************************)
module Pos = Rewriting.Position;;
module Var = Rewriting.Variable;;
module VSub = Util.Replacement.Make (Var) (Var);;
module M = U.Monad;;
module Term = U.Term;;
module Sig = U.Signature;;
module Sub = U.Substitution;;
module Rule = U.Rule;;
module Elogic = U.Elogic;;
(*** TYPES ***************************************************************)
(*** EXCEPTIONS **********************************************************)
(*** GLOBALS *************************************************************)
(*** FUNCTIONS ***********************************************************)
let (>>=) = M.(>>=)
let (>>) = M.(>>)
let return = M.return
let empty_signature = Sig.empty 50
let fresh_var sigma =
let x, sigma = Sig.fresh_var sigma in
let xn, sigma = Sig.create_var_name x sigma in
Term.Var x, Sig.add_var x xn sigma
;;
(*
let fresh_fun name a sigma = Sig.create_fun a name sigma
(* Rename variables in a term to get it to some kind of normal form.
This is to be able to easily compare nodes and avoid variant checks *)
let rec normalize_term' sigma sub = function
| Term.Var x ->
begin try
(Sub.find x sub, sub, sigma)
with
| Not_found ->
begin
let v, sigma' = fresh_var sigma in
(v, Sub.add x v sub, sigma')
end
end
| Term.Fun (f, ts) ->
let fold_norm (l, sub, sigma) t =
begin
let (t', sub', sigma') = normalize_term' sigma sub t in
(t'::l, sub', sigma')
end
in
let (ts', sub', sigma') = List.fold_left fold_norm ([], sub, sigma) ts in
(Term.Fun (f, List.rev ts'), sub', sigma')
;;
(* return normalized term together with applied substitution *)
let normalize t =
let sigma = empty_signature in
let (t', rho, _) = normalize_term' sigma Sub.empty t in
(t', rho)
;;*)
let rec normalize_term' v sub = function
| Term.Var x ->
begin try
(Sub.find x sub, sub, v)
with
| Not_found ->
(Term.Var v, Sub.add x (Term.Var v) sub, Var.next v)
end
| Term.Fun (f, ts) ->
let fold_norm (l, sub, v) t =
let (t', sub', v') = normalize_term' v sub t in (t'::l, sub', v')
in
let (ts', sub', v') = List.fold_left fold_norm ([], sub, v) ts in
(Term.Fun (f, List.rev ts'), sub', v')
;;
let normalize t =
let (t', rho, _) = normalize_term' Var.zero Sub.empty t in
(t', rho)
;;
let normalize_rule rule =
let l, r = Rule.lhs rule, Rule.rhs rule in
let (l', sub, v) = normalize_term' Var.zero Sub.empty l in
let (r', _, _) = normalize_term' v sub r in
Rule.of_terms l' r'
;;
let normalize_both s t =
if first term contains more variables , rename second after the first
term . If both sides contain the same variables , fix one order for
normalization ( by Term.compare ) to hopefully keep result
deterministic ... it does nt . ( neither side 's variables subset ! ? )
so normalize both terms , compare them then
term. If both sides contain the same variables, fix one order for
normalization (by Term.compare) to hopefully keep result
deterministic ... it doesnt. (neither side's variables subset!?)
so normalize both terms, compare them then*)
let s', _ = normalize s in
let t', _ = normalize t in
let l, r = if (Term.compare s' t') > 0 then s, t else t, s in
let rl = normalize_rule (Rule.of_terms l r) in
Rule.lhs rl, Rule.rhs rl
;;
let compare_size ((r1,_, _), _, (r2, _, _)) ((s1,_, _), _, (s2, _, _)) =
let rule_size r =
(Term.size (Rule.lhs r)) + (Term.size (Rule.rhs r))
in
let rsize = (rule_size r1) + (rule_size r2) in
let ssize = (rule_size s1) + (rule_size s2) in
(compare rsize ssize)
;;
(* functions to skolemize a term *)
let rec skolemization' s = function
| Term.Var x ->
if Sub.mem x s then M.return s
else M.fresh_fun >>=
M.create_fun_name >>= (M.create_fun 0) >>= (fun c ->
M.return (Sub.add x (Term.Fun(c,[])) s))
| Term.Fun (f,ts) -> M.foldl skolemization' s ts
;;
let skolemization = skolemization' Sub.empty
(* replace every variable by a fresh constant *)
let skolemize s t =
skolemization s >>= (fun sigma ->
skolemization' sigma t >>= (fun sigma ->
return (Pair.map (Sub.apply_term sigma) (s, t))))
;;
let lex f g (a, b) (a', b') =
let c = f a a' in
if c <> 0 then c
else g b b'
;;
let rec nonvar_subterms' p = function
| Term.Var _ -> []
| Term.Fun (f, ts) as t ->
List.fold_lefti
(fun i res y ->
let p' = Pos.add_last i p in
List.rev_append (nonvar_subterms' p' y) res
)
[t, p]
ts
;;
(* only proper subterms! *)
let nonvar_pos_proper_subterms = function
| Term.Var _ -> []
| Term.Fun (f, ts) ->
List.fold_lefti
(fun i res y ->
let p' = Pos.make i in
List.rev_append (nonvar_subterms' p' y) res
)
[]
ts
;;
let rec rename_to sigma t t' =
try (
match t, t' with
| Term.Var x, Term.Var y -> VSub.add x y sigma
| Term.Fun (f, ts), Term.Fun (f', ts') when f = f' ->
List.fold_left2 rename_to sigma ts ts'
| _ -> raise Elogic.Not_matchable
) with VSub.Inconsistent -> raise Elogic.Not_matchable
;;
let fresh_fun name a sigma = Sig.create_fun a name sigma
let rec fresh_vars = function
| Term.Var _ ->
M.get >>= fun s -> let (x,s) = Sig.fresh_var s in M.set s >>
M.return (Term.Var x)
| Term.Fun (f,ts) ->
let g ti ts = M.lift (flip List.cons ts) (fresh_vars ti) in
M.foldr g [] ts >>= fun ts -> M.return (Term.Fun (f,ts))
;;
let test_signature =
let sigma = empty_signature in
let c, sigma = fresh_fun "c" 0 sigma in
let f, sigma = fresh_fun "f" 1 sigma in
let g, sigma = fresh_fun "g" 2 sigma in
let h, sigma = fresh_fun "h" 1 sigma in
let k, sigma = fresh_fun "k" 2 sigma in
let varx, sigma = fresh_var sigma in
let vary, sigma = fresh_var sigma in
let varz, sigma = fresh_var sigma in
let vars = (varx, vary, varz) in
let funs = (c, f, g, h, k) in
vars, funs, sigma
;;
| null | https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mkbtt/termx.ml | ocaml | ** OPENS *******************************************************************
** SUBMODULES *********************************************************
** TYPES **************************************************************
** EXCEPTIONS *********************************************************
** GLOBALS ************************************************************
** FUNCTIONS **********************************************************
let fresh_fun name a sigma = Sig.create_fun a name sigma
(* Rename variables in a term to get it to some kind of normal form.
This is to be able to easily compare nodes and avoid variant checks
return normalized term together with applied substitution
functions to skolemize a term
replace every variable by a fresh constant
only proper subterms! | Copyright 2010
* GNU Lesser General Public License
*
* This file is part of MKBtt .
*
* 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 .
*
* 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 MKBtt . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of MKBtt.
*
* MKBtt 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.
*
* MKBtt 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 MKBtt. If not, see </>.
*)
* Auxiliary functions mainly related to terms
@author
@since 2008/01/16
@author Sarah Winkler
@since 2008/01/16 *)
open Util;;
module Pos = Rewriting.Position;;
module Var = Rewriting.Variable;;
module VSub = Util.Replacement.Make (Var) (Var);;
module M = U.Monad;;
module Term = U.Term;;
module Sig = U.Signature;;
module Sub = U.Substitution;;
module Rule = U.Rule;;
module Elogic = U.Elogic;;
let (>>=) = M.(>>=)
let (>>) = M.(>>)
let return = M.return
let empty_signature = Sig.empty 50
let fresh_var sigma =
let x, sigma = Sig.fresh_var sigma in
let xn, sigma = Sig.create_var_name x sigma in
Term.Var x, Sig.add_var x xn sigma
;;
let rec normalize_term' sigma sub = function
| Term.Var x ->
begin try
(Sub.find x sub, sub, sigma)
with
| Not_found ->
begin
let v, sigma' = fresh_var sigma in
(v, Sub.add x v sub, sigma')
end
end
| Term.Fun (f, ts) ->
let fold_norm (l, sub, sigma) t =
begin
let (t', sub', sigma') = normalize_term' sigma sub t in
(t'::l, sub', sigma')
end
in
let (ts', sub', sigma') = List.fold_left fold_norm ([], sub, sigma) ts in
(Term.Fun (f, List.rev ts'), sub', sigma')
;;
let normalize t =
let sigma = empty_signature in
let (t', rho, _) = normalize_term' sigma Sub.empty t in
(t', rho)
;;*)
let rec normalize_term' v sub = function
| Term.Var x ->
begin try
(Sub.find x sub, sub, v)
with
| Not_found ->
(Term.Var v, Sub.add x (Term.Var v) sub, Var.next v)
end
| Term.Fun (f, ts) ->
let fold_norm (l, sub, v) t =
let (t', sub', v') = normalize_term' v sub t in (t'::l, sub', v')
in
let (ts', sub', v') = List.fold_left fold_norm ([], sub, v) ts in
(Term.Fun (f, List.rev ts'), sub', v')
;;
let normalize t =
let (t', rho, _) = normalize_term' Var.zero Sub.empty t in
(t', rho)
;;
let normalize_rule rule =
let l, r = Rule.lhs rule, Rule.rhs rule in
let (l', sub, v) = normalize_term' Var.zero Sub.empty l in
let (r', _, _) = normalize_term' v sub r in
Rule.of_terms l' r'
;;
let normalize_both s t =
if first term contains more variables , rename second after the first
term . If both sides contain the same variables , fix one order for
normalization ( by Term.compare ) to hopefully keep result
deterministic ... it does nt . ( neither side 's variables subset ! ? )
so normalize both terms , compare them then
term. If both sides contain the same variables, fix one order for
normalization (by Term.compare) to hopefully keep result
deterministic ... it doesnt. (neither side's variables subset!?)
so normalize both terms, compare them then*)
let s', _ = normalize s in
let t', _ = normalize t in
let l, r = if (Term.compare s' t') > 0 then s, t else t, s in
let rl = normalize_rule (Rule.of_terms l r) in
Rule.lhs rl, Rule.rhs rl
;;
let compare_size ((r1,_, _), _, (r2, _, _)) ((s1,_, _), _, (s2, _, _)) =
let rule_size r =
(Term.size (Rule.lhs r)) + (Term.size (Rule.rhs r))
in
let rsize = (rule_size r1) + (rule_size r2) in
let ssize = (rule_size s1) + (rule_size s2) in
(compare rsize ssize)
;;
let rec skolemization' s = function
| Term.Var x ->
if Sub.mem x s then M.return s
else M.fresh_fun >>=
M.create_fun_name >>= (M.create_fun 0) >>= (fun c ->
M.return (Sub.add x (Term.Fun(c,[])) s))
| Term.Fun (f,ts) -> M.foldl skolemization' s ts
;;
let skolemization = skolemization' Sub.empty
let skolemize s t =
skolemization s >>= (fun sigma ->
skolemization' sigma t >>= (fun sigma ->
return (Pair.map (Sub.apply_term sigma) (s, t))))
;;
let lex f g (a, b) (a', b') =
let c = f a a' in
if c <> 0 then c
else g b b'
;;
let rec nonvar_subterms' p = function
| Term.Var _ -> []
| Term.Fun (f, ts) as t ->
List.fold_lefti
(fun i res y ->
let p' = Pos.add_last i p in
List.rev_append (nonvar_subterms' p' y) res
)
[t, p]
ts
;;
let nonvar_pos_proper_subterms = function
| Term.Var _ -> []
| Term.Fun (f, ts) ->
List.fold_lefti
(fun i res y ->
let p' = Pos.make i in
List.rev_append (nonvar_subterms' p' y) res
)
[]
ts
;;
let rec rename_to sigma t t' =
try (
match t, t' with
| Term.Var x, Term.Var y -> VSub.add x y sigma
| Term.Fun (f, ts), Term.Fun (f', ts') when f = f' ->
List.fold_left2 rename_to sigma ts ts'
| _ -> raise Elogic.Not_matchable
) with VSub.Inconsistent -> raise Elogic.Not_matchable
;;
let fresh_fun name a sigma = Sig.create_fun a name sigma
let rec fresh_vars = function
| Term.Var _ ->
M.get >>= fun s -> let (x,s) = Sig.fresh_var s in M.set s >>
M.return (Term.Var x)
| Term.Fun (f,ts) ->
let g ti ts = M.lift (flip List.cons ts) (fresh_vars ti) in
M.foldr g [] ts >>= fun ts -> M.return (Term.Fun (f,ts))
;;
let test_signature =
let sigma = empty_signature in
let c, sigma = fresh_fun "c" 0 sigma in
let f, sigma = fresh_fun "f" 1 sigma in
let g, sigma = fresh_fun "g" 2 sigma in
let h, sigma = fresh_fun "h" 1 sigma in
let k, sigma = fresh_fun "k" 2 sigma in
let varx, sigma = fresh_var sigma in
let vary, sigma = fresh_var sigma in
let varz, sigma = fresh_var sigma in
let vars = (varx, vary, varz) in
let funs = (c, f, g, h, k) in
vars, funs, sigma
;;
|
69a466e2f1161db9d29b7870aadfd1a5102be9e3f7916c8290807c20c4fddcab | thheller/shadow-grove | arborist_test.clj | (ns shadow.experiments.arborist-test
(:require
[clojure.test :as t :refer (deftest is)]
[clojure.pprint :refer (pprint)]
[clojure.string :as str]
[shadow.arborist.fragments :as frag]))
(def test-body
'[[:foo {:i/key :key :bar 1 :foo foo :x nil :bool true}]
"hello"
[:div#id
(dynamic-thing {:x 1})
(if (even? 1)
(<< [:h1 "even"])
(<< [:h2 "odd"]))
[:h1 "hello, " title ", " foo]
(let [x 1]
(<< [:h2 x]))]
1
(some-fn 1 2)])
(def test-body
#_'[[:div.card {:style {:color "red"} :foo ["xyz" "foo" "bar"] :attr toggle}
[:div.card-header title]
[:div.card-body {:on-click ^:once [::foo {:bar yo}] :attr "foo"} "Hello"]]]
'[[:div.card
[:div.card-title title]
[:div {:foo "bar" :class (css 1 2 3)} body]
[:div
[:button {:style/height "15px"} "ok"]]]]
#_[[:div x]
[:> component {:foo "bar"} [:c1 [:c2 {:x x}] y] [:c3]]])
(deftest test-macro-expand
(pprint (frag/make-fragment {} nil test-body)))
| null | https://raw.githubusercontent.com/thheller/shadow-grove/9cfa776e737d790a6390a464cc891d7d9f1e546a/src/test/shadow/experiments/arborist_test.clj | clojure | (ns shadow.experiments.arborist-test
(:require
[clojure.test :as t :refer (deftest is)]
[clojure.pprint :refer (pprint)]
[clojure.string :as str]
[shadow.arborist.fragments :as frag]))
(def test-body
'[[:foo {:i/key :key :bar 1 :foo foo :x nil :bool true}]
"hello"
[:div#id
(dynamic-thing {:x 1})
(if (even? 1)
(<< [:h1 "even"])
(<< [:h2 "odd"]))
[:h1 "hello, " title ", " foo]
(let [x 1]
(<< [:h2 x]))]
1
(some-fn 1 2)])
(def test-body
#_'[[:div.card {:style {:color "red"} :foo ["xyz" "foo" "bar"] :attr toggle}
[:div.card-header title]
[:div.card-body {:on-click ^:once [::foo {:bar yo}] :attr "foo"} "Hello"]]]
'[[:div.card
[:div.card-title title]
[:div {:foo "bar" :class (css 1 2 3)} body]
[:div
[:button {:style/height "15px"} "ok"]]]]
#_[[:div x]
[:> component {:foo "bar"} [:c1 [:c2 {:x x}] y] [:c3]]])
(deftest test-macro-expand
(pprint (frag/make-fragment {} nil test-body)))
|
|
e77b0b6bb33cc9119480a6d3e426df1bb70e229f143db76ca1d955f8ba6dc745 | Deducteam/SizeChangeTool | positivity_checker.ml | open Kernel
open Kernel.Basic
open Kernel.Term
open Sizematrix
open Sign
let d_pos = Debug.register_flag "Positivity"
type comp_cstr = Rules.rule_name * name * (int * term) * (int * term)
type constr_graph =
{ (** An array containing every type constructor and its status*)
constructors : name array
; (** The main order between type constructors *)
typ_cstr_order : Bool_matrix.t
}
(** [extract_constraints_of_typ t_arg] return the list of types which occur in positive position in [t_arg] and the list of types which occur in negative position in [t_arg]. *)
let extract_constraints_of_typ : int * term ->
(int * term) list * (int * term) list =
let rec extract_positive : int * term -> (int * term) list =
function
| _,Const(_,f)
| _,App(Const(_,f),_,_) as t -> [t]
| i,Pi(_,_,t1,t2) ->
(extract_negative (i,t1)) @ (extract_positive (i+1,t2))
| _,Type _ -> []
| _,t ->
failwith (Format.asprintf "It is quite unexpected to have a type which is not a product of application of constants: %a" pp_term t)
and extract_negative : int * term -> (int * term) list =
function
| _,Const(_,f)
| _,App(Const(_,f),_,_) -> []
| i,Pi(_,_,t1,t2) ->
(extract_positive (i,t1)) @ (extract_negative (i+1,t2))
| _,Type _ -> []
| _,t ->
failwith (Format.asprintf "It is quite unexpected to have a type which is not a product of application of constants: %a" pp_term t)
in
fun t_arg -> (extract_positive t_arg,extract_negative t_arg)
let rec is_a_kind : term -> bool =
function
| Type _ -> true
| Pi(_,_,_,t2) -> is_a_kind t2
| _ -> false
(** [empty_cst_gr] construct an graph whose labels are type constructors and the orders are the reflexive relation. *)
let empty_cst_gr : symbol IMap.t -> constr_graph =
fun m ->
let l = ref [] in
IMap.iter (fun _ f -> if is_a_kind f.typ then l:=f.name::!l) m;
let constructors = Array.of_list !l in
let lg = Array.length constructors in
{ constructors;
typ_cstr_order = Bool_matrix.diago lg}
(** [accessed r] lists all the accessed position under a constructor in the rules. *)
let accessed : Rules.pre_rule -> (Rules.rule_name * name * int) list =
fun r ->
let used_variables : term -> int list =
let rec bis : int list -> int -> term -> int list =
fun acc i ->
function
| Kind
| Type _
| Const _ -> acc
| DB(_,_,j) -> if i<=j then (j-i)::acc else acc
| App(t1,t2,l) -> List.flatten (List.map (bis acc i) (t1::t2::l))
| Lam(_,_,None,t) -> bis acc (i+1) t
| Lam(_,_,Some t1,t2)
| Pi(_,_,t1,t2) -> (bis acc i t1) @ (bis acc (i+1) t2)
in bis [] 0
in
[ list_of_access vars args ] returns the list of constructors under which you have to go to find the first occurrence of each variable whose index is listed in [ vars ]
let list_of_access : int list -> term list -> (Rules.rule_name * name * int) list =
let rec bis glob_acc loc_acc i used =
function
| [] -> glob_acc
| Kind :: tl
| Type _ :: tl
| Const _ :: tl -> bis glob_acc [] 0 used tl
| DB(_,_,j) :: tl ->
if List.mem (j-i) used
then
bis (loc_acc @ glob_acc) [] 0
(List.filter (fun x -> x <> (j-i)) used) tl
else
bis glob_acc [] 0 used tl
| App(Const(_,f),t2,l) :: tl ->
let index = ref (-1) in
List.flatten
(List.map
(fun t ->
incr index;
bis glob_acc ((r.name,f,!index)::loc_acc) i used (t::tl)
)
(t2::l)
)
| App(t1,t2,l) :: tl ->
List.flatten
(List.map
(fun t -> bis glob_acc loc_acc i used (t::tl))
(t1::t2::l)
)
| Lam(_,_,None,t) :: tl -> bis glob_acc loc_acc (i+1) used (t::tl)
| Lam(_,_,Some t1,t2) ::tl
| Pi(_,_,t1,t2) :: tl ->
(bis glob_acc loc_acc i used (t1::tl))
@ (bis glob_acc loc_acc (i+1) used (t2::tl))
in bis [] [] 0
in
let used_vars = List.sort_uniq compare (used_variables r.rhs) in
list_of_access used_vars (Array.to_list r.args)
(* [get_ith_arg_and_return] transforms the contraint of accessibility into pair of types which must be compare. (Rules.rule_name and name are kept for error messages). *)
let get_ith_arg_and_return : Sign.signature -> (Rules.rule_name * name * int)
-> comp_cstr =
let rec get_return : int -> term -> int * term =
fun i ->
function
| Pi(_,_,_,t) -> get_return (i+1) t
| u -> (i,u)
in
let rec get_ith : int -> int -> term -> int * term =
fun i remain t ->
match (remain,t) with
| 0,Pi(_,_,t1,_) -> (i,t1)
| j,Pi(_,_,_,t2) -> get_ith i (j-1) t2
| x,tt -> failwith (Format.asprintf "Over-applied symbol in the lhs: We want %i in %a" x pp_term tt)
in
fun si (r,f,i) ->
let symbols = si.symbols in
let s = IMap.find (find_symbol_index si f) symbols in
let tt = s.typ in
r,f,get_ith i i tt,get_return 0 tt
* [ arr ] find the first index [ i ] such that [ arr.(i)=x ] . If no such index exists , raise [ Not_found ]
let find_array : 'a -> 'a array -> int =
let rec bis : int -> 'a -> 'a list -> int =
fun i x ->
function
| [] -> raise Not_found
| a::_ when a=x -> i
| _::tl -> bis (i+1) x tl
in
fun x arr -> bis 0 x (Array.to_list arr)
(** [compute_main_order l gr] modifies [gr.typ_cstr_order.tab] to reflect the order *)
let compute_main_order : comp_cstr list -> constr_graph -> unit =
fun acc cst_gr ->
let cons = cst_gr.constructors in
List.iter
(fun (_,_,ti,(_,tr)) ->
let lpos,lneg = extract_constraints_of_typ ti in
List.iter
( fun (_,t) ->
match t,tr with
| Const(_,f), Const(_,g)
| App(Const(_,f),_,_), Const(_,g)
| Const(_,f), App(Const(_,g),_,_)
| App(Const(_,f),_,_), App(Const(_,g),_,_) ->
let i_f = find_array f cons in
let i_g = find_array g cons in
cst_gr.typ_cstr_order.tab.(i_f).(i_g) <- true
| _ -> failwith "Unexpected types"
) (lpos@lneg)
) acc
let main_order_type_level_rules : Callgraph.call_graph -> constr_graph -> unit =
fun gr cst_gr ->
let si = gr.signature in
let rec study i =
function
| Pi(_,_,t1,t2) -> study i t1; study i t2
| Const(_,f)
| App(Const(_,f),_,_) -> cst_gr.typ_cstr_order.tab.(find_array f cst_gr.constructors).(i) <- true
| _ -> failwith "Unexpected types"
in
IMap.iter
(fun _ r ->
let tt = (IMap.find (find_symbol_index si r.Rules.head) si.symbols).typ in
if is_a_kind tt
then
study (find_array r.Rules.head cst_gr.constructors) r.Rules.rhs
)
si.rules
let rec comp_list : (int * term) list -> (int * term) list -> bool =
fun l1 l2 ->
match l1,l2 with
| [], [] -> false
| [], _ -> true
| _, [] -> false
| (i1,a)::l1,(i2,b)::l2 ->
match Call_extractor.compare_term (i1-i2) b a with
| Infi -> false
| Zero -> comp_list l1 l2
| Min1 -> true
let verify_pos_type_level_rules : Callgraph.call_graph -> constr_graph -> bool =
fun gr cst_gr ->
let si = gr.signature in
let cons = cst_gr.constructors in
let main = cst_gr.typ_cstr_order.tab in
let res = ref true in
IMap.iter
(fun _ r ->
let symb = IMap.find (find_symbol_index si r.Rules.head) si.symbols in
let tt = symb.typ in
if is_a_kind tt
then
let i = find_array r.head cons in
let _,lneg = extract_constraints_of_typ (0,tt) in
List.iter
( fun (j,t) ->
match t with
| Const(_,f) ->
let i_f = find_array f cons in
let comp = main.(i).(i_f) in
if comp then
if Array.length r.args = 0 then
(res := false;
update_result symb (NotPositive r.name))
| App(Const(_,f),t1,l1) ->
let i_f = find_array f cons in
let comp = main.(i).(i_f) in
if comp then
let res_bis =
comp_list
(List.map (fun x -> j,x) (t1::l1))
(List.map (fun x -> 0,x) (Array.to_list r.args))
in
if not res_bis
then
(res := false;
update_result symb (NotPositive r.name))
| _ -> failwith "Unexpected types"
) lneg;
)
si.rules;
!res
let is_mkable_pos : comp_cstr -> signature -> constr_graph -> bool =
fun (r,c,(i1,ti),(i2,tr)) si cst_gr ->
let cons = cst_gr.constructors in
let main = cst_gr.typ_cstr_order.tab in
let _,lneg = extract_constraints_of_typ (i1,ti) in
let res = ref true in
List.iter
( fun (i,t) ->
match t,tr with
| Const(_,f), Const(_,g)
| App(Const(_,f),_,_), Const(_,g) ->
let i_f = find_array f cons in
let i_g = find_array g cons in
let comp = main.(i_g).(i_f) in
if comp then
(res := false;
update_result
(IMap.find (find_symbol_index si c) si.symbols)
(NotPositive r))
| Const(_,f), App(Const(_,g),_,_) -> ()
| App(Const(_,f),t1,l1), App(Const(_,g),t2,l2) ->
let i_f = find_array f cons in
let i_g = find_array g cons in
let comp = main.(i_g).(i_f) in
if comp then
let res_bis =
comp_list
(List.map (fun x -> i,x) (t1::l1))
(List.map (fun x -> i2,x) (t2::l2))
in
if not res_bis
then
(res := false;
update_result
(IMap.find (find_symbol_index si c) si.symbols)
(NotPositive r))
| _ -> failwith "Unexpected types"
) lneg;
!res
let check_positivity : Callgraph.call_graph -> bool =
fun gr ->
let si = gr.signature in
let cst_gr = empty_cst_gr si.symbols in
let acc_name = ref [] in
IMap.iter
(fun _ r -> acc_name := (accessed r)::!acc_name)
si.rules;
let acc_bis = List.flatten !acc_name in
Debug.debug d_pos "Accessed variables are:@. - %a@."
(pp_list "\n - " (pp_triple Format.pp_print_string pp_name Format.pp_print_int))
acc_bis;
let acc = List.map (get_ith_arg_and_return si) acc_bis in
compute_main_order acc cst_gr;
main_order_type_level_rules gr cst_gr;
let cst_gr2 =
{cst_gr with
typ_cstr_order = Sizematrix.Bool_matrix.trans_clos cst_gr.typ_cstr_order}
in
Debug.debug d_pos "The main order is:@.";
Debug.debug_eval
d_pos
(fun () ->
let cons = cst_gr2.constructors in
let tab = cst_gr2.typ_cstr_order.tab in
let lg = Array.length cons in
for i=0 to lg -1 do
for j=0 to lg-1 do
if tab.(i).(j)
then
Format.printf " - %a≤%a@." pp_name cons.(i) pp_name cons.(j)
done;
done;
);
let res = ref true in
res := verify_pos_type_level_rules gr cst_gr2;
List.iter
(fun r ->
res:= !res && (is_mkable_pos r si cst_gr2)
) acc;
!res
| null | https://raw.githubusercontent.com/Deducteam/SizeChangeTool/0a4db26ee1beed6ca7cf404ba6edd0539d540371/src/positivity_checker.ml | ocaml | * An array containing every type constructor and its status
* The main order between type constructors
* [extract_constraints_of_typ t_arg] return the list of types which occur in positive position in [t_arg] and the list of types which occur in negative position in [t_arg].
* [empty_cst_gr] construct an graph whose labels are type constructors and the orders are the reflexive relation.
* [accessed r] lists all the accessed position under a constructor in the rules.
[get_ith_arg_and_return] transforms the contraint of accessibility into pair of types which must be compare. (Rules.rule_name and name are kept for error messages).
* [compute_main_order l gr] modifies [gr.typ_cstr_order.tab] to reflect the order | open Kernel
open Kernel.Basic
open Kernel.Term
open Sizematrix
open Sign
let d_pos = Debug.register_flag "Positivity"
type comp_cstr = Rules.rule_name * name * (int * term) * (int * term)
type constr_graph =
constructors : name array
typ_cstr_order : Bool_matrix.t
}
let extract_constraints_of_typ : int * term ->
(int * term) list * (int * term) list =
let rec extract_positive : int * term -> (int * term) list =
function
| _,Const(_,f)
| _,App(Const(_,f),_,_) as t -> [t]
| i,Pi(_,_,t1,t2) ->
(extract_negative (i,t1)) @ (extract_positive (i+1,t2))
| _,Type _ -> []
| _,t ->
failwith (Format.asprintf "It is quite unexpected to have a type which is not a product of application of constants: %a" pp_term t)
and extract_negative : int * term -> (int * term) list =
function
| _,Const(_,f)
| _,App(Const(_,f),_,_) -> []
| i,Pi(_,_,t1,t2) ->
(extract_positive (i,t1)) @ (extract_negative (i+1,t2))
| _,Type _ -> []
| _,t ->
failwith (Format.asprintf "It is quite unexpected to have a type which is not a product of application of constants: %a" pp_term t)
in
fun t_arg -> (extract_positive t_arg,extract_negative t_arg)
let rec is_a_kind : term -> bool =
function
| Type _ -> true
| Pi(_,_,_,t2) -> is_a_kind t2
| _ -> false
let empty_cst_gr : symbol IMap.t -> constr_graph =
fun m ->
let l = ref [] in
IMap.iter (fun _ f -> if is_a_kind f.typ then l:=f.name::!l) m;
let constructors = Array.of_list !l in
let lg = Array.length constructors in
{ constructors;
typ_cstr_order = Bool_matrix.diago lg}
let accessed : Rules.pre_rule -> (Rules.rule_name * name * int) list =
fun r ->
let used_variables : term -> int list =
let rec bis : int list -> int -> term -> int list =
fun acc i ->
function
| Kind
| Type _
| Const _ -> acc
| DB(_,_,j) -> if i<=j then (j-i)::acc else acc
| App(t1,t2,l) -> List.flatten (List.map (bis acc i) (t1::t2::l))
| Lam(_,_,None,t) -> bis acc (i+1) t
| Lam(_,_,Some t1,t2)
| Pi(_,_,t1,t2) -> (bis acc i t1) @ (bis acc (i+1) t2)
in bis [] 0
in
[ list_of_access vars args ] returns the list of constructors under which you have to go to find the first occurrence of each variable whose index is listed in [ vars ]
let list_of_access : int list -> term list -> (Rules.rule_name * name * int) list =
let rec bis glob_acc loc_acc i used =
function
| [] -> glob_acc
| Kind :: tl
| Type _ :: tl
| Const _ :: tl -> bis glob_acc [] 0 used tl
| DB(_,_,j) :: tl ->
if List.mem (j-i) used
then
bis (loc_acc @ glob_acc) [] 0
(List.filter (fun x -> x <> (j-i)) used) tl
else
bis glob_acc [] 0 used tl
| App(Const(_,f),t2,l) :: tl ->
let index = ref (-1) in
List.flatten
(List.map
(fun t ->
incr index;
bis glob_acc ((r.name,f,!index)::loc_acc) i used (t::tl)
)
(t2::l)
)
| App(t1,t2,l) :: tl ->
List.flatten
(List.map
(fun t -> bis glob_acc loc_acc i used (t::tl))
(t1::t2::l)
)
| Lam(_,_,None,t) :: tl -> bis glob_acc loc_acc (i+1) used (t::tl)
| Lam(_,_,Some t1,t2) ::tl
| Pi(_,_,t1,t2) :: tl ->
(bis glob_acc loc_acc i used (t1::tl))
@ (bis glob_acc loc_acc (i+1) used (t2::tl))
in bis [] [] 0
in
let used_vars = List.sort_uniq compare (used_variables r.rhs) in
list_of_access used_vars (Array.to_list r.args)
let get_ith_arg_and_return : Sign.signature -> (Rules.rule_name * name * int)
-> comp_cstr =
let rec get_return : int -> term -> int * term =
fun i ->
function
| Pi(_,_,_,t) -> get_return (i+1) t
| u -> (i,u)
in
let rec get_ith : int -> int -> term -> int * term =
fun i remain t ->
match (remain,t) with
| 0,Pi(_,_,t1,_) -> (i,t1)
| j,Pi(_,_,_,t2) -> get_ith i (j-1) t2
| x,tt -> failwith (Format.asprintf "Over-applied symbol in the lhs: We want %i in %a" x pp_term tt)
in
fun si (r,f,i) ->
let symbols = si.symbols in
let s = IMap.find (find_symbol_index si f) symbols in
let tt = s.typ in
r,f,get_ith i i tt,get_return 0 tt
* [ arr ] find the first index [ i ] such that [ arr.(i)=x ] . If no such index exists , raise [ Not_found ]
let find_array : 'a -> 'a array -> int =
let rec bis : int -> 'a -> 'a list -> int =
fun i x ->
function
| [] -> raise Not_found
| a::_ when a=x -> i
| _::tl -> bis (i+1) x tl
in
fun x arr -> bis 0 x (Array.to_list arr)
let compute_main_order : comp_cstr list -> constr_graph -> unit =
fun acc cst_gr ->
let cons = cst_gr.constructors in
List.iter
(fun (_,_,ti,(_,tr)) ->
let lpos,lneg = extract_constraints_of_typ ti in
List.iter
( fun (_,t) ->
match t,tr with
| Const(_,f), Const(_,g)
| App(Const(_,f),_,_), Const(_,g)
| Const(_,f), App(Const(_,g),_,_)
| App(Const(_,f),_,_), App(Const(_,g),_,_) ->
let i_f = find_array f cons in
let i_g = find_array g cons in
cst_gr.typ_cstr_order.tab.(i_f).(i_g) <- true
| _ -> failwith "Unexpected types"
) (lpos@lneg)
) acc
let main_order_type_level_rules : Callgraph.call_graph -> constr_graph -> unit =
fun gr cst_gr ->
let si = gr.signature in
let rec study i =
function
| Pi(_,_,t1,t2) -> study i t1; study i t2
| Const(_,f)
| App(Const(_,f),_,_) -> cst_gr.typ_cstr_order.tab.(find_array f cst_gr.constructors).(i) <- true
| _ -> failwith "Unexpected types"
in
IMap.iter
(fun _ r ->
let tt = (IMap.find (find_symbol_index si r.Rules.head) si.symbols).typ in
if is_a_kind tt
then
study (find_array r.Rules.head cst_gr.constructors) r.Rules.rhs
)
si.rules
let rec comp_list : (int * term) list -> (int * term) list -> bool =
fun l1 l2 ->
match l1,l2 with
| [], [] -> false
| [], _ -> true
| _, [] -> false
| (i1,a)::l1,(i2,b)::l2 ->
match Call_extractor.compare_term (i1-i2) b a with
| Infi -> false
| Zero -> comp_list l1 l2
| Min1 -> true
let verify_pos_type_level_rules : Callgraph.call_graph -> constr_graph -> bool =
fun gr cst_gr ->
let si = gr.signature in
let cons = cst_gr.constructors in
let main = cst_gr.typ_cstr_order.tab in
let res = ref true in
IMap.iter
(fun _ r ->
let symb = IMap.find (find_symbol_index si r.Rules.head) si.symbols in
let tt = symb.typ in
if is_a_kind tt
then
let i = find_array r.head cons in
let _,lneg = extract_constraints_of_typ (0,tt) in
List.iter
( fun (j,t) ->
match t with
| Const(_,f) ->
let i_f = find_array f cons in
let comp = main.(i).(i_f) in
if comp then
if Array.length r.args = 0 then
(res := false;
update_result symb (NotPositive r.name))
| App(Const(_,f),t1,l1) ->
let i_f = find_array f cons in
let comp = main.(i).(i_f) in
if comp then
let res_bis =
comp_list
(List.map (fun x -> j,x) (t1::l1))
(List.map (fun x -> 0,x) (Array.to_list r.args))
in
if not res_bis
then
(res := false;
update_result symb (NotPositive r.name))
| _ -> failwith "Unexpected types"
) lneg;
)
si.rules;
!res
let is_mkable_pos : comp_cstr -> signature -> constr_graph -> bool =
fun (r,c,(i1,ti),(i2,tr)) si cst_gr ->
let cons = cst_gr.constructors in
let main = cst_gr.typ_cstr_order.tab in
let _,lneg = extract_constraints_of_typ (i1,ti) in
let res = ref true in
List.iter
( fun (i,t) ->
match t,tr with
| Const(_,f), Const(_,g)
| App(Const(_,f),_,_), Const(_,g) ->
let i_f = find_array f cons in
let i_g = find_array g cons in
let comp = main.(i_g).(i_f) in
if comp then
(res := false;
update_result
(IMap.find (find_symbol_index si c) si.symbols)
(NotPositive r))
| Const(_,f), App(Const(_,g),_,_) -> ()
| App(Const(_,f),t1,l1), App(Const(_,g),t2,l2) ->
let i_f = find_array f cons in
let i_g = find_array g cons in
let comp = main.(i_g).(i_f) in
if comp then
let res_bis =
comp_list
(List.map (fun x -> i,x) (t1::l1))
(List.map (fun x -> i2,x) (t2::l2))
in
if not res_bis
then
(res := false;
update_result
(IMap.find (find_symbol_index si c) si.symbols)
(NotPositive r))
| _ -> failwith "Unexpected types"
) lneg;
!res
let check_positivity : Callgraph.call_graph -> bool =
fun gr ->
let si = gr.signature in
let cst_gr = empty_cst_gr si.symbols in
let acc_name = ref [] in
IMap.iter
(fun _ r -> acc_name := (accessed r)::!acc_name)
si.rules;
let acc_bis = List.flatten !acc_name in
Debug.debug d_pos "Accessed variables are:@. - %a@."
(pp_list "\n - " (pp_triple Format.pp_print_string pp_name Format.pp_print_int))
acc_bis;
let acc = List.map (get_ith_arg_and_return si) acc_bis in
compute_main_order acc cst_gr;
main_order_type_level_rules gr cst_gr;
let cst_gr2 =
{cst_gr with
typ_cstr_order = Sizematrix.Bool_matrix.trans_clos cst_gr.typ_cstr_order}
in
Debug.debug d_pos "The main order is:@.";
Debug.debug_eval
d_pos
(fun () ->
let cons = cst_gr2.constructors in
let tab = cst_gr2.typ_cstr_order.tab in
let lg = Array.length cons in
for i=0 to lg -1 do
for j=0 to lg-1 do
if tab.(i).(j)
then
Format.printf " - %a≤%a@." pp_name cons.(i) pp_name cons.(j)
done;
done;
);
let res = ref true in
res := verify_pos_type_level_rules gr cst_gr2;
List.iter
(fun r ->
res:= !res && (is_mkable_pos r si cst_gr2)
) acc;
!res
|
eb5e941c540bb4aae4653606b73715de66d3783477d549be3b0cce4e331978f6 | djblue/portal | deploy.clj | (ns tasks.deploy
(:require [tasks.ci :refer [ci]]
[tasks.info :refer [options]]
[tasks.package :as pkg]
[tasks.tools :refer [*cwd* clj gradle npx]]))
(defn- deploy-vscode []
(binding [*cwd* "extension-vscode"]
(npx :vsce :publish)))
(defn- deploy-open-vsx []
(binding [*cwd* "extension-vscode"]
(npx :ovsx :publish)))
(defn deploy-intellij []
(binding [*cwd* "extension-intellij"]
(gradle :publishPlugin)))
(defn- deploy-clojars []
(clj "-X:deploy"
":installer" ":remote"
":artifact" (-> options :jar-file str pr-str)
":pom-file" (-> options pkg/pom-file str pr-str)))
(defn deploy []
(pkg/all)
(deploy-clojars)
(deploy-vscode)
(deploy-open-vsx)
(deploy-intellij))
(defn all
"Deploy all artifacts."
[]
(ci)
(deploy))
(defn -main [] (deploy))
| null | https://raw.githubusercontent.com/djblue/portal/509a606f057cc4abff435aa78e49b2a6877903f9/dev/tasks/deploy.clj | clojure | (ns tasks.deploy
(:require [tasks.ci :refer [ci]]
[tasks.info :refer [options]]
[tasks.package :as pkg]
[tasks.tools :refer [*cwd* clj gradle npx]]))
(defn- deploy-vscode []
(binding [*cwd* "extension-vscode"]
(npx :vsce :publish)))
(defn- deploy-open-vsx []
(binding [*cwd* "extension-vscode"]
(npx :ovsx :publish)))
(defn deploy-intellij []
(binding [*cwd* "extension-intellij"]
(gradle :publishPlugin)))
(defn- deploy-clojars []
(clj "-X:deploy"
":installer" ":remote"
":artifact" (-> options :jar-file str pr-str)
":pom-file" (-> options pkg/pom-file str pr-str)))
(defn deploy []
(pkg/all)
(deploy-clojars)
(deploy-vscode)
(deploy-open-vsx)
(deploy-intellij))
(defn all
"Deploy all artifacts."
[]
(ci)
(deploy))
(defn -main [] (deploy))
|
|
eb07914944bd8b13207082d554ec2d5ee679c360ee975251936b059ddf764378 | antoniogarrote/clj-s4 | core.clj | (ns sampleapp.test.core
(:use [sampleapp.core] :reload)
(:use [clojure.test]))
(deftest replace-me ;; FIXME: write
(is false "No tests have been written."))
| null | https://raw.githubusercontent.com/antoniogarrote/clj-s4/5d41b327682a532e4ed4672a139676adbc775714/sampleapps/random-numbers/test/sampleapp/test/core.clj | clojure | FIXME: write | (ns sampleapp.test.core
(:use [sampleapp.core] :reload)
(:use [clojure.test]))
(is false "No tests have been written."))
|
7648edefb379ded033bb646be76bf4ce18a05df05e031cfe0c3435d0429ed243 | wh5a/thih | HaskellList.hs | -- Automatically generated typing assumptions for List
module HaskellList where
import Testbed
import StaticList
defnsHaskellList
= ["findIndices" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList tInt)),
"findIndex" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tMaybe tInt)),
"elemIndex" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tMaybe tInt)),
"elemIndices" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList tInt)),
"find" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tMaybe (TGen 0))),
"nubBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"nub" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"deleteBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"delete" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"\\\\" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"deleteFirstsBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"unionBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"union" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"intersectBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"intersect" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"intersperse" :>:
Forall [Star]
([] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"transpose" :>:
Forall [Star]
([] :=>
(TAp tList (TAp tList (TGen 0)) `fn` TAp tList (TAp tList (TGen 0)))),
"partition" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp (TAp tTuple2 (TAp tList (TGen 0))) (TAp tList (TGen 0)))),
"groupBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TAp tList (TGen 0)))),
"group" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TAp tList (TGen 0)))),
"inits" :>:
Forall [Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TAp tList (TGen 0)))),
"tails" :>:
Forall [Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TAp tList (TGen 0)))),
"isPrefixOf" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` tBool)),
"isSuffixOf" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` tBool)),
"mapAccumL" :>:
Forall [Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TAp (TAp tTuple2 (TGen 0)) (TGen 2)) `fn` TGen 0 `fn` TAp tList (TGen 1) `fn` TAp (TAp tTuple2 (TGen 0)) (TAp tList (TGen 2)))),
"mapAccumR" :>:
Forall [Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TAp (TAp tTuple2 (TGen 0)) (TGen 2)) `fn` TGen 0 `fn` TAp tList (TGen 1) `fn` TAp (TAp tTuple2 (TGen 0)) (TAp tList (TGen 2)))),
"unfoldr" :>:
Forall [Star, Star]
([] :=>
((TGen 0 `fn` TAp tMaybe (TAp (TAp tTuple2 (TGen 1)) (TGen 0))) `fn` TGen 0 `fn` TAp tList (TGen 1))),
"insertBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tOrdering) `fn` TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"sortBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tOrdering) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"sort" :>:
Forall [Star]
([isIn1 cOrd (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"insert" :>:
Forall [Star]
([isIn1 cOrd (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"maximumBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` TGen 0) `fn` TAp tList (TGen 0) `fn` TGen 0)),
"minimumBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` TGen 0) `fn` TAp tList (TGen 0) `fn` TGen 0)),
"genericLength" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TAp tList (TGen 1) `fn` TGen 0)),
"genericTake" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 1))),
"genericDrop" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 1))),
"genericSplitAt" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 1) `fn` TAp (TAp tTuple2 (TAp tList (TGen 1))) (TAp tList (TGen 1)))),
"genericIndex" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TAp tList (TGen 1) `fn` TGen 0 `fn` TGen 1)),
"genericReplicate" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TGen 0 `fn` TGen 1 `fn` TAp tList (TGen 1))),
"zipWith4" :>:
Forall [Star, Star, Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TGen 2 `fn` TGen 3 `fn` TGen 4) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4))),
"zip4" :>:
Forall [Star, Star, Star, Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TAp (TAp (TAp (TAp tTuple4 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)))),
"zipWith5" :>:
Forall [Star, Star, Star, Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TGen 2 `fn` TGen 3 `fn` TGen 4 `fn` TGen 5) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5))),
"zip5" :>:
Forall [Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TAp (TAp (TAp (TAp (TAp tTuple5 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)))),
"zipWith6" :>:
Forall [Star, Star, Star, Star, Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TGen 2 `fn` TGen 3 `fn` TGen 4 `fn` TGen 5 `fn` TGen 6) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5) `fn` TAp tList (TGen 6))),
"zip6" :>:
Forall [Star, Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5) `fn` TAp tList (TAp (TAp (TAp (TAp (TAp (TAp tTuple6 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) (TGen 5)))),
"zipWith7" :>:
Forall [Star, Star, Star, Star, Star, Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TGen 2 `fn` TGen 3 `fn` TGen 4 `fn` TGen 5 `fn` TGen 6 `fn` TGen 7) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5) `fn` TAp tList (TGen 6) `fn` TAp tList (TGen 7))),
"zip7" :>:
Forall [Star, Star, Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5) `fn` TAp tList (TGen 6) `fn` TAp tList (TAp (TAp (TAp (TAp (TAp (TAp (TAp tTuple7 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) (TGen 5)) (TGen 6)))),
"unzip4" :>:
Forall [Star, Star, Star, Star]
([] :=>
(TAp tList (TAp (TAp (TAp (TAp tTuple4 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) `fn` TAp (TAp (TAp (TAp tTuple4 (TAp tList (TGen 0))) (TAp tList (TGen 1))) (TAp tList (TGen 2))) (TAp tList (TGen 3)))),
"unzip5" :>:
Forall [Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TAp (TAp (TAp (TAp (TAp tTuple5 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) `fn` TAp (TAp (TAp (TAp (TAp tTuple5 (TAp tList (TGen 0))) (TAp tList (TGen 1))) (TAp tList (TGen 2))) (TAp tList (TGen 3))) (TAp tList (TGen 4)))),
"unzip6" :>:
Forall [Star, Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TAp (TAp (TAp (TAp (TAp (TAp tTuple6 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) (TGen 5)) `fn` TAp (TAp (TAp (TAp (TAp (TAp tTuple6 (TAp tList (TGen 0))) (TAp tList (TGen 1))) (TAp tList (TGen 2))) (TAp tList (TGen 3))) (TAp tList (TGen 4))) (TAp tList (TGen 5)))),
"unzip7" :>:
Forall [Star, Star, Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TAp (TAp (TAp (TAp (TAp (TAp (TAp tTuple7 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) (TGen 5)) (TGen 6)) `fn` TAp (TAp (TAp (TAp (TAp (TAp (TAp tTuple7 (TAp tList (TGen 0))) (TAp tList (TGen 1))) (TAp tList (TGen 2))) (TAp tList (TGen 3))) (TAp tList (TGen 4))) (TAp tList (TGen 5))) (TAp tList (TGen 6))))]
| null | https://raw.githubusercontent.com/wh5a/thih/dc5cb16ba4e998097135beb0c7b0b416cac7bfae/src/HaskellList.hs | haskell | Automatically generated typing assumptions for List
|
module HaskellList where
import Testbed
import StaticList
defnsHaskellList
= ["findIndices" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList tInt)),
"findIndex" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tMaybe tInt)),
"elemIndex" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tMaybe tInt)),
"elemIndices" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList tInt)),
"find" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tMaybe (TGen 0))),
"nubBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"nub" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"deleteBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"delete" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"\\\\" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"deleteFirstsBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"unionBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"union" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"intersectBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"intersect" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"intersperse" :>:
Forall [Star]
([] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"transpose" :>:
Forall [Star]
([] :=>
(TAp tList (TAp tList (TGen 0)) `fn` TAp tList (TAp tList (TGen 0)))),
"partition" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp (TAp tTuple2 (TAp tList (TGen 0))) (TAp tList (TGen 0)))),
"groupBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tBool) `fn` TAp tList (TGen 0) `fn` TAp tList (TAp tList (TGen 0)))),
"group" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TAp tList (TGen 0)))),
"inits" :>:
Forall [Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TAp tList (TGen 0)))),
"tails" :>:
Forall [Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TAp tList (TGen 0)))),
"isPrefixOf" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` tBool)),
"isSuffixOf" :>:
Forall [Star]
([isIn1 cEq (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0) `fn` tBool)),
"mapAccumL" :>:
Forall [Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TAp (TAp tTuple2 (TGen 0)) (TGen 2)) `fn` TGen 0 `fn` TAp tList (TGen 1) `fn` TAp (TAp tTuple2 (TGen 0)) (TAp tList (TGen 2)))),
"mapAccumR" :>:
Forall [Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TAp (TAp tTuple2 (TGen 0)) (TGen 2)) `fn` TGen 0 `fn` TAp tList (TGen 1) `fn` TAp (TAp tTuple2 (TGen 0)) (TAp tList (TGen 2)))),
"unfoldr" :>:
Forall [Star, Star]
([] :=>
((TGen 0 `fn` TAp tMaybe (TAp (TAp tTuple2 (TGen 1)) (TGen 0))) `fn` TGen 0 `fn` TAp tList (TGen 1))),
"insertBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tOrdering) `fn` TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"sortBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` tOrdering) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"sort" :>:
Forall [Star]
([isIn1 cOrd (TGen 0)] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"insert" :>:
Forall [Star]
([isIn1 cOrd (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 0))),
"maximumBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` TGen 0) `fn` TAp tList (TGen 0) `fn` TGen 0)),
"minimumBy" :>:
Forall [Star]
([] :=>
((TGen 0 `fn` TGen 0 `fn` TGen 0) `fn` TAp tList (TGen 0) `fn` TGen 0)),
"genericLength" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TAp tList (TGen 1) `fn` TGen 0)),
"genericTake" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 1))),
"genericDrop" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 1))),
"genericSplitAt" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TGen 0 `fn` TAp tList (TGen 1) `fn` TAp (TAp tTuple2 (TAp tList (TGen 1))) (TAp tList (TGen 1)))),
"genericIndex" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TAp tList (TGen 1) `fn` TGen 0 `fn` TGen 1)),
"genericReplicate" :>:
Forall [Star, Star]
([isIn1 cIntegral (TGen 0)] :=>
(TGen 0 `fn` TGen 1 `fn` TAp tList (TGen 1))),
"zipWith4" :>:
Forall [Star, Star, Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TGen 2 `fn` TGen 3 `fn` TGen 4) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4))),
"zip4" :>:
Forall [Star, Star, Star, Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TAp (TAp (TAp (TAp tTuple4 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)))),
"zipWith5" :>:
Forall [Star, Star, Star, Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TGen 2 `fn` TGen 3 `fn` TGen 4 `fn` TGen 5) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5))),
"zip5" :>:
Forall [Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TAp (TAp (TAp (TAp (TAp tTuple5 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)))),
"zipWith6" :>:
Forall [Star, Star, Star, Star, Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TGen 2 `fn` TGen 3 `fn` TGen 4 `fn` TGen 5 `fn` TGen 6) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5) `fn` TAp tList (TGen 6))),
"zip6" :>:
Forall [Star, Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5) `fn` TAp tList (TAp (TAp (TAp (TAp (TAp (TAp tTuple6 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) (TGen 5)))),
"zipWith7" :>:
Forall [Star, Star, Star, Star, Star, Star, Star, Star]
([] :=>
((TGen 0 `fn` TGen 1 `fn` TGen 2 `fn` TGen 3 `fn` TGen 4 `fn` TGen 5 `fn` TGen 6 `fn` TGen 7) `fn` TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5) `fn` TAp tList (TGen 6) `fn` TAp tList (TGen 7))),
"zip7" :>:
Forall [Star, Star, Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TGen 0) `fn` TAp tList (TGen 1) `fn` TAp tList (TGen 2) `fn` TAp tList (TGen 3) `fn` TAp tList (TGen 4) `fn` TAp tList (TGen 5) `fn` TAp tList (TGen 6) `fn` TAp tList (TAp (TAp (TAp (TAp (TAp (TAp (TAp tTuple7 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) (TGen 5)) (TGen 6)))),
"unzip4" :>:
Forall [Star, Star, Star, Star]
([] :=>
(TAp tList (TAp (TAp (TAp (TAp tTuple4 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) `fn` TAp (TAp (TAp (TAp tTuple4 (TAp tList (TGen 0))) (TAp tList (TGen 1))) (TAp tList (TGen 2))) (TAp tList (TGen 3)))),
"unzip5" :>:
Forall [Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TAp (TAp (TAp (TAp (TAp tTuple5 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) `fn` TAp (TAp (TAp (TAp (TAp tTuple5 (TAp tList (TGen 0))) (TAp tList (TGen 1))) (TAp tList (TGen 2))) (TAp tList (TGen 3))) (TAp tList (TGen 4)))),
"unzip6" :>:
Forall [Star, Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TAp (TAp (TAp (TAp (TAp (TAp tTuple6 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) (TGen 5)) `fn` TAp (TAp (TAp (TAp (TAp (TAp tTuple6 (TAp tList (TGen 0))) (TAp tList (TGen 1))) (TAp tList (TGen 2))) (TAp tList (TGen 3))) (TAp tList (TGen 4))) (TAp tList (TGen 5)))),
"unzip7" :>:
Forall [Star, Star, Star, Star, Star, Star, Star]
([] :=>
(TAp tList (TAp (TAp (TAp (TAp (TAp (TAp (TAp tTuple7 (TGen 0)) (TGen 1)) (TGen 2)) (TGen 3)) (TGen 4)) (TGen 5)) (TGen 6)) `fn` TAp (TAp (TAp (TAp (TAp (TAp (TAp tTuple7 (TAp tList (TGen 0))) (TAp tList (TGen 1))) (TAp tList (TGen 2))) (TAp tList (TGen 3))) (TAp tList (TGen 4))) (TAp tList (TGen 5))) (TAp tList (TGen 6))))]
|
d347b07e307fee4612ffc3b13a8804e2f711b836dc0090abe354b41f3431465b | wz1000/hie-lsp | Profiled.hs | {-# LANGUAGE EmptyDataDecls #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
-- |
-- Module:
Reflex . Profiled
-- Description:
This module contains an instance of the ' Reflex ' class that provides
-- profiling/cost-center information.
module Reflex.Profiled where
import Control.Lens hiding (children)
import Control.Monad
import Control.Monad.Exception
import Control.Monad.Fix
import Control.Monad.Primitive
import Control.Monad.Reader
import Control.Monad.Ref
import Control.Monad.State.Strict (StateT, execStateT, modify)
import Data.Coerce
import Data.Dependent.Map (DMap, GCompare)
import Data.FastMutableIntMap
import Data.IORef
import Data.List
import Data.Map (Map)
import qualified Data.Map.Strict as Map
import Data.Monoid ((<>))
import Data.Ord
import qualified Data.Semigroup as S
import Data.Type.Coercion
import Foreign.Ptr
import GHC.Foreign
import GHC.IO.Encoding
import GHC.Stack
import Reflex.Class
import Reflex.Host.Class
import Reflex.PerformEvent.Class
import System.IO.Unsafe
import Unsafe.Coerce
data ProfiledTimeline t
# NOINLINE profilingData #
profilingData :: IORef (Map (Ptr CostCentreStack) Int)
profilingData = unsafePerformIO $ newIORef Map.empty
data CostCentreTree = CostCentreTree
{ _costCentreTree_ownEntries :: !Int
, _costCentreTree_cumulativeEntries :: !Int
, _costCentreTree_children :: !(Map (Ptr CostCentre) CostCentreTree)
}
deriving (Show, Eq, Ord)
instance S.Semigroup CostCentreTree where
(CostCentreTree oa ea ca) <> (CostCentreTree ob eb cb) =
CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb
instance Monoid CostCentreTree where
mempty = CostCentreTree 0 0 mempty
mappend = (S.<>)
getCostCentreStack :: Ptr CostCentreStack -> IO [Ptr CostCentre]
getCostCentreStack = go []
where go l ccs = if ccs == nullPtr
then return l
else do
cc <- ccsCC ccs
parent <- ccsParent ccs
go (cc : l) parent
toCostCentreTree :: Ptr CostCentreStack -> Int -> IO CostCentreTree
toCostCentreTree ccs n = do
ccList <- getCostCentreStack ccs
return $ foldr (\cc child -> CostCentreTree 0 n $ Map.singleton cc child) (CostCentreTree n n mempty) ccList
getCostCentreTree :: IO CostCentreTree
getCostCentreTree = do
vals <- readIORef profilingData
mconcat <$> mapM (uncurry toCostCentreTree) (Map.toList vals)
formatCostCentreTree :: CostCentreTree -> IO String
formatCostCentreTree cct0 = unlines . reverse <$> execStateT (go 0 cct0) []
where go :: Int -> CostCentreTree -> StateT [String] IO ()
go depth cct = do
let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct
indent = mconcat $ replicate depth " "
forM_ children $ \(cc, childCct) -> do
lbl <- liftIO $ peekCString utf8 =<< ccLabel cc
mdl <- liftIO $ peekCString utf8 =<< ccModule cc
loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc
let description = mdl <> "." <> lbl <> " (" <> loc <> ")"
modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)
go (succ depth) childCct
showProfilingData :: IO ()
showProfilingData = do
putStr =<< formatCostCentreTree =<< getCostCentreTree
writeProfilingData :: FilePath -> IO ()
writeProfilingData p = do
writeFile p =<< formatCostCentreTree =<< getCostCentreTree
newtype ProfiledM m a = ProfiledM { runProfiledM :: m a }
deriving (Functor, Applicative, Monad, MonadFix, MonadException, MonadAsyncException)
profileEvent :: Reflex t => Event t a -> Event t a
profileEvent e = unsafePerformIO $ do
stack <- getCurrentCCS e
let f x = unsafePerformIO $ do
modifyIORef' profilingData $ Map.insertWith (+) stack 1
return $ return $ Just x
return $ pushCheap f e
--TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs
instance Reflex t => Reflex (ProfiledTimeline t) where
newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled { unBehavior_Profiled :: Behavior t a }
newtype Event (ProfiledTimeline t) a = Event_Profiled { unEvent_Profiled :: Event t a }
newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled { unDynamic_Profiled :: Dynamic t a }
newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled { unIncremental_Profiled :: Incremental t p }
type PushM (ProfiledTimeline t) = ProfiledM (PushM t)
type PullM (ProfiledTimeline t) = ProfiledM (PullM t)
never = Event_Profiled never
constant = Behavior_Profiled . constant
push f (Event_Profiled e) = coerce $ push (coerce f) $ profileEvent e -- Profile before rather than after; this way fanout won't count against us
pushCheap f (Event_Profiled e) = coerce $ pushCheap (coerce f) $ profileEvent e
pull = Behavior_Profiled . pull . coerce
merge :: forall k. GCompare k => DMap k (Event (ProfiledTimeline t)) -> Event (ProfiledTimeline t) (DMap k Identity)
merge = Event_Profiled . merge . (unsafeCoerce :: DMap k (Event (ProfiledTimeline t)) -> DMap k (Event t))
fanG (Event_Profiled e) = EventSelectorG $ coerce $ selectG (fanG $ profileEvent e)
switch (Behavior_Profiled b) = coerce $ profileEvent $ switch (coerceBehavior b)
coincidence (Event_Profiled e) = coerce $ profileEvent $ coincidence (coerceEvent e)
current (Dynamic_Profiled d) = coerce $ current d
updated (Dynamic_Profiled d) = coerce $ profileEvent $ updated d
unsafeBuildDynamic (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildDynamic a0 a'
unsafeBuildIncremental (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildIncremental a0 a'
mergeIncremental = Event_Profiled . mergeIncremental . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchDMap k (Event (ProfiledTimeline t))) -> Incremental t (PatchDMap k (Event t)))
mergeIncrementalWithMove = Event_Profiled . mergeIncrementalWithMove . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchDMapWithMove k (Event (ProfiledTimeline t))) -> Incremental t (PatchDMapWithMove k (Event t)))
currentIncremental (Incremental_Profiled i) = coerce $ currentIncremental i
updatedIncremental (Incremental_Profiled i) = coerce $ profileEvent $ updatedIncremental i
incrementalToDynamic (Incremental_Profiled i) = coerce $ incrementalToDynamic i
behaviorCoercion (c :: Coercion a b) = case behaviorCoercion c :: Coercion (Behavior t a) (Behavior t b) of
TODO : Figure out how to make this typecheck without the unsafeCoerce
eventCoercion (c :: Coercion a b) = case eventCoercion c :: Coercion (Event t a) (Event t b) of
TODO : Figure out how to make this typecheck without the unsafeCoerce
dynamicCoercion (c :: Coercion a b) = case dynamicCoercion c :: Coercion (Dynamic t a) (Dynamic t b) of
TODO : Figure out how to make this typecheck without the unsafeCoerce
mergeIntIncremental = Event_Profiled . mergeIntIncremental . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchIntMap (Event (ProfiledTimeline t) a)) -> Incremental t (PatchIntMap (Event t a)))
fanInt (Event_Profiled e) = coerce $ fanInt $ profileEvent e
deriving instance Functor (Dynamic t) => Functor (Dynamic (ProfiledTimeline t))
deriving instance Applicative (Dynamic t) => Applicative (Dynamic (ProfiledTimeline t))
deriving instance Monad (Dynamic t) => Monad (Dynamic (ProfiledTimeline t))
instance MonadHold t m => MonadHold (ProfiledTimeline t) (ProfiledM m) where
hold v0 (Event_Profiled v') = ProfiledM $ Behavior_Profiled <$> hold v0 v'
holdDyn v0 (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> holdDyn v0 v'
holdIncremental v0 (Event_Profiled v') = ProfiledM $ Incremental_Profiled <$> holdIncremental v0 v'
buildDynamic (ProfiledM v0) (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> buildDynamic v0 v'
headE (Event_Profiled e) = ProfiledM $ Event_Profiled <$> headE e
instance MonadSample t m => MonadSample (ProfiledTimeline t) (ProfiledM m) where
sample (Behavior_Profiled b) = ProfiledM $ sample b
instance MonadTrans ProfiledM where
lift = ProfiledM
instance MonadIO m => MonadIO (ProfiledM m) where
liftIO = lift . liftIO
instance PerformEvent t m => PerformEvent (ProfiledTimeline t) (ProfiledM m) where
type Performable (ProfiledM m) = Performable m
performEvent_ = lift . performEvent_ . coerce
performEvent = lift . fmap coerce . performEvent . coerce
instance MonadRef m => MonadRef (ProfiledM m) where
type Ref (ProfiledM m) = Ref m
newRef = lift . newRef
readRef = lift . readRef
writeRef r = lift . writeRef r
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger (ProfiledTimeline t) (ProfiledM m) where
newEventWithTrigger = lift . fmap coerce . newEventWithTrigger
newFanEventWithTrigger f = do
es <- lift $ newFanEventWithTrigger f
return $ EventSelector $ \k -> coerce $ select es k
instance MonadReader r m => MonadReader r (ProfiledM m) where
ask = lift ask
local f (ProfiledM a) = ProfiledM $ local f a
reader = lift . reader
instance ReflexHost t => ReflexHost (ProfiledTimeline t) where
type EventTrigger (ProfiledTimeline t) = EventTrigger t
type EventHandle (ProfiledTimeline t) = EventHandle t
type HostFrame (ProfiledTimeline t) = ProfiledM (HostFrame t)
instance MonadSubscribeEvent t m => MonadSubscribeEvent (ProfiledTimeline t) (ProfiledM m) where
subscribeEvent = lift . subscribeEvent . coerce
instance PrimMonad m => PrimMonad (ProfiledM m) where
type PrimState (ProfiledM m) = PrimState m
primitive = lift . primitive
instance MonadReflexHost t m => MonadReflexHost (ProfiledTimeline t) (ProfiledM m) where
type ReadPhase (ProfiledM m) = ProfiledM (ReadPhase m)
fireEventsAndRead ts r = lift $ fireEventsAndRead ts $ coerce r
runHostFrame = lift . runHostFrame . coerce
instance MonadReadEvent t m => MonadReadEvent (ProfiledTimeline t) (ProfiledM m) where
readEvent = lift . fmap coerce . readEvent
| null | https://raw.githubusercontent.com/wz1000/hie-lsp/dbb3caa97c0acbff0e4fd86fc46eeea748f65e89/reflex-0.6.1/src/Reflex/Profiled.hs | haskell | # LANGUAGE EmptyDataDecls #
|
Module:
Description:
profiling/cost-center information.
TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs
Profile before rather than after; this way fanout won't count against us | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
Reflex . Profiled
This module contains an instance of the ' Reflex ' class that provides
module Reflex.Profiled where
import Control.Lens hiding (children)
import Control.Monad
import Control.Monad.Exception
import Control.Monad.Fix
import Control.Monad.Primitive
import Control.Monad.Reader
import Control.Monad.Ref
import Control.Monad.State.Strict (StateT, execStateT, modify)
import Data.Coerce
import Data.Dependent.Map (DMap, GCompare)
import Data.FastMutableIntMap
import Data.IORef
import Data.List
import Data.Map (Map)
import qualified Data.Map.Strict as Map
import Data.Monoid ((<>))
import Data.Ord
import qualified Data.Semigroup as S
import Data.Type.Coercion
import Foreign.Ptr
import GHC.Foreign
import GHC.IO.Encoding
import GHC.Stack
import Reflex.Class
import Reflex.Host.Class
import Reflex.PerformEvent.Class
import System.IO.Unsafe
import Unsafe.Coerce
data ProfiledTimeline t
# NOINLINE profilingData #
profilingData :: IORef (Map (Ptr CostCentreStack) Int)
profilingData = unsafePerformIO $ newIORef Map.empty
data CostCentreTree = CostCentreTree
{ _costCentreTree_ownEntries :: !Int
, _costCentreTree_cumulativeEntries :: !Int
, _costCentreTree_children :: !(Map (Ptr CostCentre) CostCentreTree)
}
deriving (Show, Eq, Ord)
instance S.Semigroup CostCentreTree where
(CostCentreTree oa ea ca) <> (CostCentreTree ob eb cb) =
CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb
instance Monoid CostCentreTree where
mempty = CostCentreTree 0 0 mempty
mappend = (S.<>)
getCostCentreStack :: Ptr CostCentreStack -> IO [Ptr CostCentre]
getCostCentreStack = go []
where go l ccs = if ccs == nullPtr
then return l
else do
cc <- ccsCC ccs
parent <- ccsParent ccs
go (cc : l) parent
toCostCentreTree :: Ptr CostCentreStack -> Int -> IO CostCentreTree
toCostCentreTree ccs n = do
ccList <- getCostCentreStack ccs
return $ foldr (\cc child -> CostCentreTree 0 n $ Map.singleton cc child) (CostCentreTree n n mempty) ccList
getCostCentreTree :: IO CostCentreTree
getCostCentreTree = do
vals <- readIORef profilingData
mconcat <$> mapM (uncurry toCostCentreTree) (Map.toList vals)
formatCostCentreTree :: CostCentreTree -> IO String
formatCostCentreTree cct0 = unlines . reverse <$> execStateT (go 0 cct0) []
where go :: Int -> CostCentreTree -> StateT [String] IO ()
go depth cct = do
let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct
indent = mconcat $ replicate depth " "
forM_ children $ \(cc, childCct) -> do
lbl <- liftIO $ peekCString utf8 =<< ccLabel cc
mdl <- liftIO $ peekCString utf8 =<< ccModule cc
loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc
let description = mdl <> "." <> lbl <> " (" <> loc <> ")"
modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)
go (succ depth) childCct
showProfilingData :: IO ()
showProfilingData = do
putStr =<< formatCostCentreTree =<< getCostCentreTree
writeProfilingData :: FilePath -> IO ()
writeProfilingData p = do
writeFile p =<< formatCostCentreTree =<< getCostCentreTree
newtype ProfiledM m a = ProfiledM { runProfiledM :: m a }
deriving (Functor, Applicative, Monad, MonadFix, MonadException, MonadAsyncException)
profileEvent :: Reflex t => Event t a -> Event t a
profileEvent e = unsafePerformIO $ do
stack <- getCurrentCCS e
let f x = unsafePerformIO $ do
modifyIORef' profilingData $ Map.insertWith (+) stack 1
return $ return $ Just x
return $ pushCheap f e
instance Reflex t => Reflex (ProfiledTimeline t) where
newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled { unBehavior_Profiled :: Behavior t a }
newtype Event (ProfiledTimeline t) a = Event_Profiled { unEvent_Profiled :: Event t a }
newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled { unDynamic_Profiled :: Dynamic t a }
newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled { unIncremental_Profiled :: Incremental t p }
type PushM (ProfiledTimeline t) = ProfiledM (PushM t)
type PullM (ProfiledTimeline t) = ProfiledM (PullM t)
never = Event_Profiled never
constant = Behavior_Profiled . constant
pushCheap f (Event_Profiled e) = coerce $ pushCheap (coerce f) $ profileEvent e
pull = Behavior_Profiled . pull . coerce
merge :: forall k. GCompare k => DMap k (Event (ProfiledTimeline t)) -> Event (ProfiledTimeline t) (DMap k Identity)
merge = Event_Profiled . merge . (unsafeCoerce :: DMap k (Event (ProfiledTimeline t)) -> DMap k (Event t))
fanG (Event_Profiled e) = EventSelectorG $ coerce $ selectG (fanG $ profileEvent e)
switch (Behavior_Profiled b) = coerce $ profileEvent $ switch (coerceBehavior b)
coincidence (Event_Profiled e) = coerce $ profileEvent $ coincidence (coerceEvent e)
current (Dynamic_Profiled d) = coerce $ current d
updated (Dynamic_Profiled d) = coerce $ profileEvent $ updated d
unsafeBuildDynamic (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildDynamic a0 a'
unsafeBuildIncremental (ProfiledM a0) (Event_Profiled a') = coerce $ unsafeBuildIncremental a0 a'
mergeIncremental = Event_Profiled . mergeIncremental . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchDMap k (Event (ProfiledTimeline t))) -> Incremental t (PatchDMap k (Event t)))
mergeIncrementalWithMove = Event_Profiled . mergeIncrementalWithMove . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchDMapWithMove k (Event (ProfiledTimeline t))) -> Incremental t (PatchDMapWithMove k (Event t)))
currentIncremental (Incremental_Profiled i) = coerce $ currentIncremental i
updatedIncremental (Incremental_Profiled i) = coerce $ profileEvent $ updatedIncremental i
incrementalToDynamic (Incremental_Profiled i) = coerce $ incrementalToDynamic i
behaviorCoercion (c :: Coercion a b) = case behaviorCoercion c :: Coercion (Behavior t a) (Behavior t b) of
TODO : Figure out how to make this typecheck without the unsafeCoerce
eventCoercion (c :: Coercion a b) = case eventCoercion c :: Coercion (Event t a) (Event t b) of
TODO : Figure out how to make this typecheck without the unsafeCoerce
dynamicCoercion (c :: Coercion a b) = case dynamicCoercion c :: Coercion (Dynamic t a) (Dynamic t b) of
TODO : Figure out how to make this typecheck without the unsafeCoerce
mergeIntIncremental = Event_Profiled . mergeIntIncremental . (unsafeCoerce :: Incremental (ProfiledTimeline t) (PatchIntMap (Event (ProfiledTimeline t) a)) -> Incremental t (PatchIntMap (Event t a)))
fanInt (Event_Profiled e) = coerce $ fanInt $ profileEvent e
deriving instance Functor (Dynamic t) => Functor (Dynamic (ProfiledTimeline t))
deriving instance Applicative (Dynamic t) => Applicative (Dynamic (ProfiledTimeline t))
deriving instance Monad (Dynamic t) => Monad (Dynamic (ProfiledTimeline t))
instance MonadHold t m => MonadHold (ProfiledTimeline t) (ProfiledM m) where
hold v0 (Event_Profiled v') = ProfiledM $ Behavior_Profiled <$> hold v0 v'
holdDyn v0 (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> holdDyn v0 v'
holdIncremental v0 (Event_Profiled v') = ProfiledM $ Incremental_Profiled <$> holdIncremental v0 v'
buildDynamic (ProfiledM v0) (Event_Profiled v') = ProfiledM $ Dynamic_Profiled <$> buildDynamic v0 v'
headE (Event_Profiled e) = ProfiledM $ Event_Profiled <$> headE e
instance MonadSample t m => MonadSample (ProfiledTimeline t) (ProfiledM m) where
sample (Behavior_Profiled b) = ProfiledM $ sample b
instance MonadTrans ProfiledM where
lift = ProfiledM
instance MonadIO m => MonadIO (ProfiledM m) where
liftIO = lift . liftIO
instance PerformEvent t m => PerformEvent (ProfiledTimeline t) (ProfiledM m) where
type Performable (ProfiledM m) = Performable m
performEvent_ = lift . performEvent_ . coerce
performEvent = lift . fmap coerce . performEvent . coerce
instance MonadRef m => MonadRef (ProfiledM m) where
type Ref (ProfiledM m) = Ref m
newRef = lift . newRef
readRef = lift . readRef
writeRef r = lift . writeRef r
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger (ProfiledTimeline t) (ProfiledM m) where
newEventWithTrigger = lift . fmap coerce . newEventWithTrigger
newFanEventWithTrigger f = do
es <- lift $ newFanEventWithTrigger f
return $ EventSelector $ \k -> coerce $ select es k
instance MonadReader r m => MonadReader r (ProfiledM m) where
ask = lift ask
local f (ProfiledM a) = ProfiledM $ local f a
reader = lift . reader
instance ReflexHost t => ReflexHost (ProfiledTimeline t) where
type EventTrigger (ProfiledTimeline t) = EventTrigger t
type EventHandle (ProfiledTimeline t) = EventHandle t
type HostFrame (ProfiledTimeline t) = ProfiledM (HostFrame t)
instance MonadSubscribeEvent t m => MonadSubscribeEvent (ProfiledTimeline t) (ProfiledM m) where
subscribeEvent = lift . subscribeEvent . coerce
instance PrimMonad m => PrimMonad (ProfiledM m) where
type PrimState (ProfiledM m) = PrimState m
primitive = lift . primitive
instance MonadReflexHost t m => MonadReflexHost (ProfiledTimeline t) (ProfiledM m) where
type ReadPhase (ProfiledM m) = ProfiledM (ReadPhase m)
fireEventsAndRead ts r = lift $ fireEventsAndRead ts $ coerce r
runHostFrame = lift . runHostFrame . coerce
instance MonadReadEvent t m => MonadReadEvent (ProfiledTimeline t) (ProfiledM m) where
readEvent = lift . fmap coerce . readEvent
|
52d8fff3730e7d0f01c1c2e43e5414dae298b5ee6c64b6c1cf03616d272207f0 | babashka/babashka | paths_test.cljc | (ns expound.paths-test
(:require [clojure.test :as ct :refer [is deftest use-fixtures]]
[clojure.test.check.generators :as gen]
[com.gfredericks.test.chuck.clojure-test :refer [checking]]
[expound.paths :as paths]
[expound.test-utils :as test-utils]
[com.gfredericks.test.chuck :as chuck]))
(def num-tests 100)
(use-fixtures :once
test-utils/check-spec-assertions
test-utils/instrument-all)
(deftest compare-paths-test
(checking
"path to a key comes before a path to a value"
10
[k gen/simple-type-printable]
(is (= -1 (paths/compare-paths [(paths/->KeyPathSegment k)] [k])))
(is (= 1 (paths/compare-paths [k] [(paths/->KeyPathSegment k)])))))
(defn nth-value [form i]
(let [seq (remove map-entry? (tree-seq coll? seq form))]
(nth seq (mod i (count seq)))))
(deftest paths-to-value-test
(checking
"value-in is inverse of paths-to-value"
(chuck/times num-tests)
[form test-utils/any-printable-wo-nan
i gen/nat
:let [x (nth-value form i)
paths (paths/paths-to-value form x [] [])]]
(is (seq paths))
(doseq [path paths]
(is (= x
(paths/value-in form
path))))))
| null | https://raw.githubusercontent.com/babashka/babashka/665ae4dd97535bf72a5ce34a19d624e74e5c4fe8/test-resources/lib_tests/expound/paths_test.cljc | clojure | (ns expound.paths-test
(:require [clojure.test :as ct :refer [is deftest use-fixtures]]
[clojure.test.check.generators :as gen]
[com.gfredericks.test.chuck.clojure-test :refer [checking]]
[expound.paths :as paths]
[expound.test-utils :as test-utils]
[com.gfredericks.test.chuck :as chuck]))
(def num-tests 100)
(use-fixtures :once
test-utils/check-spec-assertions
test-utils/instrument-all)
(deftest compare-paths-test
(checking
"path to a key comes before a path to a value"
10
[k gen/simple-type-printable]
(is (= -1 (paths/compare-paths [(paths/->KeyPathSegment k)] [k])))
(is (= 1 (paths/compare-paths [k] [(paths/->KeyPathSegment k)])))))
(defn nth-value [form i]
(let [seq (remove map-entry? (tree-seq coll? seq form))]
(nth seq (mod i (count seq)))))
(deftest paths-to-value-test
(checking
"value-in is inverse of paths-to-value"
(chuck/times num-tests)
[form test-utils/any-printable-wo-nan
i gen/nat
:let [x (nth-value form i)
paths (paths/paths-to-value form x [] [])]]
(is (seq paths))
(doseq [path paths]
(is (= x
(paths/value-in form
path))))))
|
|
f84e4aaf7680bd5b58d6abc0bb81b604e8326ba6479d499293129c47494f664e | originrose/cortex | optimisers_test.clj | (ns cortex.optimise.optimisers-test
(:refer-clojure :exclude [+ - * /])
(:require [clojure.core.matrix.operators :refer [+ - * /]]
[clojure.test :refer :all]
[cortex.optimise.optimisers :refer :all]
[cortex.optimise.protocols :as cp]
[cortex.util :refer [approx= def-]]))
Protocol extensions
(def- test-optimiser-map
{:initialize (fn [param-count]
{:velocity (vec (repeat param-count 0))})
:update (fn [{:keys [params velocity]} gradient]
{:params (+ params velocity)
:velocity (+ velocity gradient)})})
(def- test-optimiser-fn
(fn [params gradient]
(+ params gradient)))
(deftest protocol-extension-test
(testing "map as optimiser"
(is (= (->> test-optimiser-map
(iterate #(cp/compute-parameters % [1 2 3] (or (cp/parameters %)
[0 0 0])))
(map (juxt cp/parameters cp/get-state))
(rest)
(take 3))
[[[0 0 0] {:velocity [1 2 3]}]
[[1 2 3] {:velocity [2 4 6]}]
[[3 6 9] {:velocity [3 6 9]}]])))
(testing "fn as optimiser"
(is (= (->> test-optimiser-fn
(iterate #(cp/compute-parameters % [1 2 3] (or (cp/parameters %)
[0 0 0])))
(map (juxt cp/parameters cp/get-state))
(rest)
(take 3))
[[[1 2 3] {}]
[[2 4 6] {}]
[[3 6 9] {}]]))))
Clojure implementations
;;; Ideally, there would be a standard way to mutate the internal state of an
;;; optimiser, so that this code didn't have to rely on optimisers being of
;;; particular types. But since they are maps, it's easy to do the mutation
;;; directly, using assoc.
(deftest sgd-clojure-test
(is (= (-> (sgd-clojure :learning-rate 5)
(cp/compute-parameters [2 4 8] [1 2 3])
((juxt cp/parameters cp/get-state)))
[[-9 -18 -37] {}])))
(deftest adadelta-clojure-test
(is (approx= 1e-8
(-> (adadelta-clojure :decay-rate 0.5
:conditioning 1)
(assoc-in [:state :acc-gradient] [6 3 9])
(assoc-in [:state :acc-step] [7 8 7])
(dissoc :initialize)
(cp/compute-parameters [2 4 8] [1 2 3])
((juxt cp/parameters cp/get-state)))
;; The following was computed manually using a calculator.
[[-1.309401077 -1.703280399 -0.6950417228]
{:acc-gradient [5.0 9.5 36.5]
:acc-step [6.166666667 10.85714286 10.32666667]}])))
(deftest adam-clojure-test
(is (approx= 1e-8
(-> (adam-clojure :step-size 5
:first-moment-decay 0.75
:second-moment-decay 0.3
:conditioning 0.2)
(assoc-in [:state :first-moment] [5 2 -3])
(assoc-in [:state :second-moment] [-1 -3 -8])
(assoc-in [:state :num-steps] 2)
(dissoc :initialize)
(cp/compute-parameters [5 3 7] [1 2 -5])
((juxt cp/parameters cp/get-state)))
;; The following was computed manually using a calculator.
[[-8.81811015 -5.613809809 -4.270259223]
{:first-moment [5.0 2.25 -0.5]
:second-moment [17.2 5.4 31.9]
:num-steps 3}])))
| null | https://raw.githubusercontent.com/originrose/cortex/94b1430538e6187f3dfd1697c36ff2c62b475901/examples/optimise/test/cortex/optimise/optimisers_test.clj | clojure | Ideally, there would be a standard way to mutate the internal state of an
optimiser, so that this code didn't have to rely on optimisers being of
particular types. But since they are maps, it's easy to do the mutation
directly, using assoc.
The following was computed manually using a calculator.
The following was computed manually using a calculator. | (ns cortex.optimise.optimisers-test
(:refer-clojure :exclude [+ - * /])
(:require [clojure.core.matrix.operators :refer [+ - * /]]
[clojure.test :refer :all]
[cortex.optimise.optimisers :refer :all]
[cortex.optimise.protocols :as cp]
[cortex.util :refer [approx= def-]]))
Protocol extensions
(def- test-optimiser-map
{:initialize (fn [param-count]
{:velocity (vec (repeat param-count 0))})
:update (fn [{:keys [params velocity]} gradient]
{:params (+ params velocity)
:velocity (+ velocity gradient)})})
(def- test-optimiser-fn
(fn [params gradient]
(+ params gradient)))
(deftest protocol-extension-test
(testing "map as optimiser"
(is (= (->> test-optimiser-map
(iterate #(cp/compute-parameters % [1 2 3] (or (cp/parameters %)
[0 0 0])))
(map (juxt cp/parameters cp/get-state))
(rest)
(take 3))
[[[0 0 0] {:velocity [1 2 3]}]
[[1 2 3] {:velocity [2 4 6]}]
[[3 6 9] {:velocity [3 6 9]}]])))
(testing "fn as optimiser"
(is (= (->> test-optimiser-fn
(iterate #(cp/compute-parameters % [1 2 3] (or (cp/parameters %)
[0 0 0])))
(map (juxt cp/parameters cp/get-state))
(rest)
(take 3))
[[[1 2 3] {}]
[[2 4 6] {}]
[[3 6 9] {}]]))))
Clojure implementations
(deftest sgd-clojure-test
(is (= (-> (sgd-clojure :learning-rate 5)
(cp/compute-parameters [2 4 8] [1 2 3])
((juxt cp/parameters cp/get-state)))
[[-9 -18 -37] {}])))
(deftest adadelta-clojure-test
(is (approx= 1e-8
(-> (adadelta-clojure :decay-rate 0.5
:conditioning 1)
(assoc-in [:state :acc-gradient] [6 3 9])
(assoc-in [:state :acc-step] [7 8 7])
(dissoc :initialize)
(cp/compute-parameters [2 4 8] [1 2 3])
((juxt cp/parameters cp/get-state)))
[[-1.309401077 -1.703280399 -0.6950417228]
{:acc-gradient [5.0 9.5 36.5]
:acc-step [6.166666667 10.85714286 10.32666667]}])))
(deftest adam-clojure-test
(is (approx= 1e-8
(-> (adam-clojure :step-size 5
:first-moment-decay 0.75
:second-moment-decay 0.3
:conditioning 0.2)
(assoc-in [:state :first-moment] [5 2 -3])
(assoc-in [:state :second-moment] [-1 -3 -8])
(assoc-in [:state :num-steps] 2)
(dissoc :initialize)
(cp/compute-parameters [5 3 7] [1 2 -5])
((juxt cp/parameters cp/get-state)))
[[-8.81811015 -5.613809809 -4.270259223]
{:first-moment [5.0 2.25 -0.5]
:second-moment [17.2 5.4 31.9]
:num-steps 3}])))
|
50b1c768ca5d8a6e87be00cdcb58b8120eda388bbe0963527c4ea3e3beb5b4bf | nikita-volkov/rerebase | Environment.hs | module GHC.Environment
(
module Rebase.GHC.Environment
)
where
import Rebase.GHC.Environment
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/GHC/Environment.hs | haskell | module GHC.Environment
(
module Rebase.GHC.Environment
)
where
import Rebase.GHC.Environment
|
|
60e3e4107185f81273058ae857e0d690d58e4db9fe83f2c5d44b9218dfdea035 | lehins/primal | Raises.hs | # LANGUAGE CPP #
# LANGUAGE LambdaCase #
# LANGUAGE MagicHash #
# LANGUAGE TypeFamilies #
-- |
-- Module : Primal.Monad.Raises
Copyright : ( c ) 2020 - 2022
-- License : BSD3
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
module Primal.Monad.Raises
( Raises(..)
, raiseLeft
, handleExceptT
) where
import Control.Exception
import Control.Monad.ST
import Control.Monad.ST.Unsafe
import GHC.Conc.Sync (STM(..))
import GHC.Exts
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (ContT)
import Control.Monad.Trans.Except (ExceptT(..), throwE, catchE)
import Control.Monad.Trans.Identity (IdentityT)
import Control.Monad.Trans.Maybe (MaybeT(..))
import Control.Monad.Trans.Reader (ReaderT(..))
import Control.Monad.Trans.RWS.Lazy as Lazy (RWST)
import Control.Monad.Trans.RWS.Strict as Strict (RWST)
import Control.Monad.Trans.State.Lazy as Lazy (StateT)
import Control.Monad.Trans.State.Strict as Strict (StateT)
import Control.Monad.Trans.Writer.Lazy as Lazy (WriterT)
import Control.Monad.Trans.Writer.Strict as Strict (WriterT)
#if MIN_VERSION_transformers(0, 5, 3)
import Control.Monad.Trans.Accum (AccumT)
import Control.Monad.Trans.Select (SelectT)
#if MIN_VERSION_transformers(0, 5, 6)
import Control.Monad.Trans.RWS.CPS as CPS (RWST)
import Control.Monad.Trans.Writer.CPS as CPS (WriterT)
#endif
#endif
-- | Handle an exception of a specific type and re-raise any other exception
-- into the `Raises` monad class.
--
-- @since 1.0.0
handleExceptT :: (Exception e, Raises m) => ExceptT SomeException m a -> ExceptT e m a
handleExceptT m =
catchE m $ \exc ->
case fromException exc of
Just e -> throwE e
Nothing -> lift $ raiseM exc
# INLINE handleExceptT #
-- | A class for monads in which exceptions may be thrown.
--
-- Instances should obey the following law:
--
-- > raiseM e >> x = raiseM e
--
-- In other words, throwing an exception short-circuits the rest of the monadic
-- computation.
--
-- === Note
--
-- This is an almost identical class to
-- [MonadThrow](-Monad-Catch.html#t:MonadThrow)
-- from @exceptions@ package. The reason why it was copied, instead of a direct dependency
on the aforementioned package is because @MonadCatch@ and @MonadMask@ are not right
-- abstractions for exception handling in presence of concurrency and also because
-- instances for such transformers as `MaybeT` and `ExceptT` are flawed.
class Monad m => Raises m where
-- | Throw an exception. Note that this throws when this action is run in
-- the monad @m@, not when it is applied. It is a generalization of
" Primal . Exception " 's ' Primal.Exception.throw ' .
--
raiseM :: Exception e => e -> m a
instance Raises Maybe where
raiseM _ = Nothing
instance e ~ SomeException => Raises (Either e) where
raiseM = Left . toException
instance Raises IO where
raiseM = throwIO
instance Raises (ST s) where
raiseM e = unsafeIOToST $ throwIO e
instance Raises STM where
raiseM e = STM $ raiseIO# (toException e)
instance Raises m => Raises (ContT r m) where
raiseM = lift . raiseM
instance (e ~ SomeException, Monad m) => Raises (ExceptT e m) where
raiseM e = ExceptT (pure (Left (toException e)))
instance Raises m => Raises (IdentityT m) where
raiseM = lift . raiseM
instance Monad m => Raises (MaybeT m) where
raiseM _ = MaybeT (pure Nothing)
instance Raises m => Raises (ReaderT r m) where
raiseM = lift . raiseM
instance (Monoid w, Raises m) => Raises (Lazy.RWST r w s m) where
raiseM = lift . raiseM
instance (Monoid w, Raises m) => Raises (Strict.RWST r w s m) where
raiseM = lift . raiseM
instance Raises m => Raises (Lazy.StateT s m) where
raiseM = lift . raiseM
instance Raises m => Raises (Strict.StateT s m) where
raiseM = lift . raiseM
instance (Monoid w, Raises m) => Raises (Lazy.WriterT w m) where
raiseM = lift . raiseM
instance (Monoid w, Raises m) => Raises (Strict.WriterT w m) where
raiseM = lift . raiseM
#if MIN_VERSION_transformers(0, 5, 3)
instance (Monoid w, Raises m) => Raises (AccumT w m) where
raiseM = lift . raiseM
instance Raises m => Raises (SelectT r m) where
raiseM = lift . raiseM
#if MIN_VERSION_transformers(0, 5, 6)
instance Raises m => Raises (CPS.RWST r w st m) where
raiseM = lift . raiseM
instance Raises m => Raises (CPS.WriterT w m) where
raiseM = lift . raiseM
#endif
#endif
-- | Raise an exception when it is supplied with Left or return a value unmodified upon Right.
--
-- @since 1.0.0
raiseLeft :: (Exception e, Raises m) => Either e a -> m a
raiseLeft =
\case
Left exc -> raiseM exc
Right res -> pure res
| null | https://raw.githubusercontent.com/lehins/primal/c620bfd4f2a6475f1c12183fbe8138cf29ab1dad/primal/src/Primal/Monad/Raises.hs | haskell | |
Module : Primal.Monad.Raises
License : BSD3
Stability : experimental
Portability : non-portable
| Handle an exception of a specific type and re-raise any other exception
into the `Raises` monad class.
@since 1.0.0
| A class for monads in which exceptions may be thrown.
Instances should obey the following law:
> raiseM e >> x = raiseM e
In other words, throwing an exception short-circuits the rest of the monadic
computation.
=== Note
This is an almost identical class to
[MonadThrow](-Monad-Catch.html#t:MonadThrow)
from @exceptions@ package. The reason why it was copied, instead of a direct dependency
abstractions for exception handling in presence of concurrency and also because
instances for such transformers as `MaybeT` and `ExceptT` are flawed.
| Throw an exception. Note that this throws when this action is run in
the monad @m@, not when it is applied. It is a generalization of
| Raise an exception when it is supplied with Left or return a value unmodified upon Right.
@since 1.0.0 | # LANGUAGE CPP #
# LANGUAGE LambdaCase #
# LANGUAGE MagicHash #
# LANGUAGE TypeFamilies #
Copyright : ( c ) 2020 - 2022
Maintainer : < >
module Primal.Monad.Raises
( Raises(..)
, raiseLeft
, handleExceptT
) where
import Control.Exception
import Control.Monad.ST
import Control.Monad.ST.Unsafe
import GHC.Conc.Sync (STM(..))
import GHC.Exts
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (ContT)
import Control.Monad.Trans.Except (ExceptT(..), throwE, catchE)
import Control.Monad.Trans.Identity (IdentityT)
import Control.Monad.Trans.Maybe (MaybeT(..))
import Control.Monad.Trans.Reader (ReaderT(..))
import Control.Monad.Trans.RWS.Lazy as Lazy (RWST)
import Control.Monad.Trans.RWS.Strict as Strict (RWST)
import Control.Monad.Trans.State.Lazy as Lazy (StateT)
import Control.Monad.Trans.State.Strict as Strict (StateT)
import Control.Monad.Trans.Writer.Lazy as Lazy (WriterT)
import Control.Monad.Trans.Writer.Strict as Strict (WriterT)
#if MIN_VERSION_transformers(0, 5, 3)
import Control.Monad.Trans.Accum (AccumT)
import Control.Monad.Trans.Select (SelectT)
#if MIN_VERSION_transformers(0, 5, 6)
import Control.Monad.Trans.RWS.CPS as CPS (RWST)
import Control.Monad.Trans.Writer.CPS as CPS (WriterT)
#endif
#endif
handleExceptT :: (Exception e, Raises m) => ExceptT SomeException m a -> ExceptT e m a
handleExceptT m =
catchE m $ \exc ->
case fromException exc of
Just e -> throwE e
Nothing -> lift $ raiseM exc
# INLINE handleExceptT #
on the aforementioned package is because @MonadCatch@ and @MonadMask@ are not right
class Monad m => Raises m where
" Primal . Exception " 's ' Primal.Exception.throw ' .
raiseM :: Exception e => e -> m a
instance Raises Maybe where
raiseM _ = Nothing
instance e ~ SomeException => Raises (Either e) where
raiseM = Left . toException
instance Raises IO where
raiseM = throwIO
instance Raises (ST s) where
raiseM e = unsafeIOToST $ throwIO e
instance Raises STM where
raiseM e = STM $ raiseIO# (toException e)
instance Raises m => Raises (ContT r m) where
raiseM = lift . raiseM
instance (e ~ SomeException, Monad m) => Raises (ExceptT e m) where
raiseM e = ExceptT (pure (Left (toException e)))
instance Raises m => Raises (IdentityT m) where
raiseM = lift . raiseM
instance Monad m => Raises (MaybeT m) where
raiseM _ = MaybeT (pure Nothing)
instance Raises m => Raises (ReaderT r m) where
raiseM = lift . raiseM
instance (Monoid w, Raises m) => Raises (Lazy.RWST r w s m) where
raiseM = lift . raiseM
instance (Monoid w, Raises m) => Raises (Strict.RWST r w s m) where
raiseM = lift . raiseM
instance Raises m => Raises (Lazy.StateT s m) where
raiseM = lift . raiseM
instance Raises m => Raises (Strict.StateT s m) where
raiseM = lift . raiseM
instance (Monoid w, Raises m) => Raises (Lazy.WriterT w m) where
raiseM = lift . raiseM
instance (Monoid w, Raises m) => Raises (Strict.WriterT w m) where
raiseM = lift . raiseM
#if MIN_VERSION_transformers(0, 5, 3)
instance (Monoid w, Raises m) => Raises (AccumT w m) where
raiseM = lift . raiseM
instance Raises m => Raises (SelectT r m) where
raiseM = lift . raiseM
#if MIN_VERSION_transformers(0, 5, 6)
instance Raises m => Raises (CPS.RWST r w st m) where
raiseM = lift . raiseM
instance Raises m => Raises (CPS.WriterT w m) where
raiseM = lift . raiseM
#endif
#endif
raiseLeft :: (Exception e, Raises m) => Either e a -> m a
raiseLeft =
\case
Left exc -> raiseM exc
Right res -> pure res
|
edccbde4b31284b835bdb125e32ad562a8445fd07608db1ed7bc929d7d8c0961 | ocaml/ocaml | mctest.ml | (* TEST
* hasunix
include unix
** bytecode
** native
*)
* Copyright ( c ) 2015 , < >
* Copyright ( c ) 2015 , < >
*
* 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 .
* Copyright (c) 2015, Theo Laurent <>
* Copyright (c) 2015, KC Sivaramakrishnan <>
*
* 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.
*)
queue
module type BS = sig
type t
val create : ?max:int -> unit -> t
val once : t -> unit
val reset : t -> unit
end
module B : BS = struct
type t = int * int ref
let _ = Random.self_init ()
let create ?(max=32) () = (max, ref 1)
let once (maxv, r) =
let t = Random.int (!r) in
r := min (2 * !r) maxv;
if t = 0 then ()
else ignore (Unix.select [] [] [] (0.001 *. (float_of_int t)))
let reset (_,r) = r := 1
end
(* TODO KC: Replace with concurrent lock free bag --
* *)
module type QS = sig
type 'a t
val create : unit -> 'a t
val is_empty : 'a t -> bool
val push : 'a t -> 'a -> unit
val pop : 'a t -> 'a option
val clean_until : 'a t -> ('a -> bool) -> unit
type 'a cursor
val snapshot : 'a t -> 'a cursor
val next : 'a cursor -> ('a * 'a cursor) option
end
module Q : QS = struct
type 'a node =
| Nil
| Next of 'a * 'a node Atomic.t
type 'a t =
{ head : 'a node Atomic.t ;
tail : 'a node Atomic.t }
let create () =
let head = (Next (Obj.magic (), Atomic.make Nil)) in
{ head = Atomic.make head ; tail = Atomic.make head }
let is_empty q =
match Atomic.get q.head with
| Nil -> failwith "MSQueue.is_empty: impossible"
| Next (_,x) ->
( match Atomic.get x with
| Nil -> true
| _ -> false )
let pop q =
let b = B.create () in
let rec loop () =
let s = Atomic.get q.head in
let nhead = match s with
| Nil -> failwith "MSQueue.pop: impossible"
| Next (_, x) -> Atomic.get x
in match nhead with
| Nil -> None
| Next (v, _) when Atomic.compare_and_set q.head s nhead -> Some v
| _ -> ( B.once b ; loop () )
in loop ()
let push q v =
let rec find_tail_and_enq curr_end node =
if Atomic.compare_and_set curr_end Nil node then ()
else match Atomic.get curr_end with
| Nil -> find_tail_and_enq curr_end node
| Next (_, n) -> find_tail_and_enq n node
in
let newnode = Next (v, Atomic.make Nil) in
let tail = Atomic.get q.tail in
match tail with
| Nil -> failwith "HW_MSQueue.push: impossible"
| Next (_, n) -> begin
find_tail_and_enq n newnode;
ignore (Atomic.compare_and_set q.tail tail newnode)
end
let rec clean_until q f =
let b = B.create () in
let rec loop () =
let s = Atomic.get q.head in
let nhead = match s with
| Nil -> failwith "MSQueue.pop: impossible"
| Next (_, x) -> Atomic.get x
in match nhead with
| Nil -> ()
| Next (v, _) ->
if not (f v) then
if Atomic.compare_and_set q.head s nhead
then (B.reset b; loop ())
else (B.once b; loop ())
else ()
in loop ()
type 'a cursor = 'a node
let snapshot q =
match Atomic.get q.head with
| Nil -> failwith "MSQueue.snapshot: impossible"
| Next (_, n) -> Atomic.get n
let next c =
match c with
| Nil -> None
| Next (a, n) -> Some (a, Atomic.get n)
end
module Scheduler =
struct
open Effect
open Effect.Deep
type 'a cont = ('a, unit) continuation
type _ t += Suspend : ('a cont -> 'a option) -> 'a t
| Resume : ('a cont * 'a) -> unit t
| GetTid : int t
| Spawn : (unit -> unit) -> unit t
| Yield : unit t
let suspend f = perform (Suspend f)
let resume t v = perform (Resume (t, v))
let get_tid () = perform GetTid
let spawn f = perform (Spawn f)
let yield () = perform Yield
let pqueue = Q.create ()
let get_free_pid () = Oo.id (object end)
let enqueue k = Q.push pqueue k; Gc.minor ()
let rec dequeue () =
match Q.pop pqueue with
| Some k ->
continue k ()
| None ->
ignore (Unix.select [] [] [] 0.01);
dequeue ()
let rec exec f =
let pid = get_free_pid () in
match_with f ()
{ retc = (fun () -> dequeue ());
exnc = (fun e -> raise e);
effc = fun (type a) (e : a t) ->
match e with
| Suspend f -> Some (fun (k : (a, _) continuation) ->
match f k with
| None -> dequeue ()
| Some v -> continue k v)
| Resume (t, v) -> Some (fun (k : (a, _) continuation) ->
enqueue k;
continue t v)
| GetTid -> Some (fun (k : (a, _) continuation) ->
continue k pid)
| Spawn f -> Some (fun (k : (a, _) continuation) ->
enqueue k;
exec f)
| Yield -> Some (fun (k : (a, _) continuation) ->
enqueue k;
dequeue ())
| _ -> None }
let num_threads = 2
let start f =
for i = 1 to num_threads - 1 do
ignore (Domain.spawn dequeue)
done;
exec f
end
let _ =
let procs = 4 in
let counter = Atomic.make 0 in
let rec finish () =
let v = Atomic.get counter in
if not (Atomic.compare_and_set counter v (v+1)) then finish ();
if v + 1 = procs then exit 0
in
let rec worker n =
let r = ref 0 in
for i = 1 to 10000 do
Scheduler.yield ();
for j = 1 to 10000 do
incr r
done
done;
print_string (Printf.sprintf "done %d\n" !r); flush stdout;
finish ()
in
Scheduler.start
(fun () ->
for i = 1 to procs do
( ) ;
Scheduler.spawn (fun () -> worker i)
done;
)
| null | https://raw.githubusercontent.com/ocaml/ocaml/79c6d0565284f98683293afbce8e5e5e581ec00e/testsuite/tests/parallel/mctest.ml | ocaml | TEST
* hasunix
include unix
** bytecode
** native
TODO KC: Replace with concurrent lock free bag --
* |
* Copyright ( c ) 2015 , < >
* Copyright ( c ) 2015 , < >
*
* 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 .
* Copyright (c) 2015, Theo Laurent <>
* Copyright (c) 2015, KC Sivaramakrishnan <>
*
* 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.
*)
queue
module type BS = sig
type t
val create : ?max:int -> unit -> t
val once : t -> unit
val reset : t -> unit
end
module B : BS = struct
type t = int * int ref
let _ = Random.self_init ()
let create ?(max=32) () = (max, ref 1)
let once (maxv, r) =
let t = Random.int (!r) in
r := min (2 * !r) maxv;
if t = 0 then ()
else ignore (Unix.select [] [] [] (0.001 *. (float_of_int t)))
let reset (_,r) = r := 1
end
module type QS = sig
type 'a t
val create : unit -> 'a t
val is_empty : 'a t -> bool
val push : 'a t -> 'a -> unit
val pop : 'a t -> 'a option
val clean_until : 'a t -> ('a -> bool) -> unit
type 'a cursor
val snapshot : 'a t -> 'a cursor
val next : 'a cursor -> ('a * 'a cursor) option
end
module Q : QS = struct
type 'a node =
| Nil
| Next of 'a * 'a node Atomic.t
type 'a t =
{ head : 'a node Atomic.t ;
tail : 'a node Atomic.t }
let create () =
let head = (Next (Obj.magic (), Atomic.make Nil)) in
{ head = Atomic.make head ; tail = Atomic.make head }
let is_empty q =
match Atomic.get q.head with
| Nil -> failwith "MSQueue.is_empty: impossible"
| Next (_,x) ->
( match Atomic.get x with
| Nil -> true
| _ -> false )
let pop q =
let b = B.create () in
let rec loop () =
let s = Atomic.get q.head in
let nhead = match s with
| Nil -> failwith "MSQueue.pop: impossible"
| Next (_, x) -> Atomic.get x
in match nhead with
| Nil -> None
| Next (v, _) when Atomic.compare_and_set q.head s nhead -> Some v
| _ -> ( B.once b ; loop () )
in loop ()
let push q v =
let rec find_tail_and_enq curr_end node =
if Atomic.compare_and_set curr_end Nil node then ()
else match Atomic.get curr_end with
| Nil -> find_tail_and_enq curr_end node
| Next (_, n) -> find_tail_and_enq n node
in
let newnode = Next (v, Atomic.make Nil) in
let tail = Atomic.get q.tail in
match tail with
| Nil -> failwith "HW_MSQueue.push: impossible"
| Next (_, n) -> begin
find_tail_and_enq n newnode;
ignore (Atomic.compare_and_set q.tail tail newnode)
end
let rec clean_until q f =
let b = B.create () in
let rec loop () =
let s = Atomic.get q.head in
let nhead = match s with
| Nil -> failwith "MSQueue.pop: impossible"
| Next (_, x) -> Atomic.get x
in match nhead with
| Nil -> ()
| Next (v, _) ->
if not (f v) then
if Atomic.compare_and_set q.head s nhead
then (B.reset b; loop ())
else (B.once b; loop ())
else ()
in loop ()
type 'a cursor = 'a node
let snapshot q =
match Atomic.get q.head with
| Nil -> failwith "MSQueue.snapshot: impossible"
| Next (_, n) -> Atomic.get n
let next c =
match c with
| Nil -> None
| Next (a, n) -> Some (a, Atomic.get n)
end
module Scheduler =
struct
open Effect
open Effect.Deep
type 'a cont = ('a, unit) continuation
type _ t += Suspend : ('a cont -> 'a option) -> 'a t
| Resume : ('a cont * 'a) -> unit t
| GetTid : int t
| Spawn : (unit -> unit) -> unit t
| Yield : unit t
let suspend f = perform (Suspend f)
let resume t v = perform (Resume (t, v))
let get_tid () = perform GetTid
let spawn f = perform (Spawn f)
let yield () = perform Yield
let pqueue = Q.create ()
let get_free_pid () = Oo.id (object end)
let enqueue k = Q.push pqueue k; Gc.minor ()
let rec dequeue () =
match Q.pop pqueue with
| Some k ->
continue k ()
| None ->
ignore (Unix.select [] [] [] 0.01);
dequeue ()
let rec exec f =
let pid = get_free_pid () in
match_with f ()
{ retc = (fun () -> dequeue ());
exnc = (fun e -> raise e);
effc = fun (type a) (e : a t) ->
match e with
| Suspend f -> Some (fun (k : (a, _) continuation) ->
match f k with
| None -> dequeue ()
| Some v -> continue k v)
| Resume (t, v) -> Some (fun (k : (a, _) continuation) ->
enqueue k;
continue t v)
| GetTid -> Some (fun (k : (a, _) continuation) ->
continue k pid)
| Spawn f -> Some (fun (k : (a, _) continuation) ->
enqueue k;
exec f)
| Yield -> Some (fun (k : (a, _) continuation) ->
enqueue k;
dequeue ())
| _ -> None }
let num_threads = 2
let start f =
for i = 1 to num_threads - 1 do
ignore (Domain.spawn dequeue)
done;
exec f
end
let _ =
let procs = 4 in
let counter = Atomic.make 0 in
let rec finish () =
let v = Atomic.get counter in
if not (Atomic.compare_and_set counter v (v+1)) then finish ();
if v + 1 = procs then exit 0
in
let rec worker n =
let r = ref 0 in
for i = 1 to 10000 do
Scheduler.yield ();
for j = 1 to 10000 do
incr r
done
done;
print_string (Printf.sprintf "done %d\n" !r); flush stdout;
finish ()
in
Scheduler.start
(fun () ->
for i = 1 to procs do
( ) ;
Scheduler.spawn (fun () -> worker i)
done;
)
|
33bd3f7a1cc46206f105d646d50695f12e8a9adef95d01adca83dc7e18bfa3e8 | TrustInSoft/tis-interpreter | prover.ml | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* 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 .
(* *)
(* It 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. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
open VCS
(* -------------------------------------------------------------------------- *)
(* --- Prover Implementation against Task API --- *)
(* -------------------------------------------------------------------------- *)
open Task
open Wpo
let dispatch wpo mode prover =
begin
match prover with
| AltErgo -> ProverErgo.prove mode wpo
| Coq -> ProverCoq.prove mode wpo
| Why3 prover -> ProverWhy3.prove ~prover wpo
| Qed -> Task.return VCS.unknown
| _ -> Task.failed "Prover '%a' not available" VCS.pp_prover prover
end
let qed_time wpo =
match wpo.po_formula with
| GoalCheck _ | GoalLemma _ -> 0.0
| GoalAnnot vcq -> GOAL.qed_time vcq.VC_Annot.goal
let started ?start wpo =
match start with
| None -> ()
| Some f -> f wpo
let signal ?callin wpo prover =
match callin with
| None -> ()
| Some f -> f wpo prover
let update ?callback wpo prover result =
Wpo.set_result wpo prover result ;
match callback with
| None -> ()
| Some f -> f wpo prover result
let run_prover wpo ?(mode=BatchMode) ?callin ?callback prover =
signal ?callin wpo prover ;
dispatch wpo mode prover >>>
fun status ->
let result = match status with
| Task.Result r -> r
| Task.Canceled -> VCS.no_result
| Task.Timeout -> VCS.timeout
| Task.Failed exn -> VCS.failed (error exn)
in
let result = { result with solver_time = qed_time wpo } in
update ?callback wpo prover result ;
Task.return (Wpo.is_valid result)
let resolve wpo =
match wpo.po_formula with
| GoalAnnot vcq -> VC_Annot.resolve vcq
| GoalLemma vca -> VC_Lemma.is_trivial vca
| GoalCheck _ -> false
let simplify ?start ?callback wpo =
Task.call
(fun wpo ->
let r = Wpo.get_result wpo VCS.Qed in
VCS.( r.verdict == Valid ) ||
begin
started ?start wpo ;
if resolve wpo then
let time = qed_time wpo in
let result = VCS.result ~time VCS.Valid in
(update ?callback wpo VCS.Qed result ; true)
else false
end)
wpo
let prove wpo ?mode ?start ?callin ?callback prover =
simplify ?start ?callback wpo >>= fun succeed ->
if succeed
then Task.return true
else (run_prover wpo ?mode ?callin ?callback prover)
let spawn wpo ?start ?callin ?callback ?success provers =
let do_monitor f wpo = function
| None -> f wpo None
| Some p ->
let r = Wpo.get_result wpo VCS.Qed in
let p = if VCS.( r.verdict == Valid ) then VCS.Qed else p in
f wpo (Some p) in
let monitor = match success with
| None -> None
| Some f -> Some (do_monitor f wpo) in
ProverTask.spawn ?monitor
begin
List.map
(fun (mode,prover) ->
prover , prove wpo ~mode ?start ?callin ?callback prover)
provers
end
(* ------------------------------------------------------------------------ *)
(* --- Why3ide --- *)
(* ------------------------------------------------------------------------ *)
module String = Datatype.String
(** Different instance of why3ide can't be run simultanely *)
let why3ide_running = ref false
(** Update Wpo from Sessions *)
let update_wpo_from_session ?callback ~goals ~session:filename_session () =
let open ProverWhy3 in
let open Why3_session in
let module HStr = String.Hashtbl in
let session = read_session filename_session in
Wpo.S.Hashtbl.iter (fun wpo g ->
match g with
proved by QED
let time = qed_time wpo in
let result = VCS.result ~time VCS.Valid in
update ?callback wpo VCS.Qed result;
update ?callback wpo VCS.Why3ide (VCS.result VCS.NoResult)
| Some g ->
try
let filename =
Filepath.relativize ~base:filename_session g.gfile in
let file = HStr.find session.session_files filename in
let theory = HStr.find file.file_theories g.gtheory in
let goal = HStr.find theory.theory_goals g.ggoal in
let result = VCS.result
(if goal.goal_verified then VCS.Valid else VCS.NoResult) in
update ?callback wpo VCS.Why3ide result
with Not_found ->
if Wp_parameters.has_dkey "prover" then
Wp_parameters.feedback
"[WP.Why3ide] a goal normally present in generated file \
is not present in the session: %s %s %s@."
g.gfile g.gtheory g.ggoal;
update ?callback wpo VCS.Why3ide (VCS.result VCS.NoResult)
) goals;
why3ide_running := false
let wp_why3ide ?callback iter =
let includes = String.Hashtbl.create 2 in
let files = String.Hashtbl.create 5 in
let goals = Wpo.S.Hashtbl.create 24 in
let on_goal wpo =
match ProverWhy3.assemble_wpo wpo with
| None ->
Wpo.S.Hashtbl.add goals wpo None;
| Some (incs,goal) ->
Wpo.S.Hashtbl.add goals wpo (Some goal);
List.iter (fun f -> String.Hashtbl.replace includes f ()) incs;
String.Hashtbl.replace files goal.ProverWhy3.gfile ()
in
iter on_goal;
let dir = Wp_parameters.get_output () in
let session = Format.sprintf "%s/project.session" dir in
let get_value h = String.Hashtbl.fold_sorted (fun s () acc -> s::acc) h [] in
let includes = get_value includes in
let files = get_value files in
if files = [] then (why3ide_running := false; Task.nop)
else
begin
ProverWhy3.call_ide ~includes ~files ~session >>=
fun ok -> begin
if ok then begin
try update_wpo_from_session ?callback ~goals ~session ()
with Why3_session.LoadError ->
Wp_parameters.error
"[WP] why3session: can't import back why3 results because of \
previous error"
end;
Task.return ()
end
end
let wp_why3ide ?callback iter =
if !why3ide_running
then begin
Wp_parameters.feedback "Why3ide is already running. Close it before \
starting other tasks for it.";
Task.nop
end
else begin
why3ide_running := true;
wp_why3ide ?callback iter
end
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/wp/prover.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It 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.
************************************************************************
--------------------------------------------------------------------------
--- Prover Implementation against Task API ---
--------------------------------------------------------------------------
------------------------------------------------------------------------
--- Why3ide ---
------------------------------------------------------------------------
* Different instance of why3ide can't be run simultanely
* Update Wpo from Sessions | Modified by TrustInSoft
This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open VCS
open Task
open Wpo
let dispatch wpo mode prover =
begin
match prover with
| AltErgo -> ProverErgo.prove mode wpo
| Coq -> ProverCoq.prove mode wpo
| Why3 prover -> ProverWhy3.prove ~prover wpo
| Qed -> Task.return VCS.unknown
| _ -> Task.failed "Prover '%a' not available" VCS.pp_prover prover
end
let qed_time wpo =
match wpo.po_formula with
| GoalCheck _ | GoalLemma _ -> 0.0
| GoalAnnot vcq -> GOAL.qed_time vcq.VC_Annot.goal
let started ?start wpo =
match start with
| None -> ()
| Some f -> f wpo
let signal ?callin wpo prover =
match callin with
| None -> ()
| Some f -> f wpo prover
let update ?callback wpo prover result =
Wpo.set_result wpo prover result ;
match callback with
| None -> ()
| Some f -> f wpo prover result
let run_prover wpo ?(mode=BatchMode) ?callin ?callback prover =
signal ?callin wpo prover ;
dispatch wpo mode prover >>>
fun status ->
let result = match status with
| Task.Result r -> r
| Task.Canceled -> VCS.no_result
| Task.Timeout -> VCS.timeout
| Task.Failed exn -> VCS.failed (error exn)
in
let result = { result with solver_time = qed_time wpo } in
update ?callback wpo prover result ;
Task.return (Wpo.is_valid result)
let resolve wpo =
match wpo.po_formula with
| GoalAnnot vcq -> VC_Annot.resolve vcq
| GoalLemma vca -> VC_Lemma.is_trivial vca
| GoalCheck _ -> false
let simplify ?start ?callback wpo =
Task.call
(fun wpo ->
let r = Wpo.get_result wpo VCS.Qed in
VCS.( r.verdict == Valid ) ||
begin
started ?start wpo ;
if resolve wpo then
let time = qed_time wpo in
let result = VCS.result ~time VCS.Valid in
(update ?callback wpo VCS.Qed result ; true)
else false
end)
wpo
let prove wpo ?mode ?start ?callin ?callback prover =
simplify ?start ?callback wpo >>= fun succeed ->
if succeed
then Task.return true
else (run_prover wpo ?mode ?callin ?callback prover)
let spawn wpo ?start ?callin ?callback ?success provers =
let do_monitor f wpo = function
| None -> f wpo None
| Some p ->
let r = Wpo.get_result wpo VCS.Qed in
let p = if VCS.( r.verdict == Valid ) then VCS.Qed else p in
f wpo (Some p) in
let monitor = match success with
| None -> None
| Some f -> Some (do_monitor f wpo) in
ProverTask.spawn ?monitor
begin
List.map
(fun (mode,prover) ->
prover , prove wpo ~mode ?start ?callin ?callback prover)
provers
end
module String = Datatype.String
let why3ide_running = ref false
let update_wpo_from_session ?callback ~goals ~session:filename_session () =
let open ProverWhy3 in
let open Why3_session in
let module HStr = String.Hashtbl in
let session = read_session filename_session in
Wpo.S.Hashtbl.iter (fun wpo g ->
match g with
proved by QED
let time = qed_time wpo in
let result = VCS.result ~time VCS.Valid in
update ?callback wpo VCS.Qed result;
update ?callback wpo VCS.Why3ide (VCS.result VCS.NoResult)
| Some g ->
try
let filename =
Filepath.relativize ~base:filename_session g.gfile in
let file = HStr.find session.session_files filename in
let theory = HStr.find file.file_theories g.gtheory in
let goal = HStr.find theory.theory_goals g.ggoal in
let result = VCS.result
(if goal.goal_verified then VCS.Valid else VCS.NoResult) in
update ?callback wpo VCS.Why3ide result
with Not_found ->
if Wp_parameters.has_dkey "prover" then
Wp_parameters.feedback
"[WP.Why3ide] a goal normally present in generated file \
is not present in the session: %s %s %s@."
g.gfile g.gtheory g.ggoal;
update ?callback wpo VCS.Why3ide (VCS.result VCS.NoResult)
) goals;
why3ide_running := false
let wp_why3ide ?callback iter =
let includes = String.Hashtbl.create 2 in
let files = String.Hashtbl.create 5 in
let goals = Wpo.S.Hashtbl.create 24 in
let on_goal wpo =
match ProverWhy3.assemble_wpo wpo with
| None ->
Wpo.S.Hashtbl.add goals wpo None;
| Some (incs,goal) ->
Wpo.S.Hashtbl.add goals wpo (Some goal);
List.iter (fun f -> String.Hashtbl.replace includes f ()) incs;
String.Hashtbl.replace files goal.ProverWhy3.gfile ()
in
iter on_goal;
let dir = Wp_parameters.get_output () in
let session = Format.sprintf "%s/project.session" dir in
let get_value h = String.Hashtbl.fold_sorted (fun s () acc -> s::acc) h [] in
let includes = get_value includes in
let files = get_value files in
if files = [] then (why3ide_running := false; Task.nop)
else
begin
ProverWhy3.call_ide ~includes ~files ~session >>=
fun ok -> begin
if ok then begin
try update_wpo_from_session ?callback ~goals ~session ()
with Why3_session.LoadError ->
Wp_parameters.error
"[WP] why3session: can't import back why3 results because of \
previous error"
end;
Task.return ()
end
end
let wp_why3ide ?callback iter =
if !why3ide_running
then begin
Wp_parameters.feedback "Why3ide is already running. Close it before \
starting other tasks for it.";
Task.nop
end
else begin
why3ide_running := true;
wp_why3ide ?callback iter
end
|
db0895f81306fb20810c3e171fc96949a9a6555327dd1a333c0fe6968b965ee7 | ocaml-gospel/cameleer | power_2_above.ml | (*@ open Power *)
let rec power_2_above x n = if x >= n then x else power_2_above (x * 2) n
@ r = power_2_above x n
requires x > 0
requires exists k. k > = 0 & & x = 2 ^ k
diverges
ensures exists 0 & & r = 2 ^ k & & r > = n
requires x > 0
requires exists k. k >= 0 && x = 2 ^ k
diverges
ensures exists k. k >= 0 && r = 2 ^ k && r >= n *)
| null | https://raw.githubusercontent.com/ocaml-gospel/cameleer/fcf00fe27e0a41125880043aa9aa633399fc8cc2/examples/exercises/power_2_above.ml | ocaml | @ open Power |
let rec power_2_above x n = if x >= n then x else power_2_above (x * 2) n
@ r = power_2_above x n
requires x > 0
requires exists k. k > = 0 & & x = 2 ^ k
diverges
ensures exists 0 & & r = 2 ^ k & & r > = n
requires x > 0
requires exists k. k >= 0 && x = 2 ^ k
diverges
ensures exists k. k >= 0 && r = 2 ^ k && r >= n *)
|
ee7264e6aa0336280a8d216dd51a10657156761e4096c012b3dd963c95cbc8fe | christiankissig/ocaml99 | problem34.ml | # P34 ( *
#
# Euler's so-called totient function phi(m) is defined as the number of positive
# integers r (1 <= r < m) that are coprime to m.
#
# Example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1.
#
# * (totient-phi 10)
# 4
#
# Find out what the value of phi(m) is if m is a prime number. Euler's totient
# function plays an important role in one of the most widely used public key
# cryptography methods (RSA). In this exercise you should use the most primitive
# method to calculate this function (there are smarter ways that we shall discuss
# later).*)
let rec gcd a b =
if ( b = 0 )
then a
else gcd b ( a mod b )
;;
let totient n =
let rec iterate i =
if ( i < 1 )
then 0
else
( if ( ( gcd i n ) = 1 ) then 1 else 0 ) +
( iterate ( i - 1 ) )
in
( iterate ( n - 1 ) )
;;
if ( ( totient 10 ) = 4 )
then ( Printf.printf "ok\n" )
else ( Printf.printf "failed\n" );; | null | https://raw.githubusercontent.com/christiankissig/ocaml99/c25f1790f695f9dd68b23abb472dc7c860d840f8/problem34.ml | ocaml | # P34 ( *
#
# Euler's so-called totient function phi(m) is defined as the number of positive
# integers r (1 <= r < m) that are coprime to m.
#
# Example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1.
#
# * (totient-phi 10)
# 4
#
# Find out what the value of phi(m) is if m is a prime number. Euler's totient
# function plays an important role in one of the most widely used public key
# cryptography methods (RSA). In this exercise you should use the most primitive
# method to calculate this function (there are smarter ways that we shall discuss
# later).*)
let rec gcd a b =
if ( b = 0 )
then a
else gcd b ( a mod b )
;;
let totient n =
let rec iterate i =
if ( i < 1 )
then 0
else
( if ( ( gcd i n ) = 1 ) then 1 else 0 ) +
( iterate ( i - 1 ) )
in
( iterate ( n - 1 ) )
;;
if ( ( totient 10 ) = 4 )
then ( Printf.printf "ok\n" )
else ( Printf.printf "failed\n" );; |
|
34c624724a47a375aa0ce1f7c8a516d99082966e23ff85808f72ee4626e05e94 | erlangonrails/devdb | riak_kv_pb_listener.erl | %% -------------------------------------------------------------------
%%
%% riak_kv_pb_listener: Listen for protocol buffer clients
%%
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you 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.
%%
%% -------------------------------------------------------------------
%% @doc entry point for TCP-based protocol buffers service
-module(riak_kv_pb_listener).
-behavior(gen_nb_server).
-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-export([sock_opts/0, new_connection/2]).
-record(state, {portnum}).
start_link() ->
PortNum = app_helper:get_env(riak_kv, pb_port),
IpAddr = app_helper:get_env(riak_kv, pb_ip),
gen_nb_server:start_link(?MODULE, IpAddr, PortNum, [PortNum]).
init([PortNum]) ->
{ok, #state{portnum=PortNum}}.
sock_opts() -> [binary, {packet, 4}, {reuseaddr, true}].
handle_call(_Req, _From, State) ->
{reply, not_implemented, State}.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
new_connection(Socket, State) ->
{ok, Pid} = riak_kv_pb_socket_sup:start_socket(Socket),
ok = gen_tcp:controlling_process(Socket, Pid),
{ok, State}.
| null | https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/riak-0.11.0/apps/riak_kv/src/riak_kv_pb_listener.erl | erlang | -------------------------------------------------------------------
riak_kv_pb_listener: Listen for protocol buffer clients
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc entry point for TCP-based protocol buffers service | Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(riak_kv_pb_listener).
-behavior(gen_nb_server).
-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-export([sock_opts/0, new_connection/2]).
-record(state, {portnum}).
start_link() ->
PortNum = app_helper:get_env(riak_kv, pb_port),
IpAddr = app_helper:get_env(riak_kv, pb_ip),
gen_nb_server:start_link(?MODULE, IpAddr, PortNum, [PortNum]).
init([PortNum]) ->
{ok, #state{portnum=PortNum}}.
sock_opts() -> [binary, {packet, 4}, {reuseaddr, true}].
handle_call(_Req, _From, State) ->
{reply, not_implemented, State}.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
new_connection(Socket, State) ->
{ok, Pid} = riak_kv_pb_socket_sup:start_socket(Socket),
ok = gen_tcp:controlling_process(Socket, Pid),
{ok, State}.
|
bb1508539f906806dc84f333f296981e40cb4e257f091fbdfd5aa36c7c1437b3 | ocaml-sf/learn-ocaml-corpus | assured_win_naive.ml | open Seq
(* -------------------------------------------------------------------------- *)
(* The size of a tree. *)
let rec size (t : tree) : int =
match t with
| TLeaf _ ->
1
| TNonLeaf offspring ->
1 + size_offspring offspring
and size_offspring (offspring : offspring) : int =
match offspring() with
| Nil ->
0
| Cons ((_move, t), offspring) ->
size t + size_offspring offspring
(* -------------------------------------------------------------------------- *)
(* The height of a tree. *)
let rec height (t : tree) : int =
match t with
| TLeaf _ ->
0
| TNonLeaf offspring ->
1 + height_offspring offspring
and height_offspring (offspring : offspring) : int =
match offspring() with
| Nil ->
0
| Cons ((_move, t), offspring) ->
max (height t) (height_offspring offspring)
(* -------------------------------------------------------------------------- *)
(* Evaluating a tree, with a sense parameter: Minimax. *)
let rec eval (sense : sense) (t : tree) : value =
match t with
| TLeaf v ->
interpret sense v
| TNonLeaf offspring ->
eval_offspring sense offspring
and eval_offspring (sense : sense) (offspring : offspring) : value =
match offspring() with
| Nil ->
unit sense
| Cons ((_move, t), offspring) ->
join sense
(eval (opposite sense) t)
(eval_offspring sense offspring)
(* -------------------------------------------------------------------------- *)
(* Evaluating a tree, without a sense parameter: Negamax. *)
let rec nval (t : tree) : value =
match t with
| TLeaf v ->
v
| TNonLeaf offspring ->
nval_offspring offspring
and nval_offspring (offspring : offspring) =
match offspring() with
| Nil ->
bottom
| Cons ((_move, t), offspring) ->
max
(- nval t)
(nval_offspring offspring)
(* -------------------------------------------------------------------------- *)
Evaluating a tree , in Negamax style , and looping over children in
a tail - recursive manner .
a tail-recursive manner. *)
let rec ntval (t : tree) : value =
match t with
| TLeaf v ->
v
| TNonLeaf offspring ->
ntval_offspring bottom offspring
and ntval_offspring (running_max : value) (offspring : offspring) : value =
match offspring() with
| Nil ->
running_max
| Cons ((_move, t), offspring) ->
let v = - ntval t in
let running_max = max running_max v in
ntval_offspring running_max offspring
(* -------------------------------------------------------------------------- *)
Evaluating a tree , using the Alpha - Beta algorithm .
let rec bval (alpha : value) (beta : value) (t : tree) : value =
assert (alpha < beta);
match t with
| TLeaf v ->
(* We could project [v] onto the closed interval [alpha, beta],
but this does not make any difference; [v] is equivalent to
its projection. *)
v
| TNonLeaf offspring ->
bval_offspring alpha beta offspring
and bval_offspring (alpha : value) (beta : value) (offspring : offspring) : value =
assert (alpha < beta);
match offspring() with
| Nil ->
(* We could return the maximum of the children that we have examined,
but it would be less than or equal to [alpha], so it is equivalent
to [alpha]. *)
alpha
| Cons ((_move, t), offspring) ->
let v = - (bval (-beta) (-alpha) t) in
if beta <= v then
(* Returning [beta] or [v] makes no difference; they are equivalent. *)
v
else
let alpha = max alpha v in
(* Because v < beta holds, we still have alpha < beta. *)
assert (alpha < beta);
bval_offspring alpha beta offspring
(* -------------------------------------------------------------------------- *)
In a game tree where every leaf carries the value -1 ( loss ) , 0 ( draw ) ,
or +1 ( win ) , determining whether the first player is assured to win .
or +1 (win), determining whether the first player is assured to win. *)
let assured_win (t : tree) : bool =
let loss, win = -1, +1 in
bval loss win t >= win
(* functionally correct *)
(* wrong: too costly, uses too wide a window *)
(* -------------------------------------------------------------------------- *)
Evaluating a tree using Alpha - Beta and returning the best move .
let rec bmove_offspring alpha beta (candidate : move option) offspring : move option =
assert (alpha < beta);
match offspring() with
| Nil ->
assert (candidate <> None);
candidate
| Cons ((move, t), offspring) ->
let v = - (bval (-beta) (-alpha) t) in
if beta <= v then
Some move
else
let alpha, candidate =
if alpha < v then
(* This move improves on the previous moves: keep it. *)
v, Some move
else if candidate = None then
(* There are no previous moves, so keep this move as a default.
This ensures that we do not return [None] in the end. *)
alpha, Some move
else
(* This move does not improve on the previous candidate move
Discard it. *)
alpha, candidate
in
(* Because v < beta holds, we still have alpha < beta. *)
assert (alpha < beta);
bmove_offspring alpha beta candidate offspring
let bmove alpha beta t : move option =
assert (alpha < beta);
match t with
| TLeaf v ->
None
| TNonLeaf offspring ->
bmove_offspring alpha beta None offspring
| null | https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/alpha_beta/wrong/assured_win_naive.ml | ocaml | --------------------------------------------------------------------------
The size of a tree.
--------------------------------------------------------------------------
The height of a tree.
--------------------------------------------------------------------------
Evaluating a tree, with a sense parameter: Minimax.
--------------------------------------------------------------------------
Evaluating a tree, without a sense parameter: Negamax.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
We could project [v] onto the closed interval [alpha, beta],
but this does not make any difference; [v] is equivalent to
its projection.
We could return the maximum of the children that we have examined,
but it would be less than or equal to [alpha], so it is equivalent
to [alpha].
Returning [beta] or [v] makes no difference; they are equivalent.
Because v < beta holds, we still have alpha < beta.
--------------------------------------------------------------------------
functionally correct
wrong: too costly, uses too wide a window
--------------------------------------------------------------------------
This move improves on the previous moves: keep it.
There are no previous moves, so keep this move as a default.
This ensures that we do not return [None] in the end.
This move does not improve on the previous candidate move
Discard it.
Because v < beta holds, we still have alpha < beta. | open Seq
let rec size (t : tree) : int =
match t with
| TLeaf _ ->
1
| TNonLeaf offspring ->
1 + size_offspring offspring
and size_offspring (offspring : offspring) : int =
match offspring() with
| Nil ->
0
| Cons ((_move, t), offspring) ->
size t + size_offspring offspring
let rec height (t : tree) : int =
match t with
| TLeaf _ ->
0
| TNonLeaf offspring ->
1 + height_offspring offspring
and height_offspring (offspring : offspring) : int =
match offspring() with
| Nil ->
0
| Cons ((_move, t), offspring) ->
max (height t) (height_offspring offspring)
let rec eval (sense : sense) (t : tree) : value =
match t with
| TLeaf v ->
interpret sense v
| TNonLeaf offspring ->
eval_offspring sense offspring
and eval_offspring (sense : sense) (offspring : offspring) : value =
match offspring() with
| Nil ->
unit sense
| Cons ((_move, t), offspring) ->
join sense
(eval (opposite sense) t)
(eval_offspring sense offspring)
let rec nval (t : tree) : value =
match t with
| TLeaf v ->
v
| TNonLeaf offspring ->
nval_offspring offspring
and nval_offspring (offspring : offspring) =
match offspring() with
| Nil ->
bottom
| Cons ((_move, t), offspring) ->
max
(- nval t)
(nval_offspring offspring)
Evaluating a tree , in Negamax style , and looping over children in
a tail - recursive manner .
a tail-recursive manner. *)
let rec ntval (t : tree) : value =
match t with
| TLeaf v ->
v
| TNonLeaf offspring ->
ntval_offspring bottom offspring
and ntval_offspring (running_max : value) (offspring : offspring) : value =
match offspring() with
| Nil ->
running_max
| Cons ((_move, t), offspring) ->
let v = - ntval t in
let running_max = max running_max v in
ntval_offspring running_max offspring
Evaluating a tree , using the Alpha - Beta algorithm .
let rec bval (alpha : value) (beta : value) (t : tree) : value =
assert (alpha < beta);
match t with
| TLeaf v ->
v
| TNonLeaf offspring ->
bval_offspring alpha beta offspring
and bval_offspring (alpha : value) (beta : value) (offspring : offspring) : value =
assert (alpha < beta);
match offspring() with
| Nil ->
alpha
| Cons ((_move, t), offspring) ->
let v = - (bval (-beta) (-alpha) t) in
if beta <= v then
v
else
let alpha = max alpha v in
assert (alpha < beta);
bval_offspring alpha beta offspring
In a game tree where every leaf carries the value -1 ( loss ) , 0 ( draw ) ,
or +1 ( win ) , determining whether the first player is assured to win .
or +1 (win), determining whether the first player is assured to win. *)
let assured_win (t : tree) : bool =
let loss, win = -1, +1 in
bval loss win t >= win
Evaluating a tree using Alpha - Beta and returning the best move .
let rec bmove_offspring alpha beta (candidate : move option) offspring : move option =
assert (alpha < beta);
match offspring() with
| Nil ->
assert (candidate <> None);
candidate
| Cons ((move, t), offspring) ->
let v = - (bval (-beta) (-alpha) t) in
if beta <= v then
Some move
else
let alpha, candidate =
if alpha < v then
v, Some move
else if candidate = None then
alpha, Some move
else
alpha, candidate
in
assert (alpha < beta);
bmove_offspring alpha beta candidate offspring
let bmove alpha beta t : move option =
assert (alpha < beta);
match t with
| TLeaf v ->
None
| TNonLeaf offspring ->
bmove_offspring alpha beta None offspring
|
be95450de27257c06886dbea5693b8b683e5e5cb04f0425b536d0eb62f00c033 | EFanZh/EOPL-Exercises | exercise-4.42-test.rkt | #lang racket/base
(require rackunit)
(require "../solutions/exercise-4.x-call-by-need-lang.rkt")
(check-equal? (run "let* x = 3
in x")
(num-val 3))
(check-equal? (run "let* f = proc (x)
x
in (f 4)")
(num-val 4))
(check-equal? (run "let x = 2
in let* y = x
in begin set y = 3;
x
end")
(num-val 3))
(check-equal? (run "let x = 2
in let y = begin set x = -(x, 1);
x
end
in let a = x
in let b = y
in -(a, b)")
(num-val 0))
(check-equal? (run "let x = 2
in let* y = begin set x = -(x, 1);
x
end
in let a = x
in let b = y
in -(a, b)")
(num-val 1))
| null | https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/tests/exercise-4.42-test.rkt | racket | #lang racket/base
(require rackunit)
(require "../solutions/exercise-4.x-call-by-need-lang.rkt")
(check-equal? (run "let* x = 3
in x")
(num-val 3))
(check-equal? (run "let* f = proc (x)
x
in (f 4)")
(num-val 4))
(check-equal? (run "let x = 2
in let* y = x
x
end")
(num-val 3))
(check-equal? (run "let x = 2
x
end
in let a = x
in let b = y
in -(a, b)")
(num-val 0))
(check-equal? (run "let x = 2
x
end
in let a = x
in let b = y
in -(a, b)")
(num-val 1))
|
|
b4f686c4c56d07469478517495b46f70d99198d2b9fd34ef5230ff225cda9b28 | themetaschemer/malt | test-A-equality.rkt | (module+ test
(require rackunit)
(check-true ((equal-within-tolerance?) 1.00001 1.0001))
(check-true ((equal-within-tolerance?) 1.0002 1.0001))
(check-false ((equal-within-tolerance?) 1.0003 1.0001))
(define t0
(vector (vector (vector 0.0 2.0 4.0 6.0) (vector 8.0 10.0 12.0 14.0) (vector 16.0 18.0 20.0 22.0))
(vector (vector 24.0 26.0 28.0 30.0) (vector 32.0 34.0 36.0 38.0) (vector 40.0 42.0 44.0 46.0))))
(define t1
(vector (vector (vector 0.0 2.00001 4.00001 6.00001) (vector 8.00001 10.00001 12.00001 14.00001) (vector 16.00001 18.00001 20.00001 22.00001))
(vector (vector 24.00001 26.00001 28.00001 30.00001) (vector 32.00001 34.00001 36.00001 38.00001) (vector 40.00001 42.00001 44.00001 46.00001))))
(define t2
(vector (vector (vector (vector 0.0 2.00001 4.00001 6.00001) (vector 8.00001 10.00001 12.00001 14.00001) (vector 16.00001 18.00001 20.00001 22.00001))
(vector (vector 24.00001 26.00001 28.00001 30.00001) (vector 32.00001 34.00001 36.00001 38.00001) (vector 40.00001 42.00001 44.00001 46.00001)))))
(check-true (equal-elements? t0 t1))
(check-false (equal-elements? t0 t2))
(check-true (tensor-equal? t0 t1))
(check-false (tensor-equal? t0 t2))
(check-tensor-equal? t0 t1))
| null | https://raw.githubusercontent.com/themetaschemer/malt/78a04063a5a343f5cf4332e84da0e914cdb4d347/nested-tensors/tensors/test/test-A-equality.rkt | racket | (module+ test
(require rackunit)
(check-true ((equal-within-tolerance?) 1.00001 1.0001))
(check-true ((equal-within-tolerance?) 1.0002 1.0001))
(check-false ((equal-within-tolerance?) 1.0003 1.0001))
(define t0
(vector (vector (vector 0.0 2.0 4.0 6.0) (vector 8.0 10.0 12.0 14.0) (vector 16.0 18.0 20.0 22.0))
(vector (vector 24.0 26.0 28.0 30.0) (vector 32.0 34.0 36.0 38.0) (vector 40.0 42.0 44.0 46.0))))
(define t1
(vector (vector (vector 0.0 2.00001 4.00001 6.00001) (vector 8.00001 10.00001 12.00001 14.00001) (vector 16.00001 18.00001 20.00001 22.00001))
(vector (vector 24.00001 26.00001 28.00001 30.00001) (vector 32.00001 34.00001 36.00001 38.00001) (vector 40.00001 42.00001 44.00001 46.00001))))
(define t2
(vector (vector (vector (vector 0.0 2.00001 4.00001 6.00001) (vector 8.00001 10.00001 12.00001 14.00001) (vector 16.00001 18.00001 20.00001 22.00001))
(vector (vector 24.00001 26.00001 28.00001 30.00001) (vector 32.00001 34.00001 36.00001 38.00001) (vector 40.00001 42.00001 44.00001 46.00001)))))
(check-true (equal-elements? t0 t1))
(check-false (equal-elements? t0 t2))
(check-true (tensor-equal? t0 t1))
(check-false (tensor-equal? t0 t2))
(check-tensor-equal? t0 t1))
|
|
b95c585591ab00e5688eda7f9cb7b315097b36062b315b81f1eb8d2668a930b7 | arttuka/reagent-material-ui | noise_control_off_two_tone.cljs | (ns reagent-mui.icons.noise-control-off-two-tone
"Imports @mui/icons-material/NoiseControlOffTwoTone as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def noise-control-off-two-tone (create-svg-icon [(e "path" #js {"d" "M12 4c1.44 0 2.79.38 3.95 1.05L17.4 3.6C15.85 2.59 13.99 2 12 2s-3.85.59-5.41 1.59l1.45 1.45C9.21 4.38 10.56 4 12 4zm8 8c0 1.44-.38 2.79-1.05 3.95l1.45 1.45c1.01-1.55 1.6-3.41 1.6-5.4s-.59-3.85-1.59-5.41l-1.45 1.45C19.62 9.21 20 10.56 20 12zm-8 8c-1.44 0-2.79-.38-3.95-1.05L6.6 20.4C8.15 21.41 10.01 22 12 22s3.85-.59 5.41-1.59l-1.45-1.45C14.79 19.62 13.44 20 12 20zm-8-8c0-1.44.38-2.79 1.05-3.95L3.59 6.59C2.59 8.15 2 10.01 2 12s.59 3.85 1.59 5.41l1.45-1.45C4.38 14.79 4 13.44 4 12zm7.5-6C9.02 6 7 8.02 7 10.5c0 1.22.49 2.41 1.35 3.27l1.36 1.36c.17.17.31.44.44.82C10.56 17.17 11.71 18 13 18c1.65 0 3-1.35 3-3h-2c0 .55-.45 1-1 1-.43 0-.81-.27-.95-.68-.15-.44-.4-1.08-.93-1.61l-1.36-1.36C9.28 11.87 9 11.19 9 10.5 9 9.12 10.12 8 11.5 8c1.21 0 2.22.86 2.45 2h2.02c-.25-2.25-2.16-4-4.47-4z"}) (e "circle" #js {"cx" "13.5", "cy" "12.5", "r" "1.5"})]
"NoiseControlOffTwoTone"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/noise_control_off_two_tone.cljs | clojure | (ns reagent-mui.icons.noise-control-off-two-tone
"Imports @mui/icons-material/NoiseControlOffTwoTone as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def noise-control-off-two-tone (create-svg-icon [(e "path" #js {"d" "M12 4c1.44 0 2.79.38 3.95 1.05L17.4 3.6C15.85 2.59 13.99 2 12 2s-3.85.59-5.41 1.59l1.45 1.45C9.21 4.38 10.56 4 12 4zm8 8c0 1.44-.38 2.79-1.05 3.95l1.45 1.45c1.01-1.55 1.6-3.41 1.6-5.4s-.59-3.85-1.59-5.41l-1.45 1.45C19.62 9.21 20 10.56 20 12zm-8 8c-1.44 0-2.79-.38-3.95-1.05L6.6 20.4C8.15 21.41 10.01 22 12 22s3.85-.59 5.41-1.59l-1.45-1.45C14.79 19.62 13.44 20 12 20zm-8-8c0-1.44.38-2.79 1.05-3.95L3.59 6.59C2.59 8.15 2 10.01 2 12s.59 3.85 1.59 5.41l1.45-1.45C4.38 14.79 4 13.44 4 12zm7.5-6C9.02 6 7 8.02 7 10.5c0 1.22.49 2.41 1.35 3.27l1.36 1.36c.17.17.31.44.44.82C10.56 17.17 11.71 18 13 18c1.65 0 3-1.35 3-3h-2c0 .55-.45 1-1 1-.43 0-.81-.27-.95-.68-.15-.44-.4-1.08-.93-1.61l-1.36-1.36C9.28 11.87 9 11.19 9 10.5 9 9.12 10.12 8 11.5 8c1.21 0 2.22.86 2.45 2h2.02c-.25-2.25-2.16-4-4.47-4z"}) (e "circle" #js {"cx" "13.5", "cy" "12.5", "r" "1.5"})]
"NoiseControlOffTwoTone"))
|
|
6a7010b4f58ff590ca43c1d4ef4308e9a40968b2958a93ac9d79019ad706ccb6 | avsm/mirage-duniverse | std.ml |
module Big_int = struct
include Big_int
let sexp_of_big_int = Sexplib_num_conv.sexp_of_big_int
let big_int_of_sexp = Sexplib_num_conv.big_int_of_sexp
end
module Nat = struct
include Nat
let sexp_of_nat = Sexplib_num_conv.sexp_of_nat
let nat_of_sexp = Sexplib_num_conv.nat_of_sexp
end
module Ratio = struct
include Ratio
let sexp_of_ratio = Sexplib_num_conv.sexp_of_ratio
let ratio_of_sexp = Sexplib_num_conv.ratio_of_sexp
end
module Num = struct
include Num
let sexp_of_num = Sexplib_num_conv.sexp_of_num
let num_of_sexp = Sexplib_num_conv.num_of_sexp
end
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/sexplib/num/lib/std.ml | ocaml |
module Big_int = struct
include Big_int
let sexp_of_big_int = Sexplib_num_conv.sexp_of_big_int
let big_int_of_sexp = Sexplib_num_conv.big_int_of_sexp
end
module Nat = struct
include Nat
let sexp_of_nat = Sexplib_num_conv.sexp_of_nat
let nat_of_sexp = Sexplib_num_conv.nat_of_sexp
end
module Ratio = struct
include Ratio
let sexp_of_ratio = Sexplib_num_conv.sexp_of_ratio
let ratio_of_sexp = Sexplib_num_conv.ratio_of_sexp
end
module Num = struct
include Num
let sexp_of_num = Sexplib_num_conv.sexp_of_num
let num_of_sexp = Sexplib_num_conv.num_of_sexp
end
|
|
6b04094fa5021eeecad1f8498ae444a8ef99529ed18c4cc681f5221cdd8e8cc2 | diku-dk/futhark | Intragroup.hs | # LANGUAGE TypeFamilies #
-- | Extract limited nested parallelism for execution inside
-- individual kernel workgroups.
module Futhark.Pass.ExtractKernels.Intragroup (intraGroupParallelise) where
import Control.Monad.Identity
import Control.Monad.RWS
import Control.Monad.Trans.Maybe
import Data.Map.Strict qualified as M
import Data.Set qualified as S
import Futhark.Analysis.PrimExp.Convert
import Futhark.IR.GPU hiding (HistOp)
import Futhark.IR.GPU.Op qualified as GPU
import Futhark.IR.SOACS
import Futhark.MonadFreshNames
import Futhark.Pass.ExtractKernels.BlockedKernel
import Futhark.Pass.ExtractKernels.DistributeNests
import Futhark.Pass.ExtractKernels.Distribution
import Futhark.Pass.ExtractKernels.ToGPU
import Futhark.Tools
import Futhark.Transform.FirstOrderTransform qualified as FOT
import Futhark.Util.Log
import Prelude hiding (log)
-- | Convert the statements inside a map nest to kernel statements,
-- attempting to parallelise any remaining (top-level) parallel
-- statements. Anything that is not a map, scan or reduction will
-- simply be sequentialised. This includes sequential loops that
-- contain maps, scans or reduction. In the future, we could probably
-- do something more clever. Make sure that the amount of parallelism
-- to be exploited does not exceed the group size. Further, as a hack
-- we also consider the size of all intermediate arrays as
-- "parallelism to be exploited" to avoid exploding local memory.
--
-- We distinguish between "minimum group size" and "maximum
-- exploitable parallelism".
intraGroupParallelise ::
(MonadFreshNames m, LocalScope GPU m) =>
KernelNest ->
Lambda SOACS ->
m
( Maybe
( (SubExp, SubExp),
SubExp,
Log,
Stms GPU,
Stms GPU
)
)
intraGroupParallelise knest lam = runMaybeT $ do
(ispace, inps) <- lift $ flatKernel knest
(num_groups, w_stms) <-
lift $
runBuilder $
letSubExp "intra_num_groups"
=<< foldBinOp (Mul Int64 OverflowUndef) (intConst Int64 1) (map snd ispace)
let body = lambdaBody lam
group_size <- newVName "computed_group_size"
(wss_min, wss_avail, log, kbody) <-
lift . localScope (scopeOfLParams $ lambdaParams lam) $
intraGroupParalleliseBody body
outside_scope <- lift askScope
-- outside_scope may also contain the inputs, even though those are
-- not actually available outside the kernel.
let available v =
v `M.member` outside_scope
&& v `notElem` map kernelInputName inps
unless (all available $ namesToList $ freeIn (wss_min ++ wss_avail)) $
fail "Irregular parallelism"
((intra_avail_par, kspace, read_input_stms), prelude_stms) <- lift $
runBuilder $ do
let foldBinOp' _ [] = eSubExp $ intConst Int64 1
foldBinOp' bop (x : xs) = foldBinOp bop x xs
ws_min <-
mapM (letSubExp "one_intra_par_min" <=< foldBinOp' (Mul Int64 OverflowUndef)) $
filter (not . null) wss_min
ws_avail <-
mapM (letSubExp "one_intra_par_avail" <=< foldBinOp' (Mul Int64 OverflowUndef)) $
filter (not . null) wss_avail
-- The amount of parallelism available *in the worst case* is
equal to the smallest parallel loop , or * at least * 1 .
intra_avail_par <-
letSubExp "intra_avail_par" =<< foldBinOp' (SMin Int64) ws_avail
-- The group size is either the maximum of the minimum parallelism
exploited , or the desired parallelism ( bounded by the group
-- size) in case there is no minimum.
letBindNames [group_size]
=<< if null ws_min
then
eBinOp
(SMin Int64)
(eSubExp =<< letSubExp "max_group_size" (Op $ SizeOp $ GetSizeMax SizeGroup))
(eSubExp intra_avail_par)
else foldBinOp' (SMax Int64) ws_min
let inputIsUsed input = kernelInputName input `nameIn` freeIn body
used_inps = filter inputIsUsed inps
addStms w_stms
read_input_stms <- runBuilder_ $ mapM readGroupKernelInput used_inps
space <- mkSegSpace ispace
pure (intra_avail_par, space, read_input_stms)
let kbody' = kbody {kernelBodyStms = read_input_stms <> kernelBodyStms kbody}
let nested_pat = loopNestingPat first_nest
rts = map (length ispace `stripArray`) $ patTypes nested_pat
grid = KernelGrid (Count num_groups) (Count $ Var group_size)
lvl = SegGroup SegNoVirt (Just grid)
kstm =
Let nested_pat aux $ Op $ SegOp $ SegMap lvl kspace rts kbody'
let intra_min_par = intra_avail_par
pure
( (intra_min_par, intra_avail_par),
Var group_size,
log,
prelude_stms,
oneStm kstm
)
where
first_nest = fst knest
aux = loopNestingAux first_nest
readGroupKernelInput ::
(DistRep (Rep m), MonadBuilder m) =>
KernelInput ->
m ()
readGroupKernelInput inp
| Array {} <- kernelInputType inp = do
v <- newVName $ baseString $ kernelInputName inp
readKernelInput inp {kernelInputName = v}
letBindNames [kernelInputName inp] $ BasicOp $ Copy v
| otherwise =
readKernelInput inp
data IntraAcc = IntraAcc
{ accMinPar :: S.Set [SubExp],
accAvailPar :: S.Set [SubExp],
accLog :: Log
}
instance Semigroup IntraAcc where
IntraAcc min_x avail_x log_x <> IntraAcc min_y avail_y log_y =
IntraAcc (min_x <> min_y) (avail_x <> avail_y) (log_x <> log_y)
instance Monoid IntraAcc where
mempty = IntraAcc mempty mempty mempty
type IntraGroupM =
BuilderT GPU (RWS () IntraAcc VNameSource)
instance MonadLogger IntraGroupM where
addLog log = tell mempty {accLog = log}
runIntraGroupM ::
(MonadFreshNames m, HasScope GPU m) =>
IntraGroupM () ->
m (IntraAcc, Stms GPU)
runIntraGroupM m = do
scope <- castScope <$> askScope
modifyNameSource $ \src ->
let (((), kstms), src', acc) = runRWS (runBuilderT m scope) () src
in ((acc, kstms), src')
parallelMin :: [SubExp] -> IntraGroupM ()
parallelMin ws =
tell
mempty
{ accMinPar = S.singleton ws,
accAvailPar = S.singleton ws
}
intraGroupBody :: Body SOACS -> IntraGroupM (Body GPU)
intraGroupBody body = do
stms <- collectStms_ $ intraGroupStms $ bodyStms body
pure $ mkBody stms $ bodyResult body
intraGroupStm :: Stm SOACS -> IntraGroupM ()
intraGroupStm stm@(Let pat aux e) = do
scope <- askScope
let lvl = SegThread SegNoVirt Nothing
case e of
DoLoop merge form loopbody ->
localScope (scopeOf form') $
localScope (scopeOfFParams $ map fst merge) $ do
loopbody' <- intraGroupBody loopbody
certifying (stmAuxCerts aux) $
letBind pat $
DoLoop merge form' loopbody'
where
form' = case form of
ForLoop i it bound inps -> ForLoop i it bound inps
WhileLoop cond -> WhileLoop cond
Match cond cases defbody ifdec -> do
cases' <- mapM (traverse intraGroupBody) cases
defbody' <- intraGroupBody defbody
certifying (stmAuxCerts aux) . letBind pat $
Match cond cases' defbody' ifdec
Op soac
| "sequential_outer" `inAttrs` stmAuxAttrs aux ->
intraGroupStms . fmap (certify (stmAuxCerts aux))
=<< runBuilder_ (FOT.transformSOAC pat soac)
Op (Screma w arrs form)
| Just lam <- isMapSOAC form -> do
let loopnest = MapNesting pat aux w $ zip (lambdaParams lam) arrs
env =
DistEnv
{ distNest =
singleNesting $ Nesting mempty loopnest,
distScope =
scopeOfPat pat
<> scopeForGPU (scopeOf lam)
<> scope,
distOnInnerMap =
distributeMap,
distOnTopLevelStms =
liftInner . collectStms_ . intraGroupStms,
distSegLevel = \minw _ _ -> do
lift $ parallelMin minw
pure lvl,
distOnSOACSStms =
pure . oneStm . soacsStmToGPU,
distOnSOACSLambda =
pure . soacsLambdaToGPU
}
acc =
DistAcc
{ distTargets = singleTarget (pat, bodyResult $ lambdaBody lam),
distStms = mempty
}
addStms
=<< runDistNestT env (distributeMapBodyStms acc (bodyStms $ lambdaBody lam))
Op (Screma w arrs form)
| Just (scans, mapfun) <- isScanomapSOAC form,
Scan scanfun nes <- singleScan scans -> do
let scanfun' = soacsLambdaToGPU scanfun
mapfun' = soacsLambdaToGPU mapfun
certifying (stmAuxCerts aux) $
addStms =<< segScan lvl pat mempty w [SegBinOp Noncommutative scanfun' nes mempty] mapfun' arrs [] []
parallelMin [w]
Op (Screma w arrs form)
| Just (reds, map_lam) <- isRedomapSOAC form,
Reduce comm red_lam nes <- singleReduce reds -> do
let red_lam' = soacsLambdaToGPU red_lam
map_lam' = soacsLambdaToGPU map_lam
certifying (stmAuxCerts aux) $
addStms =<< segRed lvl pat mempty w [SegBinOp comm red_lam' nes mempty] map_lam' arrs [] []
parallelMin [w]
Op (Hist w arrs ops bucket_fun) -> do
ops' <- forM ops $ \(HistOp num_bins rf dests nes op) -> do
(op', nes', shape) <- determineReduceOp op nes
let op'' = soacsLambdaToGPU op'
pure $ GPU.HistOp num_bins rf dests nes' shape op''
let bucket_fun' = soacsLambdaToGPU bucket_fun
certifying (stmAuxCerts aux) $
addStms =<< segHist lvl pat w [] [] ops' bucket_fun' arrs
parallelMin [w]
Op (Stream w arrs accs lam)
| chunk_size_param : _ <- lambdaParams lam -> do
types <- asksScope castScope
((), stream_stms) <-
runBuilderT (sequentialStreamWholeArray pat w accs lam arrs) types
let replace (Var v) | v == paramName chunk_size_param = w
replace se = se
replaceSets (IntraAcc x y log) =
IntraAcc (S.map (map replace) x) (S.map (map replace) y) log
censor replaceSets $ intraGroupStms stream_stms
Op (Scatter w ivs lam dests) -> do
write_i <- newVName "write_i"
space <- mkSegSpace [(write_i, w)]
let lam' = soacsLambdaToGPU lam
(dests_ws, _, _) = unzip3 dests
krets = do
(a_w, a, is_vs) <-
groupScatterResults dests $ bodyResult $ lambdaBody lam'
let cs =
foldMap (foldMap resCerts . fst) is_vs
<> foldMap (resCerts . snd) is_vs
is_vs' = [(Slice $ map (DimFix . resSubExp) is, resSubExp v) | (is, v) <- is_vs]
pure $ WriteReturns cs a_w a is_vs'
inputs = do
(p, p_a) <- zip (lambdaParams lam') ivs
pure $ KernelInput (paramName p) (paramType p) p_a [Var write_i]
kstms <- runBuilder_ $
localScope (scopeOfSegSpace space) $ do
mapM_ readKernelInput inputs
addStms $ bodyStms $ lambdaBody lam'
certifying (stmAuxCerts aux) $ do
let ts = zipWith (stripArray . length) dests_ws $ patTypes pat
body = KernelBody () kstms krets
letBind pat $ Op $ SegOp $ SegMap lvl space ts body
parallelMin [w]
_ ->
addStm $ soacsStmToGPU stm
intraGroupStms :: Stms SOACS -> IntraGroupM ()
intraGroupStms = mapM_ intraGroupStm
intraGroupParalleliseBody ::
(MonadFreshNames m, HasScope GPU m) =>
Body SOACS ->
m ([[SubExp]], [[SubExp]], Log, KernelBody GPU)
intraGroupParalleliseBody body = do
(IntraAcc min_ws avail_ws log, kstms) <-
runIntraGroupM $ intraGroupStms $ bodyStms body
pure
( S.toList min_ws,
S.toList avail_ws,
log,
KernelBody () kstms $ map ret $ bodyResult body
)
where
ret (SubExpRes cs se) = Returns ResultMaySimplify cs se
| null | https://raw.githubusercontent.com/diku-dk/futhark/1955b604fabc8b86ad6c2231696eea365745480f/src/Futhark/Pass/ExtractKernels/Intragroup.hs | haskell | | Extract limited nested parallelism for execution inside
individual kernel workgroups.
| Convert the statements inside a map nest to kernel statements,
attempting to parallelise any remaining (top-level) parallel
statements. Anything that is not a map, scan or reduction will
simply be sequentialised. This includes sequential loops that
contain maps, scans or reduction. In the future, we could probably
do something more clever. Make sure that the amount of parallelism
to be exploited does not exceed the group size. Further, as a hack
we also consider the size of all intermediate arrays as
"parallelism to be exploited" to avoid exploding local memory.
We distinguish between "minimum group size" and "maximum
exploitable parallelism".
outside_scope may also contain the inputs, even though those are
not actually available outside the kernel.
The amount of parallelism available *in the worst case* is
The group size is either the maximum of the minimum parallelism
size) in case there is no minimum. | # LANGUAGE TypeFamilies #
module Futhark.Pass.ExtractKernels.Intragroup (intraGroupParallelise) where
import Control.Monad.Identity
import Control.Monad.RWS
import Control.Monad.Trans.Maybe
import Data.Map.Strict qualified as M
import Data.Set qualified as S
import Futhark.Analysis.PrimExp.Convert
import Futhark.IR.GPU hiding (HistOp)
import Futhark.IR.GPU.Op qualified as GPU
import Futhark.IR.SOACS
import Futhark.MonadFreshNames
import Futhark.Pass.ExtractKernels.BlockedKernel
import Futhark.Pass.ExtractKernels.DistributeNests
import Futhark.Pass.ExtractKernels.Distribution
import Futhark.Pass.ExtractKernels.ToGPU
import Futhark.Tools
import Futhark.Transform.FirstOrderTransform qualified as FOT
import Futhark.Util.Log
import Prelude hiding (log)
intraGroupParallelise ::
(MonadFreshNames m, LocalScope GPU m) =>
KernelNest ->
Lambda SOACS ->
m
( Maybe
( (SubExp, SubExp),
SubExp,
Log,
Stms GPU,
Stms GPU
)
)
intraGroupParallelise knest lam = runMaybeT $ do
(ispace, inps) <- lift $ flatKernel knest
(num_groups, w_stms) <-
lift $
runBuilder $
letSubExp "intra_num_groups"
=<< foldBinOp (Mul Int64 OverflowUndef) (intConst Int64 1) (map snd ispace)
let body = lambdaBody lam
group_size <- newVName "computed_group_size"
(wss_min, wss_avail, log, kbody) <-
lift . localScope (scopeOfLParams $ lambdaParams lam) $
intraGroupParalleliseBody body
outside_scope <- lift askScope
let available v =
v `M.member` outside_scope
&& v `notElem` map kernelInputName inps
unless (all available $ namesToList $ freeIn (wss_min ++ wss_avail)) $
fail "Irregular parallelism"
((intra_avail_par, kspace, read_input_stms), prelude_stms) <- lift $
runBuilder $ do
let foldBinOp' _ [] = eSubExp $ intConst Int64 1
foldBinOp' bop (x : xs) = foldBinOp bop x xs
ws_min <-
mapM (letSubExp "one_intra_par_min" <=< foldBinOp' (Mul Int64 OverflowUndef)) $
filter (not . null) wss_min
ws_avail <-
mapM (letSubExp "one_intra_par_avail" <=< foldBinOp' (Mul Int64 OverflowUndef)) $
filter (not . null) wss_avail
equal to the smallest parallel loop , or * at least * 1 .
intra_avail_par <-
letSubExp "intra_avail_par" =<< foldBinOp' (SMin Int64) ws_avail
exploited , or the desired parallelism ( bounded by the group
letBindNames [group_size]
=<< if null ws_min
then
eBinOp
(SMin Int64)
(eSubExp =<< letSubExp "max_group_size" (Op $ SizeOp $ GetSizeMax SizeGroup))
(eSubExp intra_avail_par)
else foldBinOp' (SMax Int64) ws_min
let inputIsUsed input = kernelInputName input `nameIn` freeIn body
used_inps = filter inputIsUsed inps
addStms w_stms
read_input_stms <- runBuilder_ $ mapM readGroupKernelInput used_inps
space <- mkSegSpace ispace
pure (intra_avail_par, space, read_input_stms)
let kbody' = kbody {kernelBodyStms = read_input_stms <> kernelBodyStms kbody}
let nested_pat = loopNestingPat first_nest
rts = map (length ispace `stripArray`) $ patTypes nested_pat
grid = KernelGrid (Count num_groups) (Count $ Var group_size)
lvl = SegGroup SegNoVirt (Just grid)
kstm =
Let nested_pat aux $ Op $ SegOp $ SegMap lvl kspace rts kbody'
let intra_min_par = intra_avail_par
pure
( (intra_min_par, intra_avail_par),
Var group_size,
log,
prelude_stms,
oneStm kstm
)
where
first_nest = fst knest
aux = loopNestingAux first_nest
readGroupKernelInput ::
(DistRep (Rep m), MonadBuilder m) =>
KernelInput ->
m ()
readGroupKernelInput inp
| Array {} <- kernelInputType inp = do
v <- newVName $ baseString $ kernelInputName inp
readKernelInput inp {kernelInputName = v}
letBindNames [kernelInputName inp] $ BasicOp $ Copy v
| otherwise =
readKernelInput inp
data IntraAcc = IntraAcc
{ accMinPar :: S.Set [SubExp],
accAvailPar :: S.Set [SubExp],
accLog :: Log
}
instance Semigroup IntraAcc where
IntraAcc min_x avail_x log_x <> IntraAcc min_y avail_y log_y =
IntraAcc (min_x <> min_y) (avail_x <> avail_y) (log_x <> log_y)
instance Monoid IntraAcc where
mempty = IntraAcc mempty mempty mempty
type IntraGroupM =
BuilderT GPU (RWS () IntraAcc VNameSource)
instance MonadLogger IntraGroupM where
addLog log = tell mempty {accLog = log}
runIntraGroupM ::
(MonadFreshNames m, HasScope GPU m) =>
IntraGroupM () ->
m (IntraAcc, Stms GPU)
runIntraGroupM m = do
scope <- castScope <$> askScope
modifyNameSource $ \src ->
let (((), kstms), src', acc) = runRWS (runBuilderT m scope) () src
in ((acc, kstms), src')
parallelMin :: [SubExp] -> IntraGroupM ()
parallelMin ws =
tell
mempty
{ accMinPar = S.singleton ws,
accAvailPar = S.singleton ws
}
intraGroupBody :: Body SOACS -> IntraGroupM (Body GPU)
intraGroupBody body = do
stms <- collectStms_ $ intraGroupStms $ bodyStms body
pure $ mkBody stms $ bodyResult body
intraGroupStm :: Stm SOACS -> IntraGroupM ()
intraGroupStm stm@(Let pat aux e) = do
scope <- askScope
let lvl = SegThread SegNoVirt Nothing
case e of
DoLoop merge form loopbody ->
localScope (scopeOf form') $
localScope (scopeOfFParams $ map fst merge) $ do
loopbody' <- intraGroupBody loopbody
certifying (stmAuxCerts aux) $
letBind pat $
DoLoop merge form' loopbody'
where
form' = case form of
ForLoop i it bound inps -> ForLoop i it bound inps
WhileLoop cond -> WhileLoop cond
Match cond cases defbody ifdec -> do
cases' <- mapM (traverse intraGroupBody) cases
defbody' <- intraGroupBody defbody
certifying (stmAuxCerts aux) . letBind pat $
Match cond cases' defbody' ifdec
Op soac
| "sequential_outer" `inAttrs` stmAuxAttrs aux ->
intraGroupStms . fmap (certify (stmAuxCerts aux))
=<< runBuilder_ (FOT.transformSOAC pat soac)
Op (Screma w arrs form)
| Just lam <- isMapSOAC form -> do
let loopnest = MapNesting pat aux w $ zip (lambdaParams lam) arrs
env =
DistEnv
{ distNest =
singleNesting $ Nesting mempty loopnest,
distScope =
scopeOfPat pat
<> scopeForGPU (scopeOf lam)
<> scope,
distOnInnerMap =
distributeMap,
distOnTopLevelStms =
liftInner . collectStms_ . intraGroupStms,
distSegLevel = \minw _ _ -> do
lift $ parallelMin minw
pure lvl,
distOnSOACSStms =
pure . oneStm . soacsStmToGPU,
distOnSOACSLambda =
pure . soacsLambdaToGPU
}
acc =
DistAcc
{ distTargets = singleTarget (pat, bodyResult $ lambdaBody lam),
distStms = mempty
}
addStms
=<< runDistNestT env (distributeMapBodyStms acc (bodyStms $ lambdaBody lam))
Op (Screma w arrs form)
| Just (scans, mapfun) <- isScanomapSOAC form,
Scan scanfun nes <- singleScan scans -> do
let scanfun' = soacsLambdaToGPU scanfun
mapfun' = soacsLambdaToGPU mapfun
certifying (stmAuxCerts aux) $
addStms =<< segScan lvl pat mempty w [SegBinOp Noncommutative scanfun' nes mempty] mapfun' arrs [] []
parallelMin [w]
Op (Screma w arrs form)
| Just (reds, map_lam) <- isRedomapSOAC form,
Reduce comm red_lam nes <- singleReduce reds -> do
let red_lam' = soacsLambdaToGPU red_lam
map_lam' = soacsLambdaToGPU map_lam
certifying (stmAuxCerts aux) $
addStms =<< segRed lvl pat mempty w [SegBinOp comm red_lam' nes mempty] map_lam' arrs [] []
parallelMin [w]
Op (Hist w arrs ops bucket_fun) -> do
ops' <- forM ops $ \(HistOp num_bins rf dests nes op) -> do
(op', nes', shape) <- determineReduceOp op nes
let op'' = soacsLambdaToGPU op'
pure $ GPU.HistOp num_bins rf dests nes' shape op''
let bucket_fun' = soacsLambdaToGPU bucket_fun
certifying (stmAuxCerts aux) $
addStms =<< segHist lvl pat w [] [] ops' bucket_fun' arrs
parallelMin [w]
Op (Stream w arrs accs lam)
| chunk_size_param : _ <- lambdaParams lam -> do
types <- asksScope castScope
((), stream_stms) <-
runBuilderT (sequentialStreamWholeArray pat w accs lam arrs) types
let replace (Var v) | v == paramName chunk_size_param = w
replace se = se
replaceSets (IntraAcc x y log) =
IntraAcc (S.map (map replace) x) (S.map (map replace) y) log
censor replaceSets $ intraGroupStms stream_stms
Op (Scatter w ivs lam dests) -> do
write_i <- newVName "write_i"
space <- mkSegSpace [(write_i, w)]
let lam' = soacsLambdaToGPU lam
(dests_ws, _, _) = unzip3 dests
krets = do
(a_w, a, is_vs) <-
groupScatterResults dests $ bodyResult $ lambdaBody lam'
let cs =
foldMap (foldMap resCerts . fst) is_vs
<> foldMap (resCerts . snd) is_vs
is_vs' = [(Slice $ map (DimFix . resSubExp) is, resSubExp v) | (is, v) <- is_vs]
pure $ WriteReturns cs a_w a is_vs'
inputs = do
(p, p_a) <- zip (lambdaParams lam') ivs
pure $ KernelInput (paramName p) (paramType p) p_a [Var write_i]
kstms <- runBuilder_ $
localScope (scopeOfSegSpace space) $ do
mapM_ readKernelInput inputs
addStms $ bodyStms $ lambdaBody lam'
certifying (stmAuxCerts aux) $ do
let ts = zipWith (stripArray . length) dests_ws $ patTypes pat
body = KernelBody () kstms krets
letBind pat $ Op $ SegOp $ SegMap lvl space ts body
parallelMin [w]
_ ->
addStm $ soacsStmToGPU stm
intraGroupStms :: Stms SOACS -> IntraGroupM ()
intraGroupStms = mapM_ intraGroupStm
intraGroupParalleliseBody ::
(MonadFreshNames m, HasScope GPU m) =>
Body SOACS ->
m ([[SubExp]], [[SubExp]], Log, KernelBody GPU)
intraGroupParalleliseBody body = do
(IntraAcc min_ws avail_ws log, kstms) <-
runIntraGroupM $ intraGroupStms $ bodyStms body
pure
( S.toList min_ws,
S.toList avail_ws,
log,
KernelBody () kstms $ map ret $ bodyResult body
)
where
ret (SubExpRes cs se) = Returns ResultMaySimplify cs se
|
43c80629f9f7e58445e008adbc5c8d971dbf7d326d24d7fbc7cf9bffcd18e723 | gedge-platform/gedge-platform | rabbit_mgmt_cors.erl | 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 /.
%%
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
%% Useful documentation about CORS:
%% *
%% * /
%% * -domain-requests-with-cors/
-module(rabbit_mgmt_cors).
-export([set_headers/2]).
set_headers(ReqData, Module) ->
%% Send vary: origin by default if nothing else was set.
ReqData1 = cowboy_req:set_resp_header(<<"vary">>, <<"origin">>, ReqData),
case match_origin(ReqData1) of
false ->
ReqData1;
Origin ->
ReqData2 = case cowboy_req:method(ReqData1) of
<<"OPTIONS">> -> handle_options(ReqData1, Module);
_ -> ReqData1
end,
ReqData3 = cowboy_req:set_resp_header(<<"access-control-allow-origin">>,
Origin,
ReqData2),
cowboy_req:set_resp_header(<<"access-control-allow-credentials">>,
"true",
ReqData3)
end.
Set max - age from configuration ( default : 30 minutes ) .
%% Set allow-methods from what is defined in Module:allowed_methods/2.
%% Set allow-headers to the same as the request (accept all headers).
handle_options(ReqData0, Module) ->
MaxAge = application:get_env(rabbitmq_management, cors_max_age, 1800),
Methods = case erlang:function_exported(Module, allowed_methods, 2) of
false -> [<<"HEAD">>, <<"GET">>, <<"OPTIONS">>];
true -> element(1, Module:allowed_methods(undefined, undefined))
end,
AllowMethods = string:join([binary_to_list(M) || M <- Methods], ", "),
ReqHeaders = cowboy_req:header(<<"access-control-request-headers">>, ReqData0),
ReqData1 = case MaxAge of
undefined -> ReqData0;
_ -> cowboy_req:set_resp_header(<<"access-control-max-age">>,
integer_to_list(MaxAge),
ReqData0)
end,
ReqData2 = case ReqHeaders of
undefined -> ReqData1;
_ -> cowboy_req:set_resp_header(<<"access-control-allow-headers">>,
ReqHeaders,
ReqData0)
end,
cowboy_req:set_resp_header(<<"access-control-allow-methods">>,
AllowMethods,
ReqData2).
%% If the origin header is missing or "null", we disable CORS.
%% Otherwise, we only enable it if the origin is found in the
%% cors_allow_origins configuration variable, or if "*" is (it
%% allows all origins).
match_origin(ReqData) ->
case cowboy_req:header(<<"origin">>, ReqData) of
undefined -> false;
<<"null">> -> false;
Origin ->
AllowedOrigins = application:get_env(rabbitmq_management,
cors_allow_origins, []),
case lists:member(binary_to_list(Origin), AllowedOrigins) of
true ->
Origin;
false ->
%% Maybe the configuration explicitly allows "*".
case lists:member("*", AllowedOrigins) of
true -> Origin;
false -> false
end
end
end.
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbitmq_management/src/rabbit_mgmt_cors.erl | erlang |
Useful documentation about CORS:
*
* /
* -domain-requests-with-cors/
Send vary: origin by default if nothing else was set.
Set allow-methods from what is defined in Module:allowed_methods/2.
Set allow-headers to the same as the request (accept all headers).
If the origin header is missing or "null", we disable CORS.
Otherwise, we only enable it if the origin is found in the
cors_allow_origins configuration variable, or if "*" is (it
allows all origins).
Maybe the configuration explicitly allows "*". | 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 /.
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_mgmt_cors).
-export([set_headers/2]).
set_headers(ReqData, Module) ->
ReqData1 = cowboy_req:set_resp_header(<<"vary">>, <<"origin">>, ReqData),
case match_origin(ReqData1) of
false ->
ReqData1;
Origin ->
ReqData2 = case cowboy_req:method(ReqData1) of
<<"OPTIONS">> -> handle_options(ReqData1, Module);
_ -> ReqData1
end,
ReqData3 = cowboy_req:set_resp_header(<<"access-control-allow-origin">>,
Origin,
ReqData2),
cowboy_req:set_resp_header(<<"access-control-allow-credentials">>,
"true",
ReqData3)
end.
Set max - age from configuration ( default : 30 minutes ) .
handle_options(ReqData0, Module) ->
MaxAge = application:get_env(rabbitmq_management, cors_max_age, 1800),
Methods = case erlang:function_exported(Module, allowed_methods, 2) of
false -> [<<"HEAD">>, <<"GET">>, <<"OPTIONS">>];
true -> element(1, Module:allowed_methods(undefined, undefined))
end,
AllowMethods = string:join([binary_to_list(M) || M <- Methods], ", "),
ReqHeaders = cowboy_req:header(<<"access-control-request-headers">>, ReqData0),
ReqData1 = case MaxAge of
undefined -> ReqData0;
_ -> cowboy_req:set_resp_header(<<"access-control-max-age">>,
integer_to_list(MaxAge),
ReqData0)
end,
ReqData2 = case ReqHeaders of
undefined -> ReqData1;
_ -> cowboy_req:set_resp_header(<<"access-control-allow-headers">>,
ReqHeaders,
ReqData0)
end,
cowboy_req:set_resp_header(<<"access-control-allow-methods">>,
AllowMethods,
ReqData2).
match_origin(ReqData) ->
case cowboy_req:header(<<"origin">>, ReqData) of
undefined -> false;
<<"null">> -> false;
Origin ->
AllowedOrigins = application:get_env(rabbitmq_management,
cors_allow_origins, []),
case lists:member(binary_to_list(Origin), AllowedOrigins) of
true ->
Origin;
false ->
case lists:member("*", AllowedOrigins) of
true -> Origin;
false -> false
end
end
end.
|
b99b76e8b0d730104abf8d684747fce04c5cd002f740203e0168ab8f6de08318 | higherkindness/mu-haskell | Examples.hs | # language DataKinds #
# language TypeApplications #
# language TypeFamilies #
{-|
Description : Examples for gRPC clients
Look at the source code of this module.
-}
module Mu.GRpc.Client.Examples where
import Data.Conduit
import Data.Conduit.Combinators as C
import Data.Conduit.List (consume)
import qualified Data.Text as T
import Network.HTTP2.Client (HostName, PortNumber)
import Mu.Adapter.ProtoBuf
import Mu.GRpc.Client.TyApps
import Mu.Rpc.Examples
import Mu.Schema
type instance AnnotatedSchema ProtoBufAnnotation QuickstartSchema
= '[ 'AnnField "HelloRequest" "name" ('ProtoBufId 1 '[])
, 'AnnField "HelloResponse" "message" ('ProtoBufId 1 '[])
, 'AnnField "HiRequest" "number" ('ProtoBufId 1 '[]) ]
sayHello' :: HostName -> PortNumber -> T.Text -> IO (GRpcReply T.Text)
sayHello' host port req
= do Right c <- setupGrpcClient' (grpcClientConfigSimple host port False)
fmap (\(HelloResponse r) -> r) <$> sayHello c (HelloRequest req)
sayHello :: GrpcClient -> HelloRequest -> IO (GRpcReply HelloResponse)
sayHello = gRpcCall @'MsgProtoBuf @QuickStartService @"Greeter" @"SayHello"
sayHi' :: HostName -> PortNumber -> Int -> IO [GRpcReply T.Text]
sayHi' host port n
= do Right c <- setupGrpcClient' (grpcClientConfigSimple host port False)
cndt <- sayHi c (HiRequest n)
runConduit $ cndt .| C.map (fmap (\(HelloResponse r) -> r)) .| consume
sayHi :: GrpcClient -> HiRequest -> IO (ConduitT () (GRpcReply HelloResponse) IO ())
sayHi = gRpcCall @'MsgProtoBuf @QuickStartService @"Greeter" @"SayHi"
| null | https://raw.githubusercontent.com/higherkindness/mu-haskell/e41ba786f556cfac962e0f183b36bf9ae81d69e4/grpc/client/src/Mu/GRpc/Client/Examples.hs | haskell | |
Description : Examples for gRPC clients
Look at the source code of this module.
| # language DataKinds #
# language TypeApplications #
# language TypeFamilies #
module Mu.GRpc.Client.Examples where
import Data.Conduit
import Data.Conduit.Combinators as C
import Data.Conduit.List (consume)
import qualified Data.Text as T
import Network.HTTP2.Client (HostName, PortNumber)
import Mu.Adapter.ProtoBuf
import Mu.GRpc.Client.TyApps
import Mu.Rpc.Examples
import Mu.Schema
type instance AnnotatedSchema ProtoBufAnnotation QuickstartSchema
= '[ 'AnnField "HelloRequest" "name" ('ProtoBufId 1 '[])
, 'AnnField "HelloResponse" "message" ('ProtoBufId 1 '[])
, 'AnnField "HiRequest" "number" ('ProtoBufId 1 '[]) ]
sayHello' :: HostName -> PortNumber -> T.Text -> IO (GRpcReply T.Text)
sayHello' host port req
= do Right c <- setupGrpcClient' (grpcClientConfigSimple host port False)
fmap (\(HelloResponse r) -> r) <$> sayHello c (HelloRequest req)
sayHello :: GrpcClient -> HelloRequest -> IO (GRpcReply HelloResponse)
sayHello = gRpcCall @'MsgProtoBuf @QuickStartService @"Greeter" @"SayHello"
sayHi' :: HostName -> PortNumber -> Int -> IO [GRpcReply T.Text]
sayHi' host port n
= do Right c <- setupGrpcClient' (grpcClientConfigSimple host port False)
cndt <- sayHi c (HiRequest n)
runConduit $ cndt .| C.map (fmap (\(HelloResponse r) -> r)) .| consume
sayHi :: GrpcClient -> HiRequest -> IO (ConduitT () (GRpcReply HelloResponse) IO ())
sayHi = gRpcCall @'MsgProtoBuf @QuickStartService @"Greeter" @"SayHi"
|
4c268c93e17865d7196fc4474136de70bc32dad610e67c424a09a40dcb76f99a | racket/racket7 | bulk-binding.rkt | #lang racket/base
(require "../compile/serialize-property.rkt"
"syntax.rkt"
"binding-table.rkt" ; defines `prop:bulk-binding`
"binding.rkt"
"../common/module-path.rkt"
(only-in "../compile/reserved-symbol.rkt" bulk-binding-registry-id)
"../namespace/provided.rkt")
(provide provide-binding-to-require-binding
make-bulk-binding-registry
register-bulk-provide!
registered-bulk-provide?
bulk-binding
bulk-provides-add-prefix-remove-exceptions
deserialize-bulk-binding)
;; When a require is something like `(require racket/base)`, then
we 'd like to import the many bindings from ` racket / base ` in one
;; fast step, and we'd like to share the information in syntax objects
;; from many different modules that all import `racket/base`. A
;; "bulk binding" implements that fast binding and sharing.
;; The difficult part is restoring sharing when a syntax object is
;; unmarshaled, and also leaving the binding information in the
;; providing moduling instead of the requiring module. Keeping the
;; information with the providing module should be ok, because
;; resolving a chain of module imports should ensure that the relevant
;; module is loaded before a syntax object with a bulk binding is used.
;; Still, we have to communicate information from the loading process
;; down the binding-resolving process.
;; A bulk-binding registry manages that connection. The registry is
;; similar to the module registry, in that it maps a resolved module
;; name to provide information. But it has only the provide
;; information, and not the rest of the module's implementation.
;; ----------------------------------------
;; Helper for both regular imports and bulk bindings, which converts a
providing module 's view of a binding to a requiring 's view .
(define (provide-binding-to-require-binding binding/p ; the provided binding
sym ; the symbolic name of the provide
#:self self ; the providing module's view of itself
#:mpi mpi ; the requiring module's view
#:provide-phase-level provide-phase-level
#:phase-shift phase-shift)
(define binding (provided-as-binding binding/p))
(define from-mod (module-binding-module binding))
(module-binding-update binding
#:module (module-path-index-shift from-mod self mpi)
#:nominal-module mpi
#:nominal-phase provide-phase-level
#:nominal-sym sym
#:nominal-require-phase phase-shift
#:frame-id #f
#:extra-inspector (and (not (provided-as-protected? binding/p)) ; see [*] below
(module-binding-extra-inspector binding))
#:extra-nominal-bindings null))
;; [*] If a binding has an extra inspector, it's because the binding
;; was provided as a rename transformer with a module (and the rename
;; transformer doesn't have 'not-free-identifier=?). But if we're
;; protecting the rename-transformer output, then the inspector on the
;; providing module should guard the use of the inspector attached to
;; the binding. For now, we approximate(!) that conditional use by
;; just dropping the extra inspector, which means that the original
;; binding (bounding by te rename transformer) is accessible only if
;; the end user has access to the original binding directly.
;; ----------------------------------------
(struct bulk-binding ([provides #:mutable] ; mutable so table can be found lazily on unmarshal
prefix ; #f or a prefix for the import
excepts ; hash table of excluded symbols (before adding prefix)
[self #:mutable] ; the providing module's self
mpi ; this binding's view of the providing module
provide-phase-level ; providing module's import phase
phase-shift ; providing module's instantiation phase
bulk-binding-registry) ; a registry for finding bulk bindings lazily
#:property prop:bulk-binding
(bulk-binding-class
(lambda (b mpi-shifts)
(or (bulk-binding-provides b)
;; Here's where we find provided bindings for unmarshaled syntax
(let ([mod-name (module-path-index-resolve
(apply-syntax-shifts
(bulk-binding-mpi b)
mpi-shifts))])
(unless (bulk-binding-bulk-binding-registry b)
(error "namespace mismatch: no bulk-binding registry available:"
mod-name))
(define table (bulk-binding-registry-table (bulk-binding-bulk-binding-registry b)))
(define bulk-provide (hash-ref table mod-name #f))
(unless bulk-provide
(error "namespace mismatch: bulk bindings not found in registry for module:"
mod-name))
;; Reset `provide` and `self` to the discovered information
(set-bulk-binding-self! b (bulk-provide-self bulk-provide))
(define provides (hash-ref (bulk-provide-provides bulk-provide)
(bulk-binding-provide-phase-level b)))
;; Remove exceptions and add prefix
(define excepts (bulk-binding-excepts b))
(define prefix (bulk-binding-prefix b))
(define adjusted-provides
(cond
[(or prefix (positive? (hash-count excepts)))
(bulk-provides-add-prefix-remove-exceptions provides prefix excepts)]
[else provides]))
;; Record the adjusted `provides` table for quick future access:
(set-bulk-binding-provides! b adjusted-provides)
adjusted-provides)))
(lambda (b binding sym)
;; Convert the provided binding to a required binding on
;; demand during binding resolution
(provide-binding-to-require-binding
binding (if (bulk-binding-prefix b)
(string->symbol
(substring (symbol->string sym)
(string-length (symbol->string (bulk-binding-prefix b)))))
sym)
#:self (bulk-binding-self b)
#:mpi (bulk-binding-mpi b)
#:provide-phase-level (bulk-binding-provide-phase-level b)
#:phase-shift (bulk-binding-phase-shift b))))
#:property prop:serialize
;; Serialization drops the `provides` table and the providing module's `self`
(lambda (b ser-push! reachable-scopes)
(ser-push! 'tag '#:bulk-binding)
(ser-push! (bulk-binding-prefix b))
(ser-push! (bulk-binding-excepts b))
(ser-push! (bulk-binding-mpi b))
(ser-push! (bulk-binding-provide-phase-level b))
(ser-push! (bulk-binding-phase-shift b))
(ser-push! 'tag '#:bulk-binding-registry)))
(define (deserialize-bulk-binding prefix excepts mpi provide-phase-level phase-shift bulk-binding-registry)
(bulk-binding #f prefix excepts #f mpi provide-phase-level phase-shift bulk-binding-registry))
(define (bulk-provides-add-prefix-remove-exceptions provides prefix excepts)
(for/hash ([(sym val) (in-hash provides)]
#:unless (hash-ref excepts sym #f))
(values (if prefix
(string->symbol (format "~a~a" prefix sym))
sym)
val)))
;; ----------------------------------------
;; A blk binding registry has just the provde part of a module, for
;; use in resolving bulk bindings on unmarshal
(struct bulk-provide (self provides))
;; A bulk-binding-registry object is attached to every syntax object
;; in an instantiated module, so that binding resolution on the
;; module's syntax literals can find tables of provided variables
;; based on module names
(struct bulk-binding-registry (table)) ; resolve-module-name -> bulk-provide
(define (make-bulk-binding-registry)
(bulk-binding-registry (make-hasheq)))
;; Called when a module is instantiated to register its provides:
(define (register-bulk-provide! bulk-binding-registry mod-name self provides)
(hash-set! (bulk-binding-registry-table bulk-binding-registry)
mod-name
(bulk-provide self provides)))
;; Called when a module is imported to make sure that it's in the
;; registry (as opposed to a temporary module instance during
;; expansion):
(define (registered-bulk-provide? bulk-binding-registry mod-name)
(and (hash-ref (bulk-binding-registry-table bulk-binding-registry) mod-name #f)
#t))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/expander/syntax/bulk-binding.rkt | racket | defines `prop:bulk-binding`
When a require is something like `(require racket/base)`, then
fast step, and we'd like to share the information in syntax objects
from many different modules that all import `racket/base`. A
"bulk binding" implements that fast binding and sharing.
The difficult part is restoring sharing when a syntax object is
unmarshaled, and also leaving the binding information in the
providing moduling instead of the requiring module. Keeping the
information with the providing module should be ok, because
resolving a chain of module imports should ensure that the relevant
module is loaded before a syntax object with a bulk binding is used.
Still, we have to communicate information from the loading process
down the binding-resolving process.
A bulk-binding registry manages that connection. The registry is
similar to the module registry, in that it maps a resolved module
name to provide information. But it has only the provide
information, and not the rest of the module's implementation.
----------------------------------------
Helper for both regular imports and bulk bindings, which converts a
the provided binding
the symbolic name of the provide
the providing module's view of itself
the requiring module's view
see [*] below
[*] If a binding has an extra inspector, it's because the binding
was provided as a rename transformer with a module (and the rename
transformer doesn't have 'not-free-identifier=?). But if we're
protecting the rename-transformer output, then the inspector on the
providing module should guard the use of the inspector attached to
the binding. For now, we approximate(!) that conditional use by
just dropping the extra inspector, which means that the original
binding (bounding by te rename transformer) is accessible only if
the end user has access to the original binding directly.
----------------------------------------
mutable so table can be found lazily on unmarshal
#f or a prefix for the import
hash table of excluded symbols (before adding prefix)
the providing module's self
this binding's view of the providing module
providing module's import phase
providing module's instantiation phase
a registry for finding bulk bindings lazily
Here's where we find provided bindings for unmarshaled syntax
Reset `provide` and `self` to the discovered information
Remove exceptions and add prefix
Record the adjusted `provides` table for quick future access:
Convert the provided binding to a required binding on
demand during binding resolution
Serialization drops the `provides` table and the providing module's `self`
----------------------------------------
A blk binding registry has just the provde part of a module, for
use in resolving bulk bindings on unmarshal
A bulk-binding-registry object is attached to every syntax object
in an instantiated module, so that binding resolution on the
module's syntax literals can find tables of provided variables
based on module names
resolve-module-name -> bulk-provide
Called when a module is instantiated to register its provides:
Called when a module is imported to make sure that it's in the
registry (as opposed to a temporary module instance during
expansion): | #lang racket/base
(require "../compile/serialize-property.rkt"
"syntax.rkt"
"binding.rkt"
"../common/module-path.rkt"
(only-in "../compile/reserved-symbol.rkt" bulk-binding-registry-id)
"../namespace/provided.rkt")
(provide provide-binding-to-require-binding
make-bulk-binding-registry
register-bulk-provide!
registered-bulk-provide?
bulk-binding
bulk-provides-add-prefix-remove-exceptions
deserialize-bulk-binding)
we 'd like to import the many bindings from ` racket / base ` in one
providing module 's view of a binding to a requiring 's view .
#:provide-phase-level provide-phase-level
#:phase-shift phase-shift)
(define binding (provided-as-binding binding/p))
(define from-mod (module-binding-module binding))
(module-binding-update binding
#:module (module-path-index-shift from-mod self mpi)
#:nominal-module mpi
#:nominal-phase provide-phase-level
#:nominal-sym sym
#:nominal-require-phase phase-shift
#:frame-id #f
(module-binding-extra-inspector binding))
#:extra-nominal-bindings null))
#:property prop:bulk-binding
(bulk-binding-class
(lambda (b mpi-shifts)
(or (bulk-binding-provides b)
(let ([mod-name (module-path-index-resolve
(apply-syntax-shifts
(bulk-binding-mpi b)
mpi-shifts))])
(unless (bulk-binding-bulk-binding-registry b)
(error "namespace mismatch: no bulk-binding registry available:"
mod-name))
(define table (bulk-binding-registry-table (bulk-binding-bulk-binding-registry b)))
(define bulk-provide (hash-ref table mod-name #f))
(unless bulk-provide
(error "namespace mismatch: bulk bindings not found in registry for module:"
mod-name))
(set-bulk-binding-self! b (bulk-provide-self bulk-provide))
(define provides (hash-ref (bulk-provide-provides bulk-provide)
(bulk-binding-provide-phase-level b)))
(define excepts (bulk-binding-excepts b))
(define prefix (bulk-binding-prefix b))
(define adjusted-provides
(cond
[(or prefix (positive? (hash-count excepts)))
(bulk-provides-add-prefix-remove-exceptions provides prefix excepts)]
[else provides]))
(set-bulk-binding-provides! b adjusted-provides)
adjusted-provides)))
(lambda (b binding sym)
(provide-binding-to-require-binding
binding (if (bulk-binding-prefix b)
(string->symbol
(substring (symbol->string sym)
(string-length (symbol->string (bulk-binding-prefix b)))))
sym)
#:self (bulk-binding-self b)
#:mpi (bulk-binding-mpi b)
#:provide-phase-level (bulk-binding-provide-phase-level b)
#:phase-shift (bulk-binding-phase-shift b))))
#:property prop:serialize
(lambda (b ser-push! reachable-scopes)
(ser-push! 'tag '#:bulk-binding)
(ser-push! (bulk-binding-prefix b))
(ser-push! (bulk-binding-excepts b))
(ser-push! (bulk-binding-mpi b))
(ser-push! (bulk-binding-provide-phase-level b))
(ser-push! (bulk-binding-phase-shift b))
(ser-push! 'tag '#:bulk-binding-registry)))
(define (deserialize-bulk-binding prefix excepts mpi provide-phase-level phase-shift bulk-binding-registry)
(bulk-binding #f prefix excepts #f mpi provide-phase-level phase-shift bulk-binding-registry))
(define (bulk-provides-add-prefix-remove-exceptions provides prefix excepts)
(for/hash ([(sym val) (in-hash provides)]
#:unless (hash-ref excepts sym #f))
(values (if prefix
(string->symbol (format "~a~a" prefix sym))
sym)
val)))
(struct bulk-provide (self provides))
(define (make-bulk-binding-registry)
(bulk-binding-registry (make-hasheq)))
(define (register-bulk-provide! bulk-binding-registry mod-name self provides)
(hash-set! (bulk-binding-registry-table bulk-binding-registry)
mod-name
(bulk-provide self provides)))
(define (registered-bulk-provide? bulk-binding-registry mod-name)
(and (hash-ref (bulk-binding-registry-table bulk-binding-registry) mod-name #f)
#t))
|
46b0b3a1539cfb781f4f373c330fbf9b27f4b4b85ee330433638474b6a905bdc | rowangithub/DOrder | app-succ.ml | let succ (b:int) (f:int->unit) x = f (x + 1)
let rec app (b:int) (f:int->unit) x =
if Random.bool () then app (b-1) (succ (b-1) f) (x - 1) else f x
let check (x:int) (y:int) = assert (x <= y)
let main n = app n (check n) n
let _ = main 5 | null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/popl13/app-succ.ml | ocaml | let succ (b:int) (f:int->unit) x = f (x + 1)
let rec app (b:int) (f:int->unit) x =
if Random.bool () then app (b-1) (succ (b-1) f) (x - 1) else f x
let check (x:int) (y:int) = assert (x <= y)
let main n = app n (check n) n
let _ = main 5 |
|
2e793e75700d59062956307da2ef36ed5e63a27ce9baca4f04e4b50cc20c1bb8 | Apress/practical-webdev-haskell | Auth.hs | module Adapter.PostgreSQL.Auth where
import ClassyPrelude
import qualified Domain.Auth.Types as D
import Text.StringRandom
import Data.Has
import Data.Pool
import Database.PostgreSQL.Simple.Migration
import Database.PostgreSQL.Simple
import Data.Time
type State = Pool Connection
type PG r m = (Has State r, MonadReader r m, MonadIO m, MonadThrow m)
data Config = Config
{ configUrl :: ByteString
, configStripeCount :: Int
, configMaxOpenConnPerStripe :: Int
, configIdleConnTimeout :: NominalDiffTime
} deriving (Eq, Show)
withState :: Config -> (State -> IO a) -> IO a
withState cfg action =
withPool cfg $ \state -> do
migrate state
action state
withPool :: Config -> (State -> IO a) -> IO a
withPool cfg action =
bracket initPool cleanPool action
where
initPool = createPool openConn closeConn
(configStripeCount cfg)
(configIdleConnTimeout cfg)
(configMaxOpenConnPerStripe cfg)
cleanPool = destroyAllResources
openConn = connectPostgreSQL (configUrl cfg)
closeConn = close
withConn :: PG r m => (Connection -> IO a) -> m a
withConn action = do
pool <- asks getter
liftIO . withResource pool $ \conn -> action conn
migrate :: State -> IO ()
migrate pool = withResource pool $ \conn -> do
result <- withTransaction conn (runMigrations False conn cmds)
case result of
MigrationError err -> throwString err
_ -> return ()
where
cmds = [ MigrationInitialization
, MigrationDirectory "src/Adapter/PostgreSQL/Migrations"
]
addAuth :: PG r m
=> D.Auth
-> m (Either D.RegistrationError (D.UserId, D.VerificationCode))
addAuth (D.Auth email pass) = do
let rawEmail = D.rawEmail email
rawPassw = D.rawPassword pass
generate vCode
vCode <- liftIO $ do
r <- stringRandomIO "[A-Za-z0-9]{16}"
return $ (tshow rawEmail) <> "_" <> r
-- issue query
result <- withConn $ \conn ->
try $ query conn qry (rawEmail, rawPassw, vCode)
-- interpret result
case result of
Right [Only uId] -> return $ Right (uId, vCode)
Right _ -> throwString "Should not happen: PG doesn't return userId"
Left err@SqlError{sqlState = state, sqlErrorMsg = msg} ->
if state == "23505" && "auths_email_key" `isInfixOf` msg
then return $ Left D.RegistrationErrorEmailTaken
else throwString $ "Unhandled PG exception: " <> show err
where
qry = "insert into auths \
\(email, pass, email_verification_code, is_email_verified) \
\values (?, crypt(?, gen_salt('bf')), ?, 'f') returning id"
setEmailAsVerified :: PG r m
=> D.VerificationCode
-> m (Either D.EmailVerificationError (D.UserId, D.Email))
setEmailAsVerified vCode = do
result <- withConn $ \conn -> query conn qry (Only vCode)
case result of
[(uId, mail)] -> case D.mkEmail mail of
Right email -> return $ Right (uId, email)
_ -> throwString $ "Should not happen: email in DB is not valid: " <> unpack mail
_ -> return $ Left D.EmailVerificationErrorInvalidCode
where
qry = "update auths \
\set is_email_verified = 't' \
\where email_verification_code = ? \
\returning id, cast (email as text)"
findUserByAuth :: PG r m
=> D.Auth -> m (Maybe (D.UserId, Bool))
findUserByAuth (D.Auth email pass) = do
let rawEmail = D.rawEmail email
rawPassw = D.rawPassword pass
result <- withConn $ \conn -> query conn qry (rawEmail, rawPassw)
return $ case result of
[(uId, isVerified)] -> Just (uId, isVerified)
_ -> Nothing
where
qry = "select id, is_email_verified \
\from auths \
\where email = ? and pass = crypt(?, pass)"
findEmailFromUserId :: PG r m
=> D.UserId -> m (Maybe D.Email)
findEmailFromUserId uId = do
result <- withConn $ \conn -> query conn qry (Only uId)
case result of
[Only mail] -> case D.mkEmail mail of
Right email -> return $ Just email
_ -> throwString $ "Should not happen: email in DB is not valid: " <> unpack mail
_ ->
return Nothing
where
qry = "select cast(email as text) \
\from auths \
\where id = ?" | null | https://raw.githubusercontent.com/Apress/practical-webdev-haskell/17b90c06030def254bb0497b9e357f5d3b96d0cf/11/src/Adapter/PostgreSQL/Auth.hs | haskell | issue query
interpret result | module Adapter.PostgreSQL.Auth where
import ClassyPrelude
import qualified Domain.Auth.Types as D
import Text.StringRandom
import Data.Has
import Data.Pool
import Database.PostgreSQL.Simple.Migration
import Database.PostgreSQL.Simple
import Data.Time
type State = Pool Connection
type PG r m = (Has State r, MonadReader r m, MonadIO m, MonadThrow m)
data Config = Config
{ configUrl :: ByteString
, configStripeCount :: Int
, configMaxOpenConnPerStripe :: Int
, configIdleConnTimeout :: NominalDiffTime
} deriving (Eq, Show)
withState :: Config -> (State -> IO a) -> IO a
withState cfg action =
withPool cfg $ \state -> do
migrate state
action state
withPool :: Config -> (State -> IO a) -> IO a
withPool cfg action =
bracket initPool cleanPool action
where
initPool = createPool openConn closeConn
(configStripeCount cfg)
(configIdleConnTimeout cfg)
(configMaxOpenConnPerStripe cfg)
cleanPool = destroyAllResources
openConn = connectPostgreSQL (configUrl cfg)
closeConn = close
withConn :: PG r m => (Connection -> IO a) -> m a
withConn action = do
pool <- asks getter
liftIO . withResource pool $ \conn -> action conn
migrate :: State -> IO ()
migrate pool = withResource pool $ \conn -> do
result <- withTransaction conn (runMigrations False conn cmds)
case result of
MigrationError err -> throwString err
_ -> return ()
where
cmds = [ MigrationInitialization
, MigrationDirectory "src/Adapter/PostgreSQL/Migrations"
]
addAuth :: PG r m
=> D.Auth
-> m (Either D.RegistrationError (D.UserId, D.VerificationCode))
addAuth (D.Auth email pass) = do
let rawEmail = D.rawEmail email
rawPassw = D.rawPassword pass
generate vCode
vCode <- liftIO $ do
r <- stringRandomIO "[A-Za-z0-9]{16}"
return $ (tshow rawEmail) <> "_" <> r
result <- withConn $ \conn ->
try $ query conn qry (rawEmail, rawPassw, vCode)
case result of
Right [Only uId] -> return $ Right (uId, vCode)
Right _ -> throwString "Should not happen: PG doesn't return userId"
Left err@SqlError{sqlState = state, sqlErrorMsg = msg} ->
if state == "23505" && "auths_email_key" `isInfixOf` msg
then return $ Left D.RegistrationErrorEmailTaken
else throwString $ "Unhandled PG exception: " <> show err
where
qry = "insert into auths \
\(email, pass, email_verification_code, is_email_verified) \
\values (?, crypt(?, gen_salt('bf')), ?, 'f') returning id"
setEmailAsVerified :: PG r m
=> D.VerificationCode
-> m (Either D.EmailVerificationError (D.UserId, D.Email))
setEmailAsVerified vCode = do
result <- withConn $ \conn -> query conn qry (Only vCode)
case result of
[(uId, mail)] -> case D.mkEmail mail of
Right email -> return $ Right (uId, email)
_ -> throwString $ "Should not happen: email in DB is not valid: " <> unpack mail
_ -> return $ Left D.EmailVerificationErrorInvalidCode
where
qry = "update auths \
\set is_email_verified = 't' \
\where email_verification_code = ? \
\returning id, cast (email as text)"
findUserByAuth :: PG r m
=> D.Auth -> m (Maybe (D.UserId, Bool))
findUserByAuth (D.Auth email pass) = do
let rawEmail = D.rawEmail email
rawPassw = D.rawPassword pass
result <- withConn $ \conn -> query conn qry (rawEmail, rawPassw)
return $ case result of
[(uId, isVerified)] -> Just (uId, isVerified)
_ -> Nothing
where
qry = "select id, is_email_verified \
\from auths \
\where email = ? and pass = crypt(?, pass)"
findEmailFromUserId :: PG r m
=> D.UserId -> m (Maybe D.Email)
findEmailFromUserId uId = do
result <- withConn $ \conn -> query conn qry (Only uId)
case result of
[Only mail] -> case D.mkEmail mail of
Right email -> return $ Just email
_ -> throwString $ "Should not happen: email in DB is not valid: " <> unpack mail
_ ->
return Nothing
where
qry = "select cast(email as text) \
\from auths \
\where id = ?" |
964d99234f576d9c41ce8ec85cc6f76a985bbf9eeb934215cff2762f18b90078 | zalora/aws-ec2 | Canonical.hs | module Aws.Canonical where
import Data.IORef
import Data.Time.Clock
import Aws.Core
canonicalSigData :: IO SignatureData
canonicalSigData = do
emptyRef <- newIORef []
return SignatureData { signatureTimeInfo = AbsoluteTimestamp baseTime
, signatureTime = baseTime
, signatureCredentials = Credentials "" "" emptyRef Nothing
}
baseTime = UTCTime (toEnum 0) $ secondsToDiffTime 0
| null | https://raw.githubusercontent.com/zalora/aws-ec2/60b7ad4464edf3c69da8c2f023db4ba2fa7ffc48/src/Aws/Canonical.hs | haskell | module Aws.Canonical where
import Data.IORef
import Data.Time.Clock
import Aws.Core
canonicalSigData :: IO SignatureData
canonicalSigData = do
emptyRef <- newIORef []
return SignatureData { signatureTimeInfo = AbsoluteTimestamp baseTime
, signatureTime = baseTime
, signatureCredentials = Credentials "" "" emptyRef Nothing
}
baseTime = UTCTime (toEnum 0) $ secondsToDiffTime 0
|
|
9f40151393257f602554e3b8d02f982daa0e85fa9e16360d27eb3864bae91ea0 | robert-strandh/SICL | typep-compound.lisp | (cl:in-package #:sicl-type)
;;; FIXME: check shape of type-specifier for each case.
(defun typep-compound (object type-specifier)
(case (first type-specifier)
(and
(loop for type-spec in (rest type-specifier)
always (typep object type-spec)))
(or
(loop for type-spec in (rest type-specifier)
thereis (typep object type-spec)))
(eql
(eql object (second type-specifier)))
(member
(member object (rest type-specifier)))
(not
(not (typep object (second type-specifier))))
(satisfies
(funcall (fdefinition (second type-specifier)) object))
(integer
(typep-compound-integer object (rest type-specifier)))
(cons
(cond ((null (rest type-specifier))
(consp object))
((null (rest (rest type-specifier)))
(and (consp object)
(typep (car object) (second type-specifier))))
((null (rest (rest (rest type-specifier))))
(and (consp object)
(typep (car object) (second type-specifier))
(typep (cdr object) (third type-specifier))))
(t
(error "malformed type specifier: ~s" type-specifier))))
(t
(let ((expander (type-expander (first type-specifier))))
(if (null expander)
(error "can't handle type-specifier ~s" type-specifier)
;; We found an expander. Expand TYPE-SPECIFIER and call
TYPEP recursively with the expanded type specifier .
(typep object (funcall expander type-specifier nil)))))))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/5b486e59cc0836b7650a6ad8cc0c8c2ac35b40f9/Code/Types/Typep/typep-compound.lisp | lisp | FIXME: check shape of type-specifier for each case.
We found an expander. Expand TYPE-SPECIFIER and call | (cl:in-package #:sicl-type)
(defun typep-compound (object type-specifier)
(case (first type-specifier)
(and
(loop for type-spec in (rest type-specifier)
always (typep object type-spec)))
(or
(loop for type-spec in (rest type-specifier)
thereis (typep object type-spec)))
(eql
(eql object (second type-specifier)))
(member
(member object (rest type-specifier)))
(not
(not (typep object (second type-specifier))))
(satisfies
(funcall (fdefinition (second type-specifier)) object))
(integer
(typep-compound-integer object (rest type-specifier)))
(cons
(cond ((null (rest type-specifier))
(consp object))
((null (rest (rest type-specifier)))
(and (consp object)
(typep (car object) (second type-specifier))))
((null (rest (rest (rest type-specifier))))
(and (consp object)
(typep (car object) (second type-specifier))
(typep (cdr object) (third type-specifier))))
(t
(error "malformed type specifier: ~s" type-specifier))))
(t
(let ((expander (type-expander (first type-specifier))))
(if (null expander)
(error "can't handle type-specifier ~s" type-specifier)
TYPEP recursively with the expanded type specifier .
(typep object (funcall expander type-specifier nil)))))))
|
30cfdffa2fe0a33d68f4be9a4781e705e2e9850e72bd7790bc753211799a73f7 | plumatic/grab-bag | observer.clj | (ns plumbing.observer
(:use plumbing.core)
(:require
[plumbing.error :as err]
[plumbing.logging :as log]
[plumbing.map :as map]
[plumbing.time :as time])
(:import
[java.lang.ref WeakReference]
[java.util Timer TimerTask]
[java.util.concurrent ExecutorService Executors]))
Observer Interface
(def +stop-watching+ (Object.))
(defprotocol Observer
(observed-fn [this k opts f]
"Return a wrapped version of f that logs results under k.
Opts is either :log or :stats for now.")
(watch-fn!* [this k merge-spec f args]
"For internal use. Users should call watch-fn!.")
(leaf* [this k merge-spec]
"Return a fn to call with observations, or nil.
merge-spec is {:report :merge}, with defaults identity/conj
merge-fn tells how to merge in new values, and report-fn generates a report from
map plus an additional map of global values.")
(sub-observer [this k]
"Create a new sub-observer of obs under key k.")
(report [this global-data]
"Generate a report.")
(get-path [this]
"Return the seq of keys corresponding to sub-observer paths to this"))
(defn watch-fn!
"Call f regularly, logging the results into k on obs.
f can return +stop-watching+ to stop watching it, or it will be
automatically stopped if any of the resources (passed as args)
become collectable by the GC."
[obs k merge-spec f & args]
(watch-fn!* obs k merge-spec f args))
(defn report-hook "Call f on every report, generating a map reported under k"
[observer k f]
(leaf* observer k {:report (fn [_ _] (f))}))
(defn counter
"Make a counter you can call with any number of keys, which counts into a nested map.
Expect pain if you call on a strict prefix of keys, e.g., (c :kittens) (c :kittens :chin)"
[o k]
(let [raw
(leaf*
o k
{:merge
(fn [old ks]
(update-in (or old {}) ks (fnil inc 0)))})]
(fn [& ks] (when raw (raw ks)))))
(defn stats-counter
"Like counter, but the last argument is a real number, and we'll accumulate the
mean as well as the count."
[o k]
(let [raw
(leaf*
o k
{:merge
(fn [old [ks v]]
(update-in (or old {}) ks (fn [[c t]] [(inc (or c 0)) (+ (or t 0.0) v)])))
:report (fn [m _] (map/map-leaves (fn [[c t]] {:count c :mean (/ t c) :total t}) m))})]
(fn [& ks] (when raw (raw [(drop-last ks) (last ks)])))))
(defn gen-key [^String prefix]
(-> prefix gensym name keyword))
;;; Helpers for implementors
(defn watch-with-resources! [schedule! store! f res]
(schedule!
(let [refs (doall (map #(WeakReference. %) res))]
(fn wrap []
(let [res (map #(.get ^WeakReference %) refs)]
(when (every? identity res)
(let [result (apply f res)]
(when-not (identical? result +stop-watching+)
(store! result)
(schedule! wrap)))))))))
(defn observe-fn-log [o k f]
(if-let [l (leaf* o k {})]
(comp l f)
(constantly nil)))
(defn div [x y]
(when (and x y (> y 0))
(float (/ x y))))
(defn time-reporter []
(let [start (millis)]
(fn []
(let [end (millis)]
{:last end
:time (max 0 (- end start))}))))
(defn observe-fn-stats [o k f opts]
(if-let [l (leaf*
o k
{:merge (fn [old new]
(reduce (fn [m [k v]]
(assoc m k (cons v (get m k))))
(or old {}) new))
:report
(fn [{:keys [time last] :as b} {:keys [duration]}]
(let [c (count time)
time (reduce + time)]
(assoc (map-vals count b)
:time time
:last (time/to-string (time/from-long (first last)))
:count c
:avg-time (div time c)
:p-data-loss (div (count (apply concat (vals (dissoc b :time :last)))) c))))})]
(fn [& args]
(let [time-report (time-reporter)
result (try (apply f args)
(catch Throwable t
(l (assoc (time-report) (-> t err/cause err/ex-name) 1))
(throw t)))]
(l (time-report))
result))
f))
(defn observe-fn-counts [obs k f group-fn]
(if-let [l (leaf* obs k {:merge (partial merge-with +)
:report (fn [m _]
(reduce (fn [m [ks v]] (assoc-in m ks v)) {} m))
})]
(fn [& args]
(l {(group-fn args) 1})
(apply f args))
f))
(defn default-observed-fn [obs k opts f]
(let [opts (if (map? opts) opts {:type opts})]
(case (:type opts)
:log (observe-fn-log obs k f)
:stats (observe-fn-stats obs k f opts)
:counts (observe-fn-counts obs k f (:group opts)))))
Noop implementation
(extend-type nil
Observer
(observed-fn [this k opts f] (default-observed-fn this k opts f))
(watch-fn!* [this k merge-spec f rs] nil)
(leaf* [this k merge-spec] nil)
(sub-observer [this k] nil)
(report [this global-data] nil)
(get-path [this] []))
Simple implementation --- stores under seqs of keys
;;; update-key! takes a key-seq and update-fn.
(defrecord SimpleObserver [key-seq update! get schedule! report-atom child-atom]
Observer
(observed-fn [this k opts f]
(default-observed-fn this k opts f))
(watch-fn!* [this k merge-spec f rs]
(when-let [l (leaf* this k merge-spec)]
(watch-with-resources! schedule! l f rs)))
(leaf* [this k merge-spec]
(let [{:keys [merge report]
:or {merge conj report (fn [m _] m)}} merge-spec
ks (conj key-seq k)]
(when (:report merge-spec) ;; TODO: remove this when log is fixed.
(assert (not (contains? @report-atom k))))
(swap! report-atom assoc k #(report (get ks) %))
(fn [x] (update! ks #(merge % x)))))
(sub-observer [this k]
(or (@child-atom k)
(let [sub (SimpleObserver. (conj key-seq k) update! get schedule! (atom {}) (atom {}))]
(swap! child-atom assoc k sub)
(swap! report-atom assoc k #(report sub %))
sub)))
(report [this global-data]
(map-vals #(% global-data) @report-atom))
(get-path [this] key-seq))
(defn simple-scheduler []
{:executor (Executors/newCachedThreadPool)
:timer (Timer.)})
(defn schedule-fn [{:keys [^ExecutorService executor ^Timer timer]} f in-ms]
(.schedule
timer
(proxy [TimerTask] [] (run [] (.submit executor ^Runnable f)))
(long in-ms)))
(defn make-simple-observer [update! get & [poll-delay]]
(let [scheduler (simple-scheduler)
poll-delay (or poll-delay 1000)]
(SimpleObserver.
[]
update! get
#(schedule-fn scheduler % poll-delay)
(atom {}) (atom {}))))
(defn make-atom-observer [& [poll-delay]]
(let [a (atom {})]
(make-simple-observer
(fn [ks f] (swap! a update-in ks f))
(fn [ks]
(let [vs (get-in @a ks)]
(swap! a update-in ks (constantly nil))
vs))
poll-delay)))
| null | https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/plumbing/src/plumbing/observer.clj | clojure | Helpers for implementors
update-key! takes a key-seq and update-fn.
TODO: remove this when log is fixed. | (ns plumbing.observer
(:use plumbing.core)
(:require
[plumbing.error :as err]
[plumbing.logging :as log]
[plumbing.map :as map]
[plumbing.time :as time])
(:import
[java.lang.ref WeakReference]
[java.util Timer TimerTask]
[java.util.concurrent ExecutorService Executors]))
Observer Interface
(def +stop-watching+ (Object.))
(defprotocol Observer
(observed-fn [this k opts f]
"Return a wrapped version of f that logs results under k.
Opts is either :log or :stats for now.")
(watch-fn!* [this k merge-spec f args]
"For internal use. Users should call watch-fn!.")
(leaf* [this k merge-spec]
"Return a fn to call with observations, or nil.
merge-spec is {:report :merge}, with defaults identity/conj
merge-fn tells how to merge in new values, and report-fn generates a report from
map plus an additional map of global values.")
(sub-observer [this k]
"Create a new sub-observer of obs under key k.")
(report [this global-data]
"Generate a report.")
(get-path [this]
"Return the seq of keys corresponding to sub-observer paths to this"))
(defn watch-fn!
"Call f regularly, logging the results into k on obs.
f can return +stop-watching+ to stop watching it, or it will be
automatically stopped if any of the resources (passed as args)
become collectable by the GC."
[obs k merge-spec f & args]
(watch-fn!* obs k merge-spec f args))
(defn report-hook "Call f on every report, generating a map reported under k"
[observer k f]
(leaf* observer k {:report (fn [_ _] (f))}))
(defn counter
"Make a counter you can call with any number of keys, which counts into a nested map.
Expect pain if you call on a strict prefix of keys, e.g., (c :kittens) (c :kittens :chin)"
[o k]
(let [raw
(leaf*
o k
{:merge
(fn [old ks]
(update-in (or old {}) ks (fnil inc 0)))})]
(fn [& ks] (when raw (raw ks)))))
(defn stats-counter
"Like counter, but the last argument is a real number, and we'll accumulate the
mean as well as the count."
[o k]
(let [raw
(leaf*
o k
{:merge
(fn [old [ks v]]
(update-in (or old {}) ks (fn [[c t]] [(inc (or c 0)) (+ (or t 0.0) v)])))
:report (fn [m _] (map/map-leaves (fn [[c t]] {:count c :mean (/ t c) :total t}) m))})]
(fn [& ks] (when raw (raw [(drop-last ks) (last ks)])))))
(defn gen-key [^String prefix]
(-> prefix gensym name keyword))
(defn watch-with-resources! [schedule! store! f res]
(schedule!
(let [refs (doall (map #(WeakReference. %) res))]
(fn wrap []
(let [res (map #(.get ^WeakReference %) refs)]
(when (every? identity res)
(let [result (apply f res)]
(when-not (identical? result +stop-watching+)
(store! result)
(schedule! wrap)))))))))
(defn observe-fn-log [o k f]
(if-let [l (leaf* o k {})]
(comp l f)
(constantly nil)))
(defn div [x y]
(when (and x y (> y 0))
(float (/ x y))))
(defn time-reporter []
(let [start (millis)]
(fn []
(let [end (millis)]
{:last end
:time (max 0 (- end start))}))))
(defn observe-fn-stats [o k f opts]
(if-let [l (leaf*
o k
{:merge (fn [old new]
(reduce (fn [m [k v]]
(assoc m k (cons v (get m k))))
(or old {}) new))
:report
(fn [{:keys [time last] :as b} {:keys [duration]}]
(let [c (count time)
time (reduce + time)]
(assoc (map-vals count b)
:time time
:last (time/to-string (time/from-long (first last)))
:count c
:avg-time (div time c)
:p-data-loss (div (count (apply concat (vals (dissoc b :time :last)))) c))))})]
(fn [& args]
(let [time-report (time-reporter)
result (try (apply f args)
(catch Throwable t
(l (assoc (time-report) (-> t err/cause err/ex-name) 1))
(throw t)))]
(l (time-report))
result))
f))
(defn observe-fn-counts [obs k f group-fn]
(if-let [l (leaf* obs k {:merge (partial merge-with +)
:report (fn [m _]
(reduce (fn [m [ks v]] (assoc-in m ks v)) {} m))
})]
(fn [& args]
(l {(group-fn args) 1})
(apply f args))
f))
(defn default-observed-fn [obs k opts f]
(let [opts (if (map? opts) opts {:type opts})]
(case (:type opts)
:log (observe-fn-log obs k f)
:stats (observe-fn-stats obs k f opts)
:counts (observe-fn-counts obs k f (:group opts)))))
Noop implementation
(extend-type nil
Observer
(observed-fn [this k opts f] (default-observed-fn this k opts f))
(watch-fn!* [this k merge-spec f rs] nil)
(leaf* [this k merge-spec] nil)
(sub-observer [this k] nil)
(report [this global-data] nil)
(get-path [this] []))
Simple implementation --- stores under seqs of keys
(defrecord SimpleObserver [key-seq update! get schedule! report-atom child-atom]
Observer
(observed-fn [this k opts f]
(default-observed-fn this k opts f))
(watch-fn!* [this k merge-spec f rs]
(when-let [l (leaf* this k merge-spec)]
(watch-with-resources! schedule! l f rs)))
(leaf* [this k merge-spec]
(let [{:keys [merge report]
:or {merge conj report (fn [m _] m)}} merge-spec
ks (conj key-seq k)]
(assert (not (contains? @report-atom k))))
(swap! report-atom assoc k #(report (get ks) %))
(fn [x] (update! ks #(merge % x)))))
(sub-observer [this k]
(or (@child-atom k)
(let [sub (SimpleObserver. (conj key-seq k) update! get schedule! (atom {}) (atom {}))]
(swap! child-atom assoc k sub)
(swap! report-atom assoc k #(report sub %))
sub)))
(report [this global-data]
(map-vals #(% global-data) @report-atom))
(get-path [this] key-seq))
(defn simple-scheduler []
{:executor (Executors/newCachedThreadPool)
:timer (Timer.)})
(defn schedule-fn [{:keys [^ExecutorService executor ^Timer timer]} f in-ms]
(.schedule
timer
(proxy [TimerTask] [] (run [] (.submit executor ^Runnable f)))
(long in-ms)))
(defn make-simple-observer [update! get & [poll-delay]]
(let [scheduler (simple-scheduler)
poll-delay (or poll-delay 1000)]
(SimpleObserver.
[]
update! get
#(schedule-fn scheduler % poll-delay)
(atom {}) (atom {}))))
(defn make-atom-observer [& [poll-delay]]
(let [a (atom {})]
(make-simple-observer
(fn [ks f] (swap! a update-in ks f))
(fn [ks]
(let [vs (get-in @a ks)]
(swap! a update-in ks (constantly nil))
vs))
poll-delay)))
|
b2b5ed98a804d0222a3f72fe1df7b4a9da2a88e5849d0e321d41b73ae7e2b09f | songyahui/AlgebraicEffect | parsetree.ml | (**************************************************************************)
(* *)
(* 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 Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Abstract syntax tree produced by parsing
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
*)
open Asttypes
(* basic term *)
type basic_t = BINT of int | UNIT | VARName of string | List of int list
(* an occurrence of an effect *)
type instant = Instant of string * basic_t list
type term =
| Num of int
| TList of (term list)
| TTupple of (term list)
| Var of string
| Plus of term * term
| Minus of term * term
| TListAppend of term * term
type bin_op = GT | LT | EQ | GTEQ | LTEQ
type pi =
| True
| False
| Atomic of bin_op * term * term
| And of pi * pi
| Or of pi * pi
| Imply of pi * pi
| Not of pi
| Predicate of string * term
type kappa =
| EmptyHeap
| PointsTo of (string * term)
| SepConj of kappa * kappa
type stagedSpec =
| Require of kappa
| NormalReturn of (kappa * basic_t list)
basic_t is a placeholder for the resumned value
| Exists of (string list)
(* type linearStagedSpec = stagedSpec list *)
(* type spec = (pi * linearStagedSpec) list *)
type spec = stagedSpec list
Flatten Form
= = = = = = = = = = = =
S : : = req H | H & Norm | H & Eff | local v *
N : : = \/ { S; .. ;S }
Flatten Form
============
S ::= req H | H & Norm | H & Eff | local v*
N ::= \/ {S;..;S}
*)
type constant =
Pconst_integer of string * char option
3 3l 3L 3n
Suffixes [ g - z][G - Z ] are accepted by the parser .
Suffixes except ' l ' , ' L ' and ' n ' are rejected by the typechecker
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes except 'l', 'L' and 'n' are rejected by the typechecker
*)
| Pconst_char of char
(* 'c' *)
| Pconst_string of string * Location.t * string option
(* "constant"
{delim|other constant|delim}
The location span the content of the string, without the delimiters.
*)
| Pconst_float of string * char option
(* 3.4 2e5 1.4e-4
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes are rejected by the typechecker.
*)
type location_stack = Location.t list
* { 1 Extension points }
type attribute = {
attr_name : string loc;
attr_payload : payload;
attr_loc : Location.t;
}
(* [@id ARG]
[@@id ARG]
Metadata containers passed around within the AST.
The compiler ignores unknown attributes.
*)
and extension = string loc * payload
(* [%id ARG]
[%%id ARG]
Sub-language placeholder -- rejected by the typechecker.
*)
and attributes = attribute list
and payload =
| PStr of structure
: SIG
| PTyp of core_type (* : T *)
| PPat of pattern * expression option (* ? P or ? P when E *)
* { 1 Core language }
(* Type expressions *)
and core_type =
{
ptyp_desc: core_type_desc;
ptyp_loc: Location.t;
ptyp_loc_stack: location_stack;
ptyp_attributes: attributes; (* ... [@id1] [@id2] *)
}
and core_type_desc =
| Ptyp_any
(* _ *)
| Ptyp_var of string
(* 'a *)
| Ptyp_arrow of arg_label * core_type * core_type
(* T1 -> T2 Simple
~l:T1 -> T2 Labelled
?l:T1 -> T2 Optional
*)
| Ptyp_tuple of core_type list
T1 * ... * Tn
Invariant : n > = 2
Invariant: n >= 2
*)
| Ptyp_constr of Longident.t loc * core_type list
(* tconstr
T tconstr
(T1, ..., Tn) tconstr
*)
| Ptyp_object of object_field list * closed_flag
(* < l1:T1; ...; ln:Tn > (flag = Closed)
< l1:T1; ...; ln:Tn; .. > (flag = Open)
*)
| Ptyp_class of Longident.t loc * core_type list
# tconstr
T # tconstr
( T1 , ... , Tn ) # tconstr
T #tconstr
(T1, ..., Tn) #tconstr
*)
| Ptyp_alias of core_type * string
(* T as 'a *)
| Ptyp_variant of row_field list * closed_flag * label list option
(* [ `A|`B ] (flag = Closed; labels = None)
[> `A|`B ] (flag = Open; labels = None)
[< `A|`B ] (flag = Closed; labels = Some [])
[< `A|`B > `X `Y ](flag = Closed; labels = Some ["X";"Y"])
*)
| Ptyp_poly of string loc list * core_type
' a1 ... ' an . T
Can only appear in the following context :
- As the core_type of a Ppat_constraint node corresponding
to a constraint on a let - binding : let x : ' a1 ... ' an . T
= e ...
- Under Cfk_virtual for methods ( not values ) .
- As the core_type of a Pctf_method node .
- As the core_type of a Pexp_poly node .
- As the pld_type field of a label_declaration .
- As a core_type of a Ptyp_object node .
Can only appear in the following context:
- As the core_type of a Ppat_constraint node corresponding
to a constraint on a let-binding: let x : 'a1 ... 'an. T
= e ...
- Under Cfk_virtual for methods (not values).
- As the core_type of a Pctf_method node.
- As the core_type of a Pexp_poly node.
- As the pld_type field of a label_declaration.
- As a core_type of a Ptyp_object node.
*)
| Ptyp_package of package_type
(* (module S) *)
| Ptyp_extension of extension
(* [%id] *)
and package_type = Longident.t loc * (Longident.t loc * core_type) list
(*
(module S)
(module S with type t1 = T1 and ... and tn = Tn)
*)
and row_field = {
prf_desc : row_field_desc;
prf_loc : Location.t;
prf_attributes : attributes;
}
and row_field_desc =
| Rtag of label loc * bool * core_type list
[ ` A ] ( true , [ ] )
[ ` A of T ] ( false , [ T ] )
[ ` A of T1 & .. & Tn ] ( false , [ T1; ... Tn ] )
[ ` A of & T1 & .. & Tn ] ( true , [ T1; ... Tn ] )
- The ' bool ' field is true if the tag contains a
constant ( empty ) constructor .
- ' & ' occurs when several types are used for the same constructor
( see 4.2 in the manual )
[`A of T] ( false, [T] )
[`A of T1 & .. & Tn] ( false, [T1;...Tn] )
[`A of & T1 & .. & Tn] ( true, [T1;...Tn] )
- The 'bool' field is true if the tag contains a
constant (empty) constructor.
- '&' occurs when several types are used for the same constructor
(see 4.2 in the manual)
*)
| Rinherit of core_type
(* [ | t ] *)
and object_field = {
pof_desc : object_field_desc;
pof_loc : Location.t;
pof_attributes : attributes;
}
and object_field_desc =
| Otag of label loc * core_type
| Oinherit of core_type
(* Patterns *)
and pattern =
{
ppat_desc: pattern_desc;
ppat_loc: Location.t;
ppat_loc_stack: location_stack;
ppat_attributes: attributes; (* ... [@id1] [@id2] *)
}
and pattern_desc =
| Ppat_any
(* _ *)
| Ppat_var of string loc
(* x *)
| Ppat_alias of pattern * string loc
(* P as 'a *)
| Ppat_constant of constant
1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Ppat_interval of constant * constant
(* 'a'..'z'
Other forms of interval are recognized by the parser
but rejected by the type-checker. *)
| Ppat_tuple of pattern list
( P1 , ... , Pn )
Invariant : n > = 2
Invariant: n >= 2
*)
| Ppat_construct of Longident.t loc * pattern option
C None
C P Some P
C ( P1 , ... , Pn ) Some ( Ppat_tuple [ P1 ; ... ; Pn ] )
C P Some P
C (P1, ..., Pn) Some (Ppat_tuple [P1; ...; Pn])
*)
| Ppat_variant of label * pattern option
(* `A (None)
`A P (Some P)
*)
| Ppat_record of (Longident.t loc * pattern) list * closed_flag
{ l1 = P1 ; ... ; ln = Pn } ( flag = Closed )
{ l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open )
Invariant : n > 0
{ l1=P1; ...; ln=Pn; _} (flag = Open)
Invariant: n > 0
*)
| Ppat_array of pattern list
(* [| P1; ...; Pn |] *)
| Ppat_or of pattern * pattern
P1 | P2
| Ppat_constraint of pattern * core_type
(* (P : T) *)
| Ppat_type of Longident.t loc
(* #tconst *)
| Ppat_lazy of pattern
(* lazy P *)
| Ppat_unpack of string option loc
(* (module P) Some "P"
(module _) None
Note: (module P : S) is represented as
Ppat_constraint(Ppat_unpack, Ptyp_package)
*)
| Ppat_exception of pattern
(* exception P *)
| Ppat_effect of pattern * pattern
(* effect P P *)
| Ppat_extension of extension
(* [%id] *)
| Ppat_open of Longident.t loc * pattern
(* M.(P) *)
(* Value expressions *)
and expression =
{
pexp_desc: expression_desc;
pexp_loc: Location.t;
pexp_loc_stack: location_stack;
pexp_attributes: attributes; (* ... [@id1] [@id2] *)
pexp_effectspec: spec option;
(* (spec * spec list) option; *)
}
and expression_desc =
| Pexp_ident of Longident.t loc
(* x
M.x
*)
| Pexp_constant of constant
1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Pexp_let of rec_flag * value_binding list * expression
let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Pexp_function of case list
(* function P1 -> E1 | ... | Pn -> En *)
| Pexp_fun of arg_label * expression option * pattern * expression
fun P - > E1 ( Simple , None )
fun ~l :P - > E1 ( Labelled l , None )
fun ? l :P - > E1 ( Optional l , None )
fun ? l:(P = E0 ) - > E1 ( Optional l , Some E0 )
Notes :
- If E0 is provided , only Optional is allowed .
- " fun P1 P2 .. Pn - > E1 " is represented as nested Pexp_fun .
- " let f P = E " is represented using Pexp_fun .
fun ~l:P -> E1 (Labelled l, None)
fun ?l:P -> E1 (Optional l, None)
fun ?l:(P = E0) -> E1 (Optional l, Some E0)
Notes:
- If E0 is provided, only Optional is allowed.
- "fun P1 P2 .. Pn -> E1" is represented as nested Pexp_fun.
- "let f P = E" is represented using Pexp_fun.
*)
| Pexp_apply of expression * (arg_label * expression) list
E0 ~l1 : E1 ... ~ln : En
li can be empty ( non labeled argument ) or start with ' ? '
( optional argument ) .
Invariant : n > 0
li can be empty (non labeled argument) or start with '?'
(optional argument).
Invariant: n > 0
*)
| Pexp_match of expression * case list
match E0 with P1 - > E1 | ... | Pn - > En
| Pexp_try of expression * case list
try E0 with P1 - > E1 | ... | Pn - > En
| Pexp_tuple of expression list
( E1 , ... , En )
Invariant : n > = 2
Invariant: n >= 2
*)
| Pexp_construct of Longident.t loc * expression option
(* C None
C E Some E
C (E1, ..., En) Some (Pexp_tuple[E1;...;En])
*)
| Pexp_variant of label * expression option
(* `A (None)
`A E (Some E)
*)
| Pexp_record of (Longident.t loc * expression) list * expression option
{ l1 = P1 ; ... ; ln = Pn } ( None )
{ E0 with l1 = P1 ; ... ; ln = Pn } ( Some E0 )
Invariant : n > 0
{ E0 with l1=P1; ...; ln=Pn } (Some E0)
Invariant: n > 0
*)
| Pexp_field of expression * Longident.t loc
(* E.l *)
| Pexp_setfield of expression * Longident.t loc * expression
E1.l < - E2
| Pexp_array of expression list
(* [| E1; ...; En |] *)
| Pexp_ifthenelse of expression * expression * expression option
if E1 then E2 else E3
| Pexp_sequence of expression * expression
(* E1; E2 *)
| Pexp_while of expression * expression
(* while E1 do E2 done *)
| Pexp_for of
pattern * expression * expression * direction_flag * expression
for i = E1 to E2 do E3 done ( flag = Upto )
for i = E1 downto E2 do E3 done ( flag = )
for i = E1 downto E2 do E3 done (flag = Downto)
*)
| Pexp_constraint of expression * core_type
(* (E : T) *)
| Pexp_coerce of expression * core_type option * core_type
(* (E :> T) (None, T)
(E : T0 :> T) (Some T0, T)
*)
| Pexp_send of expression * label loc
(* E # m *)
| Pexp_new of Longident.t loc
(* new M.c *)
| Pexp_setinstvar of label loc * expression
(* x <- 2 *)
| Pexp_override of (label loc * expression) list
{ < x1 = E1 ; ... ; > }
| Pexp_letmodule of string option loc * module_expr * expression
(* let module M = ME in E *)
| Pexp_letexception of extension_constructor * expression
(* let exception C in E *)
| Pexp_assert of expression
(* assert E
Note: "assert false" is treated in a special way by the
type-checker. *)
| Pexp_lazy of expression
(* lazy E *)
| Pexp_poly of expression * core_type option
Used for method bodies .
Can only be used as the expression under
for methods ( not values ) .
Can only be used as the expression under Cfk_concrete
for methods (not values). *)
| Pexp_object of class_structure
(* object ... end *)
| Pexp_newtype of string loc * expression
(* fun (type t) -> E *)
| Pexp_pack of module_expr
(* (module ME)
(module ME : S) is represented as
Pexp_constraint(Pexp_pack, Ptyp_package S) *)
| Pexp_open of open_declaration * expression
(* M.(E)
let open M in E
let! open M in E *)
| Pexp_letop of letop
(* let* P = E in E
let* P = E and* P = E in E *)
| Pexp_extension of extension
(* [%id] *)
| Pexp_unreachable
(* . *)
and case = (* (P -> E) or (P when E0 -> E) *)
{
pc_lhs: pattern;
pc_guard: expression option;
pc_rhs: expression;
}
and letop =
{
let_ : binding_op;
ands : binding_op list;
body : expression;
}
and binding_op =
{
pbop_op : string loc;
pbop_pat : pattern;
pbop_exp : expression;
pbop_loc : Location.t;
}
(* Value descriptions *)
and value_description =
{
pval_name: string loc;
pval_type: core_type;
pval_prim: string list;
pval_attributes: attributes; (* ... [@@id1] [@@id2] *)
pval_loc: Location.t;
}
(*
val x: T (prim = [])
external x: T = "s1" ... "sn" (prim = ["s1";..."sn"])
*)
(* Type declarations *)
and type_declaration =
{
ptype_name: string loc;
ptype_params: (core_type * (variance * injectivity)) list;
(* ('a1,...'an) t; None represents _*)
ptype_cstrs: (core_type * core_type * Location.t) list;
... constraint T1 = T1 ' ... constraint
ptype_kind: type_kind;
ptype_private: private_flag; (* = private ... *)
ptype_manifest: core_type option; (* = T *)
ptype_attributes: attributes; (* ... [@@id1] [@@id2] *)
ptype_loc: Location.t;
}
(*
type t (abstract, no manifest)
type t = T0 (abstract, manifest=T0)
type t = C of T | ... (variant, no manifest)
type t = T0 = C of T | ... (variant, manifest=T0)
type t = {l: T; ...} (record, no manifest)
type t = T0 = {l : T; ...} (record, manifest=T0)
type t = .. (open, no manifest)
*)
and type_kind =
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_record of label_declaration list
(* Invariant: non-empty list *)
| Ptype_open
and label_declaration =
{
pld_name: string loc;
pld_mutable: mutable_flag;
pld_type: core_type;
pld_loc: Location.t;
pld_attributes: attributes; (* l : T [@id1] [@id2] *)
}
(* { ...; l: T; ... } (mutable=Immutable)
{ ...; mutable l: T; ... } (mutable=Mutable)
Note: T can be a Ptyp_poly.
*)
and constructor_declaration =
{
pcd_name: string loc;
pcd_args: constructor_arguments;
pcd_res: core_type option;
pcd_loc: Location.t;
pcd_attributes: attributes; (* C of ... [@id1] [@id2] *)
}
and constructor_arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list
(*
| C of T1 * ... * Tn (res = None, args = Pcstr_tuple [])
| C: T0 (res = Some T0, args = [])
| C: T1 * ... * Tn -> T0 (res = Some T0, args = Pcstr_tuple)
| C of {...} (res = None, args = Pcstr_record)
| C: {...} -> T0 (res = Some T0, args = Pcstr_record)
| C of {...} as t (res = None, args = Pcstr_record)
*)
and type_extension =
{
ptyext_path: Longident.t loc;
ptyext_params: (core_type * (variance * injectivity)) list;
ptyext_constructors: extension_constructor list;
ptyext_private: private_flag;
ptyext_loc: Location.t;
ptyext_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
(*
type t += ...
*)
and extension_constructor =
{
pext_name: string loc;
pext_kind : extension_constructor_kind;
pext_loc : Location.t;
pext_attributes: attributes; (* C of ... [@id1] [@id2] *)
}
(* exception E *)
and type_exception =
{
ptyexn_constructor: extension_constructor;
ptyexn_loc: Location.t;
ptyexn_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
and extension_constructor_kind =
Pext_decl of constructor_arguments * core_type option
(*
| C of T1 * ... * Tn ([T1; ...; Tn], None)
| C: T0 ([], Some T0)
| C: T1 * ... * Tn -> T0 ([T1; ...; Tn], Some T0)
*)
| Pext_rebind of Longident.t loc
(*
| C = D
*)
and effect_constructor =
{
peff_name: string loc;
peff_kind : effect_constructor_kind;
peff_loc : Location.t;
peff_attributes: attributes; (* C [@id1] [@id2] of ... *)
}
and effect_constructor_kind =
Peff_decl of core_type list * core_type
(*
| C of T1 * ... * Tn ([T1; ...; Tn], None)
| C: T0 ([], Some T0)
| C: T1 * ... * Tn -> T0 ([T1; ...; Tn], Some T0)
*)
| Peff_rebind of Longident.t loc
(*
| C = D
*)
(** {1 Class language} *)
(* Type expressions for the class language *)
and class_type =
{
pcty_desc: class_type_desc;
pcty_loc: Location.t;
pcty_attributes: attributes; (* ... [@id1] [@id2] *)
}
and class_type_desc =
| Pcty_constr of Longident.t loc * core_type list
(* c
['a1, ..., 'an] c *)
| Pcty_signature of class_signature
(* object ... end *)
| Pcty_arrow of arg_label * core_type * class_type
(* T -> CT Simple
~l:T -> CT Labelled l
?l:T -> CT Optional l
*)
| Pcty_extension of extension
(* [%id] *)
| Pcty_open of open_description * class_type
(* let open M in CT *)
and class_signature =
{
pcsig_self: core_type;
pcsig_fields: class_type_field list;
}
(* object('selfpat) ... end
object ... end (self = Ptyp_any)
*)
and class_type_field =
{
pctf_desc: class_type_field_desc;
pctf_loc: Location.t;
pctf_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
and class_type_field_desc =
| Pctf_inherit of class_type
(* inherit CT *)
| Pctf_val of (label loc * mutable_flag * virtual_flag * core_type)
(* val x: T *)
| Pctf_method of (label loc * private_flag * virtual_flag * core_type)
(* method x: T
Note: T can be a Ptyp_poly.
*)
| Pctf_constraint of (core_type * core_type)
(* constraint T1 = T2 *)
| Pctf_attribute of attribute
(* [@@@id] *)
| Pctf_extension of extension
(* [%%id] *)
and 'a class_infos =
{
pci_virt: virtual_flag;
pci_params: (core_type * (variance * injectivity)) list;
pci_name: string loc;
pci_expr: 'a;
pci_loc: Location.t;
pci_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
(* class c = ...
class ['a1,...,'an] c = ...
class virtual c = ...
Also used for "class type" declaration.
*)
and class_description = class_type class_infos
and class_type_declaration = class_type class_infos
(* Value expressions for the class language *)
and class_expr =
{
pcl_desc: class_expr_desc;
pcl_loc: Location.t;
pcl_attributes: attributes; (* ... [@id1] [@id2] *)
}
and class_expr_desc =
| Pcl_constr of Longident.t loc * core_type list
(* c
['a1, ..., 'an] c *)
| Pcl_structure of class_structure
(* object ... end *)
| Pcl_fun of arg_label * expression option * pattern * class_expr
(* fun P -> CE (Simple, None)
fun ~l:P -> CE (Labelled l, None)
fun ?l:P -> CE (Optional l, None)
fun ?l:(P = E0) -> CE (Optional l, Some E0)
*)
| Pcl_apply of class_expr * (arg_label * expression) list
(* CE ~l1:E1 ... ~ln:En
li can be empty (non labeled argument) or start with '?'
(optional argument).
Invariant: n > 0
*)
| Pcl_let of rec_flag * value_binding list * class_expr
let P1 = E1 and ... and Pn = EN in CE ( flag = )
let rec P1 = E1 and ... and Pn = EN in CE ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in CE (flag = Recursive)
*)
| Pcl_constraint of class_expr * class_type
(* (CE : CT) *)
| Pcl_extension of extension
(* [%id] *)
| Pcl_open of open_description * class_expr
(* let open M in CE *)
and class_structure =
{
pcstr_self: pattern;
pcstr_fields: class_field list;
}
(* object(selfpat) ... end
object ... end (self = Ppat_any)
*)
and class_field =
{
pcf_desc: class_field_desc;
pcf_loc: Location.t;
pcf_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
and class_field_desc =
| Pcf_inherit of override_flag * class_expr * string loc option
(* inherit CE
inherit CE as x
inherit! CE
inherit! CE as x
*)
| Pcf_val of (label loc * mutable_flag * class_field_kind)
(* val x = E
val virtual x: T
*)
| Pcf_method of (label loc * private_flag * class_field_kind)
method x = E ( E can be a Pexp_poly )
method virtual x : T ( T can be a Ptyp_poly )
method virtual x: T (T can be a Ptyp_poly)
*)
| Pcf_constraint of (core_type * core_type)
(* constraint T1 = T2 *)
| Pcf_initializer of expression
(* initializer E *)
| Pcf_attribute of attribute
(* [@@@id] *)
| Pcf_extension of extension
(* [%%id] *)
and class_field_kind =
| Cfk_virtual of core_type
| Cfk_concrete of override_flag * expression
and class_declaration = class_expr class_infos
(** {1 Module language} *)
(* Type expressions for the module language *)
and module_type =
{
pmty_desc: module_type_desc;
pmty_loc: Location.t;
pmty_attributes: attributes; (* ... [@id1] [@id2] *)
}
and module_type_desc =
| Pmty_ident of Longident.t loc
(* S *)
| Pmty_signature of signature
(* sig ... end *)
| Pmty_functor of functor_parameter * module_type
functor(X : ) - > MT2
| Pmty_with of module_type * with_constraint list
(* MT with ... *)
| Pmty_typeof of module_expr
(* module type of ME *)
| Pmty_extension of extension
(* [%id] *)
| Pmty_alias of Longident.t loc
(* (module M) *)
and functor_parameter =
| Unit
(* () *)
| Named of string option loc * module_type
( X : MT ) Some X , MT
( _ : MT ) None , MT
(_ : MT) None, MT *)
and signature = signature_item list
and signature_item =
{
psig_desc: signature_item_desc;
psig_loc: Location.t;
}
and signature_item_desc =
| Psig_value of value_description
x : T
external x : T = " s1 " ... " sn "
val x: T
external x: T = "s1" ... "sn"
*)
| Psig_type of rec_flag * type_declaration list
type t1 = ... and ... and = ...
| Psig_typesubst of type_declaration list
(* type t1 := ... and ... and tn := ... *)
| Psig_typext of type_extension
(* type t1 += ... *)
| Psig_exception of type_exception
(* exception C of T *)
| Psig_effect of effect_constructor
(* effect C : T -> T *)
| Psig_module of module_declaration
(* module X = M
module X : MT *)
| Psig_modsubst of module_substitution
(* module X := M *)
| Psig_recmodule of module_declaration list
module rec X1 : and ... and Xn : MTn
| Psig_modtype of module_type_declaration
(* module type S = MT
module type S *)
| Psig_open of open_description
(* open X *)
| Psig_include of include_description
include MT
| Psig_class of class_description list
(* class c1 : ... and ... and cn : ... *)
| Psig_class_type of class_type_declaration list
(* class type ct1 = ... and ... and ctn = ... *)
| Psig_attribute of attribute
(* [@@@id] *)
| Psig_extension of extension * attributes
(* [%%id] *)
and module_declaration =
{
pmd_name: string option loc;
pmd_type: module_type;
pmd_attributes: attributes; (* ... [@@id1] [@@id2] *)
pmd_loc: Location.t;
}
(* S : MT *)
and module_substitution =
{
pms_name: string loc;
pms_manifest: Longident.t loc;
pms_attributes: attributes; (* ... [@@id1] [@@id2] *)
pms_loc: Location.t;
}
and module_type_declaration =
{
pmtd_name: string loc;
pmtd_type: module_type option;
pmtd_attributes: attributes; (* ... [@@id1] [@@id2] *)
pmtd_loc: Location.t;
}
S = MT
S ( abstract module type declaration , pmtd_type = None )
S (abstract module type declaration, pmtd_type = None)
*)
and 'a open_infos =
{
popen_expr: 'a;
popen_override: override_flag;
popen_loc: Location.t;
popen_attributes: attributes;
}
(* open! X - popen_override = Override (silences the 'used identifier
shadowing' warning)
open X - popen_override = Fresh
*)
and open_description = Longident.t loc open_infos
open M.N
open M(N).O
open M(N).O *)
and open_declaration = module_expr open_infos
open M.N
open M(N).O
open struct ... end
open M(N).O
open struct ... end *)
and 'a include_infos =
{
pincl_mod: 'a;
pincl_loc: Location.t;
pincl_attributes: attributes;
}
and include_description = module_type include_infos
include MT
and include_declaration = module_expr include_infos
(* include ME *)
and with_constraint =
| Pwith_type of Longident.t loc * type_declaration
(* with type X.t = ...
Note: the last component of the longident must match
the name of the type_declaration. *)
| Pwith_module of Longident.t loc * Longident.t loc
(* with module X.Y = Z *)
| Pwith_typesubst of Longident.t loc * type_declaration
(* with type X.t := ..., same format as [Pwith_type] *)
| Pwith_modsubst of Longident.t loc * Longident.t loc
(* with module X.Y := Z *)
(* Value expressions for the module language *)
and module_expr =
{
pmod_desc: module_expr_desc;
pmod_loc: Location.t;
pmod_attributes: attributes; (* ... [@id1] [@id2] *)
}
and module_expr_desc =
| Pmod_ident of Longident.t loc
(* X *)
| Pmod_structure of structure
(* struct ... end *)
| Pmod_functor of functor_parameter * module_expr
functor(X : ) - > ME
| Pmod_apply of module_expr * module_expr
(* ME1(ME2) *)
| Pmod_constraint of module_expr * module_type
(* (ME : MT) *)
| Pmod_unpack of expression
( E )
| Pmod_extension of extension
(* [%id] *)
and structure = structure_item list
and structure_item =
{
pstr_desc: structure_item_desc;
pstr_loc: Location.t;
}
and structure_item_desc =
| Pstr_eval of expression * attributes
(* E *)
| Pstr_value of rec_flag * value_binding list
let P1 = E1 and ... and Pn = EN ( flag = )
let rec P1 = E1 and ... and Pn = EN ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN (flag = Recursive)
*)
| Pstr_primitive of value_description
x : T
external x : T = " s1 " ... " sn "
external x: T = "s1" ... "sn" *)
| Pstr_type of rec_flag * type_declaration list
(* type t1 = ... and ... and tn = ... *)
| Pstr_typext of type_extension
(* type t1 += ... *)
| Pstr_exception of type_exception
exception C of T
exception C =
exception C = M.X *)
| Pstr_effect of effect_constructor
effect C : T - > T
effect C =
effect C = M.X *)
| Pstr_module of module_binding
(* module X = ME *)
| Pstr_recmodule of module_binding list
(* module rec X1 = ME1 and ... and Xn = MEn *)
| Pstr_modtype of module_type_declaration
(* module type S = MT *)
| Pstr_open of open_declaration
(* open X *)
| Pstr_class of class_declaration list
(* class c1 = ... and ... and cn = ... *)
| Pstr_class_type of class_type_declaration list
(* class type ct1 = ... and ... and ctn = ... *)
| Pstr_include of include_declaration
(* include ME *)
| Pstr_attribute of attribute
(* [@@@id] *)
| Pstr_extension of extension * attributes
(* [%%id] *)
and value_binding =
{
pvb_pat: pattern;
pvb_expr: expression;
pvb_attributes: attributes;
pvb_loc: Location.t;
}
and module_binding =
{
pmb_name: string option loc;
pmb_expr: module_expr;
pmb_attributes: attributes;
pmb_loc: Location.t;
}
(* X = ME *)
* { 1 Toplevel }
Toplevel phrases
type toplevel_phrase =
| Ptop_def of structure
| Ptop_dir of toplevel_directive
(* #use, #load ... *)
and toplevel_directive =
{
pdir_name : string loc;
pdir_arg : directive_argument option;
pdir_loc : Location.t;
}
and directive_argument =
{
pdira_desc : directive_argument_desc;
pdira_loc : Location.t;
}
and directive_argument_desc =
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool
| null | https://raw.githubusercontent.com/songyahui/AlgebraicEffect/421afc58ed355f2ce1ada7e77733d7642c328815/parsing/parsetree.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Abstract syntax tree produced by parsing
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
basic term
an occurrence of an effect
type linearStagedSpec = stagedSpec list
type spec = (pi * linearStagedSpec) list
'c'
"constant"
{delim|other constant|delim}
The location span the content of the string, without the delimiters.
3.4 2e5 1.4e-4
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes are rejected by the typechecker.
[@id ARG]
[@@id ARG]
Metadata containers passed around within the AST.
The compiler ignores unknown attributes.
[%id ARG]
[%%id ARG]
Sub-language placeholder -- rejected by the typechecker.
: T
? P or ? P when E
Type expressions
... [@id1] [@id2]
_
'a
T1 -> T2 Simple
~l:T1 -> T2 Labelled
?l:T1 -> T2 Optional
tconstr
T tconstr
(T1, ..., Tn) tconstr
< l1:T1; ...; ln:Tn > (flag = Closed)
< l1:T1; ...; ln:Tn; .. > (flag = Open)
T as 'a
[ `A|`B ] (flag = Closed; labels = None)
[> `A|`B ] (flag = Open; labels = None)
[< `A|`B ] (flag = Closed; labels = Some [])
[< `A|`B > `X `Y ](flag = Closed; labels = Some ["X";"Y"])
(module S)
[%id]
(module S)
(module S with type t1 = T1 and ... and tn = Tn)
[ | t ]
Patterns
... [@id1] [@id2]
_
x
P as 'a
'a'..'z'
Other forms of interval are recognized by the parser
but rejected by the type-checker.
`A (None)
`A P (Some P)
[| P1; ...; Pn |]
(P : T)
#tconst
lazy P
(module P) Some "P"
(module _) None
Note: (module P : S) is represented as
Ppat_constraint(Ppat_unpack, Ptyp_package)
exception P
effect P P
[%id]
M.(P)
Value expressions
... [@id1] [@id2]
(spec * spec list) option;
x
M.x
function P1 -> E1 | ... | Pn -> En
C None
C E Some E
C (E1, ..., En) Some (Pexp_tuple[E1;...;En])
`A (None)
`A E (Some E)
E.l
[| E1; ...; En |]
E1; E2
while E1 do E2 done
(E : T)
(E :> T) (None, T)
(E : T0 :> T) (Some T0, T)
E # m
new M.c
x <- 2
let module M = ME in E
let exception C in E
assert E
Note: "assert false" is treated in a special way by the
type-checker.
lazy E
object ... end
fun (type t) -> E
(module ME)
(module ME : S) is represented as
Pexp_constraint(Pexp_pack, Ptyp_package S)
M.(E)
let open M in E
let! open M in E
let* P = E in E
let* P = E and* P = E in E
[%id]
.
(P -> E) or (P when E0 -> E)
Value descriptions
... [@@id1] [@@id2]
val x: T (prim = [])
external x: T = "s1" ... "sn" (prim = ["s1";..."sn"])
Type declarations
('a1,...'an) t; None represents _
= private ...
= T
... [@@id1] [@@id2]
type t (abstract, no manifest)
type t = T0 (abstract, manifest=T0)
type t = C of T | ... (variant, no manifest)
type t = T0 = C of T | ... (variant, manifest=T0)
type t = {l: T; ...} (record, no manifest)
type t = T0 = {l : T; ...} (record, manifest=T0)
type t = .. (open, no manifest)
Invariant: non-empty list
l : T [@id1] [@id2]
{ ...; l: T; ... } (mutable=Immutable)
{ ...; mutable l: T; ... } (mutable=Mutable)
Note: T can be a Ptyp_poly.
C of ... [@id1] [@id2]
| C of T1 * ... * Tn (res = None, args = Pcstr_tuple [])
| C: T0 (res = Some T0, args = [])
| C: T1 * ... * Tn -> T0 (res = Some T0, args = Pcstr_tuple)
| C of {...} (res = None, args = Pcstr_record)
| C: {...} -> T0 (res = Some T0, args = Pcstr_record)
| C of {...} as t (res = None, args = Pcstr_record)
... [@@id1] [@@id2]
type t += ...
C of ... [@id1] [@id2]
exception E
... [@@id1] [@@id2]
| C of T1 * ... * Tn ([T1; ...; Tn], None)
| C: T0 ([], Some T0)
| C: T1 * ... * Tn -> T0 ([T1; ...; Tn], Some T0)
| C = D
C [@id1] [@id2] of ...
| C of T1 * ... * Tn ([T1; ...; Tn], None)
| C: T0 ([], Some T0)
| C: T1 * ... * Tn -> T0 ([T1; ...; Tn], Some T0)
| C = D
* {1 Class language}
Type expressions for the class language
... [@id1] [@id2]
c
['a1, ..., 'an] c
object ... end
T -> CT Simple
~l:T -> CT Labelled l
?l:T -> CT Optional l
[%id]
let open M in CT
object('selfpat) ... end
object ... end (self = Ptyp_any)
... [@@id1] [@@id2]
inherit CT
val x: T
method x: T
Note: T can be a Ptyp_poly.
constraint T1 = T2
[@@@id]
[%%id]
... [@@id1] [@@id2]
class c = ...
class ['a1,...,'an] c = ...
class virtual c = ...
Also used for "class type" declaration.
Value expressions for the class language
... [@id1] [@id2]
c
['a1, ..., 'an] c
object ... end
fun P -> CE (Simple, None)
fun ~l:P -> CE (Labelled l, None)
fun ?l:P -> CE (Optional l, None)
fun ?l:(P = E0) -> CE (Optional l, Some E0)
CE ~l1:E1 ... ~ln:En
li can be empty (non labeled argument) or start with '?'
(optional argument).
Invariant: n > 0
(CE : CT)
[%id]
let open M in CE
object(selfpat) ... end
object ... end (self = Ppat_any)
... [@@id1] [@@id2]
inherit CE
inherit CE as x
inherit! CE
inherit! CE as x
val x = E
val virtual x: T
constraint T1 = T2
initializer E
[@@@id]
[%%id]
* {1 Module language}
Type expressions for the module language
... [@id1] [@id2]
S
sig ... end
MT with ...
module type of ME
[%id]
(module M)
()
type t1 := ... and ... and tn := ...
type t1 += ...
exception C of T
effect C : T -> T
module X = M
module X : MT
module X := M
module type S = MT
module type S
open X
class c1 : ... and ... and cn : ...
class type ct1 = ... and ... and ctn = ...
[@@@id]
[%%id]
... [@@id1] [@@id2]
S : MT
... [@@id1] [@@id2]
... [@@id1] [@@id2]
open! X - popen_override = Override (silences the 'used identifier
shadowing' warning)
open X - popen_override = Fresh
include ME
with type X.t = ...
Note: the last component of the longident must match
the name of the type_declaration.
with module X.Y = Z
with type X.t := ..., same format as [Pwith_type]
with module X.Y := Z
Value expressions for the module language
... [@id1] [@id2]
X
struct ... end
ME1(ME2)
(ME : MT)
[%id]
E
type t1 = ... and ... and tn = ...
type t1 += ...
module X = ME
module rec X1 = ME1 and ... and Xn = MEn
module type S = MT
open X
class c1 = ... and ... and cn = ...
class type ct1 = ... and ... and ctn = ...
include ME
[@@@id]
[%%id]
X = ME
#use, #load ... | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Asttypes
type basic_t = BINT of int | UNIT | VARName of string | List of int list
type instant = Instant of string * basic_t list
type term =
| Num of int
| TList of (term list)
| TTupple of (term list)
| Var of string
| Plus of term * term
| Minus of term * term
| TListAppend of term * term
type bin_op = GT | LT | EQ | GTEQ | LTEQ
type pi =
| True
| False
| Atomic of bin_op * term * term
| And of pi * pi
| Or of pi * pi
| Imply of pi * pi
| Not of pi
| Predicate of string * term
type kappa =
| EmptyHeap
| PointsTo of (string * term)
| SepConj of kappa * kappa
type stagedSpec =
| Require of kappa
| NormalReturn of (kappa * basic_t list)
basic_t is a placeholder for the resumned value
| Exists of (string list)
type spec = stagedSpec list
Flatten Form
= = = = = = = = = = = =
S : : = req H | H & Norm | H & Eff | local v *
N : : = \/ { S; .. ;S }
Flatten Form
============
S ::= req H | H & Norm | H & Eff | local v*
N ::= \/ {S;..;S}
*)
type constant =
Pconst_integer of string * char option
3 3l 3L 3n
Suffixes [ g - z][G - Z ] are accepted by the parser .
Suffixes except ' l ' , ' L ' and ' n ' are rejected by the typechecker
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes except 'l', 'L' and 'n' are rejected by the typechecker
*)
| Pconst_char of char
| Pconst_string of string * Location.t * string option
| Pconst_float of string * char option
type location_stack = Location.t list
* { 1 Extension points }
type attribute = {
attr_name : string loc;
attr_payload : payload;
attr_loc : Location.t;
}
and extension = string loc * payload
and attributes = attribute list
and payload =
| PStr of structure
: SIG
* { 1 Core language }
and core_type =
{
ptyp_desc: core_type_desc;
ptyp_loc: Location.t;
ptyp_loc_stack: location_stack;
}
and core_type_desc =
| Ptyp_any
| Ptyp_var of string
| Ptyp_arrow of arg_label * core_type * core_type
| Ptyp_tuple of core_type list
T1 * ... * Tn
Invariant : n > = 2
Invariant: n >= 2
*)
| Ptyp_constr of Longident.t loc * core_type list
| Ptyp_object of object_field list * closed_flag
| Ptyp_class of Longident.t loc * core_type list
# tconstr
T # tconstr
( T1 , ... , Tn ) # tconstr
T #tconstr
(T1, ..., Tn) #tconstr
*)
| Ptyp_alias of core_type * string
| Ptyp_variant of row_field list * closed_flag * label list option
| Ptyp_poly of string loc list * core_type
' a1 ... ' an . T
Can only appear in the following context :
- As the core_type of a Ppat_constraint node corresponding
to a constraint on a let - binding : let x : ' a1 ... ' an . T
= e ...
- Under Cfk_virtual for methods ( not values ) .
- As the core_type of a Pctf_method node .
- As the core_type of a Pexp_poly node .
- As the pld_type field of a label_declaration .
- As a core_type of a Ptyp_object node .
Can only appear in the following context:
- As the core_type of a Ppat_constraint node corresponding
to a constraint on a let-binding: let x : 'a1 ... 'an. T
= e ...
- Under Cfk_virtual for methods (not values).
- As the core_type of a Pctf_method node.
- As the core_type of a Pexp_poly node.
- As the pld_type field of a label_declaration.
- As a core_type of a Ptyp_object node.
*)
| Ptyp_package of package_type
| Ptyp_extension of extension
and package_type = Longident.t loc * (Longident.t loc * core_type) list
and row_field = {
prf_desc : row_field_desc;
prf_loc : Location.t;
prf_attributes : attributes;
}
and row_field_desc =
| Rtag of label loc * bool * core_type list
[ ` A ] ( true , [ ] )
[ ` A of T ] ( false , [ T ] )
[ ` A of T1 & .. & Tn ] ( false , [ T1; ... Tn ] )
[ ` A of & T1 & .. & Tn ] ( true , [ T1; ... Tn ] )
- The ' bool ' field is true if the tag contains a
constant ( empty ) constructor .
- ' & ' occurs when several types are used for the same constructor
( see 4.2 in the manual )
[`A of T] ( false, [T] )
[`A of T1 & .. & Tn] ( false, [T1;...Tn] )
[`A of & T1 & .. & Tn] ( true, [T1;...Tn] )
- The 'bool' field is true if the tag contains a
constant (empty) constructor.
- '&' occurs when several types are used for the same constructor
(see 4.2 in the manual)
*)
| Rinherit of core_type
and object_field = {
pof_desc : object_field_desc;
pof_loc : Location.t;
pof_attributes : attributes;
}
and object_field_desc =
| Otag of label loc * core_type
| Oinherit of core_type
and pattern =
{
ppat_desc: pattern_desc;
ppat_loc: Location.t;
ppat_loc_stack: location_stack;
}
and pattern_desc =
| Ppat_any
| Ppat_var of string loc
| Ppat_alias of pattern * string loc
| Ppat_constant of constant
1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Ppat_interval of constant * constant
| Ppat_tuple of pattern list
( P1 , ... , Pn )
Invariant : n > = 2
Invariant: n >= 2
*)
| Ppat_construct of Longident.t loc * pattern option
C None
C P Some P
C ( P1 , ... , Pn ) Some ( Ppat_tuple [ P1 ; ... ; Pn ] )
C P Some P
C (P1, ..., Pn) Some (Ppat_tuple [P1; ...; Pn])
*)
| Ppat_variant of label * pattern option
| Ppat_record of (Longident.t loc * pattern) list * closed_flag
{ l1 = P1 ; ... ; ln = Pn } ( flag = Closed )
{ l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open )
Invariant : n > 0
{ l1=P1; ...; ln=Pn; _} (flag = Open)
Invariant: n > 0
*)
| Ppat_array of pattern list
| Ppat_or of pattern * pattern
P1 | P2
| Ppat_constraint of pattern * core_type
| Ppat_type of Longident.t loc
| Ppat_lazy of pattern
| Ppat_unpack of string option loc
| Ppat_exception of pattern
| Ppat_effect of pattern * pattern
| Ppat_extension of extension
| Ppat_open of Longident.t loc * pattern
and expression =
{
pexp_desc: expression_desc;
pexp_loc: Location.t;
pexp_loc_stack: location_stack;
pexp_effectspec: spec option;
}
and expression_desc =
| Pexp_ident of Longident.t loc
| Pexp_constant of constant
1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Pexp_let of rec_flag * value_binding list * expression
let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Pexp_function of case list
| Pexp_fun of arg_label * expression option * pattern * expression
fun P - > E1 ( Simple , None )
fun ~l :P - > E1 ( Labelled l , None )
fun ? l :P - > E1 ( Optional l , None )
fun ? l:(P = E0 ) - > E1 ( Optional l , Some E0 )
Notes :
- If E0 is provided , only Optional is allowed .
- " fun P1 P2 .. Pn - > E1 " is represented as nested Pexp_fun .
- " let f P = E " is represented using Pexp_fun .
fun ~l:P -> E1 (Labelled l, None)
fun ?l:P -> E1 (Optional l, None)
fun ?l:(P = E0) -> E1 (Optional l, Some E0)
Notes:
- If E0 is provided, only Optional is allowed.
- "fun P1 P2 .. Pn -> E1" is represented as nested Pexp_fun.
- "let f P = E" is represented using Pexp_fun.
*)
| Pexp_apply of expression * (arg_label * expression) list
E0 ~l1 : E1 ... ~ln : En
li can be empty ( non labeled argument ) or start with ' ? '
( optional argument ) .
Invariant : n > 0
li can be empty (non labeled argument) or start with '?'
(optional argument).
Invariant: n > 0
*)
| Pexp_match of expression * case list
match E0 with P1 - > E1 | ... | Pn - > En
| Pexp_try of expression * case list
try E0 with P1 - > E1 | ... | Pn - > En
| Pexp_tuple of expression list
( E1 , ... , En )
Invariant : n > = 2
Invariant: n >= 2
*)
| Pexp_construct of Longident.t loc * expression option
| Pexp_variant of label * expression option
| Pexp_record of (Longident.t loc * expression) list * expression option
{ l1 = P1 ; ... ; ln = Pn } ( None )
{ E0 with l1 = P1 ; ... ; ln = Pn } ( Some E0 )
Invariant : n > 0
{ E0 with l1=P1; ...; ln=Pn } (Some E0)
Invariant: n > 0
*)
| Pexp_field of expression * Longident.t loc
| Pexp_setfield of expression * Longident.t loc * expression
E1.l < - E2
| Pexp_array of expression list
| Pexp_ifthenelse of expression * expression * expression option
if E1 then E2 else E3
| Pexp_sequence of expression * expression
| Pexp_while of expression * expression
| Pexp_for of
pattern * expression * expression * direction_flag * expression
for i = E1 to E2 do E3 done ( flag = Upto )
for i = E1 downto E2 do E3 done ( flag = )
for i = E1 downto E2 do E3 done (flag = Downto)
*)
| Pexp_constraint of expression * core_type
| Pexp_coerce of expression * core_type option * core_type
| Pexp_send of expression * label loc
| Pexp_new of Longident.t loc
| Pexp_setinstvar of label loc * expression
| Pexp_override of (label loc * expression) list
{ < x1 = E1 ; ... ; > }
| Pexp_letmodule of string option loc * module_expr * expression
| Pexp_letexception of extension_constructor * expression
| Pexp_assert of expression
| Pexp_lazy of expression
| Pexp_poly of expression * core_type option
Used for method bodies .
Can only be used as the expression under
for methods ( not values ) .
Can only be used as the expression under Cfk_concrete
for methods (not values). *)
| Pexp_object of class_structure
| Pexp_newtype of string loc * expression
| Pexp_pack of module_expr
| Pexp_open of open_declaration * expression
| Pexp_letop of letop
| Pexp_extension of extension
| Pexp_unreachable
{
pc_lhs: pattern;
pc_guard: expression option;
pc_rhs: expression;
}
and letop =
{
let_ : binding_op;
ands : binding_op list;
body : expression;
}
and binding_op =
{
pbop_op : string loc;
pbop_pat : pattern;
pbop_exp : expression;
pbop_loc : Location.t;
}
and value_description =
{
pval_name: string loc;
pval_type: core_type;
pval_prim: string list;
pval_loc: Location.t;
}
and type_declaration =
{
ptype_name: string loc;
ptype_params: (core_type * (variance * injectivity)) list;
ptype_cstrs: (core_type * core_type * Location.t) list;
... constraint T1 = T1 ' ... constraint
ptype_kind: type_kind;
ptype_loc: Location.t;
}
and type_kind =
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_record of label_declaration list
| Ptype_open
and label_declaration =
{
pld_name: string loc;
pld_mutable: mutable_flag;
pld_type: core_type;
pld_loc: Location.t;
}
and constructor_declaration =
{
pcd_name: string loc;
pcd_args: constructor_arguments;
pcd_res: core_type option;
pcd_loc: Location.t;
}
and constructor_arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list
and type_extension =
{
ptyext_path: Longident.t loc;
ptyext_params: (core_type * (variance * injectivity)) list;
ptyext_constructors: extension_constructor list;
ptyext_private: private_flag;
ptyext_loc: Location.t;
}
and extension_constructor =
{
pext_name: string loc;
pext_kind : extension_constructor_kind;
pext_loc : Location.t;
}
and type_exception =
{
ptyexn_constructor: extension_constructor;
ptyexn_loc: Location.t;
}
and extension_constructor_kind =
Pext_decl of constructor_arguments * core_type option
| Pext_rebind of Longident.t loc
and effect_constructor =
{
peff_name: string loc;
peff_kind : effect_constructor_kind;
peff_loc : Location.t;
}
and effect_constructor_kind =
Peff_decl of core_type list * core_type
| Peff_rebind of Longident.t loc
and class_type =
{
pcty_desc: class_type_desc;
pcty_loc: Location.t;
}
and class_type_desc =
| Pcty_constr of Longident.t loc * core_type list
| Pcty_signature of class_signature
| Pcty_arrow of arg_label * core_type * class_type
| Pcty_extension of extension
| Pcty_open of open_description * class_type
and class_signature =
{
pcsig_self: core_type;
pcsig_fields: class_type_field list;
}
and class_type_field =
{
pctf_desc: class_type_field_desc;
pctf_loc: Location.t;
}
and class_type_field_desc =
| Pctf_inherit of class_type
| Pctf_val of (label loc * mutable_flag * virtual_flag * core_type)
| Pctf_method of (label loc * private_flag * virtual_flag * core_type)
| Pctf_constraint of (core_type * core_type)
| Pctf_attribute of attribute
| Pctf_extension of extension
and 'a class_infos =
{
pci_virt: virtual_flag;
pci_params: (core_type * (variance * injectivity)) list;
pci_name: string loc;
pci_expr: 'a;
pci_loc: Location.t;
}
and class_description = class_type class_infos
and class_type_declaration = class_type class_infos
and class_expr =
{
pcl_desc: class_expr_desc;
pcl_loc: Location.t;
}
and class_expr_desc =
| Pcl_constr of Longident.t loc * core_type list
| Pcl_structure of class_structure
| Pcl_fun of arg_label * expression option * pattern * class_expr
| Pcl_apply of class_expr * (arg_label * expression) list
| Pcl_let of rec_flag * value_binding list * class_expr
let P1 = E1 and ... and Pn = EN in CE ( flag = )
let rec P1 = E1 and ... and Pn = EN in CE ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in CE (flag = Recursive)
*)
| Pcl_constraint of class_expr * class_type
| Pcl_extension of extension
| Pcl_open of open_description * class_expr
and class_structure =
{
pcstr_self: pattern;
pcstr_fields: class_field list;
}
and class_field =
{
pcf_desc: class_field_desc;
pcf_loc: Location.t;
}
and class_field_desc =
| Pcf_inherit of override_flag * class_expr * string loc option
| Pcf_val of (label loc * mutable_flag * class_field_kind)
| Pcf_method of (label loc * private_flag * class_field_kind)
method x = E ( E can be a Pexp_poly )
method virtual x : T ( T can be a Ptyp_poly )
method virtual x: T (T can be a Ptyp_poly)
*)
| Pcf_constraint of (core_type * core_type)
| Pcf_initializer of expression
| Pcf_attribute of attribute
| Pcf_extension of extension
and class_field_kind =
| Cfk_virtual of core_type
| Cfk_concrete of override_flag * expression
and class_declaration = class_expr class_infos
and module_type =
{
pmty_desc: module_type_desc;
pmty_loc: Location.t;
}
and module_type_desc =
| Pmty_ident of Longident.t loc
| Pmty_signature of signature
| Pmty_functor of functor_parameter * module_type
functor(X : ) - > MT2
| Pmty_with of module_type * with_constraint list
| Pmty_typeof of module_expr
| Pmty_extension of extension
| Pmty_alias of Longident.t loc
and functor_parameter =
| Unit
| Named of string option loc * module_type
( X : MT ) Some X , MT
( _ : MT ) None , MT
(_ : MT) None, MT *)
and signature = signature_item list
and signature_item =
{
psig_desc: signature_item_desc;
psig_loc: Location.t;
}
and signature_item_desc =
| Psig_value of value_description
x : T
external x : T = " s1 " ... " sn "
val x: T
external x: T = "s1" ... "sn"
*)
| Psig_type of rec_flag * type_declaration list
type t1 = ... and ... and = ...
| Psig_typesubst of type_declaration list
| Psig_typext of type_extension
| Psig_exception of type_exception
| Psig_effect of effect_constructor
| Psig_module of module_declaration
| Psig_modsubst of module_substitution
| Psig_recmodule of module_declaration list
module rec X1 : and ... and Xn : MTn
| Psig_modtype of module_type_declaration
| Psig_open of open_description
| Psig_include of include_description
include MT
| Psig_class of class_description list
| Psig_class_type of class_type_declaration list
| Psig_attribute of attribute
| Psig_extension of extension * attributes
and module_declaration =
{
pmd_name: string option loc;
pmd_type: module_type;
pmd_loc: Location.t;
}
and module_substitution =
{
pms_name: string loc;
pms_manifest: Longident.t loc;
pms_loc: Location.t;
}
and module_type_declaration =
{
pmtd_name: string loc;
pmtd_type: module_type option;
pmtd_loc: Location.t;
}
S = MT
S ( abstract module type declaration , pmtd_type = None )
S (abstract module type declaration, pmtd_type = None)
*)
and 'a open_infos =
{
popen_expr: 'a;
popen_override: override_flag;
popen_loc: Location.t;
popen_attributes: attributes;
}
and open_description = Longident.t loc open_infos
open M.N
open M(N).O
open M(N).O *)
and open_declaration = module_expr open_infos
open M.N
open M(N).O
open struct ... end
open M(N).O
open struct ... end *)
and 'a include_infos =
{
pincl_mod: 'a;
pincl_loc: Location.t;
pincl_attributes: attributes;
}
and include_description = module_type include_infos
include MT
and include_declaration = module_expr include_infos
and with_constraint =
| Pwith_type of Longident.t loc * type_declaration
| Pwith_module of Longident.t loc * Longident.t loc
| Pwith_typesubst of Longident.t loc * type_declaration
| Pwith_modsubst of Longident.t loc * Longident.t loc
and module_expr =
{
pmod_desc: module_expr_desc;
pmod_loc: Location.t;
}
and module_expr_desc =
| Pmod_ident of Longident.t loc
| Pmod_structure of structure
| Pmod_functor of functor_parameter * module_expr
functor(X : ) - > ME
| Pmod_apply of module_expr * module_expr
| Pmod_constraint of module_expr * module_type
| Pmod_unpack of expression
( E )
| Pmod_extension of extension
and structure = structure_item list
and structure_item =
{
pstr_desc: structure_item_desc;
pstr_loc: Location.t;
}
and structure_item_desc =
| Pstr_eval of expression * attributes
| Pstr_value of rec_flag * value_binding list
let P1 = E1 and ... and Pn = EN ( flag = )
let rec P1 = E1 and ... and Pn = EN ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN (flag = Recursive)
*)
| Pstr_primitive of value_description
x : T
external x : T = " s1 " ... " sn "
external x: T = "s1" ... "sn" *)
| Pstr_type of rec_flag * type_declaration list
| Pstr_typext of type_extension
| Pstr_exception of type_exception
exception C of T
exception C =
exception C = M.X *)
| Pstr_effect of effect_constructor
effect C : T - > T
effect C =
effect C = M.X *)
| Pstr_module of module_binding
| Pstr_recmodule of module_binding list
| Pstr_modtype of module_type_declaration
| Pstr_open of open_declaration
| Pstr_class of class_declaration list
| Pstr_class_type of class_type_declaration list
| Pstr_include of include_declaration
| Pstr_attribute of attribute
| Pstr_extension of extension * attributes
and value_binding =
{
pvb_pat: pattern;
pvb_expr: expression;
pvb_attributes: attributes;
pvb_loc: Location.t;
}
and module_binding =
{
pmb_name: string option loc;
pmb_expr: module_expr;
pmb_attributes: attributes;
pmb_loc: Location.t;
}
* { 1 Toplevel }
Toplevel phrases
type toplevel_phrase =
| Ptop_def of structure
| Ptop_dir of toplevel_directive
and toplevel_directive =
{
pdir_name : string loc;
pdir_arg : directive_argument option;
pdir_loc : Location.t;
}
and directive_argument =
{
pdira_desc : directive_argument_desc;
pdira_loc : Location.t;
}
and directive_argument_desc =
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool
|
b9798c60f15e08499cdaa5efc3b2554e9f0d8c8ebfcb8bb8d576456ebf0d9413 | mstksg/advent-of-code-2019 | Day21.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
-- |
-- Module : AOC.Challenge.Day21
-- License : BSD3
--
-- Stability : experimental
-- Portability : non-portable
--
Day 21 . See " AOC.Solver " for the types used in this module !
module AOC.Challenge.Day21 (
day21a
, day21b
) where
import AOC.Common (_CharFinite)
import AOC.Common.Intcode (Memory, parseMem, untilHalt, stepForever, IErr, preAscii)
import AOC.Solver ((:~>)(..))
import Control.Applicative (empty)
import Control.Lens (review)
import Control.Monad ((<=<))
import Data.Char (ord)
import Data.Conduino (Pipe, runPipe, (.|), yield)
import Data.Finite (Finite, weakenN)
import Data.List (find)
import Data.Text (Text)
import Data.Void (Void)
import Text.Printf (printf)
import qualified Data.Conduino.Combinators as C
import qualified Data.Text as T
data Reg = RTemp | RJump | RInp (Finite 9)
deriving (Eq, Ord, Show)
data Com = CAnd | COr | CNot
deriving (Eq, Ord, Show)
data Instr = I Com Reg Reg
deriving (Eq, Ord, Show)
type Program = [Instr]
runSpringbot
:: Monad m
=> Pipe () Text u m Void
-> Memory
-> m [Int]
runSpringbot src m = runPipe $ src
.| preAscii
.| untilHalt (stepForever @IErr m)
.| C.sinkList
sourceWalk :: Program -> Pipe i Text u m ()
sourceWalk p = do
C.sourceList (instrCode <$> p)
yield "WALK"
theProg :: Program
theProg = [
I COr (RInp 3) RJump -- jump if target is stable
, I CNot RTemp RTemp -- RTemp == True
, I CAnd (RInp 0) RTemp -- RTemp &&= r0
, I CAnd (RInp 1) RTemp -- RTemp &&= r1
, I CAnd (RInp 2) RTemp -- RTemp &&= r2
, I CNot RTemp RTemp -- then don't jump
, I CAnd RTemp RJump
]
-- the logic:
--
-- jump whenever it is safe to do so. but don't jump frivolously (if there
-- is no hole in sight)
--
0 # # # # No
1 # # # . No
2 # # . # Yes
3 # # .. No
4 # . # # Yes
5 # . # . No
6 # .. # Yes
-- 7 #... No
8 . # # # Yes
9 . # # . Give Up
-- a .#.# Yes
-- b .#.. Give Up
-- c ..## Yes
-- d ..#. Give Up
-- e ...# Yes
-- f .... Give Up
--
day21a :: Memory :~> Int
day21a = MkSol
{ sParse = parseMem
, sShow = show
, sSolve = isGood <=< runSpringbot (sourceWalk theProg *> empty)
}
sourceRun :: Program -> Pipe i Text u m ()
sourceRun p = do
C.sourceList (instrCode <$> p)
yield "RUN"
-- the logic:
--
-- the same but also try to 'double jump' if you can.
theProg2 :: Program
theProg2 = [
I CNot (RInp 0) RJump -- jump if next spot is bad
, I COr (RInp 3) RTemp -- jump if target is stable
, I CAnd (RInp 7) RTemp -- and double-target is stable
, I COr RTemp RJump
, I CNot (RInp 0) RTemp
, I CNot RTemp RTemp
, I CAnd (RInp 1) RTemp -- RTemp &&= r1
, I CAnd (RInp 2) RTemp -- RTemp &&= r2
, I CNot RTemp RTemp -- then don't jump
, I CAnd RTemp RJump
]
day21b :: Memory :~> Int
day21b = MkSol
{ sParse = parseMem
, sShow = show
, sSolve = isGood <=< runSpringbot (sourceRun theProg2 *> empty)
}
isGood :: [Int] -> Maybe Int
isGood = find (> ord maxBound)
regCode :: Reg -> Char
regCode = \case
RTemp -> 'T'
RJump -> 'J'
RInp c -> review _CharFinite (True, weakenN c)
comCode :: Com -> String
comCode = \case
CAnd -> "AND"
COr -> "OR"
CNot -> "NOT"
instrCode :: Instr -> Text
instrCode (I c x y) = T.pack $ printf "%s %c %c" (comCode c) (regCode x) (regCode y)
| null | https://raw.githubusercontent.com/mstksg/advent-of-code-2019/df2b1c76ad26ad20306f705e923a09b14d538374/src/AOC/Challenge/Day21.hs | haskell | # LANGUAGE OverloadedStrings #
|
Module : AOC.Challenge.Day21
License : BSD3
Stability : experimental
Portability : non-portable
jump if target is stable
RTemp == True
RTemp &&= r0
RTemp &&= r1
RTemp &&= r2
then don't jump
the logic:
jump whenever it is safe to do so. but don't jump frivolously (if there
is no hole in sight)
7 #... No
a .#.# Yes
b .#.. Give Up
c ..## Yes
d ..#. Give Up
e ...# Yes
f .... Give Up
the logic:
the same but also try to 'double jump' if you can.
jump if next spot is bad
jump if target is stable
and double-target is stable
RTemp &&= r1
RTemp &&= r2
then don't jump | # LANGUAGE TypeApplications #
Day 21 . See " AOC.Solver " for the types used in this module !
module AOC.Challenge.Day21 (
day21a
, day21b
) where
import AOC.Common (_CharFinite)
import AOC.Common.Intcode (Memory, parseMem, untilHalt, stepForever, IErr, preAscii)
import AOC.Solver ((:~>)(..))
import Control.Applicative (empty)
import Control.Lens (review)
import Control.Monad ((<=<))
import Data.Char (ord)
import Data.Conduino (Pipe, runPipe, (.|), yield)
import Data.Finite (Finite, weakenN)
import Data.List (find)
import Data.Text (Text)
import Data.Void (Void)
import Text.Printf (printf)
import qualified Data.Conduino.Combinators as C
import qualified Data.Text as T
data Reg = RTemp | RJump | RInp (Finite 9)
deriving (Eq, Ord, Show)
data Com = CAnd | COr | CNot
deriving (Eq, Ord, Show)
data Instr = I Com Reg Reg
deriving (Eq, Ord, Show)
type Program = [Instr]
runSpringbot
:: Monad m
=> Pipe () Text u m Void
-> Memory
-> m [Int]
runSpringbot src m = runPipe $ src
.| preAscii
.| untilHalt (stepForever @IErr m)
.| C.sinkList
sourceWalk :: Program -> Pipe i Text u m ()
sourceWalk p = do
C.sourceList (instrCode <$> p)
yield "WALK"
theProg :: Program
theProg = [
, I CAnd RTemp RJump
]
0 # # # # No
1 # # # . No
2 # # . # Yes
3 # # .. No
4 # . # # Yes
5 # . # . No
6 # .. # Yes
8 . # # # Yes
9 . # # . Give Up
day21a :: Memory :~> Int
day21a = MkSol
{ sParse = parseMem
, sShow = show
, sSolve = isGood <=< runSpringbot (sourceWalk theProg *> empty)
}
sourceRun :: Program -> Pipe i Text u m ()
sourceRun p = do
C.sourceList (instrCode <$> p)
yield "RUN"
theProg2 :: Program
theProg2 = [
, I COr RTemp RJump
, I CNot (RInp 0) RTemp
, I CNot RTemp RTemp
, I CAnd RTemp RJump
]
day21b :: Memory :~> Int
day21b = MkSol
{ sParse = parseMem
, sShow = show
, sSolve = isGood <=< runSpringbot (sourceRun theProg2 *> empty)
}
isGood :: [Int] -> Maybe Int
isGood = find (> ord maxBound)
regCode :: Reg -> Char
regCode = \case
RTemp -> 'T'
RJump -> 'J'
RInp c -> review _CharFinite (True, weakenN c)
comCode :: Com -> String
comCode = \case
CAnd -> "AND"
COr -> "OR"
CNot -> "NOT"
instrCode :: Instr -> Text
instrCode (I c x y) = T.pack $ printf "%s %c %c" (comCode c) (regCode x) (regCode y)
|
5b46823bdf295e2d569d4d05cfe0f794a40740ad0b5d42971cb92ee588543bed | SimulaVR/godot-haskell | Marshalls.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.Marshalls
(Godot.Core.Marshalls.base64_to_raw,
Godot.Core.Marshalls.base64_to_utf8,
Godot.Core.Marshalls.base64_to_variant,
Godot.Core.Marshalls.raw_to_base64,
Godot.Core.Marshalls.utf8_to_base64,
Godot.Core.Marshalls.variant_to_base64)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Reference()
# NOINLINE bindMarshalls_base64_to_raw #
-- | Returns a decoded @PoolByteArray@ corresponding to the Base64-encoded string @base64_str@.
bindMarshalls_base64_to_raw :: MethodBind
bindMarshalls_base64_to_raw
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "base64_to_raw" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns a decoded @PoolByteArray@ corresponding to the Base64-encoded string @base64_str@.
base64_to_raw ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotString -> IO PoolByteArray
base64_to_raw cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_base64_to_raw (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "base64_to_raw" '[GodotString]
(IO PoolByteArray)
where
nodeMethod = Godot.Core.Marshalls.base64_to_raw
# NOINLINE bindMarshalls_base64_to_utf8 #
-- | Returns a decoded string corresponding to the Base64-encoded string @base64_str@.
bindMarshalls_base64_to_utf8 :: MethodBind
bindMarshalls_base64_to_utf8
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "base64_to_utf8" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns a decoded string corresponding to the Base64-encoded string @base64_str@.
base64_to_utf8 ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotString -> IO GodotString
base64_to_utf8 cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_base64_to_utf8 (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "base64_to_utf8" '[GodotString]
(IO GodotString)
where
nodeMethod = Godot.Core.Marshalls.base64_to_utf8
# NOINLINE bindMarshalls_base64_to_variant #
| Returns a decoded @Variant@ corresponding to the Base64 - encoded string @base64_str@. If @allow_objects@ is @true@ , decoding objects is allowed .
-- __Warning:__ Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution.
bindMarshalls_base64_to_variant :: MethodBind
bindMarshalls_base64_to_variant
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "base64_to_variant" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns a decoded @Variant@ corresponding to the Base64 - encoded string @base64_str@. If @allow_objects@ is @true@ , decoding objects is allowed .
-- __Warning:__ Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution.
base64_to_variant ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotString -> Maybe Bool -> IO GodotVariant
base64_to_variant cls arg1 arg2
= withVariantArray
[toVariant arg1, maybe (VariantBool False) toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_base64_to_variant (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "base64_to_variant"
'[GodotString, Maybe Bool]
(IO GodotVariant)
where
nodeMethod = Godot.Core.Marshalls.base64_to_variant
# NOINLINE bindMarshalls_raw_to_base64 #
-- | Returns a Base64-encoded string of a given @PoolByteArray@.
bindMarshalls_raw_to_base64 :: MethodBind
bindMarshalls_raw_to_base64
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "raw_to_base64" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns a Base64-encoded string of a given @PoolByteArray@.
raw_to_base64 ::
(Marshalls :< cls, Object :< cls) =>
cls -> PoolByteArray -> IO GodotString
raw_to_base64 cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_raw_to_base64 (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "raw_to_base64" '[PoolByteArray]
(IO GodotString)
where
nodeMethod = Godot.Core.Marshalls.raw_to_base64
{-# NOINLINE bindMarshalls_utf8_to_base64 #-}
| Returns a Base64 - encoded string of the UTF-8 string @utf8_str@.
bindMarshalls_utf8_to_base64 :: MethodBind
bindMarshalls_utf8_to_base64
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "utf8_to_base64" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns a Base64 - encoded string of the UTF-8 string @utf8_str@.
utf8_to_base64 ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotString -> IO GodotString
utf8_to_base64 cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_utf8_to_base64 (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "utf8_to_base64" '[GodotString]
(IO GodotString)
where
nodeMethod = Godot.Core.Marshalls.utf8_to_base64
# NOINLINE bindMarshalls_variant_to_base64 #
| Returns a Base64 - encoded string of the @Variant@ @variant@. If @full_objects@ is @true@ , encoding objects is allowed ( and can potentially include code ) .
bindMarshalls_variant_to_base64 :: MethodBind
bindMarshalls_variant_to_base64
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "variant_to_base64" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns a Base64 - encoded string of the @Variant@ @variant@. If @full_objects@ is @true@ , encoding objects is allowed ( and can potentially include code ) .
variant_to_base64 ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotVariant -> Maybe Bool -> IO GodotString
variant_to_base64 cls arg1 arg2
= withVariantArray
[toVariant arg1, maybe (VariantBool False) toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_variant_to_base64 (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "variant_to_base64"
'[GodotVariant, Maybe Bool]
(IO GodotString)
where
nodeMethod = Godot.Core.Marshalls.variant_to_base64 | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/Marshalls.hs | haskell | | Returns a decoded @PoolByteArray@ corresponding to the Base64-encoded string @base64_str@.
| Returns a decoded @PoolByteArray@ corresponding to the Base64-encoded string @base64_str@.
| Returns a decoded string corresponding to the Base64-encoded string @base64_str@.
| Returns a decoded string corresponding to the Base64-encoded string @base64_str@.
__Warning:__ Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution.
__Warning:__ Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution.
| Returns a Base64-encoded string of a given @PoolByteArray@.
| Returns a Base64-encoded string of a given @PoolByteArray@.
# NOINLINE bindMarshalls_utf8_to_base64 # | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.Marshalls
(Godot.Core.Marshalls.base64_to_raw,
Godot.Core.Marshalls.base64_to_utf8,
Godot.Core.Marshalls.base64_to_variant,
Godot.Core.Marshalls.raw_to_base64,
Godot.Core.Marshalls.utf8_to_base64,
Godot.Core.Marshalls.variant_to_base64)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Reference()
# NOINLINE bindMarshalls_base64_to_raw #
bindMarshalls_base64_to_raw :: MethodBind
bindMarshalls_base64_to_raw
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "base64_to_raw" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
base64_to_raw ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotString -> IO PoolByteArray
base64_to_raw cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_base64_to_raw (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "base64_to_raw" '[GodotString]
(IO PoolByteArray)
where
nodeMethod = Godot.Core.Marshalls.base64_to_raw
# NOINLINE bindMarshalls_base64_to_utf8 #
bindMarshalls_base64_to_utf8 :: MethodBind
bindMarshalls_base64_to_utf8
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "base64_to_utf8" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
base64_to_utf8 ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotString -> IO GodotString
base64_to_utf8 cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_base64_to_utf8 (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "base64_to_utf8" '[GodotString]
(IO GodotString)
where
nodeMethod = Godot.Core.Marshalls.base64_to_utf8
# NOINLINE bindMarshalls_base64_to_variant #
| Returns a decoded @Variant@ corresponding to the Base64 - encoded string @base64_str@. If @allow_objects@ is @true@ , decoding objects is allowed .
bindMarshalls_base64_to_variant :: MethodBind
bindMarshalls_base64_to_variant
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "base64_to_variant" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns a decoded @Variant@ corresponding to the Base64 - encoded string @base64_str@. If @allow_objects@ is @true@ , decoding objects is allowed .
base64_to_variant ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotString -> Maybe Bool -> IO GodotVariant
base64_to_variant cls arg1 arg2
= withVariantArray
[toVariant arg1, maybe (VariantBool False) toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_base64_to_variant (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "base64_to_variant"
'[GodotString, Maybe Bool]
(IO GodotVariant)
where
nodeMethod = Godot.Core.Marshalls.base64_to_variant
# NOINLINE bindMarshalls_raw_to_base64 #
bindMarshalls_raw_to_base64 :: MethodBind
bindMarshalls_raw_to_base64
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "raw_to_base64" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
raw_to_base64 ::
(Marshalls :< cls, Object :< cls) =>
cls -> PoolByteArray -> IO GodotString
raw_to_base64 cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_raw_to_base64 (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "raw_to_base64" '[PoolByteArray]
(IO GodotString)
where
nodeMethod = Godot.Core.Marshalls.raw_to_base64
| Returns a Base64 - encoded string of the UTF-8 string @utf8_str@.
bindMarshalls_utf8_to_base64 :: MethodBind
bindMarshalls_utf8_to_base64
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "utf8_to_base64" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns a Base64 - encoded string of the UTF-8 string @utf8_str@.
utf8_to_base64 ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotString -> IO GodotString
utf8_to_base64 cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_utf8_to_base64 (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "utf8_to_base64" '[GodotString]
(IO GodotString)
where
nodeMethod = Godot.Core.Marshalls.utf8_to_base64
# NOINLINE bindMarshalls_variant_to_base64 #
| Returns a Base64 - encoded string of the @Variant@ @variant@. If @full_objects@ is @true@ , encoding objects is allowed ( and can potentially include code ) .
bindMarshalls_variant_to_base64 :: MethodBind
bindMarshalls_variant_to_base64
= unsafePerformIO $
withCString "_Marshalls" $
\ clsNamePtr ->
withCString "variant_to_base64" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns a Base64 - encoded string of the @Variant@ @variant@. If @full_objects@ is @true@ , encoding objects is allowed ( and can potentially include code ) .
variant_to_base64 ::
(Marshalls :< cls, Object :< cls) =>
cls -> GodotVariant -> Maybe Bool -> IO GodotString
variant_to_base64 cls arg1 arg2
= withVariantArray
[toVariant arg1, maybe (VariantBool False) toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindMarshalls_variant_to_base64 (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Marshalls "variant_to_base64"
'[GodotVariant, Maybe Bool]
(IO GodotString)
where
nodeMethod = Godot.Core.Marshalls.variant_to_base64 |
03055315ff8c0e86ba81c52a88206580b7a94b5752a31c214d954a7df951bd22 | xmppjingle/snatch | claws_dummy.erl | -module(claws_dummy).
-compile([warnings_as_errors, debug_info]).
-export([send/2, send/3]).
send(Data, JID) ->
snatch_tests ! {?MODULE, Data, JID, undefined},
ok.
send(Data, JID, ID) ->
snatch_tests ! {?MODULE, Data, JID, ID},
ok.
| null | https://raw.githubusercontent.com/xmppjingle/snatch/da32ed1f17a05685461ec092800c4cb111a05f0b/test/claws_dummy.erl | erlang | -module(claws_dummy).
-compile([warnings_as_errors, debug_info]).
-export([send/2, send/3]).
send(Data, JID) ->
snatch_tests ! {?MODULE, Data, JID, undefined},
ok.
send(Data, JID, ID) ->
snatch_tests ! {?MODULE, Data, JID, ID},
ok.
|
|
663da6b4460471afab6aa60dd69d6c92bc1a51a3f4a27a6e057608e1d6afafbd | exercism/haskell | Grains.hs | module Grains (square, total) where
import Data.Maybe (fromJust)
square :: Integer -> Maybe Integer
square x
| x < 1 = Nothing
| x > 64 = Nothing
| otherwise = Just . (2^) . pred $ x
total :: Integer
total = sum . map (fromJust . square) $ [1..64]
| null | https://raw.githubusercontent.com/exercism/haskell/ae17e9fc5ca736a228db6dda5e3f3b057fa6f3d0/exercises/practice/grains/.meta/examples/success-standard/src/Grains.hs | haskell | module Grains (square, total) where
import Data.Maybe (fromJust)
square :: Integer -> Maybe Integer
square x
| x < 1 = Nothing
| x > 64 = Nothing
| otherwise = Just . (2^) . pred $ x
total :: Integer
total = sum . map (fromJust . square) $ [1..64]
|
|
9158c0672b4140e306a9e849ab4fb435d4b7f80f8d07430a7301ab708dc23c7f | aprolog-lang/aprolog | util.mli | Alpha Prolog
Utilities : exceptions and debugging
exception NYI;;
exception Error of string;;
exception RuntimeError of string;;
exception Impos of string;;
type 'a equal = 'a -> 'a -> bool;;
val nyi : unit -> 'a;;
val error : string -> 'a
val runtime_error : string -> 'a
val impos : string -> 'a
val do_trace : int -> (unit -> unit) -> unit
val warning : string -> unit
val nl : unit -> unit;;
val split : (char -> bool) -> string -> string list;;
val zip : 'a list -> 'b list -> ('a * 'b) list;;
val unzip : ('a * 'b) list -> 'a list * 'b list;;
val allpairs : 'a list -> 'b list -> ('a * 'b) list;;
val collect : ('a -> 'b list) -> 'a list -> 'b list;;
val map_partial : ('a -> 'b option) -> 'a list -> 'b list;;
val tabulate : (int -> 'a) -> int -> 'a list;;
| null | https://raw.githubusercontent.com/aprolog-lang/aprolog/410327a615919eb6827d71661e69de14279b8c50/src/util.mli | ocaml | Alpha Prolog
Utilities : exceptions and debugging
exception NYI;;
exception Error of string;;
exception RuntimeError of string;;
exception Impos of string;;
type 'a equal = 'a -> 'a -> bool;;
val nyi : unit -> 'a;;
val error : string -> 'a
val runtime_error : string -> 'a
val impos : string -> 'a
val do_trace : int -> (unit -> unit) -> unit
val warning : string -> unit
val nl : unit -> unit;;
val split : (char -> bool) -> string -> string list;;
val zip : 'a list -> 'b list -> ('a * 'b) list;;
val unzip : ('a * 'b) list -> 'a list * 'b list;;
val allpairs : 'a list -> 'b list -> ('a * 'b) list;;
val collect : ('a -> 'b list) -> 'a list -> 'b list;;
val map_partial : ('a -> 'b option) -> 'a list -> 'b list;;
val tabulate : (int -> 'a) -> int -> 'a list;;
|
|
c65b634b6c608b0cd24319b24f5a948b2df1cae5549b1b977d8e873444c8416a | ynadji/lisp | presentation.lisp | Presentation Macro Demo
;;;; What are macros?
(defmacro sum (x y)
`(+ ,x ,y))
;;;; syntax
(defun macro-01 (x)
x)
(defun macro-02 (x)
(x 20 30))
(defun macro-03 (x)
'(x 20 30))
(defun macro-04 (x)
(x '20 '30))
(defun macro-05 (x)
`(x 20 30))
(defun macro-06 (x)
`(,x 20 30))
;; how do we handled lists?
(defun macro-07 (lst)
`(,lst 4 5))
(defun **---** (a)
a)
(defun macro-08 (lst)
`(,@lst 4 5))
;;;; differences between defun and defmacro
(defmacro sum (x y)
`(+ ,x ,y))
(defun fsum (x y)
`(+ ,x ,y))
;; lisp-1 vs. lisp-2
(define (sum x y)
(+ x y))
(defun sum (x y)
(+ x y))
;;;; when to use macros
;; necessity due to splicing in the body
(defmacro while (test &body body)
`(do ()
((not ,test))
,@body))
(defun ex-while (n)
(let ((i 0))
(while (< i n)
(princ i)
(incf i))))
( ex - while 10 )
; (ex-while 0)
;; conditional evaluation, see while
picking apart the arguments ( setf vs. ( set - field vs. set - quantity ) )
;; compile-time compilation
(defun favg (&rest args)
(/ (apply #'+ args) (length args)))
(defmacro mavg (&rest args)
`(/ (+ ,@args) ,(length args)))
;; save function calls (just use (inline functionname))
;;;; common pitfalls -- behold (macroexpand-1)!
;; multiple evaluation
(defmacro square-01 (x)
`(* ,x ,x))
;; fix it:
(defmacro square-02 (x)
`(let ((val ,x))
(* val val)))
;; hygiene!
;; what's wrong with this macro?
(defmacro for ((var start stop) &body body)
`(do ((,var ,start (1+ ,var))
(limit ,stop))
((> ,var limit))
,@body))
;; try and call it with a predifined symbol limit
(defmacro gen-for ((var start stop) &body body)
(let ((gstop (gensym)))
`(do ((,var ,start (1+ ,var))
(,gstop ,stop))
((> ,var ,gstop))
,@body)))
;; now try broken code
;;; omg cool examples! | null | https://raw.githubusercontent.com/ynadji/lisp/758b5aebaa01f4994407d20026e617ebef90739e/chiglug-macros/presentation.lisp | lisp | What are macros?
syntax
how do we handled lists?
differences between defun and defmacro
lisp-1 vs. lisp-2
when to use macros
necessity due to splicing in the body
(ex-while 0)
conditional evaluation, see while
compile-time compilation
save function calls (just use (inline functionname))
common pitfalls -- behold (macroexpand-1)!
multiple evaluation
fix it:
hygiene!
what's wrong with this macro?
try and call it with a predifined symbol limit
now try broken code
omg cool examples! | Presentation Macro Demo
(defmacro sum (x y)
`(+ ,x ,y))
(defun macro-01 (x)
x)
(defun macro-02 (x)
(x 20 30))
(defun macro-03 (x)
'(x 20 30))
(defun macro-04 (x)
(x '20 '30))
(defun macro-05 (x)
`(x 20 30))
(defun macro-06 (x)
`(,x 20 30))
(defun macro-07 (lst)
`(,lst 4 5))
(defun **---** (a)
a)
(defun macro-08 (lst)
`(,@lst 4 5))
(defmacro sum (x y)
`(+ ,x ,y))
(defun fsum (x y)
`(+ ,x ,y))
(define (sum x y)
(+ x y))
(defun sum (x y)
(+ x y))
(defmacro while (test &body body)
`(do ()
((not ,test))
,@body))
(defun ex-while (n)
(let ((i 0))
(while (< i n)
(princ i)
(incf i))))
( ex - while 10 )
picking apart the arguments ( setf vs. ( set - field vs. set - quantity ) )
(defun favg (&rest args)
(/ (apply #'+ args) (length args)))
(defmacro mavg (&rest args)
`(/ (+ ,@args) ,(length args)))
(defmacro square-01 (x)
`(* ,x ,x))
(defmacro square-02 (x)
`(let ((val ,x))
(* val val)))
(defmacro for ((var start stop) &body body)
`(do ((,var ,start (1+ ,var))
(limit ,stop))
((> ,var limit))
,@body))
(defmacro gen-for ((var start stop) &body body)
(let ((gstop (gensym)))
`(do ((,var ,start (1+ ,var))
(,gstop ,stop))
((> ,var ,gstop))
,@body)))
|
949bf67e0575272548e10776ee59ae1c84dcb3780f3f69a1153a58a2f8a23678 | thierry-martinez/clangml | aux_lexer.mli | type lexeme =
| EOF
| Reference of { ident : string; number : string }
val main : Lexing.lexbuf -> lexeme
| null | https://raw.githubusercontent.com/thierry-martinez/clangml/de5dffeae98a9bef9934a8d272f077b307bec73f/tools/norm_extractor/aux_lexer.mli | ocaml | type lexeme =
| EOF
| Reference of { ident : string; number : string }
val main : Lexing.lexbuf -> lexeme
|
|
508a96e65c63b4cc2eeb9770fcda71a36f92c54d66cc5c3a7861bcb808354bbe | SKA-ScienceDataProcessor/RC | Scheduler.hs | -- | Schedule program for execution. At the moment it schedule for
-- exact number of threads
module DNA.Compiler.Scheduler where
import Control.Monad
import Data.Graph.Inductive.Graph
import qualified Data.IntMap as IntMap
import Data.IntMap ((!))
import DNA.AST
import DNA.Actor
import DNA.Compiler.Types
----------------------------------------------------------------
-- Simple scheduler
----------------------------------------------------------------
-- | Number of nodes in the cluster
type CAD = Int
-- | Simple scheduler. It assumes that all optimization passes are
-- done and will not try to transform graph.
schedule :: CAD -> DataflowGraph -> Compile DataflowGraph
schedule nTotal gr = do
let nMust = nMandatory gr
nVar = nVarGroups gr
We need at least 1 node per group
when (nFree < 0) $
compError ["Not enough nodes to schedule algorithm"]
-- Schedule for mandatory nodes. For each node we
let mandSched = IntMap.fromList $ mandatoryNodes gr `zip` [0..]
-- Now we should schedule remaining nodes.
let varGroups = contiguosChunks nMust (splitChunks nVar (nTotal - nMust))
varSched = IntMap.fromList $ variableNodes gr `zip` varGroups
-- Build schedule for every
let sched i (ANode _ a@(RealActor _ act)) =
case act of
StateM{} -> ANode (Single n) a
Producer{} -> ANode (Single n) a
ScatterGather{} -> ANode (MasterSlaves n (varSched ! i)) a
where
n = mandSched ! i
return $ gmap (\(a1, i, a, a2) -> (a1, i, sched i a, a2)) gr
-- | Total number of processes that we must spawn.
nMandatory :: DataflowGraph -> Int
nMandatory gr
= sum [ getN $ lab' $ context gr n | n <- nodes gr]
where
getN (ANode _ _) = 1
-- | List of all actors for which we must allocate separate cluster node.
mandatoryNodes :: DataflowGraph -> [Node]
mandatoryNodes gr =
[ n | n <- nodes gr]
variableNodes :: DataflowGraph -> [Node]
variableNodes gr =
[ n | n <- nodes gr
, isSG (lab' $ context gr n)
]
where
isSG (ANode _ (RealActor _ (ScatterGather{}))) = True
isSG _ = False
-- | Number of groups for which we can vary number of allocated nodes
nVarGroups :: DataflowGraph -> Int
nVarGroups gr
= sum [ get $ lab' $ context gr n | n <- nodes gr]
where
get (ANode _ (RealActor _ (ScatterGather{}))) = 1
get _ = 0
-- Split N items to k groups.
splitChunks :: Int -> Int -> [Int]
splitChunks nChunks nTot
= map (+1) toIncr ++ rest
where
(chunk,n) = nTot `divMod` nChunks
(toIncr,rest) = splitAt n (replicate nChunks chunk)
contiguosChunks :: Int -> [Int] -> [[Int]]
contiguosChunks off = go [off ..]
where
go _ [] = []
go xs (n:ns) = case splitAt n xs of
(a,rest) -> a : go rest ns
| null | https://raw.githubusercontent.com/SKA-ScienceDataProcessor/RC/1b5e25baf9204a9f7ef40ed8ee94a86cc6c674af/MS1/dna/DNA/Compiler/Scheduler.hs | haskell | | Schedule program for execution. At the moment it schedule for
exact number of threads
--------------------------------------------------------------
Simple scheduler
--------------------------------------------------------------
| Number of nodes in the cluster
| Simple scheduler. It assumes that all optimization passes are
done and will not try to transform graph.
Schedule for mandatory nodes. For each node we
Now we should schedule remaining nodes.
Build schedule for every
| Total number of processes that we must spawn.
| List of all actors for which we must allocate separate cluster node.
| Number of groups for which we can vary number of allocated nodes
Split N items to k groups. | module DNA.Compiler.Scheduler where
import Control.Monad
import Data.Graph.Inductive.Graph
import qualified Data.IntMap as IntMap
import Data.IntMap ((!))
import DNA.AST
import DNA.Actor
import DNA.Compiler.Types
type CAD = Int
schedule :: CAD -> DataflowGraph -> Compile DataflowGraph
schedule nTotal gr = do
let nMust = nMandatory gr
nVar = nVarGroups gr
We need at least 1 node per group
when (nFree < 0) $
compError ["Not enough nodes to schedule algorithm"]
let mandSched = IntMap.fromList $ mandatoryNodes gr `zip` [0..]
let varGroups = contiguosChunks nMust (splitChunks nVar (nTotal - nMust))
varSched = IntMap.fromList $ variableNodes gr `zip` varGroups
let sched i (ANode _ a@(RealActor _ act)) =
case act of
StateM{} -> ANode (Single n) a
Producer{} -> ANode (Single n) a
ScatterGather{} -> ANode (MasterSlaves n (varSched ! i)) a
where
n = mandSched ! i
return $ gmap (\(a1, i, a, a2) -> (a1, i, sched i a, a2)) gr
nMandatory :: DataflowGraph -> Int
nMandatory gr
= sum [ getN $ lab' $ context gr n | n <- nodes gr]
where
getN (ANode _ _) = 1
mandatoryNodes :: DataflowGraph -> [Node]
mandatoryNodes gr =
[ n | n <- nodes gr]
variableNodes :: DataflowGraph -> [Node]
variableNodes gr =
[ n | n <- nodes gr
, isSG (lab' $ context gr n)
]
where
isSG (ANode _ (RealActor _ (ScatterGather{}))) = True
isSG _ = False
nVarGroups :: DataflowGraph -> Int
nVarGroups gr
= sum [ get $ lab' $ context gr n | n <- nodes gr]
where
get (ANode _ (RealActor _ (ScatterGather{}))) = 1
get _ = 0
splitChunks :: Int -> Int -> [Int]
splitChunks nChunks nTot
= map (+1) toIncr ++ rest
where
(chunk,n) = nTot `divMod` nChunks
(toIncr,rest) = splitAt n (replicate nChunks chunk)
contiguosChunks :: Int -> [Int] -> [[Int]]
contiguosChunks off = go [off ..]
where
go _ [] = []
go xs (n:ns) = case splitAt n xs of
(a,rest) -> a : go rest ns
|
0b0758e20fbf3c97de2c5d01faf4c5dba7eb35e60444df526e8daa71e4fb5ada | sKabYY/palestra | p55.scm | (load "stream.scm")
(stream-for-n println
(partial-sums integers)
10)
| null | https://raw.githubusercontent.com/sKabYY/palestra/0906cc3a1fb786093a388d5ae7d59120f5aae16c/old1/sicp/3/p55.scm | scheme | (load "stream.scm")
(stream-for-n println
(partial-sums integers)
10)
|
|
26f03b736d506ccd1fe5af43889246f65fc3545713142d8e4ae71d68b1cdc5c0 | BillHallahan/G2 | AddToEven.hs | module AddToEven where
import Prelude hiding (zipWith)
{-@ LIQUID "--no-termination" @-}
@ type Even = { v : Int | v mod 2 = 0 } @
{-@ f :: Even -> Even @-}
f :: Int -> Int
f x = x + g 5
@ : : Int - > Even @
fBad :: Int -> Int
fBad x = x + x
Without the below refinement type for g , this file can not be verified
: : Int - > Even @- }
: : Int - > { v : Int | v /= -1 } @- }
g :: Int -> Int
g x = x + x
data List a = Emp
| (:+:) a (List a)
deriving (Eq, Ord, Show)
@ measure size : : List a - > Int
size ( Emp ) = 0
size ( (: + :) x xs ) = 1 + size xs
@
size (Emp) = 0
size ((:+:) x xs) = 1 + size xs
@-}
{-@ zipWith :: (a -> b -> c) -> v1:List a -> {v2:List b | size v1 > 0 => size v2 > 0} -> List c @-}
zipWith _ Emp Emp = Emp
zipWith f (x :+: xs) (y :+: ys) = f x y :+: zipWith f xs ys
zipWith f _ _ = die "Bad call to zipWith"
{-@ die :: {v:String | false} -> a @-}
die str = error ("Oops, I died!" ++ str)
@ f2 : : { x : Int | x mod 2 = 0 } @
f2 :: Int
f2 = g2
@ : : Int @
g2 :: Int
g2 = 0
{-@ f3 :: Int -> Even @-}
f3 :: Int -> Int
f3 x = x + g3 x
Without the below refinement type for g , this file can not be verified
{-@ g3 :: Int -> Int @-}
g3 :: Int -> Int
g3 x = x
@ h : : { x : Int | x = = 8 } @
h :: Int
h = 6 + 2
{-@ f4 :: {x:Int | x == 0} @-}
f4 :: Int
f4 = g2
{-@ g4 :: Int @-}
g4 :: Int
g4 = 0
| null | https://raw.githubusercontent.com/BillHallahan/G2/21c648d38c380041a9036d0e375ec1d54120f6b4/tests_lh/Liquid/AddToEven.hs | haskell | @ LIQUID "--no-termination" @
@ f :: Even -> Even @
@ zipWith :: (a -> b -> c) -> v1:List a -> {v2:List b | size v1 > 0 => size v2 > 0} -> List c @
@ die :: {v:String | false} -> a @
@ f3 :: Int -> Even @
@ g3 :: Int -> Int @
@ f4 :: {x:Int | x == 0} @
@ g4 :: Int @ | module AddToEven where
import Prelude hiding (zipWith)
@ type Even = { v : Int | v mod 2 = 0 } @
f :: Int -> Int
f x = x + g 5
@ : : Int - > Even @
fBad :: Int -> Int
fBad x = x + x
Without the below refinement type for g , this file can not be verified
: : Int - > Even @- }
: : Int - > { v : Int | v /= -1 } @- }
g :: Int -> Int
g x = x + x
data List a = Emp
| (:+:) a (List a)
deriving (Eq, Ord, Show)
@ measure size : : List a - > Int
size ( Emp ) = 0
size ( (: + :) x xs ) = 1 + size xs
@
size (Emp) = 0
size ((:+:) x xs) = 1 + size xs
@-}
zipWith _ Emp Emp = Emp
zipWith f (x :+: xs) (y :+: ys) = f x y :+: zipWith f xs ys
zipWith f _ _ = die "Bad call to zipWith"
die str = error ("Oops, I died!" ++ str)
@ f2 : : { x : Int | x mod 2 = 0 } @
f2 :: Int
f2 = g2
@ : : Int @
g2 :: Int
g2 = 0
f3 :: Int -> Int
f3 x = x + g3 x
Without the below refinement type for g , this file can not be verified
g3 :: Int -> Int
g3 x = x
@ h : : { x : Int | x = = 8 } @
h :: Int
h = 6 + 2
f4 :: Int
f4 = g2
g4 :: Int
g4 = 0
|
6db10931defb65a0d8bfb007d1a7dc7bf2c9c315d3b8c3b7baaa22d4d582f2b9 | ogaml/ogaml | text.mli | module Fx : sig
type t
type ('a,'b) it = 'a -> 'b -> ('b -> 'b) -> 'b
type ('a,'b,'c) full_it = ('a, 'b) it * 'b * ('b -> 'c)
val forall : 'c -> ('a, 'c list, 'c list) full_it
val foreach : ('a -> 'b) -> ('a, 'b list, 'b list) full_it
val foreachi : ('a -> int -> 'b) -> ('a, 'b list * int, 'b list) full_it
val foreachword :
(Font.code list -> 'a) -> 'a ->
(Font.code, 'a list * Font.code list, 'a list) full_it
(* TODO: Exception when the iterator doesn't return list of right size *)
val create :
(module RenderTarget.T with type t = 'a) ->
target : 'a ->
text : string ->
position : OgamlMath.Vector2f.t ->
font : Font.t ->
colors : (Font.code,'b,Color.t list) full_it ->
size : int ->
unit -> t
val draw :
(module RenderTarget.T with type t = 'a) ->
?parameters : DrawParameter.t ->
text : t ->
target : 'a ->
unit -> unit
val advance : t -> OgamlMath.Vector2f.t
val boundaries : t -> OgamlMath.FloatRect.t
end
type t
val create :
text : string ->
position : OgamlMath.Vector2f.t ->
font : Font.t ->
?color : Color.t ->
size : int ->
?bold : bool ->
unit -> t
val draw :
(module RenderTarget.T with type t = 'a) ->
?parameters : DrawParameter.t ->
text : t ->
target : 'a ->
unit -> unit
val to_source : t -> VertexArray.SimpleVertex.T.s VertexArray.VertexSource.t -> unit
val map_to_source : t ->
(VertexArray.SimpleVertex.T.s VertexArray.Vertex.t -> 'b VertexArray.Vertex.t) ->
'b VertexArray.VertexSource.t -> unit
val advance : t -> OgamlMath.Vector2f.t
val boundaries : t -> OgamlMath.FloatRect.t
| null | https://raw.githubusercontent.com/ogaml/ogaml/5e74597521abf7ba2833a9247e55780eabfbab78/src/graphics/2d/text.mli | ocaml | TODO: Exception when the iterator doesn't return list of right size | module Fx : sig
type t
type ('a,'b) it = 'a -> 'b -> ('b -> 'b) -> 'b
type ('a,'b,'c) full_it = ('a, 'b) it * 'b * ('b -> 'c)
val forall : 'c -> ('a, 'c list, 'c list) full_it
val foreach : ('a -> 'b) -> ('a, 'b list, 'b list) full_it
val foreachi : ('a -> int -> 'b) -> ('a, 'b list * int, 'b list) full_it
val foreachword :
(Font.code list -> 'a) -> 'a ->
(Font.code, 'a list * Font.code list, 'a list) full_it
val create :
(module RenderTarget.T with type t = 'a) ->
target : 'a ->
text : string ->
position : OgamlMath.Vector2f.t ->
font : Font.t ->
colors : (Font.code,'b,Color.t list) full_it ->
size : int ->
unit -> t
val draw :
(module RenderTarget.T with type t = 'a) ->
?parameters : DrawParameter.t ->
text : t ->
target : 'a ->
unit -> unit
val advance : t -> OgamlMath.Vector2f.t
val boundaries : t -> OgamlMath.FloatRect.t
end
type t
val create :
text : string ->
position : OgamlMath.Vector2f.t ->
font : Font.t ->
?color : Color.t ->
size : int ->
?bold : bool ->
unit -> t
val draw :
(module RenderTarget.T with type t = 'a) ->
?parameters : DrawParameter.t ->
text : t ->
target : 'a ->
unit -> unit
val to_source : t -> VertexArray.SimpleVertex.T.s VertexArray.VertexSource.t -> unit
val map_to_source : t ->
(VertexArray.SimpleVertex.T.s VertexArray.Vertex.t -> 'b VertexArray.Vertex.t) ->
'b VertexArray.VertexSource.t -> unit
val advance : t -> OgamlMath.Vector2f.t
val boundaries : t -> OgamlMath.FloatRect.t
|
a47439e40370d7a9aae55faee334588f3025e6d4f41c7fd85d226b35eafe02fa | LuisThiamNye/chic | source.clj | (ns chic.clj.source
(:require
[clojure.java.io :as io]
[clojure.repl :as repl]
[clojure.string :as str])
(:import
(java.io Reader PushbackReader)))
(defn reader-skip-lines [^Reader rdr nlines]
(when (< 0 nlines)
(while (let [c (.read rdr)]
(not (or (== c 10)
(== c -1)))))
(recur rdr (unchecked-dec-int nlines))))
(defn read-var-source-code [v]
(let [mmap (meta v)]
(with-open [rdr ^Reader (io/reader (:file mmap))]
(reader-skip-lines rdr (unchecked-dec-int (:line mmap)))
(.skip rdr (unchecked-dec-int (:column mmap)))
(read (PushbackReader. rdr)))))
(defn crude-source-of-var [v]
(when (= \/ (first (:file (meta v))))
(alter-meta! v (fn [m]
(update m :file
(fn [f]
(str/replace f (str (System/getProperty "user.dir") "/src/") ""))))))
(try
(push-thread-bindings {Compiler/LOADER (.getClassLoader Compiler)})
(repl/source-fn (symbol v))
(catch Exception _ nil)
(finally
(pop-thread-bindings))))
(comment
(require
'[clojure-lsp.api :as lsp.api]
'[clojure-lsp.db :as lsp.db]
'[clojure-lsp.handlers :as lsp.handlers])
(crude-source-of-var #'read-var-source-code)
(read-var-source-code #'chic.cljbwr/basic-view)
(meta #'chic.main/-main)
(meta #'chic.clj.source/reader-skip-lines)
(meta *ns*)
;; what is a namespace file?
;; - ns form
;; - def macros -> vars
;; - extend / extend-type
;; - comments lines and blocks
;; - declare
clojure.repl/source-fn depends on reading the file from disk
;; so is unreliable if the file has changed in meantime
;; also need to make sure :file is relative in the metadata:
;; (caused when defing new var from nrepl)
(alter-meta! #'chic.cljbwr/editor-view
(fn [m]
(update m :file
(fn [f]
(str/replace f (str (System/getProperty "user.dir") "/src/") "")))))
(def lspthing (lsp.api/analyze-project-and-deps! {:file (io/file ".")}))
(chic.debug/println-main (:message (lsp.api/diagnostics {:namespace '[chic.cljbwr]
:output {:canonical-paths true}})))
(chic.debug/println-main (:message (lsp.api/diagnostics {:namespace '[chic.clj.source]
:output {:canonical-paths true}})))
(lsp.handlers/did-change
{:textDocument {:uri
:version}
:contentChanges [{:start {:line start-line
:character start-character}
:end {:line end-line
:character end-character}}]})
(-> @lsp.db/db :documents keys)
(let [x(fn [])]
x)
(letfn [(x [])]
x)
(require '[clj-kondo.core :as kondo])
(def ana (atom nil))
(hash(:analysis
(kondo/run! {:lint [(io/file "src/chic/clj/source.clj")]
:cache true
:config {:output {:analysis {:arglists true
:locals true
:keywords false
:protocol-impls true
:java-class-definitions true}
:canonical-paths true}}
:custom-lint-fn (fn [{:keys [analysis] :as kondo-ctx}]
(reset! ana analysis))})))
@ana
note : can use by giving " - " as path name and using * in *
` cache - dir`/.cache ( default cfg - dir/.cache ( cfg - dir usually local to project ) )
;; directory is used to store things like arity info of functions
;; using this is controlled by :cache. Even when :cache is true, the file is read afresh
;; and may update the cache
;; kondo works by analysing single files and depending on the cache and config for additional context
*source-path*
#!
)
(let [x 7]
(def x x))
| null | https://raw.githubusercontent.com/LuisThiamNye/chic/813633a689f9080731613f788a295604d4d9a510/src/chic/clj/source.clj | clojure | what is a namespace file?
- ns form
- def macros -> vars
- extend / extend-type
- comments lines and blocks
- declare
so is unreliable if the file has changed in meantime
also need to make sure :file is relative in the metadata:
(caused when defing new var from nrepl)
directory is used to store things like arity info of functions
using this is controlled by :cache. Even when :cache is true, the file is read afresh
and may update the cache
kondo works by analysing single files and depending on the cache and config for additional context | (ns chic.clj.source
(:require
[clojure.java.io :as io]
[clojure.repl :as repl]
[clojure.string :as str])
(:import
(java.io Reader PushbackReader)))
(defn reader-skip-lines [^Reader rdr nlines]
(when (< 0 nlines)
(while (let [c (.read rdr)]
(not (or (== c 10)
(== c -1)))))
(recur rdr (unchecked-dec-int nlines))))
(defn read-var-source-code [v]
(let [mmap (meta v)]
(with-open [rdr ^Reader (io/reader (:file mmap))]
(reader-skip-lines rdr (unchecked-dec-int (:line mmap)))
(.skip rdr (unchecked-dec-int (:column mmap)))
(read (PushbackReader. rdr)))))
(defn crude-source-of-var [v]
(when (= \/ (first (:file (meta v))))
(alter-meta! v (fn [m]
(update m :file
(fn [f]
(str/replace f (str (System/getProperty "user.dir") "/src/") ""))))))
(try
(push-thread-bindings {Compiler/LOADER (.getClassLoader Compiler)})
(repl/source-fn (symbol v))
(catch Exception _ nil)
(finally
(pop-thread-bindings))))
(comment
(require
'[clojure-lsp.api :as lsp.api]
'[clojure-lsp.db :as lsp.db]
'[clojure-lsp.handlers :as lsp.handlers])
(crude-source-of-var #'read-var-source-code)
(read-var-source-code #'chic.cljbwr/basic-view)
(meta #'chic.main/-main)
(meta #'chic.clj.source/reader-skip-lines)
(meta *ns*)
clojure.repl/source-fn depends on reading the file from disk
(alter-meta! #'chic.cljbwr/editor-view
(fn [m]
(update m :file
(fn [f]
(str/replace f (str (System/getProperty "user.dir") "/src/") "")))))
(def lspthing (lsp.api/analyze-project-and-deps! {:file (io/file ".")}))
(chic.debug/println-main (:message (lsp.api/diagnostics {:namespace '[chic.cljbwr]
:output {:canonical-paths true}})))
(chic.debug/println-main (:message (lsp.api/diagnostics {:namespace '[chic.clj.source]
:output {:canonical-paths true}})))
(lsp.handlers/did-change
{:textDocument {:uri
:version}
:contentChanges [{:start {:line start-line
:character start-character}
:end {:line end-line
:character end-character}}]})
(-> @lsp.db/db :documents keys)
(let [x(fn [])]
x)
(letfn [(x [])]
x)
(require '[clj-kondo.core :as kondo])
(def ana (atom nil))
(hash(:analysis
(kondo/run! {:lint [(io/file "src/chic/clj/source.clj")]
:cache true
:config {:output {:analysis {:arglists true
:locals true
:keywords false
:protocol-impls true
:java-class-definitions true}
:canonical-paths true}}
:custom-lint-fn (fn [{:keys [analysis] :as kondo-ctx}]
(reset! ana analysis))})))
@ana
note : can use by giving " - " as path name and using * in *
` cache - dir`/.cache ( default cfg - dir/.cache ( cfg - dir usually local to project ) )
*source-path*
#!
)
(let [x 7]
(def x x))
|
dd89be86d4ae65fcfa9cd69a349e19a4f24fd15a243309db806bd248c99743ad | ocaml/opam | opamCompat.mli | (**************************************************************************)
(* *)
Copyright 2018 - 2020 OCamlPro
(* *)
(* All rights reserved. This file is distributed under the terms of the *)
GNU Lesser General Public License version 2.1 , with the special
(* exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
module String
#if OCAML_VERSION >= (4, 13, 0)
= String
#else
: sig
include module type of struct include String end
val exists: (char -> bool) -> string -> bool
end
#endif
module Char = Char
module Either
#if OCAML_VERSION >= (4, 12, 0)
= Either
#else
: sig
type ('a, 'b) t =
| Left of 'a
| Right of 'b
end
#endif
module Int
#if OCAML_VERSION >= (4, 12, 0)
= Int
#else
: sig
val compare: int -> int -> int
val equal : int -> int -> bool
end
#endif
module Printexc
#if OCAML_VERSION >= (4, 5, 0)
= Printexc
#else
: sig
include module type of struct include Printexc end
val raise_with_backtrace: exn -> raw_backtrace -> 'a
end
#endif
module Unix : sig
include module type of struct include Unix end
#if OCAML_VERSION < (4, 6, 0)
val map_file : Unix.file_descr -> ?pos:int64 -> ('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> bool -> int array ->
('a, 'b, 'c) Bigarray.Genarray.t
#endif
` realpath ` for OCaml > = 4.13.0 ,
implementation with double chdir otherwise
implementation with double chdir otherwise *)
val normalise: string -> string
end
module Uchar = Uchar
module Buffer
#if OCAML_VERSION >= (4, 6, 0)
= Buffer
#else
: sig
include module type of struct include Buffer end
val add_utf_8_uchar : t -> Uchar.t -> unit
end
#endif
module Filename
#if OCAML_VERSION >= (4, 4, 0)
= Filename
#else
: sig
include module type of struct include Filename end
val extension : string -> string
end
#endif
module Result
#if OCAML_VERSION >= (4, 8, 0)
= Result
#else
: sig
type ('a, 'e) t
= ('a, 'e) result
= Ok of 'a | Error of 'e
end
#endif
#if OCAML_VERSION < (4, 7, 0)
module Stdlib = Pervasives
#else
module Stdlib = Stdlib
#endif
module Lazy
#if OCAML_VERSION >= (4, 13, 0)
= Lazy
#else
: sig
include module type of struct include Lazy end
val map : ('a -> 'b) -> 'a t -> 'b t
end
#endif
module Fun
#if OCAML_VERSION >= (4, 08, 0)
= Fun
#else
: sig
val protect : finally:(unit -> unit) -> (unit -> 'a) -> 'a
end
#endif
| null | https://raw.githubusercontent.com/ocaml/opam/652474c528916d6bd9543a1119e56f19e3bda010/src/core/opamCompat.mli | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************ | Copyright 2018 - 2020 OCamlPro
GNU Lesser General Public License version 2.1 , with the special
module String
#if OCAML_VERSION >= (4, 13, 0)
= String
#else
: sig
include module type of struct include String end
val exists: (char -> bool) -> string -> bool
end
#endif
module Char = Char
module Either
#if OCAML_VERSION >= (4, 12, 0)
= Either
#else
: sig
type ('a, 'b) t =
| Left of 'a
| Right of 'b
end
#endif
module Int
#if OCAML_VERSION >= (4, 12, 0)
= Int
#else
: sig
val compare: int -> int -> int
val equal : int -> int -> bool
end
#endif
module Printexc
#if OCAML_VERSION >= (4, 5, 0)
= Printexc
#else
: sig
include module type of struct include Printexc end
val raise_with_backtrace: exn -> raw_backtrace -> 'a
end
#endif
module Unix : sig
include module type of struct include Unix end
#if OCAML_VERSION < (4, 6, 0)
val map_file : Unix.file_descr -> ?pos:int64 -> ('a, 'b) Bigarray.kind ->
'c Bigarray.layout -> bool -> int array ->
('a, 'b, 'c) Bigarray.Genarray.t
#endif
` realpath ` for OCaml > = 4.13.0 ,
implementation with double chdir otherwise
implementation with double chdir otherwise *)
val normalise: string -> string
end
module Uchar = Uchar
module Buffer
#if OCAML_VERSION >= (4, 6, 0)
= Buffer
#else
: sig
include module type of struct include Buffer end
val add_utf_8_uchar : t -> Uchar.t -> unit
end
#endif
module Filename
#if OCAML_VERSION >= (4, 4, 0)
= Filename
#else
: sig
include module type of struct include Filename end
val extension : string -> string
end
#endif
module Result
#if OCAML_VERSION >= (4, 8, 0)
= Result
#else
: sig
type ('a, 'e) t
= ('a, 'e) result
= Ok of 'a | Error of 'e
end
#endif
#if OCAML_VERSION < (4, 7, 0)
module Stdlib = Pervasives
#else
module Stdlib = Stdlib
#endif
module Lazy
#if OCAML_VERSION >= (4, 13, 0)
= Lazy
#else
: sig
include module type of struct include Lazy end
val map : ('a -> 'b) -> 'a t -> 'b t
end
#endif
module Fun
#if OCAML_VERSION >= (4, 08, 0)
= Fun
#else
: sig
val protect : finally:(unit -> unit) -> (unit -> 'a) -> 'a
end
#endif
|
4033cf6b8d7f899bc177c66db68192de4e85762d0e2d56d20c8fdbcaffe6d058 | DSTOQ/haskell-stellar-sdk | PrinterSpec.hs | module Stellar.Core.Key.PrinterSpec where
import Hedgehog
import Protolude
import Stellar.Core.Types.Key
import Stellar.Gens
run :: IO Bool
run = checkParallel $ Group "Printer Properties"
[ ("Roundtrip public key", prop_roundtrip_public_key)
, ("Roundtrip secret key", prop_roundtrip_secret_key)
]
prop_roundtrip_public_key :: Property
prop_roundtrip_public_key = property $ do
PublicKeyText key <- forAll genPublicKeyText
(printPublicKey <$> parsePublicKey key) === Right key
prop_roundtrip_secret_key :: Property
prop_roundtrip_secret_key = property $ do
SecretKeyText key <- forAll genSecretKeyText
(printSecretKey <$> parseSecretKey key) === Right key
| null | https://raw.githubusercontent.com/DSTOQ/haskell-stellar-sdk/82a76c2f951a2aaabdc38092fdc89044b278c53d/tests/test/Stellar/Core/Key/PrinterSpec.hs | haskell | module Stellar.Core.Key.PrinterSpec where
import Hedgehog
import Protolude
import Stellar.Core.Types.Key
import Stellar.Gens
run :: IO Bool
run = checkParallel $ Group "Printer Properties"
[ ("Roundtrip public key", prop_roundtrip_public_key)
, ("Roundtrip secret key", prop_roundtrip_secret_key)
]
prop_roundtrip_public_key :: Property
prop_roundtrip_public_key = property $ do
PublicKeyText key <- forAll genPublicKeyText
(printPublicKey <$> parsePublicKey key) === Right key
prop_roundtrip_secret_key :: Property
prop_roundtrip_secret_key = property $ do
SecretKeyText key <- forAll genSecretKeyText
(printSecretKey <$> parseSecretKey key) === Right key
|
|
666a56e6971848b2178a68d03024a0210fa2d7d4502241820532fcb78d4cd42d | hasura/graphql-parser-hs | Internal.hs | # LANGUAGE CPP #
# LANGUAGE TemplateHaskell #
# OPTIONS_GHC -fno - warn - redundant - constraints #
-- | Internal GraphQL AST functionality.
--
-- This module is primarily necessary due to an incorrect
@-Wredundant - constraints@ warning emitted by GHC when compiling
-- 'liftTypedHashMap'.
module Language.GraphQL.Draft.Syntax.Internal
( liftTypedHashMap,
)
where
-------------------------------------------------------------------------------
import Data.HashMap.Strict (HashMap)
import Data.HashMap.Strict qualified as HashMap
import Data.Hashable (Hashable)
import Language.Haskell.TH.Syntax (Lift, liftTyped)
import Language.Haskell.TH.Syntax qualified as TH
import Prelude
-------------------------------------------------------------------------------
| Lift a ' HashMap ' into a Template Haskell splice via list conversion .
#if MIN_VERSION_template_haskell(2,17,0)
liftTypedHashMap ::
( Eq k,
Hashable k,
Lift k,
Lift v,
TH.Quote m
) =>
HashMap k v ->
TH.Code m (HashMap k v)
#else
liftTypedHashMap ::
( Eq k,
Hashable k,
Lift k,
Lift v
) =>
HashMap k v ->
TH.Q (TH.TExp (HashMap k v))
#endif
liftTypedHashMap hm =
[||HashMap.fromList $$(liftTyped $ HashMap.toList hm)||]
| null | https://raw.githubusercontent.com/hasura/graphql-parser-hs/17596053e7fb24e387c9fe13fa0e48c7318c7421/src/Language/GraphQL/Draft/Syntax/Internal.hs | haskell | | Internal GraphQL AST functionality.
This module is primarily necessary due to an incorrect
'liftTypedHashMap'.
-----------------------------------------------------------------------------
----------------------------------------------------------------------------- | # LANGUAGE CPP #
# LANGUAGE TemplateHaskell #
# OPTIONS_GHC -fno - warn - redundant - constraints #
@-Wredundant - constraints@ warning emitted by GHC when compiling
module Language.GraphQL.Draft.Syntax.Internal
( liftTypedHashMap,
)
where
import Data.HashMap.Strict (HashMap)
import Data.HashMap.Strict qualified as HashMap
import Data.Hashable (Hashable)
import Language.Haskell.TH.Syntax (Lift, liftTyped)
import Language.Haskell.TH.Syntax qualified as TH
import Prelude
| Lift a ' HashMap ' into a Template Haskell splice via list conversion .
#if MIN_VERSION_template_haskell(2,17,0)
liftTypedHashMap ::
( Eq k,
Hashable k,
Lift k,
Lift v,
TH.Quote m
) =>
HashMap k v ->
TH.Code m (HashMap k v)
#else
liftTypedHashMap ::
( Eq k,
Hashable k,
Lift k,
Lift v
) =>
HashMap k v ->
TH.Q (TH.TExp (HashMap k v))
#endif
liftTypedHashMap hm =
[||HashMap.fromList $$(liftTyped $ HashMap.toList hm)||]
|
da1946aa956136914cba4652e9155c8267d7168689befff09cdeac2fe70c7189 | kronusaturn/lw2-viewer | user-context.lisp | (uiop:define-package #:lw2.user-context
(:use #:cl)
(:export #:*current-auth-token* #:*current-auth-status* #:*current-userid* #:*current-username* #:*current-user-slug* #:*current-ignore-hash*
#:logged-in-userid #:logged-in-username #:logged-in-user-slug))
(in-package #:lw2.user-context)
(defvar *current-auth-token*)
(defvar *current-auth-status*)
(defvar *current-userid*)
(defvar *current-username*)
(defvar *current-user-slug*)
(defvar *current-ignore-hash*)
(defun logged-in-userid (&optional is-userid)
(let ((current-userid *current-userid*))
(if is-userid
(string= current-userid is-userid)
current-userid)))
(defun logged-in-username ()
*current-username*)
(defun logged-in-user-slug ()
*current-user-slug*)
| null | https://raw.githubusercontent.com/kronusaturn/lw2-viewer/f328105e9640be1314d166203c8706f9470054fa/src/user-context.lisp | lisp | (uiop:define-package #:lw2.user-context
(:use #:cl)
(:export #:*current-auth-token* #:*current-auth-status* #:*current-userid* #:*current-username* #:*current-user-slug* #:*current-ignore-hash*
#:logged-in-userid #:logged-in-username #:logged-in-user-slug))
(in-package #:lw2.user-context)
(defvar *current-auth-token*)
(defvar *current-auth-status*)
(defvar *current-userid*)
(defvar *current-username*)
(defvar *current-user-slug*)
(defvar *current-ignore-hash*)
(defun logged-in-userid (&optional is-userid)
(let ((current-userid *current-userid*))
(if is-userid
(string= current-userid is-userid)
current-userid)))
(defun logged-in-username ()
*current-username*)
(defun logged-in-user-slug ()
*current-user-slug*)
|
|
3f0c34f5e35b5b2ce0fc76097caab439e4009af3196eb1e1ff4fa3c1d606ce57 | kanru/cl-isolated | isolated.lisp | ;;;; Isolated --- A isolated environment for evaluating Common Lisp
;;;; expressions
Copyright ( C ) 2014 , 2020 < >
Copyright ( C ) 2012 - 2013 < >
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation , either version 3 of the
;; License, or (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Affero General Public License for more details.
;;
You should have received a copy of the GNU Affero General Public
;; License along with this program. If not, see
;; </>.
(defpackage #:isolated
(:use #:cl #:isolated-impl)
(:export #:*env* #:*isolated-homedir-pathname*
#:read-eval-print #:reset))
(in-package #:isolated)
(declaim (optimize (safety 3)))
(defvar *msg-value-prefix* "=> ")
(defvar *msg-error-prefix* ";; ")
(define-condition all-read () ())
(defun msge (stream format-string &rest params)
(apply #'format stream (concatenate 'string "~&" *msg-error-prefix*
format-string "~%")
params))
(defun msgv (stream format-string &rest params)
(apply #'format stream (concatenate 'string "~&" *msg-value-prefix*
format-string "~%")
params))
(defun isolated-print (values &optional (stream *standard-output*))
(if values
(msgv stream "~{~S~^, ~}" values)
(msge stream "No value"))
nil)
(defun reset ()
(ignore-errors
(delete-package *env*))
(make-package *env* :use '(#:isolated-cl))
(loop :for name :in '("+" "++" "+++" "*" "**" "***" "/" "//" "///" "-")
:do (eval `(defparameter ,(intern name *env*) nil)))
(loop :for fn :in '(+ - * /)
:for symbol := (intern (symbol-name fn) *env*)
:do (setf (get symbol :isolated-locked) t)
(eval `(defun ,symbol (&rest args)
(apply ',fn args))))
*env*)
(defun read-eval-print (string &optional (stream *standard-output*))
(unless (or (find-package *env*) (reset))
(msge stream "ISOLATED-PACKAGE-ERROR: Isolated package not found.")
(return-from read-eval-print nil))
(with-isolated-env
(with-input-from-string (s string)
(flet ((sread (stream)
(translate-form (handler-case (read stream)
(end-of-file ()
(signal 'all-read)))))
(ssetq (name value)
(setf (symbol-value (find-symbol (string-upcase name) *env*))
value))
(muffle (c)
(declare (ignore c))
(when (find-restart 'muffle-warning)
(muffle-warning))))
(let (form values)
(handler-case
(handler-bind ((warning #'muffle))
(loop (setf values (multiple-value-list
(eval (prog1 (setf form (sread s))
(ssetq "-" form)))))))
(all-read ()
(isolated-print values stream))
(undefined-function (c)
(msge stream "~A: The function ~A is undefined."
(type-of c) (cell-error-name c)))
(end-of-file (c)
(msge stream "~A" (type-of c)))
(reader-error ()
(msge stream "READER-ERROR"))
(package-error ()
(msge stream "PACKAGE-ERROR"))
(stream-error (c)
(msge stream "~A" (type-of c)))
(storage-condition ()
(msge stream "STORAGE-CONDITION"))
(t (c)
(msge stream "~A: ~A" (type-of c) c)))
(flet ((svalue (string)
(symbol-value (find-symbol string *env*))))
(ssetq "///" (svalue "//"))
(ssetq "//" (svalue "/"))
(ssetq "/" values)
(ssetq "***" (svalue "**"))
(ssetq "**" (svalue "*"))
(ssetq "*" (first values))
(ssetq "+++" (svalue "++"))
(ssetq "++" (svalue "+"))
(ssetq "+" form))))))
nil)
| null | https://raw.githubusercontent.com/kanru/cl-isolated/05bbc0341b53791e1cff88ad4548bb94d0667cad/isolated.lisp | lisp | Isolated --- A isolated environment for evaluating Common Lisp
expressions
This program is free software: you can redistribute it and/or modify
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
License along with this program. If not, see
</>. |
Copyright ( C ) 2014 , 2020 < >
Copyright ( C ) 2012 - 2013 < >
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation , either version 3 of the
You should have received a copy of the GNU Affero General Public
(defpackage #:isolated
(:use #:cl #:isolated-impl)
(:export #:*env* #:*isolated-homedir-pathname*
#:read-eval-print #:reset))
(in-package #:isolated)
(declaim (optimize (safety 3)))
(defvar *msg-value-prefix* "=> ")
(defvar *msg-error-prefix* ";; ")
(define-condition all-read () ())
(defun msge (stream format-string &rest params)
(apply #'format stream (concatenate 'string "~&" *msg-error-prefix*
format-string "~%")
params))
(defun msgv (stream format-string &rest params)
(apply #'format stream (concatenate 'string "~&" *msg-value-prefix*
format-string "~%")
params))
(defun isolated-print (values &optional (stream *standard-output*))
(if values
(msgv stream "~{~S~^, ~}" values)
(msge stream "No value"))
nil)
(defun reset ()
(ignore-errors
(delete-package *env*))
(make-package *env* :use '(#:isolated-cl))
(loop :for name :in '("+" "++" "+++" "*" "**" "***" "/" "//" "///" "-")
:do (eval `(defparameter ,(intern name *env*) nil)))
(loop :for fn :in '(+ - * /)
:for symbol := (intern (symbol-name fn) *env*)
:do (setf (get symbol :isolated-locked) t)
(eval `(defun ,symbol (&rest args)
(apply ',fn args))))
*env*)
(defun read-eval-print (string &optional (stream *standard-output*))
(unless (or (find-package *env*) (reset))
(msge stream "ISOLATED-PACKAGE-ERROR: Isolated package not found.")
(return-from read-eval-print nil))
(with-isolated-env
(with-input-from-string (s string)
(flet ((sread (stream)
(translate-form (handler-case (read stream)
(end-of-file ()
(signal 'all-read)))))
(ssetq (name value)
(setf (symbol-value (find-symbol (string-upcase name) *env*))
value))
(muffle (c)
(declare (ignore c))
(when (find-restart 'muffle-warning)
(muffle-warning))))
(let (form values)
(handler-case
(handler-bind ((warning #'muffle))
(loop (setf values (multiple-value-list
(eval (prog1 (setf form (sread s))
(ssetq "-" form)))))))
(all-read ()
(isolated-print values stream))
(undefined-function (c)
(msge stream "~A: The function ~A is undefined."
(type-of c) (cell-error-name c)))
(end-of-file (c)
(msge stream "~A" (type-of c)))
(reader-error ()
(msge stream "READER-ERROR"))
(package-error ()
(msge stream "PACKAGE-ERROR"))
(stream-error (c)
(msge stream "~A" (type-of c)))
(storage-condition ()
(msge stream "STORAGE-CONDITION"))
(t (c)
(msge stream "~A: ~A" (type-of c) c)))
(flet ((svalue (string)
(symbol-value (find-symbol string *env*))))
(ssetq "///" (svalue "//"))
(ssetq "//" (svalue "/"))
(ssetq "/" values)
(ssetq "***" (svalue "**"))
(ssetq "**" (svalue "*"))
(ssetq "*" (first values))
(ssetq "+++" (svalue "++"))
(ssetq "++" (svalue "+"))
(ssetq "+" form))))))
nil)
|
28251be28d41204ae27fe7ae9e1cc9c068b24f05ed93245f543da76a96f9b109 | ekmett/category-extras | Supply.hs | --------------------------------------------------------------------
-- |
-- Module : Control.Comonad.Supply
Copyright : ( c ) 2008
( c ) Iavor , 2007
-- License : BSD3
--
Maintainer : < >
-- Stability : provisional
-- Portability: portable
--
-- The technique for generating new values is based on the paper
-- ''On Generating Unique Names''
by , , and .
--
-- Integrated from value-supply-0.1
--
-- TODO: a SupplyT Comonad Transformer
--------------------------------------------------------------------
module Control.Comonad.Supply
( module Control.Comonad
-- * Creating supplies
, Supply
, newSupply
, newEnumSupply
, newNumSupply
-- * Obtaining values from supplies
, supplyValue
-- * Generating new supplies from old
, supplyLeft
, supplyRight
, modifySupply
, split
, split2
, split3
, split4
) where
import Control.Comonad
Using ' MVar 's might be a bit heavy but it ensures that
-- multiple threads that share a supply will get distinct names.
import Control.Concurrent.MVar
import Control.Functor.Extras
import System.IO.Unsafe(unsafePerformIO)
-- Basics ----------------------------------------------------------------------
-- | A type that can be used to generate values on demand.
A supply may be turned into two different supplies by using
-- the functions 'supplyLeft' and 'supplyRight'.
data Supply a = Node
{ -- | Get the value of a supply. This function, together with
-- 'modifySupply' forms a comonad on 'Supply'.
supplyValue :: a
| Generate a new supply . This supply is different from the one
-- generated with 'supplyRight'.
, supplyLeft :: Supply a
| Generate a new supply . This supply is different from the one
-- generated with 'supplyLeft'.
, supplyRight :: Supply a
}
instance Functor Supply where
fmap f s = modifySupply s (f . supplyValue)
-- | Creates a new supply of values.
-- The arguments specify how to generate values:
the first argument is an initial value , the
second specifies how to generate a new value from an existing one .
newSupply :: a -> (a -> a) -> IO (Supply a)
newSupply x f = fmap (gen True) (newMVar (iterate f x))
-- The extra argument to ``gen'' is passed because without
it Hugs spots that the recursive calls are the same but does
not know that unsafePerformIO is unsafe .
where gen _ r = Node { supplyValue = unsafePerformIO (genSym r),
supplyLeft = gen False r,
supplyRight = gen True r }
genSym :: MVar [a] -> IO a
genSym r = do a : as <- takeMVar r
putMVar r as
return a
-- | Generate a new supply by systematically applying a function
-- to an existing supply. This function, together with 'supplyValue'
-- form a comonad on 'Supply'.
modifySupply :: Supply a -> (Supply a -> b) -> Supply b
modifySupply = flip extend
-- (Supply, supplyValue, modifySupply) forms a comonad:
law1 s = [ modifySupply s supplyValue , s ]
law2 s f = [ supplyValue ( modifySupply s f ) , f s ]
law3 s = [ ( s ` modifySupply ` f ) ` modifySupply ` g
, s ` modifySupply ` \s1 - > g ( s1 ` modifySupply ` f )
]
law1 s = [ modifySupply s supplyValue, s ]
law2 s f = [ supplyValue (modifySupply s f), f s ]
law3 s f g = [ (s `modifySupply` f) `modifySupply` g
, s `modifySupply` \s1 -> g (s1 `modifySupply` f)
]
-}
-- Derived functions -----------------------------------------------------------
| A supply of values that are in the ' ' class .
The initial value is @toEnum 0@ , new values are generates with ' succ ' .
newEnumSupply :: (Enum a) => IO (Supply a)
newEnumSupply = newSupply (toEnum 0) succ
| A supply of values that are in the ' ' class .
The initial value is 0 , new values are generated by adding 1 .
newNumSupply :: (Num a) => IO (Supply a)
newNumSupply = newSupply 0 (1+)
-- | Generate an infinite list of supplies by using 'supplyLeft' and
' ' repeatedly .
split :: Supply a -> [Supply a]
split s = supplyLeft s : split (supplyRight s)
| Split a supply into two different supplies .
-- The resulting supplies are different from the input supply.
split2 :: Supply a -> (Supply a, Supply a)
split2 s = (supplyLeft s, supplyRight s)
| Split a supply into three different supplies .
split3 :: Supply a -> (Supply a, Supply a, Supply a)
split3 s = let s1 : s2 : s3 : _ = split s
in (s1,s2,s3)
| Split a supply into four different supplies .
split4 :: Supply a -> (Supply a, Supply a, Supply a, Supply a)
split4 s = let s1 : s2 : s3 : s4 : _ = split s
in (s1,s2,s3,s4)
instance Copointed Supply where
extract = supplyValue
instance Comonad Supply where
extend f s = Node { supplyValue = f s
, supplyLeft = modifySupply (supplyLeft s) f
, supplyRight = modifySupply (supplyRight s) f
}
instance FunctorSplit Supply where
fsplit = split2
| null | https://raw.githubusercontent.com/ekmett/category-extras/f0f3ca38a3dfcb49d39aa2bb5b31b719f2a5b1ae/Control/Comonad/Supply.hs | haskell | ------------------------------------------------------------------
|
Module : Control.Comonad.Supply
License : BSD3
Stability : provisional
Portability: portable
The technique for generating new values is based on the paper
''On Generating Unique Names''
Integrated from value-supply-0.1
TODO: a SupplyT Comonad Transformer
------------------------------------------------------------------
* Creating supplies
* Obtaining values from supplies
* Generating new supplies from old
multiple threads that share a supply will get distinct names.
Basics ----------------------------------------------------------------------
| A type that can be used to generate values on demand.
the functions 'supplyLeft' and 'supplyRight'.
| Get the value of a supply. This function, together with
'modifySupply' forms a comonad on 'Supply'.
generated with 'supplyRight'.
generated with 'supplyLeft'.
| Creates a new supply of values.
The arguments specify how to generate values:
The extra argument to ``gen'' is passed because without
| Generate a new supply by systematically applying a function
to an existing supply. This function, together with 'supplyValue'
form a comonad on 'Supply'.
(Supply, supplyValue, modifySupply) forms a comonad:
Derived functions -----------------------------------------------------------
| Generate an infinite list of supplies by using 'supplyLeft' and
The resulting supplies are different from the input supply. | Copyright : ( c ) 2008
( c ) Iavor , 2007
Maintainer : < >
by , , and .
module Control.Comonad.Supply
( module Control.Comonad
, Supply
, newSupply
, newEnumSupply
, newNumSupply
, supplyValue
, supplyLeft
, supplyRight
, modifySupply
, split
, split2
, split3
, split4
) where
import Control.Comonad
Using ' MVar 's might be a bit heavy but it ensures that
import Control.Concurrent.MVar
import Control.Functor.Extras
import System.IO.Unsafe(unsafePerformIO)
A supply may be turned into two different supplies by using
data Supply a = Node
supplyValue :: a
| Generate a new supply . This supply is different from the one
, supplyLeft :: Supply a
| Generate a new supply . This supply is different from the one
, supplyRight :: Supply a
}
instance Functor Supply where
fmap f s = modifySupply s (f . supplyValue)
the first argument is an initial value , the
second specifies how to generate a new value from an existing one .
newSupply :: a -> (a -> a) -> IO (Supply a)
newSupply x f = fmap (gen True) (newMVar (iterate f x))
it Hugs spots that the recursive calls are the same but does
not know that unsafePerformIO is unsafe .
where gen _ r = Node { supplyValue = unsafePerformIO (genSym r),
supplyLeft = gen False r,
supplyRight = gen True r }
genSym :: MVar [a] -> IO a
genSym r = do a : as <- takeMVar r
putMVar r as
return a
modifySupply :: Supply a -> (Supply a -> b) -> Supply b
modifySupply = flip extend
law1 s = [ modifySupply s supplyValue , s ]
law2 s f = [ supplyValue ( modifySupply s f ) , f s ]
law3 s = [ ( s ` modifySupply ` f ) ` modifySupply ` g
, s ` modifySupply ` \s1 - > g ( s1 ` modifySupply ` f )
]
law1 s = [ modifySupply s supplyValue, s ]
law2 s f = [ supplyValue (modifySupply s f), f s ]
law3 s f g = [ (s `modifySupply` f) `modifySupply` g
, s `modifySupply` \s1 -> g (s1 `modifySupply` f)
]
-}
| A supply of values that are in the ' ' class .
The initial value is @toEnum 0@ , new values are generates with ' succ ' .
newEnumSupply :: (Enum a) => IO (Supply a)
newEnumSupply = newSupply (toEnum 0) succ
| A supply of values that are in the ' ' class .
The initial value is 0 , new values are generated by adding 1 .
newNumSupply :: (Num a) => IO (Supply a)
newNumSupply = newSupply 0 (1+)
' ' repeatedly .
split :: Supply a -> [Supply a]
split s = supplyLeft s : split (supplyRight s)
| Split a supply into two different supplies .
split2 :: Supply a -> (Supply a, Supply a)
split2 s = (supplyLeft s, supplyRight s)
| Split a supply into three different supplies .
split3 :: Supply a -> (Supply a, Supply a, Supply a)
split3 s = let s1 : s2 : s3 : _ = split s
in (s1,s2,s3)
| Split a supply into four different supplies .
split4 :: Supply a -> (Supply a, Supply a, Supply a, Supply a)
split4 s = let s1 : s2 : s3 : s4 : _ = split s
in (s1,s2,s3,s4)
instance Copointed Supply where
extract = supplyValue
instance Comonad Supply where
extend f s = Node { supplyValue = f s
, supplyLeft = modifySupply (supplyLeft s) f
, supplyRight = modifySupply (supplyRight s) f
}
instance FunctorSplit Supply where
fsplit = split2
|
dd95980c4d0b0ee2302758f2caf151e1dc41364bb6a1ecda675ef1b9c3952d05 | droitfintech/fset | bench_test.clj | (ns tech.droit.fset.bench-test
(:require
[clojure.test :refer :all]
[criterium.core :refer [bench quick-bench quick-benchmark benchmark]]
[tech.droit.fset :as fset]
[clojure.set :as cset]))
(defmacro b [expr] `(first (:mean (quick-benchmark ~expr {}))))
(deftest ^:bench rename-keys-bench
(let [m (zipmap (range 100) (range 100))
kmap {4 40 14 140 45 450 51 510 60 600 69 690 90 900}]
(is (= (cset/rename-keys m kmap) (fset/rename-keys m kmap)))
3.006680459548847E-6 cset
1.8890617169285616E-6 fset ( rename - keys )
(is
(nil?
(println
(b (cset/rename-keys m kmap))
(str "cset\n" (b (fset/rename-keys m kmap)) " fset (rename-keys)\n"))))))
(deftest ^:bench maps-bench
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}]
(is (= (into #{} (map inc (set (range 100)))) (fset/maps inc (set (range 100)))))
(is (= (into #{} (map #(assoc % :new 0) xrel)) (fset/maps #(assoc % :new 0) xrel)))
2.720073097731239E-4 core map over set
1.6059608771929826E-4 fset ( maps )
(is
(nil?
(println
(let [s (set (range 1000))]
(str (b (into #{} (map inc s)))
" core map over set \n"
(b (fset/maps inc s))
" fset (maps)\n")))))
; 5.3075209319225114E-6 core into set
3.256621217417093E-6 fset ( maps )
(is
(nil?
(println
(let [f #(assoc % :new 0)]
(b (into #{} (map f xrel)))
(str "core into set\n" (b (fset/maps f xrel)) " fset (maps)\n")))))))
(deftest ^:bench select-keys-test
(let [m (zipmap (range 100) (range 100 200))
ks (range 0 100 10)]
(is (= (select-keys m ks) (fset/select-keys m ks)))
(is (= (select-keys m [10 30 50]) (fset/select-key m 10 30 50)))
2.481968165076176E-6 core
1.0907595441876438E-6 fset ( select - keys )
(is
(nil?
(println
(b (select-keys m ks))
(str " core\n" (b (fset/select-keys m ks)) " fset (select-keys)\n"))))
8.155316297166944E-7 core
4.1558029460823247E-7 fset ( select - key )
(is
(nil?
(println
(b (select-keys m [10 30 50]))
(str "core\n" (b (fset/select-key m 10 30 50)) " fset (select-key)\n"))))))
(deftest ^:bench union-bench
(let [s1 '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}}
s2 '#{{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
s3 '#{{d d3 c c9 a a1 b b2} {d d3 c c3 a a21 b b1}
{d d3 c c11 a a3 b b1}}
s4 '#{{d d3 c c9 a a1 b b2} {d d3 c c3 a a21 b b1}
{d d3 c c11 a a3 b b1} {d d10} {c c14}}
s5 '#{{d d3 c c9 a a1 b b2} {d d3 c c3 a a21 b b1}
{d d3 c c11 a a3 b b1} {d d10} {c c14} {a a21} {a a22}}]
(is (= (cset/union s1 s2) (fset/union s1 s2)))
(is (= (cset/union s1 s2 s3) (fset/union s1 s2 s3)))
(is (= (cset/union s1 s2 s3 s4) (fset/union s1 s2 s3 s4)))
(is (= (cset/union s1 s2 s3 s4 s5) (fset/union s1 s2 s3 s4 s5)))
2.3562738773283106E-6 cset
; 1.1675215159560017E-6 fset (union)
( is ( nil ? ( println ( b ( cset / union s1 s2 ) ) ( str " cset\n " ( b ( fset / union s1 s2 ) ) " fset ( union)\n " ) ) ) )
2.2575491533853774E-6 cset
; 1.65369902375777E-6 fset
( is ( nil ? ( println ( b ( cset / union s1 s2 s3 ) ) ( str " cset\n " ( b ( fset / union s1 s2 s3 ) ) " fset\n " ) ) ) )
( is ( nil ? ( println ( b ( cset / union s1 s2 s3 s4 ) ) ( str " cset\n " ( b ( fset / union s1 s2 s3 s4 ) ) " fset\n " ) ) ) )
( is ( nil ? ( println ( b ( cset / union s1 s2 s3 ) ) ( str " cset\n " ( b ( fset / union s1 s2 s3 ) ) " fset\n " ) ) ) )
( is ( nil ? ( println ( b ( cset / union s1 s2 s3 s4 s5 # { } ) ) ( str " cset\n " ( b ( fset / union s1 s2 s3 s4 s5 # { } ) ) " fset ( union)\n " ) ) ) )
))
(deftest ^:bench index-bench
1.3768563343788355E-5 cset
0.9147070550913031E-5 fset ( index )
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
ks '[b d]]
(is (= (cset/index xrel ks) (fset/index xrel ks)))
(is
(nil?
(println
(b (cset/index xrel ks))
(str "cset\n" (b (fset/index xrel ks)) " fset (index)\n"))))))
(deftest ^:bench kset-bench
(let [rel '#{{d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3}
{d d3 c c3 a a2 b b1}
{d d3 c c1 a a3 b b1}}]
(is (= (set (keys (first rel))) (fset/kset rel)))
; 6.315077613519734E-7 core
3.577445668244377E-7 fset ( kset )
(is
(nil?
(println
(b (set (keys (first rel))))
(str "core\n" (b (fset/kset rel)) " fset (kset)\n"))))
; 6.226934114810922E-7 core
3.4987011405747016E-8 fset ( kset - native )
(is
(nil?
(println
(b (set (keys (first rel))))
(str "core\n" (b (fset/kset-native rel)) " fset (kset-native)\n"))))))
(deftest ^:bench intersection-bench
(let [s1 (set (range 1 40))
s2 (set (range 30 80))
ss1 (apply sorted-set s1)
ss2 (apply sorted-set s2)]
(is (= (cset/intersection s1 s2) (fset/intersection s1 s2)))
(is (= (cset/intersection s1 s2) (fset/intersection* s1 s2)))
(is (= (cset/intersection ss1 ss2) (fset/intersection* ss1 ss2)))
7.1893204992967655E-6 cset
4.322495438183127E-6 intersection ( compatible )
(is
(nil?
(println
(b (cset/intersection s1 s2))
(str "cset\n" (b (fset/intersection s1 s2)) " intersection (compatible)\n"))))
9.937802765155177E-6 sorted cset
7.90225522716554E-6 sorted intersection ( compatible )
#_(is
(nil?
(println
(b (cset/intersection ss1 ss2))
(str "sorted cset\n" (b (fset/intersection ss1 ss2)) " sorted intersection (compatible)\n"))))
6.842457065677723E-6 cset
3.2923806294768446E-6 intersection ( native )
#_(is
(nil?
(println
(b (cset/intersection s1 s2))
(str "cset\n" (b (fset/intersection* s1 s2)) " intersection (native)\n"))))))
(deftest ^:bench difference-bench
(let [s1 (set (range 1 50))
s2 (set (range 30 800))
ss1 (apply sorted-set s1)
ss2 (apply sorted-set s2)]
(is (= (cset/difference s1 s2) (fset/difference s1 s2)))
(is (= (cset/difference ss1 ss2) (fset/difference ss1 ss2)))
; 7.335592370838982E-6 cset
4.132627737969221E-6 difference
(is
(nil?
(println
(b (cset/difference s1 s2))
(str "cset\n" (b (fset/difference s1 s2)) " difference\n"))))
1.4298325121443442E-5 sorted cset
; 1.132363716780562E-5 sorted difference
#_(is
(nil?
(println
(b (cset/difference ss1 ss2))
(str "sorted cset\n" (b (fset/difference ss1 ss2)) " sorted difference\n"))))
5.0338101960004635E-6 cset
; 3.4274965213695293E-6 difference
#_(is
(nil?
(println
(b (cset/difference s2 s1))
(str "cset\n" (b (fset/difference s2 s1)) " difference\n"))))))
(deftest ^:bench select-bench
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
ss (apply sorted-set (range 100))
pred (comp #{'a3} 'a)]
(is (= (cset/select pred xrel) (fset/select pred xrel)))
(is (= (cset/select odd? ss) (fset/select odd? ss)))
1.5927641938447406E-5 sorted cset
1.4375441919551693E-5 sorted select
(is
(nil?
(println
(b (cset/select even? ss))
(str "sorted cset\n" (b (fset/select even? ss)) " sorted select\n"))))
2.44818399082862E-6 cset
; 1.8558549234948711E-6 select
(is
(nil?
(println
(b (cset/select pred xrel))
(str "cset\n" (b (fset/select pred xrel)) " select\n"))))))
(deftest ^:bench project-test
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
ks '[a b c]]
(is (= (cset/project xrel ks) (fset/project xrel ks)))
(is (= (cset/project xrel ks) (fset/project* xrel 'a 'b 'c)))
1.0354762891861535E-5 cset
0.5515608075685698E-5 project
(is
(nil?
(println
(b (cset/project xrel ks))
(str "cset\n" (b (fset/project xrel ks)) " project\n"))))
1.0387998330899229E-5 cset
6.966055805671281E-6 project ( WIP )
(is
(nil?
(println
(b (cset/project xrel ks))
(str "cset\n" (b (fset/project* xrel 'a 'b 'c)) " project\n"))))))
(deftest ^:bench join-bench
2.7759994340847945E-5 cset
0.7999750663668448E-5 fset ( join )
0.7712902516469042E-5 fset ( join with keys )
(let [xrel '#{{d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3}
{d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2}
{d d3 c c2 a a1 b b2}
{d d1 c c2 a a3 b b2}
{d d3 c c3 a a2 b b1}
{d d3 c c1 a a3 b b1}}
yrel '#{{e e1 f f2 g g1 b b1}
{e e3 f f1 g g2 b b8}
{e e1 f f2 g g3 b b8}
{e e3 f f1 g g2 b b3}
{e e2 f f2 g g3 b b8}
{e e1 f f3 g g1 b b8}
{e e2 f f3 g g2 b b8}
{e e1 f f3 g g1 b b2}
{e e3 f f3 g g3 b b8}}
x-keys (fset/kset-native xrel)
y-keys (fset/kset-native yrel)]
(is (= (cset/join xrel yrel) (fset/join xrel yrel)))
(is (= (cset/join xrel yrel) (fset/join xrel yrel x-keys y-keys)))
(is
(nil?
(println
(b (cset/join xrel yrel))
(str "cset\n" (b (fset/join xrel yrel)) " fset (join)\n"))))
(is
(nil?
(println
(b (cset/join xrel yrel))
(str "cset\n" (b (fset/join xrel yrel x-keys y-keys)) " fset (join with keys)\n"))))))
(deftest ^:bench subset-super-test
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
sub (set (take 4 xrel))]
(is (= true (cset/subset? sub xrel) (fset/subset? sub xrel)))
(is (= true (cset/superset? xrel sub) (fset/superset? xrel sub)))
6.955503406380901E-7 cset
1.4824609776142325E-7 subset ?
(is
(nil?
(println
(b (cset/subset? sub xrel))
(str "cset\n" (b (fset/subset? sub xrel)) " subset?\n"))))
; 7.119121416749918E-7 cset
; 1.4956368832914817E-7 subset?
(is
(nil?
(println
(b (cset/superset? xrel sub))
(str "cset\n" (b (fset/superset? xrel sub)) " superset?\n"))))))
| null | https://raw.githubusercontent.com/droitfintech/fset/2031c11dadaaf0283c699ec1d66f27c6f6c93c8d/test/tech/droit/fset/bench_test.clj | clojure | 5.3075209319225114E-6 core into set
1.1675215159560017E-6 fset (union)
1.65369902375777E-6 fset
6.315077613519734E-7 core
6.226934114810922E-7 core
7.335592370838982E-6 cset
1.132363716780562E-5 sorted difference
3.4274965213695293E-6 difference
1.8558549234948711E-6 select
7.119121416749918E-7 cset
1.4956368832914817E-7 subset? | (ns tech.droit.fset.bench-test
(:require
[clojure.test :refer :all]
[criterium.core :refer [bench quick-bench quick-benchmark benchmark]]
[tech.droit.fset :as fset]
[clojure.set :as cset]))
(defmacro b [expr] `(first (:mean (quick-benchmark ~expr {}))))
(deftest ^:bench rename-keys-bench
(let [m (zipmap (range 100) (range 100))
kmap {4 40 14 140 45 450 51 510 60 600 69 690 90 900}]
(is (= (cset/rename-keys m kmap) (fset/rename-keys m kmap)))
3.006680459548847E-6 cset
1.8890617169285616E-6 fset ( rename - keys )
(is
(nil?
(println
(b (cset/rename-keys m kmap))
(str "cset\n" (b (fset/rename-keys m kmap)) " fset (rename-keys)\n"))))))
(deftest ^:bench maps-bench
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}]
(is (= (into #{} (map inc (set (range 100)))) (fset/maps inc (set (range 100)))))
(is (= (into #{} (map #(assoc % :new 0) xrel)) (fset/maps #(assoc % :new 0) xrel)))
2.720073097731239E-4 core map over set
1.6059608771929826E-4 fset ( maps )
(is
(nil?
(println
(let [s (set (range 1000))]
(str (b (into #{} (map inc s)))
" core map over set \n"
(b (fset/maps inc s))
" fset (maps)\n")))))
3.256621217417093E-6 fset ( maps )
(is
(nil?
(println
(let [f #(assoc % :new 0)]
(b (into #{} (map f xrel)))
(str "core into set\n" (b (fset/maps f xrel)) " fset (maps)\n")))))))
(deftest ^:bench select-keys-test
(let [m (zipmap (range 100) (range 100 200))
ks (range 0 100 10)]
(is (= (select-keys m ks) (fset/select-keys m ks)))
(is (= (select-keys m [10 30 50]) (fset/select-key m 10 30 50)))
2.481968165076176E-6 core
1.0907595441876438E-6 fset ( select - keys )
(is
(nil?
(println
(b (select-keys m ks))
(str " core\n" (b (fset/select-keys m ks)) " fset (select-keys)\n"))))
8.155316297166944E-7 core
4.1558029460823247E-7 fset ( select - key )
(is
(nil?
(println
(b (select-keys m [10 30 50]))
(str "core\n" (b (fset/select-key m 10 30 50)) " fset (select-key)\n"))))))
(deftest ^:bench union-bench
(let [s1 '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}}
s2 '#{{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
s3 '#{{d d3 c c9 a a1 b b2} {d d3 c c3 a a21 b b1}
{d d3 c c11 a a3 b b1}}
s4 '#{{d d3 c c9 a a1 b b2} {d d3 c c3 a a21 b b1}
{d d3 c c11 a a3 b b1} {d d10} {c c14}}
s5 '#{{d d3 c c9 a a1 b b2} {d d3 c c3 a a21 b b1}
{d d3 c c11 a a3 b b1} {d d10} {c c14} {a a21} {a a22}}]
(is (= (cset/union s1 s2) (fset/union s1 s2)))
(is (= (cset/union s1 s2 s3) (fset/union s1 s2 s3)))
(is (= (cset/union s1 s2 s3 s4) (fset/union s1 s2 s3 s4)))
(is (= (cset/union s1 s2 s3 s4 s5) (fset/union s1 s2 s3 s4 s5)))
2.3562738773283106E-6 cset
( is ( nil ? ( println ( b ( cset / union s1 s2 ) ) ( str " cset\n " ( b ( fset / union s1 s2 ) ) " fset ( union)\n " ) ) ) )
2.2575491533853774E-6 cset
( is ( nil ? ( println ( b ( cset / union s1 s2 s3 ) ) ( str " cset\n " ( b ( fset / union s1 s2 s3 ) ) " fset\n " ) ) ) )
( is ( nil ? ( println ( b ( cset / union s1 s2 s3 s4 ) ) ( str " cset\n " ( b ( fset / union s1 s2 s3 s4 ) ) " fset\n " ) ) ) )
( is ( nil ? ( println ( b ( cset / union s1 s2 s3 ) ) ( str " cset\n " ( b ( fset / union s1 s2 s3 ) ) " fset\n " ) ) ) )
( is ( nil ? ( println ( b ( cset / union s1 s2 s3 s4 s5 # { } ) ) ( str " cset\n " ( b ( fset / union s1 s2 s3 s4 s5 # { } ) ) " fset ( union)\n " ) ) ) )
))
(deftest ^:bench index-bench
1.3768563343788355E-5 cset
0.9147070550913031E-5 fset ( index )
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
ks '[b d]]
(is (= (cset/index xrel ks) (fset/index xrel ks)))
(is
(nil?
(println
(b (cset/index xrel ks))
(str "cset\n" (b (fset/index xrel ks)) " fset (index)\n"))))))
(deftest ^:bench kset-bench
(let [rel '#{{d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3}
{d d3 c c3 a a2 b b1}
{d d3 c c1 a a3 b b1}}]
(is (= (set (keys (first rel))) (fset/kset rel)))
3.577445668244377E-7 fset ( kset )
(is
(nil?
(println
(b (set (keys (first rel))))
(str "core\n" (b (fset/kset rel)) " fset (kset)\n"))))
3.4987011405747016E-8 fset ( kset - native )
(is
(nil?
(println
(b (set (keys (first rel))))
(str "core\n" (b (fset/kset-native rel)) " fset (kset-native)\n"))))))
(deftest ^:bench intersection-bench
(let [s1 (set (range 1 40))
s2 (set (range 30 80))
ss1 (apply sorted-set s1)
ss2 (apply sorted-set s2)]
(is (= (cset/intersection s1 s2) (fset/intersection s1 s2)))
(is (= (cset/intersection s1 s2) (fset/intersection* s1 s2)))
(is (= (cset/intersection ss1 ss2) (fset/intersection* ss1 ss2)))
7.1893204992967655E-6 cset
4.322495438183127E-6 intersection ( compatible )
(is
(nil?
(println
(b (cset/intersection s1 s2))
(str "cset\n" (b (fset/intersection s1 s2)) " intersection (compatible)\n"))))
9.937802765155177E-6 sorted cset
7.90225522716554E-6 sorted intersection ( compatible )
#_(is
(nil?
(println
(b (cset/intersection ss1 ss2))
(str "sorted cset\n" (b (fset/intersection ss1 ss2)) " sorted intersection (compatible)\n"))))
6.842457065677723E-6 cset
3.2923806294768446E-6 intersection ( native )
#_(is
(nil?
(println
(b (cset/intersection s1 s2))
(str "cset\n" (b (fset/intersection* s1 s2)) " intersection (native)\n"))))))
(deftest ^:bench difference-bench
(let [s1 (set (range 1 50))
s2 (set (range 30 800))
ss1 (apply sorted-set s1)
ss2 (apply sorted-set s2)]
(is (= (cset/difference s1 s2) (fset/difference s1 s2)))
(is (= (cset/difference ss1 ss2) (fset/difference ss1 ss2)))
4.132627737969221E-6 difference
(is
(nil?
(println
(b (cset/difference s1 s2))
(str "cset\n" (b (fset/difference s1 s2)) " difference\n"))))
1.4298325121443442E-5 sorted cset
#_(is
(nil?
(println
(b (cset/difference ss1 ss2))
(str "sorted cset\n" (b (fset/difference ss1 ss2)) " sorted difference\n"))))
5.0338101960004635E-6 cset
#_(is
(nil?
(println
(b (cset/difference s2 s1))
(str "cset\n" (b (fset/difference s2 s1)) " difference\n"))))))
(deftest ^:bench select-bench
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
ss (apply sorted-set (range 100))
pred (comp #{'a3} 'a)]
(is (= (cset/select pred xrel) (fset/select pred xrel)))
(is (= (cset/select odd? ss) (fset/select odd? ss)))
1.5927641938447406E-5 sorted cset
1.4375441919551693E-5 sorted select
(is
(nil?
(println
(b (cset/select even? ss))
(str "sorted cset\n" (b (fset/select even? ss)) " sorted select\n"))))
2.44818399082862E-6 cset
(is
(nil?
(println
(b (cset/select pred xrel))
(str "cset\n" (b (fset/select pred xrel)) " select\n"))))))
(deftest ^:bench project-test
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
ks '[a b c]]
(is (= (cset/project xrel ks) (fset/project xrel ks)))
(is (= (cset/project xrel ks) (fset/project* xrel 'a 'b 'c)))
1.0354762891861535E-5 cset
0.5515608075685698E-5 project
(is
(nil?
(println
(b (cset/project xrel ks))
(str "cset\n" (b (fset/project xrel ks)) " project\n"))))
1.0387998330899229E-5 cset
6.966055805671281E-6 project ( WIP )
(is
(nil?
(println
(b (cset/project xrel ks))
(str "cset\n" (b (fset/project* xrel 'a 'b 'c)) " project\n"))))))
(deftest ^:bench join-bench
2.7759994340847945E-5 cset
0.7999750663668448E-5 fset ( join )
0.7712902516469042E-5 fset ( join with keys )
(let [xrel '#{{d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3}
{d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2}
{d d3 c c2 a a1 b b2}
{d d1 c c2 a a3 b b2}
{d d3 c c3 a a2 b b1}
{d d3 c c1 a a3 b b1}}
yrel '#{{e e1 f f2 g g1 b b1}
{e e3 f f1 g g2 b b8}
{e e1 f f2 g g3 b b8}
{e e3 f f1 g g2 b b3}
{e e2 f f2 g g3 b b8}
{e e1 f f3 g g1 b b8}
{e e2 f f3 g g2 b b8}
{e e1 f f3 g g1 b b2}
{e e3 f f3 g g3 b b8}}
x-keys (fset/kset-native xrel)
y-keys (fset/kset-native yrel)]
(is (= (cset/join xrel yrel) (fset/join xrel yrel)))
(is (= (cset/join xrel yrel) (fset/join xrel yrel x-keys y-keys)))
(is
(nil?
(println
(b (cset/join xrel yrel))
(str "cset\n" (b (fset/join xrel yrel)) " fset (join)\n"))))
(is
(nil?
(println
(b (cset/join xrel yrel))
(str "cset\n" (b (fset/join xrel yrel x-keys y-keys)) " fset (join with keys)\n"))))))
(deftest ^:bench subset-super-test
(let [xrel '#{{d d1 c c2 a a3 b b2} {d d2 c c1 a a3 b b3}
{d d2 c c2 a a2 b b3} {d d2 c c3 a a2 b b3}
{d d3 c c3 a a3 b b2} {d d3 c c2 a a1 b b2}
{d d3 c c3 a a2 b b1} {d d3 c c1 a a3 b b1}}
sub (set (take 4 xrel))]
(is (= true (cset/subset? sub xrel) (fset/subset? sub xrel)))
(is (= true (cset/superset? xrel sub) (fset/superset? xrel sub)))
6.955503406380901E-7 cset
1.4824609776142325E-7 subset ?
(is
(nil?
(println
(b (cset/subset? sub xrel))
(str "cset\n" (b (fset/subset? sub xrel)) " subset?\n"))))
(is
(nil?
(println
(b (cset/superset? xrel sub))
(str "cset\n" (b (fset/superset? xrel sub)) " superset?\n"))))))
|
dd0940030fa8b567a59d6a0125145e0dd7c6dd84d563ee2093b864a8987537e8 | philnguyen/soft-contract | parameters.rkt | #lang racket/base
(require racket/contract)
(define x (make-parameter 42))
(define y (make-parameter "hi"))
(define z (parameterize ([x (+ (x) 1)]
[y (string-length (y))])
(+ (x) 2 (y))))
(provide
(contract-out
[x (-> exact-integer?)]
[y (-> exact-integer?)]
[z exact-integer?]))
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/programs/unsafe/issues/parameters.rkt | racket | #lang racket/base
(require racket/contract)
(define x (make-parameter 42))
(define y (make-parameter "hi"))
(define z (parameterize ([x (+ (x) 1)]
[y (string-length (y))])
(+ (x) 2 (y))))
(provide
(contract-out
[x (-> exact-integer?)]
[y (-> exact-integer?)]
[z exact-integer?]))
|
|
d4a835999385cde2c184cde55c16ed101a5e5036d5397a7056866a763ac0beff | CloudI/CloudI | cloudi_environment.erl | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
%%%
%%%------------------------------------------------------------------------
%%% @doc
%%% ==CloudI Runtime Environment==
%%% @end
%%%
MIT License
%%%
Copyright ( c ) 2014 - 2022 < mjtruog at protonmail dot com >
%%%
%%% 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.
%%%
@author < mjtruog at protonmail dot com >
2014 - 2022
%%% @version 2.0.5 {@date} {@time}
%%%------------------------------------------------------------------------
-module(cloudi_environment).
-author('mjtruog at protonmail dot com').
%% external interface
-export([lookup/0,
status/0,
transform/1,
transform/2]).
-type lookup() :: cloudi_x_trie:cloudi_x_trie().
-export_type([lookup/0]).
-include("cloudi_environment.hrl").
-include("cloudi_logger.hrl").
-include_lib("kernel/include/file.hrl").
%%%------------------------------------------------------------------------
%%% External interface functions
%%%------------------------------------------------------------------------
%%-------------------------------------------------------------------------
%% @doc
%% ===Get an environment variable lookup.===
%% @end
%%-------------------------------------------------------------------------
-spec lookup() ->
lookup().
lookup() ->
cloudi_x_trie:new(lists:map(fun(Entry) ->
cloudi_string:splitl($=, Entry, input)
end, os:getenv())).
%%-------------------------------------------------------------------------
%% @doc
%% ===Get execution environment status.===
%% @end
%%-------------------------------------------------------------------------
-spec status() ->
nonempty_list({atom(), string()}).
status() ->
RuntimeErtsVersion = erlang:system_info(version),
FileErts = filename:join([code:root_dir(), "lib",
"erts-" ++ RuntimeErtsVersion,
"ebin", "erts.app"]),
FileKernel = [_ | _] = code:where_is_file("kernel.app"),
FileStdlib = [_ | _] = code:where_is_file("stdlib.app"),
FileCompiler = [_ | _] = code:where_is_file("compiler.app"),
FileCloudI = [_ | _] = code:where_is_file("cloudi_core.app"),
ApplicationVersions0 = application:loaded_applications(),
{value, {kernel, _, RuntimeErlangKernelVersion},
ApplicationVersions1} = lists:keytake(kernel, 1, ApplicationVersions0),
{value, {stdlib, _, RuntimeErlangStdlibVersion},
ApplicationVersions2} = lists:keytake(stdlib, 1, ApplicationVersions1),
{value, {compiler, _, RuntimeErlangCompilerVersion},
ApplicationVersions3} = lists:keytake(compiler, 1, ApplicationVersions2),
{value, {cloudi_core, _, RuntimeCloudIVersion},
_} = lists:keytake(cloudi_core, 1, ApplicationVersions3),
RuntimeErlangCompilation = erlang_compilation(),
RuntimeMachineProcessors = erlang:system_info(schedulers),
?CODE_STATUS_STATIC ++
[{build_erlang_erts_c_compiler_version, erts_c_compiler_version()},
{install_erlang_erts_time, status_file_time(FileErts)},
{install_erlang_kernel_time, status_file_time(FileKernel)},
{install_erlang_stdlib_time, status_file_time(FileStdlib)},
{install_erlang_compiler_time, status_file_time(FileCompiler)},
{install_cloudi_time, status_file_time(FileCloudI)},
{runtime_erlang_erts_version, RuntimeErtsVersion},
{runtime_erlang_kernel_version, RuntimeErlangKernelVersion},
{runtime_erlang_stdlib_version, RuntimeErlangStdlibVersion},
{runtime_erlang_compiler_version, RuntimeErlangCompilerVersion},
{runtime_erlang_compilation, RuntimeErlangCompilation},
{runtime_cloudi_version, RuntimeCloudIVersion},
{runtime_machine_processors, RuntimeMachineProcessors}].
%%-------------------------------------------------------------------------
%% @doc
= = = Transform a string , substituting environment variable values from the lookup.===
%% Use ${VARIABLE} or $VARIABLE syntax, where VARIABLE is a name with
%% [a-zA-Z0-9_] ASCII characters.
%% @end
%%-------------------------------------------------------------------------
-spec transform(String :: string()) ->
string().
transform(String) ->
transform(String, lookup()).
%%-------------------------------------------------------------------------
%% @doc
= = = Transform a string , substituting environment variable values from the lookup.===
%% Use ${VARIABLE} or $VARIABLE syntax, where VARIABLE is a name with
%% [a-zA-Z0-9_] ASCII characters.
%% @end
%%-------------------------------------------------------------------------
-spec transform(String :: string(),
Lookup :: lookup()) ->
string().
transform(String, Lookup) ->
transform(String, [], Lookup).
%%%------------------------------------------------------------------------
%%% Private functions
%%%------------------------------------------------------------------------
status_file_time(FilePath) ->
case file:read_file_info(FilePath, [raw, {time, posix}]) of
{ok, #file_info{mtime = MTime}} ->
cloudi_timestamp:seconds_epoch_to_string(MTime);
{error, Reason} ->
?LOG_ERROR("filesystem error (~ts): ~tp",
[FilePath, Reason]),
""
end.
erts_c_compiler_version() ->
case erlang:system_info(c_compiler_used) of
{undefined, _} ->
"";
{Name, undefined}
when is_atom(Name) ->
erlang:atom_to_list(Name);
{Name, V}
when is_atom(Name), is_tuple(V) ->
[_ | Version] = lists:flatten([[$., io_lib:format("~p", [I])]
|| I <- erlang:tuple_to_list(V)]),
erlang:atom_to_list(Name) ++ [$ | Version];
{Name, Version} ->
cloudi_string:format("~tp ~tp", [Name, Version]);
Unexpected ->
?LOG_ERROR("erlang:system_info(c_compiler_used) invalid: ~tp",
[Unexpected]),
""
end.
-ifdef(ERLANG_OTP_VERSION_24_FEATURES).
erlang_compilation() ->
case erlang:system_info(emu_flavor) of
jit ->
"jit";
_ ->
"aot"
end.
-else.
erlang_compilation() ->
"aot".
-endif.
% transform a string using a lookup containing environment variables
% (the loop doesn't have error conditions by design)
transform([], Output, _) ->
lists:reverse(Output);
transform([$\\, $$ | String], Output, Lookup) ->
transform(String, [$$ | Output], Lookup);
transform([$$ | String], Output, Lookup) ->
case String of
[${ | Rest] ->
transform_delimiter(Rest, Output, [], Lookup);
_ ->
transform_bare(String, Output, [], Lookup)
end;
transform([C | String], Output, Lookup) ->
transform(String, [C | Output], Lookup).
transform_delimiter([], Output, _, _) ->
lists:reverse(Output);
transform_delimiter([$} | String], Output, Key, Lookup) ->
transform_value(Key, String, Output, Lookup);
transform_delimiter([$= | String], Output, _, Lookup) ->
transform(String, Output, Lookup);
transform_delimiter([C | String], Output, Key, Lookup) ->
transform_delimiter(String, Output, [C | Key], Lookup).
transform_bare([] = String, Output, Key, Lookup) ->
transform_value(Key, String, Output, Lookup);
transform_bare([C | String], Output, _, Lookup)
when C == $}; C == $= ->
transform(String, Output, Lookup);
transform_bare([C | String], Output, Key, Lookup)
when C /= $$, C /= $/, C /= $ , C /= $', C /= $", C /= $` ->
transform_bare(String, Output, [C | Key], Lookup);
transform_bare(String, Output, Key, Lookup) ->
transform_value(Key, String, Output, Lookup).
transform_value([], String, Output, Lookup) ->
transform(String, Output, Lookup);
transform_value(Key, String, Output, Lookup) ->
case cloudi_x_trie:find(lists:reverse(Key), Lookup) of
{ok, Value} ->
transform(String, lists:reverse(Value, Output), Lookup);
error ->
transform(String, Output, Lookup)
end.
| null | https://raw.githubusercontent.com/CloudI/CloudI/1dea07bacc53770290cf9026989caee4b14a9551/src/lib/cloudi_core/src/cloudi_environment.erl | erlang |
------------------------------------------------------------------------
@doc
==CloudI Runtime Environment==
@end
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
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.
@version 2.0.5 {@date} {@time}
------------------------------------------------------------------------
external interface
------------------------------------------------------------------------
External interface functions
------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Get an environment variable lookup.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Get execution environment status.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
Use ${VARIABLE} or $VARIABLE syntax, where VARIABLE is a name with
[a-zA-Z0-9_] ASCII characters.
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
Use ${VARIABLE} or $VARIABLE syntax, where VARIABLE is a name with
[a-zA-Z0-9_] ASCII characters.
@end
-------------------------------------------------------------------------
------------------------------------------------------------------------
Private functions
------------------------------------------------------------------------
transform a string using a lookup containing environment variables
(the loop doesn't have error conditions by design) | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
MIT License
Copyright ( c ) 2014 - 2022 < mjtruog at protonmail dot com >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
@author < mjtruog at protonmail dot com >
2014 - 2022
-module(cloudi_environment).
-author('mjtruog at protonmail dot com').
-export([lookup/0,
status/0,
transform/1,
transform/2]).
-type lookup() :: cloudi_x_trie:cloudi_x_trie().
-export_type([lookup/0]).
-include("cloudi_environment.hrl").
-include("cloudi_logger.hrl").
-include_lib("kernel/include/file.hrl").
-spec lookup() ->
lookup().
lookup() ->
cloudi_x_trie:new(lists:map(fun(Entry) ->
cloudi_string:splitl($=, Entry, input)
end, os:getenv())).
-spec status() ->
nonempty_list({atom(), string()}).
status() ->
RuntimeErtsVersion = erlang:system_info(version),
FileErts = filename:join([code:root_dir(), "lib",
"erts-" ++ RuntimeErtsVersion,
"ebin", "erts.app"]),
FileKernel = [_ | _] = code:where_is_file("kernel.app"),
FileStdlib = [_ | _] = code:where_is_file("stdlib.app"),
FileCompiler = [_ | _] = code:where_is_file("compiler.app"),
FileCloudI = [_ | _] = code:where_is_file("cloudi_core.app"),
ApplicationVersions0 = application:loaded_applications(),
{value, {kernel, _, RuntimeErlangKernelVersion},
ApplicationVersions1} = lists:keytake(kernel, 1, ApplicationVersions0),
{value, {stdlib, _, RuntimeErlangStdlibVersion},
ApplicationVersions2} = lists:keytake(stdlib, 1, ApplicationVersions1),
{value, {compiler, _, RuntimeErlangCompilerVersion},
ApplicationVersions3} = lists:keytake(compiler, 1, ApplicationVersions2),
{value, {cloudi_core, _, RuntimeCloudIVersion},
_} = lists:keytake(cloudi_core, 1, ApplicationVersions3),
RuntimeErlangCompilation = erlang_compilation(),
RuntimeMachineProcessors = erlang:system_info(schedulers),
?CODE_STATUS_STATIC ++
[{build_erlang_erts_c_compiler_version, erts_c_compiler_version()},
{install_erlang_erts_time, status_file_time(FileErts)},
{install_erlang_kernel_time, status_file_time(FileKernel)},
{install_erlang_stdlib_time, status_file_time(FileStdlib)},
{install_erlang_compiler_time, status_file_time(FileCompiler)},
{install_cloudi_time, status_file_time(FileCloudI)},
{runtime_erlang_erts_version, RuntimeErtsVersion},
{runtime_erlang_kernel_version, RuntimeErlangKernelVersion},
{runtime_erlang_stdlib_version, RuntimeErlangStdlibVersion},
{runtime_erlang_compiler_version, RuntimeErlangCompilerVersion},
{runtime_erlang_compilation, RuntimeErlangCompilation},
{runtime_cloudi_version, RuntimeCloudIVersion},
{runtime_machine_processors, RuntimeMachineProcessors}].
= = = Transform a string , substituting environment variable values from the lookup.===
-spec transform(String :: string()) ->
string().
transform(String) ->
transform(String, lookup()).
= = = Transform a string , substituting environment variable values from the lookup.===
-spec transform(String :: string(),
Lookup :: lookup()) ->
string().
transform(String, Lookup) ->
transform(String, [], Lookup).
status_file_time(FilePath) ->
case file:read_file_info(FilePath, [raw, {time, posix}]) of
{ok, #file_info{mtime = MTime}} ->
cloudi_timestamp:seconds_epoch_to_string(MTime);
{error, Reason} ->
?LOG_ERROR("filesystem error (~ts): ~tp",
[FilePath, Reason]),
""
end.
erts_c_compiler_version() ->
case erlang:system_info(c_compiler_used) of
{undefined, _} ->
"";
{Name, undefined}
when is_atom(Name) ->
erlang:atom_to_list(Name);
{Name, V}
when is_atom(Name), is_tuple(V) ->
[_ | Version] = lists:flatten([[$., io_lib:format("~p", [I])]
|| I <- erlang:tuple_to_list(V)]),
erlang:atom_to_list(Name) ++ [$ | Version];
{Name, Version} ->
cloudi_string:format("~tp ~tp", [Name, Version]);
Unexpected ->
?LOG_ERROR("erlang:system_info(c_compiler_used) invalid: ~tp",
[Unexpected]),
""
end.
-ifdef(ERLANG_OTP_VERSION_24_FEATURES).
erlang_compilation() ->
case erlang:system_info(emu_flavor) of
jit ->
"jit";
_ ->
"aot"
end.
-else.
erlang_compilation() ->
"aot".
-endif.
transform([], Output, _) ->
lists:reverse(Output);
transform([$\\, $$ | String], Output, Lookup) ->
transform(String, [$$ | Output], Lookup);
transform([$$ | String], Output, Lookup) ->
case String of
[${ | Rest] ->
transform_delimiter(Rest, Output, [], Lookup);
_ ->
transform_bare(String, Output, [], Lookup)
end;
transform([C | String], Output, Lookup) ->
transform(String, [C | Output], Lookup).
transform_delimiter([], Output, _, _) ->
lists:reverse(Output);
transform_delimiter([$} | String], Output, Key, Lookup) ->
transform_value(Key, String, Output, Lookup);
transform_delimiter([$= | String], Output, _, Lookup) ->
transform(String, Output, Lookup);
transform_delimiter([C | String], Output, Key, Lookup) ->
transform_delimiter(String, Output, [C | Key], Lookup).
transform_bare([] = String, Output, Key, Lookup) ->
transform_value(Key, String, Output, Lookup);
transform_bare([C | String], Output, _, Lookup)
when C == $}; C == $= ->
transform(String, Output, Lookup);
transform_bare([C | String], Output, Key, Lookup)
when C /= $$, C /= $/, C /= $ , C /= $', C /= $", C /= $` ->
transform_bare(String, Output, [C | Key], Lookup);
transform_bare(String, Output, Key, Lookup) ->
transform_value(Key, String, Output, Lookup).
transform_value([], String, Output, Lookup) ->
transform(String, Output, Lookup);
transform_value(Key, String, Output, Lookup) ->
case cloudi_x_trie:find(lists:reverse(Key), Lookup) of
{ok, Value} ->
transform(String, lists:reverse(Value, Output), Lookup);
error ->
transform(String, Output, Lookup)
end.
|
97b0dcbeab7d12c3fae9cc487b1dcb5edb692e668367b24eb4c40e3a09d5d61f | erlyaws/yaws | wiki_split.erl | -module(wiki_split).
%% File : wiki_format_txt.erl
Author : ( )
: , minor modifications
%% Purpose : Wiki formatting engine
%%
%% Split the text. Looking for blocks
%% < is represented as {open,Tag,string()}
%% ...
%% >
%% < is represented as {write_append,Tag,string()}
%% ...
%% >
%%
%% Everything else is represented as {txt, Tag, string()}
%% +type str2wiki(string()) -> wikiText().
%% +type wiki2str(wikiText()) -> string().
%% +type getRegion(tag(), wikiText()) -> string().
%% +type putRegion(tag(), wikiText(), string()) -> wikiText().
%% +type writeAppendRegion(tag(), wikiText(), string()) -> wikiText().
+ deftype wikiText ( ) = { wik , [ { text , tag(),string ( ) } |
%% {open,tag(),string()} |
%% {write_append, tag(), string()}]}
%% +deftype tag() = int().
-export([str2wiki/1, wiki2str/1,
getRegion/2, putRegion/3, writeAppendRegion/3]).
str2wiki(Str) ->
Blocks = str2wiki(Str, []),
{wik, number_blocks(Blocks, 1)}.
number_blocks([{txt,[]}|T], N) -> number_blocks(T, N);
number_blocks([{Tag,Str}|T], N) -> [{Tag,N,Str}|number_blocks(T, N+1)];
number_blocks([], _) -> [].
str2wiki(Str, L) ->
{Before, Stuff} = collect_str(Str),
case Stuff of
"<<\n" ++ T ->
{In, Str3} = collect_write_append([$\n|T], []),
str2wiki(Str3, [{write_append,In},{txt,Before}|L]);
"<\n" ++ T ->
{In, Str3} = collect_open_region([$\n|T], []),
str2wiki(Str3, [{open,In},{txt,Before}|L]);
[] ->
lists:reverse([{txt,Before}|L])
end.
collect_str(Str ) - > { Str1 , Str2 }
%% where Str2 == [], "<" ++ _ | "<<" ++ _
collect_str(Str) -> collect_after_nl(Str, []).
collect_after_nl(S = "<<\n" ++ _, L) -> {lists:reverse(L), S};
collect_after_nl(S = "<\n" ++ _, L) -> {lists:reverse(L), S};
collect_after_nl(X, L) -> collect_str(X, L).
collect_str([$\n|T], L) -> collect_after_nl(T, [$\n|L]);
collect_str([H|T], L) -> collect_str(T, [H|L]);
collect_str([], L) -> {lists:reverse(L), []}.
collect_write_append("\n>>\n" ++ T, L) -> {lists:reverse([$\n|L]), [$\n|T]};
collect_write_append([H|T], L) -> collect_write_append(T, [H|L]);
collect_write_append([], L) -> {lists:reverse(L), []}.
collect_open_region("\n>\n" ++ T, L) -> {lists:reverse([$\n|L]), [$\n|T]};
collect_open_region([H|T], L) -> collect_open_region(T, [H|L]);
collect_open_region([], L) -> {lists:reverse(L), []}.
wiki2str .
wiki2str({wik,L}) -> sneaky_flatten(wiki2str1(L)).
wiki2str1([{txt,_,Str}|T]) -> [Str|wiki2str1(T)];
wiki2str1([{open,_,Str}|T]) -> ["<\n",Str,"\n>"|wiki2str1(T)];
wiki2str1([{write_append,_,Str}|T]) -> ["<<\n",Str,"\n>>"|wiki2str1(T)];
wiki2str1([]) -> [].
sneaky_flatten(L) ->
binary_to_list(list_to_binary(L)).
getRegion(Tag, {wik, L}) -> getRegion1(Tag, L).
getRegion1(Tag, [{Type,Tag,Str}|_]) -> {Type, Str};
getRegion1(Tag, [_|T]) -> getRegion1(Tag, T).
putRegion(Tag, {wik, L}, Str1) -> {wik, putRegion1(Tag, L, Str1)}.
putRegion1(Tag, [{Type,Tag,_}|T], New) -> [{Type,Tag,New}|T];
putRegion1(Tag, [H|T], New) -> [H|putRegion1(Tag, T, New)].
writeAppendRegion(Tag, Wik, Str) ->
Str1 = getRegion(Tag, Wik),
putRegion(Tag, Wik, Str ++ Str1).
| null | https://raw.githubusercontent.com/erlyaws/yaws/da198c828e9d95ca2137da7884cddadd73941d13/applications/wiki/src/wiki_split.erl | erlang | File : wiki_format_txt.erl
Purpose : Wiki formatting engine
Split the text. Looking for blocks
< is represented as {open,Tag,string()}
...
>
< is represented as {write_append,Tag,string()}
...
>
Everything else is represented as {txt, Tag, string()}
+type str2wiki(string()) -> wikiText().
+type wiki2str(wikiText()) -> string().
+type getRegion(tag(), wikiText()) -> string().
+type putRegion(tag(), wikiText(), string()) -> wikiText().
+type writeAppendRegion(tag(), wikiText(), string()) -> wikiText().
{open,tag(),string()} |
{write_append, tag(), string()}]}
+deftype tag() = int().
where Str2 == [], "<" ++ _ | "<<" ++ _ | -module(wiki_split).
Author : ( )
: , minor modifications
+ deftype wikiText ( ) = { wik , [ { text , tag(),string ( ) } |
-export([str2wiki/1, wiki2str/1,
getRegion/2, putRegion/3, writeAppendRegion/3]).
str2wiki(Str) ->
Blocks = str2wiki(Str, []),
{wik, number_blocks(Blocks, 1)}.
number_blocks([{txt,[]}|T], N) -> number_blocks(T, N);
number_blocks([{Tag,Str}|T], N) -> [{Tag,N,Str}|number_blocks(T, N+1)];
number_blocks([], _) -> [].
str2wiki(Str, L) ->
{Before, Stuff} = collect_str(Str),
case Stuff of
"<<\n" ++ T ->
{In, Str3} = collect_write_append([$\n|T], []),
str2wiki(Str3, [{write_append,In},{txt,Before}|L]);
"<\n" ++ T ->
{In, Str3} = collect_open_region([$\n|T], []),
str2wiki(Str3, [{open,In},{txt,Before}|L]);
[] ->
lists:reverse([{txt,Before}|L])
end.
collect_str(Str ) - > { Str1 , Str2 }
collect_str(Str) -> collect_after_nl(Str, []).
collect_after_nl(S = "<<\n" ++ _, L) -> {lists:reverse(L), S};
collect_after_nl(S = "<\n" ++ _, L) -> {lists:reverse(L), S};
collect_after_nl(X, L) -> collect_str(X, L).
collect_str([$\n|T], L) -> collect_after_nl(T, [$\n|L]);
collect_str([H|T], L) -> collect_str(T, [H|L]);
collect_str([], L) -> {lists:reverse(L), []}.
collect_write_append("\n>>\n" ++ T, L) -> {lists:reverse([$\n|L]), [$\n|T]};
collect_write_append([H|T], L) -> collect_write_append(T, [H|L]);
collect_write_append([], L) -> {lists:reverse(L), []}.
collect_open_region("\n>\n" ++ T, L) -> {lists:reverse([$\n|L]), [$\n|T]};
collect_open_region([H|T], L) -> collect_open_region(T, [H|L]);
collect_open_region([], L) -> {lists:reverse(L), []}.
wiki2str .
wiki2str({wik,L}) -> sneaky_flatten(wiki2str1(L)).
wiki2str1([{txt,_,Str}|T]) -> [Str|wiki2str1(T)];
wiki2str1([{open,_,Str}|T]) -> ["<\n",Str,"\n>"|wiki2str1(T)];
wiki2str1([{write_append,_,Str}|T]) -> ["<<\n",Str,"\n>>"|wiki2str1(T)];
wiki2str1([]) -> [].
sneaky_flatten(L) ->
binary_to_list(list_to_binary(L)).
getRegion(Tag, {wik, L}) -> getRegion1(Tag, L).
getRegion1(Tag, [{Type,Tag,Str}|_]) -> {Type, Str};
getRegion1(Tag, [_|T]) -> getRegion1(Tag, T).
putRegion(Tag, {wik, L}, Str1) -> {wik, putRegion1(Tag, L, Str1)}.
putRegion1(Tag, [{Type,Tag,_}|T], New) -> [{Type,Tag,New}|T];
putRegion1(Tag, [H|T], New) -> [H|putRegion1(Tag, T, New)].
writeAppendRegion(Tag, Wik, Str) ->
Str1 = getRegion(Tag, Wik),
putRegion(Tag, Wik, Str ++ Str1).
|
de11498de64566083fe2c138b722e1b80087a2cff379ffdc85ae53543a391351 | coccinelle/coccinelle | popltoctl.mli |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
type cocci_predicate = Lib_engine.predicate * Ast_cocci.meta_name Ast_ctl.modif
type formula =
(cocci_predicate,Ast_cocci.meta_name, Wrapper_ctl.info) Ast_ctl.generic_ctl
val toctl : Ast_popl.sequence -> Asttoctl2.top_formula
| null | https://raw.githubusercontent.com/coccinelle/coccinelle/57cbff0c5768e22bb2d8c20e8dae74294515c6b3/popl/popltoctl.mli | ocaml |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
type cocci_predicate = Lib_engine.predicate * Ast_cocci.meta_name Ast_ctl.modif
type formula =
(cocci_predicate,Ast_cocci.meta_name, Wrapper_ctl.info) Ast_ctl.generic_ctl
val toctl : Ast_popl.sequence -> Asttoctl2.top_formula
|
|
af32ea1b5077730fb4eae23b82580be4667eda5bf2beeed757f368a766841fc7 | Perry961002/SICP | exe4.68.scm | ( x)的反转也是(x )
(rule (reverse (?x) (?x)))
( x .
(rule (reverse (?x . ?y) ?z)
(and (reverse ?y ?reversed-y)
(append-to-form ?reversed-y (?x) ?z))) | null | https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap4/exercise/exe4.68.scm | scheme | ( x)的反转也是(x )
(rule (reverse (?x) (?x)))
( x .
(rule (reverse (?x . ?y) ?z)
(and (reverse ?y ?reversed-y)
(append-to-form ?reversed-y (?x) ?z))) |
|
d932b018bc8ecd7fa7a0eb1e4cee68cd31611ca6c280c005c99b233874d11eab | flambard/cl-erlang-term | erlang-reference.lisp | (in-package :erlang-term)
;;;;
Erlang reference
;;;;
(defconstant +reference-ext+ 101)
(defconstant +new-reference-ext+ 114)
(defclass erlang-reference (erlang-identifier)
()
(:documentation "Erlang ref."))
;;;
;;; Methods
;;;
(defun make-reference (node id creation)
(make-instance 'erlang-reference
:node (make-symbol node)
:id id
:creation creation))
(defmethod print-object ((object erlang-reference) stream)
(print-unreadable-object (object stream :type t)
(with-slots (node id) object
(format stream "~a <~{~a~^.~}>" node
(nreverse (mapcar #'bytes-to-uint32 (four-byte-blocks id)))))))
(defun four-byte-blocks (bytes)
(loop
repeat (/ (length bytes) 4)
for pos from 0 by 4
collect (subseq bytes pos (+ 4 pos))))
;;;
;;; Encode/Decode
;;;
(defmethod encode-erlang-object ((x erlang-reference))
(if (alexandria:length= 4 (slot-value x 'id))
(encode-external-reference x) ;; Perhaps always use new reference?
(encode-external-new-reference x)))
(defmethod decode-erlang-object ((tag (eql +reference-ext+)) bytes pos)
(decode-external-reference bytes pos))
(defmethod decode-erlang-object ((tag (eql +new-reference-ext+)) bytes pos)
(decode-external-new-reference bytes pos))
;; REFERENCE_EXT
;; +-----+------+----+----------+
| 1 | N | 4 | 1 |
;; +-----+------+----+----------+
;; | 101 | Node | ID | Creation |
;; +-----+------+----+----------+
;;
(defun encode-external-reference (ref)
(with-slots (node id creation) ref
(concatenate 'nibbles:simple-octet-vector
(vector +reference-ext+)
(encode-erlang-object node)
id
(vector creation))))
(defun decode-external-reference (bytes &optional (pos 0))
(multiple-value-bind (node pos1) (decode-erlang-atom bytes pos)
(values (make-instance 'erlang-reference
:node node
:id (subseq bytes pos1 (+ pos1 4))
:creation (aref bytes (+ pos1 4)))
(+ pos1 5))))
;; NEW_REFERENCE_EXT
;; +-----+-----+------+----------+--------+
| 1 | 2 | N | 1 | N ' |
;; +-----+-----+------+----------+--------+
;; | 114 | Len | Node | Creation | ID ... |
;; +-----+-----+------+----------+--------+
;;
(defun encode-external-new-reference (ref)
(with-slots (node creation id) ref
(concatenate 'nibbles:simple-octet-vector
(vector +new-reference-ext+)
(uint16-to-bytes (/ (length id) 4))
(encode-erlang-object node)
(vector creation)
Several 4 - byte IDs ..
(defun decode-external-new-reference (bytes &optional (pos 0))
(let ((length (bytes-to-uint16 bytes pos)))
(multiple-value-bind (node pos1) (decode-erlang-atom bytes (+ 2 pos))
(values (make-instance 'erlang-reference
:node node
:creation (aref bytes pos1)
:id (subseq bytes
(1+ pos1)
(+ 1 pos1 (* 4 length))))
(+ 1 pos1 (* 4 length))))))
| null | https://raw.githubusercontent.com/flambard/cl-erlang-term/8e4da084107c2a6a3778856fe554dc37e9bc46bb/src/erlang-reference.lisp | lisp |
Methods
Encode/Decode
Perhaps always use new reference?
REFERENCE_EXT
+-----+------+----+----------+
+-----+------+----+----------+
| 101 | Node | ID | Creation |
+-----+------+----+----------+
NEW_REFERENCE_EXT
+-----+-----+------+----------+--------+
+-----+-----+------+----------+--------+
| 114 | Len | Node | Creation | ID ... |
+-----+-----+------+----------+--------+
| (in-package :erlang-term)
Erlang reference
(defconstant +reference-ext+ 101)
(defconstant +new-reference-ext+ 114)
(defclass erlang-reference (erlang-identifier)
()
(:documentation "Erlang ref."))
(defun make-reference (node id creation)
(make-instance 'erlang-reference
:node (make-symbol node)
:id id
:creation creation))
(defmethod print-object ((object erlang-reference) stream)
(print-unreadable-object (object stream :type t)
(with-slots (node id) object
(format stream "~a <~{~a~^.~}>" node
(nreverse (mapcar #'bytes-to-uint32 (four-byte-blocks id)))))))
(defun four-byte-blocks (bytes)
(loop
repeat (/ (length bytes) 4)
for pos from 0 by 4
collect (subseq bytes pos (+ 4 pos))))
(defmethod encode-erlang-object ((x erlang-reference))
(if (alexandria:length= 4 (slot-value x 'id))
(encode-external-new-reference x)))
(defmethod decode-erlang-object ((tag (eql +reference-ext+)) bytes pos)
(decode-external-reference bytes pos))
(defmethod decode-erlang-object ((tag (eql +new-reference-ext+)) bytes pos)
(decode-external-new-reference bytes pos))
| 1 | N | 4 | 1 |
(defun encode-external-reference (ref)
(with-slots (node id creation) ref
(concatenate 'nibbles:simple-octet-vector
(vector +reference-ext+)
(encode-erlang-object node)
id
(vector creation))))
(defun decode-external-reference (bytes &optional (pos 0))
(multiple-value-bind (node pos1) (decode-erlang-atom bytes pos)
(values (make-instance 'erlang-reference
:node node
:id (subseq bytes pos1 (+ pos1 4))
:creation (aref bytes (+ pos1 4)))
(+ pos1 5))))
| 1 | 2 | N | 1 | N ' |
(defun encode-external-new-reference (ref)
(with-slots (node creation id) ref
(concatenate 'nibbles:simple-octet-vector
(vector +new-reference-ext+)
(uint16-to-bytes (/ (length id) 4))
(encode-erlang-object node)
(vector creation)
Several 4 - byte IDs ..
(defun decode-external-new-reference (bytes &optional (pos 0))
(let ((length (bytes-to-uint16 bytes pos)))
(multiple-value-bind (node pos1) (decode-erlang-atom bytes (+ 2 pos))
(values (make-instance 'erlang-reference
:node node
:creation (aref bytes pos1)
:id (subseq bytes
(1+ pos1)
(+ 1 pos1 (* 4 length))))
(+ 1 pos1 (* 4 length))))))
|
d0974d86db20f431f98caec97cd6a388d0626e3dc6bd726e10417975e235db31 | esl/erl_fuzzy_match | fuzzy_match_SUITE.erl | %%%-------------------------------------------------------------------
Copyright ( C ) 2015 , Erlang Solutions Ltd.
%%%
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
Fuzzy Name Matching Library .
%%% Test suite
%%% @end
Created : 9 Feb 2015 by < erlang-solutions.com >
%%%-------------------------------------------------------------------
%%%-------------------------------------------------------------------
IMPORTANT ! This file is in UTF-8 format !
%%%-------------------------------------------------------------------
-module(fuzzy_match_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
all() -> [unique, exact, abbrev, levenshtein, tokens, alternatives].
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, _Config) ->
ok.
init_per_testcase(alternatives, Config) ->
For this test we want to record the mappings of " new " names to canonicals .
{ok, _} = erl_fuzzy_match:start_link(fuzzy_test, dict:new(), names()),
Config;
init_per_testcase(_TestCase, Config) ->
% For the other tests, we run with a fixed set of canonicals and dictionary.
{ok, _} = erl_fuzzy_match:start_link(fuzzy_test, dict:new(), names(), [fixed]),
Config.
end_per_testcase(_TestCase, _Config) ->
ok = erl_fuzzy_match:stop(fuzzy_test),
ok.
unique(_Config) ->
[<<"A Bilbao">>, <<"Almeria">>, <<"Almería">>, <<"Athletic Bilbao">>,
<<"Athletic Club">>, <<"Atlético">>, <<"Atlético Madrid">>,
<<"Barcelona">>, <<"Celta Vigo">>, <<"Celta de Vigo">>,
<<"Elche">>, <<"Elche CF">>, <<"Espanyol">>, <<"FC Barcelona">>,
<<"Getafe">>, <<"Getafe CF">>, <<"Granada">>,
<<"Granada CF">>, <<"Levante">>, <<"Levante UD">>, <<"Malaga">>,
<<"Málaga">>, <<"Málaga CF">>, <<"Osasuna">>, <<"RCD Espanyol">>,
<<"Rayo Vallecano">>, <<"Real Betis">>, <<"Real Madrid">>,
<<"Real Sociedad">>, <<"Real Valladolid">>, <<"Sevilla">>,
<<"Sevilla FC">>, <<"UD Almería">>, <<"Valencia">>, <<"Valencia CF">>,
<<"Valladolid">>, <<"Villarreal">>, <<"Villarreal CF">>]
= queries().
exact(_Config) ->
{_Matches, Unmatched} = match(
[fun erl_fuzzy_match:exact/2]),
[<<"A Bilbao">>, <<"Almería">>, <<"Athletic Club">>,
<<"Atlético">>, <<"Atlético Madrid">>, <<"Celta de Vigo">>,
<<"Elche CF">>, <<"FC Barcelona">>, <<"Getafe CF">>,
<<"Granada CF">>, <<"Levante UD">>, <<"Málaga">>,
<<"Málaga CF">>, <<"RCD Espanyol">>, <<"Sevilla">>,
<<"UD Almería">>, <<"Valencia CF">>, <<"Valladolid">>,
<<"Villarreal CF">>] = Unmatched.
abbrev(_Config) ->
{_Matches, Unmatched} = match(
[fun erl_fuzzy_match:exact/2, fun erl_fuzzy_match:abbreviation/2]),
[<<"Almería">>, <<"Athletic Club">>,
<<"Atlético">>, <<"Atlético Madrid">>,
<<"FC Barcelona">>, <<"Málaga">>,
<<"Málaga CF">>, <<"RCD Espanyol">>,
<<"UD Almería">>, <<"Valladolid">>] = Unmatched.
levenshtein(_Config) ->
{_Matches, Unmatched} = match(
[fun erl_fuzzy_match:exact/2, fun erl_fuzzy_match:abbreviation/2,
fun erl_fuzzy_match:levenshtein/2]),
[<<"Athletic Club">>, <<"Atlético">>, <<"FC Barcelona">>,
<<"Málaga CF">>, <<"RCD Espanyol">>,
<<"UD Almería">>, <<"Valladolid">>] = Unmatched.
tokens(_Config) ->
{_Matches, Unmatched} = match(
[fun erl_fuzzy_match:exact/2, fun erl_fuzzy_match:abbreviation/2,
fun erl_fuzzy_match:levenshtein/2, fun erl_fuzzy_match:tokens/2]),
[] = Unmatched.
alternatives(_Config) ->
{_, _} = match(
[fun erl_fuzzy_match:exact/2, fun erl_fuzzy_match:abbreviation/2,
fun erl_fuzzy_match:levenshtein/2, fun erl_fuzzy_match:tokens/2]),
Dict = erl_fuzzy_match:dict(fuzzy_test),
Groups = dict:fold(fun
(S, S, Acc) ->
Acc;
(Key, Val, Acc) ->
case orddict:is_key(Val, Acc) of
false -> orddict:store(Val, [Key], Acc);
true -> orddict:append(Val, Key, Acc)
end
end,
orddict:new(),
Dict
),
Alternatives = orddict:fold(
fun (Key, Val, Acc) ->
Sorted = lists:sort(Val),
Acc ++ [{Key, Sorted}]
end,
[],
Groups
),
[
{<<"Almeria">>, [<<"Almería">>, <<"UD Almería">>]},
{<<"Athletic Bilbao">>, [<<"A Bilbao">>, <<"Athletic Club">>]},
{<<"Atletico Madrid">>, [<<"Atlético">>, <<"Atlético Madrid">>]},
{<<"Barcelona">>, [<<"FC Barcelona">>]},
{<<"Celta Vigo">>, [<<"Celta de Vigo">>]},
{<<"Elche">>, [<<"Elche CF">>]},
{<<"Espanyol">>, [<<"RCD Espanyol">>]},
{<<"Getafe">>, [<<"Getafe CF">>]},
{<<"Granada">>, [<<"Granada CF">>]},
{<<"Levante">>, [<<"Levante UD">>]},
{<<"Malaga">>, [<<"Málaga">>, <<"Málaga CF">>]},
{<<"Real Valladolid">>, [<<"Valladolid">>]},
{<<"Sevilla FC">>, [<<"Sevilla">>]},
{<<"Valencia">>, [<<"Valencia CF">>]},
{<<"Villarreal">>, [<<"Villarreal CF">>]}
] = Alternatives.
match(Matchers) ->
{Matches, Unmatched} = lists:foldl(fun (Query, {M, U}) ->
T = erl_fuzzy_match:translate(fuzzy_test, Query, Matchers),
case lists:member(T, names()) of
true -> {ordsets:add_element(Query, M), U};
false -> {M, ordsets:add_element(Query, U)}
end
end, {[], []}, queries()),
summarize(Matches, Unmatched),
{Matches, Unmatched}.
summarize(Matches, Unmatched) ->
ct:log("Matched: ~.2f", [100*length(Matches)/(length(Matches)+length(Unmatched))]),
if Unmatched /= [] ->
ct:log("Unmatched: ~p", [Unmatched]);
true ->
ct:log("No unmatched queries")
end.
names() -> espn_names().
queries() -> ordsets:to_list(ordsets:from_list(bbc_names() ++ soccerway_names() ++ guardian_names() ++ eurosport_names())).
espn_names() -> [
<<"Almeria">>, <<"Athletic Bilbao">>, <<"Atletico Madrid">>,
<<"Barcelona">>, <<"Celta Vigo">>, <<"Elche">>, <<"Espanyol">>,
<<"Getafe">>, <<"Granada">>, <<"Levante">>, <<"Malaga">>,
<<"Osasuna">>, <<"Rayo Vallecano">>, <<"Real Betis">>,
<<"Real Madrid">>, <<"Real Sociedad">>, <<"Real Valladolid">>,
<<"Sevilla FC">>, <<"Valencia">>, <<"Villarreal">>
].
bbc_names() -> [
<<"Almería">>, <<"Athletic Bilbao">>, <<"Atlético Madrid">>,
<<"Barcelona">>, <<"Celta de Vigo">>, <<"Elche">>, <<"Espanyol">>,
<<"Getafe">>, <<"Granada CF">>, <<"Levante">>, <<"Málaga">>,
<<"Osasuna">>, <<"Rayo Vallecano">>, <<"Real Betis">>,
<<"Real Madrid">>, <<"Real Sociedad">>, <<"Real Valladolid">>,
<<"Sevilla">>, <<"Valencia CF">>, <<"Villarreal">>
].
soccerway_names() -> [
<<"Almería">>, <<"Athletic Club">>, <<"Atlético Madrid">>,
<<"Barcelona">>, <<"Celta de Vigo">>, <<"Elche">>, <<"Espanyol">>,
<<"Getafe">>, <<"Granada">>, <<"Levante">>, <<"Málaga">>,
<<"Osasuna">>, <<"Rayo Vallecano">>, <<"Real Betis">>,
<<"Real Madrid">>, <<"Real Sociedad">>, <<"Real Valladolid">>,
<<"Sevilla">>, <<"Valencia">>, <<"Villarreal">>
].
guardian_names() -> [
<<"A Bilbao">>, <<"Almeria">>, <<"Atlético">>,
<<"Barcelona">>, <<"Celta Vigo">>, <<"Elche">>, <<"Espanyol">>,
<<"Getafe">>, <<"Granada">>, <<"Levante">>, <<"Malaga">>,
<<"Osasuna">>, <<"Rayo Vallecano">>, <<"Real Betis">>,
<<"Real Madrid">>, <<"Real Sociedad">>, <<"Sevilla">>,
<<"Valencia">>, <<"Valladolid">>, <<"Villarreal">>
].
eurosport_names() -> [
<<"Athletic Club">>, <<"Atlético Madrid">>, <<"Celta de Vigo">>,
<<"Elche CF">>, <<"FC Barcelona">>, <<"Getafe CF">>, <<"Granada CF">>,
<<"Levante UD">>, <<"Málaga CF">>, <<"Osasuna">>, <<"RCD Espanyol">>,
<<"Rayo Vallecano">>, <<"Real Betis">>, <<"Real Madrid">>,
<<"Real Sociedad">>, <<"Real Valladolid">>, <<"Sevilla FC">>,
<<"UD Almería">>, <<"Valencia CF">>, <<"Villarreal CF">>
].
| null | https://raw.githubusercontent.com/esl/erl_fuzzy_match/c2c9914ba4011ab1f59847e4b248a0a95b4c24d8/test/fuzzy_match_SUITE.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
Test suite
@end
-------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
For the other tests, we run with a fixed set of canonicals and dictionary. | Copyright ( C ) 2015 , Erlang Solutions Ltd.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
Fuzzy Name Matching Library .
Created : 9 Feb 2015 by < erlang-solutions.com >
IMPORTANT ! This file is in UTF-8 format !
-module(fuzzy_match_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
all() -> [unique, exact, abbrev, levenshtein, tokens, alternatives].
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, _Config) ->
ok.
init_per_testcase(alternatives, Config) ->
For this test we want to record the mappings of " new " names to canonicals .
{ok, _} = erl_fuzzy_match:start_link(fuzzy_test, dict:new(), names()),
Config;
init_per_testcase(_TestCase, Config) ->
{ok, _} = erl_fuzzy_match:start_link(fuzzy_test, dict:new(), names(), [fixed]),
Config.
end_per_testcase(_TestCase, _Config) ->
ok = erl_fuzzy_match:stop(fuzzy_test),
ok.
unique(_Config) ->
[<<"A Bilbao">>, <<"Almeria">>, <<"Almería">>, <<"Athletic Bilbao">>,
<<"Athletic Club">>, <<"Atlético">>, <<"Atlético Madrid">>,
<<"Barcelona">>, <<"Celta Vigo">>, <<"Celta de Vigo">>,
<<"Elche">>, <<"Elche CF">>, <<"Espanyol">>, <<"FC Barcelona">>,
<<"Getafe">>, <<"Getafe CF">>, <<"Granada">>,
<<"Granada CF">>, <<"Levante">>, <<"Levante UD">>, <<"Malaga">>,
<<"Málaga">>, <<"Málaga CF">>, <<"Osasuna">>, <<"RCD Espanyol">>,
<<"Rayo Vallecano">>, <<"Real Betis">>, <<"Real Madrid">>,
<<"Real Sociedad">>, <<"Real Valladolid">>, <<"Sevilla">>,
<<"Sevilla FC">>, <<"UD Almería">>, <<"Valencia">>, <<"Valencia CF">>,
<<"Valladolid">>, <<"Villarreal">>, <<"Villarreal CF">>]
= queries().
exact(_Config) ->
{_Matches, Unmatched} = match(
[fun erl_fuzzy_match:exact/2]),
[<<"A Bilbao">>, <<"Almería">>, <<"Athletic Club">>,
<<"Atlético">>, <<"Atlético Madrid">>, <<"Celta de Vigo">>,
<<"Elche CF">>, <<"FC Barcelona">>, <<"Getafe CF">>,
<<"Granada CF">>, <<"Levante UD">>, <<"Málaga">>,
<<"Málaga CF">>, <<"RCD Espanyol">>, <<"Sevilla">>,
<<"UD Almería">>, <<"Valencia CF">>, <<"Valladolid">>,
<<"Villarreal CF">>] = Unmatched.
abbrev(_Config) ->
{_Matches, Unmatched} = match(
[fun erl_fuzzy_match:exact/2, fun erl_fuzzy_match:abbreviation/2]),
[<<"Almería">>, <<"Athletic Club">>,
<<"Atlético">>, <<"Atlético Madrid">>,
<<"FC Barcelona">>, <<"Málaga">>,
<<"Málaga CF">>, <<"RCD Espanyol">>,
<<"UD Almería">>, <<"Valladolid">>] = Unmatched.
levenshtein(_Config) ->
{_Matches, Unmatched} = match(
[fun erl_fuzzy_match:exact/2, fun erl_fuzzy_match:abbreviation/2,
fun erl_fuzzy_match:levenshtein/2]),
[<<"Athletic Club">>, <<"Atlético">>, <<"FC Barcelona">>,
<<"Málaga CF">>, <<"RCD Espanyol">>,
<<"UD Almería">>, <<"Valladolid">>] = Unmatched.
tokens(_Config) ->
{_Matches, Unmatched} = match(
[fun erl_fuzzy_match:exact/2, fun erl_fuzzy_match:abbreviation/2,
fun erl_fuzzy_match:levenshtein/2, fun erl_fuzzy_match:tokens/2]),
[] = Unmatched.
alternatives(_Config) ->
{_, _} = match(
[fun erl_fuzzy_match:exact/2, fun erl_fuzzy_match:abbreviation/2,
fun erl_fuzzy_match:levenshtein/2, fun erl_fuzzy_match:tokens/2]),
Dict = erl_fuzzy_match:dict(fuzzy_test),
Groups = dict:fold(fun
(S, S, Acc) ->
Acc;
(Key, Val, Acc) ->
case orddict:is_key(Val, Acc) of
false -> orddict:store(Val, [Key], Acc);
true -> orddict:append(Val, Key, Acc)
end
end,
orddict:new(),
Dict
),
Alternatives = orddict:fold(
fun (Key, Val, Acc) ->
Sorted = lists:sort(Val),
Acc ++ [{Key, Sorted}]
end,
[],
Groups
),
[
{<<"Almeria">>, [<<"Almería">>, <<"UD Almería">>]},
{<<"Athletic Bilbao">>, [<<"A Bilbao">>, <<"Athletic Club">>]},
{<<"Atletico Madrid">>, [<<"Atlético">>, <<"Atlético Madrid">>]},
{<<"Barcelona">>, [<<"FC Barcelona">>]},
{<<"Celta Vigo">>, [<<"Celta de Vigo">>]},
{<<"Elche">>, [<<"Elche CF">>]},
{<<"Espanyol">>, [<<"RCD Espanyol">>]},
{<<"Getafe">>, [<<"Getafe CF">>]},
{<<"Granada">>, [<<"Granada CF">>]},
{<<"Levante">>, [<<"Levante UD">>]},
{<<"Malaga">>, [<<"Málaga">>, <<"Málaga CF">>]},
{<<"Real Valladolid">>, [<<"Valladolid">>]},
{<<"Sevilla FC">>, [<<"Sevilla">>]},
{<<"Valencia">>, [<<"Valencia CF">>]},
{<<"Villarreal">>, [<<"Villarreal CF">>]}
] = Alternatives.
match(Matchers) ->
{Matches, Unmatched} = lists:foldl(fun (Query, {M, U}) ->
T = erl_fuzzy_match:translate(fuzzy_test, Query, Matchers),
case lists:member(T, names()) of
true -> {ordsets:add_element(Query, M), U};
false -> {M, ordsets:add_element(Query, U)}
end
end, {[], []}, queries()),
summarize(Matches, Unmatched),
{Matches, Unmatched}.
summarize(Matches, Unmatched) ->
ct:log("Matched: ~.2f", [100*length(Matches)/(length(Matches)+length(Unmatched))]),
if Unmatched /= [] ->
ct:log("Unmatched: ~p", [Unmatched]);
true ->
ct:log("No unmatched queries")
end.
names() -> espn_names().
queries() -> ordsets:to_list(ordsets:from_list(bbc_names() ++ soccerway_names() ++ guardian_names() ++ eurosport_names())).
espn_names() -> [
<<"Almeria">>, <<"Athletic Bilbao">>, <<"Atletico Madrid">>,
<<"Barcelona">>, <<"Celta Vigo">>, <<"Elche">>, <<"Espanyol">>,
<<"Getafe">>, <<"Granada">>, <<"Levante">>, <<"Malaga">>,
<<"Osasuna">>, <<"Rayo Vallecano">>, <<"Real Betis">>,
<<"Real Madrid">>, <<"Real Sociedad">>, <<"Real Valladolid">>,
<<"Sevilla FC">>, <<"Valencia">>, <<"Villarreal">>
].
bbc_names() -> [
<<"Almería">>, <<"Athletic Bilbao">>, <<"Atlético Madrid">>,
<<"Barcelona">>, <<"Celta de Vigo">>, <<"Elche">>, <<"Espanyol">>,
<<"Getafe">>, <<"Granada CF">>, <<"Levante">>, <<"Málaga">>,
<<"Osasuna">>, <<"Rayo Vallecano">>, <<"Real Betis">>,
<<"Real Madrid">>, <<"Real Sociedad">>, <<"Real Valladolid">>,
<<"Sevilla">>, <<"Valencia CF">>, <<"Villarreal">>
].
soccerway_names() -> [
<<"Almería">>, <<"Athletic Club">>, <<"Atlético Madrid">>,
<<"Barcelona">>, <<"Celta de Vigo">>, <<"Elche">>, <<"Espanyol">>,
<<"Getafe">>, <<"Granada">>, <<"Levante">>, <<"Málaga">>,
<<"Osasuna">>, <<"Rayo Vallecano">>, <<"Real Betis">>,
<<"Real Madrid">>, <<"Real Sociedad">>, <<"Real Valladolid">>,
<<"Sevilla">>, <<"Valencia">>, <<"Villarreal">>
].
guardian_names() -> [
<<"A Bilbao">>, <<"Almeria">>, <<"Atlético">>,
<<"Barcelona">>, <<"Celta Vigo">>, <<"Elche">>, <<"Espanyol">>,
<<"Getafe">>, <<"Granada">>, <<"Levante">>, <<"Malaga">>,
<<"Osasuna">>, <<"Rayo Vallecano">>, <<"Real Betis">>,
<<"Real Madrid">>, <<"Real Sociedad">>, <<"Sevilla">>,
<<"Valencia">>, <<"Valladolid">>, <<"Villarreal">>
].
eurosport_names() -> [
<<"Athletic Club">>, <<"Atlético Madrid">>, <<"Celta de Vigo">>,
<<"Elche CF">>, <<"FC Barcelona">>, <<"Getafe CF">>, <<"Granada CF">>,
<<"Levante UD">>, <<"Málaga CF">>, <<"Osasuna">>, <<"RCD Espanyol">>,
<<"Rayo Vallecano">>, <<"Real Betis">>, <<"Real Madrid">>,
<<"Real Sociedad">>, <<"Real Valladolid">>, <<"Sevilla FC">>,
<<"UD Almería">>, <<"Valencia CF">>, <<"Villarreal CF">>
].
|
801a5b7b6c877f13272174026f0ecd096628ea80faaa49e4759da9d74f4c2229 | bscarlet/llvm-general | DecodeAST.hs | {-# LANGUAGE
GeneralizedNewtypeDeriving,
MultiParamTypeClasses,
UndecidableInstances
#-}
module LLVM.General.Internal.DecodeAST where
import LLVM.General.Prelude
import Control.Monad.State
import Control.Monad.AnyCont
import Foreign.Ptr
import Foreign.C
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Array (Array)
import qualified Data.Array as Array
import qualified LLVM.General.Internal.FFI.Attribute as FFI
import qualified LLVM.General.Internal.FFI.GlobalValue as FFI
import qualified LLVM.General.Internal.FFI.PtrHierarchy as FFI
import qualified LLVM.General.Internal.FFI.Value as FFI
import qualified LLVM.General.Internal.FFI.Type as FFI
import qualified LLVM.General.AST.Name as A
import qualified LLVM.General.AST.Operand as A (MetadataNodeID(..))
import qualified LLVM.General.AST.Attribute as A.A
import qualified LLVM.General.AST.COMDAT as A.COMDAT
import LLVM.General.Internal.Coding
import LLVM.General.Internal.String ()
type NameMap a = Map (Ptr a) Word
data DecodeState = DecodeState {
globalVarNum :: NameMap FFI.GlobalValue,
localVarNum :: NameMap FFI.Value,
localNameCounter :: Maybe Word,
namedTypeNum :: NameMap FFI.Type,
typesToDefine :: Seq (Ptr FFI.Type),
metadataNodesToDefine :: Seq (A.MetadataNodeID, Ptr FFI.MDNode),
metadataNodes :: Map (Ptr FFI.MDNode) A.MetadataNodeID,
metadataKinds :: Array Word String,
parameterAttributeSets :: Map FFI.ParameterAttributeSet [A.A.ParameterAttribute],
functionAttributeSetIDs :: Map FFI.FunctionAttributeSet A.A.GroupID,
comdats :: Map (Ptr FFI.COMDAT) (String, A.COMDAT.SelectionKind)
}
initialDecode = DecodeState {
globalVarNum = Map.empty,
localVarNum = Map.empty,
localNameCounter = Nothing,
namedTypeNum = Map.empty,
typesToDefine = Seq.empty,
metadataNodesToDefine = Seq.empty,
metadataNodes = Map.empty,
metadataKinds = Array.listArray (1,0) [],
parameterAttributeSets = Map.empty,
functionAttributeSetIDs = Map.empty,
comdats = Map.empty
}
newtype DecodeAST a = DecodeAST { unDecodeAST :: AnyContT (StateT DecodeState IO) a }
deriving (
Applicative,
Functor,
Monad,
MonadIO,
MonadState DecodeState,
MonadAnyCont IO,
ScopeAnyCont
)
runDecodeAST :: DecodeAST a -> IO a
runDecodeAST d = flip evalStateT initialDecode . flip runAnyContT return . unDecodeAST $ d
localScope :: DecodeAST a -> DecodeAST a
localScope (DecodeAST x) = DecodeAST (tweak x)
where tweak x = do
modify (\s@DecodeState { localNameCounter = Nothing } -> s { localNameCounter = Just 0 })
r <- x
modify (\s@DecodeState { localNameCounter = Just _ } -> s { localNameCounter = Nothing })
return r
getName :: (Ptr a -> IO CString)
-> Ptr a
-> (DecodeState -> NameMap a)
-> DecodeAST Word
-> DecodeAST A.Name
getName getCString v getNameMap generate = do
name <- liftIO $ do
n <- getCString v
if n == nullPtr then return "" else decodeM n
if name /= ""
then
return $ A.Name name
else
A.UnName <$> do
nm <- gets getNameMap
maybe generate return $ Map.lookup v nm
getValueName :: FFI.DescendentOf FFI.Value v => Ptr v -> (DecodeState -> NameMap v) -> DecodeAST Word -> DecodeAST A.Name
getValueName = getName (FFI.getValueName . FFI.upCast)
getLocalName :: FFI.DescendentOf FFI.Value v => Ptr v -> DecodeAST A.Name
getLocalName v' = do
let v = FFI.upCast v'
getValueName v localVarNum $ do
nm <- gets localVarNum
Just n <- gets localNameCounter
modify $ \s -> s { localNameCounter = Just (1 + n), localVarNum = Map.insert v n nm }
return n
getGlobalName :: FFI.DescendentOf FFI.GlobalValue v => Ptr v -> DecodeAST A.Name
getGlobalName v' = do
let v = FFI.upCast v'
getValueName v globalVarNum $ do
nm <- gets globalVarNum
let n = fromIntegral $ Map.size nm
modify $ \s -> s { globalVarNum = Map.insert v n nm }
return n
getTypeName :: Ptr FFI.Type -> DecodeAST A.Name
getTypeName t = do
getName FFI.getStructName t namedTypeNum $ do
nm <- gets namedTypeNum
let n = fromIntegral $ Map.size nm
modify $ \s -> s { namedTypeNum = Map.insert t n nm }
return n
saveNamedType :: Ptr FFI.Type -> DecodeAST ()
saveNamedType t = do
modify $ \s -> s { typesToDefine = t Seq.<| typesToDefine s }
getMetadataNodeID :: Ptr FFI.MDNode -> DecodeAST A.MetadataNodeID
getMetadataNodeID p = do
mdns <- gets metadataNodes
case Map.lookup p mdns of
Just r -> return r
Nothing -> do
let r = A.MetadataNodeID (fromIntegral (Map.size mdns))
modify $ \s -> s {
metadataNodesToDefine = (r, p) Seq.<| metadataNodesToDefine s,
metadataNodes = Map.insert p r (metadataNodes s)
}
return r
takeTypeToDefine :: DecodeAST (Maybe (Ptr FFI.Type))
takeTypeToDefine = state $ \s -> case Seq.viewr (typesToDefine s) of
remaining Seq.:> t -> (Just t, s { typesToDefine = remaining })
_ -> (Nothing, s)
takeMetadataNodeToDefine :: DecodeAST (Maybe (A.MetadataNodeID, Ptr FFI.MDNode))
takeMetadataNodeToDefine = state $ \s -> case Seq.viewr (metadataNodesToDefine s) of
remaining Seq.:> md -> (Just md, s { metadataNodesToDefine = remaining })
_ -> (Nothing, s)
instance DecodeM DecodeAST A.Name (Ptr FFI.BasicBlock) where
decodeM = getLocalName
getAttributeGroupID :: FFI.FunctionAttributeSet -> DecodeAST A.A.GroupID
getAttributeGroupID p = do
ids <- gets functionAttributeSetIDs
case Map.lookup p ids of
Just r -> return r
Nothing -> do
let r = A.A.GroupID (fromIntegral (Map.size ids))
modify $ \s -> s { functionAttributeSetIDs = Map.insert p r (functionAttributeSetIDs s) }
return r
| null | https://raw.githubusercontent.com/bscarlet/llvm-general/61fd03639063283e7dc617698265cc883baf0eec/llvm-general/src/LLVM/General/Internal/DecodeAST.hs | haskell | # LANGUAGE
GeneralizedNewtypeDeriving,
MultiParamTypeClasses,
UndecidableInstances
# | module LLVM.General.Internal.DecodeAST where
import LLVM.General.Prelude
import Control.Monad.State
import Control.Monad.AnyCont
import Foreign.Ptr
import Foreign.C
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Array (Array)
import qualified Data.Array as Array
import qualified LLVM.General.Internal.FFI.Attribute as FFI
import qualified LLVM.General.Internal.FFI.GlobalValue as FFI
import qualified LLVM.General.Internal.FFI.PtrHierarchy as FFI
import qualified LLVM.General.Internal.FFI.Value as FFI
import qualified LLVM.General.Internal.FFI.Type as FFI
import qualified LLVM.General.AST.Name as A
import qualified LLVM.General.AST.Operand as A (MetadataNodeID(..))
import qualified LLVM.General.AST.Attribute as A.A
import qualified LLVM.General.AST.COMDAT as A.COMDAT
import LLVM.General.Internal.Coding
import LLVM.General.Internal.String ()
type NameMap a = Map (Ptr a) Word
data DecodeState = DecodeState {
globalVarNum :: NameMap FFI.GlobalValue,
localVarNum :: NameMap FFI.Value,
localNameCounter :: Maybe Word,
namedTypeNum :: NameMap FFI.Type,
typesToDefine :: Seq (Ptr FFI.Type),
metadataNodesToDefine :: Seq (A.MetadataNodeID, Ptr FFI.MDNode),
metadataNodes :: Map (Ptr FFI.MDNode) A.MetadataNodeID,
metadataKinds :: Array Word String,
parameterAttributeSets :: Map FFI.ParameterAttributeSet [A.A.ParameterAttribute],
functionAttributeSetIDs :: Map FFI.FunctionAttributeSet A.A.GroupID,
comdats :: Map (Ptr FFI.COMDAT) (String, A.COMDAT.SelectionKind)
}
initialDecode = DecodeState {
globalVarNum = Map.empty,
localVarNum = Map.empty,
localNameCounter = Nothing,
namedTypeNum = Map.empty,
typesToDefine = Seq.empty,
metadataNodesToDefine = Seq.empty,
metadataNodes = Map.empty,
metadataKinds = Array.listArray (1,0) [],
parameterAttributeSets = Map.empty,
functionAttributeSetIDs = Map.empty,
comdats = Map.empty
}
newtype DecodeAST a = DecodeAST { unDecodeAST :: AnyContT (StateT DecodeState IO) a }
deriving (
Applicative,
Functor,
Monad,
MonadIO,
MonadState DecodeState,
MonadAnyCont IO,
ScopeAnyCont
)
runDecodeAST :: DecodeAST a -> IO a
runDecodeAST d = flip evalStateT initialDecode . flip runAnyContT return . unDecodeAST $ d
localScope :: DecodeAST a -> DecodeAST a
localScope (DecodeAST x) = DecodeAST (tweak x)
where tweak x = do
modify (\s@DecodeState { localNameCounter = Nothing } -> s { localNameCounter = Just 0 })
r <- x
modify (\s@DecodeState { localNameCounter = Just _ } -> s { localNameCounter = Nothing })
return r
getName :: (Ptr a -> IO CString)
-> Ptr a
-> (DecodeState -> NameMap a)
-> DecodeAST Word
-> DecodeAST A.Name
getName getCString v getNameMap generate = do
name <- liftIO $ do
n <- getCString v
if n == nullPtr then return "" else decodeM n
if name /= ""
then
return $ A.Name name
else
A.UnName <$> do
nm <- gets getNameMap
maybe generate return $ Map.lookup v nm
getValueName :: FFI.DescendentOf FFI.Value v => Ptr v -> (DecodeState -> NameMap v) -> DecodeAST Word -> DecodeAST A.Name
getValueName = getName (FFI.getValueName . FFI.upCast)
getLocalName :: FFI.DescendentOf FFI.Value v => Ptr v -> DecodeAST A.Name
getLocalName v' = do
let v = FFI.upCast v'
getValueName v localVarNum $ do
nm <- gets localVarNum
Just n <- gets localNameCounter
modify $ \s -> s { localNameCounter = Just (1 + n), localVarNum = Map.insert v n nm }
return n
getGlobalName :: FFI.DescendentOf FFI.GlobalValue v => Ptr v -> DecodeAST A.Name
getGlobalName v' = do
let v = FFI.upCast v'
getValueName v globalVarNum $ do
nm <- gets globalVarNum
let n = fromIntegral $ Map.size nm
modify $ \s -> s { globalVarNum = Map.insert v n nm }
return n
getTypeName :: Ptr FFI.Type -> DecodeAST A.Name
getTypeName t = do
getName FFI.getStructName t namedTypeNum $ do
nm <- gets namedTypeNum
let n = fromIntegral $ Map.size nm
modify $ \s -> s { namedTypeNum = Map.insert t n nm }
return n
saveNamedType :: Ptr FFI.Type -> DecodeAST ()
saveNamedType t = do
modify $ \s -> s { typesToDefine = t Seq.<| typesToDefine s }
getMetadataNodeID :: Ptr FFI.MDNode -> DecodeAST A.MetadataNodeID
getMetadataNodeID p = do
mdns <- gets metadataNodes
case Map.lookup p mdns of
Just r -> return r
Nothing -> do
let r = A.MetadataNodeID (fromIntegral (Map.size mdns))
modify $ \s -> s {
metadataNodesToDefine = (r, p) Seq.<| metadataNodesToDefine s,
metadataNodes = Map.insert p r (metadataNodes s)
}
return r
takeTypeToDefine :: DecodeAST (Maybe (Ptr FFI.Type))
takeTypeToDefine = state $ \s -> case Seq.viewr (typesToDefine s) of
remaining Seq.:> t -> (Just t, s { typesToDefine = remaining })
_ -> (Nothing, s)
takeMetadataNodeToDefine :: DecodeAST (Maybe (A.MetadataNodeID, Ptr FFI.MDNode))
takeMetadataNodeToDefine = state $ \s -> case Seq.viewr (metadataNodesToDefine s) of
remaining Seq.:> md -> (Just md, s { metadataNodesToDefine = remaining })
_ -> (Nothing, s)
instance DecodeM DecodeAST A.Name (Ptr FFI.BasicBlock) where
decodeM = getLocalName
getAttributeGroupID :: FFI.FunctionAttributeSet -> DecodeAST A.A.GroupID
getAttributeGroupID p = do
ids <- gets functionAttributeSetIDs
case Map.lookup p ids of
Just r -> return r
Nothing -> do
let r = A.A.GroupID (fromIntegral (Map.size ids))
modify $ \s -> s { functionAttributeSetIDs = Map.insert p r (functionAttributeSetIDs s) }
return r
|
ba2d97b99279bd191d1c71a9551a5b71b666f978eaff8df3a0e1c369040f5516 | nuprl/gradual-typing-performance | constants.rkt |
(module constants racket
(require racket/class
racket/draw
)
(provide ANIMATION-STEPS
ANIMATION-TIME
PRETTY-CARD-SEP-AMOUNT
white-brush
hilite-brush
black-pen
dark-gray-pen
no-pen
black-color
nice-font)
(define ANIMATION-STEPS 5)
(define ANIMATION-TIME 0.3)
(define PRETTY-CARD-SEP-AMOUNT 5)
(define black-color
(make-object color% "black"))
(define white-brush
(send the-brush-list
find-or-create-brush
"white" 'solid))
(define hilite-brush
(send the-brush-list
find-or-create-brush
black-color 'hilite))
(define black-pen
(send the-pen-list
find-or-create-pen
black-color 1 'solid))
(define dark-gray-pen
(send the-pen-list
find-or-create-pen
"dark gray" 1 'solid))
(define no-pen
(send the-pen-list
find-or-create-pen
black-color 1 'transparent))
(define nice-font
(send the-font-list
find-or-create-font
12 'decorative 'normal 'bold
#f 'default #t)))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/gofish/base/cards/constants.rkt | racket |
(module constants racket
(require racket/class
racket/draw
)
(provide ANIMATION-STEPS
ANIMATION-TIME
PRETTY-CARD-SEP-AMOUNT
white-brush
hilite-brush
black-pen
dark-gray-pen
no-pen
black-color
nice-font)
(define ANIMATION-STEPS 5)
(define ANIMATION-TIME 0.3)
(define PRETTY-CARD-SEP-AMOUNT 5)
(define black-color
(make-object color% "black"))
(define white-brush
(send the-brush-list
find-or-create-brush
"white" 'solid))
(define hilite-brush
(send the-brush-list
find-or-create-brush
black-color 'hilite))
(define black-pen
(send the-pen-list
find-or-create-pen
black-color 1 'solid))
(define dark-gray-pen
(send the-pen-list
find-or-create-pen
"dark gray" 1 'solid))
(define no-pen
(send the-pen-list
find-or-create-pen
black-color 1 'transparent))
(define nice-font
(send the-font-list
find-or-create-font
12 'decorative 'normal 'bold
#f 'default #t)))
|
|
a88592c96d8a062c6661513b428b6d993a77ef32b48b55d921eac3e5e29a2953 | thepower/tpnode | tx.erl | -module(tx).
-include("include/tplog.hrl").
-export([del_ext/2, get_ext/2, set_ext/3]).
-export([sign/2, verify/1, verify/2, pack/1, pack/2, unpack/1, unpack/2]).
-export([txlist_hash/1, rate/2, mergesig/2]).
-export([encode_purpose/1, decode_purpose/1, encode_kind/2, decode_kind/1]).
-export([construct_tx/1,construct_tx/2, get_payload/2, get_payloads/2]).
-export([unpack_naked/1]).
-export([complete_tx/2]).
-export([hashdiff/1,upgrade/1]).
-include("apps/tpnode/include/tx_const.hrl").
mergesig(#{sig:=S1}=Tx1, #{sig:=S2}) when is_map(S1), is_map(S2)->
Tx1#{sig=>
maps:merge(S1, S2)
};
mergesig(#{sig:=S1}=Tx1, #{sig:=S2}) when is_list(S1), is_list(S2)->
F=lists:foldl(
fun(P,A) ->
S=bsig:extract_pubkey(bsig:unpacksig(P)),
maps:put(S,P,A)
end,
#{},
S1++S2),
Tx1#{sig=> maps:values(F)};
mergesig(Tx1, Tx2) ->
file:write_file("tmp/merge1.txt", io_lib:format("~p.~n~p.~n", [Tx1,Tx2])),
Tx1.
checkaddr(<<Ia:64/big>>) -> {true, Ia};
checkaddr(_) -> false.
get_ext(K, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
case maps:is_key(K, Ed) of
true ->
{ok, maps:get(K, Ed)};
false ->
undefined
end.
set_ext(<<"fee">>, V, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:put(fee, V, Ed)
};
set_ext(<<"feecur">>, V, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:put(feecur, V, Ed)
};
set_ext(K, V, Tx) when is_atom(K) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:put(atom_to_binary(K, utf8), V, Ed)
};
set_ext(K, V, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:put(K, V, Ed)
}.
del_ext(K, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:remove(K, Ed)
}.
-spec to_list(Arg :: binary() | list()) -> list().
to_list(Arg) when is_list(Arg) ->
Arg;
to_list(Arg) when is_binary(Arg) ->
binary_to_list(Arg).
-spec to_binary(Arg :: binary() | list()) -> binary().
to_binary(Arg) when is_binary(Arg) ->
Arg;
to_binary(Arg) when is_list(Arg) ->
list_to_binary(Arg).
pack_body(Body) ->
msgpack:pack(Body,[{spec,new},{pack_str, from_list}]).
construct_tx(Any) ->
construct_tx(Any,[]).
construct_tx(#{
ver:=2,
kind:=patch,
patches:=Patches
}=Tx0,_Params) ->
Tx=maps:with([ver,txext,patches],Tx0),
E0=#{
"k"=>encode_kind(2,patch),
"e"=>maps:get(txext, Tx, #{}),
"p"=>Patches
},
Tx#{
patches=>settings:dmp(settings:mp(Patches)),
kind=>patch,
body=>pack_body(E0),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=register,
t:=Timestamp,
keys:=PubKeys
}=Tx0,Params) ->
Tx=maps:with([ver,t,txext],Tx0),
Keys1=iolist_to_binary(
lists:sort(
[ begin {_KeyType,RawPubKey} = tpecdsa:cmp_pubkey(PK), RawPubKey end || PK <- PubKeys ]
)
),
%Keys1=iolist_to_binary(lists:sort(PubKeys)),
KeysH=crypto:hash(sha256,Keys1),
E0=#{
"k"=>encode_kind(2,register),
"t"=>Timestamp,
"e"=>maps:get(txext, Tx, #{}),
"h"=>KeysH
},
InvBody=case Tx0 of
#{inv:=Invite} ->
E0#{"inv"=>crypto:hash(sha256,Invite)};
_ ->
E0
end,
PowBody=case proplists:get_value(pow_diff,Params) of
undefined -> InvBody;
I when is_integer(I) ->
mine_sha512(InvBody, 0, I)
end,
case Tx0 of
#{inv:=Invite1} ->
maps:remove(keys,
Tx0#{
inv=>Invite1,
kind=>register,
body=>pack_body(PowBody),
keysh=>KeysH,
sig=>[]
});
_ ->
maps:remove(keys,
Tx0#{
kind=>register,
body=>pack_body(PowBody),
keysh=>KeysH,
sig=>[]
})
end;
construct_tx(#{
ver:=2,
kind:=tstore,
from:=F,
t:=Timestamp,
seq:=Seq,
payload:=Amounts
}=Tx0,_Params) ->
Tx=maps:with([ver,from,t,seq,payload,txext],Tx0),
A1=lists:map(
fun(#{amount:=Amount, cur:=Cur, purpose:=Purpose}) when
is_integer(Amount), is_binary(Cur) ->
[encode_purpose(Purpose), to_list(Cur), Amount]
end, Amounts),
Ext=maps:get(txext, Tx, #{}),
true=is_map(Ext),
E0=#{
"k"=>encode_kind(2,tstore),
"f"=>F,
"t"=>Timestamp,
"s"=>Seq,
"p"=>{array,A1},
"e"=>Ext
},
Tx#{
kind=>tstore,
body=>msgpack:pack(E0,[{spec,new},{pack_str, from_list}]),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=lstore,
from:=F,
t:=Timestamp,
seq:=Seq,
payload:=Amounts,
patches:=Patches
}=Tx0,_Params) ->
Tx=maps:with([ver,from,t,seq,payload,patches,txext],Tx0),
A1=lists:map(
fun(#{amount:=Amount, cur:=Cur, purpose:=Purpose}) when
is_integer(Amount), is_binary(Cur) ->
[encode_purpose(Purpose), to_list(Cur), Amount]
end, Amounts),
Ext=maps:get(txext, Tx, #{}),
true=is_map(Ext),
EP=settings:mp(Patches),
E0=#{
"k"=>encode_kind(2,lstore),
"f"=>F,
"t"=>Timestamp,
"s"=>Seq,
"p"=>{array,A1},
"pa"=>EP,
"e"=>Ext
},
Tx#{
kind=>lstore,
body=>pack_body(E0),
patches=>settings:dmp(EP),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=Kind,
from:=F,
t:=Timestamp,
seq:=Seq,
payload:=Amounts
}=Tx0,_Params) when Kind==deploy; Kind==notify ->
Tx=maps:with([ver,from,to,t,seq,payload,call,txext,notify,not_before],Tx0),
A1=lists:map(
fun(#{amount:=Amount, cur:=Cur, purpose:=Purpose}) when
is_integer(Amount), is_binary(Cur) ->
[encode_purpose(Purpose), to_list(Cur), Amount]
end, Amounts),
Ext=maps:get(txext, Tx, #{}),
true=is_map(Ext),
E0=#{
"k"=>encode_kind(2,Kind),
"f"=>F,
"t"=>Timestamp,
"s"=>Seq,
"p"=>{array,A1},
"e"=>Ext
},
{E1,Tx1}=maps:fold(fun prepare_extra_args/3, {E0, Tx}, Tx),
Tx1#{
kind=>Kind,
body=>msgpack:pack(E1,[{spec,new},{pack_str, from_list}]),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=chkey,
from:=F,
t:=Timestamp,
seq:=Seq,
keys:=[_|_]=PubKeys
}=Tx0,_Params) ->
Tx=maps:with([ver,from,t,seq,keys],Tx0),
E0=#{
"k"=>encode_kind(2,chkey),
"f"=>F,
"t"=>Timestamp,
"s"=>Seq,
"y"=>{array,PubKeys}
},
Tx#{
kind=>chkey,
body=>msgpack:pack(E0,[{spec,new},{pack_str, from_list}]),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=generic,
from:=F,
to:=To,
t:=Timestamp,
seq:=Seq,
payload:=Amounts
}=Tx0,_Params) ->
Tx=maps:with([ver,from,to,t,seq,payload,call,txext,not_before,notify],Tx0),
A1=lists:map(
fun(#{amount:=Amount, cur:=Cur, purpose:=Purpose}) when
is_integer(Amount), is_binary(Cur) ->
[encode_purpose(Purpose), to_list(Cur), Amount]
end, Amounts),
Ext=maps:get(txext, Tx, #{}),
true=is_map(Ext),
E0=#{
"k"=>encode_kind(2,generic),
"f"=>F,
"to"=>To,
"t"=>Timestamp,
"s"=>Seq,
"p"=>{array,A1},
"e"=>Ext
},
{E1,Tx1}=maps:fold(fun prepare_extra_args/3, {E0, Tx}, Tx),
Tx1#{
kind=>generic,
body=>msgpack:pack(E1,[{spec,new},{pack_str, from_list}]),
sig=>[]
}.
prepare_extra_args(call, #{function:=Fun,args:=Args}, {CE,CTx}) when
is_list(Fun), is_list(Args) ->
{CE#{"c"=>[Fun,{array,Args}]},CTx};
prepare_extra_args(call, _, {CE,CTx}) ->
{CE, maps:remove(call, CTx)};
prepare_extra_args(notify, CVal, {CE,CTx}) when is_list(CVal) ->
Ntf=lists:map(
fun({URL,Payload}) when
is_binary(Payload) andalso
(is_list(URL) orelse is_integer(URL)) ->
[URL,Payload];
(Map) when is_map(Map) ->
Map
end, CVal),
{CE#{"ev"=>Ntf},CTx};
prepare_extra_args(notify, _CVal, {CE,CTx}) ->
{CE, maps:remove(notify, CTx)};
prepare_extra_args(not_before, Int, {CE,CTx}) when is_integer(Int),
Int > 1600000000,
Int < 3000000000 ->
{CE#{"nb"=>Int},CTx};
prepare_extra_args(not_before, _Int, {CE,CTx}) ->
{CE, maps:remove(not_before, CTx)};
prepare_extra_args(_, _, {CE,CTx}) ->
{CE,CTx}.
unpack_body(#{sig:=<<>>}=Tx) ->
unpack_body(Tx#{sig:=[]});
unpack_body(#{body:=Body}=Tx) ->
case msgpack:unpack(Body,[{spec,new},{unpack_str, as_list}]) of
{ok,#{"k":=IKind}=B} ->
{Ver, Kind}=decode_kind(IKind),
unpack_body(Tx#{ver=>Ver, kind=>Kind},B);
{ok, #{<<"hash">>:=_,
<<"header">>:=_,
<<"sign">>:=_}} ->
block:unpack(Body);
{error,{invalid_string,_}} ->
case msgpack:unpack(Body,[{spec,new},{unpack_str, as_binary}]) of
{ok,#{<<"k">>:=IKind}=B0} ->
{Ver, Kind}=decode_kind(IKind),
B=maps:fold(
fun(K,V,Acc) ->
maps:put(unicode:characters_to_list(K),V,Acc)
end, #{}, B0),
unpack_body(Tx#{ver=>Ver, kind=>Kind},B)
end
end.
unpack_addr(<<_:64/big>>=From,_) -> From;
unpack_addr([_,_,_,_,_,_,_,_]=From,_) -> list_to_binary(From);
unpack_addr(_,T) -> throw(T).
unpack_timestamp(Time) when is_integer(Time) -> Time;
unpack_timestamp(_Time) -> throw(bad_timestamp).
unpack_seq(Int) when is_integer(Int) -> Int;
unpack_seq(_Int) -> throw(bad_seq).
%TODO: remove this temporary fix
unpack_txext(<<>>) -> #{};
unpack_txext(Map) when is_map(Map) -> Map;
unpack_txext(_Any) -> throw(bad_ext).
unpack_payload(Amounts) when is_list(Amounts) ->
lists:map(
fun([Purpose, Cur, Amount]) ->
if is_integer(Amount) -> ok;
true -> throw('bad_amount')
end,
#{amount=>Amount,
cur=>to_binary(Cur),
purpose=>decode_purpose(Purpose)
}
end, Amounts).
unpack_call_ntf_etc("c",[Function, Args],Decoded) ->
Decoded#{
call=>#{function=>Function, args=>Args}
};
unpack_call_ntf_etc("nb",Int,Decoded) when is_integer(Int),
Int > 1600000000,
Int < 3000000000 ->
Decoded#{
not_before => Int
};
unpack_call_ntf_etc("ev",Events,Decoded) when is_list(Events) ->
Decoded#{
notify => lists:map(
fun([URL,Body]) when is_binary(Body),
is_list(URL) ->
{URL, Body};
(Map) when is_map(Map) ->
Map
end, Events)
};
unpack_call_ntf_etc(_,_,Decoded) ->
Decoded.
unpack_body(#{ ver:=2,
kind:=GenericOrDeploy
}=Tx,
#{ "f":=From,
"to":=To,
"t":=Timestamp,
"s":=Seq,
"p":=Payload
}=Unpacked) when GenericOrDeploy == generic ;
GenericOrDeploy == deploy ->
Amounts=unpack_payload(Payload),
Decoded=Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
to=>unpack_addr(To,bad_to),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
},
maps:fold(fun unpack_call_ntf_etc/3, Decoded, Unpacked);
% case maps:is_key("c",Unpacked) of
% false -> Decoded;
% true ->
[ Function , Args]=maps : ) ,
% Decoded#{
% call=>#{function=>Function, args=>Args}
% }
% end;
unpack_body(#{ ver:=2,
kind:=deploy
}=Tx,
#{ "f":=From,
"t":=Timestamp,
"s":=Seq,
"p":=Payload
}=Unpacked) ->
Amounts=unpack_payload(Payload),
Decoded=Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
},
case maps:is_key("c",Unpacked) of
false -> Decoded;
true ->
[Function, Args]=maps:get("c",Unpacked),
Decoded#{
call=>#{function=>Function, args=>Args}
}
end;
unpack_body(#{ ver:=2,
kind:=notify
}=Tx,
#{ "f":=From,
"t":=Timestamp,
"s":=Seq,
"p":=Payload
}=Unpacked) ->
Amounts=unpack_payload(Payload),
Decoded=Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
},
maps:fold(fun unpack_call_ntf_etc/3, Decoded, Unpacked);
unpack_body(#{ ver:=2,
kind:=tstore
}=Tx,
#{ "f":=From,
"t":=Timestamp,
"s":=Seq,
"p":=Payload
}=Unpacked) ->
Amounts=unpack_payload(Payload),
Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
};
unpack_body(#{ ver:=2,
kind:=lstore
}=Tx,
#{ "f":=From,
"t":=Timestamp,
"s":=Seq,
"pa":=Patches,
"p":=Payload
}=Unpacked) ->
Amounts=unpack_payload(Payload),
Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
patches=>settings:dmp(Patches),
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
};
unpack_body(#{ ver:=2,
kind:=register
}=Tx,
#{ "t":=Timestamp,
"h":=Hash
}=Unpacked) ->
Tx#{
ver=>2,
t=>unpack_timestamp(Timestamp),
keysh=>Hash,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
};
unpack_body(#{ ver:=2,
kind:=chkey
}=Tx,
#{ "t":=Timestamp,
"f":=From,
"s":=Seq,
"y":=PubKeys
}) ->
Tx#{
ver=>2,
t=>unpack_timestamp(Timestamp),
seq=>Seq,
from=>From,
keys=>PubKeys
};
unpack_body(#{ ver:=2,
kind:=patch
}=Tx,
#{ "p":=Patches
}=Unpacked) ->
Tx#{
ver=>2,
patches=>Patches,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
};
unpack_body(#{ver:=Ver, kind:=Kind},_Unpacked) ->
throw({unknown_ver_or_kind,{Ver,Kind},_Unpacked}).
sign(#{kind:=_Kind,
body:=Body,
sig:=PS}=Tx, PrivKey) ->
Sig=bsig:signhash(Body,[],PrivKey),
Tx#{sig=>[Sig|PS]};
sign(#{patch:=Patch}, PrivKey) ->
tx:sign(tx:construct_tx(#{patches=>Patch, kind=>patch, ver=>2}), PrivKey);
sign(Any, _PrivKey) ->
throw({not_a_tx,Any}).
tx1 : sign(Any , PrivKey ) .
-type tx() :: tx2() | tx1().
-type tx2() :: #{
ver:=non_neg_integer(),
kind:=atom(),
body:=binary(),
sig=>list(),
sigverify=>#{valid:=integer(),
invalid:=integer()
}
}.
-type tx1() :: #{ 'patch':=binary(), 'sig':=list() }
| #{ 'type':='register', 'pow':=binary(),
'register':=binary(), 'timestamp':=integer() }
| #{ from := binary(), sig := map(), timestamp := integer() }.
-spec verify(tx()|binary()) ->
{ok, tx()} | 'bad_sig'.
verify(Tx) ->
verify(Tx, []).
-spec verify(tx()|binary(), ['nocheck_ledger'| {ledger, pid()}]) ->
{ok, tx()} | 'bad_sig'.
verify(#{
kind:=GenericOrDeploy,
from:=From,
body:=Body,
sig:=LSigs,
ver:=2
}=Tx, Opts) when GenericOrDeploy==generic;
GenericOrDeploy==deploy;
GenericOrDeploy==chkey;
GenericOrDeploy==tstore;
GenericOrDeploy==notify;
GenericOrDeploy==lstore ->
CI=get_ext(<<"contract_issued">>, Tx),
Res=case checkaddr(From) of
{true, _IAddr} when CI=={ok, From} ->
%contract issued. Check nodes key.
try
bsig:checksig(Body, LSigs,
fun(PubKey,_) ->
chainsettings:is_our_node(PubKey) =/= false
end)
catch _:_ ->
throw(verify_error)
end;
{true, _IAddr} ->
VerFun=case lists:member(nocheck_ledger,Opts) of
false ->
LedgerInfo=mledger:get(
proplists : get_value(ledger , Opts , ledger ) ,
From),
case LedgerInfo of
#{pubkey:=PK} when is_binary(PK) ->
fun(PubKey, _) ->
tpecdsa:cmp_pubkey(PK)==tpecdsa:cmp_pubkey(PubKey)
end;
_ ->
throw({ledger_err, From})
end;
true ->
undefined
end,
bsig:checksig(Body, LSigs, VerFun);
_ ->
throw({invalid_address, from})
end,
case Res of
{[], _} ->
bad_sig;
{Valid, Invalid} when length(Valid)>0 ->
{ok, Tx#{
sigverify=>#{
valid=>length(Valid),
invalid=>Invalid,
pubkeys=>bsig:extract_pubkeys(Valid)
}
}
}
end;
verify(#{
kind:=register,
body:=Body,
sig:=LSigs,
ver:=2
}=Tx, _Opts) ->
Res=bsig:checksig(Body, LSigs),
case Res of
{[], _} ->
bad_sig;
{Valid, Invalid} when length(Valid)>0 ->
BodyHash=hashdiff(crypto:hash(sha512,Body)),
ValidPK=bsig:extract_pubkeys(Valid),
Keys1=iolist_to_binary(
lists:sort(
[ begin {_KeyType,RawPubKey} = tpecdsa:cmp_pubkey(PK), RawPubKey end || PK <- ValidPK ]
)
),
Pubs=crypto:hash(sha256,Keys1),
#{keysh:=H}=unpack_body(Tx),
if Pubs==H ->
{ok, Tx#{
sigverify=>#{
pow_diff=>BodyHash,
valid=>length(Valid),
invalid=>Invalid,
pubkeys=>ValidPK
}
}
};
true ->
bad_keys
end
end;
verify(#{
kind:=patch,
body:=Body,
sig:=LSigs,
ver:=2
}=Tx, Opts) ->
NCK=lists:member(nocheck_keys, Opts),
CheckFun=case {NCK,lists:keyfind(settings,1,Opts)} of
{true,_} ->
fun(_PubKey,_) ->
true
end;
{false, {_,Sets0}} ->
fun(PubKey,_) ->
chainsettings:is_our_node(PubKey, Sets0) =/= false
end;
{false, false} ->
fun(PubKey,_) ->
chainsettings:is_our_node(PubKey) =/= false
end
end,
Res=bsig:checksig(Body, LSigs, CheckFun),
case Res of
{[], _} when NCK==true ->
bad_sig;
{[], _} ->
Sets=case lists:keyfind(settings,1,Opts) of
{_,Sets1} ->
settings:get([<<"current">>,<<"patchkeys">>],Sets1);
false ->
chainsettings:by_path([<<"current">>,<<"patchkeys">>])
end,
case Sets of
#{keys:=Keys0} when is_list(Keys0) ->
Keys=[tpecdsa:cmp_pubkey(K) || K <- Keys0 ],
CheckFun1=fun(PubKey,_) ->
CP=tpecdsa:cmp_pubkey(PubKey),
lists:member(CP, Keys)
end,
Res1=bsig:checksig(Body, LSigs, CheckFun1),
case Res1 of
{[], _} ->
bad_sig;
{Valid, Invalid} when length(Valid)>0 ->
CPKs=lists:foldl(
fun(PubKey,A) ->
maps:put(tpecdsa:cmp_pubkey(PubKey),PubKey,A)
end, #{}, bsig:extract_pubkeys(Valid)
),
{ok, Tx#{
sigverify=>#{
valid=>maps:size(CPKs),
invalid=>Invalid,
source=>patchkeys,
pubkeys=>maps:values(CPKs)
}
}
}
end;
_ ->
bad_sig
end;
{Valid, Invalid} when length(Valid)>0 andalso NCK ->
{ok, Tx#{
sigverify=>#{
valid=>length(Valid),
invalid=>Invalid,
source=>unverified,
pubkeys=>bsig:extract_pubkeys(Valid)
}
}
};
{Valid, Invalid} when length(Valid)>0 ->
{ok, Tx#{
sigverify=>#{
valid=>length(Valid),
invalid=>Invalid,
source=>nodekeys,
pubkeys=>bsig:extract_pubkeys(Valid)
}
}
}
end;
verify(Bin, Opts) when is_binary(Bin) ->
MaxTxSize = proplists:get_value(maxsize, Opts, 0),
case size(Bin) of
_Size when MaxTxSize > 0 andalso _Size > MaxTxSize ->
tx_too_big;
_ ->
Tx = unpack(Bin),
verify(Tx, Opts)
end;
verify(Struct, _Opts) ->
throw({invalid_tx, Struct}).
tx1 : verify(Struct , ) .
-spec pack(tx()) -> binary().
pack(Tx) ->
pack(Tx, []).
pack(#{ patch:=LPatch }=OldTX, _Opts) ->
msgpack:pack(
maps:merge(
#{
type => <<"patch">>,
patch => LPatch,
sig => maps:get(sig, OldTX, [])
},
maps:with([extdata], OldTX))
);
pack(#{
hash:=_,
header:=_,
sign:=_
}=Block, _Opts) ->
msgpack:pack(
#{
"ver"=>2,
"sig"=>[],
"body" => block:pack(Block)
},
[
{spec,new},
{pack_str, from_list}
]
);
pack(#{ ver:=2,
body:=Bin,
sig:=PS}=Tx, Opts) ->
T=#{"ver"=>2,
"body"=>Bin,
"sig"=>PS
},
T1=case Tx of
#{inv:=Invite} ->
T#{"inv"=>Invite};
_ ->
T
end,
T2=case lists:member(withext, Opts) andalso maps:is_key(extdata, Tx) of
false -> T1;
true ->
T1#{
"extdata" => maps:get(extdata,Tx)
}
end,
msgpack:pack(T2,[
{spec,new},
{pack_str, from_list}
]);
pack(Any, _) ->
throw({invalid_tx, Any}).
%tx1:pack(Any).
complete_tx(BinTx,Comp) when is_binary(BinTx) ->
{ok, #{"k":=IKind}=Tx0} = msgpack:unpack(BinTx, [{unpack_str, as_list}] ),
{Ver, Kind}=decode_kind(IKind),
B=maps:merge(Comp, Tx0),
construct_tx(unpack_body(#{ver=>Ver, kind=>Kind},B)).
unpack_naked(BB) when is_binary(BB) ->
unpack_body( #{ ver=>2, sig=>[], body=>BB }).
unpack(Tx) when is_map(Tx) ->
Tx;
unpack(BinTx) when is_binary(BinTx) ->
unpack(BinTx,[]).
unpack(BinTx,Opts) when is_binary(BinTx), is_list(Opts) ->
{ok, Tx0} = msgpack:unpack(BinTx, [{known_atoms,
[type, sig, tx, patch, register,
register, address, block ] },
{unpack_str, as_binary}] ),
Trusted=lists:member(trusted, Opts),
case Tx0 of
#{<<"ver">>:=2, sig:=Sign, <<"body">>:=TxBody, <<"inv">>:=Inv} ->
unpack_body( #{
ver=>2,
sig=>Sign,
body=>TxBody,
inv=>Inv
});
#{<<"ver">>:=2, sig:=Sign, <<"body">>:=TxBody} ->
unpack_generic(Trusted, Tx0, TxBody, Sign);
_ ->
?LOG_INFO("FIXME isTXv1: ~p", [Tx0]),
tx1:unpack_mp(Tx0)
end.
unpack_generic(Trusted, Tx0, TxBody, Sign) ->
Ext=if Trusted ->
case maps:find(<<"extdata">>,Tx0) of
{ok, Val} ->
Val;
_ -> false
end;
true -> false
end,
unpack_body(
if Ext == false ->
#{ ver=>2,
sig=>Sign,
body=>TxBody
};
true ->
#{ extdata => Ext,
ver=>2,
sig=>Sign,
body=>TxBody
}
end).
txlist_hash(List) ->
crypto:hash(sha256,
iolist_to_binary(lists:foldl(
fun({Id, Bin}, Acc) when is_binary(Bin) ->
[Id, Bin|Acc];
({Id, #{}=Tx}, Acc) ->
[Id, tx:pack(Tx)|Acc]
end, [], lists:keysort(1, List)))).
get_payload(#{ver:=2, kind:=Kind, payload:=Payload}=_Tx, Purpose)
when Kind==deploy; Kind==generic; Kind==tstore; Kind==lstore ->
lists:foldl(
fun(#{amount:=_,cur:=_,purpose:=P1}=A, undefined) when P1==Purpose ->
A;
(_,A) ->
A
end, undefined, Payload);
get_payload(#{ver:=2, kind:=Kind},_) ->
throw({unknown_kind_for_get_payload,Kind}).
get_payloads(#{ver:=2, kind:=Kind, payload:=Payload}=_Tx, Purpose)
when Kind==deploy; Kind==generic; Kind==tstore; Kind==lstore ->
lists:filter(
fun(#{amount:=_,cur:=_,purpose:=P1}) ->
P1==Purpose
end, Payload);
get_payloads(#{ver:=2, kind:=Kind},_) ->
throw({unknown_kind_for_get_payloads,Kind}).
rate1(#{extradata:=ED}, Cur, TxAmount, GetRateFun) ->
#{<<"base">>:=Base,
<<"kb">>:=KB}=Rates=GetRateFun(Cur),
BaseEx=maps:get(<<"baseextra">>, Rates, 0),
ExtCur=max(0, size(ED)-BaseEx),
Cost=Base+trunc(ExtCur*KB/1024),
{TxAmount >= Cost,
#{ cur=>Cur,
cost=>Cost,
tip => max(0, TxAmount - Cost)
}}.
rate2(#{body:=Body}=_Tx, Cur, TxAmount, GetRateFun) ->
case GetRateFun(Cur) of
#{<<"base">>:=Base,
<<"kb">>:=KB}=Rates ->
BaseEx=maps:get(<<"baseextra">>, Rates, 0),
BodySize=size(Body)-32, %correcton rate
ExtCur=max(0, BodySize-BaseEx),
Cost=Base+trunc(ExtCur*KB/1024),
{TxAmount >= Cost,
#{ cur=>Cur,
cost=>Cost,
tip => max(0, TxAmount - Cost)
}};
_Any ->
throw('unsupported_fee_cur')
end.
rate(#{ver:=2, kind:=_}=Tx, GetRateFun) ->
try
case get_payload(Tx, srcfee) of
#{cur:=Cur, amount:=TxAmount} ->
rate2(Tx, Cur, TxAmount, GetRateFun);
_ ->
case GetRateFun({params, <<"feeaddr">>}) of
X when is_binary(X) ->
rate2(Tx, <<"none">>, 0, GetRateFun);
%{false, #{ cost=>null } };
_ ->
{true, #{ cost=>0, tip => 0, cur=><<"none">> }}
end
end
catch throw:Ee:S when is_atom(Ee) ->
%S=erlang:get_stacktrace(),
file:write_file("tmp/rate.txt",
[
io_lib:format("~p.~n~p.~n~n~p.~n~n~p.~n~n~p.~n",
[
throw,
Ee,
S,
Tx,
element(2,erlang:fun_info(GetRateFun,env))
])]),
?LOG_ERROR("Calc fee error ~p~ntx ~p",[{throw,Ee},Tx]),
lists:foreach(fun(SE) ->
?LOG_ERROR("@ ~p", [SE])
end, S),
throw(Ee);
Ec:Ee:S ->
%S=erlang:get_stacktrace(),
file:write_file("tmp/rate.txt",
[
io_lib:format("~p.~n~p.~n~n~p.~n~n~p.~n~n~p.~n",
[
Ec,
Ee,
S,
Tx,
element(2,erlang:fun_info(GetRateFun,env))
])]),
?LOG_ERROR("Calc fee error ~p~ntx ~p",[{Ec,Ee},Tx]),
lists:foreach(fun(SE) ->
?LOG_ERROR("@ ~p", [SE])
end, S),
throw('cant_calculate_fee')
end;
rate(#{cur:=TCur}=Tx, GetRateFun) ->
try
case maps:get(extdata, Tx, #{}) of
#{fee:=TxAmount, feecur:=Cur} ->
rate1(Tx, Cur, TxAmount, GetRateFun);
#{fee:=TxAmount} ->
rate1(Tx, TCur, TxAmount, GetRateFun);
_ ->
case GetRateFun({params, <<"feeaddr">>}) of
X when is_binary(X) ->
rate1(Tx, <<"none">>, 0, GetRateFun);
% {false, #{ cost=>null } };
_ ->
{true, #{ cost=>0, tip => 0, cur=>TCur }}
end
end
catch _:_ -> throw('cant_calculate_fee')
end.
intdiff(I) when I>0 andalso I<128 ->
intdiff(I bsl 1)+1;
intdiff(_I) ->
0.
hashdiff(<<0,_Rest/binary>>) ->
hashdiff(_Rest)+8;
hashdiff(<<I:8/integer,_Rest/binary>>) ->
intdiff(I);
hashdiff(_) ->
0.
mine_sha512(Body, Nonce, Diff) ->
DS=Body#{pow=>Nonce},
if Nonce rem 1000000 = = 0 - >
% io:format("nonce ~w~n",[Nonce]);
% true -> ok
% end,
Hash=crypto:hash(sha512,pack_body(DS)),
Act=if Diff rem 8 == 0 ->
<<Act1:Diff/big,_/binary>>=Hash,
Act1;
true ->
Pad=8-(Diff rem 8),
<<Act1:Diff/big,_:Pad/big,_/binary>>=Hash,
Act1
end,
if Act==0 ->
%io:format("Mined nonce ~w~n",[Nonce]),
DS;
true ->
mine_sha512(Body,Nonce+1,Diff)
end.
upgrade(#{
from:=From,
to:=To,
amount:=Amount,
cur:=Cur,
seq:=Seq,
timestamp:=T
}=Tx) ->
DED=jsx:decode(maps:get(extradata, Tx, "{}"), [return_maps]),
Fee=case DED of
#{ <<"fee">>:=FeeA, <<"feecur">>:=FeeC } ->
[#{amount=>FeeA, cur=>FeeC, purpose=>srcfee}];
_ ->
[]
end,
TxExt=case DED of
#{<<"message">>:=Msg} ->
#{msg=>Msg};
_ ->
#{}
end,
construct_tx(#{
ver=>2,
kind=>generic,
from=>From,
to=>To,
t=>T,
seq=>Seq,
payload=>[#{amount=>Amount, cur=>Cur, purpose=>transfer}|Fee],
txext => TxExt
}).
| null | https://raw.githubusercontent.com/thepower/tpnode/67ae060af2b2ef0ae1560085b7f9c5d92dd4f115/apps/tpnode/src/tx.erl | erlang | Keys1=iolist_to_binary(lists:sort(PubKeys)),
TODO: remove this temporary fix
case maps:is_key("c",Unpacked) of
false -> Decoded;
true ->
Decoded#{
call=>#{function=>Function, args=>Args}
}
end;
contract issued. Check nodes key.
tx1:pack(Any).
correcton rate
{false, #{ cost=>null } };
S=erlang:get_stacktrace(),
S=erlang:get_stacktrace(),
{false, #{ cost=>null } };
io:format("nonce ~w~n",[Nonce]);
true -> ok
end,
io:format("Mined nonce ~w~n",[Nonce]), | -module(tx).
-include("include/tplog.hrl").
-export([del_ext/2, get_ext/2, set_ext/3]).
-export([sign/2, verify/1, verify/2, pack/1, pack/2, unpack/1, unpack/2]).
-export([txlist_hash/1, rate/2, mergesig/2]).
-export([encode_purpose/1, decode_purpose/1, encode_kind/2, decode_kind/1]).
-export([construct_tx/1,construct_tx/2, get_payload/2, get_payloads/2]).
-export([unpack_naked/1]).
-export([complete_tx/2]).
-export([hashdiff/1,upgrade/1]).
-include("apps/tpnode/include/tx_const.hrl").
mergesig(#{sig:=S1}=Tx1, #{sig:=S2}) when is_map(S1), is_map(S2)->
Tx1#{sig=>
maps:merge(S1, S2)
};
mergesig(#{sig:=S1}=Tx1, #{sig:=S2}) when is_list(S1), is_list(S2)->
F=lists:foldl(
fun(P,A) ->
S=bsig:extract_pubkey(bsig:unpacksig(P)),
maps:put(S,P,A)
end,
#{},
S1++S2),
Tx1#{sig=> maps:values(F)};
mergesig(Tx1, Tx2) ->
file:write_file("tmp/merge1.txt", io_lib:format("~p.~n~p.~n", [Tx1,Tx2])),
Tx1.
checkaddr(<<Ia:64/big>>) -> {true, Ia};
checkaddr(_) -> false.
get_ext(K, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
case maps:is_key(K, Ed) of
true ->
{ok, maps:get(K, Ed)};
false ->
undefined
end.
set_ext(<<"fee">>, V, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:put(fee, V, Ed)
};
set_ext(<<"feecur">>, V, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:put(feecur, V, Ed)
};
set_ext(K, V, Tx) when is_atom(K) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:put(atom_to_binary(K, utf8), V, Ed)
};
set_ext(K, V, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:put(K, V, Ed)
}.
del_ext(K, Tx) ->
Ed=maps:get(extdata, Tx, #{}),
Tx#{
extdata=>maps:remove(K, Ed)
}.
-spec to_list(Arg :: binary() | list()) -> list().
to_list(Arg) when is_list(Arg) ->
Arg;
to_list(Arg) when is_binary(Arg) ->
binary_to_list(Arg).
-spec to_binary(Arg :: binary() | list()) -> binary().
to_binary(Arg) when is_binary(Arg) ->
Arg;
to_binary(Arg) when is_list(Arg) ->
list_to_binary(Arg).
pack_body(Body) ->
msgpack:pack(Body,[{spec,new},{pack_str, from_list}]).
construct_tx(Any) ->
construct_tx(Any,[]).
construct_tx(#{
ver:=2,
kind:=patch,
patches:=Patches
}=Tx0,_Params) ->
Tx=maps:with([ver,txext,patches],Tx0),
E0=#{
"k"=>encode_kind(2,patch),
"e"=>maps:get(txext, Tx, #{}),
"p"=>Patches
},
Tx#{
patches=>settings:dmp(settings:mp(Patches)),
kind=>patch,
body=>pack_body(E0),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=register,
t:=Timestamp,
keys:=PubKeys
}=Tx0,Params) ->
Tx=maps:with([ver,t,txext],Tx0),
Keys1=iolist_to_binary(
lists:sort(
[ begin {_KeyType,RawPubKey} = tpecdsa:cmp_pubkey(PK), RawPubKey end || PK <- PubKeys ]
)
),
KeysH=crypto:hash(sha256,Keys1),
E0=#{
"k"=>encode_kind(2,register),
"t"=>Timestamp,
"e"=>maps:get(txext, Tx, #{}),
"h"=>KeysH
},
InvBody=case Tx0 of
#{inv:=Invite} ->
E0#{"inv"=>crypto:hash(sha256,Invite)};
_ ->
E0
end,
PowBody=case proplists:get_value(pow_diff,Params) of
undefined -> InvBody;
I when is_integer(I) ->
mine_sha512(InvBody, 0, I)
end,
case Tx0 of
#{inv:=Invite1} ->
maps:remove(keys,
Tx0#{
inv=>Invite1,
kind=>register,
body=>pack_body(PowBody),
keysh=>KeysH,
sig=>[]
});
_ ->
maps:remove(keys,
Tx0#{
kind=>register,
body=>pack_body(PowBody),
keysh=>KeysH,
sig=>[]
})
end;
construct_tx(#{
ver:=2,
kind:=tstore,
from:=F,
t:=Timestamp,
seq:=Seq,
payload:=Amounts
}=Tx0,_Params) ->
Tx=maps:with([ver,from,t,seq,payload,txext],Tx0),
A1=lists:map(
fun(#{amount:=Amount, cur:=Cur, purpose:=Purpose}) when
is_integer(Amount), is_binary(Cur) ->
[encode_purpose(Purpose), to_list(Cur), Amount]
end, Amounts),
Ext=maps:get(txext, Tx, #{}),
true=is_map(Ext),
E0=#{
"k"=>encode_kind(2,tstore),
"f"=>F,
"t"=>Timestamp,
"s"=>Seq,
"p"=>{array,A1},
"e"=>Ext
},
Tx#{
kind=>tstore,
body=>msgpack:pack(E0,[{spec,new},{pack_str, from_list}]),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=lstore,
from:=F,
t:=Timestamp,
seq:=Seq,
payload:=Amounts,
patches:=Patches
}=Tx0,_Params) ->
Tx=maps:with([ver,from,t,seq,payload,patches,txext],Tx0),
A1=lists:map(
fun(#{amount:=Amount, cur:=Cur, purpose:=Purpose}) when
is_integer(Amount), is_binary(Cur) ->
[encode_purpose(Purpose), to_list(Cur), Amount]
end, Amounts),
Ext=maps:get(txext, Tx, #{}),
true=is_map(Ext),
EP=settings:mp(Patches),
E0=#{
"k"=>encode_kind(2,lstore),
"f"=>F,
"t"=>Timestamp,
"s"=>Seq,
"p"=>{array,A1},
"pa"=>EP,
"e"=>Ext
},
Tx#{
kind=>lstore,
body=>pack_body(E0),
patches=>settings:dmp(EP),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=Kind,
from:=F,
t:=Timestamp,
seq:=Seq,
payload:=Amounts
}=Tx0,_Params) when Kind==deploy; Kind==notify ->
Tx=maps:with([ver,from,to,t,seq,payload,call,txext,notify,not_before],Tx0),
A1=lists:map(
fun(#{amount:=Amount, cur:=Cur, purpose:=Purpose}) when
is_integer(Amount), is_binary(Cur) ->
[encode_purpose(Purpose), to_list(Cur), Amount]
end, Amounts),
Ext=maps:get(txext, Tx, #{}),
true=is_map(Ext),
E0=#{
"k"=>encode_kind(2,Kind),
"f"=>F,
"t"=>Timestamp,
"s"=>Seq,
"p"=>{array,A1},
"e"=>Ext
},
{E1,Tx1}=maps:fold(fun prepare_extra_args/3, {E0, Tx}, Tx),
Tx1#{
kind=>Kind,
body=>msgpack:pack(E1,[{spec,new},{pack_str, from_list}]),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=chkey,
from:=F,
t:=Timestamp,
seq:=Seq,
keys:=[_|_]=PubKeys
}=Tx0,_Params) ->
Tx=maps:with([ver,from,t,seq,keys],Tx0),
E0=#{
"k"=>encode_kind(2,chkey),
"f"=>F,
"t"=>Timestamp,
"s"=>Seq,
"y"=>{array,PubKeys}
},
Tx#{
kind=>chkey,
body=>msgpack:pack(E0,[{spec,new},{pack_str, from_list}]),
sig=>[]
};
construct_tx(#{
ver:=2,
kind:=generic,
from:=F,
to:=To,
t:=Timestamp,
seq:=Seq,
payload:=Amounts
}=Tx0,_Params) ->
Tx=maps:with([ver,from,to,t,seq,payload,call,txext,not_before,notify],Tx0),
A1=lists:map(
fun(#{amount:=Amount, cur:=Cur, purpose:=Purpose}) when
is_integer(Amount), is_binary(Cur) ->
[encode_purpose(Purpose), to_list(Cur), Amount]
end, Amounts),
Ext=maps:get(txext, Tx, #{}),
true=is_map(Ext),
E0=#{
"k"=>encode_kind(2,generic),
"f"=>F,
"to"=>To,
"t"=>Timestamp,
"s"=>Seq,
"p"=>{array,A1},
"e"=>Ext
},
{E1,Tx1}=maps:fold(fun prepare_extra_args/3, {E0, Tx}, Tx),
Tx1#{
kind=>generic,
body=>msgpack:pack(E1,[{spec,new},{pack_str, from_list}]),
sig=>[]
}.
prepare_extra_args(call, #{function:=Fun,args:=Args}, {CE,CTx}) when
is_list(Fun), is_list(Args) ->
{CE#{"c"=>[Fun,{array,Args}]},CTx};
prepare_extra_args(call, _, {CE,CTx}) ->
{CE, maps:remove(call, CTx)};
prepare_extra_args(notify, CVal, {CE,CTx}) when is_list(CVal) ->
Ntf=lists:map(
fun({URL,Payload}) when
is_binary(Payload) andalso
(is_list(URL) orelse is_integer(URL)) ->
[URL,Payload];
(Map) when is_map(Map) ->
Map
end, CVal),
{CE#{"ev"=>Ntf},CTx};
prepare_extra_args(notify, _CVal, {CE,CTx}) ->
{CE, maps:remove(notify, CTx)};
prepare_extra_args(not_before, Int, {CE,CTx}) when is_integer(Int),
Int > 1600000000,
Int < 3000000000 ->
{CE#{"nb"=>Int},CTx};
prepare_extra_args(not_before, _Int, {CE,CTx}) ->
{CE, maps:remove(not_before, CTx)};
prepare_extra_args(_, _, {CE,CTx}) ->
{CE,CTx}.
unpack_body(#{sig:=<<>>}=Tx) ->
unpack_body(Tx#{sig:=[]});
unpack_body(#{body:=Body}=Tx) ->
case msgpack:unpack(Body,[{spec,new},{unpack_str, as_list}]) of
{ok,#{"k":=IKind}=B} ->
{Ver, Kind}=decode_kind(IKind),
unpack_body(Tx#{ver=>Ver, kind=>Kind},B);
{ok, #{<<"hash">>:=_,
<<"header">>:=_,
<<"sign">>:=_}} ->
block:unpack(Body);
{error,{invalid_string,_}} ->
case msgpack:unpack(Body,[{spec,new},{unpack_str, as_binary}]) of
{ok,#{<<"k">>:=IKind}=B0} ->
{Ver, Kind}=decode_kind(IKind),
B=maps:fold(
fun(K,V,Acc) ->
maps:put(unicode:characters_to_list(K),V,Acc)
end, #{}, B0),
unpack_body(Tx#{ver=>Ver, kind=>Kind},B)
end
end.
unpack_addr(<<_:64/big>>=From,_) -> From;
unpack_addr([_,_,_,_,_,_,_,_]=From,_) -> list_to_binary(From);
unpack_addr(_,T) -> throw(T).
unpack_timestamp(Time) when is_integer(Time) -> Time;
unpack_timestamp(_Time) -> throw(bad_timestamp).
unpack_seq(Int) when is_integer(Int) -> Int;
unpack_seq(_Int) -> throw(bad_seq).
unpack_txext(<<>>) -> #{};
unpack_txext(Map) when is_map(Map) -> Map;
unpack_txext(_Any) -> throw(bad_ext).
unpack_payload(Amounts) when is_list(Amounts) ->
lists:map(
fun([Purpose, Cur, Amount]) ->
if is_integer(Amount) -> ok;
true -> throw('bad_amount')
end,
#{amount=>Amount,
cur=>to_binary(Cur),
purpose=>decode_purpose(Purpose)
}
end, Amounts).
unpack_call_ntf_etc("c",[Function, Args],Decoded) ->
Decoded#{
call=>#{function=>Function, args=>Args}
};
unpack_call_ntf_etc("nb",Int,Decoded) when is_integer(Int),
Int > 1600000000,
Int < 3000000000 ->
Decoded#{
not_before => Int
};
unpack_call_ntf_etc("ev",Events,Decoded) when is_list(Events) ->
Decoded#{
notify => lists:map(
fun([URL,Body]) when is_binary(Body),
is_list(URL) ->
{URL, Body};
(Map) when is_map(Map) ->
Map
end, Events)
};
unpack_call_ntf_etc(_,_,Decoded) ->
Decoded.
unpack_body(#{ ver:=2,
kind:=GenericOrDeploy
}=Tx,
#{ "f":=From,
"to":=To,
"t":=Timestamp,
"s":=Seq,
"p":=Payload
}=Unpacked) when GenericOrDeploy == generic ;
GenericOrDeploy == deploy ->
Amounts=unpack_payload(Payload),
Decoded=Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
to=>unpack_addr(To,bad_to),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
},
maps:fold(fun unpack_call_ntf_etc/3, Decoded, Unpacked);
[ Function , Args]=maps : ) ,
unpack_body(#{ ver:=2,
kind:=deploy
}=Tx,
#{ "f":=From,
"t":=Timestamp,
"s":=Seq,
"p":=Payload
}=Unpacked) ->
Amounts=unpack_payload(Payload),
Decoded=Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
},
case maps:is_key("c",Unpacked) of
false -> Decoded;
true ->
[Function, Args]=maps:get("c",Unpacked),
Decoded#{
call=>#{function=>Function, args=>Args}
}
end;
unpack_body(#{ ver:=2,
kind:=notify
}=Tx,
#{ "f":=From,
"t":=Timestamp,
"s":=Seq,
"p":=Payload
}=Unpacked) ->
Amounts=unpack_payload(Payload),
Decoded=Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
},
maps:fold(fun unpack_call_ntf_etc/3, Decoded, Unpacked);
unpack_body(#{ ver:=2,
kind:=tstore
}=Tx,
#{ "f":=From,
"t":=Timestamp,
"s":=Seq,
"p":=Payload
}=Unpacked) ->
Amounts=unpack_payload(Payload),
Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
};
unpack_body(#{ ver:=2,
kind:=lstore
}=Tx,
#{ "f":=From,
"t":=Timestamp,
"s":=Seq,
"pa":=Patches,
"p":=Payload
}=Unpacked) ->
Amounts=unpack_payload(Payload),
Tx#{
ver=>2,
from=>unpack_addr(From,bad_from),
t=>unpack_timestamp(Timestamp),
seq=>unpack_seq(Seq),
payload=>Amounts,
patches=>settings:dmp(Patches),
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
};
unpack_body(#{ ver:=2,
kind:=register
}=Tx,
#{ "t":=Timestamp,
"h":=Hash
}=Unpacked) ->
Tx#{
ver=>2,
t=>unpack_timestamp(Timestamp),
keysh=>Hash,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
};
unpack_body(#{ ver:=2,
kind:=chkey
}=Tx,
#{ "t":=Timestamp,
"f":=From,
"s":=Seq,
"y":=PubKeys
}) ->
Tx#{
ver=>2,
t=>unpack_timestamp(Timestamp),
seq=>Seq,
from=>From,
keys=>PubKeys
};
unpack_body(#{ ver:=2,
kind:=patch
}=Tx,
#{ "p":=Patches
}=Unpacked) ->
Tx#{
ver=>2,
patches=>Patches,
txext=>unpack_txext(maps:get("e", Unpacked, #{}))
};
unpack_body(#{ver:=Ver, kind:=Kind},_Unpacked) ->
throw({unknown_ver_or_kind,{Ver,Kind},_Unpacked}).
sign(#{kind:=_Kind,
body:=Body,
sig:=PS}=Tx, PrivKey) ->
Sig=bsig:signhash(Body,[],PrivKey),
Tx#{sig=>[Sig|PS]};
sign(#{patch:=Patch}, PrivKey) ->
tx:sign(tx:construct_tx(#{patches=>Patch, kind=>patch, ver=>2}), PrivKey);
sign(Any, _PrivKey) ->
throw({not_a_tx,Any}).
tx1 : sign(Any , PrivKey ) .
-type tx() :: tx2() | tx1().
-type tx2() :: #{
ver:=non_neg_integer(),
kind:=atom(),
body:=binary(),
sig=>list(),
sigverify=>#{valid:=integer(),
invalid:=integer()
}
}.
-type tx1() :: #{ 'patch':=binary(), 'sig':=list() }
| #{ 'type':='register', 'pow':=binary(),
'register':=binary(), 'timestamp':=integer() }
| #{ from := binary(), sig := map(), timestamp := integer() }.
-spec verify(tx()|binary()) ->
{ok, tx()} | 'bad_sig'.
verify(Tx) ->
verify(Tx, []).
-spec verify(tx()|binary(), ['nocheck_ledger'| {ledger, pid()}]) ->
{ok, tx()} | 'bad_sig'.
verify(#{
kind:=GenericOrDeploy,
from:=From,
body:=Body,
sig:=LSigs,
ver:=2
}=Tx, Opts) when GenericOrDeploy==generic;
GenericOrDeploy==deploy;
GenericOrDeploy==chkey;
GenericOrDeploy==tstore;
GenericOrDeploy==notify;
GenericOrDeploy==lstore ->
CI=get_ext(<<"contract_issued">>, Tx),
Res=case checkaddr(From) of
{true, _IAddr} when CI=={ok, From} ->
try
bsig:checksig(Body, LSigs,
fun(PubKey,_) ->
chainsettings:is_our_node(PubKey) =/= false
end)
catch _:_ ->
throw(verify_error)
end;
{true, _IAddr} ->
VerFun=case lists:member(nocheck_ledger,Opts) of
false ->
LedgerInfo=mledger:get(
proplists : get_value(ledger , Opts , ledger ) ,
From),
case LedgerInfo of
#{pubkey:=PK} when is_binary(PK) ->
fun(PubKey, _) ->
tpecdsa:cmp_pubkey(PK)==tpecdsa:cmp_pubkey(PubKey)
end;
_ ->
throw({ledger_err, From})
end;
true ->
undefined
end,
bsig:checksig(Body, LSigs, VerFun);
_ ->
throw({invalid_address, from})
end,
case Res of
{[], _} ->
bad_sig;
{Valid, Invalid} when length(Valid)>0 ->
{ok, Tx#{
sigverify=>#{
valid=>length(Valid),
invalid=>Invalid,
pubkeys=>bsig:extract_pubkeys(Valid)
}
}
}
end;
verify(#{
kind:=register,
body:=Body,
sig:=LSigs,
ver:=2
}=Tx, _Opts) ->
Res=bsig:checksig(Body, LSigs),
case Res of
{[], _} ->
bad_sig;
{Valid, Invalid} when length(Valid)>0 ->
BodyHash=hashdiff(crypto:hash(sha512,Body)),
ValidPK=bsig:extract_pubkeys(Valid),
Keys1=iolist_to_binary(
lists:sort(
[ begin {_KeyType,RawPubKey} = tpecdsa:cmp_pubkey(PK), RawPubKey end || PK <- ValidPK ]
)
),
Pubs=crypto:hash(sha256,Keys1),
#{keysh:=H}=unpack_body(Tx),
if Pubs==H ->
{ok, Tx#{
sigverify=>#{
pow_diff=>BodyHash,
valid=>length(Valid),
invalid=>Invalid,
pubkeys=>ValidPK
}
}
};
true ->
bad_keys
end
end;
verify(#{
kind:=patch,
body:=Body,
sig:=LSigs,
ver:=2
}=Tx, Opts) ->
NCK=lists:member(nocheck_keys, Opts),
CheckFun=case {NCK,lists:keyfind(settings,1,Opts)} of
{true,_} ->
fun(_PubKey,_) ->
true
end;
{false, {_,Sets0}} ->
fun(PubKey,_) ->
chainsettings:is_our_node(PubKey, Sets0) =/= false
end;
{false, false} ->
fun(PubKey,_) ->
chainsettings:is_our_node(PubKey) =/= false
end
end,
Res=bsig:checksig(Body, LSigs, CheckFun),
case Res of
{[], _} when NCK==true ->
bad_sig;
{[], _} ->
Sets=case lists:keyfind(settings,1,Opts) of
{_,Sets1} ->
settings:get([<<"current">>,<<"patchkeys">>],Sets1);
false ->
chainsettings:by_path([<<"current">>,<<"patchkeys">>])
end,
case Sets of
#{keys:=Keys0} when is_list(Keys0) ->
Keys=[tpecdsa:cmp_pubkey(K) || K <- Keys0 ],
CheckFun1=fun(PubKey,_) ->
CP=tpecdsa:cmp_pubkey(PubKey),
lists:member(CP, Keys)
end,
Res1=bsig:checksig(Body, LSigs, CheckFun1),
case Res1 of
{[], _} ->
bad_sig;
{Valid, Invalid} when length(Valid)>0 ->
CPKs=lists:foldl(
fun(PubKey,A) ->
maps:put(tpecdsa:cmp_pubkey(PubKey),PubKey,A)
end, #{}, bsig:extract_pubkeys(Valid)
),
{ok, Tx#{
sigverify=>#{
valid=>maps:size(CPKs),
invalid=>Invalid,
source=>patchkeys,
pubkeys=>maps:values(CPKs)
}
}
}
end;
_ ->
bad_sig
end;
{Valid, Invalid} when length(Valid)>0 andalso NCK ->
{ok, Tx#{
sigverify=>#{
valid=>length(Valid),
invalid=>Invalid,
source=>unverified,
pubkeys=>bsig:extract_pubkeys(Valid)
}
}
};
{Valid, Invalid} when length(Valid)>0 ->
{ok, Tx#{
sigverify=>#{
valid=>length(Valid),
invalid=>Invalid,
source=>nodekeys,
pubkeys=>bsig:extract_pubkeys(Valid)
}
}
}
end;
verify(Bin, Opts) when is_binary(Bin) ->
MaxTxSize = proplists:get_value(maxsize, Opts, 0),
case size(Bin) of
_Size when MaxTxSize > 0 andalso _Size > MaxTxSize ->
tx_too_big;
_ ->
Tx = unpack(Bin),
verify(Tx, Opts)
end;
verify(Struct, _Opts) ->
throw({invalid_tx, Struct}).
tx1 : verify(Struct , ) .
-spec pack(tx()) -> binary().
pack(Tx) ->
pack(Tx, []).
pack(#{ patch:=LPatch }=OldTX, _Opts) ->
msgpack:pack(
maps:merge(
#{
type => <<"patch">>,
patch => LPatch,
sig => maps:get(sig, OldTX, [])
},
maps:with([extdata], OldTX))
);
pack(#{
hash:=_,
header:=_,
sign:=_
}=Block, _Opts) ->
msgpack:pack(
#{
"ver"=>2,
"sig"=>[],
"body" => block:pack(Block)
},
[
{spec,new},
{pack_str, from_list}
]
);
pack(#{ ver:=2,
body:=Bin,
sig:=PS}=Tx, Opts) ->
T=#{"ver"=>2,
"body"=>Bin,
"sig"=>PS
},
T1=case Tx of
#{inv:=Invite} ->
T#{"inv"=>Invite};
_ ->
T
end,
T2=case lists:member(withext, Opts) andalso maps:is_key(extdata, Tx) of
false -> T1;
true ->
T1#{
"extdata" => maps:get(extdata,Tx)
}
end,
msgpack:pack(T2,[
{spec,new},
{pack_str, from_list}
]);
pack(Any, _) ->
throw({invalid_tx, Any}).
complete_tx(BinTx,Comp) when is_binary(BinTx) ->
{ok, #{"k":=IKind}=Tx0} = msgpack:unpack(BinTx, [{unpack_str, as_list}] ),
{Ver, Kind}=decode_kind(IKind),
B=maps:merge(Comp, Tx0),
construct_tx(unpack_body(#{ver=>Ver, kind=>Kind},B)).
unpack_naked(BB) when is_binary(BB) ->
unpack_body( #{ ver=>2, sig=>[], body=>BB }).
unpack(Tx) when is_map(Tx) ->
Tx;
unpack(BinTx) when is_binary(BinTx) ->
unpack(BinTx,[]).
unpack(BinTx,Opts) when is_binary(BinTx), is_list(Opts) ->
{ok, Tx0} = msgpack:unpack(BinTx, [{known_atoms,
[type, sig, tx, patch, register,
register, address, block ] },
{unpack_str, as_binary}] ),
Trusted=lists:member(trusted, Opts),
case Tx0 of
#{<<"ver">>:=2, sig:=Sign, <<"body">>:=TxBody, <<"inv">>:=Inv} ->
unpack_body( #{
ver=>2,
sig=>Sign,
body=>TxBody,
inv=>Inv
});
#{<<"ver">>:=2, sig:=Sign, <<"body">>:=TxBody} ->
unpack_generic(Trusted, Tx0, TxBody, Sign);
_ ->
?LOG_INFO("FIXME isTXv1: ~p", [Tx0]),
tx1:unpack_mp(Tx0)
end.
unpack_generic(Trusted, Tx0, TxBody, Sign) ->
Ext=if Trusted ->
case maps:find(<<"extdata">>,Tx0) of
{ok, Val} ->
Val;
_ -> false
end;
true -> false
end,
unpack_body(
if Ext == false ->
#{ ver=>2,
sig=>Sign,
body=>TxBody
};
true ->
#{ extdata => Ext,
ver=>2,
sig=>Sign,
body=>TxBody
}
end).
txlist_hash(List) ->
crypto:hash(sha256,
iolist_to_binary(lists:foldl(
fun({Id, Bin}, Acc) when is_binary(Bin) ->
[Id, Bin|Acc];
({Id, #{}=Tx}, Acc) ->
[Id, tx:pack(Tx)|Acc]
end, [], lists:keysort(1, List)))).
get_payload(#{ver:=2, kind:=Kind, payload:=Payload}=_Tx, Purpose)
when Kind==deploy; Kind==generic; Kind==tstore; Kind==lstore ->
lists:foldl(
fun(#{amount:=_,cur:=_,purpose:=P1}=A, undefined) when P1==Purpose ->
A;
(_,A) ->
A
end, undefined, Payload);
get_payload(#{ver:=2, kind:=Kind},_) ->
throw({unknown_kind_for_get_payload,Kind}).
get_payloads(#{ver:=2, kind:=Kind, payload:=Payload}=_Tx, Purpose)
when Kind==deploy; Kind==generic; Kind==tstore; Kind==lstore ->
lists:filter(
fun(#{amount:=_,cur:=_,purpose:=P1}) ->
P1==Purpose
end, Payload);
get_payloads(#{ver:=2, kind:=Kind},_) ->
throw({unknown_kind_for_get_payloads,Kind}).
rate1(#{extradata:=ED}, Cur, TxAmount, GetRateFun) ->
#{<<"base">>:=Base,
<<"kb">>:=KB}=Rates=GetRateFun(Cur),
BaseEx=maps:get(<<"baseextra">>, Rates, 0),
ExtCur=max(0, size(ED)-BaseEx),
Cost=Base+trunc(ExtCur*KB/1024),
{TxAmount >= Cost,
#{ cur=>Cur,
cost=>Cost,
tip => max(0, TxAmount - Cost)
}}.
rate2(#{body:=Body}=_Tx, Cur, TxAmount, GetRateFun) ->
case GetRateFun(Cur) of
#{<<"base">>:=Base,
<<"kb">>:=KB}=Rates ->
BaseEx=maps:get(<<"baseextra">>, Rates, 0),
ExtCur=max(0, BodySize-BaseEx),
Cost=Base+trunc(ExtCur*KB/1024),
{TxAmount >= Cost,
#{ cur=>Cur,
cost=>Cost,
tip => max(0, TxAmount - Cost)
}};
_Any ->
throw('unsupported_fee_cur')
end.
rate(#{ver:=2, kind:=_}=Tx, GetRateFun) ->
try
case get_payload(Tx, srcfee) of
#{cur:=Cur, amount:=TxAmount} ->
rate2(Tx, Cur, TxAmount, GetRateFun);
_ ->
case GetRateFun({params, <<"feeaddr">>}) of
X when is_binary(X) ->
rate2(Tx, <<"none">>, 0, GetRateFun);
_ ->
{true, #{ cost=>0, tip => 0, cur=><<"none">> }}
end
end
catch throw:Ee:S when is_atom(Ee) ->
file:write_file("tmp/rate.txt",
[
io_lib:format("~p.~n~p.~n~n~p.~n~n~p.~n~n~p.~n",
[
throw,
Ee,
S,
Tx,
element(2,erlang:fun_info(GetRateFun,env))
])]),
?LOG_ERROR("Calc fee error ~p~ntx ~p",[{throw,Ee},Tx]),
lists:foreach(fun(SE) ->
?LOG_ERROR("@ ~p", [SE])
end, S),
throw(Ee);
Ec:Ee:S ->
file:write_file("tmp/rate.txt",
[
io_lib:format("~p.~n~p.~n~n~p.~n~n~p.~n~n~p.~n",
[
Ec,
Ee,
S,
Tx,
element(2,erlang:fun_info(GetRateFun,env))
])]),
?LOG_ERROR("Calc fee error ~p~ntx ~p",[{Ec,Ee},Tx]),
lists:foreach(fun(SE) ->
?LOG_ERROR("@ ~p", [SE])
end, S),
throw('cant_calculate_fee')
end;
rate(#{cur:=TCur}=Tx, GetRateFun) ->
try
case maps:get(extdata, Tx, #{}) of
#{fee:=TxAmount, feecur:=Cur} ->
rate1(Tx, Cur, TxAmount, GetRateFun);
#{fee:=TxAmount} ->
rate1(Tx, TCur, TxAmount, GetRateFun);
_ ->
case GetRateFun({params, <<"feeaddr">>}) of
X when is_binary(X) ->
rate1(Tx, <<"none">>, 0, GetRateFun);
_ ->
{true, #{ cost=>0, tip => 0, cur=>TCur }}
end
end
catch _:_ -> throw('cant_calculate_fee')
end.
intdiff(I) when I>0 andalso I<128 ->
intdiff(I bsl 1)+1;
intdiff(_I) ->
0.
hashdiff(<<0,_Rest/binary>>) ->
hashdiff(_Rest)+8;
hashdiff(<<I:8/integer,_Rest/binary>>) ->
intdiff(I);
hashdiff(_) ->
0.
mine_sha512(Body, Nonce, Diff) ->
DS=Body#{pow=>Nonce},
if Nonce rem 1000000 = = 0 - >
Hash=crypto:hash(sha512,pack_body(DS)),
Act=if Diff rem 8 == 0 ->
<<Act1:Diff/big,_/binary>>=Hash,
Act1;
true ->
Pad=8-(Diff rem 8),
<<Act1:Diff/big,_:Pad/big,_/binary>>=Hash,
Act1
end,
if Act==0 ->
DS;
true ->
mine_sha512(Body,Nonce+1,Diff)
end.
upgrade(#{
from:=From,
to:=To,
amount:=Amount,
cur:=Cur,
seq:=Seq,
timestamp:=T
}=Tx) ->
DED=jsx:decode(maps:get(extradata, Tx, "{}"), [return_maps]),
Fee=case DED of
#{ <<"fee">>:=FeeA, <<"feecur">>:=FeeC } ->
[#{amount=>FeeA, cur=>FeeC, purpose=>srcfee}];
_ ->
[]
end,
TxExt=case DED of
#{<<"message">>:=Msg} ->
#{msg=>Msg};
_ ->
#{}
end,
construct_tx(#{
ver=>2,
kind=>generic,
from=>From,
to=>To,
t=>T,
seq=>Seq,
payload=>[#{amount=>Amount, cur=>Cur, purpose=>transfer}|Fee],
txext => TxExt
}).
|
bf7baf60687dbd7f18fed7b24b1acce50bb03d210241233f1222e075fcec183b | sdiehl/elliptic-curve | BrainpoolP320R1.hs | module Data.Curve.Weierstrass.BrainpoolP320R1
( module Data.Curve.Weierstrass
, Point(..)
-- * BrainpoolP320R1 curve
, module Data.Curve.Weierstrass.BrainpoolP320R1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
-------------------------------------------------------------------------------
-- Types
-------------------------------------------------------------------------------
-- | BrainpoolP320R1 curve.
data BrainpoolP320R1
| Field of points of BrainpoolP320R1 curve .
type Fq = Prime Q
type Q = 0xd35e472036bc4fb7e13c785ed201e065f98fcfa6f6f40def4f92b9ec7893ec28fcd412b1f1b32e27
| Field of coefficients of BrainpoolP320R1 curve .
type Fr = Prime R
type R = 0xd35e472036bc4fb7e13c785ed201e065f98fcfa5b68f12a32d482ec7ee8658e98691555b44c59311
BrainpoolP320R1 curve is a Weierstrass curve .
instance Curve 'Weierstrass c BrainpoolP320R1 Fq Fr => WCurve c BrainpoolP320R1 Fq Fr where
a_ = const _a
{-# INLINABLE a_ #-}
b_ = const _b
# INLINABLE b _ #
h_ = const _h
{-# INLINABLE h_ #-}
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
-- | Affine BrainpoolP320R1 curve point.
type PA = WAPoint BrainpoolP320R1 Fq Fr
Affine BrainpoolP320R1 curve is a Weierstrass affine curve .
instance WACurve BrainpoolP320R1 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
-- | Jacobian BrainpoolP320R1 point.
type PJ = WJPoint BrainpoolP320R1 Fq Fr
Jacobian BrainpoolP320R1 curve is a Weierstrass Jacobian curve .
instance WJCurve BrainpoolP320R1 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
-- | Projective BrainpoolP320R1 point.
type PP = WPPoint BrainpoolP320R1 Fq Fr
Projective BrainpoolP320R1 curve is a Weierstrass projective curve .
instance WPCurve BrainpoolP320R1 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
-------------------------------------------------------------------------------
-- Parameters
-------------------------------------------------------------------------------
-- | Coefficient @A@ of BrainpoolP320R1 curve.
_a :: Fq
_a = 0x3ee30b568fbab0f883ccebd46d3f3bb8a2a73513f5eb79da66190eb085ffa9f492f375a97d860eb4
# INLINABLE _ a #
| Coefficient @B@ of BrainpoolP320R1 curve .
_b :: Fq
_b = 0x520883949dfdbc42d3ad198640688a6fe13f41349554b49acc31dccd884539816f5eb4ac8fb1f1a6
{-# INLINABLE _b #-}
| Cofactor of BrainpoolP320R1 curve .
_h :: Natural
_h = 0x1
# INLINABLE _ h #
-- | Characteristic of BrainpoolP320R1 curve.
_q :: Natural
_q = 0xd35e472036bc4fb7e13c785ed201e065f98fcfa6f6f40def4f92b9ec7893ec28fcd412b1f1b32e27
{-# INLINABLE _q #-}
-- | Order of BrainpoolP320R1 curve.
_r :: Natural
_r = 0xd35e472036bc4fb7e13c785ed201e065f98fcfa5b68f12a32d482ec7ee8658e98691555b44c59311
{-# INLINABLE _r #-}
-- | Coordinate @X@ of BrainpoolP320R1 curve.
_x :: Fq
_x = 0x43bd7e9afb53d8b85289bcc48ee5bfe6f20137d10a087eb6e7871e2a10a599c710af8d0d39e20611
{-# INLINABLE _x #-}
| Coordinate @Y@ of curve .
_y :: Fq
_y = 0x14fdd05545ec1cc8ab4093247f77275e0743ffed117182eaa9c77877aaac6ac7d35245d1692e8ee1
{-# INLINABLE _y #-}
| Generator of affine BrainpoolP320R1 curve .
gA :: PA
gA = A _x _y
# INLINABLE gA #
-- | Generator of Jacobian BrainpoolP320R1 curve.
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
-- | Generator of projective BrainpoolP320R1 curve.
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
| null | https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/src/Data/Curve/Weierstrass/BrainpoolP320R1.hs | haskell | * BrainpoolP320R1 curve
-----------------------------------------------------------------------------
Types
-----------------------------------------------------------------------------
| BrainpoolP320R1 curve.
# INLINABLE a_ #
# INLINABLE h_ #
| Affine BrainpoolP320R1 curve point.
| Jacobian BrainpoolP320R1 point.
| Projective BrainpoolP320R1 point.
-----------------------------------------------------------------------------
Parameters
-----------------------------------------------------------------------------
| Coefficient @A@ of BrainpoolP320R1 curve.
# INLINABLE _b #
| Characteristic of BrainpoolP320R1 curve.
# INLINABLE _q #
| Order of BrainpoolP320R1 curve.
# INLINABLE _r #
| Coordinate @X@ of BrainpoolP320R1 curve.
# INLINABLE _x #
# INLINABLE _y #
| Generator of Jacobian BrainpoolP320R1 curve.
| Generator of projective BrainpoolP320R1 curve. | module Data.Curve.Weierstrass.BrainpoolP320R1
( module Data.Curve.Weierstrass
, Point(..)
, module Data.Curve.Weierstrass.BrainpoolP320R1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
data BrainpoolP320R1
| Field of points of BrainpoolP320R1 curve .
type Fq = Prime Q
type Q = 0xd35e472036bc4fb7e13c785ed201e065f98fcfa6f6f40def4f92b9ec7893ec28fcd412b1f1b32e27
| Field of coefficients of BrainpoolP320R1 curve .
type Fr = Prime R
type R = 0xd35e472036bc4fb7e13c785ed201e065f98fcfa5b68f12a32d482ec7ee8658e98691555b44c59311
BrainpoolP320R1 curve is a Weierstrass curve .
instance Curve 'Weierstrass c BrainpoolP320R1 Fq Fr => WCurve c BrainpoolP320R1 Fq Fr where
a_ = const _a
b_ = const _b
# INLINABLE b _ #
h_ = const _h
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
type PA = WAPoint BrainpoolP320R1 Fq Fr
Affine BrainpoolP320R1 curve is a Weierstrass affine curve .
instance WACurve BrainpoolP320R1 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
type PJ = WJPoint BrainpoolP320R1 Fq Fr
Jacobian BrainpoolP320R1 curve is a Weierstrass Jacobian curve .
instance WJCurve BrainpoolP320R1 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
type PP = WPPoint BrainpoolP320R1 Fq Fr
Projective BrainpoolP320R1 curve is a Weierstrass projective curve .
instance WPCurve BrainpoolP320R1 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
_a :: Fq
_a = 0x3ee30b568fbab0f883ccebd46d3f3bb8a2a73513f5eb79da66190eb085ffa9f492f375a97d860eb4
# INLINABLE _ a #
| Coefficient @B@ of BrainpoolP320R1 curve .
_b :: Fq
_b = 0x520883949dfdbc42d3ad198640688a6fe13f41349554b49acc31dccd884539816f5eb4ac8fb1f1a6
| Cofactor of BrainpoolP320R1 curve .
_h :: Natural
_h = 0x1
# INLINABLE _ h #
_q :: Natural
_q = 0xd35e472036bc4fb7e13c785ed201e065f98fcfa6f6f40def4f92b9ec7893ec28fcd412b1f1b32e27
_r :: Natural
_r = 0xd35e472036bc4fb7e13c785ed201e065f98fcfa5b68f12a32d482ec7ee8658e98691555b44c59311
_x :: Fq
_x = 0x43bd7e9afb53d8b85289bcc48ee5bfe6f20137d10a087eb6e7871e2a10a599c710af8d0d39e20611
| Coordinate @Y@ of curve .
_y :: Fq
_y = 0x14fdd05545ec1cc8ab4093247f77275e0743ffed117182eaa9c77877aaac6ac7d35245d1692e8ee1
| Generator of affine BrainpoolP320R1 curve .
gA :: PA
gA = A _x _y
# INLINABLE gA #
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
|
36756d11c5d61709915810997c62c2ae4f6ff2e83fb48099691db82a9b5c0a34 | relaypro-open/imetrics | imetrics_slo.erl | -module(imetrics_slo).
-export([svr_ref/1, uid_name/1,
get/3, add/3, add/4, put/4, dump/1, dump/2, info/1, foldl_dump/3, remove/2]).
-define(CATCH_KNOWN_EXC(X), try
X
catch
exit:{noproc,{gen_server,call, _}} ->
{error, unregistered_slo};
error:badarg ->
{error, {badarg, check_ets}}
end).
svr_ref(UIdName) ->
list_to_atom("imetrics_slo_" ++ atom_to_list(UIdName)).
uid_name(SvrRef) ->
case atom_to_list(SvrRef) of
"imetrics_slo_" ++ UIdNameStr ->
list_to_atom(UIdNameStr)
end.
get(UIdName, UId, Key) ->
?CATCH_KNOWN_EXC(
begin
icount:get(svr_ref(UIdName), imetrics_utils:bin(UId), imetrics_utils:bin(Key))
end
).
add(UIdName, UId, Key) ->
add(UIdName, UId, Key, 1).
add(UIdName, UId, Key, Val) ->
?CATCH_KNOWN_EXC(
begin
icount:add(svr_ref(UIdName), imetrics_utils:bin(UId), imetrics_utils:bin(Key), Val)
end
).
put(UIdName, UId, Key, Val) ->
?CATCH_KNOWN_EXC(
begin
icount:put(svr_ref(UIdName), imetrics_utils:bin(UId), imetrics_utils:bin(Key), Val)
end
).
%% @doc remove/2 is provided for completeness, but will not typically be used. It's only useful
%% if you know a particular UId is no longer relevant and want to manage its lifetime manually.
Otherwise , the icount gc has you covered .
remove(UIdName, UId) ->
?CATCH_KNOWN_EXC(
begin
icount:remove(svr_ref(UIdName), imetrics_utils:bin(UId))
end
).
dump(UIdName) ->
?CATCH_KNOWN_EXC(
begin
icount:dump(svr_ref(UIdName))
end
).
dump(UIdName, UId) ->
?CATCH_KNOWN_EXC(
begin
icount:dump(svr_ref(UIdName), imetrics_utils:bin(UId))
end
).
info(UIdName) ->
?CATCH_KNOWN_EXC(
begin
icount:info(svr_ref(UIdName))
end
).
foldl_dump(UIdName, F, A) ->
?CATCH_KNOWN_EXC(
begin
icount:foldl_dump(svr_ref(UIdName), F, A)
end
).
| null | https://raw.githubusercontent.com/relaypro-open/imetrics/d99bbafce7b564cb4527e42b2e5a23400a412668/src/imetrics_slo.erl | erlang | @doc remove/2 is provided for completeness, but will not typically be used. It's only useful
if you know a particular UId is no longer relevant and want to manage its lifetime manually. | -module(imetrics_slo).
-export([svr_ref/1, uid_name/1,
get/3, add/3, add/4, put/4, dump/1, dump/2, info/1, foldl_dump/3, remove/2]).
-define(CATCH_KNOWN_EXC(X), try
X
catch
exit:{noproc,{gen_server,call, _}} ->
{error, unregistered_slo};
error:badarg ->
{error, {badarg, check_ets}}
end).
svr_ref(UIdName) ->
list_to_atom("imetrics_slo_" ++ atom_to_list(UIdName)).
uid_name(SvrRef) ->
case atom_to_list(SvrRef) of
"imetrics_slo_" ++ UIdNameStr ->
list_to_atom(UIdNameStr)
end.
get(UIdName, UId, Key) ->
?CATCH_KNOWN_EXC(
begin
icount:get(svr_ref(UIdName), imetrics_utils:bin(UId), imetrics_utils:bin(Key))
end
).
add(UIdName, UId, Key) ->
add(UIdName, UId, Key, 1).
add(UIdName, UId, Key, Val) ->
?CATCH_KNOWN_EXC(
begin
icount:add(svr_ref(UIdName), imetrics_utils:bin(UId), imetrics_utils:bin(Key), Val)
end
).
put(UIdName, UId, Key, Val) ->
?CATCH_KNOWN_EXC(
begin
icount:put(svr_ref(UIdName), imetrics_utils:bin(UId), imetrics_utils:bin(Key), Val)
end
).
Otherwise , the icount gc has you covered .
remove(UIdName, UId) ->
?CATCH_KNOWN_EXC(
begin
icount:remove(svr_ref(UIdName), imetrics_utils:bin(UId))
end
).
dump(UIdName) ->
?CATCH_KNOWN_EXC(
begin
icount:dump(svr_ref(UIdName))
end
).
dump(UIdName, UId) ->
?CATCH_KNOWN_EXC(
begin
icount:dump(svr_ref(UIdName), imetrics_utils:bin(UId))
end
).
info(UIdName) ->
?CATCH_KNOWN_EXC(
begin
icount:info(svr_ref(UIdName))
end
).
foldl_dump(UIdName, F, A) ->
?CATCH_KNOWN_EXC(
begin
icount:foldl_dump(svr_ref(UIdName), F, A)
end
).
|
60257ad5a3317d1e44b14766a0a60035c3206b197d2d093aa132a97c642521b9 | Lysxia/twentyseven | Coord.hs | |
Encoding cube projections as @Int@ coordinates .
Explicit dictionary passing style :
using a class would require explicit type annotations /anyway/.
Encoding cube projections as @Int@ coordinates.
Explicit dictionary passing style:
using a class would require explicit type annotations /anyway/.
-}
# LANGUAGE FlexibleInstances , GeneralizedNewtypeDeriving ,
MultiParamTypeClasses , ScopedTypeVariables , ViewPatterns #
MultiParamTypeClasses, ScopedTypeVariables, ViewPatterns #-}
module Rubik.Cube.Coord where
import Rubik.Cube.Cubie.Internal
import Rubik.Misc
import Control.DeepSeq
import Control.Monad.Random
import Control.Newtype
import Data.Binary.Storable
import Data.List
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as MU
import qualified Data.Vector.Storable.Allocated as S
-- * Raw coordinates
-- Unwrapped coordinate
type RawCoord' = Int
MaxInt 2 ^ 29 = 479001600 ( at least , according to the standard )
-- | Encoding to an efficient datatype
-- for which it is possible to build tables
-- instead of computing functions.
newtype RawCoord a = RawCoord { unRawCoord :: RawCoord' }
deriving (Eq, Ord, Show, NFData, Binary)
newtype RawVector a b = RawVector { unRawVector :: U.Vector b }
newtype RawMove a = RawMove { unRawMove :: S.Vector RawCoord' }
deriving (Eq, Ord, Show, NFData, Binary)
instance Newtype (RawCoord a) Int where
pack = RawCoord
unpack = unRawCoord
instance Newtype (RawMove a) (S.Vector Int) where
pack = RawMove
unpack = unRawMove
{-# INLINE (!$) #-}
(!$) :: RawMove a -> RawCoord a -> RawCoord a
RawMove v !$ RawCoord i = RawCoord (v S.! i)
(!.) :: MU.Unbox b => RawVector a b -> RawCoord a -> b
RawVector v !. RawCoord i = v U.! i
-- * Dictionaries
-- | Encoding dictionary.
--
-- Probably synonymous with instances for both
@('Enum ' a , ' Bounded ' a)@.
--
-- > inRange (range d) $ encode x
-- > encode . decode == id
-- > decode . encode == id
--
-- A special constructor for dictionaries of product types
-- is particularly useful to create tables of functions
-- if their actions on every projection are independent.
--
class RawEncodable a where
-- | Number of elements that can be converted.
-- Their values are to lie in @[0 .. range c - 1]@.
range :: proxy a -> Int
encode :: a -> RawCoord a
decode :: RawCoord a -> a
-- ** Instances
-- | The number of elements of every set is given.
| @8 ! = 40320@
instance RawEncodable CornerPermu where
range _ = 40320
encode = RawCoord . encodeFact numCorners . U.toList . fromCornerPermu
decode = unsafeCornerPermu' . decodeFact numCorners numCorners . unRawCoord
| @12 ! = 479001600@
--
-- A bit too much to hold in memory.
--
Holds just right in a Haskell @Int@ ( @maxInt > = 2 ^ 29 - 1@ ) .
instance RawEncodable EdgePermu where
range _ = 479001600
encode = RawCoord . encodeFact numEdges . U.toList . fromEdgePermu
decode = unsafeEdgePermu' . decodeFact numEdges numEdges . unRawCoord
| @3 ^ 7 = 2187@
instance RawEncodable CornerOrien where
range _ = 2187
encode = RawCoord . encodeBaseV 3 . U.tail . fromCornerOrien
The first orientation can be deduced from the others in a solvable cube
decode (RawCoord x) = unsafeCornerOrien' (h : t)
where h = (3 - sum t) `mod` 3
t = decodeBase 3 (numCorners - 1) x
| @2 ^ 11 = 2048@
instance RawEncodable EdgeOrien where
range _ = 2048
encode = RawCoord . encodeEdgeOrien' . fromEdgeOrien
decode (RawCoord x) = unsafeEdgeOrien' (h : t)
where h = sum t `mod` 2
t = decodeBase 2 (numEdges - 1) x
encodeEdgeOrien' = encodeBaseV 2 . U.tail
numUDS = numUDSliceEdges
numUDE = numEdges - numUDS
| 12 ! / 8 ! = 11880
instance RawEncodable UDSlicePermu where
range _ = 11880
encode = RawCoord . encodeFact numEdges . U.toList . fromUDSlicePermu
decode = unsafeUDSlicePermu' . decodeFact numEdges numUDS . unRawCoord
| @12C4 = 495@
instance RawEncodable UDSlice where
range _ = 495
encode = RawCoord . encodeCV . fromUDSlice
decode = unsafeUDSlice . decodeCV numUDS . unRawCoord
| @4 ! = 24@
instance RawEncodable UDSlicePermu2 where
range _ = 24
encode = RawCoord . encodeFact numUDS . U.toList . fromUDSlicePermu2
decode = unsafeUDSlicePermu2' . decodeFact numUDS numUDS . unRawCoord
| @8 ! = 40320@
instance RawEncodable UDEdgePermu2 where
range _ = 40320
encode = RawCoord . encodeFact numUDE . U.toList . fromUDEdgePermu2
decode = unsafeUDEdgePermu2' . decodeFact numUDE numUDE . unRawCoord
instance (RawEncodable a, RawEncodable b) => RawEncodable (a, b) where
range _ = range ([] :: [a]) * range ([] :: [b])
encode (a, b) = flatCoord (encode a) (encode b)
decode (splitCoord -> (a, b)) = (decode a, decode b)
# INLINE flatCoord #
flatCoord
:: (RawEncodable a, RawEncodable b)
=> RawCoord a -> RawCoord b -> RawCoord (a, b)
flatCoord (RawCoord a) b'@(RawCoord b) = RawCoord (flatIndex (range b') a b)
# INLINE splitCoord #
splitCoord
:: (RawEncodable a, RawEncodable b)
=> RawCoord (a, b) -> (RawCoord a, RawCoord b)
splitCoord (RawCoord ab_) = (a, b)
where
(RawCoord -> a, RawCoord -> b) = ab_ `divMod` range b
-- * Table building
-- | Endofunctions
type Endo a = a -> a
-- | Lift an endofunction to its coordinate representation,
-- the dictionary provides a @RawCoord@ encoding.
--
That is , we construct a vector @v@ such that , basically ,
--
-- > decode (v ! encode x) == f x
--
-- So function application becomes simply vector indexing.
endoVector :: RawEncodable a => Endo a -> RawMove a
endoVector f
= RawMove . S.generate (range f) $
under RawCoord (encode . f . decode)
-- | The 'cubeAction' method is partially applied to a 'Cube'
-- and turned into an 'Endo' function.
--
The ' CA a ' type argument controls the refinement of the endofunction .
cubeActionToEndo :: CubeAction a => Cube -> Endo a
cubeActionToEndo c = (`cubeAction` c)
-- | Composition of 'endoVector' and 'cubeAction'.
moveTable :: (CubeAction a, RawEncodable a) => Cube -> RawMove a
moveTable = endoVector . cubeActionToEndo
symToEndo :: (Cube -> a -> a) -> Cube -> Endo a
symToEndo = id
symTable :: RawEncodable a => (Cube -> a -> a) -> Cube -> RawMove a
symTable conj = endoVector . symToEndo conj
-- * Miscellaneous
-- | Checks over the range @range@ that:
--
-- > encode . decode == id
--
checkCoord :: RawEncodable a => proxy a -> Bool
checkCoord proxy
= all (\(RawCoord -> k) -> encode (decode k `asProxyTypeOf` proxy) == k)
[0 .. range proxy - 1]
randomRawCoord :: forall a m. (MonadRandom m, RawEncodable a) => m (RawCoord a)
randomRawCoord = RawCoord <$> getRandomR (0, range ([] :: [a]) - 1)
-- * Helper
-- | Helper functions to define the dictionaries
-- ** Fixed base
-- | If
-- @all (`elem` [0 .. b-1]) v@
then @v@ is the base @b@ representation of
-- @encode b v@
-- such that its least significant digit is @head v@.
--
For any @n@ , @encodeBase b@ is a bijection from lists of length @n@
-- with elements in @[0 .. b-1]@ to @[0 .. b^n - 1]@
encodeBase :: Int -> [Int] -> Int
encodeBase b = foldr1 (\x y -> x + b * y)
-- | Vector version of 'encodeBase'.
encodeBaseV :: Int -> Vector Int -> Int
encodeBaseV b = U.foldr1' (\x y -> x + b * y)
| @len@ is the length of the resulting vector
--
-- > encodeBase b . decodeBase b len == id
-- > decodeBase b len . encodeBase b == id
--
decodeBase :: Int -> Int -> Int -> [Int]
decodeBase b len = take len . unfoldr (\x -> Just (x `modDiv` b))
where modDiv = ((.).(.)) (\(x,y) -> (y,x)) divMod
-- ** Factorial radix
-- | Input list must be a @k@-permutation of @[0 .. n-1]@.
--
-- @encodeFact@ is a bijection between k-permutations of @[0 .. n-1]@
and @[0 .. ( fact n / fact ( n - k ) ) - 1]@.
encodeFact :: Int -> [Int] -> Int
encodeFact n [] = 0
encodeFact n (y : ys) = y + n * encodeFact (n - 1) ys'
where
ys' = case elemIndex (n - 1) ys of
Nothing -> ys -- y == n - 1
Just k -> subs k y ys -- recovers a subpermutation of @[0 .. n-2]@
-- | Inverse of 'encodeFact'.
--
-- > encodeFact n . decodeFact n k == id -- k <= n
-- > decodeFact n k . encodeFact n == id -- on k-permutations
--
decodeFact :: Int -> Int -> Int -> [Int]
decodeFact n 0 _ = []
decodeFact n k x = y : ys
where
(q, y) = x `divMod` n
ys' = decodeFact (n - 1) (k - 1) q
ys = case elemIndex y ys' of
Nothing -> ys' -- y == n - 1
Just k -> subs k (n - 1) ys'
-- ** Binomial enumeration
Bijection between @[0 .. choose n ( k-1)]@
and of @[0 .. n-1]@.
-- | > cSum k z == sum [y `choose` k | y <- [k .. z-1]]
--
requires @k < cSum_mMaz@ and < cSum_nMaz@.
cSum :: Int -> Int -> Int
cSum = \k z -> v U.! (k * n + z)
where
cSum' k z = sum [y `choose` k | y <- [k .. z-1]]
v = U.generate (n * m) (uncurry cSum' . (`divMod` n))
m = cSum_mMax
n = cSum_nMax
| Bound on arguments accepted by @cSum@
cSum_mMax, cSum_nMax :: Int
cSum_mMax = 4
cSum_nMax = 16
-- | > encodeCV <y 0 .. y k> == encodeCV <y 0 .. y (k-1)> + cSum k (y k)
--
where @c@ is a @k@-combination ,
-- that is a sorted list of @k@ nonnegative elements.
--
-- @encodeCV@ is in fact a bijection between increasing lists
-- (of non-negative integers) and integers.
--
Restriction : @k < cSum_mMax@ , @y k < cSum_nMax@.
encodeCV :: Vector Int -> Int
encodeCV = U.sum . U.imap cSum
-- | Inverse of 'encodeCV'.
--
-- The length of the resulting list must be supplied as a hint
-- (although it could technically be guessed).
decodeCV :: Int -> Int -> Vector Int
decodeCV k x = U.create (do
v <- MU.new k
let
decode' (-1) _ _ = return ()
decode' k z x
| s <= x = MU.write v k z >> decode' (k-1) (z-1) (x-s)
| otherwise = decode' k (z-1) x
where
s = cSum k z
decode' (k-1) (cSum_nMax-1) x
return v)
| null | https://raw.githubusercontent.com/Lysxia/twentyseven/bfcd3ddcf938bc6db933a364d331877b0fd1257e/src/Rubik/Cube/Coord.hs | haskell | * Raw coordinates
Unwrapped coordinate
| Encoding to an efficient datatype
for which it is possible to build tables
instead of computing functions.
# INLINE (!$) #
* Dictionaries
| Encoding dictionary.
Probably synonymous with instances for both
> inRange (range d) $ encode x
> encode . decode == id
> decode . encode == id
A special constructor for dictionaries of product types
is particularly useful to create tables of functions
if their actions on every projection are independent.
| Number of elements that can be converted.
Their values are to lie in @[0 .. range c - 1]@.
** Instances
| The number of elements of every set is given.
A bit too much to hold in memory.
* Table building
| Endofunctions
| Lift an endofunction to its coordinate representation,
the dictionary provides a @RawCoord@ encoding.
> decode (v ! encode x) == f x
So function application becomes simply vector indexing.
| The 'cubeAction' method is partially applied to a 'Cube'
and turned into an 'Endo' function.
| Composition of 'endoVector' and 'cubeAction'.
* Miscellaneous
| Checks over the range @range@ that:
> encode . decode == id
* Helper
| Helper functions to define the dictionaries
** Fixed base
| If
@all (`elem` [0 .. b-1]) v@
@encode b v@
such that its least significant digit is @head v@.
with elements in @[0 .. b-1]@ to @[0 .. b^n - 1]@
| Vector version of 'encodeBase'.
> encodeBase b . decodeBase b len == id
> decodeBase b len . encodeBase b == id
** Factorial radix
| Input list must be a @k@-permutation of @[0 .. n-1]@.
@encodeFact@ is a bijection between k-permutations of @[0 .. n-1]@
y == n - 1
recovers a subpermutation of @[0 .. n-2]@
| Inverse of 'encodeFact'.
> encodeFact n . decodeFact n k == id -- k <= n
> decodeFact n k . encodeFact n == id -- on k-permutations
y == n - 1
** Binomial enumeration
| > cSum k z == sum [y `choose` k | y <- [k .. z-1]]
| > encodeCV <y 0 .. y k> == encodeCV <y 0 .. y (k-1)> + cSum k (y k)
that is a sorted list of @k@ nonnegative elements.
@encodeCV@ is in fact a bijection between increasing lists
(of non-negative integers) and integers.
| Inverse of 'encodeCV'.
The length of the resulting list must be supplied as a hint
(although it could technically be guessed). | |
Encoding cube projections as @Int@ coordinates .
Explicit dictionary passing style :
using a class would require explicit type annotations /anyway/.
Encoding cube projections as @Int@ coordinates.
Explicit dictionary passing style:
using a class would require explicit type annotations /anyway/.
-}
# LANGUAGE FlexibleInstances , GeneralizedNewtypeDeriving ,
MultiParamTypeClasses , ScopedTypeVariables , ViewPatterns #
MultiParamTypeClasses, ScopedTypeVariables, ViewPatterns #-}
module Rubik.Cube.Coord where
import Rubik.Cube.Cubie.Internal
import Rubik.Misc
import Control.DeepSeq
import Control.Monad.Random
import Control.Newtype
import Data.Binary.Storable
import Data.List
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as MU
import qualified Data.Vector.Storable.Allocated as S
type RawCoord' = Int
MaxInt 2 ^ 29 = 479001600 ( at least , according to the standard )
newtype RawCoord a = RawCoord { unRawCoord :: RawCoord' }
deriving (Eq, Ord, Show, NFData, Binary)
newtype RawVector a b = RawVector { unRawVector :: U.Vector b }
newtype RawMove a = RawMove { unRawMove :: S.Vector RawCoord' }
deriving (Eq, Ord, Show, NFData, Binary)
instance Newtype (RawCoord a) Int where
pack = RawCoord
unpack = unRawCoord
instance Newtype (RawMove a) (S.Vector Int) where
pack = RawMove
unpack = unRawMove
(!$) :: RawMove a -> RawCoord a -> RawCoord a
RawMove v !$ RawCoord i = RawCoord (v S.! i)
(!.) :: MU.Unbox b => RawVector a b -> RawCoord a -> b
RawVector v !. RawCoord i = v U.! i
@('Enum ' a , ' Bounded ' a)@.
class RawEncodable a where
range :: proxy a -> Int
encode :: a -> RawCoord a
decode :: RawCoord a -> a
| @8 ! = 40320@
instance RawEncodable CornerPermu where
range _ = 40320
encode = RawCoord . encodeFact numCorners . U.toList . fromCornerPermu
decode = unsafeCornerPermu' . decodeFact numCorners numCorners . unRawCoord
| @12 ! = 479001600@
Holds just right in a Haskell @Int@ ( @maxInt > = 2 ^ 29 - 1@ ) .
instance RawEncodable EdgePermu where
range _ = 479001600
encode = RawCoord . encodeFact numEdges . U.toList . fromEdgePermu
decode = unsafeEdgePermu' . decodeFact numEdges numEdges . unRawCoord
| @3 ^ 7 = 2187@
instance RawEncodable CornerOrien where
range _ = 2187
encode = RawCoord . encodeBaseV 3 . U.tail . fromCornerOrien
The first orientation can be deduced from the others in a solvable cube
decode (RawCoord x) = unsafeCornerOrien' (h : t)
where h = (3 - sum t) `mod` 3
t = decodeBase 3 (numCorners - 1) x
| @2 ^ 11 = 2048@
instance RawEncodable EdgeOrien where
range _ = 2048
encode = RawCoord . encodeEdgeOrien' . fromEdgeOrien
decode (RawCoord x) = unsafeEdgeOrien' (h : t)
where h = sum t `mod` 2
t = decodeBase 2 (numEdges - 1) x
encodeEdgeOrien' = encodeBaseV 2 . U.tail
numUDS = numUDSliceEdges
numUDE = numEdges - numUDS
| 12 ! / 8 ! = 11880
instance RawEncodable UDSlicePermu where
range _ = 11880
encode = RawCoord . encodeFact numEdges . U.toList . fromUDSlicePermu
decode = unsafeUDSlicePermu' . decodeFact numEdges numUDS . unRawCoord
| @12C4 = 495@
instance RawEncodable UDSlice where
range _ = 495
encode = RawCoord . encodeCV . fromUDSlice
decode = unsafeUDSlice . decodeCV numUDS . unRawCoord
| @4 ! = 24@
instance RawEncodable UDSlicePermu2 where
range _ = 24
encode = RawCoord . encodeFact numUDS . U.toList . fromUDSlicePermu2
decode = unsafeUDSlicePermu2' . decodeFact numUDS numUDS . unRawCoord
| @8 ! = 40320@
instance RawEncodable UDEdgePermu2 where
range _ = 40320
encode = RawCoord . encodeFact numUDE . U.toList . fromUDEdgePermu2
decode = unsafeUDEdgePermu2' . decodeFact numUDE numUDE . unRawCoord
instance (RawEncodable a, RawEncodable b) => RawEncodable (a, b) where
range _ = range ([] :: [a]) * range ([] :: [b])
encode (a, b) = flatCoord (encode a) (encode b)
decode (splitCoord -> (a, b)) = (decode a, decode b)
# INLINE flatCoord #
flatCoord
:: (RawEncodable a, RawEncodable b)
=> RawCoord a -> RawCoord b -> RawCoord (a, b)
flatCoord (RawCoord a) b'@(RawCoord b) = RawCoord (flatIndex (range b') a b)
# INLINE splitCoord #
splitCoord
:: (RawEncodable a, RawEncodable b)
=> RawCoord (a, b) -> (RawCoord a, RawCoord b)
splitCoord (RawCoord ab_) = (a, b)
where
(RawCoord -> a, RawCoord -> b) = ab_ `divMod` range b
type Endo a = a -> a
That is , we construct a vector @v@ such that , basically ,
endoVector :: RawEncodable a => Endo a -> RawMove a
endoVector f
= RawMove . S.generate (range f) $
under RawCoord (encode . f . decode)
The ' CA a ' type argument controls the refinement of the endofunction .
cubeActionToEndo :: CubeAction a => Cube -> Endo a
cubeActionToEndo c = (`cubeAction` c)
moveTable :: (CubeAction a, RawEncodable a) => Cube -> RawMove a
moveTable = endoVector . cubeActionToEndo
symToEndo :: (Cube -> a -> a) -> Cube -> Endo a
symToEndo = id
symTable :: RawEncodable a => (Cube -> a -> a) -> Cube -> RawMove a
symTable conj = endoVector . symToEndo conj
checkCoord :: RawEncodable a => proxy a -> Bool
checkCoord proxy
= all (\(RawCoord -> k) -> encode (decode k `asProxyTypeOf` proxy) == k)
[0 .. range proxy - 1]
randomRawCoord :: forall a m. (MonadRandom m, RawEncodable a) => m (RawCoord a)
randomRawCoord = RawCoord <$> getRandomR (0, range ([] :: [a]) - 1)
then @v@ is the base @b@ representation of
For any @n@ , @encodeBase b@ is a bijection from lists of length @n@
encodeBase :: Int -> [Int] -> Int
encodeBase b = foldr1 (\x y -> x + b * y)
encodeBaseV :: Int -> Vector Int -> Int
encodeBaseV b = U.foldr1' (\x y -> x + b * y)
| @len@ is the length of the resulting vector
decodeBase :: Int -> Int -> Int -> [Int]
decodeBase b len = take len . unfoldr (\x -> Just (x `modDiv` b))
where modDiv = ((.).(.)) (\(x,y) -> (y,x)) divMod
and @[0 .. ( fact n / fact ( n - k ) ) - 1]@.
encodeFact :: Int -> [Int] -> Int
encodeFact n [] = 0
encodeFact n (y : ys) = y + n * encodeFact (n - 1) ys'
where
ys' = case elemIndex (n - 1) ys of
decodeFact :: Int -> Int -> Int -> [Int]
decodeFact n 0 _ = []
decodeFact n k x = y : ys
where
(q, y) = x `divMod` n
ys' = decodeFact (n - 1) (k - 1) q
ys = case elemIndex y ys' of
Just k -> subs k (n - 1) ys'
Bijection between @[0 .. choose n ( k-1)]@
and of @[0 .. n-1]@.
requires @k < cSum_mMaz@ and < cSum_nMaz@.
cSum :: Int -> Int -> Int
cSum = \k z -> v U.! (k * n + z)
where
cSum' k z = sum [y `choose` k | y <- [k .. z-1]]
v = U.generate (n * m) (uncurry cSum' . (`divMod` n))
m = cSum_mMax
n = cSum_nMax
| Bound on arguments accepted by @cSum@
cSum_mMax, cSum_nMax :: Int
cSum_mMax = 4
cSum_nMax = 16
where @c@ is a @k@-combination ,
Restriction : @k < cSum_mMax@ , @y k < cSum_nMax@.
encodeCV :: Vector Int -> Int
encodeCV = U.sum . U.imap cSum
decodeCV :: Int -> Int -> Vector Int
decodeCV k x = U.create (do
v <- MU.new k
let
decode' (-1) _ _ = return ()
decode' k z x
| s <= x = MU.write v k z >> decode' (k-1) (z-1) (x-s)
| otherwise = decode' k (z-1) x
where
s = cSum k z
decode' (k-1) (cSum_nMax-1) x
return v)
|
9b7b9e42cb1a53996250853e972514670e1ff029e9de8e53807b786ed2a66c36 | replikativ/datahike-jdbc | core_test.cljc | (ns datahike-jdbc.core-test
(:require
#?(:cljs [cljs.test :as t :refer-macros [is are deftest testing]]
:clj [clojure.test :as t :refer [is are deftest testing]])
[datahike.api :as d]
[datahike-jdbc.core]))
(deftest ^:integration test-postgresql
(let [config {:store {:backend :jdbc
:dbtype "postgresql"
:host "localhost"
:dbname "config-test"
:user "alice"
:password "foo"}
:schema-flexibility :read
:keep-history? false}
_ (d/delete-database config)]
(is (not (d/database-exists? config)))
(let [_ (d/create-database config)
conn (d/connect config)]
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists? config))
(d/delete-database config)
(is (not (d/database-exists? config))))))
(deftest ^:integration test-mysql
(let [config {:store {:backend :jdbc
:dbtype "mysql"
:user "alice"
:password "foo"
:dbname "config-test"}
:schema-flexibility :write
:keep-history? false}
_ (d/delete-database config)]
(is (not (d/database-exists? config)))
(let [_ (d/create-database config)
conn (d/connect config)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists? config))
(d/delete-database config)
(is (not (d/database-exists? config))))))
(deftest ^:integration test-mssql
(let [config {:store {:backend :jdbc
:dbtype "sqlserver"
:user "sa"
:password "passwordA1!"
:dbname "tempdb"}
:schema-flexibility :write
:keep-history? false}
_ (d/delete-database config)]
(is (not (d/database-exists? config)))
(let [_ (d/create-database config)
conn (d/connect config)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists? config))
(d/delete-database config)
(is (not (d/database-exists? config))))))
(deftest ^:integration test-h2
(let [config {:store {:backend :jdbc
:dbtype "h2"
:dbname "./temp/db"}
:schema-flexibility :write
:keep-history? false}
_ (d/delete-database config)]
(is (not (d/database-exists? config)))
(let [_ (d/create-database config)
conn (d/connect config)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists? config))
(d/delete-database config)
(is (not (d/database-exists? config))))))
(deftest ^:integration test-env
(let [_ (d/delete-database)]
(is (not (d/database-exists?)))
(let [_ (d/create-database)
conn (d/connect)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists?))
(d/delete-database)
(is (not (d/database-exists?))))))
| null | https://raw.githubusercontent.com/replikativ/datahike-jdbc/6903e1bb81551a50c5b1fb9097d7d411dd00ff97/test/datahike_jdbc/core_test.cljc | clojure | (ns datahike-jdbc.core-test
(:require
#?(:cljs [cljs.test :as t :refer-macros [is are deftest testing]]
:clj [clojure.test :as t :refer [is are deftest testing]])
[datahike.api :as d]
[datahike-jdbc.core]))
(deftest ^:integration test-postgresql
(let [config {:store {:backend :jdbc
:dbtype "postgresql"
:host "localhost"
:dbname "config-test"
:user "alice"
:password "foo"}
:schema-flexibility :read
:keep-history? false}
_ (d/delete-database config)]
(is (not (d/database-exists? config)))
(let [_ (d/create-database config)
conn (d/connect config)]
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists? config))
(d/delete-database config)
(is (not (d/database-exists? config))))))
(deftest ^:integration test-mysql
(let [config {:store {:backend :jdbc
:dbtype "mysql"
:user "alice"
:password "foo"
:dbname "config-test"}
:schema-flexibility :write
:keep-history? false}
_ (d/delete-database config)]
(is (not (d/database-exists? config)))
(let [_ (d/create-database config)
conn (d/connect config)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists? config))
(d/delete-database config)
(is (not (d/database-exists? config))))))
(deftest ^:integration test-mssql
(let [config {:store {:backend :jdbc
:dbtype "sqlserver"
:user "sa"
:password "passwordA1!"
:dbname "tempdb"}
:schema-flexibility :write
:keep-history? false}
_ (d/delete-database config)]
(is (not (d/database-exists? config)))
(let [_ (d/create-database config)
conn (d/connect config)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists? config))
(d/delete-database config)
(is (not (d/database-exists? config))))))
(deftest ^:integration test-h2
(let [config {:store {:backend :jdbc
:dbtype "h2"
:dbname "./temp/db"}
:schema-flexibility :write
:keep-history? false}
_ (d/delete-database config)]
(is (not (d/database-exists? config)))
(let [_ (d/create-database config)
conn (d/connect config)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists? config))
(d/delete-database config)
(is (not (d/database-exists? config))))))
(deftest ^:integration test-env
(let [_ (d/delete-database)]
(is (not (d/database-exists?)))
(let [_ (d/create-database)
conn (d/connect)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
(d/transact conn [{:db/id 1, :name "Ivan", :age 15}
{:db/id 2, :name "Petr", :age 37}
{:db/id 3, :name "Ivan", :age 37}
{:db/id 4, :age 15}])
(is (= (d/q '[:find ?e :where [?e :name]] @conn)
#{[3] [2] [1]}))
(d/release conn)
(is (d/database-exists?))
(d/delete-database)
(is (not (d/database-exists?))))))
|
|
b0f2c1996913041c30a85b6ba6fd1ffec766102ad6e9be9e358cfbe35ae67e30 | RedBrainLabs/system-graph | system_graph_test.clj | (ns com.redbrainlabs.system-graph-test
(:require [com.stuartsierra.component :refer [Lifecycle] :as component]
[plumbing.core :refer [fnk]]
[midje.sweet :refer :all]
[com.redbrainlabs.system-graph :refer :all]))
(def lifecycle-sort :com.redbrainlabs.system-graph/lifecycle-sort)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Integration tests ... since this library is 100 % glue
(defrecord Lifecycler [!started !stopped key value]
Lifecycle
(start [this]
(swap! !started conj key)
this)
(stop [this]
(swap! !stopped conj key)
this))
(facts "system-graph"
(let [deps-started (atom [])
deps-stopped (atom [])
lifecycler (partial ->Lifecycler deps-started deps-stopped)
subgraph {:x-squared (fnk [x] (lifecycler :x-squared (* x x)))
:x-cubed (fnk [x x-squared] ;;(prn {:x x :x-squared x-squared})
(lifecycler :x-cubed (* x (:value x-squared))))}
graph {:subgraph subgraph
:y (fnk [[:subgraph x-cubed]] (lifecycler :y (inc (:value x-cubed))))
:x-inc (fnk [x] (lifecycler :x-inc (inc x)))
:no-lifecycle (fnk [x-inc] :something-that-doesnt-implement-lifecycle)}
system-graph (init-system graph {:x 4})]
(fact "starts the lifecycle deps using a toposort"
(component/start system-graph)
@deps-started => [:x-squared :x-cubed :y :x-inc])
(fact "stops the deps in the opposite order"
(component/stop system-graph)
@deps-stopped => [:x-inc :y :x-cubed :x-squared])))
(defrecord DummyComponent [name started]
Lifecycle
(start [this] (assoc this :started true))
(stop [this] (assoc this :started false)))
(defn dummy-component [name]
(->DummyComponent name false))
(facts "dependent components"
(let [graph {:a (fnk []
(dummy-component :a))
:b (fnk [a]
(-> (dummy-component :b)
(assoc :a a)))}
system-graph (init-system graph {})
started-system (start-system system-graph)]
(facts "are passed in to fnks before they are started"
(:b system-graph) => (just {:a {:name :a, :started false}, :name :b, :started false}))
(facts "are started and assoced onto lifecycle components before then dependent's #'start is called"
(:b started-system) => (just {:a {:name :a, :started true}, :name :b, :started true}))))
(facts "dependent components with different names that the system's names"
(let [graph {:a (fnk []
(dummy-component :a))
:b (-> (fnk [a]
(-> (dummy-component :b)
(assoc :foo a)))
(component/using {:foo :a}))}
system-graph (init-system graph {})
started-system (start-system system-graph)]
(facts "are passed in to fnks before they are started"
(:b system-graph) => (just {:foo {:name :a, :started false}, :name :b, :started false}))
(facts "are started and assoced onto lifecycle components with the different name before then dependent's #'start is called"
(:b started-system) => (just {:foo {:name :a, :started true}, :name :b, :started true}))))
(defrecord StatefulDummyComponent [name started !counter]
Lifecycle
(start [this] (swap! !counter update-in [:started] inc) (assoc this :started true))
(stop [this] (swap! !counter update-in [:stopped] inc) (assoc this :started false)))
(defn stateful-dummy-component [name]
(->StatefulDummyComponent name false (atom {:started 0 :stopped 0})))
(facts "systems can be started and stopped multiple times"
(let [graph {:a (fnk []
(stateful-dummy-component :a))
:b (fnk [a]
(-> (stateful-dummy-component :b)
(assoc :a a)))}
system-graph (init-system graph {})
cycled-system (reduce (fn [sys _] (-> sys start-system stop-system)) system-graph (range 5))]
(-> cycled-system :a :!counter deref) => {:started 5, :stopped 5}
(-> cycled-system start-system :b :a :started) => true
(-> cycled-system start-system stop-system :b :started) => false
;; TODO: investgate this to see if this is a system-graph bug or component..
;; it looks like component doesn't assoc the deps on stop.. but the newer version says it does..
;; (-> cycled-system start-system stop-system :b :a :started) => false
))
| null | https://raw.githubusercontent.com/RedBrainLabs/system-graph/928d5d7de34047e54b0f05d33cf5104d0d9be53a/test/com/redbrainlabs/system_graph_test.clj | clojure |
(prn {:x x :x-squared x-squared})
TODO: investgate this to see if this is a system-graph bug or component..
it looks like component doesn't assoc the deps on stop.. but the newer version says it does..
(-> cycled-system start-system stop-system :b :a :started) => false | (ns com.redbrainlabs.system-graph-test
(:require [com.stuartsierra.component :refer [Lifecycle] :as component]
[plumbing.core :refer [fnk]]
[midje.sweet :refer :all]
[com.redbrainlabs.system-graph :refer :all]))
(def lifecycle-sort :com.redbrainlabs.system-graph/lifecycle-sort)
Integration tests ... since this library is 100 % glue
(defrecord Lifecycler [!started !stopped key value]
Lifecycle
(start [this]
(swap! !started conj key)
this)
(stop [this]
(swap! !stopped conj key)
this))
(facts "system-graph"
(let [deps-started (atom [])
deps-stopped (atom [])
lifecycler (partial ->Lifecycler deps-started deps-stopped)
subgraph {:x-squared (fnk [x] (lifecycler :x-squared (* x x)))
(lifecycler :x-cubed (* x (:value x-squared))))}
graph {:subgraph subgraph
:y (fnk [[:subgraph x-cubed]] (lifecycler :y (inc (:value x-cubed))))
:x-inc (fnk [x] (lifecycler :x-inc (inc x)))
:no-lifecycle (fnk [x-inc] :something-that-doesnt-implement-lifecycle)}
system-graph (init-system graph {:x 4})]
(fact "starts the lifecycle deps using a toposort"
(component/start system-graph)
@deps-started => [:x-squared :x-cubed :y :x-inc])
(fact "stops the deps in the opposite order"
(component/stop system-graph)
@deps-stopped => [:x-inc :y :x-cubed :x-squared])))
(defrecord DummyComponent [name started]
Lifecycle
(start [this] (assoc this :started true))
(stop [this] (assoc this :started false)))
(defn dummy-component [name]
(->DummyComponent name false))
(facts "dependent components"
(let [graph {:a (fnk []
(dummy-component :a))
:b (fnk [a]
(-> (dummy-component :b)
(assoc :a a)))}
system-graph (init-system graph {})
started-system (start-system system-graph)]
(facts "are passed in to fnks before they are started"
(:b system-graph) => (just {:a {:name :a, :started false}, :name :b, :started false}))
(facts "are started and assoced onto lifecycle components before then dependent's #'start is called"
(:b started-system) => (just {:a {:name :a, :started true}, :name :b, :started true}))))
(facts "dependent components with different names that the system's names"
(let [graph {:a (fnk []
(dummy-component :a))
:b (-> (fnk [a]
(-> (dummy-component :b)
(assoc :foo a)))
(component/using {:foo :a}))}
system-graph (init-system graph {})
started-system (start-system system-graph)]
(facts "are passed in to fnks before they are started"
(:b system-graph) => (just {:foo {:name :a, :started false}, :name :b, :started false}))
(facts "are started and assoced onto lifecycle components with the different name before then dependent's #'start is called"
(:b started-system) => (just {:foo {:name :a, :started true}, :name :b, :started true}))))
(defrecord StatefulDummyComponent [name started !counter]
Lifecycle
(start [this] (swap! !counter update-in [:started] inc) (assoc this :started true))
(stop [this] (swap! !counter update-in [:stopped] inc) (assoc this :started false)))
(defn stateful-dummy-component [name]
(->StatefulDummyComponent name false (atom {:started 0 :stopped 0})))
(facts "systems can be started and stopped multiple times"
(let [graph {:a (fnk []
(stateful-dummy-component :a))
:b (fnk [a]
(-> (stateful-dummy-component :b)
(assoc :a a)))}
system-graph (init-system graph {})
cycled-system (reduce (fn [sys _] (-> sys start-system stop-system)) system-graph (range 5))]
(-> cycled-system :a :!counter deref) => {:started 5, :stopped 5}
(-> cycled-system start-system :b :a :started) => true
(-> cycled-system start-system stop-system :b :started) => false
))
|
795f4dd6aa06ef5612a6f74b24bea42ca244e9fdec95dace4ea1956899fd1201 | clj-commons/potemkin | macros.clj | (ns potemkin.macros
(:require
[potemkin.walk :refer (postwalk)]
[riddley.walk :as r]))
(defn safe-resolve [x]
(try
(resolve x)
(catch Exception _
nil)))
(def unified-gensym-regex #"([a-zA-Z0-9\-\'\*]+)#__\d+__auto__$")
(def gensym-regex #"(_|[a-zA-Z0-9\-\'\*]+)#?_+(\d+_*#?)+(auto__)?$")
(defn unified-gensym? [s]
(and
(symbol? s)
(re-find unified-gensym-regex (str s))))
(defn gensym? [s]
(and
(symbol? s)
(re-find gensym-regex (str s))))
(defn un-gensym [s]
(second (re-find gensym-regex (str s))))
(defn unify-gensyms
"All gensyms defined using two hash symbols are unified to the same
value, even if they were defined within different syntax-quote scopes."
[body]
(let [gensym* (memoize gensym)]
(postwalk
#(if (unified-gensym? %)
(symbol (str (gensym* (str (un-gensym %) "__")) "__auto__"))
%)
body)))
(defn normalize-gensyms
[body]
(let [cnt (atom 0)
gensym* #(str % "__norm__" (swap! cnt inc))]
(postwalk
#(if (gensym? %)
(symbol (gensym* (un-gensym %)))
%)
body)))
(defn equivalent?
[a b]
(if-not (and a b)
(= a b)
(=
(->> a r/macroexpand-all normalize-gensyms)
(->> b r/macroexpand-all normalize-gensyms))))
| null | https://raw.githubusercontent.com/clj-commons/potemkin/3e404364ae2fd32f7a53b362a79d2012ab958ab2/src/potemkin/macros.clj | clojure | (ns potemkin.macros
(:require
[potemkin.walk :refer (postwalk)]
[riddley.walk :as r]))
(defn safe-resolve [x]
(try
(resolve x)
(catch Exception _
nil)))
(def unified-gensym-regex #"([a-zA-Z0-9\-\'\*]+)#__\d+__auto__$")
(def gensym-regex #"(_|[a-zA-Z0-9\-\'\*]+)#?_+(\d+_*#?)+(auto__)?$")
(defn unified-gensym? [s]
(and
(symbol? s)
(re-find unified-gensym-regex (str s))))
(defn gensym? [s]
(and
(symbol? s)
(re-find gensym-regex (str s))))
(defn un-gensym [s]
(second (re-find gensym-regex (str s))))
(defn unify-gensyms
"All gensyms defined using two hash symbols are unified to the same
value, even if they were defined within different syntax-quote scopes."
[body]
(let [gensym* (memoize gensym)]
(postwalk
#(if (unified-gensym? %)
(symbol (str (gensym* (str (un-gensym %) "__")) "__auto__"))
%)
body)))
(defn normalize-gensyms
[body]
(let [cnt (atom 0)
gensym* #(str % "__norm__" (swap! cnt inc))]
(postwalk
#(if (gensym? %)
(symbol (gensym* (un-gensym %)))
%)
body)))
(defn equivalent?
[a b]
(if-not (and a b)
(= a b)
(=
(->> a r/macroexpand-all normalize-gensyms)
(->> b r/macroexpand-all normalize-gensyms))))
|
|
7659fb39d67052340b8056180536c663302b384d8d8c14ecdac1138dba8169da | khotyn/4clojure-answer | 20-penultimate-element.clj | (fn [x] (nth x (- (count x) 2)))
| null | https://raw.githubusercontent.com/khotyn/4clojure-answer/3de82d732faedceafac4f1585a72d0712fe5d3c6/20-penultimate-element.clj | clojure | (fn [x] (nth x (- (count x) 2)))
|
|
50737b4e042a580f386a7638184a8589a9ac19c9e8ae280d8ac9ee7ba8329af9 | data61/Mirza | Migrate.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE ScopedTypeVariables #-}
-- This module runs database migrations for our application.
module Mirza.SupplyChain.Database.Migrate where
import Mirza.SupplyChain.Database.Schema.V0001 (migration)
import Mirza.SupplyChain.Database.Schema.SQL.V0001 ( m_0001 )
import Mirza.Common.Database (runMigrationSimple)
import Mirza.Common.Types
import Mirza.Common.Utils
import Mirza.SupplyChain.Database.Schema (supplyChainDb)
import qualified Control.Exception as E
import Control.Monad (void)
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
import Database.Beam ()
import Database.Beam.Backend (runNoReturn)
import Database.Beam.Migrate.Types (executeMigration)
import Database.Beam.Postgres (Connection, Pg,
runBeamPostgres,
runBeamPostgresDebug)
import Database.PostgreSQL.Simple (SqlError)
runMigrationWithTriggers :: (Member context '[HasLogging, HasDB]
,Member err '[AsSqlError])
=> Connection -> context -> IO (Either err ())
runMigrationWithTriggers conn context = do
tryCreateSchema False conn
runAppM context $ runDb $ addLastUpdateTriggers supplyChainDb
-- | Whether or not to run silently
dbMigrationFunc :: Bool -> Connection -> Pg a -> IO a
dbMigrationFunc False = runBeamPostgresDebug putStrLn
dbMigrationFunc _ = runBeamPostgres
createSchema :: Bool -> Connection -> IO ()
createSchema runSilently conn =
void $ dbMigrationFunc runSilently conn $ executeMigration runNoReturn (migration ())
tryCreateSchema :: Bool -> Connection -> IO ()
tryCreateSchema runSilently conn = E.catch (createSchema runSilently conn) handleErr
where
handleErr :: SqlError -> IO ()
handleErr err = do
hPutStrLn stderr $ "Migration failed with error: " <> show err
exitFailure
migrate :: ( Member context '[HasLogging, HasDB] ) => context -> IO (Either SqlError ())
migrate ctx = runMigrationSimple ctx migrations
where
migrations = [ m_0001
]
| null | https://raw.githubusercontent.com/data61/Mirza/24e5ccddfc307cceebcc5ce26d35e91020b8ee10/projects/or_scs/src/Mirza/SupplyChain/Database/Migrate.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
This module runs database migrations for our application.
| Whether or not to run silently | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
module Mirza.SupplyChain.Database.Migrate where
import Mirza.SupplyChain.Database.Schema.V0001 (migration)
import Mirza.SupplyChain.Database.Schema.SQL.V0001 ( m_0001 )
import Mirza.Common.Database (runMigrationSimple)
import Mirza.Common.Types
import Mirza.Common.Utils
import Mirza.SupplyChain.Database.Schema (supplyChainDb)
import qualified Control.Exception as E
import Control.Monad (void)
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
import Database.Beam ()
import Database.Beam.Backend (runNoReturn)
import Database.Beam.Migrate.Types (executeMigration)
import Database.Beam.Postgres (Connection, Pg,
runBeamPostgres,
runBeamPostgresDebug)
import Database.PostgreSQL.Simple (SqlError)
runMigrationWithTriggers :: (Member context '[HasLogging, HasDB]
,Member err '[AsSqlError])
=> Connection -> context -> IO (Either err ())
runMigrationWithTriggers conn context = do
tryCreateSchema False conn
runAppM context $ runDb $ addLastUpdateTriggers supplyChainDb
dbMigrationFunc :: Bool -> Connection -> Pg a -> IO a
dbMigrationFunc False = runBeamPostgresDebug putStrLn
dbMigrationFunc _ = runBeamPostgres
createSchema :: Bool -> Connection -> IO ()
createSchema runSilently conn =
void $ dbMigrationFunc runSilently conn $ executeMigration runNoReturn (migration ())
tryCreateSchema :: Bool -> Connection -> IO ()
tryCreateSchema runSilently conn = E.catch (createSchema runSilently conn) handleErr
where
handleErr :: SqlError -> IO ()
handleErr err = do
hPutStrLn stderr $ "Migration failed with error: " <> show err
exitFailure
migrate :: ( Member context '[HasLogging, HasDB] ) => context -> IO (Either SqlError ())
migrate ctx = runMigrationSimple ctx migrations
where
migrations = [ m_0001
]
|
d025ec139c700d2b99b81be1bac801e3ed593b26d15a060f8aecbfe56733df17 | RedPRL/stagedtt | Quoting.ml | type _ Effect.t +=
| GetSize : int Effect.t
let run ~(size:int) k =
let open Effect.Deep in
try_with k ()
{ effc = fun (type a) (eff : a Effect.t) ->
match eff with
| GetSize -> Option.some @@ fun (k : (a, _) continuation) ->
continue k size
| _ -> None
}
let bind_var k =
let size = Effect.perform GetSize in
run ~size:(size + 1) @@ fun () -> k size
let level_to_index lvl =
let size = Effect.perform GetSize in
size - lvl - 1
| null | https://raw.githubusercontent.com/RedPRL/stagedtt/f88538036b51cebb83ebb0b418ec9b089550275d/lib/eff/Quoting.ml | ocaml | type _ Effect.t +=
| GetSize : int Effect.t
let run ~(size:int) k =
let open Effect.Deep in
try_with k ()
{ effc = fun (type a) (eff : a Effect.t) ->
match eff with
| GetSize -> Option.some @@ fun (k : (a, _) continuation) ->
continue k size
| _ -> None
}
let bind_var k =
let size = Effect.perform GetSize in
run ~size:(size + 1) @@ fun () -> k size
let level_to_index lvl =
let size = Effect.perform GetSize in
size - lvl - 1
|
|
7e33a8f89cf545983c4dfb274e8e77ee49102b6a84f38e4939bc87f209e5e33a | pnwamk/tr-calc | dtr-well-typed.rkt | #lang racket
(require redex
"dtr-lang.rkt"
"dtr-scope.rkt"
"dtr-subst.rkt"
"dtr-subtype.rkt"
"dtr-elim.rkt"
"utils.rkt")
(provide (all-defined-out))
;; ----------------------------------------------------------
;; Types of primitives
(define-metafunction DTR
δ-τ : p -> ([x : τ] → τ (ψ ∣ ψ))
[(δ-τ int?) ([x : ⊤] → Bool ((x ~ Int) ∣ (x ¬ Int)))]
[(δ-τ bool?) ([x : ⊤] → Bool ((x ~ Bool) ∣ (x ¬ Bool)))]
[(δ-τ +) ([x : Int] [y : Int] → {i : Int ∣ (= i (x ⊕ y))} (tt ∣ ff))]
[(δ-τ <=) ([x : Int] [y : Int] → Bool ((x ≤ y) ∣ (> x y)))]
[(δ-τ [× n]) ([x : Int] → {i : Int ∣ (= i (n ⊗ x))} (tt ∣ ff))])
;; ----------------------------------------------------------
;; Well-formedness under an environment (Δ)
(define-relation DTR
well-formed ⊆ Δ × any
[(well-formed Δ any)
(side-condition (subset? (term (fv any)) (term (fv Δ))))])
;; ----------------------------------------------------------
;; Well-Typed judgement (simplified -- type only, ignores propositions)
(define-judgment-form DTR
#:mode (wt-τ I I O)
#:contract (wt-τ Δ e τ)
[(wt Δ e τ (ψ_+ ∣ ψ_-))
----------------
(wt-τ Δ e τ)])
;; ----------------------------------------------------------
;; Well-Typed judgement
(define-judgment-form DTR
#:mode (wt I I O O)
#:contract (wt Δ e τ (ψ ∣ ψ))
[(where/hidden x ,(variable-not-in (list) (x-sym)))
---------------- "T-Int"
(wt Δ n {x : Int ∣ (= x n)} (tt ∣ ff))]
[---------------- "T-True"
(wt Δ #t ♯T (tt ∣ ff))]
[---------------- "T-False"
(wt Δ #f ♯F (ff ∣ tt))]
[---------------- "T-Prim"
(wt Δ p (δ-τ p) (tt ∣ ff))]
[(where/hidden y ,(variable-not-in (term x) (y-sym)))
(where τ (lookup x Γ))
---------------- "T-Var"
(wt [Φ Γ Ψ] x {y : τ ∣ (y ⇒ x)} (tt ∣ ff))]
[; (well-formed Δ (λ ([x : σ] ...) e)) needed? <TODO>
(where (y ...) ,(variables-not-in (term [Φ Γ Ψ]) (term (x ...))))
(wt [Φ (ext Γ (y : σ) ...) Ψ] e τ (ψ_+ ∣ ψ_-))
--------------------------------------------- "T-Lambda"
(wt [Φ Γ Ψ] (λ ([x : σ] ...) e) ([y : σ] ... → τ (ψ_+ ∣ ψ_-)) (tt ∣ ff))]
[; (well-formed Δ (e_f e_a ...) <TODO>?
; does type-of guarantee type has fresh vars in function type? <TODO>
(wt-τ Δ e_f ([x : σ_f] ... → τ_f (ψ_f+ ∣ ψ_f-)))
(wt-τ Δ e_a σ) ...
(subtype Δ σ σ_f) ...
< hidden - particulars > ∃τ , ψ_+ , and ψ_-
(where/hidden [Φ Γ Ψ] Δ)
(where/hidden τ (elim-ids Φ Γ τ_f (x ...)))
(where/hidden ψ_+ (elim-ids Φ Γ ψ_f+ (x ...)))
(where/hidden ψ_- (elim-ids Φ Γ ψ_f- (x ...)))
;; </hidden-particulars> such that
(proves (ext Δ ψ_f+ (x ~ σ) ...) ψ_+)
(proves (ext Δ ψ_f- (x ~ σ) ...) ψ_-)
(subtype (ext Δ (x ~ σ) ...) τ_f τ)
(well-formed Δ (τ (ψ_+ ∣ ψ_-)))
------------------------------ "T-App"
(wt Δ (e_f e_a ...) τ (ψ_+ ∣ ψ_-))]
[(wt Δ e_1 τ_1 (ψ_1+ ∣ ψ_1-))
(wt (ext Δ ψ_1+) e_2 τ_2 (ψ_2+ ∣ ψ_2-))
(wt (ext Δ ψ_1-) e_3 τ_3 (ψ_3+ ∣ ψ_3-))
< hidden - particulars > ∃τ
(where/hidden τ (Un τ_2 τ_3))
;; </hidden-particulars> such that
(subtype Δ τ_2 τ) (subtype Δ τ_3 τ)
(where ψ_+ ((ψ_1+ ∧ ψ_2+) ∨ (ψ_1- ∧ ψ_3+)))
(where ψ_- ((ψ_1+ ∧ ψ_2-) ∨ (ψ_1- ∧ ψ_3-)))
--------------- "T-If"
(wt Δ (if e_1 e_2 e_3) τ (ψ_+ ∣ ψ_-))]
[(wt [Φ Γ Ψ] e_1 τ_1 (ψ_1+ ∣ ψ_1-))
(where Γ_2 ((x : τ_1) · Γ))
(where Ψ_2 ((IF (x ¬ ♯f) ψ_1+ ψ_1-) · Ψ))
(wt [Φ Γ_2 Ψ_2] e_2 τ_2 (ψ_2+ ∣ ψ_2-))
< hidden - particulars > ∃τ , ψ_+ , and ψ_-
(where/hidden ψ_let (IF (x ¬ ♯f) ψ_1+ ψ_1-))
(where/hidden τ (elim-ids Φ Γ τ_2 (x)))
(where/hidden ψ_+ (elim-ids Φ Γ (ψ_let ∧ ψ_2+) (x)))
(where/hidden ψ_- (elim-ids Φ Γ (ψ_let ∧ ψ_2-) (x)))
;; </hidden-particulars> such that
(proves [Φ Γ_2 (ψ_2+ · Ψ_2)] ψ_+)
(proves [Φ Γ_2 (ψ_2- · Ψ_2)] ψ_-)
(subtype [Φ Γ_2 Ψ_2] τ_2 τ)
(well-formed [Φ Γ Ψ] (τ (ψ_+ ∣ ψ_-)))
--------------- "T-Let"
(wt [Φ Γ Ψ] (let (x e_1) e_2) τ (ψ_+ ∣ ψ_-))])
;; judgments for testing
;; types-at
tests for exactly 1 particular type
(define-judgment-form DTR
#:mode (types-at I I)
#:contract (types-at e τ)
[(wt-τ mt-Δ e τ_e)
(subtype mt-Δ τ_e τ)
(subtype mt-Δ τ τ_e)
----------------
(types-at e τ)])
;; types-at/Δ
tests for exactly 1 particular type under Δ
(define-judgment-form DTR
#:mode (types-at/Δ<: I I I)
#:contract (types-at/Δ<: Δ e τ)
[(wt-τ Δ e τ_e)
(subtype Δ τ_e τ)
----------------
(types-at/Δ<: Δ e τ)])
;; types-under
;; checks it is <: the given type
(define-judgment-form DTR
#:mode (types-under I I)
#:contract (types-under e τ)
[(wt-τ mt-Δ e τ_e)
(subtype mt-Δ τ_e τ)
----------------
(types-under e τ)])
;; testing macros
;; e is well-typed exactly at type τ
(define-syntax-rule (test*-well-typed e τ)
(test-true (judgment-holds (types-at e τ))))
;; e is well-typed as a subtype of τ
(define-syntax-rule (test*-well-typed<: e τ)
(test-true (judgment-holds (types-under e τ))))
;; e is well-typed as a subtype of τ
(define-syntax-rule (test*-well-typed/Δ<: Δ e τ)
(test-true (judgment-holds (types-at/Δ<: Δ e τ))))
;; e is not ill-typed
(define-syntax-rule (test*-ill-typed e)
(test-false (judgment-holds (wt-τ mt-Δ e τ))))
(module+ test
;; ints
(test*-well-typed<: 42 Int)
(test*-well-typed 42 {i : Int ∣ (= i 42)})
;; booleans
(test*-well-typed #t ♯T)
(test*-well-typed #f ♯F)
;; prims
(test*-well-typed int? ([z : ⊤] → Bool ((z ~ Int) ∣ (z ¬ Int))))
(test*-well-typed [× 42] ([q : Int] → {i : Int ∣ (= i (42 ⊗ q))} (tt ∣ ff)))
;; var
(test*-ill-typed x)
(test*-well-typed/Δ<: (Γ: (x : Int)) x Int)
;; function
(test*-well-typed (λ () #t) (→ ♯T (tt ∣ ff)))
(test*-well-typed (λ ([x : ⊤]) #t) ([y : ⊤] → ♯T (tt ∣ ff)))
(test*-well-typed (λ ([x : ⊤] [y : ⊤]) #f) ([y : ⊤] [z : ⊤] → ♯F (ff ∣ tt)))
)
| null | https://raw.githubusercontent.com/pnwamk/tr-calc/17baa511af28139e686737c1f4c30d3b187efa2d/rtr-redex/dtr-well-typed.rkt | racket | ----------------------------------------------------------
Types of primitives
----------------------------------------------------------
Well-formedness under an environment (Δ)
----------------------------------------------------------
Well-Typed judgement (simplified -- type only, ignores propositions)
----------------------------------------------------------
Well-Typed judgement
(well-formed Δ (λ ([x : σ] ...) e)) needed? <TODO>
(well-formed Δ (e_f e_a ...) <TODO>?
does type-of guarantee type has fresh vars in function type? <TODO>
</hidden-particulars> such that
</hidden-particulars> such that
</hidden-particulars> such that
judgments for testing
types-at
types-at/Δ
types-under
checks it is <: the given type
testing macros
e is well-typed exactly at type τ
e is well-typed as a subtype of τ
e is well-typed as a subtype of τ
e is not ill-typed
ints
booleans
prims
var
function | #lang racket
(require redex
"dtr-lang.rkt"
"dtr-scope.rkt"
"dtr-subst.rkt"
"dtr-subtype.rkt"
"dtr-elim.rkt"
"utils.rkt")
(provide (all-defined-out))
(define-metafunction DTR
δ-τ : p -> ([x : τ] → τ (ψ ∣ ψ))
[(δ-τ int?) ([x : ⊤] → Bool ((x ~ Int) ∣ (x ¬ Int)))]
[(δ-τ bool?) ([x : ⊤] → Bool ((x ~ Bool) ∣ (x ¬ Bool)))]
[(δ-τ +) ([x : Int] [y : Int] → {i : Int ∣ (= i (x ⊕ y))} (tt ∣ ff))]
[(δ-τ <=) ([x : Int] [y : Int] → Bool ((x ≤ y) ∣ (> x y)))]
[(δ-τ [× n]) ([x : Int] → {i : Int ∣ (= i (n ⊗ x))} (tt ∣ ff))])
(define-relation DTR
well-formed ⊆ Δ × any
[(well-formed Δ any)
(side-condition (subset? (term (fv any)) (term (fv Δ))))])
(define-judgment-form DTR
#:mode (wt-τ I I O)
#:contract (wt-τ Δ e τ)
[(wt Δ e τ (ψ_+ ∣ ψ_-))
----------------
(wt-τ Δ e τ)])
(define-judgment-form DTR
#:mode (wt I I O O)
#:contract (wt Δ e τ (ψ ∣ ψ))
[(where/hidden x ,(variable-not-in (list) (x-sym)))
---------------- "T-Int"
(wt Δ n {x : Int ∣ (= x n)} (tt ∣ ff))]
[---------------- "T-True"
(wt Δ #t ♯T (tt ∣ ff))]
[---------------- "T-False"
(wt Δ #f ♯F (ff ∣ tt))]
[---------------- "T-Prim"
(wt Δ p (δ-τ p) (tt ∣ ff))]
[(where/hidden y ,(variable-not-in (term x) (y-sym)))
(where τ (lookup x Γ))
---------------- "T-Var"
(wt [Φ Γ Ψ] x {y : τ ∣ (y ⇒ x)} (tt ∣ ff))]
(where (y ...) ,(variables-not-in (term [Φ Γ Ψ]) (term (x ...))))
(wt [Φ (ext Γ (y : σ) ...) Ψ] e τ (ψ_+ ∣ ψ_-))
--------------------------------------------- "T-Lambda"
(wt [Φ Γ Ψ] (λ ([x : σ] ...) e) ([y : σ] ... → τ (ψ_+ ∣ ψ_-)) (tt ∣ ff))]
(wt-τ Δ e_f ([x : σ_f] ... → τ_f (ψ_f+ ∣ ψ_f-)))
(wt-τ Δ e_a σ) ...
(subtype Δ σ σ_f) ...
< hidden - particulars > ∃τ , ψ_+ , and ψ_-
(where/hidden [Φ Γ Ψ] Δ)
(where/hidden τ (elim-ids Φ Γ τ_f (x ...)))
(where/hidden ψ_+ (elim-ids Φ Γ ψ_f+ (x ...)))
(where/hidden ψ_- (elim-ids Φ Γ ψ_f- (x ...)))
(proves (ext Δ ψ_f+ (x ~ σ) ...) ψ_+)
(proves (ext Δ ψ_f- (x ~ σ) ...) ψ_-)
(subtype (ext Δ (x ~ σ) ...) τ_f τ)
(well-formed Δ (τ (ψ_+ ∣ ψ_-)))
------------------------------ "T-App"
(wt Δ (e_f e_a ...) τ (ψ_+ ∣ ψ_-))]
[(wt Δ e_1 τ_1 (ψ_1+ ∣ ψ_1-))
(wt (ext Δ ψ_1+) e_2 τ_2 (ψ_2+ ∣ ψ_2-))
(wt (ext Δ ψ_1-) e_3 τ_3 (ψ_3+ ∣ ψ_3-))
< hidden - particulars > ∃τ
(where/hidden τ (Un τ_2 τ_3))
(subtype Δ τ_2 τ) (subtype Δ τ_3 τ)
(where ψ_+ ((ψ_1+ ∧ ψ_2+) ∨ (ψ_1- ∧ ψ_3+)))
(where ψ_- ((ψ_1+ ∧ ψ_2-) ∨ (ψ_1- ∧ ψ_3-)))
--------------- "T-If"
(wt Δ (if e_1 e_2 e_3) τ (ψ_+ ∣ ψ_-))]
[(wt [Φ Γ Ψ] e_1 τ_1 (ψ_1+ ∣ ψ_1-))
(where Γ_2 ((x : τ_1) · Γ))
(where Ψ_2 ((IF (x ¬ ♯f) ψ_1+ ψ_1-) · Ψ))
(wt [Φ Γ_2 Ψ_2] e_2 τ_2 (ψ_2+ ∣ ψ_2-))
< hidden - particulars > ∃τ , ψ_+ , and ψ_-
(where/hidden ψ_let (IF (x ¬ ♯f) ψ_1+ ψ_1-))
(where/hidden τ (elim-ids Φ Γ τ_2 (x)))
(where/hidden ψ_+ (elim-ids Φ Γ (ψ_let ∧ ψ_2+) (x)))
(where/hidden ψ_- (elim-ids Φ Γ (ψ_let ∧ ψ_2-) (x)))
(proves [Φ Γ_2 (ψ_2+ · Ψ_2)] ψ_+)
(proves [Φ Γ_2 (ψ_2- · Ψ_2)] ψ_-)
(subtype [Φ Γ_2 Ψ_2] τ_2 τ)
(well-formed [Φ Γ Ψ] (τ (ψ_+ ∣ ψ_-)))
--------------- "T-Let"
(wt [Φ Γ Ψ] (let (x e_1) e_2) τ (ψ_+ ∣ ψ_-))])
tests for exactly 1 particular type
(define-judgment-form DTR
#:mode (types-at I I)
#:contract (types-at e τ)
[(wt-τ mt-Δ e τ_e)
(subtype mt-Δ τ_e τ)
(subtype mt-Δ τ τ_e)
----------------
(types-at e τ)])
tests for exactly 1 particular type under Δ
(define-judgment-form DTR
#:mode (types-at/Δ<: I I I)
#:contract (types-at/Δ<: Δ e τ)
[(wt-τ Δ e τ_e)
(subtype Δ τ_e τ)
----------------
(types-at/Δ<: Δ e τ)])
(define-judgment-form DTR
#:mode (types-under I I)
#:contract (types-under e τ)
[(wt-τ mt-Δ e τ_e)
(subtype mt-Δ τ_e τ)
----------------
(types-under e τ)])
(define-syntax-rule (test*-well-typed e τ)
(test-true (judgment-holds (types-at e τ))))
(define-syntax-rule (test*-well-typed<: e τ)
(test-true (judgment-holds (types-under e τ))))
(define-syntax-rule (test*-well-typed/Δ<: Δ e τ)
(test-true (judgment-holds (types-at/Δ<: Δ e τ))))
(define-syntax-rule (test*-ill-typed e)
(test-false (judgment-holds (wt-τ mt-Δ e τ))))
(module+ test
(test*-well-typed<: 42 Int)
(test*-well-typed 42 {i : Int ∣ (= i 42)})
(test*-well-typed #t ♯T)
(test*-well-typed #f ♯F)
(test*-well-typed int? ([z : ⊤] → Bool ((z ~ Int) ∣ (z ¬ Int))))
(test*-well-typed [× 42] ([q : Int] → {i : Int ∣ (= i (42 ⊗ q))} (tt ∣ ff)))
(test*-ill-typed x)
(test*-well-typed/Δ<: (Γ: (x : Int)) x Int)
(test*-well-typed (λ () #t) (→ ♯T (tt ∣ ff)))
(test*-well-typed (λ ([x : ⊤]) #t) ([y : ⊤] → ♯T (tt ∣ ff)))
(test*-well-typed (λ ([x : ⊤] [y : ⊤]) #f) ([y : ⊤] [z : ⊤] → ♯F (ff ∣ tt)))
)
|
27ecf5d4a4a0e20c30473c06fec8c5f1895fadd7f84e6ba29cbd699cc43532a4 | spawnfest/eep49ers | wxTextCtrl.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
-module(wxTextCtrl).
-include("wxe.hrl").
-export([appendText/2,canCopy/1,canCut/1,canPaste/1,canRedo/1,canUndo/1,changeValue/2,
clear/1,copy/1,create/3,create/4,cut/1,destroy/1,discardEdits/1,emulateKeyPress/2,
getDefaultStyle/1,getInsertionPoint/1,getLastPosition/1,getLineLength/2,
getLineText/2,getNumberOfLines/1,getRange/3,getSelection/1,getStringSelection/1,
getStyle/3,getValue/1,isEditable/1,isModified/1,isMultiLine/1,isSingleLine/1,
loadFile/2,loadFile/3,markDirty/1,new/0,new/2,new/3,paste/1,positionToXY/2,
redo/1,remove/3,replace/4,saveFile/1,saveFile/2,setDefaultStyle/2,setEditable/2,
setInsertionPoint/2,setInsertionPointEnd/1,setMaxLength/2,setSelection/3,
setStyle/4,setValue/2,showPosition/2,undo/1,writeText/2,xYToPosition/3]).
%% inherited exports
-export([cacheBestSize/2,canSetTransparent/1,captureMouse/1,center/1,center/2,
centerOnParent/1,centerOnParent/2,centre/1,centre/2,centreOnParent/1,
centreOnParent/2,clearBackground/1,clientToScreen/2,clientToScreen/3,
close/1,close/2,connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2,
destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3,
dragAcceptFiles/2,enable/1,enable/2,findWindow/2,fit/1,fitInside/1,
freeze/1,getAcceleratorTable/1,getBackgroundColour/1,getBackgroundStyle/1,
getBestSize/1,getCaret/1,getCharHeight/1,getCharWidth/1,getChildren/1,
getClientSize/1,getContainingSizer/1,getContentScaleFactor/1,getCursor/1,
getDPI/1,getDPIScaleFactor/1,getDropTarget/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1,
getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2,
getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2,
getTextExtent/3,getThemeEnabled/1,getToolTip/1,getUpdateRegion/1,
getVirtualSize/1,getWindowStyleFlag/1,getWindowVariant/1,hasCapture/1,
hasScrollbar/2,hasTransparentBackground/1,hide/1,inheritAttributes/1,
initDialog/1,invalidateBestSize/1,isDoubleBuffered/1,isEnabled/1,
isExposed/2,isExposed/3,isExposed/5,isFrozen/1,isRetained/1,isShown/1,
isShownOnScreen/1,isTopLevel/1,layout/1,lineDown/1,lineUp/1,lower/1,
move/2,move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,
navigate/1,navigate/2,pageDown/1,pageUp/1,parent_class/1,popupMenu/2,
popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2,refreshRect/3,
releaseMouse/1,removeChild/2,reparent/2,screenToClient/1,screenToClient/2,
scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4,setAcceleratorTable/2,
setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2,setCaret/2,
setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2,
setDoubleBuffered/2,setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,
setFont/2,setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2,
setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2,
setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6,
setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3,
setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3,
setThemeEnabled/2,setToolTip/2,setTransparent/2,setVirtualSize/2,
setVirtualSize/3,setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,
shouldInheritColours/1,show/1,show/2,thaw/1,transferDataFromWindow/1,
transferDataToWindow/1,update/1,updateWindowUI/1,updateWindowUI/2,
validate/1,warpPointer/3]).
-type wxTextCtrl() :: wx:wx_object().
-export_type([wxTextCtrl/0]).
%% @hidden
parent_class(wxControl) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
%% @doc See <a href="#wxtextctrlwxtextctrl">external documentation</a>.
-spec new() -> wxTextCtrl().
new() ->
wxe_util:queue_cmd(?get_env(), ?wxTextCtrl_new_0),
wxe_util:rec(?wxTextCtrl_new_0).
@equiv new(Parent , Id , [ ] )
-spec new(Parent, Id) -> wxTextCtrl() when
Parent::wxWindow:wxWindow(), Id::integer().
new(Parent,Id)
when is_record(Parent, wx_ref),is_integer(Id) ->
new(Parent,Id, []).
%% @doc See <a href="#wxtextctrlwxtextctrl">external documentation</a>.
-spec new(Parent, Id, [Option]) -> wxTextCtrl() when
Parent::wxWindow:wxWindow(), Id::integer(),
Option :: {'value', unicode:chardata()}
| {'pos', {X::integer(), Y::integer()}}
| {'size', {W::integer(), H::integer()}}
| {'style', integer()}
| {'validator', wx:wx_object()}.
new(#wx_ref{type=ParentT}=Parent,Id, Options)
when is_integer(Id),is_list(Options) ->
?CLASS(ParentT,wxWindow),
MOpts = fun({value, Value}) -> Value_UC = unicode:characters_to_binary(Value),{value,Value_UC};
({pos, {_posX,_posY}} = Arg) -> Arg;
({size, {_sizeW,_sizeH}} = Arg) -> Arg;
({style, _style} = Arg) -> Arg;
({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Parent,Id, Opts,?get_env(),?wxTextCtrl_new_3),
wxe_util:rec(?wxTextCtrl_new_3).
%% @doc See <a href="#wxtextctrlappendtext">external documentation</a>.
-spec appendText(This, Text) -> 'ok' when
This::wxTextCtrl(), Text::unicode:chardata().
appendText(#wx_ref{type=ThisT}=This,Text)
when ?is_chardata(Text) ->
?CLASS(ThisT,wxTextCtrl),
Text_UC = unicode:characters_to_binary(Text),
wxe_util:queue_cmd(This,Text_UC,?get_env(),?wxTextCtrl_AppendText).
%% @doc See <a href="#wxtextctrlcancopy">external documentation</a>.
-spec canCopy(This) -> boolean() when
This::wxTextCtrl().
canCopy(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanCopy),
wxe_util:rec(?wxTextCtrl_CanCopy).
%% @doc See <a href="#wxtextctrlcancut">external documentation</a>.
-spec canCut(This) -> boolean() when
This::wxTextCtrl().
canCut(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanCut),
wxe_util:rec(?wxTextCtrl_CanCut).
%% @doc See <a href="#wxtextctrlcanpaste">external documentation</a>.
-spec canPaste(This) -> boolean() when
This::wxTextCtrl().
canPaste(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanPaste),
wxe_util:rec(?wxTextCtrl_CanPaste).
%% @doc See <a href="#wxtextctrlcanredo">external documentation</a>.
-spec canRedo(This) -> boolean() when
This::wxTextCtrl().
canRedo(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanRedo),
wxe_util:rec(?wxTextCtrl_CanRedo).
%% @doc See <a href="#wxtextctrlcanundo">external documentation</a>.
-spec canUndo(This) -> boolean() when
This::wxTextCtrl().
canUndo(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanUndo),
wxe_util:rec(?wxTextCtrl_CanUndo).
%% @doc See <a href="#wxtextctrlclear">external documentation</a>.
-spec clear(This) -> 'ok' when
This::wxTextCtrl().
clear(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Clear).
%% @doc See <a href="#wxtextctrlcopy">external documentation</a>.
-spec copy(This) -> 'ok' when
This::wxTextCtrl().
copy(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Copy).
%% @equiv create(This,Parent,Id, [])
-spec create(This, Parent, Id) -> boolean() when
This::wxTextCtrl(), Parent::wxWindow:wxWindow(), Id::integer().
create(This,Parent,Id)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id) ->
create(This,Parent,Id, []).
%% @doc See <a href="#wxtextctrlcreate">external documentation</a>.
-spec create(This, Parent, Id, [Option]) -> boolean() when
This::wxTextCtrl(), Parent::wxWindow:wxWindow(), Id::integer(),
Option :: {'value', unicode:chardata()}
| {'pos', {X::integer(), Y::integer()}}
| {'size', {W::integer(), H::integer()}}
| {'style', integer()}
| {'validator', wx:wx_object()}.
create(#wx_ref{type=ThisT}=This,#wx_ref{type=ParentT}=Parent,Id, Options)
when is_integer(Id),is_list(Options) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(ParentT,wxWindow),
MOpts = fun({value, Value}) -> Value_UC = unicode:characters_to_binary(Value),{value,Value_UC};
({pos, {_posX,_posY}} = Arg) -> Arg;
({size, {_sizeW,_sizeH}} = Arg) -> Arg;
({style, _style} = Arg) -> Arg;
({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Parent,Id, Opts,?get_env(),?wxTextCtrl_Create),
wxe_util:rec(?wxTextCtrl_Create).
%% @doc See <a href="#wxtextctrlcut">external documentation</a>.
-spec cut(This) -> 'ok' when
This::wxTextCtrl().
cut(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Cut).
%% @doc See <a href="#wxtextctrldiscardedits">external documentation</a>.
-spec discardEdits(This) -> 'ok' when
This::wxTextCtrl().
discardEdits(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_DiscardEdits).
%% @doc See <a href="#wxtextctrlchangevalue">external documentation</a>.
-spec changeValue(This, Value) -> 'ok' when
This::wxTextCtrl(), Value::unicode:chardata().
changeValue(#wx_ref{type=ThisT}=This,Value)
when ?is_chardata(Value) ->
?CLASS(ThisT,wxTextCtrl),
Value_UC = unicode:characters_to_binary(Value),
wxe_util:queue_cmd(This,Value_UC,?get_env(),?wxTextCtrl_ChangeValue).
@doc See < a href=" / manuals/2.8.12 / wx_wxtextctrl.html#wxtextctrlemulatekeypress">external documentation</a > .
-spec emulateKeyPress(This, Event) -> boolean() when
This::wxTextCtrl(), Event::wxKeyEvent:wxKeyEvent().
emulateKeyPress(#wx_ref{type=ThisT}=This,#wx_ref{type=EventT}=Event) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(EventT,wxKeyEvent),
wxe_util:queue_cmd(This,Event,?get_env(),?wxTextCtrl_EmulateKeyPress),
wxe_util:rec(?wxTextCtrl_EmulateKeyPress).
%% @doc See <a href="#wxtextctrlgetdefaultstyle">external documentation</a>.
-spec getDefaultStyle(This) -> wxTextAttr:wxTextAttr() when
This::wxTextCtrl().
getDefaultStyle(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetDefaultStyle),
wxe_util:rec(?wxTextCtrl_GetDefaultStyle).
%% @doc See <a href="#wxtextctrlgetinsertionpoint">external documentation</a>.
-spec getInsertionPoint(This) -> integer() when
This::wxTextCtrl().
getInsertionPoint(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetInsertionPoint),
wxe_util:rec(?wxTextCtrl_GetInsertionPoint).
%% @doc See <a href="#wxtextctrlgetlastposition">external documentation</a>.
-spec getLastPosition(This) -> integer() when
This::wxTextCtrl().
getLastPosition(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetLastPosition),
wxe_util:rec(?wxTextCtrl_GetLastPosition).
%% @doc See <a href="#wxtextctrlgetlinelength">external documentation</a>.
-spec getLineLength(This, LineNo) -> integer() when
This::wxTextCtrl(), LineNo::integer().
getLineLength(#wx_ref{type=ThisT}=This,LineNo)
when is_integer(LineNo) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,LineNo,?get_env(),?wxTextCtrl_GetLineLength),
wxe_util:rec(?wxTextCtrl_GetLineLength).
%% @doc See <a href="#wxtextctrlgetlinetext">external documentation</a>.
-spec getLineText(This, LineNo) -> unicode:charlist() when
This::wxTextCtrl(), LineNo::integer().
getLineText(#wx_ref{type=ThisT}=This,LineNo)
when is_integer(LineNo) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,LineNo,?get_env(),?wxTextCtrl_GetLineText),
wxe_util:rec(?wxTextCtrl_GetLineText).
%% @doc See <a href="#wxtextctrlgetnumberoflines">external documentation</a>.
-spec getNumberOfLines(This) -> integer() when
This::wxTextCtrl().
getNumberOfLines(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetNumberOfLines),
wxe_util:rec(?wxTextCtrl_GetNumberOfLines).
%% @doc See <a href="#wxtextctrlgetrange">external documentation</a>.
-spec getRange(This, From, To) -> unicode:charlist() when
This::wxTextCtrl(), From::integer(), To::integer().
getRange(#wx_ref{type=ThisT}=This,From,To)
when is_integer(From),is_integer(To) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,From,To,?get_env(),?wxTextCtrl_GetRange),
wxe_util:rec(?wxTextCtrl_GetRange).
%% @doc See <a href="#wxtextctrlgetselection">external documentation</a>.
-spec getSelection(This) -> {From::integer(), To::integer()} when
This::wxTextCtrl().
getSelection(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetSelection),
wxe_util:rec(?wxTextCtrl_GetSelection).
%% @doc See <a href="#wxtextctrlgetstringselection">external documentation</a>.
-spec getStringSelection(This) -> unicode:charlist() when
This::wxTextCtrl().
getStringSelection(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetStringSelection),
wxe_util:rec(?wxTextCtrl_GetStringSelection).
%% @doc See <a href="#wxtextctrlgetstyle">external documentation</a>.
-spec getStyle(This, Position, Style) -> boolean() when
This::wxTextCtrl(), Position::integer(), Style::wxTextAttr:wxTextAttr().
getStyle(#wx_ref{type=ThisT}=This,Position,#wx_ref{type=StyleT}=Style)
when is_integer(Position) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(StyleT,wxTextAttr),
wxe_util:queue_cmd(This,Position,Style,?get_env(),?wxTextCtrl_GetStyle),
wxe_util:rec(?wxTextCtrl_GetStyle).
%% @doc See <a href="#wxtextctrlgetvalue">external documentation</a>.
-spec getValue(This) -> unicode:charlist() when
This::wxTextCtrl().
getValue(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetValue),
wxe_util:rec(?wxTextCtrl_GetValue).
%% @doc See <a href="#wxtextctrliseditable">external documentation</a>.
-spec isEditable(This) -> boolean() when
This::wxTextCtrl().
isEditable(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_IsEditable),
wxe_util:rec(?wxTextCtrl_IsEditable).
%% @doc See <a href="#wxtextctrlismodified">external documentation</a>.
-spec isModified(This) -> boolean() when
This::wxTextCtrl().
isModified(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_IsModified),
wxe_util:rec(?wxTextCtrl_IsModified).
@doc See < a href=" / manuals/2.8.12 / wx_wxtextctrl.html#wxtextctrlismultiline">external documentation</a > .
-spec isMultiLine(This) -> boolean() when
This::wxTextCtrl().
isMultiLine(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_IsMultiLine),
wxe_util:rec(?wxTextCtrl_IsMultiLine).
%% @doc See <a href="#wxtextctrlissingleline">external documentation</a>.
-spec isSingleLine(This) -> boolean() when
This::wxTextCtrl().
isSingleLine(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_IsSingleLine),
wxe_util:rec(?wxTextCtrl_IsSingleLine).
%% @equiv loadFile(This,Filename, [])
-spec loadFile(This, Filename) -> boolean() when
This::wxTextCtrl(), Filename::unicode:chardata().
loadFile(This,Filename)
when is_record(This, wx_ref),?is_chardata(Filename) ->
loadFile(This,Filename, []).
%% @doc See <a href="#wxtextctrlloadfile">external documentation</a>.
-spec loadFile(This, Filename, [Option]) -> boolean() when
This::wxTextCtrl(), Filename::unicode:chardata(),
Option :: {'fileType', integer()}.
loadFile(#wx_ref{type=ThisT}=This,Filename, Options)
when ?is_chardata(Filename),is_list(Options) ->
?CLASS(ThisT,wxTextCtrl),
Filename_UC = unicode:characters_to_binary(Filename),
MOpts = fun({fileType, _fileType} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Filename_UC, Opts,?get_env(),?wxTextCtrl_LoadFile),
wxe_util:rec(?wxTextCtrl_LoadFile).
%% @doc See <a href="#wxtextctrlmarkdirty">external documentation</a>.
-spec markDirty(This) -> 'ok' when
This::wxTextCtrl().
markDirty(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_MarkDirty).
@doc See < a href=" / manuals/2.8.12 / wx_wxtextctrl.html#wxtextctrlpaste">external documentation</a > .
-spec paste(This) -> 'ok' when
This::wxTextCtrl().
paste(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Paste).
%% @doc See <a href="#wxtextctrlpositiontoxy">external documentation</a>.
-spec positionToXY(This, Pos) -> Result when
Result ::{Res ::boolean(), X::integer(), Y::integer()},
This::wxTextCtrl(), Pos::integer().
positionToXY(#wx_ref{type=ThisT}=This,Pos)
when is_integer(Pos) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Pos,?get_env(),?wxTextCtrl_PositionToXY),
wxe_util:rec(?wxTextCtrl_PositionToXY).
%% @doc See <a href="#wxtextctrlredo">external documentation</a>.
-spec redo(This) -> 'ok' when
This::wxTextCtrl().
redo(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Redo).
%% @doc See <a href="#wxtextctrlremove">external documentation</a>.
-spec remove(This, From, To) -> 'ok' when
This::wxTextCtrl(), From::integer(), To::integer().
remove(#wx_ref{type=ThisT}=This,From,To)
when is_integer(From),is_integer(To) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,From,To,?get_env(),?wxTextCtrl_Remove).
%% @doc See <a href="#wxtextctrlreplace">external documentation</a>.
-spec replace(This, From, To, Value) -> 'ok' when
This::wxTextCtrl(), From::integer(), To::integer(), Value::unicode:chardata().
replace(#wx_ref{type=ThisT}=This,From,To,Value)
when is_integer(From),is_integer(To),?is_chardata(Value) ->
?CLASS(ThisT,wxTextCtrl),
Value_UC = unicode:characters_to_binary(Value),
wxe_util:queue_cmd(This,From,To,Value_UC,?get_env(),?wxTextCtrl_Replace).
%% @equiv saveFile(This, [])
-spec saveFile(This) -> boolean() when
This::wxTextCtrl().
saveFile(This)
when is_record(This, wx_ref) ->
saveFile(This, []).
%% @doc See <a href="#wxtextctrlsavefile">external documentation</a>.
-spec saveFile(This, [Option]) -> boolean() when
This::wxTextCtrl(),
Option :: {'file', unicode:chardata()}
| {'fileType', integer()}.
saveFile(#wx_ref{type=ThisT}=This, Options)
when is_list(Options) ->
?CLASS(ThisT,wxTextCtrl),
MOpts = fun({file, File}) -> File_UC = unicode:characters_to_binary(File),{file,File_UC};
({fileType, _fileType} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This, Opts,?get_env(),?wxTextCtrl_SaveFile),
wxe_util:rec(?wxTextCtrl_SaveFile).
%% @doc See <a href="#wxtextctrlsetdefaultstyle">external documentation</a>.
-spec setDefaultStyle(This, Style) -> boolean() when
This::wxTextCtrl(), Style::wxTextAttr:wxTextAttr().
setDefaultStyle(#wx_ref{type=ThisT}=This,#wx_ref{type=StyleT}=Style) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(StyleT,wxTextAttr),
wxe_util:queue_cmd(This,Style,?get_env(),?wxTextCtrl_SetDefaultStyle),
wxe_util:rec(?wxTextCtrl_SetDefaultStyle).
%% @doc See <a href="#wxtextctrlseteditable">external documentation</a>.
-spec setEditable(This, Editable) -> 'ok' when
This::wxTextCtrl(), Editable::boolean().
setEditable(#wx_ref{type=ThisT}=This,Editable)
when is_boolean(Editable) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Editable,?get_env(),?wxTextCtrl_SetEditable).
%% @doc See <a href="#wxtextctrlsetinsertionpoint">external documentation</a>.
-spec setInsertionPoint(This, Pos) -> 'ok' when
This::wxTextCtrl(), Pos::integer().
setInsertionPoint(#wx_ref{type=ThisT}=This,Pos)
when is_integer(Pos) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Pos,?get_env(),?wxTextCtrl_SetInsertionPoint).
%% @doc See <a href="#wxtextctrlsetinsertionpointend">external documentation</a>.
-spec setInsertionPointEnd(This) -> 'ok' when
This::wxTextCtrl().
setInsertionPointEnd(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_SetInsertionPointEnd).
%% @doc See <a href="#wxtextctrlsetmaxlength">external documentation</a>.
-spec setMaxLength(This, Len) -> 'ok' when
This::wxTextCtrl(), Len::integer().
setMaxLength(#wx_ref{type=ThisT}=This,Len)
when is_integer(Len) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Len,?get_env(),?wxTextCtrl_SetMaxLength).
%% @doc See <a href="#wxtextctrlsetselection">external documentation</a>.
-spec setSelection(This, From, To) -> 'ok' when
This::wxTextCtrl(), From::integer(), To::integer().
setSelection(#wx_ref{type=ThisT}=This,From,To)
when is_integer(From),is_integer(To) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,From,To,?get_env(),?wxTextCtrl_SetSelection).
%% @doc See <a href="#wxtextctrlsetstyle">external documentation</a>.
-spec setStyle(This, Start, End, Style) -> boolean() when
This::wxTextCtrl(), Start::integer(), End::integer(), Style::wxTextAttr:wxTextAttr().
setStyle(#wx_ref{type=ThisT}=This,Start,End,#wx_ref{type=StyleT}=Style)
when is_integer(Start),is_integer(End) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(StyleT,wxTextAttr),
wxe_util:queue_cmd(This,Start,End,Style,?get_env(),?wxTextCtrl_SetStyle),
wxe_util:rec(?wxTextCtrl_SetStyle).
%% @doc See <a href="#wxtextctrlsetvalue">external documentation</a>.
-spec setValue(This, Value) -> 'ok' when
This::wxTextCtrl(), Value::unicode:chardata().
setValue(#wx_ref{type=ThisT}=This,Value)
when ?is_chardata(Value) ->
?CLASS(ThisT,wxTextCtrl),
Value_UC = unicode:characters_to_binary(Value),
wxe_util:queue_cmd(This,Value_UC,?get_env(),?wxTextCtrl_SetValue).
%% @doc See <a href="#wxtextctrlshowposition">external documentation</a>.
-spec showPosition(This, Pos) -> 'ok' when
This::wxTextCtrl(), Pos::integer().
showPosition(#wx_ref{type=ThisT}=This,Pos)
when is_integer(Pos) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Pos,?get_env(),?wxTextCtrl_ShowPosition).
%% @doc See <a href="#wxtextctrlundo">external documentation</a>.
-spec undo(This) -> 'ok' when
This::wxTextCtrl().
undo(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Undo).
%% @doc See <a href="#wxtextctrlwritetext">external documentation</a>.
-spec writeText(This, Text) -> 'ok' when
This::wxTextCtrl(), Text::unicode:chardata().
writeText(#wx_ref{type=ThisT}=This,Text)
when ?is_chardata(Text) ->
?CLASS(ThisT,wxTextCtrl),
Text_UC = unicode:characters_to_binary(Text),
wxe_util:queue_cmd(This,Text_UC,?get_env(),?wxTextCtrl_WriteText).
%% @doc See <a href="#wxtextctrlxytoposition">external documentation</a>.
-spec xYToPosition(This, X, Y) -> integer() when
This::wxTextCtrl(), X::integer(), Y::integer().
xYToPosition(#wx_ref{type=ThisT}=This,X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,X,Y,?get_env(),?wxTextCtrl_XYToPosition),
wxe_util:rec(?wxTextCtrl_XYToPosition).
%% @doc Destroys this object, do not use object again
-spec destroy(This::wxTextCtrl()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxTextCtrl),
wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT),
ok.
%% From wxControl
%% @hidden
setLabel(This,Label) -> wxControl:setLabel(This,Label).
%% @hidden
getLabel(This) -> wxControl:getLabel(This).
%% From wxWindow
%% @hidden
getDPI(This) -> wxWindow:getDPI(This).
%% @hidden
getContentScaleFactor(This) -> wxWindow:getContentScaleFactor(This).
%% @hidden
setDoubleBuffered(This,On) -> wxWindow:setDoubleBuffered(This,On).
%% @hidden
isDoubleBuffered(This) -> wxWindow:isDoubleBuffered(This).
%% @hidden
canSetTransparent(This) -> wxWindow:canSetTransparent(This).
%% @hidden
setTransparent(This,Alpha) -> wxWindow:setTransparent(This,Alpha).
%% @hidden
warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y).
%% @hidden
validate(This) -> wxWindow:validate(This).
%% @hidden
updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options).
%% @hidden
updateWindowUI(This) -> wxWindow:updateWindowUI(This).
%% @hidden
update(This) -> wxWindow:update(This).
%% @hidden
transferDataToWindow(This) -> wxWindow:transferDataToWindow(This).
%% @hidden
transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This).
%% @hidden
thaw(This) -> wxWindow:thaw(This).
%% @hidden
show(This, Options) -> wxWindow:show(This, Options).
%% @hidden
show(This) -> wxWindow:show(This).
%% @hidden
shouldInheritColours(This) -> wxWindow:shouldInheritColours(This).
%% @hidden
setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant).
%% @hidden
setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style).
%% @hidden
setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style).
%% @hidden
setVirtualSize(This,Width,Height) -> wxWindow:setVirtualSize(This,Width,Height).
%% @hidden
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
%% @hidden
setToolTip(This,TipString) -> wxWindow:setToolTip(This,TipString).
%% @hidden
setThemeEnabled(This,Enable) -> wxWindow:setThemeEnabled(This,Enable).
%% @hidden
setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options).
%% @hidden
setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer).
%% @hidden
setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options).
%% @hidden
setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer).
%% @hidden
setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options).
%% @hidden
setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH).
%% @hidden
setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize).
%% @hidden
setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options).
%% @hidden
setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height).
%% @hidden
setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height).
%% @hidden
setSize(This,Rect) -> wxWindow:setSize(This,Rect).
%% @hidden
setScrollPos(This,Orientation,Pos, Options) -> wxWindow:setScrollPos(This,Orientation,Pos, Options).
%% @hidden
setScrollPos(This,Orientation,Pos) -> wxWindow:setScrollPos(This,Orientation,Pos).
%% @hidden
setScrollbar(This,Orientation,Position,ThumbSize,Range, Options) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range, Options).
%% @hidden
setScrollbar(This,Orientation,Position,ThumbSize,Range) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range).
%% @hidden
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
%% @hidden
setName(This,Name) -> wxWindow:setName(This,Name).
%% @hidden
setId(This,Winid) -> wxWindow:setId(This,Winid).
%% @hidden
setHelpText(This,HelpText) -> wxWindow:setHelpText(This,HelpText).
%% @hidden
setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour).
%% @hidden
setFont(This,Font) -> wxWindow:setFont(This,Font).
%% @hidden
setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This).
%% @hidden
setFocus(This) -> wxWindow:setFocus(This).
%% @hidden
setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle).
%% @hidden
setDropTarget(This,Target) -> wxWindow:setDropTarget(This,Target).
%% @hidden
setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour).
%% @hidden
setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font).
%% @hidden
setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour).
%% @hidden
setMinSize(This,Size) -> wxWindow:setMinSize(This,Size).
%% @hidden
setMaxSize(This,Size) -> wxWindow:setMaxSize(This,Size).
%% @hidden
setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor).
%% @hidden
setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer).
%% @hidden
setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height).
%% @hidden
setClientSize(This,Size) -> wxWindow:setClientSize(This,Size).
%% @hidden
setCaret(This,Caret) -> wxWindow:setCaret(This,Caret).
%% @hidden
setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style).
%% @hidden
setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour).
%% @hidden
setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout).
%% @hidden
setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel).
%% @hidden
scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options).
%% @hidden
scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy).
%% @hidden
scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages).
%% @hidden
scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines).
%% @hidden
screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt).
%% @hidden
screenToClient(This) -> wxWindow:screenToClient(This).
%% @hidden
reparent(This,NewParent) -> wxWindow:reparent(This,NewParent).
%% @hidden
removeChild(This,Child) -> wxWindow:removeChild(This,Child).
%% @hidden
releaseMouse(This) -> wxWindow:releaseMouse(This).
%% @hidden
refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options).
%% @hidden
refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect).
%% @hidden
refresh(This, Options) -> wxWindow:refresh(This, Options).
%% @hidden
refresh(This) -> wxWindow:refresh(This).
%% @hidden
raise(This) -> wxWindow:raise(This).
%% @hidden
popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y).
%% @hidden
popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options).
%% @hidden
popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu).
%% @hidden
pageUp(This) -> wxWindow:pageUp(This).
%% @hidden
pageDown(This) -> wxWindow:pageDown(This).
%% @hidden
navigate(This, Options) -> wxWindow:navigate(This, Options).
%% @hidden
navigate(This) -> wxWindow:navigate(This).
%% @hidden
moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win).
%% @hidden
moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win).
%% @hidden
move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options).
%% @hidden
move(This,X,Y) -> wxWindow:move(This,X,Y).
%% @hidden
move(This,Pt) -> wxWindow:move(This,Pt).
%% @hidden
lower(This) -> wxWindow:lower(This).
%% @hidden
lineUp(This) -> wxWindow:lineUp(This).
%% @hidden
lineDown(This) -> wxWindow:lineDown(This).
%% @hidden
layout(This) -> wxWindow:layout(This).
%% @hidden
isShownOnScreen(This) -> wxWindow:isShownOnScreen(This).
%% @hidden
isTopLevel(This) -> wxWindow:isTopLevel(This).
%% @hidden
isShown(This) -> wxWindow:isShown(This).
%% @hidden
isRetained(This) -> wxWindow:isRetained(This).
%% @hidden
isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H).
%% @hidden
isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y).
%% @hidden
isExposed(This,Pt) -> wxWindow:isExposed(This,Pt).
%% @hidden
isEnabled(This) -> wxWindow:isEnabled(This).
%% @hidden
isFrozen(This) -> wxWindow:isFrozen(This).
%% @hidden
invalidateBestSize(This) -> wxWindow:invalidateBestSize(This).
%% @hidden
initDialog(This) -> wxWindow:initDialog(This).
%% @hidden
inheritAttributes(This) -> wxWindow:inheritAttributes(This).
%% @hidden
hide(This) -> wxWindow:hide(This).
%% @hidden
hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This).
%% @hidden
hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient).
%% @hidden
hasCapture(This) -> wxWindow:hasCapture(This).
%% @hidden
getWindowVariant(This) -> wxWindow:getWindowVariant(This).
%% @hidden
getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This).
%% @hidden
getVirtualSize(This) -> wxWindow:getVirtualSize(This).
%% @hidden
getUpdateRegion(This) -> wxWindow:getUpdateRegion(This).
%% @hidden
getToolTip(This) -> wxWindow:getToolTip(This).
%% @hidden
getThemeEnabled(This) -> wxWindow:getThemeEnabled(This).
%% @hidden
getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options).
%% @hidden
getTextExtent(This,String) -> wxWindow:getTextExtent(This,String).
%% @hidden
getSizer(This) -> wxWindow:getSizer(This).
%% @hidden
getSize(This) -> wxWindow:getSize(This).
%% @hidden
getScrollThumb(This,Orientation) -> wxWindow:getScrollThumb(This,Orientation).
%% @hidden
getScrollRange(This,Orientation) -> wxWindow:getScrollRange(This,Orientation).
%% @hidden
getScrollPos(This,Orientation) -> wxWindow:getScrollPos(This,Orientation).
%% @hidden
getScreenRect(This) -> wxWindow:getScreenRect(This).
%% @hidden
getScreenPosition(This) -> wxWindow:getScreenPosition(This).
%% @hidden
getRect(This) -> wxWindow:getRect(This).
%% @hidden
getPosition(This) -> wxWindow:getPosition(This).
%% @hidden
getParent(This) -> wxWindow:getParent(This).
%% @hidden
getName(This) -> wxWindow:getName(This).
%% @hidden
getMinSize(This) -> wxWindow:getMinSize(This).
%% @hidden
getMaxSize(This) -> wxWindow:getMaxSize(This).
%% @hidden
getId(This) -> wxWindow:getId(This).
%% @hidden
getHelpText(This) -> wxWindow:getHelpText(This).
%% @hidden
getHandle(This) -> wxWindow:getHandle(This).
%% @hidden
getGrandParent(This) -> wxWindow:getGrandParent(This).
%% @hidden
getForegroundColour(This) -> wxWindow:getForegroundColour(This).
%% @hidden
getFont(This) -> wxWindow:getFont(This).
%% @hidden
getExtraStyle(This) -> wxWindow:getExtraStyle(This).
%% @hidden
getDPIScaleFactor(This) -> wxWindow:getDPIScaleFactor(This).
%% @hidden
getDropTarget(This) -> wxWindow:getDropTarget(This).
%% @hidden
getCursor(This) -> wxWindow:getCursor(This).
%% @hidden
getContainingSizer(This) -> wxWindow:getContainingSizer(This).
%% @hidden
getClientSize(This) -> wxWindow:getClientSize(This).
%% @hidden
getChildren(This) -> wxWindow:getChildren(This).
%% @hidden
getCharWidth(This) -> wxWindow:getCharWidth(This).
%% @hidden
getCharHeight(This) -> wxWindow:getCharHeight(This).
%% @hidden
getCaret(This) -> wxWindow:getCaret(This).
%% @hidden
getBestSize(This) -> wxWindow:getBestSize(This).
%% @hidden
getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This).
%% @hidden
getBackgroundColour(This) -> wxWindow:getBackgroundColour(This).
%% @hidden
getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This).
%% @hidden
freeze(This) -> wxWindow:freeze(This).
%% @hidden
fitInside(This) -> wxWindow:fitInside(This).
%% @hidden
fit(This) -> wxWindow:fit(This).
%% @hidden
findWindow(This,Id) -> wxWindow:findWindow(This,Id).
%% @hidden
enable(This, Options) -> wxWindow:enable(This, Options).
%% @hidden
enable(This) -> wxWindow:enable(This).
%% @hidden
dragAcceptFiles(This,Accept) -> wxWindow:dragAcceptFiles(This,Accept).
%% @hidden
disable(This) -> wxWindow:disable(This).
%% @hidden
destroyChildren(This) -> wxWindow:destroyChildren(This).
%% @hidden
convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz).
%% @hidden
convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz).
%% @hidden
close(This, Options) -> wxWindow:close(This, Options).
%% @hidden
close(This) -> wxWindow:close(This).
%% @hidden
clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y).
%% @hidden
clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt).
%% @hidden
clearBackground(This) -> wxWindow:clearBackground(This).
%% @hidden
centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options).
%% @hidden
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
%% @hidden
centreOnParent(This) -> wxWindow:centreOnParent(This).
%% @hidden
centerOnParent(This) -> wxWindow:centerOnParent(This).
%% @hidden
centre(This, Options) -> wxWindow:centre(This, Options).
%% @hidden
center(This, Options) -> wxWindow:center(This, Options).
%% @hidden
centre(This) -> wxWindow:centre(This).
%% @hidden
center(This) -> wxWindow:center(This).
%% @hidden
captureMouse(This) -> wxWindow:captureMouse(This).
%% @hidden
cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size).
%% From wxEvtHandler
%% @hidden
disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options).
%% @hidden
disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType).
%% @hidden
disconnect(This) -> wxEvtHandler:disconnect(This).
%% @hidden
connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options).
%% @hidden
connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxTextCtrl.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
inherited exports
@hidden
@doc See <a href="#wxtextctrlwxtextctrl">external documentation</a>.
@doc See <a href="#wxtextctrlwxtextctrl">external documentation</a>.
@doc See <a href="#wxtextctrlappendtext">external documentation</a>.
@doc See <a href="#wxtextctrlcancopy">external documentation</a>.
@doc See <a href="#wxtextctrlcancut">external documentation</a>.
@doc See <a href="#wxtextctrlcanpaste">external documentation</a>.
@doc See <a href="#wxtextctrlcanredo">external documentation</a>.
@doc See <a href="#wxtextctrlcanundo">external documentation</a>.
@doc See <a href="#wxtextctrlclear">external documentation</a>.
@doc See <a href="#wxtextctrlcopy">external documentation</a>.
@equiv create(This,Parent,Id, [])
@doc See <a href="#wxtextctrlcreate">external documentation</a>.
@doc See <a href="#wxtextctrlcut">external documentation</a>.
@doc See <a href="#wxtextctrldiscardedits">external documentation</a>.
@doc See <a href="#wxtextctrlchangevalue">external documentation</a>.
@doc See <a href="#wxtextctrlgetdefaultstyle">external documentation</a>.
@doc See <a href="#wxtextctrlgetinsertionpoint">external documentation</a>.
@doc See <a href="#wxtextctrlgetlastposition">external documentation</a>.
@doc See <a href="#wxtextctrlgetlinelength">external documentation</a>.
@doc See <a href="#wxtextctrlgetlinetext">external documentation</a>.
@doc See <a href="#wxtextctrlgetnumberoflines">external documentation</a>.
@doc See <a href="#wxtextctrlgetrange">external documentation</a>.
@doc See <a href="#wxtextctrlgetselection">external documentation</a>.
@doc See <a href="#wxtextctrlgetstringselection">external documentation</a>.
@doc See <a href="#wxtextctrlgetstyle">external documentation</a>.
@doc See <a href="#wxtextctrlgetvalue">external documentation</a>.
@doc See <a href="#wxtextctrliseditable">external documentation</a>.
@doc See <a href="#wxtextctrlismodified">external documentation</a>.
@doc See <a href="#wxtextctrlissingleline">external documentation</a>.
@equiv loadFile(This,Filename, [])
@doc See <a href="#wxtextctrlloadfile">external documentation</a>.
@doc See <a href="#wxtextctrlmarkdirty">external documentation</a>.
@doc See <a href="#wxtextctrlpositiontoxy">external documentation</a>.
@doc See <a href="#wxtextctrlredo">external documentation</a>.
@doc See <a href="#wxtextctrlremove">external documentation</a>.
@doc See <a href="#wxtextctrlreplace">external documentation</a>.
@equiv saveFile(This, [])
@doc See <a href="#wxtextctrlsavefile">external documentation</a>.
@doc See <a href="#wxtextctrlsetdefaultstyle">external documentation</a>.
@doc See <a href="#wxtextctrlseteditable">external documentation</a>.
@doc See <a href="#wxtextctrlsetinsertionpoint">external documentation</a>.
@doc See <a href="#wxtextctrlsetinsertionpointend">external documentation</a>.
@doc See <a href="#wxtextctrlsetmaxlength">external documentation</a>.
@doc See <a href="#wxtextctrlsetselection">external documentation</a>.
@doc See <a href="#wxtextctrlsetstyle">external documentation</a>.
@doc See <a href="#wxtextctrlsetvalue">external documentation</a>.
@doc See <a href="#wxtextctrlshowposition">external documentation</a>.
@doc See <a href="#wxtextctrlundo">external documentation</a>.
@doc See <a href="#wxtextctrlwritetext">external documentation</a>.
@doc See <a href="#wxtextctrlxytoposition">external documentation</a>.
@doc Destroys this object, do not use object again
From wxControl
@hidden
@hidden
From wxWindow
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
From wxEvtHandler
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(wxTextCtrl).
-include("wxe.hrl").
-export([appendText/2,canCopy/1,canCut/1,canPaste/1,canRedo/1,canUndo/1,changeValue/2,
clear/1,copy/1,create/3,create/4,cut/1,destroy/1,discardEdits/1,emulateKeyPress/2,
getDefaultStyle/1,getInsertionPoint/1,getLastPosition/1,getLineLength/2,
getLineText/2,getNumberOfLines/1,getRange/3,getSelection/1,getStringSelection/1,
getStyle/3,getValue/1,isEditable/1,isModified/1,isMultiLine/1,isSingleLine/1,
loadFile/2,loadFile/3,markDirty/1,new/0,new/2,new/3,paste/1,positionToXY/2,
redo/1,remove/3,replace/4,saveFile/1,saveFile/2,setDefaultStyle/2,setEditable/2,
setInsertionPoint/2,setInsertionPointEnd/1,setMaxLength/2,setSelection/3,
setStyle/4,setValue/2,showPosition/2,undo/1,writeText/2,xYToPosition/3]).
-export([cacheBestSize/2,canSetTransparent/1,captureMouse/1,center/1,center/2,
centerOnParent/1,centerOnParent/2,centre/1,centre/2,centreOnParent/1,
centreOnParent/2,clearBackground/1,clientToScreen/2,clientToScreen/3,
close/1,close/2,connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2,
destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3,
dragAcceptFiles/2,enable/1,enable/2,findWindow/2,fit/1,fitInside/1,
freeze/1,getAcceleratorTable/1,getBackgroundColour/1,getBackgroundStyle/1,
getBestSize/1,getCaret/1,getCharHeight/1,getCharWidth/1,getChildren/1,
getClientSize/1,getContainingSizer/1,getContentScaleFactor/1,getCursor/1,
getDPI/1,getDPIScaleFactor/1,getDropTarget/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1,
getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2,
getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2,
getTextExtent/3,getThemeEnabled/1,getToolTip/1,getUpdateRegion/1,
getVirtualSize/1,getWindowStyleFlag/1,getWindowVariant/1,hasCapture/1,
hasScrollbar/2,hasTransparentBackground/1,hide/1,inheritAttributes/1,
initDialog/1,invalidateBestSize/1,isDoubleBuffered/1,isEnabled/1,
isExposed/2,isExposed/3,isExposed/5,isFrozen/1,isRetained/1,isShown/1,
isShownOnScreen/1,isTopLevel/1,layout/1,lineDown/1,lineUp/1,lower/1,
move/2,move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,
navigate/1,navigate/2,pageDown/1,pageUp/1,parent_class/1,popupMenu/2,
popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2,refreshRect/3,
releaseMouse/1,removeChild/2,reparent/2,screenToClient/1,screenToClient/2,
scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4,setAcceleratorTable/2,
setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2,setCaret/2,
setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2,
setDoubleBuffered/2,setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,
setFont/2,setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2,
setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2,
setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6,
setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3,
setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3,
setThemeEnabled/2,setToolTip/2,setTransparent/2,setVirtualSize/2,
setVirtualSize/3,setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,
shouldInheritColours/1,show/1,show/2,thaw/1,transferDataFromWindow/1,
transferDataToWindow/1,update/1,updateWindowUI/1,updateWindowUI/2,
validate/1,warpPointer/3]).
-type wxTextCtrl() :: wx:wx_object().
-export_type([wxTextCtrl/0]).
parent_class(wxControl) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-spec new() -> wxTextCtrl().
new() ->
wxe_util:queue_cmd(?get_env(), ?wxTextCtrl_new_0),
wxe_util:rec(?wxTextCtrl_new_0).
@equiv new(Parent , Id , [ ] )
-spec new(Parent, Id) -> wxTextCtrl() when
Parent::wxWindow:wxWindow(), Id::integer().
new(Parent,Id)
when is_record(Parent, wx_ref),is_integer(Id) ->
new(Parent,Id, []).
-spec new(Parent, Id, [Option]) -> wxTextCtrl() when
Parent::wxWindow:wxWindow(), Id::integer(),
Option :: {'value', unicode:chardata()}
| {'pos', {X::integer(), Y::integer()}}
| {'size', {W::integer(), H::integer()}}
| {'style', integer()}
| {'validator', wx:wx_object()}.
new(#wx_ref{type=ParentT}=Parent,Id, Options)
when is_integer(Id),is_list(Options) ->
?CLASS(ParentT,wxWindow),
MOpts = fun({value, Value}) -> Value_UC = unicode:characters_to_binary(Value),{value,Value_UC};
({pos, {_posX,_posY}} = Arg) -> Arg;
({size, {_sizeW,_sizeH}} = Arg) -> Arg;
({style, _style} = Arg) -> Arg;
({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Parent,Id, Opts,?get_env(),?wxTextCtrl_new_3),
wxe_util:rec(?wxTextCtrl_new_3).
-spec appendText(This, Text) -> 'ok' when
This::wxTextCtrl(), Text::unicode:chardata().
appendText(#wx_ref{type=ThisT}=This,Text)
when ?is_chardata(Text) ->
?CLASS(ThisT,wxTextCtrl),
Text_UC = unicode:characters_to_binary(Text),
wxe_util:queue_cmd(This,Text_UC,?get_env(),?wxTextCtrl_AppendText).
-spec canCopy(This) -> boolean() when
This::wxTextCtrl().
canCopy(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanCopy),
wxe_util:rec(?wxTextCtrl_CanCopy).
-spec canCut(This) -> boolean() when
This::wxTextCtrl().
canCut(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanCut),
wxe_util:rec(?wxTextCtrl_CanCut).
-spec canPaste(This) -> boolean() when
This::wxTextCtrl().
canPaste(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanPaste),
wxe_util:rec(?wxTextCtrl_CanPaste).
-spec canRedo(This) -> boolean() when
This::wxTextCtrl().
canRedo(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanRedo),
wxe_util:rec(?wxTextCtrl_CanRedo).
-spec canUndo(This) -> boolean() when
This::wxTextCtrl().
canUndo(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_CanUndo),
wxe_util:rec(?wxTextCtrl_CanUndo).
-spec clear(This) -> 'ok' when
This::wxTextCtrl().
clear(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Clear).
-spec copy(This) -> 'ok' when
This::wxTextCtrl().
copy(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Copy).
-spec create(This, Parent, Id) -> boolean() when
This::wxTextCtrl(), Parent::wxWindow:wxWindow(), Id::integer().
create(This,Parent,Id)
when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id) ->
create(This,Parent,Id, []).
-spec create(This, Parent, Id, [Option]) -> boolean() when
This::wxTextCtrl(), Parent::wxWindow:wxWindow(), Id::integer(),
Option :: {'value', unicode:chardata()}
| {'pos', {X::integer(), Y::integer()}}
| {'size', {W::integer(), H::integer()}}
| {'style', integer()}
| {'validator', wx:wx_object()}.
create(#wx_ref{type=ThisT}=This,#wx_ref{type=ParentT}=Parent,Id, Options)
when is_integer(Id),is_list(Options) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(ParentT,wxWindow),
MOpts = fun({value, Value}) -> Value_UC = unicode:characters_to_binary(Value),{value,Value_UC};
({pos, {_posX,_posY}} = Arg) -> Arg;
({size, {_sizeW,_sizeH}} = Arg) -> Arg;
({style, _style} = Arg) -> Arg;
({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Parent,Id, Opts,?get_env(),?wxTextCtrl_Create),
wxe_util:rec(?wxTextCtrl_Create).
-spec cut(This) -> 'ok' when
This::wxTextCtrl().
cut(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Cut).
-spec discardEdits(This) -> 'ok' when
This::wxTextCtrl().
discardEdits(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_DiscardEdits).
-spec changeValue(This, Value) -> 'ok' when
This::wxTextCtrl(), Value::unicode:chardata().
changeValue(#wx_ref{type=ThisT}=This,Value)
when ?is_chardata(Value) ->
?CLASS(ThisT,wxTextCtrl),
Value_UC = unicode:characters_to_binary(Value),
wxe_util:queue_cmd(This,Value_UC,?get_env(),?wxTextCtrl_ChangeValue).
@doc See < a href=" / manuals/2.8.12 / wx_wxtextctrl.html#wxtextctrlemulatekeypress">external documentation</a > .
-spec emulateKeyPress(This, Event) -> boolean() when
This::wxTextCtrl(), Event::wxKeyEvent:wxKeyEvent().
emulateKeyPress(#wx_ref{type=ThisT}=This,#wx_ref{type=EventT}=Event) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(EventT,wxKeyEvent),
wxe_util:queue_cmd(This,Event,?get_env(),?wxTextCtrl_EmulateKeyPress),
wxe_util:rec(?wxTextCtrl_EmulateKeyPress).
-spec getDefaultStyle(This) -> wxTextAttr:wxTextAttr() when
This::wxTextCtrl().
getDefaultStyle(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetDefaultStyle),
wxe_util:rec(?wxTextCtrl_GetDefaultStyle).
-spec getInsertionPoint(This) -> integer() when
This::wxTextCtrl().
getInsertionPoint(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetInsertionPoint),
wxe_util:rec(?wxTextCtrl_GetInsertionPoint).
-spec getLastPosition(This) -> integer() when
This::wxTextCtrl().
getLastPosition(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetLastPosition),
wxe_util:rec(?wxTextCtrl_GetLastPosition).
-spec getLineLength(This, LineNo) -> integer() when
This::wxTextCtrl(), LineNo::integer().
getLineLength(#wx_ref{type=ThisT}=This,LineNo)
when is_integer(LineNo) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,LineNo,?get_env(),?wxTextCtrl_GetLineLength),
wxe_util:rec(?wxTextCtrl_GetLineLength).
-spec getLineText(This, LineNo) -> unicode:charlist() when
This::wxTextCtrl(), LineNo::integer().
getLineText(#wx_ref{type=ThisT}=This,LineNo)
when is_integer(LineNo) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,LineNo,?get_env(),?wxTextCtrl_GetLineText),
wxe_util:rec(?wxTextCtrl_GetLineText).
-spec getNumberOfLines(This) -> integer() when
This::wxTextCtrl().
getNumberOfLines(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetNumberOfLines),
wxe_util:rec(?wxTextCtrl_GetNumberOfLines).
-spec getRange(This, From, To) -> unicode:charlist() when
This::wxTextCtrl(), From::integer(), To::integer().
getRange(#wx_ref{type=ThisT}=This,From,To)
when is_integer(From),is_integer(To) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,From,To,?get_env(),?wxTextCtrl_GetRange),
wxe_util:rec(?wxTextCtrl_GetRange).
-spec getSelection(This) -> {From::integer(), To::integer()} when
This::wxTextCtrl().
getSelection(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetSelection),
wxe_util:rec(?wxTextCtrl_GetSelection).
-spec getStringSelection(This) -> unicode:charlist() when
This::wxTextCtrl().
getStringSelection(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetStringSelection),
wxe_util:rec(?wxTextCtrl_GetStringSelection).
-spec getStyle(This, Position, Style) -> boolean() when
This::wxTextCtrl(), Position::integer(), Style::wxTextAttr:wxTextAttr().
getStyle(#wx_ref{type=ThisT}=This,Position,#wx_ref{type=StyleT}=Style)
when is_integer(Position) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(StyleT,wxTextAttr),
wxe_util:queue_cmd(This,Position,Style,?get_env(),?wxTextCtrl_GetStyle),
wxe_util:rec(?wxTextCtrl_GetStyle).
-spec getValue(This) -> unicode:charlist() when
This::wxTextCtrl().
getValue(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_GetValue),
wxe_util:rec(?wxTextCtrl_GetValue).
-spec isEditable(This) -> boolean() when
This::wxTextCtrl().
isEditable(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_IsEditable),
wxe_util:rec(?wxTextCtrl_IsEditable).
-spec isModified(This) -> boolean() when
This::wxTextCtrl().
isModified(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_IsModified),
wxe_util:rec(?wxTextCtrl_IsModified).
@doc See < a href=" / manuals/2.8.12 / wx_wxtextctrl.html#wxtextctrlismultiline">external documentation</a > .
-spec isMultiLine(This) -> boolean() when
This::wxTextCtrl().
isMultiLine(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_IsMultiLine),
wxe_util:rec(?wxTextCtrl_IsMultiLine).
-spec isSingleLine(This) -> boolean() when
This::wxTextCtrl().
isSingleLine(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_IsSingleLine),
wxe_util:rec(?wxTextCtrl_IsSingleLine).
-spec loadFile(This, Filename) -> boolean() when
This::wxTextCtrl(), Filename::unicode:chardata().
loadFile(This,Filename)
when is_record(This, wx_ref),?is_chardata(Filename) ->
loadFile(This,Filename, []).
-spec loadFile(This, Filename, [Option]) -> boolean() when
This::wxTextCtrl(), Filename::unicode:chardata(),
Option :: {'fileType', integer()}.
loadFile(#wx_ref{type=ThisT}=This,Filename, Options)
when ?is_chardata(Filename),is_list(Options) ->
?CLASS(ThisT,wxTextCtrl),
Filename_UC = unicode:characters_to_binary(Filename),
MOpts = fun({fileType, _fileType} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Filename_UC, Opts,?get_env(),?wxTextCtrl_LoadFile),
wxe_util:rec(?wxTextCtrl_LoadFile).
-spec markDirty(This) -> 'ok' when
This::wxTextCtrl().
markDirty(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_MarkDirty).
@doc See < a href=" / manuals/2.8.12 / wx_wxtextctrl.html#wxtextctrlpaste">external documentation</a > .
-spec paste(This) -> 'ok' when
This::wxTextCtrl().
paste(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Paste).
-spec positionToXY(This, Pos) -> Result when
Result ::{Res ::boolean(), X::integer(), Y::integer()},
This::wxTextCtrl(), Pos::integer().
positionToXY(#wx_ref{type=ThisT}=This,Pos)
when is_integer(Pos) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Pos,?get_env(),?wxTextCtrl_PositionToXY),
wxe_util:rec(?wxTextCtrl_PositionToXY).
-spec redo(This) -> 'ok' when
This::wxTextCtrl().
redo(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Redo).
-spec remove(This, From, To) -> 'ok' when
This::wxTextCtrl(), From::integer(), To::integer().
remove(#wx_ref{type=ThisT}=This,From,To)
when is_integer(From),is_integer(To) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,From,To,?get_env(),?wxTextCtrl_Remove).
-spec replace(This, From, To, Value) -> 'ok' when
This::wxTextCtrl(), From::integer(), To::integer(), Value::unicode:chardata().
replace(#wx_ref{type=ThisT}=This,From,To,Value)
when is_integer(From),is_integer(To),?is_chardata(Value) ->
?CLASS(ThisT,wxTextCtrl),
Value_UC = unicode:characters_to_binary(Value),
wxe_util:queue_cmd(This,From,To,Value_UC,?get_env(),?wxTextCtrl_Replace).
-spec saveFile(This) -> boolean() when
This::wxTextCtrl().
saveFile(This)
when is_record(This, wx_ref) ->
saveFile(This, []).
-spec saveFile(This, [Option]) -> boolean() when
This::wxTextCtrl(),
Option :: {'file', unicode:chardata()}
| {'fileType', integer()}.
saveFile(#wx_ref{type=ThisT}=This, Options)
when is_list(Options) ->
?CLASS(ThisT,wxTextCtrl),
MOpts = fun({file, File}) -> File_UC = unicode:characters_to_binary(File),{file,File_UC};
({fileType, _fileType} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This, Opts,?get_env(),?wxTextCtrl_SaveFile),
wxe_util:rec(?wxTextCtrl_SaveFile).
-spec setDefaultStyle(This, Style) -> boolean() when
This::wxTextCtrl(), Style::wxTextAttr:wxTextAttr().
setDefaultStyle(#wx_ref{type=ThisT}=This,#wx_ref{type=StyleT}=Style) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(StyleT,wxTextAttr),
wxe_util:queue_cmd(This,Style,?get_env(),?wxTextCtrl_SetDefaultStyle),
wxe_util:rec(?wxTextCtrl_SetDefaultStyle).
-spec setEditable(This, Editable) -> 'ok' when
This::wxTextCtrl(), Editable::boolean().
setEditable(#wx_ref{type=ThisT}=This,Editable)
when is_boolean(Editable) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Editable,?get_env(),?wxTextCtrl_SetEditable).
-spec setInsertionPoint(This, Pos) -> 'ok' when
This::wxTextCtrl(), Pos::integer().
setInsertionPoint(#wx_ref{type=ThisT}=This,Pos)
when is_integer(Pos) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Pos,?get_env(),?wxTextCtrl_SetInsertionPoint).
-spec setInsertionPointEnd(This) -> 'ok' when
This::wxTextCtrl().
setInsertionPointEnd(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_SetInsertionPointEnd).
-spec setMaxLength(This, Len) -> 'ok' when
This::wxTextCtrl(), Len::integer().
setMaxLength(#wx_ref{type=ThisT}=This,Len)
when is_integer(Len) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Len,?get_env(),?wxTextCtrl_SetMaxLength).
-spec setSelection(This, From, To) -> 'ok' when
This::wxTextCtrl(), From::integer(), To::integer().
setSelection(#wx_ref{type=ThisT}=This,From,To)
when is_integer(From),is_integer(To) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,From,To,?get_env(),?wxTextCtrl_SetSelection).
-spec setStyle(This, Start, End, Style) -> boolean() when
This::wxTextCtrl(), Start::integer(), End::integer(), Style::wxTextAttr:wxTextAttr().
setStyle(#wx_ref{type=ThisT}=This,Start,End,#wx_ref{type=StyleT}=Style)
when is_integer(Start),is_integer(End) ->
?CLASS(ThisT,wxTextCtrl),
?CLASS(StyleT,wxTextAttr),
wxe_util:queue_cmd(This,Start,End,Style,?get_env(),?wxTextCtrl_SetStyle),
wxe_util:rec(?wxTextCtrl_SetStyle).
-spec setValue(This, Value) -> 'ok' when
This::wxTextCtrl(), Value::unicode:chardata().
setValue(#wx_ref{type=ThisT}=This,Value)
when ?is_chardata(Value) ->
?CLASS(ThisT,wxTextCtrl),
Value_UC = unicode:characters_to_binary(Value),
wxe_util:queue_cmd(This,Value_UC,?get_env(),?wxTextCtrl_SetValue).
-spec showPosition(This, Pos) -> 'ok' when
This::wxTextCtrl(), Pos::integer().
showPosition(#wx_ref{type=ThisT}=This,Pos)
when is_integer(Pos) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,Pos,?get_env(),?wxTextCtrl_ShowPosition).
-spec undo(This) -> 'ok' when
This::wxTextCtrl().
undo(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,?get_env(),?wxTextCtrl_Undo).
-spec writeText(This, Text) -> 'ok' when
This::wxTextCtrl(), Text::unicode:chardata().
writeText(#wx_ref{type=ThisT}=This,Text)
when ?is_chardata(Text) ->
?CLASS(ThisT,wxTextCtrl),
Text_UC = unicode:characters_to_binary(Text),
wxe_util:queue_cmd(This,Text_UC,?get_env(),?wxTextCtrl_WriteText).
-spec xYToPosition(This, X, Y) -> integer() when
This::wxTextCtrl(), X::integer(), Y::integer().
xYToPosition(#wx_ref{type=ThisT}=This,X,Y)
when is_integer(X),is_integer(Y) ->
?CLASS(ThisT,wxTextCtrl),
wxe_util:queue_cmd(This,X,Y,?get_env(),?wxTextCtrl_XYToPosition),
wxe_util:rec(?wxTextCtrl_XYToPosition).
-spec destroy(This::wxTextCtrl()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxTextCtrl),
wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT),
ok.
setLabel(This,Label) -> wxControl:setLabel(This,Label).
getLabel(This) -> wxControl:getLabel(This).
getDPI(This) -> wxWindow:getDPI(This).
getContentScaleFactor(This) -> wxWindow:getContentScaleFactor(This).
setDoubleBuffered(This,On) -> wxWindow:setDoubleBuffered(This,On).
isDoubleBuffered(This) -> wxWindow:isDoubleBuffered(This).
canSetTransparent(This) -> wxWindow:canSetTransparent(This).
setTransparent(This,Alpha) -> wxWindow:setTransparent(This,Alpha).
warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y).
validate(This) -> wxWindow:validate(This).
updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options).
updateWindowUI(This) -> wxWindow:updateWindowUI(This).
update(This) -> wxWindow:update(This).
transferDataToWindow(This) -> wxWindow:transferDataToWindow(This).
transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This).
thaw(This) -> wxWindow:thaw(This).
show(This, Options) -> wxWindow:show(This, Options).
show(This) -> wxWindow:show(This).
shouldInheritColours(This) -> wxWindow:shouldInheritColours(This).
setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant).
setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style).
setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style).
setVirtualSize(This,Width,Height) -> wxWindow:setVirtualSize(This,Width,Height).
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
setToolTip(This,TipString) -> wxWindow:setToolTip(This,TipString).
setThemeEnabled(This,Enable) -> wxWindow:setThemeEnabled(This,Enable).
setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options).
setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer).
setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options).
setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer).
setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options).
setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH).
setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize).
setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options).
setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height).
setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height).
setSize(This,Rect) -> wxWindow:setSize(This,Rect).
setScrollPos(This,Orientation,Pos, Options) -> wxWindow:setScrollPos(This,Orientation,Pos, Options).
setScrollPos(This,Orientation,Pos) -> wxWindow:setScrollPos(This,Orientation,Pos).
setScrollbar(This,Orientation,Position,ThumbSize,Range, Options) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range, Options).
setScrollbar(This,Orientation,Position,ThumbSize,Range) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range).
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
setName(This,Name) -> wxWindow:setName(This,Name).
setId(This,Winid) -> wxWindow:setId(This,Winid).
setHelpText(This,HelpText) -> wxWindow:setHelpText(This,HelpText).
setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour).
setFont(This,Font) -> wxWindow:setFont(This,Font).
setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This).
setFocus(This) -> wxWindow:setFocus(This).
setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle).
setDropTarget(This,Target) -> wxWindow:setDropTarget(This,Target).
setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour).
setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font).
setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour).
setMinSize(This,Size) -> wxWindow:setMinSize(This,Size).
setMaxSize(This,Size) -> wxWindow:setMaxSize(This,Size).
setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor).
setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer).
setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height).
setClientSize(This,Size) -> wxWindow:setClientSize(This,Size).
setCaret(This,Caret) -> wxWindow:setCaret(This,Caret).
setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style).
setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour).
setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout).
setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel).
scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options).
scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy).
scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages).
scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines).
screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt).
screenToClient(This) -> wxWindow:screenToClient(This).
reparent(This,NewParent) -> wxWindow:reparent(This,NewParent).
removeChild(This,Child) -> wxWindow:removeChild(This,Child).
releaseMouse(This) -> wxWindow:releaseMouse(This).
refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options).
refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect).
refresh(This, Options) -> wxWindow:refresh(This, Options).
refresh(This) -> wxWindow:refresh(This).
raise(This) -> wxWindow:raise(This).
popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y).
popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options).
popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu).
pageUp(This) -> wxWindow:pageUp(This).
pageDown(This) -> wxWindow:pageDown(This).
navigate(This, Options) -> wxWindow:navigate(This, Options).
navigate(This) -> wxWindow:navigate(This).
moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win).
moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win).
move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options).
move(This,X,Y) -> wxWindow:move(This,X,Y).
move(This,Pt) -> wxWindow:move(This,Pt).
lower(This) -> wxWindow:lower(This).
lineUp(This) -> wxWindow:lineUp(This).
lineDown(This) -> wxWindow:lineDown(This).
layout(This) -> wxWindow:layout(This).
isShownOnScreen(This) -> wxWindow:isShownOnScreen(This).
isTopLevel(This) -> wxWindow:isTopLevel(This).
isShown(This) -> wxWindow:isShown(This).
isRetained(This) -> wxWindow:isRetained(This).
isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H).
isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y).
isExposed(This,Pt) -> wxWindow:isExposed(This,Pt).
isEnabled(This) -> wxWindow:isEnabled(This).
isFrozen(This) -> wxWindow:isFrozen(This).
invalidateBestSize(This) -> wxWindow:invalidateBestSize(This).
initDialog(This) -> wxWindow:initDialog(This).
inheritAttributes(This) -> wxWindow:inheritAttributes(This).
hide(This) -> wxWindow:hide(This).
hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This).
hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient).
hasCapture(This) -> wxWindow:hasCapture(This).
getWindowVariant(This) -> wxWindow:getWindowVariant(This).
getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This).
getVirtualSize(This) -> wxWindow:getVirtualSize(This).
getUpdateRegion(This) -> wxWindow:getUpdateRegion(This).
getToolTip(This) -> wxWindow:getToolTip(This).
getThemeEnabled(This) -> wxWindow:getThemeEnabled(This).
getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options).
getTextExtent(This,String) -> wxWindow:getTextExtent(This,String).
getSizer(This) -> wxWindow:getSizer(This).
getSize(This) -> wxWindow:getSize(This).
getScrollThumb(This,Orientation) -> wxWindow:getScrollThumb(This,Orientation).
getScrollRange(This,Orientation) -> wxWindow:getScrollRange(This,Orientation).
getScrollPos(This,Orientation) -> wxWindow:getScrollPos(This,Orientation).
getScreenRect(This) -> wxWindow:getScreenRect(This).
getScreenPosition(This) -> wxWindow:getScreenPosition(This).
getRect(This) -> wxWindow:getRect(This).
getPosition(This) -> wxWindow:getPosition(This).
getParent(This) -> wxWindow:getParent(This).
getName(This) -> wxWindow:getName(This).
getMinSize(This) -> wxWindow:getMinSize(This).
getMaxSize(This) -> wxWindow:getMaxSize(This).
getId(This) -> wxWindow:getId(This).
getHelpText(This) -> wxWindow:getHelpText(This).
getHandle(This) -> wxWindow:getHandle(This).
getGrandParent(This) -> wxWindow:getGrandParent(This).
getForegroundColour(This) -> wxWindow:getForegroundColour(This).
getFont(This) -> wxWindow:getFont(This).
getExtraStyle(This) -> wxWindow:getExtraStyle(This).
getDPIScaleFactor(This) -> wxWindow:getDPIScaleFactor(This).
getDropTarget(This) -> wxWindow:getDropTarget(This).
getCursor(This) -> wxWindow:getCursor(This).
getContainingSizer(This) -> wxWindow:getContainingSizer(This).
getClientSize(This) -> wxWindow:getClientSize(This).
getChildren(This) -> wxWindow:getChildren(This).
getCharWidth(This) -> wxWindow:getCharWidth(This).
getCharHeight(This) -> wxWindow:getCharHeight(This).
getCaret(This) -> wxWindow:getCaret(This).
getBestSize(This) -> wxWindow:getBestSize(This).
getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This).
getBackgroundColour(This) -> wxWindow:getBackgroundColour(This).
getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This).
freeze(This) -> wxWindow:freeze(This).
fitInside(This) -> wxWindow:fitInside(This).
fit(This) -> wxWindow:fit(This).
findWindow(This,Id) -> wxWindow:findWindow(This,Id).
enable(This, Options) -> wxWindow:enable(This, Options).
enable(This) -> wxWindow:enable(This).
dragAcceptFiles(This,Accept) -> wxWindow:dragAcceptFiles(This,Accept).
disable(This) -> wxWindow:disable(This).
destroyChildren(This) -> wxWindow:destroyChildren(This).
convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz).
convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz).
close(This, Options) -> wxWindow:close(This, Options).
close(This) -> wxWindow:close(This).
clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y).
clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt).
clearBackground(This) -> wxWindow:clearBackground(This).
centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options).
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
centreOnParent(This) -> wxWindow:centreOnParent(This).
centerOnParent(This) -> wxWindow:centerOnParent(This).
centre(This, Options) -> wxWindow:centre(This, Options).
center(This, Options) -> wxWindow:center(This, Options).
centre(This) -> wxWindow:centre(This).
center(This) -> wxWindow:center(This).
captureMouse(This) -> wxWindow:captureMouse(This).
cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size).
disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options).
disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType).
disconnect(This) -> wxEvtHandler:disconnect(This).
connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options).
connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
|
7766af2215ee792d698a2017ceabaa339f9b6c117f89e24c053545f6def1ad54 | robert-strandh/SICL | direct-slot-definition-class.lisp | (cl:in-package #:sicl-clos)
;;; For the specification of this generic function, see
;;; -MOP/direct-slot-definition-class.html
(defgeneric direct-slot-definition-class (class &rest initargs))
(defmethod direct-slot-definition-class
((class regular-class) &rest initargs)
(declare (ignore class initargs))
(find-class 'standard-direct-slot-definition))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/0de61f577f31d7e9048ac444bfdc031c12fcb212/Code/CLOS/direct-slot-definition-class.lisp | lisp | For the specification of this generic function, see
-MOP/direct-slot-definition-class.html | (cl:in-package #:sicl-clos)
(defgeneric direct-slot-definition-class (class &rest initargs))
(defmethod direct-slot-definition-class
((class regular-class) &rest initargs)
(declare (ignore class initargs))
(find-class 'standard-direct-slot-definition))
|
02988bfc831754c569f506c9c4ba19bc047c36df9ad5ec5cc3a02a42c2339c80 | acieroid/scala-am | organigram.scm | (define organigram
'(directeur
(hoofd-verkoop (verkoopsleider-vlaanderen)
(verkoopsleider-brussel))
(hoofd-productie (hoofd-inkoop (bediende1)
(bediende2)
(bediende3))
(hoofd-fakturen))
(hoofd-administratie (hoofd-personeel)
(hoofd-boekhouding))))
(define (baas organigram) (car organigram))
(define (sub-organigrammen organigram) (cdr organigram))
(define (hierarchisch? p1 p2 organigram)
(define (hierarchisch?-in path organigrammen)
(if (null? organigrammen)
#f
(or (hierarchisch? path (car organigrammen))
(hierarchisch?-in path (cdr organigrammen)))))
(define (hierarchisch? path organigram)
(cond
((and (eq? p1 (baas organigram)) (member p2 path)) #t)
((and (eq? p2 (baas organigram)) (member p1 path)) #t)
(else (hierarchisch?-in (cons (baas organigram) path)
(sub-organigrammen organigram)))))
(hierarchisch? '() organigram))
(define (collegas p organigram)
(define (collegas-in oversten organigrammen)
(if (null? organigrammen)
#f
(or (collegas oversten (car organigrammen))
(collegas-in oversten (cdr organigrammen)))))
(define (werknemers-in organigrammen)
(if (null? organigrammen)
'()
(append (werknemers (car organigrammen))
(werknemers-in (cdr organigrammen)))))
(define (werknemers organigram)
(cons (baas organigram)
(werknemers-in (sub-organigrammen organigram))))
(define (collegas oversten organigram)
(if (eq? p (baas organigram))
(append oversten
(werknemers-in (sub-organigrammen organigram)))
(collegas-in (cons (baas organigram) oversten)
(sub-organigrammen organigram))))
(collegas '() organigram))
(and (hierarchisch? 'directeur 'verkoopsleider-brussel organigram)
(hierarchisch? 'bediende1 'hoofd-productie organigram)
(not (hierarchisch? 'hoofd-personeel 'bediende3 organigram))
(equal? (collegas 'hoofd-inkoop organigram) '(hoofd-productie directeur bediende1 bediende2 bediende3)))
| null | https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/R5RS/scp1/organigram.scm | scheme | (define organigram
'(directeur
(hoofd-verkoop (verkoopsleider-vlaanderen)
(verkoopsleider-brussel))
(hoofd-productie (hoofd-inkoop (bediende1)
(bediende2)
(bediende3))
(hoofd-fakturen))
(hoofd-administratie (hoofd-personeel)
(hoofd-boekhouding))))
(define (baas organigram) (car organigram))
(define (sub-organigrammen organigram) (cdr organigram))
(define (hierarchisch? p1 p2 organigram)
(define (hierarchisch?-in path organigrammen)
(if (null? organigrammen)
#f
(or (hierarchisch? path (car organigrammen))
(hierarchisch?-in path (cdr organigrammen)))))
(define (hierarchisch? path organigram)
(cond
((and (eq? p1 (baas organigram)) (member p2 path)) #t)
((and (eq? p2 (baas organigram)) (member p1 path)) #t)
(else (hierarchisch?-in (cons (baas organigram) path)
(sub-organigrammen organigram)))))
(hierarchisch? '() organigram))
(define (collegas p organigram)
(define (collegas-in oversten organigrammen)
(if (null? organigrammen)
#f
(or (collegas oversten (car organigrammen))
(collegas-in oversten (cdr organigrammen)))))
(define (werknemers-in organigrammen)
(if (null? organigrammen)
'()
(append (werknemers (car organigrammen))
(werknemers-in (cdr organigrammen)))))
(define (werknemers organigram)
(cons (baas organigram)
(werknemers-in (sub-organigrammen organigram))))
(define (collegas oversten organigram)
(if (eq? p (baas organigram))
(append oversten
(werknemers-in (sub-organigrammen organigram)))
(collegas-in (cons (baas organigram) oversten)
(sub-organigrammen organigram))))
(collegas '() organigram))
(and (hierarchisch? 'directeur 'verkoopsleider-brussel organigram)
(hierarchisch? 'bediende1 'hoofd-productie organigram)
(not (hierarchisch? 'hoofd-personeel 'bediende3 organigram))
(equal? (collegas 'hoofd-inkoop organigram) '(hoofd-productie directeur bediende1 bediende2 bediende3)))
|
|
bf493561e9580ad87e01f318a3274706023e7370ec73cdcda4227d136782c1bb | pepeiborra/ghc-check | PackageDb.hs | # LANGUAGE CPP #
{-# LANGUAGE DeriveLift #-}
# OPTIONS_GHC -Wall #
| Discover the GHC version via the package database . Requirements :
--
-- * the package database must be compatible, which is usually not the case
across major ghc versions .
--
-- * the 'ghc' package is registered, which is not always the case.
module GHC.Check.PackageDb
( PackageVersion(abi), version,
getPackageVersion,
fromVersionString
)
where
import Control.Monad.Trans.Class as Monad (MonadTrans (lift))
import Data.String (IsString (fromString))
import Data.Version (Version)
import Language.Haskell.TH.Syntax (Lift)
import Data.Foldable (find)
import Control.Applicative (Alternative((<|>)))
#if MIN_VERSION_ghc(9,2,0)
import GHC
(Ghc,
getSession,
)
import GHC.Data.Maybe (MaybeT (MaybeT), runMaybeT)
import qualified GHC.Data.ShortText as ShortText
import GHC.Driver.Env (hsc_unit_env, )
import GHC.Unit.Info (PackageName (PackageName))
import GHC.Unit.Env (ue_units)
import GHC.Unit.State
(lookupUnit, explicitUnits, lookupUnitId,
lookupPackageName, GenericUnitInfo (..),
UnitInfo, unitPackageNameString)
#if !MIN_VERSION_ghc(9,4,0)
import GHC.Unit.Types (indefUnit)
#endif
#elif MIN_VERSION_ghc(9,0,1)
import GHC
(unitState, Ghc,
getSessionDynFlags,
)
import GHC.Data.Maybe (MaybeT (MaybeT), runMaybeT)
import GHC.Unit.Info (PackageName (PackageName))
import GHC.Unit.State
(lookupUnit, explicitUnits, lookupUnitId,
lookupPackageName, GenericUnitInfo (..),
UnitInfo, unitPackageNameString)
import GHC.Unit.Types (indefUnit)
#else
import GHC
(pkgState, Ghc,
getSessionDynFlags,
)
import Maybes (MaybeT (MaybeT), runMaybeT)
import Module (componentIdToInstalledUnitId)
import PackageConfig (PackageName (PackageName))
import Packages
(lookupPackage, explicitPackages, lookupInstalledPackage,
lookupPackageName
)
import Packages (InstalledPackageInfo (packageVersion, abiHash))
import Packages (PackageConfig)
import Packages (packageNameString)
#endif
import GHC.Stack (HasCallStack)
import GHC.Check.Util
data PackageVersion
= PackageVersion
{ myVersion :: !MyVersion,
abi :: Maybe String
}
deriving (Eq, Lift, Show)
version :: PackageVersion -> Version
version PackageVersion{ myVersion = MyVersion v} = v
#if MIN_VERSION_ghc(9,4,0)
indefUnit :: a -> a
indefUnit = id
#endif
#if MIN_VERSION_ghc(9,2,0)
| @getPackageVersion p@ returns the version of package @p@ that will be used in the Ghc session .
getPackageVersion :: String -> Ghc (Maybe PackageVersion)
getPackageVersion pName = runMaybeT $ do
hsc_env <- Monad.lift getSession
let pkgst = ue_units $ hsc_unit_env hsc_env
depends =
#if MIN_VERSION_ghc(9,4,0)
map fst $
#endif
explicitUnits pkgst
let explicit = do
pkgs <- traverse (MaybeT . return . lookupUnit pkgst) depends
MaybeT $ return $ find (\p -> unitPackageNameString p == pName ) pkgs
notExplicit = do
component <- MaybeT $ return $ lookupPackageName pkgst $ PackageName $ fromString pName
MaybeT $ return $ lookupUnitId pkgst (indefUnit component)
p <- explicit <|> notExplicit
return $ fromPackageConfig p
fromPackageConfig :: UnitInfo -> PackageVersion
fromPackageConfig p = PackageVersion (MyVersion $ unitPackageVersion p) (Just $ ShortText.unpack $ unitAbiHash p)
#elif MIN_VERSION_ghc(9,0,1)
| @getPackageVersion p@ returns the version of package @p@ that will be used in the Ghc session .
getPackageVersion :: String -> Ghc (Maybe PackageVersion)
getPackageVersion pName = runMaybeT $ do
dflags <- Monad.lift getSessionDynFlags
let pkgst = unitState dflags
depends = explicitUnits pkgst
let explicit = do
pkgs <- traverse (MaybeT . return . lookupUnit pkgst) depends
MaybeT $ return $ find (\p -> unitPackageNameString p == pName ) pkgs
notExplicit = do
component <- MaybeT $ return $ lookupPackageName pkgst $ PackageName $ fromString pName
MaybeT $ return $ lookupUnitId pkgst (indefUnit component)
p <- explicit <|> notExplicit
return $ fromPackageConfig p
fromPackageConfig :: UnitInfo -> PackageVersion
fromPackageConfig p = PackageVersion (MyVersion $ unitPackageVersion p) (Just $ unitAbiHash p)
#else
| @getPackageVersion p@ returns the version of package @p@ that will be used in the Ghc session .
getPackageVersion :: String -> Ghc (Maybe PackageVersion)
getPackageVersion pName = runMaybeT $ do
dflags <- Monad.lift getSessionDynFlags
let pkgst = pkgState dflags
depends = explicitPackages pkgst
let explicit = do
pkgs <- traverse (MaybeT . return . lookupPackage dflags) depends
MaybeT $ return $ find (\p -> packageNameString p == pName ) pkgs
notExplicit = do
component <- MaybeT $ return $ lookupPackageName dflags $ PackageName $ fromString pName
MaybeT $ return $ lookupInstalledPackage dflags (componentIdToInstalledUnitId component)
p <- explicit <|> notExplicit
return $ fromPackageConfig p
fromPackageConfig :: PackageConfig -> PackageVersion
fromPackageConfig p = PackageVersion (MyVersion $ packageVersion p) (Just $ abiHash p)
#endif
fromVersionString :: HasCallStack => String -> PackageVersion
fromVersionString v = PackageVersion (read v) Nothing
| null | https://raw.githubusercontent.com/pepeiborra/ghc-check/24da337aaecd5248cee575ddbff44bf736af58e6/src/GHC/Check/PackageDb.hs | haskell | # LANGUAGE DeriveLift #
* the package database must be compatible, which is usually not the case
* the 'ghc' package is registered, which is not always the case. | # LANGUAGE CPP #
# OPTIONS_GHC -Wall #
| Discover the GHC version via the package database . Requirements :
across major ghc versions .
module GHC.Check.PackageDb
( PackageVersion(abi), version,
getPackageVersion,
fromVersionString
)
where
import Control.Monad.Trans.Class as Monad (MonadTrans (lift))
import Data.String (IsString (fromString))
import Data.Version (Version)
import Language.Haskell.TH.Syntax (Lift)
import Data.Foldable (find)
import Control.Applicative (Alternative((<|>)))
#if MIN_VERSION_ghc(9,2,0)
import GHC
(Ghc,
getSession,
)
import GHC.Data.Maybe (MaybeT (MaybeT), runMaybeT)
import qualified GHC.Data.ShortText as ShortText
import GHC.Driver.Env (hsc_unit_env, )
import GHC.Unit.Info (PackageName (PackageName))
import GHC.Unit.Env (ue_units)
import GHC.Unit.State
(lookupUnit, explicitUnits, lookupUnitId,
lookupPackageName, GenericUnitInfo (..),
UnitInfo, unitPackageNameString)
#if !MIN_VERSION_ghc(9,4,0)
import GHC.Unit.Types (indefUnit)
#endif
#elif MIN_VERSION_ghc(9,0,1)
import GHC
(unitState, Ghc,
getSessionDynFlags,
)
import GHC.Data.Maybe (MaybeT (MaybeT), runMaybeT)
import GHC.Unit.Info (PackageName (PackageName))
import GHC.Unit.State
(lookupUnit, explicitUnits, lookupUnitId,
lookupPackageName, GenericUnitInfo (..),
UnitInfo, unitPackageNameString)
import GHC.Unit.Types (indefUnit)
#else
import GHC
(pkgState, Ghc,
getSessionDynFlags,
)
import Maybes (MaybeT (MaybeT), runMaybeT)
import Module (componentIdToInstalledUnitId)
import PackageConfig (PackageName (PackageName))
import Packages
(lookupPackage, explicitPackages, lookupInstalledPackage,
lookupPackageName
)
import Packages (InstalledPackageInfo (packageVersion, abiHash))
import Packages (PackageConfig)
import Packages (packageNameString)
#endif
import GHC.Stack (HasCallStack)
import GHC.Check.Util
data PackageVersion
= PackageVersion
{ myVersion :: !MyVersion,
abi :: Maybe String
}
deriving (Eq, Lift, Show)
version :: PackageVersion -> Version
version PackageVersion{ myVersion = MyVersion v} = v
#if MIN_VERSION_ghc(9,4,0)
indefUnit :: a -> a
indefUnit = id
#endif
#if MIN_VERSION_ghc(9,2,0)
| @getPackageVersion p@ returns the version of package @p@ that will be used in the Ghc session .
getPackageVersion :: String -> Ghc (Maybe PackageVersion)
getPackageVersion pName = runMaybeT $ do
hsc_env <- Monad.lift getSession
let pkgst = ue_units $ hsc_unit_env hsc_env
depends =
#if MIN_VERSION_ghc(9,4,0)
map fst $
#endif
explicitUnits pkgst
let explicit = do
pkgs <- traverse (MaybeT . return . lookupUnit pkgst) depends
MaybeT $ return $ find (\p -> unitPackageNameString p == pName ) pkgs
notExplicit = do
component <- MaybeT $ return $ lookupPackageName pkgst $ PackageName $ fromString pName
MaybeT $ return $ lookupUnitId pkgst (indefUnit component)
p <- explicit <|> notExplicit
return $ fromPackageConfig p
fromPackageConfig :: UnitInfo -> PackageVersion
fromPackageConfig p = PackageVersion (MyVersion $ unitPackageVersion p) (Just $ ShortText.unpack $ unitAbiHash p)
#elif MIN_VERSION_ghc(9,0,1)
| @getPackageVersion p@ returns the version of package @p@ that will be used in the Ghc session .
getPackageVersion :: String -> Ghc (Maybe PackageVersion)
getPackageVersion pName = runMaybeT $ do
dflags <- Monad.lift getSessionDynFlags
let pkgst = unitState dflags
depends = explicitUnits pkgst
let explicit = do
pkgs <- traverse (MaybeT . return . lookupUnit pkgst) depends
MaybeT $ return $ find (\p -> unitPackageNameString p == pName ) pkgs
notExplicit = do
component <- MaybeT $ return $ lookupPackageName pkgst $ PackageName $ fromString pName
MaybeT $ return $ lookupUnitId pkgst (indefUnit component)
p <- explicit <|> notExplicit
return $ fromPackageConfig p
fromPackageConfig :: UnitInfo -> PackageVersion
fromPackageConfig p = PackageVersion (MyVersion $ unitPackageVersion p) (Just $ unitAbiHash p)
#else
| @getPackageVersion p@ returns the version of package @p@ that will be used in the Ghc session .
getPackageVersion :: String -> Ghc (Maybe PackageVersion)
getPackageVersion pName = runMaybeT $ do
dflags <- Monad.lift getSessionDynFlags
let pkgst = pkgState dflags
depends = explicitPackages pkgst
let explicit = do
pkgs <- traverse (MaybeT . return . lookupPackage dflags) depends
MaybeT $ return $ find (\p -> packageNameString p == pName ) pkgs
notExplicit = do
component <- MaybeT $ return $ lookupPackageName dflags $ PackageName $ fromString pName
MaybeT $ return $ lookupInstalledPackage dflags (componentIdToInstalledUnitId component)
p <- explicit <|> notExplicit
return $ fromPackageConfig p
fromPackageConfig :: PackageConfig -> PackageVersion
fromPackageConfig p = PackageVersion (MyVersion $ packageVersion p) (Just $ abiHash p)
#endif
fromVersionString :: HasCallStack => String -> PackageVersion
fromVersionString v = PackageVersion (read v) Nothing
|
fcdd2704866fbb067c59ffa23f81da6b82609d6f2fe88dc7b01d47d43cb0e472 | uw-unsat/serval | extend-and-add.rkt | #lang rosette
(require
"common.rkt")
(provide
sxtb16 sxtb sxth
uxtb16 uxtb uxth)
(define (decode Rd rotate Rm)
(define d Rd)
(define m Rm)
(define rotation (zero-extend (concat rotate (bv #b000 3)) (bitvector 32)))
(when (|| (r15? d) (r15? m))
(unpredictable))
(values d m rotation))
(define (interpret-sxtb16 cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d
(concat (sign-extend (extract 23 16 rotated) (bitvector 16))
(sign-extend (extract 7 0 rotated) (bitvector 16)))))
(define (interpret-sxtb cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d (sign-extend (extract 7 0 rotated) (bitvector 32))))
(define (interpret-sxth cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d (sign-extend (extract 15 0 rotated) (bitvector 32))))
(define (interpret-uxtb16 cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d
(concat (zero-extend (extract 23 16 rotated) (bitvector 16))
(zero-extend (extract 7 0 rotated) (bitvector 16)))))
(define (interpret-uxtb cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d (zero-extend (extract 7 0 rotated) (bitvector 32))))
(define (interpret-uxth cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d (zero-extend (extract 15 0 rotated) (bitvector 32))))
(define-insn (Rd rotate Rm)
#:encode (lambda (U op) (list (bv #b01101 5) (bv U 1) (bv op 2) (bv #b1111 4) Rd rotate (bv #b00 2) (bv #b0111 4) Rm))
[(#b0 #b00) sxtb16 interpret-sxtb16]
[(#b0 #b10) sxtb interpret-sxtb]
[(#b0 #b11) sxth interpret-sxth]
[(#b1 #b00) uxtb16 interpret-uxtb16]
[(#b1 #b10) uxtb interpret-uxtb]
[(#b1 #b11) uxth interpret-uxth])
| null | https://raw.githubusercontent.com/uw-unsat/serval/be11ecccf03f81b8bd0557acf8385a6a5d4f51ed/serval/arm32/interp/extend-and-add.rkt | racket | #lang rosette
(require
"common.rkt")
(provide
sxtb16 sxtb sxth
uxtb16 uxtb uxth)
(define (decode Rd rotate Rm)
(define d Rd)
(define m Rm)
(define rotation (zero-extend (concat rotate (bv #b000 3)) (bitvector 32)))
(when (|| (r15? d) (r15? m))
(unpredictable))
(values d m rotation))
(define (interpret-sxtb16 cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d
(concat (sign-extend (extract 23 16 rotated) (bitvector 16))
(sign-extend (extract 7 0 rotated) (bitvector 16)))))
(define (interpret-sxtb cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d (sign-extend (extract 7 0 rotated) (bitvector 32))))
(define (interpret-sxth cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d (sign-extend (extract 15 0 rotated) (bitvector 32))))
(define (interpret-uxtb16 cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d
(concat (zero-extend (extract 23 16 rotated) (bitvector 16))
(zero-extend (extract 7 0 rotated) (bitvector 16)))))
(define (interpret-uxtb cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d (zero-extend (extract 7 0 rotated) (bitvector 32))))
(define (interpret-uxth cpu Rd rotate Rm)
(define-values (d m rotation) (decode Rd rotate Rm))
(define rotated (bvror (cpu-gpr-ref cpu m) rotation))
(cpu-gpr-set! cpu d (zero-extend (extract 15 0 rotated) (bitvector 32))))
(define-insn (Rd rotate Rm)
#:encode (lambda (U op) (list (bv #b01101 5) (bv U 1) (bv op 2) (bv #b1111 4) Rd rotate (bv #b00 2) (bv #b0111 4) Rm))
[(#b0 #b00) sxtb16 interpret-sxtb16]
[(#b0 #b10) sxtb interpret-sxtb]
[(#b0 #b11) sxth interpret-sxth]
[(#b1 #b00) uxtb16 interpret-uxtb16]
[(#b1 #b10) uxtb interpret-uxtb]
[(#b1 #b11) uxth interpret-uxth])
|
|
897f03d487547d2fd4c6c33eaf3b96a2576121c4d60a92daea2d5b1f5287899c | texmacs/tm-forge | tetris-with-tables.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; MODULE : tetris-game.scm
;; DESCRIPTION : A proof-of-concept tetris clone implemented with tables.
COPYRIGHT : ( C ) 2015
;;
This software falls under the GNU general public license version 3 or later .
;; It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
;; in the root directory or <-3.0.html>.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; DISCLAIMER:
This is a quick afternoon hack with the only purpose of having some fun .
;; It's *very* slow and lacks most of the features an actual game needs, in
;; particular lines are not deleted when completed.
;; Feel free to improve.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(use-modules (utils library cursor))
;(texmacs-module (games tetris)
; (:use (utils library cursor)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Global state (yuk!) and accessors. Maybe boards should contain the-block.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-public the-board (tree ""))
; (car (select (buffer-tree) '(:* board tabular* :* table))))
(define (board-height board) (tree-arity board))
(define (board-width board) (tree-arity (tree-ref board 0)))
(define-public the-block #f)
(define-public tetris-mode? #f)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Block definitions and accessors.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Adapted from SnowTetris
; Squares in block definitions are relative to (0 0)
'(("orange" ((0 2) (0 1) (0 0) (1 0))) ; L
("blue" ((0 2) (0 1) (0 0) (-1 0))) ; J
("cyan" ((0 2) (0 1) (0 0) (0 -1))) ; I
("purple" ((0 0) (0 1) (-1 1) (1 1))) ; T
("yellow" ((0 0) (0 1) (1 0) (1 1))) ; O
("green" ((0 0) (0 1) (1 1) (-1 0))) ; S
("red" ((0 0) (0 1) (-1 1) (1 0))))) ; Z
(define make-block list)
(define block-color car)
(define block-pos cadr)
(define block-squares caddr)
(define (in-range? what from to)
(and (>= what from) (<= what to)))
(define (paint-square center offset color)
( table - go - to ( + ( car center ) ( car offset ) ) ( + ( cadr center ) ( cadr offset ) ) )
(apply table-go-to (map + center offset))
(cell-set-background color))
(define (draw-block block)
(for-each (cut paint-square (block-pos block) <> (block-color block))
(block-squares block)))
(define (erase-block block)
(draw-block (make-block "" (block-pos block) (block-squares block))))
(define (new-block!)
(let* ((which (random 7))
(blk (list-ref blocks which)))
(set! the-block (make-block (car blk) '(1 5) (cadr blk)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Block movement
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (square-in-board? pos)
(and (in-range? (car pos) 1 (board-height the-board))
(in-range? (cadr pos) 1 (board-width the-board))))
(define (square-empty? pos)
(apply table-go-to pos)
(== "" (cell-get-format "cell-background")))
(define (block->board-squares block)
(with pos (block-pos block)
(map (lambda (p) (map + p pos)) (block-squares block))))
(define (block-can-move? block)
(with sqs (block->board-squares block)
(and (and-map square-in-board? sqs)
(and-map square-empty? sqs))))
(define (move-block-to block to)
(with new (make-block (block-color block) to (block-squares block))
(erase-block block)
(if (block-can-move? new)
(begin (draw-block new) new)
(begin (draw-block block) block))))
(define (left-of block)
(map + (block-pos block) '(0 -1)))
(define (right-of block)
(map + (block-pos block) '(0 1)))
(define (down-of block)
(map + (block-pos block) '(1 0)))
(define (move-block block dir)
(cond ((== dir "left") (move-block-to block (left-of block)))
((== dir "right") (move-block-to block (right-of block)))
((== dir "down") (move-block-to block (down-of block)))
((== dir "bottom")
(with new (move-block-to block (down-of block))
(if (== new block) block (move-block new dir))))
(else block)))
(define (mult mat vec)
"Multiply matrix ((a_11 a_12) (a_21 a_22)) with vector (v_1 v_2)"
(list (apply + (map * (car mat) vec))
(apply + (map * (cadr mat) vec))))
(define (rotate-block-with block mat)
(with new (make-block (block-color block)
(block-pos block)
(map (cut mult mat <>) (block-squares block)))
(erase-block block)
(if (block-can-move? new)
(begin (draw-block new) new)
(begin (draw-block block) block))))
(define (rotate-block block dir)
(cond ((== dir "left") (rotate-block-with block '((0 1) (-1 0)))) ; pi/2
((== dir "right") (rotate-block-with block '((0 -1) (1 0)))) ; -pi/2
(else (noop))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Board management .
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (clear-board)
SLOOOOW !
(with-cursor (tree->path (tree-ref the-board 0 0))
(for-each
(lambda (i)
(for-each (lambda (j) (paint-square (list i j) '(0 0) ""))
(.. 1 (+ 1 (board-width the-board)))))
(.. 1 (+ 1 (board-height the-board))))))
(define (toggle-board t)
(with pt (tree-search-upwards t '(hidden shown))
(and (if (== (tree-label pt) 'hidden)
(tree-assign-node pt 'shown)
(tree-assign-node pt 'hidden))
#t)))
(define (test-lines-around pos)
; TODO: check for completed lines
(noop))
(tm-define (board-update)
placeholder required to avoid TeXmacs warning
(noop))
(tm-define (board-update)
(:require tetris-mode?)
(delayed
(:every 750)
(with new (move-block the-block "down")
(if (== new the-block)
(begin
(test-lines-around (block-pos the-block))
(new-block!)
(draw-block the-block))
(set! the-block new)))
(board-update)))
(define (draw-cursor draw?)
(set-boolean-preference "draw cursor" draw?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Game and keyboard management.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(tm-define (keyboard-press key time)
(:require tetris-mode?)
(cond ((in? key '("escape" "C-c")) (end-game))
((in? key '("left" "right" "down"))
(set! the-block (move-block the-block key)))
((== key "q")
(set! the-block (rotate-block the-block "left")))
((== key "w")
(set! the-block (rotate-block the-block "right")))
((== key "space")
(set! the-block (move-block the-block "bottom")))
((== key "e")
(end-game))
(else (former key time))))
(define (start-game)
(set! the-board
(car (select (buffer-tree) '(:* board tabular* :* table))))
;(toggle-board the-board)
;(draw-cursor #f)
;(clear-board)
(tree-go-to the-board)
(set! tetris-mode? #t)
(new-block!)
(board-update))
(define (end-game)
(draw-cursor #t)
(set! tetris-mode? #f)
;(toggle-board the-board)
)
| null | https://raw.githubusercontent.com/texmacs/tm-forge/ee6e11a8f000b0971d6071733c66cc04cac3b319/miscellanea/tetris/tetris-with-tables.scm | scheme |
MODULE : tetris-game.scm
DESCRIPTION : A proof-of-concept tetris clone implemented with tables.
It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
in the root directory or <-3.0.html>.
DISCLAIMER:
It's *very* slow and lacks most of the features an actual game needs, in
particular lines are not deleted when completed.
Feel free to improve.
(texmacs-module (games tetris)
(:use (utils library cursor)))
Global state (yuk!) and accessors. Maybe boards should contain the-block.
(car (select (buffer-tree) '(:* board tabular* :* table))))
Block definitions and accessors.
Squares in block definitions are relative to (0 0)
L
J
I
T
O
S
Z
Block movement
pi/2
-pi/2
TODO: check for completed lines
Game and keyboard management.
(toggle-board the-board)
(draw-cursor #f)
(clear-board)
(toggle-board the-board) | COPYRIGHT : ( C ) 2015
This software falls under the GNU general public license version 3 or later .
This is a quick afternoon hack with the only purpose of having some fun .
(use-modules (utils library cursor))
(define-public the-board (tree ""))
(define (board-height board) (tree-arity board))
(define (board-width board) (tree-arity (tree-ref board 0)))
(define-public the-block #f)
(define-public tetris-mode? #f)
Adapted from SnowTetris
(define make-block list)
(define block-color car)
(define block-pos cadr)
(define block-squares caddr)
(define (in-range? what from to)
(and (>= what from) (<= what to)))
(define (paint-square center offset color)
( table - go - to ( + ( car center ) ( car offset ) ) ( + ( cadr center ) ( cadr offset ) ) )
(apply table-go-to (map + center offset))
(cell-set-background color))
(define (draw-block block)
(for-each (cut paint-square (block-pos block) <> (block-color block))
(block-squares block)))
(define (erase-block block)
(draw-block (make-block "" (block-pos block) (block-squares block))))
(define (new-block!)
(let* ((which (random 7))
(blk (list-ref blocks which)))
(set! the-block (make-block (car blk) '(1 5) (cadr blk)))))
(define (square-in-board? pos)
(and (in-range? (car pos) 1 (board-height the-board))
(in-range? (cadr pos) 1 (board-width the-board))))
(define (square-empty? pos)
(apply table-go-to pos)
(== "" (cell-get-format "cell-background")))
(define (block->board-squares block)
(with pos (block-pos block)
(map (lambda (p) (map + p pos)) (block-squares block))))
(define (block-can-move? block)
(with sqs (block->board-squares block)
(and (and-map square-in-board? sqs)
(and-map square-empty? sqs))))
(define (move-block-to block to)
(with new (make-block (block-color block) to (block-squares block))
(erase-block block)
(if (block-can-move? new)
(begin (draw-block new) new)
(begin (draw-block block) block))))
(define (left-of block)
(map + (block-pos block) '(0 -1)))
(define (right-of block)
(map + (block-pos block) '(0 1)))
(define (down-of block)
(map + (block-pos block) '(1 0)))
(define (move-block block dir)
(cond ((== dir "left") (move-block-to block (left-of block)))
((== dir "right") (move-block-to block (right-of block)))
((== dir "down") (move-block-to block (down-of block)))
((== dir "bottom")
(with new (move-block-to block (down-of block))
(if (== new block) block (move-block new dir))))
(else block)))
(define (mult mat vec)
"Multiply matrix ((a_11 a_12) (a_21 a_22)) with vector (v_1 v_2)"
(list (apply + (map * (car mat) vec))
(apply + (map * (cadr mat) vec))))
(define (rotate-block-with block mat)
(with new (make-block (block-color block)
(block-pos block)
(map (cut mult mat <>) (block-squares block)))
(erase-block block)
(if (block-can-move? new)
(begin (draw-block new) new)
(begin (draw-block block) block))))
(define (rotate-block block dir)
(else (noop))))
Board management .
(define (clear-board)
SLOOOOW !
(with-cursor (tree->path (tree-ref the-board 0 0))
(for-each
(lambda (i)
(for-each (lambda (j) (paint-square (list i j) '(0 0) ""))
(.. 1 (+ 1 (board-width the-board)))))
(.. 1 (+ 1 (board-height the-board))))))
(define (toggle-board t)
(with pt (tree-search-upwards t '(hidden shown))
(and (if (== (tree-label pt) 'hidden)
(tree-assign-node pt 'shown)
(tree-assign-node pt 'hidden))
#t)))
(define (test-lines-around pos)
(noop))
(tm-define (board-update)
placeholder required to avoid TeXmacs warning
(noop))
(tm-define (board-update)
(:require tetris-mode?)
(delayed
(:every 750)
(with new (move-block the-block "down")
(if (== new the-block)
(begin
(test-lines-around (block-pos the-block))
(new-block!)
(draw-block the-block))
(set! the-block new)))
(board-update)))
(define (draw-cursor draw?)
(set-boolean-preference "draw cursor" draw?))
(tm-define (keyboard-press key time)
(:require tetris-mode?)
(cond ((in? key '("escape" "C-c")) (end-game))
((in? key '("left" "right" "down"))
(set! the-block (move-block the-block key)))
((== key "q")
(set! the-block (rotate-block the-block "left")))
((== key "w")
(set! the-block (rotate-block the-block "right")))
((== key "space")
(set! the-block (move-block the-block "bottom")))
((== key "e")
(end-game))
(else (former key time))))
(define (start-game)
(set! the-board
(car (select (buffer-tree) '(:* board tabular* :* table))))
(tree-go-to the-board)
(set! tetris-mode? #t)
(new-block!)
(board-update))
(define (end-game)
(draw-cursor #t)
(set! tetris-mode? #f)
)
|
0d0de803fd3fa5174b77b18ee546072ba69e809f2cf19282d7e2f8c9653647e0 | jeroanan/rkt-coreutils | uptime.rkt | #lang s-exp "util/frontend-program.rkt"
(require "repl/uptime.rkt")
(uptime)
| null | https://raw.githubusercontent.com/jeroanan/rkt-coreutils/571629d1e2562c557ba258b31ce454add2e93dd9/src/uptime.rkt | racket | #lang s-exp "util/frontend-program.rkt"
(require "repl/uptime.rkt")
(uptime)
|
|
ad8d83160814231f2182fd6f352a1641a5a1459e082b8486b70b2e69c7ec8e3f | huangz1990/SICP-answers | test-29-branch-torque.scm | (load "test-manager/load.scm")
(load "29-mobile-represent.scm")
(load "29-branch-torque.scm")
(define branch (make-branch 10 20))
(define-each-check
(= (branch-torque branch)
200)
)
(run-registered-tests)
| null | https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp2/code/test-29-branch-torque.scm | scheme | (load "test-manager/load.scm")
(load "29-mobile-represent.scm")
(load "29-branch-torque.scm")
(define branch (make-branch 10 20))
(define-each-check
(= (branch-torque branch)
200)
)
(run-registered-tests)
|
|
1246a3496613152e4519a7277434376968e013cc14d19bc80191869a918ee242 | odo/ramjet | ramjet_sup.erl | -module(ramjet_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%% ===================================================================
%% API functions
%% ===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% ===================================================================
%% Supervisor callbacks
%% ===================================================================
init([]) ->
Metrics = ramjet:config(metrics),
IgnoreMetrics = ramjet:config(no_stats_for),
StatsInterval = ramjet:config(stats_interval),
Monitor = {
ramjet_monitor, {
ramjet_monitor,
start_link,
[]
},
permanent,
2000,
worker,
[ramjet_monitor]},
Stats = {
ramjet_stats, {
ramjet_stats,
start_link,
[Metrics, IgnoreMetrics, StatsInterval]
},
permanent,
2000,
worker,
[ramjet_stats]},
SessionSup = {
ramjet_session_sup, {
ramjet_session_sup,
start_link,
[]
},
permanent,
2000,
supervisor,
[ramjet_session_sup, ramjet_session]},
Children =
case ramjet:config(report) of
true ->
[Monitor, SessionSup, Stats];
false ->
[Monitor, SessionSup]
end,
{ok, { {one_for_one, 5, 10}, Children} }.
| null | https://raw.githubusercontent.com/odo/ramjet/e0453169abf574f81045c88bd1a43c143d977049/src/ramjet_sup.erl | erlang | API
Supervisor callbacks
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
=================================================================== | -module(ramjet_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Metrics = ramjet:config(metrics),
IgnoreMetrics = ramjet:config(no_stats_for),
StatsInterval = ramjet:config(stats_interval),
Monitor = {
ramjet_monitor, {
ramjet_monitor,
start_link,
[]
},
permanent,
2000,
worker,
[ramjet_monitor]},
Stats = {
ramjet_stats, {
ramjet_stats,
start_link,
[Metrics, IgnoreMetrics, StatsInterval]
},
permanent,
2000,
worker,
[ramjet_stats]},
SessionSup = {
ramjet_session_sup, {
ramjet_session_sup,
start_link,
[]
},
permanent,
2000,
supervisor,
[ramjet_session_sup, ramjet_session]},
Children =
case ramjet:config(report) of
true ->
[Monitor, SessionSup, Stats];
false ->
[Monitor, SessionSup]
end,
{ok, { {one_for_one, 5, 10}, Children} }.
|
608b9a751aa50b530d10fae104b953b7d625522ae49038352ad65a4352c56edd | prestancedesign/pingcrm-clojure | contacts.clj | (ns pingcrm.models.contacts
(:require [honey.sql :as h]
[honey.sql.helpers :refer [where]]
[next.jdbc :as jdbc]
[next.jdbc.sql :as sql]))
(defn retrieve-and-filter-contacts
([db filters]
(retrieve-and-filter-contacts db filters nil))
([db {:keys [search trashed]} offset]
(let [query (h/format
(cond-> {:select (if offset [[:c.*] [[:|| :c.first_name " " :c.last_name] :name] [:o.name :organization]] [[:%count.* :aggregate]])
:from [[:contacts :c]]
:left-join [[:organizations :o] [:= :c.organization_id :o.id]]
:order-by [:last_name :first_name]}
offset (merge {:limit 10
:offset offset})
search (where [:or [:like :c.first_name (str "%" search "%")]
[:like :c.last_name (str "%" search "%")]
[:like :c.email (str "%" search "%")]])
true (where (case trashed
"with" nil
"only" [:<> :c.deleted_at nil]
[:= :c.deleted_at nil]))))]
(jdbc/execute! db query))))
(defn get-contact-by-id
[db id]
(sql/get-by-id db :contacts id))
(defn insert-contact!
[db contact]
(let [query (h/format {:insert-into :contacts
:values [(merge contact {:created_at :current_timestamp
:updated_at :current_timestamp})]})]
(jdbc/execute-one! db query)))
(defn update-contact!
[db contact id]
(sql/update! db :contacts contact {:id id}))
(defn soft-delete-contact!
[db id]
(let [query (h/format {:update :contacts
:set {:deleted_at :current_timestamp
:updated_at :current_timestamp}
:where [:= :id id]})]
(jdbc/execute-one! db query)))
(defn restore-deleted-contact!
[db id]
(let [query (h/format {:update :contacts
:set {:deleted_at nil
:updated_at :current_timestamp}
:where [:= :id id]})]
(jdbc/execute-one! db query)))
| null | https://raw.githubusercontent.com/prestancedesign/pingcrm-clojure/18c8cca1d068e56b71955081755c0eb152cbf29a/src/clj/pingcrm/models/contacts.clj | clojure | (ns pingcrm.models.contacts
(:require [honey.sql :as h]
[honey.sql.helpers :refer [where]]
[next.jdbc :as jdbc]
[next.jdbc.sql :as sql]))
(defn retrieve-and-filter-contacts
([db filters]
(retrieve-and-filter-contacts db filters nil))
([db {:keys [search trashed]} offset]
(let [query (h/format
(cond-> {:select (if offset [[:c.*] [[:|| :c.first_name " " :c.last_name] :name] [:o.name :organization]] [[:%count.* :aggregate]])
:from [[:contacts :c]]
:left-join [[:organizations :o] [:= :c.organization_id :o.id]]
:order-by [:last_name :first_name]}
offset (merge {:limit 10
:offset offset})
search (where [:or [:like :c.first_name (str "%" search "%")]
[:like :c.last_name (str "%" search "%")]
[:like :c.email (str "%" search "%")]])
true (where (case trashed
"with" nil
"only" [:<> :c.deleted_at nil]
[:= :c.deleted_at nil]))))]
(jdbc/execute! db query))))
(defn get-contact-by-id
[db id]
(sql/get-by-id db :contacts id))
(defn insert-contact!
[db contact]
(let [query (h/format {:insert-into :contacts
:values [(merge contact {:created_at :current_timestamp
:updated_at :current_timestamp})]})]
(jdbc/execute-one! db query)))
(defn update-contact!
[db contact id]
(sql/update! db :contacts contact {:id id}))
(defn soft-delete-contact!
[db id]
(let [query (h/format {:update :contacts
:set {:deleted_at :current_timestamp
:updated_at :current_timestamp}
:where [:= :id id]})]
(jdbc/execute-one! db query)))
(defn restore-deleted-contact!
[db id]
(let [query (h/format {:update :contacts
:set {:deleted_at nil
:updated_at :current_timestamp}
:where [:= :id id]})]
(jdbc/execute-one! db query)))
|
|
442cc724aaedcc6dfac585d28d9d1890e63d56245c2923fcf6056b028b9b2a0a | HeinrichApfelmus/reactive-banana | CRUD.hs | {-----------------------------------------------------------------------------
reactive-banana-wx
Example:
Small database with CRUD operations and filtering.
To keep things simple, the list box is rebuild every time
that the database is updated. This is perfectly fine for rapid prototyping.
A more sophisticated approach would use incremental updates.
------------------------------------------------------------------------------}
# LANGUAGE ScopedTypeVariables #
-- allows pattern signatures like
-- do
-- (b :: Behavior Int) <- stepper 0 ...
# LANGUAGE RecursiveDo #
-- allows recursive do notation
-- mdo
-- ...
import Prelude hiding (lookup)
import Data.List (isPrefixOf)
import Data.Maybe
import qualified Data.Map as Map
import Graphics.UI.WX hiding (Event, update)
import Reactive.Banana
import Reactive.Banana.WX
import Tidings
{-----------------------------------------------------------------------------
Main
------------------------------------------------------------------------------}
main :: IO ()
main = start $ do
-- GUI layout
f <- frame [ text := "CRUD Example (Simple)" ]
listBox <- singleListBox f []
createBtn <- button f [ text := "Create" ]
deleteBtn <- button f [ text := "Delete" ]
filterEntry <- entry f [ ]
firstname <- entry f [ ]
lastname <- entry f [ ]
let dataItem = grid 10 10 [[label "First Name:", widget firstname]
,[label "Last Name:" , widget lastname]]
set f [layout := margin 10 $
grid 10 5
[[row 5 [label "Filter prefix:", widget filterEntry], glue]
,[minsize (sz 200 300) $ widget listBox, dataItem]
,[row 10 [widget createBtn, widget deleteBtn], glue]
]]
-- event network
let networkDescription :: MomentIO ()
networkDescription = mdo
-- events from buttons
eCreate <- event0 createBtn command
eDelete <- event0 deleteBtn command
-- filter string
tFilterString <- reactiveTextEntry filterEntry bFilterString
bFilterString <- stepper "" $ rumors tFilterString
let tFilter = isPrefixOf <$> tFilterString
bFilter = facts tFilter
eFilter = rumors tFilter
-- list box with selection
eSelection <- rumors <$> reactiveListDisplay listBox
bListBoxItems bSelection bShowDataItem
-- data item display
eDataItemIn <- rumors <$> reactiveDataItem (firstname,lastname)
bSelectionDataItem
-- database
(bDatabase :: Behavior (Database DataItem))
<- accumB emptydb $ unions
[ create ("Emil","Example") <$ eCreate
, filterJust $ update' <$> bSelection <@> eDataItemIn
, delete <$> filterJust (bSelection <@ eDelete)
]
let update' mkey x = flip update x <$> mkey
-- selection
(bSelection :: Behavior (Maybe DatabaseKey))
<- stepper Nothing $ foldr1 (unionWith const)
[ eSelection
, Nothing <$ eDelete
, Just . nextKey <$> bDatabase <@ eCreate
, (\b s p -> b >>= \a -> if p (s a) then Just a else Nothing)
<$> bSelection <*> bShowDataItem <@> eFilter
]
let
bLookup :: Behavior (DatabaseKey -> Maybe DataItem)
bLookup = flip lookup <$> bDatabase
bShowDataItem :: Behavior (DatabaseKey -> String)
bShowDataItem = (maybe "" showDataItem .) <$> bLookup
bListBoxItems :: Behavior [DatabaseKey]
bListBoxItems = (\p show -> filter (p. show) . keys)
<$> bFilter <*> bShowDataItem <*> bDatabase
bSelectionDataItem :: Behavior (Maybe DataItem)
bSelectionDataItem = (=<<) <$> bLookup <*> bSelection
-- automatically enable / disable editing
let
bDisplayItem :: Behavior Bool
bDisplayItem = isJust <$> bSelection
sink deleteBtn [ enabled :== bDisplayItem ]
sink firstname [ enabled :== bDisplayItem ]
sink lastname [ enabled :== bDisplayItem ]
network <- compile networkDescription
actuate network
{-----------------------------------------------------------------------------
Database Model
------------------------------------------------------------------------------}
type DatabaseKey = Int
data Database a = Database { nextKey :: !Int, db :: Map.Map DatabaseKey a }
emptydb :: Database a
emptydb = Database 0 Map.empty
keys :: Database a -> [DatabaseKey]
keys = Map.keys . db
create :: a -> Database a -> Database a
create x (Database newkey db) = Database (newkey+1) $ Map.insert newkey x db
update :: DatabaseKey -> a -> Database a -> Database a
update key x (Database newkey db) = Database newkey $ Map.insert key x db
delete :: DatabaseKey -> Database a -> Database a
delete key (Database newkey db) = Database newkey $ Map.delete key db
lookup :: DatabaseKey -> Database a -> Maybe a
lookup key (Database _ db) = Map.lookup key db
{-----------------------------------------------------------------------------
Data items that are stored in the data base
------------------------------------------------------------------------------}
type DataItem = (String, String)
showDataItem :: ([Char], [Char]) -> [Char]
showDataItem (firstname, lastname) = lastname ++ ", " ++ firstname
-- single text entry
reactiveTextEntry
:: TextCtrl a
-> Behavior String -- text value
-> MomentIO (Tidings String) -- user changes
reactiveTextEntry w btext = do
eUser <- eventText w -- user changes
-- filter text setting that are simultaneous with user events
etext <- changes btext
let
etext2 = fst $ split $ unionWith (curry snd) (Left () <$ etext) (Right () <$ eUser)
btext2 = imposeChanges btext etext2
sink w [ text :== btext2 ] -- display value
return $ tidings btext eUser
whole data item ( consisting of two text entries )
reactiveDataItem
:: (TextCtrl a, TextCtrl b)
-> Behavior (Maybe DataItem)
-> MomentIO (Tidings DataItem)
reactiveDataItem (firstname,lastname) binput = do
t1 <- reactiveTextEntry firstname (fst . fromMaybe ("","") <$> binput)
t2 <- reactiveTextEntry lastname (snd . fromMaybe ("","") <$> binput)
return $ (,) <$> t1 <*> t2
----------------------------------------------------------------------------
reactive list display
Display a list of ( distinct ) items in a list box .
The current selection contains one or no items .
Changing the set may unselect the current item ,
but will not change it to another item .
-----------------------------------------------------------------------------
reactive list display
Display a list of (distinct) items in a list box.
The current selection contains one or no items.
Changing the set may unselect the current item,
but will not change it to another item.
------------------------------------------------------------------------------}
reactiveListDisplay :: forall a b. Ord a
ListBox widget to use
-> Behavior [a] -- list of items
-> Behavior (Maybe a) -- selected element
-> Behavior (a -> String) -- display an item
-> MomentIO
(Tidings (Maybe a)) -- current selection as item (possibly empty)
reactiveListDisplay w bitems bsel bdisplay = do
-- animate output items
sink w [ items :== map <$> bdisplay <*> bitems ]
-- animate output selection
let bindices :: Behavior (Map.Map a Int)
bindices = (Map.fromList . flip zip [0..]) <$> bitems
bindex = (\m a -> fromMaybe (-1) $ flip Map.lookup m =<< a) <$>
bindices <*> bsel
sink w [ selection :== bindex ]
-- changing the display won't change the current selection
-- eDisplay <- changes display
-- sink listBox [ selection :== stepper (-1) $ bSelection <@ eDisplay ]
-- user selection
let bindices2 :: Behavior (Map.Map Int a)
bindices2 = Map.fromList . zip [0..] <$> bitems
esel <- eventSelection w
return $ tidings bsel $ flip Map.lookup <$> bindices2 <@> esel
{-----------------------------------------------------------------------------
wxHaskell convenience wrappers and bug fixes
------------------------------------------------------------------------------}
Currently exported from Reactive . Banana . WX
-- user input event - text for text entries
eventText : : t ( Event t String )
eventText w = do
-- Should probably be wxEVT_COMMAND_TEXT_UPDATED ,
-- but that 's missing from wxHaskell .
-- Note : Observing keyUp events does create a small lag
$ event1ToAddHandler w keyboardUp
fromAddHandler $ mapIO ( const $ get w text )
-- observe " key up " events ( many thanks to )
-- this should probably be in the wxHaskell library
keyboardUp : : WX.Event ( Window a ) ( EventKey - > IO ( ) )
" keyboardUp " WXCore.windowGetOnKeyUp WXCore.windowOnKeyUp
-- user input event - selection marker for list events
eventSelection : : SingleListBox b - > Moment t ( Event t Int )
eventSelection w = do
liftIO $ fixSelectionEvent w
$ event1ToAddHandler w ( event0ToEvent1 select )
fromAddHandler $ mapIO ( const $ get w selection )
-- Fix @select@ event not being fired when items are * un*selected .
fixSelectionEvent listbox =
liftIO $ set listbox [ on unclick : = handler ]
where
handler _ = do
s < - get listbox selection
when ( s = = -1 ) $ ( get listbox ( on select ) ) > > = i d
-- user input event - text for text entries
eventText :: TextCtrl w -> Moment t (Event t String)
eventText w = do
-- Should probably be wxEVT_COMMAND_TEXT_UPDATED ,
-- but that's missing from wxHaskell.
-- Note: Observing keyUp events does create a small lag
addHandler <- liftIO $ event1ToAddHandler w keyboardUp
fromAddHandler $ mapIO (const $ get w text) addHandler
-- observe "key up" events (many thanks to Abu Alam)
-- this should probably be in the wxHaskell library
keyboardUp :: WX.Event (Window a) (EventKey -> IO ())
keyboardUp = WX.newEvent "keyboardUp" WXCore.windowGetOnKeyUp WXCore.windowOnKeyUp
-- user input event - selection marker for list events
eventSelection :: SingleListBox b -> Moment t (Event t Int)
eventSelection w = do
liftIO $ fixSelectionEvent w
addHandler <- liftIO $ event1ToAddHandler w (event0ToEvent1 select)
fromAddHandler $ mapIO (const $ get w selection) addHandler
-- Fix @select@ event not being fired when items are *un*selected.
fixSelectionEvent listbox =
liftIO $ set listbox [ on unclick := handler ]
where
handler _ = do
propagateEvent
s <- get listbox selection
when (s == -1) $ (get listbox (on select)) >>= id
-}
| null | https://raw.githubusercontent.com/HeinrichApfelmus/reactive-banana/79482f3e9bfab493e2d2197f70cdb11787b33a03/reactive-banana-wx/src/CRUD.hs | haskell | ----------------------------------------------------------------------------
reactive-banana-wx
Example:
Small database with CRUD operations and filtering.
To keep things simple, the list box is rebuild every time
that the database is updated. This is perfectly fine for rapid prototyping.
A more sophisticated approach would use incremental updates.
-----------------------------------------------------------------------------
allows pattern signatures like
do
(b :: Behavior Int) <- stepper 0 ...
allows recursive do notation
mdo
...
----------------------------------------------------------------------------
Main
-----------------------------------------------------------------------------
GUI layout
event network
events from buttons
filter string
list box with selection
data item display
database
selection
automatically enable / disable editing
----------------------------------------------------------------------------
Database Model
-----------------------------------------------------------------------------
----------------------------------------------------------------------------
Data items that are stored in the data base
-----------------------------------------------------------------------------
single text entry
text value
user changes
user changes
filter text setting that are simultaneous with user events
display value
--------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------------}
list of items
selected element
display an item
current selection as item (possibly empty)
animate output items
animate output selection
changing the display won't change the current selection
eDisplay <- changes display
sink listBox [ selection :== stepper (-1) $ bSelection <@ eDisplay ]
user selection
----------------------------------------------------------------------------
wxHaskell convenience wrappers and bug fixes
-----------------------------------------------------------------------------
user input event - text for text entries
Should probably be wxEVT_COMMAND_TEXT_UPDATED ,
but that 's missing from wxHaskell .
Note : Observing keyUp events does create a small lag
observe " key up " events ( many thanks to )
this should probably be in the wxHaskell library
user input event - selection marker for list events
Fix @select@ event not being fired when items are * un*selected .
user input event - text for text entries
Should probably be wxEVT_COMMAND_TEXT_UPDATED ,
but that's missing from wxHaskell.
Note: Observing keyUp events does create a small lag
observe "key up" events (many thanks to Abu Alam)
this should probably be in the wxHaskell library
user input event - selection marker for list events
Fix @select@ event not being fired when items are *un*selected. | # LANGUAGE ScopedTypeVariables #
# LANGUAGE RecursiveDo #
import Prelude hiding (lookup)
import Data.List (isPrefixOf)
import Data.Maybe
import qualified Data.Map as Map
import Graphics.UI.WX hiding (Event, update)
import Reactive.Banana
import Reactive.Banana.WX
import Tidings
main :: IO ()
main = start $ do
f <- frame [ text := "CRUD Example (Simple)" ]
listBox <- singleListBox f []
createBtn <- button f [ text := "Create" ]
deleteBtn <- button f [ text := "Delete" ]
filterEntry <- entry f [ ]
firstname <- entry f [ ]
lastname <- entry f [ ]
let dataItem = grid 10 10 [[label "First Name:", widget firstname]
,[label "Last Name:" , widget lastname]]
set f [layout := margin 10 $
grid 10 5
[[row 5 [label "Filter prefix:", widget filterEntry], glue]
,[minsize (sz 200 300) $ widget listBox, dataItem]
,[row 10 [widget createBtn, widget deleteBtn], glue]
]]
let networkDescription :: MomentIO ()
networkDescription = mdo
eCreate <- event0 createBtn command
eDelete <- event0 deleteBtn command
tFilterString <- reactiveTextEntry filterEntry bFilterString
bFilterString <- stepper "" $ rumors tFilterString
let tFilter = isPrefixOf <$> tFilterString
bFilter = facts tFilter
eFilter = rumors tFilter
eSelection <- rumors <$> reactiveListDisplay listBox
bListBoxItems bSelection bShowDataItem
eDataItemIn <- rumors <$> reactiveDataItem (firstname,lastname)
bSelectionDataItem
(bDatabase :: Behavior (Database DataItem))
<- accumB emptydb $ unions
[ create ("Emil","Example") <$ eCreate
, filterJust $ update' <$> bSelection <@> eDataItemIn
, delete <$> filterJust (bSelection <@ eDelete)
]
let update' mkey x = flip update x <$> mkey
(bSelection :: Behavior (Maybe DatabaseKey))
<- stepper Nothing $ foldr1 (unionWith const)
[ eSelection
, Nothing <$ eDelete
, Just . nextKey <$> bDatabase <@ eCreate
, (\b s p -> b >>= \a -> if p (s a) then Just a else Nothing)
<$> bSelection <*> bShowDataItem <@> eFilter
]
let
bLookup :: Behavior (DatabaseKey -> Maybe DataItem)
bLookup = flip lookup <$> bDatabase
bShowDataItem :: Behavior (DatabaseKey -> String)
bShowDataItem = (maybe "" showDataItem .) <$> bLookup
bListBoxItems :: Behavior [DatabaseKey]
bListBoxItems = (\p show -> filter (p. show) . keys)
<$> bFilter <*> bShowDataItem <*> bDatabase
bSelectionDataItem :: Behavior (Maybe DataItem)
bSelectionDataItem = (=<<) <$> bLookup <*> bSelection
let
bDisplayItem :: Behavior Bool
bDisplayItem = isJust <$> bSelection
sink deleteBtn [ enabled :== bDisplayItem ]
sink firstname [ enabled :== bDisplayItem ]
sink lastname [ enabled :== bDisplayItem ]
network <- compile networkDescription
actuate network
type DatabaseKey = Int
data Database a = Database { nextKey :: !Int, db :: Map.Map DatabaseKey a }
emptydb :: Database a
emptydb = Database 0 Map.empty
keys :: Database a -> [DatabaseKey]
keys = Map.keys . db
create :: a -> Database a -> Database a
create x (Database newkey db) = Database (newkey+1) $ Map.insert newkey x db
update :: DatabaseKey -> a -> Database a -> Database a
update key x (Database newkey db) = Database newkey $ Map.insert key x db
delete :: DatabaseKey -> Database a -> Database a
delete key (Database newkey db) = Database newkey $ Map.delete key db
lookup :: DatabaseKey -> Database a -> Maybe a
lookup key (Database _ db) = Map.lookup key db
type DataItem = (String, String)
showDataItem :: ([Char], [Char]) -> [Char]
showDataItem (firstname, lastname) = lastname ++ ", " ++ firstname
reactiveTextEntry
:: TextCtrl a
reactiveTextEntry w btext = do
etext <- changes btext
let
etext2 = fst $ split $ unionWith (curry snd) (Left () <$ etext) (Right () <$ eUser)
btext2 = imposeChanges btext etext2
return $ tidings btext eUser
whole data item ( consisting of two text entries )
reactiveDataItem
:: (TextCtrl a, TextCtrl b)
-> Behavior (Maybe DataItem)
-> MomentIO (Tidings DataItem)
reactiveDataItem (firstname,lastname) binput = do
t1 <- reactiveTextEntry firstname (fst . fromMaybe ("","") <$> binput)
t2 <- reactiveTextEntry lastname (snd . fromMaybe ("","") <$> binput)
return $ (,) <$> t1 <*> t2
reactive list display
Display a list of ( distinct ) items in a list box .
The current selection contains one or no items .
Changing the set may unselect the current item ,
but will not change it to another item .
reactive list display
Display a list of (distinct) items in a list box.
The current selection contains one or no items.
Changing the set may unselect the current item,
but will not change it to another item.
reactiveListDisplay :: forall a b. Ord a
ListBox widget to use
-> MomentIO
reactiveListDisplay w bitems bsel bdisplay = do
sink w [ items :== map <$> bdisplay <*> bitems ]
let bindices :: Behavior (Map.Map a Int)
bindices = (Map.fromList . flip zip [0..]) <$> bitems
bindex = (\m a -> fromMaybe (-1) $ flip Map.lookup m =<< a) <$>
bindices <*> bsel
sink w [ selection :== bindex ]
let bindices2 :: Behavior (Map.Map Int a)
bindices2 = Map.fromList . zip [0..] <$> bitems
esel <- eventSelection w
return $ tidings bsel $ flip Map.lookup <$> bindices2 <@> esel
Currently exported from Reactive . Banana . WX
eventText : : t ( Event t String )
eventText w = do
$ event1ToAddHandler w keyboardUp
fromAddHandler $ mapIO ( const $ get w text )
keyboardUp : : WX.Event ( Window a ) ( EventKey - > IO ( ) )
" keyboardUp " WXCore.windowGetOnKeyUp WXCore.windowOnKeyUp
eventSelection : : SingleListBox b - > Moment t ( Event t Int )
eventSelection w = do
liftIO $ fixSelectionEvent w
$ event1ToAddHandler w ( event0ToEvent1 select )
fromAddHandler $ mapIO ( const $ get w selection )
fixSelectionEvent listbox =
liftIO $ set listbox [ on unclick : = handler ]
where
handler _ = do
s < - get listbox selection
when ( s = = -1 ) $ ( get listbox ( on select ) ) > > = i d
eventText :: TextCtrl w -> Moment t (Event t String)
eventText w = do
addHandler <- liftIO $ event1ToAddHandler w keyboardUp
fromAddHandler $ mapIO (const $ get w text) addHandler
keyboardUp :: WX.Event (Window a) (EventKey -> IO ())
keyboardUp = WX.newEvent "keyboardUp" WXCore.windowGetOnKeyUp WXCore.windowOnKeyUp
eventSelection :: SingleListBox b -> Moment t (Event t Int)
eventSelection w = do
liftIO $ fixSelectionEvent w
addHandler <- liftIO $ event1ToAddHandler w (event0ToEvent1 select)
fromAddHandler $ mapIO (const $ get w selection) addHandler
fixSelectionEvent listbox =
liftIO $ set listbox [ on unclick := handler ]
where
handler _ = do
propagateEvent
s <- get listbox selection
when (s == -1) $ (get listbox (on select)) >>= id
-}
|
ab7c43d9429722216cb947e9298dba09c742068a1c9bd3d713f3ccb366b804ce | RefactoringTools/wrangler | inspec_feedback_wrangler.erl | %% =====================================================================
Wrangler 's feedback interface module to Erlang E - learning
%% =====================================================================
%%
@author
[ ]
%%
%%
@doc Wrangler 's feedback interface module to Erlang E - learning
%%@private
-module(inspec_feedback_wrangler).
-export([do_code_inspection/2]).
%% API for feedback tool.
-export([long_functions/2,
large_modules/2,
calls_to_specific_function/2,
calls_to_specific_functions/2,
classify_pattern_match/1,
nested_if_exprs/2,
nested_case_exprs/2,
nested_receive_exprs/2,
not_flush_unknown_messages/1,
top_level_if/1,
unnecessary_match/1,
append_two_lists/1,
non_tail_recursive_function/1,
use_of_specific_ops/2,
use_of_export_all/1
]).
-export([test/1,
collect_function_apps/2,
collect_function_apps2/2]).
-include("wrangler.hrl").
-type (message()::string()).
-type (tag() :: atom()).
-spec do_code_inspection([dir()|filename()], [{atom(), [any()]}]) ->
[{message(), [{tag, list()}]}].
do_code_inspection(SearchPaths, Options) ->
do_code_inspection(SearchPaths, Options, []).
do_code_inspection(_SearchPaths, [], Acc) ->
lists:append(lists:reverse(Acc));
do_code_inspection(SearchPaths, [{FunName, Args}|Options], Acc) ->
Res= try_inspector(?MODULE, FunName,
Args++[SearchPaths]),
do_code_inspection(SearchPaths, Options, [Res|Acc]).
try_inspector(Mod, Fun, Args) ->
case try_to_apply(Mod, Fun, Args) of
{error, {Reason, StackTrace}} ->
wrangler_io:format("Wrangler failed to run '~p':\n{~p, \n~s}\n",
[Fun, Reason, StackTrace]),
[];
{ok, Res} ->
Res
end.
try_to_apply(Mod, Fun, Args) ->
try apply(Mod, Fun, Args)
catch
throw:Error ->
Error;
_E1:E2:StackTrace ->
Reason=lists:flatten(
io_lib:format("~p",[StackTrace])),
{error, {E2,Reason}}
end.
-spec long_functions(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
long_functions(Lines, SearchPaths) ->
{ok, LongFuns} = wrangler_code_inspector_lib:long_functions(
SearchPaths, Lines, SearchPaths, 8),
Res=[begin
Msg=lists:flatten(
io_lib:format("Function ~p:~p/~p has more than ~p "
"lines of code.", [M, F, A, Lines])),
{Msg, [{file, File},
{line, integer_to_list(Line)}]}
end ||{{M, F, A}, {File, Line}}<-LongFuns],
{ok, Res}.
-spec large_modules(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
large_modules(Lines, SearchPaths) ->
{ok, LargeMods}= wrangler_code_inspector_lib:large_modules(Lines, SearchPaths, 8),
Res = [begin
M=filename:basename(File, ".erl"),
Msg=lists:flatten(
io_lib:format("The module '~p' has more than ~p "
"lines of code.", [list_to_atom(M), Lines])),
{Msg, [{file, File}]}
end ||File<-LargeMods],
{ok, Res}.
-spec nested_case_exprs(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
nested_case_exprs(NestLevel, SearchPaths) ->
nested_exprs(NestLevel, SearchPaths, 'case').
-spec nested_if_exprs(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
nested_if_exprs(NestLevel, SearchPaths) ->
nested_exprs(NestLevel, SearchPaths, 'if').
-spec nested_receive_exprs(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
nested_receive_exprs(NestLevel, SearchPaths) ->
nested_exprs(NestLevel, SearchPaths, 'receive').
nested_exprs(NestLevel, SearchPaths, ExprType) ->
Files = wrangler_misc:expand_files(SearchPaths, ".erl"),
Funs = lists:flatmap(fun (File) ->
ResRanges=wrangler_code_inspector_lib:nested_exprs_1(
File, NestLevel, ExprType, SearchPaths, 8),
[{File, M, F, A, Ln}||{M,F, A, {{Ln, _},_}}<-ResRanges]
end, Files),
Res = [begin
Msg = lists:flatten(
io_lib:format("The ~p expression in function ~p:~p/~p is nested ~p times or more.",
[ExprType, M, F, A, NestLevel])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, M, F, A, Ln}<-Funs],
{ok, Res}.
-spec not_flush_unknown_messages([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
not_flush_unknown_messages(SearchPaths) ->
Files = wrangler_misc:expand_files(SearchPaths, ".erl"),
Funs = lists:flatmap(fun (F) ->
wrangler_code_inspector_lib:not_flush_unknown_messages_1(F, SearchPaths, 8)
end, Files),
Res = [begin
Msg = lists:flatten(
io_lib:format("The receive expression in function ~p:~p/~p does not flush unknown messages.",
[M, F, A])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, M, F, A, Ln}<-Funs],
{ok, Res}.
-spec calls_to_specific_function(mfa(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
calls_to_specific_function({M, F, A}, SearchPaths) ->
{ok, Calls} = wrangler_code_inspector_lib:calls_to_specific_function(
{M,F,A}, SearchPaths),
Res=[begin
Msg=lists:flatten(
io_lib:format("Oops. You've called the blacklisted function ~p:~p/~p at line ~p.",
[M, F, A, Line])),
{Msg, [{file, File},
{line, integer_to_list(Line)}]}
end ||{File,{{Line, _}, _}}<-Calls],
{ok, Res}.
-spec calls_to_specific_functions([mfa()], [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
calls_to_specific_functions(MFAs, SearchPaths) ->
{ok, Calls} = wrangler_code_inspector_lib:calls_to_specific_functions(
MFAs, SearchPaths),
Res=[begin
Msg=lists:flatten(
io_lib:format("Oops. You've called the blacklisted function ~p:~p/~p at line ~p.",
[M, F, A, Line])),
{Msg, [{file, File},
{line, integer_to_list(Line)}]}
end ||{File,{M, F, A}, {{Line, _}, _}}<-Calls],
{ok, Res}.
-type (op():: atom()).
-spec use_of_specific_ops([op()], [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
use_of_specific_ops(Ops, SearchPaths) ->
{ok, Calls} = use_of_specific_ops_1(Ops, SearchPaths),
Res=[begin
Msg=lists:flatten(
io_lib:format("Oops. You've used the blacklisted operaotr ~p.",
[Op])),
{Msg, [{file, File},
{line, integer_to_list(Line)}]}
end ||{File,Op, {{Line, _}, _}}<-Calls],
{ok, Res}.
use_of_specific_ops_1(Ops, SearchPaths) ->
{ok, ?FULL_TD_TU([?COLLECT(?T("E@"),
{_File@, get_operator(E@),api_refac:start_end_loc(_This@)},
lists:member(api_refac:type(E@),
[infix_expr, prefix_expr]) andalso
lists:member(get_operator(E@), Ops))],
[SearchPaths])}.
get_operator(Expr) ->
Op=case api_refac:type(Expr) of
infix_expr ->
wrangler_syntax:infix_expr_operator(Expr);
prefix_expr ->
wrangler_syntax:prefix_expr_operator(Expr)
end,
wrangler_syntax:operator_name(Op).
-spec use_of_export_all([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
use_of_export_all(SearchPaths) ->
{ok, Uses} = use_of_export_all_1(SearchPaths),
Res=[begin
Msg="Oops. You've used the 'export_all' directive.",
{Msg, [{file, File}]}
end ||File<-Uses],
{ok, Res}.
use_of_export_all_1(SearchPaths) ->
Files = wrangler_misc:expand_files(SearchPaths, ".erl"),
{ok, [File||File<-Files, use_of_export_all_2(File)]}.
use_of_export_all_2(File)->
try wrangler_ast_server:parse_annotate_file(File, false) of
{ok, {_, ModInfo}} ->
case lists:keysearch(attributes, 1, ModInfo) of
{value, {attributes, Attrs}} ->
lists:member({compile, export_all}, Attrs);
false -> false
end
catch _E1:_E2 ->
false
end.
%% Give the type (according to syntax_tools) of the patterns
%% in a function definition.
classify_pattern_match(File) ->
Classify = ?FULL_TD_TU([?COLLECT(?T("f@(Args@@@) when _Guard@@@ -> _Body@@@."),
{api_refac:fun_define_info(f@),
api_refac:start_end_loc(_This@),
overall_classify([pattern_type(Pat) || Pat <- lists:flatten(Args@@@)])},
true
)],
[File]),
MsgFun = fun (mixed) -> " patterns made up entirely of variables or of literals.";
(variable) -> " mixed patterns or patterns of literals only.";
(literal) -> " mixed patterns or patterns of variables only."
end,
Res=[begin
Msg=lists:flatten(
io_lib:format("This function could be defined differently: try it with~s~n", [MsgFun(Kind)])),
{Msg, [{file, File},
{line_from, integer_to_list(LineFrom)},
{line_to, integer_to_list(LineTo)}]}
end ||{_, {{LineFrom,_},{LineTo,_}}, Kind}<-Classify, Kind /= none],
{ok, Res}.
-spec pattern_type(syntaxTree()) -> variable | literal | mixed.
pattern_type(Pat) ->
case wrangler_syntax:is_literal(Pat) of
true -> literal;
false -> case api_refac:type(Pat) of
variable -> variable;
_ -> mixed
end
end.
-spec overall_classify([atom()]) -> atom().
overall_classify([]) ->
none;
overall_classify([X|Xs]) ->
overall_classify(X,Xs).
-spec overall_classify(atom(),[atom()]) -> atom().
overall_classify(X,[]) ->
X;
overall_classify(X,[Y|Ys]) ->
case X==Y of
true ->
overall_classify(X,Ys);
false ->
mixed
end.
%% Collect all the function applications within a function definition.
Returns { erlang , apply,3 } for uses of apply .
collect_function_apps({M, F, A}, SearchPaths) ->
?FULL_TD_TU([?COLLECT(?T("f@(Args@@) when _Guard@@ -> Body@@;"),
collect_apps_within(_This@),
{M, F, A} == api_refac:fun_define_info(f@))
],
[SearchPaths]).
collect_apps_within(Node) ->
?FULL_TD_TU([?COLLECT(?T("F@(Argss@@)"),
api_refac:fun_define_info(F@),
true)
],
Node).
collect_function_apps2({M, F, A}, SearchPaths) ->
?FULL_TD_TU([?COLLECT(?T("f@(Args@@) when _Guard@@ -> Body@@;"),
collect_apps_within2(_This@),
{M, F, A} == api_refac:fun_define_info(f@))
],
[SearchPaths]).
collect_apps_within2(Node) ->
?FULL_TD_TU([?COLLECT(?T("F@(Argss@@)"),
?PP(api_refac:get_app_mod(_This@)),
true)
],
Node).
-spec top_level_if([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
top_level_if(SearchPaths)->
Funs=?FULL_TD_TU([?COLLECT(?T("f@(Args@@) when Guard@@ ->Body@."),
{_File@, api_refac:fun_define_info(f@), api_refac:start_end_loc(_This@)},
api_refac:type(Body@) == if_expr)],
[SearchPaths]),
Res = [begin
Msg = lists:flatten(
io_lib:format("The function ~p:~p/~p consists of a top-level if expression.",
[M, F, A])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, {M, F, A}, {{Ln, _}, _}}<-Funs],
{ok, Res}.
-spec unnecessary_match([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
unnecessary_match(SearchPaths) ->
Funs=?FULL_TD_TU([?COLLECT(?T("Body@@, V@=Expr@, V@"),
{_File@, wrangler_misc:start_end_loc(lists:nthtail(length(Body@@), _This@))},
api_refac:type(V@) == variable andalso length(api_refac:var_refs(V@))==1)],
SearchPaths),
Res = [begin
Msg = lists:flatten(
io_lib:format("This is an unnecessary match expression at line ~p.",
[Ln])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, {{Ln, _}, _}}<-Funs],
{ok, Res}.
-spec append_two_lists([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
append_two_lists(SearchPaths) ->
Uses=?STOP_TD_TU([?COLLECT(?T("F@(L1@, L2@)"),
{_File@, wrangler_misc:start_end_loc(_This@)},
{lists, append, 2} == api_refac:fun_define_info(F@))],
SearchPaths),
Res = [begin
Msg = lists:flatten(
io_lib:format("This is a use of lists:append/2 at line ~p.",
[Ln])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, {{Ln, _}, _}}<-Uses],
{ok, Res}.
-spec non_tail_recursive_function([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
non_tail_recursive_function(SearchPaths) ->
Funs=?FULL_TD_TU([?COLLECT(?T("f@(Args@@@) when Guard@@@-> Body@@@."),
{_File@, api_refac:fun_define_info(f@),wrangler_misc:start_end_loc(_This@)},
inspec_examples:is_non_tail_recursive(_This@))],
[SearchPaths]),
Res = [begin
Msg = lists:flatten(
io_lib:format("Function ~p:~p/~p is not tail recursive.",
[M,F, A])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, {M, F, A},{{Ln, _}, _}}<-Funs],
{ok, Res}.
In this test , I try to detect two code code smells . One is
function definitions with 40 or more lines of code , and the
%% other is the use of outdated function lists:keysearch/3.
test(SearchPaths)->
Options=[{long_functions, [40]},
{calls_to_specific_function, [{lists, keysearch, 3}]}],
do_code_inspection(SearchPaths, Options).
| null | https://raw.githubusercontent.com/RefactoringTools/wrangler/d3d84879b4269759b26d009013edc5bcff49a1af/src/inspec_feedback_wrangler.erl | erlang | =====================================================================
=====================================================================
@private
API for feedback tool.
Give the type (according to syntax_tools) of the patterns
in a function definition.
Collect all the function applications within a function definition.
other is the use of outdated function lists:keysearch/3. | Wrangler 's feedback interface module to Erlang E - learning
@author
[ ]
@doc Wrangler 's feedback interface module to Erlang E - learning
-module(inspec_feedback_wrangler).
-export([do_code_inspection/2]).
-export([long_functions/2,
large_modules/2,
calls_to_specific_function/2,
calls_to_specific_functions/2,
classify_pattern_match/1,
nested_if_exprs/2,
nested_case_exprs/2,
nested_receive_exprs/2,
not_flush_unknown_messages/1,
top_level_if/1,
unnecessary_match/1,
append_two_lists/1,
non_tail_recursive_function/1,
use_of_specific_ops/2,
use_of_export_all/1
]).
-export([test/1,
collect_function_apps/2,
collect_function_apps2/2]).
-include("wrangler.hrl").
-type (message()::string()).
-type (tag() :: atom()).
-spec do_code_inspection([dir()|filename()], [{atom(), [any()]}]) ->
[{message(), [{tag, list()}]}].
do_code_inspection(SearchPaths, Options) ->
do_code_inspection(SearchPaths, Options, []).
do_code_inspection(_SearchPaths, [], Acc) ->
lists:append(lists:reverse(Acc));
do_code_inspection(SearchPaths, [{FunName, Args}|Options], Acc) ->
Res= try_inspector(?MODULE, FunName,
Args++[SearchPaths]),
do_code_inspection(SearchPaths, Options, [Res|Acc]).
try_inspector(Mod, Fun, Args) ->
case try_to_apply(Mod, Fun, Args) of
{error, {Reason, StackTrace}} ->
wrangler_io:format("Wrangler failed to run '~p':\n{~p, \n~s}\n",
[Fun, Reason, StackTrace]),
[];
{ok, Res} ->
Res
end.
try_to_apply(Mod, Fun, Args) ->
try apply(Mod, Fun, Args)
catch
throw:Error ->
Error;
_E1:E2:StackTrace ->
Reason=lists:flatten(
io_lib:format("~p",[StackTrace])),
{error, {E2,Reason}}
end.
-spec long_functions(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
long_functions(Lines, SearchPaths) ->
{ok, LongFuns} = wrangler_code_inspector_lib:long_functions(
SearchPaths, Lines, SearchPaths, 8),
Res=[begin
Msg=lists:flatten(
io_lib:format("Function ~p:~p/~p has more than ~p "
"lines of code.", [M, F, A, Lines])),
{Msg, [{file, File},
{line, integer_to_list(Line)}]}
end ||{{M, F, A}, {File, Line}}<-LongFuns],
{ok, Res}.
-spec large_modules(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
large_modules(Lines, SearchPaths) ->
{ok, LargeMods}= wrangler_code_inspector_lib:large_modules(Lines, SearchPaths, 8),
Res = [begin
M=filename:basename(File, ".erl"),
Msg=lists:flatten(
io_lib:format("The module '~p' has more than ~p "
"lines of code.", [list_to_atom(M), Lines])),
{Msg, [{file, File}]}
end ||File<-LargeMods],
{ok, Res}.
-spec nested_case_exprs(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
nested_case_exprs(NestLevel, SearchPaths) ->
nested_exprs(NestLevel, SearchPaths, 'case').
-spec nested_if_exprs(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
nested_if_exprs(NestLevel, SearchPaths) ->
nested_exprs(NestLevel, SearchPaths, 'if').
-spec nested_receive_exprs(integer(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
nested_receive_exprs(NestLevel, SearchPaths) ->
nested_exprs(NestLevel, SearchPaths, 'receive').
nested_exprs(NestLevel, SearchPaths, ExprType) ->
Files = wrangler_misc:expand_files(SearchPaths, ".erl"),
Funs = lists:flatmap(fun (File) ->
ResRanges=wrangler_code_inspector_lib:nested_exprs_1(
File, NestLevel, ExprType, SearchPaths, 8),
[{File, M, F, A, Ln}||{M,F, A, {{Ln, _},_}}<-ResRanges]
end, Files),
Res = [begin
Msg = lists:flatten(
io_lib:format("The ~p expression in function ~p:~p/~p is nested ~p times or more.",
[ExprType, M, F, A, NestLevel])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, M, F, A, Ln}<-Funs],
{ok, Res}.
-spec not_flush_unknown_messages([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
not_flush_unknown_messages(SearchPaths) ->
Files = wrangler_misc:expand_files(SearchPaths, ".erl"),
Funs = lists:flatmap(fun (F) ->
wrangler_code_inspector_lib:not_flush_unknown_messages_1(F, SearchPaths, 8)
end, Files),
Res = [begin
Msg = lists:flatten(
io_lib:format("The receive expression in function ~p:~p/~p does not flush unknown messages.",
[M, F, A])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, M, F, A, Ln}<-Funs],
{ok, Res}.
-spec calls_to_specific_function(mfa(), [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
calls_to_specific_function({M, F, A}, SearchPaths) ->
{ok, Calls} = wrangler_code_inspector_lib:calls_to_specific_function(
{M,F,A}, SearchPaths),
Res=[begin
Msg=lists:flatten(
io_lib:format("Oops. You've called the blacklisted function ~p:~p/~p at line ~p.",
[M, F, A, Line])),
{Msg, [{file, File},
{line, integer_to_list(Line)}]}
end ||{File,{{Line, _}, _}}<-Calls],
{ok, Res}.
-spec calls_to_specific_functions([mfa()], [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
calls_to_specific_functions(MFAs, SearchPaths) ->
{ok, Calls} = wrangler_code_inspector_lib:calls_to_specific_functions(
MFAs, SearchPaths),
Res=[begin
Msg=lists:flatten(
io_lib:format("Oops. You've called the blacklisted function ~p:~p/~p at line ~p.",
[M, F, A, Line])),
{Msg, [{file, File},
{line, integer_to_list(Line)}]}
end ||{File,{M, F, A}, {{Line, _}, _}}<-Calls],
{ok, Res}.
-type (op():: atom()).
-spec use_of_specific_ops([op()], [dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
use_of_specific_ops(Ops, SearchPaths) ->
{ok, Calls} = use_of_specific_ops_1(Ops, SearchPaths),
Res=[begin
Msg=lists:flatten(
io_lib:format("Oops. You've used the blacklisted operaotr ~p.",
[Op])),
{Msg, [{file, File},
{line, integer_to_list(Line)}]}
end ||{File,Op, {{Line, _}, _}}<-Calls],
{ok, Res}.
use_of_specific_ops_1(Ops, SearchPaths) ->
{ok, ?FULL_TD_TU([?COLLECT(?T("E@"),
{_File@, get_operator(E@),api_refac:start_end_loc(_This@)},
lists:member(api_refac:type(E@),
[infix_expr, prefix_expr]) andalso
lists:member(get_operator(E@), Ops))],
[SearchPaths])}.
get_operator(Expr) ->
Op=case api_refac:type(Expr) of
infix_expr ->
wrangler_syntax:infix_expr_operator(Expr);
prefix_expr ->
wrangler_syntax:prefix_expr_operator(Expr)
end,
wrangler_syntax:operator_name(Op).
-spec use_of_export_all([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
use_of_export_all(SearchPaths) ->
{ok, Uses} = use_of_export_all_1(SearchPaths),
Res=[begin
Msg="Oops. You've used the 'export_all' directive.",
{Msg, [{file, File}]}
end ||File<-Uses],
{ok, Res}.
use_of_export_all_1(SearchPaths) ->
Files = wrangler_misc:expand_files(SearchPaths, ".erl"),
{ok, [File||File<-Files, use_of_export_all_2(File)]}.
use_of_export_all_2(File)->
try wrangler_ast_server:parse_annotate_file(File, false) of
{ok, {_, ModInfo}} ->
case lists:keysearch(attributes, 1, ModInfo) of
{value, {attributes, Attrs}} ->
lists:member({compile, export_all}, Attrs);
false -> false
end
catch _E1:_E2 ->
false
end.
classify_pattern_match(File) ->
Classify = ?FULL_TD_TU([?COLLECT(?T("f@(Args@@@) when _Guard@@@ -> _Body@@@."),
{api_refac:fun_define_info(f@),
api_refac:start_end_loc(_This@),
overall_classify([pattern_type(Pat) || Pat <- lists:flatten(Args@@@)])},
true
)],
[File]),
MsgFun = fun (mixed) -> " patterns made up entirely of variables or of literals.";
(variable) -> " mixed patterns or patterns of literals only.";
(literal) -> " mixed patterns or patterns of variables only."
end,
Res=[begin
Msg=lists:flatten(
io_lib:format("This function could be defined differently: try it with~s~n", [MsgFun(Kind)])),
{Msg, [{file, File},
{line_from, integer_to_list(LineFrom)},
{line_to, integer_to_list(LineTo)}]}
end ||{_, {{LineFrom,_},{LineTo,_}}, Kind}<-Classify, Kind /= none],
{ok, Res}.
-spec pattern_type(syntaxTree()) -> variable | literal | mixed.
pattern_type(Pat) ->
case wrangler_syntax:is_literal(Pat) of
true -> literal;
false -> case api_refac:type(Pat) of
variable -> variable;
_ -> mixed
end
end.
-spec overall_classify([atom()]) -> atom().
overall_classify([]) ->
none;
overall_classify([X|Xs]) ->
overall_classify(X,Xs).
-spec overall_classify(atom(),[atom()]) -> atom().
overall_classify(X,[]) ->
X;
overall_classify(X,[Y|Ys]) ->
case X==Y of
true ->
overall_classify(X,Ys);
false ->
mixed
end.
Returns { erlang , apply,3 } for uses of apply .
collect_function_apps({M, F, A}, SearchPaths) ->
?FULL_TD_TU([?COLLECT(?T("f@(Args@@) when _Guard@@ -> Body@@;"),
collect_apps_within(_This@),
{M, F, A} == api_refac:fun_define_info(f@))
],
[SearchPaths]).
collect_apps_within(Node) ->
?FULL_TD_TU([?COLLECT(?T("F@(Argss@@)"),
api_refac:fun_define_info(F@),
true)
],
Node).
collect_function_apps2({M, F, A}, SearchPaths) ->
?FULL_TD_TU([?COLLECT(?T("f@(Args@@) when _Guard@@ -> Body@@;"),
collect_apps_within2(_This@),
{M, F, A} == api_refac:fun_define_info(f@))
],
[SearchPaths]).
collect_apps_within2(Node) ->
?FULL_TD_TU([?COLLECT(?T("F@(Argss@@)"),
?PP(api_refac:get_app_mod(_This@)),
true)
],
Node).
-spec top_level_if([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
top_level_if(SearchPaths)->
Funs=?FULL_TD_TU([?COLLECT(?T("f@(Args@@) when Guard@@ ->Body@."),
{_File@, api_refac:fun_define_info(f@), api_refac:start_end_loc(_This@)},
api_refac:type(Body@) == if_expr)],
[SearchPaths]),
Res = [begin
Msg = lists:flatten(
io_lib:format("The function ~p:~p/~p consists of a top-level if expression.",
[M, F, A])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, {M, F, A}, {{Ln, _}, _}}<-Funs],
{ok, Res}.
-spec unnecessary_match([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
unnecessary_match(SearchPaths) ->
Funs=?FULL_TD_TU([?COLLECT(?T("Body@@, V@=Expr@, V@"),
{_File@, wrangler_misc:start_end_loc(lists:nthtail(length(Body@@), _This@))},
api_refac:type(V@) == variable andalso length(api_refac:var_refs(V@))==1)],
SearchPaths),
Res = [begin
Msg = lists:flatten(
io_lib:format("This is an unnecessary match expression at line ~p.",
[Ln])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, {{Ln, _}, _}}<-Funs],
{ok, Res}.
-spec append_two_lists([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
append_two_lists(SearchPaths) ->
Uses=?STOP_TD_TU([?COLLECT(?T("F@(L1@, L2@)"),
{_File@, wrangler_misc:start_end_loc(_This@)},
{lists, append, 2} == api_refac:fun_define_info(F@))],
SearchPaths),
Res = [begin
Msg = lists:flatten(
io_lib:format("This is a use of lists:append/2 at line ~p.",
[Ln])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, {{Ln, _}, _}}<-Uses],
{ok, Res}.
-spec non_tail_recursive_function([dir()|filename()]) ->
{ok, [{message(), [{tag(), list()}]}]}.
non_tail_recursive_function(SearchPaths) ->
Funs=?FULL_TD_TU([?COLLECT(?T("f@(Args@@@) when Guard@@@-> Body@@@."),
{_File@, api_refac:fun_define_info(f@),wrangler_misc:start_end_loc(_This@)},
inspec_examples:is_non_tail_recursive(_This@))],
[SearchPaths]),
Res = [begin
Msg = lists:flatten(
io_lib:format("Function ~p:~p/~p is not tail recursive.",
[M,F, A])),
{Msg, [{file, File},
{line, integer_to_list(Ln)}]}
end || {File, {M, F, A},{{Ln, _}, _}}<-Funs],
{ok, Res}.
In this test , I try to detect two code code smells . One is
function definitions with 40 or more lines of code , and the
test(SearchPaths)->
Options=[{long_functions, [40]},
{calls_to_specific_function, [{lists, keysearch, 3}]}],
do_code_inspection(SearchPaths, Options).
|
965a82f972b12c289e9525e4990806647081168e048bafcbf4aac88737129e7d | mirage/mirage-flow-rawlink | mirage_flow_rawlink.ml |
* Copyright ( c ) 2017 < >
*
* 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) 2017 Thomas Gazagnaire <>
*
* 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.Infix
type 'a io = 'a Lwt.t
type buffer = Cstruct.t
type error = [`Msg of string]
type write_error = [ Mirage_flow.write_error | error ]
let pp_error ppf (`Msg s) = Fmt.string ppf s
let pp_write_error ppf = function
| #Mirage_flow.write_error as e -> Mirage_flow.pp_write_error ppf e
| #error as e -> pp_error ppf e
type flow = Lwt_rawlink.t
let err e = Lwt.return (Error (`Msg (Printexc.to_string e)))
let read t =
Lwt.catch (fun () ->
Lwt_rawlink.read_packet t >|= fun buf -> Ok (`Data buf)
) (function Failure _ -> Lwt.return (Ok `Eof) | e -> err e)
let write t b =
Lwt.catch (fun () ->
Lwt_rawlink.send_packet t b >|= fun () -> Ok ()
) (fun e -> err e)
let close t = Lwt_rawlink.close_link t
let writev t bs =
Lwt.catch (fun () ->
Lwt_list.iter_s (Lwt_rawlink.send_packet t) bs >|= fun () -> Ok ()
) (fun e -> err e)
| null | https://raw.githubusercontent.com/mirage/mirage-flow-rawlink/b0edf6c9b7ba5bbc6e58347a0e47cd05355155d1/src/mirage_flow_rawlink.ml | ocaml |
* Copyright ( c ) 2017 < >
*
* 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) 2017 Thomas Gazagnaire <>
*
* 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.Infix
type 'a io = 'a Lwt.t
type buffer = Cstruct.t
type error = [`Msg of string]
type write_error = [ Mirage_flow.write_error | error ]
let pp_error ppf (`Msg s) = Fmt.string ppf s
let pp_write_error ppf = function
| #Mirage_flow.write_error as e -> Mirage_flow.pp_write_error ppf e
| #error as e -> pp_error ppf e
type flow = Lwt_rawlink.t
let err e = Lwt.return (Error (`Msg (Printexc.to_string e)))
let read t =
Lwt.catch (fun () ->
Lwt_rawlink.read_packet t >|= fun buf -> Ok (`Data buf)
) (function Failure _ -> Lwt.return (Ok `Eof) | e -> err e)
let write t b =
Lwt.catch (fun () ->
Lwt_rawlink.send_packet t b >|= fun () -> Ok ()
) (fun e -> err e)
let close t = Lwt_rawlink.close_link t
let writev t bs =
Lwt.catch (fun () ->
Lwt_list.iter_s (Lwt_rawlink.send_packet t) bs >|= fun () -> Ok ()
) (fun e -> err e)
|
|
93d5336e637e3a113386a42a6d6da8ddb2441912de5626ca59abcf9cf1dca4f8 | cxphoe/SICP-solutions | 2.20.rkt | (define (same-parity x . y)
(define (filter proc items)
(if (null? items)
'()
(if (proc (car items))
(cons (car items)
(filter proc (cdr items)))
(filter proc (cdr items)))))
(let ((tail (if (even? x)
(filter even? y)
(filter odd? y))))
(cons x tail))) | null | https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%202-Building%20Abstractions%20with%20Data/2.Hierarchical%20Data%20and%20the%20Closure%20Property/2.20.rkt | racket | (define (same-parity x . y)
(define (filter proc items)
(if (null? items)
'()
(if (proc (car items))
(cons (car items)
(filter proc (cdr items)))
(filter proc (cdr items)))))
(let ((tail (if (even? x)
(filter even? y)
(filter odd? y))))
(cons x tail))) |
|
9259e09755f96076f7384246570467e696550ad1615327d81ba8e5a937d7db2d | khibino/haskell-relational-record | DS.hs | module DS (definePgConTable) where
import Language.Haskell.TH
import Language . Haskell . TH.Name . CamelCase ( ConName )
import Database.HDBC.PostgreSQL (connectPostgreSQL)
import Database.HDBC.Query.TH
import Database.HDBC.Schema.PostgreSQL (driverPostgreSQL)
definePgConTable :: String -> String -> [Name] -> Q [Dec]
definePgConTable =
defineTableFromDB (connectPostgreSQL "dbname=pgcon") driverPostgreSQL
| null | https://raw.githubusercontent.com/khibino/haskell-relational-record/759b3d7cea207e64d2bd1cf195125182f73d2a52/doc/slide/code-reading-201601/DS.hs | haskell | module DS (definePgConTable) where
import Language.Haskell.TH
import Language . Haskell . TH.Name . CamelCase ( ConName )
import Database.HDBC.PostgreSQL (connectPostgreSQL)
import Database.HDBC.Query.TH
import Database.HDBC.Schema.PostgreSQL (driverPostgreSQL)
definePgConTable :: String -> String -> [Name] -> Q [Dec]
definePgConTable =
defineTableFromDB (connectPostgreSQL "dbname=pgcon") driverPostgreSQL
|
|
bd54a8a00bbd440920764d5e340e3220eec6fda6d32ad53005650e441c99bbdf | footprintanalytics/footprint-web | pre_alias_aggregations_test.clj | (ns metabase.query-processor.middleware.pre-alias-aggregations-test
"Tests for the `pre-alias-aggregations` middleware. For the most part we don't need to test the actual pre-alias
logic, as that comes from the MBQL library and is tested thoroughly there -- we just need to test that it gets
applied in the correct places."
(:require [clojure.test :refer :all]
[metabase.driver :as driver]
[metabase.query-processor.middleware.pre-alias-aggregations :as qp.pre-alias-aggregations]
[metabase.test :as mt]))
(defn- pre-alias [query]
(driver/with-driver (or driver/*driver* :h2)
(qp.pre-alias-aggregations/pre-alias-aggregations query)))
(deftest pre-alias-aggregations-test
(is (= (mt/mbql-query checkins
{:source-table $$checkins
:aggregation [[:aggregation-options [:sum $user_id] {:name "sum"} ]
[:aggregation-options [:sum $venue_id] {:name "sum_2"} ]]})
(pre-alias
(mt/mbql-query checkins
{:source-table $$checkins
:aggregation [[:sum $user_id] [:sum $venue_id]]})))))
(deftest named-aggregations-test
(testing "if one or more aggregations are already named, do things still work correctly?"
(is (= (mt/mbql-query checkins
{:source-table $$checkins
:aggregation [[:aggregation-options [:sum $user_id] {:name "sum"}]
[:aggregation-options [:sum $venue_id] {:name "sum_2"}]]})
(pre-alias
(mt/mbql-query checkins
{:source-table $$checkins
:aggregation [[:sum $user_id]
[:aggregation-options [:sum $venue_id] {:name "sum"}]]}))))))
(deftest source-queries-test
(testing "do aggregations inside source queries get pre-aliased?")
(is (= (mt/mbql-query checkins
{:source-query {:source-table $$checkins
:aggregation [[:aggregation-options [:sum $user_id] {:name "sum"}]
[:aggregation-options [:sum $venue_id] {:name "sum_2"}]]}
:aggregation [[:aggregation-options [:count] {:name "count"}]]})
(pre-alias
(mt/mbql-query checkins
{:source-query {:source-table $$checkins
:aggregation [[:sum $user_id] [:sum $venue_id]]}
:aggregation [[:count]]})))))
(deftest source-queries-inside-joins-test
(testing "do aggregatons inside of source queries inside joins get pre-aliased?"
(is (= (mt/mbql-query checkins
{:source-table $$venues
:aggregation [[:aggregation-options [:count] {:name "count"}]]
:joins [{:source-query {:source-table $$checkins
:aggregation [[:aggregation-options [:sum $user_id] {:name "sum"}]
[:aggregation-options [:sum $venue_id] {:name "sum_2"}]]
:breakout [$venue_id]}
:alias "checkins"
:condition [:= &checkins.venue_id $venues.id]}]})
(pre-alias
(mt/mbql-query checkins
{:source-table $$venues
:aggregation [[:count]]
:joins [{:source-query {:source-table $$checkins
:aggregation [[:sum $user_id] [:sum $venue_id]]
:breakout [$venue_id]}
:alias "checkins"
:condition [:= &checkins.venue_id $venues.id]}]}))))))
(deftest expressions-test
(testing "does pre-aliasing work the way we'd expect with expressions?"
(is (= {:database 1
:type :query
:query {:source-table 1
:aggregation [[:aggregation-options [:+ 20 [:sum [:field 2 nil]]] {:name "expression"}]]}}
(pre-alias
{:database 1
:type :query
:query {:source-table 1
:aggregation [[:+ 20 [:sum [:field 2 nil]]]]}})))
(is (= {:database 1
:type :query
:query {:source-table 1
:aggregation [[:aggregation-options
[:+ 20 [:sum [:field 2 nil]]]
{:name "expression"}]
[:aggregation-options
[:- 20 [:sum [:field 2 nil]]]
{:name "expression_2"}]]}}
(pre-alias
{:database 1
:type :query
:query {:source-table 1
:aggregation [[:+ 20 [:sum [:field 2 nil]]]
[:- 20 [:sum [:field 2 nil]]]]}})))))
(driver/register! ::test-driver, :abstract? true, :parent :sql)
(defmethod driver/escape-alias ::test-driver [_ custom-field-name]
(str \_ custom-field-name))
(deftest use-escape-alias-test
(testing (str "we should use [[driver/escape-alias]] on the generated aggregation names in case the "
"drivers need to tweak the default names we generate."))
(is (= {:database 1
:type :query
:query {:source-table 1
:aggregation [[:aggregation-options [:+ 20 [:sum [:field 2 nil]]] {:name "_expression"}]
[:aggregation-options [:count] {:name "_count"}]]}}
(driver/with-driver ::test-driver
(pre-alias
{:database 1
:type :query
:query {:source-table 1
:aggregation [[:+ 20 [:sum [:field 2 nil]]]
[:count]]}})))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/query_processor/middleware/pre_alias_aggregations_test.clj | clojure | (ns metabase.query-processor.middleware.pre-alias-aggregations-test
"Tests for the `pre-alias-aggregations` middleware. For the most part we don't need to test the actual pre-alias
logic, as that comes from the MBQL library and is tested thoroughly there -- we just need to test that it gets
applied in the correct places."
(:require [clojure.test :refer :all]
[metabase.driver :as driver]
[metabase.query-processor.middleware.pre-alias-aggregations :as qp.pre-alias-aggregations]
[metabase.test :as mt]))
(defn- pre-alias [query]
(driver/with-driver (or driver/*driver* :h2)
(qp.pre-alias-aggregations/pre-alias-aggregations query)))
(deftest pre-alias-aggregations-test
(is (= (mt/mbql-query checkins
{:source-table $$checkins
:aggregation [[:aggregation-options [:sum $user_id] {:name "sum"} ]
[:aggregation-options [:sum $venue_id] {:name "sum_2"} ]]})
(pre-alias
(mt/mbql-query checkins
{:source-table $$checkins
:aggregation [[:sum $user_id] [:sum $venue_id]]})))))
(deftest named-aggregations-test
(testing "if one or more aggregations are already named, do things still work correctly?"
(is (= (mt/mbql-query checkins
{:source-table $$checkins
:aggregation [[:aggregation-options [:sum $user_id] {:name "sum"}]
[:aggregation-options [:sum $venue_id] {:name "sum_2"}]]})
(pre-alias
(mt/mbql-query checkins
{:source-table $$checkins
:aggregation [[:sum $user_id]
[:aggregation-options [:sum $venue_id] {:name "sum"}]]}))))))
(deftest source-queries-test
(testing "do aggregations inside source queries get pre-aliased?")
(is (= (mt/mbql-query checkins
{:source-query {:source-table $$checkins
:aggregation [[:aggregation-options [:sum $user_id] {:name "sum"}]
[:aggregation-options [:sum $venue_id] {:name "sum_2"}]]}
:aggregation [[:aggregation-options [:count] {:name "count"}]]})
(pre-alias
(mt/mbql-query checkins
{:source-query {:source-table $$checkins
:aggregation [[:sum $user_id] [:sum $venue_id]]}
:aggregation [[:count]]})))))
(deftest source-queries-inside-joins-test
(testing "do aggregatons inside of source queries inside joins get pre-aliased?"
(is (= (mt/mbql-query checkins
{:source-table $$venues
:aggregation [[:aggregation-options [:count] {:name "count"}]]
:joins [{:source-query {:source-table $$checkins
:aggregation [[:aggregation-options [:sum $user_id] {:name "sum"}]
[:aggregation-options [:sum $venue_id] {:name "sum_2"}]]
:breakout [$venue_id]}
:alias "checkins"
:condition [:= &checkins.venue_id $venues.id]}]})
(pre-alias
(mt/mbql-query checkins
{:source-table $$venues
:aggregation [[:count]]
:joins [{:source-query {:source-table $$checkins
:aggregation [[:sum $user_id] [:sum $venue_id]]
:breakout [$venue_id]}
:alias "checkins"
:condition [:= &checkins.venue_id $venues.id]}]}))))))
(deftest expressions-test
(testing "does pre-aliasing work the way we'd expect with expressions?"
(is (= {:database 1
:type :query
:query {:source-table 1
:aggregation [[:aggregation-options [:+ 20 [:sum [:field 2 nil]]] {:name "expression"}]]}}
(pre-alias
{:database 1
:type :query
:query {:source-table 1
:aggregation [[:+ 20 [:sum [:field 2 nil]]]]}})))
(is (= {:database 1
:type :query
:query {:source-table 1
:aggregation [[:aggregation-options
[:+ 20 [:sum [:field 2 nil]]]
{:name "expression"}]
[:aggregation-options
[:- 20 [:sum [:field 2 nil]]]
{:name "expression_2"}]]}}
(pre-alias
{:database 1
:type :query
:query {:source-table 1
:aggregation [[:+ 20 [:sum [:field 2 nil]]]
[:- 20 [:sum [:field 2 nil]]]]}})))))
(driver/register! ::test-driver, :abstract? true, :parent :sql)
(defmethod driver/escape-alias ::test-driver [_ custom-field-name]
(str \_ custom-field-name))
(deftest use-escape-alias-test
(testing (str "we should use [[driver/escape-alias]] on the generated aggregation names in case the "
"drivers need to tweak the default names we generate."))
(is (= {:database 1
:type :query
:query {:source-table 1
:aggregation [[:aggregation-options [:+ 20 [:sum [:field 2 nil]]] {:name "_expression"}]
[:aggregation-options [:count] {:name "_count"}]]}}
(driver/with-driver ::test-driver
(pre-alias
{:database 1
:type :query
:query {:source-table 1
:aggregation [[:+ 20 [:sum [:field 2 nil]]]
[:count]]}})))))
|
|
2e018275470ee61a9cada4dd167c9e238eee2fcc06732f8511da6a5a17364b3c | yurug/ocaml4.04.0-copatterns | spacetime.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
and ,
(* *)
Copyright 2015 - -2016 Jane Street Group LLC
(* *)
(* 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. *)
(* *)
(**************************************************************************)
* Profiling of a program 's space behaviour over time .
Currently only supported on x86 - 64 platforms running 64 - bit code .
To use the functions in this module you must :
- configure the compiler with " -spacetime " ;
- compile to native code .
Without these conditions being satisfied the functions in this module
will have no effect .
Instead of manually taking profiling heap snapshots with this module it is
possible to use an automatic snapshot facility that writes profiling
information at fixed intervals to a file . To enable this , all that needs to
be done is to build the relevant program using a compiler configured with
-spacetime ; and set the environment variable OCAML_SPACETIME_INTERVAL to an
integer number of milliseconds giving the interval between profiling heap
snapshots . This interval should not be made excessively small relative to
the running time of the program . A typical interval to start with might be
1/100 of the running time of the program . The program must exit " normally "
( i.e. by calling [ exit ] , with whatever exit code , rather than being
abnormally terminated by a signal ) so that the snapshot file is
correctly completed .
When using the automatic snapshot mode the profiling output is written
to a file called " spacetime-<pid > " where < pid > is the process ID of the
program . ( If the program forks and continues executing then multiple
files may be produced with different pid numbers . ) The profiling output
is by default written to the current working directory when the program
starts . This may be customised by setting the OCAML_SPACETIME_SNAPSHOT_DIR
environment variable to the name of the desired directory .
If using automatic snapshots the presence of the
[ save_event_for_automatic_snapshots ] function , below , should be noted .
The functions in this module are thread safe .
For functions to decode the information recorded by the profiler ,
see the Spacetime offline library in otherlibs/.
Currently only supported on x86-64 platforms running 64-bit code.
To use the functions in this module you must:
- configure the compiler with "-spacetime";
- compile to native code.
Without these conditions being satisfied the functions in this module
will have no effect.
Instead of manually taking profiling heap snapshots with this module it is
possible to use an automatic snapshot facility that writes profiling
information at fixed intervals to a file. To enable this, all that needs to
be done is to build the relevant program using a compiler configured with
-spacetime; and set the environment variable OCAML_SPACETIME_INTERVAL to an
integer number of milliseconds giving the interval between profiling heap
snapshots. This interval should not be made excessively small relative to
the running time of the program. A typical interval to start with might be
1/100 of the running time of the program. The program must exit "normally"
(i.e. by calling [exit], with whatever exit code, rather than being
abnormally terminated by a signal) so that the snapshot file is
correctly completed.
When using the automatic snapshot mode the profiling output is written
to a file called "spacetime-<pid>" where <pid> is the process ID of the
program. (If the program forks and continues executing then multiple
files may be produced with different pid numbers.) The profiling output
is by default written to the current working directory when the program
starts. This may be customised by setting the OCAML_SPACETIME_SNAPSHOT_DIR
environment variable to the name of the desired directory.
If using automatic snapshots the presence of the
[save_event_for_automatic_snapshots] function, below, should be noted.
The functions in this module are thread safe.
For functions to decode the information recorded by the profiler,
see the Spacetime offline library in otherlibs/. *)
module Series : sig
(** Type representing a file that will hold a series of heap snapshots
together with additional information required to interpret those
snapshots. *)
type t
(** [create ~path] creates a series file at [path]. *)
val create : path:string -> t
(** [save_event] writes an event, which is an arbitrary string, into the
given series file. This may be used for identifying particular points
during program execution when analysing the profile.
The optional [time] parameter is as for [Snapshot.take].
*)
val save_event : ?time:float -> t -> event_name:string -> unit
(** [save_and_close series] writes information into [series] required for
interpeting the snapshots that [series] contains and then closes the
[series] file. This function must be called to produce a valid series
file.
The optional [time] parameter is as for [Snapshot.take].
*)
val save_and_close : ?time:float -> t -> unit
end
module Snapshot : sig
* [ take series ] takes a snapshot of the profiling annotations on the values
in the minor and major heaps , together with GC stats , and write the
result to the [ series ] file . This function triggers a minor GC but does
not allocate any memory itself .
If the optional [ time ] is specified , it will be used instead of the
result of [ Sys.time ] as the timestamp of the snapshot . Such [ time]s
should start from zero and be monotonically increasing . This parameter
is intended to be used so that snapshots can be correlated against wall
clock time ( which is not supported in the standard library ) rather than
elapsed CPU time .
in the minor and major heaps, together with GC stats, and write the
result to the [series] file. This function triggers a minor GC but does
not allocate any memory itself.
If the optional [time] is specified, it will be used instead of the
result of [Sys.time] as the timestamp of the snapshot. Such [time]s
should start from zero and be monotonically increasing. This parameter
is intended to be used so that snapshots can be correlated against wall
clock time (which is not supported in the standard library) rather than
elapsed CPU time.
*)
val take : ?time:float -> Series.t -> unit
end
(** Like [Series.save_event], but writes to the automatic snapshot file.
This function is a no-op if OCAML_SPACETIME_INTERVAL was not set. *)
val save_event_for_automatic_snapshots : event_name:string -> unit
| null | https://raw.githubusercontent.com/yurug/ocaml4.04.0-copatterns/b3ec6a3cc203bd2cde3b618546d29e10f1102323/stdlib/spacetime.mli | ocaml | ************************************************************************
OCaml
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Type representing a file that will hold a series of heap snapshots
together with additional information required to interpret those
snapshots.
* [create ~path] creates a series file at [path].
* [save_event] writes an event, which is an arbitrary string, into the
given series file. This may be used for identifying particular points
during program execution when analysing the profile.
The optional [time] parameter is as for [Snapshot.take].
* [save_and_close series] writes information into [series] required for
interpeting the snapshots that [series] contains and then closes the
[series] file. This function must be called to produce a valid series
file.
The optional [time] parameter is as for [Snapshot.take].
* Like [Series.save_event], but writes to the automatic snapshot file.
This function is a no-op if OCAML_SPACETIME_INTERVAL was not set. | and ,
Copyright 2015 - -2016 Jane Street Group LLC
the GNU Lesser General Public License version 2.1 , with the
* Profiling of a program 's space behaviour over time .
Currently only supported on x86 - 64 platforms running 64 - bit code .
To use the functions in this module you must :
- configure the compiler with " -spacetime " ;
- compile to native code .
Without these conditions being satisfied the functions in this module
will have no effect .
Instead of manually taking profiling heap snapshots with this module it is
possible to use an automatic snapshot facility that writes profiling
information at fixed intervals to a file . To enable this , all that needs to
be done is to build the relevant program using a compiler configured with
-spacetime ; and set the environment variable OCAML_SPACETIME_INTERVAL to an
integer number of milliseconds giving the interval between profiling heap
snapshots . This interval should not be made excessively small relative to
the running time of the program . A typical interval to start with might be
1/100 of the running time of the program . The program must exit " normally "
( i.e. by calling [ exit ] , with whatever exit code , rather than being
abnormally terminated by a signal ) so that the snapshot file is
correctly completed .
When using the automatic snapshot mode the profiling output is written
to a file called " spacetime-<pid > " where < pid > is the process ID of the
program . ( If the program forks and continues executing then multiple
files may be produced with different pid numbers . ) The profiling output
is by default written to the current working directory when the program
starts . This may be customised by setting the OCAML_SPACETIME_SNAPSHOT_DIR
environment variable to the name of the desired directory .
If using automatic snapshots the presence of the
[ save_event_for_automatic_snapshots ] function , below , should be noted .
The functions in this module are thread safe .
For functions to decode the information recorded by the profiler ,
see the Spacetime offline library in otherlibs/.
Currently only supported on x86-64 platforms running 64-bit code.
To use the functions in this module you must:
- configure the compiler with "-spacetime";
- compile to native code.
Without these conditions being satisfied the functions in this module
will have no effect.
Instead of manually taking profiling heap snapshots with this module it is
possible to use an automatic snapshot facility that writes profiling
information at fixed intervals to a file. To enable this, all that needs to
be done is to build the relevant program using a compiler configured with
-spacetime; and set the environment variable OCAML_SPACETIME_INTERVAL to an
integer number of milliseconds giving the interval between profiling heap
snapshots. This interval should not be made excessively small relative to
the running time of the program. A typical interval to start with might be
1/100 of the running time of the program. The program must exit "normally"
(i.e. by calling [exit], with whatever exit code, rather than being
abnormally terminated by a signal) so that the snapshot file is
correctly completed.
When using the automatic snapshot mode the profiling output is written
to a file called "spacetime-<pid>" where <pid> is the process ID of the
program. (If the program forks and continues executing then multiple
files may be produced with different pid numbers.) The profiling output
is by default written to the current working directory when the program
starts. This may be customised by setting the OCAML_SPACETIME_SNAPSHOT_DIR
environment variable to the name of the desired directory.
If using automatic snapshots the presence of the
[save_event_for_automatic_snapshots] function, below, should be noted.
The functions in this module are thread safe.
For functions to decode the information recorded by the profiler,
see the Spacetime offline library in otherlibs/. *)
module Series : sig
type t
val create : path:string -> t
val save_event : ?time:float -> t -> event_name:string -> unit
val save_and_close : ?time:float -> t -> unit
end
module Snapshot : sig
* [ take series ] takes a snapshot of the profiling annotations on the values
in the minor and major heaps , together with GC stats , and write the
result to the [ series ] file . This function triggers a minor GC but does
not allocate any memory itself .
If the optional [ time ] is specified , it will be used instead of the
result of [ Sys.time ] as the timestamp of the snapshot . Such [ time]s
should start from zero and be monotonically increasing . This parameter
is intended to be used so that snapshots can be correlated against wall
clock time ( which is not supported in the standard library ) rather than
elapsed CPU time .
in the minor and major heaps, together with GC stats, and write the
result to the [series] file. This function triggers a minor GC but does
not allocate any memory itself.
If the optional [time] is specified, it will be used instead of the
result of [Sys.time] as the timestamp of the snapshot. Such [time]s
should start from zero and be monotonically increasing. This parameter
is intended to be used so that snapshots can be correlated against wall
clock time (which is not supported in the standard library) rather than
elapsed CPU time.
*)
val take : ?time:float -> Series.t -> unit
end
val save_event_for_automatic_snapshots : event_name:string -> unit
|
8f483b98ade08eacae937ccb24c85db48205d8cedfe7ac36141c65593e49880e | tormaroe/cl-nats | nats.subject.lisp |
(in-package #:nats.subject)
(defun every-subject-char-p (str)
(cl-ppcre:scan "^[^\\s\\r\\n]+$" str))
(deftype subject ()
"SUBJECT must be a string containing at least one character,
and only visible characters."
'(and string
(satisfies every-subject-char-p))) | null | https://raw.githubusercontent.com/tormaroe/cl-nats/3aa6eb98401849aabecb553266c49d7a8a7d73fd/nats.subject.lisp | lisp |
(in-package #:nats.subject)
(defun every-subject-char-p (str)
(cl-ppcre:scan "^[^\\s\\r\\n]+$" str))
(deftype subject ()
"SUBJECT must be a string containing at least one character,
and only visible characters."
'(and string
(satisfies every-subject-char-p))) |
|
3a4e2ee8c103f39d51bdeb6b41344377a0e103d19820c26ca918a1de65717b35 | AlfrescoLabs/technical-validation | util.clj | ;
Copyright © 2013,2014 ( )
;
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.
;
This file is part of an unsupported extension to Alfresco .
;
(ns alfresco-technical-validation.impl.util
(:require [clojure.string :as s]
[clojure.tools.logging :as log]
[clojure.java.io :as io]
))
(defn declare-result
"Builds a map representing the result of testing a single validation criteria."
([criteria-id message] (declare-result criteria-id nil message))
([criteria-id passes message]
(if (nil? passes)
{ :criteria-id criteria-id
:message message }
{ :criteria-id criteria-id
:passes passes
:message message } )))
(defn build-binary-message
[query-result]
(s/join "\n"
(map #(str (get % "ClassName")
" uses "
(s/join ", " (get % "APIs")))
query-result)))
(defn standard-binary-validation
([criteria-id query-result manual-followup-required success-message]
(standard-binary-validation criteria-id query-result manual-followup-required success-message empty?))
([criteria-id query-result manual-followup-required success-message comparison-fn]
(let [query-result-as-string (build-binary-message query-result)
message (if (empty? query-result-as-string) success-message query-result-as-string)]
(declare-result criteria-id
(comparison-fn query-result)
(if manual-followup-required (str message "\n#### Manual followup required. ####") message)))))
(defn build-source-message
[source header matches]
(str header ":\n"
(s/join "\n"
(map #(str (subs (str (:file %)) (.length ^String source)) " line " (:line-number %) ": " (s/trim (:line %)))
matches))))
(defn standard-source-validation
([source content-index regex-id criteria-id message-header manual-followup-required success-message]
(standard-source-validation source content-index regex-id criteria-id message-header manual-followup-required success-message empty?))
([source content-index regex-id criteria-id message-header manual-followup-required success-message comparison-fn]
(let [matches (filter #(= regex-id (:regex-id %)) content-index)
message (if (empty? matches)
success-message
(build-source-message source message-header matches))]
(declare-result criteria-id
(comparison-fn matches)
(if manual-followup-required (str message "\n#### Manual followup required. ####") message)))))
| null | https://raw.githubusercontent.com/AlfrescoLabs/technical-validation/bd1b4b83f6a5e9dd150eedbeebecd30970d3b4aa/src/clojure/alfresco_technical_validation/impl/util.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| Copyright © 2013,2014 ( )
distributed under the License is distributed on an " AS IS " BASIS ,
This file is part of an unsupported extension to Alfresco .
(ns alfresco-technical-validation.impl.util
(:require [clojure.string :as s]
[clojure.tools.logging :as log]
[clojure.java.io :as io]
))
(defn declare-result
"Builds a map representing the result of testing a single validation criteria."
([criteria-id message] (declare-result criteria-id nil message))
([criteria-id passes message]
(if (nil? passes)
{ :criteria-id criteria-id
:message message }
{ :criteria-id criteria-id
:passes passes
:message message } )))
(defn build-binary-message
[query-result]
(s/join "\n"
(map #(str (get % "ClassName")
" uses "
(s/join ", " (get % "APIs")))
query-result)))
(defn standard-binary-validation
([criteria-id query-result manual-followup-required success-message]
(standard-binary-validation criteria-id query-result manual-followup-required success-message empty?))
([criteria-id query-result manual-followup-required success-message comparison-fn]
(let [query-result-as-string (build-binary-message query-result)
message (if (empty? query-result-as-string) success-message query-result-as-string)]
(declare-result criteria-id
(comparison-fn query-result)
(if manual-followup-required (str message "\n#### Manual followup required. ####") message)))))
(defn build-source-message
[source header matches]
(str header ":\n"
(s/join "\n"
(map #(str (subs (str (:file %)) (.length ^String source)) " line " (:line-number %) ": " (s/trim (:line %)))
matches))))
(defn standard-source-validation
([source content-index regex-id criteria-id message-header manual-followup-required success-message]
(standard-source-validation source content-index regex-id criteria-id message-header manual-followup-required success-message empty?))
([source content-index regex-id criteria-id message-header manual-followup-required success-message comparison-fn]
(let [matches (filter #(= regex-id (:regex-id %)) content-index)
message (if (empty? matches)
success-message
(build-source-message source message-header matches))]
(declare-result criteria-id
(comparison-fn matches)
(if manual-followup-required (str message "\n#### Manual followup required. ####") message)))))
|
e40e646324c3fce6568e8ad56abd291f42d36e499139917d45ccbed1e1cc160a | tanders/cluster-engine | 5f.lisp | (in-package cluster-engine) (setf *random-state* (make-random-state t)) (print
(cluster-engine::ClusterEngine 20 t nil
(append (cluster-engine::R-rhythms-one-voice-at-timepoints #'(lambda (x) (equal x '(0 1/4))) 0 '(2) :dur-start)
(cluster-engine::R-only-m-motifs 0))
'((4 4))
'(((1/4) (1/8) (1/16) (3/8)) ((60)(m 7 -3)(m -7 3))))
) | null | https://raw.githubusercontent.com/tanders/cluster-engine/064ad4fd107f8d9a3dfcaf260524c2ab034c6d3f/test_files/5f.lisp | lisp | (in-package cluster-engine) (setf *random-state* (make-random-state t)) (print
(cluster-engine::ClusterEngine 20 t nil
(append (cluster-engine::R-rhythms-one-voice-at-timepoints #'(lambda (x) (equal x '(0 1/4))) 0 '(2) :dur-start)
(cluster-engine::R-only-m-motifs 0))
'((4 4))
'(((1/4) (1/8) (1/16) (3/8)) ((60)(m 7 -3)(m -7 3))))
) |
|
6c8f124d0c3713a81c459b11835038eb6bd6e6a17a06c37bdb02efd5ff0d39b8 | tsloughter/kuberl | kuberl_v1_quobyte_volume_source.erl | -module(kuberl_v1_quobyte_volume_source).
-export([encode/1]).
-export_type([kuberl_v1_quobyte_volume_source/0]).
-type kuberl_v1_quobyte_volume_source() ::
#{ 'group' => binary(),
'readOnly' => boolean(),
'registry' := binary(),
'tenant' => binary(),
'user' => binary(),
'volume' := binary()
}.
encode(#{ 'group' := Group,
'readOnly' := ReadOnly,
'registry' := Registry,
'tenant' := Tenant,
'user' := User,
'volume' := Volume
}) ->
#{ 'group' => Group,
'readOnly' => ReadOnly,
'registry' => Registry,
'tenant' => Tenant,
'user' => User,
'volume' => Volume
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_quobyte_volume_source.erl | erlang | -module(kuberl_v1_quobyte_volume_source).
-export([encode/1]).
-export_type([kuberl_v1_quobyte_volume_source/0]).
-type kuberl_v1_quobyte_volume_source() ::
#{ 'group' => binary(),
'readOnly' => boolean(),
'registry' := binary(),
'tenant' => binary(),
'user' => binary(),
'volume' := binary()
}.
encode(#{ 'group' := Group,
'readOnly' := ReadOnly,
'registry' := Registry,
'tenant' := Tenant,
'user' := User,
'volume' := Volume
}) ->
#{ 'group' => Group,
'readOnly' => ReadOnly,
'registry' => Registry,
'tenant' => Tenant,
'user' => User,
'volume' => Volume
}.
|
|
eddba04179ea23d8bba4cadec5b273992c96e7c448cff4c85da35bc66dfa16b1 | well-typed/large-records | Simple.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeOperators #-}
# LANGUAGE ViewPatterns #
module Test.Prop.Record.Combinators.Simple (tests) where
import Control.Monad.State
import Data.Bifunctor
import Data.SOP
import qualified Data.Record.Anon.Advanced as Anon
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Prop.Record.Model.Orphans ()
import Test.Prop.Record.Model.Generator
import qualified Test.Prop.Record.Model as Modl
tests :: TestTree
tests = testGroup "Test.Prop.Record.Combinators.Simple" [
testProperty "map" test_map
, testProperty "mapM" test_mapM
, testProperty "zip" test_zip
, testProperty "zipWith" test_zipWith
, testProperty "zipWithM" test_zipWithM
, testProperty "collapse" test_collapse
, testProperty "sequenceA" test_sequenceA
, testProperty "pure" test_pure
, testProperty "ap" test_ap
]
{-------------------------------------------------------------------------------
Auxiliary
-------------------------------------------------------------------------------}
pTop :: Proxy Top
pTop = Proxy
{-------------------------------------------------------------------------------
Tests proper
-------------------------------------------------------------------------------}
test_map ::
SomeRecord (K Int)
-> Fun Int Int
-> Property
test_map r (applyFun -> f) =
onModlRecord pTop (Modl.map f') r
=== onAnonRecord pTop (Anon.map f') r
where
f' :: K Int x -> K Int x
f' = mapKK f
test_mapM ::
SomeRecord (K Int)
-> Fun (Int, Word) (Int, Word)
-> Property
test_mapM r (applyFun -> f) =
(run $ onModlRecordM pTop (Modl.mapM f') r)
=== (run $ onAnonRecordM pTop (Anon.mapM f') r)
where
run :: State Word a -> a
run = flip evalState 0
f' :: K Int x -> State Word (K Int x)
f' (K x) = state $ \s -> first K $ f (x, s)
test_zip ::
SomeRecordPair (K Int) (K Int)
-> Property
test_zip r =
onModlRecordPair pTop Modl.zip r
=== onAnonRecordPair pTop Anon.zip r
test_zipWith ::
SomeRecordPair (K Int) (K Int)
-> Fun (Int, Int) Int
-> Property
test_zipWith r (applyFun -> f) =
onModlRecordPair pTop (Modl.zipWith f') r
=== onAnonRecordPair pTop (Anon.zipWith f') r
where
f' :: K Int x -> K Int x -> K Int x
f' (K x) (K y) = K $ f (x, y)
test_zipWithM ::
SomeRecordPair (K Int) (K Int)
-> Fun (Int, Int, Word) (Int, Word)
-> Property
test_zipWithM r (applyFun -> f) =
(run $ onModlRecordPairM pTop (Modl.zipWithM f') r)
=== (run $ onAnonRecordPairM pTop (Anon.zipWithM f') r)
where
run :: State Word a -> a
run = flip evalState 0
f' :: K Int x -> K Int x -> State Word (K Int x)
f' (K x) (K y) = state $ \s -> first K $ f (x, y, s)
test_collapse ::
SomeRecord (K Int)
-> Property
test_collapse (SR mf r) =
Modl.collapse r
=== Anon.collapse (Modl.toRecord mf r)
test_sequenceA ::
SomeRecord (K Int)
-> Fun (Int, Word) (Int, Word)
-> Property
test_sequenceA r (applyFun -> f) =
(run $ onModlRecordM pTop Modl.sequenceA r')
=== (run $ onAnonRecordM pTop Anon.sequenceA r')
where
run :: State Word a -> a
run = flip evalState 0
r' :: SomeRecord (State Word :.: K Int)
r' = onModlRecord pTop (Modl.map f') r
f' :: K Int x -> (State Word :.: K Int) x
f' (K x) = Comp $ state $ \s -> first K $ f (x, s)
test_pure :: SomeFields -> Property
test_pure sf =
someModlRecord sf (\mf -> Modl.pure mf (K True))
=== someAnonRecord pTop sf ( Anon.pure (K True))
test_ap ::
SomeRecordPair (K Int) (K Int)
-> Property
test_ap (SR2 mf rx ry) =
onModlRecordPair pTop Modl.ap r'
=== onAnonRecordPair pTop Anon.ap r'
where
r' :: SomeRecordPair (K Int -.-> K Int) (K Int)
r' = SR2 mf (Modl.map f rx) ry
f :: K Int x -> (K Int -.-> K Int) x
f (K x) = fn $ \(K y) -> K (x + y)
| null | https://raw.githubusercontent.com/well-typed/large-records/78d0966e4871847e2c17a0aa821bacf38bdf96bc/large-anon/test/Test/Prop/Record/Combinators/Simple.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE TypeOperators #
------------------------------------------------------------------------------
Auxiliary
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Tests proper
------------------------------------------------------------------------------ | # LANGUAGE TypeApplications #
# LANGUAGE ViewPatterns #
module Test.Prop.Record.Combinators.Simple (tests) where
import Control.Monad.State
import Data.Bifunctor
import Data.SOP
import qualified Data.Record.Anon.Advanced as Anon
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Prop.Record.Model.Orphans ()
import Test.Prop.Record.Model.Generator
import qualified Test.Prop.Record.Model as Modl
tests :: TestTree
tests = testGroup "Test.Prop.Record.Combinators.Simple" [
testProperty "map" test_map
, testProperty "mapM" test_mapM
, testProperty "zip" test_zip
, testProperty "zipWith" test_zipWith
, testProperty "zipWithM" test_zipWithM
, testProperty "collapse" test_collapse
, testProperty "sequenceA" test_sequenceA
, testProperty "pure" test_pure
, testProperty "ap" test_ap
]
pTop :: Proxy Top
pTop = Proxy
test_map ::
SomeRecord (K Int)
-> Fun Int Int
-> Property
test_map r (applyFun -> f) =
onModlRecord pTop (Modl.map f') r
=== onAnonRecord pTop (Anon.map f') r
where
f' :: K Int x -> K Int x
f' = mapKK f
test_mapM ::
SomeRecord (K Int)
-> Fun (Int, Word) (Int, Word)
-> Property
test_mapM r (applyFun -> f) =
(run $ onModlRecordM pTop (Modl.mapM f') r)
=== (run $ onAnonRecordM pTop (Anon.mapM f') r)
where
run :: State Word a -> a
run = flip evalState 0
f' :: K Int x -> State Word (K Int x)
f' (K x) = state $ \s -> first K $ f (x, s)
test_zip ::
SomeRecordPair (K Int) (K Int)
-> Property
test_zip r =
onModlRecordPair pTop Modl.zip r
=== onAnonRecordPair pTop Anon.zip r
test_zipWith ::
SomeRecordPair (K Int) (K Int)
-> Fun (Int, Int) Int
-> Property
test_zipWith r (applyFun -> f) =
onModlRecordPair pTop (Modl.zipWith f') r
=== onAnonRecordPair pTop (Anon.zipWith f') r
where
f' :: K Int x -> K Int x -> K Int x
f' (K x) (K y) = K $ f (x, y)
test_zipWithM ::
SomeRecordPair (K Int) (K Int)
-> Fun (Int, Int, Word) (Int, Word)
-> Property
test_zipWithM r (applyFun -> f) =
(run $ onModlRecordPairM pTop (Modl.zipWithM f') r)
=== (run $ onAnonRecordPairM pTop (Anon.zipWithM f') r)
where
run :: State Word a -> a
run = flip evalState 0
f' :: K Int x -> K Int x -> State Word (K Int x)
f' (K x) (K y) = state $ \s -> first K $ f (x, y, s)
test_collapse ::
SomeRecord (K Int)
-> Property
test_collapse (SR mf r) =
Modl.collapse r
=== Anon.collapse (Modl.toRecord mf r)
test_sequenceA ::
SomeRecord (K Int)
-> Fun (Int, Word) (Int, Word)
-> Property
test_sequenceA r (applyFun -> f) =
(run $ onModlRecordM pTop Modl.sequenceA r')
=== (run $ onAnonRecordM pTop Anon.sequenceA r')
where
run :: State Word a -> a
run = flip evalState 0
r' :: SomeRecord (State Word :.: K Int)
r' = onModlRecord pTop (Modl.map f') r
f' :: K Int x -> (State Word :.: K Int) x
f' (K x) = Comp $ state $ \s -> first K $ f (x, s)
test_pure :: SomeFields -> Property
test_pure sf =
someModlRecord sf (\mf -> Modl.pure mf (K True))
=== someAnonRecord pTop sf ( Anon.pure (K True))
test_ap ::
SomeRecordPair (K Int) (K Int)
-> Property
test_ap (SR2 mf rx ry) =
onModlRecordPair pTop Modl.ap r'
=== onAnonRecordPair pTop Anon.ap r'
where
r' :: SomeRecordPair (K Int -.-> K Int) (K Int)
r' = SR2 mf (Modl.map f rx) ry
f :: K Int x -> (K Int -.-> K Int) x
f (K x) = fn $ \(K y) -> K (x + y)
|
aca86c1046f1c552f73fe94bc4806435a9873e374adecb286d3a67a0596a39d3 | replikativ/datahike | tools.cljc | (ns ^:no-doc datahike.tools
(:require
[superv.async :refer [throw-if-exception-]]
#?(:clj [clojure.java.io :as io])
[taoensso.timbre :as log])
#?(:clj (:import [java.util Properties UUID Date])))
(defn combine-hashes [x y]
#?(:clj (clojure.lang.Util/hashCombine x y)
:cljs (hash-combine x y)))
#?(:clj
(defn- -case-tree [queries variants]
(if queries
(let [v1 (take (/ (count variants) 2) variants)
v2 (drop (/ (count variants) 2) variants)]
(list 'if (first queries)
(-case-tree (next queries) v1)
(-case-tree (next queries) v2)))
(first variants))))
#?(:clj
(defmacro case-tree [qs vs]
(-case-tree qs vs)))
(defn ^:dynamic get-time []
#?(:clj (java.util.Date.)
:cljs (js/Date.)))
(defmacro raise
"Logging an error and throwing an exception with message and structured data.
Arguments:
- Any number of strings that describe the error
- Last argument is a map of data that helps understanding the source of the error"
[& fragments]
(let [msgs (butlast fragments)
data (last fragments)]
(list `(log/log! :error :p ~fragments ~{:?line (:line (meta &form))})
`(throw #?(:clj (ex-info (str ~@(map (fn [m#] (if (string? m#) m# (list 'pr-str m#))) msgs)) ~data)
:cljs (error (str ~@(map (fn [m#] (if (string? m#) m# (list 'pr-str m#))) msgs)) ~data))))))
; (throwable-promise) derived from (promise) in clojure/core.clj.
; * Clojure
* Copyright ( c ) . All rights reserved .
; * The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 ( -1.0.php )
; * which can be found in the file epl-v10.html at the root of this distribution.
; * By using this software in any fashion, you are agreeing to be bound by
; * the terms of this license.
; * You must not remove this notice, or any other, from this software.
(defn throwable-promise
"Returns a promise object that can be read with deref/@, and set,
once only, with deliver. Calls to deref/@ prior to delivery will
block, unless the variant of deref with timeout is used. All
subsequent derefs will return the same delivered value without
blocking. Exceptions delivered to the promise will throw on deref."
[]
(let [d (java.util.concurrent.CountDownLatch. 1)
v (atom d)]
(reify
clojure.lang.IDeref
(deref [_] (.await d) (throw-if-exception- @v))
clojure.lang.IBlockingDeref
(deref
[_ timeout-ms timeout-val]
(if (.await d timeout-ms java.util.concurrent.TimeUnit/MILLISECONDS)
(throw-if-exception- @v)
timeout-val))
clojure.lang.IPending
(isRealized [this]
(zero? (.getCount d)))
clojure.lang.IFn
(invoke
[this x]
(when (and (pos? (.getCount d))
(compare-and-set! v d x))
(.countDown d)
this)))))
(defn get-version
"Retrieves the current version of a dependency. Thanks to "
[dep]
#?(:clj
(let [path (str "META-INF/maven/" (or (namespace dep) (name dep))
"/" (name dep) "/pom.properties")
props (io/resource path)]
(when props
(with-open [stream (io/input-stream props)]
(let [props (doto (Properties.) (.load stream))]
(.getProperty props "version")))))
:cljs
"JavaScript"))
(defn meta-data []
{:datahike/version (or (get-version 'io.replikativ/datahike) "DEVELOPMENT")
:konserve/version (get-version 'io.replikativ/konserve)
:hitchhiker.tree/version (get-version 'io.replikativ/hitchhiker-tree)
:persistent.set/version (get-version 'persistent-sorted-set/persistent-sorted-set)
:datahike/id (UUID/randomUUID)
:datahike/created-at (Date.)})
(defn deep-merge
"Recursively merges maps together. If all the maps supplied have nested maps
under the same keys, these nested maps are merged. Otherwise the value is
overwritten, as in `clojure.core/merge`.
Copied from weavejester/medley 1.3.0"
{:arglists '([& maps])
:added "1.1.0"}
([])
([a] a)
([a b]
(when (or a b)
(letfn [(merge-entry [m e]
(let [k (key e)
v' (val e)]
(if (contains? m k)
(assoc m k (let [v (get m k)]
(if (and (map? v) (map? v'))
(deep-merge v v')
v')))
(assoc m k v'))))]
(reduce merge-entry (or a {}) (seq b)))))
([a b & more]
(reduce deep-merge (or a {}) (cons b more))))
(defn timed [f]
(let [now #?(:clj #(. System (nanoTime))
:cljs #(* 1000 (. (js/Date.) (getTime))))
start (now)
result (f)
end (now)
t (/ (double (- end start))
1000000.0)]
{:res result
:t t}))
| null | https://raw.githubusercontent.com/replikativ/datahike/b7795e6b0ae9c6649a11a27e958f6716c1b1ec9b/src/datahike/tools.cljc | clojure | (throwable-promise) derived from (promise) in clojure/core.clj.
* Clojure
* The use and distribution terms for this software are covered by the
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software. | (ns ^:no-doc datahike.tools
(:require
[superv.async :refer [throw-if-exception-]]
#?(:clj [clojure.java.io :as io])
[taoensso.timbre :as log])
#?(:clj (:import [java.util Properties UUID Date])))
(defn combine-hashes [x y]
#?(:clj (clojure.lang.Util/hashCombine x y)
:cljs (hash-combine x y)))
#?(:clj
(defn- -case-tree [queries variants]
(if queries
(let [v1 (take (/ (count variants) 2) variants)
v2 (drop (/ (count variants) 2) variants)]
(list 'if (first queries)
(-case-tree (next queries) v1)
(-case-tree (next queries) v2)))
(first variants))))
#?(:clj
(defmacro case-tree [qs vs]
(-case-tree qs vs)))
(defn ^:dynamic get-time []
#?(:clj (java.util.Date.)
:cljs (js/Date.)))
(defmacro raise
"Logging an error and throwing an exception with message and structured data.
Arguments:
- Any number of strings that describe the error
- Last argument is a map of data that helps understanding the source of the error"
[& fragments]
(let [msgs (butlast fragments)
data (last fragments)]
(list `(log/log! :error :p ~fragments ~{:?line (:line (meta &form))})
`(throw #?(:clj (ex-info (str ~@(map (fn [m#] (if (string? m#) m# (list 'pr-str m#))) msgs)) ~data)
:cljs (error (str ~@(map (fn [m#] (if (string? m#) m# (list 'pr-str m#))) msgs)) ~data))))))
* Copyright ( c ) . All rights reserved .
* Eclipse Public License 1.0 ( -1.0.php )
(defn throwable-promise
"Returns a promise object that can be read with deref/@, and set,
once only, with deliver. Calls to deref/@ prior to delivery will
block, unless the variant of deref with timeout is used. All
subsequent derefs will return the same delivered value without
blocking. Exceptions delivered to the promise will throw on deref."
[]
(let [d (java.util.concurrent.CountDownLatch. 1)
v (atom d)]
(reify
clojure.lang.IDeref
(deref [_] (.await d) (throw-if-exception- @v))
clojure.lang.IBlockingDeref
(deref
[_ timeout-ms timeout-val]
(if (.await d timeout-ms java.util.concurrent.TimeUnit/MILLISECONDS)
(throw-if-exception- @v)
timeout-val))
clojure.lang.IPending
(isRealized [this]
(zero? (.getCount d)))
clojure.lang.IFn
(invoke
[this x]
(when (and (pos? (.getCount d))
(compare-and-set! v d x))
(.countDown d)
this)))))
(defn get-version
"Retrieves the current version of a dependency. Thanks to "
[dep]
#?(:clj
(let [path (str "META-INF/maven/" (or (namespace dep) (name dep))
"/" (name dep) "/pom.properties")
props (io/resource path)]
(when props
(with-open [stream (io/input-stream props)]
(let [props (doto (Properties.) (.load stream))]
(.getProperty props "version")))))
:cljs
"JavaScript"))
(defn meta-data []
{:datahike/version (or (get-version 'io.replikativ/datahike) "DEVELOPMENT")
:konserve/version (get-version 'io.replikativ/konserve)
:hitchhiker.tree/version (get-version 'io.replikativ/hitchhiker-tree)
:persistent.set/version (get-version 'persistent-sorted-set/persistent-sorted-set)
:datahike/id (UUID/randomUUID)
:datahike/created-at (Date.)})
(defn deep-merge
"Recursively merges maps together. If all the maps supplied have nested maps
under the same keys, these nested maps are merged. Otherwise the value is
overwritten, as in `clojure.core/merge`.
Copied from weavejester/medley 1.3.0"
{:arglists '([& maps])
:added "1.1.0"}
([])
([a] a)
([a b]
(when (or a b)
(letfn [(merge-entry [m e]
(let [k (key e)
v' (val e)]
(if (contains? m k)
(assoc m k (let [v (get m k)]
(if (and (map? v) (map? v'))
(deep-merge v v')
v')))
(assoc m k v'))))]
(reduce merge-entry (or a {}) (seq b)))))
([a b & more]
(reduce deep-merge (or a {}) (cons b more))))
(defn timed [f]
(let [now #?(:clj #(. System (nanoTime))
:cljs #(* 1000 (. (js/Date.) (getTime))))
start (now)
result (f)
end (now)
t (/ (double (- end start))
1000000.0)]
{:res result
:t t}))
|
8531fcdc5de3c6844e38148fd4aabc092a6e16034c1038bb9630872d79e630b3 | SilentCircle/scpf | scpf_SUITE.erl | %%%----------------------------------------------------------------
%%% Purpose: Test suite for the 'scpf' module.
%%%-----------------------------------------------------------------
-module(scpf_SUITE).
-include_lib("common_test/include/ct.hrl").
-include("scpf_SUITE.hrl").
-import(scpf_test_support,
[
get_sim_config/2,
get_svc_config/2,
make_sim_notification/2,
multi_store/2,
pv/2,
pv/3,
req_val/2,
start_apnsv3_sim/3,
start_gcm_sim/3
]).
-compile(export_all).
%%--------------------------------------------------------------------
%% COMMON TEST CALLBACK FUNCTIONS
%%--------------------------------------------------------------------
suite() -> [
{timetrap, {seconds, 30}},
{require, sc_push},
{require, gcm_erl},
{require, apns_erlv3},
{require, registrations},
{require, gcm_sim_node},
{require, gcm_sim_config},
{require, apnsv3_sim_node},
{require, apnsv3_sim_config},
{require, lager},
{require, databases},
{require, connect_info}
].
%%--------------------------------------------------------------------
init_per_suite(Config) ->
Sasl = ct:get_config(sasl),
ct:pal("SASL: ~p~n", [Sasl]),
set_all_env(sasl, Sasl),
ensure_started(sasl),
Databases = ct:get_config(databases),
ct:pal("Databases: ~p~n", [Databases]),
ConnectInfo = ct:get_config(connect_info),
ct:pal("connect_info config: ~p~n", [ConnectInfo]),
Cookie = "scpf",
{ApnsV3SimNode, ApnsV3SimCfg} = get_sim_config(apnsv3_sim_config, Config),
{GcmSimNode, GcmSimCfg} = get_sim_config(gcm_sim_config, Config),
%% Start GCM simulator
ct:log("Starting GCM simulator with config: ~p", [GcmSimCfg]),
{ok, GcmSimStartedApps} = start_gcm_sim(GcmSimNode, GcmSimCfg, Cookie),
ct:log("Starting APNS HTTP/2 simulator with config: ~p", [ApnsV3SimCfg]),
{ok, ApnsSimStartedApps} = start_apnsv3_sim(ApnsV3SimNode, ApnsV3SimCfg,
Cookie),
ct:pal("init_per_suite: Started apns sim apps=~p", [ApnsSimStartedApps]),
Started = start_per_suite_apps(Config),
ct:pal("init_per_suite: Started apps=~p", [Started]),
Registrations = ct:get_config(registrations),
ct:pal("Registrations: ~p", [Registrations]),
multi_store(Config, [{apnsv3_sim_started_apps, ApnsSimStartedApps},
{gcm_sim_started_apps, GcmSimStartedApps},
{suite_started_apps, Started},
{apnsv3_sim_node, ApnsV3SimNode},
{apnsv3_sim_config, ApnsV3SimCfg},
{gcm_sim_node, GcmSimNode},
{gcm_sim_config, GcmSimCfg},
{registrations, Registrations},
{databases, Databases},
{connect_info, ConnectInfo}]
).
%%--------------------------------------------------------------------
end_per_suite(Config) ->
We do n't care about because they are on
% a slave node that will get shut down.
Apps = req_val(suite_started_apps, Config),
[application:stop(App) || App <- Apps],
ok.
%%--------------------------------------------------------------------
init_per_group(Group, Config) when Group =:= internal_db;
Group =:= external_db ->
ct:pal("===== Running test group ~p =====", [Group]),
DBMap = req_val(databases, Config),
DBInfo = maps:get(Group, DBMap),
NewConfig = lists:keystore(dbinfo, 1, Config, {dbinfo, DBInfo}),
ok = application:set_env(sc_push_lib, db_pools, db_pools(DBInfo, NewConfig)),
{ok, DbPools} = application:get_env(sc_push_lib, db_pools),
ct:pal("DbPools: ~p", [DbPools]),
case check_db_availability(NewConfig) of
ok ->
NewConfig;
Error ->
Reason = lists:flatten(
io_lib:format("Cannot communicate with ~p,"
" error: ~p", [Group, Error])),
{skip, Reason}
end;
init_per_group(_GroupName, Config) ->
Config.
%%--------------------------------------------------------------------
end_per_group(_GroupName, _Config) ->
ok.
%%--------------------------------------------------------------------
init_per_testcase(_Case, Config) ->
init_per_testcase_common(Config).
%%--------------------------------------------------------------------
end_per_testcase(_Case, Config) ->
end_per_testcase_common(Config).
%%--------------------------------------------------------------------
groups() ->
[
{service, [], [
{internal_db, [], service_test_groups()},
{external_db, [], service_test_groups()}
]
}
].
%%--------------------------------------------------------------------
service_test_groups() ->
[
send_msg_test,
send_msg_fail_test,
send_msg_no_reg_test
].
%%--------------------------------------------------------------------
all() ->
[
{group, service}
].
%%--------------------------------------------------------------------
%% TEST CASES
%%--------------------------------------------------------------------
send_msg_test(doc) ->
["sc_push:send/1 should send a message to all push services"];
send_msg_test(suite) ->
[];
send_msg_test(Config) ->
RegPLs = req_val(registrations, Config),
SimHdrs = [{"X-GCMSimulator-StatusCode", "200"},
{"X-GCMSimulator-Results", "message_id:1000"}],
ok = sc_push:register_ids(RegPLs),
[
begin
Tag = req_val(tag, RegPL),
Notification = [
{alert, ?ALERT_MSG},
{tag, Tag},
{aps, [{badge, 42}]},
{gcm, [{collapse_key, <<"alert">>}]},
{return, success} % Will only work with sc_push_svc_null!
],
ct:pal("Sending notification ~p to ~p", [Notification, Tag]),
Opts = [{http_headers, SimHdrs}], % Only for GCM
Res = sc_push:send(Notification, Opts),
ct:pal("Got result ~p", [Res]),
[{ok, {UUID, Props}}] = Res,
ct:pal("Sent notification to ~p, uuid: ~s, props: ~p",
[Tag, uuid_to_str(UUID), Props])
end || RegPL <- RegPLs
],
deregister_ids(RegPLs),
ok.
%%--------------------------------------------------------------------
send_msg_fail_test(doc) ->
["sc_push:send/1 should fail"];
send_msg_fail_test(suite) ->
[];
send_msg_fail_test(Config) ->
RegPLs = req_val(registrations, Config),
ServiceName = null,
NullRegPL = get_service_properties(ServiceName, RegPLs),
ok = sc_push:register_id(NullRegPL),
Tag = req_val(tag, NullRegPL),
ExpectedError = {error, forced_test_failure},
Notification = [
{alert, ?ALERT_MSG},
{tag, Tag},
{return, ExpectedError} % Will only work with sc_push_svc_null!
],
ct:pal("Sending notification ~p to ~p", [Notification, Tag]),
Res = sc_push:send(Notification),
ct:pal("Got result: ~p", [Res]),
[{error, {_UUID, ExpectedError}}] = Res,
ct:pal("Expected failure sending notification to service ~p, tag ~p",
[ServiceName, Tag]),
deregister_ids(RegPLs),
ok.
%%--------------------------------------------------------------------
send_msg_no_reg_test(doc) ->
["sc_push:send/1 should fail with tag not found"];
send_msg_no_reg_test(suite) ->
[];
send_msg_no_reg_test(Config) ->
RegPLs = req_val(registrations, Config),
ServiceName = null,
NullRegPL = get_service_properties(ServiceName, RegPLs),
ok = sc_push:register_id(NullRegPL),
FakeTag = <<"$$Completely bogus tag$$">>,
ExpectedError = [{reg_not_found_for_tag, FakeTag}],
Notification = [
{alert, ?ALERT_MSG},
{tag, FakeTag}
],
Res = sc_push:send(Notification),
ct:pal("Got result: ~p", [Res]),
[{error, ExpectedError}] = Res,
ct:pal("Got expected error (~p) from send notification", [ExpectedError]),
deregister_ids(RegPLs),
ok.
%%====================================================================
Internal helper functions
%%====================================================================
init_per_testcase_common(Config) ->
(catch end_per_testcase_common(Config)),
db_create(Config),
Apps = [sc_push, gcm_erl, apns_erlv3],
AppList = lists:foldl(
fun(App, Acc) ->
set_env(App, get_svc_config(App, Config)),
{ok, L} = application:ensure_all_started(App),
Acc ++ L
end, [], Apps),
multi_store(Config, [{started_apps, AppList}]).
%%--------------------------------------------------------------------
end_per_testcase_common(Config) ->
Apps = lists:reverse(pv(started_apps, Config, [])),
_ = [ok = application:stop(App) || App <- Apps],
db_destroy(Config),
lists:keydelete(started_apps, 1, Config).
%%--------------------------------------------------------------------
set_env(App, FromEnv) ->
[ok = application:set_env(App, K, V) || {K, V} <- FromEnv].
%%--------------------------------------------------------------------
First try to get the app config from Config , failing which get it from
ct : ( ) .
get_env_val(App, Config) ->
case pv(App, Config) of
undefined ->
ct:get_config(App);
Env ->
Env
end.
%%--------------------------------------------------------------------
deregister_ids(RegPLs) ->
[deregister_id(RegPL) || RegPL <- RegPLs].
%%--------------------------------------------------------------------
deregister_id(RegPL) ->
ct:pal("Deregistering ~p", [RegPL]),
Service = req_val(service, RegPL),
Token = req_val(token, RegPL),
ID = sc_push_reg_api:make_id(Service, Token),
ok = sc_push:deregister_ids([ID]),
ct:pal("Deregistered IDs ~p", [ID]).
%%====================================================================
%% Lager support
%%====================================================================
lager_config(Config, RawLagerConfig) ->
PrivDir = req_val(priv_dir, Config), % Standard CT variable
Replacements = [
{error_log_file, filename:join(PrivDir, "error.log")},
{console_log_file, filename:join(PrivDir, "console.log")},
{crash_log_file, filename:join(PrivDir, "crash.log")}
],
replace_template_vars(RawLagerConfig, Replacements).
replace_template_vars(RawLagerConfig, Replacements) ->
Ctx = dict:from_list(Replacements),
Str = lists:flatten(io_lib:fwrite("~1000p~s", [RawLagerConfig, "."])),
SConfig = mustache:render(Str, Ctx),
{ok, Tokens, _} = erl_scan:string(SConfig),
{ok, LagerConfig} = erl_parse:parse_term(Tokens),
LagerConfig.
%%====================================================================
%% General helper functions
%%====================================================================
start_per_suite_apps(Config) ->
Apps = [lager, ssl],
Lager = lager_config(Config, ct:get_config(lager)),
set_env(lager, Lager),
Fun = fun(App, Acc) ->
{ok, L} = application:ensure_all_started(App),
Acc ++ L
end,
StartedApps = lists:foldl(Fun, [], Apps),
lists:usort(StartedApps).
set_mnesia_dir(Config) ->
DataDir = req_val(data_dir, Config),
MnesiaDir = filename:join(DataDir, "db"),
ok = filelib:ensure_dir(MnesiaDir),
ok = application:set_env(mnesia, dir, MnesiaDir).
uuid_to_str(UUID) ->
uuid:uuid_to_string(UUID, binary_standard).
get_service_properties(Service, [_|_]=RegPLs) when is_atom(Service) ->
case [PL || PL <- RegPLs, req_val(service, PL) =:= Service] of
[RegPL] ->
RegPL;
[] ->
ct:fail({cannot_find_service, Service});
L ->
ct:fail({unexpected_response, L})
end.
%%--------------------------------------------------------------------
db_create(Config) ->
DBInfo = req_val(dbinfo, Config),
DB = maps:get(db, DBInfo),
db_create(DB, DBInfo, Config).
db_create(mnesia, _DBInfo, Config) ->
PrivDir = req_val(priv_dir, Config), % Standard CT variable
MnesiaDir = filename:join(PrivDir, "mnesia"),
ok = application:set_env(mnesia, dir, MnesiaDir),
db_destroy(mnesia, _DBInfo, Config),
ok = mnesia:create_schema([node()]);
db_create(DB, DBInfo, Config) ->
db_create(mnesia, DBInfo, Config),
clear_external_db(DB, DBInfo, Config).
%%--------------------------------------------------------------------
db_destroy(Config) ->
DBInfo = req_val(dbinfo, Config),
DB = maps:get(db, DBInfo),
db_destroy(DB, DBInfo, Config).
db_destroy(mnesia, _DBInfo, _Config) ->
mnesia:stop(),
ok = mnesia:delete_schema([node()]);
db_destroy(DB, DBInfo, Config) ->
db_destroy(mnesia, DBInfo, Config),
clear_external_db(DB, DBInfo, Config).
%%--------------------------------------------------------------------
clear_external_db(postgres=EDB, _DBInfo, Config) ->
ConnParams = db_conn_params(postgres, Config),
Tables = ["scpf.push_tokens"],
case epgsql:connect(ConnParams) of
{ok, Conn} ->
lists:foreach(
fun(Table) ->
{ok, _} = epgsql:squery(Conn, "delete from " ++ Table)
end, Tables),
ok = epgsql:close(Conn);
Error ->
ct:fail("~p error: ~p", [EDB, Error])
end.
%%--------------------------------------------------------------------
check_db_availability(Config) ->
DBInfo = req_val(dbinfo, Config),
DB = maps:get(db, DBInfo),
check_db_availability(DB, Config).
check_db_availability(mnesia, _Config) ->
ok;
check_db_availability(postgres, Config) ->
ConnParams = db_conn_params(postgres, Config),
try epgsql:connect(ConnParams) of
{ok, Conn} ->
ok = epgsql:close(Conn);
Error ->
Error
catch
_:Reason ->
{error, Reason}
end.
%%--------------------------------------------------------------------
db_pools(#{db := DB, mod := DBMod}, Config) ->
[
{sc_push_reg_pool, % name
[ % sizeargs
{size, 10},
{max_overflow, 20}
],
[ % workerargs
{db_mod, DBMod},
{db_config, db_config(DB, Config)}
]}
].
%%--------------------------------------------------------------------
db_config(DB, Config) ->
maps:get(DB, req_val(connect_info, Config), []).
%%--------------------------------------------------------------------
db_conn_params(DB, Config) ->
case db_config(DB, Config) of
#{connection := ConnParams} ->
ConnParams;
Val ->
Val
end.
%%--------------------------------------------------------------------
set_all_env(App, Props) ->
lists:foreach(fun({K, V}) ->
ok = application:set_env(App, K, V)
end, Props).
%%--------------------------------------------------------------------
ensure_started(App) ->
case application:start(App) of
ok ->
ok;
{error, {already_started, App}} ->
ok
end.
| null | https://raw.githubusercontent.com/SilentCircle/scpf/68d46626a056cfd8234d3b6f4661d7d037758619/test/scpf_SUITE.erl | erlang | ----------------------------------------------------------------
Purpose: Test suite for the 'scpf' module.
-----------------------------------------------------------------
--------------------------------------------------------------------
COMMON TEST CALLBACK FUNCTIONS
--------------------------------------------------------------------
--------------------------------------------------------------------
Start GCM simulator
--------------------------------------------------------------------
a slave node that will get shut down.
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
TEST CASES
--------------------------------------------------------------------
Will only work with sc_push_svc_null!
Only for GCM
--------------------------------------------------------------------
Will only work with sc_push_svc_null!
--------------------------------------------------------------------
====================================================================
====================================================================
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
====================================================================
Lager support
====================================================================
Standard CT variable
====================================================================
General helper functions
====================================================================
--------------------------------------------------------------------
Standard CT variable
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
name
sizeargs
workerargs
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- |
-module(scpf_SUITE).
-include_lib("common_test/include/ct.hrl").
-include("scpf_SUITE.hrl").
-import(scpf_test_support,
[
get_sim_config/2,
get_svc_config/2,
make_sim_notification/2,
multi_store/2,
pv/2,
pv/3,
req_val/2,
start_apnsv3_sim/3,
start_gcm_sim/3
]).
-compile(export_all).
suite() -> [
{timetrap, {seconds, 30}},
{require, sc_push},
{require, gcm_erl},
{require, apns_erlv3},
{require, registrations},
{require, gcm_sim_node},
{require, gcm_sim_config},
{require, apnsv3_sim_node},
{require, apnsv3_sim_config},
{require, lager},
{require, databases},
{require, connect_info}
].
init_per_suite(Config) ->
Sasl = ct:get_config(sasl),
ct:pal("SASL: ~p~n", [Sasl]),
set_all_env(sasl, Sasl),
ensure_started(sasl),
Databases = ct:get_config(databases),
ct:pal("Databases: ~p~n", [Databases]),
ConnectInfo = ct:get_config(connect_info),
ct:pal("connect_info config: ~p~n", [ConnectInfo]),
Cookie = "scpf",
{ApnsV3SimNode, ApnsV3SimCfg} = get_sim_config(apnsv3_sim_config, Config),
{GcmSimNode, GcmSimCfg} = get_sim_config(gcm_sim_config, Config),
ct:log("Starting GCM simulator with config: ~p", [GcmSimCfg]),
{ok, GcmSimStartedApps} = start_gcm_sim(GcmSimNode, GcmSimCfg, Cookie),
ct:log("Starting APNS HTTP/2 simulator with config: ~p", [ApnsV3SimCfg]),
{ok, ApnsSimStartedApps} = start_apnsv3_sim(ApnsV3SimNode, ApnsV3SimCfg,
Cookie),
ct:pal("init_per_suite: Started apns sim apps=~p", [ApnsSimStartedApps]),
Started = start_per_suite_apps(Config),
ct:pal("init_per_suite: Started apps=~p", [Started]),
Registrations = ct:get_config(registrations),
ct:pal("Registrations: ~p", [Registrations]),
multi_store(Config, [{apnsv3_sim_started_apps, ApnsSimStartedApps},
{gcm_sim_started_apps, GcmSimStartedApps},
{suite_started_apps, Started},
{apnsv3_sim_node, ApnsV3SimNode},
{apnsv3_sim_config, ApnsV3SimCfg},
{gcm_sim_node, GcmSimNode},
{gcm_sim_config, GcmSimCfg},
{registrations, Registrations},
{databases, Databases},
{connect_info, ConnectInfo}]
).
end_per_suite(Config) ->
We do n't care about because they are on
Apps = req_val(suite_started_apps, Config),
[application:stop(App) || App <- Apps],
ok.
init_per_group(Group, Config) when Group =:= internal_db;
Group =:= external_db ->
ct:pal("===== Running test group ~p =====", [Group]),
DBMap = req_val(databases, Config),
DBInfo = maps:get(Group, DBMap),
NewConfig = lists:keystore(dbinfo, 1, Config, {dbinfo, DBInfo}),
ok = application:set_env(sc_push_lib, db_pools, db_pools(DBInfo, NewConfig)),
{ok, DbPools} = application:get_env(sc_push_lib, db_pools),
ct:pal("DbPools: ~p", [DbPools]),
case check_db_availability(NewConfig) of
ok ->
NewConfig;
Error ->
Reason = lists:flatten(
io_lib:format("Cannot communicate with ~p,"
" error: ~p", [Group, Error])),
{skip, Reason}
end;
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, _Config) ->
ok.
init_per_testcase(_Case, Config) ->
init_per_testcase_common(Config).
end_per_testcase(_Case, Config) ->
end_per_testcase_common(Config).
groups() ->
[
{service, [], [
{internal_db, [], service_test_groups()},
{external_db, [], service_test_groups()}
]
}
].
service_test_groups() ->
[
send_msg_test,
send_msg_fail_test,
send_msg_no_reg_test
].
all() ->
[
{group, service}
].
send_msg_test(doc) ->
["sc_push:send/1 should send a message to all push services"];
send_msg_test(suite) ->
[];
send_msg_test(Config) ->
RegPLs = req_val(registrations, Config),
SimHdrs = [{"X-GCMSimulator-StatusCode", "200"},
{"X-GCMSimulator-Results", "message_id:1000"}],
ok = sc_push:register_ids(RegPLs),
[
begin
Tag = req_val(tag, RegPL),
Notification = [
{alert, ?ALERT_MSG},
{tag, Tag},
{aps, [{badge, 42}]},
{gcm, [{collapse_key, <<"alert">>}]},
],
ct:pal("Sending notification ~p to ~p", [Notification, Tag]),
Res = sc_push:send(Notification, Opts),
ct:pal("Got result ~p", [Res]),
[{ok, {UUID, Props}}] = Res,
ct:pal("Sent notification to ~p, uuid: ~s, props: ~p",
[Tag, uuid_to_str(UUID), Props])
end || RegPL <- RegPLs
],
deregister_ids(RegPLs),
ok.
send_msg_fail_test(doc) ->
["sc_push:send/1 should fail"];
send_msg_fail_test(suite) ->
[];
send_msg_fail_test(Config) ->
RegPLs = req_val(registrations, Config),
ServiceName = null,
NullRegPL = get_service_properties(ServiceName, RegPLs),
ok = sc_push:register_id(NullRegPL),
Tag = req_val(tag, NullRegPL),
ExpectedError = {error, forced_test_failure},
Notification = [
{alert, ?ALERT_MSG},
{tag, Tag},
],
ct:pal("Sending notification ~p to ~p", [Notification, Tag]),
Res = sc_push:send(Notification),
ct:pal("Got result: ~p", [Res]),
[{error, {_UUID, ExpectedError}}] = Res,
ct:pal("Expected failure sending notification to service ~p, tag ~p",
[ServiceName, Tag]),
deregister_ids(RegPLs),
ok.
send_msg_no_reg_test(doc) ->
["sc_push:send/1 should fail with tag not found"];
send_msg_no_reg_test(suite) ->
[];
send_msg_no_reg_test(Config) ->
RegPLs = req_val(registrations, Config),
ServiceName = null,
NullRegPL = get_service_properties(ServiceName, RegPLs),
ok = sc_push:register_id(NullRegPL),
FakeTag = <<"$$Completely bogus tag$$">>,
ExpectedError = [{reg_not_found_for_tag, FakeTag}],
Notification = [
{alert, ?ALERT_MSG},
{tag, FakeTag}
],
Res = sc_push:send(Notification),
ct:pal("Got result: ~p", [Res]),
[{error, ExpectedError}] = Res,
ct:pal("Got expected error (~p) from send notification", [ExpectedError]),
deregister_ids(RegPLs),
ok.
Internal helper functions
init_per_testcase_common(Config) ->
(catch end_per_testcase_common(Config)),
db_create(Config),
Apps = [sc_push, gcm_erl, apns_erlv3],
AppList = lists:foldl(
fun(App, Acc) ->
set_env(App, get_svc_config(App, Config)),
{ok, L} = application:ensure_all_started(App),
Acc ++ L
end, [], Apps),
multi_store(Config, [{started_apps, AppList}]).
end_per_testcase_common(Config) ->
Apps = lists:reverse(pv(started_apps, Config, [])),
_ = [ok = application:stop(App) || App <- Apps],
db_destroy(Config),
lists:keydelete(started_apps, 1, Config).
set_env(App, FromEnv) ->
[ok = application:set_env(App, K, V) || {K, V} <- FromEnv].
First try to get the app config from Config , failing which get it from
ct : ( ) .
get_env_val(App, Config) ->
case pv(App, Config) of
undefined ->
ct:get_config(App);
Env ->
Env
end.
deregister_ids(RegPLs) ->
[deregister_id(RegPL) || RegPL <- RegPLs].
deregister_id(RegPL) ->
ct:pal("Deregistering ~p", [RegPL]),
Service = req_val(service, RegPL),
Token = req_val(token, RegPL),
ID = sc_push_reg_api:make_id(Service, Token),
ok = sc_push:deregister_ids([ID]),
ct:pal("Deregistered IDs ~p", [ID]).
lager_config(Config, RawLagerConfig) ->
Replacements = [
{error_log_file, filename:join(PrivDir, "error.log")},
{console_log_file, filename:join(PrivDir, "console.log")},
{crash_log_file, filename:join(PrivDir, "crash.log")}
],
replace_template_vars(RawLagerConfig, Replacements).
replace_template_vars(RawLagerConfig, Replacements) ->
Ctx = dict:from_list(Replacements),
Str = lists:flatten(io_lib:fwrite("~1000p~s", [RawLagerConfig, "."])),
SConfig = mustache:render(Str, Ctx),
{ok, Tokens, _} = erl_scan:string(SConfig),
{ok, LagerConfig} = erl_parse:parse_term(Tokens),
LagerConfig.
start_per_suite_apps(Config) ->
Apps = [lager, ssl],
Lager = lager_config(Config, ct:get_config(lager)),
set_env(lager, Lager),
Fun = fun(App, Acc) ->
{ok, L} = application:ensure_all_started(App),
Acc ++ L
end,
StartedApps = lists:foldl(Fun, [], Apps),
lists:usort(StartedApps).
set_mnesia_dir(Config) ->
DataDir = req_val(data_dir, Config),
MnesiaDir = filename:join(DataDir, "db"),
ok = filelib:ensure_dir(MnesiaDir),
ok = application:set_env(mnesia, dir, MnesiaDir).
uuid_to_str(UUID) ->
uuid:uuid_to_string(UUID, binary_standard).
get_service_properties(Service, [_|_]=RegPLs) when is_atom(Service) ->
case [PL || PL <- RegPLs, req_val(service, PL) =:= Service] of
[RegPL] ->
RegPL;
[] ->
ct:fail({cannot_find_service, Service});
L ->
ct:fail({unexpected_response, L})
end.
db_create(Config) ->
DBInfo = req_val(dbinfo, Config),
DB = maps:get(db, DBInfo),
db_create(DB, DBInfo, Config).
db_create(mnesia, _DBInfo, Config) ->
MnesiaDir = filename:join(PrivDir, "mnesia"),
ok = application:set_env(mnesia, dir, MnesiaDir),
db_destroy(mnesia, _DBInfo, Config),
ok = mnesia:create_schema([node()]);
db_create(DB, DBInfo, Config) ->
db_create(mnesia, DBInfo, Config),
clear_external_db(DB, DBInfo, Config).
db_destroy(Config) ->
DBInfo = req_val(dbinfo, Config),
DB = maps:get(db, DBInfo),
db_destroy(DB, DBInfo, Config).
db_destroy(mnesia, _DBInfo, _Config) ->
mnesia:stop(),
ok = mnesia:delete_schema([node()]);
db_destroy(DB, DBInfo, Config) ->
db_destroy(mnesia, DBInfo, Config),
clear_external_db(DB, DBInfo, Config).
clear_external_db(postgres=EDB, _DBInfo, Config) ->
ConnParams = db_conn_params(postgres, Config),
Tables = ["scpf.push_tokens"],
case epgsql:connect(ConnParams) of
{ok, Conn} ->
lists:foreach(
fun(Table) ->
{ok, _} = epgsql:squery(Conn, "delete from " ++ Table)
end, Tables),
ok = epgsql:close(Conn);
Error ->
ct:fail("~p error: ~p", [EDB, Error])
end.
check_db_availability(Config) ->
DBInfo = req_val(dbinfo, Config),
DB = maps:get(db, DBInfo),
check_db_availability(DB, Config).
check_db_availability(mnesia, _Config) ->
ok;
check_db_availability(postgres, Config) ->
ConnParams = db_conn_params(postgres, Config),
try epgsql:connect(ConnParams) of
{ok, Conn} ->
ok = epgsql:close(Conn);
Error ->
Error
catch
_:Reason ->
{error, Reason}
end.
db_pools(#{db := DB, mod := DBMod}, Config) ->
[
{size, 10},
{max_overflow, 20}
],
{db_mod, DBMod},
{db_config, db_config(DB, Config)}
]}
].
db_config(DB, Config) ->
maps:get(DB, req_val(connect_info, Config), []).
db_conn_params(DB, Config) ->
case db_config(DB, Config) of
#{connection := ConnParams} ->
ConnParams;
Val ->
Val
end.
set_all_env(App, Props) ->
lists:foreach(fun({K, V}) ->
ok = application:set_env(App, K, V)
end, Props).
ensure_started(App) ->
case application:start(App) of
ok ->
ok;
{error, {already_started, App}} ->
ok
end.
|