_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 |
|---|---|---|---|---|---|---|---|---|
170fe7d3444f59b7e55996de13997cd330757e0d873e786215cd711a6f3c83f5 | GlideAngle/flare-timing | Task.hs | module Flight.Gap.Validity.Task (TaskValidity(..)) where
import GHC.Generics (Generic)
import Data.Typeable (Typeable, typeOf)
import "newtype" Control.Newtype (Newtype(..))
import Data.Via.Scientific
( DecimalPlaces(..), deriveDecimalPlaces, deriveJsonViaSci, deriveShowViaSci)
| Also called Day Quality .
newtype TaskValidity = TaskValidity Rational
deriving (Eq, Ord, Typeable, Generic)
instance Newtype TaskValidity Rational where
pack = TaskValidity
unpack (TaskValidity a) = a
deriveDecimalPlaces (DecimalPlaces 8) ''TaskValidity
deriveJsonViaSci ''TaskValidity
deriveShowViaSci ''TaskValidity
| null | https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/gap-valid/library/Flight/Gap/Validity/Task.hs | haskell | module Flight.Gap.Validity.Task (TaskValidity(..)) where
import GHC.Generics (Generic)
import Data.Typeable (Typeable, typeOf)
import "newtype" Control.Newtype (Newtype(..))
import Data.Via.Scientific
( DecimalPlaces(..), deriveDecimalPlaces, deriveJsonViaSci, deriveShowViaSci)
| Also called Day Quality .
newtype TaskValidity = TaskValidity Rational
deriving (Eq, Ord, Typeable, Generic)
instance Newtype TaskValidity Rational where
pack = TaskValidity
unpack (TaskValidity a) = a
deriveDecimalPlaces (DecimalPlaces 8) ''TaskValidity
deriveJsonViaSci ''TaskValidity
deriveShowViaSci ''TaskValidity
| |
303d7dece2a12379b5471c9536389585a7b19d854655f9cead9a0e0c9142559d | ertugrulcetin/ClojureNews | login.cljs | (ns controller.login
(:require [ajax.core :as ajax :refer [GET POST PUT]]
[cljc.validation :as validation]
[reagent.core :as r]
[util.view]
[util.controller]
[view.login]))
(declare log-in
sign-up)
(defn handler
[_]
(util.view/change-url "/"))
(defn log-in-page
[]
(util.view/change-page-title "Login")
(r/render-component [(fn []
(view.login/component log-in sign-up))] util.view/main-container))
(defn log-in
[field-ids]
(let [data (util.view/create-field-val-map field-ids)
username (:username data)
password (:password data)]
(cond
(not (validation/username? username))
(util.view/render-error-message "Usernames can only contain ltters, digits and underscores, and should be between 2 and 15 characters long. Please choose another.")
(not (validation/password? password))
(util.view/render-error-message "Passwords should be between 8 and 128 characters long. Please choose another.")
:else
(POST "/login"
{:params data
:handler handler
:error-handler util.controller/error-handler
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})}))))
(defn log-out
[]
(POST "/logout"
{:handler handler
:error-handler util.controller/error-handler
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})}))
(defn sign-up
[field-ids]
(let [data (util.view/create-field-val-map field-ids)
username (:username data)
password (:password data)]
(cond
(not (validation/username? username))
(util.view/render-error-message "Usernames can only contain letters, digits and underscores, and should be between 2 and 15 characters long. Please choose another.")
(not (validation/password? password))
(util.view/render-error-message "Passwords should be between 8 and 128 characters long. Please choose another.")
:else
(PUT "/signup"
{:params data
:handler handler
:error-handler util.controller/error-handler
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})})))) | null | https://raw.githubusercontent.com/ertugrulcetin/ClojureNews/28002f6b620fa4977d561b0cfca0c7f6a635057b/src/cljs/controller/login.cljs | clojure | (ns controller.login
(:require [ajax.core :as ajax :refer [GET POST PUT]]
[cljc.validation :as validation]
[reagent.core :as r]
[util.view]
[util.controller]
[view.login]))
(declare log-in
sign-up)
(defn handler
[_]
(util.view/change-url "/"))
(defn log-in-page
[]
(util.view/change-page-title "Login")
(r/render-component [(fn []
(view.login/component log-in sign-up))] util.view/main-container))
(defn log-in
[field-ids]
(let [data (util.view/create-field-val-map field-ids)
username (:username data)
password (:password data)]
(cond
(not (validation/username? username))
(util.view/render-error-message "Usernames can only contain ltters, digits and underscores, and should be between 2 and 15 characters long. Please choose another.")
(not (validation/password? password))
(util.view/render-error-message "Passwords should be between 8 and 128 characters long. Please choose another.")
:else
(POST "/login"
{:params data
:handler handler
:error-handler util.controller/error-handler
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})}))))
(defn log-out
[]
(POST "/logout"
{:handler handler
:error-handler util.controller/error-handler
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})}))
(defn sign-up
[field-ids]
(let [data (util.view/create-field-val-map field-ids)
username (:username data)
password (:password data)]
(cond
(not (validation/username? username))
(util.view/render-error-message "Usernames can only contain letters, digits and underscores, and should be between 2 and 15 characters long. Please choose another.")
(not (validation/password? password))
(util.view/render-error-message "Passwords should be between 8 and 128 characters long. Please choose another.")
:else
(PUT "/signup"
{:params data
:handler handler
:error-handler util.controller/error-handler
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})})))) | |
9adb008835892c3142f68af281d68da339fc61fe47d255592819e1a8cbc0be14 | jxv/dino-rush | Sfx.hs | module DinoRush.Engine.Sfx where
data Sfx
= Sfx'Jump
| Sfx'Point
| Sfx'Duck
| Sfx'Bird
| Sfx'Hurt
| Sfx'Lava
| Sfx'Quake
| Sfx'Rock
| Sfx'Recover
| Sfx'Stock
deriving (Show, Eq)
| null | https://raw.githubusercontent.com/jxv/dino-rush/f888bc05fe734ced2c49bec81f9c804b47c81069/library/DinoRush/Engine/Sfx.hs | haskell | module DinoRush.Engine.Sfx where
data Sfx
= Sfx'Jump
| Sfx'Point
| Sfx'Duck
| Sfx'Bird
| Sfx'Hurt
| Sfx'Lava
| Sfx'Quake
| Sfx'Rock
| Sfx'Recover
| Sfx'Stock
deriving (Show, Eq)
| |
23d00336a4ffc5e4205fbd72b6c5fef88519b4b8f1828c13c764a4e0de940b64 | pveber/bistro | idr.ml | open Bistro
open Bistro.Shell_dsl
type 'a format = NarrowPeak | BroadPeak | Bed | Gff
let narrowPeak = NarrowPeak
let broadPeak = BroadPeak
let bed = Bed
let gff = Gff
type 'a output = [`idr_output of 'a]
let string_of_file_format = function
| NarrowPeak -> "narrowPeak"
| BroadPeak -> "broadPeak"
| Bed -> "bed"
| Gff -> "gff"
let file_format x = string (string_of_file_format x)
let string_of_merge_method = function
| `sum -> "sum"
| `avg -> "avg"
| `min -> "min"
| `max -> "max"
let merge_method x = string (string_of_merge_method x)
let token_of_rank r =
string (
match r with
| `signal -> "signal.value"
| `pvalue -> "p.value"
| `qvalue -> "q.value"
)
let img = [ docker_image ~account:"pveber" ~name:"idr" ~tag:"2.0.3" () ]
let idr
~input_file_type ?idr_threshold ?soft_idr_threshold
?peak_merge_method ?rank ?random_seed ?peak_list
sample1 sample2 =
Workflow.shell ~descr:"Idr.idr" ~img [
mkdir_p dest ;
cmd "idr" [
opt "--input-file-type" file_format input_file_type ;
opt "--output-file" (fun x -> x) (dest // "items.tsv") ;
option (opt "--idr-threshold" float) idr_threshold ;
option (opt "--soft-idr-threshold" float) soft_idr_threshold ;
option (opt "--peak-merge-method" merge_method) peak_merge_method ;
option (opt "--rank" token_of_rank) rank ;
option (opt "--random-seed" int) random_seed ;
option (opt "--peak-list" dep) peak_list ;
string "--plot" ;
opt "--samples" (list ~sep:" " dep) [ sample1 ; sample2 ] ;
]
]
let items x = Workflow.select x [ "items.tsv" ]
let figure x = Workflow.select x [ "items.tsv.png" ]
| null | https://raw.githubusercontent.com/pveber/bistro/da0ebc969c8c5ca091905366875cbf8366622280/lib/bio/idr.ml | ocaml | open Bistro
open Bistro.Shell_dsl
type 'a format = NarrowPeak | BroadPeak | Bed | Gff
let narrowPeak = NarrowPeak
let broadPeak = BroadPeak
let bed = Bed
let gff = Gff
type 'a output = [`idr_output of 'a]
let string_of_file_format = function
| NarrowPeak -> "narrowPeak"
| BroadPeak -> "broadPeak"
| Bed -> "bed"
| Gff -> "gff"
let file_format x = string (string_of_file_format x)
let string_of_merge_method = function
| `sum -> "sum"
| `avg -> "avg"
| `min -> "min"
| `max -> "max"
let merge_method x = string (string_of_merge_method x)
let token_of_rank r =
string (
match r with
| `signal -> "signal.value"
| `pvalue -> "p.value"
| `qvalue -> "q.value"
)
let img = [ docker_image ~account:"pveber" ~name:"idr" ~tag:"2.0.3" () ]
let idr
~input_file_type ?idr_threshold ?soft_idr_threshold
?peak_merge_method ?rank ?random_seed ?peak_list
sample1 sample2 =
Workflow.shell ~descr:"Idr.idr" ~img [
mkdir_p dest ;
cmd "idr" [
opt "--input-file-type" file_format input_file_type ;
opt "--output-file" (fun x -> x) (dest // "items.tsv") ;
option (opt "--idr-threshold" float) idr_threshold ;
option (opt "--soft-idr-threshold" float) soft_idr_threshold ;
option (opt "--peak-merge-method" merge_method) peak_merge_method ;
option (opt "--rank" token_of_rank) rank ;
option (opt "--random-seed" int) random_seed ;
option (opt "--peak-list" dep) peak_list ;
string "--plot" ;
opt "--samples" (list ~sep:" " dep) [ sample1 ; sample2 ] ;
]
]
let items x = Workflow.select x [ "items.tsv" ]
let figure x = Workflow.select x [ "items.tsv.png" ]
| |
be2dc05b288ba15f3c8caeab4b56cb77874bb1442d91616a476689816d38d6b2 | pzque/realword-haskell | Prettify.hs | module Prettify where
import Data.Bits (shiftR, (.&.))
import Data.Char (ord)
import Numeric (showHex)
import SimpleJSON
data Doc
= Empty
| Char Char
| Symbol Char
| Text String
| Line
| Concat Doc
Doc
| Union Doc
Doc
deriving (Show, Eq)
-------------------------------------------
-- constructors
-------------------------------------------
empty :: Doc
empty = Empty
char :: Char -> Doc
char c = Char c
symbol :: Char -> Doc
symbol ',' = Symbol ','
symbol ':' = Symbol ':'
symbol '[' = Symbol '['
symbol ']' = Symbol ']'
symbol '{' = Symbol '{'
symbol '}' = Symbol '}'
symbol '"' = Symbol '"'
symbol '\'' = Symbol '\''
symbol ' ' = Symbol ' '
symbol '\n' = Symbol '\n'
text :: String -> Doc
text "" = Empty
text s = Text s
-- |construct Doc form double
1 - > Text 1
double :: Double -> Doc
double d = text (show d)
-- |construct a string literal Doc from a string
eg : " z\n " - > " \"z\\n\ " "
-- 将 oneChar 函数应用于字符串的每一个字符,然后把拼接起来的结果放入引号中。
string :: String -> Doc
string = enclose '"' '"' . hcat . map oneChar
-- |把一个 Doc 值用起始字符和终止字符包起来
-- eg:
enclose ' [ ' ' ] ' ( Text " 1 " ) - > Concat ( Concat ( ' [ ' ) ( Text " 1 " ) ) ( ' ] ' )
enclose :: Char -> Char -> Doc -> Doc
enclose left right x = symbol left <> x <> symbol right
值拼接成一个,类似列表中的 concat 函数
-- eg:
-- d=Text "a"; hcat [d,d,d] -> Concat (Text "a") (Concat (Text "a") (Text "a"))
hcat :: [Doc] -> Doc
hcat = fold (<>)
-- |连接两个doc为一个
text " < > text " peng " - > Concat ( Text " zhang " ) ( Text " " )
(<>) :: Doc -> Doc -> Doc
Empty <> y = y
x <> Empty = x
x <> y = x `Concat` y
-- |fold function f on a Doc list
fold
:: (Doc -> Doc -> Doc) -- ^ f
-> [Doc] -- ^Doc list
-> Doc
fold f = foldr f empty
-- |转义一个字符
-- 可见的ascii直接输出,例如:'c -> Char 'c'
-- 不可见的ascii和unicode要进行转义,如:
-- '字' -> Concat (Text "\\u") (Text "5b57")
' \31 ' - > Concat ( Concat ( Text " \\u " ) ( Text " 00 " ) ) ( Text " 1f " )
oneChar :: Char -> Doc
oneChar c =
case lookup c simpleEscapes of
Just r -> text r
Nothing
| mustEscape c -> hexEscape c
| otherwise -> char c
where
mustEscape c = c < ' ' || c == '\x7f' || c > '\xff'
-- |转义字符对应表
-- [('\b',"\\b"),('\n',"\\n"),('\f',"\\f"),('\r',"\\r"),('\t',"\\t"),('\\',"\\\\"),('"',"\\\""),('/',"\\/")]
simpleEscapes :: [(Char, String)]
simpleEscapes = zipWith ch "\b\n\f\r\t\\\"/" "bnfrt\\\"/"
where
ch a b = (a, ['\\', b])
-- |将一个unicode字符转义为Doc
-- eg
-- '字' -> Concat (Text "\\u") (Text "5b57")
hexEscape :: Char -> Doc
hexEscape c
| d < 0x10000 = smallHex d
| otherwise = astral (d - 0x10000)
where
d = ord c
smallHex :: Int -> Doc
smallHex x = text "\\u" <> text (replicate (4 - length h) '0') <> text h
where
h = showHex x ""
astral :: Int -> Doc
astral n = smallHex (a + 0xd800) <> smallHex (b + 0xdc00)
where
a = (n `shiftR` 10) .&. 0x3ff
b = n .&. 0x3ff
-- |l硬换行
line :: Doc
line = Line
-- | 批量列表转换,接受起始符open,终止符close,函数f,列表l
-- 首先执行 map f l,即对列表的每个元素执行函数f,将每个元素转为Doc,得到[d:Doc]
-- 然后执行 punctuate (char ',') [d:Doc],将其使用逗号分隔得到[d1:Doc]
-- 然后执行 fsep [d1:Doc] 对列表使用软换行分隔并且连接成一个Doc,得到 d2
-- 然后调用enclose给d2加上首尾(open和close)
series
^ open 起始符
^ close 终止符
-> (a -> Doc) -- ^ f 函数
-> [a] -- ^ a类型的列表
-> Doc -- ^ 返回值
series open close f = enclose open close . fsep . punctuate (symbol ',') . map f
punctuate :: Doc -> [Doc] -> [Doc]
punctuate p [] = []
punctuate p [d] = [d]
punctuate p (d:ds) = (d <> p) : punctuate p ds
|将一个Doc list内的全部元素用软换行连接
fsep :: [Doc] -> Doc
fsep = fold (</>)
-- |将两个Doc用软换行连接
(</>) :: Doc -> Doc -> Doc
x </> y = x <> softline <> y
-- |软换行,一行放不下的时候
如果当前行变得太长,softline
这该怎么实现呢 ? 答案是每次碰到这种情况,我们使用 Union 构造器来用两种不同的方式保存文档 。
softline :: Doc
softline = group line
group :: Doc -> Doc
group x = flatten x `Union` x
flatten :: Doc -> Doc
flatten (x `Concat` y) = flatten x `Concat` flatten y
flatten Line = symbol ' '
flatten (x `Union` _) = flatten x
flatten other = other
| null | https://raw.githubusercontent.com/pzque/realword-haskell/1da0188a3293fd417740fe12167eebccef4ba626/modules/ch5/Prettify.hs | haskell | -----------------------------------------
constructors
-----------------------------------------
|construct Doc form double
|construct a string literal Doc from a string
将 oneChar 函数应用于字符串的每一个字符,然后把拼接起来的结果放入引号中。
|把一个 Doc 值用起始字符和终止字符包起来
eg:
eg:
d=Text "a"; hcat [d,d,d] -> Concat (Text "a") (Concat (Text "a") (Text "a"))
|连接两个doc为一个
|fold function f on a Doc list
^ f
^Doc list
|转义一个字符
可见的ascii直接输出,例如:'c -> Char 'c'
不可见的ascii和unicode要进行转义,如:
'字' -> Concat (Text "\\u") (Text "5b57")
|转义字符对应表
[('\b',"\\b"),('\n',"\\n"),('\f',"\\f"),('\r',"\\r"),('\t',"\\t"),('\\',"\\\\"),('"',"\\\""),('/',"\\/")]
|将一个unicode字符转义为Doc
eg
'字' -> Concat (Text "\\u") (Text "5b57")
|l硬换行
| 批量列表转换,接受起始符open,终止符close,函数f,列表l
首先执行 map f l,即对列表的每个元素执行函数f,将每个元素转为Doc,得到[d:Doc]
然后执行 punctuate (char ',') [d:Doc],将其使用逗号分隔得到[d1:Doc]
然后执行 fsep [d1:Doc] 对列表使用软换行分隔并且连接成一个Doc,得到 d2
然后调用enclose给d2加上首尾(open和close)
^ f 函数
^ a类型的列表
^ 返回值
|将两个Doc用软换行连接
|软换行,一行放不下的时候 | module Prettify where
import Data.Bits (shiftR, (.&.))
import Data.Char (ord)
import Numeric (showHex)
import SimpleJSON
data Doc
= Empty
| Char Char
| Symbol Char
| Text String
| Line
| Concat Doc
Doc
| Union Doc
Doc
deriving (Show, Eq)
empty :: Doc
empty = Empty
char :: Char -> Doc
char c = Char c
symbol :: Char -> Doc
symbol ',' = Symbol ','
symbol ':' = Symbol ':'
symbol '[' = Symbol '['
symbol ']' = Symbol ']'
symbol '{' = Symbol '{'
symbol '}' = Symbol '}'
symbol '"' = Symbol '"'
symbol '\'' = Symbol '\''
symbol ' ' = Symbol ' '
symbol '\n' = Symbol '\n'
text :: String -> Doc
text "" = Empty
text s = Text s
1 - > Text 1
double :: Double -> Doc
double d = text (show d)
eg : " z\n " - > " \"z\\n\ " "
string :: String -> Doc
string = enclose '"' '"' . hcat . map oneChar
enclose ' [ ' ' ] ' ( Text " 1 " ) - > Concat ( Concat ( ' [ ' ) ( Text " 1 " ) ) ( ' ] ' )
enclose :: Char -> Char -> Doc -> Doc
enclose left right x = symbol left <> x <> symbol right
值拼接成一个,类似列表中的 concat 函数
hcat :: [Doc] -> Doc
hcat = fold (<>)
text " < > text " peng " - > Concat ( Text " zhang " ) ( Text " " )
(<>) :: Doc -> Doc -> Doc
Empty <> y = y
x <> Empty = x
x <> y = x `Concat` y
fold
-> Doc
fold f = foldr f empty
' \31 ' - > Concat ( Concat ( Text " \\u " ) ( Text " 00 " ) ) ( Text " 1f " )
oneChar :: Char -> Doc
oneChar c =
case lookup c simpleEscapes of
Just r -> text r
Nothing
| mustEscape c -> hexEscape c
| otherwise -> char c
where
mustEscape c = c < ' ' || c == '\x7f' || c > '\xff'
simpleEscapes :: [(Char, String)]
simpleEscapes = zipWith ch "\b\n\f\r\t\\\"/" "bnfrt\\\"/"
where
ch a b = (a, ['\\', b])
hexEscape :: Char -> Doc
hexEscape c
| d < 0x10000 = smallHex d
| otherwise = astral (d - 0x10000)
where
d = ord c
smallHex :: Int -> Doc
smallHex x = text "\\u" <> text (replicate (4 - length h) '0') <> text h
where
h = showHex x ""
astral :: Int -> Doc
astral n = smallHex (a + 0xd800) <> smallHex (b + 0xdc00)
where
a = (n `shiftR` 10) .&. 0x3ff
b = n .&. 0x3ff
line :: Doc
line = Line
series
^ open 起始符
^ close 终止符
series open close f = enclose open close . fsep . punctuate (symbol ',') . map f
punctuate :: Doc -> [Doc] -> [Doc]
punctuate p [] = []
punctuate p [d] = [d]
punctuate p (d:ds) = (d <> p) : punctuate p ds
|将一个Doc list内的全部元素用软换行连接
fsep :: [Doc] -> Doc
fsep = fold (</>)
(</>) :: Doc -> Doc -> Doc
x </> y = x <> softline <> y
如果当前行变得太长,softline
这该怎么实现呢 ? 答案是每次碰到这种情况,我们使用 Union 构造器来用两种不同的方式保存文档 。
softline :: Doc
softline = group line
group :: Doc -> Doc
group x = flatten x `Union` x
flatten :: Doc -> Doc
flatten (x `Concat` y) = flatten x `Concat` flatten y
flatten Line = symbol ' '
flatten (x `Union` _) = flatten x
flatten other = other
|
0cf8ca76313290acda4c753ba5ef34aecc0d02a32db3ee1a62a7ca30ee199113 | nyu-acsys/drift | abstractTransformer.ml | open AbstractDomain
open Syntax
open SemanticDomain
open SemanticsDomain
open SensitiveDomain
open SenSemantics
open Printer
open Util
open Config
* * c[M ] is a single base refinement type that pulls in all the environment dependencies from M
M = n1 |- > { v : int | v > = 2 } , n2 |- > z:{v : int | v > = 0 } - > { v : int | v = z } , n3 |- > { v : bool | v = true }
c[M ] = { v : int | v = c & & n1 > = 2 }
* * t[M ]
t ' = { v : int | v = 2 }
x in scope and M^t[x ] = { v : bool | v = true }
the scope of t is the set of all nodes in the range ( i.e. codomain ) of the environment component of n.
t'[M^t ] = { v : int | v = 2 & & x = true }
* * True False
Using v = 1 be true once inside vt and v = 1 be false inside vf
** c[M] is a single base refinement type that pulls in all the environment dependencies from M
M = n1 |-> {v: int | v >= 2}, n2 |-> z:{v: int | v >= 0} -> {v: int | v = z}, n3 |-> {v: bool | v = true}
c[M] = {v: int | v = c && n1 >= 2}
** t[M]
t' = {v:int | v = 2}
x in scope and M^t[x] = {v: bool | v = true}
the scope of t is the set of all nodes in the range (i.e. codomain) of the environment component of n.
t'[M^t] = {v: int | v = 2 && x = true}
** True False
Using v = 1 be true once inside vt and v = 1 be false inside vf
*)
type stage_t =
| Widening
| Narrowing
module AssertionPosMap = Map.Make(struct
type t = Syntax.pos
let compare = compare
end)
type asst_map_t = (int * int) AssertionPosMap.t
let sens : asst_map_t ref = ref AssertionPosMap.empty
let env0, m0 =
let enva, ma = array_M VarMap.empty (NodeMap.create 500) in
let envb, mb = list_M enva ma in
envb, mb
(* Create a fresh variable name *)
let fresh_z= fresh_func "z"
let arrow_V x1 x2 = measure_call "arrow_V" (arrow_V x1 x2)
let forget_V x = measure_call "forget_V" (forget_V x)
let stren_V x = measure_call "stren_V" (stren_V x)
let join_V e = measure_call "join_V" (join_V e)
let meet_V e = measure_call "meet_V" (meet_V e)
let equal_V e = measure_call "equal_V" (equal_V e)
let proj_V e = measure_call "proj_V" (proj_V e)
let sat_equal_V e = measure_call "sat_equal_V" (sat_equal_V e)
let rec prop (v1: value_t) (v2: value_t): (value_t * value_t) = match v1, v2 with
| Top, Bot | Table _, Top -> Top, Top
| Table t, Bot ->
let t' = init_T (dx_T v1) in
v1, Table t'
| Relation r1, Relation r2 ->
if leq_R r1 r2 then v1, v2 else
Relation r1, Relation (join_R r1 r2)
| Table t1, Table t2 ->
let prop_table_entry cs (v1i, v1o) (v2i, v2o) =
let _, z = cs in
let v1ot, v2ip =
if (is_Array v1i && is_Array v2i) || (is_List v1i && is_List v2i) then
let l1 = get_len_var_V v1i in
let e1 = get_item_var_V v1i in
let l2 = get_len_var_V v2i in
let e2 = get_item_var_V v2i in
let v = replace_V v1o l1 l2 in
replace_V v e1 e2, (forget_V l1 v2i |> forget_V e1)
else v1o, v2i
in
let v1i', v2i', v1o', v2o' =
let opt_i = false
Optimization 1 : If those two are the same , ignore the prop step
|| (v1i <> Bot && v2i <> Bot && eq_V v2i v1i) in
let v2i', v1i' =
if opt_i then v2i, v1i else
prop v2i v1i
in
let opt_o = false
Optimization 2 : If those two are the same , ignore the prop step
|| (v2o <> Bot && v1o <> Bot && eq_V v1ot v2o)
in
let v1o', v2o' =
if opt_o then v1ot, v2o else
prop (arrow_V z v1ot v2ip) (arrow_V z v2o v2ip)
in
let v1o' =
if (is_Array v1i' && is_Array v2i') || (is_List v1i' && is_List v2i') then
let l1 = get_len_var_V v1i' in
let e1 = get_item_var_V v1i' in
let l2 = get_len_var_V v2i' in
let e2 = get_item_var_V v2i' in
let v = replace_V v1o' l2 l1 in
replace_V v e2 e1
else v1o'
in
if true then
begin
( if true then
begin
" \n<=== prop o = = = > % s\n " z ;
pr_value Format.std_formatter v1ot ;
" " ;
" \n<--- v2i --->\n " ;
pr_value Format.std_formatter v2i ;
" \n " ;
pr_value Format.std_formatter v2ip ;
" \n " ;
pr_value Format.std_formatter ( arrow_V z v1ot v2ip ) ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter ( arrow_V z v2o v2ip ) ;
" " ;
end
) ;
( if true then
begin
" \n<=== res = = = > % s\n " z ;
pr_value Format.std_formatter v1o ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter v2o ' ;
" " ;
end
) ;
end ;
begin
(if true then
begin
Format.printf "\n<=== prop o ===>%s\n" z;
pr_value Format.std_formatter v1ot;
Format.printf "\n";
Format.printf "\n<--- v2i --->\n";
pr_value Format.std_formatter v2i;
Format.printf "\n";
pr_value Format.std_formatter v2ip;
Format.printf "\n";
pr_value Format.std_formatter (arrow_V z v1ot v2ip);
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter (arrow_V z v2o v2ip);
Format.printf "\n";
end
);
(if true then
begin
Format.printf "\n<=== res ===>%s\n" z;
pr_value Format.std_formatter v1o';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter v2o';
Format.printf "\n";
end
);
end; *)
let v1o', v2o' =
if opt_o then v1o', v2o' else (join_V v1o v1o', join_V v2o v2o')
in
v1i', v2i', v1o', v2o'
in
(v1i', v1o'), (v2i', v2o')
in
let t1', t2' =
prop_table prop_table_entry alpha_rename_V t1 t2
in
Table t1', Table t2'
| Ary ary1, Ary ary2 -> let ary1', ary2' = alpha_rename_Arys ary1 ary2 in
let ary' = (join_Ary ary1' ary2') in
let _, ary2'' = alpha_rename_Arys ary2 ary' in
(* let _ = alpha_rename_Arys ary1 ary' in *)
Ary ary1, Ary ary2''
| Lst lst1, Lst lst2 ->
( if true then
begin
" \n<=== prop list = = = > \n " ;
pr_value Format.std_formatter ( ) ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter ( Lst lst2 ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== prop list ===>\n";
pr_value Format.std_formatter (Lst lst1);
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter (Lst lst2);
Format.printf "\n";
end
); *)
let lst1', lst2' = alpha_rename_Lsts lst1 lst2 in
( if true then
begin
" \n<=== after rename list = = = > \n " ;
pr_value Format.std_formatter ( ) ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter ( Lst lst2 ' ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== after rename list ===>\n";
pr_value Format.std_formatter (Lst lst1');
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter (Lst lst2');
Format.printf "\n";
end
); *)
let lst1'', lst2'' = prop_Lst prop lst1' lst2' in
( if true then
begin
" \n<=== res = = = > \n " ;
pr_value Format.std_formatter ( ) ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter ( Lst lst2 '' ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== res ===>\n";
pr_value Format.std_formatter (Lst lst1'');
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter (Lst lst2'');
Format.printf "\n";
end
); *)
let _, lst2'' = alpha_rename_Lsts lst2 lst2'' in
Lst lst1'', Lst lst2''
| Ary ary, Bot -> let vars, r = ary in
let ary' = init_Ary vars in
v1, Ary ary'
| Lst lst, Bot -> let vars, r = lst in
let lst' = init_Lst vars in
v1, Lst lst'
| Tuple u, Bot -> let u' = List.init (List.length u) (fun _ ->
Bot) in
v1, Tuple u'
| Tuple u1, Tuple u2 -> if List.length u1 <> List.length u2 then
raise (Invalid_argument "Prop tuples should have the same form")
else
let u1', u2' = List.fold_right2 (fun v1 v2 (u1', u2') ->
let v1', v2' = prop v1 v2 in
(v1'::u1', v2'::u2')
) u1 u2 ([],[]) in
Tuple u1', Tuple u2'
| _, _ -> if leq_V v1 v2 then v1, v2 else v1, join_V v1 v2
let prop p = measure_call "prop" (prop p)
(* let lc_env env1 env2 =
Array.fold_left (fun a id -> if Array.mem id a then a else Array.append a [|id|] ) env2 env1 *)
let rec nav ( v1 : value_t ) ( v2 : value_t ): ( value_t * value_t ) = match v1 , v2 with
| Relation r1 , Relation r2 - >
let r2 ' = if leq_R r1 r2 then r1 else r2
in
Relation r1 , Relation r2 '
| Ary ary1 , let ary1 ' , ary2 ' = alpha_rename_Arys ary1 ary2 in
let _ , ary2 '' = alpha_rename_Arys ary2 ( ary1 ' ary2 ' ) in
Ary ary1 , Ary ary2 ''
| Table t1 , Table t2 - >
let t1 ' , t2 ' = alpha_rename t1 t2 in
let ( z1 , v1i , v1o ) = t1 ' and ( z2 , v2i , v2o ) = t2 ' in
let v1ot =
if is_Array v1i & & is_Array v2i then
let l1 = get_len_var_V v1i in
let l2 = get_len_var_V v2i in
replace_V v1o l1 l2
else v1o
in
let p1 , p2 =
let v1i ' , v2i ' , v1o ' , v2o ' =
let v2i ' , v1i ' = nav v2i v1i in
let v1o ' , v2o ' = nav ( arrow_V z1 v1ot v2i ) ( arrow_V z1 v2o v2i ) in
let v1o ' , v2o ' = match leq_V v1o ' v1ot , v2o ' v2o with
| false , false - > v1ot , v2o
| true , false - > v1o ' , v2o
| false , true - > v1ot , v2o '
| true , true - > v1o ' , v2o '
in
let v1o ' =
if is_Array v1i ' & & is_Array v2i ' then
let l1 = get_len_var_V v1i ' in
let l2 = get_len_var_V v2i ' in
replace_V v1o ' l2 l1
else v1o '
in
v1i ' , v2i ' , v1o ' , v2o '
in
( v1i ' , v1o ' ) , ( v2i ' , v2o ' )
in
let t1 '' = ( z1 , fst p1 , snd p1 ) and t2 '' = ( z2 , fst p2 , snd p2 ) in
Table t1 '' , Table t2 ''
| _ , _ - > v1 , v2
| Relation r1, Relation r2 ->
let r2' = if leq_R r1 r2 then r1 else r2
in
Relation r1, Relation r2'
| Ary ary1, Ary ary2 -> let ary1', ary2' = alpha_rename_Arys ary1 ary2 in
let _, ary2'' = alpha_rename_Arys ary2 (join_Ary ary1' ary2') in
Ary ary1, Ary ary2''
| Table t1, Table t2 ->
let t1', t2' = alpha_rename t1 t2 in
let (z1, v1i, v1o) = t1' and (z2, v2i, v2o) = t2' in
let v1ot =
if is_Array v1i && is_Array v2i then
let l1 = get_len_var_V v1i in
let l2 = get_len_var_V v2i in
replace_V v1o l1 l2
else v1o
in
let p1, p2 =
let v1i', v2i', v1o', v2o' =
let v2i', v1i' = nav v2i v1i in
let v1o', v2o' = nav (arrow_V z1 v1ot v2i) (arrow_V z1 v2o v2i) in
let v1o', v2o' = match leq_V v1o' v1ot, leq_V v2o' v2o with
| false, false -> v1ot, v2o
| true, false -> v1o', v2o
| false, true -> v1ot, v2o'
| true, true -> v1o', v2o'
in
let v1o' =
if is_Array v1i' && is_Array v2i' then
let l1 = get_len_var_V v1i' in
let l2 = get_len_var_V v2i' in
replace_V v1o' l2 l1
else v1o'
in
v1i', v2i', v1o', v2o'
in
(v1i', v1o'), (v2i', v2o')
in
let t1'' = (z1, fst p1, snd p1) and t2'' = (z2, fst p2, snd p2) in
Table t1'', Table t2''
| _, _ -> v1, v2 *)
let get_env_list (env: env_t) (sx: var) (m: exec_map_t) =
let find n m = NodeMap.find_opt n m |> Opt.get_or_else Bot in
let env_l = VarMap.bindings env in
let helper lst (x, (n, _)) =
let n = construct_snode sx n in
let t = find n m in
let lst' = if is_List t then
(get_item_var_V t) :: (get_len_var_V t) :: lst
else lst
in
x :: lst'
in
List.fold_left helper [] env_l
let get_env_list e sx = measure_call "get_env_list" (get_env_list e sx)
let prop_scope (env1: env_t) (env2: env_t) (sx: var) (m: exec_map_t) (v1: value_t) (v2: value_t): (value_t * value_t) =
let env1 = get_env_list env1 sx m in
let env2 = get_env_list env2 sx m in
(* let v1'',_ = prop v1 (proj_V v2 env1)in
let _, v2'' = prop (proj_V v1 env2) v2 in *)
let v1', v2' = prop v1 v2 in
let v1'' = proj_V v1' env1 in
let v2'' = proj_V v2' env2 in
v1'', v2''
let prop_scope x1 x2 x3 x4 x5 = measure_call "prop_scope" (prop_scope x1 x2 x3 x4 x5)
(** Reset the array nodes **)
let reset (m:exec_map_t): exec_map_t = NodeMap.fold (fun n t m ->
m |> NodeMap.add n t
) m0 m
(* let iterUpdate m v l = NodeMap.map (fun x -> arrow_V l x v) m *)
(* let getVars env = VarMap.fold (fun var n lst -> var :: lst) env [] *)
let iterEnv_c env m c = VarMap.fold ( fun var n a - >
let v = NodeMap.find_opt n m | > Opt.get_or_else Top in
let EN ( env ' , l ) = n in
let in
c_V a v lb ) env ( init_V_c c )
let iterEnv_v env m v = VarMap.fold ( fun var n a - >
let ai = NodeMap.find_opt n m | > Opt.get_or_else Top in
arrow_V var a ai ) env v
let v = NodeMap.find_opt n m |> Opt.get_or_else Top in
let EN (env', l) = n in
let lb = name_of_node l in
c_V a v lb) env (init_V_c c)
let iterEnv_v env m v = VarMap.fold (fun var n a ->
let ai = NodeMap.find_opt n m |> Opt.get_or_else Top in
arrow_V var a ai) env v *)
(* let optmization m n find = (* Not sound for work *)
if !st <= 6000 then false else
let t = find n m in
let pre_t = find n !pre_m in
opt_eq_V pre_t t *)
let rec list_var_item eis sx (cs: (var * loc)) m env nlst left_or_right lst_len =
let find n m = NodeMap.find_opt n m |> Opt.get_or_else Bot in
let vlst = find nlst m in
match eis, left_or_right with
| Var (x, l), true ->
let n = construct_vnode env l cs in
let env1 = env |> VarMap.add x (n, false) in
let n = construct_snode sx n in
let t = find n m in
let tp = cons_temp_lst_V t vlst in
( if ! debug then
begin
Format.printf " \n<---Pattern var--- > % s\n " l ;
pr_value Format.std_formatter vlst ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t ;
pr_value Format.std_formatter tp ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<---Pattern var---> %s\n" l;
pr_value Format.std_formatter vlst;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t;
pr_value Format.std_formatter tp;
Format.printf "\n";
end
); *)
let vlst', tp' = prop vlst tp in
let t' = extrac_item_V (get_env_list env1 sx m) tp' in
( if ! debug then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter vlst ' ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t ' ;
Format.printf " " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter vlst';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
let m' = m |> NodeMap.add n t' |> NodeMap.add nlst vlst' in
m', env1
| Var(x, l), false ->
let n = construct_vnode env l cs in
let env1 = env |> VarMap.add x (n, false) in
let n = construct_snode sx n in
let lst = find n m |> get_list_length_item_V in
let t_new = reduce_len_V lst_len lst vlst in
let _, t' = prop t_new (find n m) in
let m' = NodeMap.add n t' m in
m', env1
| Const (c, l), false ->
let n = construct_enode env l |> construct_snode sx in
let t_new = pattern_empty_lst_V vlst in
let _, t' = prop t_new (find n m) in
let m' = NodeMap.add n t' m in
m', env
| TupleLst (termlst, l), true ->
let n = construct_enode env l |> construct_snode sx in
let t =
let raw_t = find n m in
if is_tuple_V raw_t then raw_t
else
let u' = List.init (List.length termlst) (fun _ ->
Bot) in Tuple u' in
( if ! debug then
begin
Format.printf " \n<---Pattern tuple--- > % s\n " l ;
pr_value Format.std_formatter vlst ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<---Pattern tuple---> %s\n" l;
pr_value Format.std_formatter vlst;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t;
Format.printf "\n";
end
); *)
let tlst = get_tuple_list_V t in
let tllst = extrac_item_V (get_env_list env sx m) vlst |> get_tuple_list_V in
let env', m', tlst', tllst' = List.fold_left2 (fun (env, m, li, llst) e (ti, tlsti) ->
match e with
| Var (x, l') ->
let nx = construct_vnode env l' cs in
let env1 = env |> VarMap.add x (nx, false) in
let nx = construct_snode sx nx in
let tx = find nx m in
let ti', tx' = prop ti tx in
let tlsti', ti'' = prop tlsti ti in
let m' = m |> NodeMap.add nx tx' in
env1, m', (join_V ti' ti'') :: li, tlsti' :: llst
| _ -> raise (Invalid_argument "Tuple only for variables now")
) (env, m, [], []) termlst (zip_list tlst tllst) in
let tlst', tllst' = List.rev tlst', List.rev tllst' in
let t', vlst' = Tuple tlst', (cons_temp_lst_V (Tuple tllst') vlst) in
let m'' = m' |> NodeMap. add n t'
|> NodeMap.add nlst vlst' in
( if ! debug then
begin
Format.printf " \nRES for tuple:\n " ;
pr_value Format.std_formatter vlst ' ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t ' ;
Format.printf " " ;
end
) ;
begin
Format.printf "\nRES for tuple:\n";
pr_value Format.std_formatter vlst';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
m'', env'
| BinOp (bop, e1, e2, l), _ ->
let m', env' = list_var_item e1 sx cs m env nlst true 0 in
let m'', env'' = list_var_item e2 sx cs m' env' nlst false (lst_len + 1) in
m'', env''
| UnOp (uop, e1, l), true ->
let m', env' = list_var_item e1 sx cs m env nlst true 0 in
m', env'
| _ -> raise (Invalid_argument "Pattern should only be either constant, variable, and list cons")
let prop_predef l v0 v =
let l = l |> name_of_node in
let rec alpha_rename v0 v =
match v0, v with
| Table t0, Table t ->
if table_isempty t || table_isempty t0 then Table t else
let (var0, z0), (vi0, vo0) = get_full_table_T t0 in
let (var, z), (vi, vo) = get_full_table_T t in
let vo' = alpha_rename vo0 (alpha_rename_V vo z z0) in
let t' = construct_table (var0,z0) (vi, vo') in
Table t'
| _, _ -> v
in
match v0, v with
| Table t0, Table t ->
let cs0, _ = get_full_table_T t0 in
let vpdef = Table (construct_table cs0 (get_table_by_cs_T cs0 t)) in
let pdefvp = ref (construct_table cs0 (get_table_by_cs_T cs0 t)) in
let t' = table_mapi (fun cs (vi, vo) ->
let _, l' = cs in
if cs = cs0 || l' <> l then vi, vo else
let vs = Table (construct_table cs (vi, vo)) in
let v' = vs |> alpha_rename v0 in
let vt, v'' = prop vpdef v' in
pdefvp := join_V vt (Table !pdefvp) |> get_table_T;
let vi', vo' = match alpha_rename vs v'' with
| Table t'' -> let _, (vi, vo) = get_full_table_T t'' in (vi, vo)
| _ -> raise (Invalid_argument "Expect predefined functions as table")
in vi', vo') t
in Table (
let _, vio = get_full_table_T !pdefvp in
t' |> update_table cs0 vio
)
| _, _ -> v
let rec step term (env: env_t) (sx: var) (cs: (var * loc)) (ae: value_t) (assertion: bool) (is_rec: bool) (m:exec_map_t) =
let n = construct_enode env (loc term) |> construct_snode sx in
let update widen n v m =
n ( function
| None - > v
| Some v ' - > if false & & widen then wid_V v ' v else ( * join_V v '
| None -> v
| Some v' -> if false && widen then wid_V v' v else (*join_V v'*) v) m*)
NodeMap.add n v m
in
let find n m = NodeMap.find_opt n m |> Opt.get_or_else Bot in
match term with
| Const (c, l) ->
( if ! debug then
begin
Format.printf " \n<=== Const = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Const ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
(* if optmization m n find then m else *)
let t = find n m in (* M[env*l] *)
let t' =
if leq_V ae t then t
else
let ct = init_V_c c in
let t' = join_V t ct in
(stren_V t' ae)
in
( if l = " 11 " then
begin
Format.printf " \n<=== Const = = = > % s\n " l ;
pr_value Format.std_formatter t ;
Format.printf " \n<<~~ae~~ > > % s\n " l ;
pr_value Format.std_formatter ae ;
Format.printf " \n<<~~ RES ~~>>\n " ;
pr_value Format.std_formatter t ' ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Const ===> %s\n" l;
pr_value Format.std_formatter t;
Format.printf "\n<<~~ae~~>> %s\n" l;
pr_value Format.std_formatter ae;
Format.printf "\n<<~~ RES ~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
m |> update false n t' (* {v = c ^ aE}*)
| Var (x, l) ->
( if ! debug then
begin
Format.printf " \n<=== Var = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Var ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let (nx, recnb) = VarMap.find x env in
let envx, lx, (varcs, lcs) = get_vnode nx in
let nx = construct_snode sx nx in
let tx = let tx' = find nx m in
if is_Relation tx' then
if sat_equal_V tx' x then tx'
else equal_V (forget_V x tx') x (* M<E(x)>[v=E(x)] *)
else tx'
in
let t = find n m in (* M[env*l] *)
( if l = " 10 " || l = " 14 " then
begin
Format.printf " \n<=== Prop Var % s % b = = = > % s\n " x lx ;
Format.printf " cs % s , % s \n " varcs lcs ;
pr_value Format.std_formatter tx ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t ;
Format.printf " \n<<~~ae~~ > > % s\n " l ;
pr_value Format.std_formatter ae ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Prop Var %s %b ===> %s\n" x recnb lx;
Format.printf "cs %s, %s \n" varcs lcs;
pr_value Format.std_formatter tx;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t;
Format.printf "\n<<~~ae~~>> %s\n" l;
pr_value Format.std_formatter ae;
Format.printf "\n";
end
); *)
let tx', t' =
if optmization m n find & & optmization m nx find then tx , t else
if List.mem lx !pre_def_func then
let tx0 = find nx m0 in
let tx = if !sensitive then prop_predef l tx0 tx else tx in
prop tx t
else
if then prop tx t else
prop_scope envx env sx m tx t
in
( if l = " 10 " || l = " 14 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter tx ' ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t ' ;
Format.printf " " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter tx';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
m |> update false nx tx' |> update false n (stren_V t' ae) (* t' ^ ae *)
| App (e1, e2, l) ->
( if ! debug then
begin
Format.printf " \n<=== App = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== App ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let m0 = step e1 env sx cs ae assertion is_rec m in
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let t0 = find n1 m0 in
let t1, m1 =
match t0 with
| Bot when false ->
let te =
let z = fresh_z () in
init_T (z,z)
in
let t1 = Table te in
t1, update false n1 t1 m0
| _ -> t0, m0
in
if t1 <> Bot && not @@ is_table t1 then
(Format.printf "Error at location %s: expected function, but found %s.\n"
(loc e1) (string_of_value t1);
m1 |> update false n Top)
else
let m2 = step e2 env sx cs ae assertion is_rec m1 in
let n2 = construct_enode env (loc e2) |> construct_snode sx in
]
(match t1, t2 with
| Bot, _ | _, Bot -> m2
| _, Top -> m2 |> update false n Top
| _ ->
let t = find n m2 in
let cs =
if !sensitive then
if is_rec && is_func e1 then cs
else (loc e1, loc e1 |> name_of_node)
else (dx_T t1)
in
let t_temp = Table (construct_table cs (t2, t)) in
let var1 , var2 = cs in
( Format.printf " \nis_rec ? % b\n " ) is_rec ;
( Format.printf " \nAPP cs at % s : % s , % s\n " ) ( loc e1 ) var1 var2 ;
(Format.printf "\nis_rec? %b\n") is_rec;
(Format.printf "\nAPP cs at %s: %s, %s\n") (loc e1) var1 var2; *)
( if loc e1 = " 20 " then
begin
Format.printf " \n<=== Prop APP = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t1 ;
Format.printf " \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t_temp ;
Format.printf " \n " ;
end
) ;
begin
Format.printf "\n<=== Prop APP ===> %s\n" (loc e1);
pr_value Format.std_formatter t1;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t_temp;
Format.printf "\n";
end
); *)
let t1', t0 =
if optmization m2 n1 find & & optmization m2 n2 find & & optmization m2 n find then t1 , t_temp else
prop t1 t_temp
in
( if loc e1 = " 20 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter t1 ' ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t0 ;
Format.printf " \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter t1';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t0;
Format.printf "\n";
end
); *)
let t2', raw_t' =
(* if is_array_set e1 then
let t2', t' = io_T cs t0 in
let elt = proj_V (get_second_table_input_V t') [] in
join_for_item_V t2' elt, t'
else *)
io_T cs t0
in
let t' = get_env_list env sx m |> proj_V raw_t' in
let res_m = m2 |> update false n1 t1' |> update false n2 t2' |> update false n (stren_V t' ae) in
if is_array_set e1 & & only_shape_V t2 ' = false then
let nx = VarMap.find ( get_var_name e2 ) env in
let envx , lx , _ = get_vnode nx in
let nx = construct_snode sx nx in
let tx = find nx m in
let , t2 ' = prop_scope env sx res_m t2 ' tx in
res_m | > NodeMap.add n2 t2 ' | > NodeMap.add nx tx '
else
let nx = VarMap.find (get_var_name e2) env in
let envx, lx,_ = get_vnode nx in
let nx = construct_snode sx nx in
let tx = find nx m in
let tx', t2' = prop_scope envx env sx res_m t2' tx in
res_m |> NodeMap.add n2 t2' |> NodeMap.add nx tx'
else *)
res_m
)
| BinOp (bop, e1, e2, l) ->
( if ! debug then
begin
Format.printf " \n<=== = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Binop ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let m1 =
match bop with
| Cons ->
let rec cons_list_items m term = match term with
| BinOp (Cons, e1', e2', l') ->
let l1, t1', m1' = cons_list_items m e1' in
let l2, t2', m2' = cons_list_items m1' e2' in
l1 + l2, join_V t1' t2', m2'
| _ ->
let m' = step term env sx cs ae assertion is_rec m in
let n' = construct_enode env (loc term) |> construct_snode sx in
let t' = find n' m' in
1, t', m'
in
let len, t1', m1 = cons_list_items m e1 in
let t1 = find n1 m1 in
let t1', _ = prop t1 t1' in
m1 |> update false n1 t1'
| _ -> step e1 env sx cs ae assertion is_rec m
in
let m2 = step e2 env sx cs ae assertion is_rec m1 in
let t1 = find n1 m2 in
let n2 = construct_enode env (loc e2) |> construct_snode sx in
let t2 = find n2 m2 in
if t1 = Bot || t2 = Bot then m2
else
begin
if not @@ is_List t2 then
if not @@ ( is_Relation t1 ) then
( Format.printf " Error at location % s : expected value , but found % s.\n "
( loc e1 ) ( string_of_value t1 ) )
else ( if not @@ ( is_Relation t2 ) then
" Error at location % s : expected value , but found % s.\n "
( loc e2 ) ( string_of_value t2 ) ) ;
if not @@ (is_Relation t1) then
(Format.printf "Error at location %s: expected value, but found %s.\n"
(loc e1) (string_of_value t1))
else (if not @@ (is_Relation t2) then
Format.printf "Error at location %s: expected value, but found %s.\n"
(loc e2) (string_of_value t2));*)
let bop =
match bop, e1, e2 with
| Mod, Const _, Const _ -> Mod
| Mod, _, Const _ -> Modc
| _ -> bop
in
let t = find n m2 in
if optmization m2 n1 find & & optmization m2 n2 find & & optmization m2 n find then m2 else
let raw_t =
match bop with
| Cons (* list op *) ->
list_cons_V prop t1 t2
| And | Or (* bool op *) ->
bool_op_V bop t1 t2
| Modc ->
(* {v:int | a(t) ^ v = n1 mod const }[n1 <- t1] *)
let td = Relation (top_R bop) in
let node_1 = e1 |> loc |> name_of_node in
let t' = arrow_V node_1 td t1 in
let t''' = op_V node_1 (str_of_const e2) bop t' in
let t = get_env_list env sx m2 |> proj_V t''' in
t
| Seq ->
t2
| _ ->
(* {v:int | a(t) ^ v = n1 op n2 }[n1 <- t1, n2 <- t2] *)
let td = Relation (top_R bop) in
let node_1 = e1 |> loc |> name_of_node in
let node_2 = e2 |> loc |> name_of_node in
let t' = arrow_V node_1 td t1 in
let t'' = arrow_V node_2 t' t2 in
( if ! debug then
begin
Format.printf " \n<=== Op = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter t '' ;
" " ;
end
) ;
begin
Format.printf "\n<=== Op binop ===> %s\n" (loc e1);
pr_value Format.std_formatter t';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t'';
Format.printf "\n";
end
); *)
let t''' = op_V node_1 node_2 bop t'' in
( if ! debug then
begin
Format.printf " \n<=== RES Op = = = > \n " ;
pr_value Format.std_formatter t '' ' ;
" " ;
end
) ;
begin
Format.printf "\n<=== RES Op binop ===> \n";
pr_value Format.std_formatter t''';
Format.printf "\n";
end
); *)
let temp_t = get_env_list env sx m2 |> proj_V t''' in
(* if !domain = "Box" then
temp_t |> der_V e1 |> der_V e2 (* Deprecated: Solve remaining constraint only for box*)
else *)
temp_t
in
( if ! debug then
begin
" \n<=== Prop = = = > % s\n " l ;
pr_value Format.std_formatter raw_t ;
" \n<<~~~~ > > \n " ;
pr_value Format.std_formatter t ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== Prop binop ===> %s\n" l;
pr_value Format.std_formatter raw_t;
Format.printf "\n<<~~~~>> \n";
pr_value Format.std_formatter t;
Format.printf "\n";
end
); *)
let _, re_t =
if is_Relation raw_t then raw_t,raw_t else
let t , raw_t = alpha_rename_Vs t raw_t in
prop raw_t t
in
( if l = " 18 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter re_t ;
Format.printf " \n<-- ae -->\n " ;
pr_value Format.std_formatter ae ;
" " ;
end
) ;
begin
Format.printf "\nRES binop for prop:\n";
pr_value Format.std_formatter re_t;
Format.printf "\n<-- ae -->\n";
pr_value Format.std_formatter ae;
Format.printf "\n";
end
); *)
let m2, re_t =
match bop with
| Cons ->
let t1l = cons_temp_lst_V t1 re_t in
let t1l', re_t' = prop t1l re_t in
let t1' = extrac_item_V (get_env_list env sx m2) t1l' in
let t2', re_t'' = prop t2 re_t' in
m2 |> update false n1 t1' |> update false n2 t2', re_t'
| Seq ->
let t2', re_t' = prop t2 re_t in
m2 |> update false n2 t2', re_t'
| _ -> m2, re_t
in
( if l = " 73 " then
begin
Format.printf " \nRES for op:\n " ;
pr_value Format.std_formatter re_t ;
" " ;
end
) ;
begin
Format.printf "\nRES for op:\n";
pr_value Format.std_formatter re_t;
Format.printf "\n";
end
); *)
( if string_of_op bop = " > " then
begin
" \nRES for test:\n " ;
pr_value Format.std_formatter re_t ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for test:\n";
pr_value Format.std_formatter re_t;
Format.printf "\n";
end
); *)
m2 |> update false n (stren_V re_t ae)
end
| UnOp (uop, e1, l) ->
( if ! debug then
begin
Format.printf " \n<=== Unop = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Unop ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let m1 = step e1 env sx cs ae assertion is_rec m in
let t1 = find n1 m1 in
if t1 = Bot then m1
else
let node_1 = e1 |> loc |> name_of_node in
let td = Relation (utop_R uop) in
let t = find n m1 in
let t' = arrow_V node_1 td t1 in
let t'' = uop_V uop node_1 t' in
let raw_t = get_env_list env sx m1 |> proj_V t'' in
(* if !domain = "Box" then
temp_t |> der_V e1 |> der_V e2 (* Deprecated: Solve remaining constraint only for box*)
else *)
let _, re_t =
if is_Relation raw_t
then raw_t, raw_t
else prop raw_t t
in
m1 |> update false n (stren_V re_t ae)
| Ite (e0, e1, e2, l, asst) ->
( if ! debug then
begin
Format.printf " \n<=== Ite = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Ite ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let n0 = construct_enode env (loc e0) |> construct_snode sx in
let m0 =
if optmization m n0 find then m else
step e0 env sx cs ae assertion is_rec m in
let t0 = find n0 m0 in
if t0 = Bot then m0 else
if not @@ is_bool_V t0 then m0 |> update false n Top else
begin
let { isast = isast; ps = pos } = asst in
if assertion && isast && not (is_bool_bot_V t0) && not (is_bool_false_V t0)
then print_loc pos else
let t_true = meet_V (extrac_bool_V t0 true) ae in (* Meet with ae*)
let t_false = meet_V (extrac_bool_V t0 false) ae in
(if assertion && isast then
let i, j = AssertionPosMap.find_opt pos !sens |> Opt.get_or_else (0,0) in
sens := AssertionPosMap.add pos ((if is_bool_bot_V t0 &&
(is_asst_false e0 = false && only_shape_V ae = false)
then i + 1 else i), j + 1) !sens);
let t = find n m0 in
let m1 = step e1 env sx cs t_true assertion is_rec m0 in
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let t1 = find n1 m1 in
( if ! debug then
begin
" \n<=== Prop then = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t1 ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter ( find n m1 ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== Prop then ===> %s\n" (loc e1);
pr_value Format.std_formatter t1;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter (find n m1);
Format.printf "\n";
end
); *)
let t1', t' =
(* if optmization m1 n1 find && optmization m1 n find then t1, (find n m1) else *)
(* let t1, t = alpha_rename_Vs t1 t in *)
prop t1 t in
( if ! debug then
begin
" \nRES for prop:\n " ;
pr_value Format.std_formatter t1 ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter t ' ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter t1';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
let m2 = step e2 env sx cs t_false assertion is_rec m1 in
let n2 = construct_enode env (loc e2) |> construct_snode sx in
let t2 = find n2 m2 in
( if ! debug then
begin
" \n<=== Prop else = = = > % s\n " ( loc e2 ) ;
pr_value Format.std_formatter t2 ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter ( find n m2 ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== Prop else ===> %s\n" (loc e2);
pr_value Format.std_formatter t2;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter (find n m2);
Format.printf "\n";
end
); *)
let t2', t'' =
if optmization m2 n2 find & & optmization m2 n find then t1 , ( find n m2 ) else
(* let t2, t = alpha_rename_Vs t2 t in *)
prop t2 t in
( if ! debug then
begin
" \nRES for prop:\n " ;
pr_value Format.std_formatter t2 ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter t '' ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter t2';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t'';
Format.printf "\n";
end
); *)
( if ( loc e1 ) = " 63 " then
begin
" \n<=== join then else = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t ' ;
" \n<<~~~~ > > % s\n " ( loc e2 ) ;
pr_value Format.std_formatter t '' ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== join then else ===> %s\n" (loc e1);
pr_value Format.std_formatter t';
Format.printf "\n<<~~~~>> %s\n" (loc e2);
pr_value Format.std_formatter t'';
Format.printf "\n";
end
); *)
( if loc e0 = " 10 " then
begin
" \n<=== ite ae = = = > % s % b\n " l ( only_shape_V ae ) ;
pr_value Format.std_formatter ae ;
" \n<<~~ then part ~~>>\n " ;
pr_value Format.std_formatter t_true ;
" \n<----->\n " ;
pr_value Format.std_formatter t1 ' ;
" \n<<~~ else part ~~>>\n " ;
pr_value Format.std_formatter t_false ;
Format.printf " \n<----->\n " ;
pr_value Format.std_formatter t2 ' ;
" " ;
end
) ;
begin
Format.printf "\n<=== ite ae ===> %s %b\n" l (only_shape_V ae);
pr_value Format.std_formatter ae;
Format.printf "\n<<~~ then part ~~>>\n";
pr_value Format.std_formatter t_true;
Format.printf "\n<----->\n";
pr_value Format.std_formatter t1';
Format.printf "\n<<~~ else part ~~>>\n";
pr_value Format.std_formatter t_false;
Format.printf "\n<----->\n";
pr_value Format.std_formatter t2';
Format.printf "\n";
end
); *)
(* let t'', t' = alpha_rename_Vs t'' t' in *)
let t1' = stren_ite_V t1' t_true in
let t2' = stren_ite_V t2' t_false in
( if loc e0 = " 10 " then
begin
" \n<=== RES for ae = = = > % s\n " l ;
pr_value Format.std_formatter t1 ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter t2 ' ;
" " ;
end
) ;
begin
Format.printf "\n<=== RES for ae ===> %s\n" l;
pr_value Format.std_formatter t1';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t2';
Format.printf "\n";
end
); *)
let t_n' = join_V (stren_V t' ae) (stren_V t'' ae) in
( if ( loc e1 ) = " 63 " then
begin
" \nRES for join then else:\n " ;
pr_value Format.std_formatter t_n ' ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for join then else:\n";
pr_value Format.std_formatter t_n';
Format.printf "\n";
end
); *)
let res_m = m2 |> update false n1 t1' |> update false n2 t2' |> update false n t_n' in
res_m
end
| Rec (f_opt, (x, lx), e1, l) ->
( if ! debug then
begin
Format.printf " \n<=== Func = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Func ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let t0 = find n m in
let t =
match t0 with
| Bot ->
let te = let z = fresh_z () in init_T (z,z) in
Table te
| _ -> t0
in
let cs' = cs in
let is_rec' = Opt.exist f_opt || is_rec in
step_func (fun cs (tl, tr) m' ->
if tl = Bot then m' |> update false n t
else if tr = Top then top_M m' else
begin
let _, var = cs in
let f_nf_opt =
Opt.map (fun (f, lf) -> f, (construct_vnode env lf cs, true)) f_opt
in
let nx = construct_vnode env lx cs in
let env' = env |> VarMap.add x (nx, false) in
let nx = construct_snode x nx in
let env1 =
env' |>
(Opt.map (uncurry VarMap.add) f_nf_opt |>
Opt.get_or_else (fun env -> env))
in
let n1 = construct_enode env1 (loc e1) |> construct_snode x in
let tx = find nx m in
let ae' = if (x <> "_" && is_Relation tx) || is_List tx then
if only_shape_V tx then ae else
(arrow_V x ae tx) else ae in
let t1 = if x = "_" then find n1 m else replace_V (find n1 m) x var in
let prop_t = Table (construct_table cs (tx, t1)) in
( if l = " 20 " then
begin
Format.printf " \n<=== Prop lamb = = = > % s % s\n " lx ( loc e1 ) ;
pr_value Format.std_formatter prop_t ;
Format.printf " \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t ;
end
) ;
begin
Format.printf "\n<=== Prop lamb ===> %s %s\n" lx (loc e1);
pr_value Format.std_formatter prop_t;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t;
end
); *)
let px_t, t1 = prop_scope env1 env' x m prop_t t in
( if l = " 20 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter px_t ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t1 ;
Format.printf " \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter px_t;
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t1;
Format.printf "\n";
end
); *)
let nf_t2_tf'_opt =
Opt.map (fun (_, (nf, bf)) ->
let envf, lf, fcs = get_vnode nf in
let nf = construct_snode x nf in
let tf = find nf m in
( if lf = " 4 " then
begin
Format.printf " \n<=== Prop um = = = > % s\n " l ;
pr_value Format.std_formatter t ;
" \n<<~~~~ > > % s\n " lf ;
pr_value Format.std_formatter tf ;
" " ;
end
) ;
begin
Format.printf "\n<=== Prop um ===> %s\n" l;
pr_value Format.std_formatter t;
Format.printf "\n<<~~~~>> %s\n" lf;
pr_value Format.std_formatter tf;
Format.printf "\n";
end
); *)
let t2, tf' = prop_scope env' envf x m t tf in
(* let t2, tf' = prop t tf in *)
( if lf = " 4 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter t2 ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter tf ' ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter t2;
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter tf';
Format.printf "\n";
end
); *)
nf, t2, tf') f_nf_opt
in
let tx', t1' = io_T cs px_t in
let m1 = m |> update is_rec' nx tx' |> update false n1 (if x = "_" then t1' else replace_V t1' var x) |>
(Opt.map (fun (nf, t2, tf') -> fun m' -> m' |> update true nf tf' |> update false n (join_V t1 t2))
nf_t2_tf'_opt |> Opt.get_or_else (update false n t1)) in
let cs = if is_rec' && x = "_" then cs' else cs in
let m1' = step e1 env1 x cs ae' assertion is_rec' m1 in
let t1 = if x = " _ " then find n1 m1 ' else replace_V ( find n1 m1 ' ) x var in
let prop_t = Table ( construct_table cs ( tx , t1 ) ) in
let px_t , t1 = prop_scope env1 env ' x m1 ' prop_t t in
let nf_t2_tf'_opt =
Opt.map ( fun ( _ , ( nf , bf ) ) - >
let envf , lf , fcs = get_vnode nf in
let nf = construct_snode x nf in
let tf = find nf m1 ' in
let t2 , tf ' = prop_scope env ' envf x m1 ' t tf in
nf , t2 , tf ' ) f_nf_opt
in
let ' , t1 ' = io_T cs px_t in
let m1 ' = m1 ' | > update nx tx ' | > update n1 ( if x = " _ " then t1 ' else replace_V t1 ' var x ) | >
( Opt.map ( fun ( nf , t2 , tf ' ) - > fun m ' - > m ' | > update nf tf ' | > update n ( join_V t1 t2 ) )
nf_t2_tf'_opt | > Opt.get_or_else ( update n t1 ) ) in
let prop_t = Table (construct_table cs (tx, t1)) in
let px_t, t1 = prop_scope env1 env' x m1' prop_t t in
let nf_t2_tf'_opt =
Opt.map (fun (_, (nf, bf)) ->
let envf, lf, fcs = get_vnode nf in
let nf = construct_snode x nf in
let tf = find nf m1' in
let t2, tf' = prop_scope env' envf x m1' t tf in
nf, t2, tf') f_nf_opt
in
let tx', t1' = io_T cs px_t in
let m1' = m1' |> update nx tx' |> update n1 (if x = "_" then t1' else replace_V t1' var x) |>
(Opt.map (fun (nf, t2, tf') -> fun m' -> m' |> update nf tf' |> update n (join_V t1 t2))
nf_t2_tf'_opt |> Opt.get_or_else (update n t1)) in *)
join_M m1' m'
end
) t (m |> update false n t |> Hashtbl.copy)
| TupleLst (tlst, l) ->
( if ! debug then
begin
Format.printf " \n<=== Tuple = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Tuple ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let t = find n m in
if List.length tlst = 0 then
let t' = let ct = init_V_c UnitLit in
join_V t ct in
m |> update false n t'
else
let tp, m' = List.fold_right (fun e (t, m) ->
let m' = step e env sx cs ae assertion is_rec m in
let ne = construct_enode env (loc e) |> construct_snode sx in
let te = find ne m' in
let t' = add_tuple_item_V t te in
t', m'
) tlst (Tuple [], m) in
let _, t' = prop tp t in
m' |> update false n t'
| PatMat (e, patlst, l) ->
( if ! debug then
begin
Format.printf " \n<=== Pattern Match = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Pattern Match ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let ne = construct_enode env (loc e) |> construct_snode sx in
(* let ex = get_var_name e in *)
let m' = step e env sx cs ae assertion is_rec m in
let te = find ne m' in
if te = Bot || only_shape_V te then m' else
let m'' = List.fold_left (fun m (Case (e1, e2)) ->
( if ! debug then
begin
" \n<=== Pattern = = = > \n " ;
pr_exp true Format.std_formatter e1 ;
" " ;
pr_exp true Format.std_formatter e2 ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== Pattern ===>\n";
pr_exp true Format.std_formatter e1;
Format.printf "\n";
pr_exp true Format.std_formatter e2;
Format.printf "\n";
end
); *)
match e1 with
| Const (c, l') ->
let m1 = step e1 env sx cs ae assertion is_rec m in
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let te, t1 = find ne m1, find n1 m1 in
let te, t1 = alpha_rename_Vs te t1 in
if leq_V te t1 then m' else
let t1 = if is_List te then
item_shape_V te t1
else t1 in
( if true then
begin
" % s\n " ( loc e1 ) ;
pr_exp true Format.std_formatter e1 ;
" " ;
pr_value Format.std_formatter t1 ;
" \n<<~~~~ > > % s\n " ( loc e ) ;
pr_value Format.std_formatter te ;
" " ;
pr_value Format.std_formatter ( join_V t1 te ) ;
" " ;
end
) ;
begin
Format.printf "\n Pattern %s\n" (loc e1);
pr_exp true Format.std_formatter e1;
Format.printf "\n";
pr_value Format.std_formatter t1;
Format.printf "\n<<~~~~>> %s\n" (loc e);
pr_value Format.std_formatter te;
Format.printf "\n";
pr_value Format.std_formatter (join_V t1 te);
Format.printf "\n";
end
); *)
let m1 = m1 |> update false n1 t1 in
let b =
sat_leq_V t1 te
in
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let n2 = construct_enode env (loc e2) |> construct_snode sx in
( if true then
begin
Format.printf " \npattern ae : % b\n " b ;
pr_value Format.std_formatter ae ;
" " ;
end
) ;
begin
Format.printf "\npattern ae: %b\n" b;
pr_value Format.std_formatter ae;
Format.printf "\n";
end
); *)
let ae' = if not b then bot_relation_V Int else
arrow_V (loc e) ae (find n1 m1) in
( if true then
begin
Format.printf " \nRES for ae:\n " ;
pr_value Format.std_formatter ae ' ;
" " ;
end
) ;
begin
Format.printf "\nRES for ae:\n";
pr_value Format.std_formatter ae';
Format.printf "\n";
end
); *)
let m2 = step e2 env sx cs ae' assertion is_rec m1 in
if not b then
let t, t2 = find n m2, find n2 m2 in
let t2', t' = prop t2 t in
m2 |> update false n1 t1 |> update false n2 t2' |> update false n t'
else
let te, t, t1, t2 = find ne m2, find n m2, find n1 m2, find n2 m2 in
let t1', te' = let te, t1 = alpha_rename_Vs te t1 in
t1, join_V t1 te in
let t2', t' = prop t2 t in
m2 |> update false ne te' |> update false n1 t1'
|> update false n2 t2' |> update false n t'
| Var (x, l') ->
let n1 = construct_vnode env l' (sx,sx) in
let env1 = env |> VarMap.add x (n1, false) in
let n1 = construct_snode x n1 in
let t1 = find n1 m in let te = find ne m in
let _, t1' = prop te t1 in
let m1 = m |> update false n1 t1' in
let m2 = step e2 env1 sx cs ae assertion is_rec m1 in
let n2 = construct_enode env1 (loc e2) |> construct_snode sx in
let t = find n m2 in let t2 = find n2 m2 in
let t2', t' = prop t2 t in
m2 |> update false n2 t2' |> update false n t'
| BinOp (Cons, el, er, l') ->
( if true then
begin
" \n<=== Prop then = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t1 ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter ( find n m1 ) ;
" " ;
end
) ;
begin
Format.printf "\n<=== Prop then ===> %s\n" (loc e1);
pr_value Format.std_formatter t1;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter (find n m1);
Format.printf "\n";
end
); *)
let ml, envl = list_var_item el sx cs m env ne true 0 in
( if ! debug then
begin
" \n<=== Pattern binop = = = > \n " ;
pr_exp true Format.std_formatter er ;
" " ;
end
) ;
begin
Format.printf "\n<=== Pattern binop ===>\n";
pr_exp true Format.std_formatter er;
Format.printf "\n";
end
); *)
let mr, envr = list_var_item er sx cs ml envl ne false 1 in
let nr = construct_enode envr (loc er) |> construct_snode sx in
let n2 = construct_enode envr (loc e2) |> construct_snode sx in
let n1 = construct_enode envr l' |> construct_snode sx in
let m1 = step e1 envr sx cs ae assertion is_rec mr in
let te, t1 = find ne m1, find n1 m1 in
let te, t1 = alpha_rename_Vs te t1 in
let ae' =
let ae = arrow_V (loc e) ae t1 in
arrow_V (loc er) ae (find nr m1)
in
let m2 = step e2 envr sx cs ae' assertion is_rec m1 in
let te, t, t1, t2 = find ne m2, find n m2, find n1 m2, find n2 m2 in
let t1', te' =
let te, t1 = alpha_rename_Vs te t1 in
prop t1 te
in
let t2', t' = prop t2 t in
m2 |> update false ne te' |> update false n1 t1'
|> update false n2 t2' |> update false n t'
| TupleLst (termlst, l') ->
let n1 = construct_enode env l' |> construct_snode sx in
let t1 =
let raw_t1 = find n1 m in
if is_tuple_V raw_t1 then raw_t1
else
let u' = List.init (List.length termlst) (fun _ ->
Bot) in Tuple u' in
let te = find ne m in
let te, t1 = alpha_rename_Vs te t1 in
let tlst = get_tuple_list_V t1 in
let tllst = te |> get_tuple_list_V in
let env', m', tlst', tllst' = List.fold_left2 (fun (env, m, li, llst) e (ti, tlsti) ->
match e with
| Var (x, l') ->
let nx = construct_vnode env l' cs in
let env1 = env |> VarMap.add x (nx, false) in
let nx = construct_snode sx nx in
let tx = find nx m in
let ti', tx' = prop ti tx in
let tlsti', ti'' = prop tlsti ti in
let m' = m |> update false nx tx' in
env1, m', (join_V ti' ti'') :: li, tlsti' :: llst
| _ -> raise (Invalid_argument "Tuple only for variables now")
) (env, m, [], []) termlst (zip_list tlst tllst) in
let tlst', tllst' = List.rev tlst', List.rev tllst' in
let t1', te' = Tuple tlst', Tuple tllst' in
let _, t1' = prop t1' t1 in
let te', _ = prop te te' in
let m1 = m |> update false n1 t1' |> update false ne te' in
let m2 = step e2 env' sx cs ae assertion is_rec m1 in
let n2 = construct_enode env' (loc e2) |> construct_snode sx in
let t = find n m2 in let t2 = find n2 m2 in
let t2', t' = prop t2 t in
m2 |> update false n2 t2' |> update false n t'
| _ -> raise (Invalid_argument "Pattern should only be either constant, variable, or list cons")
) (update false ne te m' |> Hashtbl.copy) patlst in
m''
let step x1 x2 x3 x4 x5 x6 x7 = measure_call "step" (step x1 x2 x3 x4 x5 x6 x7)
(** Widening **)
let widening k (m1:exec_map_t) (m2:exec_map_t): exec_map_t =
if k > !delay_wid then wid_M m1 m2 else join_M m1 m2
let widening k m = measure_call "widening" (widening k m)
(** Narrowing **)
let narrowing (m1:exec_map_t) (m2:exec_map_t): exec_map_t =
meet_M m1 m2
* Fixpoint loop
let rec fix stage env e (k: int) (m:exec_map_t) (assertion:bool): string * exec_map_t =
(if !out_put_level = 0 then
begin
let process = match stage with
| Widening -> "Wid"
| Narrowing -> "Nar"
in
Format.printf "%s step %d\n" process k;
print_exec_map m;
end);
if k > 40 then exit 0 else
let ae = VarMap.fold (fun var (n, b) ae ->
let n = construct_snode "" n in
let find n m = NodeMap.find_opt n m |> Opt.get_or_else Bot in
let t = find n m in
if is_Relation t then
arrow_V var ae t else ae
) env (Relation (top_R Plus)) in
let m_t = Hashtbl.copy m in
let m' = step e env "" ("","") ae assertion false m_t in
if k < 0 then if k = -1 then "", m' else fix stage env e (k+1) m' assertion else
if k > 2 then Hashtbl.reset ! pre_m ;
pre_m : = m ;
pre_m := m; *)
(* Format.printf "\nFinish step %d\n" k;
flush stdout; *)
let m'' = if stage = Widening then widening k m m' else narrowing m m' in
let comp = if stage = Widening then leq_M m'' m else leq_M m m'' in
if comp then
begin
if assertion || !narrow then
let s = AssertionPosMap.fold (fun pos (i, j) s ->
if i = j then try print_loc pos with
Input_Assert_failure s -> s else s) !sens "The input program is safe\n" in
s, m
else
begin
try fix stage env e k m true (* Final step to check assertions *)
with Input_Assert_failure s -> s, m
end
end
else (fix stage env e (k+1) m'' assertion) (*Hashtbl.reset m; *)
(** Semantic function *)
let s e =
( if ! debug then
begin
" % % Pre vals : % % \n " ;
pr_pre_def_vars Format.std_formatter ;
" \n\n " ;
end ) ;
begin
Format.printf "%% Pre vals: %%\n";
pr_pre_def_vars Format.std_formatter;
Format.printf "\n\n";
end); *)
(* exit 0; *)
(* let rec print_list = function
[] -> ()
| e::l -> print_int e ; print_string " " ; print_list l in
ThresholdsSetType.elements !thresholdsSet |> print_list; *)
(* AbstractDomain.AbstractValue.licons_ref := AbstractDomain.AbstractValue.licons_earray [|"cur_v"|]; *)
let envt, m0' = pref_M env0 (Hashtbl.copy m0) in
let fv_e = fv e in
let envt =
VarMap.filter
(fun x (n, _) ->
if StringSet.mem x fv_e then true
else
let n = construct_snode "" n in
(Hashtbl.remove m0' n; false)) envt
in
thresholdsSet := !thresholdsSet |> ThresholdsSetType.add 0 |> ThresholdsSetType.add 111 |> ThresholdsSetType.add 101
|> ThresholdsSetType.add 2 |> ThresholdsSetType.add 4 |> ThresholdsSetType.add (-1) |> ThresholdsSetType.add (-2);
pre_m : = m0 ' ;
let check_str, m =
let s1, m1 = (fix Widening envt e 0 m0' false) in
if !narrow then
begin
narrow := false;
let _ , m1 = fix e ( -10 ) m1 false in ( * step^10(fixw ) < = fixw
let m1 = m1 |> reset in
let s2, m2 = fix Narrowing envt e 0 m1 false in
if eq_PM m0 m2 then s2, m2
else exit 0
end
else s1, m1
in
if !out_put_level = 1 then
begin
Format.printf "Final step \n";
print_exec_map m;
end;
Format.printf "%s" check_str;
m
| null | https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/src/algo/abstractTransformer.ml | ocaml | Create a fresh variable name
let _ = alpha_rename_Arys ary1 ary' in
let lc_env env1 env2 =
Array.fold_left (fun a id -> if Array.mem id a then a else Array.append a [|id|] ) env2 env1
let v1'',_ = prop v1 (proj_V v2 env1)in
let _, v2'' = prop (proj_V v1 env2) v2 in
* Reset the array nodes *
let iterUpdate m v l = NodeMap.map (fun x -> arrow_V l x v) m
let getVars env = VarMap.fold (fun var n lst -> var :: lst) env []
let optmization m n find = (* Not sound for work
join_V v'
if optmization m n find then m else
M[env*l]
{v = c ^ aE}
M<E(x)>[v=E(x)]
M[env*l]
t' ^ ae
if is_array_set e1 then
let t2', t' = io_T cs t0 in
let elt = proj_V (get_second_table_input_V t') [] in
join_for_item_V t2' elt, t'
else
list op
bool op
{v:int | a(t) ^ v = n1 mod const }[n1 <- t1]
{v:int | a(t) ^ v = n1 op n2 }[n1 <- t1, n2 <- t2]
if !domain = "Box" then
temp_t |> der_V e1 |> der_V e2 (* Deprecated: Solve remaining constraint only for box
if !domain = "Box" then
temp_t |> der_V e1 |> der_V e2 (* Deprecated: Solve remaining constraint only for box
Meet with ae
if optmization m1 n1 find && optmization m1 n find then t1, (find n m1) else
let t1, t = alpha_rename_Vs t1 t in
let t2, t = alpha_rename_Vs t2 t in
let t'', t' = alpha_rename_Vs t'' t' in
let t2, tf' = prop t tf in
let ex = get_var_name e in
* Widening *
* Narrowing *
Format.printf "\nFinish step %d\n" k;
flush stdout;
Final step to check assertions
Hashtbl.reset m;
* Semantic function
exit 0;
let rec print_list = function
[] -> ()
| e::l -> print_int e ; print_string " " ; print_list l in
ThresholdsSetType.elements !thresholdsSet |> print_list;
AbstractDomain.AbstractValue.licons_ref := AbstractDomain.AbstractValue.licons_earray [|"cur_v"|]; | open AbstractDomain
open Syntax
open SemanticDomain
open SemanticsDomain
open SensitiveDomain
open SenSemantics
open Printer
open Util
open Config
* * c[M ] is a single base refinement type that pulls in all the environment dependencies from M
M = n1 |- > { v : int | v > = 2 } , n2 |- > z:{v : int | v > = 0 } - > { v : int | v = z } , n3 |- > { v : bool | v = true }
c[M ] = { v : int | v = c & & n1 > = 2 }
* * t[M ]
t ' = { v : int | v = 2 }
x in scope and M^t[x ] = { v : bool | v = true }
the scope of t is the set of all nodes in the range ( i.e. codomain ) of the environment component of n.
t'[M^t ] = { v : int | v = 2 & & x = true }
* * True False
Using v = 1 be true once inside vt and v = 1 be false inside vf
** c[M] is a single base refinement type that pulls in all the environment dependencies from M
M = n1 |-> {v: int | v >= 2}, n2 |-> z:{v: int | v >= 0} -> {v: int | v = z}, n3 |-> {v: bool | v = true}
c[M] = {v: int | v = c && n1 >= 2}
** t[M]
t' = {v:int | v = 2}
x in scope and M^t[x] = {v: bool | v = true}
the scope of t is the set of all nodes in the range (i.e. codomain) of the environment component of n.
t'[M^t] = {v: int | v = 2 && x = true}
** True False
Using v = 1 be true once inside vt and v = 1 be false inside vf
*)
type stage_t =
| Widening
| Narrowing
module AssertionPosMap = Map.Make(struct
type t = Syntax.pos
let compare = compare
end)
type asst_map_t = (int * int) AssertionPosMap.t
let sens : asst_map_t ref = ref AssertionPosMap.empty
let env0, m0 =
let enva, ma = array_M VarMap.empty (NodeMap.create 500) in
let envb, mb = list_M enva ma in
envb, mb
let fresh_z= fresh_func "z"
let arrow_V x1 x2 = measure_call "arrow_V" (arrow_V x1 x2)
let forget_V x = measure_call "forget_V" (forget_V x)
let stren_V x = measure_call "stren_V" (stren_V x)
let join_V e = measure_call "join_V" (join_V e)
let meet_V e = measure_call "meet_V" (meet_V e)
let equal_V e = measure_call "equal_V" (equal_V e)
let proj_V e = measure_call "proj_V" (proj_V e)
let sat_equal_V e = measure_call "sat_equal_V" (sat_equal_V e)
let rec prop (v1: value_t) (v2: value_t): (value_t * value_t) = match v1, v2 with
| Top, Bot | Table _, Top -> Top, Top
| Table t, Bot ->
let t' = init_T (dx_T v1) in
v1, Table t'
| Relation r1, Relation r2 ->
if leq_R r1 r2 then v1, v2 else
Relation r1, Relation (join_R r1 r2)
| Table t1, Table t2 ->
let prop_table_entry cs (v1i, v1o) (v2i, v2o) =
let _, z = cs in
let v1ot, v2ip =
if (is_Array v1i && is_Array v2i) || (is_List v1i && is_List v2i) then
let l1 = get_len_var_V v1i in
let e1 = get_item_var_V v1i in
let l2 = get_len_var_V v2i in
let e2 = get_item_var_V v2i in
let v = replace_V v1o l1 l2 in
replace_V v e1 e2, (forget_V l1 v2i |> forget_V e1)
else v1o, v2i
in
let v1i', v2i', v1o', v2o' =
let opt_i = false
Optimization 1 : If those two are the same , ignore the prop step
|| (v1i <> Bot && v2i <> Bot && eq_V v2i v1i) in
let v2i', v1i' =
if opt_i then v2i, v1i else
prop v2i v1i
in
let opt_o = false
Optimization 2 : If those two are the same , ignore the prop step
|| (v2o <> Bot && v1o <> Bot && eq_V v1ot v2o)
in
let v1o', v2o' =
if opt_o then v1ot, v2o else
prop (arrow_V z v1ot v2ip) (arrow_V z v2o v2ip)
in
let v1o' =
if (is_Array v1i' && is_Array v2i') || (is_List v1i' && is_List v2i') then
let l1 = get_len_var_V v1i' in
let e1 = get_item_var_V v1i' in
let l2 = get_len_var_V v2i' in
let e2 = get_item_var_V v2i' in
let v = replace_V v1o' l2 l1 in
replace_V v e2 e1
else v1o'
in
if true then
begin
( if true then
begin
" \n<=== prop o = = = > % s\n " z ;
pr_value Format.std_formatter v1ot ;
" " ;
" \n<--- v2i --->\n " ;
pr_value Format.std_formatter v2i ;
" \n " ;
pr_value Format.std_formatter v2ip ;
" \n " ;
pr_value Format.std_formatter ( arrow_V z v1ot v2ip ) ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter ( arrow_V z v2o v2ip ) ;
" " ;
end
) ;
( if true then
begin
" \n<=== res = = = > % s\n " z ;
pr_value Format.std_formatter v1o ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter v2o ' ;
" " ;
end
) ;
end ;
begin
(if true then
begin
Format.printf "\n<=== prop o ===>%s\n" z;
pr_value Format.std_formatter v1ot;
Format.printf "\n";
Format.printf "\n<--- v2i --->\n";
pr_value Format.std_formatter v2i;
Format.printf "\n";
pr_value Format.std_formatter v2ip;
Format.printf "\n";
pr_value Format.std_formatter (arrow_V z v1ot v2ip);
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter (arrow_V z v2o v2ip);
Format.printf "\n";
end
);
(if true then
begin
Format.printf "\n<=== res ===>%s\n" z;
pr_value Format.std_formatter v1o';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter v2o';
Format.printf "\n";
end
);
end; *)
let v1o', v2o' =
if opt_o then v1o', v2o' else (join_V v1o v1o', join_V v2o v2o')
in
v1i', v2i', v1o', v2o'
in
(v1i', v1o'), (v2i', v2o')
in
let t1', t2' =
prop_table prop_table_entry alpha_rename_V t1 t2
in
Table t1', Table t2'
| Ary ary1, Ary ary2 -> let ary1', ary2' = alpha_rename_Arys ary1 ary2 in
let ary' = (join_Ary ary1' ary2') in
let _, ary2'' = alpha_rename_Arys ary2 ary' in
Ary ary1, Ary ary2''
| Lst lst1, Lst lst2 ->
( if true then
begin
" \n<=== prop list = = = > \n " ;
pr_value Format.std_formatter ( ) ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter ( Lst lst2 ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== prop list ===>\n";
pr_value Format.std_formatter (Lst lst1);
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter (Lst lst2);
Format.printf "\n";
end
); *)
let lst1', lst2' = alpha_rename_Lsts lst1 lst2 in
( if true then
begin
" \n<=== after rename list = = = > \n " ;
pr_value Format.std_formatter ( ) ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter ( Lst lst2 ' ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== after rename list ===>\n";
pr_value Format.std_formatter (Lst lst1');
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter (Lst lst2');
Format.printf "\n";
end
); *)
let lst1'', lst2'' = prop_Lst prop lst1' lst2' in
( if true then
begin
" \n<=== res = = = > \n " ;
pr_value Format.std_formatter ( ) ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter ( Lst lst2 '' ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== res ===>\n";
pr_value Format.std_formatter (Lst lst1'');
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter (Lst lst2'');
Format.printf "\n";
end
); *)
let _, lst2'' = alpha_rename_Lsts lst2 lst2'' in
Lst lst1'', Lst lst2''
| Ary ary, Bot -> let vars, r = ary in
let ary' = init_Ary vars in
v1, Ary ary'
| Lst lst, Bot -> let vars, r = lst in
let lst' = init_Lst vars in
v1, Lst lst'
| Tuple u, Bot -> let u' = List.init (List.length u) (fun _ ->
Bot) in
v1, Tuple u'
| Tuple u1, Tuple u2 -> if List.length u1 <> List.length u2 then
raise (Invalid_argument "Prop tuples should have the same form")
else
let u1', u2' = List.fold_right2 (fun v1 v2 (u1', u2') ->
let v1', v2' = prop v1 v2 in
(v1'::u1', v2'::u2')
) u1 u2 ([],[]) in
Tuple u1', Tuple u2'
| _, _ -> if leq_V v1 v2 then v1, v2 else v1, join_V v1 v2
let prop p = measure_call "prop" (prop p)
let rec nav ( v1 : value_t ) ( v2 : value_t ): ( value_t * value_t ) = match v1 , v2 with
| Relation r1 , Relation r2 - >
let r2 ' = if leq_R r1 r2 then r1 else r2
in
Relation r1 , Relation r2 '
| Ary ary1 , let ary1 ' , ary2 ' = alpha_rename_Arys ary1 ary2 in
let _ , ary2 '' = alpha_rename_Arys ary2 ( ary1 ' ary2 ' ) in
Ary ary1 , Ary ary2 ''
| Table t1 , Table t2 - >
let t1 ' , t2 ' = alpha_rename t1 t2 in
let ( z1 , v1i , v1o ) = t1 ' and ( z2 , v2i , v2o ) = t2 ' in
let v1ot =
if is_Array v1i & & is_Array v2i then
let l1 = get_len_var_V v1i in
let l2 = get_len_var_V v2i in
replace_V v1o l1 l2
else v1o
in
let p1 , p2 =
let v1i ' , v2i ' , v1o ' , v2o ' =
let v2i ' , v1i ' = nav v2i v1i in
let v1o ' , v2o ' = nav ( arrow_V z1 v1ot v2i ) ( arrow_V z1 v2o v2i ) in
let v1o ' , v2o ' = match leq_V v1o ' v1ot , v2o ' v2o with
| false , false - > v1ot , v2o
| true , false - > v1o ' , v2o
| false , true - > v1ot , v2o '
| true , true - > v1o ' , v2o '
in
let v1o ' =
if is_Array v1i ' & & is_Array v2i ' then
let l1 = get_len_var_V v1i ' in
let l2 = get_len_var_V v2i ' in
replace_V v1o ' l2 l1
else v1o '
in
v1i ' , v2i ' , v1o ' , v2o '
in
( v1i ' , v1o ' ) , ( v2i ' , v2o ' )
in
let t1 '' = ( z1 , fst p1 , snd p1 ) and t2 '' = ( z2 , fst p2 , snd p2 ) in
Table t1 '' , Table t2 ''
| _ , _ - > v1 , v2
| Relation r1, Relation r2 ->
let r2' = if leq_R r1 r2 then r1 else r2
in
Relation r1, Relation r2'
| Ary ary1, Ary ary2 -> let ary1', ary2' = alpha_rename_Arys ary1 ary2 in
let _, ary2'' = alpha_rename_Arys ary2 (join_Ary ary1' ary2') in
Ary ary1, Ary ary2''
| Table t1, Table t2 ->
let t1', t2' = alpha_rename t1 t2 in
let (z1, v1i, v1o) = t1' and (z2, v2i, v2o) = t2' in
let v1ot =
if is_Array v1i && is_Array v2i then
let l1 = get_len_var_V v1i in
let l2 = get_len_var_V v2i in
replace_V v1o l1 l2
else v1o
in
let p1, p2 =
let v1i', v2i', v1o', v2o' =
let v2i', v1i' = nav v2i v1i in
let v1o', v2o' = nav (arrow_V z1 v1ot v2i) (arrow_V z1 v2o v2i) in
let v1o', v2o' = match leq_V v1o' v1ot, leq_V v2o' v2o with
| false, false -> v1ot, v2o
| true, false -> v1o', v2o
| false, true -> v1ot, v2o'
| true, true -> v1o', v2o'
in
let v1o' =
if is_Array v1i' && is_Array v2i' then
let l1 = get_len_var_V v1i' in
let l2 = get_len_var_V v2i' in
replace_V v1o' l2 l1
else v1o'
in
v1i', v2i', v1o', v2o'
in
(v1i', v1o'), (v2i', v2o')
in
let t1'' = (z1, fst p1, snd p1) and t2'' = (z2, fst p2, snd p2) in
Table t1'', Table t2''
| _, _ -> v1, v2 *)
let get_env_list (env: env_t) (sx: var) (m: exec_map_t) =
let find n m = NodeMap.find_opt n m |> Opt.get_or_else Bot in
let env_l = VarMap.bindings env in
let helper lst (x, (n, _)) =
let n = construct_snode sx n in
let t = find n m in
let lst' = if is_List t then
(get_item_var_V t) :: (get_len_var_V t) :: lst
else lst
in
x :: lst'
in
List.fold_left helper [] env_l
let get_env_list e sx = measure_call "get_env_list" (get_env_list e sx)
let prop_scope (env1: env_t) (env2: env_t) (sx: var) (m: exec_map_t) (v1: value_t) (v2: value_t): (value_t * value_t) =
let env1 = get_env_list env1 sx m in
let env2 = get_env_list env2 sx m in
let v1', v2' = prop v1 v2 in
let v1'' = proj_V v1' env1 in
let v2'' = proj_V v2' env2 in
v1'', v2''
let prop_scope x1 x2 x3 x4 x5 = measure_call "prop_scope" (prop_scope x1 x2 x3 x4 x5)
let reset (m:exec_map_t): exec_map_t = NodeMap.fold (fun n t m ->
m |> NodeMap.add n t
) m0 m
let iterEnv_c env m c = VarMap.fold ( fun var n a - >
let v = NodeMap.find_opt n m | > Opt.get_or_else Top in
let EN ( env ' , l ) = n in
let in
c_V a v lb ) env ( init_V_c c )
let iterEnv_v env m v = VarMap.fold ( fun var n a - >
let ai = NodeMap.find_opt n m | > Opt.get_or_else Top in
arrow_V var a ai ) env v
let v = NodeMap.find_opt n m |> Opt.get_or_else Top in
let EN (env', l) = n in
let lb = name_of_node l in
c_V a v lb) env (init_V_c c)
let iterEnv_v env m v = VarMap.fold (fun var n a ->
let ai = NodeMap.find_opt n m |> Opt.get_or_else Top in
arrow_V var a ai) env v *)
if !st <= 6000 then false else
let t = find n m in
let pre_t = find n !pre_m in
opt_eq_V pre_t t *)
let rec list_var_item eis sx (cs: (var * loc)) m env nlst left_or_right lst_len =
let find n m = NodeMap.find_opt n m |> Opt.get_or_else Bot in
let vlst = find nlst m in
match eis, left_or_right with
| Var (x, l), true ->
let n = construct_vnode env l cs in
let env1 = env |> VarMap.add x (n, false) in
let n = construct_snode sx n in
let t = find n m in
let tp = cons_temp_lst_V t vlst in
( if ! debug then
begin
Format.printf " \n<---Pattern var--- > % s\n " l ;
pr_value Format.std_formatter vlst ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t ;
pr_value Format.std_formatter tp ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<---Pattern var---> %s\n" l;
pr_value Format.std_formatter vlst;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t;
pr_value Format.std_formatter tp;
Format.printf "\n";
end
); *)
let vlst', tp' = prop vlst tp in
let t' = extrac_item_V (get_env_list env1 sx m) tp' in
( if ! debug then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter vlst ' ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t ' ;
Format.printf " " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter vlst';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
let m' = m |> NodeMap.add n t' |> NodeMap.add nlst vlst' in
m', env1
| Var(x, l), false ->
let n = construct_vnode env l cs in
let env1 = env |> VarMap.add x (n, false) in
let n = construct_snode sx n in
let lst = find n m |> get_list_length_item_V in
let t_new = reduce_len_V lst_len lst vlst in
let _, t' = prop t_new (find n m) in
let m' = NodeMap.add n t' m in
m', env1
| Const (c, l), false ->
let n = construct_enode env l |> construct_snode sx in
let t_new = pattern_empty_lst_V vlst in
let _, t' = prop t_new (find n m) in
let m' = NodeMap.add n t' m in
m', env
| TupleLst (termlst, l), true ->
let n = construct_enode env l |> construct_snode sx in
let t =
let raw_t = find n m in
if is_tuple_V raw_t then raw_t
else
let u' = List.init (List.length termlst) (fun _ ->
Bot) in Tuple u' in
( if ! debug then
begin
Format.printf " \n<---Pattern tuple--- > % s\n " l ;
pr_value Format.std_formatter vlst ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<---Pattern tuple---> %s\n" l;
pr_value Format.std_formatter vlst;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t;
Format.printf "\n";
end
); *)
let tlst = get_tuple_list_V t in
let tllst = extrac_item_V (get_env_list env sx m) vlst |> get_tuple_list_V in
let env', m', tlst', tllst' = List.fold_left2 (fun (env, m, li, llst) e (ti, tlsti) ->
match e with
| Var (x, l') ->
let nx = construct_vnode env l' cs in
let env1 = env |> VarMap.add x (nx, false) in
let nx = construct_snode sx nx in
let tx = find nx m in
let ti', tx' = prop ti tx in
let tlsti', ti'' = prop tlsti ti in
let m' = m |> NodeMap.add nx tx' in
env1, m', (join_V ti' ti'') :: li, tlsti' :: llst
| _ -> raise (Invalid_argument "Tuple only for variables now")
) (env, m, [], []) termlst (zip_list tlst tllst) in
let tlst', tllst' = List.rev tlst', List.rev tllst' in
let t', vlst' = Tuple tlst', (cons_temp_lst_V (Tuple tllst') vlst) in
let m'' = m' |> NodeMap. add n t'
|> NodeMap.add nlst vlst' in
( if ! debug then
begin
Format.printf " \nRES for tuple:\n " ;
pr_value Format.std_formatter vlst ' ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t ' ;
Format.printf " " ;
end
) ;
begin
Format.printf "\nRES for tuple:\n";
pr_value Format.std_formatter vlst';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
m'', env'
| BinOp (bop, e1, e2, l), _ ->
let m', env' = list_var_item e1 sx cs m env nlst true 0 in
let m'', env'' = list_var_item e2 sx cs m' env' nlst false (lst_len + 1) in
m'', env''
| UnOp (uop, e1, l), true ->
let m', env' = list_var_item e1 sx cs m env nlst true 0 in
m', env'
| _ -> raise (Invalid_argument "Pattern should only be either constant, variable, and list cons")
let prop_predef l v0 v =
let l = l |> name_of_node in
let rec alpha_rename v0 v =
match v0, v with
| Table t0, Table t ->
if table_isempty t || table_isempty t0 then Table t else
let (var0, z0), (vi0, vo0) = get_full_table_T t0 in
let (var, z), (vi, vo) = get_full_table_T t in
let vo' = alpha_rename vo0 (alpha_rename_V vo z z0) in
let t' = construct_table (var0,z0) (vi, vo') in
Table t'
| _, _ -> v
in
match v0, v with
| Table t0, Table t ->
let cs0, _ = get_full_table_T t0 in
let vpdef = Table (construct_table cs0 (get_table_by_cs_T cs0 t)) in
let pdefvp = ref (construct_table cs0 (get_table_by_cs_T cs0 t)) in
let t' = table_mapi (fun cs (vi, vo) ->
let _, l' = cs in
if cs = cs0 || l' <> l then vi, vo else
let vs = Table (construct_table cs (vi, vo)) in
let v' = vs |> alpha_rename v0 in
let vt, v'' = prop vpdef v' in
pdefvp := join_V vt (Table !pdefvp) |> get_table_T;
let vi', vo' = match alpha_rename vs v'' with
| Table t'' -> let _, (vi, vo) = get_full_table_T t'' in (vi, vo)
| _ -> raise (Invalid_argument "Expect predefined functions as table")
in vi', vo') t
in Table (
let _, vio = get_full_table_T !pdefvp in
t' |> update_table cs0 vio
)
| _, _ -> v
let rec step term (env: env_t) (sx: var) (cs: (var * loc)) (ae: value_t) (assertion: bool) (is_rec: bool) (m:exec_map_t) =
let n = construct_enode env (loc term) |> construct_snode sx in
let update widen n v m =
n ( function
| None - > v
| Some v ' - > if false & & widen then wid_V v ' v else ( * join_V v '
| None -> v
NodeMap.add n v m
in
let find n m = NodeMap.find_opt n m |> Opt.get_or_else Bot in
match term with
| Const (c, l) ->
( if ! debug then
begin
Format.printf " \n<=== Const = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Const ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let t' =
if leq_V ae t then t
else
let ct = init_V_c c in
let t' = join_V t ct in
(stren_V t' ae)
in
( if l = " 11 " then
begin
Format.printf " \n<=== Const = = = > % s\n " l ;
pr_value Format.std_formatter t ;
Format.printf " \n<<~~ae~~ > > % s\n " l ;
pr_value Format.std_formatter ae ;
Format.printf " \n<<~~ RES ~~>>\n " ;
pr_value Format.std_formatter t ' ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Const ===> %s\n" l;
pr_value Format.std_formatter t;
Format.printf "\n<<~~ae~~>> %s\n" l;
pr_value Format.std_formatter ae;
Format.printf "\n<<~~ RES ~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
| Var (x, l) ->
( if ! debug then
begin
Format.printf " \n<=== Var = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Var ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let (nx, recnb) = VarMap.find x env in
let envx, lx, (varcs, lcs) = get_vnode nx in
let nx = construct_snode sx nx in
let tx = let tx' = find nx m in
if is_Relation tx' then
if sat_equal_V tx' x then tx'
else tx'
in
( if l = " 10 " || l = " 14 " then
begin
Format.printf " \n<=== Prop Var % s % b = = = > % s\n " x lx ;
Format.printf " cs % s , % s \n " varcs lcs ;
pr_value Format.std_formatter tx ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t ;
Format.printf " \n<<~~ae~~ > > % s\n " l ;
pr_value Format.std_formatter ae ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Prop Var %s %b ===> %s\n" x recnb lx;
Format.printf "cs %s, %s \n" varcs lcs;
pr_value Format.std_formatter tx;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t;
Format.printf "\n<<~~ae~~>> %s\n" l;
pr_value Format.std_formatter ae;
Format.printf "\n";
end
); *)
let tx', t' =
if optmization m n find & & optmization m nx find then tx , t else
if List.mem lx !pre_def_func then
let tx0 = find nx m0 in
let tx = if !sensitive then prop_predef l tx0 tx else tx in
prop tx t
else
if then prop tx t else
prop_scope envx env sx m tx t
in
( if l = " 10 " || l = " 14 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter tx ' ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t ' ;
Format.printf " " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter tx';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
| App (e1, e2, l) ->
( if ! debug then
begin
Format.printf " \n<=== App = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== App ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let m0 = step e1 env sx cs ae assertion is_rec m in
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let t0 = find n1 m0 in
let t1, m1 =
match t0 with
| Bot when false ->
let te =
let z = fresh_z () in
init_T (z,z)
in
let t1 = Table te in
t1, update false n1 t1 m0
| _ -> t0, m0
in
if t1 <> Bot && not @@ is_table t1 then
(Format.printf "Error at location %s: expected function, but found %s.\n"
(loc e1) (string_of_value t1);
m1 |> update false n Top)
else
let m2 = step e2 env sx cs ae assertion is_rec m1 in
let n2 = construct_enode env (loc e2) |> construct_snode sx in
]
(match t1, t2 with
| Bot, _ | _, Bot -> m2
| _, Top -> m2 |> update false n Top
| _ ->
let t = find n m2 in
let cs =
if !sensitive then
if is_rec && is_func e1 then cs
else (loc e1, loc e1 |> name_of_node)
else (dx_T t1)
in
let t_temp = Table (construct_table cs (t2, t)) in
let var1 , var2 = cs in
( Format.printf " \nis_rec ? % b\n " ) is_rec ;
( Format.printf " \nAPP cs at % s : % s , % s\n " ) ( loc e1 ) var1 var2 ;
(Format.printf "\nis_rec? %b\n") is_rec;
(Format.printf "\nAPP cs at %s: %s, %s\n") (loc e1) var1 var2; *)
( if loc e1 = " 20 " then
begin
Format.printf " \n<=== Prop APP = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t1 ;
Format.printf " \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t_temp ;
Format.printf " \n " ;
end
) ;
begin
Format.printf "\n<=== Prop APP ===> %s\n" (loc e1);
pr_value Format.std_formatter t1;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t_temp;
Format.printf "\n";
end
); *)
let t1', t0 =
if optmization m2 n1 find & & optmization m2 n2 find & & optmization m2 n find then t1 , t_temp else
prop t1 t_temp
in
( if loc e1 = " 20 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter t1 ' ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t0 ;
Format.printf " \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter t1';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t0;
Format.printf "\n";
end
); *)
let t2', raw_t' =
io_T cs t0
in
let t' = get_env_list env sx m |> proj_V raw_t' in
let res_m = m2 |> update false n1 t1' |> update false n2 t2' |> update false n (stren_V t' ae) in
if is_array_set e1 & & only_shape_V t2 ' = false then
let nx = VarMap.find ( get_var_name e2 ) env in
let envx , lx , _ = get_vnode nx in
let nx = construct_snode sx nx in
let tx = find nx m in
let , t2 ' = prop_scope env sx res_m t2 ' tx in
res_m | > NodeMap.add n2 t2 ' | > NodeMap.add nx tx '
else
let nx = VarMap.find (get_var_name e2) env in
let envx, lx,_ = get_vnode nx in
let nx = construct_snode sx nx in
let tx = find nx m in
let tx', t2' = prop_scope envx env sx res_m t2' tx in
res_m |> NodeMap.add n2 t2' |> NodeMap.add nx tx'
else *)
res_m
)
| BinOp (bop, e1, e2, l) ->
( if ! debug then
begin
Format.printf " \n<=== = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Binop ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let m1 =
match bop with
| Cons ->
let rec cons_list_items m term = match term with
| BinOp (Cons, e1', e2', l') ->
let l1, t1', m1' = cons_list_items m e1' in
let l2, t2', m2' = cons_list_items m1' e2' in
l1 + l2, join_V t1' t2', m2'
| _ ->
let m' = step term env sx cs ae assertion is_rec m in
let n' = construct_enode env (loc term) |> construct_snode sx in
let t' = find n' m' in
1, t', m'
in
let len, t1', m1 = cons_list_items m e1 in
let t1 = find n1 m1 in
let t1', _ = prop t1 t1' in
m1 |> update false n1 t1'
| _ -> step e1 env sx cs ae assertion is_rec m
in
let m2 = step e2 env sx cs ae assertion is_rec m1 in
let t1 = find n1 m2 in
let n2 = construct_enode env (loc e2) |> construct_snode sx in
let t2 = find n2 m2 in
if t1 = Bot || t2 = Bot then m2
else
begin
if not @@ is_List t2 then
if not @@ ( is_Relation t1 ) then
( Format.printf " Error at location % s : expected value , but found % s.\n "
( loc e1 ) ( string_of_value t1 ) )
else ( if not @@ ( is_Relation t2 ) then
" Error at location % s : expected value , but found % s.\n "
( loc e2 ) ( string_of_value t2 ) ) ;
if not @@ (is_Relation t1) then
(Format.printf "Error at location %s: expected value, but found %s.\n"
(loc e1) (string_of_value t1))
else (if not @@ (is_Relation t2) then
Format.printf "Error at location %s: expected value, but found %s.\n"
(loc e2) (string_of_value t2));*)
let bop =
match bop, e1, e2 with
| Mod, Const _, Const _ -> Mod
| Mod, _, Const _ -> Modc
| _ -> bop
in
let t = find n m2 in
if optmization m2 n1 find & & optmization m2 n2 find & & optmization m2 n find then m2 else
let raw_t =
match bop with
list_cons_V prop t1 t2
bool_op_V bop t1 t2
| Modc ->
let td = Relation (top_R bop) in
let node_1 = e1 |> loc |> name_of_node in
let t' = arrow_V node_1 td t1 in
let t''' = op_V node_1 (str_of_const e2) bop t' in
let t = get_env_list env sx m2 |> proj_V t''' in
t
| Seq ->
t2
| _ ->
let td = Relation (top_R bop) in
let node_1 = e1 |> loc |> name_of_node in
let node_2 = e2 |> loc |> name_of_node in
let t' = arrow_V node_1 td t1 in
let t'' = arrow_V node_2 t' t2 in
( if ! debug then
begin
Format.printf " \n<=== Op = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter t '' ;
" " ;
end
) ;
begin
Format.printf "\n<=== Op binop ===> %s\n" (loc e1);
pr_value Format.std_formatter t';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t'';
Format.printf "\n";
end
); *)
let t''' = op_V node_1 node_2 bop t'' in
( if ! debug then
begin
Format.printf " \n<=== RES Op = = = > \n " ;
pr_value Format.std_formatter t '' ' ;
" " ;
end
) ;
begin
Format.printf "\n<=== RES Op binop ===> \n";
pr_value Format.std_formatter t''';
Format.printf "\n";
end
); *)
let temp_t = get_env_list env sx m2 |> proj_V t''' in
else *)
temp_t
in
( if ! debug then
begin
" \n<=== Prop = = = > % s\n " l ;
pr_value Format.std_formatter raw_t ;
" \n<<~~~~ > > \n " ;
pr_value Format.std_formatter t ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== Prop binop ===> %s\n" l;
pr_value Format.std_formatter raw_t;
Format.printf "\n<<~~~~>> \n";
pr_value Format.std_formatter t;
Format.printf "\n";
end
); *)
let _, re_t =
if is_Relation raw_t then raw_t,raw_t else
let t , raw_t = alpha_rename_Vs t raw_t in
prop raw_t t
in
( if l = " 18 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter re_t ;
Format.printf " \n<-- ae -->\n " ;
pr_value Format.std_formatter ae ;
" " ;
end
) ;
begin
Format.printf "\nRES binop for prop:\n";
pr_value Format.std_formatter re_t;
Format.printf "\n<-- ae -->\n";
pr_value Format.std_formatter ae;
Format.printf "\n";
end
); *)
let m2, re_t =
match bop with
| Cons ->
let t1l = cons_temp_lst_V t1 re_t in
let t1l', re_t' = prop t1l re_t in
let t1' = extrac_item_V (get_env_list env sx m2) t1l' in
let t2', re_t'' = prop t2 re_t' in
m2 |> update false n1 t1' |> update false n2 t2', re_t'
| Seq ->
let t2', re_t' = prop t2 re_t in
m2 |> update false n2 t2', re_t'
| _ -> m2, re_t
in
( if l = " 73 " then
begin
Format.printf " \nRES for op:\n " ;
pr_value Format.std_formatter re_t ;
" " ;
end
) ;
begin
Format.printf "\nRES for op:\n";
pr_value Format.std_formatter re_t;
Format.printf "\n";
end
); *)
( if string_of_op bop = " > " then
begin
" \nRES for test:\n " ;
pr_value Format.std_formatter re_t ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for test:\n";
pr_value Format.std_formatter re_t;
Format.printf "\n";
end
); *)
m2 |> update false n (stren_V re_t ae)
end
| UnOp (uop, e1, l) ->
( if ! debug then
begin
Format.printf " \n<=== Unop = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Unop ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let m1 = step e1 env sx cs ae assertion is_rec m in
let t1 = find n1 m1 in
if t1 = Bot then m1
else
let node_1 = e1 |> loc |> name_of_node in
let td = Relation (utop_R uop) in
let t = find n m1 in
let t' = arrow_V node_1 td t1 in
let t'' = uop_V uop node_1 t' in
let raw_t = get_env_list env sx m1 |> proj_V t'' in
else *)
let _, re_t =
if is_Relation raw_t
then raw_t, raw_t
else prop raw_t t
in
m1 |> update false n (stren_V re_t ae)
| Ite (e0, e1, e2, l, asst) ->
( if ! debug then
begin
Format.printf " \n<=== Ite = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Ite ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let n0 = construct_enode env (loc e0) |> construct_snode sx in
let m0 =
if optmization m n0 find then m else
step e0 env sx cs ae assertion is_rec m in
let t0 = find n0 m0 in
if t0 = Bot then m0 else
if not @@ is_bool_V t0 then m0 |> update false n Top else
begin
let { isast = isast; ps = pos } = asst in
if assertion && isast && not (is_bool_bot_V t0) && not (is_bool_false_V t0)
then print_loc pos else
let t_false = meet_V (extrac_bool_V t0 false) ae in
(if assertion && isast then
let i, j = AssertionPosMap.find_opt pos !sens |> Opt.get_or_else (0,0) in
sens := AssertionPosMap.add pos ((if is_bool_bot_V t0 &&
(is_asst_false e0 = false && only_shape_V ae = false)
then i + 1 else i), j + 1) !sens);
let t = find n m0 in
let m1 = step e1 env sx cs t_true assertion is_rec m0 in
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let t1 = find n1 m1 in
( if ! debug then
begin
" \n<=== Prop then = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t1 ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter ( find n m1 ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== Prop then ===> %s\n" (loc e1);
pr_value Format.std_formatter t1;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter (find n m1);
Format.printf "\n";
end
); *)
let t1', t' =
prop t1 t in
( if ! debug then
begin
" \nRES for prop:\n " ;
pr_value Format.std_formatter t1 ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter t ' ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter t1';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t';
Format.printf "\n";
end
); *)
let m2 = step e2 env sx cs t_false assertion is_rec m1 in
let n2 = construct_enode env (loc e2) |> construct_snode sx in
let t2 = find n2 m2 in
( if ! debug then
begin
" \n<=== Prop else = = = > % s\n " ( loc e2 ) ;
pr_value Format.std_formatter t2 ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter ( find n m2 ) ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== Prop else ===> %s\n" (loc e2);
pr_value Format.std_formatter t2;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter (find n m2);
Format.printf "\n";
end
); *)
let t2', t'' =
if optmization m2 n2 find & & optmization m2 n find then t1 , ( find n m2 ) else
prop t2 t in
( if ! debug then
begin
" \nRES for prop:\n " ;
pr_value Format.std_formatter t2 ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter t '' ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter t2';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t'';
Format.printf "\n";
end
); *)
( if ( loc e1 ) = " 63 " then
begin
" \n<=== join then else = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t ' ;
" \n<<~~~~ > > % s\n " ( loc e2 ) ;
pr_value Format.std_formatter t '' ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== join then else ===> %s\n" (loc e1);
pr_value Format.std_formatter t';
Format.printf "\n<<~~~~>> %s\n" (loc e2);
pr_value Format.std_formatter t'';
Format.printf "\n";
end
); *)
( if loc e0 = " 10 " then
begin
" \n<=== ite ae = = = > % s % b\n " l ( only_shape_V ae ) ;
pr_value Format.std_formatter ae ;
" \n<<~~ then part ~~>>\n " ;
pr_value Format.std_formatter t_true ;
" \n<----->\n " ;
pr_value Format.std_formatter t1 ' ;
" \n<<~~ else part ~~>>\n " ;
pr_value Format.std_formatter t_false ;
Format.printf " \n<----->\n " ;
pr_value Format.std_formatter t2 ' ;
" " ;
end
) ;
begin
Format.printf "\n<=== ite ae ===> %s %b\n" l (only_shape_V ae);
pr_value Format.std_formatter ae;
Format.printf "\n<<~~ then part ~~>>\n";
pr_value Format.std_formatter t_true;
Format.printf "\n<----->\n";
pr_value Format.std_formatter t1';
Format.printf "\n<<~~ else part ~~>>\n";
pr_value Format.std_formatter t_false;
Format.printf "\n<----->\n";
pr_value Format.std_formatter t2';
Format.printf "\n";
end
); *)
let t1' = stren_ite_V t1' t_true in
let t2' = stren_ite_V t2' t_false in
( if loc e0 = " 10 " then
begin
" \n<=== RES for ae = = = > % s\n " l ;
pr_value Format.std_formatter t1 ' ;
" \n<<~~~~>>\n " ;
pr_value Format.std_formatter t2 ' ;
" " ;
end
) ;
begin
Format.printf "\n<=== RES for ae ===> %s\n" l;
pr_value Format.std_formatter t1';
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t2';
Format.printf "\n";
end
); *)
let t_n' = join_V (stren_V t' ae) (stren_V t'' ae) in
( if ( loc e1 ) = " 63 " then
begin
" \nRES for join then else:\n " ;
pr_value Format.std_formatter t_n ' ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for join then else:\n";
pr_value Format.std_formatter t_n';
Format.printf "\n";
end
); *)
let res_m = m2 |> update false n1 t1' |> update false n2 t2' |> update false n t_n' in
res_m
end
| Rec (f_opt, (x, lx), e1, l) ->
( if ! debug then
begin
Format.printf " \n<=== Func = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Func ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let t0 = find n m in
let t =
match t0 with
| Bot ->
let te = let z = fresh_z () in init_T (z,z) in
Table te
| _ -> t0
in
let cs' = cs in
let is_rec' = Opt.exist f_opt || is_rec in
step_func (fun cs (tl, tr) m' ->
if tl = Bot then m' |> update false n t
else if tr = Top then top_M m' else
begin
let _, var = cs in
let f_nf_opt =
Opt.map (fun (f, lf) -> f, (construct_vnode env lf cs, true)) f_opt
in
let nx = construct_vnode env lx cs in
let env' = env |> VarMap.add x (nx, false) in
let nx = construct_snode x nx in
let env1 =
env' |>
(Opt.map (uncurry VarMap.add) f_nf_opt |>
Opt.get_or_else (fun env -> env))
in
let n1 = construct_enode env1 (loc e1) |> construct_snode x in
let tx = find nx m in
let ae' = if (x <> "_" && is_Relation tx) || is_List tx then
if only_shape_V tx then ae else
(arrow_V x ae tx) else ae in
let t1 = if x = "_" then find n1 m else replace_V (find n1 m) x var in
let prop_t = Table (construct_table cs (tx, t1)) in
( if l = " 20 " then
begin
Format.printf " \n<=== Prop lamb = = = > % s % s\n " lx ( loc e1 ) ;
pr_value Format.std_formatter prop_t ;
Format.printf " \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter t ;
end
) ;
begin
Format.printf "\n<=== Prop lamb ===> %s %s\n" lx (loc e1);
pr_value Format.std_formatter prop_t;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter t;
end
); *)
let px_t, t1 = prop_scope env1 env' x m prop_t t in
( if l = " 20 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter px_t ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter t1 ;
Format.printf " \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter px_t;
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter t1;
Format.printf "\n";
end
); *)
let nf_t2_tf'_opt =
Opt.map (fun (_, (nf, bf)) ->
let envf, lf, fcs = get_vnode nf in
let nf = construct_snode x nf in
let tf = find nf m in
( if lf = " 4 " then
begin
Format.printf " \n<=== Prop um = = = > % s\n " l ;
pr_value Format.std_formatter t ;
" \n<<~~~~ > > % s\n " lf ;
pr_value Format.std_formatter tf ;
" " ;
end
) ;
begin
Format.printf "\n<=== Prop um ===> %s\n" l;
pr_value Format.std_formatter t;
Format.printf "\n<<~~~~>> %s\n" lf;
pr_value Format.std_formatter tf;
Format.printf "\n";
end
); *)
let t2, tf' = prop_scope env' envf x m t tf in
( if lf = " 4 " then
begin
Format.printf " \nRES for prop:\n " ;
pr_value Format.std_formatter t2 ;
Format.printf " \n<<~~~~>>\n " ;
pr_value Format.std_formatter tf ' ;
" \n " ;
end
) ;
begin
Format.printf "\nRES for prop:\n";
pr_value Format.std_formatter t2;
Format.printf "\n<<~~~~>>\n";
pr_value Format.std_formatter tf';
Format.printf "\n";
end
); *)
nf, t2, tf') f_nf_opt
in
let tx', t1' = io_T cs px_t in
let m1 = m |> update is_rec' nx tx' |> update false n1 (if x = "_" then t1' else replace_V t1' var x) |>
(Opt.map (fun (nf, t2, tf') -> fun m' -> m' |> update true nf tf' |> update false n (join_V t1 t2))
nf_t2_tf'_opt |> Opt.get_or_else (update false n t1)) in
let cs = if is_rec' && x = "_" then cs' else cs in
let m1' = step e1 env1 x cs ae' assertion is_rec' m1 in
let t1 = if x = " _ " then find n1 m1 ' else replace_V ( find n1 m1 ' ) x var in
let prop_t = Table ( construct_table cs ( tx , t1 ) ) in
let px_t , t1 = prop_scope env1 env ' x m1 ' prop_t t in
let nf_t2_tf'_opt =
Opt.map ( fun ( _ , ( nf , bf ) ) - >
let envf , lf , fcs = get_vnode nf in
let nf = construct_snode x nf in
let tf = find nf m1 ' in
let t2 , tf ' = prop_scope env ' envf x m1 ' t tf in
nf , t2 , tf ' ) f_nf_opt
in
let ' , t1 ' = io_T cs px_t in
let m1 ' = m1 ' | > update nx tx ' | > update n1 ( if x = " _ " then t1 ' else replace_V t1 ' var x ) | >
( Opt.map ( fun ( nf , t2 , tf ' ) - > fun m ' - > m ' | > update nf tf ' | > update n ( join_V t1 t2 ) )
nf_t2_tf'_opt | > Opt.get_or_else ( update n t1 ) ) in
let prop_t = Table (construct_table cs (tx, t1)) in
let px_t, t1 = prop_scope env1 env' x m1' prop_t t in
let nf_t2_tf'_opt =
Opt.map (fun (_, (nf, bf)) ->
let envf, lf, fcs = get_vnode nf in
let nf = construct_snode x nf in
let tf = find nf m1' in
let t2, tf' = prop_scope env' envf x m1' t tf in
nf, t2, tf') f_nf_opt
in
let tx', t1' = io_T cs px_t in
let m1' = m1' |> update nx tx' |> update n1 (if x = "_" then t1' else replace_V t1' var x) |>
(Opt.map (fun (nf, t2, tf') -> fun m' -> m' |> update nf tf' |> update n (join_V t1 t2))
nf_t2_tf'_opt |> Opt.get_or_else (update n t1)) in *)
join_M m1' m'
end
) t (m |> update false n t |> Hashtbl.copy)
| TupleLst (tlst, l) ->
( if ! debug then
begin
Format.printf " \n<=== Tuple = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Tuple ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let t = find n m in
if List.length tlst = 0 then
let t' = let ct = init_V_c UnitLit in
join_V t ct in
m |> update false n t'
else
let tp, m' = List.fold_right (fun e (t, m) ->
let m' = step e env sx cs ae assertion is_rec m in
let ne = construct_enode env (loc e) |> construct_snode sx in
let te = find ne m' in
let t' = add_tuple_item_V t te in
t', m'
) tlst (Tuple [], m) in
let _, t' = prop tp t in
m' |> update false n t'
| PatMat (e, patlst, l) ->
( if ! debug then
begin
Format.printf " \n<=== Pattern Match = = = > \n " ;
pr_exp true Format.std_formatter term ;
Format.printf " " ;
end
) ;
begin
Format.printf "\n<=== Pattern Match ===>\n";
pr_exp true Format.std_formatter term;
Format.printf "\n";
end
); *)
let ne = construct_enode env (loc e) |> construct_snode sx in
let m' = step e env sx cs ae assertion is_rec m in
let te = find ne m' in
if te = Bot || only_shape_V te then m' else
let m'' = List.fold_left (fun m (Case (e1, e2)) ->
( if ! debug then
begin
" \n<=== Pattern = = = > \n " ;
pr_exp true Format.std_formatter e1 ;
" " ;
pr_exp true Format.std_formatter e2 ;
" \n " ;
end
) ;
begin
Format.printf "\n<=== Pattern ===>\n";
pr_exp true Format.std_formatter e1;
Format.printf "\n";
pr_exp true Format.std_formatter e2;
Format.printf "\n";
end
); *)
match e1 with
| Const (c, l') ->
let m1 = step e1 env sx cs ae assertion is_rec m in
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let te, t1 = find ne m1, find n1 m1 in
let te, t1 = alpha_rename_Vs te t1 in
if leq_V te t1 then m' else
let t1 = if is_List te then
item_shape_V te t1
else t1 in
( if true then
begin
" % s\n " ( loc e1 ) ;
pr_exp true Format.std_formatter e1 ;
" " ;
pr_value Format.std_formatter t1 ;
" \n<<~~~~ > > % s\n " ( loc e ) ;
pr_value Format.std_formatter te ;
" " ;
pr_value Format.std_formatter ( join_V t1 te ) ;
" " ;
end
) ;
begin
Format.printf "\n Pattern %s\n" (loc e1);
pr_exp true Format.std_formatter e1;
Format.printf "\n";
pr_value Format.std_formatter t1;
Format.printf "\n<<~~~~>> %s\n" (loc e);
pr_value Format.std_formatter te;
Format.printf "\n";
pr_value Format.std_formatter (join_V t1 te);
Format.printf "\n";
end
); *)
let m1 = m1 |> update false n1 t1 in
let b =
sat_leq_V t1 te
in
let n1 = construct_enode env (loc e1) |> construct_snode sx in
let n2 = construct_enode env (loc e2) |> construct_snode sx in
( if true then
begin
Format.printf " \npattern ae : % b\n " b ;
pr_value Format.std_formatter ae ;
" " ;
end
) ;
begin
Format.printf "\npattern ae: %b\n" b;
pr_value Format.std_formatter ae;
Format.printf "\n";
end
); *)
let ae' = if not b then bot_relation_V Int else
arrow_V (loc e) ae (find n1 m1) in
( if true then
begin
Format.printf " \nRES for ae:\n " ;
pr_value Format.std_formatter ae ' ;
" " ;
end
) ;
begin
Format.printf "\nRES for ae:\n";
pr_value Format.std_formatter ae';
Format.printf "\n";
end
); *)
let m2 = step e2 env sx cs ae' assertion is_rec m1 in
if not b then
let t, t2 = find n m2, find n2 m2 in
let t2', t' = prop t2 t in
m2 |> update false n1 t1 |> update false n2 t2' |> update false n t'
else
let te, t, t1, t2 = find ne m2, find n m2, find n1 m2, find n2 m2 in
let t1', te' = let te, t1 = alpha_rename_Vs te t1 in
t1, join_V t1 te in
let t2', t' = prop t2 t in
m2 |> update false ne te' |> update false n1 t1'
|> update false n2 t2' |> update false n t'
| Var (x, l') ->
let n1 = construct_vnode env l' (sx,sx) in
let env1 = env |> VarMap.add x (n1, false) in
let n1 = construct_snode x n1 in
let t1 = find n1 m in let te = find ne m in
let _, t1' = prop te t1 in
let m1 = m |> update false n1 t1' in
let m2 = step e2 env1 sx cs ae assertion is_rec m1 in
let n2 = construct_enode env1 (loc e2) |> construct_snode sx in
let t = find n m2 in let t2 = find n2 m2 in
let t2', t' = prop t2 t in
m2 |> update false n2 t2' |> update false n t'
| BinOp (Cons, el, er, l') ->
( if true then
begin
" \n<=== Prop then = = = > % s\n " ( loc e1 ) ;
pr_value Format.std_formatter t1 ;
" \n<<~~~~ > > % s\n " l ;
pr_value Format.std_formatter ( find n m1 ) ;
" " ;
end
) ;
begin
Format.printf "\n<=== Prop then ===> %s\n" (loc e1);
pr_value Format.std_formatter t1;
Format.printf "\n<<~~~~>> %s\n" l;
pr_value Format.std_formatter (find n m1);
Format.printf "\n";
end
); *)
let ml, envl = list_var_item el sx cs m env ne true 0 in
( if ! debug then
begin
" \n<=== Pattern binop = = = > \n " ;
pr_exp true Format.std_formatter er ;
" " ;
end
) ;
begin
Format.printf "\n<=== Pattern binop ===>\n";
pr_exp true Format.std_formatter er;
Format.printf "\n";
end
); *)
let mr, envr = list_var_item er sx cs ml envl ne false 1 in
let nr = construct_enode envr (loc er) |> construct_snode sx in
let n2 = construct_enode envr (loc e2) |> construct_snode sx in
let n1 = construct_enode envr l' |> construct_snode sx in
let m1 = step e1 envr sx cs ae assertion is_rec mr in
let te, t1 = find ne m1, find n1 m1 in
let te, t1 = alpha_rename_Vs te t1 in
let ae' =
let ae = arrow_V (loc e) ae t1 in
arrow_V (loc er) ae (find nr m1)
in
let m2 = step e2 envr sx cs ae' assertion is_rec m1 in
let te, t, t1, t2 = find ne m2, find n m2, find n1 m2, find n2 m2 in
let t1', te' =
let te, t1 = alpha_rename_Vs te t1 in
prop t1 te
in
let t2', t' = prop t2 t in
m2 |> update false ne te' |> update false n1 t1'
|> update false n2 t2' |> update false n t'
| TupleLst (termlst, l') ->
let n1 = construct_enode env l' |> construct_snode sx in
let t1 =
let raw_t1 = find n1 m in
if is_tuple_V raw_t1 then raw_t1
else
let u' = List.init (List.length termlst) (fun _ ->
Bot) in Tuple u' in
let te = find ne m in
let te, t1 = alpha_rename_Vs te t1 in
let tlst = get_tuple_list_V t1 in
let tllst = te |> get_tuple_list_V in
let env', m', tlst', tllst' = List.fold_left2 (fun (env, m, li, llst) e (ti, tlsti) ->
match e with
| Var (x, l') ->
let nx = construct_vnode env l' cs in
let env1 = env |> VarMap.add x (nx, false) in
let nx = construct_snode sx nx in
let tx = find nx m in
let ti', tx' = prop ti tx in
let tlsti', ti'' = prop tlsti ti in
let m' = m |> update false nx tx' in
env1, m', (join_V ti' ti'') :: li, tlsti' :: llst
| _ -> raise (Invalid_argument "Tuple only for variables now")
) (env, m, [], []) termlst (zip_list tlst tllst) in
let tlst', tllst' = List.rev tlst', List.rev tllst' in
let t1', te' = Tuple tlst', Tuple tllst' in
let _, t1' = prop t1' t1 in
let te', _ = prop te te' in
let m1 = m |> update false n1 t1' |> update false ne te' in
let m2 = step e2 env' sx cs ae assertion is_rec m1 in
let n2 = construct_enode env' (loc e2) |> construct_snode sx in
let t = find n m2 in let t2 = find n2 m2 in
let t2', t' = prop t2 t in
m2 |> update false n2 t2' |> update false n t'
| _ -> raise (Invalid_argument "Pattern should only be either constant, variable, or list cons")
) (update false ne te m' |> Hashtbl.copy) patlst in
m''
let step x1 x2 x3 x4 x5 x6 x7 = measure_call "step" (step x1 x2 x3 x4 x5 x6 x7)
let widening k (m1:exec_map_t) (m2:exec_map_t): exec_map_t =
if k > !delay_wid then wid_M m1 m2 else join_M m1 m2
let widening k m = measure_call "widening" (widening k m)
let narrowing (m1:exec_map_t) (m2:exec_map_t): exec_map_t =
meet_M m1 m2
* Fixpoint loop
let rec fix stage env e (k: int) (m:exec_map_t) (assertion:bool): string * exec_map_t =
(if !out_put_level = 0 then
begin
let process = match stage with
| Widening -> "Wid"
| Narrowing -> "Nar"
in
Format.printf "%s step %d\n" process k;
print_exec_map m;
end);
if k > 40 then exit 0 else
let ae = VarMap.fold (fun var (n, b) ae ->
let n = construct_snode "" n in
let find n m = NodeMap.find_opt n m |> Opt.get_or_else Bot in
let t = find n m in
if is_Relation t then
arrow_V var ae t else ae
) env (Relation (top_R Plus)) in
let m_t = Hashtbl.copy m in
let m' = step e env "" ("","") ae assertion false m_t in
if k < 0 then if k = -1 then "", m' else fix stage env e (k+1) m' assertion else
if k > 2 then Hashtbl.reset ! pre_m ;
pre_m : = m ;
pre_m := m; *)
let m'' = if stage = Widening then widening k m m' else narrowing m m' in
let comp = if stage = Widening then leq_M m'' m else leq_M m m'' in
if comp then
begin
if assertion || !narrow then
let s = AssertionPosMap.fold (fun pos (i, j) s ->
if i = j then try print_loc pos with
Input_Assert_failure s -> s else s) !sens "The input program is safe\n" in
s, m
else
begin
with Input_Assert_failure s -> s, m
end
end
let s e =
( if ! debug then
begin
" % % Pre vals : % % \n " ;
pr_pre_def_vars Format.std_formatter ;
" \n\n " ;
end ) ;
begin
Format.printf "%% Pre vals: %%\n";
pr_pre_def_vars Format.std_formatter;
Format.printf "\n\n";
end); *)
let envt, m0' = pref_M env0 (Hashtbl.copy m0) in
let fv_e = fv e in
let envt =
VarMap.filter
(fun x (n, _) ->
if StringSet.mem x fv_e then true
else
let n = construct_snode "" n in
(Hashtbl.remove m0' n; false)) envt
in
thresholdsSet := !thresholdsSet |> ThresholdsSetType.add 0 |> ThresholdsSetType.add 111 |> ThresholdsSetType.add 101
|> ThresholdsSetType.add 2 |> ThresholdsSetType.add 4 |> ThresholdsSetType.add (-1) |> ThresholdsSetType.add (-2);
pre_m : = m0 ' ;
let check_str, m =
let s1, m1 = (fix Widening envt e 0 m0' false) in
if !narrow then
begin
narrow := false;
let _ , m1 = fix e ( -10 ) m1 false in ( * step^10(fixw ) < = fixw
let m1 = m1 |> reset in
let s2, m2 = fix Narrowing envt e 0 m1 false in
if eq_PM m0 m2 then s2, m2
else exit 0
end
else s1, m1
in
if !out_put_level = 1 then
begin
Format.printf "Final step \n";
print_exec_map m;
end;
Format.printf "%s" check_str;
m
|
842f9b661fe8be86598dd92d12b573abafa954b363154d173191302afdd25086 | arachne-framework/factui | txdata.cljc | (ns factui.impl.txdata
"Tools for converting Datomic-style txdata to sets of Clara facts"
(:require [factui.facts :as f]
[clojure.spec.alpha :as s]))
(s/def ::txdata (s/coll-of ::tx-item :min-count 1))
(s/def ::entity-id (s/or :eid pos-int?
:tempid any?))
(s/def ::attr-name qualified-keyword?)
(s/def ::primitive-value (complement coll?))
(s/def ::fn qualified-keyword?)
(s/def ::list (s/cat :fn ::fn :args (s/* any?)))
(s/def ::tx-item (s/or :list ::list
:map ::map))
(s/def ::map (s/map-of ::attr-name (s/or :map ::map
:coll (s/coll-of
(s/or :primitive ::primitive-value
:map ::map)
:min-count 1)
:value ::primitive-value)
:min-count 1))
(let [next (atom -10001)]
(defn next-tempid
"Return a unique tempid value"
[]
(swap! next dec)))
(declare map->lists)
(defn- map-child
"Generate a seq of list txdata for a map child of the given entity ID"
[parent-eid parent-attr child-map]
(let [[child-eid child-lists] (map->lists child-map)]
(conj child-lists
[:db/add parent-eid parent-attr child-eid])))
(defn- map->lists
"Convert map txdata to a tuple of [eid list-txdata]"
[txmap]
(let [eid (or (second (:db/id txmap)) (next-tempid))
txmap (dissoc txmap :db/id)]
[eid
(mapcat (fn [[attr [type value]]]
(case type
:map (map-child eid attr value)
:coll (mapcat (fn [[type value]]
(case type
:primitive [[:db/add eid attr value]]
:map (map-child eid attr value)))
value)
:value [[:db/add eid attr value]]))
txmap)]))
(defn- to-list
"Convert a conformed txitem to a seq of list-form txdata"
[[type txitem]]
(case type
:list [(s/unform ::list txitem)]
:map (second (map->lists txitem))))
(defn operations
"Given Datomic-style txdata, convert to a set of operation tuples.
If an entity ID is a positive integer, it is presumed to be a concrete
entity ID, otherwise it will be treated as a tempid."
[txdata]
(let [conformed (s/conform ::txdata txdata)]
(when (= ::s/invalid conformed) (s/assert* ::txdata txdata))
(->> conformed
(mapcat to-list)))) | null | https://raw.githubusercontent.com/arachne-framework/factui/818ea79d7f84dfe80ad23ade0b6b2ed5bb1c6287/src/factui/impl/txdata.cljc | clojure | (ns factui.impl.txdata
"Tools for converting Datomic-style txdata to sets of Clara facts"
(:require [factui.facts :as f]
[clojure.spec.alpha :as s]))
(s/def ::txdata (s/coll-of ::tx-item :min-count 1))
(s/def ::entity-id (s/or :eid pos-int?
:tempid any?))
(s/def ::attr-name qualified-keyword?)
(s/def ::primitive-value (complement coll?))
(s/def ::fn qualified-keyword?)
(s/def ::list (s/cat :fn ::fn :args (s/* any?)))
(s/def ::tx-item (s/or :list ::list
:map ::map))
(s/def ::map (s/map-of ::attr-name (s/or :map ::map
:coll (s/coll-of
(s/or :primitive ::primitive-value
:map ::map)
:min-count 1)
:value ::primitive-value)
:min-count 1))
(let [next (atom -10001)]
(defn next-tempid
"Return a unique tempid value"
[]
(swap! next dec)))
(declare map->lists)
(defn- map-child
"Generate a seq of list txdata for a map child of the given entity ID"
[parent-eid parent-attr child-map]
(let [[child-eid child-lists] (map->lists child-map)]
(conj child-lists
[:db/add parent-eid parent-attr child-eid])))
(defn- map->lists
"Convert map txdata to a tuple of [eid list-txdata]"
[txmap]
(let [eid (or (second (:db/id txmap)) (next-tempid))
txmap (dissoc txmap :db/id)]
[eid
(mapcat (fn [[attr [type value]]]
(case type
:map (map-child eid attr value)
:coll (mapcat (fn [[type value]]
(case type
:primitive [[:db/add eid attr value]]
:map (map-child eid attr value)))
value)
:value [[:db/add eid attr value]]))
txmap)]))
(defn- to-list
"Convert a conformed txitem to a seq of list-form txdata"
[[type txitem]]
(case type
:list [(s/unform ::list txitem)]
:map (second (map->lists txitem))))
(defn operations
"Given Datomic-style txdata, convert to a set of operation tuples.
If an entity ID is a positive integer, it is presumed to be a concrete
entity ID, otherwise it will be treated as a tempid."
[txdata]
(let [conformed (s/conform ::txdata txdata)]
(when (= ::s/invalid conformed) (s/assert* ::txdata txdata))
(->> conformed
(mapcat to-list)))) | |
638f43b8e2efcf1c4ef473db2511889055732949ed2687998240cf78ef57cb22 | niklasl/clj-rdfa | dom.clj | (ns rdfa.dom)
(defprotocol DomAccess
(get-name [this])
(get-attr [this attr-name])
(get-ns-map [this])
(is-root? [this])
(find-by-tag [this tag])
(get-child-elements [this])
(get-text [this])
(get-inner-xml [this xmlns-map lang]))
| null | https://raw.githubusercontent.com/niklasl/clj-rdfa/5b49a2106bb7ebb2497b156bb27ec479fb4d66ec/src/rdfa/dom.clj | clojure | (ns rdfa.dom)
(defprotocol DomAccess
(get-name [this])
(get-attr [this attr-name])
(get-ns-map [this])
(is-root? [this])
(find-by-tag [this tag])
(get-child-elements [this])
(get-text [this])
(get-inner-xml [this xmlns-map lang]))
| |
f7a8bb1832c3c7252439abc9a3beaed6e780ace0b5afdb970752cb9c1d82ff31 | seek-oss/serverless-haskell | SNSEventSpec.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module AWSLambda.Events.SNSEventSpec where
import AWSLambda.Events.MessageAttribute
import AWSLambda.Events.Records
import AWSLambda.Events.S3Event
import AWSLambda.Events.SNSEvent
import Data.Aeson
import Data.Aeson.Embedded
import Data.Aeson.TextValue
import Data.ByteString.Lazy (ByteString)
import qualified Data.HashMap.Strict as HashMap
import Data.Text (Text)
import Data.Time.Calendar
import Data.Time.Clock
import Network.AWS.S3 as S3
import Text.RawString.QQ
import Test.Hspec
spec :: Spec
spec =
describe "SNSEvent" $ do
it "parses sample text event" $
decode sampleSNSJSON `shouldBe` Just sampleSNSEvent
it "parses sample embedded S3 event" $
decode sampleSNSS3JSON `shouldBe` Just sampleSNSS3Event
sampleSNSJSON :: ByteString
sampleSNSJSON = [r|
{
"Records": [
{
"EventVersion": "1.0",
"EventSubscriptionArn": "eventsubscriptionarn",
"EventSource": "aws:sns",
"Sns": {
"SignatureVersion": "1",
"Timestamp": "1970-01-01T00:00:00.000Z",
"Signature": "EXAMPLE",
"SigningCertUrl": "EXAMPLE",
"MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
"Message": "Hello from SNS!",
"MessageAttributes": {
"Test": {
"Type": "String",
"Value": "TestString"
},
"TestBinary": {
"Type": "Binary",
"Value": "TestBinary"
}
},
"Type": "Notification",
"UnsubscribeUrl": "EXAMPLE",
"TopicArn": "topicarn",
"Subject": "TestInvoke"
}
}
]
}
|]
sampleSNSEvent :: SNSEvent Text
sampleSNSEvent =
RecordsEvent
[ SNSRecord
{ _srEventVersion = "1.0"
, _srEventSubscriptionArn = "eventsubscriptionarn"
, _srEventSource = "aws:sns"
, _srSns =
SNSMessage
{ _smMessage = "Hello from SNS!"
, _smMessageAttributes =
HashMap.fromList
[ ( "Test"
, MessageAttribute
{ _maType = "String"
, _maValue = "TestString"
})
, ( "TestBinary"
, MessageAttribute
{ _maType = "Binary"
, _maValue = "TestBinary"
})
]
, _smMessageId = "95df01b4-ee98-5cb9-9903-4c221d41eb5e"
, _smSignature = "EXAMPLE"
, _smSignatureVersion = "1"
, _smSigningCertUrl = "EXAMPLE"
, _smSubject = "TestInvoke"
, _smTimestamp = UTCTime (fromGregorian 1970 1 1) (secondsToDiffTime 0)
, _smTopicArn = "topicarn"
, _smType = "Notification"
, _smUnsubscribeUrl = "EXAMPLE"
}
}
]
sampleSNSS3JSON :: ByteString
sampleSNSS3JSON = [r|
{"Records":
[
{"EventSource":"aws:sns",
"EventVersion":"1.0",
"EventSubscriptionArn":"arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent:23e2d254-e8bb-4db5-92ce-d917e5aad090",
"Sns":{
"Type":"Notification",
"MessageId":"89f6fe8b-a751-5dcd-8e0c-afbd75420455",
"TopicArn":"arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent",
"Subject":"Amazon S3 Notification",
"Message": "{\"Records\":[{\"eventVersion\":\"2.0\",\"eventSource\":\"aws:s3\",\"awsRegion\":\"ap-southeast-2\",\"eventTime\":\"2017-03-06T02:56:19.713Z\",\"eventName\":\"ObjectCreated:Put\",\"userIdentity\":{\"principalId\":\"AWS:DFLKSDFLKJ987SDFLJJDJ:some-principal-id\"},\"requestParameters\":{\"sourceIPAddress\":\"192.168.0.1\"},\"responseElements\":{\"x-amz-request-id\":\"324098EDFLK0894F\",\"x-amz-id-2\":\"xsdSDF/pgAl401Fz3UIATJ5/didfljDSFDSFsdfkjsdfl8JdsfLSDF89ldsf7SDF898jsdfljiA=\"},\"s3\":{\"s3SchemaVersion\":\"1.0\",\"configurationId\":\"SomeS3Event:Created\",\"bucket\":{\"name\":\"some-bucket\",\"ownerIdentity\":{\"principalId\":\"A3O1SDFLKJIJXU\"},\"arn\":\"arn:aws:s3:::some-bucket\"},\"object\":{\"key\":\"path/to/some/object\",\"size\":53598442,\"eTag\":\"6b1f72b9e81e4d6fcd3e0c808e8477f8\",\"sequencer\":\"0058BCCFD25C798E7B\"}}}]}",
"Timestamp":"2017-03-06T02:56:19.834Z",
"SignatureVersion":"1",
"Signature":"aybEgnTjKzSbC2puHxho7SUnYOje4SjBoCyt0Q13bMWyp7M64+EU6jzi7P01+gSIuBFyYPsHreSmyqGMRSxbFuzn7rG5JcVGN0901U3CRXdk42eh03je8evRvs/Oa7TJlhpCTEDDOScalCWbIH0RthYONQpPR01nEgaNKj3e8YVJqyRQV+4RbU3YWJOj+Spyi4u1hOC9PLUv4BH7U80nbhbOe9EwgX0zpeNU1WBRbEpqPoACm+7/uB0w79qFBKjB/Q7OWc1kASUZV9q8bz03yceoQeVvza0QGhPsnSXi49sn1mLWQOFS4KvgbJIC/Qk7H036ShrDioP6pP+UEg6kow==",
"SigningCertUrl":"-southeast-2.amazonaws.com/SimpleNotificationService-b95095beb82e8f6a046b3aafc7f4149a.pem",
"UnsubscribeUrl":"-southeast-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent:23e2d254-e8bb-4db5-92ce-d917e5aad090",
"MessageAttributes":{}
}
}
]
}
|]
sampleSNSS3Event :: SNSEvent (Embedded S3Event)
sampleSNSS3Event =
RecordsEvent
{ _reRecords =
[ SNSRecord
{ _srEventVersion = "1.0"
, _srEventSubscriptionArn =
"arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent:23e2d254-e8bb-4db5-92ce-d917e5aad090"
, _srEventSource = "aws:sns"
, _srSns =
SNSMessage
{ _smMessage =
TextValue
{ _unTextValue =
Embedded
{ _unEmbed =
RecordsEvent
{ _reRecords =
[ S3EventNotification
{ _senAwsRegion = Sydney
, _senEventName = S3ObjectCreatedPut
, _senEventSource = "aws:s3"
, _senEventTime =
UTCTime
(fromGregorian 2017 3 6)
(picosecondsToDiffTime 10579713000000000)
, _senEventVersion = "2.0"
, _senRequestParameters =
RequestParametersEntity
{ _rpeSourceIPAddress = "192.168.0.1"
}
, _senResponseElements =
ResponseElementsEntity
{ _reeXAmzId2 =
"xsdSDF/pgAl401Fz3UIATJ5/didfljDSFDSFsdfkjsdfl8JdsfLSDF89ldsf7SDF898jsdfljiA="
, _reeXAmzRequestId = "324098EDFLK0894F"
}
, _senS3 =
S3Entity
{ _seBucket =
S3BucketEntity
{ _sbeArn = "arn:aws:s3:::some-bucket"
, _sbeName = BucketName "some-bucket"
, _sbeOwnerIdentity =
UserIdentityEntity
{ _uiePrincipalId = "A3O1SDFLKJIJXU"
}
}
, _seConfigurationId = "SomeS3Event:Created"
, _seObject =
S3ObjectEntity
{ _soeETag =
Just (ETag "6b1f72b9e81e4d6fcd3e0c808e8477f8")
, _soeKey = ObjectKey "path/to/some/object"
, _soeSize = Just 53598442
, _soeSequencer = "0058BCCFD25C798E7B"
, _soeVersionId = Nothing
}
, _seS3SchemaVersion = "1.0"
}
, _senUserIdentity =
UserIdentityEntity
{ _uiePrincipalId =
"AWS:DFLKSDFLKJ987SDFLJJDJ:some-principal-id"
}
}
]
}
}
}
, _smMessageAttributes = HashMap.fromList []
, _smMessageId = "89f6fe8b-a751-5dcd-8e0c-afbd75420455"
, _smSignature =
"aybEgnTjKzSbC2puHxho7SUnYOje4SjBoCyt0Q13bMWyp7M64+EU6jzi7P01+gSIuBFyYPsHreSmyqGMRSxbFuzn7rG5JcVGN0901U3CRXdk42eh03je8evRvs/Oa7TJlhpCTEDDOScalCWbIH0RthYONQpPR01nEgaNKj3e8YVJqyRQV+4RbU3YWJOj+Spyi4u1hOC9PLUv4BH7U80nbhbOe9EwgX0zpeNU1WBRbEpqPoACm+7/uB0w79qFBKjB/Q7OWc1kASUZV9q8bz03yceoQeVvza0QGhPsnSXi49sn1mLWQOFS4KvgbJIC/Qk7H036ShrDioP6pP+UEg6kow=="
, _smSignatureVersion = "1"
, _smSigningCertUrl =
"-southeast-2.amazonaws.com/SimpleNotificationService-b95095beb82e8f6a046b3aafc7f4149a.pem"
, _smSubject = "Amazon S3 Notification"
, _smTimestamp =
UTCTime
(fromGregorian 2017 3 6)
(picosecondsToDiffTime 10579834000000000)
, _smTopicArn = "arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent"
, _smType = "Notification"
, _smUnsubscribeUrl =
"-southeast-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent:23e2d254-e8bb-4db5-92ce-d917e5aad090"
}
}
]
}
| null | https://raw.githubusercontent.com/seek-oss/serverless-haskell/dbea96e657e23fd4a3fef03bdf182f060dc2590d/test/AWSLambda/Events/SNSEventSpec.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes # |
module AWSLambda.Events.SNSEventSpec where
import AWSLambda.Events.MessageAttribute
import AWSLambda.Events.Records
import AWSLambda.Events.S3Event
import AWSLambda.Events.SNSEvent
import Data.Aeson
import Data.Aeson.Embedded
import Data.Aeson.TextValue
import Data.ByteString.Lazy (ByteString)
import qualified Data.HashMap.Strict as HashMap
import Data.Text (Text)
import Data.Time.Calendar
import Data.Time.Clock
import Network.AWS.S3 as S3
import Text.RawString.QQ
import Test.Hspec
spec :: Spec
spec =
describe "SNSEvent" $ do
it "parses sample text event" $
decode sampleSNSJSON `shouldBe` Just sampleSNSEvent
it "parses sample embedded S3 event" $
decode sampleSNSS3JSON `shouldBe` Just sampleSNSS3Event
sampleSNSJSON :: ByteString
sampleSNSJSON = [r|
{
"Records": [
{
"EventVersion": "1.0",
"EventSubscriptionArn": "eventsubscriptionarn",
"EventSource": "aws:sns",
"Sns": {
"SignatureVersion": "1",
"Timestamp": "1970-01-01T00:00:00.000Z",
"Signature": "EXAMPLE",
"SigningCertUrl": "EXAMPLE",
"MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
"Message": "Hello from SNS!",
"MessageAttributes": {
"Test": {
"Type": "String",
"Value": "TestString"
},
"TestBinary": {
"Type": "Binary",
"Value": "TestBinary"
}
},
"Type": "Notification",
"UnsubscribeUrl": "EXAMPLE",
"TopicArn": "topicarn",
"Subject": "TestInvoke"
}
}
]
}
|]
sampleSNSEvent :: SNSEvent Text
sampleSNSEvent =
RecordsEvent
[ SNSRecord
{ _srEventVersion = "1.0"
, _srEventSubscriptionArn = "eventsubscriptionarn"
, _srEventSource = "aws:sns"
, _srSns =
SNSMessage
{ _smMessage = "Hello from SNS!"
, _smMessageAttributes =
HashMap.fromList
[ ( "Test"
, MessageAttribute
{ _maType = "String"
, _maValue = "TestString"
})
, ( "TestBinary"
, MessageAttribute
{ _maType = "Binary"
, _maValue = "TestBinary"
})
]
, _smMessageId = "95df01b4-ee98-5cb9-9903-4c221d41eb5e"
, _smSignature = "EXAMPLE"
, _smSignatureVersion = "1"
, _smSigningCertUrl = "EXAMPLE"
, _smSubject = "TestInvoke"
, _smTimestamp = UTCTime (fromGregorian 1970 1 1) (secondsToDiffTime 0)
, _smTopicArn = "topicarn"
, _smType = "Notification"
, _smUnsubscribeUrl = "EXAMPLE"
}
}
]
sampleSNSS3JSON :: ByteString
sampleSNSS3JSON = [r|
{"Records":
[
{"EventSource":"aws:sns",
"EventVersion":"1.0",
"EventSubscriptionArn":"arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent:23e2d254-e8bb-4db5-92ce-d917e5aad090",
"Sns":{
"Type":"Notification",
"MessageId":"89f6fe8b-a751-5dcd-8e0c-afbd75420455",
"TopicArn":"arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent",
"Subject":"Amazon S3 Notification",
"Message": "{\"Records\":[{\"eventVersion\":\"2.0\",\"eventSource\":\"aws:s3\",\"awsRegion\":\"ap-southeast-2\",\"eventTime\":\"2017-03-06T02:56:19.713Z\",\"eventName\":\"ObjectCreated:Put\",\"userIdentity\":{\"principalId\":\"AWS:DFLKSDFLKJ987SDFLJJDJ:some-principal-id\"},\"requestParameters\":{\"sourceIPAddress\":\"192.168.0.1\"},\"responseElements\":{\"x-amz-request-id\":\"324098EDFLK0894F\",\"x-amz-id-2\":\"xsdSDF/pgAl401Fz3UIATJ5/didfljDSFDSFsdfkjsdfl8JdsfLSDF89ldsf7SDF898jsdfljiA=\"},\"s3\":{\"s3SchemaVersion\":\"1.0\",\"configurationId\":\"SomeS3Event:Created\",\"bucket\":{\"name\":\"some-bucket\",\"ownerIdentity\":{\"principalId\":\"A3O1SDFLKJIJXU\"},\"arn\":\"arn:aws:s3:::some-bucket\"},\"object\":{\"key\":\"path/to/some/object\",\"size\":53598442,\"eTag\":\"6b1f72b9e81e4d6fcd3e0c808e8477f8\",\"sequencer\":\"0058BCCFD25C798E7B\"}}}]}",
"Timestamp":"2017-03-06T02:56:19.834Z",
"SignatureVersion":"1",
"Signature":"aybEgnTjKzSbC2puHxho7SUnYOje4SjBoCyt0Q13bMWyp7M64+EU6jzi7P01+gSIuBFyYPsHreSmyqGMRSxbFuzn7rG5JcVGN0901U3CRXdk42eh03je8evRvs/Oa7TJlhpCTEDDOScalCWbIH0RthYONQpPR01nEgaNKj3e8YVJqyRQV+4RbU3YWJOj+Spyi4u1hOC9PLUv4BH7U80nbhbOe9EwgX0zpeNU1WBRbEpqPoACm+7/uB0w79qFBKjB/Q7OWc1kASUZV9q8bz03yceoQeVvza0QGhPsnSXi49sn1mLWQOFS4KvgbJIC/Qk7H036ShrDioP6pP+UEg6kow==",
"SigningCertUrl":"-southeast-2.amazonaws.com/SimpleNotificationService-b95095beb82e8f6a046b3aafc7f4149a.pem",
"UnsubscribeUrl":"-southeast-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent:23e2d254-e8bb-4db5-92ce-d917e5aad090",
"MessageAttributes":{}
}
}
]
}
|]
sampleSNSS3Event :: SNSEvent (Embedded S3Event)
sampleSNSS3Event =
RecordsEvent
{ _reRecords =
[ SNSRecord
{ _srEventVersion = "1.0"
, _srEventSubscriptionArn =
"arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent:23e2d254-e8bb-4db5-92ce-d917e5aad090"
, _srEventSource = "aws:sns"
, _srSns =
SNSMessage
{ _smMessage =
TextValue
{ _unTextValue =
Embedded
{ _unEmbed =
RecordsEvent
{ _reRecords =
[ S3EventNotification
{ _senAwsRegion = Sydney
, _senEventName = S3ObjectCreatedPut
, _senEventSource = "aws:s3"
, _senEventTime =
UTCTime
(fromGregorian 2017 3 6)
(picosecondsToDiffTime 10579713000000000)
, _senEventVersion = "2.0"
, _senRequestParameters =
RequestParametersEntity
{ _rpeSourceIPAddress = "192.168.0.1"
}
, _senResponseElements =
ResponseElementsEntity
{ _reeXAmzId2 =
"xsdSDF/pgAl401Fz3UIATJ5/didfljDSFDSFsdfkjsdfl8JdsfLSDF89ldsf7SDF898jsdfljiA="
, _reeXAmzRequestId = "324098EDFLK0894F"
}
, _senS3 =
S3Entity
{ _seBucket =
S3BucketEntity
{ _sbeArn = "arn:aws:s3:::some-bucket"
, _sbeName = BucketName "some-bucket"
, _sbeOwnerIdentity =
UserIdentityEntity
{ _uiePrincipalId = "A3O1SDFLKJIJXU"
}
}
, _seConfigurationId = "SomeS3Event:Created"
, _seObject =
S3ObjectEntity
{ _soeETag =
Just (ETag "6b1f72b9e81e4d6fcd3e0c808e8477f8")
, _soeKey = ObjectKey "path/to/some/object"
, _soeSize = Just 53598442
, _soeSequencer = "0058BCCFD25C798E7B"
, _soeVersionId = Nothing
}
, _seS3SchemaVersion = "1.0"
}
, _senUserIdentity =
UserIdentityEntity
{ _uiePrincipalId =
"AWS:DFLKSDFLKJ987SDFLJJDJ:some-principal-id"
}
}
]
}
}
}
, _smMessageAttributes = HashMap.fromList []
, _smMessageId = "89f6fe8b-a751-5dcd-8e0c-afbd75420455"
, _smSignature =
"aybEgnTjKzSbC2puHxho7SUnYOje4SjBoCyt0Q13bMWyp7M64+EU6jzi7P01+gSIuBFyYPsHreSmyqGMRSxbFuzn7rG5JcVGN0901U3CRXdk42eh03je8evRvs/Oa7TJlhpCTEDDOScalCWbIH0RthYONQpPR01nEgaNKj3e8YVJqyRQV+4RbU3YWJOj+Spyi4u1hOC9PLUv4BH7U80nbhbOe9EwgX0zpeNU1WBRbEpqPoACm+7/uB0w79qFBKjB/Q7OWc1kASUZV9q8bz03yceoQeVvza0QGhPsnSXi49sn1mLWQOFS4KvgbJIC/Qk7H036ShrDioP6pP+UEg6kow=="
, _smSignatureVersion = "1"
, _smSigningCertUrl =
"-southeast-2.amazonaws.com/SimpleNotificationService-b95095beb82e8f6a046b3aafc7f4149a.pem"
, _smSubject = "Amazon S3 Notification"
, _smTimestamp =
UTCTime
(fromGregorian 2017 3 6)
(picosecondsToDiffTime 10579834000000000)
, _smTopicArn = "arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent"
, _smType = "Notification"
, _smUnsubscribeUrl =
"-southeast-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-2:012345678901:SomeSNSEvent:23e2d254-e8bb-4db5-92ce-d917e5aad090"
}
}
]
}
|
5bc5644f28a122f96435fb6f6e1086bfd7b02d6cb45f211dbda0dd686f8c8968 | wh5a/thih | FoldlCont.hs | myfoldr :: (a -> b -> b) -> b -> [a] -> b
myfoldr = \f z xs -> foldrC (\x -> x) f z xs
foldrC :: (a -> b) -> (c -> a -> a) -> a -> [c] -> b
foldrC = \c f z l ->
case l of
[] -> c z
(:) x xs -> foldrC (\n -> c (f x n)) f z xs
main = myfoldr (+) 0 [1,2,3]
| null | https://raw.githubusercontent.com/wh5a/thih/dc5cb16ba4e998097135beb0c7b0b416cac7bfae/hatchet/examples/FoldlCont.hs | haskell | myfoldr :: (a -> b -> b) -> b -> [a] -> b
myfoldr = \f z xs -> foldrC (\x -> x) f z xs
foldrC :: (a -> b) -> (c -> a -> a) -> a -> [c] -> b
foldrC = \c f z l ->
case l of
[] -> c z
(:) x xs -> foldrC (\n -> c (f x n)) f z xs
main = myfoldr (+) 0 [1,2,3]
| |
fd2f325a4ff4e6f86b943c1d091e6e13c125e35d5d7418d1a59772571a06b382 | bishboria/learnyouahaskell | 14_knight_moves.hs | import Data.List
import Control.Monad
type KnightPos = (Int,Int)
canReachIn :: Int -> KnightPos -> KnightPos -> Bool
canReachIn x start end = end `elem` inMany x start
inMany :: Int -> KnightPos -> [KnightPos]
inMany x start = return start >>= foldr (<=<) return (replicate x moveKnight)
moveKnight :: KnightPos -> [KnightPos]
moveKnight (c,r) = do
(c',r') <- [(c+2,r-1),(c+2,r+1),(c-2,r-1),(c-2,r+1)
,(c+1,r-2),(c+1,r+2),(c-1,r-2),(c-1,r+2)
]
guard (c' `elem` [1..8] && r' `elem` [1..8])
return (c',r')
canReachIn 3 ( 1,1 ) ( 8,8 )
-- False
canReachIn 4 ( 1,1 ) ( 8,8 )
-- False
canReachIn 5 ( 1,1 ) ( 8,8 )
-- False
canReachIn 6 ( 1,1 ) ( 8,8 )
-- True
| null | https://raw.githubusercontent.com/bishboria/learnyouahaskell/d8c7b41398e9672db18c1b1360372fc4a4adefa8/14/14_knight_moves.hs | haskell | False
False
False
True | import Data.List
import Control.Monad
type KnightPos = (Int,Int)
canReachIn :: Int -> KnightPos -> KnightPos -> Bool
canReachIn x start end = end `elem` inMany x start
inMany :: Int -> KnightPos -> [KnightPos]
inMany x start = return start >>= foldr (<=<) return (replicate x moveKnight)
moveKnight :: KnightPos -> [KnightPos]
moveKnight (c,r) = do
(c',r') <- [(c+2,r-1),(c+2,r+1),(c-2,r-1),(c-2,r+1)
,(c+1,r-2),(c+1,r+2),(c-1,r-2),(c-1,r+2)
]
guard (c' `elem` [1..8] && r' `elem` [1..8])
return (c',r')
canReachIn 3 ( 1,1 ) ( 8,8 )
canReachIn 4 ( 1,1 ) ( 8,8 )
canReachIn 5 ( 1,1 ) ( 8,8 )
canReachIn 6 ( 1,1 ) ( 8,8 )
|
06d0c2c5e046fb5bd31c8e7ef9417ae56ac000d55d7efe738403ccf74776f5e6 | heraldry/heraldicon | quartered.cljs | (ns heraldicon.heraldry.field.type.quartered
(:require
[heraldicon.context :as c]
[heraldicon.heraldry.field.environment :as environment]
[heraldicon.heraldry.field.interface :as field.interface]
[heraldicon.heraldry.line.core :as line]
[heraldicon.heraldry.option.position :as position]
[heraldicon.heraldry.ordinary.post-process :as post-process]
[heraldicon.interface :as interface]
[heraldicon.math.bounding-box :as bb]
[heraldicon.math.vector :as v]
[heraldicon.options :as options]
[heraldicon.svg.shape :as shape]))
(def field-type :heraldry.field.type/quartered)
(defmethod field.interface/display-name field-type [_] :string.field.type/quartered)
(defmethod field.interface/part-names field-type [_] ["I" "II" "III" "IV"])
(defmethod field.interface/options field-type [context]
(let [line-style (-> (line/options (c/++ context :line)
:fimbriation? false)
(options/override-if-exists [:offset :min] 0)
(options/override-if-exists [:base-line] nil))
opposite-line-style (-> (line/options (c/++ context :opposite-line)
:fimbriation? false
:inherited-options line-style)
(options/override-if-exists [:offset :min] 0)
(options/override-if-exists [:base-line] nil))]
{:anchor {:point {:type :option.type/choice
:choices (position/anchor-choices
[:chief
:base
:fess
:dexter
:sinister
:honour
:nombril
:hoist
:fly
:center])
:default :fess
:ui/label :string.option/point}
:offset-x {:type :option.type/range
:min -45
:max 45
:default 0
:ui/label :string.option/offset-x
:ui/step 0.1}
:offset-y {:type :option.type/range
:min -45
:max 45
:default 0
:ui/label :string.option/offset-y
:ui/step 0.1}
:ui/label :string.option/anchor
:ui/element :ui.element/position}
:line line-style
:opposite-line opposite-line-style
:outline? options/plain-outline?-option}))
(defmethod interface/properties field-type [context]
(let [parent-environment (interface/get-subfields-environment context)
{:keys [top bottom left right]} (:points parent-environment)
percentage-base (:height parent-environment)
anchor (interface/get-sanitized-data (c/++ context :anchor))
anchor-point (position/calculate anchor parent-environment :fess)
{edge-x :x
edge-y :y} anchor-point
parent-shape (interface/get-subfields-shape context)
[left-end right-end] (v/intersections-with-shape
(v/Vector. (:x left) edge-y) (v/Vector. (:x right) edge-y)
parent-shape :default? true)
[top-end bottom-end] (v/intersections-with-shape
(v/Vector. edge-x (:y top)) (v/Vector. edge-x (:y bottom))
parent-shape :default? true)
line-length (->> [top-end bottom-end
left-end right-end]
(map (fn [v]
(v/sub v anchor-point)))
(map v/abs)
(apply max))]
(post-process/properties
{:type field-type
:edge-left [anchor-point left-end]
:edge-right [anchor-point right-end]
:edge-top [anchor-point top-end]
:edge-bottom [anchor-point bottom-end]
:anchor-point anchor-point
:line-length line-length
:percentage-base percentage-base
:num-subfields 4
:overlap?-fn #{0 3}}
context)))
(defmethod interface/subfield-environments field-type [context]
(let [{:keys [anchor-point]
[_edge-top-1 edge-top-2] :edge-top
[_edge-bottom-1 edge-bottom-2] :edge-bottom
[_edge-left-1 edge-left-2] :edge-left
[_edge-right-1 edge-right-2] :edge-right} (interface/get-properties context)
{:keys [points]} (interface/get-subfields-environment context)
{:keys [top-left top-right
bottom-left bottom-right]} points]
{:subfields [(environment/create (bb/from-points [top-left edge-top-2
edge-left-2 anchor-point]))
(environment/create (bb/from-points [edge-top-2 top-right
anchor-point edge-right-2]))
(environment/create (bb/from-points [edge-left-2 anchor-point
bottom-left edge-bottom-2]))
(environment/create (bb/from-points [anchor-point edge-right-2
edge-bottom-2 bottom-right]))]}))
(defmethod interface/subfield-render-shapes field-type [context]
(let [{:keys [line opposite-line]
[edge-top-1 edge-top-2] :edge-top
[edge-bottom-1 edge-bottom-2] :edge-bottom
[edge-left-1 edge-left-2] :edge-left
[edge-right-1 edge-right-2] :edge-right} (interface/get-properties context)
{:keys [bounding-box]} (interface/get-subfields-environment context)
line-edge-top (line/create-with-extension context
line
edge-top-1 edge-top-2
bounding-box
:reversed? true
:extend-from? false)
line-edge-bottom (line/create-with-extension context
line
edge-bottom-1 edge-bottom-2
bounding-box
:reversed? true
:extend-from? false)
line-edge-left (line/create-with-extension context
opposite-line
edge-left-1 edge-left-2
bounding-box
:mirrored? true
:flipped? true
:extend-from? false)
line-edge-right (line/create-with-extension context
opposite-line
edge-right-1 edge-right-2
bounding-box
:mirrored? true
:flipped? true
:extend-from? false)]
{:subfields [{:shape [(shape/build-shape
(c/++ context :fields 0)
line-edge-top
line-edge-left
:clockwise)]}
{:shape [(shape/build-shape
(c/++ context :fields 1)
line-edge-top
line-edge-right
:counter-clockwise)]}
{:shape [(shape/build-shape
(c/++ context :fields 2)
line-edge-bottom
line-edge-left
:counter-clockwise)]}
{:shape [(shape/build-shape
(c/++ context :fields 3)
line-edge-bottom
line-edge-right
:clockwise)]}]
:edges [{:lines [line-edge-top]}
{:lines [line-edge-bottom]}
{:lines [line-edge-left]}
{:lines [line-edge-right]}]}))
| null | https://raw.githubusercontent.com/heraldry/heraldicon/71126cfd7ba342dea0d1bb849be92cbe5290a6fd/src/heraldicon/heraldry/field/type/quartered.cljs | clojure | (ns heraldicon.heraldry.field.type.quartered
(:require
[heraldicon.context :as c]
[heraldicon.heraldry.field.environment :as environment]
[heraldicon.heraldry.field.interface :as field.interface]
[heraldicon.heraldry.line.core :as line]
[heraldicon.heraldry.option.position :as position]
[heraldicon.heraldry.ordinary.post-process :as post-process]
[heraldicon.interface :as interface]
[heraldicon.math.bounding-box :as bb]
[heraldicon.math.vector :as v]
[heraldicon.options :as options]
[heraldicon.svg.shape :as shape]))
(def field-type :heraldry.field.type/quartered)
(defmethod field.interface/display-name field-type [_] :string.field.type/quartered)
(defmethod field.interface/part-names field-type [_] ["I" "II" "III" "IV"])
(defmethod field.interface/options field-type [context]
(let [line-style (-> (line/options (c/++ context :line)
:fimbriation? false)
(options/override-if-exists [:offset :min] 0)
(options/override-if-exists [:base-line] nil))
opposite-line-style (-> (line/options (c/++ context :opposite-line)
:fimbriation? false
:inherited-options line-style)
(options/override-if-exists [:offset :min] 0)
(options/override-if-exists [:base-line] nil))]
{:anchor {:point {:type :option.type/choice
:choices (position/anchor-choices
[:chief
:base
:fess
:dexter
:sinister
:honour
:nombril
:hoist
:fly
:center])
:default :fess
:ui/label :string.option/point}
:offset-x {:type :option.type/range
:min -45
:max 45
:default 0
:ui/label :string.option/offset-x
:ui/step 0.1}
:offset-y {:type :option.type/range
:min -45
:max 45
:default 0
:ui/label :string.option/offset-y
:ui/step 0.1}
:ui/label :string.option/anchor
:ui/element :ui.element/position}
:line line-style
:opposite-line opposite-line-style
:outline? options/plain-outline?-option}))
(defmethod interface/properties field-type [context]
(let [parent-environment (interface/get-subfields-environment context)
{:keys [top bottom left right]} (:points parent-environment)
percentage-base (:height parent-environment)
anchor (interface/get-sanitized-data (c/++ context :anchor))
anchor-point (position/calculate anchor parent-environment :fess)
{edge-x :x
edge-y :y} anchor-point
parent-shape (interface/get-subfields-shape context)
[left-end right-end] (v/intersections-with-shape
(v/Vector. (:x left) edge-y) (v/Vector. (:x right) edge-y)
parent-shape :default? true)
[top-end bottom-end] (v/intersections-with-shape
(v/Vector. edge-x (:y top)) (v/Vector. edge-x (:y bottom))
parent-shape :default? true)
line-length (->> [top-end bottom-end
left-end right-end]
(map (fn [v]
(v/sub v anchor-point)))
(map v/abs)
(apply max))]
(post-process/properties
{:type field-type
:edge-left [anchor-point left-end]
:edge-right [anchor-point right-end]
:edge-top [anchor-point top-end]
:edge-bottom [anchor-point bottom-end]
:anchor-point anchor-point
:line-length line-length
:percentage-base percentage-base
:num-subfields 4
:overlap?-fn #{0 3}}
context)))
(defmethod interface/subfield-environments field-type [context]
(let [{:keys [anchor-point]
[_edge-top-1 edge-top-2] :edge-top
[_edge-bottom-1 edge-bottom-2] :edge-bottom
[_edge-left-1 edge-left-2] :edge-left
[_edge-right-1 edge-right-2] :edge-right} (interface/get-properties context)
{:keys [points]} (interface/get-subfields-environment context)
{:keys [top-left top-right
bottom-left bottom-right]} points]
{:subfields [(environment/create (bb/from-points [top-left edge-top-2
edge-left-2 anchor-point]))
(environment/create (bb/from-points [edge-top-2 top-right
anchor-point edge-right-2]))
(environment/create (bb/from-points [edge-left-2 anchor-point
bottom-left edge-bottom-2]))
(environment/create (bb/from-points [anchor-point edge-right-2
edge-bottom-2 bottom-right]))]}))
(defmethod interface/subfield-render-shapes field-type [context]
(let [{:keys [line opposite-line]
[edge-top-1 edge-top-2] :edge-top
[edge-bottom-1 edge-bottom-2] :edge-bottom
[edge-left-1 edge-left-2] :edge-left
[edge-right-1 edge-right-2] :edge-right} (interface/get-properties context)
{:keys [bounding-box]} (interface/get-subfields-environment context)
line-edge-top (line/create-with-extension context
line
edge-top-1 edge-top-2
bounding-box
:reversed? true
:extend-from? false)
line-edge-bottom (line/create-with-extension context
line
edge-bottom-1 edge-bottom-2
bounding-box
:reversed? true
:extend-from? false)
line-edge-left (line/create-with-extension context
opposite-line
edge-left-1 edge-left-2
bounding-box
:mirrored? true
:flipped? true
:extend-from? false)
line-edge-right (line/create-with-extension context
opposite-line
edge-right-1 edge-right-2
bounding-box
:mirrored? true
:flipped? true
:extend-from? false)]
{:subfields [{:shape [(shape/build-shape
(c/++ context :fields 0)
line-edge-top
line-edge-left
:clockwise)]}
{:shape [(shape/build-shape
(c/++ context :fields 1)
line-edge-top
line-edge-right
:counter-clockwise)]}
{:shape [(shape/build-shape
(c/++ context :fields 2)
line-edge-bottom
line-edge-left
:counter-clockwise)]}
{:shape [(shape/build-shape
(c/++ context :fields 3)
line-edge-bottom
line-edge-right
:clockwise)]}]
:edges [{:lines [line-edge-top]}
{:lines [line-edge-bottom]}
{:lines [line-edge-left]}
{:lines [line-edge-right]}]}))
| |
9d2f0a5b080c7929e6a04af6c7346cd29594dbfa6017904b41554d495e6e16d3 | adamschoenemann/clofrp | Expr.hs | # LANGUAGE DeriveFunctor #
{-# LANGUAGE OverloadedStrings #-}
module CloFRP.Parser.Expr where
import Text.Parsec.Pos
import Text.Parsec
import Data.List (foldl')
import qualified CloFRP.Annotated as A
import qualified CloFRP.AST as E
import qualified CloFRP.AST.Prim as P
import CloFRP.Parser.Lang
import qualified CloFRP.Parser.Type as T
import CloFRP.AST.Name
type Expr = E.Expr SourcePos
type Pat = E.Pat SourcePos
nat :: Parser Expr
nat = ann <*> (E.Prim . P.Integer <$> natural)
tuple :: Parser Expr
tuple = ann <*> (E.Tuple <$> parens (expr `sepBy2` comma))
lname :: Parser Name
lname = UName <$> lidentifier
name :: Parser Name
name = UName <$> identifier
tickabs :: Parser Expr
tickabs = do
ps <- symbol "\\\\" *> many1 param
bd <- reservedOp "->" *> expr
pure $ foldr (\(A.A a (nm, kappa)) acc -> A.A a $ E.TickAbs nm kappa acc) bd ps
where
param = ann <*> parens ((,) <$> lname <*> (reservedOp ":" *> name))
letp :: Parser Expr
letp = ann <*> p where
p = E.Let <$> (reserved "let" *> pat <* reservedOp "=") <*> (expr <* reserved "in") <*> expr
lam :: Parser Expr
lam = do
ps <- symbol "\\" *> many1 param
bd <- reservedOp "->" *> expr
pure $ foldr (\(A.A a nm, ty) acc -> A.A a $ E.Lam nm ty acc) bd ps
where
param = (\x -> (x, Nothing)) <$> (ann <*> lname)
<|> parens ((,) <$> (ann <*> lname)
<*> (optionMaybe $ reservedOp ":" *> T.typep))
var :: Parser Expr
var = ann <*> (E.Var . UName <$> identifier)
tickvar :: Parser Expr
tickvar = ann <*> (E.TickVar <$> brackets lname)
anno :: Parser Expr
anno = ann <*> ((\t e -> E.Ann e t) <$> (reserved "the" *> parens T.typep) <*> expr)
casep :: Parser Expr
casep = do
_ <- reserved "case"
scrutinee <- expr
_ <- reserved "of"
_ <- reservedOp "|"
r <- ann <*> (E.Case scrutinee <$> matchp `sepBy` (reservedOp "|"))
_ <- reserved "end"
pure r
where
matchp = (,) <$> (pat <* reservedOp "->") <*> expr
fmapp :: Parser Expr
fmapp = ann <*> p where
p = E.Fmap <$> (reserved "fmap" *> braces (T.typep))
primRecP :: Parser Expr
primRecP = ann <*> p where
p = E.PrimRec <$> (reserved "primRec" *> braces (T.typep))
-- a bit annoying with all this copy-paste but meh
pat :: Parser Pat
pat = ann <*> p where
p = (bind <|> match <|> try ptuple <|> parens p)
bind = E.Bind . UName <$> lidentifier
match = E.Match <$> (UName <$> uidentifier) <*> many (ann <*> pat')
ptuple = parens (E.PTuple <$> pat `sepBy2` comma)
pat' = E.Match <$> (UName <$> uidentifier) <*> pure []
<|> E.Bind . UName <$> lidentifier
<|> try (parens (E.PTuple <$> pat `sepBy2` comma))
<|> parens (E.Match <$> (UName <$> uidentifier) <*> many pat)
atom :: Parser Expr
atom = nat
<|> try tuple
<|> reserved "fold" *> (ann <*> pure (E.Prim E.Fold))
<|> reserved "unfold" *> (ann <*> pure (E.Prim E.Unfold))
<|> reserved "[<>]" *> (ann <*> pure (E.Prim E.Tick))
<|> reserved "fix" *> (ann <*> pure (E.Prim E.Fix))
<|> reserved "undefined" *> (ann <*> pure (E.Prim E.Undefined))
<|> primRecP
<|> fmapp
<|> letp
<|> var
<|> tickvar
<|> anno
<|> casep
<|> parens expr
expr :: Parser Expr
expr = try tickabs <|> lam <|> buildExpressionParser table atom where
table =
[ [Infix spacef AssocLeft, Postfix typeapp]
, [binary' "+" (binOp "+") AssocLeft]
, [binary' "<" (binOp "<") AssocLeft]
, [Postfix tanno]
]
binOp nm = do
p <- getPosition
pure (\e1 -> A.A p . E.BinOp nm e1)
spacef :: Parser (Expr -> Expr -> Expr)
spacef =
ws *> notFollowedBy (choice . map reservedOp $ opNames) *> app
<?> "space application"
tanno :: Parser (Expr -> Expr)
tanno = do
p <- getPosition
t <- reservedOp ":" *> T.typep
pure (\e -> A.A p $ E.Ann e t)
typeapp :: Parser (Expr -> Expr)
typeapp = do
p <- getPosition
-- nasty hack to make it behave "infixl" ish
ts <- many1 (ann <*> braces T.typep)
pure (\e -> foldl' (\acc (A.A a t) -> A.A a $ E.TypeApp acc t) e ts)
app :: Parser (Expr -> Expr -> Expr)
app = fn <$> getPosition where
fn p e1 e2 = A.A p $ E.App e1 e2
parseExpr :: String -> Either ParseError Expr
parseExpr = parse (ws *> expr <* eof) "parseExpr" | null | https://raw.githubusercontent.com/adamschoenemann/clofrp/c26f86aec2cdb8fa7fd317acd13f7d77af984bd3/library/CloFRP/Parser/Expr.hs | haskell | # LANGUAGE OverloadedStrings #
a bit annoying with all this copy-paste but meh
nasty hack to make it behave "infixl" ish | # LANGUAGE DeriveFunctor #
module CloFRP.Parser.Expr where
import Text.Parsec.Pos
import Text.Parsec
import Data.List (foldl')
import qualified CloFRP.Annotated as A
import qualified CloFRP.AST as E
import qualified CloFRP.AST.Prim as P
import CloFRP.Parser.Lang
import qualified CloFRP.Parser.Type as T
import CloFRP.AST.Name
type Expr = E.Expr SourcePos
type Pat = E.Pat SourcePos
nat :: Parser Expr
nat = ann <*> (E.Prim . P.Integer <$> natural)
tuple :: Parser Expr
tuple = ann <*> (E.Tuple <$> parens (expr `sepBy2` comma))
lname :: Parser Name
lname = UName <$> lidentifier
name :: Parser Name
name = UName <$> identifier
tickabs :: Parser Expr
tickabs = do
ps <- symbol "\\\\" *> many1 param
bd <- reservedOp "->" *> expr
pure $ foldr (\(A.A a (nm, kappa)) acc -> A.A a $ E.TickAbs nm kappa acc) bd ps
where
param = ann <*> parens ((,) <$> lname <*> (reservedOp ":" *> name))
letp :: Parser Expr
letp = ann <*> p where
p = E.Let <$> (reserved "let" *> pat <* reservedOp "=") <*> (expr <* reserved "in") <*> expr
lam :: Parser Expr
lam = do
ps <- symbol "\\" *> many1 param
bd <- reservedOp "->" *> expr
pure $ foldr (\(A.A a nm, ty) acc -> A.A a $ E.Lam nm ty acc) bd ps
where
param = (\x -> (x, Nothing)) <$> (ann <*> lname)
<|> parens ((,) <$> (ann <*> lname)
<*> (optionMaybe $ reservedOp ":" *> T.typep))
var :: Parser Expr
var = ann <*> (E.Var . UName <$> identifier)
tickvar :: Parser Expr
tickvar = ann <*> (E.TickVar <$> brackets lname)
anno :: Parser Expr
anno = ann <*> ((\t e -> E.Ann e t) <$> (reserved "the" *> parens T.typep) <*> expr)
casep :: Parser Expr
casep = do
_ <- reserved "case"
scrutinee <- expr
_ <- reserved "of"
_ <- reservedOp "|"
r <- ann <*> (E.Case scrutinee <$> matchp `sepBy` (reservedOp "|"))
_ <- reserved "end"
pure r
where
matchp = (,) <$> (pat <* reservedOp "->") <*> expr
fmapp :: Parser Expr
fmapp = ann <*> p where
p = E.Fmap <$> (reserved "fmap" *> braces (T.typep))
primRecP :: Parser Expr
primRecP = ann <*> p where
p = E.PrimRec <$> (reserved "primRec" *> braces (T.typep))
pat :: Parser Pat
pat = ann <*> p where
p = (bind <|> match <|> try ptuple <|> parens p)
bind = E.Bind . UName <$> lidentifier
match = E.Match <$> (UName <$> uidentifier) <*> many (ann <*> pat')
ptuple = parens (E.PTuple <$> pat `sepBy2` comma)
pat' = E.Match <$> (UName <$> uidentifier) <*> pure []
<|> E.Bind . UName <$> lidentifier
<|> try (parens (E.PTuple <$> pat `sepBy2` comma))
<|> parens (E.Match <$> (UName <$> uidentifier) <*> many pat)
atom :: Parser Expr
atom = nat
<|> try tuple
<|> reserved "fold" *> (ann <*> pure (E.Prim E.Fold))
<|> reserved "unfold" *> (ann <*> pure (E.Prim E.Unfold))
<|> reserved "[<>]" *> (ann <*> pure (E.Prim E.Tick))
<|> reserved "fix" *> (ann <*> pure (E.Prim E.Fix))
<|> reserved "undefined" *> (ann <*> pure (E.Prim E.Undefined))
<|> primRecP
<|> fmapp
<|> letp
<|> var
<|> tickvar
<|> anno
<|> casep
<|> parens expr
expr :: Parser Expr
expr = try tickabs <|> lam <|> buildExpressionParser table atom where
table =
[ [Infix spacef AssocLeft, Postfix typeapp]
, [binary' "+" (binOp "+") AssocLeft]
, [binary' "<" (binOp "<") AssocLeft]
, [Postfix tanno]
]
binOp nm = do
p <- getPosition
pure (\e1 -> A.A p . E.BinOp nm e1)
spacef :: Parser (Expr -> Expr -> Expr)
spacef =
ws *> notFollowedBy (choice . map reservedOp $ opNames) *> app
<?> "space application"
tanno :: Parser (Expr -> Expr)
tanno = do
p <- getPosition
t <- reservedOp ":" *> T.typep
pure (\e -> A.A p $ E.Ann e t)
typeapp :: Parser (Expr -> Expr)
typeapp = do
p <- getPosition
ts <- many1 (ann <*> braces T.typep)
pure (\e -> foldl' (\acc (A.A a t) -> A.A a $ E.TypeApp acc t) e ts)
app :: Parser (Expr -> Expr -> Expr)
app = fn <$> getPosition where
fn p e1 e2 = A.A p $ E.App e1 e2
parseExpr :: String -> Either ParseError Expr
parseExpr = parse (ws *> expr <* eof) "parseExpr" |
8dd7aac1ccb77ce96950a35d1a53f6ee1542ba2f63c1931e216f3173916271d3 | AndrasKovacs/normalization-bench | Main.hs |
module Main where
import qualified HOASCBV
import qualified HOASCBN
import qualified Interp
main :: IO ()
main = do
-- putStrLn "HOAS call-by-value"
-- putStrLn "----------------------------------------"
-- HOASCBV.bench
-- putStrLn "HOAS call-by-need"
-- putStrLn "----------------------------------------"
HOASCBN.bench
putStrLn "Interpreted call-by-value"
putStrLn "----------------------------------------"
Interp.bench
| null | https://raw.githubusercontent.com/AndrasKovacs/normalization-bench/bef02243cc70415ab2ec7a5db823a448b07bf4db/haskell/Main.hs | haskell | putStrLn "HOAS call-by-value"
putStrLn "----------------------------------------"
HOASCBV.bench
putStrLn "HOAS call-by-need"
putStrLn "----------------------------------------" |
module Main where
import qualified HOASCBV
import qualified HOASCBN
import qualified Interp
main :: IO ()
main = do
HOASCBN.bench
putStrLn "Interpreted call-by-value"
putStrLn "----------------------------------------"
Interp.bench
|
971a8c82621bb4731e0a275bf19d6b0abec502f5be7f3f77680c4ec0003be4de | rabbitmq/erlando | test.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is Erlando .
%%
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2011 - 2013 VMware , Inc. All rights reserved .
%%
-module(test).
-export([test/2]).
-compile({parse_transform, do}).
test(Funs, Options) ->
ErrorT = error_t:new(identity_m),
Result = ErrorT:run(test_funs(ErrorT, Funs)),
case proplists:get_bool(report, Options) of
true ->
Name = proplists:get_value(name, Options, anonymous),
case Result of
{ok, passed} ->
io:format("Test suite '~p' passed.~n", [Name]);
{error, Reason} ->
io:format("Test suite '~p' failed with ~p.~n",
[Name, Reason])
end;
false ->
ok
end,
case Result of
{ok, passed} -> ok;
_ -> Result
end.
test_funs(ErrorT, []) ->
ErrorT:return(passed);
test_funs(ErrorT, [{Module, {Label, FunName}}|Funs])
when is_atom(Module) andalso is_atom(FunName) ->
do([ErrorT || hoist(ErrorT, Label, fun () -> Module:FunName() end),
test_funs(ErrorT, Funs)]);
test_funs(ErrorT, [{Module, FunName}|Funs])
when is_atom(Module) andalso is_atom(FunName)
andalso is_function({Module, FunName}, 0) ->
do([ErrorT || hoist(ErrorT, FunName, fun () -> Module:FunName() end),
test_funs(ErrorT, Funs)]);
test_funs(ErrorT, [{_Module, []}|Funs]) ->
test_funs(ErrorT, Funs);
test_funs(ErrorT, [{Module, [FunName|FunNames]}|Funs])
when is_atom(Module) andalso is_atom(FunName) ->
test_funs(ErrorT, [{Module, FunName}, {Module, FunNames} | Funs]);
test_funs(ErrorT, [{Label, Fun}|Funs]) when is_function(Fun, 0) ->
do([ErrorT || hoist(ErrorT, Label, Fun),
test_funs(ErrorT, Funs)]);
test_funs(ErrorT, [Fun|Funs]) when is_function(Fun, 0) ->
do([ErrorT || hoist(ErrorT, anonymous_function, Fun),
test_funs(ErrorT, Funs)]).
hoist(ErrorT, Label, PlainFun) ->
do([ErrorT ||
try
PlainFun(),
return(passed)
catch
Class:Reason ->
fail({Label, Class, Reason, erlang:get_stacktrace()})
end]).
| null | https://raw.githubusercontent.com/rabbitmq/erlando/1c1ef25a9bc228671b32b4a6ee30c7525314b1fd/src/test.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
| The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is Erlando .
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2011 - 2013 VMware , Inc. All rights reserved .
-module(test).
-export([test/2]).
-compile({parse_transform, do}).
test(Funs, Options) ->
ErrorT = error_t:new(identity_m),
Result = ErrorT:run(test_funs(ErrorT, Funs)),
case proplists:get_bool(report, Options) of
true ->
Name = proplists:get_value(name, Options, anonymous),
case Result of
{ok, passed} ->
io:format("Test suite '~p' passed.~n", [Name]);
{error, Reason} ->
io:format("Test suite '~p' failed with ~p.~n",
[Name, Reason])
end;
false ->
ok
end,
case Result of
{ok, passed} -> ok;
_ -> Result
end.
test_funs(ErrorT, []) ->
ErrorT:return(passed);
test_funs(ErrorT, [{Module, {Label, FunName}}|Funs])
when is_atom(Module) andalso is_atom(FunName) ->
do([ErrorT || hoist(ErrorT, Label, fun () -> Module:FunName() end),
test_funs(ErrorT, Funs)]);
test_funs(ErrorT, [{Module, FunName}|Funs])
when is_atom(Module) andalso is_atom(FunName)
andalso is_function({Module, FunName}, 0) ->
do([ErrorT || hoist(ErrorT, FunName, fun () -> Module:FunName() end),
test_funs(ErrorT, Funs)]);
test_funs(ErrorT, [{_Module, []}|Funs]) ->
test_funs(ErrorT, Funs);
test_funs(ErrorT, [{Module, [FunName|FunNames]}|Funs])
when is_atom(Module) andalso is_atom(FunName) ->
test_funs(ErrorT, [{Module, FunName}, {Module, FunNames} | Funs]);
test_funs(ErrorT, [{Label, Fun}|Funs]) when is_function(Fun, 0) ->
do([ErrorT || hoist(ErrorT, Label, Fun),
test_funs(ErrorT, Funs)]);
test_funs(ErrorT, [Fun|Funs]) when is_function(Fun, 0) ->
do([ErrorT || hoist(ErrorT, anonymous_function, Fun),
test_funs(ErrorT, Funs)]).
hoist(ErrorT, Label, PlainFun) ->
do([ErrorT ||
try
PlainFun(),
return(passed)
catch
Class:Reason ->
fail({Label, Class, Reason, erlang:get_stacktrace()})
end]).
|
77d92b6f9bacd5d7e55f8da05f5ad075bd53e1dcff9bbd491c9deefb6a9b2bc8 | takikawa/racket-ppa | performance.rkt | #lang racket/base
(require racket/private/place-local)
(provide performance-region
performance-place-init!)
;; To enable measurement, see the end of this file.
;; The expression form
;;
;; (performance-region [key-expr ...] body ....)
;;
;; records the time of `body ...` and associated it with
;; the path `(list key-expr ...)`. Times for a path
;; are included in the times for the path's prefixes, but
;; not for any other path. When regions that are nested
;; dynamically, time accumlates only for the most nested
;; region.
;;
;; For example,
;;
;; (performance-region
;; ['compile 'module]
;; (do-expand-module))
;;
;; counts the time for `(do-expand-module)` to '(compile) and
;; to '(compile module), and not to any other path, even if
;; the compilation occurs while expanding another module.
;;
;; The key '_ as a path element is special: it is replaced
;; by the correspondig element of the enclosing region's
;; path (if any).
;;
;; Beware that `body ...` is not in tail position when
;; performance measurement is enabled.
(provide performance-region)
(define log-performance? (and (environment-variables-ref
(current-environment-variables)
#"PLT_EXPANDER_TIMES")
#t))
(define-syntax-rule (performance-region [tag0-expr tag-expr ...] body ...)
(begin
(when log-performance?
(start-performance-region tag0-expr tag-expr ...))
(begin0
(let () body ...)
(when log-performance?
(end-performance-region)))))
(define-place-local region-stack #f)
(define-place-local accums (make-hasheq))
(define (performance-place-init!)
(set! accums (make-hasheq)))
(struct region (path
[start #:mutable] ; start time
[start-memory #:mutable] ; memory allocated before start time
[as-nested #:mutable] ; time accumulated for nested regions
[as-nested-memory #:mutable])) ; ditto, for memory
(struct stat ([msecs #:mutable] [memory #:mutable] [count #:mutable]))
(define stat-key (gensym))
(define (start-performance-region . path)
(set! region-stack (cons (region (if region-stack
;; Replace '_ elements:
(let loop ([path path]
[enclosing-path (region-path (car region-stack))])
(if (null? path)
null
(cons (if (and (eq? '_ (car path))
(pair? enclosing-path))
(car enclosing-path)
(car path))
(loop (cdr path)
(if (pair? enclosing-path)
(cdr enclosing-path)
null)))))
path)
(current-inexact-monotonic-milliseconds)
(current-memory-use 'cumulative)
0.0
0)
region-stack)))
(define (end-performance-region)
(define now (current-inexact-monotonic-milliseconds))
(define now-memory (current-memory-use 'cumulative))
(define r (car region-stack))
(set! region-stack (cdr region-stack))
(define full-delta (- now (region-start r)))
(define delta (- full-delta (region-as-nested r)))
(define full-delta-memory (- now-memory (region-start-memory r)))
(define delta-memory (- full-delta-memory (region-as-nested-memory r)))
(let loop ([accums accums] [path (region-path r)])
(define key (car path))
(let ([accum (or (hash-ref accums key #f)
(let ([accum (make-hasheq)])
(hash-set! accums key accum)
accum))])
(define s (or (hash-ref accum stat-key #f)
(let ([s (stat 0.0 0 0)])
(hash-set! accum stat-key s)
s)))
(set-stat-msecs! s (+ delta (stat-msecs s)))
(set-stat-memory! s (+ delta-memory (stat-memory s)))
(when (null? (cdr path))
(set-stat-count! s (add1 (stat-count s))))
(unless (null? (cdr path))
(loop accum (cdr path)))))
(when region-stack
(set-region-as-nested! (car region-stack)
(+ (region-as-nested (car region-stack))
full-delta))
(set-region-as-nested-memory! (car region-stack)
(+ (region-as-nested-memory (car region-stack))
full-delta-memory))))
(when log-performance?
(void
(plumber-add-flush! (current-plumber)
(lambda (h)
(define (whole-len s)
(caar (or (regexp-match-positions #rx"[.]" s) '(0))))
(define (kb b)
(define s (number->string (quotient b 1024)))
(list->string
(for/fold ([l null]) ([c (in-list (reverse (string->list s)))]
[i (in-naturals)])
(cond
[(and (positive? i) (zero? (modulo i 3)))
(list* c #\, l)]
[else (cons c l)]))))
(define-values (label-max-len value-max-len memory-max-len count-max-len)
(let loop ([accums accums] [label-len 6] [value-len 5] [memory-len 4] [count-len 5] [indent 2])
(for/fold ([label-len label-len]
[value-len value-len]
[memory-len memory-len]
[count-len count-len])
([(k v) (in-hash accums)])
(cond
[(eq? k stat-key)
(values label-len
(max value-len (whole-len (format "~a" (stat-msecs v))))
(max memory-len (string-length (format "~a" (kb (stat-memory v)))))
(max count-len (string-length (format "~a" (stat-count v)))))]
[else (loop v
(max label-len (+ indent (string-length (format "~a" k))))
value-len
memory-len
count-len
(+ 2 indent))]))))
(log-error "REGION ~aMSECS ~aMEMK ~aCOUNT"
(make-string (- (+ label-max-len value-max-len) 11)
#\space)
(make-string (- memory-max-len 4)
#\space)
(make-string (- count-max-len 5)
#\space))
(let loop ([name #f] [accums accums] [indent ""] [newline? #t])
(when name
(define v (hash-ref accums stat-key))
(log-error "~a~a ~a~a ~a~a ~a~a"
indent
name
(make-string (+ (- label-max-len (string-length (format "~a" name)) (string-length indent))
(- value-max-len (whole-len (format "~a" (stat-msecs v)))))
#\space)
(regexp-replace #rx"[.](..).*" (format "~a00" (stat-msecs v)) ".\\1")
(make-string (- memory-max-len (string-length (format "~a" (kb (stat-memory v)))))
#\space)
(kb (stat-memory v))
(make-string (- count-max-len (string-length (format "~a" (stat-count v))))
#\space)
(stat-count v)))
(define keys (sort (for/list ([k (in-hash-keys accums)] #:when (not (eq? k stat-key))) k)
>
#:key (lambda (key) (stat-msecs (hash-ref (hash-ref accums key) stat-key)))))
(for ([k (in-list keys)]
[i (in-naturals)])
(when (and newline? (positive? i)) (log-error ""))
(loop k (hash-ref accums k) (string-append indent " ") #f)))))))
| null | https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/src/expander/common/performance.rkt | racket | To enable measurement, see the end of this file.
The expression form
(performance-region [key-expr ...] body ....)
records the time of `body ...` and associated it with
the path `(list key-expr ...)`. Times for a path
are included in the times for the path's prefixes, but
not for any other path. When regions that are nested
dynamically, time accumlates only for the most nested
region.
For example,
(performance-region
['compile 'module]
(do-expand-module))
counts the time for `(do-expand-module)` to '(compile) and
to '(compile module), and not to any other path, even if
the compilation occurs while expanding another module.
The key '_ as a path element is special: it is replaced
by the correspondig element of the enclosing region's
path (if any).
Beware that `body ...` is not in tail position when
performance measurement is enabled.
start time
memory allocated before start time
time accumulated for nested regions
ditto, for memory
Replace '_ elements: | #lang racket/base
(require racket/private/place-local)
(provide performance-region
performance-place-init!)
(provide performance-region)
(define log-performance? (and (environment-variables-ref
(current-environment-variables)
#"PLT_EXPANDER_TIMES")
#t))
(define-syntax-rule (performance-region [tag0-expr tag-expr ...] body ...)
(begin
(when log-performance?
(start-performance-region tag0-expr tag-expr ...))
(begin0
(let () body ...)
(when log-performance?
(end-performance-region)))))
(define-place-local region-stack #f)
(define-place-local accums (make-hasheq))
(define (performance-place-init!)
(set! accums (make-hasheq)))
(struct region (path
(struct stat ([msecs #:mutable] [memory #:mutable] [count #:mutable]))
(define stat-key (gensym))
(define (start-performance-region . path)
(set! region-stack (cons (region (if region-stack
(let loop ([path path]
[enclosing-path (region-path (car region-stack))])
(if (null? path)
null
(cons (if (and (eq? '_ (car path))
(pair? enclosing-path))
(car enclosing-path)
(car path))
(loop (cdr path)
(if (pair? enclosing-path)
(cdr enclosing-path)
null)))))
path)
(current-inexact-monotonic-milliseconds)
(current-memory-use 'cumulative)
0.0
0)
region-stack)))
(define (end-performance-region)
(define now (current-inexact-monotonic-milliseconds))
(define now-memory (current-memory-use 'cumulative))
(define r (car region-stack))
(set! region-stack (cdr region-stack))
(define full-delta (- now (region-start r)))
(define delta (- full-delta (region-as-nested r)))
(define full-delta-memory (- now-memory (region-start-memory r)))
(define delta-memory (- full-delta-memory (region-as-nested-memory r)))
(let loop ([accums accums] [path (region-path r)])
(define key (car path))
(let ([accum (or (hash-ref accums key #f)
(let ([accum (make-hasheq)])
(hash-set! accums key accum)
accum))])
(define s (or (hash-ref accum stat-key #f)
(let ([s (stat 0.0 0 0)])
(hash-set! accum stat-key s)
s)))
(set-stat-msecs! s (+ delta (stat-msecs s)))
(set-stat-memory! s (+ delta-memory (stat-memory s)))
(when (null? (cdr path))
(set-stat-count! s (add1 (stat-count s))))
(unless (null? (cdr path))
(loop accum (cdr path)))))
(when region-stack
(set-region-as-nested! (car region-stack)
(+ (region-as-nested (car region-stack))
full-delta))
(set-region-as-nested-memory! (car region-stack)
(+ (region-as-nested-memory (car region-stack))
full-delta-memory))))
(when log-performance?
(void
(plumber-add-flush! (current-plumber)
(lambda (h)
(define (whole-len s)
(caar (or (regexp-match-positions #rx"[.]" s) '(0))))
(define (kb b)
(define s (number->string (quotient b 1024)))
(list->string
(for/fold ([l null]) ([c (in-list (reverse (string->list s)))]
[i (in-naturals)])
(cond
[(and (positive? i) (zero? (modulo i 3)))
(list* c #\, l)]
[else (cons c l)]))))
(define-values (label-max-len value-max-len memory-max-len count-max-len)
(let loop ([accums accums] [label-len 6] [value-len 5] [memory-len 4] [count-len 5] [indent 2])
(for/fold ([label-len label-len]
[value-len value-len]
[memory-len memory-len]
[count-len count-len])
([(k v) (in-hash accums)])
(cond
[(eq? k stat-key)
(values label-len
(max value-len (whole-len (format "~a" (stat-msecs v))))
(max memory-len (string-length (format "~a" (kb (stat-memory v)))))
(max count-len (string-length (format "~a" (stat-count v)))))]
[else (loop v
(max label-len (+ indent (string-length (format "~a" k))))
value-len
memory-len
count-len
(+ 2 indent))]))))
(log-error "REGION ~aMSECS ~aMEMK ~aCOUNT"
(make-string (- (+ label-max-len value-max-len) 11)
#\space)
(make-string (- memory-max-len 4)
#\space)
(make-string (- count-max-len 5)
#\space))
(let loop ([name #f] [accums accums] [indent ""] [newline? #t])
(when name
(define v (hash-ref accums stat-key))
(log-error "~a~a ~a~a ~a~a ~a~a"
indent
name
(make-string (+ (- label-max-len (string-length (format "~a" name)) (string-length indent))
(- value-max-len (whole-len (format "~a" (stat-msecs v)))))
#\space)
(regexp-replace #rx"[.](..).*" (format "~a00" (stat-msecs v)) ".\\1")
(make-string (- memory-max-len (string-length (format "~a" (kb (stat-memory v)))))
#\space)
(kb (stat-memory v))
(make-string (- count-max-len (string-length (format "~a" (stat-count v))))
#\space)
(stat-count v)))
(define keys (sort (for/list ([k (in-hash-keys accums)] #:when (not (eq? k stat-key))) k)
>
#:key (lambda (key) (stat-msecs (hash-ref (hash-ref accums key) stat-key)))))
(for ([k (in-list keys)]
[i (in-naturals)])
(when (and newline? (positive? i)) (log-error ""))
(loop k (hash-ref accums k) (string-append indent " ") #f)))))))
|
ddc27f73c2c48a9debc1f9c159f64e3f77e0f69742ada9316d7dda25a71f1d9b | haroldcarr/learn-haskell-coq-ml-etc | X02.hs | # LANGUAGE NoImplicitPrelude #
module X02 where
import Protolude
-- /#phantom-types
newtypes to distinguish between plaintext and
newtype PlaintextNT = PlaintextNT Text
newtype CryptotextNT = CryptotextNT Text
data Key = Key
encryptNT :: Key -> PlaintextNT -> CryptotextNT
decryptNT :: Key -> CryptotextNT -> PlaintextNT
encryptNT _k (PlaintextNT t) = CryptotextNT t
decryptNT _k (CryptotextNT t) = PlaintextNT t
-- via phantom types
data Cryptotext
data Plaintext
newtype Msg a = Msg Text
encrypt :: Key -> Msg Plaintext -> Msg Cryptotext
decrypt :: Key -> Msg Cryptotext -> Msg Plaintext
encrypt _k (Msg t) = Msg t
decrypt _k (Msg t) = Msg t
-- -XEmptyDataDecls with phantom types that contain no value inhabitants : "anonymous types"
-- {-# LANGUAGE EmptyDataDecls #-}
data Token a
-- The tagged library defines a similar Tagged newtype wrapper.
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/topic/phantoms/hc-phantom/src/X02.hs | haskell | /#phantom-types
via phantom types
-XEmptyDataDecls with phantom types that contain no value inhabitants : "anonymous types"
{-# LANGUAGE EmptyDataDecls #-}
The tagged library defines a similar Tagged newtype wrapper. | # LANGUAGE NoImplicitPrelude #
module X02 where
import Protolude
newtypes to distinguish between plaintext and
newtype PlaintextNT = PlaintextNT Text
newtype CryptotextNT = CryptotextNT Text
data Key = Key
encryptNT :: Key -> PlaintextNT -> CryptotextNT
decryptNT :: Key -> CryptotextNT -> PlaintextNT
encryptNT _k (PlaintextNT t) = CryptotextNT t
decryptNT _k (CryptotextNT t) = PlaintextNT t
data Cryptotext
data Plaintext
newtype Msg a = Msg Text
encrypt :: Key -> Msg Plaintext -> Msg Cryptotext
decrypt :: Key -> Msg Cryptotext -> Msg Plaintext
encrypt _k (Msg t) = Msg t
decrypt _k (Msg t) = Msg t
data Token a
|
3b27999508b2fa58e3aa89a97c631026f7a22b3e7aa64fdd07ddfa221c2ee1ea | bristolpl/intensional-datatys | Constraints.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE BangPatterns #-}
module Self.Constraints
( Guard,
singleton,
Atomic,
Constraint (..),
ConstraintSet,
insert,
guardWith,
saturate,
size
)
where
import Self.Ubiq
import Binary
import Self.Constructors
import Control.Monad.RWS (RWS)
import qualified Control.Monad.RWS as RWS
import Data.Monoid
import Control.Monad.State (State)
import qualified Control.Monad.State as State
import Data.Bifunctor
import qualified Data.Maybe as Maybe
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.IntSet as IS
import qualified GhcPlugins as GHC
import qualified Data.List as List
import Self.Types
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Debug.Trace
data Named a = Named {toPair :: (GHC.Name, a)}
deriving (Eq,Functor)
instance Semigroup a => Semigroup (Named a) where
Named (n, ks1) <> Named (_, ks2) = Named (n, ks1 <> ks2)
instance GHC.Uniquable (Named a) where
getUnique (Named (n,_)) = GHC.getUnique n
instance Binary a => Binary (Named a) where
put_ bh = put_ bh . toPair
get bh = Named <$> Binary.get bh
A set of simple inclusion constraints , i.e. k in X(d ) , grouped by X(d )
newtype Guard
= Guard
{ groups :: IntMap (GHC.NameEnv (Named (GHC.UniqSet GHC.Name)))
}
deriving (Eq)
instance Semigroup Guard where
Guard g <> Guard g' = Guard (IntMap.unionWith (GHC.plusUFM_C (<>)) g g')
instance Monoid Guard where
mempty = Guard mempty
instance GHC.Outputable Guard where
ppr (Guard g) =
let processInner xs =
foldr (\(x,ml) acc -> map ((,) x) ml ++ acc) [] xs
in GHC.pprWithCommas (\(x, (d, ks)) -> GHC.hsep [GHC.ppr ks, GHC.text "in", GHC.ppr (Inj x d)]) $
fmap (second (second GHC.nonDetEltsUniqSet)) . processInner $ second (fmap toPair . GHC.nameEnvElts) <$> IntMap.toList g
instance Binary Guard where
put_ bh (Guard g) = put_ bh (IntMap.toList $ fmap (fmap snd . GHC.nonDetUFMToList . fmap (fmap GHC.nonDetEltsUniqSet)) g)
get bh = Guard . IntMap.fromList . fmap (second (GHC.mkNameEnv . fmap (\(n,ks) -> (n, Named (n, GHC.mkUniqSet ks))))) <$> Binary.get bh
instance Refined Guard where
domain (Guard g) = IntMap.keysSet g
rename x y (Guard g) =
Guard
( IntMap.fromList $
IntMap.foldrWithKey (\k a as -> (if k == x then y else k, a) : as) [] g
)
guardLookup :: DataType GHC.Name -> Guard -> Maybe (GHC.UniqSet GHC.Name)
guardLookup (Inj x d) (Guard g) =
fmap (snd . toPair) . flip GHC.lookupUFM d =<< IntMap.lookup x g
-- A guard literal
Ignorning possibly trivial guards ( e.g. 1 - constructor types has already
-- happened in InferM.branch)
singleton :: GHC.Name -> DataType GHC.Name -> Guard
singleton k (Inj x d) =
Guard (IntMap.singleton x (GHC.unitNameEnv d (Named (d, GHC.unitUniqSet k))))
guardsFromList :: [GHC.Name] -> DataType GHC.Name -> Guard
guardsFromList ks (Inj x d) = foldr (\k gs -> singleton k (Inj x d) <> gs) mempty ks
type Atomic = Constraint 'L 'R
-- A pair of constructor sets
data Constraint l r
= Constraint
{ left :: K l,
right :: K r,
guard :: Guard,
srcSpan :: GHC.SrcSpan
}
-- Disregard location in comparison
instance Eq (Constraint l r) where
Constraint l r g _ == Constraint l' r' g' _ = l == l' && r == r' && g == g'
instance Hashable ( Constraint l r ) where
hashWithSalt s c = hashWithSalt s ( left c , right c , second GHC.nonDetEltsUniqSet < $ > HM.toList ( groups ( guard c ) ) )
instance GHC.Outputable (Constraint l r) where
ppr a = GHC.ppr (guard a) GHC.<+> GHC.char '?' GHC.<+> GHC.ppr (left a) GHC.<+> GHC.arrowt GHC.<+> GHC.ppr (right a)
instance (Binary (K l), Binary (K r)) => Binary (Constraint l r) where
put_ bh c = put_ bh (left c) >> put_ bh (right c) >> put_ bh (guard c) >> put_ bh (Self.Constraints.srcSpan c)
get bh = Constraint <$> Binary.get bh <*> Binary.get bh <*> Binary.get bh <*> Binary.get bh
instance Refined (Constraint l r) where
domain c = domain (left c) <> domain (right c) <> domain (guard c)
rename x y c =
c
{ left = rename x y (left c),
right = rename x y (right c),
guard = rename x y (guard c)
}
Is the first constraint a weaker version of the second , i.e. has a larger guard
impliedBy :: Atomic -> Atomic -> Bool
impliedBy a a' =
left a == left a' && right a == right a' && guard a `gimpliedBy` guard a'
gimpliedBy :: Guard -> Guard -> Bool
gimpliedBy a a' =
let Guard g = a
Guard g' = a'
keyInclusion (Named (_,u1)) (Named (_,u2)) =
# SCC keyInclusion #
IntMap.isSubmapOfBy (\_ _ -> True) (GHC.ufmToIntMap $ GHC.getUniqSet u1) (GHC.ufmToIntMap $ GHC.getUniqSet u2)
# SCC " InnerLoop " #
-- in getAll $
-- HM.foldMapWithKey
( \d ks - >
case of
Nothing - > All ( ks )
-- Just ks' -> All (GHC.uniqSetAll (`GHC.elementOfUniqSet` ks') ks)
-- )
-- g'
-- A constraint is trivially satisfied
tautology :: Atomic -> Bool
tautology a =
case left a of
Dom d ->
case right a of
Dom d' -> d == d'
_ -> False
Con k _ ->
case right a of
Dom d ->
case guardLookup d (guard a) of
Just ks -> GHC.elementOfUniqSet k ks
Nothing -> False
Set ks _ -> GHC.elementOfUniqSet k ks
-- A constraint that defines a refinement variable which also appears in the guard
i.e. k in X(d ) ? Y(d ) = > X(d )
-- A group of recursive constraints has an empty minimum model
recursive :: Atomic -> Bool
recursive a =
case right a of
Dom d ->
case guardLookup d (guard a) of
Nothing -> False
Just ks -> not (GHC.isEmptyUniqSet ks)
Set _ _ -> False
Apply all possible lhs constraints to a in all possible ways using the saturation rules
resolve' :: IS.IntSet -> ConstraintSet -> Atomic -> [Atomic]
trace ( " Totalling : " + + show ( length new ) ) new
where
-- Turn the guard into a list of shape [(x,[(d1,[k1,...]),...]),...]
guardAsList = fmap (second (fmap toPair . GHC.nameEnvElts)) $ IntMap.toList (groups $ guard a)
We need to unpack it into atomic propositions [ ( x , d1,k1 ) , ... ]
easierGuardList1 = concatMap (\(x,ds) -> [ (x, d, GHC.nonDetEltsUniqSet ks) | (d,ks) <- ds]) guardAsList
easierGuardList2 = concatMap ( \(x , ds ) - > [ ( x , d , k ) | ( d , k ) < - concatMap ( \(d , ks ) - > [ ( d , k ) | k < - GHC.nonDetEltsUniqSet ks ] ) ds ] ) guardAsList
-- Map each entry `k in x(d)` to a list of possible resolvants
guardAlternatives = map getAlts easierGuardList1
where getAlts (x,d,ks) =
let -- Substitutions
ne = IntMap.findWithDefault mempty x (definite cs)
hm = GHC.lookupWithDefaultUFM ne mempty d
as = HashMap.toList hm
ne' = IntMap.findWithDefault mempty x (indefinite cs)
hm' = GHC.lookupWithDefaultUFM ne' mempty d
in if not (x `IS.member` dom)
then [guardsFromList ks (Inj x d)] -- x is not in the domain of resolution
else concatMap (\((y,_), bs) -> [guardsFromList ks (Inj y d) <> guard b | b <- bs]) as
++ (map mconcat $ sequence (map (\k -> map guard (HashMap.findWithDefault [] k hm')) ks))
Note : if one of the guards involves ) and x is in the domain but there are no
resolvers with x(d ) in the head , then prodOfAlts will be empty and so we will return [ ]
This corresponds to setting ) to empty , which falisfies the guard and renders the
-- constraint trivial.
impSequenceW :: (a -> Guard -> Guard) -> [[a]] -> [Guard]
impSequenceW _ [] = [mempty]
impSequenceW f (ma:mas) =
foldl addToResult [] [ (a, as) | a <- ma, as <- allMas]
where
allMas = impSequenceW f mas
addToResult gs (a,as) =
let g = f a as in if any (g `gimpliedBy`) gs then gs else g : filter (not . (`gimpliedBy` g)) gs
prodOfAlts = impSequenceW (<>) guardAlternatives
-- Resolve `left a` with all possibilities
addOrNot (b, g) rs =
let c = a { left = left b, guard = guard b <> g }
in if any (c `impliedBy`) rs then rs else c:filter (not . (`impliedBy` c)) rs
new = foldr addOrNot [] $ [ (x,y) | x <- bs, y <- prodOfAlts]
where
bs =
case left a of
Con _ _ -> [a]
Dom (Inj x d) ->
let -- Transitivity
ne = IntMap.findWithDefault mempty x (definite cs)
hm = GHC.lookupWithDefaultUFM ne mempty d
ne' = IntMap.findWithDefault mempty x (indefinite cs)
hm' = GHC.lookupWithDefaultUFM ne' mempty d
in if not (x `IS.member` dom) then [a] else concat $ HashMap.elems hm ++ HashMap.elems hm'
_ -> GHC.pprPanic "Not possible to have any other kind of constructor here" GHC.empty
data ConstraintSet
= ConstraintSet
{
definite :: IntMap (GHC.NameEnv (HashMap (Int,GHC.Name) [Atomic])),
indefinite :: IntMap (GHC.NameEnv (HashMap GHC.Name [Atomic])),
goal :: [Atomic]
}
deriving (Eq)
instance Semigroup ConstraintSet where
cs <> ds = fold (flip insert) ds cs
instance Monoid ConstraintSet where
mempty = empty
instance GHC.Outputable ConstraintSet where
ppr = fold (flip $ (GHC.$$) . GHC.ppr) GHC.empty
instance Binary ConstraintSet where
put_ bh cs =
do put_ bh (IntMap.toList $ fmap GHC.nameEnvElts $ fmap (fmap HashMap.toList) (definite cs))
put_ bh (IntMap.toList $ fmap GHC.nameEnvElts $ fmap (fmap HashMap.toList) (indefinite cs))
put_ bh (goal cs)
get bh =
do df <- fmap (fmap HashMap.fromList) <$> (fmap GHC.mkNameEnv <$> (IntMap.fromList <$> Binary.get bh))
nf <- fmap (fmap HashMap.fromList) <$> (fmap GHC.mkNameEnv <$> (IntMap.fromList <$> Binary.get bh))
gl <- Binary.get bh
return (ConstraintSet df nf gl)
instance Refined ConstraintSet where
domain cs =
foldMap (foldMapUFM (foldMap (foldMap domain))) (definite cs)
<> foldMap (foldMapUFM (foldMap (foldMap domain))) (indefinite cs)
<> foldMap domain (goal cs)
where
foldMapUFM f u =
GHC.foldUFM (\a b -> f a <> b) mempty u
rename x y cs =
fold (\ds a -> unsafeInsert (rename x y a) ds) empty cs
empty :: ConstraintSet
empty =
ConstraintSet {
definite = mempty,
indefinite = mempty,
goal = []
}
fold :: (b -> Atomic -> b) -> b -> ConstraintSet -> b
fold f z0 cs = z3
where
foldlUFM f b = IntMap.foldl' f b . GHC.ufmToIntMap
!z1 = IntMap.foldl' (foldlUFM (HashMap.foldl' (List.foldl' f))) z0 (definite cs)
!z2 = IntMap.foldl' (foldlUFM (HashMap.foldl' (List.foldl' f))) z1 (indefinite cs)
!z3 = List.foldl' f z2 (goal cs)
-- | When `cs` is a constraint set, `size cs` is the number of constraints in it.
size :: ConstraintSet -> Int
size = fold (\sz _ -> 1 + sz) 0
mapAction :: Monad m => (Atomic -> m ()) -> ConstraintSet -> m ()
mapAction f cs = fold (\b a -> b >> f a) (return ()) cs
unsafeInsert :: Atomic -> ConstraintSet -> ConstraintSet
unsafeInsert a cs =
case (left a, right a) of
(Dom (Inj x xd), Dom (Inj y yd)) ->
let ne = IntMap.findWithDefault mempty y (definite cs)
hm = GHC.lookupWithDefaultUFM ne mempty yd
as = HashMap.findWithDefault [] (x,xd) hm
in cs { definite = IntMap.insert y (GHC.addToUFM ne yd (HashMap.insert (x,xd) (a:as) hm)) (definite cs) }
(Con k _, Dom (Inj y yd)) ->
let ne = IntMap.findWithDefault mempty y (indefinite cs)
hm = GHC.lookupWithDefaultUFM ne mempty yd
as = HashMap.findWithDefault [] k hm
in cs { indefinite = IntMap.insert y (GHC.addToUFM ne yd (HashMap.insert k (a:as) hm)) (indefinite cs) }
(_, Set _ _) -> cs { goal = a : goal cs }
(_, _) -> cs
insert' :: Atomic -> ConstraintSet -> Maybe ConstraintSet
insert' a cs | not (tautology a) =
case (left a, right a) of
(Dom (Inj x xd), Dom (Inj y yd)) ->
let ne = IntMap.findWithDefault mempty y (definite cs)
hm = GHC.lookupWithDefaultUFM ne mempty yd
as = HashMap.findWithDefault [] (x,xd) hm
in fmap (\as' -> cs { definite = IntMap.insert y (GHC.addToUFM ne yd (HashMap.insert (x,xd) as' hm)) (definite cs) }) (maintain as)
(Con k _, Dom (Inj y yd)) ->
let ne = IntMap.findWithDefault mempty y (indefinite cs)
hm = GHC.lookupWithDefaultUFM ne mempty yd
as = HashMap.findWithDefault [] k hm
in fmap (\as' -> cs { indefinite = IntMap.insert y (GHC.addToUFM ne yd (HashMap.insert k as' hm)) (indefinite cs) }) (maintain as)
(_, Set _ _) ->
fmap (\as' -> cs { goal = as' }) (maintain (goal cs))
(_, _) -> Nothing -- Ignore constraints concerning base types
where
maintain ds =
if any (a `impliedBy`) ds then Nothing else Just (a : filter (not . (`impliedBy` a)) ds)
insert' _ _ = Nothing
-- Add an atomic constriant to the set
-- ensuring to maintain the invariant
insert :: Atomic -> ConstraintSet -> ConstraintSet
insert a cs = Maybe.fromMaybe cs (insert' a cs)
-- Add a guard to every constraint
guardWith :: Guard -> ConstraintSet -> ConstraintSet
guardWith g cs =
cs
{
definite = IntMap.map (GHC.mapUFM (HashMap.map (List.map go))) (definite cs),
indefinite = IntMap.map (GHC.mapUFM (HashMap.map (List.map go))) (indefinite cs),
goal = map go (goal cs)
}
where
go a = a {guard = g <> guard a}
saturate :: IS.IntSet -> ConstraintSet -> ConstraintSet
saturate iface cs =
if size ds <= size cs then ds else cs
where
dom = domain cs IS.\\ iface
ds = State.execState (mapM_ saturateI $ IS.toList dom) cs
saturateI :: Int -> State ConstraintSet ()
saturateI i =
do cs <- State.get -- dom is the domain of ds
let df = IntMap.lookup i $ definite cs
let nf = IntMap.lookup i $ indefinite cs
let rs = cs { definite = IntMap.delete i (definite cs), indefinite = IntMap.delete i (indefinite cs) }
let is = empty { definite = maybe mempty (IntMap.singleton i) df, indefinite = maybe mempty (IntMap.singleton i) nf }
let filterRec1 =
GHC.filterUFM (not . null) . fmap (HashMap.filter (not . null)) . fmap (fmap $ List.filter (\a -> not $ IS.member i $ domain (left a) <> domain (guard a)))
let filterRec2 =
GHC.filterUFM (not . null) . fmap (HashMap.filter (not . null)) . fmap (fmap $ List.filter (\a -> not $ IS.member i $ domain (left a) <> domain (guard a)))
let ss = fixI (IS.singleton i) is is
-- Remove any recursive clauses since saturation completed
let ls = ss { definite = IntMap.adjust filterRec1 i (definite ss), indefinite = IntMap.adjust filterRec2 i (indefinite ss) }
let ds = fst $ RWS.execRWS (saturateF (IS.singleton i) ls rs) mempty mempty
let ds' = if debugging then trace ("[TRACE] SaturateI (#lhs: " ++ show (size ls) ++ ") (#rhs: " ++ show (size rs) ++ ") (#resolvants:" ++ show (size ds) ++ ")") ds else ds
State.put ds'
fixI :: IS.IntSet -> ConstraintSet -> ConstraintSet -> ConstraintSet
fixI dom ls rs =
case RWS.execRWS (saturateF dom ls rs) rs mempty of
(!cs', Any True) -> fixI dom ls cs' -- New constraint have been found, i.e. not a fixedpoint
(!cs', Any False) -> cs'
One step consequence operator for saturation rules concerning a particular refinement variable
saturateF :: IS.IntSet -> ConstraintSet -> ConstraintSet -> RWS ConstraintSet Any ConstraintSet ()
saturateF dom ls rs =
mapAction resolveWith rs
where
addResolvant r = do
es <- RWS.ask
ds <- RWS.get
case insert' r ds of
Just ds' ->
do RWS.put ds'
case insert' r es of
Nothing -> return ()
Just _ -> RWS.tell (Any True)
Nothing -> return ()
resolveWith c = do
let rss = resolve' dom ls c
mapM_ addResolvant rss
| null | https://raw.githubusercontent.com/bristolpl/intensional-datatys/ce6e7f5069530ea21a3e19c8e9e17fc23dc8e66c/test/Self/Constraints.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE BangPatterns #
A guard literal
happened in InferM.branch)
A pair of constructor sets
Disregard location in comparison
in getAll $
HM.foldMapWithKey
Just ks' -> All (GHC.uniqSetAll (`GHC.elementOfUniqSet` ks') ks)
)
g'
A constraint is trivially satisfied
A constraint that defines a refinement variable which also appears in the guard
A group of recursive constraints has an empty minimum model
Turn the guard into a list of shape [(x,[(d1,[k1,...]),...]),...]
Map each entry `k in x(d)` to a list of possible resolvants
Substitutions
x is not in the domain of resolution
constraint trivial.
Resolve `left a` with all possibilities
Transitivity
| When `cs` is a constraint set, `size cs` is the number of constraints in it.
Ignore constraints concerning base types
Add an atomic constriant to the set
ensuring to maintain the invariant
Add a guard to every constraint
dom is the domain of ds
Remove any recursive clauses since saturation completed
New constraint have been found, i.e. not a fixedpoint | # LANGUAGE DataKinds #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
module Self.Constraints
( Guard,
singleton,
Atomic,
Constraint (..),
ConstraintSet,
insert,
guardWith,
saturate,
size
)
where
import Self.Ubiq
import Binary
import Self.Constructors
import Control.Monad.RWS (RWS)
import qualified Control.Monad.RWS as RWS
import Data.Monoid
import Control.Monad.State (State)
import qualified Control.Monad.State as State
import Data.Bifunctor
import qualified Data.Maybe as Maybe
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.IntSet as IS
import qualified GhcPlugins as GHC
import qualified Data.List as List
import Self.Types
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Debug.Trace
data Named a = Named {toPair :: (GHC.Name, a)}
deriving (Eq,Functor)
instance Semigroup a => Semigroup (Named a) where
Named (n, ks1) <> Named (_, ks2) = Named (n, ks1 <> ks2)
instance GHC.Uniquable (Named a) where
getUnique (Named (n,_)) = GHC.getUnique n
instance Binary a => Binary (Named a) where
put_ bh = put_ bh . toPair
get bh = Named <$> Binary.get bh
A set of simple inclusion constraints , i.e. k in X(d ) , grouped by X(d )
newtype Guard
= Guard
{ groups :: IntMap (GHC.NameEnv (Named (GHC.UniqSet GHC.Name)))
}
deriving (Eq)
instance Semigroup Guard where
Guard g <> Guard g' = Guard (IntMap.unionWith (GHC.plusUFM_C (<>)) g g')
instance Monoid Guard where
mempty = Guard mempty
instance GHC.Outputable Guard where
ppr (Guard g) =
let processInner xs =
foldr (\(x,ml) acc -> map ((,) x) ml ++ acc) [] xs
in GHC.pprWithCommas (\(x, (d, ks)) -> GHC.hsep [GHC.ppr ks, GHC.text "in", GHC.ppr (Inj x d)]) $
fmap (second (second GHC.nonDetEltsUniqSet)) . processInner $ second (fmap toPair . GHC.nameEnvElts) <$> IntMap.toList g
instance Binary Guard where
put_ bh (Guard g) = put_ bh (IntMap.toList $ fmap (fmap snd . GHC.nonDetUFMToList . fmap (fmap GHC.nonDetEltsUniqSet)) g)
get bh = Guard . IntMap.fromList . fmap (second (GHC.mkNameEnv . fmap (\(n,ks) -> (n, Named (n, GHC.mkUniqSet ks))))) <$> Binary.get bh
instance Refined Guard where
domain (Guard g) = IntMap.keysSet g
rename x y (Guard g) =
Guard
( IntMap.fromList $
IntMap.foldrWithKey (\k a as -> (if k == x then y else k, a) : as) [] g
)
guardLookup :: DataType GHC.Name -> Guard -> Maybe (GHC.UniqSet GHC.Name)
guardLookup (Inj x d) (Guard g) =
fmap (snd . toPair) . flip GHC.lookupUFM d =<< IntMap.lookup x g
Ignorning possibly trivial guards ( e.g. 1 - constructor types has already
singleton :: GHC.Name -> DataType GHC.Name -> Guard
singleton k (Inj x d) =
Guard (IntMap.singleton x (GHC.unitNameEnv d (Named (d, GHC.unitUniqSet k))))
guardsFromList :: [GHC.Name] -> DataType GHC.Name -> Guard
guardsFromList ks (Inj x d) = foldr (\k gs -> singleton k (Inj x d) <> gs) mempty ks
type Atomic = Constraint 'L 'R
data Constraint l r
= Constraint
{ left :: K l,
right :: K r,
guard :: Guard,
srcSpan :: GHC.SrcSpan
}
instance Eq (Constraint l r) where
Constraint l r g _ == Constraint l' r' g' _ = l == l' && r == r' && g == g'
instance Hashable ( Constraint l r ) where
hashWithSalt s c = hashWithSalt s ( left c , right c , second GHC.nonDetEltsUniqSet < $ > HM.toList ( groups ( guard c ) ) )
instance GHC.Outputable (Constraint l r) where
ppr a = GHC.ppr (guard a) GHC.<+> GHC.char '?' GHC.<+> GHC.ppr (left a) GHC.<+> GHC.arrowt GHC.<+> GHC.ppr (right a)
instance (Binary (K l), Binary (K r)) => Binary (Constraint l r) where
put_ bh c = put_ bh (left c) >> put_ bh (right c) >> put_ bh (guard c) >> put_ bh (Self.Constraints.srcSpan c)
get bh = Constraint <$> Binary.get bh <*> Binary.get bh <*> Binary.get bh <*> Binary.get bh
instance Refined (Constraint l r) where
domain c = domain (left c) <> domain (right c) <> domain (guard c)
rename x y c =
c
{ left = rename x y (left c),
right = rename x y (right c),
guard = rename x y (guard c)
}
Is the first constraint a weaker version of the second , i.e. has a larger guard
impliedBy :: Atomic -> Atomic -> Bool
impliedBy a a' =
left a == left a' && right a == right a' && guard a `gimpliedBy` guard a'
gimpliedBy :: Guard -> Guard -> Bool
gimpliedBy a a' =
let Guard g = a
Guard g' = a'
keyInclusion (Named (_,u1)) (Named (_,u2)) =
# SCC keyInclusion #
IntMap.isSubmapOfBy (\_ _ -> True) (GHC.ufmToIntMap $ GHC.getUniqSet u1) (GHC.ufmToIntMap $ GHC.getUniqSet u2)
# SCC " InnerLoop " #
( \d ks - >
case of
Nothing - > All ( ks )
tautology :: Atomic -> Bool
tautology a =
case left a of
Dom d ->
case right a of
Dom d' -> d == d'
_ -> False
Con k _ ->
case right a of
Dom d ->
case guardLookup d (guard a) of
Just ks -> GHC.elementOfUniqSet k ks
Nothing -> False
Set ks _ -> GHC.elementOfUniqSet k ks
i.e. k in X(d ) ? Y(d ) = > X(d )
recursive :: Atomic -> Bool
recursive a =
case right a of
Dom d ->
case guardLookup d (guard a) of
Nothing -> False
Just ks -> not (GHC.isEmptyUniqSet ks)
Set _ _ -> False
Apply all possible lhs constraints to a in all possible ways using the saturation rules
resolve' :: IS.IntSet -> ConstraintSet -> Atomic -> [Atomic]
trace ( " Totalling : " + + show ( length new ) ) new
where
guardAsList = fmap (second (fmap toPair . GHC.nameEnvElts)) $ IntMap.toList (groups $ guard a)
We need to unpack it into atomic propositions [ ( x , d1,k1 ) , ... ]
easierGuardList1 = concatMap (\(x,ds) -> [ (x, d, GHC.nonDetEltsUniqSet ks) | (d,ks) <- ds]) guardAsList
easierGuardList2 = concatMap ( \(x , ds ) - > [ ( x , d , k ) | ( d , k ) < - concatMap ( \(d , ks ) - > [ ( d , k ) | k < - GHC.nonDetEltsUniqSet ks ] ) ds ] ) guardAsList
guardAlternatives = map getAlts easierGuardList1
where getAlts (x,d,ks) =
ne = IntMap.findWithDefault mempty x (definite cs)
hm = GHC.lookupWithDefaultUFM ne mempty d
as = HashMap.toList hm
ne' = IntMap.findWithDefault mempty x (indefinite cs)
hm' = GHC.lookupWithDefaultUFM ne' mempty d
in if not (x `IS.member` dom)
else concatMap (\((y,_), bs) -> [guardsFromList ks (Inj y d) <> guard b | b <- bs]) as
++ (map mconcat $ sequence (map (\k -> map guard (HashMap.findWithDefault [] k hm')) ks))
Note : if one of the guards involves ) and x is in the domain but there are no
resolvers with x(d ) in the head , then prodOfAlts will be empty and so we will return [ ]
This corresponds to setting ) to empty , which falisfies the guard and renders the
impSequenceW :: (a -> Guard -> Guard) -> [[a]] -> [Guard]
impSequenceW _ [] = [mempty]
impSequenceW f (ma:mas) =
foldl addToResult [] [ (a, as) | a <- ma, as <- allMas]
where
allMas = impSequenceW f mas
addToResult gs (a,as) =
let g = f a as in if any (g `gimpliedBy`) gs then gs else g : filter (not . (`gimpliedBy` g)) gs
prodOfAlts = impSequenceW (<>) guardAlternatives
addOrNot (b, g) rs =
let c = a { left = left b, guard = guard b <> g }
in if any (c `impliedBy`) rs then rs else c:filter (not . (`impliedBy` c)) rs
new = foldr addOrNot [] $ [ (x,y) | x <- bs, y <- prodOfAlts]
where
bs =
case left a of
Con _ _ -> [a]
Dom (Inj x d) ->
ne = IntMap.findWithDefault mempty x (definite cs)
hm = GHC.lookupWithDefaultUFM ne mempty d
ne' = IntMap.findWithDefault mempty x (indefinite cs)
hm' = GHC.lookupWithDefaultUFM ne' mempty d
in if not (x `IS.member` dom) then [a] else concat $ HashMap.elems hm ++ HashMap.elems hm'
_ -> GHC.pprPanic "Not possible to have any other kind of constructor here" GHC.empty
data ConstraintSet
= ConstraintSet
{
definite :: IntMap (GHC.NameEnv (HashMap (Int,GHC.Name) [Atomic])),
indefinite :: IntMap (GHC.NameEnv (HashMap GHC.Name [Atomic])),
goal :: [Atomic]
}
deriving (Eq)
instance Semigroup ConstraintSet where
cs <> ds = fold (flip insert) ds cs
instance Monoid ConstraintSet where
mempty = empty
instance GHC.Outputable ConstraintSet where
ppr = fold (flip $ (GHC.$$) . GHC.ppr) GHC.empty
instance Binary ConstraintSet where
put_ bh cs =
do put_ bh (IntMap.toList $ fmap GHC.nameEnvElts $ fmap (fmap HashMap.toList) (definite cs))
put_ bh (IntMap.toList $ fmap GHC.nameEnvElts $ fmap (fmap HashMap.toList) (indefinite cs))
put_ bh (goal cs)
get bh =
do df <- fmap (fmap HashMap.fromList) <$> (fmap GHC.mkNameEnv <$> (IntMap.fromList <$> Binary.get bh))
nf <- fmap (fmap HashMap.fromList) <$> (fmap GHC.mkNameEnv <$> (IntMap.fromList <$> Binary.get bh))
gl <- Binary.get bh
return (ConstraintSet df nf gl)
instance Refined ConstraintSet where
domain cs =
foldMap (foldMapUFM (foldMap (foldMap domain))) (definite cs)
<> foldMap (foldMapUFM (foldMap (foldMap domain))) (indefinite cs)
<> foldMap domain (goal cs)
where
foldMapUFM f u =
GHC.foldUFM (\a b -> f a <> b) mempty u
rename x y cs =
fold (\ds a -> unsafeInsert (rename x y a) ds) empty cs
empty :: ConstraintSet
empty =
ConstraintSet {
definite = mempty,
indefinite = mempty,
goal = []
}
fold :: (b -> Atomic -> b) -> b -> ConstraintSet -> b
fold f z0 cs = z3
where
foldlUFM f b = IntMap.foldl' f b . GHC.ufmToIntMap
!z1 = IntMap.foldl' (foldlUFM (HashMap.foldl' (List.foldl' f))) z0 (definite cs)
!z2 = IntMap.foldl' (foldlUFM (HashMap.foldl' (List.foldl' f))) z1 (indefinite cs)
!z3 = List.foldl' f z2 (goal cs)
size :: ConstraintSet -> Int
size = fold (\sz _ -> 1 + sz) 0
mapAction :: Monad m => (Atomic -> m ()) -> ConstraintSet -> m ()
mapAction f cs = fold (\b a -> b >> f a) (return ()) cs
unsafeInsert :: Atomic -> ConstraintSet -> ConstraintSet
unsafeInsert a cs =
case (left a, right a) of
(Dom (Inj x xd), Dom (Inj y yd)) ->
let ne = IntMap.findWithDefault mempty y (definite cs)
hm = GHC.lookupWithDefaultUFM ne mempty yd
as = HashMap.findWithDefault [] (x,xd) hm
in cs { definite = IntMap.insert y (GHC.addToUFM ne yd (HashMap.insert (x,xd) (a:as) hm)) (definite cs) }
(Con k _, Dom (Inj y yd)) ->
let ne = IntMap.findWithDefault mempty y (indefinite cs)
hm = GHC.lookupWithDefaultUFM ne mempty yd
as = HashMap.findWithDefault [] k hm
in cs { indefinite = IntMap.insert y (GHC.addToUFM ne yd (HashMap.insert k (a:as) hm)) (indefinite cs) }
(_, Set _ _) -> cs { goal = a : goal cs }
(_, _) -> cs
insert' :: Atomic -> ConstraintSet -> Maybe ConstraintSet
insert' a cs | not (tautology a) =
case (left a, right a) of
(Dom (Inj x xd), Dom (Inj y yd)) ->
let ne = IntMap.findWithDefault mempty y (definite cs)
hm = GHC.lookupWithDefaultUFM ne mempty yd
as = HashMap.findWithDefault [] (x,xd) hm
in fmap (\as' -> cs { definite = IntMap.insert y (GHC.addToUFM ne yd (HashMap.insert (x,xd) as' hm)) (definite cs) }) (maintain as)
(Con k _, Dom (Inj y yd)) ->
let ne = IntMap.findWithDefault mempty y (indefinite cs)
hm = GHC.lookupWithDefaultUFM ne mempty yd
as = HashMap.findWithDefault [] k hm
in fmap (\as' -> cs { indefinite = IntMap.insert y (GHC.addToUFM ne yd (HashMap.insert k as' hm)) (indefinite cs) }) (maintain as)
(_, Set _ _) ->
fmap (\as' -> cs { goal = as' }) (maintain (goal cs))
where
maintain ds =
if any (a `impliedBy`) ds then Nothing else Just (a : filter (not . (`impliedBy` a)) ds)
insert' _ _ = Nothing
insert :: Atomic -> ConstraintSet -> ConstraintSet
insert a cs = Maybe.fromMaybe cs (insert' a cs)
guardWith :: Guard -> ConstraintSet -> ConstraintSet
guardWith g cs =
cs
{
definite = IntMap.map (GHC.mapUFM (HashMap.map (List.map go))) (definite cs),
indefinite = IntMap.map (GHC.mapUFM (HashMap.map (List.map go))) (indefinite cs),
goal = map go (goal cs)
}
where
go a = a {guard = g <> guard a}
saturate :: IS.IntSet -> ConstraintSet -> ConstraintSet
saturate iface cs =
if size ds <= size cs then ds else cs
where
dom = domain cs IS.\\ iface
ds = State.execState (mapM_ saturateI $ IS.toList dom) cs
saturateI :: Int -> State ConstraintSet ()
saturateI i =
let df = IntMap.lookup i $ definite cs
let nf = IntMap.lookup i $ indefinite cs
let rs = cs { definite = IntMap.delete i (definite cs), indefinite = IntMap.delete i (indefinite cs) }
let is = empty { definite = maybe mempty (IntMap.singleton i) df, indefinite = maybe mempty (IntMap.singleton i) nf }
let filterRec1 =
GHC.filterUFM (not . null) . fmap (HashMap.filter (not . null)) . fmap (fmap $ List.filter (\a -> not $ IS.member i $ domain (left a) <> domain (guard a)))
let filterRec2 =
GHC.filterUFM (not . null) . fmap (HashMap.filter (not . null)) . fmap (fmap $ List.filter (\a -> not $ IS.member i $ domain (left a) <> domain (guard a)))
let ss = fixI (IS.singleton i) is is
let ls = ss { definite = IntMap.adjust filterRec1 i (definite ss), indefinite = IntMap.adjust filterRec2 i (indefinite ss) }
let ds = fst $ RWS.execRWS (saturateF (IS.singleton i) ls rs) mempty mempty
let ds' = if debugging then trace ("[TRACE] SaturateI (#lhs: " ++ show (size ls) ++ ") (#rhs: " ++ show (size rs) ++ ") (#resolvants:" ++ show (size ds) ++ ")") ds else ds
State.put ds'
fixI :: IS.IntSet -> ConstraintSet -> ConstraintSet -> ConstraintSet
fixI dom ls rs =
case RWS.execRWS (saturateF dom ls rs) rs mempty of
(!cs', Any False) -> cs'
One step consequence operator for saturation rules concerning a particular refinement variable
saturateF :: IS.IntSet -> ConstraintSet -> ConstraintSet -> RWS ConstraintSet Any ConstraintSet ()
saturateF dom ls rs =
mapAction resolveWith rs
where
addResolvant r = do
es <- RWS.ask
ds <- RWS.get
case insert' r ds of
Just ds' ->
do RWS.put ds'
case insert' r es of
Nothing -> return ()
Just _ -> RWS.tell (Any True)
Nothing -> return ()
resolveWith c = do
let rss = resolve' dom ls c
mapM_ addResolvant rss
|
b939fcd33021936f1a4565234d7a461f52e6ddf4e2e0dbbf734dc56e9afe902e | avsm/eeww | tests.ml |
let mk_temp_dir () =
let rand_num = Random.int 1000000 |> string_of_int in
let tmp_dir = Filename.get_temp_dir_name () ^ "/test-cstruct-unix-" ^ rand_num in
try
Unix.mkdir tmp_dir 0o700;
tmp_dir
with Unix.Unix_error(Unix.EEXIST, _, _) ->
re - use the old one
tmp_dir
| e -> raise (Sys_error ("Cannot create temp dir " ^ tmp_dir ^ " " ^ (Printexc.to_string e)))
let rmdir path =
(* non-recursive for safety *)
match Sys.is_directory path with
| true ->
Sys.readdir path |>
Array.iter (fun name -> Sys.remove (Filename.concat path name));
Unix.rmdir path
| false -> Sys.remove path
let finally f g =
try
let r = f () in
g ();
r
with e ->
g ();
raise e
let with_tmp_dir f =
let dir = mk_temp_dir () in
finally (fun () -> f dir) (fun () -> rmdir dir)
let test_message_list =[
Cstruct.of_string "hello";
Cstruct.of_string " ";
Cstruct.of_string "cstruct";
Cstruct.create 0;
Cstruct.of_string " ";
Cstruct.of_string "world";
]
let read_and_check fd sent_message =
let expected = Cstruct.(to_string @@ concat sent_message) in
let buf = Cstruct.create 1024 in
let read = ref 0 in
while !read < (String.length expected) do
let n = Unix_cstruct.read fd (Cstruct.shift buf !read) in
if n = 0 then raise End_of_file;
read := !read + n
done;
let actual = Cstruct.(to_string @@ sub buf 0 !read) in
Alcotest.(check string) "read contents" expected actual
let test_writev_file () =
with_tmp_dir
(fun dir ->
let test = Filename.concat dir "test" in
let fd = Unix.openfile test [ Unix.O_CREAT; Unix.O_RDWR ] 0o644 in
finally (fun () ->
Unix_cstruct.writev fd test_message_list;
let ofs = Unix.lseek fd 0 Unix.SEEK_SET in
Alcotest.(check int) "file offset" 0 ofs;
read_and_check fd test_message_list
) (fun () -> Unix.close fd)
)
let with_sock_stream f =
let s = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
finally (fun () -> f s) (fun () -> Unix.close s)
let localhost = Unix.inet_addr_of_string "127.0.0.1"
let bind_random_port s =
Unix.bind s (Unix.ADDR_INET(localhost, 0));
match Unix.getsockname s with
| Unix.ADDR_INET(_, port) -> port
| _ -> assert false
let test_writev_socket () =
with_sock_stream (fun s ->
let port = bind_random_port s in
Unix.listen s 1;
let t = Thread.create (fun () ->
let client, _ = Unix.accept s in
finally
(fun () ->
read_and_check client test_message_list
) (fun () -> Unix.close client)
) () in
with_sock_stream (fun c ->
Unix.connect c (Unix.ADDR_INET(localhost, port));
Unix_cstruct.writev c test_message_list;
);
Thread.join t
)
let with_sock_dgram f =
let s = Unix.socket Unix.PF_INET Unix.SOCK_DGRAM 0 in
finally (fun () -> f s) (fun () -> Unix.close s)
let with_mutex m f =
Mutex.lock m;
finally f (fun () -> Mutex.unlock m)
let test_send_recv () =
let test_message = Cstruct.concat test_message_list in
with_sock_dgram (fun s ->
let port = bind_random_port s in
let m = Mutex.create () in
let finished = ref false in
let t = Thread.create (fun () ->
let buf = Cstruct.create 1024 in
let n = Unix_cstruct.recv s buf [] in
Alcotest.(check int) "recv length" (Cstruct.length test_message) n;
let expected = Cstruct.to_string test_message in
let actual = Cstruct.(to_string @@ sub buf 0 n) in
Alcotest.(check string) "read contents" expected actual;
with_mutex m (fun () -> finished := true)
) () in
with_sock_dgram (fun c ->
Unix.connect c (Unix.ADDR_INET(localhost, port));
while with_mutex m (fun () -> not !finished) do
let n = Unix_cstruct.send c test_message [] in
Alcotest.(check int) "send length" (Cstruct.length test_message) n;
Thread.delay 0.1
done
);
Thread.join t
)
let test_sendto_recvfrom () =
let test_message = Cstruct.concat test_message_list in
with_sock_dgram @@ fun s ->
with_sock_dgram @@ fun c ->
let sport = bind_random_port s in
let cport = bind_random_port c in (* So we can assert the sender on receiver port *)
let server () =
let buf = Cstruct.create 1024 in
let n, (addr:Unix.sockaddr) = Unix_cstruct.recvfrom s buf [] in
let addr, port = match addr with
| ADDR_INET (a, p) -> Unix.string_of_inet_addr a, p
| _ -> Alcotest.fail "Bad AF_FAMILY"
in
Alcotest.(check string) "recvfrom inetaddr" addr "127.0.0.1";
Alcotest.(check int) "recvfrom port" port cport;
Alcotest.(check int) "recvfrom length" (Cstruct.length test_message) n;
let expected = Cstruct.to_string test_message in
let actual = Cstruct.(to_string @@ sub buf 0 n) in
Alcotest.(check string) "read contents" expected actual
in
let client () =
let addr = Unix.ADDR_INET (Unix.inet_addr_loopback, sport) in
let n = Unix_cstruct.sendto c test_message [] addr in
Alcotest.(check int) "sendto length" (Cstruct.length test_message) n;
in
client ();
server ()
let suite = [
"writev", [
"test read and writev via a file", `Quick, test_writev_file;
"test read and writev via a socket", `Quick, test_writev_socket;
];
"send recv", [
"test send and recv", `Quick, test_send_recv;
];
"sendto recvfrom", [
"test sendto and recvfrom", `Quick, test_sendto_recvfrom;
]
]
let () = Alcotest.run "cstruct.unix" suite
| null | https://raw.githubusercontent.com/avsm/eeww/651d8da20a3cc9e88354ed0c8da270632b9c0c19/lib/cstruct/unix_test/tests.ml | ocaml | non-recursive for safety
So we can assert the sender on receiver port |
let mk_temp_dir () =
let rand_num = Random.int 1000000 |> string_of_int in
let tmp_dir = Filename.get_temp_dir_name () ^ "/test-cstruct-unix-" ^ rand_num in
try
Unix.mkdir tmp_dir 0o700;
tmp_dir
with Unix.Unix_error(Unix.EEXIST, _, _) ->
re - use the old one
tmp_dir
| e -> raise (Sys_error ("Cannot create temp dir " ^ tmp_dir ^ " " ^ (Printexc.to_string e)))
let rmdir path =
match Sys.is_directory path with
| true ->
Sys.readdir path |>
Array.iter (fun name -> Sys.remove (Filename.concat path name));
Unix.rmdir path
| false -> Sys.remove path
let finally f g =
try
let r = f () in
g ();
r
with e ->
g ();
raise e
let with_tmp_dir f =
let dir = mk_temp_dir () in
finally (fun () -> f dir) (fun () -> rmdir dir)
let test_message_list =[
Cstruct.of_string "hello";
Cstruct.of_string " ";
Cstruct.of_string "cstruct";
Cstruct.create 0;
Cstruct.of_string " ";
Cstruct.of_string "world";
]
let read_and_check fd sent_message =
let expected = Cstruct.(to_string @@ concat sent_message) in
let buf = Cstruct.create 1024 in
let read = ref 0 in
while !read < (String.length expected) do
let n = Unix_cstruct.read fd (Cstruct.shift buf !read) in
if n = 0 then raise End_of_file;
read := !read + n
done;
let actual = Cstruct.(to_string @@ sub buf 0 !read) in
Alcotest.(check string) "read contents" expected actual
let test_writev_file () =
with_tmp_dir
(fun dir ->
let test = Filename.concat dir "test" in
let fd = Unix.openfile test [ Unix.O_CREAT; Unix.O_RDWR ] 0o644 in
finally (fun () ->
Unix_cstruct.writev fd test_message_list;
let ofs = Unix.lseek fd 0 Unix.SEEK_SET in
Alcotest.(check int) "file offset" 0 ofs;
read_and_check fd test_message_list
) (fun () -> Unix.close fd)
)
let with_sock_stream f =
let s = Unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
finally (fun () -> f s) (fun () -> Unix.close s)
let localhost = Unix.inet_addr_of_string "127.0.0.1"
let bind_random_port s =
Unix.bind s (Unix.ADDR_INET(localhost, 0));
match Unix.getsockname s with
| Unix.ADDR_INET(_, port) -> port
| _ -> assert false
let test_writev_socket () =
with_sock_stream (fun s ->
let port = bind_random_port s in
Unix.listen s 1;
let t = Thread.create (fun () ->
let client, _ = Unix.accept s in
finally
(fun () ->
read_and_check client test_message_list
) (fun () -> Unix.close client)
) () in
with_sock_stream (fun c ->
Unix.connect c (Unix.ADDR_INET(localhost, port));
Unix_cstruct.writev c test_message_list;
);
Thread.join t
)
let with_sock_dgram f =
let s = Unix.socket Unix.PF_INET Unix.SOCK_DGRAM 0 in
finally (fun () -> f s) (fun () -> Unix.close s)
let with_mutex m f =
Mutex.lock m;
finally f (fun () -> Mutex.unlock m)
let test_send_recv () =
let test_message = Cstruct.concat test_message_list in
with_sock_dgram (fun s ->
let port = bind_random_port s in
let m = Mutex.create () in
let finished = ref false in
let t = Thread.create (fun () ->
let buf = Cstruct.create 1024 in
let n = Unix_cstruct.recv s buf [] in
Alcotest.(check int) "recv length" (Cstruct.length test_message) n;
let expected = Cstruct.to_string test_message in
let actual = Cstruct.(to_string @@ sub buf 0 n) in
Alcotest.(check string) "read contents" expected actual;
with_mutex m (fun () -> finished := true)
) () in
with_sock_dgram (fun c ->
Unix.connect c (Unix.ADDR_INET(localhost, port));
while with_mutex m (fun () -> not !finished) do
let n = Unix_cstruct.send c test_message [] in
Alcotest.(check int) "send length" (Cstruct.length test_message) n;
Thread.delay 0.1
done
);
Thread.join t
)
let test_sendto_recvfrom () =
let test_message = Cstruct.concat test_message_list in
with_sock_dgram @@ fun s ->
with_sock_dgram @@ fun c ->
let sport = bind_random_port s in
let server () =
let buf = Cstruct.create 1024 in
let n, (addr:Unix.sockaddr) = Unix_cstruct.recvfrom s buf [] in
let addr, port = match addr with
| ADDR_INET (a, p) -> Unix.string_of_inet_addr a, p
| _ -> Alcotest.fail "Bad AF_FAMILY"
in
Alcotest.(check string) "recvfrom inetaddr" addr "127.0.0.1";
Alcotest.(check int) "recvfrom port" port cport;
Alcotest.(check int) "recvfrom length" (Cstruct.length test_message) n;
let expected = Cstruct.to_string test_message in
let actual = Cstruct.(to_string @@ sub buf 0 n) in
Alcotest.(check string) "read contents" expected actual
in
let client () =
let addr = Unix.ADDR_INET (Unix.inet_addr_loopback, sport) in
let n = Unix_cstruct.sendto c test_message [] addr in
Alcotest.(check int) "sendto length" (Cstruct.length test_message) n;
in
client ();
server ()
let suite = [
"writev", [
"test read and writev via a file", `Quick, test_writev_file;
"test read and writev via a socket", `Quick, test_writev_socket;
];
"send recv", [
"test send and recv", `Quick, test_send_recv;
];
"sendto recvfrom", [
"test sendto and recvfrom", `Quick, test_sendto_recvfrom;
]
]
let () = Alcotest.run "cstruct.unix" suite
|
34d790053a559a23d9790b95312106062c8ec24496b0c79aac135203ade76a3d | maximedenes/native-coq | proofview.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Compat
(* The proofview datastructure is a pure datastructure underlying the notion
of proof (namely, a proof is a proofview which can evolve and has safety
mechanisms attached).
The general idea of the structure is that it is composed of a chemical
solution: an unstructured bag of stuff which has some relations with
one another, which represents the various subnodes of the proof, together
with a comb: a datastructure that gives order to some of these nodes,
namely the open goals.
The natural candidate for the solution is an {!Evd.evar_map}, that is
a calculus of evars. The comb is then a list of goals (evars wrapped
with some extra information, like possible name anotations).
There is also need of a list of the evars which initialised the proofview
to be able to return information about the proofview. *)
Type of proofviews .
type proofview = {
initial : (Term.constr * Term.types) list;
solution : Evd.evar_map;
comb : Goal.goal list
}
(* Initialises a proofview, the argument is a list of environement,
conclusion types, and optional names, creating that many initial goals. *)
let init =
let rec aux = function
| [] -> { initial = [] ;
solution = Evd.empty ;
comb = []
}
| (env,typ)::l -> let { initial = ret ; solution = sol ; comb = comb } =
aux l
in
let ( new_defs , econstr ) =
Evarutil.new_evar sol env typ
in
let (e,_) = Term.destEvar econstr in
let gl = Goal.build e in
{ initial = (econstr,typ)::ret;
solution = new_defs ;
comb = gl::comb }
in
fun l -> let v = aux l in
Marks all the goal unresolvable for typeclasses .
{ v with solution = Typeclasses.mark_unresolvables v.solution }
(* Returns whether this proofview is finished or not. That is,
if it has empty subgoals in the comb. There could still be unsolved
subgoaled, but they would then be out of the view, focused out. *)
let finished = function
| {comb = []} -> true
| _ -> false
(* Returns the current value of the proofview partial proofs. *)
let return { initial=init; solution=defs } =
List.map (fun (c,t) -> (Evarutil.nf_evar defs c , t)) init
(* spiwack: this function should probably go in the Util section,
but I'd rather have Util (or a separate module for lists)
raise proper exceptions before *)
[ IndexOutOfRange ] occurs in case of malformed indices
with respect to list lengths .
with respect to list lengths. *)
exception IndexOutOfRange
(* no handler: should not be allowed to reach toplevel *)
[ list_goto i l ] returns a pair of lists [ c , t ] where
[ c ] has length [ i ] and is the reversed of the [ i ] first
elements of [ l ] , and [ t ] is the rest of the list .
The idea is to navigate through the list , [ c ] is then
seen as the context of the current position .
Raises [ IndexOutOfRange ] if [ i > length l ]
[c] has length [i] and is the reversed of the [i] first
elements of [l], and [t] is the rest of the list.
The idea is to navigate through the list, [c] is then
seen as the context of the current position.
Raises [IndexOutOfRange] if [i > length l]*)
let list_goto =
let rec aux acc index = function
| l when index = 0-> (acc,l)
| [] -> raise IndexOutOfRange
| a::q -> aux (a::acc) (index-1) q
in
fun i l ->
if i < 0 then
raise IndexOutOfRange
else
aux [] i l
Type of the object which allow to unfocus a view .
First component is a reverse list of what comes before
and second component is what goes after ( in the expected
order )
and second component is what goes after (in the expected
order) *)
type focus_context = Goal.goal list * Goal.goal list
This ( internal ) function extracts a sublist between two indices , and
returns this sublist together with its context :
if it returns [ ( a,(b , c ) ) ] then [ a ] is the sublist and ( rev b)@a@c is the
original list .
The focused list has [ j - i-1 ] and contains the goals from
number [ i ] to number [ j ] ( both included ) the first goal of the list
being numbered [ 1 ] .
[ focus_sublist i j l ] raises [ IndexOutOfRange ] if
[ i > length l ] , or [ j > length l ] or [ j < i ] .
returns this sublist together with its context:
if it returns [(a,(b,c))] then [a] is the sublist and (rev b)@a@c is the
original list.
The focused list has lenght [j-i-1] and contains the goals from
number [i] to number [j] (both included) the first goal of the list
being numbered [1].
[focus_sublist i j l] raises [IndexOutOfRange] if
[i > length l], or [j > length l] or [ j < i ]. *)
let focus_sublist i j l =
let (left,sub_right) = list_goto (i-1) l in
let (sub, right) =
try
Util.list_chop (j-i+1) sub_right
with Failure "list_chop" ->
Errors.errorlabstrm "nth_unproven" (Pp.str"No such unproven subgoal")
in
(sub, (left,right))
(* Inverse operation to the previous one. *)
let unfocus_sublist (left,right) s =
List.rev_append left (s@right)
[ focus i j ] focuses a proofview on the goals from index [ i ] to index [ j ]
( inclusive ) . ( i.e. goals number [ i ] to [ j ] become the only goals of the
returned proofview ) . The first goal has index 1 .
It returns the focus proof , and a context for the focus trace .
(inclusive). (i.e. goals number [i] to [j] become the only goals of the
returned proofview). The first goal has index 1.
It returns the focus proof, and a context for the focus trace. *)
let focus i j sp =
let (new_comb, context) = focus_sublist i j sp.comb in
( { sp with comb = new_comb } , context )
(* Unfocuses a proofview with respect to a context. *)
let undefined defs l =
Option.List.flatten (List.map (Goal.advance defs) l)
let unfocus c sp =
{ sp with comb = undefined sp.solution (unfocus_sublist c sp.comb) }
(* The tactic monad:
- Tactics are objects which apply a transformation to all
the subgoals of the current view at the same time. By opposed
to the old vision of applying it to a single goal. It mostly
allows to consider tactic like [reorder] to reorder the goals
in the current view (which might be useful for the tactic designer)
(* spiwack: the ordering of goals, though, is perhaps a bit
brittle. It would be much more interesting to find a more
robust way to adress goals, I have no idea at this time
though*)
or global automation tactic for dependent subgoals (instantiating
an evar has influences on the other goals of the proof in progress,
not being able to take that into account causes the current eauto
tactic to fail on some instances where it could succeed).
- Tactics are a monad ['a tactic], in a sense a tactic can be
seens as a function (without argument) which returns a value
of type 'a and modifies the environement (in our case: the view).
Tactics of course have arguments, but these are given at the
meta-level as OCaml functions.
Most tactics, in the sense we are used to, return [ () ], that is
no really interesting values. But some might pass information
around; the [(>>--)] and [(>>==)] bind-like construction are the
main ingredients of this information passing.
spiwack : I do n't know how much all this relates to and
. I was n't able to understand how they used the monad
structure in there developpement .
C. Muñoz. I wasn't able to understand how they used the monad
structure in there developpement.
*)
The tactics seen in Coq's Ltac are (for now at least) only
[unit tactic], the return values are kept for the OCaml toolkit.
The operation or the monad are [Proofview.tclUNIT] (which is the
"return" of the tactic monad) [Proofview.tclBIND] (which is
the "bind", also noted [(>=)]) and [Proofview.tclTHEN] (which is a
specialized bind on unit-returning tactics).
*)
(* type of tactics *)
spiwack : double - continuation backtracking monads are reasonable
folklore for " search " implementations ( including Tac interactive prover 's
tactics ) . Yet it 's quite hard to wrap your head around these .
I recommand reading a few times the " Backtracking , Interleaving , and Terminating
Monad Transformers " paper by O. Kiselyov , , .
The peculiar shape of the monadic type is reminiscent of that of the continuation
monad transformer .
A good way to get a feel of what 's happening is to look at what happens when
executing [ apply ( tclUNIT ( ) ) ] .
The disjunction function is unlike that of the LogicT paper , because we want and
need to backtrack over state as well as values . Therefore we can not be
polymorphic over the inner monad .
folklore for "search" implementations (including Tac interactive prover's
tactics). Yet it's quite hard to wrap your head around these.
I recommand reading a few times the "Backtracking, Interleaving, and Terminating
Monad Transformers" paper by O. Kiselyov, C. Chen, D. Fridman.
The peculiar shape of the monadic type is reminiscent of that of the continuation
monad transformer.
A good way to get a feel of what's happening is to look at what happens when
executing [apply (tclUNIT ())].
The disjunction function is unlike that of the LogicT paper, because we want and
need to backtrack over state as well as values. Therefore we cannot be
polymorphic over the inner monad. *)
type proof_step = { goals : Goal.goal list ; defs : Evd.evar_map }
type +'a result = { proof_step : proof_step ;
content : 'a }
(* nb=non-backtracking *)
type +'a nb_tactic = proof_step -> 'a result
(* double-continutation backtracking *)
(* "sk" stands for "success continuation", "fk" for "failure continuation" *)
type 'r fk = exn -> 'r
type (-'a,'r) sk = 'a -> 'r fk -> 'r
type +'a tactic0 = { go : 'r. ('a, 'r nb_tactic) sk -> 'r nb_tactic fk -> 'r nb_tactic }
(* We obtain a tactic by parametrizing with an environment *)
(* spiwack: alternatively the environment could be part of the "nb_tactic" state
monad. As long as we do not intend to change the environment during a tactic,
it's probably better here. *)
type +'a tactic = Environ.env -> 'a tactic0
(* unit of [nb_tactic] *)
let nb_tac_unit a step = { proof_step = step ; content = a }
(* Applies a tactic to the current proofview. *)
let apply env t sp =
let start = { goals = sp.comb ; defs = sp.solution } in
let res = (t env).go (fun a _ step -> nb_tac_unit a step) (fun e _ -> raise e) start in
let next = res.proof_step in
{sp with
solution = next.defs ;
comb = next.goals
}
(*** tacticals ***)
(* Unit of the tactic monad *)
let tclUNIT a _ = { go = fun sk fk step -> sk a fk step }
Bind operation of the tactic monad
let tclBIND t k env = { go = fun sk fk step ->
(t env).go (fun a fk -> (k a env).go sk fk) fk step
}
Interpretes the " ; " ( semicolon ) of .
As a monadic operation , it 's a specialized " bind "
on unit - returning tactic ( meaning " there is no value to bind " )
As a monadic operation, it's a specialized "bind"
on unit-returning tactic (meaning "there is no value to bind") *)
let tclTHEN t1 t2 env = { go = fun sk fk step ->
(t1 env).go (fun () fk -> (t2 env).go sk fk) fk step
}
(* [tclIGNORE t] has the same operational content as [t],
but drops the value at the end. *)
let tclIGNORE tac env = { go = fun sk fk step ->
(tac env).go (fun _ fk -> sk () fk) fk step
}
(* [tclOR t1 t2 = t1] if t1 succeeds and [tclOR t1 t2 = t2] if t1 fails.
No interleaving for the moment. *)
(* spiwack: compared to the LogicT paper, we backtrack at the same state
where [t1] has been called, not the state where [t1] failed. *)
let tclOR t1 t2 env = { go = fun sk fk step ->
(t1 env).go sk (fun _ _ -> (t2 env).go sk fk step) step
}
(* [tclZERO e] always fails with error message [e]*)
let tclZERO e env = { go = fun _ fk step -> fk e step }
(* Focusing operation on proof_steps. *)
let focus_proof_step i j ps =
let (new_subgoals, context) = focus_sublist i j ps.goals in
( { ps with goals = new_subgoals } , context )
(* Unfocusing operation of proof_steps. *)
let unfocus_proof_step c ps =
{ ps with
goals = undefined ps.defs (unfocus_sublist c ps.goals)
}
(* Focuses a tactic at a range of subgoals, found by their indices. *)
(* arnaud: bug if 0 goals ! *)
let tclFOCUS i j t env = { go = fun sk fk step ->
let (focused,context) = focus_proof_step i j step in
(t env).go (fun a fk step -> sk a fk (unfocus_proof_step context step)) fk focused
}
Dispatch tacticals are used to apply a different tactic to each goal under
consideration . They come in two flavours :
[ tclDISPATCH ] takes a list of [ unit tactic]-s and build a [ unit tactic ] .
[ tclDISPATCHS ] takes a list of [ ' a sensitive tactic ] and returns and returns
and [ ' a sensitive tactic ] where the [ ' a sensitive ] interpreted in a goal [ g ]
corresponds to that of the tactic which created [ g ] .
It is to be noted that the return value of [ tclDISPATCHS ts ] makes only
sense in the goals immediatly built by it , and would cause an anomaly
is used otherwise .
consideration. They come in two flavours:
[tclDISPATCH] takes a list of [unit tactic]-s and build a [unit tactic].
[tclDISPATCHS] takes a list of ['a sensitive tactic] and returns and returns
and ['a sensitive tactic] where the ['a sensitive] interpreted in a goal [g]
corresponds to that of the tactic which created [g].
It is to be noted that the return value of [tclDISPATCHS ts] makes only
sense in the goals immediatly built by it, and would cause an anomaly
is used otherwise. *)
exception SizeMismatch
let _ = Errors.register_handler begin function
| SizeMismatch -> Errors.error "Incorrect number of goals."
| _ -> raise Errors.Unhandled
end
spiwack : we use an parametrised function to generate the dispatch tacticals .
[ tclDISPATCHGEN ] takes a [ null ] argument to generate the return value
if there are no goal under focus , and a [ join ] argument to explain how
the return value at two given lists of subgoals are combined when
both lists are being concatenated .
[ join ] and [ null ] need be some sort of comutative monoid .
[tclDISPATCHGEN] takes a [null] argument to generate the return value
if there are no goal under focus, and a [join] argument to explain how
the return value at two given lists of subgoals are combined when
both lists are being concatenated.
[join] and [null] need be some sort of comutative monoid. *)
let rec tclDISPATCHGEN null join tacs env = { go = fun sk fk step ->
match tacs,step.goals with
| [] , [] -> (tclUNIT null env).go sk fk step
| t::tacs , first::goals ->
(tclDISPATCHGEN null join tacs env).go
begin fun x fk step ->
match Goal.advance step.defs first with
| None -> sk x fk step
| Some first ->
(t env).go
begin fun y fk step' ->
sk (join x y) fk { step' with
goals = step'
}
end
fk
{ step with goals = [first] }
end
fk
{ step with goals = goals }
| _ -> raise SizeMismatch
}
(* takes a tactic which can raise exception and makes it pure by *failing*
on with these exceptions. Does not catch anomalies. *)
let purify t =
let t' env = { go = fun sk fk step -> try (t env).go (fun x -> sk (Util.Inl x)) fk step
with Errors.Anomaly _ as e -> raise e
| e -> sk (Util.Inr e) fk step
}
in
tclBIND t' begin function
| Util.Inl x -> tclUNIT x
| Util.Inr e -> tclZERO e
end
let tclDISPATCHGEN null join tacs = purify (tclDISPATCHGEN null join tacs)
let unitK () () = ()
let tclDISPATCH = tclDISPATCHGEN () unitK
let extend_to_list =
let rec copy n x l =
if n < 0 then raise SizeMismatch
else if n = 0 then l
else copy (n-1) x (x::l)
in
fun startxs rx endxs l ->
let ns = List.length startxs in
let ne = List.length endxs in
let n = List.length l in
startxs@(copy (n-ne-ns) rx endxs)
let tclEXTEND tacs1 rtac tacs2 env = { go = fun sk fk step ->
let tacs = extend_to_list tacs1 rtac tacs2 step.goals in
(tclDISPATCH tacs env).go sk fk step
}
[ tclGOALBIND ] and [ tclGOALBINDU ] are sorts of bind which take a
[ Goal.sensitive ] as a first argument , the tactic then acts on each goal separately .
Allows backtracking between goals .
[Goal.sensitive] as a first argument, the tactic then acts on each goal separately.
Allows backtracking between goals. *)
let list_of_sensitive s k env step =
Goal.list_map begin fun defs g ->
let (a,defs) = Goal.eval s env defs g in
(k a) , defs
end step.goals step.defs
(* In form of a tactic *)
let list_of_sensitive s k env = { go = fun sk fk step ->
let (tacs,defs) = list_of_sensitive s k env step in
sk tacs fk { step with defs = defs }
}
(* This is a helper function for the dispatching tactics (like [tclGOALBIND] and
[tclDISPATCHS]). It takes an ['a sensitive] value, and returns a tactic
whose return value is, again, ['a sensitive] but only has value in the
(unmodified) goals under focus. *)
let here_s b env = { go = fun sk fk step ->
sk (Goal.bind (Goal.here_list step.goals b) (fun b -> b)) fk step
}
let rec tclGOALBIND s k =
spiwack : the first line ensures that the value returned by the tactic [ k ] will
not " escape its scope " .
not "escape its scope". *)
let k a = tclBIND (k a) here_s in
purify begin
tclBIND (list_of_sensitive s k) begin fun tacs ->
tclDISPATCHGEN Goal.null Goal.plus tacs
end
end
(* spiwack: this should probably be moved closer to the [tclDISPATCH] tactical. *)
let tclDISPATCHS tacs =
let tacs =
List.map begin fun tac ->
tclBIND tac here_s
end tacs
in
purify begin
tclDISPATCHGEN Goal.null Goal.plus tacs
end
let rec tclGOALBINDU s k =
purify begin
tclBIND (list_of_sensitive s k) begin fun tacs ->
tclDISPATCHGEN () unitK tacs
end
end
spiwack : up to a few details , same errors are in the Logic module .
this should be maintained synchronized , probably .
this should be maintained synchronized, probably. *)
open Pretype_errors
let rec catchable_exception = function
| Loc.Exc_located(_,e) -> catchable_exception e
| Errors.UserError _
| Type_errors.TypeError _ | PretypeError (_,_,TypingError _)
| Indrec.RecursionSchemeError _
| Nametab.GlobalizationError _ | PretypeError (_,_,VarNotFound _)
(* unification errors *)
| PretypeError(_,_,(CannotUnify _|CannotUnifyLocal _|CannotGeneralize _
|NoOccurrenceFound _|CannotUnifyBindingType _|NotClean _
|CannotFindWellTypedAbstraction _
|UnsolvableImplicit _)) -> true
| Typeclasses_errors.TypeClassError
(_, Typeclasses_errors.UnsatisfiableConstraints _) -> true
| _ -> false
No backtracking can happen here , hence , as opposed to the dispatch tacticals ,
everything is done in one step .
everything is done in one step. *)
let sensitive_on_step s env step =
let wrap g ((defs, partial_list) as partial_res) =
match Goal.advance defs g with
| None ->partial_res
| Some g ->
let {Goal.subgoals = sg } , d' = Goal.eval s env defs g in
(d',sg::partial_list)
in
let ( new_defs , combed_subgoals ) =
List.fold_right wrap step.goals (step.defs,[])
in
{ defs = new_defs;
goals = List.flatten combed_subgoals }
let tclSENSITIVE s =
purify begin
fun env -> { go = fun sk fk step -> sk () fk (sensitive_on_step s env step) }
end
(*** Commands ***)
let in_proofview p k =
k p.solution
module Notations = struct
let (>-) = Goal.bind
let (>>-) = tclGOALBINDU
let (>>--) = tclGOALBIND
let (>=) = tclBIND
let (>>=) t k = t >= fun s -> s >>- k
let (>>==) t k = t >= fun s -> s >>-- k
let (<*>) = tclTHEN
let (<+>) = tclOR
end
* * Compatibility layer with < = 8.2 tactics * *
module V82 = struct
type tac = Goal.goal Evd.sigma -> Goal.goal list Evd.sigma
let tactic tac _ = { go = fun sk fk ps ->
spiwack : we ignore the dependencies between goals here , expectingly
preserving the semantics of < = 8.2 tactics
preserving the semantics of <= 8.2 tactics *)
let tac evd gl =
let glsigma = tac { Evd.it = gl ; Evd.sigma = evd } in
let sigma = glsigma.Evd.sigma in
let g = glsigma.Evd.it in
( g , sigma )
in
(* Old style tactics expect the goals normalized with respect to evars. *)
let (initgoals,initevd) =
Goal.list_map Goal.V82.nf_evar ps.goals ps.defs
in
let (goalss,evd) = Goal.list_map tac initgoals initevd in
let sgs = List.flatten goalss in
sk () fk { defs = evd ; goals = sgs }
}
let has_unresolved_evar pv =
Evd.has_undefined pv.solution
Main function in the implementation of Grab Existential Variables .
let grab pv =
let goals =
List.map begin fun (e,_) ->
Goal.build e
end (Evd.undefined_list pv.solution)
in
{ pv with comb = goals }
(* Returns the open goals of the proofview together with the evar_map to
interprete them. *)
let goals { comb = comb ; solution = solution } =
{ Evd.it = comb ; sigma = solution}
let top_goals { initial=initial ; solution=solution } =
let goals = List.map (fun (t,_) -> Goal.V82.build (fst (Term.destEvar t))) initial in
{ Evd.it = goals ; sigma=solution }
let top_evars { initial=initial } =
let evars_of_initial (c,_) =
Util.Intset.elements (Evarutil.evars_of_term c)
in
List.flatten (List.map evars_of_initial initial)
let instantiate_evar n com pv =
let (evk,_) =
let evl = Evarutil.non_instantiated pv.solution in
if (n <= 0) then
Errors.error "incorrect existential variable index"
else if List.length evl < n then
Errors.error "not so many uninstantiated existential variables"
else
List.nth evl (n-1)
in
{ pv with
solution = Evar_refiner.instantiate_pf_com evk com pv.solution }
let purify = purify
end
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/proofs/proofview.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
The proofview datastructure is a pure datastructure underlying the notion
of proof (namely, a proof is a proofview which can evolve and has safety
mechanisms attached).
The general idea of the structure is that it is composed of a chemical
solution: an unstructured bag of stuff which has some relations with
one another, which represents the various subnodes of the proof, together
with a comb: a datastructure that gives order to some of these nodes,
namely the open goals.
The natural candidate for the solution is an {!Evd.evar_map}, that is
a calculus of evars. The comb is then a list of goals (evars wrapped
with some extra information, like possible name anotations).
There is also need of a list of the evars which initialised the proofview
to be able to return information about the proofview.
Initialises a proofview, the argument is a list of environement,
conclusion types, and optional names, creating that many initial goals.
Returns whether this proofview is finished or not. That is,
if it has empty subgoals in the comb. There could still be unsolved
subgoaled, but they would then be out of the view, focused out.
Returns the current value of the proofview partial proofs.
spiwack: this function should probably go in the Util section,
but I'd rather have Util (or a separate module for lists)
raise proper exceptions before
no handler: should not be allowed to reach toplevel
Inverse operation to the previous one.
Unfocuses a proofview with respect to a context.
The tactic monad:
- Tactics are objects which apply a transformation to all
the subgoals of the current view at the same time. By opposed
to the old vision of applying it to a single goal. It mostly
allows to consider tactic like [reorder] to reorder the goals
in the current view (which might be useful for the tactic designer)
(* spiwack: the ordering of goals, though, is perhaps a bit
brittle. It would be much more interesting to find a more
robust way to adress goals, I have no idea at this time
though
type of tactics
nb=non-backtracking
double-continutation backtracking
"sk" stands for "success continuation", "fk" for "failure continuation"
We obtain a tactic by parametrizing with an environment
spiwack: alternatively the environment could be part of the "nb_tactic" state
monad. As long as we do not intend to change the environment during a tactic,
it's probably better here.
unit of [nb_tactic]
Applies a tactic to the current proofview.
** tacticals **
Unit of the tactic monad
[tclIGNORE t] has the same operational content as [t],
but drops the value at the end.
[tclOR t1 t2 = t1] if t1 succeeds and [tclOR t1 t2 = t2] if t1 fails.
No interleaving for the moment.
spiwack: compared to the LogicT paper, we backtrack at the same state
where [t1] has been called, not the state where [t1] failed.
[tclZERO e] always fails with error message [e]
Focusing operation on proof_steps.
Unfocusing operation of proof_steps.
Focuses a tactic at a range of subgoals, found by their indices.
arnaud: bug if 0 goals !
takes a tactic which can raise exception and makes it pure by *failing*
on with these exceptions. Does not catch anomalies.
In form of a tactic
This is a helper function for the dispatching tactics (like [tclGOALBIND] and
[tclDISPATCHS]). It takes an ['a sensitive] value, and returns a tactic
whose return value is, again, ['a sensitive] but only has value in the
(unmodified) goals under focus.
spiwack: this should probably be moved closer to the [tclDISPATCH] tactical.
unification errors
** Commands **
Old style tactics expect the goals normalized with respect to evars.
Returns the open goals of the proofview together with the evar_map to
interprete them. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Compat
Type of proofviews .
type proofview = {
initial : (Term.constr * Term.types) list;
solution : Evd.evar_map;
comb : Goal.goal list
}
let init =
let rec aux = function
| [] -> { initial = [] ;
solution = Evd.empty ;
comb = []
}
| (env,typ)::l -> let { initial = ret ; solution = sol ; comb = comb } =
aux l
in
let ( new_defs , econstr ) =
Evarutil.new_evar sol env typ
in
let (e,_) = Term.destEvar econstr in
let gl = Goal.build e in
{ initial = (econstr,typ)::ret;
solution = new_defs ;
comb = gl::comb }
in
fun l -> let v = aux l in
Marks all the goal unresolvable for typeclasses .
{ v with solution = Typeclasses.mark_unresolvables v.solution }
let finished = function
| {comb = []} -> true
| _ -> false
let return { initial=init; solution=defs } =
List.map (fun (c,t) -> (Evarutil.nf_evar defs c , t)) init
[ IndexOutOfRange ] occurs in case of malformed indices
with respect to list lengths .
with respect to list lengths. *)
exception IndexOutOfRange
[ list_goto i l ] returns a pair of lists [ c , t ] where
[ c ] has length [ i ] and is the reversed of the [ i ] first
elements of [ l ] , and [ t ] is the rest of the list .
The idea is to navigate through the list , [ c ] is then
seen as the context of the current position .
Raises [ IndexOutOfRange ] if [ i > length l ]
[c] has length [i] and is the reversed of the [i] first
elements of [l], and [t] is the rest of the list.
The idea is to navigate through the list, [c] is then
seen as the context of the current position.
Raises [IndexOutOfRange] if [i > length l]*)
let list_goto =
let rec aux acc index = function
| l when index = 0-> (acc,l)
| [] -> raise IndexOutOfRange
| a::q -> aux (a::acc) (index-1) q
in
fun i l ->
if i < 0 then
raise IndexOutOfRange
else
aux [] i l
Type of the object which allow to unfocus a view .
First component is a reverse list of what comes before
and second component is what goes after ( in the expected
order )
and second component is what goes after (in the expected
order) *)
type focus_context = Goal.goal list * Goal.goal list
This ( internal ) function extracts a sublist between two indices , and
returns this sublist together with its context :
if it returns [ ( a,(b , c ) ) ] then [ a ] is the sublist and ( rev b)@a@c is the
original list .
The focused list has [ j - i-1 ] and contains the goals from
number [ i ] to number [ j ] ( both included ) the first goal of the list
being numbered [ 1 ] .
[ focus_sublist i j l ] raises [ IndexOutOfRange ] if
[ i > length l ] , or [ j > length l ] or [ j < i ] .
returns this sublist together with its context:
if it returns [(a,(b,c))] then [a] is the sublist and (rev b)@a@c is the
original list.
The focused list has lenght [j-i-1] and contains the goals from
number [i] to number [j] (both included) the first goal of the list
being numbered [1].
[focus_sublist i j l] raises [IndexOutOfRange] if
[i > length l], or [j > length l] or [ j < i ]. *)
let focus_sublist i j l =
let (left,sub_right) = list_goto (i-1) l in
let (sub, right) =
try
Util.list_chop (j-i+1) sub_right
with Failure "list_chop" ->
Errors.errorlabstrm "nth_unproven" (Pp.str"No such unproven subgoal")
in
(sub, (left,right))
let unfocus_sublist (left,right) s =
List.rev_append left (s@right)
[ focus i j ] focuses a proofview on the goals from index [ i ] to index [ j ]
( inclusive ) . ( i.e. goals number [ i ] to [ j ] become the only goals of the
returned proofview ) . The first goal has index 1 .
It returns the focus proof , and a context for the focus trace .
(inclusive). (i.e. goals number [i] to [j] become the only goals of the
returned proofview). The first goal has index 1.
It returns the focus proof, and a context for the focus trace. *)
let focus i j sp =
let (new_comb, context) = focus_sublist i j sp.comb in
( { sp with comb = new_comb } , context )
let undefined defs l =
Option.List.flatten (List.map (Goal.advance defs) l)
let unfocus c sp =
{ sp with comb = undefined sp.solution (unfocus_sublist c sp.comb) }
or global automation tactic for dependent subgoals (instantiating
an evar has influences on the other goals of the proof in progress,
not being able to take that into account causes the current eauto
tactic to fail on some instances where it could succeed).
- Tactics are a monad ['a tactic], in a sense a tactic can be
seens as a function (without argument) which returns a value
of type 'a and modifies the environement (in our case: the view).
Tactics of course have arguments, but these are given at the
meta-level as OCaml functions.
Most tactics, in the sense we are used to, return [ () ], that is
no really interesting values. But some might pass information
around; the [(>>--)] and [(>>==)] bind-like construction are the
main ingredients of this information passing.
spiwack : I do n't know how much all this relates to and
. I was n't able to understand how they used the monad
structure in there developpement .
C. Muñoz. I wasn't able to understand how they used the monad
structure in there developpement.
*)
The tactics seen in Coq's Ltac are (for now at least) only
[unit tactic], the return values are kept for the OCaml toolkit.
The operation or the monad are [Proofview.tclUNIT] (which is the
"return" of the tactic monad) [Proofview.tclBIND] (which is
the "bind", also noted [(>=)]) and [Proofview.tclTHEN] (which is a
specialized bind on unit-returning tactics).
*)
spiwack : double - continuation backtracking monads are reasonable
folklore for " search " implementations ( including Tac interactive prover 's
tactics ) . Yet it 's quite hard to wrap your head around these .
I recommand reading a few times the " Backtracking , Interleaving , and Terminating
Monad Transformers " paper by O. Kiselyov , , .
The peculiar shape of the monadic type is reminiscent of that of the continuation
monad transformer .
A good way to get a feel of what 's happening is to look at what happens when
executing [ apply ( tclUNIT ( ) ) ] .
The disjunction function is unlike that of the LogicT paper , because we want and
need to backtrack over state as well as values . Therefore we can not be
polymorphic over the inner monad .
folklore for "search" implementations (including Tac interactive prover's
tactics). Yet it's quite hard to wrap your head around these.
I recommand reading a few times the "Backtracking, Interleaving, and Terminating
Monad Transformers" paper by O. Kiselyov, C. Chen, D. Fridman.
The peculiar shape of the monadic type is reminiscent of that of the continuation
monad transformer.
A good way to get a feel of what's happening is to look at what happens when
executing [apply (tclUNIT ())].
The disjunction function is unlike that of the LogicT paper, because we want and
need to backtrack over state as well as values. Therefore we cannot be
polymorphic over the inner monad. *)
type proof_step = { goals : Goal.goal list ; defs : Evd.evar_map }
type +'a result = { proof_step : proof_step ;
content : 'a }
type +'a nb_tactic = proof_step -> 'a result
type 'r fk = exn -> 'r
type (-'a,'r) sk = 'a -> 'r fk -> 'r
type +'a tactic0 = { go : 'r. ('a, 'r nb_tactic) sk -> 'r nb_tactic fk -> 'r nb_tactic }
type +'a tactic = Environ.env -> 'a tactic0
let nb_tac_unit a step = { proof_step = step ; content = a }
let apply env t sp =
let start = { goals = sp.comb ; defs = sp.solution } in
let res = (t env).go (fun a _ step -> nb_tac_unit a step) (fun e _ -> raise e) start in
let next = res.proof_step in
{sp with
solution = next.defs ;
comb = next.goals
}
let tclUNIT a _ = { go = fun sk fk step -> sk a fk step }
Bind operation of the tactic monad
let tclBIND t k env = { go = fun sk fk step ->
(t env).go (fun a fk -> (k a env).go sk fk) fk step
}
Interpretes the " ; " ( semicolon ) of .
As a monadic operation , it 's a specialized " bind "
on unit - returning tactic ( meaning " there is no value to bind " )
As a monadic operation, it's a specialized "bind"
on unit-returning tactic (meaning "there is no value to bind") *)
let tclTHEN t1 t2 env = { go = fun sk fk step ->
(t1 env).go (fun () fk -> (t2 env).go sk fk) fk step
}
let tclIGNORE tac env = { go = fun sk fk step ->
(tac env).go (fun _ fk -> sk () fk) fk step
}
let tclOR t1 t2 env = { go = fun sk fk step ->
(t1 env).go sk (fun _ _ -> (t2 env).go sk fk step) step
}
let tclZERO e env = { go = fun _ fk step -> fk e step }
let focus_proof_step i j ps =
let (new_subgoals, context) = focus_sublist i j ps.goals in
( { ps with goals = new_subgoals } , context )
let unfocus_proof_step c ps =
{ ps with
goals = undefined ps.defs (unfocus_sublist c ps.goals)
}
let tclFOCUS i j t env = { go = fun sk fk step ->
let (focused,context) = focus_proof_step i j step in
(t env).go (fun a fk step -> sk a fk (unfocus_proof_step context step)) fk focused
}
Dispatch tacticals are used to apply a different tactic to each goal under
consideration . They come in two flavours :
[ tclDISPATCH ] takes a list of [ unit tactic]-s and build a [ unit tactic ] .
[ tclDISPATCHS ] takes a list of [ ' a sensitive tactic ] and returns and returns
and [ ' a sensitive tactic ] where the [ ' a sensitive ] interpreted in a goal [ g ]
corresponds to that of the tactic which created [ g ] .
It is to be noted that the return value of [ tclDISPATCHS ts ] makes only
sense in the goals immediatly built by it , and would cause an anomaly
is used otherwise .
consideration. They come in two flavours:
[tclDISPATCH] takes a list of [unit tactic]-s and build a [unit tactic].
[tclDISPATCHS] takes a list of ['a sensitive tactic] and returns and returns
and ['a sensitive tactic] where the ['a sensitive] interpreted in a goal [g]
corresponds to that of the tactic which created [g].
It is to be noted that the return value of [tclDISPATCHS ts] makes only
sense in the goals immediatly built by it, and would cause an anomaly
is used otherwise. *)
exception SizeMismatch
let _ = Errors.register_handler begin function
| SizeMismatch -> Errors.error "Incorrect number of goals."
| _ -> raise Errors.Unhandled
end
spiwack : we use an parametrised function to generate the dispatch tacticals .
[ tclDISPATCHGEN ] takes a [ null ] argument to generate the return value
if there are no goal under focus , and a [ join ] argument to explain how
the return value at two given lists of subgoals are combined when
both lists are being concatenated .
[ join ] and [ null ] need be some sort of comutative monoid .
[tclDISPATCHGEN] takes a [null] argument to generate the return value
if there are no goal under focus, and a [join] argument to explain how
the return value at two given lists of subgoals are combined when
both lists are being concatenated.
[join] and [null] need be some sort of comutative monoid. *)
let rec tclDISPATCHGEN null join tacs env = { go = fun sk fk step ->
match tacs,step.goals with
| [] , [] -> (tclUNIT null env).go sk fk step
| t::tacs , first::goals ->
(tclDISPATCHGEN null join tacs env).go
begin fun x fk step ->
match Goal.advance step.defs first with
| None -> sk x fk step
| Some first ->
(t env).go
begin fun y fk step' ->
sk (join x y) fk { step' with
goals = step'
}
end
fk
{ step with goals = [first] }
end
fk
{ step with goals = goals }
| _ -> raise SizeMismatch
}
let purify t =
let t' env = { go = fun sk fk step -> try (t env).go (fun x -> sk (Util.Inl x)) fk step
with Errors.Anomaly _ as e -> raise e
| e -> sk (Util.Inr e) fk step
}
in
tclBIND t' begin function
| Util.Inl x -> tclUNIT x
| Util.Inr e -> tclZERO e
end
let tclDISPATCHGEN null join tacs = purify (tclDISPATCHGEN null join tacs)
let unitK () () = ()
let tclDISPATCH = tclDISPATCHGEN () unitK
let extend_to_list =
let rec copy n x l =
if n < 0 then raise SizeMismatch
else if n = 0 then l
else copy (n-1) x (x::l)
in
fun startxs rx endxs l ->
let ns = List.length startxs in
let ne = List.length endxs in
let n = List.length l in
startxs@(copy (n-ne-ns) rx endxs)
let tclEXTEND tacs1 rtac tacs2 env = { go = fun sk fk step ->
let tacs = extend_to_list tacs1 rtac tacs2 step.goals in
(tclDISPATCH tacs env).go sk fk step
}
[ tclGOALBIND ] and [ tclGOALBINDU ] are sorts of bind which take a
[ Goal.sensitive ] as a first argument , the tactic then acts on each goal separately .
Allows backtracking between goals .
[Goal.sensitive] as a first argument, the tactic then acts on each goal separately.
Allows backtracking between goals. *)
let list_of_sensitive s k env step =
Goal.list_map begin fun defs g ->
let (a,defs) = Goal.eval s env defs g in
(k a) , defs
end step.goals step.defs
let list_of_sensitive s k env = { go = fun sk fk step ->
let (tacs,defs) = list_of_sensitive s k env step in
sk tacs fk { step with defs = defs }
}
let here_s b env = { go = fun sk fk step ->
sk (Goal.bind (Goal.here_list step.goals b) (fun b -> b)) fk step
}
let rec tclGOALBIND s k =
spiwack : the first line ensures that the value returned by the tactic [ k ] will
not " escape its scope " .
not "escape its scope". *)
let k a = tclBIND (k a) here_s in
purify begin
tclBIND (list_of_sensitive s k) begin fun tacs ->
tclDISPATCHGEN Goal.null Goal.plus tacs
end
end
let tclDISPATCHS tacs =
let tacs =
List.map begin fun tac ->
tclBIND tac here_s
end tacs
in
purify begin
tclDISPATCHGEN Goal.null Goal.plus tacs
end
let rec tclGOALBINDU s k =
purify begin
tclBIND (list_of_sensitive s k) begin fun tacs ->
tclDISPATCHGEN () unitK tacs
end
end
spiwack : up to a few details , same errors are in the Logic module .
this should be maintained synchronized , probably .
this should be maintained synchronized, probably. *)
open Pretype_errors
let rec catchable_exception = function
| Loc.Exc_located(_,e) -> catchable_exception e
| Errors.UserError _
| Type_errors.TypeError _ | PretypeError (_,_,TypingError _)
| Indrec.RecursionSchemeError _
| Nametab.GlobalizationError _ | PretypeError (_,_,VarNotFound _)
| PretypeError(_,_,(CannotUnify _|CannotUnifyLocal _|CannotGeneralize _
|NoOccurrenceFound _|CannotUnifyBindingType _|NotClean _
|CannotFindWellTypedAbstraction _
|UnsolvableImplicit _)) -> true
| Typeclasses_errors.TypeClassError
(_, Typeclasses_errors.UnsatisfiableConstraints _) -> true
| _ -> false
No backtracking can happen here , hence , as opposed to the dispatch tacticals ,
everything is done in one step .
everything is done in one step. *)
let sensitive_on_step s env step =
let wrap g ((defs, partial_list) as partial_res) =
match Goal.advance defs g with
| None ->partial_res
| Some g ->
let {Goal.subgoals = sg } , d' = Goal.eval s env defs g in
(d',sg::partial_list)
in
let ( new_defs , combed_subgoals ) =
List.fold_right wrap step.goals (step.defs,[])
in
{ defs = new_defs;
goals = List.flatten combed_subgoals }
let tclSENSITIVE s =
purify begin
fun env -> { go = fun sk fk step -> sk () fk (sensitive_on_step s env step) }
end
let in_proofview p k =
k p.solution
module Notations = struct
let (>-) = Goal.bind
let (>>-) = tclGOALBINDU
let (>>--) = tclGOALBIND
let (>=) = tclBIND
let (>>=) t k = t >= fun s -> s >>- k
let (>>==) t k = t >= fun s -> s >>-- k
let (<*>) = tclTHEN
let (<+>) = tclOR
end
* * Compatibility layer with < = 8.2 tactics * *
module V82 = struct
type tac = Goal.goal Evd.sigma -> Goal.goal list Evd.sigma
let tactic tac _ = { go = fun sk fk ps ->
spiwack : we ignore the dependencies between goals here , expectingly
preserving the semantics of < = 8.2 tactics
preserving the semantics of <= 8.2 tactics *)
let tac evd gl =
let glsigma = tac { Evd.it = gl ; Evd.sigma = evd } in
let sigma = glsigma.Evd.sigma in
let g = glsigma.Evd.it in
( g , sigma )
in
let (initgoals,initevd) =
Goal.list_map Goal.V82.nf_evar ps.goals ps.defs
in
let (goalss,evd) = Goal.list_map tac initgoals initevd in
let sgs = List.flatten goalss in
sk () fk { defs = evd ; goals = sgs }
}
let has_unresolved_evar pv =
Evd.has_undefined pv.solution
Main function in the implementation of Grab Existential Variables .
let grab pv =
let goals =
List.map begin fun (e,_) ->
Goal.build e
end (Evd.undefined_list pv.solution)
in
{ pv with comb = goals }
let goals { comb = comb ; solution = solution } =
{ Evd.it = comb ; sigma = solution}
let top_goals { initial=initial ; solution=solution } =
let goals = List.map (fun (t,_) -> Goal.V82.build (fst (Term.destEvar t))) initial in
{ Evd.it = goals ; sigma=solution }
let top_evars { initial=initial } =
let evars_of_initial (c,_) =
Util.Intset.elements (Evarutil.evars_of_term c)
in
List.flatten (List.map evars_of_initial initial)
let instantiate_evar n com pv =
let (evk,_) =
let evl = Evarutil.non_instantiated pv.solution in
if (n <= 0) then
Errors.error "incorrect existential variable index"
else if List.length evl < n then
Errors.error "not so many uninstantiated existential variables"
else
List.nth evl (n-1)
in
{ pv with
solution = Evar_refiner.instantiate_pf_com evk com pv.solution }
let purify = purify
end
|
d66fdcd7eebbce321f444f2464e3ef23fc7af3896605a9aa1ed7da78509803f7 | alanzplus/EOPL | 6.21.rkt | #lang eopl
(define list-last-index
(lambda (predicate lst)
(let helper ([lst lst] [idx 0])
(if (null? lst)
#f
(let ((res (helper (cdr lst) (+ 1 idx))))
(if res
res
(if (predicate (car lst)) idx #f)))))))
(define cps-of-exps
(lambda (exps builder)
(let cps-of-rest ([exps exps])
(let ((pos (list-last-index
(lambda (exp)
(not (expression-simple? exp)))
exps)))
(if (not pos)
(builder (map cps-of-simple-exp exps))
(let ((var (fresh-identifier 'var)))
(cps-of-exp
(list-ref exps pos)
(cps-proc-exp (list var)
(cps-of-rest
(list-set exps pos (var-exp var)))))))))))
| null | https://raw.githubusercontent.com/alanzplus/EOPL/d7b06392d26d93df851d0ca66d9edc681a06693c/EOPL/ch6/6.21.rkt | racket | #lang eopl
(define list-last-index
(lambda (predicate lst)
(let helper ([lst lst] [idx 0])
(if (null? lst)
#f
(let ((res (helper (cdr lst) (+ 1 idx))))
(if res
res
(if (predicate (car lst)) idx #f)))))))
(define cps-of-exps
(lambda (exps builder)
(let cps-of-rest ([exps exps])
(let ((pos (list-last-index
(lambda (exp)
(not (expression-simple? exp)))
exps)))
(if (not pos)
(builder (map cps-of-simple-exp exps))
(let ((var (fresh-identifier 'var)))
(cps-of-exp
(list-ref exps pos)
(cps-proc-exp (list var)
(cps-of-rest
(list-set exps pos (var-exp var)))))))))))
| |
dc7579a797ab9244a9070ccddb2cc45b62a4e6aac53c7cb6482fa65820922594 | ilyasergey/monadic-cfa | MonadCFA.hs | module Main where
-- Imports.
import CPS
import Data.Map as Map
import Data.Set as Set
-- Abbreviations.
type k :-> v = Map.Map k v
type ℙ a = Set.Set a
(==>) :: a -> b -> (a,b)
(==>) x y = (x,y)
(//) :: Ord k => (k :-> v) -> [(k,v)] -> (k :-> v)
(//) f [] = f
(//) f ((x,y):tl) = Map.insert x y (f // tl)
-- Partial order theory.
class Lattice a where
bot :: a
top :: a
(⊑) :: a -> a -> Bool
(⊔) :: a -> a -> a
(⊓) :: a -> a -> a
instance (Ord s, Eq s) => Lattice (ℙ s) where
bot = Set.empty
top = error "no representation of universal set"
x ⊔ y = x `Set.union` y
x ⊓ y = x `Set.intersection` y
x ⊑ y = x `Set.isSubsetOf` y
instance (Ord k, Lattice v) => Lattice (k :-> v) where
bot = Map.empty
top = error "no representation of top map"
f ⊑ g = Map.isSubmapOfBy (⊑) f g
f ⊔ g = Map.unionWith (⊔) f g
f ⊓ g = Map.intersectionWith (⊓) f g
(⨆) :: (Ord k, Lattice v) => (k :-> v) -> [(k,v)] -> (k :-> v)
f ⨆ [] = f
f ⨆ ((k,v):tl) = Map.insertWith (⊔) k v (f ⨆ tl)
(!!) :: (Ord k, Lattice v) => (k :-> v) -> k -> v
f !! k = Map.findWithDefault bot k f
State - space .
type Ctx = (CExp, Env, Time)
type Env = Var :-> Addr
type Store = Addr :-> D
type D = ℙ Val
data Val = Clo (Lambda, Env)
deriving (Eq,Ord)
data Addr = Bind Var Time
deriving (Eq,Ord)
data Time = CallSeq [CExp]
deriving (Eq,Ord)
class Monad m => Analysis m where
funEval :: Env -> AExp -> m Val
argEval :: Env -> AExp -> m D
($=) :: Addr -> D -> m ()
alloc :: Var -> m Addr
tick :: (Ctx,Time) -> m Time
class where
-- (>>=) :: m a -> (a -> m b) -> m b
-- (>>) :: m a -> m b -> m b
-- return :: a -> m a
-- fail :: String -> m a
data Exact a = Exact !(Store -> (a,Store))
data KCFA a = KCFA { kf :: !((Choices,Store) -> [(a,(Choices,Store))]) }
data Choice = Invoke Val
| Ticked Time
type Choices = [Choice]
timeFrom ((Ticked t):_) = t
k = 1
-- return a >>= k = k a
-- m >>= return = m
m > > = ( \x - > k x > > = h ) = ( m > > = k ) > > = h
instance Monad KCFA where
(>>=) (KCFA f) g = KCFA (\ (ch, σ) ->
let chs = f(ch, σ)
in concatMap (\ (a, (ch',σ')) -> (kf $ g(a))(ch', σ')) chs)
return a = KCFA (\ (ch, σ) -> [(a,(ch, σ))])
instance Analysis KCFA where
funEval ρ (Lam l) = KCFA (\ (ch,σ) ->
let proc = Clo(l, ρ)
in [ (proc,((Invoke proc) : ch, σ)) ])
funEval ρ (Ref v) = KCFA (\ (ch,σ) ->
let procs = σ!(ρ!v)
in [ (proc,((Invoke proc) : ch, σ)) | proc <- Set.toList procs ])
argEval ρ (Lam l) = KCFA (\ (ch,σ) ->
let proc = Clo(l, ρ)
in [ (Set.singleton proc, (ch, σ)) ])
argEval ρ (Ref v) = KCFA (\ (ch,σ) ->
let procs = σ!(ρ!v)
in [ (procs, (ch, σ)) ])
a $= d = KCFA (\ (ch,σ) -> [((),(ch,σ ⨆ [a ==> d]))])
alloc v = KCFA (\ (ch, σ) ->
let t' = timeFrom(ch)
in [(Bind v t',(ch, σ))])
tick ((call, ρ, _),CallSeq t) = KCFA (\ (ch, σ) ->
[(CallSeq (take k (call:t)), (ch,σ))])
mnext :: (Analysis m) => (CExp,Env,Time) -> m (CExp,Env,Time)
mnext ctx@(Call f aes, ρ, t) = do
clo@(Clo (vs :=> call', ρ')) <- funEval ρ f
t' <- tick(ctx,t)
as <- mapM alloc vs
ds <- mapM (argEval ρ) aes
let ρ'' = ρ' // [ v ==> a | v <- vs | a <- as ]
sequence [ a $= d | a <- as | d <- ds ]
return $! (call', ρ'', t')
main :: IO ()
main = do
return ()
| null | https://raw.githubusercontent.com/ilyasergey/monadic-cfa/caeb9e5375affe9c3cdee0753ae2ba489cdc328a/obsolete/MonadCFA.hs | haskell | Imports.
Abbreviations.
Partial order theory.
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
fail :: String -> m a
return a >>= k = k a
m >>= return = m | module Main where
import CPS
import Data.Map as Map
import Data.Set as Set
type k :-> v = Map.Map k v
type ℙ a = Set.Set a
(==>) :: a -> b -> (a,b)
(==>) x y = (x,y)
(//) :: Ord k => (k :-> v) -> [(k,v)] -> (k :-> v)
(//) f [] = f
(//) f ((x,y):tl) = Map.insert x y (f // tl)
class Lattice a where
bot :: a
top :: a
(⊑) :: a -> a -> Bool
(⊔) :: a -> a -> a
(⊓) :: a -> a -> a
instance (Ord s, Eq s) => Lattice (ℙ s) where
bot = Set.empty
top = error "no representation of universal set"
x ⊔ y = x `Set.union` y
x ⊓ y = x `Set.intersection` y
x ⊑ y = x `Set.isSubsetOf` y
instance (Ord k, Lattice v) => Lattice (k :-> v) where
bot = Map.empty
top = error "no representation of top map"
f ⊑ g = Map.isSubmapOfBy (⊑) f g
f ⊔ g = Map.unionWith (⊔) f g
f ⊓ g = Map.intersectionWith (⊓) f g
(⨆) :: (Ord k, Lattice v) => (k :-> v) -> [(k,v)] -> (k :-> v)
f ⨆ [] = f
f ⨆ ((k,v):tl) = Map.insertWith (⊔) k v (f ⨆ tl)
(!!) :: (Ord k, Lattice v) => (k :-> v) -> k -> v
f !! k = Map.findWithDefault bot k f
State - space .
type Ctx = (CExp, Env, Time)
type Env = Var :-> Addr
type Store = Addr :-> D
type D = ℙ Val
data Val = Clo (Lambda, Env)
deriving (Eq,Ord)
data Addr = Bind Var Time
deriving (Eq,Ord)
data Time = CallSeq [CExp]
deriving (Eq,Ord)
class Monad m => Analysis m where
funEval :: Env -> AExp -> m Val
argEval :: Env -> AExp -> m D
($=) :: Addr -> D -> m ()
alloc :: Var -> m Addr
tick :: (Ctx,Time) -> m Time
class where
data Exact a = Exact !(Store -> (a,Store))
data KCFA a = KCFA { kf :: !((Choices,Store) -> [(a,(Choices,Store))]) }
data Choice = Invoke Val
| Ticked Time
type Choices = [Choice]
timeFrom ((Ticked t):_) = t
k = 1
m > > = ( \x - > k x > > = h ) = ( m > > = k ) > > = h
instance Monad KCFA where
(>>=) (KCFA f) g = KCFA (\ (ch, σ) ->
let chs = f(ch, σ)
in concatMap (\ (a, (ch',σ')) -> (kf $ g(a))(ch', σ')) chs)
return a = KCFA (\ (ch, σ) -> [(a,(ch, σ))])
instance Analysis KCFA where
funEval ρ (Lam l) = KCFA (\ (ch,σ) ->
let proc = Clo(l, ρ)
in [ (proc,((Invoke proc) : ch, σ)) ])
funEval ρ (Ref v) = KCFA (\ (ch,σ) ->
let procs = σ!(ρ!v)
in [ (proc,((Invoke proc) : ch, σ)) | proc <- Set.toList procs ])
argEval ρ (Lam l) = KCFA (\ (ch,σ) ->
let proc = Clo(l, ρ)
in [ (Set.singleton proc, (ch, σ)) ])
argEval ρ (Ref v) = KCFA (\ (ch,σ) ->
let procs = σ!(ρ!v)
in [ (procs, (ch, σ)) ])
a $= d = KCFA (\ (ch,σ) -> [((),(ch,σ ⨆ [a ==> d]))])
alloc v = KCFA (\ (ch, σ) ->
let t' = timeFrom(ch)
in [(Bind v t',(ch, σ))])
tick ((call, ρ, _),CallSeq t) = KCFA (\ (ch, σ) ->
[(CallSeq (take k (call:t)), (ch,σ))])
mnext :: (Analysis m) => (CExp,Env,Time) -> m (CExp,Env,Time)
mnext ctx@(Call f aes, ρ, t) = do
clo@(Clo (vs :=> call', ρ')) <- funEval ρ f
t' <- tick(ctx,t)
as <- mapM alloc vs
ds <- mapM (argEval ρ) aes
let ρ'' = ρ' // [ v ==> a | v <- vs | a <- as ]
sequence [ a $= d | a <- as | d <- ds ]
return $! (call', ρ'', t')
main :: IO ()
main = do
return ()
|
b5b1ebe9fba2af3ddb44e22c6b1efef6b468163b584ddb8f3ed49357b8f31563 | repl-acement/repl-acement | page_view.cljs | (ns replacement.ui.page-view
(:require ["@codemirror/closebrackets" :refer [closeBrackets]]
["@codemirror/fold" :as fold]
["@codemirror/gutter" :refer [lineNumbers]]
["@codemirror/highlight" :as highlight]
["@codemirror/history" :refer [history historyKeymap]]
["@codemirror/state" :refer [EditorState]]
["@codemirror/view" :as view :refer [EditorView]]
["lezer" :as lezer]
["lezer-generator" :as lg]
["lezer-tree" :as lz-tree]
[applied-science.js-interop :as j]
[cljs.tools.reader.edn :as edn]
[clojure.string :as str]
[nextjournal.clojure-mode :as cm-clj]
[nextjournal.clojure-mode.extensions.close-brackets :as close-brackets]
[nextjournal.clojure-mode.extensions.formatting :as format]
[nextjournal.clojure-mode.extensions.selection-history :as sel-history]
[nextjournal.clojure-mode.keymap :as keymap]
[nextjournal.clojure-mode.live-grammar :as live-grammar]
[nextjournal.clojure-mode.node :as n]
[nextjournal.clojure-mode.selections :as sel]
[nextjournal.clojure-mode.test-utils :as test-utils]
[reagent.core :as r]
[reagent.dom :as rdom]
[re-com.core :refer [h-box v-box checkbox box button gap line scroller border label input-text md-circle-icon-button
md-icon-button input-textarea h-split v-split popover-anchor-wrapper
popover-content-wrapper title flex-child-style p slider]]
[re-com.splits :refer [hv-split-args-desc]]
[re-com.tabs :refer [vertical-pill-tabs horizontal-tabs]]
[re-frame.core :as re-frame]
[replacement.forms.events.common :as common-events]
[replacement.forms.events.def :as def-events]
[replacement.forms.events.defn :as defn-events]
[replacement.forms.events.ns :as ns-events]
[replacement.forms.events.req-libs :as req-lib-events]
[replacement.forms.events.whole-ns :as whole-ns]
[replacement.forms.parser.parse :as form-parser]
[replacement.protocol.data :as protocol-data]
[replacement.structure.wiring :as wiring]
[replacement.ui.remote-prepl :as prepl]
[replacement.ui.subs :as subs]
[zprint.core :refer [zprint-file-str]]))
;; TODO - migrate from random data structures to event protocol data structures
;; Actions:
DONE 1 . Have both structures in the re - frame DB
DONE 2 . Use the same means to generate IDs for both structures
DONE 1 . Ensure new structures have correct keywords
PLAN 1a . Start with ` whole - ns ` working with new data structures
PLAN 2 . Start with ` def ` working with new data structures
PLAN 2a . Try to create common functions on how to transform the protocol data
PLAN 3 . Proceed with ` defn ` and the new data structures
;; PLAN 4. Finish up with `ns` working with new data structures
(def theme
(.theme EditorView
(j/lit {"&" {:font-size "16px"
}
".cm-content" {:white-space "pre-wrap"
:padding "10px 0"}
"&.cm-focused" {:outline "none"}
".cm-line" {:padding "0 9px"
:line-height "1.6"
:font-size "16px"
:font-family "var(--code-font)"}
".cm-matchingBracket" {:border-bottom "1px solid #ff0000"
:color "inherit"}
".cm-gutters" {:background "transparent"
:border "none"}
".cm-gutterElement" {:margin-left "5px"}
;; only show cursor when focused
".cm-cursor" {:visibility "hidden"}
"&.cm-focused .cm-cursor" {:visibility "visible"}})))
(def ^:private extensions
#js[theme
(history)
highlight/defaultHighlightStyle
(view/drawSelection)
(fold/foldGutter)
(.. EditorState -allowMultipleSelections (of true))
cm-clj/default-extensions
(.of view/keymap cm-clj/complete-keymap)
(.of view/keymap historyKeymap)
(.of view/keymap
(j/lit
[{:key "Alt-Enter"
:run (fn [x] (prepl/eval-cell x))}]))])
(def extensions-read-only
#js[theme
highlight/defaultHighlightStyle
(view/drawSelection)
(.. EditorState -allowMultipleSelections (of true))
cm-clj/default-extensions
(.. EditorView -editable (of false))])
(defn linux? []
(some? (re-find #"(Linux)|(X11)" js/navigator.userAgent)))
(defn mac? []
(and (not (linux?))
(some? (re-find #"(Mac)|(iPhone)|(iPad)|(iPod)" js/navigator.platform))))
(defn key-mapping []
(cond-> {"ArrowUp" "↑"
"ArrowDown" "↓"
"ArrowRight" "→"
"ArrowLeft" "←"
"Mod" "Ctrl"}
(mac?)
(merge {"Alt" "⌥"
"Shift" "⇧"
"Enter" "⏎"
"Ctrl" "⌃"
"Mod" "⌘"})))
(defn editor-view
[component initial-document event-name index]
(EditorView. #js {:state (.create EditorState #js {:doc initial-document
:extensions extensions})
:parent (rdom/dom-node component)
:dispatch (fn [tx]
(re-frame/dispatch [event-name tx index]))}))
(defn part-edit
[part-cm-name event-name tx]
(re-frame/dispatch [event-name part-cm-name tx]))
(defn comp-editor-view
[dom-element initial-document part-cm-name edit-event]
(EditorView. #js {:state (.create EditorState #js {:doc initial-document
:extensions extensions})
:parent (rdom/dom-node dom-element)
:dispatch (partial part-edit part-cm-name edit-event)}))
(defn comp-editor
"Produces a function to act on a code mirror view with the given cm-name
using an optional initial document. An empty string is used if no
document is provided."
([cm-name edit-event-name]
(comp-editor cm-name "" edit-event-name))
([cm-name initial-document edit-event-name]
(fn [dom-element]
(let [!view (comp-editor-view dom-element initial-document cm-name edit-event-name)]
(re-frame/dispatch-sync [::common-events/set-cm+name !view cm-name])))))
(defn part-editor
([cm-name part-type]
(part-editor cm-name part-type ""))
([cm-name part-type document]
(let [editor (partial comp-editor cm-name document)]
[:div {:ref (condp = part-type
:req-libs (editor ::req-lib-events/part-edit)
:def (editor ::def-events/part-edit)
:defn (editor ::defn-events/part-edit)
:ns (editor ::ns-events/part-edit))}])))
(defn form-editor
[{:keys [data text-key cm-key tx-event-name cm-event-name]}]
(let [initial-document (-> (get-in data [:form text-key])
common-events/fix-width-format)
!mount (fn [comp]
(let [cm-name (wiring/comp-name->cm-name cm-key)
!view (EditorView. #js {:state (.create EditorState #js {:doc initial-document
:extensions extensions})
:parent (rdom/dom-node comp)
:dispatch (fn [tx]
(re-frame/dispatch [tx-event-name cm-name tx]))})]
(re-frame/dispatch-sync [cm-event-name !view cm-name])))]
[:div {:ref !mount}]))
(defn def-form-editor
[form-data]
(form-editor {:data form-data
:text-key :def.text
:cm-key :def.form
:tx-event-name ::def-events/def-whole-form-tx
:cm-event-name ::common-events/set-cm+name}))
(defn defn-form-editor
[form-data]
(form-editor {:data form-data
:text-key :defn.text
:cm-key :defn.form
:tx-event-name ::defn-events/form-tx
:cm-event-name ::common-events/set-cm+name}))
(defn ns-form-editor
[form-data]
(form-editor {:data form-data
:text-key :ns.text
:cm-key :ns.form
:tx-event-name ::ns-events/whole-form-tx
:cm-event-name ::common-events/set-cm+name}))
(defn result-view [{:keys [val]}]
(let [!mount (fn [comp]
(EditorView. #js {:state (.create EditorState #js {:doc (str "=> " val)
:extensions extensions-read-only})
:parent (rdom/dom-node comp)}))]
[:div {:ref !mount}]))
(defn result-box []
[v-box :children
[[title :level :level2 :label "REPL Output"]
(let [results (re-frame/subscribe [::subs/latest-result])]
(fn []
(prn :result-box (:val @results))
(when @results [result-view @results])))]])
(defn prepend-index
[arity-index n-arities label]
(if (>= 1 n-arities)
label
(str arity-index "-" label)))
(defn pretty-label
[label-keyword]
(-> (name label-keyword)
(str/replace #".*\." "")
(str/capitalize)))
(defn component-part
([form-type part-name label-text]
(component-part form-type part-name label-text ""))
([form-type part-name label-text document]
[h-box :gap "5px" :align :center :justify :start
:children
[[label :width "50px" :style {:font-weight :bold :font-size "16px"} :label label-text]
[gap :size "10px"]
[part-editor (wiring/comp-name->cm-name part-name) form-type document]]]))
(defn- defn-component-parts
[part-list]
(mapcat (fn [part-name]
[[component-part :defn part-name (pretty-label part-name)]
[line :color "#D8D8D8"]])
part-list))
(defn- require-component-parts
[part-list]
(mapcat (fn [part-name]
[[component-part :req-libs part-name (pretty-label part-name)]
[line :color "#D8D8D8"]])
part-list))
;; NO !!! Set it in the DB
(def editable-defn-arity-parts (atom nil))
(defn defn-arity-parts
[]
(let [arity-parts (or @editable-defn-arity-parts
(reset! editable-defn-arity-parts (defn-component-parts defn-events/arity-parts)))]
[v-box :gap "10px" :width "800px" :children arity-parts]))
;; NO !!! Set it in the DB
(def editable-defn-multi-attrs (r/atom nil))
(defn defn-multi-attrs
[]
(let [attrs (or @editable-defn-multi-attrs
(reset! editable-defn-multi-attrs (defn-component-parts defn-events/multi-arity-attrs)))]
[v-box :gap "10px" :width "800px" :children
[[gap :size "10px"]
[label :style {:font-size "16px" :color :gray} :label "Multi Arity Metadata"]
[line :color "#D8D8D8"]
(first attrs)]]))
;; NO !!! Set it in the DB
(def editable-defn-parts (r/atom nil))
(defn defn-parts
[{:keys [form]}]
(let [arity-index @(re-frame/subscribe [::subs/arity-index])
{:keys [single-arity? arity-data]} form
arity-elements (map-indexed (fn [idx _]
{:id idx
:label (str "Arity " (inc idx))})
arity-data)
common-parts (or @editable-defn-parts
(reset! editable-defn-parts (defn-component-parts defn-events/fixed-parts)))]
(tap> [::defn-parts :arity-elements arity-elements :form form])
;; NO!!!! - FFS Write down why next time cos I'm lost dude. And I am you :(
(re-frame/dispatch [::defn-events/set-form arity-index])
[v-box :gap "10px" :children
[[v-box :gap "10px" :children common-parts]
[horizontal-tabs
:style {:font-size "16px"}
:model arity-index
:tabs arity-elements
:on-change (fn [index]
(re-frame/dispatch [::defn-events/arity-update-cms index]))]
[defn-arity-parts]
(when-not single-arity?
[defn-multi-attrs])]]))
;; NO !!! Set it in the DB
(def editable-def-parts (atom nil))
;; TODO - fix the init string to be the value from the vector rather than the vector itself
(defn def-parts
[{:keys [id]}]
(let [parts (or @editable-def-parts
(reset! editable-def-parts (mapcat (fn [part-name]
[[component-part :def part-name (pretty-label part-name)]
[line :color "#D8D8D8"]])
def-events/parts)))]
;; NO !!!
(re-frame/dispatch [::def-events/set-view id])
[v-box :width "800px" :gap "10px" :children parts]))
;; NO !!! Set it in the DB
(def editable-require-parts (atom nil))
(defn ns-parts
[form-data]
(let [structured-view-active? @(re-frame/subscribe [::subs/structured-view?])]
(when structured-view-active?
(let [requires (map-indexed (fn [idx {:keys [require]}]
(let [{:keys [lib]} require]
{:id idx
:label (ns-events/shortened-ns-name (str (last lib)))}))
(get-in form-data [:form :ns.parts :require-libs]))
ns-part-forms (or @editable-require-parts
(reset! editable-require-parts (require-component-parts req-lib-events/parts)))
first-parts (mapcat (fn [part-name]
[[component-part :req-libs part-name (pretty-label part-name)]
[line :color "#D8D8D8"]])
ns-events/parts)
selected-var (r/atom (:id (first requires)))]
;; NO !!!
(re-frame/dispatch [::ns-events/transact-whole-form (get-in form-data [:form :ns.text])])
(fn []
[v-box :width "800px" :children
[[v-box :gap "5px" :children first-parts]
[gap :size "20px"]
[label :style {:font-weight :bold :font-size "16px"} :label "Requires"]
[gap :size "20px"]
[h-box :style {:font-size "16px"} :gap "25px" :children
[[vertical-pill-tabs
:model selected-var
:tabs requires
:on-change (fn [index]
(re-frame/dispatch [::req-lib-events/update-cms index])
(reset! selected-var index))]
[v-box :width "500px" :children ns-part-forms]]]]])))))
(defn view-toggle
[structured?]
[md-icon-button :md-icon-name (if structured? "zmdi-code-setting" "zmdi-wrap-text")
:tooltip (str "Edit using " (if structured? "structure" "text"))
:on-click (fn []
(re-frame/dispatch-sync [::whole-ns/set-view])
(re-frame/dispatch [::whole-ns/swap-structured-view]))])
(defn editable-parts
[form-data]
(let [structured-view-active? @(re-frame/subscribe [::subs/structured-view?])]
(when structured-view-active?
[h-box :children
[[v-box :width "800px" :gap "20px" :children
[[title :level :level2 :label (:name form-data)]
(condp = (:type form-data)
:defn [defn-parts form-data]
:def [def-parts form-data]
:ns [ns-parts form-data]
TODO - improve default behaviour ...
[label :label "Unknown parts"])]]
[view-toggle false]]])))
(defn type-label
[ref-type]
(condp = ref-type
:def "zmdi-settings"
:defn "zmdi-functions"
:ns "zmdi-format-list-bulleted"
"zmdi-help"))
(def editable-forms (atom nil))
(defn editable-text
[form-data]
(let [structured-view-active? @(re-frame/subscribe [::subs/structured-view?])]
(when-not structured-view-active?
[h-box :children
[[v-box :width "800px" :gap "20px" :children
[[title :level :level2 :label (:name form-data)]
(condp = (:type form-data)
:def (or (:var-form @editable-forms)
(:var-form (swap! editable-forms assoc :var-form [def-form-editor form-data])))
:defn (or (:defn-form @editable-forms)
(:defn-form (swap! editable-forms assoc :defn-form [defn-form-editor form-data])))
:ns (or (:ns-form @editable-forms)
(:ns-form (swap! editable-forms assoc :ns-form [ns-form-editor form-data])))
TODO - improve default behaviour ...
[label :label "Unknown form"])]]
[view-toggle true]]])))
(defn form-view
[form-data]
[h-box :children
[[editable-parts form-data]
[editable-text form-data]]])
(defn ns-list-view
[var-data default-var]
(let [ns-vars (mapv (fn [args]
(let [[id data] (first args)
{::protocol-data/keys [type var-name]} data]
(merge (select-keys data [::protocol-data/type ::protocol-data/var-name])
{:id id
:label [h-box :align :center :gap "7px" :children
[[md-icon-button :md-icon-name (type-label type) :size :smaller]
[label :label var-name]]]})))
var-data)
type-mapping (apply merge (map #(hash-map (:id %) (select-keys % [::protocol-data/type ::protocol-data/var-name])) ns-vars))
TODO fix to have it come from a subs
selected-var (r/atom default-var)]
[v-box :style {:font-size "16px"} :gap "5px"
:children
[[vertical-pill-tabs
:model selected-var
:tabs ns-vars
:on-change (fn [var-id]
(let [var-type (get (type-mapping var-id) ::protocol-data/type)
var-name (get (type-mapping var-id) ::protocol-data/var-name)
form-data {:id var-id :type var-type :name var-name}]
NEXT ... Fix ... current - form - data should take the new ns keywords version of the data
(re-frame/dispatch-sync [::whole-ns/current-form-data form-data])
(re-frame/dispatch-sync [::whole-ns/set-view])
(reset! selected-var var-id)))]]]))
(defn format-ns
[the-ns-name]
(let [[_ first-part last-part] (re-find #"(.*)\.(.*)" (str the-ns-name))]
[h-box :align :center :children
[[label :style {:color "grey" :font-size :smaller} :label (str first-part ".")]
[label :style {:color "blue" :font-weight :bolder} :label last-part]]]))
(defn ns-view
[view-ns-data {:keys [id] :as _highlighted-form}]
(let [new-ns-data (map (fn [id]
(hash-map id (get (:forms view-ns-data) id)))
(:index view-ns-data))]
(when id
[v-box :width "175px" :gap "5px"
:children
[[title :level :level2 :label (format-ns (::protocol-data/ns-name new-ns-data))]
(ns-list-view new-ns-data id)]])))
(defn transformers []
(let [prn-ticked? (r/atom false)
tap-ticked? (r/atom false)]
;; read this from config
[h-box :align :center :gap "15px"
:children
[[checkbox
:label "Print params"
:model prn-ticked?
:on-change (fn [setting]
(reset! prn-ticked? setting)
(re-frame/dispatch [::whole-ns/defn-transforms-toggle :defn.params.prn setting]))]
[checkbox
:label "Tap params"
:model tap-ticked?
:on-change (fn [setting]
(reset! tap-ticked? setting)
(re-frame/dispatch [::whole-ns/defn-transforms-toggle :defn.params.tap setting]))]]]))
(defn transform-options []
[h-box :align :center :gap "20px"
:children
[[title :level :level2 :label "Transformations"]
[gap :size "10px"]
[transformers]]])
(defn whole-ns-view []
(let [ns-data @(re-frame/subscribe [::subs/current-ns])
current-form @(re-frame/subscribe [::subs/current-form-data])]
[v-box :gap "20px" :justify :center :padding "15px"
:children
[[transform-options]
[line :color "#D8D8D8"]
[h-box :align :start :gap "75px"
:children
[[ns-view ns-data current-form]
[form-view current-form]]]]]))
(defn render []
(rdom/render [whole-ns-view] (js/document.getElementById "form-editor"))
(let [mapping (key-mapping)]
(.. (js/document.querySelectorAll ".mod,.alt,.ctrl")
(forEach #(when-let [k (get mapping (.-innerHTML %))]
(set! (.-innerHTML %) k)))))
(when (linux?)
(js/twemoji.parse (.-body js/document))))
| null | https://raw.githubusercontent.com/repl-acement/repl-acement/2a1c5762ebe6225cd9c53e4ce0413046495ce0d8/repl-ui/replacement/ui/page_view.cljs | clojure | TODO - migrate from random data structures to event protocol data structures
Actions:
PLAN 4. Finish up with `ns` working with new data structures
only show cursor when focused
NO !!! Set it in the DB
NO !!! Set it in the DB
NO !!! Set it in the DB
NO!!!! - FFS Write down why next time cos I'm lost dude. And I am you :(
NO !!! Set it in the DB
TODO - fix the init string to be the value from the vector rather than the vector itself
NO !!!
NO !!! Set it in the DB
NO !!!
read this from config | (ns replacement.ui.page-view
(:require ["@codemirror/closebrackets" :refer [closeBrackets]]
["@codemirror/fold" :as fold]
["@codemirror/gutter" :refer [lineNumbers]]
["@codemirror/highlight" :as highlight]
["@codemirror/history" :refer [history historyKeymap]]
["@codemirror/state" :refer [EditorState]]
["@codemirror/view" :as view :refer [EditorView]]
["lezer" :as lezer]
["lezer-generator" :as lg]
["lezer-tree" :as lz-tree]
[applied-science.js-interop :as j]
[cljs.tools.reader.edn :as edn]
[clojure.string :as str]
[nextjournal.clojure-mode :as cm-clj]
[nextjournal.clojure-mode.extensions.close-brackets :as close-brackets]
[nextjournal.clojure-mode.extensions.formatting :as format]
[nextjournal.clojure-mode.extensions.selection-history :as sel-history]
[nextjournal.clojure-mode.keymap :as keymap]
[nextjournal.clojure-mode.live-grammar :as live-grammar]
[nextjournal.clojure-mode.node :as n]
[nextjournal.clojure-mode.selections :as sel]
[nextjournal.clojure-mode.test-utils :as test-utils]
[reagent.core :as r]
[reagent.dom :as rdom]
[re-com.core :refer [h-box v-box checkbox box button gap line scroller border label input-text md-circle-icon-button
md-icon-button input-textarea h-split v-split popover-anchor-wrapper
popover-content-wrapper title flex-child-style p slider]]
[re-com.splits :refer [hv-split-args-desc]]
[re-com.tabs :refer [vertical-pill-tabs horizontal-tabs]]
[re-frame.core :as re-frame]
[replacement.forms.events.common :as common-events]
[replacement.forms.events.def :as def-events]
[replacement.forms.events.defn :as defn-events]
[replacement.forms.events.ns :as ns-events]
[replacement.forms.events.req-libs :as req-lib-events]
[replacement.forms.events.whole-ns :as whole-ns]
[replacement.forms.parser.parse :as form-parser]
[replacement.protocol.data :as protocol-data]
[replacement.structure.wiring :as wiring]
[replacement.ui.remote-prepl :as prepl]
[replacement.ui.subs :as subs]
[zprint.core :refer [zprint-file-str]]))
DONE 1 . Have both structures in the re - frame DB
DONE 2 . Use the same means to generate IDs for both structures
DONE 1 . Ensure new structures have correct keywords
PLAN 1a . Start with ` whole - ns ` working with new data structures
PLAN 2 . Start with ` def ` working with new data structures
PLAN 2a . Try to create common functions on how to transform the protocol data
PLAN 3 . Proceed with ` defn ` and the new data structures
(def theme
(.theme EditorView
(j/lit {"&" {:font-size "16px"
}
".cm-content" {:white-space "pre-wrap"
:padding "10px 0"}
"&.cm-focused" {:outline "none"}
".cm-line" {:padding "0 9px"
:line-height "1.6"
:font-size "16px"
:font-family "var(--code-font)"}
".cm-matchingBracket" {:border-bottom "1px solid #ff0000"
:color "inherit"}
".cm-gutters" {:background "transparent"
:border "none"}
".cm-gutterElement" {:margin-left "5px"}
".cm-cursor" {:visibility "hidden"}
"&.cm-focused .cm-cursor" {:visibility "visible"}})))
(def ^:private extensions
#js[theme
(history)
highlight/defaultHighlightStyle
(view/drawSelection)
(fold/foldGutter)
(.. EditorState -allowMultipleSelections (of true))
cm-clj/default-extensions
(.of view/keymap cm-clj/complete-keymap)
(.of view/keymap historyKeymap)
(.of view/keymap
(j/lit
[{:key "Alt-Enter"
:run (fn [x] (prepl/eval-cell x))}]))])
(def extensions-read-only
#js[theme
highlight/defaultHighlightStyle
(view/drawSelection)
(.. EditorState -allowMultipleSelections (of true))
cm-clj/default-extensions
(.. EditorView -editable (of false))])
(defn linux? []
(some? (re-find #"(Linux)|(X11)" js/navigator.userAgent)))
(defn mac? []
(and (not (linux?))
(some? (re-find #"(Mac)|(iPhone)|(iPad)|(iPod)" js/navigator.platform))))
(defn key-mapping []
(cond-> {"ArrowUp" "↑"
"ArrowDown" "↓"
"ArrowRight" "→"
"ArrowLeft" "←"
"Mod" "Ctrl"}
(mac?)
(merge {"Alt" "⌥"
"Shift" "⇧"
"Enter" "⏎"
"Ctrl" "⌃"
"Mod" "⌘"})))
(defn editor-view
[component initial-document event-name index]
(EditorView. #js {:state (.create EditorState #js {:doc initial-document
:extensions extensions})
:parent (rdom/dom-node component)
:dispatch (fn [tx]
(re-frame/dispatch [event-name tx index]))}))
(defn part-edit
[part-cm-name event-name tx]
(re-frame/dispatch [event-name part-cm-name tx]))
(defn comp-editor-view
[dom-element initial-document part-cm-name edit-event]
(EditorView. #js {:state (.create EditorState #js {:doc initial-document
:extensions extensions})
:parent (rdom/dom-node dom-element)
:dispatch (partial part-edit part-cm-name edit-event)}))
(defn comp-editor
"Produces a function to act on a code mirror view with the given cm-name
using an optional initial document. An empty string is used if no
document is provided."
([cm-name edit-event-name]
(comp-editor cm-name "" edit-event-name))
([cm-name initial-document edit-event-name]
(fn [dom-element]
(let [!view (comp-editor-view dom-element initial-document cm-name edit-event-name)]
(re-frame/dispatch-sync [::common-events/set-cm+name !view cm-name])))))
(defn part-editor
([cm-name part-type]
(part-editor cm-name part-type ""))
([cm-name part-type document]
(let [editor (partial comp-editor cm-name document)]
[:div {:ref (condp = part-type
:req-libs (editor ::req-lib-events/part-edit)
:def (editor ::def-events/part-edit)
:defn (editor ::defn-events/part-edit)
:ns (editor ::ns-events/part-edit))}])))
(defn form-editor
[{:keys [data text-key cm-key tx-event-name cm-event-name]}]
(let [initial-document (-> (get-in data [:form text-key])
common-events/fix-width-format)
!mount (fn [comp]
(let [cm-name (wiring/comp-name->cm-name cm-key)
!view (EditorView. #js {:state (.create EditorState #js {:doc initial-document
:extensions extensions})
:parent (rdom/dom-node comp)
:dispatch (fn [tx]
(re-frame/dispatch [tx-event-name cm-name tx]))})]
(re-frame/dispatch-sync [cm-event-name !view cm-name])))]
[:div {:ref !mount}]))
(defn def-form-editor
[form-data]
(form-editor {:data form-data
:text-key :def.text
:cm-key :def.form
:tx-event-name ::def-events/def-whole-form-tx
:cm-event-name ::common-events/set-cm+name}))
(defn defn-form-editor
[form-data]
(form-editor {:data form-data
:text-key :defn.text
:cm-key :defn.form
:tx-event-name ::defn-events/form-tx
:cm-event-name ::common-events/set-cm+name}))
(defn ns-form-editor
[form-data]
(form-editor {:data form-data
:text-key :ns.text
:cm-key :ns.form
:tx-event-name ::ns-events/whole-form-tx
:cm-event-name ::common-events/set-cm+name}))
(defn result-view [{:keys [val]}]
(let [!mount (fn [comp]
(EditorView. #js {:state (.create EditorState #js {:doc (str "=> " val)
:extensions extensions-read-only})
:parent (rdom/dom-node comp)}))]
[:div {:ref !mount}]))
(defn result-box []
[v-box :children
[[title :level :level2 :label "REPL Output"]
(let [results (re-frame/subscribe [::subs/latest-result])]
(fn []
(prn :result-box (:val @results))
(when @results [result-view @results])))]])
(defn prepend-index
[arity-index n-arities label]
(if (>= 1 n-arities)
label
(str arity-index "-" label)))
(defn pretty-label
[label-keyword]
(-> (name label-keyword)
(str/replace #".*\." "")
(str/capitalize)))
(defn component-part
([form-type part-name label-text]
(component-part form-type part-name label-text ""))
([form-type part-name label-text document]
[h-box :gap "5px" :align :center :justify :start
:children
[[label :width "50px" :style {:font-weight :bold :font-size "16px"} :label label-text]
[gap :size "10px"]
[part-editor (wiring/comp-name->cm-name part-name) form-type document]]]))
(defn- defn-component-parts
[part-list]
(mapcat (fn [part-name]
[[component-part :defn part-name (pretty-label part-name)]
[line :color "#D8D8D8"]])
part-list))
(defn- require-component-parts
[part-list]
(mapcat (fn [part-name]
[[component-part :req-libs part-name (pretty-label part-name)]
[line :color "#D8D8D8"]])
part-list))
(def editable-defn-arity-parts (atom nil))
(defn defn-arity-parts
[]
(let [arity-parts (or @editable-defn-arity-parts
(reset! editable-defn-arity-parts (defn-component-parts defn-events/arity-parts)))]
[v-box :gap "10px" :width "800px" :children arity-parts]))
(def editable-defn-multi-attrs (r/atom nil))
(defn defn-multi-attrs
[]
(let [attrs (or @editable-defn-multi-attrs
(reset! editable-defn-multi-attrs (defn-component-parts defn-events/multi-arity-attrs)))]
[v-box :gap "10px" :width "800px" :children
[[gap :size "10px"]
[label :style {:font-size "16px" :color :gray} :label "Multi Arity Metadata"]
[line :color "#D8D8D8"]
(first attrs)]]))
(def editable-defn-parts (r/atom nil))
(defn defn-parts
[{:keys [form]}]
(let [arity-index @(re-frame/subscribe [::subs/arity-index])
{:keys [single-arity? arity-data]} form
arity-elements (map-indexed (fn [idx _]
{:id idx
:label (str "Arity " (inc idx))})
arity-data)
common-parts (or @editable-defn-parts
(reset! editable-defn-parts (defn-component-parts defn-events/fixed-parts)))]
(tap> [::defn-parts :arity-elements arity-elements :form form])
(re-frame/dispatch [::defn-events/set-form arity-index])
[v-box :gap "10px" :children
[[v-box :gap "10px" :children common-parts]
[horizontal-tabs
:style {:font-size "16px"}
:model arity-index
:tabs arity-elements
:on-change (fn [index]
(re-frame/dispatch [::defn-events/arity-update-cms index]))]
[defn-arity-parts]
(when-not single-arity?
[defn-multi-attrs])]]))
(def editable-def-parts (atom nil))
(defn def-parts
[{:keys [id]}]
(let [parts (or @editable-def-parts
(reset! editable-def-parts (mapcat (fn [part-name]
[[component-part :def part-name (pretty-label part-name)]
[line :color "#D8D8D8"]])
def-events/parts)))]
(re-frame/dispatch [::def-events/set-view id])
[v-box :width "800px" :gap "10px" :children parts]))
(def editable-require-parts (atom nil))
(defn ns-parts
[form-data]
(let [structured-view-active? @(re-frame/subscribe [::subs/structured-view?])]
(when structured-view-active?
(let [requires (map-indexed (fn [idx {:keys [require]}]
(let [{:keys [lib]} require]
{:id idx
:label (ns-events/shortened-ns-name (str (last lib)))}))
(get-in form-data [:form :ns.parts :require-libs]))
ns-part-forms (or @editable-require-parts
(reset! editable-require-parts (require-component-parts req-lib-events/parts)))
first-parts (mapcat (fn [part-name]
[[component-part :req-libs part-name (pretty-label part-name)]
[line :color "#D8D8D8"]])
ns-events/parts)
selected-var (r/atom (:id (first requires)))]
(re-frame/dispatch [::ns-events/transact-whole-form (get-in form-data [:form :ns.text])])
(fn []
[v-box :width "800px" :children
[[v-box :gap "5px" :children first-parts]
[gap :size "20px"]
[label :style {:font-weight :bold :font-size "16px"} :label "Requires"]
[gap :size "20px"]
[h-box :style {:font-size "16px"} :gap "25px" :children
[[vertical-pill-tabs
:model selected-var
:tabs requires
:on-change (fn [index]
(re-frame/dispatch [::req-lib-events/update-cms index])
(reset! selected-var index))]
[v-box :width "500px" :children ns-part-forms]]]]])))))
(defn view-toggle
[structured?]
[md-icon-button :md-icon-name (if structured? "zmdi-code-setting" "zmdi-wrap-text")
:tooltip (str "Edit using " (if structured? "structure" "text"))
:on-click (fn []
(re-frame/dispatch-sync [::whole-ns/set-view])
(re-frame/dispatch [::whole-ns/swap-structured-view]))])
(defn editable-parts
[form-data]
(let [structured-view-active? @(re-frame/subscribe [::subs/structured-view?])]
(when structured-view-active?
[h-box :children
[[v-box :width "800px" :gap "20px" :children
[[title :level :level2 :label (:name form-data)]
(condp = (:type form-data)
:defn [defn-parts form-data]
:def [def-parts form-data]
:ns [ns-parts form-data]
TODO - improve default behaviour ...
[label :label "Unknown parts"])]]
[view-toggle false]]])))
(defn type-label
[ref-type]
(condp = ref-type
:def "zmdi-settings"
:defn "zmdi-functions"
:ns "zmdi-format-list-bulleted"
"zmdi-help"))
(def editable-forms (atom nil))
(defn editable-text
[form-data]
(let [structured-view-active? @(re-frame/subscribe [::subs/structured-view?])]
(when-not structured-view-active?
[h-box :children
[[v-box :width "800px" :gap "20px" :children
[[title :level :level2 :label (:name form-data)]
(condp = (:type form-data)
:def (or (:var-form @editable-forms)
(:var-form (swap! editable-forms assoc :var-form [def-form-editor form-data])))
:defn (or (:defn-form @editable-forms)
(:defn-form (swap! editable-forms assoc :defn-form [defn-form-editor form-data])))
:ns (or (:ns-form @editable-forms)
(:ns-form (swap! editable-forms assoc :ns-form [ns-form-editor form-data])))
TODO - improve default behaviour ...
[label :label "Unknown form"])]]
[view-toggle true]]])))
(defn form-view
[form-data]
[h-box :children
[[editable-parts form-data]
[editable-text form-data]]])
(defn ns-list-view
[var-data default-var]
(let [ns-vars (mapv (fn [args]
(let [[id data] (first args)
{::protocol-data/keys [type var-name]} data]
(merge (select-keys data [::protocol-data/type ::protocol-data/var-name])
{:id id
:label [h-box :align :center :gap "7px" :children
[[md-icon-button :md-icon-name (type-label type) :size :smaller]
[label :label var-name]]]})))
var-data)
type-mapping (apply merge (map #(hash-map (:id %) (select-keys % [::protocol-data/type ::protocol-data/var-name])) ns-vars))
TODO fix to have it come from a subs
selected-var (r/atom default-var)]
[v-box :style {:font-size "16px"} :gap "5px"
:children
[[vertical-pill-tabs
:model selected-var
:tabs ns-vars
:on-change (fn [var-id]
(let [var-type (get (type-mapping var-id) ::protocol-data/type)
var-name (get (type-mapping var-id) ::protocol-data/var-name)
form-data {:id var-id :type var-type :name var-name}]
NEXT ... Fix ... current - form - data should take the new ns keywords version of the data
(re-frame/dispatch-sync [::whole-ns/current-form-data form-data])
(re-frame/dispatch-sync [::whole-ns/set-view])
(reset! selected-var var-id)))]]]))
(defn format-ns
[the-ns-name]
(let [[_ first-part last-part] (re-find #"(.*)\.(.*)" (str the-ns-name))]
[h-box :align :center :children
[[label :style {:color "grey" :font-size :smaller} :label (str first-part ".")]
[label :style {:color "blue" :font-weight :bolder} :label last-part]]]))
(defn ns-view
[view-ns-data {:keys [id] :as _highlighted-form}]
(let [new-ns-data (map (fn [id]
(hash-map id (get (:forms view-ns-data) id)))
(:index view-ns-data))]
(when id
[v-box :width "175px" :gap "5px"
:children
[[title :level :level2 :label (format-ns (::protocol-data/ns-name new-ns-data))]
(ns-list-view new-ns-data id)]])))
(defn transformers []
(let [prn-ticked? (r/atom false)
tap-ticked? (r/atom false)]
[h-box :align :center :gap "15px"
:children
[[checkbox
:label "Print params"
:model prn-ticked?
:on-change (fn [setting]
(reset! prn-ticked? setting)
(re-frame/dispatch [::whole-ns/defn-transforms-toggle :defn.params.prn setting]))]
[checkbox
:label "Tap params"
:model tap-ticked?
:on-change (fn [setting]
(reset! tap-ticked? setting)
(re-frame/dispatch [::whole-ns/defn-transforms-toggle :defn.params.tap setting]))]]]))
(defn transform-options []
[h-box :align :center :gap "20px"
:children
[[title :level :level2 :label "Transformations"]
[gap :size "10px"]
[transformers]]])
(defn whole-ns-view []
(let [ns-data @(re-frame/subscribe [::subs/current-ns])
current-form @(re-frame/subscribe [::subs/current-form-data])]
[v-box :gap "20px" :justify :center :padding "15px"
:children
[[transform-options]
[line :color "#D8D8D8"]
[h-box :align :start :gap "75px"
:children
[[ns-view ns-data current-form]
[form-view current-form]]]]]))
(defn render []
(rdom/render [whole-ns-view] (js/document.getElementById "form-editor"))
(let [mapping (key-mapping)]
(.. (js/document.querySelectorAll ".mod,.alt,.ctrl")
(forEach #(when-let [k (get mapping (.-innerHTML %))]
(set! (.-innerHTML %) k)))))
(when (linux?)
(js/twemoji.parse (.-body js/document))))
|
05dde625636437389ac6ec6d63a2931fbc8423355bf3b48cde7e08af813796ed | lpeterse/haskell-terminal | TerminalT.hs | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module System.Terminal.TerminalT
( TerminalT ()
, runTerminalT
)
where
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.STM
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader
import Data.Foldable (forM_)
import qualified Data.Text as Text
import Prelude hiding (putChar)
import System.Terminal.MonadInput
import System.Terminal.MonadPrinter
import System.Terminal.MonadScreen
import System.Terminal.MonadTerminal
import qualified System.Terminal.Terminal as T
-- | This monad transformer represents terminal applications.
--
-- It implements all classes in this module and should serve as a good
-- foundation for most use cases.
--
-- Note that it is not necessary nor recommended to have this type in
-- every signature. Keep your application abstract and mention `TerminalT`
-- only once at the top level.
--
-- Example:
--
-- @
-- main :: IO ()
-- main = `withTerminal` (`runTerminalT` myApplication)
--
-- myApplication :: (`MonadPrinter` m) => m ()
-- myApplication = do
` putTextLn ` " Hello world ! "
-- `flush`
-- @
newtype TerminalT t m a
= TerminalT (ReaderT t m a)
deriving (Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch, MonadMask)
-- | Run a `TerminalT` application on the given terminal.
runTerminalT :: (MonadIO m, MonadMask m, T.Terminal t) => TerminalT t m a -> t -> m a
runTerminalT tma t = runReaderT ma t
where
TerminalT ma = tma
instance MonadTrans (TerminalT t) where
lift = TerminalT . lift
instance (MonadIO m, T.Terminal t) => MonadInput (TerminalT t m) where
awaitWith f = TerminalT do
t <- ask
liftIO $ atomically $ f (T.termInterrupt t) (T.termEvent t)
setBracketedPasteMode b =
command (T.SetBracketedPasteMode b)
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadPrinter (TerminalT t m) where
putLn =
command T.PutLn
putChar c =
command (T.PutText $ Text.singleton c)
putString cs =
forM_ cs (command . T.PutText . Text.singleton)
putText t =
command (T.PutText t)
flush = TerminalT do
t <- ask
liftIO $ T.termFlush t
getLineWidth = TerminalT do
t <- ask
liftIO (width <$> T.termGetWindowSize t)
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadMarkupPrinter (TerminalT t m) where
data Attribute (TerminalT t m) = AttributeT T.Attribute deriving (Eq, Ord, Show)
setAttribute (AttributeT a) = command (T.SetAttribute a)
resetAttribute (AttributeT a) = command (T.ResetAttribute a)
resetAttributes = command T.ResetAttributes
resetsAttribute (AttributeT T.Bold {}) (AttributeT T.Bold {}) = True
resetsAttribute (AttributeT T.Italic {}) (AttributeT T.Italic {}) = True
resetsAttribute (AttributeT T.Underlined {}) (AttributeT T.Underlined {}) = True
resetsAttribute (AttributeT T.Inverted {}) (AttributeT T.Inverted {}) = True
resetsAttribute (AttributeT T.Foreground {}) (AttributeT T.Foreground {}) = True
resetsAttribute (AttributeT T.Foreground {}) (AttributeT T.Background {}) = True
resetsAttribute _ _ = False
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadFormattingPrinter (TerminalT t m) where
bold = AttributeT T.Bold
italic = AttributeT T.Italic
underlined = AttributeT T.Underlined
inverted = AttributeT T.Inverted
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadColorPrinter (TerminalT t m) where
data Color (TerminalT t m) = ColorT T.Color deriving (Eq, Ord, Show)
black = ColorT T.Black
red = ColorT T.Red
green = ColorT T.Green
yellow = ColorT T.Yellow
blue = ColorT T.Blue
magenta = ColorT T.Magenta
cyan = ColorT T.Cyan
white = ColorT T.White
bright (ColorT T.Black ) = ColorT T.BrightBlack
bright (ColorT T.Red ) = ColorT T.BrightRed
bright (ColorT T.Green ) = ColorT T.BrightGreen
bright (ColorT T.Yellow ) = ColorT T.BrightYellow
bright (ColorT T.Blue ) = ColorT T.BrightBlue
bright (ColorT T.Magenta) = ColorT T.BrightMagenta
bright (ColorT T.Cyan ) = ColorT T.BrightCyan
bright (ColorT T.White ) = ColorT T.BrightWhite
bright (ColorT c ) = ColorT c
foreground (ColorT c) = AttributeT (T.Foreground c)
background (ColorT c) = AttributeT (T.Background c)
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadScreen (TerminalT t m) where
getWindowSize =
TerminalT (liftIO . T.termGetWindowSize =<< ask)
moveCursorUp i
| i > 0 = command (T.MoveCursorUp i)
| i < 0 = moveCursorDown i
| otherwise = pure ()
moveCursorDown i
| i > 0 = command (T.MoveCursorDown i)
| i < 0 = moveCursorUp i
| otherwise = pure ()
moveCursorForward i
| i > 0 = command (T.MoveCursorForward i)
| i < 0 = moveCursorBackward i
| otherwise = pure ()
moveCursorBackward i
| i > 0 = command (T.MoveCursorBackward i)
| i < 0 = moveCursorForward i
| otherwise = pure ()
getCursorPosition =
TerminalT (liftIO . T.termGetCursorPosition =<< ask)
setCursorPosition pos =
command (T.SetCursorPosition pos)
setCursorRow i =
command (T.SetCursorRow i)
setCursorColumn i =
command (T.SetCursorColumn i)
saveCursor =
command T.SaveCursor
restoreCursor =
command T.RestoreCursor
insertChars i = do
command (T.InsertChars i)
deleteChars i = do
command (T.DeleteChars i)
eraseChars i = do
command (T.EraseChars i)
insertLines i = do
command (T.InsertLines i)
deleteLines i = do
command (T.DeleteLines i)
eraseInLine =
command . T.EraseInLine
eraseInDisplay =
command . T.EraseInDisplay
showCursor =
command T.ShowCursor
hideCursor =
command T.HideCursor
setAutoWrap x =
command (T.SetAutoWrap x)
setAlternateScreenBuffer x =
command (T.SetAlternateScreenBuffer x)
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadTerminal (TerminalT t m) where
command :: (MonadIO m, T.Terminal t) => T.Command -> TerminalT t m ()
command c = TerminalT do
t <- ask
liftIO $ T.termCommand t c
| null | https://raw.githubusercontent.com/lpeterse/haskell-terminal/994602af65e7f038bc387139ec961248760fd6e6/src/System/Terminal/TerminalT.hs | haskell | | This monad transformer represents terminal applications.
It implements all classes in this module and should serve as a good
foundation for most use cases.
Note that it is not necessary nor recommended to have this type in
every signature. Keep your application abstract and mention `TerminalT`
only once at the top level.
Example:
@
main :: IO ()
main = `withTerminal` (`runTerminalT` myApplication)
myApplication :: (`MonadPrinter` m) => m ()
myApplication = do
`flush`
@
| Run a `TerminalT` application on the given terminal. | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module System.Terminal.TerminalT
( TerminalT ()
, runTerminalT
)
where
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.STM
import Control.Monad.Trans.Class
import Control.Monad.Trans.Reader
import Data.Foldable (forM_)
import qualified Data.Text as Text
import Prelude hiding (putChar)
import System.Terminal.MonadInput
import System.Terminal.MonadPrinter
import System.Terminal.MonadScreen
import System.Terminal.MonadTerminal
import qualified System.Terminal.Terminal as T
` putTextLn ` " Hello world ! "
newtype TerminalT t m a
= TerminalT (ReaderT t m a)
deriving (Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch, MonadMask)
runTerminalT :: (MonadIO m, MonadMask m, T.Terminal t) => TerminalT t m a -> t -> m a
runTerminalT tma t = runReaderT ma t
where
TerminalT ma = tma
instance MonadTrans (TerminalT t) where
lift = TerminalT . lift
instance (MonadIO m, T.Terminal t) => MonadInput (TerminalT t m) where
awaitWith f = TerminalT do
t <- ask
liftIO $ atomically $ f (T.termInterrupt t) (T.termEvent t)
setBracketedPasteMode b =
command (T.SetBracketedPasteMode b)
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadPrinter (TerminalT t m) where
putLn =
command T.PutLn
putChar c =
command (T.PutText $ Text.singleton c)
putString cs =
forM_ cs (command . T.PutText . Text.singleton)
putText t =
command (T.PutText t)
flush = TerminalT do
t <- ask
liftIO $ T.termFlush t
getLineWidth = TerminalT do
t <- ask
liftIO (width <$> T.termGetWindowSize t)
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadMarkupPrinter (TerminalT t m) where
data Attribute (TerminalT t m) = AttributeT T.Attribute deriving (Eq, Ord, Show)
setAttribute (AttributeT a) = command (T.SetAttribute a)
resetAttribute (AttributeT a) = command (T.ResetAttribute a)
resetAttributes = command T.ResetAttributes
resetsAttribute (AttributeT T.Bold {}) (AttributeT T.Bold {}) = True
resetsAttribute (AttributeT T.Italic {}) (AttributeT T.Italic {}) = True
resetsAttribute (AttributeT T.Underlined {}) (AttributeT T.Underlined {}) = True
resetsAttribute (AttributeT T.Inverted {}) (AttributeT T.Inverted {}) = True
resetsAttribute (AttributeT T.Foreground {}) (AttributeT T.Foreground {}) = True
resetsAttribute (AttributeT T.Foreground {}) (AttributeT T.Background {}) = True
resetsAttribute _ _ = False
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadFormattingPrinter (TerminalT t m) where
bold = AttributeT T.Bold
italic = AttributeT T.Italic
underlined = AttributeT T.Underlined
inverted = AttributeT T.Inverted
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadColorPrinter (TerminalT t m) where
data Color (TerminalT t m) = ColorT T.Color deriving (Eq, Ord, Show)
black = ColorT T.Black
red = ColorT T.Red
green = ColorT T.Green
yellow = ColorT T.Yellow
blue = ColorT T.Blue
magenta = ColorT T.Magenta
cyan = ColorT T.Cyan
white = ColorT T.White
bright (ColorT T.Black ) = ColorT T.BrightBlack
bright (ColorT T.Red ) = ColorT T.BrightRed
bright (ColorT T.Green ) = ColorT T.BrightGreen
bright (ColorT T.Yellow ) = ColorT T.BrightYellow
bright (ColorT T.Blue ) = ColorT T.BrightBlue
bright (ColorT T.Magenta) = ColorT T.BrightMagenta
bright (ColorT T.Cyan ) = ColorT T.BrightCyan
bright (ColorT T.White ) = ColorT T.BrightWhite
bright (ColorT c ) = ColorT c
foreground (ColorT c) = AttributeT (T.Foreground c)
background (ColorT c) = AttributeT (T.Background c)
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadScreen (TerminalT t m) where
getWindowSize =
TerminalT (liftIO . T.termGetWindowSize =<< ask)
moveCursorUp i
| i > 0 = command (T.MoveCursorUp i)
| i < 0 = moveCursorDown i
| otherwise = pure ()
moveCursorDown i
| i > 0 = command (T.MoveCursorDown i)
| i < 0 = moveCursorUp i
| otherwise = pure ()
moveCursorForward i
| i > 0 = command (T.MoveCursorForward i)
| i < 0 = moveCursorBackward i
| otherwise = pure ()
moveCursorBackward i
| i > 0 = command (T.MoveCursorBackward i)
| i < 0 = moveCursorForward i
| otherwise = pure ()
getCursorPosition =
TerminalT (liftIO . T.termGetCursorPosition =<< ask)
setCursorPosition pos =
command (T.SetCursorPosition pos)
setCursorRow i =
command (T.SetCursorRow i)
setCursorColumn i =
command (T.SetCursorColumn i)
saveCursor =
command T.SaveCursor
restoreCursor =
command T.RestoreCursor
insertChars i = do
command (T.InsertChars i)
deleteChars i = do
command (T.DeleteChars i)
eraseChars i = do
command (T.EraseChars i)
insertLines i = do
command (T.InsertLines i)
deleteLines i = do
command (T.DeleteLines i)
eraseInLine =
command . T.EraseInLine
eraseInDisplay =
command . T.EraseInDisplay
showCursor =
command T.ShowCursor
hideCursor =
command T.HideCursor
setAutoWrap x =
command (T.SetAutoWrap x)
setAlternateScreenBuffer x =
command (T.SetAlternateScreenBuffer x)
instance (MonadIO m, MonadThrow m, T.Terminal t) => MonadTerminal (TerminalT t m) where
command :: (MonadIO m, T.Terminal t) => T.Command -> TerminalT t m ()
command c = TerminalT do
t <- ask
liftIO $ T.termCommand t c
|
bde3fabb3e5597c45ef070a2f759dd594addc84f57e29743bc12741213a5bcfa | karamellpelle/grid | Helpers.hs | grid is a game written in Haskell
Copyright ( C ) 2018
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
You should have received a copy of the GNU General Public License
-- along with grid. If not, see </>.
--
module Game.LevelPuzzle.Helpers
(
levelpuzzleCameraCmdsIsComplete,
levelpuzzleSetCameraCmds,
levelpuzzlePushCameraCmds,
levelpuzzleModifyContent,
levelpuzzleModifyGrid,
levelpuzzleModifyCamera,
levelpuzzleModifyPath,
levelpuzzleCamera,
levelpuzzleGrid,
levelpuzzlePath,
levelpuzzleClearEvents,
levelpuzzleIsSpecial,
levelpuzzleLevelPuzzleTag,
levelpuzzleLevelIx,
levelpuzzleBeginLevel,
contentIsEmpty,
contentModifyGrid,
) where
import MyPrelude
import File
import File.Binary
import Game
import Game.Grid.Helpers
import Game.LevelPuzzle.LevelPuzzleWorld
import Game.LevelPuzzle.File
--------------------------------------------------------------------------------
--
levelpuzzleCameraCmdsIsComplete :: LevelPuzzleWorld -> Bool
levelpuzzleCameraCmdsIsComplete =
gridCameraCmdsIsComplete . levelpuzzleGrid
levelpuzzleSetCameraCmds :: LevelPuzzleWorld -> [CameraCommand] -> LevelPuzzleWorld
levelpuzzleSetCameraCmds lvl cmds =
levelpuzzleModifyGrid lvl $ \grid -> gridSetCameraCmds grid cmds
levelpuzzlePushCameraCmds :: LevelPuzzleWorld -> [CameraCommand] -> LevelPuzzleWorld
levelpuzzlePushCameraCmds lvl cmds =
levelpuzzleModifyGrid lvl $ \grid -> gridPushCameraCmds grid cmds
levelpuzzleClearEvents :: LevelPuzzleWorld -> LevelPuzzleWorld
levelpuzzleClearEvents lvl =
lvl { levelpuzzleEvents = [] }
levelpuzzleGrid :: LevelPuzzleWorld -> GridWorld
levelpuzzleGrid =
contentGrid . levelpuzzleContent
levelpuzzlePath :: LevelPuzzleWorld -> Path
levelpuzzlePath =
gridPath . levelpuzzleGrid
levelpuzzleCamera :: LevelPuzzleWorld -> Camera
levelpuzzleCamera =
gridCamera . levelpuzzleGrid
levelpuzzleModifyContent :: LevelPuzzleWorld -> (Content -> Content) -> LevelPuzzleWorld
levelpuzzleModifyContent lvl f =
lvl { levelpuzzleContent = f (levelpuzzleContent lvl) }
levelpuzzleModifyGrid :: LevelPuzzleWorld -> (GridWorld -> GridWorld) -> LevelPuzzleWorld
levelpuzzleModifyGrid lvl f =
levelpuzzleModifyContent lvl $ \cnt -> contentModifyGrid cnt f
levelpuzzleModifyCamera :: LevelPuzzleWorld -> (Camera -> Camera) -> LevelPuzzleWorld
levelpuzzleModifyCamera lvl f =
levelpuzzleModifyGrid lvl $ \grid -> gridModifyCamera grid f
levelpuzzleModifyPath :: LevelPuzzleWorld -> (Path -> Path) -> LevelPuzzleWorld
levelpuzzleModifyPath lvl f =
levelpuzzleModifyGrid lvl $ \grid -> gridModifyPath grid f
--------------------------------------------------------------------------------
-- Level
levelpuzzleLevelPuzzleTag :: LevelPuzzleWorld -> Bool
levelpuzzleLevelPuzzleTag =
levelPuzzleTag . levelpuzzleLevel
--------------------------------------------------------------------------------
--
| there is a special LevelPuzzleWorld
levelpuzzleIsSpecial :: LevelPuzzleWorld -> Bool
levelpuzzleIsSpecial lvl =
takeFileName (levelpuzzleFile lvl) == valueFileNameSpecialLevelPuzzleWorld
--takeFileName (levelpuzzleFile lvl) == ""
--------------------------------------------------------------------------------
-- begin
levelpuzzleBeginLevel :: LevelPuzzleWorld -> MEnv' LevelPuzzleWorld
levelpuzzleBeginLevel lvl = do
cnt' <- contentBegin $ levelpuzzleContent lvl
return lvl
{
levelpuzzleContent = cnt',
levelpuzzleEvents = [],
levelpuzzleSegmentsCount = levelSegments (levelpuzzleLevel lvl)
}
--------------------------------------------------------------------------------
-- Content
contentIsEmpty :: Content -> Bool
contentIsEmpty cnt =
gridIsEmpty $ contentGrid cnt
contentModifyGrid :: Content -> (GridWorld -> GridWorld) -> Content
contentModifyGrid cnt f =
cnt { contentGrid = f (contentGrid cnt) }
contentBegin :: Content -> MEnv' Content
contentBegin cnt = do
roomsBegin (contentRoomsSize cnt) (contentRooms cnt)
grid' <- gridBegin $ contentGrid cnt
return cnt
{
contentGrid = grid',
contentRoom = 0,
contentEatPathBegin = 0,
contentEatRoom = 0,
contentEatTick = 0.0
}
where
gridBegin grid = do
path' <- pathClear $ gridPath grid
return $ gridModifyCamera (grid { gridPath = path' }) $ \cam ->
cameraSetPath cam path'
roomsBegin size rooms = io $
roomarrayUpdateIO size rooms $ \room -> do
dotplainarrayUpdate (roomDotPlainSize room) (roomDotPlain room) $ \dot ->
dot { dotplainCount = dotplainSize dot }
dotbonusarrayUpdate (roomDotBonusSize room) (roomDotBonus room) $ \dot ->
dot { dotbonusCount = dotbonusSize dot }
dottelearrayUpdate (roomDotTeleSize room) (roomDotTele room) $ \dot ->
dot { dotteleCount = dotteleSize dot }
dottelearrayUpdate (roomDotTeleSize room) (roomDotTele room) $ \dot ->
dot { dotteleCount = dotteleSize dot }
return room { roomPathBeginEnd = [] }
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/source/Game/LevelPuzzle/Helpers.hs | haskell |
This file is part of grid.
grid is free software: you can redistribute it and/or modify
(at your option) any later version.
grid is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with grid. If not, see </>.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Level
------------------------------------------------------------------------------
takeFileName (levelpuzzleFile lvl) == ""
------------------------------------------------------------------------------
begin
------------------------------------------------------------------------------
Content | grid is a game written in Haskell
Copyright ( C ) 2018
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
module Game.LevelPuzzle.Helpers
(
levelpuzzleCameraCmdsIsComplete,
levelpuzzleSetCameraCmds,
levelpuzzlePushCameraCmds,
levelpuzzleModifyContent,
levelpuzzleModifyGrid,
levelpuzzleModifyCamera,
levelpuzzleModifyPath,
levelpuzzleCamera,
levelpuzzleGrid,
levelpuzzlePath,
levelpuzzleClearEvents,
levelpuzzleIsSpecial,
levelpuzzleLevelPuzzleTag,
levelpuzzleLevelIx,
levelpuzzleBeginLevel,
contentIsEmpty,
contentModifyGrid,
) where
import MyPrelude
import File
import File.Binary
import Game
import Game.Grid.Helpers
import Game.LevelPuzzle.LevelPuzzleWorld
import Game.LevelPuzzle.File
levelpuzzleCameraCmdsIsComplete :: LevelPuzzleWorld -> Bool
levelpuzzleCameraCmdsIsComplete =
gridCameraCmdsIsComplete . levelpuzzleGrid
levelpuzzleSetCameraCmds :: LevelPuzzleWorld -> [CameraCommand] -> LevelPuzzleWorld
levelpuzzleSetCameraCmds lvl cmds =
levelpuzzleModifyGrid lvl $ \grid -> gridSetCameraCmds grid cmds
levelpuzzlePushCameraCmds :: LevelPuzzleWorld -> [CameraCommand] -> LevelPuzzleWorld
levelpuzzlePushCameraCmds lvl cmds =
levelpuzzleModifyGrid lvl $ \grid -> gridPushCameraCmds grid cmds
levelpuzzleClearEvents :: LevelPuzzleWorld -> LevelPuzzleWorld
levelpuzzleClearEvents lvl =
lvl { levelpuzzleEvents = [] }
levelpuzzleGrid :: LevelPuzzleWorld -> GridWorld
levelpuzzleGrid =
contentGrid . levelpuzzleContent
levelpuzzlePath :: LevelPuzzleWorld -> Path
levelpuzzlePath =
gridPath . levelpuzzleGrid
levelpuzzleCamera :: LevelPuzzleWorld -> Camera
levelpuzzleCamera =
gridCamera . levelpuzzleGrid
levelpuzzleModifyContent :: LevelPuzzleWorld -> (Content -> Content) -> LevelPuzzleWorld
levelpuzzleModifyContent lvl f =
lvl { levelpuzzleContent = f (levelpuzzleContent lvl) }
levelpuzzleModifyGrid :: LevelPuzzleWorld -> (GridWorld -> GridWorld) -> LevelPuzzleWorld
levelpuzzleModifyGrid lvl f =
levelpuzzleModifyContent lvl $ \cnt -> contentModifyGrid cnt f
levelpuzzleModifyCamera :: LevelPuzzleWorld -> (Camera -> Camera) -> LevelPuzzleWorld
levelpuzzleModifyCamera lvl f =
levelpuzzleModifyGrid lvl $ \grid -> gridModifyCamera grid f
levelpuzzleModifyPath :: LevelPuzzleWorld -> (Path -> Path) -> LevelPuzzleWorld
levelpuzzleModifyPath lvl f =
levelpuzzleModifyGrid lvl $ \grid -> gridModifyPath grid f
levelpuzzleLevelPuzzleTag :: LevelPuzzleWorld -> Bool
levelpuzzleLevelPuzzleTag =
levelPuzzleTag . levelpuzzleLevel
| there is a special LevelPuzzleWorld
levelpuzzleIsSpecial :: LevelPuzzleWorld -> Bool
levelpuzzleIsSpecial lvl =
takeFileName (levelpuzzleFile lvl) == valueFileNameSpecialLevelPuzzleWorld
levelpuzzleBeginLevel :: LevelPuzzleWorld -> MEnv' LevelPuzzleWorld
levelpuzzleBeginLevel lvl = do
cnt' <- contentBegin $ levelpuzzleContent lvl
return lvl
{
levelpuzzleContent = cnt',
levelpuzzleEvents = [],
levelpuzzleSegmentsCount = levelSegments (levelpuzzleLevel lvl)
}
contentIsEmpty :: Content -> Bool
contentIsEmpty cnt =
gridIsEmpty $ contentGrid cnt
contentModifyGrid :: Content -> (GridWorld -> GridWorld) -> Content
contentModifyGrid cnt f =
cnt { contentGrid = f (contentGrid cnt) }
contentBegin :: Content -> MEnv' Content
contentBegin cnt = do
roomsBegin (contentRoomsSize cnt) (contentRooms cnt)
grid' <- gridBegin $ contentGrid cnt
return cnt
{
contentGrid = grid',
contentRoom = 0,
contentEatPathBegin = 0,
contentEatRoom = 0,
contentEatTick = 0.0
}
where
gridBegin grid = do
path' <- pathClear $ gridPath grid
return $ gridModifyCamera (grid { gridPath = path' }) $ \cam ->
cameraSetPath cam path'
roomsBegin size rooms = io $
roomarrayUpdateIO size rooms $ \room -> do
dotplainarrayUpdate (roomDotPlainSize room) (roomDotPlain room) $ \dot ->
dot { dotplainCount = dotplainSize dot }
dotbonusarrayUpdate (roomDotBonusSize room) (roomDotBonus room) $ \dot ->
dot { dotbonusCount = dotbonusSize dot }
dottelearrayUpdate (roomDotTeleSize room) (roomDotTele room) $ \dot ->
dot { dotteleCount = dotteleSize dot }
dottelearrayUpdate (roomDotTeleSize room) (roomDotTele room) $ \dot ->
dot { dotteleCount = dotteleSize dot }
return room { roomPathBeginEnd = [] }
|
8978d31ac7b7b8af62ee284708a801ab1a0fb173d80392ce7f567525ef39de79 | puppetlabs/puppetdb | overrideable_generators_test.clj | (ns puppetlabs.puppetdb.generative.overrideable-generators-test
(:require [clojure.test :refer :all]
[clojure.test.check.clojure-test :as tc]
[clojure.test.check.properties :as prop]
[puppetlabs.puppetdb.generative.overridable-generators :as ogen]))
(ogen/defgen :test/a ogen/boolean)
(ogen/defgen :test/b ogen/uuid)
(ogen/defgen :test/map (ogen/keys :test/a :test/b))
(tc/defspec keys-generator 100
(prop/for-all [m (ogen/convert :test/map)]
(is (= [:a :b] (keys m)))))
(tc/defspec overrides 100
(prop/for-all [m (->> :test/map
(ogen/override {:test/a (ogen/return true)})
ogen/convert)]
(is (= [:a :b] (clojure.core/keys m)))
(is (= true (:a m)))))
(tc/defspec override-presedence-is-outside-in 100
(prop/for-all [m (->> :test/map
(ogen/override {:test/a (ogen/return true)})
(ogen/override {:test/a (ogen/return false)})
ogen/convert)]
(is (= [:a :b] (clojure.core/keys m)))
(is (= false (:a m)))))
| null | https://raw.githubusercontent.com/puppetlabs/puppetdb/b3d6d10555561657150fa70b6d1e609fba9c0eda/test/puppetlabs/puppetdb/generative/overrideable_generators_test.clj | clojure | (ns puppetlabs.puppetdb.generative.overrideable-generators-test
(:require [clojure.test :refer :all]
[clojure.test.check.clojure-test :as tc]
[clojure.test.check.properties :as prop]
[puppetlabs.puppetdb.generative.overridable-generators :as ogen]))
(ogen/defgen :test/a ogen/boolean)
(ogen/defgen :test/b ogen/uuid)
(ogen/defgen :test/map (ogen/keys :test/a :test/b))
(tc/defspec keys-generator 100
(prop/for-all [m (ogen/convert :test/map)]
(is (= [:a :b] (keys m)))))
(tc/defspec overrides 100
(prop/for-all [m (->> :test/map
(ogen/override {:test/a (ogen/return true)})
ogen/convert)]
(is (= [:a :b] (clojure.core/keys m)))
(is (= true (:a m)))))
(tc/defspec override-presedence-is-outside-in 100
(prop/for-all [m (->> :test/map
(ogen/override {:test/a (ogen/return true)})
(ogen/override {:test/a (ogen/return false)})
ogen/convert)]
(is (= [:a :b] (clojure.core/keys m)))
(is (= false (:a m)))))
| |
7800e6b74d04fa1968823a14d461e680803317c4a9889f279ffda37f96188fa9 | kaizhang/SciFlow | Async.hs | {-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
| Asynchronous arrows over monads with MonadBaseControl IO , using
-- lifted-async.
module Control.Arrow.Async where
import Control.Arrow
import Control.Category
import Control.Concurrent.Async.Lifted
import Control.Monad.Trans.Control (MonadBaseControl)
import Prelude hiding (id, (.))
newtype AsyncA m a b = AsyncA { runAsyncA :: a -> m b }
instance Monad m => Category (AsyncA m) where
id = AsyncA return
(AsyncA f) . (AsyncA g) = AsyncA (\b -> g b >>= f)
| @since 2.01
instance MonadBaseControl IO m => Arrow (AsyncA m) where
arr f = AsyncA (return . f)
first (AsyncA f) = AsyncA (\ ~(b,d) -> f b >>= \c -> return (c,d))
second (AsyncA f) = AsyncA (\ ~(d,b) -> f b >>= \c -> return (d,c))
(AsyncA f) *** (AsyncA g) = AsyncA $ \ ~(a,b) ->
withAsync (f a) $ \c ->
withAsync (g b) $ \d ->
waitBoth c d
instance MonadBaseControl IO m => ArrowChoice (AsyncA m) where
left f = f +++ arr id
right f = arr id +++ f
f +++ g = (f >>> arr Left) ||| (g >>> arr Right)
AsyncA f ||| AsyncA g = AsyncA (either f g) | null | https://raw.githubusercontent.com/kaizhang/SciFlow/c9d85008e9db598d2addc8fe999e1abad9147e1c/SciFlow/src/Control/Arrow/Async.hs | haskell | # LANGUAGE FlexibleContexts #
lifted-async. | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
| Asynchronous arrows over monads with MonadBaseControl IO , using
module Control.Arrow.Async where
import Control.Arrow
import Control.Category
import Control.Concurrent.Async.Lifted
import Control.Monad.Trans.Control (MonadBaseControl)
import Prelude hiding (id, (.))
newtype AsyncA m a b = AsyncA { runAsyncA :: a -> m b }
instance Monad m => Category (AsyncA m) where
id = AsyncA return
(AsyncA f) . (AsyncA g) = AsyncA (\b -> g b >>= f)
| @since 2.01
instance MonadBaseControl IO m => Arrow (AsyncA m) where
arr f = AsyncA (return . f)
first (AsyncA f) = AsyncA (\ ~(b,d) -> f b >>= \c -> return (c,d))
second (AsyncA f) = AsyncA (\ ~(d,b) -> f b >>= \c -> return (d,c))
(AsyncA f) *** (AsyncA g) = AsyncA $ \ ~(a,b) ->
withAsync (f a) $ \c ->
withAsync (g b) $ \d ->
waitBoth c d
instance MonadBaseControl IO m => ArrowChoice (AsyncA m) where
left f = f +++ arr id
right f = arr id +++ f
f +++ g = (f >>> arr Left) ||| (g >>> arr Right)
AsyncA f ||| AsyncA g = AsyncA (either f g) |
c7b8628188b731b85da83ad6a3069ea3d5d02e9e159cb506590089ce2105456b | noinia/hgeometry | Sides.hs | # LANGUAGE TemplateHaskell #
--------------------------------------------------------------------------------
-- |
-- Module : Geometry.Box.Sides
Copyright : ( C )
-- License : see the LICENSE file
Maintainer :
--------------------------------------------------------------------------------
module Geometry.Box.Sides
( Sides(Sides), north, east, south, west
, topSide, bottomSide, leftSide, rightSide
, sides, sides'
, sideDirections
) where
import Geometry.Directions
import Geometry.Box.Internal
import Geometry.Box.Corners
import Geometry.LineSegment.Internal
import Data.Functor.Apply
import Data.Semigroup.Foldable.Class
import Data.Semigroup.Traversable.Class
import GHC.Generics (Generic)
import Control.Lens(makeLenses, Ixed(..), Index, IxValue)
--------------------------------------------------------------------------------
| The four sides of a rectangle
data Sides a = Sides { _north :: !a
, _east :: !a
, _south :: !a
, _west :: !a
} deriving (Show,Read,Eq,Generic,Ord,Foldable,Functor,Traversable)
makeLenses ''Sides
instance Applicative Sides where
pure x = Sides x x x x
(Sides f g h i) <*> (Sides a b c d) = Sides (f a) (g b) (h c) (i d)
instance Foldable1 Sides
instance Traversable1 Sides where
traverse1 f (Sides a b c d) = Sides <$> f a <.> f b <.> f c <.> f d
instance Semigroup a => Semigroup (Sides a) where
s <> s' = (<>) <$> s <*> s'
instance Monoid a => Monoid (Sides a) where
mempty = pure mempty
type instance Index (Sides a) = CardinalDirection
type instance IxValue (Sides a) = a
instance Ixed (Sides a) where
ix = \case
North -> north
East -> east
South -> south
West -> west
-- | Constructs a Sides value that indicates the appropriate
-- direction.
sideDirections :: Sides CardinalDirection
sideDirections = Sides North East South West
--------------------------------------------------------------------------------
-- | The top side of the box, from left to right.
topSide :: Num r => Rectangle p r -> LineSegment 2 p r
topSide = (\(Corners l r _ _) -> ClosedLineSegment l r) . corners
-- | Oriented from *left to right*
bottomSide :: Num r => Rectangle p r -> LineSegment 2 p r
bottomSide = (\(Corners _ _ r l) -> ClosedLineSegment l r) . corners
-- | Left side of the box, from bottom to top
leftSide :: Num r => Rectangle p r -> LineSegment 2 p r
leftSide = (\(Corners t _ _ b) -> ClosedLineSegment b t) . corners
-- | The right side, oriented from *bottom* to top
rightSide :: Num r => Rectangle p r -> LineSegment 2 p r
rightSide = (\(Corners _ t b _) -> ClosedLineSegment b t) . corners
-- | The sides of the rectangle, in order (Top, Right, Bottom, Left). The sides
-- themselves are also oriented in clockwise order. If, you want them in the
-- same order as the functions `topSide`, `bottomSide`, `leftSide`, and
-- `rightSide`, use `sides'` instead.
sides :: Num r => Rectangle p r -> Sides (LineSegment 2 p r)
sides r = let Corners nw ne se sw = corners r
in Sides (ClosedLineSegment nw ne) (ClosedLineSegment ne se)
(ClosedLineSegment se sw) (ClosedLineSegment sw nw)
-- | The sides of the rectangle. The order of the segments is (Top, Right,
-- Bottom, Left). Note that the segments themselves, are oriented as described
-- by the functions topSide, bottomSide, leftSide, rightSide (basically: from
-- left to right, and from bottom to top). If you want the segments oriented
-- along the boundary of the rectangle, use the `sides` function instead.
sides' :: Num r => Rectangle p r -> Sides (LineSegment 2 p r)
sides' r = Sides (topSide r) (rightSide r) (bottomSide r) (leftSide r)
| null | https://raw.githubusercontent.com/noinia/hgeometry/1205c406f3e7f13a5abee8939ae8b40d2ee2063d/hgeometry/src/Geometry/Box/Sides.hs | haskell | ------------------------------------------------------------------------------
|
Module : Geometry.Box.Sides
License : see the LICENSE file
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Constructs a Sides value that indicates the appropriate
direction.
------------------------------------------------------------------------------
| The top side of the box, from left to right.
| Oriented from *left to right*
| Left side of the box, from bottom to top
| The right side, oriented from *bottom* to top
| The sides of the rectangle, in order (Top, Right, Bottom, Left). The sides
themselves are also oriented in clockwise order. If, you want them in the
same order as the functions `topSide`, `bottomSide`, `leftSide`, and
`rightSide`, use `sides'` instead.
| The sides of the rectangle. The order of the segments is (Top, Right,
Bottom, Left). Note that the segments themselves, are oriented as described
by the functions topSide, bottomSide, leftSide, rightSide (basically: from
left to right, and from bottom to top). If you want the segments oriented
along the boundary of the rectangle, use the `sides` function instead. | # LANGUAGE TemplateHaskell #
Copyright : ( C )
Maintainer :
module Geometry.Box.Sides
( Sides(Sides), north, east, south, west
, topSide, bottomSide, leftSide, rightSide
, sides, sides'
, sideDirections
) where
import Geometry.Directions
import Geometry.Box.Internal
import Geometry.Box.Corners
import Geometry.LineSegment.Internal
import Data.Functor.Apply
import Data.Semigroup.Foldable.Class
import Data.Semigroup.Traversable.Class
import GHC.Generics (Generic)
import Control.Lens(makeLenses, Ixed(..), Index, IxValue)
| The four sides of a rectangle
data Sides a = Sides { _north :: !a
, _east :: !a
, _south :: !a
, _west :: !a
} deriving (Show,Read,Eq,Generic,Ord,Foldable,Functor,Traversable)
makeLenses ''Sides
instance Applicative Sides where
pure x = Sides x x x x
(Sides f g h i) <*> (Sides a b c d) = Sides (f a) (g b) (h c) (i d)
instance Foldable1 Sides
instance Traversable1 Sides where
traverse1 f (Sides a b c d) = Sides <$> f a <.> f b <.> f c <.> f d
instance Semigroup a => Semigroup (Sides a) where
s <> s' = (<>) <$> s <*> s'
instance Monoid a => Monoid (Sides a) where
mempty = pure mempty
type instance Index (Sides a) = CardinalDirection
type instance IxValue (Sides a) = a
instance Ixed (Sides a) where
ix = \case
North -> north
East -> east
South -> south
West -> west
sideDirections :: Sides CardinalDirection
sideDirections = Sides North East South West
topSide :: Num r => Rectangle p r -> LineSegment 2 p r
topSide = (\(Corners l r _ _) -> ClosedLineSegment l r) . corners
bottomSide :: Num r => Rectangle p r -> LineSegment 2 p r
bottomSide = (\(Corners _ _ r l) -> ClosedLineSegment l r) . corners
leftSide :: Num r => Rectangle p r -> LineSegment 2 p r
leftSide = (\(Corners t _ _ b) -> ClosedLineSegment b t) . corners
rightSide :: Num r => Rectangle p r -> LineSegment 2 p r
rightSide = (\(Corners _ t b _) -> ClosedLineSegment b t) . corners
sides :: Num r => Rectangle p r -> Sides (LineSegment 2 p r)
sides r = let Corners nw ne se sw = corners r
in Sides (ClosedLineSegment nw ne) (ClosedLineSegment ne se)
(ClosedLineSegment se sw) (ClosedLineSegment sw nw)
sides' :: Num r => Rectangle p r -> Sides (LineSegment 2 p r)
sides' r = Sides (topSide r) (rightSide r) (bottomSide r) (leftSide r)
|
bd1af46d32e692e0680ba8a0ec6d4b1e5c65837cafbd7328b722d5ee80449d38 | fukamachi/clozure-cl | arm-hash.lisp | -*- Mode : Lisp ; Package : CCL -*-
;;;
Copyright ( C ) 2010 Clozure Associates
This file is part of Clozure CL .
;;;
Clozure CL is licensed under the terms of the Lisp Lesser GNU Public
License , known as the LLGPL and distributed with Clozure CL as the
;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL,
which is distributed with Clozure CL as the file " LGPL " . Where these
;;; conflict, the preamble takes precedence.
;;;
;;; Clozure CL is referenced in the preamble as the "LIBRARY."
;;;
;;; The LLGPL is also available online at
;;;
level-0;ARM;arm - hash.lisp
(in-package "CCL")
(eval-when (:compile-toplevel :execute)
(require "HASHENV" "ccl:xdump;hashenv"))
This should stay in LAP so that it 's fast
;;; Equivalent to cl:mod when both args are positive fixnums
(defarmlapfunction fast-mod ((number arg_y) (divisor arg_z))
(build-lisp-frame imm0)
(mov imm0 (:lsr number (:$ arm::fixnumshift)))
(mov imm1 (:lsr divisor (:$ arm::fixnumshift)))
(sploadlr .SPudiv32)
(blx lr)
(box-fixnum arg_z imm1)
(return-lisp-frame imm0))
(defarmlapfunction fast-mod-3 ((number arg_x) (divisor arg_y) (recip arg_z))
(mov imm0 (:lsr number (:$ arm::fixnumshift)))
(smull imm2 imm1 imm0 recip)
(mul imm0 imm1 divisor)
(sub number number imm0)
(sub number number divisor)
(mov imm0 (:asr number (:$ (1- arm::nbits-in-word))))
(and divisor divisor imm0)
(add arg_z number divisor)
(bx lr))
(defarmlapfunction %dfloat-hash ((key arg_z))
(ldr imm0 (:@ key (:$ arm::double-float.value)))
(ldr imm1 (:@ key (:$ arm::double-float.val-low)))
(add imm0 imm0 imm1)
(box-fixnum arg_z imm0)
(bx lr))
(defarmlapfunction %sfloat-hash ((key arg_z))
(ldr imm0 (:@ key (:$ arm::single-float.value)))
(box-fixnum arg_z imm0)
(bx lr))
(defarmlapfunction %macptr-hash ((key arg_z))
(ldr imm0 (:@ key (:$ arm::macptr.address)))
(add imm0 imm0 (:lsr imm0 (:$ 24)))
(bic arg_z imm0 (:$ arm::fixnummask))
(bx lr))
(defarmlapfunction %bignum-hash ((key arg_z))
(let ((header imm1)
(offset imm2)
(ndigits temp1)
(immhash imm0))
(mov immhash (:$ 0))
(mov offset (:$ arm::misc-data-offset))
(getvheader header key)
(header-length ndigits header)
(let ((next header))
@loop
(subs ndigits ndigits '1)
(ldr next (:@ key offset))
(add offset offset (:$ 4))
(add immhash next (:ror immhash (:$ 19)))
(bne @loop))
(bic arg_z immhash (:$ arm::fixnummask))
(bx lr)))
(defarmlapfunction %get-fwdnum ()
(ref-global arg_z arm::fwdnum)
(bx lr))
(defarmlapfunction %get-gc-count ()
(ref-global arg_z arm::gc-count)
(bx lr))
;;; Setting a key in a hash-table vector needs to
;;; ensure that the vector header gets memoized as well
(defarmlapfunction %set-hash-table-vector-key ((vector arg_x) (index arg_y) (value arg_z))
(spjump .SPset-hash-key))
(defarmlapfunction %set-hash-table-vector-key-conditional ((offset 0) (vector arg_x) (old arg_y) (new arg_z))
(spjump .SPset-hash-key-conditional))
Strip the tag bits to turn x into a fixnum
(defarmlapfunction strip-tag-to-fixnum ((x arg_z))
(tst x (:$ arm::fixnummask))
(bxeq lr)
(bic arg_z x (:$ arm::fulltagmask))
(mov arg_z (:lsr arg_z (:$ (- arm::ntagbits arm::nfixnumtagbits))))
(bx lr))
;;; end of arm-hash.lisp
| null | https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/level-0/ARM/arm-hash.lisp | lisp | Package : CCL -*-
file "LICENSE". The LLGPL consists of a preamble and the LGPL,
conflict, the preamble takes precedence.
Clozure CL is referenced in the preamble as the "LIBRARY."
The LLGPL is also available online at
ARM;arm - hash.lisp
Equivalent to cl:mod when both args are positive fixnums
Setting a key in a hash-table vector needs to
ensure that the vector header gets memoized as well
end of arm-hash.lisp | Copyright ( C ) 2010 Clozure Associates
This file is part of Clozure CL .
Clozure CL is licensed under the terms of the Lisp Lesser GNU Public
License , known as the LLGPL and distributed with Clozure CL as the
which is distributed with Clozure CL as the file " LGPL " . Where these
(in-package "CCL")
(eval-when (:compile-toplevel :execute)
(require "HASHENV" "ccl:xdump;hashenv"))
This should stay in LAP so that it 's fast
(defarmlapfunction fast-mod ((number arg_y) (divisor arg_z))
(build-lisp-frame imm0)
(mov imm0 (:lsr number (:$ arm::fixnumshift)))
(mov imm1 (:lsr divisor (:$ arm::fixnumshift)))
(sploadlr .SPudiv32)
(blx lr)
(box-fixnum arg_z imm1)
(return-lisp-frame imm0))
(defarmlapfunction fast-mod-3 ((number arg_x) (divisor arg_y) (recip arg_z))
(mov imm0 (:lsr number (:$ arm::fixnumshift)))
(smull imm2 imm1 imm0 recip)
(mul imm0 imm1 divisor)
(sub number number imm0)
(sub number number divisor)
(mov imm0 (:asr number (:$ (1- arm::nbits-in-word))))
(and divisor divisor imm0)
(add arg_z number divisor)
(bx lr))
(defarmlapfunction %dfloat-hash ((key arg_z))
(ldr imm0 (:@ key (:$ arm::double-float.value)))
(ldr imm1 (:@ key (:$ arm::double-float.val-low)))
(add imm0 imm0 imm1)
(box-fixnum arg_z imm0)
(bx lr))
(defarmlapfunction %sfloat-hash ((key arg_z))
(ldr imm0 (:@ key (:$ arm::single-float.value)))
(box-fixnum arg_z imm0)
(bx lr))
(defarmlapfunction %macptr-hash ((key arg_z))
(ldr imm0 (:@ key (:$ arm::macptr.address)))
(add imm0 imm0 (:lsr imm0 (:$ 24)))
(bic arg_z imm0 (:$ arm::fixnummask))
(bx lr))
(defarmlapfunction %bignum-hash ((key arg_z))
(let ((header imm1)
(offset imm2)
(ndigits temp1)
(immhash imm0))
(mov immhash (:$ 0))
(mov offset (:$ arm::misc-data-offset))
(getvheader header key)
(header-length ndigits header)
(let ((next header))
@loop
(subs ndigits ndigits '1)
(ldr next (:@ key offset))
(add offset offset (:$ 4))
(add immhash next (:ror immhash (:$ 19)))
(bne @loop))
(bic arg_z immhash (:$ arm::fixnummask))
(bx lr)))
(defarmlapfunction %get-fwdnum ()
(ref-global arg_z arm::fwdnum)
(bx lr))
(defarmlapfunction %get-gc-count ()
(ref-global arg_z arm::gc-count)
(bx lr))
(defarmlapfunction %set-hash-table-vector-key ((vector arg_x) (index arg_y) (value arg_z))
(spjump .SPset-hash-key))
(defarmlapfunction %set-hash-table-vector-key-conditional ((offset 0) (vector arg_x) (old arg_y) (new arg_z))
(spjump .SPset-hash-key-conditional))
Strip the tag bits to turn x into a fixnum
(defarmlapfunction strip-tag-to-fixnum ((x arg_z))
(tst x (:$ arm::fixnummask))
(bxeq lr)
(bic arg_z x (:$ arm::fulltagmask))
(mov arg_z (:lsr arg_z (:$ (- arm::ntagbits arm::nfixnumtagbits))))
(bx lr))
|
1e674d4bc864a5f84d3a8d4a2fc6238b22933e78183e997ef9eb8eb16c44ec48 | mbj/stratosphere | NotificationTargetItemProperty.hs | module Stratosphere.SSMIncidents.ResponsePlan.NotificationTargetItemProperty (
NotificationTargetItemProperty(..),
mkNotificationTargetItemProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data NotificationTargetItemProperty
= NotificationTargetItemProperty {snsTopicArn :: (Prelude.Maybe (Value Prelude.Text))}
mkNotificationTargetItemProperty :: NotificationTargetItemProperty
mkNotificationTargetItemProperty
= NotificationTargetItemProperty {snsTopicArn = Prelude.Nothing}
instance ToResourceProperties NotificationTargetItemProperty where
toResourceProperties NotificationTargetItemProperty {..}
= ResourceProperties
{awsType = "AWS::SSMIncidents::ResponsePlan.NotificationTargetItem",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "SnsTopicArn" Prelude.<$> snsTopicArn])}
instance JSON.ToJSON NotificationTargetItemProperty where
toJSON NotificationTargetItemProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "SnsTopicArn" Prelude.<$> snsTopicArn]))
instance Property "SnsTopicArn" NotificationTargetItemProperty where
type PropertyType "SnsTopicArn" NotificationTargetItemProperty = Value Prelude.Text
set newValue NotificationTargetItemProperty {}
= NotificationTargetItemProperty
{snsTopicArn = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/ssmincidents/gen/Stratosphere/SSMIncidents/ResponsePlan/NotificationTargetItemProperty.hs | haskell | module Stratosphere.SSMIncidents.ResponsePlan.NotificationTargetItemProperty (
NotificationTargetItemProperty(..),
mkNotificationTargetItemProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data NotificationTargetItemProperty
= NotificationTargetItemProperty {snsTopicArn :: (Prelude.Maybe (Value Prelude.Text))}
mkNotificationTargetItemProperty :: NotificationTargetItemProperty
mkNotificationTargetItemProperty
= NotificationTargetItemProperty {snsTopicArn = Prelude.Nothing}
instance ToResourceProperties NotificationTargetItemProperty where
toResourceProperties NotificationTargetItemProperty {..}
= ResourceProperties
{awsType = "AWS::SSMIncidents::ResponsePlan.NotificationTargetItem",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "SnsTopicArn" Prelude.<$> snsTopicArn])}
instance JSON.ToJSON NotificationTargetItemProperty where
toJSON NotificationTargetItemProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "SnsTopicArn" Prelude.<$> snsTopicArn]))
instance Property "SnsTopicArn" NotificationTargetItemProperty where
type PropertyType "SnsTopicArn" NotificationTargetItemProperty = Value Prelude.Text
set newValue NotificationTargetItemProperty {}
= NotificationTargetItemProperty
{snsTopicArn = Prelude.pure newValue, ..} | |
8886c677d01b731b22dbd902cf1933a21adde19af00731f161a46100c209d531 | michaelballantyne/syntax-spec | peg2.rkt | #lang racket/base
(require "../../testing.rkt")
(begin-for-syntax
(define-syntax-class string
(pattern val #:when (string? (syntax-e #'val)))))
(syntax-spec
(binding-class var #:description "PEG variable")
(binding-class nonterm #:description "PEG nonterminal")
(extension-class peg-macro #:description "PEG macro")
(nonterminal peg-el
#:description "PEG expression"
#:allow-extension peg-macro
n:nonterm
(eps)
(char e:expr)
(token e:expr)
(alt e1:peg e2:peg)
(not e:peg)
(text e:racket-expr)
(=> ps:peg-seq e:racket-expr)
#:binding (nest-one ps e))
(nonterminal/nesting peg-seq (tail)
#:description "PEG expression"
#:allow-extension peg-macro
(bind v:var ps:peg-seq)
#:binding {(bind v) (nest-one ps tail)}
(seq ps1:peg-seq ps2:peg-seq)
#:binding (nest-one ps1 (nest-one ps2 tail))
(repeat ps:peg-seq)
#:binding (nest-one ps tail)
(src-span v:var ps:peg-seq)
#:binding {(bind v) (nest-one ps tail)}
pe:peg-el)
(nonterminal peg
ps:peg-seq
#:binding (nest-one ps [])))
(require racket/match)
(check-true
(match (expand-nonterminal/datum peg
(=> (seq (bind a (text "a")) (bind b (=> (bind c (text "b"))
(list a c))))
(list a b)))
[`(=> (seq (bind a (text ,_)) (bind b (=> (bind c (text ,_))
,_)))
,_)
#t]))
| null | https://raw.githubusercontent.com/michaelballantyne/syntax-spec/1eca406e83468601ce7507de25fb036f6ff4d0ff/test/dsls/peg2.rkt | racket | #lang racket/base
(require "../../testing.rkt")
(begin-for-syntax
(define-syntax-class string
(pattern val #:when (string? (syntax-e #'val)))))
(syntax-spec
(binding-class var #:description "PEG variable")
(binding-class nonterm #:description "PEG nonterminal")
(extension-class peg-macro #:description "PEG macro")
(nonterminal peg-el
#:description "PEG expression"
#:allow-extension peg-macro
n:nonterm
(eps)
(char e:expr)
(token e:expr)
(alt e1:peg e2:peg)
(not e:peg)
(text e:racket-expr)
(=> ps:peg-seq e:racket-expr)
#:binding (nest-one ps e))
(nonterminal/nesting peg-seq (tail)
#:description "PEG expression"
#:allow-extension peg-macro
(bind v:var ps:peg-seq)
#:binding {(bind v) (nest-one ps tail)}
(seq ps1:peg-seq ps2:peg-seq)
#:binding (nest-one ps1 (nest-one ps2 tail))
(repeat ps:peg-seq)
#:binding (nest-one ps tail)
(src-span v:var ps:peg-seq)
#:binding {(bind v) (nest-one ps tail)}
pe:peg-el)
(nonterminal peg
ps:peg-seq
#:binding (nest-one ps [])))
(require racket/match)
(check-true
(match (expand-nonterminal/datum peg
(=> (seq (bind a (text "a")) (bind b (=> (bind c (text "b"))
(list a c))))
(list a b)))
[`(=> (seq (bind a (text ,_)) (bind b (=> (bind c (text ,_))
,_)))
,_)
#t]))
| |
26c130d20c9e1b51d978ce68004e052f98cc1974e85f9a7074e9912c460be170 | jrm-code-project/LISP-Machine | interpreter-hooks.lisp | -*- Mode : LISP ; Package : USER ; ; : CL -*-
;;;
INTERPRETER - HOOKS.LISP
;;;
;;; Let the new interpreter slither into the old evaluator's wake.
;;;
(defvar *use-old-evaluator* t)
(defvar *inform-user* t)
(defun inform-user (stream format-string &rest format-args)
(when *inform-user*
(apply #'format stream format-string format-args)))
(defun make-hook-function (old-version new-version)
#'(lambda (&rest args)
(setq args (copylist args))
(if *use-old-evaluator*
(apply old-version args)
(apply new-version old-version args))))
(defun install-hook (old-function new-function)
(fdefine old-function
(make-hook-function (fsymeval old-function) new-function)))
(defun eval-hook (old-version form &optional (nohook nil n-sup))
(declare (ignore old-version nohook))
(when n-sup
(format t "~&Eval called with optional nohook."))
(k-lisp:eval form))
(defun eval1-hook (old-version form &optional (nohook nil n-sup))
(declare (ignore old-version nohook))
(inform-user t "~&Eval1 called")
(if n-sup
(inform-user t " with optional nohook.")
(inform-user t "."))
(k-lisp:eval form))
(defun apply-lambda-hook (old-version fctn value-list &optional (environment nil env-sup))
(cond ((and (null environment)
(consp fctn)
(eq (car fctn) 'lambda))
(let ((closure (k-lisp:eval `(FUNCTION ,fctn))))
(apply closure value-list)))
((not *ki-allow-apply-lambda-bagbiting*)
(ferror "Bagbiting in APPLY-LAMBDA"))
((and (null environment)
(consp fctn)
(eq (car fctn) 'named-lambda))
(inform-user *error-output*
"~&>>WARNING: NAMED-LAMBDA is not valid in Common Lisp.")
(let ((closure (k-lisp:eval `(FUNCTION (LAMBDA ,@(cddr fctn))))))
(apply closure value-list)))
(t
(let ((*use-old-evaluator* t))
(inform-user *error-output*
"~&>>WARNING: Biting the bag with APPLY-LAMBDA.")
(if env-sup
(funcall old-version fctn value-list environment)
(funcall old-version fctn value-list))))))
(defun evalhook-hook (old-version form *evalhook* *applyhook* &optional (env nil env-sup))
(declare (ignore old-version))
; (format t "~&Called evalhook.")
(if env-sup
(k-lisp:evalhook form *evalhook* *applyhook* env)
(k-lisp:evalhook form *evalhook* *applyhook*)))
(defun applyhook-hook (old-version fn args *evalhook* *applyhook* &optional (env nil env-sup))
(declare (ignore old-version))
(if env-sup
(k-lisp:applyhook fn args *evalhook* *applyhook* env)
(k-lisp:applyhook fn args *evalhook* *applyhook*)))
(defun eval-special-ok-hook (old-version form &optional (nohook nil n-sup))
(declare (ignore old-version nohook))
(when n-sup
(format t "~&Eval-special-ok called with optional nohook."))
(interpreter::eval-special-ok form))
(defun fsymeval-in-environment-hook (old-version symbol env check-symbol-function)
"This behaves incorrectly for lexical functions"
(if (interp::nframe-p env)
(let ((lexical-binding (interp::lookup-binding-in-environment symbol env :function)))
(if (not lexical-binding)
(if check-symbol-function (symbol-function symbol) NIL)
(case (interp::preprocessor-funmac-binding-type lexical-binding)
(function (error "internal: lexical value of function not yet available"))
(macro (interp::preprocessor-funmac-binding-value lexical-binding)))))
(funcall old-version symbol env check-symbol-function)))
;;; This variable prevents re-hooking.
(defvar *hooks-installed*)
(eval-when (load global:eval)
(when (not (boundp '*hooks-installed*))
(install-hook 'si::eval 'eval-hook)
(install-hook 'si::eval1 'eval1-hook)
(install-hook 'si::apply-lambda 'apply-lambda-hook)
(install-hook 'si::evalhook 'evalhook-hook)
(install-hook 'si::applyhook 'applyhook-hook)
(install-hook 'si::eval-special-ok 'eval-special-ok-hook)
(install-hook 'si::fsymeval-in-environment 'fsymeval-in-environment-hook)
(setq *hooks-installed* t)
))
(eval-when (load global:eval)
(setf (macro-function 'global:defun)
(macro-function 'k-lisp:defun))
(setf (macro-function 'global:defvar)
(macro-function 'k-lisp:defvar))
(setf (macro-function 'si::defvar-1)
(macro-function 'interpreter::defvar-1))
(setf (macro-function 'global:defparameter)
(macro-function 'k-lisp:defparameter))
(setf (macro-function 'global:defconstant)
(macro-function 'k-lisp:defconstant))
(setf (macro-function 'si::defconst-1)
(macro-function 'interpreter::defconst-1)))
(defun new () (setq *use-old-evaluator* nil))
(defun old () (setq *use-old-evaluator* t))
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/rauen/interpreter-hooks.lisp | lisp | Package : USER ; ; : CL -*-
Let the new interpreter slither into the old evaluator's wake.
(format t "~&Called evalhook.")
This variable prevents re-hooking. | INTERPRETER - HOOKS.LISP
(defvar *use-old-evaluator* t)
(defvar *inform-user* t)
(defun inform-user (stream format-string &rest format-args)
(when *inform-user*
(apply #'format stream format-string format-args)))
(defun make-hook-function (old-version new-version)
#'(lambda (&rest args)
(setq args (copylist args))
(if *use-old-evaluator*
(apply old-version args)
(apply new-version old-version args))))
(defun install-hook (old-function new-function)
(fdefine old-function
(make-hook-function (fsymeval old-function) new-function)))
(defun eval-hook (old-version form &optional (nohook nil n-sup))
(declare (ignore old-version nohook))
(when n-sup
(format t "~&Eval called with optional nohook."))
(k-lisp:eval form))
(defun eval1-hook (old-version form &optional (nohook nil n-sup))
(declare (ignore old-version nohook))
(inform-user t "~&Eval1 called")
(if n-sup
(inform-user t " with optional nohook.")
(inform-user t "."))
(k-lisp:eval form))
(defun apply-lambda-hook (old-version fctn value-list &optional (environment nil env-sup))
(cond ((and (null environment)
(consp fctn)
(eq (car fctn) 'lambda))
(let ((closure (k-lisp:eval `(FUNCTION ,fctn))))
(apply closure value-list)))
((not *ki-allow-apply-lambda-bagbiting*)
(ferror "Bagbiting in APPLY-LAMBDA"))
((and (null environment)
(consp fctn)
(eq (car fctn) 'named-lambda))
(inform-user *error-output*
"~&>>WARNING: NAMED-LAMBDA is not valid in Common Lisp.")
(let ((closure (k-lisp:eval `(FUNCTION (LAMBDA ,@(cddr fctn))))))
(apply closure value-list)))
(t
(let ((*use-old-evaluator* t))
(inform-user *error-output*
"~&>>WARNING: Biting the bag with APPLY-LAMBDA.")
(if env-sup
(funcall old-version fctn value-list environment)
(funcall old-version fctn value-list))))))
(defun evalhook-hook (old-version form *evalhook* *applyhook* &optional (env nil env-sup))
(declare (ignore old-version))
(if env-sup
(k-lisp:evalhook form *evalhook* *applyhook* env)
(k-lisp:evalhook form *evalhook* *applyhook*)))
(defun applyhook-hook (old-version fn args *evalhook* *applyhook* &optional (env nil env-sup))
(declare (ignore old-version))
(if env-sup
(k-lisp:applyhook fn args *evalhook* *applyhook* env)
(k-lisp:applyhook fn args *evalhook* *applyhook*)))
(defun eval-special-ok-hook (old-version form &optional (nohook nil n-sup))
(declare (ignore old-version nohook))
(when n-sup
(format t "~&Eval-special-ok called with optional nohook."))
(interpreter::eval-special-ok form))
(defun fsymeval-in-environment-hook (old-version symbol env check-symbol-function)
"This behaves incorrectly for lexical functions"
(if (interp::nframe-p env)
(let ((lexical-binding (interp::lookup-binding-in-environment symbol env :function)))
(if (not lexical-binding)
(if check-symbol-function (symbol-function symbol) NIL)
(case (interp::preprocessor-funmac-binding-type lexical-binding)
(function (error "internal: lexical value of function not yet available"))
(macro (interp::preprocessor-funmac-binding-value lexical-binding)))))
(funcall old-version symbol env check-symbol-function)))
(defvar *hooks-installed*)
(eval-when (load global:eval)
(when (not (boundp '*hooks-installed*))
(install-hook 'si::eval 'eval-hook)
(install-hook 'si::eval1 'eval1-hook)
(install-hook 'si::apply-lambda 'apply-lambda-hook)
(install-hook 'si::evalhook 'evalhook-hook)
(install-hook 'si::applyhook 'applyhook-hook)
(install-hook 'si::eval-special-ok 'eval-special-ok-hook)
(install-hook 'si::fsymeval-in-environment 'fsymeval-in-environment-hook)
(setq *hooks-installed* t)
))
(eval-when (load global:eval)
(setf (macro-function 'global:defun)
(macro-function 'k-lisp:defun))
(setf (macro-function 'global:defvar)
(macro-function 'k-lisp:defvar))
(setf (macro-function 'si::defvar-1)
(macro-function 'interpreter::defvar-1))
(setf (macro-function 'global:defparameter)
(macro-function 'k-lisp:defparameter))
(setf (macro-function 'global:defconstant)
(macro-function 'k-lisp:defconstant))
(setf (macro-function 'si::defconst-1)
(macro-function 'interpreter::defconst-1)))
(defun new () (setq *use-old-evaluator* nil))
(defun old () (setq *use-old-evaluator* t))
|
4e7d93532d84787feb6d8f5e8687ceee1bdf2ad679b19a36957c85c3b4caab6d | kztk-m/sparcl | Eval.hs | # LANGUAGE RecursiveDo #
module Language.Sparcl.Eval where
import Language.Sparcl.Core.Syntax
import Language.Sparcl.Exception
import Language.Sparcl.Value
import Control.Monad.Except
import Data.Maybe (fromMaybe)
import Control . Monad . State
-- import qualified Control.Monad.Fail as Fail
import Control . Monad . State
-- import qualified Control.Monad.Fail as Fail
import Control.Monad.Reader (MonadReader (local), ask)
-- import Debug.Trace (trace)
import Language.Sparcl.Pretty hiding ((<$>))
-- lookupEnvR :: QName -> Env -> Eval Value
lookupEnvR n env = case M.lookup n env of
-- Nothing -> throwError $ "Undefined value: " ++ show n
-- Just v -> return v
evalUBind :: Env -> Bind Name -> Eval Env
evalUBind env ds = do
rec ev <- mapM (\(n,_,e) -> do
v <- evalU env' e
return (n,v)) ds
let env' = extendsEnv ev env
return env'
evalU :: Env -> Exp Name -> Eval Value
evalU env expr = case expr of
Lit l -> return $ VLit l
Var n ->
lookupEnv n env
App e1 e2 -> do
v1 <- evalU env e1
case v1 of
VFun f -> do
v2 <- evalU env e2
f v2
_ ->
rtError $ text "the first component of application must be a function, but we got " <> ppr v1 <> text " from " <> ppr e1
Abs n e ->
return $ VFun (\v -> evalU (extendEnv n v env) e)
Con q es ->
VCon q <$> mapM (evalU env) es
Case e0 pes -> do
v0 <- evalU env e0
evalCase env v0 pes
Lift ef eb -> do
VFun vf <- evalU env ef
VFun vb <- evalU env eb
return $ VFun $ \(VRes f b) -> return $ VRes (f >=> vf) (vb >=> b)
VBang ( VFun vf ) < - evalU env ef
VBang ( VFun vb ) < - evalU env eb
let vf ' = vf . VBang
let vb ' = vb . VBang
return $ VBang $ VFun $ \(VRes f b ) - >
return $ VRes ( f > = > vf ' ) ( vb ' > = > b )
Let ds e -> do
env' <- evalUBind env ds
evalU env' e
Unlift e -> do
VBang ( VFun f ) < - evalU env e
VFun f <- evalU env e
newAddr $ \a -> do
VRes f0 b0 <- f (VRes (lookupHeap a)
(return . singletonHeap a))
let f0' v = f0 (singletonHeap a v)
let b0' v = do hp <- b0 v
lookupHeap a hp
let f0 ' ( VBang v ) = f0 ( singletonHeap a v )
-- f0' _ = error "expecting !"
let b0 ' ( VBang v ) = do v
-- lookupHeap a hp
-- b0' _ = error "expecting !"
let c = nameTuple 2
return $ VCon c [ VBang ( VFun f0 ' ) , VBang ( VFun b0 ' ) ]
return $ VCon c [VFun f0', VFun b0']
RCon q es -> do
vs <- mapM (evalU env) es
return $ VRes (\heap -> do
us <- mapM (\v -> runFwd v heap) vs
return $ VCon q us)
(\v' ->
case v' of
VCon q' us' | q == q' && length us' == length es -> do
envs <- zipWithM runBwd vs us'
return $ foldr unionHeap emptyHeap envs
_ ->
rtError $ text "out of the range:" <+> ppr v' <+> text "for" <+> ppr expr)
RCase e0 pes -> do
VRes f0 b0 <- evalU env e0
pes' <- mapM (\(p,e,e') -> do
VBang ( VFun ch ) < - evalU env e '
VFun ch <- evalU env e'
let ch' v = do
res <- ch v
case res of
VCon q [] | q == conTrue -> return True
_ -> return False
return (p, e, ch')) pes
lvl <- ask
return $ VRes (\hp -> local (const lvl) $ evalCaseF env hp f0 pes')
(\v -> local (const lvl) $ evalCaseB env v b0 pes')
RPin e1 e2 -> do
VRes f1 b1 <- evalU env e1
VFun h <- evalU env e2
let c = nameTuple 2
return $ VRes (\hp -> do
a <- f1 hp
( VBang a )
b <- f2 hp
return $ VCon c [a, b])
(\case
VCon c' [a,b] | c' == c -> do
( VBang a )
hp2 <- b2 b
hp1 <- b1 a
return $ unionHeap hp1 hp2
_ -> rtError $ text "Expected a pair"
)
evalCase :: Env -> Value -> [ (Pat Name, Exp Name) ] -> Eval Value
evalCase _ v [] = rtError $ text "pattern match error" <+> ppr v
evalCase env v ((p, e):pes) =
case findMatch v p of
Just binds -> evalU (extendsEnv binds env) e
_ -> evalCase env v pes
findMatch :: Value -> Pat Name -> Maybe [ (Name, Value) ]
findMatch v (PVar n) = return [(n, v)]
findMatch (VCon q vs) (PCon q' ps) | q == q' && length vs == length ps =
concat <$> zipWithM findMatch vs ps
findMatch _ _ = Nothing
evalCaseF :: Env -> Heap -> (Heap -> Eval Value) -> [ (Pat Name, Exp Name, Value -> Eval Bool) ] -> Eval Value
evalCaseF env hp f0 alts = do
v0 <- f0 hp
go v0 [] alts
where
go :: Value -> [Value -> Eval Bool] -> [ (Pat Name, Exp Name, Value -> Eval Bool) ] -> Eval Value
go v0 _ [] = rtError $ text $ "pattern match failure (fwd): " ++ prettyShow v0
go v0 checker ((p,e,ch) : pes) =
case findMatch v0 p of
Nothing ->
go v0 (ch:checker) pes
Just binds ->
newAddrs (length binds) $ \as -> do
let hbinds = zipWith (\a (_, v) -> (a, v)) as binds
let binds' = zipWith (\a (x, _) ->
(x, VRes (lookupHeap a) (return . singletonHeap a))) as binds
VRes f _ <- evalU (extendsEnv binds' env) e
res <- f (foldr (uncurry extendHeap) hp hbinds)
checkAssert ch checker res
checkAssert :: (Value -> Eval Bool) -> [Value -> Eval Bool] -> Value -> Eval Value
checkAssert ch checker res = do
v < - ch ( VBang res )
vs < - mapM ( - > c ( VBang res ) ) checker
v <- ch res
vs <- mapM (\c -> c res) checker
() <- unless (v && not (or vs)) $
rtError (text "Assertion failed (fwd)")
return res
evalCaseB :: Env -> Value -> (Value -> Eval Heap) -> [ (Pat Name, Exp Name, Value -> Eval Bool) ] -> Eval Heap
evalCaseB env vres b0 alts = do
(v, hp) <- go [] alts
trace ( show $ text " hp = " < > pprHeap hp < > comma < + > text " v = " < > ppr v ) $
return $ unionHeap hp hp'
where
mkAssert :: Pat Name -> Value -> Bool
mkAssert p v = case findMatch v p of
Just _ -> True
_ -> False
go _ [] = rtError $ text "pattern match failure (bwd)"
go checker ((p,e,ch):pes) = do
flg < - ch ( VBang vres )
flg <- ch vres
if flg
then do
let xs = freeVarsP p
newAddrs (length xs) $ \as -> do
let binds' = zipWith (\x a ->
(x, VRes (lookupHeap a) (return . singletonHeap a))) xs as
VRes _ b <- {- trace ("Evaluating bodies") $ -} evalU (extendsEnv binds' env) e
trace ( " vres = " + + show ( ) ) $
v0 <- {- trace ("hpBr = " ++ show (pprHeap hpBr)) $ -} fillPat p <$> zipWithM (\x a -> (x,) <$> lookupHeap a hpBr) xs as
unless (any ($ v0) checker) $
rtError $ text "Assertion failed (bwd)"
return (v0, removesHeap as hpBr)
else go (mkAssert p:checker) pes
fillPat :: Pat Name -> [ (Name, Value) ] -> Value
fillPat (PVar n) bs =
fromMaybe (error "Shouldn't happen") (lookup n bs)
fillPat (PCon c ps) bs =
VCon c (map (flip fillPat bs) ps)
runFwd :: Value -> Heap -> Eval Value
runFwd (VRes f _) = f
runFwd _ = \_ -> rtError $ text "expected a reversible comp."
runBwd :: Value -> Value -> Eval Heap
runBwd (VRes _ b) = b
runBwd _ = \_ -> rtError $ text "expected a reversible comp."
| null | https://raw.githubusercontent.com/kztk-m/sparcl/443724980c52ab8759be3caf803e0cf64dff72f2/src/Language/Sparcl/Eval.hs | haskell | import qualified Control.Monad.Fail as Fail
import qualified Control.Monad.Fail as Fail
import Debug.Trace (trace)
lookupEnvR :: QName -> Env -> Eval Value
Nothing -> throwError $ "Undefined value: " ++ show n
Just v -> return v
f0' _ = error "expecting !"
lookupHeap a hp
b0' _ = error "expecting !"
trace ("Evaluating bodies") $
trace ("hpBr = " ++ show (pprHeap hpBr)) $ | # LANGUAGE RecursiveDo #
module Language.Sparcl.Eval where
import Language.Sparcl.Core.Syntax
import Language.Sparcl.Exception
import Language.Sparcl.Value
import Control.Monad.Except
import Data.Maybe (fromMaybe)
import Control . Monad . State
import Control . Monad . State
import Control.Monad.Reader (MonadReader (local), ask)
import Language.Sparcl.Pretty hiding ((<$>))
lookupEnvR n env = case M.lookup n env of
evalUBind :: Env -> Bind Name -> Eval Env
evalUBind env ds = do
rec ev <- mapM (\(n,_,e) -> do
v <- evalU env' e
return (n,v)) ds
let env' = extendsEnv ev env
return env'
evalU :: Env -> Exp Name -> Eval Value
evalU env expr = case expr of
Lit l -> return $ VLit l
Var n ->
lookupEnv n env
App e1 e2 -> do
v1 <- evalU env e1
case v1 of
VFun f -> do
v2 <- evalU env e2
f v2
_ ->
rtError $ text "the first component of application must be a function, but we got " <> ppr v1 <> text " from " <> ppr e1
Abs n e ->
return $ VFun (\v -> evalU (extendEnv n v env) e)
Con q es ->
VCon q <$> mapM (evalU env) es
Case e0 pes -> do
v0 <- evalU env e0
evalCase env v0 pes
Lift ef eb -> do
VFun vf <- evalU env ef
VFun vb <- evalU env eb
return $ VFun $ \(VRes f b) -> return $ VRes (f >=> vf) (vb >=> b)
VBang ( VFun vf ) < - evalU env ef
VBang ( VFun vb ) < - evalU env eb
let vf ' = vf . VBang
let vb ' = vb . VBang
return $ VBang $ VFun $ \(VRes f b ) - >
return $ VRes ( f > = > vf ' ) ( vb ' > = > b )
Let ds e -> do
env' <- evalUBind env ds
evalU env' e
Unlift e -> do
VBang ( VFun f ) < - evalU env e
VFun f <- evalU env e
newAddr $ \a -> do
VRes f0 b0 <- f (VRes (lookupHeap a)
(return . singletonHeap a))
let f0' v = f0 (singletonHeap a v)
let b0' v = do hp <- b0 v
lookupHeap a hp
let f0 ' ( VBang v ) = f0 ( singletonHeap a v )
let b0 ' ( VBang v ) = do v
let c = nameTuple 2
return $ VCon c [ VBang ( VFun f0 ' ) , VBang ( VFun b0 ' ) ]
return $ VCon c [VFun f0', VFun b0']
RCon q es -> do
vs <- mapM (evalU env) es
return $ VRes (\heap -> do
us <- mapM (\v -> runFwd v heap) vs
return $ VCon q us)
(\v' ->
case v' of
VCon q' us' | q == q' && length us' == length es -> do
envs <- zipWithM runBwd vs us'
return $ foldr unionHeap emptyHeap envs
_ ->
rtError $ text "out of the range:" <+> ppr v' <+> text "for" <+> ppr expr)
RCase e0 pes -> do
VRes f0 b0 <- evalU env e0
pes' <- mapM (\(p,e,e') -> do
VBang ( VFun ch ) < - evalU env e '
VFun ch <- evalU env e'
let ch' v = do
res <- ch v
case res of
VCon q [] | q == conTrue -> return True
_ -> return False
return (p, e, ch')) pes
lvl <- ask
return $ VRes (\hp -> local (const lvl) $ evalCaseF env hp f0 pes')
(\v -> local (const lvl) $ evalCaseB env v b0 pes')
RPin e1 e2 -> do
VRes f1 b1 <- evalU env e1
VFun h <- evalU env e2
let c = nameTuple 2
return $ VRes (\hp -> do
a <- f1 hp
( VBang a )
b <- f2 hp
return $ VCon c [a, b])
(\case
VCon c' [a,b] | c' == c -> do
( VBang a )
hp2 <- b2 b
hp1 <- b1 a
return $ unionHeap hp1 hp2
_ -> rtError $ text "Expected a pair"
)
evalCase :: Env -> Value -> [ (Pat Name, Exp Name) ] -> Eval Value
evalCase _ v [] = rtError $ text "pattern match error" <+> ppr v
evalCase env v ((p, e):pes) =
case findMatch v p of
Just binds -> evalU (extendsEnv binds env) e
_ -> evalCase env v pes
findMatch :: Value -> Pat Name -> Maybe [ (Name, Value) ]
findMatch v (PVar n) = return [(n, v)]
findMatch (VCon q vs) (PCon q' ps) | q == q' && length vs == length ps =
concat <$> zipWithM findMatch vs ps
findMatch _ _ = Nothing
evalCaseF :: Env -> Heap -> (Heap -> Eval Value) -> [ (Pat Name, Exp Name, Value -> Eval Bool) ] -> Eval Value
evalCaseF env hp f0 alts = do
v0 <- f0 hp
go v0 [] alts
where
go :: Value -> [Value -> Eval Bool] -> [ (Pat Name, Exp Name, Value -> Eval Bool) ] -> Eval Value
go v0 _ [] = rtError $ text $ "pattern match failure (fwd): " ++ prettyShow v0
go v0 checker ((p,e,ch) : pes) =
case findMatch v0 p of
Nothing ->
go v0 (ch:checker) pes
Just binds ->
newAddrs (length binds) $ \as -> do
let hbinds = zipWith (\a (_, v) -> (a, v)) as binds
let binds' = zipWith (\a (x, _) ->
(x, VRes (lookupHeap a) (return . singletonHeap a))) as binds
VRes f _ <- evalU (extendsEnv binds' env) e
res <- f (foldr (uncurry extendHeap) hp hbinds)
checkAssert ch checker res
checkAssert :: (Value -> Eval Bool) -> [Value -> Eval Bool] -> Value -> Eval Value
checkAssert ch checker res = do
v < - ch ( VBang res )
vs < - mapM ( - > c ( VBang res ) ) checker
v <- ch res
vs <- mapM (\c -> c res) checker
() <- unless (v && not (or vs)) $
rtError (text "Assertion failed (fwd)")
return res
evalCaseB :: Env -> Value -> (Value -> Eval Heap) -> [ (Pat Name, Exp Name, Value -> Eval Bool) ] -> Eval Heap
evalCaseB env vres b0 alts = do
(v, hp) <- go [] alts
trace ( show $ text " hp = " < > pprHeap hp < > comma < + > text " v = " < > ppr v ) $
return $ unionHeap hp hp'
where
mkAssert :: Pat Name -> Value -> Bool
mkAssert p v = case findMatch v p of
Just _ -> True
_ -> False
go _ [] = rtError $ text "pattern match failure (bwd)"
go checker ((p,e,ch):pes) = do
flg < - ch ( VBang vres )
flg <- ch vres
if flg
then do
let xs = freeVarsP p
newAddrs (length xs) $ \as -> do
let binds' = zipWith (\x a ->
(x, VRes (lookupHeap a) (return . singletonHeap a))) xs as
trace ( " vres = " + + show ( ) ) $
unless (any ($ v0) checker) $
rtError $ text "Assertion failed (bwd)"
return (v0, removesHeap as hpBr)
else go (mkAssert p:checker) pes
fillPat :: Pat Name -> [ (Name, Value) ] -> Value
fillPat (PVar n) bs =
fromMaybe (error "Shouldn't happen") (lookup n bs)
fillPat (PCon c ps) bs =
VCon c (map (flip fillPat bs) ps)
runFwd :: Value -> Heap -> Eval Value
runFwd (VRes f _) = f
runFwd _ = \_ -> rtError $ text "expected a reversible comp."
runBwd :: Value -> Value -> Eval Heap
runBwd (VRes _ b) = b
runBwd _ = \_ -> rtError $ text "expected a reversible comp."
|
2cea5953c525fb41192929f184c2b667aae83a3eefb32f563f561c3c984c3c45 | litaocheng/erl-test | client_stat.erl | -module(client_stat).
-export([run/0]).
-include("tcp_test.hrl").
-define(RECV_TIMEOUT, 100).
run() ->
N = 10,
C = 2,
Per = N div C,
Server = ?SERVER,
Now = now(),
Procs = [new_client(self(), Server, Per) || _ <- lists:seq(1, C)],
{Satis0, Timeout} =
lists:foldl(
fun(_E, {SAcc, Timeout}) ->
receive
{S, T} ->
{[S | SAcc], T + Timeout}
end
end,
{[], 0},
Procs),
T = timer:now_diff(now(), Now),
{Satis, NotSatis} =
lists:partition(
fun(E) when E =< 10000 ->
true;
(_) ->
false
end,
lists:flatten(Satis0)),
?P("request count: ~p use time:~p(us) speed:~p/s~n", [N, T, N * 1000000 div T]),
?P("timeout: ~p statify: ~p~n", [Timeout + length(NotSatis), length(Satis)]),
?P("rsp time(us):~n", []),
?P("min:~p max:~p avg:~p~n", [lists:min(Satis),
lists:max(Satis),
lists:sum(Satis) div N
]),
erlang:halt(0).
new_client(Parent, Server, N) ->
F = fun() ->
random_init(),
{ok, Sock} = connect_server(Server),
%timer:sleep(random:uniform(1000)),
{ok, Statics} = client_loop(Sock, N, {[], 0}),
Parent ! Statics
end,
spawn_link(F).
random_init() ->
{A, B, C} = erlang:now(),
random:seed(A, B, C).
connect_server(Server) ->
case gen_tcp:connect(Server, ?PORT, [binary, {packet, 2}, {active, false}]) of
{ok, S} ->
{ok, S};
{error, R} ->
?P("connect server error! ~p~n", [R]),
{error, R}
end.
client_loop(Sock, 0, Acc) ->
{ok, Acc};
client_loop(Sock, N, {Statify, Timeout}) ->
T1 = now(),
ok = gen_tcp:send(Sock, <<"get">>),
case gen_tcp:recv(Sock, 0, ?RECV_TIMEOUT) of
{error, timeout} ->
?P("recv data timeout!~n", []),
client_loop(Sock, N - 1, {Statify, Timeout + 1});
{ok, Packet} ->
T2 = now(),
%?P("recv ~p~n", [Packet]),
%timer:sleep(10),
client_loop(Sock, N - 1, {[timer:now_diff(T2, T1) | Statify], Timeout});
{error, closed} ->
?P("socket closed!~p~n", [Sock]),
ok
end.
stop(Procs) ->
[exit(Pid, kill) || Pid <- Procs].
| null | https://raw.githubusercontent.com/litaocheng/erl-test/893679fccb1c16dda45d40d2b9e12d78db991b8a/tcp_test/client_stat.erl | erlang | timer:sleep(random:uniform(1000)),
?P("recv ~p~n", [Packet]),
timer:sleep(10), | -module(client_stat).
-export([run/0]).
-include("tcp_test.hrl").
-define(RECV_TIMEOUT, 100).
run() ->
N = 10,
C = 2,
Per = N div C,
Server = ?SERVER,
Now = now(),
Procs = [new_client(self(), Server, Per) || _ <- lists:seq(1, C)],
{Satis0, Timeout} =
lists:foldl(
fun(_E, {SAcc, Timeout}) ->
receive
{S, T} ->
{[S | SAcc], T + Timeout}
end
end,
{[], 0},
Procs),
T = timer:now_diff(now(), Now),
{Satis, NotSatis} =
lists:partition(
fun(E) when E =< 10000 ->
true;
(_) ->
false
end,
lists:flatten(Satis0)),
?P("request count: ~p use time:~p(us) speed:~p/s~n", [N, T, N * 1000000 div T]),
?P("timeout: ~p statify: ~p~n", [Timeout + length(NotSatis), length(Satis)]),
?P("rsp time(us):~n", []),
?P("min:~p max:~p avg:~p~n", [lists:min(Satis),
lists:max(Satis),
lists:sum(Satis) div N
]),
erlang:halt(0).
new_client(Parent, Server, N) ->
F = fun() ->
random_init(),
{ok, Sock} = connect_server(Server),
{ok, Statics} = client_loop(Sock, N, {[], 0}),
Parent ! Statics
end,
spawn_link(F).
random_init() ->
{A, B, C} = erlang:now(),
random:seed(A, B, C).
connect_server(Server) ->
case gen_tcp:connect(Server, ?PORT, [binary, {packet, 2}, {active, false}]) of
{ok, S} ->
{ok, S};
{error, R} ->
?P("connect server error! ~p~n", [R]),
{error, R}
end.
client_loop(Sock, 0, Acc) ->
{ok, Acc};
client_loop(Sock, N, {Statify, Timeout}) ->
T1 = now(),
ok = gen_tcp:send(Sock, <<"get">>),
case gen_tcp:recv(Sock, 0, ?RECV_TIMEOUT) of
{error, timeout} ->
?P("recv data timeout!~n", []),
client_loop(Sock, N - 1, {Statify, Timeout + 1});
{ok, Packet} ->
T2 = now(),
client_loop(Sock, N - 1, {[timer:now_diff(T2, T1) | Statify], Timeout});
{error, closed} ->
?P("socket closed!~p~n", [Sock]),
ok
end.
stop(Procs) ->
[exit(Pid, kill) || Pid <- Procs].
|
cd61531f90f82503e7ae90efd5b33c6cb03a2610d6a998e1d2dcf07dbd22ca66 | ylgrgyq/resilience-for-clojure | timelimiter.clj | (ns resilience.timelimiter
(:refer-clojure :exclude [name])
(:require [resilience.spec :as s]
[resilience.util :as u])
(:import (java.time Duration)
(io.github.resilience4j.timelimiter TimeLimiterConfig TimeLimiterConfig$Builder TimeLimiter TimeLimiterRegistry)
(io.github.resilience4j.timelimiter.event TimeLimiterEvent TimeLimiterEvent$Type TimeLimiterOnErrorEvent TimeLimiterOnSuccessEvent TimeLimiterOnTimeoutEvent)
(io.github.resilience4j.core EventConsumer)
(java.util.function Supplier)))
(defmacro to-future-supplier
"Wrap body to a Future Supplier."
[& body]
`(reify Supplier
(get [_]
~@body)))
(defn ^TimeLimiterConfig time-limiter-config
"Create a TimeLimiterConfig.
Allowed options are:
* :timeout-millis
Configures the thread execution timeout.
Default value is 1 second.
* :cancel-running-future?
Configures whether cancel is called on the running future.
Defaults to true.
"
[opts]
(s/verify-opt-map-keys-with-spec :timelimiter/time-limiter-config opts)
(if (empty? opts)
(TimeLimiterConfig/ofDefaults)
(let [^TimeLimiterConfig$Builder config (TimeLimiterConfig/custom)]
(when-let [timeout (:timeout-millis opts)]
(.timeoutDuration config (Duration/ofMillis timeout)))
(when (contains? opts :cancel-running-future?)
(.cancelRunningFuture config (true? (:cancel-running-future? opts))))
(.build config))))
(defn ^TimeLimiterRegistry registry-with-config
"Create a TimeLimiterRegistry with a time limiter
configurations map.
Please refer to `time-limiter-config` for allowed key value pairs
within the time limiter configuration map."
[config]
(let [^TimeLimiterConfig c (if (instance? TimeLimiterConfig config)
config
(time-limiter-config config))]
(TimeLimiterRegistry/of c)))
(defmacro defregistry
"Define a TimeLimiterRegistry under `name` with a default or custom
circuit breaker configuration.
Please refer to `time-limiter-config` for allowed key value pairs
within the time limiter configuration map."
([name]
(let [sym (with-meta (symbol name) {:tag `TimeLimiterRegistry})]
`(def ~sym (TimeLimiterRegistry/ofDefaults))))
([name config]
(let [sym (with-meta (symbol name) {:tag `TimeLimiterRegistry})]
`(def ~sym
(let [config# (time-limiter-config ~config)]
(registry-with-config config#))))))
(defn get-all-time-limiters
"Get all time limiters registered to this time limiter registry instance"
[^TimeLimiterRegistry registry]
(let [heads (.getAllTimeLimiters registry)
iter (.iterator heads)]
(u/lazy-seq-from-iterator iter)))
(defn ^TimeLimiter time-limiter
"Create a time limiter with a default or custom time limiter configuration.
Please refer to `time-limiter-config` for allowed key value pairs
within the time limiter configuration."
([] (TimeLimiter/ofDefaults))
([config]
(let [config (time-limiter-config config)]
(TimeLimiter/of ^TimeLimiterConfig config))))
(defmacro deftimelimiter
"Define a time limiter under `name`.
Please refer to `time-limiter-config` for allowed key value pairs
within the time limiter configuration."
([name]
(let [sym (with-meta (symbol name) {:tag `TimeLimiter})]
`(def ~sym (time-limiter))))
([name config]
(let [sym (with-meta (symbol name) {:tag `TimeLimiter})]
`(def ~sym (time-limiter ~config)))))
(defn ^String name
"Get the name of this TimeLimiter"
[^TimeLimiter limiter]
(.getName limiter))
(defn ^TimeLimiterConfig config
"Get the Metrics of this TimeLimiter"
[^TimeLimiter limiter]
(.getTimeLimiterConfig limiter))
(defn on-success
"Records a successful call.
This method must be invoked when a call was successful."
[^TimeLimiter limiter]
(.onSuccess limiter))
(defn on-error
"Records a failed call. This method must be invoked when a call failed."
[^TimeLimiter limiter ^Throwable throwable]
(.onError limiter throwable))
(defmacro execute-future-with-time-limiter
"Execute the following codes with the protection
of a time limiter given by `time-limiter` argument."
[time-limiter & body]
(let [timelimiter (vary-meta time-limiter assoc :tag `TimeLimiter)
future-supplier (with-meta `(to-future-supplier ~@body) {:tag `Supplier})]
`(.executeFutureSupplier ~timelimiter ~future-supplier)))
(def ^{:dynamic true
:doc "Contextual value represents timer limiter name"}
*time-limiter-name*)
(def ^{:dynamic true
:doc "Contextual value represents event create time"}
*creation-time*)
(defmacro ^{:private true :no-doc true} with-context [abstract-event & body]
(let [abstract-event (vary-meta abstract-event assoc :tag `TimeLimiterEvent)]
`(binding [*time-limiter-name* (.getTimeLimiterName ~abstract-event)
*creation-time* (.getCreationTime ~abstract-event)]
~@body)))
(defmulti ^:private on-event (fn [_ event] (.getEventType ^TimeLimiterEvent event)))
(defmethod on-event TimeLimiterEvent$Type/SUCCESS
[consumer-fn-map ^TimeLimiterOnSuccessEvent event]
(with-context event
(when-let [consumer-fn (get consumer-fn-map :on-success)]
(consumer-fn))))
(defmethod on-event TimeLimiterEvent$Type/ERROR
[consumer-fn-map ^TimeLimiterOnErrorEvent event]
(with-context event
(when-let [consumer-fn (get consumer-fn-map :on-error)]
(consumer-fn (.getThrowable event)))))
(defmethod on-event TimeLimiterEvent$Type/TIMEOUT
[consumer-fn-map ^TimeLimiterOnTimeoutEvent event]
(with-context event
(when-let [consumer-fn (get consumer-fn-map :on-timeout)]
(consumer-fn))))
(defn- create-consumer
([consumer-fn-map]
(reify EventConsumer
(consumeEvent [_ event]
(on-event consumer-fn-map event))))
([k consumer-fn]
(reify EventConsumer
(consumeEvent [_ event]
(on-event {k consumer-fn} event)))))
(defn set-on-success-event-consumer!
[^TimeLimiter limiter consumer-fn]
"set a consumer to consume `on-success` event which emitted when execution success from time limiter.
`consumer-fn` accepts a function which takes no arguments.
Please note that in `consumer-fn` you can get the time limiter name and the creation time of the
consumed event by accessing `*time-limiter-name*` and `*creation-time*` under this namespace."
(let [pub (.getEventPublisher limiter)]
(.onSuccess pub (create-consumer :on-success consumer-fn))))
(defn set-on-error-event-consumer!
[^TimeLimiter limiter consumer-fn]
"set a consumer to consume `on-error` event which emitted when execution failed from time limiter.
`consumer-fn` accepts a function which takes a Throwable as argument.
Please note that in `consumer-fn` you can get the time limiter name and the creation time of the
consumed event by accessing `*time-limiter-name*` and `*creation-time*` under this namespace."
(let [pub (.getEventPublisher limiter)]
(.onError pub (create-consumer :on-error consumer-fn))))
(defn set-on-timeout-event-consumer!
[^TimeLimiter limiter consumer-fn]
"set a consumer to consume `on-timeout` event which emitted when execution timeout from time limiter.
`consumer-fn` accepts a function which takes no arguments.
Please note that in `consumer-fn` you can get the time limiter name and the creation time of the
consumed event by accessing `*time-limiter-name*` and `*creation-time*` under this namespace."
(let [pub (.getEventPublisher limiter)]
(.onTimeout pub (create-consumer :on-timeout consumer-fn))))
(defn set-on-all-event-consumer!
[^TimeLimiter limiter consumer-fn-map]
"set a consumer to consume all available events emitted from time limiter.
`consumer-fn-map` accepts a map which contains following key and function pairs:
* `on-success` accepts a function which takes no arguments
* `on-error` accepts a function which takes Throwable as a argument
* `on-timeout` accepts a function which takes no arguments
Please note that in `consumer-fn` you can get the time limiter name and the creation time of the
consumed event by accessing `*time-limiter-name*` and `*creation-time*` under this namespace."
(let [pub (.getEventPublisher limiter)]
(.onEvent pub (create-consumer consumer-fn-map))))
| null | https://raw.githubusercontent.com/ylgrgyq/resilience-for-clojure/7b0532d1c72d416020402c15eb5699143be4b7bf/src/resilience/timelimiter.clj | clojure | (ns resilience.timelimiter
(:refer-clojure :exclude [name])
(:require [resilience.spec :as s]
[resilience.util :as u])
(:import (java.time Duration)
(io.github.resilience4j.timelimiter TimeLimiterConfig TimeLimiterConfig$Builder TimeLimiter TimeLimiterRegistry)
(io.github.resilience4j.timelimiter.event TimeLimiterEvent TimeLimiterEvent$Type TimeLimiterOnErrorEvent TimeLimiterOnSuccessEvent TimeLimiterOnTimeoutEvent)
(io.github.resilience4j.core EventConsumer)
(java.util.function Supplier)))
(defmacro to-future-supplier
"Wrap body to a Future Supplier."
[& body]
`(reify Supplier
(get [_]
~@body)))
(defn ^TimeLimiterConfig time-limiter-config
"Create a TimeLimiterConfig.
Allowed options are:
* :timeout-millis
Configures the thread execution timeout.
Default value is 1 second.
* :cancel-running-future?
Configures whether cancel is called on the running future.
Defaults to true.
"
[opts]
(s/verify-opt-map-keys-with-spec :timelimiter/time-limiter-config opts)
(if (empty? opts)
(TimeLimiterConfig/ofDefaults)
(let [^TimeLimiterConfig$Builder config (TimeLimiterConfig/custom)]
(when-let [timeout (:timeout-millis opts)]
(.timeoutDuration config (Duration/ofMillis timeout)))
(when (contains? opts :cancel-running-future?)
(.cancelRunningFuture config (true? (:cancel-running-future? opts))))
(.build config))))
(defn ^TimeLimiterRegistry registry-with-config
"Create a TimeLimiterRegistry with a time limiter
configurations map.
Please refer to `time-limiter-config` for allowed key value pairs
within the time limiter configuration map."
[config]
(let [^TimeLimiterConfig c (if (instance? TimeLimiterConfig config)
config
(time-limiter-config config))]
(TimeLimiterRegistry/of c)))
(defmacro defregistry
"Define a TimeLimiterRegistry under `name` with a default or custom
circuit breaker configuration.
Please refer to `time-limiter-config` for allowed key value pairs
within the time limiter configuration map."
([name]
(let [sym (with-meta (symbol name) {:tag `TimeLimiterRegistry})]
`(def ~sym (TimeLimiterRegistry/ofDefaults))))
([name config]
(let [sym (with-meta (symbol name) {:tag `TimeLimiterRegistry})]
`(def ~sym
(let [config# (time-limiter-config ~config)]
(registry-with-config config#))))))
(defn get-all-time-limiters
"Get all time limiters registered to this time limiter registry instance"
[^TimeLimiterRegistry registry]
(let [heads (.getAllTimeLimiters registry)
iter (.iterator heads)]
(u/lazy-seq-from-iterator iter)))
(defn ^TimeLimiter time-limiter
"Create a time limiter with a default or custom time limiter configuration.
Please refer to `time-limiter-config` for allowed key value pairs
within the time limiter configuration."
([] (TimeLimiter/ofDefaults))
([config]
(let [config (time-limiter-config config)]
(TimeLimiter/of ^TimeLimiterConfig config))))
(defmacro deftimelimiter
"Define a time limiter under `name`.
Please refer to `time-limiter-config` for allowed key value pairs
within the time limiter configuration."
([name]
(let [sym (with-meta (symbol name) {:tag `TimeLimiter})]
`(def ~sym (time-limiter))))
([name config]
(let [sym (with-meta (symbol name) {:tag `TimeLimiter})]
`(def ~sym (time-limiter ~config)))))
(defn ^String name
"Get the name of this TimeLimiter"
[^TimeLimiter limiter]
(.getName limiter))
(defn ^TimeLimiterConfig config
"Get the Metrics of this TimeLimiter"
[^TimeLimiter limiter]
(.getTimeLimiterConfig limiter))
(defn on-success
"Records a successful call.
This method must be invoked when a call was successful."
[^TimeLimiter limiter]
(.onSuccess limiter))
(defn on-error
"Records a failed call. This method must be invoked when a call failed."
[^TimeLimiter limiter ^Throwable throwable]
(.onError limiter throwable))
(defmacro execute-future-with-time-limiter
"Execute the following codes with the protection
of a time limiter given by `time-limiter` argument."
[time-limiter & body]
(let [timelimiter (vary-meta time-limiter assoc :tag `TimeLimiter)
future-supplier (with-meta `(to-future-supplier ~@body) {:tag `Supplier})]
`(.executeFutureSupplier ~timelimiter ~future-supplier)))
(def ^{:dynamic true
:doc "Contextual value represents timer limiter name"}
*time-limiter-name*)
(def ^{:dynamic true
:doc "Contextual value represents event create time"}
*creation-time*)
(defmacro ^{:private true :no-doc true} with-context [abstract-event & body]
(let [abstract-event (vary-meta abstract-event assoc :tag `TimeLimiterEvent)]
`(binding [*time-limiter-name* (.getTimeLimiterName ~abstract-event)
*creation-time* (.getCreationTime ~abstract-event)]
~@body)))
(defmulti ^:private on-event (fn [_ event] (.getEventType ^TimeLimiterEvent event)))
(defmethod on-event TimeLimiterEvent$Type/SUCCESS
[consumer-fn-map ^TimeLimiterOnSuccessEvent event]
(with-context event
(when-let [consumer-fn (get consumer-fn-map :on-success)]
(consumer-fn))))
(defmethod on-event TimeLimiterEvent$Type/ERROR
[consumer-fn-map ^TimeLimiterOnErrorEvent event]
(with-context event
(when-let [consumer-fn (get consumer-fn-map :on-error)]
(consumer-fn (.getThrowable event)))))
(defmethod on-event TimeLimiterEvent$Type/TIMEOUT
[consumer-fn-map ^TimeLimiterOnTimeoutEvent event]
(with-context event
(when-let [consumer-fn (get consumer-fn-map :on-timeout)]
(consumer-fn))))
(defn- create-consumer
([consumer-fn-map]
(reify EventConsumer
(consumeEvent [_ event]
(on-event consumer-fn-map event))))
([k consumer-fn]
(reify EventConsumer
(consumeEvent [_ event]
(on-event {k consumer-fn} event)))))
(defn set-on-success-event-consumer!
[^TimeLimiter limiter consumer-fn]
"set a consumer to consume `on-success` event which emitted when execution success from time limiter.
`consumer-fn` accepts a function which takes no arguments.
Please note that in `consumer-fn` you can get the time limiter name and the creation time of the
consumed event by accessing `*time-limiter-name*` and `*creation-time*` under this namespace."
(let [pub (.getEventPublisher limiter)]
(.onSuccess pub (create-consumer :on-success consumer-fn))))
(defn set-on-error-event-consumer!
[^TimeLimiter limiter consumer-fn]
"set a consumer to consume `on-error` event which emitted when execution failed from time limiter.
`consumer-fn` accepts a function which takes a Throwable as argument.
Please note that in `consumer-fn` you can get the time limiter name and the creation time of the
consumed event by accessing `*time-limiter-name*` and `*creation-time*` under this namespace."
(let [pub (.getEventPublisher limiter)]
(.onError pub (create-consumer :on-error consumer-fn))))
(defn set-on-timeout-event-consumer!
[^TimeLimiter limiter consumer-fn]
"set a consumer to consume `on-timeout` event which emitted when execution timeout from time limiter.
`consumer-fn` accepts a function which takes no arguments.
Please note that in `consumer-fn` you can get the time limiter name and the creation time of the
consumed event by accessing `*time-limiter-name*` and `*creation-time*` under this namespace."
(let [pub (.getEventPublisher limiter)]
(.onTimeout pub (create-consumer :on-timeout consumer-fn))))
(defn set-on-all-event-consumer!
[^TimeLimiter limiter consumer-fn-map]
"set a consumer to consume all available events emitted from time limiter.
`consumer-fn-map` accepts a map which contains following key and function pairs:
* `on-success` accepts a function which takes no arguments
* `on-error` accepts a function which takes Throwable as a argument
* `on-timeout` accepts a function which takes no arguments
Please note that in `consumer-fn` you can get the time limiter name and the creation time of the
consumed event by accessing `*time-limiter-name*` and `*creation-time*` under this namespace."
(let [pub (.getEventPublisher limiter)]
(.onEvent pub (create-consumer consumer-fn-map))))
| |
4507104a208ff689ac4af29cb2e5e1b2d9b5b13502dd4cef301d513aa7dc9022 | okuoku/nausicaa | make-inspector.sps | ;;;!mosh
-*- coding : utf-8 - unix -*-
;;;
Part of : / Sqlite
;;;Contents: foreign library inspection generator
Date : Fri Nov 27 , 2009
;;;
;;;Abstract
;;;
;;;
;;;
Copyright ( c ) 2009 , 2010 < >
;;;
;;;This program is free software: you can redistribute it and/or modify
;;;it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or ( at
;;;your option) any later version.
;;;
;;;This program is distributed in the hope that it will be useful, but
;;;WITHOUT ANY WARRANTY; without even the implied warranty of
;;;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details .
;;;
You should have received a copy of the GNU General Public License
;;;along with this program. If not, see </>.
;;;
(import (nausicaa)
(foreign ffi inspector-maker))
;;;; data types inspection
(define-c-type sqlite3_int64 signed-int)
(define-c-type sqlite3_uint64 unsigned-int)
;;;; data structures inspection
(define-c-struct sqlite3_file
"sqlite3_file"
(pointer pMethods))
(define-c-struct sqlite3_io_methods
"sqlite3_io_methods"
(signed-int iVersion)
(pointer xClose)
(pointer xRead)
(pointer xWrite)
(pointer xTruncate)
(pointer xSync)
(pointer xFileSize)
(pointer xLock)
(pointer xUnlock)
(pointer xCheckReservedLock)
(pointer xFileControl)
(pointer xSectorSize)
(pointer xDeviceCharacteristics))
(define-c-struct sqlite3_vfs
"sqlite3_vfs"
(signed-int iVersion)
(signed-int szOsFile)
(signed-int mxPathname)
(pointer pNext)
(pointer zName)
(pointer pAppData)
(pointer xOpen)
(pointer xDelete)
(pointer xAccess)
(pointer xFullPathname)
(pointer xDlOpen)
(pointer xDlError)
(pointer xDlSym)
(pointer xDlClose)
(pointer xRandomness)
(pointer xSleep)
(pointer xCurrentTime)
(pointer xGetLastError))
(define-c-struct sqlite3_mem_methods
"sqlite3_mem_methods"
(pointer xMalloc)
(pointer xFree)
(pointer xRealloc)
(pointer xSize)
(pointer xRoundup)
(pointer xInit)
(pointer xShutdown)
(pointer pAppData))
(define-c-struct sqlite3_mutex_methods
"sqlite3_mutex_methods"
(pointer xMutexInit)
(pointer xMutexEnd)
(pointer xMutexAlloc)
(pointer xMutexFree)
(pointer xMutexEnter)
(pointer xMutexTry)
(pointer xMutexLeave)
(pointer xMutexHeld)
(pointer xMutexNotheld))
(define-c-struct sqlite3_pcache_methods
"sqlite3_pcache_methods"
(pointer pArg)
(pointer xInit)
(pointer xShutdown)
(pointer xCreate)
(pointer xCachesize)
(pointer xPagecount)
(pointer xFetch)
(pointer xUnpin)
(pointer xRekey)
(pointer xTruncate)
(pointer xDestroy))
;;;; constants
(sizeof-lib
(define SQLITE_ENABLE_COLUMN_METADATA ^SQLITE_ENABLE_COLUMN_METADATA^)
(define SQLITE_DEBUG ^SQLITE_DEBUG^)
(define SQLITE_ENABLE_UNLOCK_NOTIFY ^SQLITE_ENABLE_UNLOCK_NOTIFY^))
(sizeof-lib-exports
SQLITE_ENABLE_COLUMN_METADATA
SQLITE_DEBUG
SQLITE_ENABLE_UNLOCK_NOTIFY)
(define-c-string-defines "version strings"
SQLITE_VERSION
SQLITE_SOURCE_ID)
(define-c-defines "version numbers"
SQLITE_VERSION_NUMBER)
(define-c-defines "error codes"
SQLITE_OK
SQLITE_ERROR
SQLITE_INTERNAL
SQLITE_PERM
SQLITE_ABORT
SQLITE_BUSY
SQLITE_LOCKED
SQLITE_NOMEM
SQLITE_READONLY
SQLITE_INTERRUPT
SQLITE_IOERR
SQLITE_CORRUPT
SQLITE_NOTFOUND
SQLITE_FULL
SQLITE_CANTOPEN
SQLITE_PROTOCOL
SQLITE_EMPTY
SQLITE_SCHEMA
SQLITE_TOOBIG
SQLITE_CONSTRAINT
SQLITE_MISMATCH
SQLITE_MISUSE
SQLITE_NOLFS
SQLITE_AUTH
SQLITE_FORMAT
SQLITE_RANGE
SQLITE_NOTADB
SQLITE_ROW
SQLITE_DONE)
(define-c-defines "extended error codes"
SQLITE_IOERR_READ
SQLITE_IOERR_SHORT_READ
SQLITE_IOERR_WRITE
SQLITE_IOERR_FSYNC
SQLITE_IOERR_DIR_FSYNC
SQLITE_IOERR_TRUNCATE
SQLITE_IOERR_FSTAT
SQLITE_IOERR_UNLOCK
SQLITE_IOERR_RDLOCK
SQLITE_IOERR_DELETE
SQLITE_IOERR_BLOCKED
SQLITE_IOERR_NOMEM
SQLITE_IOERR_ACCESS
SQLITE_IOERR_CHECKRESERVEDLOCK
SQLITE_IOERR_LOCK
SQLITE_IOERR_CLOSE
SQLITE_IOERR_DIR_CLOSE
SQLITE_LOCKED_SHAREDCACHE)
(define-c-defines "file open flags"
SQLITE_OPEN_READONLY
SQLITE_OPEN_READWRITE
SQLITE_OPEN_CREATE
SQLITE_OPEN_DELETEONCLOSE
SQLITE_OPEN_EXCLUSIVE
SQLITE_OPEN_MAIN_DB
SQLITE_OPEN_TEMP_DB
SQLITE_OPEN_TRANSIENT_DB
SQLITE_OPEN_MAIN_JOURNAL
SQLITE_OPEN_TEMP_JOURNAL
SQLITE_OPEN_SUBJOURNAL
SQLITE_OPEN_MASTER_JOURNAL
SQLITE_OPEN_NOMUTEX
SQLITE_OPEN_FULLMUTEX
SQLITE_OPEN_SHAREDCACHE
SQLITE_OPEN_PRIVATECACHE)
(define-c-defines "device characteristics"
SQLITE_IOCAP_ATOMIC
SQLITE_IOCAP_ATOMIC512
SQLITE_IOCAP_ATOMIC1K
SQLITE_IOCAP_ATOMIC2K
SQLITE_IOCAP_ATOMIC4K
SQLITE_IOCAP_ATOMIC8K
SQLITE_IOCAP_ATOMIC16K
SQLITE_IOCAP_ATOMIC32K
SQLITE_IOCAP_ATOMIC64K
SQLITE_IOCAP_SAFE_APPEND
SQLITE_IOCAP_SEQUENTIAL)
(define-c-defines "file locking levels"
SQLITE_LOCK_NONE
SQLITE_LOCK_SHARED
SQLITE_LOCK_RESERVED
SQLITE_LOCK_PENDING
SQLITE_LOCK_EXCLUSIVE)
(define-c-defines "synchronisation type flags"
SQLITE_SYNC_NORMAL
SQLITE_SYNC_FULL
SQLITE_SYNC_DATAONLY)
(define-c-defines "file control opcodes"
SQLITE_FCNTL_LOCKSTATE
SQLITE_GET_LOCKPROXYFILE
SQLITE_SET_LOCKPROXYFILE
SQLITE_LAST_ERRNO)
(define-c-defines "flags for the xAccess method"
SQLITE_ACCESS_EXISTS
SQLITE_ACCESS_READWRITE
SQLITE_ACCESS_READ)
(define-c-defines "configuration options"
SQLITE_CONFIG_SINGLETHREAD
SQLITE_CONFIG_MULTITHREAD
SQLITE_CONFIG_SERIALIZED
SQLITE_CONFIG_MALLOC
SQLITE_CONFIG_GETMALLOC
SQLITE_CONFIG_SCRATCH
SQLITE_CONFIG_PAGECACHE
SQLITE_CONFIG_HEAP
SQLITE_CONFIG_MEMSTATUS
SQLITE_CONFIG_MUTEX
SQLITE_CONFIG_GETMUTEX
SQLITE_CONFIG_CHUNKALLOC
SQLITE_CONFIG_LOOKASIDE
SQLITE_CONFIG_PCACHE
SQLITE_CONFIG_GETPCACHE)
(define-c-defines "other configuration options"
SQLITE_DBCONFIG_LOOKASIDE)
(define-c-defines "authoriser return codes"
SQLITE_DENY
SQLITE_IGNORE)
(define-c-defines "authoriser action codes"
SQLITE_CREATE_INDEX
SQLITE_CREATE_TABLE
SQLITE_CREATE_TEMP_INDEX
SQLITE_CREATE_TEMP_TABLE
SQLITE_CREATE_TEMP_TRIGGER
SQLITE_CREATE_TEMP_VIEW
SQLITE_CREATE_TRIGGER
SQLITE_CREATE_VIEW
SQLITE_DELETE
SQLITE_DROP_INDEX
SQLITE_DROP_TABLE
SQLITE_DROP_TEMP_INDEX
SQLITE_DROP_TEMP_TABLE
SQLITE_DROP_TEMP_TRIGGER
SQLITE_DROP_TEMP_VIEW
SQLITE_DROP_TRIGGER
SQLITE_DROP_VIEW
SQLITE_INSERT
SQLITE_PRAGMA
SQLITE_READ
SQLITE_SELECT
SQLITE_TRANSACTION
SQLITE_UPDATE
SQLITE_ATTACH
SQLITE_DETACH
SQLITE_ALTER_TABLE
SQLITE_REINDEX
SQLITE_ANALYZE
SQLITE_CREATE_VTABLE
SQLITE_DROP_VTABLE
SQLITE_FUNCTION
SQLITE_SAVEPOINT
SQLITE_COPY)
(define-c-defines "run-time limit categories"
SQLITE_LIMIT_LENGTH
SQLITE_LIMIT_SQL_LENGTH
SQLITE_LIMIT_COLUMN
SQLITE_LIMIT_EXPR_DEPTH
SQLITE_LIMIT_COMPOUND_SELECT
SQLITE_LIMIT_VDBE_OP
SQLITE_LIMIT_FUNCTION_ARG
SQLITE_LIMIT_ATTACHED
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
SQLITE_LIMIT_VARIABLE_NUMBER
SQLITE_LIMIT_TRIGGER_DEPTH)
(define-c-defines "fundamental data types"
SQLITE_INTEGER
SQLITE_FLOAT
SQLITE_BLOB
SQLITE_NULL
SQLITE_TEXT
SQLITE3_TEXT)
(define-c-defines "text encodings"
SQLITE_UTF8
SQLITE_UTF16LE
SQLITE_UTF16BE
SQLITE_UTF16
SQLITE_ANY
SQLITE_UTF16_ALIGNED)
(define-c-defines "special constructor behaviour"
SQLITE_STATIC
SQLITE_TRANSIENT)
(define-c-defines "mutex types"
SQLITE_MUTEX_FAST
SQLITE_MUTEX_RECURSIVE
SQLITE_MUTEX_STATIC_MASTER
SQLITE_MUTEX_STATIC_MEM
SQLITE_MUTEX_STATIC_MEM2
SQLITE_MUTEX_STATIC_OPEN
SQLITE_MUTEX_STATIC_PRNG
SQLITE_MUTEX_STATIC_LRU
SQLITE_MUTEX_STATIC_LRU2)
(define-c-defines "test operation codes"
SQLITE_TESTCTRL_PRNG_SAVE
SQLITE_TESTCTRL_PRNG_RESTORE
SQLITE_TESTCTRL_PRNG_RESET
SQLITE_TESTCTRL_BITVEC_TEST
SQLITE_TESTCTRL_FAULT_INSTALL
SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
SQLITE_TESTCTRL_PENDING_BYTE
SQLITE_TESTCTRL_ASSERT
SQLITE_TESTCTRL_ALWAYS
SQLITE_TESTCTRL_RESERVE)
(define-c-defines "status parameters"
SQLITE_STATUS_MEMORY_USED
SQLITE_STATUS_PAGECACHE_USED
SQLITE_STATUS_PAGECACHE_OVERFLOW
SQLITE_STATUS_SCRATCH_USED
SQLITE_STATUS_SCRATCH_OVERFLOW
SQLITE_STATUS_MALLOC_SIZE
SQLITE_STATUS_PARSER_STACK
SQLITE_STATUS_PAGECACHE_SIZE
SQLITE_STATUS_SCRATCH_SIZE
SQLITE_DBSTATUS_LOOKASIDE_USED
SQLITE_STMTSTATUS_FULLSCAN_STEP
SQLITE_STMTSTATUS_SORT)
;;;; done
(define-shared-object sqlite libsqlite3.so)
(define sqlite-library-spec
'(foreign databases sqlite sizeof))
(autoconf-lib-write "configuration/sqlite-inspector.m4" sqlite-library-spec
"NAUSICAA_SQLITE")
(sizeof-lib-write "src/libraries/foreign/databases/sqlite/sizeof.sls.in" sqlite-library-spec)
;;; end of file
| null | https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/sqlite/make-inspector.sps | scheme | !mosh
Contents: foreign library inspection generator
Abstract
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
along with this program. If not, see </>.
data types inspection
data structures inspection
constants
done
end of file | -*- coding : utf-8 - unix -*-
Part of : / Sqlite
Date : Fri Nov 27 , 2009
Copyright ( c ) 2009 , 2010 < >
the Free Software Foundation , either version 3 of the License , or ( at
General Public License for more details .
You should have received a copy of the GNU General Public License
(import (nausicaa)
(foreign ffi inspector-maker))
(define-c-type sqlite3_int64 signed-int)
(define-c-type sqlite3_uint64 unsigned-int)
(define-c-struct sqlite3_file
"sqlite3_file"
(pointer pMethods))
(define-c-struct sqlite3_io_methods
"sqlite3_io_methods"
(signed-int iVersion)
(pointer xClose)
(pointer xRead)
(pointer xWrite)
(pointer xTruncate)
(pointer xSync)
(pointer xFileSize)
(pointer xLock)
(pointer xUnlock)
(pointer xCheckReservedLock)
(pointer xFileControl)
(pointer xSectorSize)
(pointer xDeviceCharacteristics))
(define-c-struct sqlite3_vfs
"sqlite3_vfs"
(signed-int iVersion)
(signed-int szOsFile)
(signed-int mxPathname)
(pointer pNext)
(pointer zName)
(pointer pAppData)
(pointer xOpen)
(pointer xDelete)
(pointer xAccess)
(pointer xFullPathname)
(pointer xDlOpen)
(pointer xDlError)
(pointer xDlSym)
(pointer xDlClose)
(pointer xRandomness)
(pointer xSleep)
(pointer xCurrentTime)
(pointer xGetLastError))
(define-c-struct sqlite3_mem_methods
"sqlite3_mem_methods"
(pointer xMalloc)
(pointer xFree)
(pointer xRealloc)
(pointer xSize)
(pointer xRoundup)
(pointer xInit)
(pointer xShutdown)
(pointer pAppData))
(define-c-struct sqlite3_mutex_methods
"sqlite3_mutex_methods"
(pointer xMutexInit)
(pointer xMutexEnd)
(pointer xMutexAlloc)
(pointer xMutexFree)
(pointer xMutexEnter)
(pointer xMutexTry)
(pointer xMutexLeave)
(pointer xMutexHeld)
(pointer xMutexNotheld))
(define-c-struct sqlite3_pcache_methods
"sqlite3_pcache_methods"
(pointer pArg)
(pointer xInit)
(pointer xShutdown)
(pointer xCreate)
(pointer xCachesize)
(pointer xPagecount)
(pointer xFetch)
(pointer xUnpin)
(pointer xRekey)
(pointer xTruncate)
(pointer xDestroy))
(sizeof-lib
(define SQLITE_ENABLE_COLUMN_METADATA ^SQLITE_ENABLE_COLUMN_METADATA^)
(define SQLITE_DEBUG ^SQLITE_DEBUG^)
(define SQLITE_ENABLE_UNLOCK_NOTIFY ^SQLITE_ENABLE_UNLOCK_NOTIFY^))
(sizeof-lib-exports
SQLITE_ENABLE_COLUMN_METADATA
SQLITE_DEBUG
SQLITE_ENABLE_UNLOCK_NOTIFY)
(define-c-string-defines "version strings"
SQLITE_VERSION
SQLITE_SOURCE_ID)
(define-c-defines "version numbers"
SQLITE_VERSION_NUMBER)
(define-c-defines "error codes"
SQLITE_OK
SQLITE_ERROR
SQLITE_INTERNAL
SQLITE_PERM
SQLITE_ABORT
SQLITE_BUSY
SQLITE_LOCKED
SQLITE_NOMEM
SQLITE_READONLY
SQLITE_INTERRUPT
SQLITE_IOERR
SQLITE_CORRUPT
SQLITE_NOTFOUND
SQLITE_FULL
SQLITE_CANTOPEN
SQLITE_PROTOCOL
SQLITE_EMPTY
SQLITE_SCHEMA
SQLITE_TOOBIG
SQLITE_CONSTRAINT
SQLITE_MISMATCH
SQLITE_MISUSE
SQLITE_NOLFS
SQLITE_AUTH
SQLITE_FORMAT
SQLITE_RANGE
SQLITE_NOTADB
SQLITE_ROW
SQLITE_DONE)
(define-c-defines "extended error codes"
SQLITE_IOERR_READ
SQLITE_IOERR_SHORT_READ
SQLITE_IOERR_WRITE
SQLITE_IOERR_FSYNC
SQLITE_IOERR_DIR_FSYNC
SQLITE_IOERR_TRUNCATE
SQLITE_IOERR_FSTAT
SQLITE_IOERR_UNLOCK
SQLITE_IOERR_RDLOCK
SQLITE_IOERR_DELETE
SQLITE_IOERR_BLOCKED
SQLITE_IOERR_NOMEM
SQLITE_IOERR_ACCESS
SQLITE_IOERR_CHECKRESERVEDLOCK
SQLITE_IOERR_LOCK
SQLITE_IOERR_CLOSE
SQLITE_IOERR_DIR_CLOSE
SQLITE_LOCKED_SHAREDCACHE)
(define-c-defines "file open flags"
SQLITE_OPEN_READONLY
SQLITE_OPEN_READWRITE
SQLITE_OPEN_CREATE
SQLITE_OPEN_DELETEONCLOSE
SQLITE_OPEN_EXCLUSIVE
SQLITE_OPEN_MAIN_DB
SQLITE_OPEN_TEMP_DB
SQLITE_OPEN_TRANSIENT_DB
SQLITE_OPEN_MAIN_JOURNAL
SQLITE_OPEN_TEMP_JOURNAL
SQLITE_OPEN_SUBJOURNAL
SQLITE_OPEN_MASTER_JOURNAL
SQLITE_OPEN_NOMUTEX
SQLITE_OPEN_FULLMUTEX
SQLITE_OPEN_SHAREDCACHE
SQLITE_OPEN_PRIVATECACHE)
(define-c-defines "device characteristics"
SQLITE_IOCAP_ATOMIC
SQLITE_IOCAP_ATOMIC512
SQLITE_IOCAP_ATOMIC1K
SQLITE_IOCAP_ATOMIC2K
SQLITE_IOCAP_ATOMIC4K
SQLITE_IOCAP_ATOMIC8K
SQLITE_IOCAP_ATOMIC16K
SQLITE_IOCAP_ATOMIC32K
SQLITE_IOCAP_ATOMIC64K
SQLITE_IOCAP_SAFE_APPEND
SQLITE_IOCAP_SEQUENTIAL)
(define-c-defines "file locking levels"
SQLITE_LOCK_NONE
SQLITE_LOCK_SHARED
SQLITE_LOCK_RESERVED
SQLITE_LOCK_PENDING
SQLITE_LOCK_EXCLUSIVE)
(define-c-defines "synchronisation type flags"
SQLITE_SYNC_NORMAL
SQLITE_SYNC_FULL
SQLITE_SYNC_DATAONLY)
(define-c-defines "file control opcodes"
SQLITE_FCNTL_LOCKSTATE
SQLITE_GET_LOCKPROXYFILE
SQLITE_SET_LOCKPROXYFILE
SQLITE_LAST_ERRNO)
(define-c-defines "flags for the xAccess method"
SQLITE_ACCESS_EXISTS
SQLITE_ACCESS_READWRITE
SQLITE_ACCESS_READ)
(define-c-defines "configuration options"
SQLITE_CONFIG_SINGLETHREAD
SQLITE_CONFIG_MULTITHREAD
SQLITE_CONFIG_SERIALIZED
SQLITE_CONFIG_MALLOC
SQLITE_CONFIG_GETMALLOC
SQLITE_CONFIG_SCRATCH
SQLITE_CONFIG_PAGECACHE
SQLITE_CONFIG_HEAP
SQLITE_CONFIG_MEMSTATUS
SQLITE_CONFIG_MUTEX
SQLITE_CONFIG_GETMUTEX
SQLITE_CONFIG_CHUNKALLOC
SQLITE_CONFIG_LOOKASIDE
SQLITE_CONFIG_PCACHE
SQLITE_CONFIG_GETPCACHE)
(define-c-defines "other configuration options"
SQLITE_DBCONFIG_LOOKASIDE)
(define-c-defines "authoriser return codes"
SQLITE_DENY
SQLITE_IGNORE)
(define-c-defines "authoriser action codes"
SQLITE_CREATE_INDEX
SQLITE_CREATE_TABLE
SQLITE_CREATE_TEMP_INDEX
SQLITE_CREATE_TEMP_TABLE
SQLITE_CREATE_TEMP_TRIGGER
SQLITE_CREATE_TEMP_VIEW
SQLITE_CREATE_TRIGGER
SQLITE_CREATE_VIEW
SQLITE_DELETE
SQLITE_DROP_INDEX
SQLITE_DROP_TABLE
SQLITE_DROP_TEMP_INDEX
SQLITE_DROP_TEMP_TABLE
SQLITE_DROP_TEMP_TRIGGER
SQLITE_DROP_TEMP_VIEW
SQLITE_DROP_TRIGGER
SQLITE_DROP_VIEW
SQLITE_INSERT
SQLITE_PRAGMA
SQLITE_READ
SQLITE_SELECT
SQLITE_TRANSACTION
SQLITE_UPDATE
SQLITE_ATTACH
SQLITE_DETACH
SQLITE_ALTER_TABLE
SQLITE_REINDEX
SQLITE_ANALYZE
SQLITE_CREATE_VTABLE
SQLITE_DROP_VTABLE
SQLITE_FUNCTION
SQLITE_SAVEPOINT
SQLITE_COPY)
(define-c-defines "run-time limit categories"
SQLITE_LIMIT_LENGTH
SQLITE_LIMIT_SQL_LENGTH
SQLITE_LIMIT_COLUMN
SQLITE_LIMIT_EXPR_DEPTH
SQLITE_LIMIT_COMPOUND_SELECT
SQLITE_LIMIT_VDBE_OP
SQLITE_LIMIT_FUNCTION_ARG
SQLITE_LIMIT_ATTACHED
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
SQLITE_LIMIT_VARIABLE_NUMBER
SQLITE_LIMIT_TRIGGER_DEPTH)
(define-c-defines "fundamental data types"
SQLITE_INTEGER
SQLITE_FLOAT
SQLITE_BLOB
SQLITE_NULL
SQLITE_TEXT
SQLITE3_TEXT)
(define-c-defines "text encodings"
SQLITE_UTF8
SQLITE_UTF16LE
SQLITE_UTF16BE
SQLITE_UTF16
SQLITE_ANY
SQLITE_UTF16_ALIGNED)
(define-c-defines "special constructor behaviour"
SQLITE_STATIC
SQLITE_TRANSIENT)
(define-c-defines "mutex types"
SQLITE_MUTEX_FAST
SQLITE_MUTEX_RECURSIVE
SQLITE_MUTEX_STATIC_MASTER
SQLITE_MUTEX_STATIC_MEM
SQLITE_MUTEX_STATIC_MEM2
SQLITE_MUTEX_STATIC_OPEN
SQLITE_MUTEX_STATIC_PRNG
SQLITE_MUTEX_STATIC_LRU
SQLITE_MUTEX_STATIC_LRU2)
(define-c-defines "test operation codes"
SQLITE_TESTCTRL_PRNG_SAVE
SQLITE_TESTCTRL_PRNG_RESTORE
SQLITE_TESTCTRL_PRNG_RESET
SQLITE_TESTCTRL_BITVEC_TEST
SQLITE_TESTCTRL_FAULT_INSTALL
SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
SQLITE_TESTCTRL_PENDING_BYTE
SQLITE_TESTCTRL_ASSERT
SQLITE_TESTCTRL_ALWAYS
SQLITE_TESTCTRL_RESERVE)
(define-c-defines "status parameters"
SQLITE_STATUS_MEMORY_USED
SQLITE_STATUS_PAGECACHE_USED
SQLITE_STATUS_PAGECACHE_OVERFLOW
SQLITE_STATUS_SCRATCH_USED
SQLITE_STATUS_SCRATCH_OVERFLOW
SQLITE_STATUS_MALLOC_SIZE
SQLITE_STATUS_PARSER_STACK
SQLITE_STATUS_PAGECACHE_SIZE
SQLITE_STATUS_SCRATCH_SIZE
SQLITE_DBSTATUS_LOOKASIDE_USED
SQLITE_STMTSTATUS_FULLSCAN_STEP
SQLITE_STMTSTATUS_SORT)
(define-shared-object sqlite libsqlite3.so)
(define sqlite-library-spec
'(foreign databases sqlite sizeof))
(autoconf-lib-write "configuration/sqlite-inspector.m4" sqlite-library-spec
"NAUSICAA_SQLITE")
(sizeof-lib-write "src/libraries/foreign/databases/sqlite/sizeof.sls.in" sqlite-library-spec)
|
dbf0753df32565ad3284c17369a578a84e0450aa0e749b6d3ace5a2cbf4f38d7 | willowtreeapps/wombats-api | helpers.clj | (ns wombats.daos.helpers
(:require [datomic.api :as d]))
(defn get-fn
"Helper function used to pull the correct dao out of context"
[fn-key context]
(let [dao-fn (fn-key (:wombats.interceptors.dao/daos context))]
(if dao-fn
dao-fn
(throw (Exception. (str "Dao function " fn-key " was not found in the dao map"))))))
(defn gen-id
"Generates a uuid string to use with db entities"
[]
(str (java.util.UUID/randomUUID)))
(defn get-entity-by-prop
"Helper function for pulling an entity out of datomic.
It seems that if [*] is passed to pull and the value you are
searching for the result will be '{:db/id nil}'. This helper
will normalize all results to 'nil' if the record is not found."
([conn prop value]
(get-entity-by-prop conn prop value '[*]))
([conn prop value display-props]
(let [result (d/pull (d/db conn) display-props [prop value])
no-result (or (= result nil)
(and (= display-props '[*])
(= nil (:db/id result))))]
(if no-result nil result))))
(defn get-entities-by-prop
"Returns a collection of entites that contain a given prop"
([conn prop]
(get-entities-by-prop conn prop '[*]))
([conn prop display-props]
(let [db (d/db conn)
eids (apply concat
(d/q '[:find ?e
:in $ ?entity-prop
:where [?e ?entity-prop]]
db
prop))]
(remove nil?
(d/pull-many db
display-props
eids)))))
(defn get-entity-id
"Returns the entity id associated with a given unique prop / value"
[conn prop value]
(ffirst
(d/q '[:find ?e
:in $ ?prop-name ?prop-value
:where [?e ?prop-name ?prop-value]]
(d/db conn)
prop
value)))
(defn retract-entity-by-prop
([conn prop value]
(retract-entity-by-prop conn prop value "Entity removed"))
([conn prop value msg]
(let [entity-id (get-entity-id conn prop value)]
(future
(if entity-id
(do
@(d/transact-async conn [[:db.fn/retractEntity entity-id]])
msg)
msg)))))
| null | https://raw.githubusercontent.com/willowtreeapps/wombats-api/738e4cc8d7011998695ec85e663f650be71f60ae/src/wombats/daos/helpers.clj | clojure | (ns wombats.daos.helpers
(:require [datomic.api :as d]))
(defn get-fn
"Helper function used to pull the correct dao out of context"
[fn-key context]
(let [dao-fn (fn-key (:wombats.interceptors.dao/daos context))]
(if dao-fn
dao-fn
(throw (Exception. (str "Dao function " fn-key " was not found in the dao map"))))))
(defn gen-id
"Generates a uuid string to use with db entities"
[]
(str (java.util.UUID/randomUUID)))
(defn get-entity-by-prop
"Helper function for pulling an entity out of datomic.
It seems that if [*] is passed to pull and the value you are
searching for the result will be '{:db/id nil}'. This helper
will normalize all results to 'nil' if the record is not found."
([conn prop value]
(get-entity-by-prop conn prop value '[*]))
([conn prop value display-props]
(let [result (d/pull (d/db conn) display-props [prop value])
no-result (or (= result nil)
(and (= display-props '[*])
(= nil (:db/id result))))]
(if no-result nil result))))
(defn get-entities-by-prop
"Returns a collection of entites that contain a given prop"
([conn prop]
(get-entities-by-prop conn prop '[*]))
([conn prop display-props]
(let [db (d/db conn)
eids (apply concat
(d/q '[:find ?e
:in $ ?entity-prop
:where [?e ?entity-prop]]
db
prop))]
(remove nil?
(d/pull-many db
display-props
eids)))))
(defn get-entity-id
"Returns the entity id associated with a given unique prop / value"
[conn prop value]
(ffirst
(d/q '[:find ?e
:in $ ?prop-name ?prop-value
:where [?e ?prop-name ?prop-value]]
(d/db conn)
prop
value)))
(defn retract-entity-by-prop
([conn prop value]
(retract-entity-by-prop conn prop value "Entity removed"))
([conn prop value msg]
(let [entity-id (get-entity-id conn prop value)]
(future
(if entity-id
(do
@(d/transact-async conn [[:db.fn/retractEntity entity-id]])
msg)
msg)))))
| |
08fcb65f794788236b85e2eaedc8998b7978b65f583e5ca580b1f9707c400639 | basho/riak_test | gh_riak_core_176.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2012 Basho Technologies , Inc.
%%
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.
%%
%% -------------------------------------------------------------------
-module(gh_riak_core_176).
-behavior(riak_test).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
confirm() ->
Nodes = rt:deploy_nodes(3),
[Node1, Node2, Node3] = Nodes,
Nodes12 = [Node1, Node2],
Nodes123 = Nodes,
Stolen from riak_core_handoff_sender.erl
[_Name,Host] = string:tokens(atom_to_list(Node2), "@"),
%% Get IP associated with node name
{ok, NodeIP} = inet:getaddr(Host, inet),
%% Find alternative IP
{ok, IfAddrs} = inet:getifaddrs(),
Addrs =
lists:flatmap(
fun({_If, Props}) ->
[Addr || {addr, Addr} <- Props,
size(Addr) == 4]
end, IfAddrs),
AlternateIP = ip_tuple_to_string(hd(Addrs -- [NodeIP])),
lager:info("Change ~p handoff_ip from ~p to ~p",
[Node2, NodeIP, AlternateIP]),
NewConfig = [{riak_core, [{handoff_ip, AlternateIP}]}],
rt:update_app_config(Node2, NewConfig),
rt:wait_for_service(Node2, riak_kv),
lager:info("Write data to the cluster"),
rt:systest_write(Node1, 100),
lager:info("Join ~p to the cluster and wait for handoff to finish",
[Node2]),
rt:join(Node2, Node1),
?assertEqual(ok, rt:wait_until_nodes_ready(Nodes12)),
?assertEqual(ok, rt:wait_until_no_pending_changes(Nodes12)),
rt:wait_until_nodes_agree_about_ownership(Nodes12),
Check 0.0.0.0 address works
lager:info("Change ~p handoff_ip to \"0.0.0.0\"", [Node3]),
rt:update_app_config(Node3,
[{riak_core, [{handoff_ip, "0.0.0.0"}]}]),
lager:info("Join ~p to the cluster and wait for handoff to finish",
[Node3]),
rt:wait_for_service(Node3, riak_kv),
rt:join(Node3, Node1),
?assertEqual(ok, rt:wait_until_nodes_ready(Nodes123)),
?assertEqual(ok, rt:wait_until_no_pending_changes(Nodes123)),
rt:wait_until_nodes_agree_about_ownership(Nodes123),
lager:info("Test gh_riak_core_176 passed"),
pass.
ip_tuple_to_string(T) ->
L = tuple_to_list(T),
string:join([integer_to_list(X) || X <- L], ".").
| null | https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/gh_riak_core_176.erl | erlang | -------------------------------------------------------------------
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.
-------------------------------------------------------------------
Get IP associated with node name
Find alternative IP | Copyright ( c ) 2012 Basho Technologies , Inc.
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(gh_riak_core_176).
-behavior(riak_test).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
confirm() ->
Nodes = rt:deploy_nodes(3),
[Node1, Node2, Node3] = Nodes,
Nodes12 = [Node1, Node2],
Nodes123 = Nodes,
Stolen from riak_core_handoff_sender.erl
[_Name,Host] = string:tokens(atom_to_list(Node2), "@"),
{ok, NodeIP} = inet:getaddr(Host, inet),
{ok, IfAddrs} = inet:getifaddrs(),
Addrs =
lists:flatmap(
fun({_If, Props}) ->
[Addr || {addr, Addr} <- Props,
size(Addr) == 4]
end, IfAddrs),
AlternateIP = ip_tuple_to_string(hd(Addrs -- [NodeIP])),
lager:info("Change ~p handoff_ip from ~p to ~p",
[Node2, NodeIP, AlternateIP]),
NewConfig = [{riak_core, [{handoff_ip, AlternateIP}]}],
rt:update_app_config(Node2, NewConfig),
rt:wait_for_service(Node2, riak_kv),
lager:info("Write data to the cluster"),
rt:systest_write(Node1, 100),
lager:info("Join ~p to the cluster and wait for handoff to finish",
[Node2]),
rt:join(Node2, Node1),
?assertEqual(ok, rt:wait_until_nodes_ready(Nodes12)),
?assertEqual(ok, rt:wait_until_no_pending_changes(Nodes12)),
rt:wait_until_nodes_agree_about_ownership(Nodes12),
Check 0.0.0.0 address works
lager:info("Change ~p handoff_ip to \"0.0.0.0\"", [Node3]),
rt:update_app_config(Node3,
[{riak_core, [{handoff_ip, "0.0.0.0"}]}]),
lager:info("Join ~p to the cluster and wait for handoff to finish",
[Node3]),
rt:wait_for_service(Node3, riak_kv),
rt:join(Node3, Node1),
?assertEqual(ok, rt:wait_until_nodes_ready(Nodes123)),
?assertEqual(ok, rt:wait_until_no_pending_changes(Nodes123)),
rt:wait_until_nodes_agree_about_ownership(Nodes123),
lager:info("Test gh_riak_core_176 passed"),
pass.
ip_tuple_to_string(T) ->
L = tuple_to_list(T),
string:join([integer_to_list(X) || X <- L], ".").
|
aa91dd464b287f3634064c2a617bcea24f84682e4560b80e652a373cec892948 | fpco/ide-backend | TestSuite.hs | module Main where
import Data.Foldable (forM_)
import Data.List (isPrefixOf)
import System.Process (readProcess)
import System.Environment
import Test.HUnit
import Test.Tasty
import IdeSession
import TestSuite.State
import TestSuite.Tests.API
import TestSuite.Tests.Autocompletion
import TestSuite.Tests.BufferMode
import TestSuite.Tests.BuildDoc
import TestSuite.Tests.BuildExe
import TestSuite.Tests.BuildLicenses
import TestSuite.Tests.C
import TestSuite.Tests.CabalMacros
import TestSuite.Tests.Compilation
import TestSuite.Tests.Compliance
import TestSuite.Tests.Concurrency
import TestSuite.Tests.Crash
import TestSuite.Tests.Debugger
import TestSuite.Tests.FFI
import TestSuite.Tests.Integration
import TestSuite.Tests.InterruptRunExe
import TestSuite.Tests.InterruptRunStmt
import TestSuite.Tests.Issues
import TestSuite.Tests.Packages
import TestSuite.Tests.Performance
import TestSuite.Tests.Pseudoterminal
import TestSuite.Tests.SessionRestart
import TestSuite.Tests.SessionState
import TestSuite.Tests.SnippetEnvironment
import TestSuite.Tests.StdIO
import TestSuite.Tests.TH
import TestSuite.Tests.TypeInformation
import TestSuite.Tests.UpdateTargets
-- | Sanity check: make sure we can communicate with the server at all
-- and that we get the expected version
testGetGhcVersion :: TestSuiteEnv -> Assertion
testGetGhcVersion env = withAvailableSession env $ \session -> do
version <- getGhcVersion session
assertEqual "" (testSuiteEnvGhcVersion env) version
allTests :: String -> TestSuiteEnv -> TestTree
allTests name env = testGroup name [
stdTest env "getGhcVersion" testGetGhcVersion
, testGroupIntegration env
, testGroupAPI env
, testGroupSessionState env
, testGroupCompilation env
, testGroupUpdateTargets env
, testGroupInterruptRunStmt env
, testGroupInterruptRunExe env
, testGroupStdIO env
, testGroupBufferMode env
, testGroupSnippetEnvironment env
, testGroupTypeInformation env
, testGroupAutocompletion env
, testGroupFFI env
, testGroupC env
, testGroupBuildExe env
, testGroupBuildDoc env
, testGroupBuildLicenses env
, testGroupCabalMacros env
, testGroupTH env
, testGroupIssues env
, testGroupPackages env
, testGroupSessionRestart env
, testGroupCrash env
, testGroupCompliance env
, testGroupDebugger env
, testGroupConcurrency env
, testGroupPerformance env
, testGroupPseudoterminal env
]
main :: IO ()
main = do
-- Yes, this is hacky, but I couldn't figure out how to easily do
-- this with tasty's API... So, instead of trying to
-- programatically modify the config, we generate arguments.
args <- getArgs
let noGhcSpecified =
"--test-74" `notElem` args &&
"--test-78" `notElem` args &&
"--test-710" `notElem` args
args' <-
if noGhcSpecified
then do
putStrLn "No GHC version specified (--test-74, --test-78, --test-710)."
putStrLn "Asking local GHC for its version, and defaulting to that."
output <- readProcess "ghc" ["--version"] ""
putStrLn output
let version = last (words output)
versionCode =
if "7.4" `isPrefixOf` version then "74" else
if "7.8" `isPrefixOf` version then "78" else
if "7.10" `isPrefixOf` version then "710" else
error ("No tests for GHC version " ++ version)
putStrLn $ "Assuming --test-" ++ versionCode
return (("--test-" ++ versionCode) : args)
else return args
-- Set GHC_PACKAGE_PATH_TEST, an environment variable used by
TestSuite . State.startNewSession . This is needed because
-- ide-backend unsets GHC_PACKAGE_PATH.
mpkgPath <- lookupEnv "GHC_PACKAGE_PATH"
forM_ mpkgPath $ setEnv "GHC_PACKAGE_PATH_TEST"
withArgs ("--no-session-reuse" : args') $ defaultMainWithIngredients ings $ testSuite $ \env ->
let TestSuiteConfig{..} = testSuiteEnvConfig env
env74 = env { testSuiteEnvGhcVersion = GHC_7_4 }
env78 = env { testSuiteEnvGhcVersion = GHC_7_8 }
env710 = env { testSuiteEnvGhcVersion = GHC_7_10 }
in testGroup "IDE backend tests" $
(if testSuiteConfigTest74 then [allTests "GHC 7.4" env74] else [])
++ (if testSuiteConfigTest78 then [allTests "GHC 7.8" env78] else [])
++ (if testSuiteConfigTest710 then [allTests "GHC 7.10" env710] else [])
where
ings = includingOptions testSuiteCommandLineOptions
: defaultIngredients
| null | https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/TestSuite/TestSuite.hs | haskell | | Sanity check: make sure we can communicate with the server at all
and that we get the expected version
Yes, this is hacky, but I couldn't figure out how to easily do
this with tasty's API... So, instead of trying to
programatically modify the config, we generate arguments.
Set GHC_PACKAGE_PATH_TEST, an environment variable used by
ide-backend unsets GHC_PACKAGE_PATH. | module Main where
import Data.Foldable (forM_)
import Data.List (isPrefixOf)
import System.Process (readProcess)
import System.Environment
import Test.HUnit
import Test.Tasty
import IdeSession
import TestSuite.State
import TestSuite.Tests.API
import TestSuite.Tests.Autocompletion
import TestSuite.Tests.BufferMode
import TestSuite.Tests.BuildDoc
import TestSuite.Tests.BuildExe
import TestSuite.Tests.BuildLicenses
import TestSuite.Tests.C
import TestSuite.Tests.CabalMacros
import TestSuite.Tests.Compilation
import TestSuite.Tests.Compliance
import TestSuite.Tests.Concurrency
import TestSuite.Tests.Crash
import TestSuite.Tests.Debugger
import TestSuite.Tests.FFI
import TestSuite.Tests.Integration
import TestSuite.Tests.InterruptRunExe
import TestSuite.Tests.InterruptRunStmt
import TestSuite.Tests.Issues
import TestSuite.Tests.Packages
import TestSuite.Tests.Performance
import TestSuite.Tests.Pseudoterminal
import TestSuite.Tests.SessionRestart
import TestSuite.Tests.SessionState
import TestSuite.Tests.SnippetEnvironment
import TestSuite.Tests.StdIO
import TestSuite.Tests.TH
import TestSuite.Tests.TypeInformation
import TestSuite.Tests.UpdateTargets
testGetGhcVersion :: TestSuiteEnv -> Assertion
testGetGhcVersion env = withAvailableSession env $ \session -> do
version <- getGhcVersion session
assertEqual "" (testSuiteEnvGhcVersion env) version
allTests :: String -> TestSuiteEnv -> TestTree
allTests name env = testGroup name [
stdTest env "getGhcVersion" testGetGhcVersion
, testGroupIntegration env
, testGroupAPI env
, testGroupSessionState env
, testGroupCompilation env
, testGroupUpdateTargets env
, testGroupInterruptRunStmt env
, testGroupInterruptRunExe env
, testGroupStdIO env
, testGroupBufferMode env
, testGroupSnippetEnvironment env
, testGroupTypeInformation env
, testGroupAutocompletion env
, testGroupFFI env
, testGroupC env
, testGroupBuildExe env
, testGroupBuildDoc env
, testGroupBuildLicenses env
, testGroupCabalMacros env
, testGroupTH env
, testGroupIssues env
, testGroupPackages env
, testGroupSessionRestart env
, testGroupCrash env
, testGroupCompliance env
, testGroupDebugger env
, testGroupConcurrency env
, testGroupPerformance env
, testGroupPseudoterminal env
]
main :: IO ()
main = do
args <- getArgs
let noGhcSpecified =
"--test-74" `notElem` args &&
"--test-78" `notElem` args &&
"--test-710" `notElem` args
args' <-
if noGhcSpecified
then do
putStrLn "No GHC version specified (--test-74, --test-78, --test-710)."
putStrLn "Asking local GHC for its version, and defaulting to that."
output <- readProcess "ghc" ["--version"] ""
putStrLn output
let version = last (words output)
versionCode =
if "7.4" `isPrefixOf` version then "74" else
if "7.8" `isPrefixOf` version then "78" else
if "7.10" `isPrefixOf` version then "710" else
error ("No tests for GHC version " ++ version)
putStrLn $ "Assuming --test-" ++ versionCode
return (("--test-" ++ versionCode) : args)
else return args
TestSuite . State.startNewSession . This is needed because
mpkgPath <- lookupEnv "GHC_PACKAGE_PATH"
forM_ mpkgPath $ setEnv "GHC_PACKAGE_PATH_TEST"
withArgs ("--no-session-reuse" : args') $ defaultMainWithIngredients ings $ testSuite $ \env ->
let TestSuiteConfig{..} = testSuiteEnvConfig env
env74 = env { testSuiteEnvGhcVersion = GHC_7_4 }
env78 = env { testSuiteEnvGhcVersion = GHC_7_8 }
env710 = env { testSuiteEnvGhcVersion = GHC_7_10 }
in testGroup "IDE backend tests" $
(if testSuiteConfigTest74 then [allTests "GHC 7.4" env74] else [])
++ (if testSuiteConfigTest78 then [allTests "GHC 7.8" env78] else [])
++ (if testSuiteConfigTest710 then [allTests "GHC 7.10" env710] else [])
where
ings = includingOptions testSuiteCommandLineOptions
: defaultIngredients
|
da0320e5973835331139923d61d30e30e9ecd181c5535db124029b784cac9851 | crclark/foundationdb-haskell | Main.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.ByteString (ByteString)
import qualified Data.Text as T
import FoundationDB.Versionstamp
import FoundationDB.Layer.Tuple.Internal
import Gauge.Main
mixedTuple :: ByteString
mixedTuple = "\SOHsome_prefix\NUL\SOHsome_other_prefix\NUL3\NUL\NUL\NUL\NUL\NUL\NUL\NUL\SOH\NUL\STX\NUL\ETX\NAK\f"
longTextTuple :: ByteString
longTextTuple =
encodeTupleElems [Text (T.replicate 80000 "a")]
main :: IO ()
main =
Gauge.Main.defaultMain
[ bgroup "bisectSize"
[ bench "bisectSize small" (nf bisectSize 1025)
, bench "bisectSize medium" (nf bisectSize 123456789012)
, bench "bisectSize large" (nf bisectSize 1234567890123454555)]
, bgroup "encodeTupleElems"
[ bench "Tuple" (nf encodeTupleElems [Tuple [Bytes "hello"]])
, bench "Bytes" (nf encodeTupleElems [Bytes "hello"])
, bench "Text" (nf encodeTupleElems [Text "hello"])
, bench "Int small pos" (nf encodeTupleElems [Int 1024])
, bench "Int small neg" (nf encodeTupleElems [Int (-1024)])
, bench "Int large pos" (nf encodeTupleElems [Int 102400000000000000])
, bench "Int large neg" (nf encodeTupleElems [Int (-102400000000000000)])
, bench "Float" (nf encodeTupleElems [Float 12.356])
, bench "Double" (nf encodeTupleElems [Double 12.356])
, bench "Bool" (nf encodeTupleElems [Bool True])
, bench "UUID" (nf encodeTupleElems [UUID 1 2 3 4])
, bench "CompleteVS"
(nf encodeTupleElems
[CompleteVS (CompleteVersionstamp
(TransactionVersionstamp 1 2)
3)])
, bench "IncompleteVS"
(nf encodeTupleElems [IncompleteVS (IncompleteVersionstamp 1)])
, bench "Mixed"
(nf encodeTupleElems
[ Bytes "some_prefix"
, Bytes "some_other_prefix"
, IncompleteVS (IncompleteVersionstamp 123)
, Int 12])
]
, bgroup "decodeTupleElems"
[ bench "Tuple" (nf decodeTupleElems "\ENQ\SOHhello\NUL\NUL")
, bench "Bytes" (nf decodeTupleElems "\SOHhello\NUL")
, bench "Text" (nf decodeTupleElems "\STXhello\NUL")
, bench "Text long" (nf decodeTupleElems longTextTuple)
, bench "Int small pos" (nf decodeTupleElems "\SYN\EOT\NUL")
, bench "Int small neg" (nf decodeTupleElems "\DC2\251\255")
, bench "Int large pos" (nf decodeTupleElems "\FS\SOHk\204A\233\NUL\NUL\NUL")
, bench "Int large neg" (nf decodeTupleElems "\f\254\148\&3\190\SYN\255\255\255")
, bench "Float" (nf decodeTupleElems " \193E\178-")
, bench "Double" (nf decodeTupleElems "!\192(\182E\161\202\192\131")
, bench "Bool" (nf decodeTupleElems "'")
, bench "UUID" (nf decodeTupleElems "0\NUL\NUL\NUL\SOH\NUL\NUL\NUL\STX\NUL\NUL\NUL\ETX\NUL\NUL\NUL\EOT")
, bench "CompleteVS" (nf decodeTupleElems "3\NUL\NUL\NUL\NUL\NUL\NUL\NUL\SOH\NUL\STX\NUL\ETX")
, bench "Mixed" (nf decodeTupleElems mixedTuple)
, bench "WPrefix" (nf (decodeTupleElemsWPrefix
"\SOHsome_prefix\NUL\SOHsome_other_prefix\NUL")
mixedTuple)
]
]
| null | https://raw.githubusercontent.com/crclark/foundationdb-haskell/510836a5fabe5b5b2dfc7e66438ded846f3ce085/bench/tuple/Main.hs | haskell | # LANGUAGE OverloadedStrings # |
module Main where
import Data.ByteString (ByteString)
import qualified Data.Text as T
import FoundationDB.Versionstamp
import FoundationDB.Layer.Tuple.Internal
import Gauge.Main
mixedTuple :: ByteString
mixedTuple = "\SOHsome_prefix\NUL\SOHsome_other_prefix\NUL3\NUL\NUL\NUL\NUL\NUL\NUL\NUL\SOH\NUL\STX\NUL\ETX\NAK\f"
longTextTuple :: ByteString
longTextTuple =
encodeTupleElems [Text (T.replicate 80000 "a")]
main :: IO ()
main =
Gauge.Main.defaultMain
[ bgroup "bisectSize"
[ bench "bisectSize small" (nf bisectSize 1025)
, bench "bisectSize medium" (nf bisectSize 123456789012)
, bench "bisectSize large" (nf bisectSize 1234567890123454555)]
, bgroup "encodeTupleElems"
[ bench "Tuple" (nf encodeTupleElems [Tuple [Bytes "hello"]])
, bench "Bytes" (nf encodeTupleElems [Bytes "hello"])
, bench "Text" (nf encodeTupleElems [Text "hello"])
, bench "Int small pos" (nf encodeTupleElems [Int 1024])
, bench "Int small neg" (nf encodeTupleElems [Int (-1024)])
, bench "Int large pos" (nf encodeTupleElems [Int 102400000000000000])
, bench "Int large neg" (nf encodeTupleElems [Int (-102400000000000000)])
, bench "Float" (nf encodeTupleElems [Float 12.356])
, bench "Double" (nf encodeTupleElems [Double 12.356])
, bench "Bool" (nf encodeTupleElems [Bool True])
, bench "UUID" (nf encodeTupleElems [UUID 1 2 3 4])
, bench "CompleteVS"
(nf encodeTupleElems
[CompleteVS (CompleteVersionstamp
(TransactionVersionstamp 1 2)
3)])
, bench "IncompleteVS"
(nf encodeTupleElems [IncompleteVS (IncompleteVersionstamp 1)])
, bench "Mixed"
(nf encodeTupleElems
[ Bytes "some_prefix"
, Bytes "some_other_prefix"
, IncompleteVS (IncompleteVersionstamp 123)
, Int 12])
]
, bgroup "decodeTupleElems"
[ bench "Tuple" (nf decodeTupleElems "\ENQ\SOHhello\NUL\NUL")
, bench "Bytes" (nf decodeTupleElems "\SOHhello\NUL")
, bench "Text" (nf decodeTupleElems "\STXhello\NUL")
, bench "Text long" (nf decodeTupleElems longTextTuple)
, bench "Int small pos" (nf decodeTupleElems "\SYN\EOT\NUL")
, bench "Int small neg" (nf decodeTupleElems "\DC2\251\255")
, bench "Int large pos" (nf decodeTupleElems "\FS\SOHk\204A\233\NUL\NUL\NUL")
, bench "Int large neg" (nf decodeTupleElems "\f\254\148\&3\190\SYN\255\255\255")
, bench "Float" (nf decodeTupleElems " \193E\178-")
, bench "Double" (nf decodeTupleElems "!\192(\182E\161\202\192\131")
, bench "Bool" (nf decodeTupleElems "'")
, bench "UUID" (nf decodeTupleElems "0\NUL\NUL\NUL\SOH\NUL\NUL\NUL\STX\NUL\NUL\NUL\ETX\NUL\NUL\NUL\EOT")
, bench "CompleteVS" (nf decodeTupleElems "3\NUL\NUL\NUL\NUL\NUL\NUL\NUL\SOH\NUL\STX\NUL\ETX")
, bench "Mixed" (nf decodeTupleElems mixedTuple)
, bench "WPrefix" (nf (decodeTupleElemsWPrefix
"\SOHsome_prefix\NUL\SOHsome_other_prefix\NUL")
mixedTuple)
]
]
|
a982030422ced4aabd083b821a546e64dc64b2b8eff69adc66a8bf5a16221596 | clojure-interop/aws-api | AmazonTranscribeAsyncClient.clj | (ns com.amazonaws.services.transcribe.AmazonTranscribeAsyncClient
"Client for accessing Amazon Transcribe Service asynchronously. Each asynchronous method will return a Java Future
overloads which accept an AsyncHandler can be used to receive
notification when an asynchronous operation completes.
Operations and objects for transcribing speech to text."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.transcribe AmazonTranscribeAsyncClient]))
(defn *async-builder
"returns: `com.amazonaws.services.transcribe.AmazonTranscribeAsyncClientBuilder`"
(^com.amazonaws.services.transcribe.AmazonTranscribeAsyncClientBuilder []
(AmazonTranscribeAsyncClient/asyncBuilder )))
(defn start-transcription-job-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.StartTranscriptionJobRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the StartTranscriptionJob operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.StartTranscriptionJobResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.StartTranscriptionJobRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.startTranscriptionJobAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.StartTranscriptionJobRequest request]
(-> this (.startTranscriptionJobAsync request))))
(defn get-transcription-job-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.GetTranscriptionJobRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetTranscriptionJob operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.GetTranscriptionJobResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.GetTranscriptionJobRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getTranscriptionJobAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.GetTranscriptionJobRequest request]
(-> this (.getTranscriptionJobAsync request))))
(defn get-executor-service
"Returns the executor service used by this client to execute async requests.
returns: The executor service used by this client to execute async requests. - `java.util.concurrent.ExecutorService`"
(^java.util.concurrent.ExecutorService [^AmazonTranscribeAsyncClient this]
(-> this (.getExecutorService))))
(defn list-vocabularies-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.ListVocabulariesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListVocabularies operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.ListVocabulariesResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.ListVocabulariesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listVocabulariesAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.ListVocabulariesRequest request]
(-> this (.listVocabulariesAsync request))))
(defn list-transcription-jobs-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.ListTranscriptionJobsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListTranscriptionJobs operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.ListTranscriptionJobsResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.ListTranscriptionJobsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listTranscriptionJobsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.ListTranscriptionJobsRequest request]
(-> this (.listTranscriptionJobsAsync request))))
(defn delete-transcription-job-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.DeleteTranscriptionJobRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteTranscriptionJob operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.DeleteTranscriptionJobResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.DeleteTranscriptionJobRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteTranscriptionJobAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.DeleteTranscriptionJobRequest request]
(-> this (.deleteTranscriptionJobAsync request))))
(defn update-vocabulary-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.UpdateVocabularyRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateVocabulary operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.UpdateVocabularyResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.UpdateVocabularyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateVocabularyAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.UpdateVocabularyRequest request]
(-> this (.updateVocabularyAsync request))))
(defn create-vocabulary-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.CreateVocabularyRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateVocabulary operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.CreateVocabularyResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.CreateVocabularyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createVocabularyAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.CreateVocabularyRequest request]
(-> this (.createVocabularyAsync request))))
(defn shutdown
"Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending
asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should
call getExecutorService().shutdown() followed by getExecutorService().awaitTermination() prior to
calling this method."
([^AmazonTranscribeAsyncClient this]
(-> this (.shutdown))))
(defn get-vocabulary-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.GetVocabularyRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetVocabulary operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.GetVocabularyResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.GetVocabularyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getVocabularyAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.GetVocabularyRequest request]
(-> this (.getVocabularyAsync request))))
(defn delete-vocabulary-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.DeleteVocabularyRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteVocabulary operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.DeleteVocabularyResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.DeleteVocabularyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteVocabularyAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.DeleteVocabularyRequest request]
(-> this (.deleteVocabularyAsync request))))
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.transcribe/src/com/amazonaws/services/transcribe/AmazonTranscribeAsyncClient.clj | clojure | (ns com.amazonaws.services.transcribe.AmazonTranscribeAsyncClient
"Client for accessing Amazon Transcribe Service asynchronously. Each asynchronous method will return a Java Future
overloads which accept an AsyncHandler can be used to receive
notification when an asynchronous operation completes.
Operations and objects for transcribing speech to text."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.transcribe AmazonTranscribeAsyncClient]))
(defn *async-builder
"returns: `com.amazonaws.services.transcribe.AmazonTranscribeAsyncClientBuilder`"
(^com.amazonaws.services.transcribe.AmazonTranscribeAsyncClientBuilder []
(AmazonTranscribeAsyncClient/asyncBuilder )))
(defn start-transcription-job-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.StartTranscriptionJobRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the StartTranscriptionJob operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.StartTranscriptionJobResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.StartTranscriptionJobRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.startTranscriptionJobAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.StartTranscriptionJobRequest request]
(-> this (.startTranscriptionJobAsync request))))
(defn get-transcription-job-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.GetTranscriptionJobRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetTranscriptionJob operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.GetTranscriptionJobResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.GetTranscriptionJobRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getTranscriptionJobAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.GetTranscriptionJobRequest request]
(-> this (.getTranscriptionJobAsync request))))
(defn get-executor-service
"Returns the executor service used by this client to execute async requests.
returns: The executor service used by this client to execute async requests. - `java.util.concurrent.ExecutorService`"
(^java.util.concurrent.ExecutorService [^AmazonTranscribeAsyncClient this]
(-> this (.getExecutorService))))
(defn list-vocabularies-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.ListVocabulariesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListVocabularies operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.ListVocabulariesResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.ListVocabulariesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listVocabulariesAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.ListVocabulariesRequest request]
(-> this (.listVocabulariesAsync request))))
(defn list-transcription-jobs-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.ListTranscriptionJobsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListTranscriptionJobs operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.ListTranscriptionJobsResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.ListTranscriptionJobsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listTranscriptionJobsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.ListTranscriptionJobsRequest request]
(-> this (.listTranscriptionJobsAsync request))))
(defn delete-transcription-job-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.DeleteTranscriptionJobRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteTranscriptionJob operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.DeleteTranscriptionJobResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.DeleteTranscriptionJobRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteTranscriptionJobAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.DeleteTranscriptionJobRequest request]
(-> this (.deleteTranscriptionJobAsync request))))
(defn update-vocabulary-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.UpdateVocabularyRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateVocabulary operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.UpdateVocabularyResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.UpdateVocabularyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateVocabularyAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.UpdateVocabularyRequest request]
(-> this (.updateVocabularyAsync request))))
(defn create-vocabulary-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.CreateVocabularyRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateVocabulary operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.CreateVocabularyResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.CreateVocabularyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createVocabularyAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.CreateVocabularyRequest request]
(-> this (.createVocabularyAsync request))))
(defn shutdown
"Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending
asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should
call getExecutorService().shutdown() followed by getExecutorService().awaitTermination() prior to
calling this method."
([^AmazonTranscribeAsyncClient this]
(-> this (.shutdown))))
(defn get-vocabulary-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.GetVocabularyRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the GetVocabulary operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.GetVocabularyResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.GetVocabularyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.getVocabularyAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.GetVocabularyRequest request]
(-> this (.getVocabularyAsync request))))
(defn delete-vocabulary-async
"Description copied from interface: AmazonTranscribeAsync
request - `com.amazonaws.services.transcribe.model.DeleteVocabularyRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteVocabulary operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.transcribe.model.DeleteVocabularyResult>`"
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.DeleteVocabularyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteVocabularyAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonTranscribeAsyncClient this ^com.amazonaws.services.transcribe.model.DeleteVocabularyRequest request]
(-> this (.deleteVocabularyAsync request))))
| |
6e72eb67ffb5bc9e83122cd3c79a6fe0163573fcfbf6b21d1fe2b30ecb382f67 | CarlosMChica/HaskellBook | eqInstances.hs | module EqInstances where
exercise 1
data TisAndInteger = ThisAn Integer
instance Eq TisAndInteger where
(==) (ThisAn x) (ThisAn x') =
x == x'
exercise 2
data TwoIntegers = Two Integer Integer
instance Eq TwoIntegers where
(==) (Two x y) (Two x' y') =
x == x' && y == y'
exercise 3
data StringOrInt = TisAndInt Int | TisAString String
instance Eq StringOrInt where
(==) (TisAndInt x) (TisAndInt x') = x == x'
(==) (TisAString x) (TisAString x') = x == x'
(==) _ _ = False
exercise 4
data Pair a = Pair a a
instance Eq a => Eq (Pair a) where
(==) (Pair a b) (Pair a' b') = a == a' && b == b'
exercise 5
data Tuple a b = Tuple a b
instance (Eq a, Eq b) => Eq (Tuple a b) where
(==) (Tuple a b) (Tuple a' b') = a == a' && b == b'
exercise 6
data Which a = ThisOne a | ThatOne a
instance Eq a => Eq (Which a) where
(==) (ThisOne a) (ThisOne a') = a == a'
(==) (ThatOne a) (ThatOne a') = a == a'
(==) _ _ = False
exercise 7
data EitherOr a b = Hello a | Goodbye b
instance (Eq a, Eq b) => Eq (EitherOr a b) where
(==) (Hello a) (Hello a') = a == a'
(==) (Goodbye b) (Goodbye b') = b == b'
(==) _ _ = False
| null | https://raw.githubusercontent.com/CarlosMChica/HaskellBook/86f82cf36cd00003b1a1aebf264e4b5d606ddfad/chapter6/eqInstances.hs | haskell | module EqInstances where
exercise 1
data TisAndInteger = ThisAn Integer
instance Eq TisAndInteger where
(==) (ThisAn x) (ThisAn x') =
x == x'
exercise 2
data TwoIntegers = Two Integer Integer
instance Eq TwoIntegers where
(==) (Two x y) (Two x' y') =
x == x' && y == y'
exercise 3
data StringOrInt = TisAndInt Int | TisAString String
instance Eq StringOrInt where
(==) (TisAndInt x) (TisAndInt x') = x == x'
(==) (TisAString x) (TisAString x') = x == x'
(==) _ _ = False
exercise 4
data Pair a = Pair a a
instance Eq a => Eq (Pair a) where
(==) (Pair a b) (Pair a' b') = a == a' && b == b'
exercise 5
data Tuple a b = Tuple a b
instance (Eq a, Eq b) => Eq (Tuple a b) where
(==) (Tuple a b) (Tuple a' b') = a == a' && b == b'
exercise 6
data Which a = ThisOne a | ThatOne a
instance Eq a => Eq (Which a) where
(==) (ThisOne a) (ThisOne a') = a == a'
(==) (ThatOne a) (ThatOne a') = a == a'
(==) _ _ = False
exercise 7
data EitherOr a b = Hello a | Goodbye b
instance (Eq a, Eq b) => Eq (EitherOr a b) where
(==) (Hello a) (Hello a') = a == a'
(==) (Goodbye b) (Goodbye b') = b == b'
(==) _ _ = False
| |
76bb73140c4df8a3f1ce8f5b85e6423dd839f98b14988106ba5842c4e4a5f2c9 | monadbobo/ocaml-core | no_polymorphic_compare.ml | type compare =
[`no_polymorphic_compare]
-> [`no_polymorphic_compare]
-> [`no_polymorphic_compare]
let compare _ _ = `no_polymorphic_compare
let (<) _ _ = `no_polymorphic_compare
let (<=) _ _ = `no_polymorphic_compare
let (>) _ _ = `no_polymorphic_compare
let (>=) _ _ = `no_polymorphic_compare
let (=) _ _ = `no_polymorphic_compare
let (<>) _ _ = `no_polymorphic_compare
let equal _ _ = `no_polymorphic_compare
let min _ _ = `no_polymorphic_compare
let max _ _ = `no_polymorphic_compare
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib/no_polymorphic_compare.ml | ocaml | type compare =
[`no_polymorphic_compare]
-> [`no_polymorphic_compare]
-> [`no_polymorphic_compare]
let compare _ _ = `no_polymorphic_compare
let (<) _ _ = `no_polymorphic_compare
let (<=) _ _ = `no_polymorphic_compare
let (>) _ _ = `no_polymorphic_compare
let (>=) _ _ = `no_polymorphic_compare
let (=) _ _ = `no_polymorphic_compare
let (<>) _ _ = `no_polymorphic_compare
let equal _ _ = `no_polymorphic_compare
let min _ _ = `no_polymorphic_compare
let max _ _ = `no_polymorphic_compare
| |
c8e75eabd2d8247b56d05c744c84b89e7afff5192a791a24cc9415de856e44ca | puppetlabs/puppetdb | resources.clj | (ns puppetlabs.puppetdb.query.resources
"Resource querying
This implements resource querying, using the query compiler in
`puppetlabs.puppetdb.query`, basically by munging the results into the
right format and picking out the desired columns."
(:import [org.postgresql.util PGobject])
(:require [puppetlabs.puppetdb.query :as query]
[puppetlabs.puppetdb.schema :as pls]
[puppetlabs.puppetdb.utils :as utils]
[schema.spec.core :as spec]
[schema.spec.leaf :as leaf]
[schema.core :as s]))
;; SCHEMA
(defrecord OptionalNameMatching [pattern]
s/Schema
(spec [this] (leaf/leaf-spec
(spec/precondition this
#(re-matches pattern (name %))
#(list 're-matches pattern %))))
(explain [_] '(re-matches pattern)))
(defn optional-matching-keyword
"A regex pattern to check the keyword for."
[pattern]
(->OptionalNameMatching pattern))
(def row-schema
"Resource query row schema."
(query/wrap-with-supported-fns
{(s/optional-key :certname) s/Str
(s/optional-key :environment) (s/maybe s/Str)
(s/optional-key :exported) s/Bool
(s/optional-key :file) (s/maybe s/Str)
(s/optional-key :line) (s/maybe s/Int)
(s/optional-key :parameters) (s/maybe PGobject)
(optional-matching-keyword #"parameters\..*") (s/maybe PGobject)
(s/optional-key :resource) s/Str
(s/optional-key :tags) [(s/maybe s/Str)]
(s/optional-key :title) s/Str
(s/optional-key :type) s/Str}))
(pls/defn-validated row->resource
"Convert resource query row into a final resource format."
[row :- row-schema]
(utils/update-when row [:parameters] #(or % {})))
(pls/defn-validated munge-result-rows
"Munge the result rows so that they will be compatible with the version
specified API specification"
[_ _]
(fn [rows]
(map row->resource rows)))
| null | https://raw.githubusercontent.com/puppetlabs/puppetdb/b3d6d10555561657150fa70b6d1e609fba9c0eda/src/puppetlabs/puppetdb/query/resources.clj | clojure | SCHEMA | (ns puppetlabs.puppetdb.query.resources
"Resource querying
This implements resource querying, using the query compiler in
`puppetlabs.puppetdb.query`, basically by munging the results into the
right format and picking out the desired columns."
(:import [org.postgresql.util PGobject])
(:require [puppetlabs.puppetdb.query :as query]
[puppetlabs.puppetdb.schema :as pls]
[puppetlabs.puppetdb.utils :as utils]
[schema.spec.core :as spec]
[schema.spec.leaf :as leaf]
[schema.core :as s]))
(defrecord OptionalNameMatching [pattern]
s/Schema
(spec [this] (leaf/leaf-spec
(spec/precondition this
#(re-matches pattern (name %))
#(list 're-matches pattern %))))
(explain [_] '(re-matches pattern)))
(defn optional-matching-keyword
"A regex pattern to check the keyword for."
[pattern]
(->OptionalNameMatching pattern))
(def row-schema
"Resource query row schema."
(query/wrap-with-supported-fns
{(s/optional-key :certname) s/Str
(s/optional-key :environment) (s/maybe s/Str)
(s/optional-key :exported) s/Bool
(s/optional-key :file) (s/maybe s/Str)
(s/optional-key :line) (s/maybe s/Int)
(s/optional-key :parameters) (s/maybe PGobject)
(optional-matching-keyword #"parameters\..*") (s/maybe PGobject)
(s/optional-key :resource) s/Str
(s/optional-key :tags) [(s/maybe s/Str)]
(s/optional-key :title) s/Str
(s/optional-key :type) s/Str}))
(pls/defn-validated row->resource
"Convert resource query row into a final resource format."
[row :- row-schema]
(utils/update-when row [:parameters] #(or % {})))
(pls/defn-validated munge-result-rows
"Munge the result rows so that they will be compatible with the version
specified API specification"
[_ _]
(fn [rows]
(map row->resource rows)))
|
0b739ee2e559c0402ba3e27459e05722ec1a282c0029e1a881288370e1856e15 | imitator-model-checker/imitator | AbstractProperty.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : Property description
*
* File contributors : * Created : 2019/10/08
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: Property description
*
* File contributors : Étienne André
* Created : 2019/10/08
*
************************************************************)
(************************************************************)
(* Modules *)
(************************************************************)
open Automaton
open DiscreteExpressions
(****************************************************************)
(** Predicates for properties *)
(****************************************************************)
type loc_predicate =
| Loc_predicate_EQ of automaton_index * location_index
| Loc_predicate_NEQ of automaton_index * location_index
type simple_predicate =
| State_predicate_discrete_boolean_expression of discrete_boolean_expression
| Loc_predicate of loc_predicate
| State_predicate_true
| State_predicate_false
| State_predicate_accepting
type state_predicate_factor =
| State_predicate_factor_NOT of state_predicate_factor
| Simple_predicate of simple_predicate
| State_predicate of state_predicate
and state_predicate_term =
| State_predicate_term_AND of state_predicate_term * state_predicate_term
| State_predicate_factor of state_predicate_factor
and state_predicate =
| State_predicate_OR of state_predicate * state_predicate
| State_predicate_term of state_predicate_term
(************************************************************)
(** Definition of property *)
(************************************************************)
type duration = LinearConstraint.p_linear_term
type property =
(*------------------------------------------------------------*)
Non - nested CTL
(*------------------------------------------------------------*)
Reachability
| EF of state_predicate
Safety
| AGnot of state_predicate
(*
(* Unavoidability *)
| AF of state_predicate
*)
(*------------------------------------------------------------*)
(* Optimized reachability *)
(*------------------------------------------------------------*)
Reachability with minimization of a parameter valuation
| EFpmin of state_predicate * parameter_index
Reachability with maximization of a parameter valuation
| EFpmax of state_predicate * parameter_index
Reachability with minimal - time
| EFtmin of state_predicate
(*------------------------------------------------------------*)
(* Cycles *)
(*------------------------------------------------------------*)
(** Accepting infinite-run (cycle) through a state predicate *)
| Cycle_through of state_predicate
* Accepting infinite - run ( cycle ) through a generalized condition ( list of state predicates , and one of them must hold on at least one state in a given cycle )
| Cycle_through_generalized of state_predicate list
* Infinite - run ( cycle ) with assumption
| NZ_Cycle
(*------------------------------------------------------------*)
(* Deadlock-freeness *)
(*------------------------------------------------------------*)
(* Deadlock-free synthesis *)
| Deadlock_Freeness
(*------------------------------------------------------------*)
(* Inverse method, trace preservation, robustness *)
(*------------------------------------------------------------*)
(* Inverse method with complete, non-convex result *)
| IM of PVal.pval
(* Non-complete, non-deterministic inverse method with convex result *)
| ConvexIM of PVal.pval
Parametric reachability preservation
| PRP of state_predicate * PVal.pval
Variant IMK of the Inverse method
| IMK of PVal.pval
(* Variant IMunion of the Inverse method *)
| IMunion of PVal.pval
(*------------------------------------------------------------*)
(* Cartography algorithms *)
(*------------------------------------------------------------*)
(*** NOTE: the last argument is the step; it is optional in the parser, and its value is otherwise defined in Constants ***)
(* Cartography *)
| Cover_cartography of HyperRectangle.hyper_rectangle * NumConst.t
(** Cover the whole cartography using learning-based abstractions *)
| Learning_cartography of state_predicate * HyperRectangle.hyper_rectangle * NumConst.t
* Cover the whole cartography after shuffling point ( mostly useful for the distributed IMITATOR )
| Shuffle_cartography of HyperRectangle.hyper_rectangle * NumConst.t
(** Look for the border using the cartography*)
| Border_cartography of HyperRectangle.hyper_rectangle * NumConst.t
(** Randomly pick up values for a given number of iterations *)
| Random_cartography of HyperRectangle.hyper_rectangle * int * NumConst.t
* Randomly pick up values for a given number of iterations , then switch to sequential algorithm once no more point has been found after a given max number of attempts ( mostly useful for the distributed IMITATOR )
| RandomSeq_cartography of HyperRectangle.hyper_rectangle * int * NumConst.t
Parametric reachability preservation
| PRPC of state_predicate * HyperRectangle.hyper_rectangle * NumConst.t
type synthesis_type =
(* (tentative) exemplification of concrete runs *)
| Exemplification
(* (tentative) synthesis of all valuations for which a property holds *)
| Synthesis
( tentative ) exhibition of at least one valuation for which a property holds
| Witness
type projection = (parameter_index list) option
(************************************************************)
(** The actual property *)
(************************************************************)
type abstract_property = {
(* Emptiness or synthesis *)
synthesis_type : synthesis_type;
(* Property *)
property : property;
(* Projection of the result *)
projection : projection;
}
| null | https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/AbstractProperty.mli | ocaml | **********************************************************
Modules
**********************************************************
**************************************************************
* Predicates for properties
**************************************************************
**********************************************************
* Definition of property
**********************************************************
------------------------------------------------------------
------------------------------------------------------------
(* Unavoidability
------------------------------------------------------------
Optimized reachability
------------------------------------------------------------
------------------------------------------------------------
Cycles
------------------------------------------------------------
* Accepting infinite-run (cycle) through a state predicate
------------------------------------------------------------
Deadlock-freeness
------------------------------------------------------------
Deadlock-free synthesis
------------------------------------------------------------
Inverse method, trace preservation, robustness
------------------------------------------------------------
Inverse method with complete, non-convex result
Non-complete, non-deterministic inverse method with convex result
Variant IMunion of the Inverse method
------------------------------------------------------------
Cartography algorithms
------------------------------------------------------------
** NOTE: the last argument is the step; it is optional in the parser, and its value is otherwise defined in Constants **
Cartography
* Cover the whole cartography using learning-based abstractions
* Look for the border using the cartography
* Randomly pick up values for a given number of iterations
(tentative) exemplification of concrete runs
(tentative) synthesis of all valuations for which a property holds
**********************************************************
* The actual property
**********************************************************
Emptiness or synthesis
Property
Projection of the result | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : Property description
*
* File contributors : * Created : 2019/10/08
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: Property description
*
* File contributors : Étienne André
* Created : 2019/10/08
*
************************************************************)
open Automaton
open DiscreteExpressions
type loc_predicate =
| Loc_predicate_EQ of automaton_index * location_index
| Loc_predicate_NEQ of automaton_index * location_index
type simple_predicate =
| State_predicate_discrete_boolean_expression of discrete_boolean_expression
| Loc_predicate of loc_predicate
| State_predicate_true
| State_predicate_false
| State_predicate_accepting
type state_predicate_factor =
| State_predicate_factor_NOT of state_predicate_factor
| Simple_predicate of simple_predicate
| State_predicate of state_predicate
and state_predicate_term =
| State_predicate_term_AND of state_predicate_term * state_predicate_term
| State_predicate_factor of state_predicate_factor
and state_predicate =
| State_predicate_OR of state_predicate * state_predicate
| State_predicate_term of state_predicate_term
type duration = LinearConstraint.p_linear_term
type property =
Non - nested CTL
Reachability
| EF of state_predicate
Safety
| AGnot of state_predicate
| AF of state_predicate
*)
Reachability with minimization of a parameter valuation
| EFpmin of state_predicate * parameter_index
Reachability with maximization of a parameter valuation
| EFpmax of state_predicate * parameter_index
Reachability with minimal - time
| EFtmin of state_predicate
| Cycle_through of state_predicate
* Accepting infinite - run ( cycle ) through a generalized condition ( list of state predicates , and one of them must hold on at least one state in a given cycle )
| Cycle_through_generalized of state_predicate list
* Infinite - run ( cycle ) with assumption
| NZ_Cycle
| Deadlock_Freeness
| IM of PVal.pval
| ConvexIM of PVal.pval
Parametric reachability preservation
| PRP of state_predicate * PVal.pval
Variant IMK of the Inverse method
| IMK of PVal.pval
| IMunion of PVal.pval
| Cover_cartography of HyperRectangle.hyper_rectangle * NumConst.t
| Learning_cartography of state_predicate * HyperRectangle.hyper_rectangle * NumConst.t
* Cover the whole cartography after shuffling point ( mostly useful for the distributed IMITATOR )
| Shuffle_cartography of HyperRectangle.hyper_rectangle * NumConst.t
| Border_cartography of HyperRectangle.hyper_rectangle * NumConst.t
| Random_cartography of HyperRectangle.hyper_rectangle * int * NumConst.t
* Randomly pick up values for a given number of iterations , then switch to sequential algorithm once no more point has been found after a given max number of attempts ( mostly useful for the distributed IMITATOR )
| RandomSeq_cartography of HyperRectangle.hyper_rectangle * int * NumConst.t
Parametric reachability preservation
| PRPC of state_predicate * HyperRectangle.hyper_rectangle * NumConst.t
type synthesis_type =
| Exemplification
| Synthesis
( tentative ) exhibition of at least one valuation for which a property holds
| Witness
type projection = (parameter_index list) option
type abstract_property = {
synthesis_type : synthesis_type;
property : property;
projection : projection;
}
|
0b79ee506c445382db0de4052adc4baf4a718290c95da45cf4f7f6324f5871b9 | GregoryTravis/holfenstein | Larf.hs | module Main (main) where
import System.IO
import Img
import Shader
import Util
(screenWidth, screenHeight) = (640, 480)
type Shader = Double -> Int -> Int -> Int -> Int -> Color
type FShader = Double -> Double -> Double -> Color
shader :: Shader
shader t x y w h = Color (fade x w) (fade y h) 0
where fade x m = (floor (256.0 * (((fromIntegral x) / (fromIntegral m)) + t))) `mod` 256
fshaderToShader :: FShader -> Shader
fshaderToShader fs t x y w h = fs t fx fy
where minDim = min w h
fx = (fromIntegral (x - (w `div` 2))) / (fromIntegral (minDim `div` 2))
fy = - ((fromIntegral (y - (h `div` 2))) / (fromIntegral (minDim `div` 2)))
fshader :: FShader
fshader t x y = --Color r 0 0
if y > 0.5 then Color 255 0 0 else Color 0 255 0
where r = clip $ x * 256.0
clip x | x < 0.0 = 0
| x >= 256.0 = 255
| otherwise = floor x
main = do
hSetBuffering stdout NoBuffering
shaderMain screenWidth screenHeight (fshaderToShader fshader)
| null | https://raw.githubusercontent.com/GregoryTravis/holfenstein/fcb8743351700c701757dc13fb6defcde53be306/Larf.hs | haskell | Color r 0 0 | module Main (main) where
import System.IO
import Img
import Shader
import Util
(screenWidth, screenHeight) = (640, 480)
type Shader = Double -> Int -> Int -> Int -> Int -> Color
type FShader = Double -> Double -> Double -> Color
shader :: Shader
shader t x y w h = Color (fade x w) (fade y h) 0
where fade x m = (floor (256.0 * (((fromIntegral x) / (fromIntegral m)) + t))) `mod` 256
fshaderToShader :: FShader -> Shader
fshaderToShader fs t x y w h = fs t fx fy
where minDim = min w h
fx = (fromIntegral (x - (w `div` 2))) / (fromIntegral (minDim `div` 2))
fy = - ((fromIntegral (y - (h `div` 2))) / (fromIntegral (minDim `div` 2)))
fshader :: FShader
if y > 0.5 then Color 255 0 0 else Color 0 255 0
where r = clip $ x * 256.0
clip x | x < 0.0 = 0
| x >= 256.0 = 255
| otherwise = floor x
main = do
hSetBuffering stdout NoBuffering
shaderMain screenWidth screenHeight (fshaderToShader fshader)
|
cac2b21e508bcec9efadf6cfc52c69ddab3a31caed5bad3c9117ddda46457277 | uents/sicp | ch3.5.5.scm | SICP Chapter 3.5.5
;;;;
;;;; Author @uents on twitter
;;;;
#lang racket
(require "../misc.scm")
(require "streams.scm")
;; §3.1から転用
(define (rand-update x)
(modulo (+ (* 13 x) 47) 97))
(define random-init 7)
(define random-numbers
(cons-stream random-init
(stream-map rand-update random-numbers)))
;; racket@> (map (lambda (i) (stream-ref random-numbers i))
( enumerate - interval 0 20 ) )
= > ' ( 7 41 95 21 29 36 30 49 5 15 48 89 40 82 46 63 90 53 57 12 9 )
;;
;; random-initは定数なので何度やっても結果は同じになる
(define (map-successive-pairs f s)
(cons-stream
(f (stream-car s) (stream-car (stream-cdr s)))
(map-successive-pairs f (stream-cdr (stream-cdr s)))))
(define cesaro-stream
(map-successive-pairs (lambda (r1 r2) (= (gcd r1 r2) 1))
random-numbers))
;; racket@> (map (lambda (i) (stream-ref cesaro-stream i))
( enumerate - interval 0 20 ) )
;; => '(#t #t #t #t #f #t #f #t #t #f #t #f #f #f #t #f #f #t #t #t #t)
(define (monte-carlo-stream experiment-stream passed failed)
(define (next passed failed)
(cons-stream
(monte-carlo-stream
(stream-cdr experiment-stream) passed failed)))
(if (stream-car experiment-stream)
(next (+ passed 1) failed)
(next passed (+ failed 1))))
(define pi-stream
(stream-map (lambda (p) (sqrt (/ 6 p)))
(monte-carlo-stream cesaro-stream 0 0)))
;; racket@> (stream-ref pi-stream 0)
= > 2.449489742783178
racket@ > ( stream - ref pi - stream 100 )
= > 3.1780497164141406
racket@ > ( stream - ref pi - stream 1000 )
= > 3.2041639575194445
racket@ > ( stream - ref pi - stream 10000 )
= > 3.2073868966203145
racket@ > ( stream - ref pi - stream 100000 )
= > 3.2071601019111857
racket@ > ( stream - ref pi - stream 1000000 )
= > 3.207137422841252
ex 3.81
;; rand-exは問題3.6を流用
(define rand-ex
(let ((x random-init))
(define (generate)
(set! x (rand-update x))
x)
(define (reset)
(set! x random-init)
x)
(define (dispatch m)
(cond ((eq? m 'generate) generate)
((eq? m 'reset) reset)
(else (error "Unknown request -- RAND" m))))
dispatch))
(define (rand-stream s)
(let ((item (stream-car s)))
(cons-stream
(if (eq? item 'generate)
((rand-ex 'generate))
(begin (set! random-init item)
((rand-ex 'reset))))
(rand-stream (stream-cdr s)))))
;; racket@> (define s
;; (rand-stream
( list->stream ( list 100 ' generate ' generate ' generate
;; 100 'generate 'generate 'generate))))
;; racket@> (map (lambda (i) (stream-ref s i))
( enumerate - interval 0 7 ) )
= > ' ( 100 86 1 60 100 86 1 60 )
ex 3.82
(define (range low high x)
(+ low (modulo x (+ 1 (- high low)))))
(define (random-in-range-stream low high)
(stream-map (lambda (x) (range low high x))
random-numbers))
racket@ > ( map ( lambda ( i ) ( stream - ref ( random - in - range - stream 2 8) i ) )
( enumerate - interval 0 20 ) )
= > ' ( 5 3 6 5 2 2 5 6 6 8 3 2 7 8 4 7 5 4 3 6 4 )
(define (estimate-integral-stream predicate x1 y1 x2 y2)
(let* ((area (* (- x2 x1) (- y2 y1)))
(x-stream (random-in-range-stream x1 x2))
(y-stream (random-in-range-stream y1 y2))
(passed-ratio-stream (monte-carlo-stream
(stream-map predicate
x-stream
y-stream)
0 0)))
(scale-stream passed-ratio-stream area)))
;; racket@> (define s (estimate-integral-stream
;; (lambda (x y)
( < = ( + ( square ( - x 5 ) ) ( square ( - y 7 ) ) ) ( square 3 ) ) )
2 4 8 10 ) )
racket@ > ( stream - ref s 100 )
= > 25.306930693069305
racket@ > ( stream - ref s 1000 )
= > 25.858141858141856
racket@ > ( stream - ref s 10000 )
= > 25.867013298670134
racket@ > ( stream - ref s 100000 )
= > 25.875821241787584
racket@ > ( stream - ref s 1000000 )
= > 25.875082124917874
| null | https://raw.githubusercontent.com/uents/sicp/c29b2582feee452ec0714fdc1eec6b406b94cd27/ch3/ch3.5.5.scm | scheme |
Author @uents on twitter
§3.1から転用
racket@> (map (lambda (i) (stream-ref random-numbers i))
random-initは定数なので何度やっても結果は同じになる
racket@> (map (lambda (i) (stream-ref cesaro-stream i))
=> '(#t #t #t #t #f #t #f #t #t #f #t #f #f #f #t #f #f #t #t #t #t)
racket@> (stream-ref pi-stream 0)
rand-exは問題3.6を流用
racket@> (define s
(rand-stream
100 'generate 'generate 'generate))))
racket@> (map (lambda (i) (stream-ref s i))
racket@> (define s (estimate-integral-stream
(lambda (x y) | SICP Chapter 3.5.5
#lang racket
(require "../misc.scm")
(require "streams.scm")
(define (rand-update x)
(modulo (+ (* 13 x) 47) 97))
(define random-init 7)
(define random-numbers
(cons-stream random-init
(stream-map rand-update random-numbers)))
( enumerate - interval 0 20 ) )
= > ' ( 7 41 95 21 29 36 30 49 5 15 48 89 40 82 46 63 90 53 57 12 9 )
(define (map-successive-pairs f s)
(cons-stream
(f (stream-car s) (stream-car (stream-cdr s)))
(map-successive-pairs f (stream-cdr (stream-cdr s)))))
(define cesaro-stream
(map-successive-pairs (lambda (r1 r2) (= (gcd r1 r2) 1))
random-numbers))
( enumerate - interval 0 20 ) )
(define (monte-carlo-stream experiment-stream passed failed)
(define (next passed failed)
(cons-stream
(monte-carlo-stream
(stream-cdr experiment-stream) passed failed)))
(if (stream-car experiment-stream)
(next (+ passed 1) failed)
(next passed (+ failed 1))))
(define pi-stream
(stream-map (lambda (p) (sqrt (/ 6 p)))
(monte-carlo-stream cesaro-stream 0 0)))
= > 2.449489742783178
racket@ > ( stream - ref pi - stream 100 )
= > 3.1780497164141406
racket@ > ( stream - ref pi - stream 1000 )
= > 3.2041639575194445
racket@ > ( stream - ref pi - stream 10000 )
= > 3.2073868966203145
racket@ > ( stream - ref pi - stream 100000 )
= > 3.2071601019111857
racket@ > ( stream - ref pi - stream 1000000 )
= > 3.207137422841252
ex 3.81
(define rand-ex
(let ((x random-init))
(define (generate)
(set! x (rand-update x))
x)
(define (reset)
(set! x random-init)
x)
(define (dispatch m)
(cond ((eq? m 'generate) generate)
((eq? m 'reset) reset)
(else (error "Unknown request -- RAND" m))))
dispatch))
(define (rand-stream s)
(let ((item (stream-car s)))
(cons-stream
(if (eq? item 'generate)
((rand-ex 'generate))
(begin (set! random-init item)
((rand-ex 'reset))))
(rand-stream (stream-cdr s)))))
( list->stream ( list 100 ' generate ' generate ' generate
( enumerate - interval 0 7 ) )
= > ' ( 100 86 1 60 100 86 1 60 )
ex 3.82
(define (range low high x)
(+ low (modulo x (+ 1 (- high low)))))
(define (random-in-range-stream low high)
(stream-map (lambda (x) (range low high x))
random-numbers))
racket@ > ( map ( lambda ( i ) ( stream - ref ( random - in - range - stream 2 8) i ) )
( enumerate - interval 0 20 ) )
= > ' ( 5 3 6 5 2 2 5 6 6 8 3 2 7 8 4 7 5 4 3 6 4 )
(define (estimate-integral-stream predicate x1 y1 x2 y2)
(let* ((area (* (- x2 x1) (- y2 y1)))
(x-stream (random-in-range-stream x1 x2))
(y-stream (random-in-range-stream y1 y2))
(passed-ratio-stream (monte-carlo-stream
(stream-map predicate
x-stream
y-stream)
0 0)))
(scale-stream passed-ratio-stream area)))
( < = ( + ( square ( - x 5 ) ) ( square ( - y 7 ) ) ) ( square 3 ) ) )
2 4 8 10 ) )
racket@ > ( stream - ref s 100 )
= > 25.306930693069305
racket@ > ( stream - ref s 1000 )
= > 25.858141858141856
racket@ > ( stream - ref s 10000 )
= > 25.867013298670134
racket@ > ( stream - ref s 100000 )
= > 25.875821241787584
racket@ > ( stream - ref s 1000000 )
= > 25.875082124917874
|
1c5a422351b9aed74f7ab05f668528817e22d70831ae6309500f646732451964 | MondayMorningHaskell/haskellings | IO1.hs | -- I AM NOT DONE
import System.Directory
- The * IO * monad is perhaps the most important to know about in Haskell .
It 's also the most special , carrying a different kind of effect to other monads .
- Most functions we run are " pure " . Their output ca n't be influenced by
anything besides the direct input values we use , whether explicitly as
arguments , or implicitly through a Stateful monad .
- They also do n't produce additional side effects . They can provide a
return value to the rest of our program , and they can have an implicit
output through the Writer or State monad .
- The * IO * monad provides the computation context of
* interaction with the outside world * .
- This means it allows us to take additional inputs like reading from the
terminal , opening up a file from the OS , or reading a network connection .
- The IO monad is different from other monads in that there is no ' runIO ' function .
You * can not * run ' IO ' code from non - IO code . The entrypoint for any program
you write is the ' main ' function . This has the type ' IO ( ) ' :
main : : IO ( )
main = do
...
- You can run non - IO code from this function using ' let ' or ' where ' clauses ,
like we 've already seen in monads . But any ' IO ' code must be called from
a chain of other ' IO ' code going back to this function .
- In this exercise , you 'll practice using a few basic ' IO ' functions :
-- Prints a ' String ' object to the terminal .
putStrLn : : String - > IO ( )
-- Prints any ' Show ' object to the terminal .
-- ( Note , ' print'-ing a ' String ' will cause it to appear with extra quotation marks )
-- ( Hello vs. " Hello " )
print : : ( Show a ) - > a - > IO ( )
-- A ' FilePath ' is just an alias for a ' String '
-- This function retrieves the directory the program is being run from .
getCurrentDirectory : : IO FilePath
-- This retrieves the " Home " directory path on your system .
getHomeDirectory : : IO FilePath
-- This provides a list of all the files and directories within the input .
-- ( Like running the ' ls ' or ' dir ' command )
listDirectory : : FilePath - > IO [ FilePath ]
- The *IO* monad is perhaps the most important to know about in Haskell.
It's also the most special, carrying a different kind of effect to other monads.
- Most functions we run are "pure". Their output can't be influenced by
anything besides the direct input values we use, whether explicitly as
arguments, or implicitly through a Stateful monad.
- They also don't produce additional side effects. They can provide a
return value to the rest of our program, and they can have an implicit
output through the Writer or State monad.
- The *IO* monad provides the computation context of
*interaction with the outside world*.
- This means it allows us to take additional inputs like reading from the
terminal, opening up a file from the OS, or reading a network connection.
- The IO monad is different from other monads in that there is no 'runIO' function.
You *cannot* run 'IO' code from non-IO code. The entrypoint for any program
you write is the 'main' function. This has the type 'IO ()':
main :: IO ()
main = do
...
- You can run non-IO code from this function using 'let' or 'where' clauses,
like we've already seen in monads. But any 'IO' code must be called from
a chain of other 'IO' code going back to this function.
- In this exercise, you'll practice using a few basic 'IO' functions:
-- Prints a 'String' object to the terminal.
putStrLn :: String -> IO ()
-- Prints any 'Show' object to the terminal.
-- (Note, 'print'-ing a 'String' will cause it to appear with extra quotation marks)
-- (Hello vs. "Hello")
print :: (Show a) -> a -> IO ()
-- A 'FilePath' is just an alias for a 'String'
-- This function retrieves the directory the program is being run from.
getCurrentDirectory :: IO FilePath
-- This retrieves the "Home" directory path on your system.
getHomeDirectory :: IO FilePath
-- This provides a list of all the files and directories within the input.
-- (Like running the 'ls' or 'dir' command)
listDirectory :: FilePath -> IO [FilePath]
-}
-- TODO:
Print four messages to the terminal .
1 . First use putStrLn to produce the string " Hello , World ! "
2 . Then print " Running from directory : " plus the " current " directory .
3 . Next , find the home directory and print it out : " Home directory is : ... "
4 . Finally , list the home directory and print how many elements it has :
" Home directory contains 10 sub - paths . "
--
-- To run this code without evaluating it, use 'haskellings exec IO1'
main :: IO ()
main = ???
Sample Output :
Hello , World !
Running from directory : /home / myuser / haskellings
Home directory is : /home / myuser
Home directory contains 10 sub - paths .
Sample Output:
Hello, World!
Running from directory: /home/myuser/haskellings
Home directory is: /home/myuser
Home directory contains 10 sub-paths.
-}
| null | https://raw.githubusercontent.com/MondayMorningHaskell/haskellings/fafadd5bbb722b54c1b7b114e34dc9b96bb7ca4d/exercises/monads/IO1.hs | haskell | I AM NOT DONE
Prints a ' String ' object to the terminal .
Prints any ' Show ' object to the terminal .
( Note , ' print'-ing a ' String ' will cause it to appear with extra quotation marks )
( Hello vs. " Hello " )
A ' FilePath ' is just an alias for a ' String '
This function retrieves the directory the program is being run from .
This retrieves the " Home " directory path on your system .
This provides a list of all the files and directories within the input .
( Like running the ' ls ' or ' dir ' command )
Prints a 'String' object to the terminal.
Prints any 'Show' object to the terminal.
(Note, 'print'-ing a 'String' will cause it to appear with extra quotation marks)
(Hello vs. "Hello")
A 'FilePath' is just an alias for a 'String'
This function retrieves the directory the program is being run from.
This retrieves the "Home" directory path on your system.
This provides a list of all the files and directories within the input.
(Like running the 'ls' or 'dir' command)
TODO:
To run this code without evaluating it, use 'haskellings exec IO1' |
import System.Directory
- The * IO * monad is perhaps the most important to know about in Haskell .
It 's also the most special , carrying a different kind of effect to other monads .
- Most functions we run are " pure " . Their output ca n't be influenced by
anything besides the direct input values we use , whether explicitly as
arguments , or implicitly through a Stateful monad .
- They also do n't produce additional side effects . They can provide a
return value to the rest of our program , and they can have an implicit
output through the Writer or State monad .
- The * IO * monad provides the computation context of
* interaction with the outside world * .
- This means it allows us to take additional inputs like reading from the
terminal , opening up a file from the OS , or reading a network connection .
- The IO monad is different from other monads in that there is no ' runIO ' function .
You * can not * run ' IO ' code from non - IO code . The entrypoint for any program
you write is the ' main ' function . This has the type ' IO ( ) ' :
main : : IO ( )
main = do
...
- You can run non - IO code from this function using ' let ' or ' where ' clauses ,
like we 've already seen in monads . But any ' IO ' code must be called from
a chain of other ' IO ' code going back to this function .
- In this exercise , you 'll practice using a few basic ' IO ' functions :
putStrLn : : String - > IO ( )
print : : ( Show a ) - > a - > IO ( )
getCurrentDirectory : : IO FilePath
getHomeDirectory : : IO FilePath
listDirectory : : FilePath - > IO [ FilePath ]
- The *IO* monad is perhaps the most important to know about in Haskell.
It's also the most special, carrying a different kind of effect to other monads.
- Most functions we run are "pure". Their output can't be influenced by
anything besides the direct input values we use, whether explicitly as
arguments, or implicitly through a Stateful monad.
- They also don't produce additional side effects. They can provide a
return value to the rest of our program, and they can have an implicit
output through the Writer or State monad.
- The *IO* monad provides the computation context of
*interaction with the outside world*.
- This means it allows us to take additional inputs like reading from the
terminal, opening up a file from the OS, or reading a network connection.
- The IO monad is different from other monads in that there is no 'runIO' function.
You *cannot* run 'IO' code from non-IO code. The entrypoint for any program
you write is the 'main' function. This has the type 'IO ()':
main :: IO ()
main = do
...
- You can run non-IO code from this function using 'let' or 'where' clauses,
like we've already seen in monads. But any 'IO' code must be called from
a chain of other 'IO' code going back to this function.
- In this exercise, you'll practice using a few basic 'IO' functions:
putStrLn :: String -> IO ()
print :: (Show a) -> a -> IO ()
getCurrentDirectory :: IO FilePath
getHomeDirectory :: IO FilePath
listDirectory :: FilePath -> IO [FilePath]
-}
Print four messages to the terminal .
1 . First use putStrLn to produce the string " Hello , World ! "
2 . Then print " Running from directory : " plus the " current " directory .
3 . Next , find the home directory and print it out : " Home directory is : ... "
4 . Finally , list the home directory and print how many elements it has :
" Home directory contains 10 sub - paths . "
main :: IO ()
main = ???
Sample Output :
Hello , World !
Running from directory : /home / myuser / haskellings
Home directory is : /home / myuser
Home directory contains 10 sub - paths .
Sample Output:
Hello, World!
Running from directory: /home/myuser/haskellings
Home directory is: /home/myuser
Home directory contains 10 sub-paths.
-}
|
fe3ef6b836ca51b1e478cbb60098cdc27d7ffdbd6f222aa345060ee1f615aa7c | oakes/Nightlight | nightlight.clj | (ns leiningen.nightlight
(:require [leinjacker.deps :as deps]
[leinjacker.eval :as eval]
[clojure.tools.cli :as cli]
[clojure.edn :as edn]
[clojure.string :as str]
[nightlight.utils :as u]))
(defn start-nightlight
[{:keys [main] :as project} options]
(eval/eval-in-project
(deps/add-if-missing
project
'[nightlight/lein-nightlight "2.4.4"])
`(nightlight.core/start (assoc ~options :main '~main))
`(require 'nightlight.core)))
(defn nightlight
"A conveninent Nightlight launcher
Run with -u to see CLI usage."
[project & args]
(let [cli (cli/parse-opts args u/cli-options)]
(cond
;; if there are CLI errors, print error messages and usage summary
(:errors cli)
(println (:errors cli) "\n" (:summary cli))
;; if user asked for CLI usage, print the usage summary
(get-in cli [:options :usage])
(println (:summary cli))
in other cases start Nightlight
:otherwise
(start-nightlight project (:options cli)))))
| null | https://raw.githubusercontent.com/oakes/Nightlight/51ed9bcd7286c2833bb48daf9cb0624e4e7b0e14/lein-nightlight/src/leiningen/nightlight.clj | clojure | if there are CLI errors, print error messages and usage summary
if user asked for CLI usage, print the usage summary | (ns leiningen.nightlight
(:require [leinjacker.deps :as deps]
[leinjacker.eval :as eval]
[clojure.tools.cli :as cli]
[clojure.edn :as edn]
[clojure.string :as str]
[nightlight.utils :as u]))
(defn start-nightlight
[{:keys [main] :as project} options]
(eval/eval-in-project
(deps/add-if-missing
project
'[nightlight/lein-nightlight "2.4.4"])
`(nightlight.core/start (assoc ~options :main '~main))
`(require 'nightlight.core)))
(defn nightlight
"A conveninent Nightlight launcher
Run with -u to see CLI usage."
[project & args]
(let [cli (cli/parse-opts args u/cli-options)]
(cond
(:errors cli)
(println (:errors cli) "\n" (:summary cli))
(get-in cli [:options :usage])
(println (:summary cli))
in other cases start Nightlight
:otherwise
(start-nightlight project (:options cli)))))
|
85bfc471817497a09e99b8b2f5d23225f9b0047aac048d5d41141051aa1d384e | philopon/apiary | EventSource.hs | {-# LANGUAGE OverloadedStrings #-}
module Web.Apiary.EventSource
( eventSourceIO, eventSourceChan
, module Network.Wai.EventSource.EventStream
) where
import Web.Apiary(MonadIO(..), status200)
import Network.Wai.EventSource.EventStream (ServerEvent(..))
import qualified Network.Wai.EventSource.EventStream as E
import Control.Concurrent.Chan (Chan, dupChan, readChan)
import Control.Monad.Apiary.Action
(ActionT, status, contentType, stream, StreamingBody)
import Data.Function(fix)
ioToSource :: IO ServerEvent -> StreamingBody
ioToSource src send flush = fix $ \loop -> do
se <- src
case E.eventToBuilder se of
Nothing -> return ()
Just b -> send b >> flush >> loop
| eventsource with io action . since 0.11.3 .
eventSourceIO :: Monad m => IO ServerEvent -> ActionT exts prms m ()
eventSourceIO io = do
status status200
contentType "text/event-stream"
stream $ ioToSource io
| eventsource with chan . since 0.11.3 .
eventSourceChan :: MonadIO m => Chan ServerEvent -> ActionT exts prms m ()
eventSourceChan chan = do
chan' <- liftIO $ dupChan chan
eventSourceIO (readChan chan')
| null | https://raw.githubusercontent.com/philopon/apiary/7da306fcbfcdec85d073746968298de4540d7235/apiary-eventsource/src/Web/Apiary/EventSource.hs | haskell | # LANGUAGE OverloadedStrings # |
module Web.Apiary.EventSource
( eventSourceIO, eventSourceChan
, module Network.Wai.EventSource.EventStream
) where
import Web.Apiary(MonadIO(..), status200)
import Network.Wai.EventSource.EventStream (ServerEvent(..))
import qualified Network.Wai.EventSource.EventStream as E
import Control.Concurrent.Chan (Chan, dupChan, readChan)
import Control.Monad.Apiary.Action
(ActionT, status, contentType, stream, StreamingBody)
import Data.Function(fix)
ioToSource :: IO ServerEvent -> StreamingBody
ioToSource src send flush = fix $ \loop -> do
se <- src
case E.eventToBuilder se of
Nothing -> return ()
Just b -> send b >> flush >> loop
| eventsource with io action . since 0.11.3 .
eventSourceIO :: Monad m => IO ServerEvent -> ActionT exts prms m ()
eventSourceIO io = do
status status200
contentType "text/event-stream"
stream $ ioToSource io
| eventsource with chan . since 0.11.3 .
eventSourceChan :: MonadIO m => Chan ServerEvent -> ActionT exts prms m ()
eventSourceChan chan = do
chan' <- liftIO $ dupChan chan
eventSourceIO (readChan chan')
|
bcef13e7155dec76cc1f5379774a73ddca19a8ca16a2db61f87b280303137c27 | szos/My-Stumpwm-Init | init.lisp | (in-package :stumpwm)
(setf *maximum-completions* 50) ; make sure completions dont run off screen
(set-prefix-key (kbd "C-j"))
( set - prefix - key ( " F20 " ) )
(setf *mouse-focus-policy* :click)
(setf *window-border-style* :thick
*normal-border-width* 1
*maxsize-border-width* 1)
(init-load-path "~/.stumpwm.d/stumpwm-contrib/")
;; Float vlc windows that arent the main window. (eg the open file dialog)
(defun float-vlc-stuff (window)
(and (not (roled-p window "vlc-main"))
(classed-p window "vlc")
(typed-p window :dialog)))
(define-frame-preference nil
(:float t nil :match-properties-or-function float-vlc-stuff))
;; keep a list of loaded modules. this could be simplified.
(let ((loaded-modules-list nil))
(defun use-module (module-name)
(labels ((%use-module (named-module)
(let* ((mod (cond ((stringp named-module) named-module)
((symbolp named-module)
(format nil "~a" named-module))
(t (error "could not convert datum ~a to an acceptable module name" named-module))))
(module (find-module (string-downcase mod))))
(if module
(progn
(asdf:operate 'asdf:load-op module)
(unless (member module loaded-modules-list :test #'string=)
(setf loaded-modules-list
(cons module loaded-modules-list))))
(error "Could not load or find module: ~s" module-name)))))
(if (listp module-name)
(mapcar #'%use-module module-name)
(%use-module module-name))))
(defun list-loaded-modules ()
loaded-modules-list))
(use-module '("hostname" "cpu" "stumptray"))
(stumptray::add-mode-line-hooks)
(setf *window-format* "%m%n%s%20c")
(load "~/.stumpwm.d/utilities.lisp")
(load "~/.stumpwm.d/commands.lisp")
(load "~/.stumpwm.d/keybindings.lisp")
(load "~/.stumpwm.d/rebind-keys.lisp")
(load "~/.stumpwm.d/swank-server.lisp")
(load "~/.stumpwm.d/mode-line.lisp")
;; grabbed pointer anyone?
(setf *grab-pointer-character* 50)
(setf *grab-pointer-character-mask* 51)
cool cursors : 40 , 32 , 30 , 48
| null | https://raw.githubusercontent.com/szos/My-Stumpwm-Init/c0acd5a98671f0d95290fbdef0dbac58fd64c494/init.lisp | lisp | make sure completions dont run off screen
Float vlc windows that arent the main window. (eg the open file dialog)
keep a list of loaded modules. this could be simplified.
grabbed pointer anyone? | (in-package :stumpwm)
(set-prefix-key (kbd "C-j"))
( set - prefix - key ( " F20 " ) )
(setf *mouse-focus-policy* :click)
(setf *window-border-style* :thick
*normal-border-width* 1
*maxsize-border-width* 1)
(init-load-path "~/.stumpwm.d/stumpwm-contrib/")
(defun float-vlc-stuff (window)
(and (not (roled-p window "vlc-main"))
(classed-p window "vlc")
(typed-p window :dialog)))
(define-frame-preference nil
(:float t nil :match-properties-or-function float-vlc-stuff))
(let ((loaded-modules-list nil))
(defun use-module (module-name)
(labels ((%use-module (named-module)
(let* ((mod (cond ((stringp named-module) named-module)
((symbolp named-module)
(format nil "~a" named-module))
(t (error "could not convert datum ~a to an acceptable module name" named-module))))
(module (find-module (string-downcase mod))))
(if module
(progn
(asdf:operate 'asdf:load-op module)
(unless (member module loaded-modules-list :test #'string=)
(setf loaded-modules-list
(cons module loaded-modules-list))))
(error "Could not load or find module: ~s" module-name)))))
(if (listp module-name)
(mapcar #'%use-module module-name)
(%use-module module-name))))
(defun list-loaded-modules ()
loaded-modules-list))
(use-module '("hostname" "cpu" "stumptray"))
(stumptray::add-mode-line-hooks)
(setf *window-format* "%m%n%s%20c")
(load "~/.stumpwm.d/utilities.lisp")
(load "~/.stumpwm.d/commands.lisp")
(load "~/.stumpwm.d/keybindings.lisp")
(load "~/.stumpwm.d/rebind-keys.lisp")
(load "~/.stumpwm.d/swank-server.lisp")
(load "~/.stumpwm.d/mode-line.lisp")
(setf *grab-pointer-character* 50)
(setf *grab-pointer-character-mask* 51)
cool cursors : 40 , 32 , 30 , 48
|
d1008eca33e3a603c9a071765441d143bb25f0b73511131e7b5c27091bf386b0 | nackjicholson/haskellbook-solutions | exercises.hs | -- chapter10/exercises.hs
module Exercises where
import Data.List
stops :: String
stops = "pbtdkg"
vowels :: String
vowels = "aeiou"
1(a ) Write a function that takes inputs from stops and vowels and
makes 3 - tuples of all possible stop - vowel - stop combinations .
These will not all correspond to real words in English , although
-- the stop-vowel-stop pattern is common enough that
-- many of them will.
stopVowelStopCombos ::[(Char, Char, Char)]
stopVowelStopCombos = [(s1, v, s2) | s1 <- stops, v <- vowels, s2 <- stops]
1(b ) Modify that function so that it only returns the combinations
-- that begin with a p.
pCombos :: [(Char, Char, Char)]
pCombos = [(s1, v, s2) | s1 <- stops, v <- vowels, s2 <- stops, s1 == 'p']
1(c ) Now set up lists of nouns and verbs ( instead of stops and
-- vowels) and modify the function to make tuples representing
-- possible noun-verb-noun sentences.
nouns, verbs :: [String]
nouns = ["larry", "curly", "moe"]
verbs = ["hits", "slaps", "kicks"]
stoogeCombos :: [(String, String, String)]
stoogeCombos = [(n1, v, n2) | n1 <- nouns, v <- verbs, n2 <- nouns]
3 .
avgWordLength :: (Fractional a) => String -> a
avgWordLength text = numberOfLetters / numberOfWords
where numberOfWords = (fromIntegral . length . words) text
numberOfLetters = sum (map (fromIntegral . length) (words text))
-- Functions using Folds
1 . returns True if any in the list is True .
myOr :: [Bool] -> Bool
myOr = foldr (||) False
2 . returns True if a - > Bool applied to any of the values in the
-- list returns True.
myAny :: (a -> Bool) -> [a] -> Bool
myAny f = foldr (\a b -> f a || b) False
3 . In addition to the recursive and fold based myElem , write a version
-- that uses any.
myElem :: Eq a => a -> [a] -> Bool
myElem x = any (==x)
4 . Implement myReverse , do n’t worry about trying to make it lazy .
myReverse :: [a] -> [a]
myReverse = foldl (flip (:)) []
5 . Write in terms of foldr . It should have the same behavior
-- as the built-in map.
myMap :: (a -> b) -> [a] -> [b]
myMap f = foldr ((:) . f) []
6 . Write in terms of foldr . It should have the same behavior
-- as the built-in filter.
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f = foldr (\x xs -> if f x then x:xs else xs) []
7 . flattens a list of lists into a list
squish :: [[a]] -> [a]
squish = foldr (++) []
8 . maps a function over a list and concatenates the results .
squishMap :: (a -> [b]) -> [a] -> [b]
squishMap f = foldr ((++) . f) []
9 . flattens a list of lists into a list . This time re - use the
function .
squishAgain :: [[a]] -> [a]
squishAgain = squishMap id
-- 10. myMaximumBy takes a comparison function and a list and returns
-- the greatest element of the list based on the last value that the
comparison returned GT for .
myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
myMaximumBy _ [] = undefined
myMaximumBy f (x:xs) = foldl compareFn x xs
where compareFn b x' = if f x' b == GT then x' else b
11 . takes a comparison function and a list and returns
-- the least element of the list based on the last value that the comparison
returned LT for .
myMinimumBy :: (a -> a -> Ordering) -> [a] -> a
myMinimumBy _ [] = undefined
myMinimumBy f (x:xs) = foldl compareFn x xs
where compareFn b x' = if f x' b == LT then x' else b
| null | https://raw.githubusercontent.com/nackjicholson/haskellbook-solutions/c21bd87773734ba2ae1559553a6a4d10891c61c8/chapter10/exercises.hs | haskell | chapter10/exercises.hs
the stop-vowel-stop pattern is common enough that
many of them will.
that begin with a p.
vowels) and modify the function to make tuples representing
possible noun-verb-noun sentences.
Functions using Folds
list returns True.
that uses any.
as the built-in map.
as the built-in filter.
10. myMaximumBy takes a comparison function and a list and returns
the greatest element of the list based on the last value that the
the least element of the list based on the last value that the comparison | module Exercises where
import Data.List
stops :: String
stops = "pbtdkg"
vowels :: String
vowels = "aeiou"
1(a ) Write a function that takes inputs from stops and vowels and
makes 3 - tuples of all possible stop - vowel - stop combinations .
These will not all correspond to real words in English , although
stopVowelStopCombos ::[(Char, Char, Char)]
stopVowelStopCombos = [(s1, v, s2) | s1 <- stops, v <- vowels, s2 <- stops]
1(b ) Modify that function so that it only returns the combinations
pCombos :: [(Char, Char, Char)]
pCombos = [(s1, v, s2) | s1 <- stops, v <- vowels, s2 <- stops, s1 == 'p']
1(c ) Now set up lists of nouns and verbs ( instead of stops and
nouns, verbs :: [String]
nouns = ["larry", "curly", "moe"]
verbs = ["hits", "slaps", "kicks"]
stoogeCombos :: [(String, String, String)]
stoogeCombos = [(n1, v, n2) | n1 <- nouns, v <- verbs, n2 <- nouns]
3 .
avgWordLength :: (Fractional a) => String -> a
avgWordLength text = numberOfLetters / numberOfWords
where numberOfWords = (fromIntegral . length . words) text
numberOfLetters = sum (map (fromIntegral . length) (words text))
1 . returns True if any in the list is True .
myOr :: [Bool] -> Bool
myOr = foldr (||) False
2 . returns True if a - > Bool applied to any of the values in the
myAny :: (a -> Bool) -> [a] -> Bool
myAny f = foldr (\a b -> f a || b) False
3 . In addition to the recursive and fold based myElem , write a version
myElem :: Eq a => a -> [a] -> Bool
myElem x = any (==x)
4 . Implement myReverse , do n’t worry about trying to make it lazy .
myReverse :: [a] -> [a]
myReverse = foldl (flip (:)) []
5 . Write in terms of foldr . It should have the same behavior
myMap :: (a -> b) -> [a] -> [b]
myMap f = foldr ((:) . f) []
6 . Write in terms of foldr . It should have the same behavior
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f = foldr (\x xs -> if f x then x:xs else xs) []
7 . flattens a list of lists into a list
squish :: [[a]] -> [a]
squish = foldr (++) []
8 . maps a function over a list and concatenates the results .
squishMap :: (a -> [b]) -> [a] -> [b]
squishMap f = foldr ((++) . f) []
9 . flattens a list of lists into a list . This time re - use the
function .
squishAgain :: [[a]] -> [a]
squishAgain = squishMap id
comparison returned GT for .
myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
myMaximumBy _ [] = undefined
myMaximumBy f (x:xs) = foldl compareFn x xs
where compareFn b x' = if f x' b == GT then x' else b
11 . takes a comparison function and a list and returns
returned LT for .
myMinimumBy :: (a -> a -> Ordering) -> [a] -> a
myMinimumBy _ [] = undefined
myMinimumBy f (x:xs) = foldl compareFn x xs
where compareFn b x' = if f x' b == LT then x' else b
|
0388fe779b3b58de6b3b71187cec1ef20d16fa20f0657d3080bc3ea9c2c32869 | ronxin/stolzen | ex3.28.scm | #lang scheme
(define or-gate-delay 1)
(define (or-gate in1 in2 output)
(define (or-action-procedure)
(let
((new-value
(logical-or (get-signal in1) (get-signal in2))))
(after-delay or-gate-delay
(lambda () (set-signal! output new-value)))
)
)
(add-action! in1 or-action-procedure)
(add-action! in2 or-action-procedure)
(void)
)
(define (logical-or s1 s2)
(cond
((and (= s1 1) (= s2 1)) 1)
((and (= s1 0) (= s2 1)) 1)
((and (= s1 1) (= s2 0)) 1)
((and (= s1 0) (= s2 0)) 0)
(else
(error "Invalid signal" s))
)
)
| null | https://raw.githubusercontent.com/ronxin/stolzen/bb13d0a7deea53b65253bb4b61aaf2abe4467f0d/sicp/chapter3/3.3/ex3.28.scm | scheme | #lang scheme
(define or-gate-delay 1)
(define (or-gate in1 in2 output)
(define (or-action-procedure)
(let
((new-value
(logical-or (get-signal in1) (get-signal in2))))
(after-delay or-gate-delay
(lambda () (set-signal! output new-value)))
)
)
(add-action! in1 or-action-procedure)
(add-action! in2 or-action-procedure)
(void)
)
(define (logical-or s1 s2)
(cond
((and (= s1 1) (= s2 1)) 1)
((and (= s1 0) (= s2 1)) 1)
((and (= s1 1) (= s2 0)) 1)
((and (= s1 0) (= s2 0)) 0)
(else
(error "Invalid signal" s))
)
)
| |
3cccbfbb3661a41d4c62801a08b2ddd295e5954be25c150aac6a8314ac69be1c | aeolus-project/zephyrus | json_v1_v.mli | Auto - generated from " json_v1.atd "
(** Type definition for syntax version. *)
(** Type definitions for naming. *)
type version = Json_versions_t.version
type component_type_name = Json_v1_t.component_type_name
type port_name = Json_v1_t.port_name
type component_name = Json_v1_t.component_name
type package_name = Json_v1_t.package_name
type repository_name = Json_v1_t.repository_name
type location_name = Json_v1_t.location_name
* Type definitions for Universe .
type resource_name = Json_v1_t.resource_name
type provide_arity = Json_v1_t.provide_arity
type require_arity = Json_v1_t.require_arity
type resource_consumption = Json_v1_t.resource_consumption
type resource_provide_arity = Json_v1_t.resource_provide_arity
type component_type = Json_v1_t.component_type = {
atd name
atd provide
atd require
component_type_conflict (*atd conflict *): port_name list;
atd consume
(resource_name * resource_consumption) list
}
type component_types = Json_v1_t.component_types
type package = Json_v1_t.package = {
atd name
atd depend
package_conflict (*atd conflict *): package_name list;
atd consume
(resource_name * resource_consumption) list
}
type packages = Json_v1_t.packages
type repository = Json_v1_t.repository = {
atd name
atd packages
}
type repositories = Json_v1_t.repositories
type package_names = Json_v1_t.package_names
(** Type definitions for Configuration. *)
type universe = Json_v1_t.universe = {
atd version
atd component_types
universe_implementation (*atd implementation *):
(component_type_name * package_names) list;
universe_repositories (*atd repositories *): repositories
}
type resources_provided = Json_v1_t.resources_provided
type location_cost = Json_v1_t.location_cost
type location = Json_v1_t.location = {
atd name
location_provide_resources (*atd provide_resources *): resources_provided;
atd repository
location_packages_installed (*atd packages_installed *): package_name list;
location_cost (*atd cost *): location_cost
}
type component = Json_v1_t.component = {
atd name
component_type (*atd component_type_workaround *): component_type_name;
atd location
}
type binding = Json_v1_t.binding = {
atd port
binding_requirer (*atd requirer *): component_name;
binding_provider (*atd provider *): component_name
}
type configuration = Json_v1_t.configuration = {
atd version
configuration_locations (*atd locations *): location list;
atd components
configuration_bindings (*atd bindings *): binding list
}
val validate_version :
Ag_util.Validation.path -> version -> Ag_util.Validation.error option
(** Validate a value of type {!version}. *)
val validate_component_type_name :
Ag_util.Validation.path -> component_type_name -> Ag_util.Validation.error option
(** Validate a value of type {!component_type_name}. *)
val validate_port_name :
Ag_util.Validation.path -> port_name -> Ag_util.Validation.error option
(** Validate a value of type {!port_name}. *)
val validate_component_name :
Ag_util.Validation.path -> component_name -> Ag_util.Validation.error option
(** Validate a value of type {!component_name}. *)
val validate_package_name :
Ag_util.Validation.path -> package_name -> Ag_util.Validation.error option
(** Validate a value of type {!package_name}. *)
val validate_repository_name :
Ag_util.Validation.path -> repository_name -> Ag_util.Validation.error option
(** Validate a value of type {!repository_name}. *)
val validate_location_name :
Ag_util.Validation.path -> location_name -> Ag_util.Validation.error option
(** Validate a value of type {!location_name}. *)
val validate_resource_name :
Ag_util.Validation.path -> resource_name -> Ag_util.Validation.error option
(** Validate a value of type {!resource_name}. *)
val validate_provide_arity :
Ag_util.Validation.path -> provide_arity -> Ag_util.Validation.error option
(** Validate a value of type {!provide_arity}. *)
val validate_require_arity :
Ag_util.Validation.path -> require_arity -> Ag_util.Validation.error option
(** Validate a value of type {!require_arity}. *)
val validate_resource_consumption :
Ag_util.Validation.path -> resource_consumption -> Ag_util.Validation.error option
* Validate a value of type { ! .
val validate_resource_provide_arity :
Ag_util.Validation.path -> resource_provide_arity -> Ag_util.Validation.error option
(** Validate a value of type {!resource_provide_arity}. *)
val create_component_type :
component_type_name: component_type_name ->
?component_type_provide: (port_name * provide_arity) list ->
?component_type_require: (port_name * require_arity) list ->
?component_type_conflict: port_name list ->
?component_type_consume: (resource_name * resource_consumption) list ->
unit -> component_type
(** Create a record of type {!component_type}. *)
val validate_component_type :
Ag_util.Validation.path -> component_type -> Ag_util.Validation.error option
(** Validate a value of type {!component_type}. *)
val validate_component_types :
Ag_util.Validation.path -> component_types -> Ag_util.Validation.error option
(** Validate a value of type {!component_types}. *)
val create_package :
package_name: package_name ->
?package_depend: package_name list list ->
?package_conflict: package_name list ->
?package_consume: (resource_name * resource_consumption) list ->
unit -> package
(** Create a record of type {!package}. *)
val validate_package :
Ag_util.Validation.path -> package -> Ag_util.Validation.error option
(** Validate a value of type {!package}. *)
val validate_packages :
Ag_util.Validation.path -> packages -> Ag_util.Validation.error option
(** Validate a value of type {!packages}. *)
val create_repository :
repository_name: repository_name ->
?repository_packages: package list ->
unit -> repository
(** Create a record of type {!repository}. *)
val validate_repository :
Ag_util.Validation.path -> repository -> Ag_util.Validation.error option
(** Validate a value of type {!repository}. *)
val validate_repositories :
Ag_util.Validation.path -> repositories -> Ag_util.Validation.error option
(** Validate a value of type {!repositories}. *)
val validate_package_names :
Ag_util.Validation.path -> package_names -> Ag_util.Validation.error option
(** Validate a value of type {!package_names}. *)
val create_universe :
universe_version: version ->
?universe_component_types: component_types ->
?universe_implementation: (component_type_name * package_names) list ->
?universe_repositories: repositories ->
unit -> universe
(** Create a record of type {!universe}. *)
val validate_universe :
Ag_util.Validation.path -> universe -> Ag_util.Validation.error option
(** Validate a value of type {!universe}. *)
val validate_resources_provided :
Ag_util.Validation.path -> resources_provided -> Ag_util.Validation.error option
(** Validate a value of type {!resources_provided}. *)
val validate_location_cost :
Ag_util.Validation.path -> location_cost -> Ag_util.Validation.error option
(** Validate a value of type {!location_cost}. *)
val create_location :
location_name: location_name ->
?location_provide_resources: resources_provided ->
location_repository: repository_name ->
?location_packages_installed: package_name list ->
?location_cost: location_cost ->
unit -> location
(** Create a record of type {!location}. *)
val validate_location :
Ag_util.Validation.path -> location -> Ag_util.Validation.error option
(** Validate a value of type {!location}. *)
val create_component :
component_name: component_name ->
component_type: component_type_name ->
component_location: location_name ->
unit -> component
(** Create a record of type {!component}. *)
val validate_component :
Ag_util.Validation.path -> component -> Ag_util.Validation.error option
(** Validate a value of type {!component}. *)
val create_binding :
binding_port: port_name ->
binding_requirer: component_name ->
binding_provider: component_name ->
unit -> binding
(** Create a record of type {!binding}. *)
val validate_binding :
Ag_util.Validation.path -> binding -> Ag_util.Validation.error option
(** Validate a value of type {!binding}. *)
val create_configuration :
configuration_version: version ->
?configuration_locations: location list ->
?configuration_components: component list ->
?configuration_bindings: binding list ->
unit -> configuration
(** Create a record of type {!configuration}. *)
val validate_configuration :
Ag_util.Validation.path -> configuration -> Ag_util.Validation.error option
(** Validate a value of type {!configuration}. *)
| null | https://raw.githubusercontent.com/aeolus-project/zephyrus/0b52de4038bbab724e6a9628430165a7f09f77ae/src/atd/json_v1_v.mli | ocaml | * Type definition for syntax version.
* Type definitions for naming.
atd conflict
atd conflict
* Type definitions for Configuration.
atd implementation
atd repositories
atd provide_resources
atd packages_installed
atd cost
atd component_type_workaround
atd requirer
atd provider
atd locations
atd bindings
* Validate a value of type {!version}.
* Validate a value of type {!component_type_name}.
* Validate a value of type {!port_name}.
* Validate a value of type {!component_name}.
* Validate a value of type {!package_name}.
* Validate a value of type {!repository_name}.
* Validate a value of type {!location_name}.
* Validate a value of type {!resource_name}.
* Validate a value of type {!provide_arity}.
* Validate a value of type {!require_arity}.
* Validate a value of type {!resource_provide_arity}.
* Create a record of type {!component_type}.
* Validate a value of type {!component_type}.
* Validate a value of type {!component_types}.
* Create a record of type {!package}.
* Validate a value of type {!package}.
* Validate a value of type {!packages}.
* Create a record of type {!repository}.
* Validate a value of type {!repository}.
* Validate a value of type {!repositories}.
* Validate a value of type {!package_names}.
* Create a record of type {!universe}.
* Validate a value of type {!universe}.
* Validate a value of type {!resources_provided}.
* Validate a value of type {!location_cost}.
* Create a record of type {!location}.
* Validate a value of type {!location}.
* Create a record of type {!component}.
* Validate a value of type {!component}.
* Create a record of type {!binding}.
* Validate a value of type {!binding}.
* Create a record of type {!configuration}.
* Validate a value of type {!configuration}. | Auto - generated from " json_v1.atd "
type version = Json_versions_t.version
type component_type_name = Json_v1_t.component_type_name
type port_name = Json_v1_t.port_name
type component_name = Json_v1_t.component_name
type package_name = Json_v1_t.package_name
type repository_name = Json_v1_t.repository_name
type location_name = Json_v1_t.location_name
* Type definitions for Universe .
type resource_name = Json_v1_t.resource_name
type provide_arity = Json_v1_t.provide_arity
type require_arity = Json_v1_t.require_arity
type resource_consumption = Json_v1_t.resource_consumption
type resource_provide_arity = Json_v1_t.resource_provide_arity
type component_type = Json_v1_t.component_type = {
atd name
atd provide
atd require
atd consume
(resource_name * resource_consumption) list
}
type component_types = Json_v1_t.component_types
type package = Json_v1_t.package = {
atd name
atd depend
atd consume
(resource_name * resource_consumption) list
}
type packages = Json_v1_t.packages
type repository = Json_v1_t.repository = {
atd name
atd packages
}
type repositories = Json_v1_t.repositories
type package_names = Json_v1_t.package_names
type universe = Json_v1_t.universe = {
atd version
atd component_types
(component_type_name * package_names) list;
}
type resources_provided = Json_v1_t.resources_provided
type location_cost = Json_v1_t.location_cost
type location = Json_v1_t.location = {
atd name
atd repository
}
type component = Json_v1_t.component = {
atd name
atd location
}
type binding = Json_v1_t.binding = {
atd port
}
type configuration = Json_v1_t.configuration = {
atd version
atd components
}
val validate_version :
Ag_util.Validation.path -> version -> Ag_util.Validation.error option
val validate_component_type_name :
Ag_util.Validation.path -> component_type_name -> Ag_util.Validation.error option
val validate_port_name :
Ag_util.Validation.path -> port_name -> Ag_util.Validation.error option
val validate_component_name :
Ag_util.Validation.path -> component_name -> Ag_util.Validation.error option
val validate_package_name :
Ag_util.Validation.path -> package_name -> Ag_util.Validation.error option
val validate_repository_name :
Ag_util.Validation.path -> repository_name -> Ag_util.Validation.error option
val validate_location_name :
Ag_util.Validation.path -> location_name -> Ag_util.Validation.error option
val validate_resource_name :
Ag_util.Validation.path -> resource_name -> Ag_util.Validation.error option
val validate_provide_arity :
Ag_util.Validation.path -> provide_arity -> Ag_util.Validation.error option
val validate_require_arity :
Ag_util.Validation.path -> require_arity -> Ag_util.Validation.error option
val validate_resource_consumption :
Ag_util.Validation.path -> resource_consumption -> Ag_util.Validation.error option
* Validate a value of type { ! .
val validate_resource_provide_arity :
Ag_util.Validation.path -> resource_provide_arity -> Ag_util.Validation.error option
val create_component_type :
component_type_name: component_type_name ->
?component_type_provide: (port_name * provide_arity) list ->
?component_type_require: (port_name * require_arity) list ->
?component_type_conflict: port_name list ->
?component_type_consume: (resource_name * resource_consumption) list ->
unit -> component_type
val validate_component_type :
Ag_util.Validation.path -> component_type -> Ag_util.Validation.error option
val validate_component_types :
Ag_util.Validation.path -> component_types -> Ag_util.Validation.error option
val create_package :
package_name: package_name ->
?package_depend: package_name list list ->
?package_conflict: package_name list ->
?package_consume: (resource_name * resource_consumption) list ->
unit -> package
val validate_package :
Ag_util.Validation.path -> package -> Ag_util.Validation.error option
val validate_packages :
Ag_util.Validation.path -> packages -> Ag_util.Validation.error option
val create_repository :
repository_name: repository_name ->
?repository_packages: package list ->
unit -> repository
val validate_repository :
Ag_util.Validation.path -> repository -> Ag_util.Validation.error option
val validate_repositories :
Ag_util.Validation.path -> repositories -> Ag_util.Validation.error option
val validate_package_names :
Ag_util.Validation.path -> package_names -> Ag_util.Validation.error option
val create_universe :
universe_version: version ->
?universe_component_types: component_types ->
?universe_implementation: (component_type_name * package_names) list ->
?universe_repositories: repositories ->
unit -> universe
val validate_universe :
Ag_util.Validation.path -> universe -> Ag_util.Validation.error option
val validate_resources_provided :
Ag_util.Validation.path -> resources_provided -> Ag_util.Validation.error option
val validate_location_cost :
Ag_util.Validation.path -> location_cost -> Ag_util.Validation.error option
val create_location :
location_name: location_name ->
?location_provide_resources: resources_provided ->
location_repository: repository_name ->
?location_packages_installed: package_name list ->
?location_cost: location_cost ->
unit -> location
val validate_location :
Ag_util.Validation.path -> location -> Ag_util.Validation.error option
val create_component :
component_name: component_name ->
component_type: component_type_name ->
component_location: location_name ->
unit -> component
val validate_component :
Ag_util.Validation.path -> component -> Ag_util.Validation.error option
val create_binding :
binding_port: port_name ->
binding_requirer: component_name ->
binding_provider: component_name ->
unit -> binding
val validate_binding :
Ag_util.Validation.path -> binding -> Ag_util.Validation.error option
val create_configuration :
configuration_version: version ->
?configuration_locations: location list ->
?configuration_components: component list ->
?configuration_bindings: binding list ->
unit -> configuration
val validate_configuration :
Ag_util.Validation.path -> configuration -> Ag_util.Validation.error option
|
aafa0cb8ae963e66986d7fe98da22e03bd2f8bc82ec0892a0e169f72dfe5b32d | cardmagic/lucash | interp.scm | ; -*- Mode: Scheme; Syntax: Scheme; Package: Scheme; -*-
Copyright ( c ) 1993 - 1999 by and . See file COPYING .
;Need to fix the byte-code compiler to make jump etc. offsets from the
;beginning of the instruction.
; This is file interp.scm.
; Interpreter state
(define *template*) ; current template
(define *code-pointer*) ; pointer to next instruction byte
(define *val*) ; last value produced
vector of procedures , one per opcode
vector of procedures , one per interrupt type
Two registers used only by the RTS ( except for one hack ; see GET - CURRENT - PORT
in prim-io.scm ) .
(define *current-thread*) ; dynamic state
(define *session-data*) ; session state
; Finalizers
(define *finalizer-alist*) ; list of (<thing> . <procedure>) pairs
(define *finalize-these*) ; list of such pairs that should be executed
; Interrupts
(define *enabled-interrupts*) ; bitmask of enabled interrupts
(define s48-*pending-interrupt?*) ; true if an interrupt is pending
(define *interrupted-template*) ; template in place when the most recent
; interrupt occured - for profiling
(define *interrupt-template*) ; used to return from interrupts
(define *exception-template*) ; used to mark exception continuations
; These are referred to from other modules.
(define (val) *val*)
(define (set-val! val) (set! *val* val))
(define (code-pointer) *code-pointer*)
(define (current-thread) *current-thread*)
;----------------
(define (clear-registers)
(reset-stack-pointer false)
(set-current-env! unspecific-value)
(set-template! *interrupt-template* ; has to be some template
(enter-fixnum 0))
(set! *val* unspecific-value)
(set! *current-thread* null)
(set! *session-data* null)
(set! *exception-handlers* null)
(set! *interrupt-handlers* null)
(set! *enabled-interrupts* 0)
(set! *finalizer-alist* null)
(set! *finalize-these* null)
(pending-interrupts-clear!)
(set! s48-*pending-interrupt?* #f)
(set! *interrupted-template* false)
unspecific-value)
for saving the pc across GC 's
(add-gc-root!
(lambda ()
(set! *saved-pc* (current-pc)) ; headers may be busted here...
(set! *template* (s48-trace-value *template*))
(set! *val* (s48-trace-value *val*))
(set! *current-thread* (s48-trace-value *current-thread*))
(set! *session-data* (s48-trace-value *session-data*))
(set! *exception-handlers* (s48-trace-value *exception-handlers*))
(set! *exception-template* (s48-trace-value *exception-template*))
(set! *interrupt-handlers* (s48-trace-value *interrupt-handlers*))
(set! *interrupt-template* (s48-trace-value *interrupt-template*))
(set! *interrupted-template* (s48-trace-value *interrupted-template*))
(set! *finalize-these* (s48-trace-value *finalize-these*))
(set! *os-signal-list* (s48-trace-value *os-signal-list*))
(trace-finalizer-alist!)
; These could be moved to the appropriate modules.
(set-current-env! (s48-trace-value (current-env)))
(trace-io s48-trace-value)
(trace-stack s48-trace-locations! s48-trace-stob-contents! s48-trace-value)))
(add-post-gc-cleanup!
(lambda ()
(set-template! *template* *saved-pc*)
(partition-finalizer-alist!)
(close-untraced-channels!)
(note-interrupt! (enum interrupt post-gc))))
;----------------
; Dealing with the list of finalizers.
;
; Pre-gc:
Trace the contents of every finalizer object , updating them in oldspace .
; If any contains a pointer to itself, quit and trace it normally.
; If any have already been copied, ignore it.
; Post-gc:
; Check each to see if each has been copied. If not, copy it. There is
; no need to trace any additional pointers.
; Walk down the finalizer alist, tracing the procedures and the contents of
; the things.
(define (trace-finalizer-alist!)
(let loop ((alist *finalizer-alist*))
(if (not (vm-eq? alist null))
(let* ((pair (vm-car alist)))
(if (not (s48-extant? (vm-car pair))) ; if not already traced
(s48-trace-stob-contents! (vm-car pair)))
(vm-set-cdr! pair (s48-trace-value (vm-cdr pair)))
(loop (vm-cdr alist))))))
; Walk down the finalizer alist, separating out the pairs whose things
; have been copied.
(define (partition-finalizer-alist!)
(let loop ((alist *finalizer-alist*) (okay null) (goners null))
(if (vm-eq? alist null)
(begin
(set! *finalizer-alist* okay)
(set! *finalize-these* (vm-append! goners *finalize-these*)))
(let* ((alist (s48-trace-value alist))
(pair (s48-trace-value (vm-car alist)))
(thing (vm-car pair))
(next (vm-cdr alist))
(traced? (s48-extant? thing)))
(vm-set-car! pair (s48-trace-value thing))
(vm-set-car! alist pair)
(cond (traced?
(vm-set-cdr! alist okay)
(loop next alist goners))
(else
(vm-set-cdr! alist goners)
(loop next okay alist)))))))
(define (vm-append! l1 l2)
(if (vm-eq? l1 null)
l2
(let ((last-pair (let loop ((l l1))
(if (vm-eq? (vm-cdr l) null)
l
(loop (vm-cdr l))))))
(vm-set-cdr! last-pair l2)
l1)))
;----------------
(define (set-template! tem pc)
(set! *template* tem)
(set-code-pointer! (template-code tem) (extract-fixnum pc)))
(define (set-code-pointer! code pc)
(set! *code-pointer* (address+ (address-after-header code) pc)))
(define (code-pointer->pc pointer template)
(enter-fixnum (address-difference
pointer
(address-after-header (template-code template)))))
(define (current-pc)
(code-pointer->pc *code-pointer* *template*))
(define (initialize-interpreter+gc) ;Used only at startup
(let ((key (ensure-space (op-template-size 2))))
(set! *interrupt-template*
(make-template-containing-ops (enum op ignore-values)
(enum op return-from-interrupt)
key))
(set! *exception-template*
(make-template-containing-ops (enum op return-from-exception)
(enum op false) ; ignored
key))))
;----------------
; Continuations
(define (push-continuation! code-pointer size)
(let ((pc (code-pointer->pc code-pointer *template*)))
(push-continuation-on-stack *template* pc size)))
(define (pop-continuation!)
(pop-continuation-from-stack set-template!))
;----------------
; Instruction stream access
(define (code-byte index)
(fetch-byte (address+ *code-pointer* (+ index 1))))
(define (code-offset index)
(adjoin-bits (code-byte index)
(code-byte (+ index 1))
bits-used-per-byte))
(define (get-literal index)
(template-ref *template* (code-offset index)))
; Return the current op-code. CODE-ARGS is the number of argument bytes that
; have been used.
(define (current-opcode)
(code-byte -1))
; INTERPRET is the main instruction dispatch for the interpreter.
;(define trace-instructions? #f)
;(define *bad-count* 0)
;(define *i* 0)
(define (interpret code-pointer)
; (if (and trace-instructions? (> *i* *bad-count*))
( write - instruction * template * ( extract - fixnum ( current - pc ) ) 1 # f ) )
( set ! * i * ( + * i * 1 ) )
((vector-ref opcode-dispatch (fetch-byte code-pointer))))
(define (continue bytes-used)
(set! *code-pointer* (address+ *code-pointer* (+ bytes-used 1)))
(goto interpret *code-pointer*))
(define (continue-with-value value bytes-used)
(set! *val* value)
(goto continue bytes-used))
;----------------
; Opcodes
(define (uuo)
(raise-exception unimplemented-instruction 0))
(define opcode-dispatch (make-vector op-count))
(vector+length-fill! opcode-dispatch op-count uuo)
(define-syntax define-opcode
(syntax-rules ()
((define-opcode op-name body ...)
(vector-set! opcode-dispatch (enum op op-name) (lambda () body ...)))))
;----------------
; Exception syntax
; For restartable exceptions the saved code-pointer points to the instruction
; following the offending one. For all other exceptions it points to the
; offending instruction.
;
; The ...* versions evaluate the exception enum argument, the plain ones
; invoke the enumeration.
(define-syntax raise-exception
(syntax-rules ()
((raise-exception why byte-args stuff ...)
(raise-exception* (enum exception why) byte-args stuff ...))))
(define-syntax count-exception-args
(syntax-rules ()
((count-exception-args) 0)
((count-exception-args arg1 rest ...)
(+ 1 (count-exception-args rest ...)))))
(define-syntax raise-exception*
(syntax-rules ()
((raise-exception* why byte-args arg1 ...)
(begin
add 1 for the opcode
(push arg1) ...
(goto raise (count-exception-args arg1 ...))))))
;----------------
; Exceptions
; The system reserves enough stack space to allow for an exception at any time.
; If the reserved space is used a gc must be done before the exception handler
; is called.
; New exception handlers in *val*.
(define-opcode set-exception-handlers!
(cond ((or (not (vm-vector? *val*))
(< (vm-vector-length *val*) op-count))
(raise-exception wrong-type-argument 0 *val*))
(else
(let ((temp *exception-handlers*))
(set! *exception-handlers* *val*)
(goto continue-with-value
temp
0)))))
; The current opcode and the exception are pushed as arguments to the handler.
; INSTRUCTION-SIZE is the size of the current instruction and is used to jump
; to the next instruction when returning. The exception is saved in the
; continuation for use in debugging.
(define (push-exception-continuation! exception instruction-size)
(let ((opcode (current-opcode)))
(push (enter-fixnum instruction-size))
(push (enter-fixnum exception))
(push *template*)
(push (current-pc))
(set-template! *exception-template* (enter-fixnum 0))
(push-continuation! *code-pointer* (arguments-on-stack))
(push (enter-fixnum opcode))
(push (enter-fixnum exception))))
(define-opcode return-from-exception
(let* ((pc (extract-fixnum (pop)))
(template (pop))
(exception (pop)) ; ignored
(size (extract-fixnum (pop))))
(set-template! template (enter-fixnum (+ pc size)))
(goto interpret *code-pointer*)))
;(define no-exceptions? #t)
(define (raise nargs)
( let ( ( opcode ( enumerand->name ( extract - fixnum ( stack - ref ( + nargs 1 ) ) ) op ) )
; (why (enumerand->name (extract-fixnum (stack-ref nargs)) exception)))
; (if (and no-exceptions?
; (not (and (eq? 'write-char opcode)
; (eq? 'buffer-full/empty why))))
( breakpoint " exception check ~A ~A ~A " opcode why ) ) )
;; try to be helpful when all collapses
(let* ((opcode (extract-fixnum (stack-ref (+ nargs 1))))
(lose (lambda (message)
(let ((why (extract-fixnum (stack-ref nargs))))
(write-string "Template UIDs: " (current-error-port))
(report-continuation-uids *template* (current-error-port))
(newline (current-error-port))
(if (and (eq? why (enum exception undefined-global))
(fixnum? (location-id (stack-ref (- nargs 1)))))
(error message opcode why
(extract-fixnum (location-id (stack-ref (- nargs 1)))))
(error message opcode why))))))
(if (not (vm-vector? *exception-handlers*))
(lose "exception-handlers is not a vector"))
(set! *val* (vm-vector-ref *exception-handlers* opcode))
(if (not (closure? *val*))
(lose "exception handler is not a closure"))
(goto call-exception-handler (+ nargs 2) opcode)))
;----------------
; Literals
Loaded from * template * into * val * , using either a one - byte or two - byte index .
(define-opcode literal ;Load a literal into *val*.
(goto continue-with-value
(get-literal 0)
2)) ; offset
(define-opcode small-literal
(goto continue-with-value
(template-ref *template* (code-byte 0))
2)) ; byte + wasted byte
;----------------
; Environment creation
; The MAKE-ENV instruction adds a env to the local environment.
; It pops values off the stack and stores them into the new env.
(define-opcode make-env
(pop-args-into-env (code-offset 0))
(goto continue 2)) ; offset
; Local variable access and assignment
(define-opcode local ;Load value of a local.
(goto finish-local (env-back (current-env) (code-byte 0)) 1))
(define-opcode local0
(goto finish-local (current-env) 0))
(define-opcode push-local0
(push *val*)
(goto finish-local (current-env) 1))
(define-opcode local0-push
(set! *val* (env-ref (current-env) (code-byte 0)))
(if (not (vm-eq? *val* unassigned-marker))
(begin
(push *val*)
(goto continue 2))
(raise-exception unassigned-local 2)))
(define-opcode local1
(goto finish-local (env-parent (current-env)) 0))
(define-opcode local2
(goto finish-local (env-parent (env-parent (current-env))) 0))
(define (finish-local env arg-count)
(set! *val* (env-ref env (code-byte arg-count)))
(if (not (vm-eq? *val* unassigned-marker))
(goto continue (+ arg-count 1))
(raise-exception unassigned-local (+ arg-count 1))))
(define-opcode big-local
(let ((back (code-offset 0)))
(set! *val* (env-ref (env-back (current-env) back)
(code-offset 2)))
(if (not (vm-eq? *val* unassigned-marker))
(goto continue 4) ; byte + offset
(raise-exception unassigned-local 4))))
(define-opcode set-local!
(let ((back (code-offset 0)))
(env-set! (env-back (current-env) back)
(code-offset 2)
*val*)
(set! *val* unspecific-value)
(goto continue 4))) ; byte + offset
;----------------
; Global variable access
(define-opcode global ;Load a global variable.
(let ((location (get-literal 0)))
(set! *val* (contents location))
(if (undefined? *val*) ;unbound or unassigned
(raise-exception undefined-global 2 location)
(goto continue 2)))) ; offset
(define-opcode set-global!
(let ((location (get-literal 0)))
(cond ((vm-eq? (contents location) unbound-marker)
(raise-exception undefined-global 2 location *val*))
(else
(set-contents! location *val*)
(goto continue-with-value
unspecific-value
2))))) ; offset
;----------------
Stack operation
(define-opcode push ;Push *val* onto the stack.
(push *val*)
(goto continue 0))
(define-opcode pop ;Pop *val* from the stack.
(goto continue-with-value
(pop)
0))
(define-opcode stack-ref
(goto continue-with-value
(stack-ref (code-byte 0))
1))
(define-opcode stack-set!
(stack-set! (code-byte 0) *val*)
(goto continue 1))
;----------------
; LAMBDA
(define-opcode closure
(let ((env (if (= 0 (code-byte 2))
(preserve-current-env (ensure-space (current-env-size)))
*val*)))
(receive (key env)
(ensure-space-saving-temp closure-size env)
(goto continue-with-value
(make-closure (get-literal 0) env key)
3))))
; Looks like:
; (enum op make-flat-env)
; number of vars
use * val * as first element ?
depth of first level
; number of vars in level
; offsets of vars in level
delta of depth of second level
; ...
(define-opcode make-flat-env
(let* ((total-count (code-byte 1))
(new-env (vm-make-vector total-count
(ensure-space (vm-vector-size total-count))))
(start-i (if (= 0 (code-byte 0))
0
(begin
(vm-vector-set! new-env 0 *val*)
1))))
(let loop ((i start-i)
(offset 2) ; count and use-*val*
(env (current-env)))
(if (= i total-count)
(goto continue-with-value
new-env
offset)
(let ((env (env-back env (code-byte offset)))
(count (code-byte (+ offset 1))))
(do ((count count (- count 1))
(i i (+ i 1))
(offset (+ offset 2) (+ offset 1))) ; env-back and count
((= count 0)
(loop i offset env))
(vm-vector-set! new-env
i
(vm-vector-ref env
(code-byte offset)))))))))
;----------------
; Continuation creation and invocation
(define-opcode make-cont ;Start a non-tail call.
(push-continuation! (address+ *code-pointer*
(code-offset 0))
(code-byte 2))
(goto continue 3))
(define-opcode make-big-cont ;Start a non-tail call.
(push-continuation! (address+ *code-pointer*
(code-offset 0))
(code-offset 2))
(goto continue 4))
(define-opcode return ;Invoke the continuation.
(pop-continuation!)
(goto interpret *code-pointer*))
; This is only used in the closed-compiled version of VALUES.
Stack is : ... argN rest - list N+1 total - arg - count .
If REST - LIST is non - empty then there are at least two arguments on the stack .
(define-opcode closed-values
(let* ((nargs (extract-fixnum (pop)))
(stack-nargs (extract-fixnum (pop)))
(rest-list (pop)))
(goto return-values stack-nargs rest-list (- nargs stack-nargs))))
; Same as the above, except that the value count is in the instruction stream
; and all of the arguments are on the stack.
; This is used for in-lining calls to VALUES.
(define-opcode values
(goto return-values (code-offset 0) null 0))
STACK - NARGS return values are on the stack . If there is only one value , pop
; it off and do a normal return. Otherwise, find the actual continuation
; and see if it ignores the values, wants the values, or doesn't know
; anything about them.
(define (return-values stack-nargs list-args list-arg-count)
if list - arg - count > 0 then stack - nargs > 1
(set! *val* (pop))
(pop-continuation!)
(goto interpret *code-pointer*))
(else
(let ((cont (peek-at-current-continuation)))
(if (continuation? cont)
(goto really-return-values
cont stack-nargs list-args list-arg-count)
(goto return-exception stack-nargs list-args))))))
; If the next op-code is:
; op/ignore-values - just return, ignoring the return values
; op/call-with-values - remove the continuation containing the consumer
; (the consumer is the only useful information it contains), and then call
; the consumer.
; anything else - only one argument was expected so raise an exception.
(define (really-return-values cont stack-nargs list-args list-arg-count)
(let ((next-op (code-vector-ref (template-code (continuation-template cont))
(extract-fixnum (continuation-pc cont)))))
(cond ((= next-op (enum op ignore-values))
(pop-continuation!)
(goto interpret *code-pointer*))
((= next-op (enum op call-with-values))
(skip-current-continuation!)
(set! *val* (continuation-ref cont continuation-cells))
(goto perform-application-with-rest-list stack-nargs
list-args
list-arg-count))
(else
(goto return-exception stack-nargs list-args)))))
; This would avoid the need for the consumer to be a closure. It doesn't
work because the NARGS check ( which would be the next instruction to be
; executed) assumes that a closure has just been called.
;(define (do-call-with-values nargs)
; (cond ((address= *cont* *bottom-of-stack*)
; (restore-from-continuation (continuation-cont *cont*))
; (set-continuation-cont! *bottom-of-stack* *cont*)
; (set! *cont* *bottom-of-stack*))
; (else
; (restore-from-continuation cont)))
( set ! * code - pointer * ( address+ * code - pointer * 1 ) ) ; move past ( enum op call - with - values
;) (goto interpret *code-pointer*))
(define (return-exception stack-nargs list-args)
(let ((args (pop-args->list* list-args stack-nargs)))
(raise-exception wrong-number-of-arguments -1 false args))) ; no next opcode
This is executed only if the producer returned exactly one value .
(define-opcode call-with-values
(let ((consumer (pop)))
(push *val*)
(set! *val* consumer)
(goto perform-application 1)))
; This is just a marker for the code that handles returns.
(define-opcode ignore-values
(goto continue 0))
;----------------
; Preserve the current continuation and put it in *val*.
(define-opcode current-cont
(let ((key (ensure-space (current-continuation-size))))
(goto continue-with-value
(current-continuation key)
0)))
(define-opcode with-continuation
(set-current-continuation! (pop))
(goto perform-application 0))
; only used in the stack underflow template
(define-opcode get-cont-from-heap
(let ((cont (get-continuation-from-heap)))
(cond ((continuation? cont)
(set-current-continuation! cont)
(goto continue 0))
((and (false? cont)
(fixnum? *val*)) ; VM returns here
(set! s48-*callback-return-stack-block* false) ; not from a callback
(reset-stack-pointer false) ; for libscsh
(extract-fixnum *val*))
(else
(set-current-continuation! false)
(raise-exception wrong-type-argument 0 *val* cont)))))
;----------------
; Control flow
; IF
(define-opcode jump-if-false
(cond ((false? *val*)
(set! *code-pointer*
(address+ *code-pointer*
(code-offset 0)))
(goto interpret *code-pointer*))
(else
(goto continue 2))))
; Unconditional jump
(define-opcode jump
(set! *code-pointer*
(address+ *code-pointer*
(code-offset 0)))
(goto interpret *code-pointer*))
; Computed goto
index is in * val * , the next byte is the number of offsets specified
; The default is to jump to the instruction following the offsets
; The instruction stream looks like
op / computed - goto max offset0 ... offsetmax-1 code - for - default ...
(define-opcode computed-goto
(if (not (fixnum? *val*))
(raise-exception wrong-type-argument -1 *val*) ; back up over opcode
(let ((max (code-byte 0))
(val (extract-fixnum *val*)))
(let ((offset (if (and (>= val 0)
(< val max))
(code-offset (+ (* val 2) 1))
(+ (* max 2) 2))))
(set! *code-pointer* (address+ *code-pointer* offset))
(goto interpret *code-pointer*)))))
;----------------
; Miscellaneous primitive procedures
(define-opcode unassigned
(goto continue-with-value
unassigned-marker
0))
(define-opcode unspecific
(goto continue-with-value
unspecific-value
0))
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scheme/vm/interp.scm | scheme | -*- Mode: Scheme; Syntax: Scheme; Package: Scheme; -*-
Need to fix the byte-code compiler to make jump etc. offsets from the
beginning of the instruction.
This is file interp.scm.
Interpreter state
current template
pointer to next instruction byte
last value produced
see GET - CURRENT - PORT
dynamic state
session state
Finalizers
list of (<thing> . <procedure>) pairs
list of such pairs that should be executed
Interrupts
bitmask of enabled interrupts
true if an interrupt is pending
template in place when the most recent
interrupt occured - for profiling
used to return from interrupts
used to mark exception continuations
These are referred to from other modules.
----------------
has to be some template
headers may be busted here...
These could be moved to the appropriate modules.
----------------
Dealing with the list of finalizers.
Pre-gc:
If any contains a pointer to itself, quit and trace it normally.
If any have already been copied, ignore it.
Post-gc:
Check each to see if each has been copied. If not, copy it. There is
no need to trace any additional pointers.
Walk down the finalizer alist, tracing the procedures and the contents of
the things.
if not already traced
Walk down the finalizer alist, separating out the pairs whose things
have been copied.
----------------
Used only at startup
ignored
----------------
Continuations
----------------
Instruction stream access
Return the current op-code. CODE-ARGS is the number of argument bytes that
have been used.
INTERPRET is the main instruction dispatch for the interpreter.
(define trace-instructions? #f)
(define *bad-count* 0)
(define *i* 0)
(if (and trace-instructions? (> *i* *bad-count*))
----------------
Opcodes
----------------
Exception syntax
For restartable exceptions the saved code-pointer points to the instruction
following the offending one. For all other exceptions it points to the
offending instruction.
The ...* versions evaluate the exception enum argument, the plain ones
invoke the enumeration.
----------------
Exceptions
The system reserves enough stack space to allow for an exception at any time.
If the reserved space is used a gc must be done before the exception handler
is called.
New exception handlers in *val*.
The current opcode and the exception are pushed as arguments to the handler.
INSTRUCTION-SIZE is the size of the current instruction and is used to jump
to the next instruction when returning. The exception is saved in the
continuation for use in debugging.
ignored
(define no-exceptions? #t)
(why (enumerand->name (extract-fixnum (stack-ref nargs)) exception)))
(if (and no-exceptions?
(not (and (eq? 'write-char opcode)
(eq? 'buffer-full/empty why))))
try to be helpful when all collapses
----------------
Literals
Load a literal into *val*.
offset
byte + wasted byte
----------------
Environment creation
The MAKE-ENV instruction adds a env to the local environment.
It pops values off the stack and stores them into the new env.
offset
Local variable access and assignment
Load value of a local.
byte + offset
byte + offset
----------------
Global variable access
Load a global variable.
unbound or unassigned
offset
offset
----------------
Push *val* onto the stack.
Pop *val* from the stack.
----------------
LAMBDA
Looks like:
(enum op make-flat-env)
number of vars
number of vars in level
offsets of vars in level
...
count and use-*val*
env-back and count
----------------
Continuation creation and invocation
Start a non-tail call.
Start a non-tail call.
Invoke the continuation.
This is only used in the closed-compiled version of VALUES.
Same as the above, except that the value count is in the instruction stream
and all of the arguments are on the stack.
This is used for in-lining calls to VALUES.
it off and do a normal return. Otherwise, find the actual continuation
and see if it ignores the values, wants the values, or doesn't know
anything about them.
If the next op-code is:
op/ignore-values - just return, ignoring the return values
op/call-with-values - remove the continuation containing the consumer
(the consumer is the only useful information it contains), and then call
the consumer.
anything else - only one argument was expected so raise an exception.
This would avoid the need for the consumer to be a closure. It doesn't
executed) assumes that a closure has just been called.
(define (do-call-with-values nargs)
(cond ((address= *cont* *bottom-of-stack*)
(restore-from-continuation (continuation-cont *cont*))
(set-continuation-cont! *bottom-of-stack* *cont*)
(set! *cont* *bottom-of-stack*))
(else
(restore-from-continuation cont)))
move past ( enum op call - with - values
) (goto interpret *code-pointer*))
no next opcode
This is just a marker for the code that handles returns.
----------------
Preserve the current continuation and put it in *val*.
only used in the stack underflow template
VM returns here
not from a callback
for libscsh
----------------
Control flow
IF
Unconditional jump
Computed goto
The default is to jump to the instruction following the offsets
The instruction stream looks like
back up over opcode
----------------
Miscellaneous primitive procedures | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
vector of procedures , one per opcode
vector of procedures , one per interrupt type
in prim-io.scm ) .
(define (val) *val*)
(define (set-val! val) (set! *val* val))
(define (code-pointer) *code-pointer*)
(define (current-thread) *current-thread*)
(define (clear-registers)
(reset-stack-pointer false)
(set-current-env! unspecific-value)
(enter-fixnum 0))
(set! *val* unspecific-value)
(set! *current-thread* null)
(set! *session-data* null)
(set! *exception-handlers* null)
(set! *interrupt-handlers* null)
(set! *enabled-interrupts* 0)
(set! *finalizer-alist* null)
(set! *finalize-these* null)
(pending-interrupts-clear!)
(set! s48-*pending-interrupt?* #f)
(set! *interrupted-template* false)
unspecific-value)
for saving the pc across GC 's
(add-gc-root!
(lambda ()
(set! *template* (s48-trace-value *template*))
(set! *val* (s48-trace-value *val*))
(set! *current-thread* (s48-trace-value *current-thread*))
(set! *session-data* (s48-trace-value *session-data*))
(set! *exception-handlers* (s48-trace-value *exception-handlers*))
(set! *exception-template* (s48-trace-value *exception-template*))
(set! *interrupt-handlers* (s48-trace-value *interrupt-handlers*))
(set! *interrupt-template* (s48-trace-value *interrupt-template*))
(set! *interrupted-template* (s48-trace-value *interrupted-template*))
(set! *finalize-these* (s48-trace-value *finalize-these*))
(set! *os-signal-list* (s48-trace-value *os-signal-list*))
(trace-finalizer-alist!)
(set-current-env! (s48-trace-value (current-env)))
(trace-io s48-trace-value)
(trace-stack s48-trace-locations! s48-trace-stob-contents! s48-trace-value)))
(add-post-gc-cleanup!
(lambda ()
(set-template! *template* *saved-pc*)
(partition-finalizer-alist!)
(close-untraced-channels!)
(note-interrupt! (enum interrupt post-gc))))
Trace the contents of every finalizer object , updating them in oldspace .
(define (trace-finalizer-alist!)
(let loop ((alist *finalizer-alist*))
(if (not (vm-eq? alist null))
(let* ((pair (vm-car alist)))
(s48-trace-stob-contents! (vm-car pair)))
(vm-set-cdr! pair (s48-trace-value (vm-cdr pair)))
(loop (vm-cdr alist))))))
(define (partition-finalizer-alist!)
(let loop ((alist *finalizer-alist*) (okay null) (goners null))
(if (vm-eq? alist null)
(begin
(set! *finalizer-alist* okay)
(set! *finalize-these* (vm-append! goners *finalize-these*)))
(let* ((alist (s48-trace-value alist))
(pair (s48-trace-value (vm-car alist)))
(thing (vm-car pair))
(next (vm-cdr alist))
(traced? (s48-extant? thing)))
(vm-set-car! pair (s48-trace-value thing))
(vm-set-car! alist pair)
(cond (traced?
(vm-set-cdr! alist okay)
(loop next alist goners))
(else
(vm-set-cdr! alist goners)
(loop next okay alist)))))))
(define (vm-append! l1 l2)
(if (vm-eq? l1 null)
l2
(let ((last-pair (let loop ((l l1))
(if (vm-eq? (vm-cdr l) null)
l
(loop (vm-cdr l))))))
(vm-set-cdr! last-pair l2)
l1)))
(define (set-template! tem pc)
(set! *template* tem)
(set-code-pointer! (template-code tem) (extract-fixnum pc)))
(define (set-code-pointer! code pc)
(set! *code-pointer* (address+ (address-after-header code) pc)))
(define (code-pointer->pc pointer template)
(enter-fixnum (address-difference
pointer
(address-after-header (template-code template)))))
(define (current-pc)
(code-pointer->pc *code-pointer* *template*))
(let ((key (ensure-space (op-template-size 2))))
(set! *interrupt-template*
(make-template-containing-ops (enum op ignore-values)
(enum op return-from-interrupt)
key))
(set! *exception-template*
(make-template-containing-ops (enum op return-from-exception)
key))))
(define (push-continuation! code-pointer size)
(let ((pc (code-pointer->pc code-pointer *template*)))
(push-continuation-on-stack *template* pc size)))
(define (pop-continuation!)
(pop-continuation-from-stack set-template!))
(define (code-byte index)
(fetch-byte (address+ *code-pointer* (+ index 1))))
(define (code-offset index)
(adjoin-bits (code-byte index)
(code-byte (+ index 1))
bits-used-per-byte))
(define (get-literal index)
(template-ref *template* (code-offset index)))
(define (current-opcode)
(code-byte -1))
(define (interpret code-pointer)
( write - instruction * template * ( extract - fixnum ( current - pc ) ) 1 # f ) )
( set ! * i * ( + * i * 1 ) )
((vector-ref opcode-dispatch (fetch-byte code-pointer))))
(define (continue bytes-used)
(set! *code-pointer* (address+ *code-pointer* (+ bytes-used 1)))
(goto interpret *code-pointer*))
(define (continue-with-value value bytes-used)
(set! *val* value)
(goto continue bytes-used))
(define (uuo)
(raise-exception unimplemented-instruction 0))
(define opcode-dispatch (make-vector op-count))
(vector+length-fill! opcode-dispatch op-count uuo)
(define-syntax define-opcode
(syntax-rules ()
((define-opcode op-name body ...)
(vector-set! opcode-dispatch (enum op op-name) (lambda () body ...)))))
(define-syntax raise-exception
(syntax-rules ()
((raise-exception why byte-args stuff ...)
(raise-exception* (enum exception why) byte-args stuff ...))))
(define-syntax count-exception-args
(syntax-rules ()
((count-exception-args) 0)
((count-exception-args arg1 rest ...)
(+ 1 (count-exception-args rest ...)))))
(define-syntax raise-exception*
(syntax-rules ()
((raise-exception* why byte-args arg1 ...)
(begin
add 1 for the opcode
(push arg1) ...
(goto raise (count-exception-args arg1 ...))))))
(define-opcode set-exception-handlers!
(cond ((or (not (vm-vector? *val*))
(< (vm-vector-length *val*) op-count))
(raise-exception wrong-type-argument 0 *val*))
(else
(let ((temp *exception-handlers*))
(set! *exception-handlers* *val*)
(goto continue-with-value
temp
0)))))
(define (push-exception-continuation! exception instruction-size)
(let ((opcode (current-opcode)))
(push (enter-fixnum instruction-size))
(push (enter-fixnum exception))
(push *template*)
(push (current-pc))
(set-template! *exception-template* (enter-fixnum 0))
(push-continuation! *code-pointer* (arguments-on-stack))
(push (enter-fixnum opcode))
(push (enter-fixnum exception))))
(define-opcode return-from-exception
(let* ((pc (extract-fixnum (pop)))
(template (pop))
(size (extract-fixnum (pop))))
(set-template! template (enter-fixnum (+ pc size)))
(goto interpret *code-pointer*)))
(define (raise nargs)
( let ( ( opcode ( enumerand->name ( extract - fixnum ( stack - ref ( + nargs 1 ) ) ) op ) )
( breakpoint " exception check ~A ~A ~A " opcode why ) ) )
(let* ((opcode (extract-fixnum (stack-ref (+ nargs 1))))
(lose (lambda (message)
(let ((why (extract-fixnum (stack-ref nargs))))
(write-string "Template UIDs: " (current-error-port))
(report-continuation-uids *template* (current-error-port))
(newline (current-error-port))
(if (and (eq? why (enum exception undefined-global))
(fixnum? (location-id (stack-ref (- nargs 1)))))
(error message opcode why
(extract-fixnum (location-id (stack-ref (- nargs 1)))))
(error message opcode why))))))
(if (not (vm-vector? *exception-handlers*))
(lose "exception-handlers is not a vector"))
(set! *val* (vm-vector-ref *exception-handlers* opcode))
(if (not (closure? *val*))
(lose "exception handler is not a closure"))
(goto call-exception-handler (+ nargs 2) opcode)))
Loaded from * template * into * val * , using either a one - byte or two - byte index .
(goto continue-with-value
(get-literal 0)
(define-opcode small-literal
(goto continue-with-value
(template-ref *template* (code-byte 0))
(define-opcode make-env
(pop-args-into-env (code-offset 0))
(goto finish-local (env-back (current-env) (code-byte 0)) 1))
(define-opcode local0
(goto finish-local (current-env) 0))
(define-opcode push-local0
(push *val*)
(goto finish-local (current-env) 1))
(define-opcode local0-push
(set! *val* (env-ref (current-env) (code-byte 0)))
(if (not (vm-eq? *val* unassigned-marker))
(begin
(push *val*)
(goto continue 2))
(raise-exception unassigned-local 2)))
(define-opcode local1
(goto finish-local (env-parent (current-env)) 0))
(define-opcode local2
(goto finish-local (env-parent (env-parent (current-env))) 0))
(define (finish-local env arg-count)
(set! *val* (env-ref env (code-byte arg-count)))
(if (not (vm-eq? *val* unassigned-marker))
(goto continue (+ arg-count 1))
(raise-exception unassigned-local (+ arg-count 1))))
(define-opcode big-local
(let ((back (code-offset 0)))
(set! *val* (env-ref (env-back (current-env) back)
(code-offset 2)))
(if (not (vm-eq? *val* unassigned-marker))
(raise-exception unassigned-local 4))))
(define-opcode set-local!
(let ((back (code-offset 0)))
(env-set! (env-back (current-env) back)
(code-offset 2)
*val*)
(set! *val* unspecific-value)
(let ((location (get-literal 0)))
(set! *val* (contents location))
(raise-exception undefined-global 2 location)
(define-opcode set-global!
(let ((location (get-literal 0)))
(cond ((vm-eq? (contents location) unbound-marker)
(raise-exception undefined-global 2 location *val*))
(else
(set-contents! location *val*)
(goto continue-with-value
unspecific-value
Stack operation
(push *val*)
(goto continue 0))
(goto continue-with-value
(pop)
0))
(define-opcode stack-ref
(goto continue-with-value
(stack-ref (code-byte 0))
1))
(define-opcode stack-set!
(stack-set! (code-byte 0) *val*)
(goto continue 1))
(define-opcode closure
(let ((env (if (= 0 (code-byte 2))
(preserve-current-env (ensure-space (current-env-size)))
*val*)))
(receive (key env)
(ensure-space-saving-temp closure-size env)
(goto continue-with-value
(make-closure (get-literal 0) env key)
3))))
use * val * as first element ?
depth of first level
delta of depth of second level
(define-opcode make-flat-env
(let* ((total-count (code-byte 1))
(new-env (vm-make-vector total-count
(ensure-space (vm-vector-size total-count))))
(start-i (if (= 0 (code-byte 0))
0
(begin
(vm-vector-set! new-env 0 *val*)
1))))
(let loop ((i start-i)
(env (current-env)))
(if (= i total-count)
(goto continue-with-value
new-env
offset)
(let ((env (env-back env (code-byte offset)))
(count (code-byte (+ offset 1))))
(do ((count count (- count 1))
(i i (+ i 1))
((= count 0)
(loop i offset env))
(vm-vector-set! new-env
i
(vm-vector-ref env
(code-byte offset)))))))))
(push-continuation! (address+ *code-pointer*
(code-offset 0))
(code-byte 2))
(goto continue 3))
(push-continuation! (address+ *code-pointer*
(code-offset 0))
(code-offset 2))
(goto continue 4))
(pop-continuation!)
(goto interpret *code-pointer*))
Stack is : ... argN rest - list N+1 total - arg - count .
If REST - LIST is non - empty then there are at least two arguments on the stack .
(define-opcode closed-values
(let* ((nargs (extract-fixnum (pop)))
(stack-nargs (extract-fixnum (pop)))
(rest-list (pop)))
(goto return-values stack-nargs rest-list (- nargs stack-nargs))))
(define-opcode values
(goto return-values (code-offset 0) null 0))
STACK - NARGS return values are on the stack . If there is only one value , pop
(define (return-values stack-nargs list-args list-arg-count)
if list - arg - count > 0 then stack - nargs > 1
(set! *val* (pop))
(pop-continuation!)
(goto interpret *code-pointer*))
(else
(let ((cont (peek-at-current-continuation)))
(if (continuation? cont)
(goto really-return-values
cont stack-nargs list-args list-arg-count)
(goto return-exception stack-nargs list-args))))))
(define (really-return-values cont stack-nargs list-args list-arg-count)
(let ((next-op (code-vector-ref (template-code (continuation-template cont))
(extract-fixnum (continuation-pc cont)))))
(cond ((= next-op (enum op ignore-values))
(pop-continuation!)
(goto interpret *code-pointer*))
((= next-op (enum op call-with-values))
(skip-current-continuation!)
(set! *val* (continuation-ref cont continuation-cells))
(goto perform-application-with-rest-list stack-nargs
list-args
list-arg-count))
(else
(goto return-exception stack-nargs list-args)))))
work because the NARGS check ( which would be the next instruction to be
(define (return-exception stack-nargs list-args)
(let ((args (pop-args->list* list-args stack-nargs)))
This is executed only if the producer returned exactly one value .
(define-opcode call-with-values
(let ((consumer (pop)))
(push *val*)
(set! *val* consumer)
(goto perform-application 1)))
(define-opcode ignore-values
(goto continue 0))
(define-opcode current-cont
(let ((key (ensure-space (current-continuation-size))))
(goto continue-with-value
(current-continuation key)
0)))
(define-opcode with-continuation
(set-current-continuation! (pop))
(goto perform-application 0))
(define-opcode get-cont-from-heap
(let ((cont (get-continuation-from-heap)))
(cond ((continuation? cont)
(set-current-continuation! cont)
(goto continue 0))
((and (false? cont)
(extract-fixnum *val*))
(else
(set-current-continuation! false)
(raise-exception wrong-type-argument 0 *val* cont)))))
(define-opcode jump-if-false
(cond ((false? *val*)
(set! *code-pointer*
(address+ *code-pointer*
(code-offset 0)))
(goto interpret *code-pointer*))
(else
(goto continue 2))))
(define-opcode jump
(set! *code-pointer*
(address+ *code-pointer*
(code-offset 0)))
(goto interpret *code-pointer*))
index is in * val * , the next byte is the number of offsets specified
op / computed - goto max offset0 ... offsetmax-1 code - for - default ...
(define-opcode computed-goto
(if (not (fixnum? *val*))
(let ((max (code-byte 0))
(val (extract-fixnum *val*)))
(let ((offset (if (and (>= val 0)
(< val max))
(code-offset (+ (* val 2) 1))
(+ (* max 2) 2))))
(set! *code-pointer* (address+ *code-pointer* offset))
(goto interpret *code-pointer*)))))
(define-opcode unassigned
(goto continue-with-value
unassigned-marker
0))
(define-opcode unspecific
(goto continue-with-value
unspecific-value
0))
|
7473088b3924f391859c13d662ac08b410e2efaaa9dd3b7d839f8291defe00ca | kallisti-dev/hs-webdriver | webserver.hs | module Main where
import Control.Exception
import Control.Concurrent
import Network.Wai.Handler.Warp
import Network.Wai.Application.Static
import WaiAppStatic.Types
import Config
import Test.WebDriver
import qualified Test . BasicTests as BasicTests
serverConf = setPort Config.serverPort
$ defaultSettings
serverStaticConf = defaultFileServerSettings staticContentPath
browsers = [firefox, chrome]
wdConfigs = map (`useBrowser` conf) browsers
where
conf = defaultConfig
{ wdPort = getPort serverConf
}
main = bracket
( forkIO $ runSettings serverConf (staticApp serverStaticConf) )
( \ _ - > mapM _ BasicTests.runTestsWith )
killThread
| null | https://raw.githubusercontent.com/kallisti-dev/hs-webdriver/ea594ce8720c9e11f053b2567f250079f0eac33b/test/webserver.hs | haskell | module Main where
import Control.Exception
import Control.Concurrent
import Network.Wai.Handler.Warp
import Network.Wai.Application.Static
import WaiAppStatic.Types
import Config
import Test.WebDriver
import qualified Test . BasicTests as BasicTests
serverConf = setPort Config.serverPort
$ defaultSettings
serverStaticConf = defaultFileServerSettings staticContentPath
browsers = [firefox, chrome]
wdConfigs = map (`useBrowser` conf) browsers
where
conf = defaultConfig
{ wdPort = getPort serverConf
}
main = bracket
( forkIO $ runSettings serverConf (staticApp serverStaticConf) )
( \ _ - > mapM _ BasicTests.runTestsWith )
killThread
| |
f37900b642e8a58e027c50e77715a1cd67b45b9dc05deac7cd3e438e6276f99e | Gopiandcode/petrol | query.ml | type ('y, 'ty) t = ('y, 'ty) Types.query
type join_op = Types.join_op = LEFT | RIGHT | INNER
type ('a,'c) where_fun =
bool Expr.t -> ('c, 'a) t
-> ('c, 'a) t
constraint 'a =
([< `SELECT_CORE | `SELECT | `DELETE | `UPDATE]) as 'a
type ('a,'b,'c) group_by_fun =
'b Expr.expr_list -> ('c, 'a) t -> ('c, 'a) t constraint 'a = ([< `SELECT_CORE | `SELECT ] as 'a)
type ('a,'c) having_fun =
bool Expr.t -> ('c, 'a) t
-> ('c, 'a) t
constraint 'a =
([< `SELECT_CORE | `SELECT ]) as 'a
type ('a,'b,'d,'c) join_fun =
?op:Types.join_op -> on:bool Expr.t ->
('b, [< `SELECT_CORE | `SELECT ] as 'd) t
-> ('c, 'a) t -> ('c, 'a) t
constraint 'a = ([< `SELECT_CORE]) as 'a
type ('a,'b,'c) on_err_fun =
([< `ABORT | `FAIL | `IGNORE | `REPLACE | `ROLLBACK ] as 'b) ->
('c, 'a) t
-> ('c, 'a) t
constraint 'a = ([> `UPDATE | `INSERT]) as 'a
let query_values query = List.rev (Types.query_values [] query)
let pp = Types.pp_query
let show q = Format.asprintf "%a" pp q
let query_ret_ty: 'a 'b. ('a,'b) t -> 'a Type.ty_list =
fun (type a b) (query: (a,b) t) : a Type.ty_list ->
match query with
| SELECT_CORE { exprs; table=_; join=_; where=_; group_by=_; having=_ } ->
Expr.ty_expr_list exprs
| SELECT { core=
SELECT_CORE { exprs; table=_; join=_; where=_; group_by=_; having=_ };
order_by=_; limit=_; offset=_ } ->
Expr.ty_expr_list exprs
| DELETE _ -> Nil
| UPDATE _ -> Nil
| INSERT _ -> Nil
let select exprs ~from:table_name =
Types.SELECT_CORE {
exprs; join=[]; table=table_name; where=None;
group_by=None; having=None;
}
let update ~table:table_name ~set =
Types.UPDATE { table=table_name; on_err=None; where=None; set; }
let insert ~table:table_name ~values:set =
Types.INSERT { table=table_name; on_err=None; set; }
let delete ~from:table_name =
Types.DELETE { table=table_name; where=None }
let where : ('a,'c) where_fun
= fun by (type a b) (table : (b, a) t) : (b, a) t ->
let update_where where by =
match where with
None -> Some by
| Some old_by -> Some Expr.(by && old_by) in
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
let where = update_where where by in
SELECT_CORE { exprs; table; join; where; group_by; having }
| Types.SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; order_by; limit; offset } ->
let where = update_where where by in
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; order_by; limit; offset }
| Types.DELETE { table; where } ->
let where = update_where where by in
DELETE { table; where }
| Types.UPDATE { table; on_err; set; where } ->
let where = update_where where by in
UPDATE { table; on_err; set; where }
| Types.INSERT _ -> invalid_arg "where on insert clause not supported"
let group_by : ('a,'b,'c) group_by_fun =
fun by (type a b) (table : (b, a) t) : (b, a) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by=_; having } ->
SELECT_CORE { exprs; table; join; where; group_by=Some by; having }
| Types.SELECT { core=SELECT_CORE { exprs; table; join; where; group_by=_; having }; order_by; limit; offset } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by=Some by; having }; order_by; limit; offset }
| Types.DELETE _
| Types.UPDATE _
| Types.INSERT _ -> invalid_arg "group by only supported on select clause"
let having : ('a,'c) having_fun =
fun having (type a b) (table : (b, a) t) : (b, a) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having=_ } ->
SELECT_CORE { exprs; table; join; where; group_by; having=Some having }
| Types.SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having=_ }; order_by; limit; offset } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having=Some having }; order_by; limit; offset }
| Types.DELETE _
| Types.UPDATE _
| Types.INSERT _ -> invalid_arg "group by only supported on select clause"
let join : ('a,'b,'d,'c) join_fun =
fun ?(op=INNER) ~on (type a b c) (ot: (b, _) t)
(table : (c, a) t) ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
Types.SELECT_CORE {
exprs; table;
join=join @ [MkJoin {
table=ot;
on;
join_op=op
}];
where; group_by; having
}
| Types.SELECT _
| Types.DELETE _
| Types.UPDATE _
| Types.INSERT _ ->
invalid_arg "group by only supported on select clause"
let on_err : 'a . [`ABORT | `FAIL | `IGNORE | `REPLACE | `ROLLBACK ] -> ('c, 'a) t -> ('c, 'a) t =
fun on_err (type a) (table : (_, a) t) : (_, a) t ->
match table with
| Types.SELECT_CORE _
| Types.SELECT _
| Types.DELETE _ -> invalid_arg "on_err only supported for update and insert"
| Types.UPDATE { table; on_err=_; set; where } -> UPDATE { table; on_err=Some on_err; set; where }
| Types.INSERT { table; on_err=_; set } -> INSERT { table; on_err=Some on_err; set }
let limit :
'a 'i .
int Types.expr -> ('a, [< `SELECT | `SELECT_CORE ] as 'i) t ->
('a, [> `SELECT ]) t =
fun (type a i) by (table: (a, i) t) : (a, [> `SELECT]) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; limit=Some by; offset=None; order_by=None}
| Types.SELECT { core; order_by; limit=_; offset } ->
SELECT { core; order_by; limit=Some by; offset }
| DELETE _
| UPDATE _
| INSERT _ -> invalid_arg "limit only supported for select"
let offset :
'a 'i .
int Types.expr -> ('a, [< `SELECT | `SELECT_CORE ] as 'i) t ->
('a, [> `SELECT ]) t =
fun (type a i) by (table: (a, i) t) : (a, [> `SELECT]) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; limit=None; offset=Some by; order_by=None}
| Types.SELECT { core; order_by; limit; offset=_ } ->
SELECT { core; order_by; limit; offset=Some by }
| DELETE _
| UPDATE _
| INSERT _ -> invalid_arg "offset only supported for select"
let order_by :
'a 'b. ?direction:[ `ASC | `DESC ] ->
'c Types.expr -> ('a, [< `SELECT | `SELECT_CORE] as 'b) t ->
('a, [> `SELECT ]) t =
fun (type a b) ?(direction=`ASC) field (table: (a, b) t) : (a, [> `SELECT]) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; limit=None; offset=None; order_by=Some (direction,Expr.[field])}
| Types.SELECT { core; order_by=_; limit; offset } ->
SELECT { core; order_by= Some(direction,Expr.[field]); limit; offset }
| DELETE _
| UPDATE _
| INSERT _ -> invalid_arg "order by only supported for select"
let order_by_ :
'a 'b. ?direction:[ `ASC | `DESC ] ->
'c Types.expr_list -> ('a, [< `SELECT | `SELECT_CORE] as 'b) t ->
('a, [> `SELECT ]) t =
fun (type a b) ?(direction=`ASC) field (table: (a, b) t) : (a, [> `SELECT]) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; limit=None; offset=None; order_by=Some (direction,field)}
| Types.SELECT { core; order_by=_; limit; offset } ->
SELECT { core; order_by= Some(direction,field); limit; offset }
| DELETE _
| UPDATE _
| INSERT _ -> invalid_arg "order by only supported for select"
| null | https://raw.githubusercontent.com/Gopiandcode/petrol/48b57e5996997e50911d7d5bb0701a9bdd794fb2/lib/query.ml | ocaml | type ('y, 'ty) t = ('y, 'ty) Types.query
type join_op = Types.join_op = LEFT | RIGHT | INNER
type ('a,'c) where_fun =
bool Expr.t -> ('c, 'a) t
-> ('c, 'a) t
constraint 'a =
([< `SELECT_CORE | `SELECT | `DELETE | `UPDATE]) as 'a
type ('a,'b,'c) group_by_fun =
'b Expr.expr_list -> ('c, 'a) t -> ('c, 'a) t constraint 'a = ([< `SELECT_CORE | `SELECT ] as 'a)
type ('a,'c) having_fun =
bool Expr.t -> ('c, 'a) t
-> ('c, 'a) t
constraint 'a =
([< `SELECT_CORE | `SELECT ]) as 'a
type ('a,'b,'d,'c) join_fun =
?op:Types.join_op -> on:bool Expr.t ->
('b, [< `SELECT_CORE | `SELECT ] as 'd) t
-> ('c, 'a) t -> ('c, 'a) t
constraint 'a = ([< `SELECT_CORE]) as 'a
type ('a,'b,'c) on_err_fun =
([< `ABORT | `FAIL | `IGNORE | `REPLACE | `ROLLBACK ] as 'b) ->
('c, 'a) t
-> ('c, 'a) t
constraint 'a = ([> `UPDATE | `INSERT]) as 'a
let query_values query = List.rev (Types.query_values [] query)
let pp = Types.pp_query
let show q = Format.asprintf "%a" pp q
let query_ret_ty: 'a 'b. ('a,'b) t -> 'a Type.ty_list =
fun (type a b) (query: (a,b) t) : a Type.ty_list ->
match query with
| SELECT_CORE { exprs; table=_; join=_; where=_; group_by=_; having=_ } ->
Expr.ty_expr_list exprs
| SELECT { core=
SELECT_CORE { exprs; table=_; join=_; where=_; group_by=_; having=_ };
order_by=_; limit=_; offset=_ } ->
Expr.ty_expr_list exprs
| DELETE _ -> Nil
| UPDATE _ -> Nil
| INSERT _ -> Nil
let select exprs ~from:table_name =
Types.SELECT_CORE {
exprs; join=[]; table=table_name; where=None;
group_by=None; having=None;
}
let update ~table:table_name ~set =
Types.UPDATE { table=table_name; on_err=None; where=None; set; }
let insert ~table:table_name ~values:set =
Types.INSERT { table=table_name; on_err=None; set; }
let delete ~from:table_name =
Types.DELETE { table=table_name; where=None }
let where : ('a,'c) where_fun
= fun by (type a b) (table : (b, a) t) : (b, a) t ->
let update_where where by =
match where with
None -> Some by
| Some old_by -> Some Expr.(by && old_by) in
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
let where = update_where where by in
SELECT_CORE { exprs; table; join; where; group_by; having }
| Types.SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; order_by; limit; offset } ->
let where = update_where where by in
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; order_by; limit; offset }
| Types.DELETE { table; where } ->
let where = update_where where by in
DELETE { table; where }
| Types.UPDATE { table; on_err; set; where } ->
let where = update_where where by in
UPDATE { table; on_err; set; where }
| Types.INSERT _ -> invalid_arg "where on insert clause not supported"
let group_by : ('a,'b,'c) group_by_fun =
fun by (type a b) (table : (b, a) t) : (b, a) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by=_; having } ->
SELECT_CORE { exprs; table; join; where; group_by=Some by; having }
| Types.SELECT { core=SELECT_CORE { exprs; table; join; where; group_by=_; having }; order_by; limit; offset } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by=Some by; having }; order_by; limit; offset }
| Types.DELETE _
| Types.UPDATE _
| Types.INSERT _ -> invalid_arg "group by only supported on select clause"
let having : ('a,'c) having_fun =
fun having (type a b) (table : (b, a) t) : (b, a) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having=_ } ->
SELECT_CORE { exprs; table; join; where; group_by; having=Some having }
| Types.SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having=_ }; order_by; limit; offset } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having=Some having }; order_by; limit; offset }
| Types.DELETE _
| Types.UPDATE _
| Types.INSERT _ -> invalid_arg "group by only supported on select clause"
let join : ('a,'b,'d,'c) join_fun =
fun ?(op=INNER) ~on (type a b c) (ot: (b, _) t)
(table : (c, a) t) ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
Types.SELECT_CORE {
exprs; table;
join=join @ [MkJoin {
table=ot;
on;
join_op=op
}];
where; group_by; having
}
| Types.SELECT _
| Types.DELETE _
| Types.UPDATE _
| Types.INSERT _ ->
invalid_arg "group by only supported on select clause"
let on_err : 'a . [`ABORT | `FAIL | `IGNORE | `REPLACE | `ROLLBACK ] -> ('c, 'a) t -> ('c, 'a) t =
fun on_err (type a) (table : (_, a) t) : (_, a) t ->
match table with
| Types.SELECT_CORE _
| Types.SELECT _
| Types.DELETE _ -> invalid_arg "on_err only supported for update and insert"
| Types.UPDATE { table; on_err=_; set; where } -> UPDATE { table; on_err=Some on_err; set; where }
| Types.INSERT { table; on_err=_; set } -> INSERT { table; on_err=Some on_err; set }
let limit :
'a 'i .
int Types.expr -> ('a, [< `SELECT | `SELECT_CORE ] as 'i) t ->
('a, [> `SELECT ]) t =
fun (type a i) by (table: (a, i) t) : (a, [> `SELECT]) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; limit=Some by; offset=None; order_by=None}
| Types.SELECT { core; order_by; limit=_; offset } ->
SELECT { core; order_by; limit=Some by; offset }
| DELETE _
| UPDATE _
| INSERT _ -> invalid_arg "limit only supported for select"
let offset :
'a 'i .
int Types.expr -> ('a, [< `SELECT | `SELECT_CORE ] as 'i) t ->
('a, [> `SELECT ]) t =
fun (type a i) by (table: (a, i) t) : (a, [> `SELECT]) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; limit=None; offset=Some by; order_by=None}
| Types.SELECT { core; order_by; limit; offset=_ } ->
SELECT { core; order_by; limit; offset=Some by }
| DELETE _
| UPDATE _
| INSERT _ -> invalid_arg "offset only supported for select"
let order_by :
'a 'b. ?direction:[ `ASC | `DESC ] ->
'c Types.expr -> ('a, [< `SELECT | `SELECT_CORE] as 'b) t ->
('a, [> `SELECT ]) t =
fun (type a b) ?(direction=`ASC) field (table: (a, b) t) : (a, [> `SELECT]) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; limit=None; offset=None; order_by=Some (direction,Expr.[field])}
| Types.SELECT { core; order_by=_; limit; offset } ->
SELECT { core; order_by= Some(direction,Expr.[field]); limit; offset }
| DELETE _
| UPDATE _
| INSERT _ -> invalid_arg "order by only supported for select"
let order_by_ :
'a 'b. ?direction:[ `ASC | `DESC ] ->
'c Types.expr_list -> ('a, [< `SELECT | `SELECT_CORE] as 'b) t ->
('a, [> `SELECT ]) t =
fun (type a b) ?(direction=`ASC) field (table: (a, b) t) : (a, [> `SELECT]) t ->
match table with
| Types.SELECT_CORE { exprs; table; join; where; group_by; having } ->
SELECT { core=SELECT_CORE { exprs; table; join; where; group_by; having }; limit=None; offset=None; order_by=Some (direction,field)}
| Types.SELECT { core; order_by=_; limit; offset } ->
SELECT { core; order_by= Some(direction,field); limit; offset }
| DELETE _
| UPDATE _
| INSERT _ -> invalid_arg "order by only supported for select"
| |
708331f0f7e9f1e8938c79e9fcedb006f4b376d319a412a7b9e60b04a454bae5 | Frama-C/headache | config.ml | (**************************************************************************)
(* *)
(* Headache *)
(* *)
, Projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002
Institut National de Recherche en Informatique et en Automatique .
(* All rights reserved. This file is distributed under the terms of *)
the GNU Library General Public License .
(* *)
/~simonet/
(* *)
(**************************************************************************)
exception Error of string * int * int
| null | https://raw.githubusercontent.com/Frama-C/headache/cf3890fd27e08613397ad0386390250f206dc01f/config.ml | ocaml | ************************************************************************
Headache
All rights reserved. This file is distributed under the terms of
************************************************************************ | , Projet Cristal , INRIA Rocquencourt
Copyright 2002
Institut National de Recherche en Informatique et en Automatique .
the GNU Library General Public License .
/~simonet/
exception Error of string * int * int
|
d5f97b87f0adb37b952e1bea6ba713f17b462462a16ba60f3524f2dba1b3fd3d | dongcarl/guix | ftp.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 , 2015 , 2018 , 2021 , 2021 < >
Copyright © 2015 < >
Copyright © 2015 < >
Copyright © 2016–2021 < >
Copyright © 2017 < >
Copyright © 2021 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages ftp)
#:use-module ((guix licenses) #:select (gpl2 gpl2+ gpl3+ clarified-artistic))
#:use-module (guix build-system gnu)
#:use-module (guix download)
#:use-module (guix packages)
#:use-module (guix utils)
#:use-module (gnu packages)
#:use-module (gnu packages autotools)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages gcc)
#:use-module (gnu packages gettext)
#:use-module (gnu packages glib)
#:use-module (gnu packages gtk)
#:use-module (gnu packages libidn)
#:use-module (gnu packages linux)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages nettle)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages readline)
#:use-module (gnu packages sqlite)
#:use-module (gnu packages tls)
#:use-module (gnu packages wxwidgets)
#:use-module (gnu packages xml))
(define-public lftp
(package
(name "lftp")
(version "4.9.2")
(source (origin
(method url-fetch)
;; See for mirrors.
(uri (list (string-append "-"
version ".tar.xz")
(string-append "-"
version ".tar.xz")
(string-append "ftp/"
"ftp/lftp/lftp-" version ".tar.xz")))
(sha256
(base32
"03b7y0h3mf4jfq5y8zw6hv9v44z3n6i8hc1iswax96y3z7sc85y5"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("zlib" ,zlib)
("readline" ,readline)
("gnutls" ,gnutls)))
(arguments
`(#:phases
(modify-phases %standard-phases
;; Disable tests that require network access, which is most of them.
(add-before 'check 'disable-impure-tests
(lambda _
(substitute* "tests/Makefile"
(("(ftp-cls-l|ftp-list|http-get)\\$\\(EXEEXT\\)") "")
(("lftp-https-get ") ""))
#t)))
#:configure-flags
(list (string-append "--with-readline="
(assoc-ref %build-inputs "readline")))))
(home-page "/")
(synopsis "Command-line file transfer program")
(description
"LFTP is a sophisticated FTP/HTTP client, and a file transfer program
supporting a number of network protocols. Like Bash, it has job control and
uses the Readline library for input. It has bookmarks, a built-in mirror
command, and can transfer several files in parallel. It was designed with
reliability in mind.")
(license gpl3+)))
(define-public ncftp
(package
(name "ncftp")
(version "3.2.6")
(source (origin
(method url-fetch)
(uri (string-append "ftp-"
version "-src.tar.xz"))
(sha256
(base32
"1389657cwgw5a3kljnqmhvfh4vr2gcr71dwz1mlhf22xq23hc82z"))
(modules '((guix build utils)))
(snippet
'(begin
;; Use the right 'rm' and 'ls'.
(substitute* (cons "configure"
(find-files "."
"^(Makefile\\.in|.*\\.sh)$"))
(("/bin/(rm|ls)" _ command)
command))
;; This is free software, avoid any confusion.
(substitute* (find-files "." "\\.c$")
(("a freeware program")
"free software"))
#t))))
(properties
`((release-monitoring-url . "/")))
(build-system gnu-build-system)
(arguments
'(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
;; This is an old 'configure' script that doesn't
;; understand variables passed as arguments.
(let ((out (assoc-ref outputs "out")))
(setenv "CONFIG_SHELL" (which "sh"))
(setenv "SHELL" (which "sh"))
(invoke "./configure"
(string-append "--prefix=" out))))))
#:tests? #f)) ;there are no tests
(inputs `(("ncurses" ,ncurses)))
(home-page "/")
(synopsis "Command-line File Transfer Protocol (FTP) client")
(description
"NcFTP Client (or just NcFTP) is a set of command-line programs to access
File Transfer Protocol (FTP) servers. This includes @code{ncftp}, an interactive
FTP browser, as well as non-interactive commands such as @code{ncftpput} and
@code{ncftpget}.")
(license clarified-artistic)))
(define-public weex
(package
(name "weex")
(version "2.8.2")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
"/weex_" version ".tar.gz"))
(sha256
(base32
"1ir761hjncr1bamaqcw9j7x57xi3s9jax3223bxwbq30a0vsw1pd"))))
(build-system gnu-build-system)
(native-inputs
`(("automake" ,automake)
("autoconf" ,autoconf)
("gettext" ,gettext-minimal)))
(home-page "/")
(synopsis "Non-interactive client for FTP synchronization")
(description
"Weex is a utility designed to automate the task of remotely
maintaining a web page or other FTP archive. It synchronizes a set of
local files to a remote server by performing uploads and remote deletes
as required.")
(license gpl2+)))
(define-public libfilezilla
(package
(name "libfilezilla")
(version "0.30.0")
(source
(origin
(method url-fetch)
(uri (string-append "-project.org/"
"libfilezilla/libfilezilla-" version ".tar.bz2"))
(sha256
(base32 "0h6wa1dfd14z9ai00a85pahsb4fs3rlb8haiw3vd9pmjrpdgcvf1"))))
(build-system gnu-build-system)
(arguments
`(#:configure-flags
(list "--disable-static")))
(native-inputs
`(("cppunit" ,cppunit)
("gcc" ,gcc-8) ; XXX remove when it's the default
("gettext" ,gettext-minimal)
("pkg-config" ,pkg-config)))
(inputs
`(("gnutls" ,gnutls)
("nettle" ,nettle)))
(home-page "-project.org")
(synopsis "Cross-platform C++ library used by Filezilla client")
(description
"This package provides some basic functionality to build high-performing,
platform-independent programs.
Some of the highlights include:
@itemize
@item
A type-safe, multi-threaded event system that's simple to use yet efficient.
@item
Timers for periodic events.
@item
A @code{datetime} class that not only tracks timestamp but also their accuracy,
which simplifies dealing with timestamps originating from different sources.
@item
Simple process handling for spawning child processes with redirected input and
output.
@end itemize\n")
(license gpl2+)))
(define-public filezilla
(package
(name "filezilla")
(version "3.55.0")
(source
(origin
(method url-fetch)
(uri (string-append "-project.org/client/"
"FileZilla_" version "_src.tar.bz2"))
(sha256
(base32 "10lwmf6cvryw2gja6vj1zh2y55z4i38wsvxdpclvwdnih10ynw5f"))))
(build-system gnu-build-system)
(arguments
;; Don't let filezilla phone home to check for updates.
'(#:configure-flags '("--disable-autoupdatecheck")))
(native-inputs
`(("cppunit" ,cppunit)
("gettext" ,gettext-minimal)
("pkg-config" ,pkg-config)
("xdg-utils" ,xdg-utils)))
(inputs
`(("dbus" ,dbus)
("gnutls" ,gnutls)
("gtk+" ,gtk+)
("libfilezilla" ,libfilezilla)
("libidn" ,libidn)
("nettle" ,nettle)
("pugixml" ,pugixml)
("sqlite" ,sqlite)
("wxwidgets" ,wxwidgets)))
(home-page "-project.org")
(synopsis "Full-featured graphical FTP/FTPS/SFTP client")
(description
"Filezilla client supports FTP, FTP over SSL/TLS (FTPS),
SSH File Transfer Protocol (SFTP), HTTP/1.1, SOCKS5, FTP-Proxy, IPv6
and others features such as bookmarks, drag and drop, filename filters,
directory comparison and more.")
(license gpl2+)
(properties '((upstream-name . "FileZilla")))))
(define-public vsftpd
(package
(name "vsftpd")
(version "3.0.4")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"vsftpd-" version ".tar.gz"))
(sha256
(base32 "09kap2qsd80m0x80jv5224x002x2jkr584dksppcv9p84yyj353b"))))
(build-system gnu-build-system)
(arguments
`(#:make-flags
(list (string-append "CC=" ,(cc-for-target))
;; vsf_findlibs.sh looks only for hard-coded {/usr,}/lib file names
that will never exist on . Manage libraries ourselves .
"LDFLAGS=-lcap -lpam"
"INSTALL=install -D")
#:tests? #f ; no test suite
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'build-SSL
(lambda _
(substitute* "builddefs.h"
(("#undef (VSF_BUILD_SSL)" _ symbol)
(string-append "#define " symbol)))))
(add-after 'unpack 'append-make-flags
(lambda _
(substitute* "Makefile"
(("(CFLAGS|LDFLAGS)[[:blank:]]*=" _ variable)
(format #f "UPSTREAM_~a +=" variable))
(("\\$\\((CFLAGS|LDFLAGS)\\)" _ variable)
(format #f "$(UPSTREAM_~a) $(~@*~a)" variable)))))
(add-after 'unpack 'patch-installation-directory
(lambda* (#:key outputs #:allow-other-keys)
(substitute* "Makefile"
(("/usr") (assoc-ref outputs "out")))))
(delete 'configure)))) ; no configure script
(inputs
`(("libcap" ,libcap)
("linux-pam" ,linux-pam)
("openssl" ,openssl)))
(synopsis "Small FTP server with a focus on security")
(description
"The Very Secure File Transfer Protocol Daemon or @command{vsftpd} is a
server that listens on a TCP socket for clients and gives them access to local
files via @acronym{FTP, the File Transfer Protocol}. Security is a goal; not a
guarantee.")
(home-page "")
with OpenSSL exception
| null | https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/gnu/packages/ftp.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
See for mirrors.
Disable tests that require network access, which is most of them.
Use the right 'rm' and 'ls'.
This is free software, avoid any confusion.
This is an old 'configure' script that doesn't
understand variables passed as arguments.
there are no tests
XXX remove when it's the default
Don't let filezilla phone home to check for updates.
vsf_findlibs.sh looks only for hard-coded {/usr,}/lib file names
no test suite
no configure script
not a | Copyright © 2014 , 2015 , 2018 , 2021 , 2021 < >
Copyright © 2015 < >
Copyright © 2015 < >
Copyright © 2016–2021 < >
Copyright © 2017 < >
Copyright © 2021 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages ftp)
#:use-module ((guix licenses) #:select (gpl2 gpl2+ gpl3+ clarified-artistic))
#:use-module (guix build-system gnu)
#:use-module (guix download)
#:use-module (guix packages)
#:use-module (guix utils)
#:use-module (gnu packages)
#:use-module (gnu packages autotools)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages gcc)
#:use-module (gnu packages gettext)
#:use-module (gnu packages glib)
#:use-module (gnu packages gtk)
#:use-module (gnu packages libidn)
#:use-module (gnu packages linux)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages nettle)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages readline)
#:use-module (gnu packages sqlite)
#:use-module (gnu packages tls)
#:use-module (gnu packages wxwidgets)
#:use-module (gnu packages xml))
(define-public lftp
(package
(name "lftp")
(version "4.9.2")
(source (origin
(method url-fetch)
(uri (list (string-append "-"
version ".tar.xz")
(string-append "-"
version ".tar.xz")
(string-append "ftp/"
"ftp/lftp/lftp-" version ".tar.xz")))
(sha256
(base32
"03b7y0h3mf4jfq5y8zw6hv9v44z3n6i8hc1iswax96y3z7sc85y5"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("zlib" ,zlib)
("readline" ,readline)
("gnutls" ,gnutls)))
(arguments
`(#:phases
(modify-phases %standard-phases
(add-before 'check 'disable-impure-tests
(lambda _
(substitute* "tests/Makefile"
(("(ftp-cls-l|ftp-list|http-get)\\$\\(EXEEXT\\)") "")
(("lftp-https-get ") ""))
#t)))
#:configure-flags
(list (string-append "--with-readline="
(assoc-ref %build-inputs "readline")))))
(home-page "/")
(synopsis "Command-line file transfer program")
(description
"LFTP is a sophisticated FTP/HTTP client, and a file transfer program
supporting a number of network protocols. Like Bash, it has job control and
uses the Readline library for input. It has bookmarks, a built-in mirror
command, and can transfer several files in parallel. It was designed with
reliability in mind.")
(license gpl3+)))
(define-public ncftp
(package
(name "ncftp")
(version "3.2.6")
(source (origin
(method url-fetch)
(uri (string-append "ftp-"
version "-src.tar.xz"))
(sha256
(base32
"1389657cwgw5a3kljnqmhvfh4vr2gcr71dwz1mlhf22xq23hc82z"))
(modules '((guix build utils)))
(snippet
'(begin
(substitute* (cons "configure"
(find-files "."
"^(Makefile\\.in|.*\\.sh)$"))
(("/bin/(rm|ls)" _ command)
command))
(substitute* (find-files "." "\\.c$")
(("a freeware program")
"free software"))
#t))))
(properties
`((release-monitoring-url . "/")))
(build-system gnu-build-system)
(arguments
'(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(setenv "CONFIG_SHELL" (which "sh"))
(setenv "SHELL" (which "sh"))
(invoke "./configure"
(string-append "--prefix=" out))))))
(inputs `(("ncurses" ,ncurses)))
(home-page "/")
(synopsis "Command-line File Transfer Protocol (FTP) client")
(description
"NcFTP Client (or just NcFTP) is a set of command-line programs to access
File Transfer Protocol (FTP) servers. This includes @code{ncftp}, an interactive
FTP browser, as well as non-interactive commands such as @code{ncftpput} and
@code{ncftpget}.")
(license clarified-artistic)))
(define-public weex
(package
(name "weex")
(version "2.8.2")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
"/weex_" version ".tar.gz"))
(sha256
(base32
"1ir761hjncr1bamaqcw9j7x57xi3s9jax3223bxwbq30a0vsw1pd"))))
(build-system gnu-build-system)
(native-inputs
`(("automake" ,automake)
("autoconf" ,autoconf)
("gettext" ,gettext-minimal)))
(home-page "/")
(synopsis "Non-interactive client for FTP synchronization")
(description
"Weex is a utility designed to automate the task of remotely
maintaining a web page or other FTP archive. It synchronizes a set of
local files to a remote server by performing uploads and remote deletes
as required.")
(license gpl2+)))
(define-public libfilezilla
(package
(name "libfilezilla")
(version "0.30.0")
(source
(origin
(method url-fetch)
(uri (string-append "-project.org/"
"libfilezilla/libfilezilla-" version ".tar.bz2"))
(sha256
(base32 "0h6wa1dfd14z9ai00a85pahsb4fs3rlb8haiw3vd9pmjrpdgcvf1"))))
(build-system gnu-build-system)
(arguments
`(#:configure-flags
(list "--disable-static")))
(native-inputs
`(("cppunit" ,cppunit)
("gettext" ,gettext-minimal)
("pkg-config" ,pkg-config)))
(inputs
`(("gnutls" ,gnutls)
("nettle" ,nettle)))
(home-page "-project.org")
(synopsis "Cross-platform C++ library used by Filezilla client")
(description
"This package provides some basic functionality to build high-performing,
platform-independent programs.
Some of the highlights include:
@itemize
@item
A type-safe, multi-threaded event system that's simple to use yet efficient.
@item
Timers for periodic events.
@item
A @code{datetime} class that not only tracks timestamp but also their accuracy,
which simplifies dealing with timestamps originating from different sources.
@item
Simple process handling for spawning child processes with redirected input and
output.
@end itemize\n")
(license gpl2+)))
(define-public filezilla
(package
(name "filezilla")
(version "3.55.0")
(source
(origin
(method url-fetch)
(uri (string-append "-project.org/client/"
"FileZilla_" version "_src.tar.bz2"))
(sha256
(base32 "10lwmf6cvryw2gja6vj1zh2y55z4i38wsvxdpclvwdnih10ynw5f"))))
(build-system gnu-build-system)
(arguments
'(#:configure-flags '("--disable-autoupdatecheck")))
(native-inputs
`(("cppunit" ,cppunit)
("gettext" ,gettext-minimal)
("pkg-config" ,pkg-config)
("xdg-utils" ,xdg-utils)))
(inputs
`(("dbus" ,dbus)
("gnutls" ,gnutls)
("gtk+" ,gtk+)
("libfilezilla" ,libfilezilla)
("libidn" ,libidn)
("nettle" ,nettle)
("pugixml" ,pugixml)
("sqlite" ,sqlite)
("wxwidgets" ,wxwidgets)))
(home-page "-project.org")
(synopsis "Full-featured graphical FTP/FTPS/SFTP client")
(description
"Filezilla client supports FTP, FTP over SSL/TLS (FTPS),
SSH File Transfer Protocol (SFTP), HTTP/1.1, SOCKS5, FTP-Proxy, IPv6
and others features such as bookmarks, drag and drop, filename filters,
directory comparison and more.")
(license gpl2+)
(properties '((upstream-name . "FileZilla")))))
(define-public vsftpd
(package
(name "vsftpd")
(version "3.0.4")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"vsftpd-" version ".tar.gz"))
(sha256
(base32 "09kap2qsd80m0x80jv5224x002x2jkr584dksppcv9p84yyj353b"))))
(build-system gnu-build-system)
(arguments
`(#:make-flags
(list (string-append "CC=" ,(cc-for-target))
that will never exist on . Manage libraries ourselves .
"LDFLAGS=-lcap -lpam"
"INSTALL=install -D")
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'build-SSL
(lambda _
(substitute* "builddefs.h"
(("#undef (VSF_BUILD_SSL)" _ symbol)
(string-append "#define " symbol)))))
(add-after 'unpack 'append-make-flags
(lambda _
(substitute* "Makefile"
(("(CFLAGS|LDFLAGS)[[:blank:]]*=" _ variable)
(format #f "UPSTREAM_~a +=" variable))
(("\\$\\((CFLAGS|LDFLAGS)\\)" _ variable)
(format #f "$(UPSTREAM_~a) $(~@*~a)" variable)))))
(add-after 'unpack 'patch-installation-directory
(lambda* (#:key outputs #:allow-other-keys)
(substitute* "Makefile"
(("/usr") (assoc-ref outputs "out")))))
(inputs
`(("libcap" ,libcap)
("linux-pam" ,linux-pam)
("openssl" ,openssl)))
(synopsis "Small FTP server with a focus on security")
(description
"The Very Secure File Transfer Protocol Daemon or @command{vsftpd} is a
server that listens on a TCP socket for clients and gives them access to local
guarantee.")
(home-page "")
with OpenSSL exception
|
c6f01f09868e857283c973df0b77a19554be34c7475aef032f5e63549e0a9e82 | felixmulder/haskell-in-production | Class.hs | module Web.SimpleHttp.Class
( ToResponse(..)
) where
import Prelude
import Web.SimpleHttp.Types (Response(..), Error(..))
import Network.HTTP.Types.Status (status400, status500)
class ToResponse a where
toResponseFrom :: a -> Response
instance ToResponse a => ToResponse (Either Error a) where
toResponseFrom = \case
Left (InternalError e) -> Response status500 e
Left (BadRequest e) -> Response status400 e
Right a -> toResponseFrom a
| null | https://raw.githubusercontent.com/felixmulder/haskell-in-production/ff3431f01342b8689d3449007759706d0bba6488/part-1-testable-components/src/Web/SimpleHttp/Class.hs | haskell | module Web.SimpleHttp.Class
( ToResponse(..)
) where
import Prelude
import Web.SimpleHttp.Types (Response(..), Error(..))
import Network.HTTP.Types.Status (status400, status500)
class ToResponse a where
toResponseFrom :: a -> Response
instance ToResponse a => ToResponse (Either Error a) where
toResponseFrom = \case
Left (InternalError e) -> Response status500 e
Left (BadRequest e) -> Response status400 e
Right a -> toResponseFrom a
| |
ec56854e431d4a292f260abd15a50edc2fedc421cb9d82aca0e7ca0bb5a69ae2 | aphyr/merkle | linear.clj | (ns merkle.kv.linear
"Merkle trees are a data structure used to efficiently localize differences
between two copies of an ordered collection. Each element in the collection
is hashed into a leaf node. Every n leaf nodes have their hashes concatenated
and hashed to produce a supervening node. Those nodes are then combined and
hashed again, until a single root node has hashed the entire collection.
Given two of these trees, one can find differences between two copies of the
collection by finding nodes with differing hashes.
This particular implementation is aimed at a specific sub-problem: comparing
two key-value collections where:
1. The key set could vary between copies.
2. The collections could be much larger than RAM.
3. Keys are in sorted order.
4. The keyspace and probability distribution of keys is unknown.
5. New keys are usually added at the end.
Because the key set varies, we need to encode some information about the keys
in the tree nodes. Each of our nodes keeps the minimum and maximum key
covered by its hash. We can then consider nodes equal when they have the
same hash and the same start and end key, which makes it possible to compare
collections with different keys.
Since the collection is much larger than RAM (for instance, a table on disk),
but the distribution of the keyspace is unknown, our algorithm forgoes having
a well-balanced tree in favor of a single linear scan over the collection,
accruing at most log(n) nodes in RAM.
Because the key are in sorted order, we can efficiently construct this tree
in a single linear pass, at the cost of having a much smaller right-hand
subtree. The best-case scenario is a fully balanced tree, and the worst-case
scenario is a root node with a fully balanced subtree on the left, and a
single leaf node on the right. The worst-case cost for this structure, as
compared to a balanced btree, is one additional layer of depth.
Since new keys are added mostly to the end, two collections which are
periodically synchronized will tend to agree on their
first/smallest/left-hand keys and nodes. If two collections agree on the
first N keys, their hash trees will have an identical node->key distribution
over those N keys. In a periodically synchronized collection, this means
we'll only differ on a few keys towards the end, and can efficiently ignore
the bulk of the dataset. In the worst-case scenario, a single key is added to
the beginning of the collection, and none of the hashes are aligned, forcing
a full resync."
(:require [merkle.range :as range]))
(defrecord Node [^long hash min-key max-key left right])
(defn node->map
"Converts a Node to a standard Clojure map; useful for serialization."
[^Node node]
(when node
{:hash (.hash node)
:min-key (.min-key node)
:max-key (.max-key node)
:left (node->map (.left node))
:right (node->map (.right node))}))
(defn map->node
"Converts a map to a Node; useful for serialization."
[m]
(when m
(Node. (:hash m)
(:min-key m)
(:max-key m)
(map->node (:left m))
(map->node (:right m)))))
(defn key-range
"The inclusive range of keys a Node covers."
[^Node node]
(when node
(list (.min-key node)
(.max-key node))))
(defn aligned?
"Are two nodes comparable--i.e. do they have the same min-key and max-key?"
[^Node n1 ^Node n2]
(if (nil? n1)
(nil? n2)
(and n2
(= (.min-key n1) (.min-key n2))
(= (.max-key n1) (.max-key n2)))))
(defn same?
"Are two nodes equivalent; i.e. do they have the same hash, min-key, and
max-key?"
[^Node n1 ^Node n2]
(if (nil? n1)
(nil? n2)
(and n2
(= (.hash n1) (.hash n2))
(= (.min-key n1) (.min-key n2))
(= (.max-key n1) (.max-key n2)))))
(defn hash-nodes
"Combines two nodes together."
[^Node left ^Node right]
(cond
(nil? left) right
(nil? right) left
:else (Node. (hash (list (.hash left)
(.hash right)))
(.min-key left)
(.max-key right)
left
right)))
(defn assoc-or-conj!
"Associates, and conj's on OutOfBoundsException."
[v i value]
(try
(assoc! v i value)
(catch IndexOutOfBoundsException e
(conj! v value))))
(defn percolate
"Takes a vector of nodes awaiting merging with their neighbors, and a new
node to merge into position i. Returns a new vector of nodes awaiting merging
with their neighbors."
[levels i right]
(let [left (try (nth levels i)
(catch IndexOutOfBoundsException e
:out-of-bounds))]
(let [x (persistent! levels)
levels (transient x)]
(condp = left
; Fill in an empty space above
nil (assoc! levels i right)
; Add a new slot to the top
:out-of-bounds (conj! levels right)
; Merge with the left node and recur upwards.
(recur (assoc! levels i nil)
(inc i)
(hash-nodes left right))))))
(defn transient-seq
"A sequence over a transient collection. Definitely not safe unless you
realize it immediately."
[levels]
(->> levels
count
range
(map (partial nth levels))))
(defn compact?
"Is the given level merged into a single node--i.e. does it look like [nil
nil nil nil node]. Levels are transient so we have to use nth."
[levels]
(->> levels
transient-seq
(remove nil?)
(count)
(<= 1)))
(defn compact
"Takes a vector of nodes awaiting merging with their neighbors, and merges
them all into a single node. This handles the (usual) case where the right
side of the tree has fewer entries than the right, leaving us with dangling
levels."
[levels]
(let [levels (persistent! levels)]
(if (empty? levels)
nil
(->> levels reverse (remove nil?) (reduce hash-nodes)))))
(defn tree
"Computes a merkle tree for a sorted kv collection. Does not retain the head.
Can take two optional functions: keyfn and valfn, which extract the key and
the value from a given element of the collection; if not given, these default
to key and val, respectively."
([coll]
(tree coll key val))
([coll keyfn valfn]
; We keep a temporary vector containing uncombined nodes in the tree as we
move through the collection . The 0th entry of this vector is a node for a
; single element. The last entry is the Node at the highest level yet
; reached. Nodes percolate upwards through this vector until we have a
; single node at the top containing the full tree.
(->> coll
(reduce (fn [levels element]
Construct base - level node
(let [k (keyfn element)
h (hash (valfn element))
node (Node. h k k nil nil)]
(percolate levels 0 node)))
(transient []))
compact)))
(defn pr-node
[^Node node]
(if node
(str (pr-str (.hash node)) " (" (.min-key node) " " (.max-key node) ")")
"nil"))
(defn identical-ranges
"Returns an ordered lazy sequence of (start-key end-key) pairs for which two
trees are known to be identical."
[^Node t1 ^Node t2]
; (println "compare" (pr-node t1) (pr-node t2))
(let [r1 (key-range t1)
r2 (key-range t2)]
(cond
One node is nil
(nil? t1) (list)
(nil? t2) (list)
; Nodes cover the same key range.
(= r1 r2)
(if (= (.hash t1) (.hash t2))
; Nodes are identical.
(list (list (.min-key t1) (.max-key t1)))
; We *know* these keys differ.
(lazy-cat (identical-ranges (.left t1) (.left t2))
(identical-ranges (.right t1) (.right t2))))
; t1 and t2 are totally disjoint; nothing here for us.
(range/disjoint? r1 r2)
(list)
; t1 is a proper subset of t2; descend into t2 looking for t1.
(range/subset? r1 r2)
(lazy-cat (identical-ranges t1 (.left t2))
(identical-ranges t1 (.right t2)))
; t2 is a proper subset of t1; descend into t1 looking for it.
(range/subset? r2 r1)
(lazy-cat (identical-ranges (.left t1) t2)
(identical-ranges (.right t1) t2))
; t1 and t2 intersect, but neither is a subset of the other. Expand to
; all branches.
(range/intersect? r1 r2)
(lazy-cat (identical-ranges (.left t1) (.left t2))
(identical-ranges (.left t1) (.right t2))
(identical-ranges (.right t1) (.left t2))
(identical-ranges (.right t1) (.right t2)))
:else (throw (IllegalStateException. "Shouldn't get here.")))))
(defn diff-helper
"Given a sorted sequence of identical ranges, and a sequence of elements from
a local collection, yields elements which differ by riffling through both
sequences."
[ranges coll keyfn]
[ range 1 ] [ range 2 ] [ range 3 ]
; x x o x o o o
(when-let [element (first coll)]
(let [k (keyfn element)
range (first ranges)]
(cond
; We're out of ranges; return entire remaining collection.
(nil? range)
coll
; Element lies before the range and should be included.
(< (compare k (first range)) 0)
(cons element
(lazy-seq (diff-helper ranges (next coll) keyfn)))
; Element lies within the range
(<= (compare k (second range)) 0)
(lazy-seq (diff-helper ranges (next coll) keyfn))
; Element lies after the range.
:else
(lazy-seq (diff-helper (next ranges) coll keyfn))))))
(defn diff
"Given a local collection, a local tree, and a remote tree, yields a lazy
sequence of elements from the local collection which are not known to be
identical based on the two trees."
([coll local-tree remote-tree]
(diff coll local-tree remote-tree key))
([coll local-tree remote-tree keyfn]
(diff-helper (identical-ranges local-tree remote-tree) coll keyfn)))
| null | https://raw.githubusercontent.com/aphyr/merkle/4cb63269947f679551fbae277e8488b7406b18f6/src/merkle/kv/linear.clj | clojure | i.e. do they have the same hash, min-key, and
Fill in an empty space above
Add a new slot to the top
Merge with the left node and recur upwards.
if not given, these default
We keep a temporary vector containing uncombined nodes in the tree as we
single element. The last entry is the Node at the highest level yet
reached. Nodes percolate upwards through this vector until we have a
single node at the top containing the full tree.
(println "compare" (pr-node t1) (pr-node t2))
Nodes cover the same key range.
Nodes are identical.
We *know* these keys differ.
t1 and t2 are totally disjoint; nothing here for us.
t1 is a proper subset of t2; descend into t2 looking for t1.
t2 is a proper subset of t1; descend into t1 looking for it.
t1 and t2 intersect, but neither is a subset of the other. Expand to
all branches.
x x o x o o o
We're out of ranges; return entire remaining collection.
Element lies before the range and should be included.
Element lies within the range
Element lies after the range. | (ns merkle.kv.linear
"Merkle trees are a data structure used to efficiently localize differences
between two copies of an ordered collection. Each element in the collection
is hashed into a leaf node. Every n leaf nodes have their hashes concatenated
and hashed to produce a supervening node. Those nodes are then combined and
hashed again, until a single root node has hashed the entire collection.
Given two of these trees, one can find differences between two copies of the
collection by finding nodes with differing hashes.
This particular implementation is aimed at a specific sub-problem: comparing
two key-value collections where:
1. The key set could vary between copies.
2. The collections could be much larger than RAM.
3. Keys are in sorted order.
4. The keyspace and probability distribution of keys is unknown.
5. New keys are usually added at the end.
Because the key set varies, we need to encode some information about the keys
in the tree nodes. Each of our nodes keeps the minimum and maximum key
covered by its hash. We can then consider nodes equal when they have the
same hash and the same start and end key, which makes it possible to compare
collections with different keys.
Since the collection is much larger than RAM (for instance, a table on disk),
but the distribution of the keyspace is unknown, our algorithm forgoes having
a well-balanced tree in favor of a single linear scan over the collection,
accruing at most log(n) nodes in RAM.
Because the key are in sorted order, we can efficiently construct this tree
in a single linear pass, at the cost of having a much smaller right-hand
subtree. The best-case scenario is a fully balanced tree, and the worst-case
scenario is a root node with a fully balanced subtree on the left, and a
single leaf node on the right. The worst-case cost for this structure, as
compared to a balanced btree, is one additional layer of depth.
Since new keys are added mostly to the end, two collections which are
periodically synchronized will tend to agree on their
first/smallest/left-hand keys and nodes. If two collections agree on the
first N keys, their hash trees will have an identical node->key distribution
over those N keys. In a periodically synchronized collection, this means
we'll only differ on a few keys towards the end, and can efficiently ignore
the bulk of the dataset. In the worst-case scenario, a single key is added to
the beginning of the collection, and none of the hashes are aligned, forcing
a full resync."
(:require [merkle.range :as range]))
(defrecord Node [^long hash min-key max-key left right])
(defn node->map
"Converts a Node to a standard Clojure map; useful for serialization."
[^Node node]
(when node
{:hash (.hash node)
:min-key (.min-key node)
:max-key (.max-key node)
:left (node->map (.left node))
:right (node->map (.right node))}))
(defn map->node
"Converts a map to a Node; useful for serialization."
[m]
(when m
(Node. (:hash m)
(:min-key m)
(:max-key m)
(map->node (:left m))
(map->node (:right m)))))
(defn key-range
"The inclusive range of keys a Node covers."
[^Node node]
(when node
(list (.min-key node)
(.max-key node))))
(defn aligned?
"Are two nodes comparable--i.e. do they have the same min-key and max-key?"
[^Node n1 ^Node n2]
(if (nil? n1)
(nil? n2)
(and n2
(= (.min-key n1) (.min-key n2))
(= (.max-key n1) (.max-key n2)))))
(defn same?
max-key?"
[^Node n1 ^Node n2]
(if (nil? n1)
(nil? n2)
(and n2
(= (.hash n1) (.hash n2))
(= (.min-key n1) (.min-key n2))
(= (.max-key n1) (.max-key n2)))))
(defn hash-nodes
"Combines two nodes together."
[^Node left ^Node right]
(cond
(nil? left) right
(nil? right) left
:else (Node. (hash (list (.hash left)
(.hash right)))
(.min-key left)
(.max-key right)
left
right)))
(defn assoc-or-conj!
"Associates, and conj's on OutOfBoundsException."
[v i value]
(try
(assoc! v i value)
(catch IndexOutOfBoundsException e
(conj! v value))))
(defn percolate
"Takes a vector of nodes awaiting merging with their neighbors, and a new
node to merge into position i. Returns a new vector of nodes awaiting merging
with their neighbors."
[levels i right]
(let [left (try (nth levels i)
(catch IndexOutOfBoundsException e
:out-of-bounds))]
(let [x (persistent! levels)
levels (transient x)]
(condp = left
nil (assoc! levels i right)
:out-of-bounds (conj! levels right)
(recur (assoc! levels i nil)
(inc i)
(hash-nodes left right))))))
(defn transient-seq
"A sequence over a transient collection. Definitely not safe unless you
realize it immediately."
[levels]
(->> levels
count
range
(map (partial nth levels))))
(defn compact?
"Is the given level merged into a single node--i.e. does it look like [nil
nil nil nil node]. Levels are transient so we have to use nth."
[levels]
(->> levels
transient-seq
(remove nil?)
(count)
(<= 1)))
(defn compact
"Takes a vector of nodes awaiting merging with their neighbors, and merges
them all into a single node. This handles the (usual) case where the right
side of the tree has fewer entries than the right, leaving us with dangling
levels."
[levels]
(let [levels (persistent! levels)]
(if (empty? levels)
nil
(->> levels reverse (remove nil?) (reduce hash-nodes)))))
(defn tree
"Computes a merkle tree for a sorted kv collection. Does not retain the head.
Can take two optional functions: keyfn and valfn, which extract the key and
to key and val, respectively."
([coll]
(tree coll key val))
([coll keyfn valfn]
move through the collection . The 0th entry of this vector is a node for a
(->> coll
(reduce (fn [levels element]
Construct base - level node
(let [k (keyfn element)
h (hash (valfn element))
node (Node. h k k nil nil)]
(percolate levels 0 node)))
(transient []))
compact)))
(defn pr-node
[^Node node]
(if node
(str (pr-str (.hash node)) " (" (.min-key node) " " (.max-key node) ")")
"nil"))
(defn identical-ranges
"Returns an ordered lazy sequence of (start-key end-key) pairs for which two
trees are known to be identical."
[^Node t1 ^Node t2]
(let [r1 (key-range t1)
r2 (key-range t2)]
(cond
One node is nil
(nil? t1) (list)
(nil? t2) (list)
(= r1 r2)
(if (= (.hash t1) (.hash t2))
(list (list (.min-key t1) (.max-key t1)))
(lazy-cat (identical-ranges (.left t1) (.left t2))
(identical-ranges (.right t1) (.right t2))))
(range/disjoint? r1 r2)
(list)
(range/subset? r1 r2)
(lazy-cat (identical-ranges t1 (.left t2))
(identical-ranges t1 (.right t2)))
(range/subset? r2 r1)
(lazy-cat (identical-ranges (.left t1) t2)
(identical-ranges (.right t1) t2))
(range/intersect? r1 r2)
(lazy-cat (identical-ranges (.left t1) (.left t2))
(identical-ranges (.left t1) (.right t2))
(identical-ranges (.right t1) (.left t2))
(identical-ranges (.right t1) (.right t2)))
:else (throw (IllegalStateException. "Shouldn't get here.")))))
(defn diff-helper
"Given a sorted sequence of identical ranges, and a sequence of elements from
a local collection, yields elements which differ by riffling through both
sequences."
[ranges coll keyfn]
[ range 1 ] [ range 2 ] [ range 3 ]
(when-let [element (first coll)]
(let [k (keyfn element)
range (first ranges)]
(cond
(nil? range)
coll
(< (compare k (first range)) 0)
(cons element
(lazy-seq (diff-helper ranges (next coll) keyfn)))
(<= (compare k (second range)) 0)
(lazy-seq (diff-helper ranges (next coll) keyfn))
:else
(lazy-seq (diff-helper (next ranges) coll keyfn))))))
(defn diff
"Given a local collection, a local tree, and a remote tree, yields a lazy
sequence of elements from the local collection which are not known to be
identical based on the two trees."
([coll local-tree remote-tree]
(diff coll local-tree remote-tree key))
([coll local-tree remote-tree keyfn]
(diff-helper (identical-ranges local-tree remote-tree) coll keyfn)))
|
ea3768ca21b9620d7aebfede2e35715478e0f2b6057601f2f1caa5d515d64b74 | open-company/open-company-web | email_domains.cljs | (ns oc.web.components.ui.email-domains
(:require [rum.core :as rum]
[org.martinklepsch.derivatives :as drv]
[oc.web.dispatcher :as dis]
[oc.web.lib.utils :as utils]
[oc.web.mixins.ui :as ui-mixins]
[oc.web.lib.responsive :as responsive]
[oc.web.actions.team :as team-actions]
[oc.web.components.ui.alert-modal :as alert-modal]
[oc.web.actions.notifications :as notification-actions]))
(defn email-domain-removed [success?]
(notification-actions/show-notification
{:title (if success? "Email domain successfully removed" "Error")
:description (when-not success? "An error occurred while removing the email domain, please try again.")
:expire 3
:id (if success? :email-domain-remove-success :email-domain-remove-error)
:dismiss true}))
(defn email-domain-added [success?]
(notification-actions/show-notification
{:title (if success? "Email domain successfully added" "Error")
:description (when-not success? "An error occurred while adding the email domain, please try again.")
:expire 3
:id (if success? :email-domain-add-success :email-domain-add-error)
:dismiss true}))
(defn remove-email-domain-prompt [domain]
(let [alert-data {:icon "/img/ML/trash.svg"
:action "org-email-domain-remove"
:message "Are you sure you want to remove this email domain?"
:link-button-title "Keep"
:link-button-cb #(alert-modal/hide-alert)
:solid-button-style :red
:solid-button-title "Yes"
:solid-button-cb #(do
(alert-modal/hide-alert)
(team-actions/remove-team (:links domain) email-domain-removed))}]
(alert-modal/show-alert alert-data)))
(rum/defcs email-domains < rum/reactive
(drv/drv :org-settings-team-management)
ui-mixins/refresh-tooltips-mixin
[s]
(let [{:keys [um-domain-invite team-data]} (drv/react s :org-settings-team-management)
is-mobile? (responsive/is-mobile-size?)]
[:div.email-domain-container
[:div.email-domain-title
"Allowed email domains"
[:i.mdi.mdi-information-outline
{:title "Any user that signs up with an allowed email domain and verifies their email address will have contributor access to your team."
:data-toggle (when-not is-mobile? "tooltip")
:data-placement "top"
:data-container "body"}]]
[:div.email-domain-field-container.oc-input.group
[:input.email-domain-field
{:type "text"
:placeholder "@domain.com"
:auto-capitalize "none"
:value (or (:domain um-domain-invite) "")
:pattern "@?[a-z0-9.-]+\\.[a-z]{2,4}$"
:on-change #(dis/dispatch! [:input [:um-domain-invite :domain] (.. % -target -value)])
:on-key-press (fn [e]
(when (= (.-key e) "Enter")
(let [domain (:domain um-domain-invite)]
(when (utils/valid-domain? domain)
(team-actions/email-domain-team-add domain email-domain-added)))))}]
[:button.mlb-reset.add-email-domain-bt
{:disabled (not (utils/valid-domain? (:domain um-domain-invite)))
:on-click (fn [e]
(let [domain (:domain um-domain-invite)]
(when (utils/valid-domain? domain)
(team-actions/email-domain-team-add domain email-domain-added))))}
"Add"]]
[:div.email-domain-list
(for [domain (:email-domains team-data)]
[:div.email-domain-row
{:key (str "org-settings-domain-" domain)}
(str "@" (:domain domain))
(when (utils/link-for (:links domain) "remove")
[:button.mlb-reset.remove-email-bt
{:on-click #(remove-email-domain-prompt domain)}
"Remove"])])]])) | null | https://raw.githubusercontent.com/open-company/open-company-web/dfce3dd9bc115df91003179bceb87cca1f84b6cf/src/main/oc/web/components/ui/email_domains.cljs | clojure | (ns oc.web.components.ui.email-domains
(:require [rum.core :as rum]
[org.martinklepsch.derivatives :as drv]
[oc.web.dispatcher :as dis]
[oc.web.lib.utils :as utils]
[oc.web.mixins.ui :as ui-mixins]
[oc.web.lib.responsive :as responsive]
[oc.web.actions.team :as team-actions]
[oc.web.components.ui.alert-modal :as alert-modal]
[oc.web.actions.notifications :as notification-actions]))
(defn email-domain-removed [success?]
(notification-actions/show-notification
{:title (if success? "Email domain successfully removed" "Error")
:description (when-not success? "An error occurred while removing the email domain, please try again.")
:expire 3
:id (if success? :email-domain-remove-success :email-domain-remove-error)
:dismiss true}))
(defn email-domain-added [success?]
(notification-actions/show-notification
{:title (if success? "Email domain successfully added" "Error")
:description (when-not success? "An error occurred while adding the email domain, please try again.")
:expire 3
:id (if success? :email-domain-add-success :email-domain-add-error)
:dismiss true}))
(defn remove-email-domain-prompt [domain]
(let [alert-data {:icon "/img/ML/trash.svg"
:action "org-email-domain-remove"
:message "Are you sure you want to remove this email domain?"
:link-button-title "Keep"
:link-button-cb #(alert-modal/hide-alert)
:solid-button-style :red
:solid-button-title "Yes"
:solid-button-cb #(do
(alert-modal/hide-alert)
(team-actions/remove-team (:links domain) email-domain-removed))}]
(alert-modal/show-alert alert-data)))
(rum/defcs email-domains < rum/reactive
(drv/drv :org-settings-team-management)
ui-mixins/refresh-tooltips-mixin
[s]
(let [{:keys [um-domain-invite team-data]} (drv/react s :org-settings-team-management)
is-mobile? (responsive/is-mobile-size?)]
[:div.email-domain-container
[:div.email-domain-title
"Allowed email domains"
[:i.mdi.mdi-information-outline
{:title "Any user that signs up with an allowed email domain and verifies their email address will have contributor access to your team."
:data-toggle (when-not is-mobile? "tooltip")
:data-placement "top"
:data-container "body"}]]
[:div.email-domain-field-container.oc-input.group
[:input.email-domain-field
{:type "text"
:placeholder "@domain.com"
:auto-capitalize "none"
:value (or (:domain um-domain-invite) "")
:pattern "@?[a-z0-9.-]+\\.[a-z]{2,4}$"
:on-change #(dis/dispatch! [:input [:um-domain-invite :domain] (.. % -target -value)])
:on-key-press (fn [e]
(when (= (.-key e) "Enter")
(let [domain (:domain um-domain-invite)]
(when (utils/valid-domain? domain)
(team-actions/email-domain-team-add domain email-domain-added)))))}]
[:button.mlb-reset.add-email-domain-bt
{:disabled (not (utils/valid-domain? (:domain um-domain-invite)))
:on-click (fn [e]
(let [domain (:domain um-domain-invite)]
(when (utils/valid-domain? domain)
(team-actions/email-domain-team-add domain email-domain-added))))}
"Add"]]
[:div.email-domain-list
(for [domain (:email-domains team-data)]
[:div.email-domain-row
{:key (str "org-settings-domain-" domain)}
(str "@" (:domain domain))
(when (utils/link-for (:links domain) "remove")
[:button.mlb-reset.remove-email-bt
{:on-click #(remove-email-domain-prompt domain)}
"Remove"])])]])) | |
274caaa2c342a18512ba657c858bc9f54f5879c9ba75711962d9026b5ad09571 | sullyj3/adventofcode2022 | Day10.hs | module Day10 (main) where
import AOC
import AOC.Parse
import AOC.Parsers
import Extra (chunksOf)
import PyF
import Text.Megaparsec.Char (string)
import Utils (imap1, selectIndices1)
import Optics.Core (imap)
data Instruction = Noop
| Addx Int
deriving (Eq, Show)
-------------
-- Parsing --
-------------
parseInput ∷ Text → [Instruction]
parseInput = unsafeParse (linesOf instructionP)
where
instructionP = try (Noop <$ string "noop") <|> (Addx <$> (string "addx " *> signedInt))
---------------
-- Solutions --
---------------
--
-- Part 1
--
part1 ∷ [Instruction] → Int
part1 = sum . selectIndices1 [20,60..220] . imap1 (*) . xValues
xValues ∷ [Instruction] → [Int]
xValues = scanl (+) 1 . concatMap \case
Noop -> [0]
Addx x -> [0, x]
--
Part 2
--
part2 ∷ [Instruction] → Text
part2 = unlines . map (toText . imap renderPixel) . chunksOf 40 . xValues
where
renderPixel ix x = if abs (x - ix) <= 1 then '█' else ' '
main ∷ IO ()
main = do
putStrLn "Part 1:"
aocSinglePartMain "inputs/10.txt" exampleInput parseInput part1
putStrLn ""
putStrLn "Part 2:"
input <- parseInput <$> readFileText "inputs/10.txt"
putTextLn $ part2 input
exampleInput ∷ Text
exampleInput = toText @String [str|addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop|]
| null | https://raw.githubusercontent.com/sullyj3/adventofcode2022/1b8f28e78ac69ec7af857132eb4785c1e9dca011/src/Day10.hs | haskell | -----------
Parsing --
-----------
-------------
Solutions --
-------------
Part 1
| module Day10 (main) where
import AOC
import AOC.Parse
import AOC.Parsers
import Extra (chunksOf)
import PyF
import Text.Megaparsec.Char (string)
import Utils (imap1, selectIndices1)
import Optics.Core (imap)
data Instruction = Noop
| Addx Int
deriving (Eq, Show)
parseInput ∷ Text → [Instruction]
parseInput = unsafeParse (linesOf instructionP)
where
instructionP = try (Noop <$ string "noop") <|> (Addx <$> (string "addx " *> signedInt))
part1 ∷ [Instruction] → Int
part1 = sum . selectIndices1 [20,60..220] . imap1 (*) . xValues
xValues ∷ [Instruction] → [Int]
xValues = scanl (+) 1 . concatMap \case
Noop -> [0]
Addx x -> [0, x]
Part 2
part2 ∷ [Instruction] → Text
part2 = unlines . map (toText . imap renderPixel) . chunksOf 40 . xValues
where
renderPixel ix x = if abs (x - ix) <= 1 then '█' else ' '
main ∷ IO ()
main = do
putStrLn "Part 1:"
aocSinglePartMain "inputs/10.txt" exampleInput parseInput part1
putStrLn ""
putStrLn "Part 2:"
input <- parseInput <$> readFileText "inputs/10.txt"
putTextLn $ part2 input
exampleInput ∷ Text
exampleInput = toText @String [str|addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop|]
|
018eb3b4eff5846d20aa713274e36c6e10b52c11a73633602ed376c16540ca71 | flexsurfer/re-frisk | core.cljs | (ns ^{:mranderson/inlined true} re-frisk.inlined-deps.reagent.v1v0v0.reagent.core
(:require-macros [re-frisk.inlined-deps.reagent.v1v0v0.reagent.core])
(:refer-clojure :exclude [partial atom flush])
(:require [react :as react]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.template :as tmpl]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.component :as comp]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.util :as util]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.batching :as batch]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.protocols :as p]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.ratom :as ratom]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.debug :as deb :refer-macros [assert-some assert-component
assert-js-object assert-new-state
assert-callable]]))
(def is-client util/is-client)
(defn create-element
"Create a native React element, by calling React.createElement directly.
That means the second argument must be a javascript object (or nil), and
that any Reagent hiccup forms must be processed with as-element. For example
like this:
```cljs
(r/create-element \"div\" #js{:className \"foo\"}
\"Hi \" (r/as-element [:strong \"world!\"])
```
which is equivalent to
```cljs
[:div.foo \"Hi\" [:strong \"world!\"]]
```"
([type]
(create-element type nil))
([type props]
(assert-js-object props)
(react/createElement type props))
([type props child]
(assert-js-object props)
(react/createElement type props child))
([type props child & children]
(assert-js-object props)
(apply react/createElement type props child children)))
(defn as-element
"Turns a vector of Hiccup syntax into a React element. Returns form
unchanged if it is not a vector."
([form] (p/as-element tmpl/default-compiler form))
([form compiler] (p/as-element compiler form)))
(defn adapt-react-class
"Returns an adapter for a native React class, that may be used
just like a Reagent component function or class in Hiccup forms."
[c]
(assert-some c "Component")
(tmpl/adapt-react-class c))
(defn reactify-component
"Returns an adapter for a Reagent component, that may be used from
React, for example in JSX. A single argument, props, is passed to
the component, converted to a map."
([c] (reactify-component c tmpl/default-compiler))
([c compiler]
(assert-some c "Component")
(comp/reactify-component c compiler)))
(defn create-class
"Creates JS class based on provided Clojure map, for example:
```cljs
Constructor
:constructor (fn [this props])
:get-initial-state (fn [this])
;; Static methods
:get-derived-state-from-props (fn [props state] partial-state)
:get-derived-state-from-error (fn [error] partial-state)
;; Methods
:get-snapshot-before-update (fn [this old-argv new-argv] snapshot)
:should-component-update (fn [this old-argv new-argv])
:component-did-mount (fn [this])
:component-did-update (fn [this old-argv old-state snapshot])
:component-will-unmount (fn [this])
:component-did-catch (fn [this error info])
:reagent-render (fn [args....])
;; Or alternatively:
:render (fn [this])
;; Deprecated methods:
:UNSAFE_component-will-receive-props (fn [this new-argv])
:UNSAFE_component-will-update (fn [this new-argv new-state])
:UNSAFE_component-will-mount (fn [this])}
```
Everything is optional, except either :reagent-render or :render.
Map keys should use `React.Component` method names (-component.html),
and can be provided in snake-case or camelCase.
State can be initialized using constructor, which matches React.Component class,
or using getInitialState which matches old React createClass function and is
now implemented by Reagent for compatibility.
State can usually be anything, e.g. Cljs object. But if using getDerivedState
methods, the state has to be plain JS object as React implementation uses
Object.assign to merge partial state into the current state.
React built-in static methods or properties are automatically defined as statics."
([spec]
(comp/create-class spec tmpl/default-compiler))
([spec compiler]
(comp/create-class spec compiler)))
(defn current-component
"Returns the current React component (a.k.a `this`) in a component
function."
[]
comp/*current-component*)
(defn state-atom
"Returns an atom containing a components state."
[this]
(assert-component this)
(comp/state-atom this))
(defn state
"Returns the state of a component, as set with replace-state or set-state.
Equivalent to `(deref (r/state-atom this))`"
[this]
(assert-component this)
(deref (state-atom this)))
(defn replace-state
"Set state of a component.
Equivalent to `(reset! (state-atom this) new-state)`"
[this new-state]
(assert-component this)
(assert-new-state new-state)
(reset! (state-atom this) new-state))
(defn set-state
"Merge component state with new-state.
Equivalent to `(swap! (state-atom this) merge new-state)`"
[this new-state]
(assert-component this)
(assert-new-state new-state)
(swap! (state-atom this) merge new-state))
(defn force-update
"Force a component to re-render immediately.
If the second argument is true, child components will also be
re-rendered, even is their arguments have not changed."
([this]
(force-update this false))
([this deep]
(ratom/flush!)
(util/force-update this deep)
(batch/flush-after-render)))
(defn props
"Returns the props passed to a component."
[this]
(assert-component this)
(comp/get-props this))
(defn children
"Returns the children passed to a component."
[this]
(assert-component this)
(comp/get-children this))
(defn argv
"Returns the entire Hiccup form passed to the component."
[this]
(assert-component this)
(comp/get-argv this))
(defn class-names
"Function which normalizes and combines class values to a string
Reagent allows classes to be defined as:
- Strings
- Named objects (Symbols or Keywords)
- Collections of previous types"
([])
([class] (util/class-names class))
([class1 class2] (util/class-names class1 class2))
([class1 class2 & others] (apply util/class-names class1 class2 others)))
(defn merge-props
"Utility function that merges some maps, handling `:class` and `:style`.
The :class value is always normalized (using `class-names`) even if no
merging is done."
([] (util/merge-props))
([defaults] (util/merge-props defaults))
([defaults props] (util/merge-props defaults props))
([defaults props & others] (apply util/merge-props defaults props others)))
(defn flush
"Render dirty components immediately.
Note that this may not work in event handlers, since React.js does
batching of updates there."
[]
(batch/flush))
Ratom
(defn atom
"Like clojure.core/atom, except that it keeps track of derefs.
Reagent components that derefs one of these are automatically
re-rendered."
([x] (ratom/atom x))
([x & rest] (apply ratom/atom x rest)))
(defn track
"Takes a function and optional arguments, and returns a derefable
containing the output of that function. If the function derefs
Reagent atoms (or track, etc), the value will be updated whenever
the atom changes.
In other words, `@(track foo bar)` will produce the same result
as `(foo bar)`, but foo will only be called again when the atoms it
depends on changes, and will only trigger updates of components when
its result changes.
track is lazy, i.e the function is only evaluated on deref."
[f & args]
{:pre [(ifn? f)]}
(ratom/make-track f args))
(defn track!
"An eager version of track. The function passed is called
immediately, and continues to be called when needed, until stopped
with dispose!."
[f & args]
{:pre [(ifn? f)]}
(ratom/make-track! f args))
(defn dispose!
"Stop the result of track! from updating."
[x]
(ratom/dispose! x))
(defn wrap
"Provide a combination of value and callback, that looks like an atom.
The first argument can be any value, that will be returned when the
result is deref'ed.
The second argument should be a function, that is called with the
optional extra arguments provided to wrap, and the new value of the
resulting 'atom'.
Use for example like this:
```cljs
(wrap (:foo @state)
swap! state assoc :foo)
```
Probably useful only for passing to child components."
[value reset-fn & args]
(assert-callable reset-fn)
(ratom/make-wrapper value reset-fn args))
;; RCursor
(defn cursor
"Provide a cursor into a Reagent atom.
Behaves like a Reagent atom but focuses updates and derefs to
the specified path within the wrapped Reagent atom. e.g.,
```cljs
(let [c (cursor ra [:nested :content])]
equivalent to ( get - in @ra [: nested : content ] )
equivalent to ( swap ! in [: nested : content ] 42 )
... (swap! c inc) ;; equivalence to (swap! ra update-in [:nested :content] inc)
)
```
The first parameter can also be a function, that should look
something like this:
```cljs
(defn set-get
([k] (get-in @state k))
([k v] (swap! state assoc-in k v)))
```
The function will be called with one argument – the path passed to
cursor – when the cursor is deref'ed, and two arguments (path and
new value) when the cursor is modified.
Given that set-get function, (and that state is a Reagent atom, or
another cursor) these cursors are equivalent:
`(cursor state [:foo])` and `(cursor set-get [:foo])`.
Note that a cursor is lazy: its value will not change until it is
used. This may be noticed with add-watch."
([src path]
(ratom/cursor src path)))
Utilities
(defn rswap!
"Swaps the value of a to be `(apply f current-value-of-atom args)`.
rswap! works like swap!, except that recursive calls to rswap! on
the same atom are allowed – and it always returns nil."
[^IAtom a f & args]
{:pre [(satisfies? IAtom a)
(ifn? f)]}
(if (.-rswapping a)
(-> (or (.-rswapfs a)
(set! (.-rswapfs a) (array)))
(.push #(apply f % args)))
(do (set! (.-rswapping a) true)
(try (swap! a (fn [state]
(loop [s (apply f state args)]
(if-some [sf (some-> a .-rswapfs .shift)]
(recur (sf s))
s))))
(finally
(set! (.-rswapping a) false)))))
nil)
(defn next-tick
"Run f using requestAnimationFrame or equivalent.
f will be called just before components are rendered."
[f]
(batch/do-before-flush f))
(defn after-render
"Run f using requestAnimationFrame or equivalent.
f will be called just after any queued renders in the next animation
frame (and even if no renders actually occur)."
[f]
(batch/do-after-render f))
(defn partial
"Works just like clojure.core/partial, but the result can be compared with ="
[f & args]
(util/make-partial-fn f args))
(defn create-compiler
"Creates Compiler object with given `opts`,
this can be passed to `render`, `as-element` and other functions to control
how they turn the Reagent-style Hiccup into React components and elements."
[opts]
(tmpl/create-compiler opts))
(defn set-default-compiler!
"Globally sets the Compiler object used by `render`, `as-element` and other
calls by default, when no `compiler` parameter is provided.
Use `nil` value to restore the original default compiler."
[compiler]
(tmpl/set-default-compiler! (if (nil? compiler)
tmpl/default-compiler*
compiler)))
(defn render
{:deprecated "0.10.0"}
[& _]
(throw (js/Error. "Reagent.core/render function was moved to re-frisk.inlined-deps.reagent.v1v0v0.reagent.dom namespace in Reagent v1.0."))
nil)
| null | https://raw.githubusercontent.com/flexsurfer/re-frisk/638d820c84e23be79b8c52f8f136a611d942443f/re-frisk/src/re_frisk/inlined_deps/reagent/v1v0v0/reagent/core.cljs | clojure | Static methods
Methods
Or alternatively:
Deprecated methods:
RCursor
equivalence to (swap! ra update-in [:nested :content] inc) | (ns ^{:mranderson/inlined true} re-frisk.inlined-deps.reagent.v1v0v0.reagent.core
(:require-macros [re-frisk.inlined-deps.reagent.v1v0v0.reagent.core])
(:refer-clojure :exclude [partial atom flush])
(:require [react :as react]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.template :as tmpl]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.component :as comp]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.util :as util]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.batching :as batch]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.impl.protocols :as p]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.ratom :as ratom]
[re-frisk.inlined-deps.reagent.v1v0v0.reagent.debug :as deb :refer-macros [assert-some assert-component
assert-js-object assert-new-state
assert-callable]]))
(def is-client util/is-client)
(defn create-element
"Create a native React element, by calling React.createElement directly.
That means the second argument must be a javascript object (or nil), and
that any Reagent hiccup forms must be processed with as-element. For example
like this:
```cljs
(r/create-element \"div\" #js{:className \"foo\"}
\"Hi \" (r/as-element [:strong \"world!\"])
```
which is equivalent to
```cljs
[:div.foo \"Hi\" [:strong \"world!\"]]
```"
([type]
(create-element type nil))
([type props]
(assert-js-object props)
(react/createElement type props))
([type props child]
(assert-js-object props)
(react/createElement type props child))
([type props child & children]
(assert-js-object props)
(apply react/createElement type props child children)))
(defn as-element
"Turns a vector of Hiccup syntax into a React element. Returns form
unchanged if it is not a vector."
([form] (p/as-element tmpl/default-compiler form))
([form compiler] (p/as-element compiler form)))
(defn adapt-react-class
"Returns an adapter for a native React class, that may be used
just like a Reagent component function or class in Hiccup forms."
[c]
(assert-some c "Component")
(tmpl/adapt-react-class c))
(defn reactify-component
"Returns an adapter for a Reagent component, that may be used from
React, for example in JSX. A single argument, props, is passed to
the component, converted to a map."
([c] (reactify-component c tmpl/default-compiler))
([c compiler]
(assert-some c "Component")
(comp/reactify-component c compiler)))
(defn create-class
"Creates JS class based on provided Clojure map, for example:
```cljs
Constructor
:constructor (fn [this props])
:get-initial-state (fn [this])
:get-derived-state-from-props (fn [props state] partial-state)
:get-derived-state-from-error (fn [error] partial-state)
:get-snapshot-before-update (fn [this old-argv new-argv] snapshot)
:should-component-update (fn [this old-argv new-argv])
:component-did-mount (fn [this])
:component-did-update (fn [this old-argv old-state snapshot])
:component-will-unmount (fn [this])
:component-did-catch (fn [this error info])
:reagent-render (fn [args....])
:render (fn [this])
:UNSAFE_component-will-receive-props (fn [this new-argv])
:UNSAFE_component-will-update (fn [this new-argv new-state])
:UNSAFE_component-will-mount (fn [this])}
```
Everything is optional, except either :reagent-render or :render.
Map keys should use `React.Component` method names (-component.html),
and can be provided in snake-case or camelCase.
State can be initialized using constructor, which matches React.Component class,
or using getInitialState which matches old React createClass function and is
now implemented by Reagent for compatibility.
State can usually be anything, e.g. Cljs object. But if using getDerivedState
methods, the state has to be plain JS object as React implementation uses
Object.assign to merge partial state into the current state.
React built-in static methods or properties are automatically defined as statics."
([spec]
(comp/create-class spec tmpl/default-compiler))
([spec compiler]
(comp/create-class spec compiler)))
(defn current-component
"Returns the current React component (a.k.a `this`) in a component
function."
[]
comp/*current-component*)
(defn state-atom
"Returns an atom containing a components state."
[this]
(assert-component this)
(comp/state-atom this))
(defn state
"Returns the state of a component, as set with replace-state or set-state.
Equivalent to `(deref (r/state-atom this))`"
[this]
(assert-component this)
(deref (state-atom this)))
(defn replace-state
"Set state of a component.
Equivalent to `(reset! (state-atom this) new-state)`"
[this new-state]
(assert-component this)
(assert-new-state new-state)
(reset! (state-atom this) new-state))
(defn set-state
"Merge component state with new-state.
Equivalent to `(swap! (state-atom this) merge new-state)`"
[this new-state]
(assert-component this)
(assert-new-state new-state)
(swap! (state-atom this) merge new-state))
(defn force-update
"Force a component to re-render immediately.
If the second argument is true, child components will also be
re-rendered, even is their arguments have not changed."
([this]
(force-update this false))
([this deep]
(ratom/flush!)
(util/force-update this deep)
(batch/flush-after-render)))
(defn props
"Returns the props passed to a component."
[this]
(assert-component this)
(comp/get-props this))
(defn children
"Returns the children passed to a component."
[this]
(assert-component this)
(comp/get-children this))
(defn argv
"Returns the entire Hiccup form passed to the component."
[this]
(assert-component this)
(comp/get-argv this))
(defn class-names
"Function which normalizes and combines class values to a string
Reagent allows classes to be defined as:
- Strings
- Named objects (Symbols or Keywords)
- Collections of previous types"
([])
([class] (util/class-names class))
([class1 class2] (util/class-names class1 class2))
([class1 class2 & others] (apply util/class-names class1 class2 others)))
(defn merge-props
"Utility function that merges some maps, handling `:class` and `:style`.
The :class value is always normalized (using `class-names`) even if no
merging is done."
([] (util/merge-props))
([defaults] (util/merge-props defaults))
([defaults props] (util/merge-props defaults props))
([defaults props & others] (apply util/merge-props defaults props others)))
(defn flush
"Render dirty components immediately.
Note that this may not work in event handlers, since React.js does
batching of updates there."
[]
(batch/flush))
Ratom
(defn atom
"Like clojure.core/atom, except that it keeps track of derefs.
Reagent components that derefs one of these are automatically
re-rendered."
([x] (ratom/atom x))
([x & rest] (apply ratom/atom x rest)))
(defn track
"Takes a function and optional arguments, and returns a derefable
containing the output of that function. If the function derefs
Reagent atoms (or track, etc), the value will be updated whenever
the atom changes.
In other words, `@(track foo bar)` will produce the same result
as `(foo bar)`, but foo will only be called again when the atoms it
depends on changes, and will only trigger updates of components when
its result changes.
track is lazy, i.e the function is only evaluated on deref."
[f & args]
{:pre [(ifn? f)]}
(ratom/make-track f args))
(defn track!
"An eager version of track. The function passed is called
immediately, and continues to be called when needed, until stopped
with dispose!."
[f & args]
{:pre [(ifn? f)]}
(ratom/make-track! f args))
(defn dispose!
"Stop the result of track! from updating."
[x]
(ratom/dispose! x))
(defn wrap
"Provide a combination of value and callback, that looks like an atom.
The first argument can be any value, that will be returned when the
result is deref'ed.
The second argument should be a function, that is called with the
optional extra arguments provided to wrap, and the new value of the
resulting 'atom'.
Use for example like this:
```cljs
(wrap (:foo @state)
swap! state assoc :foo)
```
Probably useful only for passing to child components."
[value reset-fn & args]
(assert-callable reset-fn)
(ratom/make-wrapper value reset-fn args))
(defn cursor
"Provide a cursor into a Reagent atom.
Behaves like a Reagent atom but focuses updates and derefs to
the specified path within the wrapped Reagent atom. e.g.,
```cljs
(let [c (cursor ra [:nested :content])]
equivalent to ( get - in @ra [: nested : content ] )
equivalent to ( swap ! in [: nested : content ] 42 )
)
```
The first parameter can also be a function, that should look
something like this:
```cljs
(defn set-get
([k] (get-in @state k))
([k v] (swap! state assoc-in k v)))
```
The function will be called with one argument – the path passed to
cursor – when the cursor is deref'ed, and two arguments (path and
new value) when the cursor is modified.
Given that set-get function, (and that state is a Reagent atom, or
another cursor) these cursors are equivalent:
`(cursor state [:foo])` and `(cursor set-get [:foo])`.
Note that a cursor is lazy: its value will not change until it is
used. This may be noticed with add-watch."
([src path]
(ratom/cursor src path)))
Utilities
(defn rswap!
"Swaps the value of a to be `(apply f current-value-of-atom args)`.
rswap! works like swap!, except that recursive calls to rswap! on
the same atom are allowed – and it always returns nil."
[^IAtom a f & args]
{:pre [(satisfies? IAtom a)
(ifn? f)]}
(if (.-rswapping a)
(-> (or (.-rswapfs a)
(set! (.-rswapfs a) (array)))
(.push #(apply f % args)))
(do (set! (.-rswapping a) true)
(try (swap! a (fn [state]
(loop [s (apply f state args)]
(if-some [sf (some-> a .-rswapfs .shift)]
(recur (sf s))
s))))
(finally
(set! (.-rswapping a) false)))))
nil)
(defn next-tick
"Run f using requestAnimationFrame or equivalent.
f will be called just before components are rendered."
[f]
(batch/do-before-flush f))
(defn after-render
"Run f using requestAnimationFrame or equivalent.
f will be called just after any queued renders in the next animation
frame (and even if no renders actually occur)."
[f]
(batch/do-after-render f))
(defn partial
"Works just like clojure.core/partial, but the result can be compared with ="
[f & args]
(util/make-partial-fn f args))
(defn create-compiler
"Creates Compiler object with given `opts`,
this can be passed to `render`, `as-element` and other functions to control
how they turn the Reagent-style Hiccup into React components and elements."
[opts]
(tmpl/create-compiler opts))
(defn set-default-compiler!
"Globally sets the Compiler object used by `render`, `as-element` and other
calls by default, when no `compiler` parameter is provided.
Use `nil` value to restore the original default compiler."
[compiler]
(tmpl/set-default-compiler! (if (nil? compiler)
tmpl/default-compiler*
compiler)))
(defn render
{:deprecated "0.10.0"}
[& _]
(throw (js/Error. "Reagent.core/render function was moved to re-frisk.inlined-deps.reagent.v1v0v0.reagent.dom namespace in Reagent v1.0."))
nil)
|
8e41ae615c36df343d0bc5a1fc3d7451382f336cb8ab483cfd4643cb0f2cd4d7 | mirage/bechamel | mperf.mli | module Attr : sig
type flag =
| Disabled (** off by default *)
| Inherit (** children inherit it *)
| Exclude_user (** don't count user *)
| Exclude_kernel (** don't count kernel *)
| Exclude_hv (** don't count hypervisor *)
| Exclude_idle (** don't count when idle *)
| Enable_on_exec (** next exec enables *)
module Kind : sig
type t =
| Cycles
| Instructions
| Cache_references
| Cache_misses
| Branch_instructions
| Branch_misses
| Bus_cycles
| Stalled_cycles_frontend
| Stalled_cycles_backend
| Ref_cpu_cycles
| Cpu_clock
| Task_clock
| Page_faults
| Context_switches
| Cpu_migrations
| Page_faults_min
| Page_faults_maj
| Alignment_faults
| Emulation_faults
| Dummy
val to_string : t -> string
val of_string : string -> t
end
type t
(** Opaque type of a perf event attribute. *)
val make : ?flags:flag list -> Kind.t -> t
(** [make ?flags kind] is a perf event attribute of type [kind], with flags
[flags]. *)
val compare : t -> t -> int
(** comparison function on {!t}. *)
end
module KindMap : Map.S with type key = Attr.Kind.t
type flag =
| Fd_cloexec
* ( since Linux 3.14 ) . This flag enables the close - on - exec flag for the
created event file descriptor , so that the file descriptor is
automatically closed on execve(2 ) . Setting the close - on - exec flags at
creation time , rather than later with fcntl(2 ) , avoids potential race
conditions where the calling thread invokes perf_event_open ( ) and
fcntl(2 ) at the same time as another thread calls fork(2 ) then
execve(2 ) .
created event file descriptor, so that the file descriptor is
automatically closed on execve(2). Setting the close-on-exec flags at
creation time, rather than later with fcntl(2), avoids potential race
conditions where the calling thread invokes perf_event_open() and
fcntl(2) at the same time as another thread calls fork(2) then
execve(2). *)
| Fd_no_group
(** This flag allows creating an event as part of an event group but
having no group leader. It is unclear why this is useful.*)
| Fd_output
(** This flag reroutes the output from an event to the group leader. *)
| Pid_cgroup
* This flag activates per - container system - wide monitoring . A container
is an abstraction that isolates a set of resources for finer - grained
control ( CPUs , memory , etc . ) . In this mode , the event is measured only
if the thread running on the monitored CPU belongs to the designated
container ( cgroup ) . The cgroup is identified by passing a file
descriptor opened on its directory in the filesystem . For
instance , if the cgroup to monitor is called test , then a file
descriptor opened on /dev / cgroup / test ( assuming is mounted on
/dev / cgroup ) must be passed as the pid parameter . monitoring is
available only for system - wide events and may therefore require extra
permissions .
is an abstraction that isolates a set of resources for finer-grained
control (CPUs, memory, etc.). In this mode, the event is measured only
if the thread running on the monitored CPU belongs to the designated
container (cgroup). The cgroup is identified by passing a file
descriptor opened on its directory in the cgroupfs filesystem. For
instance, if the cgroup to monitor is called test, then a file
descriptor opened on /dev/cgroup/test (assuming cgroupfs is mounted on
/dev/cgroup) must be passed as the pid parameter. cgroup monitoring is
available only for system-wide events and may therefore require extra
permissions. *)
type t
* Opaque type of an event counter ( internally [ t ] is a file descriptor ) . Each
file descriptor corresponds to one event that is measured ; these can be
grouped together to measure multiple events simultaneously .
file descriptor corresponds to one event that is measured; these can be
grouped together to measure multiple events simultaneously. *)
val make : ?pid:int -> ?cpu:int -> ?group:t -> ?flags:flag list -> Attr.t -> t
* [ make ~pid ~cpu ? group ? flags attr ] is a perf event counter . Refer to
perf_event_open(2 ) for the description of the arguments . One counter only
counts one kind of attribute at a time . If you want to simultanously count
different metrics ( like the perf stat tool does ) , you have to setup several
counters .
perf_event_open(2) for the description of the arguments. One counter only
counts one kind of attribute at a time. If you want to simultanously count
different metrics (like the perf stat tool does), you have to setup several
counters. *)
val kind : t -> Attr.Kind.t
(** [kind c] is the kind of events that this counter counts. *)
val read : t -> int64
(** [read c] is the value of the counter [c]. *)
val reset : t -> unit
* [ reset c ] sets [ c ] to zero .
val enable : t -> unit
(** Start measuring. *)
val disable : t -> unit
(** Disabling an event. When an event is disabled it does not count or generate
overflows but does continue to exist and maintain its count value. *)
val close : t -> unit
(** Free resources associated with a counter. *)
type execution = private
{ process_status : Unix.process_status
; stdout : string
; stderr : string
; data : Int64.t KindMap.t
}
(** Type returned by [with_process] *)
val with_process :
?env:string list
-> ?timeout:int
-> ?stdout:string
-> ?stderr:string
-> string list
-> Attr.t list
-> [ `Ok of execution | `Timeout | `Exn of exn ]
(** [with_process ?env ?timeout ?stdout ?stderr cmd attrs] is the result of the
execution of the program described by [cmd]. This can either be a successful
execution, or an error. *)
val enable_all : unit -> unit
(** A process can enable or disable all the event groups that are attached to it
using the prctl(2) PR_TASK_PERF_EVENTS_ENABLE and
PR_TASK_PERF_EVENTS_DISABLE operations. This applies to all counters on the
calling process, whether created by this process or by another, and does not
affect any counters that this process has created on other processes. It
enables or disables only the group leaders, not any other members in the
groups. *)
val disable_all : unit -> unit
| null | https://raw.githubusercontent.com/mirage/bechamel/8e1a3e64c6723d1d9b2081aeb06d725024f88012/mperf/lib/mperf.mli | ocaml | * off by default
* children inherit it
* don't count user
* don't count kernel
* don't count hypervisor
* don't count when idle
* next exec enables
* Opaque type of a perf event attribute.
* [make ?flags kind] is a perf event attribute of type [kind], with flags
[flags].
* comparison function on {!t}.
* This flag allows creating an event as part of an event group but
having no group leader. It is unclear why this is useful.
* This flag reroutes the output from an event to the group leader.
* [kind c] is the kind of events that this counter counts.
* [read c] is the value of the counter [c].
* Start measuring.
* Disabling an event. When an event is disabled it does not count or generate
overflows but does continue to exist and maintain its count value.
* Free resources associated with a counter.
* Type returned by [with_process]
* [with_process ?env ?timeout ?stdout ?stderr cmd attrs] is the result of the
execution of the program described by [cmd]. This can either be a successful
execution, or an error.
* A process can enable or disable all the event groups that are attached to it
using the prctl(2) PR_TASK_PERF_EVENTS_ENABLE and
PR_TASK_PERF_EVENTS_DISABLE operations. This applies to all counters on the
calling process, whether created by this process or by another, and does not
affect any counters that this process has created on other processes. It
enables or disables only the group leaders, not any other members in the
groups. | module Attr : sig
type flag =
module Kind : sig
type t =
| Cycles
| Instructions
| Cache_references
| Cache_misses
| Branch_instructions
| Branch_misses
| Bus_cycles
| Stalled_cycles_frontend
| Stalled_cycles_backend
| Ref_cpu_cycles
| Cpu_clock
| Task_clock
| Page_faults
| Context_switches
| Cpu_migrations
| Page_faults_min
| Page_faults_maj
| Alignment_faults
| Emulation_faults
| Dummy
val to_string : t -> string
val of_string : string -> t
end
type t
val make : ?flags:flag list -> Kind.t -> t
val compare : t -> t -> int
end
module KindMap : Map.S with type key = Attr.Kind.t
type flag =
| Fd_cloexec
* ( since Linux 3.14 ) . This flag enables the close - on - exec flag for the
created event file descriptor , so that the file descriptor is
automatically closed on execve(2 ) . Setting the close - on - exec flags at
creation time , rather than later with fcntl(2 ) , avoids potential race
conditions where the calling thread invokes perf_event_open ( ) and
fcntl(2 ) at the same time as another thread calls fork(2 ) then
execve(2 ) .
created event file descriptor, so that the file descriptor is
automatically closed on execve(2). Setting the close-on-exec flags at
creation time, rather than later with fcntl(2), avoids potential race
conditions where the calling thread invokes perf_event_open() and
fcntl(2) at the same time as another thread calls fork(2) then
execve(2). *)
| Fd_no_group
| Fd_output
| Pid_cgroup
* This flag activates per - container system - wide monitoring . A container
is an abstraction that isolates a set of resources for finer - grained
control ( CPUs , memory , etc . ) . In this mode , the event is measured only
if the thread running on the monitored CPU belongs to the designated
container ( cgroup ) . The cgroup is identified by passing a file
descriptor opened on its directory in the filesystem . For
instance , if the cgroup to monitor is called test , then a file
descriptor opened on /dev / cgroup / test ( assuming is mounted on
/dev / cgroup ) must be passed as the pid parameter . monitoring is
available only for system - wide events and may therefore require extra
permissions .
is an abstraction that isolates a set of resources for finer-grained
control (CPUs, memory, etc.). In this mode, the event is measured only
if the thread running on the monitored CPU belongs to the designated
container (cgroup). The cgroup is identified by passing a file
descriptor opened on its directory in the cgroupfs filesystem. For
instance, if the cgroup to monitor is called test, then a file
descriptor opened on /dev/cgroup/test (assuming cgroupfs is mounted on
/dev/cgroup) must be passed as the pid parameter. cgroup monitoring is
available only for system-wide events and may therefore require extra
permissions. *)
type t
* Opaque type of an event counter ( internally [ t ] is a file descriptor ) . Each
file descriptor corresponds to one event that is measured ; these can be
grouped together to measure multiple events simultaneously .
file descriptor corresponds to one event that is measured; these can be
grouped together to measure multiple events simultaneously. *)
val make : ?pid:int -> ?cpu:int -> ?group:t -> ?flags:flag list -> Attr.t -> t
* [ make ~pid ~cpu ? group ? flags attr ] is a perf event counter . Refer to
perf_event_open(2 ) for the description of the arguments . One counter only
counts one kind of attribute at a time . If you want to simultanously count
different metrics ( like the perf stat tool does ) , you have to setup several
counters .
perf_event_open(2) for the description of the arguments. One counter only
counts one kind of attribute at a time. If you want to simultanously count
different metrics (like the perf stat tool does), you have to setup several
counters. *)
val kind : t -> Attr.Kind.t
val read : t -> int64
val reset : t -> unit
* [ reset c ] sets [ c ] to zero .
val enable : t -> unit
val disable : t -> unit
val close : t -> unit
type execution = private
{ process_status : Unix.process_status
; stdout : string
; stderr : string
; data : Int64.t KindMap.t
}
val with_process :
?env:string list
-> ?timeout:int
-> ?stdout:string
-> ?stderr:string
-> string list
-> Attr.t list
-> [ `Ok of execution | `Timeout | `Exn of exn ]
val enable_all : unit -> unit
val disable_all : unit -> unit
|
9647cb644cc2525122292245ffc205177abd13ee9058f3ab82e8e49915a1b7ef | samrushing/irken-compiler | dns.scm | ;; -*- Mode: Irken -*-
(require "lib/basis.scm")
(require "lib/pack.scm")
(require "lib/codecs/base64.scm")
(require "doom/doom.scm")
;; for now, we are only including types, opcodes, and rcodes
;; that are actually used.
;; I think these can be done with `make-enum`.
(datatype dnstype
(:a) ;; a host address [RFC1035]
(:ns) ;; an authoritative name server [RFC1035]
(:cname) ;; the canonical name for an alias [RFC1035]
(:soa) ;; marks the start of a zone of authority [RFC1035]
(:ptr) ;; a domain name pointer [RFC1035]
(:mx) ;; mail exchange [RFC1035]
(:txt) ;; text strings [RFC1035]
(:aaaa) ;; IP6 Address [Thomson]
(:srv) ;; Server Selection [RFC2782]
(:dnskey) ;; DNSSEC Key [RFC4034]
(:rrsig) ;; DNSSEC RRSIG [RFC4034]
(:any) ;; A request for all records [RFC1035]
(:other int) ;; all other types.
)
(define (DNST t name val) {name=name t=t val=val})
(define dnstype-table
(list
(DNST (dnstype:a) "a" 1)
(DNST (dnstype:ns) "ns" 2)
(DNST (dnstype:cname) "cname" 5)
(DNST (dnstype:soa) "soa" 6)
(DNST (dnstype:ptr) "ptr" 12)
(DNST (dnstype:mx) "mx" 15)
(DNST (dnstype:txt) "txt" 16)
(DNST (dnstype:aaaa) "aaaa" 28)
(DNST (dnstype:srv) "srv" 33)
(DNST (dnstype:dnskey) "dnskey" 48)
(DNST (dnstype:rrsig) "rrsig" 46)
(DNST (dnstype:any) "any" 255)
))
(define (int->dnstype n)
(let/cc return
(for-list item dnstype-table
(if (= item.val n)
(return item.t)))
(dnstype:other n)))
(define (dnstype->int t)
(let/cc return
(for-list item dnstype-table
(if (eq? item.t t)
(return item.val)))
(match t with
(dnstype:other n) -> n
_ -> (impossible)
)))
(define (name->dnstype name)
(let/cc return
(for-list item dnstype-table
(if (string=? item.name name)
(return item.t)))
(raise (:DNSUnknownType name))))
no need for a ' class ' afaik see , " there is only one ! " .
(define dnsclass-in 1)
only one opcode in real use , QUERY : = 0
(define dnsopcode-query 0)
(datatype dnsrcode
(:NoError)
(:ServFail)
(:NXDomain)
)
(define int->dnsrcode
(alist/make
(0 (dnsrcode:NoError))
(2 (dnsrcode:ServFail))
(3 (dnsrcode:NXDomain))
))
(define dnsrcode->int (alist/inverse int->dnsrcode))
(define (dnsheader-make)
{qid=0 qr=0 opcode=0 aa=0 tc=0 rd=0 ra=0 z=0 rcode=0
qdcount=0 ancount=0 nscount=0 arcount=0})
(define (dnsheader-repr r)
(format "<head qid=" (int r.qid) " qr=" (int r.qr) " op=" (int r.opcode)
" aa=" (int r.aa) " tc=" (int r.tc) " rd=" (int r.rd) " ra=" (int r.ra)
" z=" (int r.z) " rcode=" (int r.rcode)
" qd=" (int r.qdcount) " an=" (int r.ancount) " ns=" (int r.nscount)
" ar=" (int r.arcount) ">"))
(define (add-header p h)
(p::u16 h.qid)
(p::u16
(packbits
(4 h.rcode)
(3 0)
(1 h.ra)
(1 h.rd)
(1 h.tc)
(1 h.aa)
(4 h.opcode)
(1 h.qr)))
(p::u16 h.qdcount)
(p::u16 h.ancount)
(p::u16 h.nscount)
(p::u16 h.arcount)
)
(define (build-question qid name qtype qclass recursion)
(let ((h (dnsheader-make))
(p (pbuf/make 512))
(nameparts (map-maker magic-cmp)))
(define (pack-name s)
(let loop ((parts (string-split s #\.)))
(match (nameparts::get parts) with
(maybe:yes pos)
-> (p::u16 (logior #xc0 pos))
(maybe:no)
-> (match parts with
() -> (p::u8 0) ;; normal name
("") -> (p::u8 0) ;; name ending in dot
("" . tl) ;; name with empty label
-> (raise (:BadDNSName s))
(label . tl) ;; normal case
-> (let ((len (string-length label)))
(if (> len 63)
(raise (:BadDNSName s))
(begin
;; record this partial name's location
(nameparts::add parts (p::pos))
(p::u8 len)
(p::string label)
(loop tl)))))
)))
(set! h.opcode dnsopcode-query)
(set! h.qid 3141)
(set! h.qdcount 1)
(set! h.rd recursion)
(add-header p h)
(pack-name name)
(p::u16 (dnstype->int qtype))
(p::u16 dnsclass-in)
(p::val)
))
(datatype dnsrr
(:a (vector char))
(:aaaa (vector char))
(:cname string)
(:mx int string)
(:ns string)
(:ptr string)
(:soa string string int int int int int)
(:txt string)
(:srv int int int string)
(:dnskey int int int string)
(:rrsig int int int int int int int string string)
(:other int string)
)
(define dnsrr-repr
(dnsrr:a chars)
-> (format "<a " (join int->string "." (map char->ascii (vector->list chars))) ">")
(dnsrr:aaaa bytes)
-> (format "<aaaa " (join int->hex-string ":" (map char->ascii (vector->list bytes))) ">")
(dnsrr:cname name)
-> (format "<cname " name ">")
(dnsrr:mx pref name)
-> (format "<mx " (int pref) " " name ">")
(dnsrr:ns name)
-> (format "<ns " name ">")
(dnsrr:ptr name)
-> (format "<ptr " name ">")
(dnsrr:soa mname rname serial refresh retry expire minimum)
-> (format "<soa " mname " " rname " serial=" (int serial) " refresh=" (int refresh)
" retry=" (int retry) " expire=" (int expire) " min=" (int minimum) ">")
(dnsrr:txt data)
-> (format "<txt " (string data) ">")
(dnsrr:srv priority weight port target)
-> (format "<srv pri=" (int priority) " weight= " (int weight)
" port=" (int port) " target=" target ">")
(dnsrr:dnskey flags proto algo key)
-> (format "<dnskeky flags=#x" (hex flags) " proto=" (int proto) " algo=" (int algo)
" key=" (base64 key) ">")
(dnsrr:rrsig type algo labels ttl expire incept keytag name sig)
-> (format "<rrsig type=" (int type) " algo=" (int algo) " labels=" (int labels)
" ttl=" (int ttl) " exp=" (int expire) " inc=" (int incept)
" tag=" (int keytag) " name=" (string name) " sig=" (base64 sig) ">")
(dnsrr:other type data)
-> (format "<other type=" (int type) " data=" (string data) ">")
)
(define (unpack-reply data)
(let ((u (ubuf/make data))
(h (dnsheader-make))
(qid (u::u16))
(flags (u::u16))
(nameparts (map-maker magic-cmp))
(r {qd='() an='() ns='() ar='()}))
(define (unpack-name* acc)
(let ((pos (u::pos))
(n0 (u::u8))
(n1 (logand n0 #x3f)))
(cond ((= #xc0 (logand n0 #xc0))
;; pointer
(match (nameparts::get (logior (<< n1 8) (u::u8))) with
(maybe:yes parts) -> (append parts acc)
(maybe:no) -> (raise (:BadDNSPacket "bad name pointer" u))))
((= n1 0) acc)
(else
;; normal label
(let ((label (u::string n1))
(r (unpack-name* (list:cons label acc))))
;; tricky: we want to store only the labels that came *after* this point.
(nameparts::add pos (slice r 0 (- (length r) (length acc))))
r)))
))
(define (unpack-name)
(let ((labels (unpack-name* '())))
(string-join (reverse labels) ".")))
(define (decode-rr type len)
(match type with
(dnstype:a)
-> (let ((data (u::string len))
(r (make-vector len #\0)))
(for-range i len
(set! r[i] (string-ref data i)))
(dnsrr:a r))
(dnstype:aaaa)
-> (let ((data (u::string len))
(r (make-vector len #\0)))
(for-range i len
(set! r[i] (string-ref data i)))
(dnsrr:aaaa r))
(dnstype:mx)
-> (let ((pref (u::u16))
(name (unpack-name)))
(dnsrr:mx pref name))
(dnstype:soa)
-> (let ((mname (unpack-name))
(rname (unpack-name))
(serial (u::u32))
(refresh (u::u32))
(retry (u::u32))
(expire (u::u32))
(minimum (u::u32)))
(dnsrr:soa mname rname serial refresh retry expire minimum))
;; fun note: this wire format is actually not in the rfc.
(dnstype:srv)
-> (let ((priority (u::u16))
(weight (u::u16))
(port (u::u16))
(target (unpack-name)))
(dnsrr:srv priority weight port target))
(dnstype:dnskey)
-> (let ((flags (u::u16))
(proto (u::u8))
(algo (u::u8)))
(dnsrr:dnskey flags proto algo (u::string (- len 4))))
(dnstype:rrsig)
-> (let ((pos0 (u::pos))
(type (u::u16))
(algo (u::u8))
(labels (u::u8))
(ttl (u::u32))
(exp (u::u32))
(inc (u::u32))
(tag (u::u16))
(name (unpack-name))
(pos1 (u::pos)))
(dnsrr:rrsig type algo labels ttl exp inc tag name
(u::string (- len (- pos1 pos0)))))
(dnstype:ns) -> (dnsrr:ns (unpack-name))
(dnstype:cname) -> (dnsrr:cname (unpack-name))
(dnstype:ptr) -> (dnsrr:ptr (unpack-name))
(dnstype:txt) -> (dnsrr:txt (u::string len))
(dnstype:other x) -> (dnsrr:other x (u::string len))
;; this should not happen
(dnstype:any) -> (dnsrr:other 255 (u::string len))
))
(define (unpack-rr)
(let ((name (unpack-name))
(type (int->dnstype (u::u16)))
(class (u::u16)) ;; XXX verify as `IN`
(ttl (u::u32))
(rdlength (u::u16)))
{name=name type=type class=class ttl=ttl
data=(decode-rr type rdlength)}
))
(define (unpack-question)
(let ((name (unpack-name))
(qtype (u::u16))
(qclass (u::u16)))
{name=name qtype=qtype qclass=qclass}))
(unpackbits
flags
(4 h.rcode)
(3 h.z)
(1 h.ra)
(1 h.rd)
(1 h.tc)
(1 h.aa)
(4 h.opcode)
(1 h.qr))
(set! h.qdcount (u::u16))
(set! h.ancount (u::u16))
(set! h.nscount (u::u16))
(set! h.arcount (u::u16))
(when (= h.tc 1)
(printf "reply truncated\n")
(raise (:DNSTruncated)))
(printf "header: " (dnsheader-repr h) "\n")
(for-range i h.qdcount (push! r.qd (unpack-question)))
(for-range i h.ancount (push! r.an (unpack-rr)))
(for-range i h.nscount (push! r.ns (unpack-rr)))
(for-range i h.arcount (push! r.ar (unpack-rr)))
(:tuple h r)
))
(define rr-repr
{name=name type=type class=class ttl=ttl data=rr}
-> (format "(" name " ttl=" (int ttl) " " (dnsrr-repr rr) ")"))
(define print-reply
(:tuple h r)
-> (begin
(printf "reply: {\n")
(printf " " (dnsheader-repr h) "\n")
(for-list item r.qd
(printf " Q " item.name " qtype=" (int item.qtype) " qclass=" (int item.qclass) "\n"))
(for-list item r.an (printf " AN " (rr-repr item) "\n"))
(for-list item r.ns (printf " NS " (rr-repr item) "\n"))
(for-list item r.ar (printf " AR " (rr-repr item) "\n"))
(printf "}\n")
))
(define (tcp-enc-size-prefix len)
(list->string
(list (ascii->char (>> len 8))
(ascii->char (logand #xff len)))))
(define (tcp-dec-size-prefix s)
(logior
(<< (char->ascii (string-ref s 0)) 8)
(char->ascii (string-ref s 1))))
(define (go ip name)
(let ((sock (doom/make (udp4-sock) 1024 1024))
(addr (address/make4 ip 53))
(packet (build-question 3141 name (dnstype:any) dnsclass-in 1)))
(try
(begin
(sock.connect addr)
(sock.send packet)
(let ((reply (sock.recv))
(unpacked (unpack-reply reply)))
(print-reply unpacked)
(sock.close)))
except
(:DNSTruncated)
-> (begin
(printf "trying tcp...\n")
(sock.close)
(set! sock (doom/make (tcp4-sock) 8192 1024))
(sock.connect addr)
(sock.send (string-append (tcp-enc-size-prefix (string-length packet)) packet))
(let ((size (tcp-dec-size-prefix (sock.recv-exact 2)))
(_ (printf "tcp reply size = " (int size) "\n"))
(reply (sock.recv-exact size))
(unpacked (unpack-reply reply)))
(print-reply unpacked)
(sock.close))
)
)))
(poller/fork (lambda () (go "10.0.0.1" sys.argv[1])))
(poller/wait-and-schedule)
| null | https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/doom/dns.scm | scheme | -*- Mode: Irken -*-
for now, we are only including types, opcodes, and rcodes
that are actually used.
I think these can be done with `make-enum`.
a host address [RFC1035]
an authoritative name server [RFC1035]
the canonical name for an alias [RFC1035]
marks the start of a zone of authority [RFC1035]
a domain name pointer [RFC1035]
mail exchange [RFC1035]
text strings [RFC1035]
IP6 Address [Thomson]
Server Selection [RFC2782]
DNSSEC Key [RFC4034]
DNSSEC RRSIG [RFC4034]
A request for all records [RFC1035]
all other types.
normal name
name ending in dot
name with empty label
normal case
record this partial name's location
pointer
normal label
tricky: we want to store only the labels that came *after* this point.
fun note: this wire format is actually not in the rfc.
this should not happen
XXX verify as `IN` |
(require "lib/basis.scm")
(require "lib/pack.scm")
(require "lib/codecs/base64.scm")
(require "doom/doom.scm")
(datatype dnstype
)
(define (DNST t name val) {name=name t=t val=val})
(define dnstype-table
(list
(DNST (dnstype:a) "a" 1)
(DNST (dnstype:ns) "ns" 2)
(DNST (dnstype:cname) "cname" 5)
(DNST (dnstype:soa) "soa" 6)
(DNST (dnstype:ptr) "ptr" 12)
(DNST (dnstype:mx) "mx" 15)
(DNST (dnstype:txt) "txt" 16)
(DNST (dnstype:aaaa) "aaaa" 28)
(DNST (dnstype:srv) "srv" 33)
(DNST (dnstype:dnskey) "dnskey" 48)
(DNST (dnstype:rrsig) "rrsig" 46)
(DNST (dnstype:any) "any" 255)
))
(define (int->dnstype n)
(let/cc return
(for-list item dnstype-table
(if (= item.val n)
(return item.t)))
(dnstype:other n)))
(define (dnstype->int t)
(let/cc return
(for-list item dnstype-table
(if (eq? item.t t)
(return item.val)))
(match t with
(dnstype:other n) -> n
_ -> (impossible)
)))
(define (name->dnstype name)
(let/cc return
(for-list item dnstype-table
(if (string=? item.name name)
(return item.t)))
(raise (:DNSUnknownType name))))
no need for a ' class ' afaik see , " there is only one ! " .
(define dnsclass-in 1)
only one opcode in real use , QUERY : = 0
(define dnsopcode-query 0)
(datatype dnsrcode
(:NoError)
(:ServFail)
(:NXDomain)
)
(define int->dnsrcode
(alist/make
(0 (dnsrcode:NoError))
(2 (dnsrcode:ServFail))
(3 (dnsrcode:NXDomain))
))
(define dnsrcode->int (alist/inverse int->dnsrcode))
(define (dnsheader-make)
{qid=0 qr=0 opcode=0 aa=0 tc=0 rd=0 ra=0 z=0 rcode=0
qdcount=0 ancount=0 nscount=0 arcount=0})
(define (dnsheader-repr r)
(format "<head qid=" (int r.qid) " qr=" (int r.qr) " op=" (int r.opcode)
" aa=" (int r.aa) " tc=" (int r.tc) " rd=" (int r.rd) " ra=" (int r.ra)
" z=" (int r.z) " rcode=" (int r.rcode)
" qd=" (int r.qdcount) " an=" (int r.ancount) " ns=" (int r.nscount)
" ar=" (int r.arcount) ">"))
(define (add-header p h)
(p::u16 h.qid)
(p::u16
(packbits
(4 h.rcode)
(3 0)
(1 h.ra)
(1 h.rd)
(1 h.tc)
(1 h.aa)
(4 h.opcode)
(1 h.qr)))
(p::u16 h.qdcount)
(p::u16 h.ancount)
(p::u16 h.nscount)
(p::u16 h.arcount)
)
(define (build-question qid name qtype qclass recursion)
(let ((h (dnsheader-make))
(p (pbuf/make 512))
(nameparts (map-maker magic-cmp)))
(define (pack-name s)
(let loop ((parts (string-split s #\.)))
(match (nameparts::get parts) with
(maybe:yes pos)
-> (p::u16 (logior #xc0 pos))
(maybe:no)
-> (match parts with
-> (raise (:BadDNSName s))
-> (let ((len (string-length label)))
(if (> len 63)
(raise (:BadDNSName s))
(begin
(nameparts::add parts (p::pos))
(p::u8 len)
(p::string label)
(loop tl)))))
)))
(set! h.opcode dnsopcode-query)
(set! h.qid 3141)
(set! h.qdcount 1)
(set! h.rd recursion)
(add-header p h)
(pack-name name)
(p::u16 (dnstype->int qtype))
(p::u16 dnsclass-in)
(p::val)
))
(datatype dnsrr
(:a (vector char))
(:aaaa (vector char))
(:cname string)
(:mx int string)
(:ns string)
(:ptr string)
(:soa string string int int int int int)
(:txt string)
(:srv int int int string)
(:dnskey int int int string)
(:rrsig int int int int int int int string string)
(:other int string)
)
(define dnsrr-repr
(dnsrr:a chars)
-> (format "<a " (join int->string "." (map char->ascii (vector->list chars))) ">")
(dnsrr:aaaa bytes)
-> (format "<aaaa " (join int->hex-string ":" (map char->ascii (vector->list bytes))) ">")
(dnsrr:cname name)
-> (format "<cname " name ">")
(dnsrr:mx pref name)
-> (format "<mx " (int pref) " " name ">")
(dnsrr:ns name)
-> (format "<ns " name ">")
(dnsrr:ptr name)
-> (format "<ptr " name ">")
(dnsrr:soa mname rname serial refresh retry expire minimum)
-> (format "<soa " mname " " rname " serial=" (int serial) " refresh=" (int refresh)
" retry=" (int retry) " expire=" (int expire) " min=" (int minimum) ">")
(dnsrr:txt data)
-> (format "<txt " (string data) ">")
(dnsrr:srv priority weight port target)
-> (format "<srv pri=" (int priority) " weight= " (int weight)
" port=" (int port) " target=" target ">")
(dnsrr:dnskey flags proto algo key)
-> (format "<dnskeky flags=#x" (hex flags) " proto=" (int proto) " algo=" (int algo)
" key=" (base64 key) ">")
(dnsrr:rrsig type algo labels ttl expire incept keytag name sig)
-> (format "<rrsig type=" (int type) " algo=" (int algo) " labels=" (int labels)
" ttl=" (int ttl) " exp=" (int expire) " inc=" (int incept)
" tag=" (int keytag) " name=" (string name) " sig=" (base64 sig) ">")
(dnsrr:other type data)
-> (format "<other type=" (int type) " data=" (string data) ">")
)
(define (unpack-reply data)
(let ((u (ubuf/make data))
(h (dnsheader-make))
(qid (u::u16))
(flags (u::u16))
(nameparts (map-maker magic-cmp))
(r {qd='() an='() ns='() ar='()}))
(define (unpack-name* acc)
(let ((pos (u::pos))
(n0 (u::u8))
(n1 (logand n0 #x3f)))
(cond ((= #xc0 (logand n0 #xc0))
(match (nameparts::get (logior (<< n1 8) (u::u8))) with
(maybe:yes parts) -> (append parts acc)
(maybe:no) -> (raise (:BadDNSPacket "bad name pointer" u))))
((= n1 0) acc)
(else
(let ((label (u::string n1))
(r (unpack-name* (list:cons label acc))))
(nameparts::add pos (slice r 0 (- (length r) (length acc))))
r)))
))
(define (unpack-name)
(let ((labels (unpack-name* '())))
(string-join (reverse labels) ".")))
(define (decode-rr type len)
(match type with
(dnstype:a)
-> (let ((data (u::string len))
(r (make-vector len #\0)))
(for-range i len
(set! r[i] (string-ref data i)))
(dnsrr:a r))
(dnstype:aaaa)
-> (let ((data (u::string len))
(r (make-vector len #\0)))
(for-range i len
(set! r[i] (string-ref data i)))
(dnsrr:aaaa r))
(dnstype:mx)
-> (let ((pref (u::u16))
(name (unpack-name)))
(dnsrr:mx pref name))
(dnstype:soa)
-> (let ((mname (unpack-name))
(rname (unpack-name))
(serial (u::u32))
(refresh (u::u32))
(retry (u::u32))
(expire (u::u32))
(minimum (u::u32)))
(dnsrr:soa mname rname serial refresh retry expire minimum))
(dnstype:srv)
-> (let ((priority (u::u16))
(weight (u::u16))
(port (u::u16))
(target (unpack-name)))
(dnsrr:srv priority weight port target))
(dnstype:dnskey)
-> (let ((flags (u::u16))
(proto (u::u8))
(algo (u::u8)))
(dnsrr:dnskey flags proto algo (u::string (- len 4))))
(dnstype:rrsig)
-> (let ((pos0 (u::pos))
(type (u::u16))
(algo (u::u8))
(labels (u::u8))
(ttl (u::u32))
(exp (u::u32))
(inc (u::u32))
(tag (u::u16))
(name (unpack-name))
(pos1 (u::pos)))
(dnsrr:rrsig type algo labels ttl exp inc tag name
(u::string (- len (- pos1 pos0)))))
(dnstype:ns) -> (dnsrr:ns (unpack-name))
(dnstype:cname) -> (dnsrr:cname (unpack-name))
(dnstype:ptr) -> (dnsrr:ptr (unpack-name))
(dnstype:txt) -> (dnsrr:txt (u::string len))
(dnstype:other x) -> (dnsrr:other x (u::string len))
(dnstype:any) -> (dnsrr:other 255 (u::string len))
))
(define (unpack-rr)
(let ((name (unpack-name))
(type (int->dnstype (u::u16)))
(ttl (u::u32))
(rdlength (u::u16)))
{name=name type=type class=class ttl=ttl
data=(decode-rr type rdlength)}
))
(define (unpack-question)
(let ((name (unpack-name))
(qtype (u::u16))
(qclass (u::u16)))
{name=name qtype=qtype qclass=qclass}))
(unpackbits
flags
(4 h.rcode)
(3 h.z)
(1 h.ra)
(1 h.rd)
(1 h.tc)
(1 h.aa)
(4 h.opcode)
(1 h.qr))
(set! h.qdcount (u::u16))
(set! h.ancount (u::u16))
(set! h.nscount (u::u16))
(set! h.arcount (u::u16))
(when (= h.tc 1)
(printf "reply truncated\n")
(raise (:DNSTruncated)))
(printf "header: " (dnsheader-repr h) "\n")
(for-range i h.qdcount (push! r.qd (unpack-question)))
(for-range i h.ancount (push! r.an (unpack-rr)))
(for-range i h.nscount (push! r.ns (unpack-rr)))
(for-range i h.arcount (push! r.ar (unpack-rr)))
(:tuple h r)
))
(define rr-repr
{name=name type=type class=class ttl=ttl data=rr}
-> (format "(" name " ttl=" (int ttl) " " (dnsrr-repr rr) ")"))
(define print-reply
(:tuple h r)
-> (begin
(printf "reply: {\n")
(printf " " (dnsheader-repr h) "\n")
(for-list item r.qd
(printf " Q " item.name " qtype=" (int item.qtype) " qclass=" (int item.qclass) "\n"))
(for-list item r.an (printf " AN " (rr-repr item) "\n"))
(for-list item r.ns (printf " NS " (rr-repr item) "\n"))
(for-list item r.ar (printf " AR " (rr-repr item) "\n"))
(printf "}\n")
))
(define (tcp-enc-size-prefix len)
(list->string
(list (ascii->char (>> len 8))
(ascii->char (logand #xff len)))))
(define (tcp-dec-size-prefix s)
(logior
(<< (char->ascii (string-ref s 0)) 8)
(char->ascii (string-ref s 1))))
(define (go ip name)
(let ((sock (doom/make (udp4-sock) 1024 1024))
(addr (address/make4 ip 53))
(packet (build-question 3141 name (dnstype:any) dnsclass-in 1)))
(try
(begin
(sock.connect addr)
(sock.send packet)
(let ((reply (sock.recv))
(unpacked (unpack-reply reply)))
(print-reply unpacked)
(sock.close)))
except
(:DNSTruncated)
-> (begin
(printf "trying tcp...\n")
(sock.close)
(set! sock (doom/make (tcp4-sock) 8192 1024))
(sock.connect addr)
(sock.send (string-append (tcp-enc-size-prefix (string-length packet)) packet))
(let ((size (tcp-dec-size-prefix (sock.recv-exact 2)))
(_ (printf "tcp reply size = " (int size) "\n"))
(reply (sock.recv-exact size))
(unpacked (unpack-reply reply)))
(print-reply unpacked)
(sock.close))
)
)))
(poller/fork (lambda () (go "10.0.0.1" sys.argv[1])))
(poller/wait-and-schedule)
|
b373239cf9d5a549a32758b99ec2fd2bb7eeb785efccc5905bcefdbf4786f9ab | caisah/sicp-exercises-and-examples | ex_2.64.scm | The following procedure list->tree converts an ordered list to a balanced bianry tree .
the helper procedure partial - tree takes as arguments an integer n and list of at least
n elements and constructs a balanced tree containing the first n elements of the list .
;; The result returned by partial-tree is a pair (formed with cons) whose car is the
;; constructed tree and whose cdr is the list of elements not included in the tree.
(define (list->tree elements)
(car (partial-tree elements (length elements))))
(define (partial-tree elts n)
(if (= n 0)
(cons '() elts)
(let ((left-size (quotient (- n 1) 2)))
(let ((left-result (partial-tree elts left-size)))
(let ((left-tree (car left-result))
(non-left-elts (cdr left-result))
(right-size (- n (+ left-size 1))))
(let ((this-entry (car non-left-elts))
(right-result (partial-tree
(cdr non-left-elts)
right-size)))
(let ((right-tree (car right-result))
(remaining-elts (cdr right-result)))
(cons (make-tree
this-entry left-tree right-tree)
remaining-elts))))))))
(list->tree (list 1 3 5 7 9 11))
a. Draw the tree produced by list->tree for the list ( 1 3 5 7 9 11 )
5
;; / \
1 9
;; \ / \
3 7 11
b. What is the order of growth in the number of steps required by list->tree to convert
;; a list of n elements?
;; O(n)
| null | https://raw.githubusercontent.com/caisah/sicp-exercises-and-examples/605c698d7495aa3474c2b6edcd1312cb16c5b5cb/2.3.3-representing_sets/ex_2.64.scm | scheme | The result returned by partial-tree is a pair (formed with cons) whose car is the
constructed tree and whose cdr is the list of elements not included in the tree.
/ \
\ / \
a list of n elements?
O(n) | The following procedure list->tree converts an ordered list to a balanced bianry tree .
the helper procedure partial - tree takes as arguments an integer n and list of at least
n elements and constructs a balanced tree containing the first n elements of the list .
(define (list->tree elements)
(car (partial-tree elements (length elements))))
(define (partial-tree elts n)
(if (= n 0)
(cons '() elts)
(let ((left-size (quotient (- n 1) 2)))
(let ((left-result (partial-tree elts left-size)))
(let ((left-tree (car left-result))
(non-left-elts (cdr left-result))
(right-size (- n (+ left-size 1))))
(let ((this-entry (car non-left-elts))
(right-result (partial-tree
(cdr non-left-elts)
right-size)))
(let ((right-tree (car right-result))
(remaining-elts (cdr right-result)))
(cons (make-tree
this-entry left-tree right-tree)
remaining-elts))))))))
(list->tree (list 1 3 5 7 9 11))
a. Draw the tree produced by list->tree for the list ( 1 3 5 7 9 11 )
5
1 9
3 7 11
b. What is the order of growth in the number of steps required by list->tree to convert
|
841787d99bb58e45af25e9e1258637c4fe84f620d15979812cdb90a43d1dae60 | GaloisInc/saw-core | Constant.hs | |
Module : Verifier . SAW.Constant
Copyright : Galois , Inc. 2012 - 2015
License : :
Stability : experimental
Portability : non - portable ( language extensions )
Module : Verifier.SAW.Constant
Copyright : Galois, Inc. 2012-2015
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable (language extensions)
-}
module Verifier.SAW.Constant (scConst) where
import Verifier.SAW.SharedTerm
import Verifier.SAW.Rewriter
import Verifier.SAW.Conversion
scConst :: SharedContext -> String -> Term -> IO Term
scConst sc name t = do
ty <- scTypeOf sc t
ty' <- rewriteSharedTerm sc (addConvs natConversions emptySimpset) ty
scConstant sc name t ty'
| null | https://raw.githubusercontent.com/GaloisInc/saw-core/ea914a9eea8e484189ee6e4c4dcdfc7db831d987/saw-core/src/Verifier/SAW/Constant.hs | haskell | |
Module : Verifier . SAW.Constant
Copyright : Galois , Inc. 2012 - 2015
License : :
Stability : experimental
Portability : non - portable ( language extensions )
Module : Verifier.SAW.Constant
Copyright : Galois, Inc. 2012-2015
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable (language extensions)
-}
module Verifier.SAW.Constant (scConst) where
import Verifier.SAW.SharedTerm
import Verifier.SAW.Rewriter
import Verifier.SAW.Conversion
scConst :: SharedContext -> String -> Term -> IO Term
scConst sc name t = do
ty <- scTypeOf sc t
ty' <- rewriteSharedTerm sc (addConvs natConversions emptySimpset) ty
scConstant sc name t ty'
| |
63edcadf8c5b34349a0da70cf58ba399c5cd3f333c09f36bc9e24a98fc1c7cac | avsm/mirage-duniverse | grep2.ml | open StdLabels
let underline_on = Format.sprintf "%c[4m" (Char.chr 27)
let underline_off = Format.sprintf "%c[24m" (Char.chr 27)
let usage = Format.sprintf "%s [options] pattern" (Array.get Sys.argv 0)
let pattern = ref ""
let rewrite = ref "\\0"
let underline = ref false
let only_matching = ref false
let str_sub = ref ""
(* this is just drudgery *)
let () =
Arg.parse [
"--underline", Arg.Set underline, "underline rewrites";
"--rewrite", Arg.Set_string rewrite, "rewrite the match";
"--only-matching", Arg.Set only_matching, "only print the match, not the line";
"--extract-submatch", Arg.Set_string str_sub,
"ignored unless --only-matching is also passed; whole match is submatch 0";
]
(fun pattern' -> pattern := pattern')
usage
;;
this is the only interesting ( i.e. , Re2 - using ) part
let () =
if !underline then
let re = Re2.create_exn "\\\\[0-9]" in
let template = Format.sprintf "%c[4m\\0%c[24m" (Char.chr 27) (Char.chr 27) in
match (Re2.rewrite re ~template !rewrite) with
| Core_kernel.Result.Ok s -> rewrite := s
| Core_kernel.Result.Error _ -> ()
;;
let re =
if !pattern = ""
then raise (Failure (Format.sprintf "invalid pattern /%s/" !pattern))
else begin
try
Re2.create_exn !pattern
with
| _ ->
raise (Failure (Format.sprintf "invalid pattern /%s/" !pattern))
end
;;
let sub =
if !str_sub = "" then `Index 0
else let id = try `Index (int_of_string !str_sub) with _ -> `Name !str_sub in
`Index (Re2.index_of_id_exn re id)
;;
let grep str =
try
if not (Re2.matches re str) then None else
let str = if not !only_matching then str else Re2.find_first_exn ~sub re str in
Some (Re2.rewrite re ~template:(!rewrite) str)
with
| err -> raise err
;;
(* okay, more drudgery *)
let _ =
let rec iter ~unfold ~fold ~init seed =
match unfold seed with
| None -> init
| Some (x, seed) -> iter ~unfold ~fold ~init:(fold init x) seed
in
iter
~unfold:(fun channel ->
match
try grep (input_line channel) with
| End_of_file -> None
| err -> raise err
with
| None -> None
| Some r -> Some (r, channel))
~fold:(fun channel str_result ->
match str_result with
| Core_kernel.Result.Error _ -> channel
| Core_kernel.Result.Ok str -> output_string channel (str ^ "\n") ; channel)
~init:stdout
stdin
;;
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/re2/example/grep2.ml | ocaml | this is just drudgery
okay, more drudgery | open StdLabels
let underline_on = Format.sprintf "%c[4m" (Char.chr 27)
let underline_off = Format.sprintf "%c[24m" (Char.chr 27)
let usage = Format.sprintf "%s [options] pattern" (Array.get Sys.argv 0)
let pattern = ref ""
let rewrite = ref "\\0"
let underline = ref false
let only_matching = ref false
let str_sub = ref ""
let () =
Arg.parse [
"--underline", Arg.Set underline, "underline rewrites";
"--rewrite", Arg.Set_string rewrite, "rewrite the match";
"--only-matching", Arg.Set only_matching, "only print the match, not the line";
"--extract-submatch", Arg.Set_string str_sub,
"ignored unless --only-matching is also passed; whole match is submatch 0";
]
(fun pattern' -> pattern := pattern')
usage
;;
this is the only interesting ( i.e. , Re2 - using ) part
let () =
if !underline then
let re = Re2.create_exn "\\\\[0-9]" in
let template = Format.sprintf "%c[4m\\0%c[24m" (Char.chr 27) (Char.chr 27) in
match (Re2.rewrite re ~template !rewrite) with
| Core_kernel.Result.Ok s -> rewrite := s
| Core_kernel.Result.Error _ -> ()
;;
let re =
if !pattern = ""
then raise (Failure (Format.sprintf "invalid pattern /%s/" !pattern))
else begin
try
Re2.create_exn !pattern
with
| _ ->
raise (Failure (Format.sprintf "invalid pattern /%s/" !pattern))
end
;;
let sub =
if !str_sub = "" then `Index 0
else let id = try `Index (int_of_string !str_sub) with _ -> `Name !str_sub in
`Index (Re2.index_of_id_exn re id)
;;
let grep str =
try
if not (Re2.matches re str) then None else
let str = if not !only_matching then str else Re2.find_first_exn ~sub re str in
Some (Re2.rewrite re ~template:(!rewrite) str)
with
| err -> raise err
;;
let _ =
let rec iter ~unfold ~fold ~init seed =
match unfold seed with
| None -> init
| Some (x, seed) -> iter ~unfold ~fold ~init:(fold init x) seed
in
iter
~unfold:(fun channel ->
match
try grep (input_line channel) with
| End_of_file -> None
| err -> raise err
with
| None -> None
| Some r -> Some (r, channel))
~fold:(fun channel str_result ->
match str_result with
| Core_kernel.Result.Error _ -> channel
| Core_kernel.Result.Ok str -> output_string channel (str ^ "\n") ; channel)
~init:stdout
stdin
;;
|
1305738540558d08b63d3c6d07ae84e51ccaec067fe0b3210c9672aef8ecf945 | flosell/lambdacd | output_test.clj | (ns lambdacd.stepsupport.output-test
(:require [clojure.test :refer :all]
[lambdacd.stepsupport.output :refer :all]
[lambdacd.testsupport.test-util :refer [slurp-chan call-with-timeout]]
[lambdacd.testsupport.data :refer [some-ctx some-ctx-with]]
[lambdacd.testsupport.matchers :refer [map-containing]]
[clojure.core.async :as async]
[lambdacd.testsupport.noop-pipeline-state :as noop-pipeline-state]
[lambdacd.execution.core :as execution]
[lambdacd.stepsupport.killable :as killable]
[lambdacd.stepsupport.chaining :as chaining]))
(defn some-step [args ctx]
{:status :success :foo :bar})
(defn some-other-step [args ctx]
{:status :success :foo :baz})
(defn some-failling-step [args ctx]
{:status :failure})
(defn some-successful-step [args ctx]
{:status :success})
(defn some-step-that-returns-a-value [args ctx]
{:v 42 :status :success})
(defn some-step-returning-a-global [args ctx]
{:global {:g 42} :status :success})
(defn some-step-returning-a-different-global [args ctx]
{:global {:v 21} :status :success})
(defn some-step-returning-a-global-argument-passed-in [args ctx]
{:the-global-arg (:g (:global args)) :status :success})
(defn some-step-returning-an-argument-passed-in [args ctx]
{:status :success :the-arg (:v args)})
(defn some-step-receiving-only-args [args]
{:status :success :the-arg (:v args)})
(defn some-step-receiving-nothing []
{:status :success :no-arg :passed-in})
(defn some-step-returning-the-context-passed-in [args ctx]
{:status :success :the-ctx-1 (:v ctx)})
(defn some-step-receiving-only-ctx [ctx]
{:status :success :the-ctx-1 (:v ctx)})
(defn some-other-step-returning-the-context-passed-in [args ctx]
{:status :success :the-ctx-2 (:v ctx)})
(defn some-step-saying-hello [args ctx]
{:status :success :out "hello"})
(defn some-step-saying-world [args ctx]
{:status :success :out "world"})
(defn some-step-printing-to-intermediate-output [args ctx]
(capture-output ctx
(println "helloworld")
{:status :success}))
(defn some-step-with-additional-arguments [args ctx hello world]
{:status :success :hello hello :world world})
(defn some-step-with-arbitrary-arguments [hello world]
{:status :success :hello hello :world world})
(defn step-that-should-never-be-called [args ctx]
(throw (IllegalStateException. "do not call me!")))
(deftest print-to-output-test
(testing "that it writes to the result-channel with every call and accumulates writes"
(let [result-channel (async/chan 100)
printer (new-printer)
ctx (some-ctx-with :result-channel result-channel)]
(print-to-output ctx printer "Hello")
(print-to-output ctx printer "World")
(is (= [[:out "Hello\n"]
[:out "Hello\nWorld\n"]] (slurp-chan result-channel))))))
(deftest printed-output-test
(testing "that we can get the things we printed before"
(let [printer (new-printer)
ctx (some-ctx)]
(print-to-output ctx printer "Hello")
(print-to-output ctx printer "World")
(is (= "Hello\nWorld\n" (printed-output printer))))))
(defn output-load-test-ctx []
(some-ctx-with :pipeline-state-component (noop-pipeline-state/new-no-op-pipeline-state)))
(defn log-lots-of-output [args ctx]
(doall (for [i (range 800)]
(killable/if-not-killed ctx
(async/>!! (:result-channel ctx) [:xyz i]))))
{:status :success})
(defn log-lots-of-output-in-chaining [args ctx]
(chaining/chaining args ctx
(log-lots-of-output chaining/injected-args chaining/injected-ctx)))
reproduces # 135
(testing "that we don't fail if we come across lots of output for just in general"
(is (= :success (:status (call-with-timeout 10000
(execution/execute-step {} [(output-load-test-ctx) log-lots-of-output]))))))
(testing "that we don't fail if we come across lots of output for chaining"
(is (= :success (:status (call-with-timeout 10000
(execution/execute-step {} [(output-load-test-ctx) log-lots-of-output-in-chaining])))))))
(deftest capture-output-test
(testing "that the original step result is kept"
(is (map-containing {:foo :bar :status :success}
(capture-output (some-ctx)
(some-step nil nil)))))
(testing "we can deal with static output"
(is (map-containing {:foo :bar :status :success}
(capture-output (some-ctx)
{:foo :bar :status :success}))))
(testing "that everything written to stdout is written to the result channel as output"
(let [result-channel (async/chan 100)
ctx (some-ctx-with :result-channel result-channel)]
(capture-output ctx
(println "Hello")
(println "World"))
(is (= [[:out "Hello\n"]
[:out "Hello\nWorld\n"]] (slurp-chan result-channel)))))
(testing "that it returns the accumulated output"
(is (map-containing {:out "Hello\nWorld\n"}
(capture-output (some-ctx)
(println "Hello")
(println "World")
{:status :success}))))
(testing "that a steps :out is appended to the captured output" ; appending was a more or less random decision,
(is (map-containing {:out "Hello\nWorld\n\nFrom Step"}
(capture-output (some-ctx)
(println "Hello")
(println "World")
{:status :success
:out "From Step"}))))
(testing "that hijacking *out* doesn't interfere with other threads"
(let [not-stopped (atom true)]
(async/thread (while @not-stopped
(print " "))
(println))
(is (= "Hello\n" (:out
(capture-output (some-ctx)
(println "Hello")
{:status :success}))))
(reset! not-stopped false)))
(testing "that it can deal with a body that returns nil"
(is (= nil (capture-output (some-ctx)
nil))))
(testing "that it can deal with a body that returns something that is not a map"
(is (= nil (capture-output (some-ctx)
"this is not a map")))))
| null | https://raw.githubusercontent.com/flosell/lambdacd/e9ba3cebb2d5f0070a2e0e1e08fc85fc99ee7135/test/clj/lambdacd/stepsupport/output_test.clj | clojure | appending was a more or less random decision, | (ns lambdacd.stepsupport.output-test
(:require [clojure.test :refer :all]
[lambdacd.stepsupport.output :refer :all]
[lambdacd.testsupport.test-util :refer [slurp-chan call-with-timeout]]
[lambdacd.testsupport.data :refer [some-ctx some-ctx-with]]
[lambdacd.testsupport.matchers :refer [map-containing]]
[clojure.core.async :as async]
[lambdacd.testsupport.noop-pipeline-state :as noop-pipeline-state]
[lambdacd.execution.core :as execution]
[lambdacd.stepsupport.killable :as killable]
[lambdacd.stepsupport.chaining :as chaining]))
(defn some-step [args ctx]
{:status :success :foo :bar})
(defn some-other-step [args ctx]
{:status :success :foo :baz})
(defn some-failling-step [args ctx]
{:status :failure})
(defn some-successful-step [args ctx]
{:status :success})
(defn some-step-that-returns-a-value [args ctx]
{:v 42 :status :success})
(defn some-step-returning-a-global [args ctx]
{:global {:g 42} :status :success})
(defn some-step-returning-a-different-global [args ctx]
{:global {:v 21} :status :success})
(defn some-step-returning-a-global-argument-passed-in [args ctx]
{:the-global-arg (:g (:global args)) :status :success})
(defn some-step-returning-an-argument-passed-in [args ctx]
{:status :success :the-arg (:v args)})
(defn some-step-receiving-only-args [args]
{:status :success :the-arg (:v args)})
(defn some-step-receiving-nothing []
{:status :success :no-arg :passed-in})
(defn some-step-returning-the-context-passed-in [args ctx]
{:status :success :the-ctx-1 (:v ctx)})
(defn some-step-receiving-only-ctx [ctx]
{:status :success :the-ctx-1 (:v ctx)})
(defn some-other-step-returning-the-context-passed-in [args ctx]
{:status :success :the-ctx-2 (:v ctx)})
(defn some-step-saying-hello [args ctx]
{:status :success :out "hello"})
(defn some-step-saying-world [args ctx]
{:status :success :out "world"})
(defn some-step-printing-to-intermediate-output [args ctx]
(capture-output ctx
(println "helloworld")
{:status :success}))
(defn some-step-with-additional-arguments [args ctx hello world]
{:status :success :hello hello :world world})
(defn some-step-with-arbitrary-arguments [hello world]
{:status :success :hello hello :world world})
(defn step-that-should-never-be-called [args ctx]
(throw (IllegalStateException. "do not call me!")))
(deftest print-to-output-test
(testing "that it writes to the result-channel with every call and accumulates writes"
(let [result-channel (async/chan 100)
printer (new-printer)
ctx (some-ctx-with :result-channel result-channel)]
(print-to-output ctx printer "Hello")
(print-to-output ctx printer "World")
(is (= [[:out "Hello\n"]
[:out "Hello\nWorld\n"]] (slurp-chan result-channel))))))
(deftest printed-output-test
(testing "that we can get the things we printed before"
(let [printer (new-printer)
ctx (some-ctx)]
(print-to-output ctx printer "Hello")
(print-to-output ctx printer "World")
(is (= "Hello\nWorld\n" (printed-output printer))))))
(defn output-load-test-ctx []
(some-ctx-with :pipeline-state-component (noop-pipeline-state/new-no-op-pipeline-state)))
(defn log-lots-of-output [args ctx]
(doall (for [i (range 800)]
(killable/if-not-killed ctx
(async/>!! (:result-channel ctx) [:xyz i]))))
{:status :success})
(defn log-lots-of-output-in-chaining [args ctx]
(chaining/chaining args ctx
(log-lots-of-output chaining/injected-args chaining/injected-ctx)))
reproduces # 135
(testing "that we don't fail if we come across lots of output for just in general"
(is (= :success (:status (call-with-timeout 10000
(execution/execute-step {} [(output-load-test-ctx) log-lots-of-output]))))))
(testing "that we don't fail if we come across lots of output for chaining"
(is (= :success (:status (call-with-timeout 10000
(execution/execute-step {} [(output-load-test-ctx) log-lots-of-output-in-chaining])))))))
(deftest capture-output-test
(testing "that the original step result is kept"
(is (map-containing {:foo :bar :status :success}
(capture-output (some-ctx)
(some-step nil nil)))))
(testing "we can deal with static output"
(is (map-containing {:foo :bar :status :success}
(capture-output (some-ctx)
{:foo :bar :status :success}))))
(testing "that everything written to stdout is written to the result channel as output"
(let [result-channel (async/chan 100)
ctx (some-ctx-with :result-channel result-channel)]
(capture-output ctx
(println "Hello")
(println "World"))
(is (= [[:out "Hello\n"]
[:out "Hello\nWorld\n"]] (slurp-chan result-channel)))))
(testing "that it returns the accumulated output"
(is (map-containing {:out "Hello\nWorld\n"}
(capture-output (some-ctx)
(println "Hello")
(println "World")
{:status :success}))))
(is (map-containing {:out "Hello\nWorld\n\nFrom Step"}
(capture-output (some-ctx)
(println "Hello")
(println "World")
{:status :success
:out "From Step"}))))
(testing "that hijacking *out* doesn't interfere with other threads"
(let [not-stopped (atom true)]
(async/thread (while @not-stopped
(print " "))
(println))
(is (= "Hello\n" (:out
(capture-output (some-ctx)
(println "Hello")
{:status :success}))))
(reset! not-stopped false)))
(testing "that it can deal with a body that returns nil"
(is (= nil (capture-output (some-ctx)
nil))))
(testing "that it can deal with a body that returns something that is not a map"
(is (= nil (capture-output (some-ctx)
"this is not a map")))))
|
fd35f19968a8a2ef1ab260d34831d0564552270822ffbb21af6fe1a62e5b51d3 | juxt/jig | todo.clj | Copyright © 2013 , JUXT LTD . 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.
(ns jig.console.todo
(:require
[ring.util.response :as ring-resp]
[clojure.java.io :as io]
[hiccup.core :refer (html h)]
jig
[jig.console :refer (add-extension ->Boilerplate)])
(:import (jig Lifecycle)))
(defn find-todo-lines [f]
(filter :todo
(map
(partial zipmap [:file :line :todo])
(map vector
(repeat (str f))
(map inc (range))
(map #(second (re-find (re-pattern (str \T \O \D \O \: "?\\s*([^\r\n\"]*)")) %))
(line-seq (io/reader f)))))))
(defn extract-snippet [file line]
(apply str
(interpose \newline
(->> file (io/reader) line-seq (drop (- line 5)) (take 10)))))
(defn todo-finder [dir]
(apply concat
(for [f (.listFiles dir)]
(cond
(.isDirectory f) (todo-finder f)
(.isFile f) (find-todo-lines f)))))
(defn todos-page [request]
(ring-resp/response
(html
;; string split so this doesn't end up as a TO-DO
[:h1 (str \T \O \D \O \s)]
[:p (format "Developers sometimes think of things to do while coding which, for whatever reason, isn't possible to do at the time. A common convention is to label the comment with '%s'." (str \T \O \D \O))]
(let [content (for [project (-> request :jig/system :jig/projects)]
(let [paths (->> project :project :source-paths (map (comp (memfn getCanonicalFile) io/file)))
todos (mapcat todo-finder paths)]
(when (pos? (count todos))
[:div
[:h2 (:name project)]
[:p (format "%d remaining %ss" (count todos) (str \T \O \D \O))]
[:ul
(for [{:keys [file line todo]} todos]
[:div
[:h4 [:i todo]]
[:p "File: " file]
[:p "Line: " line]
[:pre (extract-snippet file line)]
])]])))]
(if (empty? content)
[:p (format "There are currently no %s. That's good. But if you add them, they'll appear here."
(str \T \O \D \O \s))]
(list
[:p (format "Here are the %s items that remain in the code-base." (str \T \O \D \O))]
content)))
)))
(deftype JigComponent [config]
Lifecycle
(init [_ system]
(add-extension
system config
:route ["" (->Boilerplate todos-page)]
:menuitems [[(str \T \O \D \O \s) todos-page]]))
(start [_ system] system)
(stop [_ system] system))
| null | https://raw.githubusercontent.com/juxt/jig/3997887e5a56faadb1b48eccecbc7034b3d31e41/console/extensions/todo-browser/src/jig/console/todo.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.
string split so this doesn't end up as a TO-DO | Copyright © 2013 , JUXT LTD . All Rights Reserved .
Eclipse Public License 1.0 ( -1.0.php )
(ns jig.console.todo
(:require
[ring.util.response :as ring-resp]
[clojure.java.io :as io]
[hiccup.core :refer (html h)]
jig
[jig.console :refer (add-extension ->Boilerplate)])
(:import (jig Lifecycle)))
(defn find-todo-lines [f]
(filter :todo
(map
(partial zipmap [:file :line :todo])
(map vector
(repeat (str f))
(map inc (range))
(map #(second (re-find (re-pattern (str \T \O \D \O \: "?\\s*([^\r\n\"]*)")) %))
(line-seq (io/reader f)))))))
(defn extract-snippet [file line]
(apply str
(interpose \newline
(->> file (io/reader) line-seq (drop (- line 5)) (take 10)))))
(defn todo-finder [dir]
(apply concat
(for [f (.listFiles dir)]
(cond
(.isDirectory f) (todo-finder f)
(.isFile f) (find-todo-lines f)))))
(defn todos-page [request]
(ring-resp/response
(html
[:h1 (str \T \O \D \O \s)]
[:p (format "Developers sometimes think of things to do while coding which, for whatever reason, isn't possible to do at the time. A common convention is to label the comment with '%s'." (str \T \O \D \O))]
(let [content (for [project (-> request :jig/system :jig/projects)]
(let [paths (->> project :project :source-paths (map (comp (memfn getCanonicalFile) io/file)))
todos (mapcat todo-finder paths)]
(when (pos? (count todos))
[:div
[:h2 (:name project)]
[:p (format "%d remaining %ss" (count todos) (str \T \O \D \O))]
[:ul
(for [{:keys [file line todo]} todos]
[:div
[:h4 [:i todo]]
[:p "File: " file]
[:p "Line: " line]
[:pre (extract-snippet file line)]
])]])))]
(if (empty? content)
[:p (format "There are currently no %s. That's good. But if you add them, they'll appear here."
(str \T \O \D \O \s))]
(list
[:p (format "Here are the %s items that remain in the code-base." (str \T \O \D \O))]
content)))
)))
(deftype JigComponent [config]
Lifecycle
(init [_ system]
(add-extension
system config
:route ["" (->Boilerplate todos-page)]
:menuitems [[(str \T \O \D \O \s) todos-page]]))
(start [_ system] system)
(stop [_ system] system))
|
97b50472a61b33aa21b9da10692256bc7643ee83191b24e0201fefe65770b89c | evrim/core-server | init.lisp | (in-package :manager)
;; +-------------------------------------------------------------------------
;; | Manager Instance
;; +-------------------------------------------------------------------------
(defun register-me (&optional (server *server*))
(if (null (status *app*)) (start *app*))
(register server *app*))
(defun unregister-me (&optional (server *server*))
(unregister server *app*))
(defvar *app* (make-instance 'manager-application))
| null | https://raw.githubusercontent.com/evrim/core-server/200ea8151d2f8d81b593d605b183a9cddae1e82d/src/manager/src/init.lisp | lisp | +-------------------------------------------------------------------------
| Manager Instance
+------------------------------------------------------------------------- | (in-package :manager)
(defun register-me (&optional (server *server*))
(if (null (status *app*)) (start *app*))
(register server *app*))
(defun unregister-me (&optional (server *server*))
(unregister server *app*))
(defvar *app* (make-instance 'manager-application))
|
de7bfc0e4a80a613a2ed58f359adbfed13a293f9f1522d93951f234d171db3dc | input-output-hk/cardano-sl | Core.hs |
| Core logic of LRC .
module Pos.Chain.Lrc.Core
( findDelegationStakes
, findRichmenStakes
) where
import Universum hiding (id)
import Data.Conduit (ConduitT, await)
import qualified Data.Conduit.List as CL
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import Pos.Chain.Lrc.Types (RichmenSet, RichmenStakes)
import Pos.Core.Common (Coin, StakeholderId, mkCoin, unsafeAddCoin)
import Pos.Util.Util (getKeys)
-- | Function helper for delegated richmen. Iterates @Delegate ->
[ Issuer]@ map and computes the following two sets :
--
1 . Old richmen set : those who delegated their own stake and thus
-- lost richmen status.
--
2 . Delegates who became richmen .
findDelegationStakes
:: forall m . Monad m
=> (StakeholderId -> m Bool) -- ^ Check if user is issuer?
-> (StakeholderId -> m (Maybe Coin)) -- ^ Gets effective stake.
-> Coin -- ^ Coin threshold
-> ConduitT (StakeholderId, HashSet StakeholderId)
Void
m
(RichmenSet, RichmenStakes) -- ^ Old richmen, new richmen
findDelegationStakes isIssuer stakeResolver t = do
(old, new) <- step (mempty, mempty)
pure (getKeys ((HS.toMap old) `HM.difference` new), new)
where
step :: (RichmenSet, RichmenStakes)
-> ConduitT (StakeholderId, HashSet StakeholderId)
Void
m
(RichmenSet, RichmenStakes)
step richmen = do
v <- await
maybe (pure richmen) (onItem richmen >=> step) v
onItem (old, new) (delegate, issuers) = do
sumIssuers <-
foldM (\cr id -> (unsafeAddCoin cr) <$> safeGetStake id)
(mkCoin 0)
issuers
isIss <- lift $ isIssuer delegate
curStake <- if isIss then pure sumIssuers
else (unsafeAddCoin sumIssuers) <$> safeGetStake delegate
let newRichmen =
if curStake >= t then HM.insert delegate curStake new
else new
oldRichmen <-
foldM (\hs is -> ifM ((>= t) <$> safeGetStake is)
(pure $ HS.insert is hs)
(pure hs))
old
issuers
pure (oldRichmen, newRichmen)
safeGetStake id = fromMaybe (mkCoin 0) <$> lift (stakeResolver id)
-- | Find all stake holders which have at least 'eligibility threshold' coins.
-- Assumes that the `StakeholderId`s are unique. The consumer of the generated
` RichmenStakes ` further assumes that the provided ` Coin ` values are valid ,
-- and that the sum of the input `Coin` values is less than `maxCoinVal`.
findRichmenStakes
:: forall m . Monad m
=> Coin -- ^ Eligibility threshold
-> ConduitT (StakeholderId, Coin) Void m RichmenStakes
findRichmenStakes t = CL.fold thresholdInsert mempty
where
thresholdInsert
:: HashMap StakeholderId Coin
-> (StakeholderId, Coin)
-> HashMap StakeholderId Coin
thresholdInsert hm (a, c) = if c >= t then HM.insert a c hm else hm
| null | https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/chain/src/Pos/Chain/Lrc/Core.hs | haskell | | Function helper for delegated richmen. Iterates @Delegate ->
lost richmen status.
^ Check if user is issuer?
^ Gets effective stake.
^ Coin threshold
^ Old richmen, new richmen
| Find all stake holders which have at least 'eligibility threshold' coins.
Assumes that the `StakeholderId`s are unique. The consumer of the generated
and that the sum of the input `Coin` values is less than `maxCoinVal`.
^ Eligibility threshold |
| Core logic of LRC .
module Pos.Chain.Lrc.Core
( findDelegationStakes
, findRichmenStakes
) where
import Universum hiding (id)
import Data.Conduit (ConduitT, await)
import qualified Data.Conduit.List as CL
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import Pos.Chain.Lrc.Types (RichmenSet, RichmenStakes)
import Pos.Core.Common (Coin, StakeholderId, mkCoin, unsafeAddCoin)
import Pos.Util.Util (getKeys)
[ Issuer]@ map and computes the following two sets :
1 . Old richmen set : those who delegated their own stake and thus
2 . Delegates who became richmen .
findDelegationStakes
:: forall m . Monad m
-> ConduitT (StakeholderId, HashSet StakeholderId)
Void
m
findDelegationStakes isIssuer stakeResolver t = do
(old, new) <- step (mempty, mempty)
pure (getKeys ((HS.toMap old) `HM.difference` new), new)
where
step :: (RichmenSet, RichmenStakes)
-> ConduitT (StakeholderId, HashSet StakeholderId)
Void
m
(RichmenSet, RichmenStakes)
step richmen = do
v <- await
maybe (pure richmen) (onItem richmen >=> step) v
onItem (old, new) (delegate, issuers) = do
sumIssuers <-
foldM (\cr id -> (unsafeAddCoin cr) <$> safeGetStake id)
(mkCoin 0)
issuers
isIss <- lift $ isIssuer delegate
curStake <- if isIss then pure sumIssuers
else (unsafeAddCoin sumIssuers) <$> safeGetStake delegate
let newRichmen =
if curStake >= t then HM.insert delegate curStake new
else new
oldRichmen <-
foldM (\hs is -> ifM ((>= t) <$> safeGetStake is)
(pure $ HS.insert is hs)
(pure hs))
old
issuers
pure (oldRichmen, newRichmen)
safeGetStake id = fromMaybe (mkCoin 0) <$> lift (stakeResolver id)
` RichmenStakes ` further assumes that the provided ` Coin ` values are valid ,
findRichmenStakes
:: forall m . Monad m
-> ConduitT (StakeholderId, Coin) Void m RichmenStakes
findRichmenStakes t = CL.fold thresholdInsert mempty
where
thresholdInsert
:: HashMap StakeholderId Coin
-> (StakeholderId, Coin)
-> HashMap StakeholderId Coin
thresholdInsert hm (a, c) = if c >= t then HM.insert a c hm else hm
|
f2f5f035331d04ab49532e134fc3958e16ea5b69e4ad2b3f0427af622c5c47e8 | haskell-tools/haskell-tools | NormalExistential.hs | {-# LANGUAGE GADTs #-}
module NormalExistential where
{-@ GADTs @-}
data T a where
T1 :: b -> T a {-* GADTSyntax, GADTs + ExistentialQuantification *-}
T2 :: a -> a -> T a {-* GADTSyntax *-}
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/test/ExtensionOrganizerTest/GADTsTest/NormalExistential.hs | haskell | # LANGUAGE GADTs #
@ GADTs @
* GADTSyntax, GADTs + ExistentialQuantification *
* GADTSyntax * |
module NormalExistential where
data T a where
|
95f3d236d83a68d67a0448a782528693c938d860d884febd1a78ecee1ea6f699 | RefactoringTools/wrangler | eqc_fold_expr.erl | -module(eqc_fold_expr).
-compile(export_all).
-include_lib("eqc/include/eqc.hrl").
% filename generator
gen_filename(Dirs) ->
AllErlFiles = wrangler_misc:expand_files(Dirs, ".erl"),
oneof(AllErlFiles).
%% collect function define locations in an AST
collect_fold_candidates(FName, SearchPaths, TabWidth) ->
{ok, {AST, _Info}} = wrangler_ast_server:parse_annotate_file(FName, true, SearchPaths, TabWidth),
F = fun (T, S) ->
case wrangler_syntax:type(T) of
function ->
FunName = wrangler_syntax:data(wrangler_syntax:function_name(T)),
Arity1 = wrangler_syntax:function_arity(T),
Cs = wrangler_syntax:function_clauses(T),
Rs = lists:map(fun (C) -> api_refac:start_end_loc(C) end, Cs),
Res = lists:flatmap(fun (R) ->
{{StartLine, StartCol}, _} = R,
Args = [FName, StartLine, StartCol, SearchPaths, TabWidth, emacs],
try apply(refac_fold_expression, fold_expression, Args) of
{ok, Regions} ->
Regions1 = lists:map(fun (Reg) ->
list_to_tuple([FunName, Arity1| tuple_to_list(Reg)])
end,
Regions),
Regions1;
_ -> []
catch
E1:E2 -> []
end
end, Rs),
Res ++ S;
_ -> S
end
end,
Res = lists:usort(api_ast_traverse:fold(F, [], AST)),
case Res of
[] ->
[{0,0,0,0,0,0,0,{0,0,0,0}}];
_ -> Res
end.
prop_fold_expr({FunName, Arity, StartLine, StartCol, EndLine, EndCol, NewExp, ClauseInfo={FName, _Mod, _Def, Index}}, SearchPaths) ->
?IMPLIES(StartLine=/=0,
begin
Args1 = [FName, StartLine, StartCol, EndLine, EndCol, NewExp, ClauseInfo, SearchPaths, 8],
io:format("\nCMDInfo: fold_expression_1:~p\n", [{FName, FunName, Arity, Index}]),
try apply(refac_fold_expression, fold_expression_1, Args1) of
{ok, _Res} ->
wrangler_preview_server:commit(),
case compile:file(FName, [{i, "c:/cygwin/home/hl/test_codebase"}]) of
{ok, _} -> wrangler_undo_server:undo(),
io:format("\nOk, refactoring succeeded.\n"),
true;
_ ->wrangler_undo_server:undo(),
io:format("\nResulted file:~p does not compole!\n", [FName]),
false
end;
{error, Msg} ->
io:format("\n~p\n", [{error,Msg}]),
true
catch
throw:Error ->
io:format("Error:\n~\pn", [Error]),
error;
E1:E2 ->
io:format("E1:E2:\n~p\n", [{E1, E2}]),
false
end
end).
gen_fold_expr_commands(Dirs) ->
noshrink(?LET(FileName, (gen_filename(Dirs)),
oneof(collect_fold_candidates(FileName, Dirs, 8)))).
test_fold_expr(Dirs) ->
application:start(wrangler_app),
eqc:quickcheck(numtests(500,?FORALL(C, (gen_fold_expr_commands(Dirs)), prop_fold_expr(C, Dirs)))),
application:stop(wrangler_app).
test_fold_expr1() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/tableau"]).
test_fold_expr2() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/eunit"]).
test_fold_expr3() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/refactorerl-0.5"]).
test_fold_expr4() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/suite"]).
test_fold_expr5() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/wrangler-0.7"]).
test_fold_expr6() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/umbria"]).
test_fold_expr7() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/yaws-1.77"]).
test_fold_expr8() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/dialyzer-1.8.3"]).
test_fold_expr() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase"]).
run_test() ->
test_fold_expr1(),
test_fold_expr2(),
%% test_fold_expr3(),
%% test_fold_expr4(),
%% test_fold_expr5(),
test_fold_expr6().
%% test_fold_expr7(),
( ) .
| null | https://raw.githubusercontent.com/RefactoringTools/wrangler/1c33ad0e923bb7bcebb6fd75347638def91e50a8/qc_test/eqc_fold_expr.erl | erlang | filename generator
collect function define locations in an AST
test_fold_expr3(),
test_fold_expr4(),
test_fold_expr5(),
test_fold_expr7(),
| -module(eqc_fold_expr).
-compile(export_all).
-include_lib("eqc/include/eqc.hrl").
gen_filename(Dirs) ->
AllErlFiles = wrangler_misc:expand_files(Dirs, ".erl"),
oneof(AllErlFiles).
collect_fold_candidates(FName, SearchPaths, TabWidth) ->
{ok, {AST, _Info}} = wrangler_ast_server:parse_annotate_file(FName, true, SearchPaths, TabWidth),
F = fun (T, S) ->
case wrangler_syntax:type(T) of
function ->
FunName = wrangler_syntax:data(wrangler_syntax:function_name(T)),
Arity1 = wrangler_syntax:function_arity(T),
Cs = wrangler_syntax:function_clauses(T),
Rs = lists:map(fun (C) -> api_refac:start_end_loc(C) end, Cs),
Res = lists:flatmap(fun (R) ->
{{StartLine, StartCol}, _} = R,
Args = [FName, StartLine, StartCol, SearchPaths, TabWidth, emacs],
try apply(refac_fold_expression, fold_expression, Args) of
{ok, Regions} ->
Regions1 = lists:map(fun (Reg) ->
list_to_tuple([FunName, Arity1| tuple_to_list(Reg)])
end,
Regions),
Regions1;
_ -> []
catch
E1:E2 -> []
end
end, Rs),
Res ++ S;
_ -> S
end
end,
Res = lists:usort(api_ast_traverse:fold(F, [], AST)),
case Res of
[] ->
[{0,0,0,0,0,0,0,{0,0,0,0}}];
_ -> Res
end.
prop_fold_expr({FunName, Arity, StartLine, StartCol, EndLine, EndCol, NewExp, ClauseInfo={FName, _Mod, _Def, Index}}, SearchPaths) ->
?IMPLIES(StartLine=/=0,
begin
Args1 = [FName, StartLine, StartCol, EndLine, EndCol, NewExp, ClauseInfo, SearchPaths, 8],
io:format("\nCMDInfo: fold_expression_1:~p\n", [{FName, FunName, Arity, Index}]),
try apply(refac_fold_expression, fold_expression_1, Args1) of
{ok, _Res} ->
wrangler_preview_server:commit(),
case compile:file(FName, [{i, "c:/cygwin/home/hl/test_codebase"}]) of
{ok, _} -> wrangler_undo_server:undo(),
io:format("\nOk, refactoring succeeded.\n"),
true;
_ ->wrangler_undo_server:undo(),
io:format("\nResulted file:~p does not compole!\n", [FName]),
false
end;
{error, Msg} ->
io:format("\n~p\n", [{error,Msg}]),
true
catch
throw:Error ->
io:format("Error:\n~\pn", [Error]),
error;
E1:E2 ->
io:format("E1:E2:\n~p\n", [{E1, E2}]),
false
end
end).
gen_fold_expr_commands(Dirs) ->
noshrink(?LET(FileName, (gen_filename(Dirs)),
oneof(collect_fold_candidates(FileName, Dirs, 8)))).
test_fold_expr(Dirs) ->
application:start(wrangler_app),
eqc:quickcheck(numtests(500,?FORALL(C, (gen_fold_expr_commands(Dirs)), prop_fold_expr(C, Dirs)))),
application:stop(wrangler_app).
test_fold_expr1() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/tableau"]).
test_fold_expr2() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/eunit"]).
test_fold_expr3() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/refactorerl-0.5"]).
test_fold_expr4() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/suite"]).
test_fold_expr5() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/wrangler-0.7"]).
test_fold_expr6() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/umbria"]).
test_fold_expr7() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/yaws-1.77"]).
test_fold_expr8() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase/dialyzer-1.8.3"]).
test_fold_expr() ->
test_fold_expr(["c:/cygwin/home/hl/test_codebase"]).
run_test() ->
test_fold_expr1(),
test_fold_expr2(),
test_fold_expr6().
( ) .
|
2528770b4b42f86cba98e5e1b82270527baa6f449fdd446994ad0ab0514e6a50 | MaxOw/computational-geometry | CrossPoint.hs | # Language MultiParamTypeClasses #
{-# Language FlexibleInstances #-}
--------------------------------------------------------------------------------
-- |
Module : Geometry . SetOperations .
Copyright : ( C ) 2017
-- License : BSD-style (see LICENSE)
Maintainer :
--
--------------------------------------------------------------------------------
module Geometry.SetOperations.CrossPoint
( Sign (..)
, toSign
, CrossPoint (..)
, MakeCrossPoint (..)
, toCrossPoint
) where
import Protolude
import Linear
import Linear.Affine (Point)
import qualified Linear.Affine as Point
import Data.EqZero
import Geometry.Plane.General
--------------------------------------------------------------------------------
data Sign = M | Z | P deriving (Show, Eq)
toSign :: (EqZero n, Ord n, Num n) => n -> Sign
toSign x
| eqZero x = Z
| x < 0 = M
| otherwise = P
data CrossPoint v n = CP
{ orientation :: Plane v n -> Sign
, getPoint :: Point v n
}
| Convert a point to CrossPoint
toCrossPoint :: (EqZero n, Foldable v, Num n, Ord n)
=> Point v n -> CrossPoint v n
toCrossPoint pt = CP orient pt
where
orient p = toSign . ((planeLast p) +) . sum
$ zipWith (*) (toList $ planeVector p) (toList pt)
class MakeCrossPoint v n where
makeCrossPoint :: v (Plane v n) -> Maybe (CrossPoint v n)
instance (Fractional n, Ord n, EqZero n) => MakeCrossPoint V2 n where
makeCrossPoint planes
| eqZero d2 = Nothing
| otherwise = Just $ CP orient solved
where
V2 (Plane (V2 a b) c)
(Plane (V2 d e) f) = planes
orient ( Plane ( V2 g h ) i ) = toSign $ d2*(g*d0 - h*d1 + i*d2 )
orient (Plane (V2 g h) i) = toSign $ g*dd0 + h*dd1 + i
dd0 = d2*d0
dd1 = d2*d1
d0 = b*f - c*e
d1 = a*f - c*d
d2 = a*e - b*d
dd = 1/d2
solved = Point.P $ V2 (dd*d0) (dd*d1)
instance (Fractional n, Ord n, EqZero n) => MakeCrossPoint V3 n where
makeCrossPoint planes
| eqZero d3 = Nothing
| otherwise = Just $ CP orient solved
where
V3 (Plane (V3 a b c) d)
(Plane (V3 e f g) h)
(Plane (V3 i j k) l) = planes
orient (Plane (V3 m n o) p) = toSign $ -d3*(m*d0 - n*d1 + o*d2 - p*d3)
d0 = k*m1 - j*m0 + l*m2
d1 = k*m3 - i*m0 + l*m4
d2 = j*m3 - i*m1 + l*m5
d3 = i*m2 - j*m4 + k*m5
m0 = c*h - d*g
m1 = b*h - d*f
m2 = c*f - b*g
m3 = a*h - d*e
m4 = c*e - a*g
m5 = b*e - a*f
dd = 1/d3
solved = Point.P $ V3 (-dd*d0) (dd*d1) (-dd*d2)
| null | https://raw.githubusercontent.com/MaxOw/computational-geometry/20c93aa05b151b115250a18d1203fdf9a01f705e/src/Geometry/SetOperations/CrossPoint.hs | haskell | # Language FlexibleInstances #
------------------------------------------------------------------------------
|
License : BSD-style (see LICENSE)
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | # Language MultiParamTypeClasses #
Module : Geometry . SetOperations .
Copyright : ( C ) 2017
Maintainer :
module Geometry.SetOperations.CrossPoint
( Sign (..)
, toSign
, CrossPoint (..)
, MakeCrossPoint (..)
, toCrossPoint
) where
import Protolude
import Linear
import Linear.Affine (Point)
import qualified Linear.Affine as Point
import Data.EqZero
import Geometry.Plane.General
data Sign = M | Z | P deriving (Show, Eq)
toSign :: (EqZero n, Ord n, Num n) => n -> Sign
toSign x
| eqZero x = Z
| x < 0 = M
| otherwise = P
data CrossPoint v n = CP
{ orientation :: Plane v n -> Sign
, getPoint :: Point v n
}
| Convert a point to CrossPoint
toCrossPoint :: (EqZero n, Foldable v, Num n, Ord n)
=> Point v n -> CrossPoint v n
toCrossPoint pt = CP orient pt
where
orient p = toSign . ((planeLast p) +) . sum
$ zipWith (*) (toList $ planeVector p) (toList pt)
class MakeCrossPoint v n where
makeCrossPoint :: v (Plane v n) -> Maybe (CrossPoint v n)
instance (Fractional n, Ord n, EqZero n) => MakeCrossPoint V2 n where
makeCrossPoint planes
| eqZero d2 = Nothing
| otherwise = Just $ CP orient solved
where
V2 (Plane (V2 a b) c)
(Plane (V2 d e) f) = planes
orient ( Plane ( V2 g h ) i ) = toSign $ d2*(g*d0 - h*d1 + i*d2 )
orient (Plane (V2 g h) i) = toSign $ g*dd0 + h*dd1 + i
dd0 = d2*d0
dd1 = d2*d1
d0 = b*f - c*e
d1 = a*f - c*d
d2 = a*e - b*d
dd = 1/d2
solved = Point.P $ V2 (dd*d0) (dd*d1)
instance (Fractional n, Ord n, EqZero n) => MakeCrossPoint V3 n where
makeCrossPoint planes
| eqZero d3 = Nothing
| otherwise = Just $ CP orient solved
where
V3 (Plane (V3 a b c) d)
(Plane (V3 e f g) h)
(Plane (V3 i j k) l) = planes
orient (Plane (V3 m n o) p) = toSign $ -d3*(m*d0 - n*d1 + o*d2 - p*d3)
d0 = k*m1 - j*m0 + l*m2
d1 = k*m3 - i*m0 + l*m4
d2 = j*m3 - i*m1 + l*m5
d3 = i*m2 - j*m4 + k*m5
m0 = c*h - d*g
m1 = b*h - d*f
m2 = c*f - b*g
m3 = a*h - d*e
m4 = c*e - a*g
m5 = b*e - a*f
dd = 1/d3
solved = Point.P $ V3 (-dd*d0) (dd*d1) (-dd*d2)
|
6a0ffdc5149c2b89bd48b7830fb0048bc977f323a7ad8dbe6456d515758f7bbe | ndmitchell/hoogle | Util.hs | # LANGUAGE PatternGuards , ViewPatterns , CPP , ScopedTypeVariables #
module General.Util(
PkgName, ModName,
URL,
pretty, parseMode, applyType, applyFun1, unapplyFun, fromName, fromQName, fromTyVarBind, declNames, isTypeSig,
fromDeclHead, fromContext, fromIParen, fromInstHead,
tarballReadFiles,
isUpper1, isAlpha1,
joinPair,
testing, testEq,
showUTCTime,
strict,
withs,
escapeHTML, unescapeHTML, unHTML,
escapeURL,
takeSortOn,
Average, toAverage, fromAverage,
inRanges,
parseTrailingVersion,
trimVersion,
exitFail,
prettyTable,
getStatsPeakAllocBytes, getStatsCurrentLiveBytes, getStatsDebug,
hackagePackageURL, hackageModuleURL, hackageDeclURL, ghcModuleURL,
minimum', maximum',
general_util_test
) where
import Language.Haskell.Exts
import Control.Applicative
import Data.List.Extra
import Data.Char
import Data.Either.Extra
import Data.Semigroup
import Data.Tuple.Extra
import Control.Monad.Extra
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import Data.Ix
import Numeric.Extra
import Codec.Compression.GZip as GZip
import Codec.Archive.Tar as Tar
import Data.Time.Clock
import Data.Time.Format
import Control.DeepSeq
import Control.Exception.Extra
import Test.QuickCheck
import Data.Version
import Data.Int
import System.IO
import System.Exit
import System.Mem
import GHC.Stats
import General.Str
import Prelude
import qualified Network.HTTP.Types.URI as URI
import qualified Data.ByteString.UTF8 as UTF8
type PkgName = Str
type ModName = Str
-- | A URL, complete with a @https:@ prefix.
type URL = String
#if __GLASGOW_HASKELL__ >= 802
#define RTS_STATS 1
#endif
showMb :: (Show a, Integral a) => a -> String
#if RTS_STATS
showMb x = show (x `div` (1024*1024)) ++ "Mb"
#else
showMb x = show x ++ "Mb"
#endif
#if RTS_STATS
withRTSStats :: (RTSStats -> a) -> IO (Maybe a)
withRTSStats f = ifM getRTSStatsEnabled (Just . f <$> getRTSStats) (pure Nothing)
#else
withGCStats :: (GCStats -> a) -> IO (Maybe a)
withGCStats f = ifM getGCStatsEnabled (Just . f <$> getGCStats) (pure Nothing)
#endif
getStatsCurrentLiveBytes :: IO (Maybe String)
getStatsCurrentLiveBytes = do
performGC
#if RTS_STATS
withRTSStats $ showMb . gcdetails_live_bytes . gc
#else
withGCStats $ showMb . currentBytesUsed
#endif
getStatsPeakAllocBytes :: IO (Maybe String)
getStatsPeakAllocBytes = do
#if RTS_STATS
withRTSStats $ showMb . max_mem_in_use_bytes
#else
withGCStats $ showMb . peakMegabytesAllocated
#endif
getStatsDebug :: IO (Maybe String)
getStatsDebug = do
let dump = replace ", " "\n" . takeWhile (/= '}') . drop1 . dropWhile (/= '{') . show
#if RTS_STATS
withRTSStats dump
#else
withGCStats dump
#endif
exitFail :: String -> IO ()
exitFail msg = do
hPutStrLn stderr msg
exitFailure
pretty :: Pretty a => a -> String
pretty = prettyPrintWithMode defaultMode{layout=PPNoLayout}
parseMode :: ParseMode
parseMode = defaultParseMode{extensions=map EnableExtension es}
where es = [ConstraintKinds,EmptyDataDecls,TypeOperators,ExplicitForAll,GADTs,KindSignatures,MultiParamTypeClasses
,TypeFamilies,FlexibleContexts,FunctionalDependencies,ImplicitParams,MagicHash,UnboxedTuples
,ParallelArrays,UnicodeSyntax,DataKinds,PolyKinds,PatternSynonyms]
applyType :: Type a -> [Type a] -> Type a
applyType x (t:ts) = applyType (TyApp (ann t) x t) ts
applyType x [] = x
applyFun1 :: [Type a] -> Type a
applyFun1 [x] = x
applyFun1 (x:xs) = TyFun (ann x) x $ applyFun1 xs
unapplyFun :: Type a -> [Type a]
unapplyFun (TyFun _ x y) = x : unapplyFun y
unapplyFun x = [x]
fromName :: Name a -> String
fromName (Ident _ x) = x
fromName (Symbol _ x) = x
fromQName :: QName a -> String
fromQName (Qual _ _ x) = fromName x
fromQName (UnQual _ x) = fromName x
fromQName (Special _ UnitCon{}) = "()"
fromQName (Special _ ListCon{}) = "[]"
fromQName (Special _ FunCon{}) = "->"
fromQName (Special _ (TupleCon _ box n)) = "(" ++ h ++ replicate n ',' ++ h ++ ")"
where h = ['#' | box == Unboxed]
fromQName (Special _ UnboxedSingleCon{}) = "(##)"
fromQName (Special _ Cons{}) = ":"
fromContext :: Context a -> [Asst a]
fromContext (CxSingle _ x) = [x]
fromContext (CxTuple _ xs) = xs
fromContext _ = []
fromIParen :: InstRule a -> InstRule a
fromIParen (IParen _ x) = fromIParen x
fromIParen x = x
fromTyVarBind :: TyVarBind a -> Name a
fromTyVarBind (KindedVar _ x _) = x
fromTyVarBind (UnkindedVar _ x) = x
fromDeclHead :: DeclHead a -> (Name a, [TyVarBind a])
fromDeclHead (DHead _ n) = (n, [])
fromDeclHead (DHInfix _ x n) = (n, [x])
fromDeclHead (DHParen _ x) = fromDeclHead x
fromDeclHead (DHApp _ dh x) = second (++[x]) $ fromDeclHead dh
fromInstHead :: InstHead a -> (QName a, [Type a])
fromInstHead (IHCon _ n) = (n, [])
fromInstHead (IHInfix _ x n) = (n, [x])
fromInstHead (IHParen _ x) = fromInstHead x
fromInstHead (IHApp _ ih x) = second (++[x]) $ fromInstHead ih
declNames :: Decl a -> [String]
declNames x = map fromName $ case x of
TypeDecl _ hd _ -> f hd
DataDecl _ _ _ hd _ _ -> f hd
GDataDecl _ _ _ hd _ _ _ -> f hd
TypeFamDecl _ hd _ _ -> f hd
DataFamDecl _ _ hd _ -> f hd
ClassDecl _ _ hd _ _ -> f hd
TypeSig _ names _ -> names
PatSynSig _ names _ _ _ _ _ -> names
_ -> []
where f x = [fst $ fromDeclHead x]
isTypeSig :: Decl a -> Bool
isTypeSig TypeSig{} = True
isTypeSig PatSynSig{} = True
isTypeSig _ = False
tarballReadFiles :: FilePath -> IO [(FilePath, LBS.ByteString)]
tarballReadFiles file = f . Tar.read . GZip.decompress <$> LBS.readFile file
where
f (Next e rest) | NormalFile body _ <- entryContent e = (entryPath e, body) : f rest
f (Next _ rest) = f rest
f Done = []
f (Fail e) = error $ "tarballReadFiles on " ++ file ++ ", " ++ show e
innerTextHTML :: String -> String
innerTextHTML ('<':xs) = innerTextHTML $ drop1 $ dropWhile (/= '>') xs
innerTextHTML (x:xs) = x : innerTextHTML xs
innerTextHTML [] = []
unHTML :: String -> String
unHTML = unescapeHTML . innerTextHTML
escapeURL :: String -> String
escapeURL = UTF8.toString . URI.urlEncode True . UTF8.fromString
isUpper1 (x:xs) = isUpper x
isUpper1 _ = False
isAlpha1 (x:xs) = isAlpha x
isAlpha1 [] = False
splitPair :: String -> String -> (String, String)
splitPair x y | (a,stripPrefix x -> Just b) <- breakOn x y = (a,b)
| otherwise = error $ "splitPair does not contain separator " ++ show x ++ " in " ++ show y
joinPair :: [a] -> ([a], [a]) -> [a]
joinPair sep (a,b) = a ++ sep ++ b
testing_, testing :: String -> IO () -> IO ()
testing_ name act = do putStr $ "Test " ++ name ++ " "; act
testing name act = do testing_ name act; putStrLn ""
testEq :: (Show a, Eq a) => a -> a -> IO ()
testEq a b | a == b = putStr "."
| otherwise = errorIO $ "Expected equal, but " ++ show a ++ " /= " ++ show b
showUTCTime :: String -> UTCTime -> String
showUTCTime = formatTime defaultTimeLocale
withs :: [(a -> r) -> r] -> ([a] -> r) -> r
withs [] act = act []
withs (f:fs) act = f $ \a -> withs fs $ \as -> act $ a:as
prettyTable :: Int -> String -> [(String, Double)] -> [String]
prettyTable dp units xs =
( padR len units ++ "\tPercent\tName") :
[ padL len (showDP dp b) ++ "\t" ++ padL 7 (showDP 1 (100 * b / tot) ++ "%") ++ "\t" ++ a
| (a,b) <- ("Total", tot) : sortOn (negate . snd) xs]
where
tot = sum $ map snd xs
len = length units `max` length (showDP dp tot)
padL n s = replicate (n - length s) ' ' ++ s
padR n s = s ++ replicate (n - length s) ' '
-- ensure that no value escapes in a thunk from the value
strict :: NFData a => IO a -> IO a
strict act = do
res <- try_ act
case res of
Left e -> do msg <- showException e; evaluate $ rnf msg; errorIO msg
Right v -> evaluate $ force v
data Average a = Average !a {-# UNPACK #-} !Int deriving Show -- a / b
toAverage :: a -> Average a
toAverage x = Average x 1
fromAverage :: Fractional a => Average a -> a
fromAverage (Average a b) = a / fromIntegral b
instance Num a => Semigroup (Average a) where
Average x1 x2 <> Average y1 y2 = Average (x1+y1) (x2+y2)
instance Num a => Monoid (Average a) where
mempty = Average 0 0
mappend = (<>)
data TakeSort k v = More !Int !(Map.Map k [v])
| Full !k !(Map.Map k [v])
-- | @takeSortOn n op == take n . sortOn op@
takeSortOn :: Ord k => (a -> k) -> Int -> [a] -> [a]
takeSortOn op n xs
| n <= 0 = []
| otherwise = concatMap reverse $ Map.elems $ getMap $ foldl' add (More n Map.empty) xs
where
getMap (More _ mp) = mp
getMap (Full _ mp) = mp
add (More n mp) x = (if n <= 1 then full else More (n-1)) $ Map.insertWith (++) (op x) [x] mp
add o@(Full mx mp) x = let k = op x in if k >= mx then o else full $ Map.insertWith (++) k [x] $ delMax mp
full mp = Full (fst $ Map.findMax mp) mp
delMax mp | Just ((k,_:vs), mp) <- Map.maxViewWithKey mp = if null vs then mp else Map.insert k vs mp
See - they broke
maximumBy' :: (a -> a -> Ordering) -> [a] -> a
maximumBy' cmp = foldl1' $ \x y -> if cmp x y == GT then x else y
maximum' :: Ord a => [a] -> a
maximum' = maximumBy' compare
minimumBy' :: (a -> a -> Ordering) -> [a] -> a
minimumBy' cmp = foldl1' $ \x y -> if cmp x y == LT then x else y
minimum' :: Ord a => [a] -> a
minimum' = minimumBy' compare
hackagePackageURL :: PkgName -> URL
hackagePackageURL x = "/" ++ strUnpack x
hackageModuleURL :: ModName -> URL
hackageModuleURL x = "/docs/" ++ ghcModuleURL x
ghcModuleURL :: ModName -> URL
ghcModuleURL x = replace "." "-" (strUnpack x) ++ ".html"
hackageDeclURL :: Bool -> String -> URL
hackageDeclURL typesig x = "#" ++ (if typesig then "v" else "t") ++ ":" ++ concatMap f x
where
f x | isLegal x = [x]
| otherwise = "-" ++ show (ord x) ++ "-"
-- isLegal is from haddock-api:Haddock.Utils; we need to use
-- the same escaping strategy here in order for fragment links
-- to work
isLegal ':' = True
isLegal '_' = True
isLegal '.' = True
isLegal c = isAscii c && isAlphaNum c
trimVersion :: Int -> Version -> Version
trimVersion i v = v{versionBranch = take 3 $ versionBranch v}
parseTrailingVersion :: String -> (String, [Int])
parseTrailingVersion = (reverse *** reverse) . f . reverse
where
f xs | (ver@(_:_),sep:xs) <- span isDigit xs
, sep == '-' || sep == '.'
, (a, b) <- f xs
= (a, Prelude.read (reverse ver) : b)
f xs = (xs, [])
-- | Equivalent to any (`inRange` x) xs, but more efficient
inRanges :: Ix a => [(a,a)] -> (a -> Bool)
inRanges xs = \x -> maybe False (`inRange` x) $ Map.lookupLE x mp
where
mp = foldl' add Map.empty xs
merge (l1,u1) (l2,u2) = (min l1 l2, max u1 u2)
overlap x1 x2 = x1 `inRange` fst x2 || x2 `inRange` fst x1
add mp x
| Just x2 <- Map.lookupLE (fst x) mp, overlap x x2 = add (Map.delete (fst x2) mp) (merge x x2)
| Just x2 <- Map.lookupGE (fst x) mp, overlap x x2 = add (Map.delete (fst x2) mp) (merge x x2)
| otherwise = uncurry Map.insert x mp
general_util_test :: IO ()
general_util_test = do
testing "General.Util.splitPair" $ do
let a === b = if a == b then putChar '.' else errorIO $ show (a,b)
splitPair ":" "module:foo:bar" === ("module","foo:bar")
do x <- try_ $ evaluate $ rnf $ splitPair "-" "module:foo"; isLeft x === True
splitPair "-" "module-" === ("module","")
testing_ "General.Util.inRanges" $ do
quickCheck $ \(x :: Int8) xs -> inRanges xs x == any (`inRange` x) xs
testing "General.Util.parseTrailingVersion" $ do
let a === b = if a == b then putChar '.' else errorIO $ show (a,b)
parseTrailingVersion "shake-0.15.2" === ("shake",[0,15,2])
parseTrailingVersion "test-of-stuff1" === ("test-of-stuff1",[])
| null | https://raw.githubusercontent.com/ndmitchell/hoogle/25b2872929e3fccd5bbcdef026cec63ce365647e/src/General/Util.hs | haskell | | A URL, complete with a @https:@ prefix.
ensure that no value escapes in a thunk from the value
# UNPACK #
a / b
| @takeSortOn n op == take n . sortOn op@
isLegal is from haddock-api:Haddock.Utils; we need to use
the same escaping strategy here in order for fragment links
to work
| Equivalent to any (`inRange` x) xs, but more efficient | # LANGUAGE PatternGuards , ViewPatterns , CPP , ScopedTypeVariables #
module General.Util(
PkgName, ModName,
URL,
pretty, parseMode, applyType, applyFun1, unapplyFun, fromName, fromQName, fromTyVarBind, declNames, isTypeSig,
fromDeclHead, fromContext, fromIParen, fromInstHead,
tarballReadFiles,
isUpper1, isAlpha1,
joinPair,
testing, testEq,
showUTCTime,
strict,
withs,
escapeHTML, unescapeHTML, unHTML,
escapeURL,
takeSortOn,
Average, toAverage, fromAverage,
inRanges,
parseTrailingVersion,
trimVersion,
exitFail,
prettyTable,
getStatsPeakAllocBytes, getStatsCurrentLiveBytes, getStatsDebug,
hackagePackageURL, hackageModuleURL, hackageDeclURL, ghcModuleURL,
minimum', maximum',
general_util_test
) where
import Language.Haskell.Exts
import Control.Applicative
import Data.List.Extra
import Data.Char
import Data.Either.Extra
import Data.Semigroup
import Data.Tuple.Extra
import Control.Monad.Extra
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import Data.Ix
import Numeric.Extra
import Codec.Compression.GZip as GZip
import Codec.Archive.Tar as Tar
import Data.Time.Clock
import Data.Time.Format
import Control.DeepSeq
import Control.Exception.Extra
import Test.QuickCheck
import Data.Version
import Data.Int
import System.IO
import System.Exit
import System.Mem
import GHC.Stats
import General.Str
import Prelude
import qualified Network.HTTP.Types.URI as URI
import qualified Data.ByteString.UTF8 as UTF8
type PkgName = Str
type ModName = Str
type URL = String
#if __GLASGOW_HASKELL__ >= 802
#define RTS_STATS 1
#endif
showMb :: (Show a, Integral a) => a -> String
#if RTS_STATS
showMb x = show (x `div` (1024*1024)) ++ "Mb"
#else
showMb x = show x ++ "Mb"
#endif
#if RTS_STATS
withRTSStats :: (RTSStats -> a) -> IO (Maybe a)
withRTSStats f = ifM getRTSStatsEnabled (Just . f <$> getRTSStats) (pure Nothing)
#else
withGCStats :: (GCStats -> a) -> IO (Maybe a)
withGCStats f = ifM getGCStatsEnabled (Just . f <$> getGCStats) (pure Nothing)
#endif
getStatsCurrentLiveBytes :: IO (Maybe String)
getStatsCurrentLiveBytes = do
performGC
#if RTS_STATS
withRTSStats $ showMb . gcdetails_live_bytes . gc
#else
withGCStats $ showMb . currentBytesUsed
#endif
getStatsPeakAllocBytes :: IO (Maybe String)
getStatsPeakAllocBytes = do
#if RTS_STATS
withRTSStats $ showMb . max_mem_in_use_bytes
#else
withGCStats $ showMb . peakMegabytesAllocated
#endif
getStatsDebug :: IO (Maybe String)
getStatsDebug = do
let dump = replace ", " "\n" . takeWhile (/= '}') . drop1 . dropWhile (/= '{') . show
#if RTS_STATS
withRTSStats dump
#else
withGCStats dump
#endif
exitFail :: String -> IO ()
exitFail msg = do
hPutStrLn stderr msg
exitFailure
pretty :: Pretty a => a -> String
pretty = prettyPrintWithMode defaultMode{layout=PPNoLayout}
parseMode :: ParseMode
parseMode = defaultParseMode{extensions=map EnableExtension es}
where es = [ConstraintKinds,EmptyDataDecls,TypeOperators,ExplicitForAll,GADTs,KindSignatures,MultiParamTypeClasses
,TypeFamilies,FlexibleContexts,FunctionalDependencies,ImplicitParams,MagicHash,UnboxedTuples
,ParallelArrays,UnicodeSyntax,DataKinds,PolyKinds,PatternSynonyms]
applyType :: Type a -> [Type a] -> Type a
applyType x (t:ts) = applyType (TyApp (ann t) x t) ts
applyType x [] = x
applyFun1 :: [Type a] -> Type a
applyFun1 [x] = x
applyFun1 (x:xs) = TyFun (ann x) x $ applyFun1 xs
unapplyFun :: Type a -> [Type a]
unapplyFun (TyFun _ x y) = x : unapplyFun y
unapplyFun x = [x]
fromName :: Name a -> String
fromName (Ident _ x) = x
fromName (Symbol _ x) = x
fromQName :: QName a -> String
fromQName (Qual _ _ x) = fromName x
fromQName (UnQual _ x) = fromName x
fromQName (Special _ UnitCon{}) = "()"
fromQName (Special _ ListCon{}) = "[]"
fromQName (Special _ FunCon{}) = "->"
fromQName (Special _ (TupleCon _ box n)) = "(" ++ h ++ replicate n ',' ++ h ++ ")"
where h = ['#' | box == Unboxed]
fromQName (Special _ UnboxedSingleCon{}) = "(##)"
fromQName (Special _ Cons{}) = ":"
fromContext :: Context a -> [Asst a]
fromContext (CxSingle _ x) = [x]
fromContext (CxTuple _ xs) = xs
fromContext _ = []
fromIParen :: InstRule a -> InstRule a
fromIParen (IParen _ x) = fromIParen x
fromIParen x = x
fromTyVarBind :: TyVarBind a -> Name a
fromTyVarBind (KindedVar _ x _) = x
fromTyVarBind (UnkindedVar _ x) = x
fromDeclHead :: DeclHead a -> (Name a, [TyVarBind a])
fromDeclHead (DHead _ n) = (n, [])
fromDeclHead (DHInfix _ x n) = (n, [x])
fromDeclHead (DHParen _ x) = fromDeclHead x
fromDeclHead (DHApp _ dh x) = second (++[x]) $ fromDeclHead dh
fromInstHead :: InstHead a -> (QName a, [Type a])
fromInstHead (IHCon _ n) = (n, [])
fromInstHead (IHInfix _ x n) = (n, [x])
fromInstHead (IHParen _ x) = fromInstHead x
fromInstHead (IHApp _ ih x) = second (++[x]) $ fromInstHead ih
declNames :: Decl a -> [String]
declNames x = map fromName $ case x of
TypeDecl _ hd _ -> f hd
DataDecl _ _ _ hd _ _ -> f hd
GDataDecl _ _ _ hd _ _ _ -> f hd
TypeFamDecl _ hd _ _ -> f hd
DataFamDecl _ _ hd _ -> f hd
ClassDecl _ _ hd _ _ -> f hd
TypeSig _ names _ -> names
PatSynSig _ names _ _ _ _ _ -> names
_ -> []
where f x = [fst $ fromDeclHead x]
isTypeSig :: Decl a -> Bool
isTypeSig TypeSig{} = True
isTypeSig PatSynSig{} = True
isTypeSig _ = False
tarballReadFiles :: FilePath -> IO [(FilePath, LBS.ByteString)]
tarballReadFiles file = f . Tar.read . GZip.decompress <$> LBS.readFile file
where
f (Next e rest) | NormalFile body _ <- entryContent e = (entryPath e, body) : f rest
f (Next _ rest) = f rest
f Done = []
f (Fail e) = error $ "tarballReadFiles on " ++ file ++ ", " ++ show e
innerTextHTML :: String -> String
innerTextHTML ('<':xs) = innerTextHTML $ drop1 $ dropWhile (/= '>') xs
innerTextHTML (x:xs) = x : innerTextHTML xs
innerTextHTML [] = []
unHTML :: String -> String
unHTML = unescapeHTML . innerTextHTML
escapeURL :: String -> String
escapeURL = UTF8.toString . URI.urlEncode True . UTF8.fromString
isUpper1 (x:xs) = isUpper x
isUpper1 _ = False
isAlpha1 (x:xs) = isAlpha x
isAlpha1 [] = False
splitPair :: String -> String -> (String, String)
splitPair x y | (a,stripPrefix x -> Just b) <- breakOn x y = (a,b)
| otherwise = error $ "splitPair does not contain separator " ++ show x ++ " in " ++ show y
joinPair :: [a] -> ([a], [a]) -> [a]
joinPair sep (a,b) = a ++ sep ++ b
testing_, testing :: String -> IO () -> IO ()
testing_ name act = do putStr $ "Test " ++ name ++ " "; act
testing name act = do testing_ name act; putStrLn ""
testEq :: (Show a, Eq a) => a -> a -> IO ()
testEq a b | a == b = putStr "."
| otherwise = errorIO $ "Expected equal, but " ++ show a ++ " /= " ++ show b
showUTCTime :: String -> UTCTime -> String
showUTCTime = formatTime defaultTimeLocale
withs :: [(a -> r) -> r] -> ([a] -> r) -> r
withs [] act = act []
withs (f:fs) act = f $ \a -> withs fs $ \as -> act $ a:as
prettyTable :: Int -> String -> [(String, Double)] -> [String]
prettyTable dp units xs =
( padR len units ++ "\tPercent\tName") :
[ padL len (showDP dp b) ++ "\t" ++ padL 7 (showDP 1 (100 * b / tot) ++ "%") ++ "\t" ++ a
| (a,b) <- ("Total", tot) : sortOn (negate . snd) xs]
where
tot = sum $ map snd xs
len = length units `max` length (showDP dp tot)
padL n s = replicate (n - length s) ' ' ++ s
padR n s = s ++ replicate (n - length s) ' '
strict :: NFData a => IO a -> IO a
strict act = do
res <- try_ act
case res of
Left e -> do msg <- showException e; evaluate $ rnf msg; errorIO msg
Right v -> evaluate $ force v
toAverage :: a -> Average a
toAverage x = Average x 1
fromAverage :: Fractional a => Average a -> a
fromAverage (Average a b) = a / fromIntegral b
instance Num a => Semigroup (Average a) where
Average x1 x2 <> Average y1 y2 = Average (x1+y1) (x2+y2)
instance Num a => Monoid (Average a) where
mempty = Average 0 0
mappend = (<>)
data TakeSort k v = More !Int !(Map.Map k [v])
| Full !k !(Map.Map k [v])
takeSortOn :: Ord k => (a -> k) -> Int -> [a] -> [a]
takeSortOn op n xs
| n <= 0 = []
| otherwise = concatMap reverse $ Map.elems $ getMap $ foldl' add (More n Map.empty) xs
where
getMap (More _ mp) = mp
getMap (Full _ mp) = mp
add (More n mp) x = (if n <= 1 then full else More (n-1)) $ Map.insertWith (++) (op x) [x] mp
add o@(Full mx mp) x = let k = op x in if k >= mx then o else full $ Map.insertWith (++) k [x] $ delMax mp
full mp = Full (fst $ Map.findMax mp) mp
delMax mp | Just ((k,_:vs), mp) <- Map.maxViewWithKey mp = if null vs then mp else Map.insert k vs mp
See - they broke
maximumBy' :: (a -> a -> Ordering) -> [a] -> a
maximumBy' cmp = foldl1' $ \x y -> if cmp x y == GT then x else y
maximum' :: Ord a => [a] -> a
maximum' = maximumBy' compare
minimumBy' :: (a -> a -> Ordering) -> [a] -> a
minimumBy' cmp = foldl1' $ \x y -> if cmp x y == LT then x else y
minimum' :: Ord a => [a] -> a
minimum' = minimumBy' compare
hackagePackageURL :: PkgName -> URL
hackagePackageURL x = "/" ++ strUnpack x
hackageModuleURL :: ModName -> URL
hackageModuleURL x = "/docs/" ++ ghcModuleURL x
ghcModuleURL :: ModName -> URL
ghcModuleURL x = replace "." "-" (strUnpack x) ++ ".html"
hackageDeclURL :: Bool -> String -> URL
hackageDeclURL typesig x = "#" ++ (if typesig then "v" else "t") ++ ":" ++ concatMap f x
where
f x | isLegal x = [x]
| otherwise = "-" ++ show (ord x) ++ "-"
isLegal ':' = True
isLegal '_' = True
isLegal '.' = True
isLegal c = isAscii c && isAlphaNum c
trimVersion :: Int -> Version -> Version
trimVersion i v = v{versionBranch = take 3 $ versionBranch v}
parseTrailingVersion :: String -> (String, [Int])
parseTrailingVersion = (reverse *** reverse) . f . reverse
where
f xs | (ver@(_:_),sep:xs) <- span isDigit xs
, sep == '-' || sep == '.'
, (a, b) <- f xs
= (a, Prelude.read (reverse ver) : b)
f xs = (xs, [])
inRanges :: Ix a => [(a,a)] -> (a -> Bool)
inRanges xs = \x -> maybe False (`inRange` x) $ Map.lookupLE x mp
where
mp = foldl' add Map.empty xs
merge (l1,u1) (l2,u2) = (min l1 l2, max u1 u2)
overlap x1 x2 = x1 `inRange` fst x2 || x2 `inRange` fst x1
add mp x
| Just x2 <- Map.lookupLE (fst x) mp, overlap x x2 = add (Map.delete (fst x2) mp) (merge x x2)
| Just x2 <- Map.lookupGE (fst x) mp, overlap x x2 = add (Map.delete (fst x2) mp) (merge x x2)
| otherwise = uncurry Map.insert x mp
general_util_test :: IO ()
general_util_test = do
testing "General.Util.splitPair" $ do
let a === b = if a == b then putChar '.' else errorIO $ show (a,b)
splitPair ":" "module:foo:bar" === ("module","foo:bar")
do x <- try_ $ evaluate $ rnf $ splitPair "-" "module:foo"; isLeft x === True
splitPair "-" "module-" === ("module","")
testing_ "General.Util.inRanges" $ do
quickCheck $ \(x :: Int8) xs -> inRanges xs x == any (`inRange` x) xs
testing "General.Util.parseTrailingVersion" $ do
let a === b = if a == b then putChar '.' else errorIO $ show (a,b)
parseTrailingVersion "shake-0.15.2" === ("shake",[0,15,2])
parseTrailingVersion "test-of-stuff1" === ("test-of-stuff1",[])
|
caa7b433d85db96115af8582edf33cf9975aa587b7141a7fc30ac0abb3aed2be | expipiplus1/vulkan | VK_KHR_multiview.hs | {-# language CPP #-}
-- | = Name
--
-- VK_KHR_multiview - device extension
--
-- == VK_KHR_multiview
--
-- [__Name String__]
-- @VK_KHR_multiview@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
54
--
-- [__Revision__]
1
--
-- [__Extension and Version Dependencies__]
--
- Requires support for Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@ to be enabled
-- for any device-level functionality
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <-extensions/html/vkspec.html#versions-1.1-promotions Vulkan 1.1>
--
-- [__Contact__]
--
-
-- <-Docs/issues/new?body=[VK_KHR_multiview] @jeffbolznv%0A*Here describe the issue or question you have about the VK_KHR_multiview extension* >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
2016 - 10 - 28
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Interactions and External Dependencies__]
--
- Promoted to Vulkan 1.1 Core
--
-- - This extension requires
-- <-Registry/blob/master/extensions/KHR/SPV_KHR_multiview.html SPV_KHR_multiview>
--
-- - This extension provides API support for
-- < GL_EXT_multiview>
--
-- [__Contributors__]
--
- , NVIDIA
--
-- == Description
--
-- This extension has the same goal as the OpenGL ES @GL_OVR_multiview@
extension . Multiview is a rendering technique originally designed for VR
-- where it is more efficient to record a single set of commands to be
-- executed with slightly different behavior for each “view”.
--
-- It includes a concise way to declare a render pass with multiple views,
-- and gives implementations freedom to render the views in the most
-- efficient way possible. This is done with a multiview configuration
-- specified during
< -extensions/html/vkspec.html#renderpass render pass >
-- creation with the
' Vulkan . Core11.Promoted_From_VK_KHR_multiview . RenderPassMultiviewCreateInfo '
passed into ' Vulkan . Core10.Pass . RenderPassCreateInfo'::@pNext@.
--
-- This extension enables the use of the
-- <-Registry/blob/master/extensions/KHR/SPV_KHR_multiview.html SPV_KHR_multiview>
-- shader extension, which adds a new @ViewIndex@ built-in type that allows
shaders to control what to do for each view . If using GLSL there is also
-- the
-- < GL_EXT_multiview>
extension that introduces a @highp int gl_ViewIndex;@ built - in variable
-- for vertex, tessellation, geometry, and fragment shaders.
--
= = Promotion to Vulkan 1.1
--
All functionality in this extension is included in core Vulkan 1.1 , with
the suffix omitted . The original type , enum and command names are
-- still available as aliases of the core functionality.
--
-- == New Structures
--
-- - Extending
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 ' ,
' Vulkan . Core10.Device . DeviceCreateInfo ' :
--
-- - 'PhysicalDeviceMultiviewFeaturesKHR'
--
-- - Extending
' Vulkan . ' :
--
-- - 'PhysicalDeviceMultiviewPropertiesKHR'
--
- Extending ' Vulkan . Core10.Pass . RenderPassCreateInfo ' :
--
-- - 'RenderPassMultiviewCreateInfoKHR'
--
-- == New Enum Constants
--
-- - 'KHR_MULTIVIEW_EXTENSION_NAME'
--
- ' '
--
-- - Extending
' Vulkan . Core10.Enums . DependencyFlagBits . DependencyFlagBits ' :
--
- ' '
--
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
--
- ' '
--
- ' '
--
- ' STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR '
--
-- == New Built-In Variables
--
-- - <-extensions/html/vkspec.html#interfaces-builtin-variables-viewindex ViewIndex>
--
-- == New SPIR-V Capabilities
--
-- - <-extensions/html/vkspec.html#spirvenv-capabilities-table-MultiView MultiView>
--
-- == Version History
--
- Revision 1 , 2016 - 10 - 28 ( )
--
-- - Internal revisions
--
-- == See Also
--
-- 'PhysicalDeviceMultiviewFeaturesKHR',
-- 'PhysicalDeviceMultiviewPropertiesKHR',
-- 'RenderPassMultiviewCreateInfoKHR'
--
-- == Document Notes
--
-- For more information, see the
-- <-extensions/html/vkspec.html#VK_KHR_multiview Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_KHR_multiview ( pattern STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR
, pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHR
, pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHR
, pattern DEPENDENCY_VIEW_LOCAL_BIT_KHR
, PhysicalDeviceMultiviewFeaturesKHR
, PhysicalDeviceMultiviewPropertiesKHR
, RenderPassMultiviewCreateInfoKHR
, KHR_MULTIVIEW_SPEC_VERSION
, pattern KHR_MULTIVIEW_SPEC_VERSION
, KHR_MULTIVIEW_EXTENSION_NAME
, pattern KHR_MULTIVIEW_EXTENSION_NAME
) where
import Data.String (IsString)
import Vulkan.Core11.Promoted_From_VK_KHR_multiview (PhysicalDeviceMultiviewFeatures)
import Vulkan.Core11.Promoted_From_VK_KHR_multiview (PhysicalDeviceMultiviewProperties)
import Vulkan.Core11.Promoted_From_VK_KHR_multiview (RenderPassMultiviewCreateInfo)
import Vulkan.Core10.Enums.DependencyFlagBits (DependencyFlags)
import Vulkan.Core10.Enums.DependencyFlagBits (DependencyFlagBits(DEPENDENCY_VIEW_LOCAL_BIT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO))
No documentation found for TopLevel " VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR "
pattern STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR = STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO
No documentation found for TopLevel " "
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES
No documentation found for TopLevel " VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHR "
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES
No documentation found for TopLevel " VK_DEPENDENCY_VIEW_LOCAL_BIT_KHR "
pattern DEPENDENCY_VIEW_LOCAL_BIT_KHR = DEPENDENCY_VIEW_LOCAL_BIT
No documentation found for TopLevel " VkPhysicalDeviceMultiviewFeaturesKHR "
type PhysicalDeviceMultiviewFeaturesKHR = PhysicalDeviceMultiviewFeatures
No documentation found for TopLevel " VkPhysicalDeviceMultiviewPropertiesKHR "
type PhysicalDeviceMultiviewPropertiesKHR = PhysicalDeviceMultiviewProperties
No documentation found for TopLevel " VkRenderPassMultiviewCreateInfoKHR "
type RenderPassMultiviewCreateInfoKHR = RenderPassMultiviewCreateInfo
type KHR_MULTIVIEW_SPEC_VERSION = 1
No documentation found for TopLevel " VK_KHR_MULTIVIEW_SPEC_VERSION "
pattern KHR_MULTIVIEW_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_MULTIVIEW_SPEC_VERSION = 1
type KHR_MULTIVIEW_EXTENSION_NAME = "VK_KHR_multiview"
No documentation found for TopLevel " VK_KHR_MULTIVIEW_EXTENSION_NAME "
pattern KHR_MULTIVIEW_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_MULTIVIEW_EXTENSION_NAME = "VK_KHR_multiview"
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/src/Vulkan/Extensions/VK_KHR_multiview.hs | haskell | # language CPP #
| = Name
VK_KHR_multiview - device extension
== VK_KHR_multiview
[__Name String__]
@VK_KHR_multiview@
[__Extension Type__]
Device extension
[__Registered Extension Number__]
[__Revision__]
[__Extension and Version Dependencies__]
- Requires @VK_KHR_get_physical_device_properties2@ to be enabled
for any device-level functionality
[__Deprecation state__]
- /Promoted/ to
<-extensions/html/vkspec.html#versions-1.1-promotions Vulkan 1.1>
[__Contact__]
<-Docs/issues/new?body=[VK_KHR_multiview] @jeffbolznv%0A*Here describe the issue or question you have about the VK_KHR_multiview extension* >
== Other Extension Metadata
[__Last Modified Date__]
[__IP Status__]
No known IP claims.
[__Interactions and External Dependencies__]
- This extension requires
<-Registry/blob/master/extensions/KHR/SPV_KHR_multiview.html SPV_KHR_multiview>
- This extension provides API support for
< GL_EXT_multiview>
[__Contributors__]
== Description
This extension has the same goal as the OpenGL ES @GL_OVR_multiview@
where it is more efficient to record a single set of commands to be
executed with slightly different behavior for each “view”.
It includes a concise way to declare a render pass with multiple views,
and gives implementations freedom to render the views in the most
efficient way possible. This is done with a multiview configuration
specified during
creation with the
This extension enables the use of the
<-Registry/blob/master/extensions/KHR/SPV_KHR_multiview.html SPV_KHR_multiview>
shader extension, which adds a new @ViewIndex@ built-in type that allows
the
< GL_EXT_multiview>
for vertex, tessellation, geometry, and fragment shaders.
still available as aliases of the core functionality.
== New Structures
- Extending
- 'PhysicalDeviceMultiviewFeaturesKHR'
- Extending
- 'PhysicalDeviceMultiviewPropertiesKHR'
- 'RenderPassMultiviewCreateInfoKHR'
== New Enum Constants
- 'KHR_MULTIVIEW_EXTENSION_NAME'
- Extending
== New Built-In Variables
- <-extensions/html/vkspec.html#interfaces-builtin-variables-viewindex ViewIndex>
== New SPIR-V Capabilities
- <-extensions/html/vkspec.html#spirvenv-capabilities-table-MultiView MultiView>
== Version History
- Internal revisions
== See Also
'PhysicalDeviceMultiviewFeaturesKHR',
'PhysicalDeviceMultiviewPropertiesKHR',
'RenderPassMultiviewCreateInfoKHR'
== Document Notes
For more information, see the
<-extensions/html/vkspec.html#VK_KHR_multiview Vulkan Specification>
This page is a generated document. Fixes and changes should be made to
the generator scripts, not directly. | 54
1
- Requires support for Vulkan 1.0
-
2016 - 10 - 28
- Promoted to Vulkan 1.1 Core
- , NVIDIA
extension . Multiview is a rendering technique originally designed for VR
< -extensions/html/vkspec.html#renderpass render pass >
' Vulkan . Core11.Promoted_From_VK_KHR_multiview . RenderPassMultiviewCreateInfo '
passed into ' Vulkan . Core10.Pass . RenderPassCreateInfo'::@pNext@.
shaders to control what to do for each view . If using GLSL there is also
extension that introduces a @highp int gl_ViewIndex;@ built - in variable
= = Promotion to Vulkan 1.1
All functionality in this extension is included in core Vulkan 1.1 , with
the suffix omitted . The original type , enum and command names are
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 ' ,
' Vulkan . Core10.Device . DeviceCreateInfo ' :
' Vulkan . ' :
- Extending ' Vulkan . Core10.Pass . RenderPassCreateInfo ' :
- ' '
' Vulkan . Core10.Enums . DependencyFlagBits . DependencyFlagBits ' :
- ' '
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
- ' '
- ' '
- ' STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR '
- Revision 1 , 2016 - 10 - 28 ( )
module Vulkan.Extensions.VK_KHR_multiview ( pattern STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR
, pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHR
, pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHR
, pattern DEPENDENCY_VIEW_LOCAL_BIT_KHR
, PhysicalDeviceMultiviewFeaturesKHR
, PhysicalDeviceMultiviewPropertiesKHR
, RenderPassMultiviewCreateInfoKHR
, KHR_MULTIVIEW_SPEC_VERSION
, pattern KHR_MULTIVIEW_SPEC_VERSION
, KHR_MULTIVIEW_EXTENSION_NAME
, pattern KHR_MULTIVIEW_EXTENSION_NAME
) where
import Data.String (IsString)
import Vulkan.Core11.Promoted_From_VK_KHR_multiview (PhysicalDeviceMultiviewFeatures)
import Vulkan.Core11.Promoted_From_VK_KHR_multiview (PhysicalDeviceMultiviewProperties)
import Vulkan.Core11.Promoted_From_VK_KHR_multiview (RenderPassMultiviewCreateInfo)
import Vulkan.Core10.Enums.DependencyFlagBits (DependencyFlags)
import Vulkan.Core10.Enums.DependencyFlagBits (DependencyFlagBits(DEPENDENCY_VIEW_LOCAL_BIT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO))
No documentation found for TopLevel " VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR "
pattern STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR = STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO
No documentation found for TopLevel " "
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES
No documentation found for TopLevel " VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHR "
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES
No documentation found for TopLevel " VK_DEPENDENCY_VIEW_LOCAL_BIT_KHR "
pattern DEPENDENCY_VIEW_LOCAL_BIT_KHR = DEPENDENCY_VIEW_LOCAL_BIT
No documentation found for TopLevel " VkPhysicalDeviceMultiviewFeaturesKHR "
type PhysicalDeviceMultiviewFeaturesKHR = PhysicalDeviceMultiviewFeatures
No documentation found for TopLevel " VkPhysicalDeviceMultiviewPropertiesKHR "
type PhysicalDeviceMultiviewPropertiesKHR = PhysicalDeviceMultiviewProperties
No documentation found for TopLevel " VkRenderPassMultiviewCreateInfoKHR "
type RenderPassMultiviewCreateInfoKHR = RenderPassMultiviewCreateInfo
type KHR_MULTIVIEW_SPEC_VERSION = 1
No documentation found for TopLevel " VK_KHR_MULTIVIEW_SPEC_VERSION "
pattern KHR_MULTIVIEW_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_MULTIVIEW_SPEC_VERSION = 1
type KHR_MULTIVIEW_EXTENSION_NAME = "VK_KHR_multiview"
No documentation found for TopLevel " VK_KHR_MULTIVIEW_EXTENSION_NAME "
pattern KHR_MULTIVIEW_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_MULTIVIEW_EXTENSION_NAME = "VK_KHR_multiview"
|
316506a347806091b08b664d8a6839e51cda52fd5f1ec1b8a3cf9137d429983a | ghcjs/ghcjs-dom | ApplePaySession.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
module GHCJS.DOM.JSFFI.Generated.ApplePaySession
(js_newApplePaySession, newApplePaySession, js_supportsVersion,
supportsVersion, supportsVersion_, js_canMakePayments,
canMakePayments, canMakePayments_,
js_canMakePaymentsWithActiveCard, canMakePaymentsWithActiveCard,
canMakePaymentsWithActiveCard_, js_openPaymentSetup,
openPaymentSetup, openPaymentSetup_, js_begin, begin, js_abort,
abort, js_completeMerchantValidation, completeMerchantValidation,
js_completeShippingMethodSelectionUpdate,
completeShippingMethodSelectionUpdate,
js_completeShippingContactSelectionUpdate,
completeShippingContactSelectionUpdate,
js_completePaymentMethodSelectionUpdate,
completePaymentMethodSelectionUpdate, js_completePaymentResult,
completePaymentResult, js_completeShippingMethodSelection,
completeShippingMethodSelection,
js_completeShippingContactSelection,
completeShippingContactSelection,
js_completePaymentMethodSelection, completePaymentMethodSelection,
js_completePayment, completePayment, pattern STATUS_SUCCESS,
pattern STATUS_FAILURE,
pattern STATUS_INVALID_BILLING_POSTAL_ADDRESS,
pattern STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
pattern STATUS_INVALID_SHIPPING_CONTACT,
pattern STATUS_PIN_REQUIRED, pattern STATUS_PIN_INCORRECT,
pattern STATUS_PIN_LOCKOUT, validatemerchant,
paymentmethodselected, paymentauthorized, shippingmethodselected,
shippingcontactselected, cancel, ApplePaySession(..),
gTypeApplePaySession)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript safe
"new window[\"ApplePaySession\"]($1,\n$2)" js_newApplePaySession ::
Word -> ApplePayPaymentRequest -> IO ApplePaySession
| < -US/docs/Web/API/ApplePaySession Mozilla ApplePaySession documentation >
newApplePaySession ::
(MonadIO m) => Word -> ApplePayPaymentRequest -> m ApplePaySession
newApplePaySession version paymentRequest
= liftIO (js_newApplePaySession version paymentRequest)
foreign import javascript safe
"(window[\"ApplePaySession\"][\"supportsVersion\"]($1) ? 1 : 0)"
js_supportsVersion :: Word -> IO Bool
| < -US/docs/Web/API/ApplePaySession.supportsVersion Mozilla ApplePaySession.supportsVersion documentation >
supportsVersion :: (MonadIO m) => Word -> m Bool
supportsVersion version = liftIO (js_supportsVersion version)
| < -US/docs/Web/API/ApplePaySession.supportsVersion Mozilla ApplePaySession.supportsVersion documentation >
supportsVersion_ :: (MonadIO m) => Word -> m ()
supportsVersion_ version
= liftIO (void (js_supportsVersion version))
foreign import javascript safe
"(window[\"ApplePaySession\"][\"canMakePayments\"]() ? 1 : 0)"
js_canMakePayments :: IO Bool
| < -US/docs/Web/API/ApplePaySession.canMakePayments Mozilla ApplePaySession.canMakePayments documentation >
canMakePayments :: (MonadIO m) => m Bool
canMakePayments = liftIO (js_canMakePayments)
| < -US/docs/Web/API/ApplePaySession.canMakePayments Mozilla ApplePaySession.canMakePayments documentation >
canMakePayments_ :: (MonadIO m) => m ()
canMakePayments_ = liftIO (void (js_canMakePayments))
foreign import javascript interruptible
"window[\"ApplePaySession\"][\"canMakePaymentsWithActiveCard\"]($1).then(function(s) { $c(null, s);}, function(e) { $c(e, null);});"
js_canMakePaymentsWithActiveCard :: JSString -> IO (JSVal, Bool)
-- | <-US/docs/Web/API/ApplePaySession.canMakePaymentsWithActiveCard Mozilla ApplePaySession.canMakePaymentsWithActiveCard documentation>
canMakePaymentsWithActiveCard ::
(MonadIO m, ToJSString merchantIdentifier) =>
merchantIdentifier -> m Bool
canMakePaymentsWithActiveCard merchantIdentifier
= liftIO
((js_canMakePaymentsWithActiveCard (toJSString merchantIdentifier))
>>= checkPromiseResult)
-- | <-US/docs/Web/API/ApplePaySession.canMakePaymentsWithActiveCard Mozilla ApplePaySession.canMakePaymentsWithActiveCard documentation>
canMakePaymentsWithActiveCard_ ::
(MonadIO m, ToJSString merchantIdentifier) =>
merchantIdentifier -> m ()
canMakePaymentsWithActiveCard_ merchantIdentifier
= liftIO
(void
(js_canMakePaymentsWithActiveCard (toJSString merchantIdentifier)))
foreign import javascript interruptible
"window[\"ApplePaySession\"][\"openPaymentSetup\"]($1).then(function(s) { $c(null, s);}, function(e) { $c(e, null);});"
js_openPaymentSetup :: JSString -> IO (JSVal, Bool)
| < -US/docs/Web/API/ApplePaySession.openPaymentSetup Mozilla ApplePaySession.openPaymentSetup documentation >
openPaymentSetup ::
(MonadIO m, ToJSString merchantIdentifier) =>
merchantIdentifier -> m Bool
openPaymentSetup merchantIdentifier
= liftIO
((js_openPaymentSetup (toJSString merchantIdentifier)) >>=
checkPromiseResult)
| < -US/docs/Web/API/ApplePaySession.openPaymentSetup Mozilla ApplePaySession.openPaymentSetup documentation >
openPaymentSetup_ ::
(MonadIO m, ToJSString merchantIdentifier) =>
merchantIdentifier -> m ()
openPaymentSetup_ merchantIdentifier
= liftIO
(void (js_openPaymentSetup (toJSString merchantIdentifier)))
foreign import javascript safe "$1[\"begin\"]()" js_begin ::
ApplePaySession -> IO ()
| < -US/docs/Web/API/ApplePaySession.begin Mozilla ApplePaySession.begin documentation >
begin :: (MonadIO m) => ApplePaySession -> m ()
begin self = liftIO (js_begin self)
foreign import javascript safe "$1[\"abort\"]()" js_abort ::
ApplePaySession -> IO ()
| < -US/docs/Web/API/ApplePaySession.abort Mozilla ApplePaySession.abort documentation >
abort :: (MonadIO m) => ApplePaySession -> m ()
abort self = liftIO (js_abort self)
foreign import javascript safe
"$1[\"completeMerchantValidation\"]($2)"
js_completeMerchantValidation :: ApplePaySession -> JSVal -> IO ()
| < -US/docs/Web/API/ApplePaySession.completeMerchantValidation Mozilla ApplePaySession.completeMerchantValidation documentation >
completeMerchantValidation ::
(MonadIO m, ToJSVal merchantSession) =>
ApplePaySession -> merchantSession -> m ()
completeMerchantValidation self merchantSession
= liftIO
(toJSVal merchantSession >>=
\ merchantSession' ->
js_completeMerchantValidation self merchantSession')
foreign import javascript safe
"$1[\"completeShippingMethodSelection\"]($2)"
js_completeShippingMethodSelectionUpdate ::
ApplePaySession -> ApplePayShippingMethodUpdate -> IO ()
| < -US/docs/Web/API/ApplePaySession.completeShippingMethodSelection Mozilla ApplePaySession.completeShippingMethodSelection documentation >
completeShippingMethodSelectionUpdate ::
(MonadIO m) =>
ApplePaySession -> ApplePayShippingMethodUpdate -> m ()
completeShippingMethodSelectionUpdate self update
= liftIO (js_completeShippingMethodSelectionUpdate self update)
foreign import javascript safe
"$1[\"completeShippingContactSelection\"]($2)"
js_completeShippingContactSelectionUpdate ::
ApplePaySession -> ApplePayShippingContactUpdate -> IO ()
-- | <-US/docs/Web/API/ApplePaySession.completeShippingContactSelection Mozilla ApplePaySession.completeShippingContactSelection documentation>
completeShippingContactSelectionUpdate ::
(MonadIO m) =>
ApplePaySession -> ApplePayShippingContactUpdate -> m ()
completeShippingContactSelectionUpdate self update
= liftIO (js_completeShippingContactSelectionUpdate self update)
foreign import javascript safe
"$1[\"completePaymentMethodSelection\"]($2)"
js_completePaymentMethodSelectionUpdate ::
ApplePaySession -> ApplePayPaymentMethodUpdate -> IO ()
| < -US/docs/Web/API/ApplePaySession.completePaymentMethodSelection Mozilla ApplePaySession.completePaymentMethodSelection documentation >
completePaymentMethodSelectionUpdate ::
(MonadIO m) =>
ApplePaySession -> ApplePayPaymentMethodUpdate -> m ()
completePaymentMethodSelectionUpdate self update
= liftIO (js_completePaymentMethodSelectionUpdate self update)
foreign import javascript safe "$1[\"completePayment\"]($2)"
js_completePaymentResult ::
ApplePaySession -> ApplePayPaymentAuthorizationResult -> IO ()
| < -US/docs/Web/API/ApplePaySession.completePayment Mozilla ApplePaySession.completePayment documentation >
completePaymentResult ::
(MonadIO m) =>
ApplePaySession -> ApplePayPaymentAuthorizationResult -> m ()
completePaymentResult self result
= liftIO (js_completePaymentResult self result)
foreign import javascript safe
"$1[\"completeShippingMethodSelection\"]($2,\n$3, $4)"
js_completeShippingMethodSelection ::
ApplePaySession -> Word -> ApplePayLineItem -> JSVal -> IO ()
| < -US/docs/Web/API/ApplePaySession.completeShippingMethodSelection Mozilla ApplePaySession.completeShippingMethodSelection documentation >
completeShippingMethodSelection ::
(MonadIO m) =>
ApplePaySession ->
Word -> ApplePayLineItem -> [ApplePayLineItem] -> m ()
completeShippingMethodSelection self status newTotal newLineItems
= liftIO
(toJSVal newLineItems >>=
\ newLineItems' ->
js_completeShippingMethodSelection self status newTotal
newLineItems')
foreign import javascript safe
"$1[\"completeShippingContactSelection\"]($2,\n$3, $4, $5)"
js_completeShippingContactSelection ::
ApplePaySession ->
Word -> JSVal -> ApplePayLineItem -> JSVal -> IO ()
-- | <-US/docs/Web/API/ApplePaySession.completeShippingContactSelection Mozilla ApplePaySession.completeShippingContactSelection documentation>
completeShippingContactSelection ::
(MonadIO m) =>
ApplePaySession ->
Word ->
[ApplePayShippingMethod] ->
ApplePayLineItem -> [ApplePayLineItem] -> m ()
completeShippingContactSelection self status newShippingMethods
newTotal newLineItems
= liftIO
(toJSVal newLineItems >>=
\ newLineItems' ->
toJSVal newShippingMethods >>=
\ newShippingMethods' ->
js_completeShippingContactSelection self status newShippingMethods'
newTotal
newLineItems')
foreign import javascript safe
"$1[\"completePaymentMethodSelection\"]($2,\n$3)"
js_completePaymentMethodSelection ::
ApplePaySession -> ApplePayLineItem -> JSVal -> IO ()
| < -US/docs/Web/API/ApplePaySession.completePaymentMethodSelection Mozilla ApplePaySession.completePaymentMethodSelection documentation >
completePaymentMethodSelection ::
(MonadIO m) =>
ApplePaySession -> ApplePayLineItem -> [ApplePayLineItem] -> m ()
completePaymentMethodSelection self newTotal newLineItems
= liftIO
(toJSVal newLineItems >>=
\ newLineItems' ->
js_completePaymentMethodSelection self newTotal newLineItems')
foreign import javascript safe "$1[\"completePayment\"]($2)"
js_completePayment :: ApplePaySession -> Word -> IO ()
| < -US/docs/Web/API/ApplePaySession.completePayment Mozilla ApplePaySession.completePayment documentation >
completePayment :: (MonadIO m) => ApplePaySession -> Word -> m ()
completePayment self status
= liftIO (js_completePayment self status)
pattern STATUS_SUCCESS = 0
pattern STATUS_FAILURE = 1
pattern STATUS_INVALID_BILLING_POSTAL_ADDRESS = 2
pattern STATUS_INVALID_SHIPPING_POSTAL_ADDRESS = 3
pattern STATUS_INVALID_SHIPPING_CONTACT = 4
pattern STATUS_PIN_REQUIRED = 5
pattern STATUS_PIN_INCORRECT = 6
pattern STATUS_PIN_LOCKOUT = 7
| < -US/docs/Web/API/ApplePaySession.onvalidatemerchant Mozilla ApplePaySession.onvalidatemerchant documentation >
validatemerchant :: EventName ApplePaySession onvalidatemerchant
validatemerchant = unsafeEventName (toJSString "validatemerchant")
| < -US/docs/Web/API/ApplePaySession.onpaymentmethodselected Mozilla ApplePaySession.onpaymentmethodselected documentation >
paymentmethodselected ::
EventName ApplePaySession onpaymentmethodselected
paymentmethodselected
= unsafeEventName (toJSString "paymentmethodselected")
| < -US/docs/Web/API/ApplePaySession.onpaymentauthorized Mozilla ApplePaySession.onpaymentauthorized documentation >
paymentauthorized :: EventName ApplePaySession onpaymentauthorized
paymentauthorized
= unsafeEventName (toJSString "paymentauthorized")
| < -US/docs/Web/API/ApplePaySession.onshippingmethodselected Mozilla ApplePaySession.onshippingmethodselected documentation >
shippingmethodselected ::
EventName ApplePaySession onshippingmethodselected
shippingmethodselected
= unsafeEventName (toJSString "shippingmethodselected")
| < -US/docs/Web/API/ApplePaySession.onshippingcontactselected Mozilla ApplePaySession.onshippingcontactselected documentation >
shippingcontactselected ::
EventName ApplePaySession onshippingcontactselected
shippingcontactselected
= unsafeEventName (toJSString "shippingcontactselected")
-- | <-US/docs/Web/API/ApplePaySession.oncancel Mozilla ApplePaySession.oncancel documentation>
cancel :: EventName ApplePaySession oncancel
cancel = unsafeEventName (toJSString "cancel") | null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/ApplePaySession.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
| <-US/docs/Web/API/ApplePaySession.canMakePaymentsWithActiveCard Mozilla ApplePaySession.canMakePaymentsWithActiveCard documentation>
| <-US/docs/Web/API/ApplePaySession.canMakePaymentsWithActiveCard Mozilla ApplePaySession.canMakePaymentsWithActiveCard documentation>
| <-US/docs/Web/API/ApplePaySession.completeShippingContactSelection Mozilla ApplePaySession.completeShippingContactSelection documentation>
| <-US/docs/Web/API/ApplePaySession.completeShippingContactSelection Mozilla ApplePaySession.completeShippingContactSelection documentation>
| <-US/docs/Web/API/ApplePaySession.oncancel Mozilla ApplePaySession.oncancel documentation> | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.Generated.ApplePaySession
(js_newApplePaySession, newApplePaySession, js_supportsVersion,
supportsVersion, supportsVersion_, js_canMakePayments,
canMakePayments, canMakePayments_,
js_canMakePaymentsWithActiveCard, canMakePaymentsWithActiveCard,
canMakePaymentsWithActiveCard_, js_openPaymentSetup,
openPaymentSetup, openPaymentSetup_, js_begin, begin, js_abort,
abort, js_completeMerchantValidation, completeMerchantValidation,
js_completeShippingMethodSelectionUpdate,
completeShippingMethodSelectionUpdate,
js_completeShippingContactSelectionUpdate,
completeShippingContactSelectionUpdate,
js_completePaymentMethodSelectionUpdate,
completePaymentMethodSelectionUpdate, js_completePaymentResult,
completePaymentResult, js_completeShippingMethodSelection,
completeShippingMethodSelection,
js_completeShippingContactSelection,
completeShippingContactSelection,
js_completePaymentMethodSelection, completePaymentMethodSelection,
js_completePayment, completePayment, pattern STATUS_SUCCESS,
pattern STATUS_FAILURE,
pattern STATUS_INVALID_BILLING_POSTAL_ADDRESS,
pattern STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
pattern STATUS_INVALID_SHIPPING_CONTACT,
pattern STATUS_PIN_REQUIRED, pattern STATUS_PIN_INCORRECT,
pattern STATUS_PIN_LOCKOUT, validatemerchant,
paymentmethodselected, paymentauthorized, shippingmethodselected,
shippingcontactselected, cancel, ApplePaySession(..),
gTypeApplePaySession)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript safe
"new window[\"ApplePaySession\"]($1,\n$2)" js_newApplePaySession ::
Word -> ApplePayPaymentRequest -> IO ApplePaySession
| < -US/docs/Web/API/ApplePaySession Mozilla ApplePaySession documentation >
newApplePaySession ::
(MonadIO m) => Word -> ApplePayPaymentRequest -> m ApplePaySession
newApplePaySession version paymentRequest
= liftIO (js_newApplePaySession version paymentRequest)
foreign import javascript safe
"(window[\"ApplePaySession\"][\"supportsVersion\"]($1) ? 1 : 0)"
js_supportsVersion :: Word -> IO Bool
| < -US/docs/Web/API/ApplePaySession.supportsVersion Mozilla ApplePaySession.supportsVersion documentation >
supportsVersion :: (MonadIO m) => Word -> m Bool
supportsVersion version = liftIO (js_supportsVersion version)
| < -US/docs/Web/API/ApplePaySession.supportsVersion Mozilla ApplePaySession.supportsVersion documentation >
supportsVersion_ :: (MonadIO m) => Word -> m ()
supportsVersion_ version
= liftIO (void (js_supportsVersion version))
foreign import javascript safe
"(window[\"ApplePaySession\"][\"canMakePayments\"]() ? 1 : 0)"
js_canMakePayments :: IO Bool
| < -US/docs/Web/API/ApplePaySession.canMakePayments Mozilla ApplePaySession.canMakePayments documentation >
canMakePayments :: (MonadIO m) => m Bool
canMakePayments = liftIO (js_canMakePayments)
| < -US/docs/Web/API/ApplePaySession.canMakePayments Mozilla ApplePaySession.canMakePayments documentation >
canMakePayments_ :: (MonadIO m) => m ()
canMakePayments_ = liftIO (void (js_canMakePayments))
foreign import javascript interruptible
"window[\"ApplePaySession\"][\"canMakePaymentsWithActiveCard\"]($1).then(function(s) { $c(null, s);}, function(e) { $c(e, null);});"
js_canMakePaymentsWithActiveCard :: JSString -> IO (JSVal, Bool)
canMakePaymentsWithActiveCard ::
(MonadIO m, ToJSString merchantIdentifier) =>
merchantIdentifier -> m Bool
canMakePaymentsWithActiveCard merchantIdentifier
= liftIO
((js_canMakePaymentsWithActiveCard (toJSString merchantIdentifier))
>>= checkPromiseResult)
canMakePaymentsWithActiveCard_ ::
(MonadIO m, ToJSString merchantIdentifier) =>
merchantIdentifier -> m ()
canMakePaymentsWithActiveCard_ merchantIdentifier
= liftIO
(void
(js_canMakePaymentsWithActiveCard (toJSString merchantIdentifier)))
foreign import javascript interruptible
"window[\"ApplePaySession\"][\"openPaymentSetup\"]($1).then(function(s) { $c(null, s);}, function(e) { $c(e, null);});"
js_openPaymentSetup :: JSString -> IO (JSVal, Bool)
| < -US/docs/Web/API/ApplePaySession.openPaymentSetup Mozilla ApplePaySession.openPaymentSetup documentation >
openPaymentSetup ::
(MonadIO m, ToJSString merchantIdentifier) =>
merchantIdentifier -> m Bool
openPaymentSetup merchantIdentifier
= liftIO
((js_openPaymentSetup (toJSString merchantIdentifier)) >>=
checkPromiseResult)
| < -US/docs/Web/API/ApplePaySession.openPaymentSetup Mozilla ApplePaySession.openPaymentSetup documentation >
openPaymentSetup_ ::
(MonadIO m, ToJSString merchantIdentifier) =>
merchantIdentifier -> m ()
openPaymentSetup_ merchantIdentifier
= liftIO
(void (js_openPaymentSetup (toJSString merchantIdentifier)))
foreign import javascript safe "$1[\"begin\"]()" js_begin ::
ApplePaySession -> IO ()
| < -US/docs/Web/API/ApplePaySession.begin Mozilla ApplePaySession.begin documentation >
begin :: (MonadIO m) => ApplePaySession -> m ()
begin self = liftIO (js_begin self)
foreign import javascript safe "$1[\"abort\"]()" js_abort ::
ApplePaySession -> IO ()
| < -US/docs/Web/API/ApplePaySession.abort Mozilla ApplePaySession.abort documentation >
abort :: (MonadIO m) => ApplePaySession -> m ()
abort self = liftIO (js_abort self)
foreign import javascript safe
"$1[\"completeMerchantValidation\"]($2)"
js_completeMerchantValidation :: ApplePaySession -> JSVal -> IO ()
| < -US/docs/Web/API/ApplePaySession.completeMerchantValidation Mozilla ApplePaySession.completeMerchantValidation documentation >
completeMerchantValidation ::
(MonadIO m, ToJSVal merchantSession) =>
ApplePaySession -> merchantSession -> m ()
completeMerchantValidation self merchantSession
= liftIO
(toJSVal merchantSession >>=
\ merchantSession' ->
js_completeMerchantValidation self merchantSession')
foreign import javascript safe
"$1[\"completeShippingMethodSelection\"]($2)"
js_completeShippingMethodSelectionUpdate ::
ApplePaySession -> ApplePayShippingMethodUpdate -> IO ()
| < -US/docs/Web/API/ApplePaySession.completeShippingMethodSelection Mozilla ApplePaySession.completeShippingMethodSelection documentation >
completeShippingMethodSelectionUpdate ::
(MonadIO m) =>
ApplePaySession -> ApplePayShippingMethodUpdate -> m ()
completeShippingMethodSelectionUpdate self update
= liftIO (js_completeShippingMethodSelectionUpdate self update)
foreign import javascript safe
"$1[\"completeShippingContactSelection\"]($2)"
js_completeShippingContactSelectionUpdate ::
ApplePaySession -> ApplePayShippingContactUpdate -> IO ()
completeShippingContactSelectionUpdate ::
(MonadIO m) =>
ApplePaySession -> ApplePayShippingContactUpdate -> m ()
completeShippingContactSelectionUpdate self update
= liftIO (js_completeShippingContactSelectionUpdate self update)
foreign import javascript safe
"$1[\"completePaymentMethodSelection\"]($2)"
js_completePaymentMethodSelectionUpdate ::
ApplePaySession -> ApplePayPaymentMethodUpdate -> IO ()
| < -US/docs/Web/API/ApplePaySession.completePaymentMethodSelection Mozilla ApplePaySession.completePaymentMethodSelection documentation >
completePaymentMethodSelectionUpdate ::
(MonadIO m) =>
ApplePaySession -> ApplePayPaymentMethodUpdate -> m ()
completePaymentMethodSelectionUpdate self update
= liftIO (js_completePaymentMethodSelectionUpdate self update)
foreign import javascript safe "$1[\"completePayment\"]($2)"
js_completePaymentResult ::
ApplePaySession -> ApplePayPaymentAuthorizationResult -> IO ()
| < -US/docs/Web/API/ApplePaySession.completePayment Mozilla ApplePaySession.completePayment documentation >
completePaymentResult ::
(MonadIO m) =>
ApplePaySession -> ApplePayPaymentAuthorizationResult -> m ()
completePaymentResult self result
= liftIO (js_completePaymentResult self result)
foreign import javascript safe
"$1[\"completeShippingMethodSelection\"]($2,\n$3, $4)"
js_completeShippingMethodSelection ::
ApplePaySession -> Word -> ApplePayLineItem -> JSVal -> IO ()
| < -US/docs/Web/API/ApplePaySession.completeShippingMethodSelection Mozilla ApplePaySession.completeShippingMethodSelection documentation >
completeShippingMethodSelection ::
(MonadIO m) =>
ApplePaySession ->
Word -> ApplePayLineItem -> [ApplePayLineItem] -> m ()
completeShippingMethodSelection self status newTotal newLineItems
= liftIO
(toJSVal newLineItems >>=
\ newLineItems' ->
js_completeShippingMethodSelection self status newTotal
newLineItems')
foreign import javascript safe
"$1[\"completeShippingContactSelection\"]($2,\n$3, $4, $5)"
js_completeShippingContactSelection ::
ApplePaySession ->
Word -> JSVal -> ApplePayLineItem -> JSVal -> IO ()
completeShippingContactSelection ::
(MonadIO m) =>
ApplePaySession ->
Word ->
[ApplePayShippingMethod] ->
ApplePayLineItem -> [ApplePayLineItem] -> m ()
completeShippingContactSelection self status newShippingMethods
newTotal newLineItems
= liftIO
(toJSVal newLineItems >>=
\ newLineItems' ->
toJSVal newShippingMethods >>=
\ newShippingMethods' ->
js_completeShippingContactSelection self status newShippingMethods'
newTotal
newLineItems')
foreign import javascript safe
"$1[\"completePaymentMethodSelection\"]($2,\n$3)"
js_completePaymentMethodSelection ::
ApplePaySession -> ApplePayLineItem -> JSVal -> IO ()
| < -US/docs/Web/API/ApplePaySession.completePaymentMethodSelection Mozilla ApplePaySession.completePaymentMethodSelection documentation >
completePaymentMethodSelection ::
(MonadIO m) =>
ApplePaySession -> ApplePayLineItem -> [ApplePayLineItem] -> m ()
completePaymentMethodSelection self newTotal newLineItems
= liftIO
(toJSVal newLineItems >>=
\ newLineItems' ->
js_completePaymentMethodSelection self newTotal newLineItems')
foreign import javascript safe "$1[\"completePayment\"]($2)"
js_completePayment :: ApplePaySession -> Word -> IO ()
| < -US/docs/Web/API/ApplePaySession.completePayment Mozilla ApplePaySession.completePayment documentation >
completePayment :: (MonadIO m) => ApplePaySession -> Word -> m ()
completePayment self status
= liftIO (js_completePayment self status)
pattern STATUS_SUCCESS = 0
pattern STATUS_FAILURE = 1
pattern STATUS_INVALID_BILLING_POSTAL_ADDRESS = 2
pattern STATUS_INVALID_SHIPPING_POSTAL_ADDRESS = 3
pattern STATUS_INVALID_SHIPPING_CONTACT = 4
pattern STATUS_PIN_REQUIRED = 5
pattern STATUS_PIN_INCORRECT = 6
pattern STATUS_PIN_LOCKOUT = 7
| < -US/docs/Web/API/ApplePaySession.onvalidatemerchant Mozilla ApplePaySession.onvalidatemerchant documentation >
validatemerchant :: EventName ApplePaySession onvalidatemerchant
validatemerchant = unsafeEventName (toJSString "validatemerchant")
| < -US/docs/Web/API/ApplePaySession.onpaymentmethodselected Mozilla ApplePaySession.onpaymentmethodselected documentation >
paymentmethodselected ::
EventName ApplePaySession onpaymentmethodselected
paymentmethodselected
= unsafeEventName (toJSString "paymentmethodselected")
| < -US/docs/Web/API/ApplePaySession.onpaymentauthorized Mozilla ApplePaySession.onpaymentauthorized documentation >
paymentauthorized :: EventName ApplePaySession onpaymentauthorized
paymentauthorized
= unsafeEventName (toJSString "paymentauthorized")
| < -US/docs/Web/API/ApplePaySession.onshippingmethodselected Mozilla ApplePaySession.onshippingmethodselected documentation >
shippingmethodselected ::
EventName ApplePaySession onshippingmethodselected
shippingmethodselected
= unsafeEventName (toJSString "shippingmethodselected")
| < -US/docs/Web/API/ApplePaySession.onshippingcontactselected Mozilla ApplePaySession.onshippingcontactselected documentation >
shippingcontactselected ::
EventName ApplePaySession onshippingcontactselected
shippingcontactselected
= unsafeEventName (toJSString "shippingcontactselected")
cancel :: EventName ApplePaySession oncancel
cancel = unsafeEventName (toJSString "cancel") |
4d27e181cf9eec3f7b5dcb35f8bc36168ad86f4222e7e217c8de615cdc90ff62 | input-output-hk/cardano-wallet | Ntp.hs | # LANGUAGE DataKinds #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE LambdaCase #
# LANGUAGE NumericUnderscores #
# LANGUAGE TypeApplications #
# OPTIONS_GHC -fno - warn - orphans #
-- |
Copyright : © 2020
-- License: Apache-2.0
--
This module provides the client related settings , types
-- and re-exports used in a number of places throughout codebase.
module Network.Ntp
( withWalletNtpClient
, getNtpStatus
, NtpSyncingStatus (..)
, NtpStatusWithOffset (..)
, ForceCheck (..)
* re - exports from ntp - client
, NtpTrace (..)
, NtpClient (..)
) where
import Prelude
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..) )
import Control.DeepSeq
( NFData )
import Control.Tracer
( Tracer )
import Data.Quantity
( Quantity (..) )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import GHC.Generics
( Generic )
import Network.NTP.Client
( IPVersion (..)
, NtpClient (..)
, NtpSettings (..)
, NtpStatus (..)
, NtpTrace (..)
, ResultOrFailure (..)
, withNtpClient
)
import System.IOManager
( IOManager )
import UnliftIO.STM
( atomically, checkSTM )
import qualified Data.Text as T
| Set up a ' NtpClient ' and pass it to the given action . The ' NtpClient ' is
-- terminated when the callback returns.
withWalletNtpClient
:: IOManager
-- ^ The global 'IOManager' instance, set up by the application main function.
-> Tracer IO NtpTrace
-- ^ Logging object
-> (NtpClient -> IO a)
-- ^ Action to run
-> IO a
withWalletNtpClient ioManager tr = withNtpClient ioManager tr ntpSettings
-- | Hard-coded NTP servers for cardano-wallet.
ntpSettings :: NtpSettings
ntpSettings = NtpSettings
{ ntpServers = [ "0.de.pool.ntp.org", "0.europe.pool.ntp.org"
, "0.pool.ntp.org", "1.pool.ntp.org"
, "2.pool.ntp.org", "3.pool.ntp.org" ]
, ntpRequiredNumberOfResults = 3
, ntpResponseTimeout = 1_000_000
, ntpPollDelay = 300_000_000
}
--------------------------------------------------------------------------------
-- Types
--------------------------------------------------------------------------------
data NtpSyncingStatus
= NtpSyncingStatusUnavailable
| NtpSyncingStatusPending
| NtpSyncingStatusAvailable
deriving (Eq, Generic, Show)
deriving anyclass NFData
data NtpStatusWithOffset = NtpStatusWithOffset
{ status :: !NtpSyncingStatus
, offset :: !(Maybe (Quantity "microsecond" Integer))
}
deriving (Eq, Generic, Show)
deriving anyclass NFData
--------------------------------------------------------------------------------
-- Printing and Logging
--------------------------------------------------------------------------------
-- TODO: Move this upstream.
prettyNtpStatus :: NtpStatus -> Text
prettyNtpStatus = \case
NtpDrift o -> "drifting by " <> prettyNtpOffset o
NtpSyncPending -> "pending"
NtpSyncUnavailable -> "unavailable"
-- Using 'Integral' here because 'NtpOffset' is not exposed :/
--
-- TODO: Move this upstream.
prettyNtpOffset :: Integral a => a -> Text
prettyNtpOffset n =
T.pack (show $ fromIntegral @_ @Integer n) <> "μs"
-- TODO: Move this upstream
prettyResultOrFailure :: (a -> Text) -> ResultOrFailure a -> Text
prettyResultOrFailure prettyA = \case
BothSucceeded a ->
prettyA a
SuccessAndFailure a ip e ->
"succeeded and failed with " <> prettyA a <> ", " <> T.pack (show (ip, e))
BothFailed e0 e1 ->
"failed with " <> T.pack (show e0) <> ", " <> T.pack (show e1)
instance ToText IPVersion where
toText IPv4 = "IPv4"
toText IPv6 = "IPv6"
instance ToText NtpTrace where
toText msg = case msg of
NtpTraceStartNtpClient ->
"Starting ntp client"
NtpTraceRestartDelay d ->
"ntp client restart delay is " <> toText d
NtpTraceRestartingClient ->
"ntp client is restarting"
NtpTraceIOError e ->
"ntp client experienced io error " <> toText (show e)
NtpTraceLookupsFails ->
"ntp client failed to lookup the ntp servers"
NtpTraceClientStartQuery ->
"query to ntp client invoked"
NtpTraceNoLocalAddr ->
"no local address error when running ntp client"
NtpTraceResult a ->
"local clock is " <> prettyNtpStatus a
NtpTraceRunProtocolResults a ->
"ntp client run protocol results: "
<> prettyResultOrFailure (T.intercalate ", " . map prettyNtpOffset) a
NtpTracePacketSent _ a ->
"ntp client sent packet when running " <> toText (show a)
NtpTracePacketSendError _ e ->
"ntp client experienced error " <> toText (show e)
<> " when sending packet"
NtpTracePacketDecodeError _ e ->
"ntp client experienced error " <> toText (show e)
<> " when decoding packet"
NtpTracePacketReceived _ a ->
"ntp client received packet: " <> toText (show a)
NtpTraceWaitingForRepliesTimeout v ->
"ntp client experienced timeout using " <> toText v <> " protocol"
instance HasPrivacyAnnotation NtpTrace
instance HasSeverityAnnotation NtpTrace where
getSeverityAnnotation ev = case ev of
NtpTraceStartNtpClient -> Debug
NtpTraceRestartDelay _ -> Debug
NtpTraceRestartingClient -> Debug
NtpTraceIOError _ -> Notice
NtpTraceLookupsFails -> Notice
NtpTraceClientStartQuery -> Debug
NtpTraceNoLocalAddr -> Notice
NtpTraceResult (NtpDrift micro)
| abs micro < (500*ms) -> Debug -- Not sure what limits actually
| abs micro < (1_000*ms) -> Notice -- matter, but these seem
| otherwise -> Warning -- reasonable.
NtpTraceResult _ -> Debug
NtpTraceRunProtocolResults _ -> Debug
NtpTracePacketSent _ _ -> Debug
NtpTracePacketSendError _ _ -> Notice
NtpTracePacketDecodeError _ _ -> Notice
NtpTracePacketReceived _ _ -> Debug
NtpTraceWaitingForRepliesTimeout _ -> Notice
where
ms = 1_000
data ForceCheck = ForceBlockingRequest | CanUseCachedResults
getNtpStatus :: NtpClient -> ForceCheck -> IO NtpStatusWithOffset
getNtpStatus client forceCheck = toStatus <$> case forceCheck of
ForceBlockingRequest ->
-- Forces an NTP check / query on the central servers, use with care
ntpQueryBlocking client
CanUseCachedResults -> atomically $ do
Reads a cached NTP status from an STM.TVar so we do n't get
-- blacklisted by the central NTP "authorities" for sending
too many NTP requests .
s <- ntpGetStatus client
checkSTM (s /= NtpSyncPending)
pure s
where
toStatus = \case
NtpSyncPending ->
NtpStatusWithOffset NtpSyncingStatusPending Nothing
NtpSyncUnavailable ->
NtpStatusWithOffset NtpSyncingStatusUnavailable Nothing
NtpDrift ms ->
NtpStatusWithOffset NtpSyncingStatusAvailable
(Just $ Quantity (fromIntegral ms :: Integer))
| null | https://raw.githubusercontent.com/input-output-hk/cardano-wallet/7b541e0b11fdd69b30d94104dbd5fa633ff1d5c3/lib/wallet/src/Network/Ntp.hs | haskell | # LANGUAGE DeriveAnyClass #
|
License: Apache-2.0
and re-exports used in a number of places throughout codebase.
terminated when the callback returns.
^ The global 'IOManager' instance, set up by the application main function.
^ Logging object
^ Action to run
| Hard-coded NTP servers for cardano-wallet.
------------------------------------------------------------------------------
Types
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Printing and Logging
------------------------------------------------------------------------------
TODO: Move this upstream.
Using 'Integral' here because 'NtpOffset' is not exposed :/
TODO: Move this upstream.
TODO: Move this upstream
Not sure what limits actually
matter, but these seem
reasonable.
Forces an NTP check / query on the central servers, use with care
blacklisted by the central NTP "authorities" for sending | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE LambdaCase #
# LANGUAGE NumericUnderscores #
# LANGUAGE TypeApplications #
# OPTIONS_GHC -fno - warn - orphans #
Copyright : © 2020
This module provides the client related settings , types
module Network.Ntp
( withWalletNtpClient
, getNtpStatus
, NtpSyncingStatus (..)
, NtpStatusWithOffset (..)
, ForceCheck (..)
* re - exports from ntp - client
, NtpTrace (..)
, NtpClient (..)
) where
import Prelude
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..) )
import Control.DeepSeq
( NFData )
import Control.Tracer
( Tracer )
import Data.Quantity
( Quantity (..) )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import GHC.Generics
( Generic )
import Network.NTP.Client
( IPVersion (..)
, NtpClient (..)
, NtpSettings (..)
, NtpStatus (..)
, NtpTrace (..)
, ResultOrFailure (..)
, withNtpClient
)
import System.IOManager
( IOManager )
import UnliftIO.STM
( atomically, checkSTM )
import qualified Data.Text as T
| Set up a ' NtpClient ' and pass it to the given action . The ' NtpClient ' is
withWalletNtpClient
:: IOManager
-> Tracer IO NtpTrace
-> (NtpClient -> IO a)
-> IO a
withWalletNtpClient ioManager tr = withNtpClient ioManager tr ntpSettings
ntpSettings :: NtpSettings
ntpSettings = NtpSettings
{ ntpServers = [ "0.de.pool.ntp.org", "0.europe.pool.ntp.org"
, "0.pool.ntp.org", "1.pool.ntp.org"
, "2.pool.ntp.org", "3.pool.ntp.org" ]
, ntpRequiredNumberOfResults = 3
, ntpResponseTimeout = 1_000_000
, ntpPollDelay = 300_000_000
}
data NtpSyncingStatus
= NtpSyncingStatusUnavailable
| NtpSyncingStatusPending
| NtpSyncingStatusAvailable
deriving (Eq, Generic, Show)
deriving anyclass NFData
data NtpStatusWithOffset = NtpStatusWithOffset
{ status :: !NtpSyncingStatus
, offset :: !(Maybe (Quantity "microsecond" Integer))
}
deriving (Eq, Generic, Show)
deriving anyclass NFData
prettyNtpStatus :: NtpStatus -> Text
prettyNtpStatus = \case
NtpDrift o -> "drifting by " <> prettyNtpOffset o
NtpSyncPending -> "pending"
NtpSyncUnavailable -> "unavailable"
prettyNtpOffset :: Integral a => a -> Text
prettyNtpOffset n =
T.pack (show $ fromIntegral @_ @Integer n) <> "μs"
prettyResultOrFailure :: (a -> Text) -> ResultOrFailure a -> Text
prettyResultOrFailure prettyA = \case
BothSucceeded a ->
prettyA a
SuccessAndFailure a ip e ->
"succeeded and failed with " <> prettyA a <> ", " <> T.pack (show (ip, e))
BothFailed e0 e1 ->
"failed with " <> T.pack (show e0) <> ", " <> T.pack (show e1)
instance ToText IPVersion where
toText IPv4 = "IPv4"
toText IPv6 = "IPv6"
instance ToText NtpTrace where
toText msg = case msg of
NtpTraceStartNtpClient ->
"Starting ntp client"
NtpTraceRestartDelay d ->
"ntp client restart delay is " <> toText d
NtpTraceRestartingClient ->
"ntp client is restarting"
NtpTraceIOError e ->
"ntp client experienced io error " <> toText (show e)
NtpTraceLookupsFails ->
"ntp client failed to lookup the ntp servers"
NtpTraceClientStartQuery ->
"query to ntp client invoked"
NtpTraceNoLocalAddr ->
"no local address error when running ntp client"
NtpTraceResult a ->
"local clock is " <> prettyNtpStatus a
NtpTraceRunProtocolResults a ->
"ntp client run protocol results: "
<> prettyResultOrFailure (T.intercalate ", " . map prettyNtpOffset) a
NtpTracePacketSent _ a ->
"ntp client sent packet when running " <> toText (show a)
NtpTracePacketSendError _ e ->
"ntp client experienced error " <> toText (show e)
<> " when sending packet"
NtpTracePacketDecodeError _ e ->
"ntp client experienced error " <> toText (show e)
<> " when decoding packet"
NtpTracePacketReceived _ a ->
"ntp client received packet: " <> toText (show a)
NtpTraceWaitingForRepliesTimeout v ->
"ntp client experienced timeout using " <> toText v <> " protocol"
instance HasPrivacyAnnotation NtpTrace
instance HasSeverityAnnotation NtpTrace where
getSeverityAnnotation ev = case ev of
NtpTraceStartNtpClient -> Debug
NtpTraceRestartDelay _ -> Debug
NtpTraceRestartingClient -> Debug
NtpTraceIOError _ -> Notice
NtpTraceLookupsFails -> Notice
NtpTraceClientStartQuery -> Debug
NtpTraceNoLocalAddr -> Notice
NtpTraceResult (NtpDrift micro)
NtpTraceResult _ -> Debug
NtpTraceRunProtocolResults _ -> Debug
NtpTracePacketSent _ _ -> Debug
NtpTracePacketSendError _ _ -> Notice
NtpTracePacketDecodeError _ _ -> Notice
NtpTracePacketReceived _ _ -> Debug
NtpTraceWaitingForRepliesTimeout _ -> Notice
where
ms = 1_000
data ForceCheck = ForceBlockingRequest | CanUseCachedResults
getNtpStatus :: NtpClient -> ForceCheck -> IO NtpStatusWithOffset
getNtpStatus client forceCheck = toStatus <$> case forceCheck of
ForceBlockingRequest ->
ntpQueryBlocking client
CanUseCachedResults -> atomically $ do
Reads a cached NTP status from an STM.TVar so we do n't get
too many NTP requests .
s <- ntpGetStatus client
checkSTM (s /= NtpSyncPending)
pure s
where
toStatus = \case
NtpSyncPending ->
NtpStatusWithOffset NtpSyncingStatusPending Nothing
NtpSyncUnavailable ->
NtpStatusWithOffset NtpSyncingStatusUnavailable Nothing
NtpDrift ms ->
NtpStatusWithOffset NtpSyncingStatusAvailable
(Just $ Quantity (fromIntegral ms :: Integer))
|
0ba05b135cda3ef48ae3084d1616afe67542cf1833736a558edb9410432086c3 | mbj/stratosphere | LocationProperty.hs | module Stratosphere.Pinpoint.Segment.LocationProperty (
module Exports, LocationProperty(..), mkLocationProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.Pinpoint.Segment.GPSPointProperty as Exports
import {-# SOURCE #-} Stratosphere.Pinpoint.Segment.SetDimensionProperty as Exports
import Stratosphere.ResourceProperties
data LocationProperty
= LocationProperty {country :: (Prelude.Maybe SetDimensionProperty),
gPSPoint :: (Prelude.Maybe GPSPointProperty)}
mkLocationProperty :: LocationProperty
mkLocationProperty
= LocationProperty
{country = Prelude.Nothing, gPSPoint = Prelude.Nothing}
instance ToResourceProperties LocationProperty where
toResourceProperties LocationProperty {..}
= ResourceProperties
{awsType = "AWS::Pinpoint::Segment.Location",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Country" Prelude.<$> country,
(JSON..=) "GPSPoint" Prelude.<$> gPSPoint])}
instance JSON.ToJSON LocationProperty where
toJSON LocationProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Country" Prelude.<$> country,
(JSON..=) "GPSPoint" Prelude.<$> gPSPoint]))
instance Property "Country" LocationProperty where
type PropertyType "Country" LocationProperty = SetDimensionProperty
set newValue LocationProperty {..}
= LocationProperty {country = Prelude.pure newValue, ..}
instance Property "GPSPoint" LocationProperty where
type PropertyType "GPSPoint" LocationProperty = GPSPointProperty
set newValue LocationProperty {..}
= LocationProperty {gPSPoint = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/pinpoint/gen/Stratosphere/Pinpoint/Segment/LocationProperty.hs | haskell | # SOURCE #
# SOURCE # | module Stratosphere.Pinpoint.Segment.LocationProperty (
module Exports, LocationProperty(..), mkLocationProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
data LocationProperty
= LocationProperty {country :: (Prelude.Maybe SetDimensionProperty),
gPSPoint :: (Prelude.Maybe GPSPointProperty)}
mkLocationProperty :: LocationProperty
mkLocationProperty
= LocationProperty
{country = Prelude.Nothing, gPSPoint = Prelude.Nothing}
instance ToResourceProperties LocationProperty where
toResourceProperties LocationProperty {..}
= ResourceProperties
{awsType = "AWS::Pinpoint::Segment.Location",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Country" Prelude.<$> country,
(JSON..=) "GPSPoint" Prelude.<$> gPSPoint])}
instance JSON.ToJSON LocationProperty where
toJSON LocationProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Country" Prelude.<$> country,
(JSON..=) "GPSPoint" Prelude.<$> gPSPoint]))
instance Property "Country" LocationProperty where
type PropertyType "Country" LocationProperty = SetDimensionProperty
set newValue LocationProperty {..}
= LocationProperty {country = Prelude.pure newValue, ..}
instance Property "GPSPoint" LocationProperty where
type PropertyType "GPSPoint" LocationProperty = GPSPointProperty
set newValue LocationProperty {..}
= LocationProperty {gPSPoint = Prelude.pure newValue, ..} |
505ffe8f281effa1fe5f7c91593a8c9e85a1d7f7bd373791e8bfcedcfe2cbade | danielsz/certificaat | hooks.clj | (ns certificaat.hooks
(:require [certificaat.plugins.webroot :as w]
[certificaat.plugins.report :as r]
[certificaat.plugins.server :as s]
[certificaat.plugins.copy-to-path :as cp]
[certificaat.plugins.diffie-hellman :as dh]
[certificaat.hooks :as h]))
(defmulti run (fn [hook options] hook))
(defmethod run :before-challenge [_ options]
(w/webroot options)
(s/listen options))
(defmethod run :after-request [_ options]
(r/report options)
(dh/params options)
(cp/copy options))
| null | https://raw.githubusercontent.com/danielsz/certificaat/955429f6303da9a687cf636d93437281f43ddb71/src/certificaat/hooks.clj | clojure | (ns certificaat.hooks
(:require [certificaat.plugins.webroot :as w]
[certificaat.plugins.report :as r]
[certificaat.plugins.server :as s]
[certificaat.plugins.copy-to-path :as cp]
[certificaat.plugins.diffie-hellman :as dh]
[certificaat.hooks :as h]))
(defmulti run (fn [hook options] hook))
(defmethod run :before-challenge [_ options]
(w/webroot options)
(s/listen options))
(defmethod run :after-request [_ options]
(r/report options)
(dh/params options)
(cp/copy options))
| |
59ce8e6b58e3db08f0797cbcdfd38bb807ab7b61add79a25f5f306fab5ea2f64 | pol-is/polisMath | corr.clj | Copyright ( C ) 2012 - present , The Authors . This program is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . 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 < / > .
(ns polismath.math.corr
(:refer-clojure :exclude [* - + == /])
(:require
[taoensso.timbre :as log]
[taoensso.timbre.profiling :as prof]
;[plumbing.core :as pc
; :refer (fnk map-vals <-)]
;[plumbing.graph :as gr]
;[clojure.tools.trace :as tr]
;[polismath.utils :as utils]
;[polismath.math.stats :as stats]
[polismath.math.named-matrix :as nm]
[clojure.spec.alpha :as s]
[clojure.core.matrix :as matrix]
;[clojure.core.matrix.stats :as matrix-stats]
[clojure.core.matrix.selection :as matrix.selection]
[clojure.core.matrix.operators :refer :all]
;;
;[incanter.charts :as charts]
;[polismath.conv-man :as conv-man]
[clojure.set :as set]
[polismath.components.postgres :as postgres]
[incanter.stats :as ic-stats]))
;; The following is a naive hclust implementation for clustering comments using the rating matrix.
This is so that we can rearrange a correlation matrix according to the hclust ordering for one of them slick heatmap things .
;; This is not a particularly efficient algorithm, but it gets the job done for now.
(defn -hclust
"Implements the inner recursive agglomeration step for the hclust function."
([clusters distances]
(if (= (count clusters) 1)
clusters
(let [[c1 c2] (->> (for [c1 clusters
c2 clusters
;; Make sure we don't traverse [c c], or both [x y] and [y x]
:when (< (:id c1) (:id c2))]
[c1 c2])
(apply min-key
(fn [[c1 c2]]
(let [key [(:id c1) (:id c2)]]
(if-let [dist (get @distances key)]
dist
(let [dist (matrix/distance (:center c1) (:center c2))]
(swap! distances assoc key dist)
dist))))))
size (+ (:size c1) (:size c2))
clusters (-> clusters
(->> (remove #{c1 c2}))
(conj {:id (inc (apply max (map :id clusters)))
:children [c1 c2]
:members (concat (:members c1) (:members c2))
:distance (get @distances [(:id c1) (:id c2)])
:center (/ (+ (* (:size c1) (:center c1))
(* (:size c2) (:center c2)))
size)
:size size}))]
(-hclust clusters))))
([clusters]
(-hclust clusters (atom {}))))
(defn hclust
"Performs hclust on a named matrix"
[nmatrix]
(log/debug "hclust on matrix of shape" (matrix/shape (nm/get-matrix nmatrix)))
(-hclust
(mapv (fn [id row]
{:center row :id id :size 1 :members [id]})
(nm/rownames nmatrix)
(matrix/rows (nm/get-matrix nmatrix)))))
(defn flatten-hclust
"Extracts out the tip/leaf node ordering from the hclust results.
(This is rendered somewhat irrelevant by the fact that the hclust algorithm now tracks this data using :members attr)"
[clusters]
(mapcat
(fn [cluster]
(if-let [children (:children cluster)]
(flatten-hclust children)
[(:id cluster)]))
clusters))
(defn blockify-corr-matrix
"Rearrange the given correlation matrix ({:comments :matrix}) such that"
[corr-matrix clusters]
(let [comments (:comments corr-matrix)
matrix (:matrix corr-matrix)
members (:members (first clusters))
member-indices (mapv #(.indexOf comments %) members)]
{:matrix (matrix.selection/sel matrix member-indices member-indices)
:comments members}))
;; Need to remove nulls to compute cov/corr
;; Ideally we'd have something like a null senstive implementation of corr/cov? Restrict to overlapping dimensions?
;; What to do about 0 variance comments (all pass/null)?
These return NaN ; treat as 0 ?
;; These things really should be in the named matrix namespace?
(defn cleaned-nmat [nmat]
(nm/named-matrix
(nm/rownames nmat)
(nm/colnames nmat)
(matrix/matrix
(mapv (fn [row] (map #(or % 0) row))
(matrix/rows (nm/get-matrix nmat))))))
(defn transpose-nmat [nmat]
(nm/named-matrix
(nm/colnames nmat)
(nm/rownames nmat)
(matrix/transpose (nm/get-matrix nmat))))
( defn cleaned - matrix [ conv ]
; (mapv (fn [row] (map #(or % 0) row))
; (matrix/rows (nm/get-matrix (:rating-mat conv)))))
;; The actual correlation matrix stuff
(defn correlation-matrix
[nmat]
{:matrix (ic-stats/correlation (matrix/matrix (nm/get-matrix nmat)))
:comments (nm/colnames nmat)})
;; Here's some stuff for spitting out the actual results.
(require '[cheshire.core :as cheshire])
(defn prepare-hclust-for-export
[clusters]
(mapv
(fn [cluster]
(-> cluster
(update :center (partial into []))))
clusters))
(defn default-tids
;; Gonna need to get all of this under group clusters vs subgroups
[{:as conv :keys [repness consensus group-clusters rating-mat pca]}]
(let [{:keys [extremity]} pca
{:keys [agree disagree]} consensus]
(set
(concat
(map :tid (concat agree disagree))
(mapcat
(fn [[gid gid-repness]]
(map :tid gid-repness))
repness)))))
(defn compute-corr
([conv tids]
(let [matrix (:rating-mat conv)
subset-matrix (if tids (nm/colname-subset matrix tids) matrix)
cleaned-matrix (cleaned-nmat subset-matrix)
transposed-matrix (transpose-nmat cleaned-matrix)
corr-mat (prof/profile :info :corr-mat (correlation-matrix cleaned-matrix))
hclusters (prof/profile :info ::hclust (hclust transposed-matrix))
corr-mat' (blockify-corr-matrix corr-mat hclusters)
corr-mat'
;; Prep for export...
(update corr-mat' :matrix (comp (partial mapv (fn [row] (into [] row)))
matrix/rows))]
corr-mat'))
([conv]
(compute-corr conv (default-tids conv))))
(defn spit-json
[filename data]
(spit
filename
(cheshire/encode data)))
(defn spit-hclust
[filename clusters]
(spit-json
filename
(prepare-hclust-for-export clusters)))
;; We should add a little clarity on where things are regular matrices vs our {:comments :matrix} matrices for final export...
;; And probably just use named matrices everywhere
(defn spit-matrix
[filename matrix]
(spit-json
filename
(update matrix :matrix (comp (partial mapv (fn [row] (into [] row)))
matrix/rows))))
;; We have metadata/tags on the argument symbols of function vars
;; So what if we built a macro that copied over entire namespaces of functions to a new ns, but binds them to some sort of default system?
;; System bind!
;; Then you can access a mirror api that has sans-1 arity versions of all the functions, so you don't have to think about system!
;; This could solve the battle between component and mount
(comment
;; Here we're putting everything together
This may not all be 100 % correct , as it was copied over from the repl ... but I ran through all but the spit and sanity checks pass
(require '[incanter.charts :as charts]
'[polismath.runner :as runner]
'[polismath.conv-man :as conv-man]
'[polismath.system :as system])
( runner / run ! system / base - system { : math - env : } )
Load the data for 15117 ( zinvite 2ez5beswtc )
;(def focus-id 15117)
(def focus-zinvite "36jajfnhhn")
(def focus-id 15228)
(def conv (conv-man/load-or-init (:conversation-manager runner/system) focus-id))
(compute-corr conv)
:ok
;conv
(matrix/shape (nm/get-matrix (:rating-mat conv)))
;; Compute hclust on a cleaned, transposed rating matrix
(def tids (nm/rownames (:rating-mat conv)))
tids
(def corr-mat' (compute-corr (:darwin runner/system)))
;; Spit this out
(spit-matrix (str focus-zinvite ".corrmat.json") corr-mat)
(spit-matrix (str focus-zinvite ".corrmat-whclust.json") corr-mat')
(spit-hclust (str focus-zinvite ".hclust.json") hclusters)
;; All done
:endcomment)
| null | https://raw.githubusercontent.com/pol-is/polisMath/dfe233e8c9207c2ce11e1379286ad0cf0f732067/src/polismath/math/corr.clj | clojure | 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 < / > .
[plumbing.core :as pc
:refer (fnk map-vals <-)]
[plumbing.graph :as gr]
[clojure.tools.trace :as tr]
[polismath.utils :as utils]
[polismath.math.stats :as stats]
[clojure.core.matrix.stats :as matrix-stats]
[incanter.charts :as charts]
[polismath.conv-man :as conv-man]
The following is a naive hclust implementation for clustering comments using the rating matrix.
This is not a particularly efficient algorithm, but it gets the job done for now.
Make sure we don't traverse [c c], or both [x y] and [y x]
Need to remove nulls to compute cov/corr
Ideally we'd have something like a null senstive implementation of corr/cov? Restrict to overlapping dimensions?
What to do about 0 variance comments (all pass/null)?
treat as 0 ?
These things really should be in the named matrix namespace?
(mapv (fn [row] (map #(or % 0) row))
(matrix/rows (nm/get-matrix (:rating-mat conv)))))
The actual correlation matrix stuff
Here's some stuff for spitting out the actual results.
Gonna need to get all of this under group clusters vs subgroups
Prep for export...
We should add a little clarity on where things are regular matrices vs our {:comments :matrix} matrices for final export...
And probably just use named matrices everywhere
We have metadata/tags on the argument symbols of function vars
So what if we built a macro that copied over entire namespaces of functions to a new ns, but binds them to some sort of default system?
System bind!
Then you can access a mirror api that has sans-1 arity versions of all the functions, so you don't have to think about system!
This could solve the battle between component and mount
Here we're putting everything together
(def focus-id 15117)
conv
Compute hclust on a cleaned, transposed rating matrix
Spit this out
All done |
(ns polismath.math.corr
(:refer-clojure :exclude [* - + == /])
(:require
[taoensso.timbre :as log]
[taoensso.timbre.profiling :as prof]
[polismath.math.named-matrix :as nm]
[clojure.spec.alpha :as s]
[clojure.core.matrix :as matrix]
[clojure.core.matrix.selection :as matrix.selection]
[clojure.core.matrix.operators :refer :all]
[clojure.set :as set]
[polismath.components.postgres :as postgres]
[incanter.stats :as ic-stats]))
This is so that we can rearrange a correlation matrix according to the hclust ordering for one of them slick heatmap things .
(defn -hclust
"Implements the inner recursive agglomeration step for the hclust function."
([clusters distances]
(if (= (count clusters) 1)
clusters
(let [[c1 c2] (->> (for [c1 clusters
c2 clusters
:when (< (:id c1) (:id c2))]
[c1 c2])
(apply min-key
(fn [[c1 c2]]
(let [key [(:id c1) (:id c2)]]
(if-let [dist (get @distances key)]
dist
(let [dist (matrix/distance (:center c1) (:center c2))]
(swap! distances assoc key dist)
dist))))))
size (+ (:size c1) (:size c2))
clusters (-> clusters
(->> (remove #{c1 c2}))
(conj {:id (inc (apply max (map :id clusters)))
:children [c1 c2]
:members (concat (:members c1) (:members c2))
:distance (get @distances [(:id c1) (:id c2)])
:center (/ (+ (* (:size c1) (:center c1))
(* (:size c2) (:center c2)))
size)
:size size}))]
(-hclust clusters))))
([clusters]
(-hclust clusters (atom {}))))
(defn hclust
"Performs hclust on a named matrix"
[nmatrix]
(log/debug "hclust on matrix of shape" (matrix/shape (nm/get-matrix nmatrix)))
(-hclust
(mapv (fn [id row]
{:center row :id id :size 1 :members [id]})
(nm/rownames nmatrix)
(matrix/rows (nm/get-matrix nmatrix)))))
(defn flatten-hclust
"Extracts out the tip/leaf node ordering from the hclust results.
(This is rendered somewhat irrelevant by the fact that the hclust algorithm now tracks this data using :members attr)"
[clusters]
(mapcat
(fn [cluster]
(if-let [children (:children cluster)]
(flatten-hclust children)
[(:id cluster)]))
clusters))
(defn blockify-corr-matrix
"Rearrange the given correlation matrix ({:comments :matrix}) such that"
[corr-matrix clusters]
(let [comments (:comments corr-matrix)
matrix (:matrix corr-matrix)
members (:members (first clusters))
member-indices (mapv #(.indexOf comments %) members)]
{:matrix (matrix.selection/sel matrix member-indices member-indices)
:comments members}))
(defn cleaned-nmat [nmat]
(nm/named-matrix
(nm/rownames nmat)
(nm/colnames nmat)
(matrix/matrix
(mapv (fn [row] (map #(or % 0) row))
(matrix/rows (nm/get-matrix nmat))))))
(defn transpose-nmat [nmat]
(nm/named-matrix
(nm/colnames nmat)
(nm/rownames nmat)
(matrix/transpose (nm/get-matrix nmat))))
( defn cleaned - matrix [ conv ]
(defn correlation-matrix
[nmat]
{:matrix (ic-stats/correlation (matrix/matrix (nm/get-matrix nmat)))
:comments (nm/colnames nmat)})
(require '[cheshire.core :as cheshire])
(defn prepare-hclust-for-export
[clusters]
(mapv
(fn [cluster]
(-> cluster
(update :center (partial into []))))
clusters))
(defn default-tids
[{:as conv :keys [repness consensus group-clusters rating-mat pca]}]
(let [{:keys [extremity]} pca
{:keys [agree disagree]} consensus]
(set
(concat
(map :tid (concat agree disagree))
(mapcat
(fn [[gid gid-repness]]
(map :tid gid-repness))
repness)))))
(defn compute-corr
([conv tids]
(let [matrix (:rating-mat conv)
subset-matrix (if tids (nm/colname-subset matrix tids) matrix)
cleaned-matrix (cleaned-nmat subset-matrix)
transposed-matrix (transpose-nmat cleaned-matrix)
corr-mat (prof/profile :info :corr-mat (correlation-matrix cleaned-matrix))
hclusters (prof/profile :info ::hclust (hclust transposed-matrix))
corr-mat' (blockify-corr-matrix corr-mat hclusters)
corr-mat'
(update corr-mat' :matrix (comp (partial mapv (fn [row] (into [] row)))
matrix/rows))]
corr-mat'))
([conv]
(compute-corr conv (default-tids conv))))
(defn spit-json
[filename data]
(spit
filename
(cheshire/encode data)))
(defn spit-hclust
[filename clusters]
(spit-json
filename
(prepare-hclust-for-export clusters)))
(defn spit-matrix
[filename matrix]
(spit-json
filename
(update matrix :matrix (comp (partial mapv (fn [row] (into [] row)))
matrix/rows))))
(comment
This may not all be 100 % correct , as it was copied over from the repl ... but I ran through all but the spit and sanity checks pass
(require '[incanter.charts :as charts]
'[polismath.runner :as runner]
'[polismath.conv-man :as conv-man]
'[polismath.system :as system])
( runner / run ! system / base - system { : math - env : } )
Load the data for 15117 ( zinvite 2ez5beswtc )
(def focus-zinvite "36jajfnhhn")
(def focus-id 15228)
(def conv (conv-man/load-or-init (:conversation-manager runner/system) focus-id))
(compute-corr conv)
:ok
(matrix/shape (nm/get-matrix (:rating-mat conv)))
(def tids (nm/rownames (:rating-mat conv)))
tids
(def corr-mat' (compute-corr (:darwin runner/system)))
(spit-matrix (str focus-zinvite ".corrmat.json") corr-mat)
(spit-matrix (str focus-zinvite ".corrmat-whclust.json") corr-mat')
(spit-hclust (str focus-zinvite ".hclust.json") hclusters)
:endcomment)
|
45692b8ca1f92eea9377d58b73e536da3628bcce2e9eba4b3ddcc95e54ac0fab | irastypain/sicp-on-language-racket | exercise_2_52.rkt | #lang racket
(require racket/gui/base
"../lib/vectors.rkt"
"../lib/segments.rkt"
(only-in "../lib/graphics.rkt"
make-frame
frame-coord-map
polyline
polygon
up-split
right-split
beside
below
square-of-four
flip-horiz
flip-vert
rotate90
rotate180
rotate270))
(define width 512)
(define height 512)
(define target (make-screen-bitmap width height))
(define dc (new bitmap-dc% [bitmap target]))
(define frame
(make-frame (make-vect 0 0)
(make-vect width 0)
(make-vect 0 height)))
Процедура отрисовки отрезка прямой
(define (draw-line start-vect end-vect)
(send dc draw-line
(xcor-vect start-vect)
(ycor-vect start-vect)
(xcor-vect end-vect)
(ycor-vect end-vect)))
Процедура отрисовки отрезков внутри переданной рамки
(define (segments->painter segment-list)
(lambda (frame)
(for-each
(lambda (segment)
(draw-line
((frame-coord-map frame) (start-segment segment))
((frame-coord-map frame) (end-segment segment))))
segment-list)))
; Реализация рисовалки 'wave'
(define wave
(segments->painter
(append (polyline (list (make-vect 0 0.15)
(make-vect 0.15 0.4)
(make-vect 0.3 0.35)
(make-vect 0.4 0.35)
(make-vect 0.35 0.15)
(make-vect 0.4 0)))
(polyline (list (make-vect 0 0.35)
(make-vect 0.15 0.6)
(make-vect 0.3 0.4)
(make-vect 0.35 0.5)
(make-vect 0.25 1)))
(polyline (list (make-vect 0.4 1)
(make-vect 0.5 0.7)
(make-vect 0.6 1)))
(polyline (list (make-vect 0.75 1)
(make-vect 0.6 0.5)
(make-vect 1 0.85)))
(polyline (list (make-vect 0.6 0)
(make-vect 0.65 0.15)
(make-vect 0.6 0.35)
(make-vect 0.75 0.35)
(make-vect 1 0.65)))
(polyline (list (make-vect 0.45 0.25)
(make-vect 0.5 0.27)
(make-vect 0.55 0.25))))))
; Процедура дублирует painter, располагая сверху,
; дублирует, располагая справа и выполняет рекурсивный вызов
для отрисовки в правом верхнем углу
(define (corner-split painter n)
(if (= n 0)
painter
(let ((up (up-split painter (- n 1)))
(right (right-split painter (- n 1))))
(let ((corner (corner-split painter (- n 1))))
(beside (below painter up)
(below right corner))))))
Процедура располагает 4 результата процедуры corner - split
(define (square-limit painter n)
(let ((combine4 (square-of-four flip-vert rotate180
identity flip-horiz)))
(combine4 (corner-split painter n))))
;(wave frame)
( ( corner - split wave 4 ) frame )
((square-limit wave 4) frame)
(send target save-file "/tmp/image.png" 'png) | null | https://raw.githubusercontent.com/irastypain/sicp-on-language-racket/0052f91d3c2432a00e7e15310f416cb77eeb4c9c/src/chapter02/exercise_2_52.rkt | racket | Реализация рисовалки 'wave'
Процедура дублирует painter, располагая сверху,
дублирует, располагая справа и выполняет рекурсивный вызов
(wave frame) | #lang racket
(require racket/gui/base
"../lib/vectors.rkt"
"../lib/segments.rkt"
(only-in "../lib/graphics.rkt"
make-frame
frame-coord-map
polyline
polygon
up-split
right-split
beside
below
square-of-four
flip-horiz
flip-vert
rotate90
rotate180
rotate270))
(define width 512)
(define height 512)
(define target (make-screen-bitmap width height))
(define dc (new bitmap-dc% [bitmap target]))
(define frame
(make-frame (make-vect 0 0)
(make-vect width 0)
(make-vect 0 height)))
Процедура отрисовки отрезка прямой
(define (draw-line start-vect end-vect)
(send dc draw-line
(xcor-vect start-vect)
(ycor-vect start-vect)
(xcor-vect end-vect)
(ycor-vect end-vect)))
Процедура отрисовки отрезков внутри переданной рамки
(define (segments->painter segment-list)
(lambda (frame)
(for-each
(lambda (segment)
(draw-line
((frame-coord-map frame) (start-segment segment))
((frame-coord-map frame) (end-segment segment))))
segment-list)))
(define wave
(segments->painter
(append (polyline (list (make-vect 0 0.15)
(make-vect 0.15 0.4)
(make-vect 0.3 0.35)
(make-vect 0.4 0.35)
(make-vect 0.35 0.15)
(make-vect 0.4 0)))
(polyline (list (make-vect 0 0.35)
(make-vect 0.15 0.6)
(make-vect 0.3 0.4)
(make-vect 0.35 0.5)
(make-vect 0.25 1)))
(polyline (list (make-vect 0.4 1)
(make-vect 0.5 0.7)
(make-vect 0.6 1)))
(polyline (list (make-vect 0.75 1)
(make-vect 0.6 0.5)
(make-vect 1 0.85)))
(polyline (list (make-vect 0.6 0)
(make-vect 0.65 0.15)
(make-vect 0.6 0.35)
(make-vect 0.75 0.35)
(make-vect 1 0.65)))
(polyline (list (make-vect 0.45 0.25)
(make-vect 0.5 0.27)
(make-vect 0.55 0.25))))))
для отрисовки в правом верхнем углу
(define (corner-split painter n)
(if (= n 0)
painter
(let ((up (up-split painter (- n 1)))
(right (right-split painter (- n 1))))
(let ((corner (corner-split painter (- n 1))))
(beside (below painter up)
(below right corner))))))
Процедура располагает 4 результата процедуры corner - split
(define (square-limit painter n)
(let ((combine4 (square-of-four flip-vert rotate180
identity flip-horiz)))
(combine4 (corner-split painter n))))
( ( corner - split wave 4 ) frame )
((square-limit wave 4) frame)
(send target save-file "/tmp/image.png" 'png) |
b797ac1d9bd9a823589a51b66ca4a8c76213cfb11486c38f7ff8e4246030e9c0 | benzap/flyer.js | storage.cljs | (ns flyer.storage
"includes functions for storing window information. This window
information is stored in the parent window under the
`window-list-key`."
(:require [flyer.utils :as utils]))
(declare get-window-refs)
(def storage (utils/get-main-parent))
(def window-list-key "flyer_WindowReferences")
(defn init-window-refs
"Initializes our window references"
[]
(when (nil? (get-window-refs))
(aset storage window-list-key (set nil))))
(defn get-window-refs
"Returns the window references, or an empty set"
[]
(or
(aget storage window-list-key)
nil))
(defn insert-window-ref! [window]
(init-window-refs)
(aset storage window-list-key
(conj (get-window-refs) window)))
(defn remove-window-ref! [window]
(init-window-refs)
(aset storage window-list-key
(disj (get-window-refs) window)))
| null | https://raw.githubusercontent.com/benzap/flyer.js/3f9a1ce9d56cc2c369864b3c04c69694bf95595b/src-cljs/flyer/storage.cljs | clojure | (ns flyer.storage
"includes functions for storing window information. This window
information is stored in the parent window under the
`window-list-key`."
(:require [flyer.utils :as utils]))
(declare get-window-refs)
(def storage (utils/get-main-parent))
(def window-list-key "flyer_WindowReferences")
(defn init-window-refs
"Initializes our window references"
[]
(when (nil? (get-window-refs))
(aset storage window-list-key (set nil))))
(defn get-window-refs
"Returns the window references, or an empty set"
[]
(or
(aget storage window-list-key)
nil))
(defn insert-window-ref! [window]
(init-window-refs)
(aset storage window-list-key
(conj (get-window-refs) window)))
(defn remove-window-ref! [window]
(init-window-refs)
(aset storage window-list-key
(disj (get-window-refs) window)))
| |
dda2273d0f3aef215859ab68f0332b66efb70f86aa6e4bfbf52ea17242bc9d30 | Kakadu/fp2022 | pass.mli | * Copyright 2021 - 2022 , Kakadu , and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
module type State = sig
type t
end
module Pass (S : State) : sig
type 'r t
(* Run *)
val run_pass : 'a t -> init:S.t -> S.t * 'a
(* Combinators *)
val access : S.t t
val put : S.t -> unit t
val return : 'r -> 'r t
val bind : 'r t -> ('r -> 'rr t) -> 'rr t
val ( let* ) : 'r t -> ('r -> 'rr t) -> 'rr t
(* High-level combinators *)
val ignore : 'a t -> unit t
val ( *> ) : 'a t -> 'b t -> 'b t
val ( <* ) : 'a t -> 'b t -> 'a t
val many : 'a list -> f:('a -> 'b t) -> 'b list t
val fold_state : 'a list -> f:('a -> unit t) -> unit t
end
val ident_sign_to_string_sign : Ident.ident Ast.signature -> string Ast.signature
| null | https://raw.githubusercontent.com/Kakadu/fp2022/853ab6831fdce3b3e1b68d49e5163d0293d56bf5/Golang/lib/pass.mli | ocaml | Run
Combinators
High-level combinators | * Copyright 2021 - 2022 , Kakadu , and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
module type State = sig
type t
end
module Pass (S : State) : sig
type 'r t
val run_pass : 'a t -> init:S.t -> S.t * 'a
val access : S.t t
val put : S.t -> unit t
val return : 'r -> 'r t
val bind : 'r t -> ('r -> 'rr t) -> 'rr t
val ( let* ) : 'r t -> ('r -> 'rr t) -> 'rr t
val ignore : 'a t -> unit t
val ( *> ) : 'a t -> 'b t -> 'b t
val ( <* ) : 'a t -> 'b t -> 'a t
val many : 'a list -> f:('a -> 'b t) -> 'b list t
val fold_state : 'a list -> f:('a -> unit t) -> unit t
end
val ident_sign_to_string_sign : Ident.ident Ast.signature -> string Ast.signature
|
313ead946b97773a026d0771f1c0323cdb849a951fa359b7bef9f90e0ca98669 | clojupyter/clojupyter | inspect.clj | (ns clojupyter.kernel.handle-event.inspect
(:require
[clojure.string :as str]
[io.simplect.compose.action :refer [step]]
,,
[clojupyter.kernel.cljsrv :refer [nrepl-doc]]
[clojupyter.kernel.handle-event.ops :refer [definterceptor s*append-enter-action s*set-response]]
[clojupyter.messages :as msgs]
[clojupyter.plan :refer [s*bind-state]]
))
(defn- re-index
"Returns a sorted-map of indicies to matches."
[re s]
(loop [matcher (re-matcher re s)
matches (sorted-map)]
(if (.find matcher)
(recur matcher
(assoc matches (.start matcher) (.group matcher)))
matches)))
(defn- token-at
"Returns the token at the given position."
[code position]
(->>
(loop [token-pos (re-index #"\S+" code)]
(cond
(nil? (first token-pos)) nil
(nil? (second token-pos)) (val (first token-pos))
(< position (key (second token-pos))) (val (first token-pos))
:else (recur (rest token-pos))))
(re-find #"[^\(\)\{\}\[\]\"\']+")))
(defn inspect-info
[req-message]
(let [code (msgs/message-code req-message)
cursor-pos (msgs/message-cursor-pos req-message)
inspect-string (token-at code cursor-pos)]
{:code code, :cursor-pos cursor-pos, :inspect-string inspect-string}))
(definterceptor ic*inspect msgs/INSPECT-REQUEST
(s*bind-state {:keys [cljsrv req-message] :as ctx}
(let [{:keys [inspect-string] :as inspect-info} (inspect-info req-message)]
(s*append-enter-action (step (fn [S] (-> (assoc S ::inspect-info inspect-info)
(assoc ::inspect-result (nrepl-doc cljsrv inspect-string))))
{:nrepl :inspect :data inspect-info}))))
(s*bind-state {:keys [::inspect-result] {:keys [code]} ::inspect-info}
(let [doc inspect-result
result-str (when (string? doc)
(if-let [i (str/index-of doc \newline)]
(subs doc (inc i) (count doc))
doc))]
(s*set-response msgs/INSPECT-REPLY (msgs/inspect-reply-content code result-str)))))
| null | https://raw.githubusercontent.com/clojupyter/clojupyter/b54b30b5efa115937b7a85e708a7402bd9efa0ab/src/clojupyter/kernel/handle_event/inspect.clj | clojure | (ns clojupyter.kernel.handle-event.inspect
(:require
[clojure.string :as str]
[io.simplect.compose.action :refer [step]]
,,
[clojupyter.kernel.cljsrv :refer [nrepl-doc]]
[clojupyter.kernel.handle-event.ops :refer [definterceptor s*append-enter-action s*set-response]]
[clojupyter.messages :as msgs]
[clojupyter.plan :refer [s*bind-state]]
))
(defn- re-index
"Returns a sorted-map of indicies to matches."
[re s]
(loop [matcher (re-matcher re s)
matches (sorted-map)]
(if (.find matcher)
(recur matcher
(assoc matches (.start matcher) (.group matcher)))
matches)))
(defn- token-at
"Returns the token at the given position."
[code position]
(->>
(loop [token-pos (re-index #"\S+" code)]
(cond
(nil? (first token-pos)) nil
(nil? (second token-pos)) (val (first token-pos))
(< position (key (second token-pos))) (val (first token-pos))
:else (recur (rest token-pos))))
(re-find #"[^\(\)\{\}\[\]\"\']+")))
(defn inspect-info
[req-message]
(let [code (msgs/message-code req-message)
cursor-pos (msgs/message-cursor-pos req-message)
inspect-string (token-at code cursor-pos)]
{:code code, :cursor-pos cursor-pos, :inspect-string inspect-string}))
(definterceptor ic*inspect msgs/INSPECT-REQUEST
(s*bind-state {:keys [cljsrv req-message] :as ctx}
(let [{:keys [inspect-string] :as inspect-info} (inspect-info req-message)]
(s*append-enter-action (step (fn [S] (-> (assoc S ::inspect-info inspect-info)
(assoc ::inspect-result (nrepl-doc cljsrv inspect-string))))
{:nrepl :inspect :data inspect-info}))))
(s*bind-state {:keys [::inspect-result] {:keys [code]} ::inspect-info}
(let [doc inspect-result
result-str (when (string? doc)
(if-let [i (str/index-of doc \newline)]
(subs doc (inc i) (count doc))
doc))]
(s*set-response msgs/INSPECT-REPLY (msgs/inspect-reply-content code result-str)))))
| |
b512fe63a2a16b2c4a685145ada20e6c6677c707aa3d5228579121cff17f0dbd | peterhudec/cljsx | core_test.clj | (ns cljsx.core-test
(:require [midje.sweet :refer [fact facts throws]]
[cljsx.core :as sut]))
(sut/defjsx my> my-jsx my-fragment)
(defn my-jsx [tag props & children]
{:tag tag
:props props
:children (into [] children)})
(def my-fragment "MY FRAGMENT")
(fact
"Custom JSX"
(my>
(+ 100 10 1))
=>
111
(my>
(<foo> "child-1"
"child-2"))
=>
{:tag "foo"
:props nil
:children ["child-1" "child-2"]}
(my>
(<> "child-1"
"child-2"))
=>
{:tag my-fragment
:props nil
:children ["child-1" "child-2"]}
(my>
(<foo> "foo-child-1"
(<bar> "bar-child-1"
"bar-child-2")
"foo-child-3"))
=>
{:tag "foo"
:props nil
:children ["foo-child-1"
{:tag "bar"
:props nil
:children ["bar-child-1"
"bar-child-2"]}
"foo-child-3"]}
(my>
(<foo :a "A" :b "B" :c "C"
... {:a "AA"}
:c "CC" >
"foo-child"))
=>
{:tag "foo"
:props {:a "AA"
:b "B"
:c "CC"}
:children ["foo-child"]}
(my>
(let [bar (<bar>)
Baz "BAZ"]
(<foo> "foo"
bar
(<Baz> "baz")
"foo")))
=>
{:tag "foo"
:props nil
:children ["foo"
{:tag "bar"
:props nil
:children []}
{:tag "BAZ"
:props nil
:children ["baz"]}
"foo"]}
(my>
(let [bar (<bar>)
Baz "BAZ"]
(<> "foo"
bar
(<Baz> "baz")
"foo")))
=>
{:tag my-fragment
:props nil
:children ["foo"
{:tag "bar"
:props nil
:children []}
{:tag "BAZ"
:props nil
:children ["baz"]}
"foo"]}
(my>
(map (fn [x] (<foo> x))
["A" "B" "C"]))
=>
'({:tag "foo", :props nil, :children ["A"]}
{:tag "foo", :props nil, :children ["B"]}
{:tag "foo", :props nil, :children ["C"]})
(my>
(map (fn [x] (<> x))
["A" "B" "C"]))
=>
`({:tag ~my-fragment, :props nil, :children ["A"]}
{:tag ~my-fragment, :props nil, :children ["B"]}
{:tag ~my-fragment, :props nil, :children ["C"]})
(my>
(map (fn [Tag] (<Tag> "child"))
["a" "b" "c"]))
=>
'({:tag "a", :props nil, :children ["child"]}
{:tag "b", :props nil, :children ["child"]}
{:tag "c", :props nil, :children ["child"]})
(my>
(map #(<foo :prop % > %)
["a" "b" "c"]))
=>
'({:tag "foo", :props {:prop "a"}, :children ["a"]}
{:tag "foo", :props {:prop "b"}, :children ["b"]}
{:tag "foo", :props {:prop "c"}, :children ["c"]})
(my>
(map #(<> %)
["a" "b" "c"]))
=>
`({:tag ~my-fragment, :props nil, :children ["a"]}
{:tag ~my-fragment, :props nil, :children ["b"]}
{:tag ~my-fragment, :props nil, :children ["c"]})
(my>
(let [Foo "FOO"]
(map #(<Foo :prop % > %)
["a" "b" "c"])))
=> '({:tag "FOO", :props {:prop "a"}, :children ["a"]}
{:tag "FOO", :props {:prop "b"}, :children ["b"]}
{:tag "FOO", :props {:prop "c"}, :children ["c"]})
(macroexpand
'(my>
(<foo> "foo")
(<bar> "bar")
(<baz> "baz")))
=>
'(do (my-jsx "foo" nil "foo")
(my-jsx "bar" nil "bar")
(my-jsx "baz" nil "baz")))
| null | https://raw.githubusercontent.com/peterhudec/cljsx/3a23dbc085fed0c79d4e865c88ae7da55bdaa789/test/cljsx/core_test.clj | clojure | (ns cljsx.core-test
(:require [midje.sweet :refer [fact facts throws]]
[cljsx.core :as sut]))
(sut/defjsx my> my-jsx my-fragment)
(defn my-jsx [tag props & children]
{:tag tag
:props props
:children (into [] children)})
(def my-fragment "MY FRAGMENT")
(fact
"Custom JSX"
(my>
(+ 100 10 1))
=>
111
(my>
(<foo> "child-1"
"child-2"))
=>
{:tag "foo"
:props nil
:children ["child-1" "child-2"]}
(my>
(<> "child-1"
"child-2"))
=>
{:tag my-fragment
:props nil
:children ["child-1" "child-2"]}
(my>
(<foo> "foo-child-1"
(<bar> "bar-child-1"
"bar-child-2")
"foo-child-3"))
=>
{:tag "foo"
:props nil
:children ["foo-child-1"
{:tag "bar"
:props nil
:children ["bar-child-1"
"bar-child-2"]}
"foo-child-3"]}
(my>
(<foo :a "A" :b "B" :c "C"
... {:a "AA"}
:c "CC" >
"foo-child"))
=>
{:tag "foo"
:props {:a "AA"
:b "B"
:c "CC"}
:children ["foo-child"]}
(my>
(let [bar (<bar>)
Baz "BAZ"]
(<foo> "foo"
bar
(<Baz> "baz")
"foo")))
=>
{:tag "foo"
:props nil
:children ["foo"
{:tag "bar"
:props nil
:children []}
{:tag "BAZ"
:props nil
:children ["baz"]}
"foo"]}
(my>
(let [bar (<bar>)
Baz "BAZ"]
(<> "foo"
bar
(<Baz> "baz")
"foo")))
=>
{:tag my-fragment
:props nil
:children ["foo"
{:tag "bar"
:props nil
:children []}
{:tag "BAZ"
:props nil
:children ["baz"]}
"foo"]}
(my>
(map (fn [x] (<foo> x))
["A" "B" "C"]))
=>
'({:tag "foo", :props nil, :children ["A"]}
{:tag "foo", :props nil, :children ["B"]}
{:tag "foo", :props nil, :children ["C"]})
(my>
(map (fn [x] (<> x))
["A" "B" "C"]))
=>
`({:tag ~my-fragment, :props nil, :children ["A"]}
{:tag ~my-fragment, :props nil, :children ["B"]}
{:tag ~my-fragment, :props nil, :children ["C"]})
(my>
(map (fn [Tag] (<Tag> "child"))
["a" "b" "c"]))
=>
'({:tag "a", :props nil, :children ["child"]}
{:tag "b", :props nil, :children ["child"]}
{:tag "c", :props nil, :children ["child"]})
(my>
(map #(<foo :prop % > %)
["a" "b" "c"]))
=>
'({:tag "foo", :props {:prop "a"}, :children ["a"]}
{:tag "foo", :props {:prop "b"}, :children ["b"]}
{:tag "foo", :props {:prop "c"}, :children ["c"]})
(my>
(map #(<> %)
["a" "b" "c"]))
=>
`({:tag ~my-fragment, :props nil, :children ["a"]}
{:tag ~my-fragment, :props nil, :children ["b"]}
{:tag ~my-fragment, :props nil, :children ["c"]})
(my>
(let [Foo "FOO"]
(map #(<Foo :prop % > %)
["a" "b" "c"])))
=> '({:tag "FOO", :props {:prop "a"}, :children ["a"]}
{:tag "FOO", :props {:prop "b"}, :children ["b"]}
{:tag "FOO", :props {:prop "c"}, :children ["c"]})
(macroexpand
'(my>
(<foo> "foo")
(<bar> "bar")
(<baz> "baz")))
=>
'(do (my-jsx "foo" nil "foo")
(my-jsx "bar" nil "bar")
(my-jsx "baz" nil "baz")))
| |
ed7f8da19806f3b85b798d64604c887af79a8bcf6ca39f1a728a8847d15eeffa | processone/ejabberd | mod_configure.erl | %%%----------------------------------------------------------------------
File :
Author : < >
%%% Purpose : Support for online configuration of ejabberd
Created : 19 Jan 2003 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(mod_configure).
-author('').
-protocol({xep, 133, '1.1'}).
-behaviour(gen_mod).
-export([start/2, stop/1, reload/3, get_local_identity/5,
get_local_features/5, get_local_items/5,
adhoc_local_items/4, adhoc_local_commands/4,
get_sm_identity/5, get_sm_features/5, get_sm_items/5,
adhoc_sm_items/4, adhoc_sm_commands/4, mod_options/1,
depends/2, mod_doc/0]).
-include("logger.hrl").
-include_lib("xmpp/include/xmpp.hrl").
-include("ejabberd_sm.hrl").
-include("translate.hrl").
-include_lib("stdlib/include/ms_transform.hrl").
start(Host, _Opts) ->
ejabberd_hooks:add(disco_local_items, Host, ?MODULE,
get_local_items, 50),
ejabberd_hooks:add(disco_local_features, Host, ?MODULE,
get_local_features, 50),
ejabberd_hooks:add(disco_local_identity, Host, ?MODULE,
get_local_identity, 50),
ejabberd_hooks:add(disco_sm_items, Host, ?MODULE,
get_sm_items, 50),
ejabberd_hooks:add(disco_sm_features, Host, ?MODULE,
get_sm_features, 50),
ejabberd_hooks:add(disco_sm_identity, Host, ?MODULE,
get_sm_identity, 50),
ejabberd_hooks:add(adhoc_local_items, Host, ?MODULE,
adhoc_local_items, 50),
ejabberd_hooks:add(adhoc_local_commands, Host, ?MODULE,
adhoc_local_commands, 50),
ejabberd_hooks:add(adhoc_sm_items, Host, ?MODULE,
adhoc_sm_items, 50),
ejabberd_hooks:add(adhoc_sm_commands, Host, ?MODULE,
adhoc_sm_commands, 50),
ok.
stop(Host) ->
ejabberd_hooks:delete(adhoc_sm_commands, Host, ?MODULE,
adhoc_sm_commands, 50),
ejabberd_hooks:delete(adhoc_sm_items, Host, ?MODULE,
adhoc_sm_items, 50),
ejabberd_hooks:delete(adhoc_local_commands, Host,
?MODULE, adhoc_local_commands, 50),
ejabberd_hooks:delete(adhoc_local_items, Host, ?MODULE,
adhoc_local_items, 50),
ejabberd_hooks:delete(disco_sm_identity, Host, ?MODULE,
get_sm_identity, 50),
ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE,
get_sm_features, 50),
ejabberd_hooks:delete(disco_sm_items, Host, ?MODULE,
get_sm_items, 50),
ejabberd_hooks:delete(disco_local_identity, Host,
?MODULE, get_local_identity, 50),
ejabberd_hooks:delete(disco_local_features, Host,
?MODULE, get_local_features, 50),
ejabberd_hooks:delete(disco_local_items, Host, ?MODULE,
get_local_items, 50).
reload(_Host, _NewOpts, _OldOpts) ->
ok.
depends(_Host, _Opts) ->
[{mod_adhoc, hard}, {mod_last, soft}].
%%%-----------------------------------------------------------------------
-define(INFO_IDENTITY(Category, Type, Name, Lang),
[#identity{category = Category, type = Type, name = tr(Lang, Name)}]).
-define(INFO_COMMAND(Name, Lang),
?INFO_IDENTITY(<<"automation">>, <<"command-node">>,
Name, Lang)).
-define(NODEJID(To, Name, Node),
#disco_item{jid = To, name = tr(Lang, Name), node = Node}).
-define(NODE(Name, Node),
#disco_item{jid = jid:make(Server),
node = Node,
name = tr(Lang, Name)}).
-define(NS_ADMINX(Sub),
<<(?NS_ADMIN)/binary, "#", Sub/binary>>).
-define(NS_ADMINL(Sub),
[<<"http:">>, <<"jabber.org">>, <<"protocol">>,
<<"admin">>, Sub]).
-spec tokenize(binary()) -> [binary()].
tokenize(Node) -> str:tokens(Node, <<"/#">>).
-spec get_sm_identity([identity()], jid(), jid(), binary(), binary()) -> [identity()].
get_sm_identity(Acc, _From, _To, Node, Lang) ->
case Node of
<<"config">> ->
?INFO_COMMAND(?T("Configuration"), Lang);
_ -> Acc
end.
-spec get_local_identity([identity()], jid(), jid(), binary(), binary()) -> [identity()].
get_local_identity(Acc, _From, _To, Node, Lang) ->
LNode = tokenize(Node),
case LNode of
[<<"running nodes">>, ENode] ->
?INFO_IDENTITY(<<"ejabberd">>, <<"node">>, ENode, Lang);
[<<"running nodes">>, _ENode, <<"DB">>] ->
?INFO_COMMAND(?T("Database"), Lang);
[<<"running nodes">>, _ENode, <<"backup">>,
<<"backup">>] ->
?INFO_COMMAND(?T("Backup"), Lang);
[<<"running nodes">>, _ENode, <<"backup">>,
<<"restore">>] ->
?INFO_COMMAND(?T("Restore"), Lang);
[<<"running nodes">>, _ENode, <<"backup">>,
<<"textfile">>] ->
?INFO_COMMAND(?T("Dump to Text File"), Lang);
[<<"running nodes">>, _ENode, <<"import">>,
<<"file">>] ->
?INFO_COMMAND(?T("Import File"), Lang);
[<<"running nodes">>, _ENode, <<"import">>,
<<"dir">>] ->
?INFO_COMMAND(?T("Import Directory"), Lang);
[<<"running nodes">>, _ENode, <<"restart">>] ->
?INFO_COMMAND(?T("Restart Service"), Lang);
[<<"running nodes">>, _ENode, <<"shutdown">>] ->
?INFO_COMMAND(?T("Shut Down Service"), Lang);
?NS_ADMINL(<<"add-user">>) ->
?INFO_COMMAND(?T("Add User"), Lang);
?NS_ADMINL(<<"delete-user">>) ->
?INFO_COMMAND(?T("Delete User"), Lang);
?NS_ADMINL(<<"end-user-session">>) ->
?INFO_COMMAND(?T("End User Session"), Lang);
?NS_ADMINL(<<"get-user-password">>) ->
?INFO_COMMAND(?T("Get User Password"), Lang);
?NS_ADMINL(<<"change-user-password">>) ->
?INFO_COMMAND(?T("Change User Password"), Lang);
?NS_ADMINL(<<"get-user-lastlogin">>) ->
?INFO_COMMAND(?T("Get User Last Login Time"), Lang);
?NS_ADMINL(<<"user-stats">>) ->
?INFO_COMMAND(?T("Get User Statistics"), Lang);
?NS_ADMINL(<<"get-registered-users-list">>) ->
?INFO_COMMAND(?T("Get List of Registered Users"),
Lang);
?NS_ADMINL(<<"get-registered-users-num">>) ->
?INFO_COMMAND(?T("Get Number of Registered Users"),
Lang);
?NS_ADMINL(<<"get-online-users-list">>) ->
?INFO_COMMAND(?T("Get List of Online Users"), Lang);
?NS_ADMINL(<<"get-online-users-num">>) ->
?INFO_COMMAND(?T("Get Number of Online Users"), Lang);
_ -> Acc
end.
%%%-----------------------------------------------------------------------
-define(INFO_RESULT(Allow, Feats, Lang),
case Allow of
deny -> {error, xmpp:err_forbidden(?T("Access denied by service policy"), Lang)};
allow -> {result, Feats}
end).
-spec get_sm_features(mod_disco:features_acc(), jid(), jid(),
binary(), binary()) -> mod_disco:features_acc().
get_sm_features(Acc, From,
#jid{lserver = LServer} = _To, Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
Allow = acl:match_rule(LServer, configure, From),
case Node of
<<"config">> -> ?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
_ -> Acc
end
end.
-spec get_local_features(mod_disco:features_acc(), jid(), jid(),
binary(), binary()) -> mod_disco:features_acc().
get_local_features(Acc, From,
#jid{lserver = LServer} = _To, Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
LNode = tokenize(Node),
Allow = acl:match_rule(LServer, configure, From),
case LNode of
[<<"config">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"user">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"online users">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"all users">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"all users">>, <<$@, _/binary>>] ->
?INFO_RESULT(Allow, [], Lang);
[<<"outgoing s2s">> | _] -> ?INFO_RESULT(Allow, [], Lang);
[<<"running nodes">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"stopped nodes">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"running nodes">>, _ENode] ->
?INFO_RESULT(Allow, [?NS_STATS], Lang);
[<<"running nodes">>, _ENode, <<"DB">>] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"running nodes">>, _ENode, <<"backup">>] ->
?INFO_RESULT(Allow, [], Lang);
[<<"running nodes">>, _ENode, <<"backup">>, _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"running nodes">>, _ENode, <<"import">>] ->
?INFO_RESULT(Allow, [], Lang);
[<<"running nodes">>, _ENode, <<"import">>, _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"running nodes">>, _ENode, <<"restart">>] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"running nodes">>, _ENode, <<"shutdown">>] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"config">>, _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"add-user">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"delete-user">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"end-user-session">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-user-password">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"change-user-password">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-user-lastlogin">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"user-stats">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-registered-users-list">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-registered-users-num">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-online-users-list">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-online-users-num">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
_ -> Acc
end
end.
%%%-----------------------------------------------------------------------
-spec adhoc_sm_items(mod_disco:items_acc(),
jid(), jid(), binary()) -> mod_disco:items_acc().
adhoc_sm_items(Acc, From, #jid{lserver = LServer} = To,
Lang) ->
case acl:match_rule(LServer, configure, From) of
allow ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Nodes = [#disco_item{jid = To, node = <<"config">>,
name = tr(Lang, ?T("Configuration"))}],
{result, Items ++ Nodes};
_ -> Acc
end.
%%%-----------------------------------------------------------------------
-spec get_sm_items(mod_disco:items_acc(), jid(), jid(),
binary(), binary()) -> mod_disco:items_acc().
get_sm_items(Acc, From,
#jid{user = User, server = Server, lserver = LServer} =
To,
Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
case {acl:match_rule(LServer, configure, From), Node} of
{allow, <<"">>} ->
Nodes = [?NODEJID(To, ?T("Configuration"),
<<"config">>),
?NODEJID(To, ?T("User Management"), <<"user">>)],
{result,
Items ++ Nodes ++ get_user_resources(User, Server)};
{allow, <<"config">>} -> {result, []};
{_, <<"config">>} ->
{error, xmpp:err_forbidden(?T("Access denied by service policy"), Lang)};
_ -> Acc
end
end.
-spec get_user_resources(binary(), binary()) -> [disco_item()].
get_user_resources(User, Server) ->
Rs = ejabberd_sm:get_user_resources(User, Server),
lists:map(fun (R) ->
#disco_item{jid = jid:make(User, Server, R),
name = User}
end,
lists:sort(Rs)).
%%%-----------------------------------------------------------------------
-spec adhoc_local_items(mod_disco:items_acc(),
jid(), jid(), binary()) -> mod_disco:items_acc().
adhoc_local_items(Acc, From,
#jid{lserver = LServer, server = Server} = To, Lang) ->
case acl:match_rule(LServer, configure, From) of
allow ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
PermLev = get_permission_level(From),
Nodes = recursively_get_local_items(PermLev, LServer,
<<"">>, Server, Lang),
Nodes1 = lists:filter(
fun (#disco_item{node = Nd}) ->
F = get_local_features(empty, From, To, Nd, Lang),
case F of
{result, [?NS_COMMANDS]} -> true;
_ -> false
end
end,
Nodes),
{result, Items ++ Nodes1};
_ -> Acc
end.
-spec recursively_get_local_items(global | vhost, binary(), binary(),
binary(), binary()) -> [disco_item()].
recursively_get_local_items(_PermLev, _LServer,
<<"online users">>, _Server, _Lang) ->
[];
recursively_get_local_items(_PermLev, _LServer,
<<"all users">>, _Server, _Lang) ->
[];
recursively_get_local_items(PermLev, LServer, Node,
Server, Lang) ->
LNode = tokenize(Node),
Items = case get_local_items({PermLev, LServer}, LNode,
Server, Lang)
of
{result, Res} -> Res;
{error, _Error} -> []
end,
lists:flatten(
lists:map(
fun(#disco_item{jid = #jid{server = S}, node = Nd} = Item) ->
if (S /= Server) or
(Nd == <<"">>) ->
[];
true ->
[Item,
recursively_get_local_items(
PermLev, LServer, Nd, Server, Lang)]
end
end,
Items)).
-spec get_permission_level(jid()) -> global | vhost.
get_permission_level(JID) ->
case acl:match_rule(global, configure, JID) of
allow -> global;
deny -> vhost
end.
%%%-----------------------------------------------------------------------
-define(ITEMS_RESULT(Allow, LNode, Fallback),
case Allow of
deny -> Fallback;
allow ->
PermLev = get_permission_level(From),
case get_local_items({PermLev, LServer}, LNode,
jid:encode(To), Lang)
of
{result, Res} -> {result, Res};
{error, Error} -> {error, Error}
end
end).
-spec get_local_items(mod_disco:items_acc(), jid(), jid(),
binary(), binary()) -> mod_disco:items_acc().
get_local_items(Acc, From, #jid{lserver = LServer} = To,
<<"">>, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Allow = acl:match_rule(LServer, configure, From),
case Allow of
deny -> {result, Items};
allow ->
PermLev = get_permission_level(From),
case get_local_items({PermLev, LServer}, [],
jid:encode(To), Lang)
of
{result, Res} -> {result, Items ++ Res};
{error, _Error} -> {result, Items}
end
end
end;
get_local_items(Acc, From, #jid{lserver = LServer} = To,
Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
LNode = tokenize(Node),
Allow = acl:match_rule(LServer, configure, From),
Err = xmpp:err_forbidden(?T("Access denied by service policy"), Lang),
case LNode of
[<<"config">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"user">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"online users">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"all users">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"all users">>, <<$@, _/binary>>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"outgoing s2s">> | _] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"stopped nodes">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"DB">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"backup">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"backup">>, _] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"import">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"import">>, _] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"restart">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"shutdown">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"config">>, _] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"add-user">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"delete-user">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"end-user-session">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-user-password">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"change-user-password">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-user-lastlogin">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"user-stats">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-registered-users-list">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-registered-users-num">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-online-users-list">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-online-users-num">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
_ -> Acc
end
end.
%%%-----------------------------------------------------------------------
-spec get_local_items({global | vhost, binary()}, [binary()],
binary(), binary()) -> {result, [disco_item()]} | {error, stanza_error()}.
get_local_items(_Host, [], Server, Lang) ->
{result,
[?NODE(?T("Configuration"), <<"config">>),
?NODE(?T("User Management"), <<"user">>),
?NODE(?T("Online Users"), <<"online users">>),
?NODE(?T("All Users"), <<"all users">>),
?NODE(?T("Outgoing s2s Connections"),
<<"outgoing s2s">>),
?NODE(?T("Running Nodes"), <<"running nodes">>),
?NODE(?T("Stopped Nodes"), <<"stopped nodes">>)]};
get_local_items(_Host, [<<"config">>, _], _Server,
_Lang) ->
{result, []};
get_local_items(_Host, [<<"user">>], Server, Lang) ->
{result,
[?NODE(?T("Add User"), (?NS_ADMINX(<<"add-user">>))),
?NODE(?T("Delete User"),
(?NS_ADMINX(<<"delete-user">>))),
?NODE(?T("End User Session"),
(?NS_ADMINX(<<"end-user-session">>))),
?NODE(?T("Get User Password"),
(?NS_ADMINX(<<"get-user-password">>))),
?NODE(?T("Change User Password"),
(?NS_ADMINX(<<"change-user-password">>))),
?NODE(?T("Get User Last Login Time"),
(?NS_ADMINX(<<"get-user-lastlogin">>))),
?NODE(?T("Get User Statistics"),
(?NS_ADMINX(<<"user-stats">>))),
?NODE(?T("Get List of Registered Users"),
(?NS_ADMINX(<<"get-registered-users-list">>))),
?NODE(?T("Get Number of Registered Users"),
(?NS_ADMINX(<<"get-registered-users-num">>))),
?NODE(?T("Get List of Online Users"),
(?NS_ADMINX(<<"get-online-users-list">>))),
?NODE(?T("Get Number of Online Users"),
(?NS_ADMINX(<<"get-online-users-num">>)))]};
get_local_items(_Host, [<<"http:">> | _], _Server,
_Lang) ->
{result, []};
get_local_items({_, Host}, [<<"online users">>],
_Server, _Lang) ->
{result, get_online_vh_users(Host)};
get_local_items({_, Host}, [<<"all users">>], _Server,
_Lang) ->
{result, get_all_vh_users(Host)};
get_local_items({_, Host},
[<<"all users">>, <<$@, Diap/binary>>], _Server,
_Lang) ->
Users = ejabberd_auth:get_users(Host),
SUsers = lists:sort([{S, U} || {U, S} <- Users]),
try
[S1, S2] = ejabberd_regexp:split(Diap, <<"-">>),
N1 = binary_to_integer(S1),
N2 = binary_to_integer(S2),
Sub = lists:sublist(SUsers, N1, N2 - N1 + 1),
{result, lists:map(
fun({S, U}) ->
#disco_item{jid = jid:make(U, S),
name = <<U/binary, $@, S/binary>>}
end, Sub)}
catch _:_ ->
{error, xmpp:err_not_acceptable()}
end;
get_local_items({_, Host}, [<<"outgoing s2s">>],
_Server, Lang) ->
{result, get_outgoing_s2s(Host, Lang)};
get_local_items({_, Host}, [<<"outgoing s2s">>, To],
_Server, Lang) ->
{result, get_outgoing_s2s(Host, Lang, To)};
get_local_items(_Host, [<<"running nodes">>], Server,
Lang) ->
{result, get_running_nodes(Server, Lang)};
get_local_items(_Host, [<<"stopped nodes">>], _Server,
Lang) ->
{result, get_stopped_nodes(Lang)};
get_local_items({global, _Host},
[<<"running nodes">>, ENode], Server, Lang) ->
{result,
[?NODE(?T("Database"),
<<"running nodes/", ENode/binary, "/DB">>),
?NODE(?T("Backup Management"),
<<"running nodes/", ENode/binary, "/backup">>),
?NODE(?T("Import Users From jabberd14 Spool Files"),
<<"running nodes/", ENode/binary, "/import">>),
?NODE(?T("Restart Service"),
<<"running nodes/", ENode/binary, "/restart">>),
?NODE(?T("Shut Down Service"),
<<"running nodes/", ENode/binary, "/shutdown">>)]};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"DB">>], _Server,
_Lang) ->
{result, []};
get_local_items(_Host,
[<<"running nodes">>, ENode, <<"backup">>], Server,
Lang) ->
{result,
[?NODE(?T("Backup"),
<<"running nodes/", ENode/binary, "/backup/backup">>),
?NODE(?T("Restore"),
<<"running nodes/", ENode/binary, "/backup/restore">>),
?NODE(?T("Dump to Text File"),
<<"running nodes/", ENode/binary,
"/backup/textfile">>)]};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"backup">>, _], _Server,
_Lang) ->
{result, []};
get_local_items(_Host,
[<<"running nodes">>, ENode, <<"import">>], Server,
Lang) ->
{result,
[?NODE(?T("Import File"),
<<"running nodes/", ENode/binary, "/import/file">>),
?NODE(?T("Import Directory"),
<<"running nodes/", ENode/binary, "/import/dir">>)]};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"import">>, _], _Server,
_Lang) ->
{result, []};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"restart">>], _Server,
_Lang) ->
{result, []};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"shutdown">>], _Server,
_Lang) ->
{result, []};
get_local_items(_Host, _, _Server, _Lang) ->
{error, xmpp:err_item_not_found()}.
-spec get_online_vh_users(binary()) -> [disco_item()].
get_online_vh_users(Host) ->
USRs = ejabberd_sm:get_vh_session_list(Host),
SURs = lists:sort([{S, U, R} || {U, S, R} <- USRs]),
lists:map(
fun({S, U, R}) ->
#disco_item{jid = jid:make(U, S, R),
name = <<U/binary, "@", S/binary>>}
end, SURs).
-spec get_all_vh_users(binary()) -> [disco_item()].
get_all_vh_users(Host) ->
Users = ejabberd_auth:get_users(Host),
SUsers = lists:sort([{S, U} || {U, S} <- Users]),
case length(SUsers) of
N when N =< 100 ->
lists:map(fun({S, U}) ->
#disco_item{jid = jid:make(U, S),
name = <<U/binary, $@, S/binary>>}
end, SUsers);
N ->
NParts = trunc(math:sqrt(N * 6.17999999999999993783e-1)) + 1,
M = trunc(N / NParts) + 1,
lists:map(
fun (K) ->
L = K + M - 1,
Node = <<"@",
(integer_to_binary(K))/binary,
"-",
(integer_to_binary(L))/binary>>,
{FS, FU} = lists:nth(K, SUsers),
{LS, LU} = if L < N -> lists:nth(L, SUsers);
true -> lists:last(SUsers)
end,
Name = <<FU/binary, "@", FS/binary, " -- ",
LU/binary, "@", LS/binary>>,
#disco_item{jid = jid:make(Host),
node = <<"all users/", Node/binary>>,
name = Name}
end, lists:seq(1, N, M))
end.
-spec get_outgoing_s2s(binary(), binary()) -> [disco_item()].
get_outgoing_s2s(Host, Lang) ->
Connections = ejabberd_s2s:dirty_get_connections(),
DotHost = <<".", Host/binary>>,
TConns = [TH || {FH, TH} <- Connections,
Host == FH orelse str:suffix(DotHost, FH)],
lists:map(
fun (T) ->
Name = str:translate_and_format(Lang, ?T("To ~ts"),[T]),
#disco_item{jid = jid:make(Host),
node = <<"outgoing s2s/", T/binary>>,
name = Name}
end, lists:usort(TConns)).
-spec get_outgoing_s2s(binary(), binary(), binary()) -> [disco_item()].
get_outgoing_s2s(Host, Lang, To) ->
Connections = ejabberd_s2s:dirty_get_connections(),
lists:map(
fun ({F, _T}) ->
Node = <<"outgoing s2s/", To/binary, "/", F/binary>>,
Name = str:translate_and_format(Lang, ?T("From ~ts"), [F]),
#disco_item{jid = jid:make(Host), node = Node, name = Name}
end,
lists:keysort(
1,
lists:filter(fun (E) -> element(2, E) == To end,
Connections))).
-spec get_running_nodes(binary(), binary()) -> [disco_item()].
get_running_nodes(Server, _Lang) ->
DBNodes = mnesia:system_info(running_db_nodes),
lists:map(
fun (N) ->
S = iolist_to_binary(atom_to_list(N)),
#disco_item{jid = jid:make(Server),
node = <<"running nodes/", S/binary>>,
name = S}
end, lists:sort(DBNodes)).
-spec get_stopped_nodes(binary()) -> [disco_item()].
get_stopped_nodes(_Lang) ->
DBNodes = lists:usort(mnesia:system_info(db_nodes) ++
mnesia:system_info(extra_db_nodes))
-- mnesia:system_info(running_db_nodes),
lists:map(
fun (N) ->
S = iolist_to_binary(atom_to_list(N)),
#disco_item{jid = jid:make(ejabberd_config:get_myname()),
node = <<"stopped nodes/", S/binary>>,
name = S}
end, lists:sort(DBNodes)).
%%-------------------------------------------------------------------------
-define(COMMANDS_RESULT(LServerOrGlobal, From, To,
Request, Lang),
case acl:match_rule(LServerOrGlobal, configure, From) of
deny -> {error, xmpp:err_forbidden(?T("Access denied by service policy"), Lang)};
allow -> adhoc_local_commands(From, To, Request)
end).
-spec adhoc_local_commands(adhoc_command(), jid(), jid(), adhoc_command()) ->
adhoc_command() | {error, stanza_error()}.
adhoc_local_commands(Acc, From,
#jid{lserver = LServer} = To,
#adhoc_command{node = Node, lang = Lang} = Request) ->
LNode = tokenize(Node),
case LNode of
[<<"running nodes">>, _ENode, <<"DB">>] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"running nodes">>, _ENode, <<"backup">>, _] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"running nodes">>, _ENode, <<"import">>, _] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"running nodes">>, _ENode, <<"restart">>] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"running nodes">>, _ENode, <<"shutdown">>] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"config">>, _] ->
?COMMANDS_RESULT(LServer, From, To, Request, Lang);
?NS_ADMINL(_) ->
?COMMANDS_RESULT(LServer, From, To, Request, Lang);
_ -> Acc
end.
-spec adhoc_local_commands(jid(), jid(), adhoc_command()) -> adhoc_command() | {error, stanza_error()}.
adhoc_local_commands(From,
#jid{lserver = LServer} = _To,
#adhoc_command{lang = Lang, node = Node,
sid = SessionID, action = Action,
xdata = XData} = Request) ->
LNode = tokenize(Node),
ActionIsExecute = Action == execute orelse Action == complete,
if Action == cancel ->
#adhoc_command{status = canceled, lang = Lang,
node = Node, sid = SessionID};
XData == undefined, ActionIsExecute ->
case get_form(LServer, LNode, Lang) of
{result, Form} ->
xmpp_util:make_adhoc_response(
Request,
#adhoc_command{status = executing, xdata = Form});
{result, Status, Form} ->
xmpp_util:make_adhoc_response(
Request,
#adhoc_command{status = Status, xdata = Form});
{error, Error} -> {error, Error}
end;
XData /= undefined, ActionIsExecute ->
case set_form(From, LServer, LNode, Lang, XData) of
{result, Res} ->
xmpp_util:make_adhoc_response(
Request,
#adhoc_command{xdata = Res, status = completed});
{ ' EXIT ' , _ } - > { error , xmpp : err_bad_request ( ) } ;
{error, Error} -> {error, Error}
end;
true ->
{error, xmpp:err_bad_request(?T("Unexpected action"), Lang)}
end.
-define(TVFIELD(Type, Var, Val),
#xdata_field{type = Type, var = Var, values = [Val]}).
-define(HFIELD(),
?TVFIELD(hidden, <<"FORM_TYPE">>, (?NS_ADMIN))).
-define(TLFIELD(Type, Label, Var),
#xdata_field{type = Type, label = tr(Lang, Label), var = Var}).
-define(XFIELD(Type, Label, Var, Val),
#xdata_field{type = Type, label = tr(Lang, Label),
var = Var, values = [Val]}).
-define(XMFIELD(Type, Label, Var, Vals),
#xdata_field{type = Type, label = tr(Lang, Label),
var = Var, values = Vals}).
-define(TABLEFIELD(Table, Val),
#xdata_field{
type = 'list-single',
label = iolist_to_binary(atom_to_list(Table)),
var = iolist_to_binary(atom_to_list(Table)),
values = [iolist_to_binary(atom_to_list(Val))],
options = [#xdata_option{label = tr(Lang, ?T("RAM copy")),
value = <<"ram_copies">>},
#xdata_option{label = tr(Lang, ?T("RAM and disc copy")),
value = <<"disc_copies">>},
#xdata_option{label = tr(Lang, ?T("Disc only copy")),
value = <<"disc_only_copies">>},
#xdata_option{label = tr(Lang, ?T("Remote copy")),
value = <<"unknown">>}]}).
-spec get_form(binary(), [binary()], binary()) -> {result, xdata()} |
{result, completed, xdata()} |
{error, stanza_error()}.
get_form(_Host, [<<"running nodes">>, ENode, <<"DB">>],
Lang) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case ejabberd_cluster:call(Node, mnesia, system_info, [tables]) of
{badrpc, Reason} ->
?ERROR_MSG("RPC call mnesia:system_info(tables) on node "
"~ts failed: ~p", [Node, Reason]),
{error, xmpp:err_internal_server_error()};
Tables ->
STables = lists:sort(Tables),
Title = <<(tr(Lang, ?T("Database Tables Configuration at ")))/binary,
ENode/binary>>,
Instr = tr(Lang, ?T("Choose storage type of tables")),
try
Fs = lists:map(
fun(Table) ->
case ejabberd_cluster:call(
Node, mnesia, table_info,
[Table, storage_type]) of
Type when is_atom(Type) ->
?TABLEFIELD(Table, Type)
end
end, STables),
{result, #xdata{title = Title,
type = form,
instructions = [Instr],
fields = [?HFIELD()|Fs]}}
catch _:{case_clause, {badrpc, Reason}} ->
?ERROR_MSG("RPC call mnesia:table_info/2 "
"on node ~ts failed: ~p", [Node, Reason]),
{error, xmpp:err_internal_server_error()}
end
end
end;
get_form(_Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"backup">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Backup to File at ")))/binary, ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to backup file"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to File"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"restore">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Restore Backup from File at ")))/binary,
ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to backup file"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to File"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"textfile">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Dump Backup to Text File at ")))/binary,
ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to text file"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to File"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, ENode, <<"import">>, <<"file">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Import User from File at ")))/binary,
ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to jabberd14 spool file"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to File"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, ENode, <<"import">>, <<"dir">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Import Users from Dir at ")))/binary,
ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to jabberd14 spool dir"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to Dir"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, _ENode, <<"restart">>], Lang) ->
Make_option =
fun (LabelNum, LabelUnit, Value) ->
#xdata_option{
label = <<LabelNum/binary, (tr(Lang, LabelUnit))/binary>>,
value = Value}
end,
{result,
#xdata{title = tr(Lang, ?T("Restart Service")),
type = form,
fields = [?HFIELD(),
#xdata_field{
type = 'list-single',
label = tr(Lang, ?T("Time delay")),
var = <<"delay">>,
required = true,
options =
[Make_option(<<"">>, <<"immediately">>, <<"1">>),
Make_option(<<"15 ">>, <<"seconds">>, <<"15">>),
Make_option(<<"30 ">>, <<"seconds">>, <<"30">>),
Make_option(<<"60 ">>, <<"seconds">>, <<"60">>),
Make_option(<<"90 ">>, <<"seconds">>, <<"90">>),
Make_option(<<"2 ">>, <<"minutes">>, <<"120">>),
Make_option(<<"3 ">>, <<"minutes">>, <<"180">>),
Make_option(<<"4 ">>, <<"minutes">>, <<"240">>),
Make_option(<<"5 ">>, <<"minutes">>, <<"300">>),
Make_option(<<"10 ">>, <<"minutes">>, <<"600">>),
Make_option(<<"15 ">>, <<"minutes">>, <<"900">>),
Make_option(<<"30 ">>, <<"minutes">>, <<"1800">>)]},
#xdata_field{type = fixed,
label = tr(Lang,
?T("Send announcement to all online users "
"on all hosts"))},
#xdata_field{var = <<"subject">>,
type = 'text-single',
label = tr(Lang, ?T("Subject"))},
#xdata_field{var = <<"announcement">>,
type = 'text-multi',
label = tr(Lang, ?T("Message body"))}]}};
get_form(_Host,
[<<"running nodes">>, _ENode, <<"shutdown">>], Lang) ->
Make_option =
fun (LabelNum, LabelUnit, Value) ->
#xdata_option{
label = <<LabelNum/binary, (tr(Lang, LabelUnit))/binary>>,
value = Value}
end,
{result,
#xdata{title = tr(Lang, ?T("Shut Down Service")),
type = form,
fields = [?HFIELD(),
#xdata_field{
type = 'list-single',
label = tr(Lang, ?T("Time delay")),
var = <<"delay">>,
required = true,
options =
[Make_option(<<"">>, <<"immediately">>, <<"1">>),
Make_option(<<"15 ">>, <<"seconds">>, <<"15">>),
Make_option(<<"30 ">>, <<"seconds">>, <<"30">>),
Make_option(<<"60 ">>, <<"seconds">>, <<"60">>),
Make_option(<<"90 ">>, <<"seconds">>, <<"90">>),
Make_option(<<"2 ">>, <<"minutes">>, <<"120">>),
Make_option(<<"3 ">>, <<"minutes">>, <<"180">>),
Make_option(<<"4 ">>, <<"minutes">>, <<"240">>),
Make_option(<<"5 ">>, <<"minutes">>, <<"300">>),
Make_option(<<"10 ">>, <<"minutes">>, <<"600">>),
Make_option(<<"15 ">>, <<"minutes">>, <<"900">>),
Make_option(<<"30 ">>, <<"minutes">>, <<"1800">>)]},
#xdata_field{type = fixed,
label = tr(Lang,
?T("Send announcement to all online users "
"on all hosts"))},
#xdata_field{var = <<"subject">>,
type = 'text-single',
label = tr(Lang, ?T("Subject"))},
#xdata_field{var = <<"announcement">>,
type = 'text-multi',
label = tr(Lang, ?T("Message body"))}]}};
get_form(_Host, ?NS_ADMINL(<<"add-user">>), Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Add User")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
required = true,
var = <<"accountjid">>},
#xdata_field{type = 'text-private',
label = tr(Lang, ?T("Password")),
required = true,
var = <<"password">>},
#xdata_field{type = 'text-private',
label = tr(Lang, ?T("Password Verification")),
required = true,
var = <<"password-verify">>}]}};
get_form(_Host, ?NS_ADMINL(<<"delete-user">>), Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Delete User")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-multi',
label = tr(Lang, ?T("Jabber ID")),
required = true,
var = <<"accountjids">>}]}};
get_form(_Host, ?NS_ADMINL(<<"end-user-session">>),
Lang) ->
{result,
#xdata{title = tr(Lang, ?T("End User Session")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
required = true,
var = <<"accountjid">>}]}};
get_form(_Host, ?NS_ADMINL(<<"get-user-password">>),
Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Get User Password")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
var = <<"accountjid">>,
required = true}]}};
get_form(_Host, ?NS_ADMINL(<<"change-user-password">>),
Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Change User Password")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
required = true,
var = <<"accountjid">>},
#xdata_field{type = 'text-private',
label = tr(Lang, ?T("Password")),
required = true,
var = <<"password">>}]}};
get_form(_Host, ?NS_ADMINL(<<"get-user-lastlogin">>),
Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Get User Last Login Time")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
var = <<"accountjid">>,
required = true}]}};
get_form(_Host, ?NS_ADMINL(<<"user-stats">>), Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Get User Statistics")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
var = <<"accountjid">>,
required = true}]}};
get_form(Host, ?NS_ADMINL(<<"get-registered-users-list">>), Lang) ->
Values = [jid:encode(jid:make(U, Host))
|| {U, _} <- ejabberd_auth:get_users(Host)],
{result, completed,
#xdata{type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-multi',
label = tr(Lang, ?T("The list of all users")),
var = <<"registereduserjids">>,
values = Values}]}};
get_form(Host,
?NS_ADMINL(<<"get-registered-users-num">>), Lang) ->
Num = integer_to_binary(ejabberd_auth:count_users(Host)),
{result, completed,
#xdata{type = form,
fields = [?HFIELD(),
#xdata_field{type = 'text-single',
label = tr(Lang, ?T("Number of registered users")),
var = <<"registeredusersnum">>,
values = [Num]}]}};
get_form(Host, ?NS_ADMINL(<<"get-online-users-list">>), Lang) ->
Accounts = [jid:encode(jid:make(U, Host))
|| {U, _, _} <- ejabberd_sm:get_vh_session_list(Host)],
Values = lists:usort(Accounts),
{result, completed,
#xdata{type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-multi',
label = tr(Lang, ?T("The list of all online users")),
var = <<"onlineuserjids">>,
values = Values}]}};
get_form(Host, ?NS_ADMINL(<<"get-online-users-num">>),
Lang) ->
Num = integer_to_binary(ejabberd_sm:get_vh_session_number(Host)),
{result, completed,
#xdata{type = form,
fields = [?HFIELD(),
#xdata_field{type = 'text-single',
label = tr(Lang, ?T("Number of online users")),
var = <<"onlineusersnum">>,
values = [Num]}]}};
get_form(_Host, _, _Lang) ->
{error, xmpp:err_service_unavailable()}.
-spec set_form(jid(), binary(), [binary()], binary(), xdata()) -> {result, xdata() | undefined} |
{error, stanza_error()}.
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"DB">>], Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
lists:foreach(
fun(#xdata_field{var = SVar, values = SVals}) ->
Table = misc:binary_to_atom(SVar),
Type = case SVals of
[<<"unknown">>] -> unknown;
[<<"ram_copies">>] -> ram_copies;
[<<"disc_copies">>] -> disc_copies;
[<<"disc_only_copies">>] -> disc_only_copies;
_ -> false
end,
if Type == false -> ok;
Type == unknown ->
mnesia:del_table_copy(Table, Node);
true ->
case mnesia:add_table_copy(Table, Node, Type) of
{aborted, _} ->
mnesia:change_table_copy_type(
Table, Node, Type);
_ -> ok
end
end
end, XData#xdata.fields),
{result, undefined}
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"backup">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
case ejabberd_cluster:call(
Node, mnesia, backup, [binary_to_list(String)],
timer:minutes(10)) of
{badrpc, Reason} ->
?ERROR_MSG("RPC call mnesia:backup(~ts) to node ~ts "
"failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
{error, Reason} ->
?ERROR_MSG("RPC call mnesia:backup(~ts) to node ~ts "
"failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
_ ->
{result, undefined}
end;
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"restore">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
case ejabberd_cluster:call(
Node, ejabberd_admin, restore,
[String], timer:minutes(10)) of
{badrpc, Reason} ->
?ERROR_MSG("RPC call ejabberd_admin:restore(~ts) to node "
"~ts failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
{error, Reason} ->
?ERROR_MSG("RPC call ejabberd_admin:restore(~ts) to node "
"~ts failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
_ ->
{result, undefined}
end;
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"textfile">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
case ejabberd_cluster:call(
Node, ejabberd_admin, dump_to_textfile,
[String], timer:minutes(10)) of
{badrpc, Reason} ->
?ERROR_MSG("RPC call ejabberd_admin:dump_to_textfile(~ts) "
"to node ~ts failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
{error, Reason} ->
?ERROR_MSG("RPC call ejabberd_admin:dump_to_textfile(~ts) "
"to node ~ts failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
_ ->
{result, undefined}
end;
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"import">>, <<"file">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
ejabberd_cluster:call(Node, jd2ejd, import_file, [String]),
{result, undefined};
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"import">>, <<"dir">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
ejabberd_cluster:call(Node, jd2ejd, import_dir, [String]),
{result, undefined};
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(From, Host,
[<<"running nodes">>, ENode, <<"restart">>], _Lang,
XData) ->
stop_node(From, Host, ENode, restart, XData);
set_form(From, Host,
[<<"running nodes">>, ENode, <<"shutdown">>], _Lang,
XData) ->
stop_node(From, Host, ENode, stop, XData);
set_form(From, Host, ?NS_ADMINL(<<"add-user">>), _Lang,
XData) ->
AccountString = get_value(<<"accountjid">>, XData),
Password = get_value(<<"password">>, XData),
Password = get_value(<<"password-verify">>, XData),
AccountJID = jid:decode(AccountString),
User = AccountJID#jid.luser,
Server = AccountJID#jid.lserver,
true = lists:member(Server, ejabberd_option:hosts()),
true = Server == Host orelse
get_permission_level(From) == global,
case ejabberd_auth:try_register(User, Server, Password) of
ok -> {result, undefined};
{error, exists} -> {error, xmpp:err_conflict()};
{error, not_allowed} -> {error, xmpp:err_not_allowed()}
end;
set_form(From, Host, ?NS_ADMINL(<<"delete-user">>),
_Lang, XData) ->
AccountStringList = get_values(<<"accountjids">>,
XData),
[_ | _] = AccountStringList,
ASL2 = lists:map(fun (AccountString) ->
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
true = ejabberd_auth:user_exists(User, Server),
{User, Server}
end,
AccountStringList),
[ejabberd_auth:remove_user(User, Server)
|| {User, Server} <- ASL2],
{result, undefined};
set_form(From, Host, ?NS_ADMINL(<<"end-user-session">>),
_Lang, XData) ->
AccountString = get_value(<<"accountjid">>, XData),
JID = jid:decode(AccountString),
LServer = JID#jid.lserver,
true = LServer == Host orelse
get_permission_level(From) == global,
case JID#jid.lresource of
<<>> ->
ejabberd_sm:kick_user(JID#jid.luser, JID#jid.lserver);
R ->
ejabberd_sm:kick_user(JID#jid.luser, JID#jid.lserver, R)
end,
{result, undefined};
set_form(From, Host,
?NS_ADMINL(<<"get-user-password">>), Lang, XData) ->
AccountString = get_value(<<"accountjid">>, XData),
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
Password = ejabberd_auth:get_password(User, Server),
true = is_binary(Password),
{result,
#xdata{type = form,
fields = [?HFIELD(),
?XFIELD('jid-single', ?T("Jabber ID"),
<<"accountjid">>, AccountString),
?XFIELD('text-single', ?T("Password"),
<<"password">>, Password)]}};
set_form(From, Host,
?NS_ADMINL(<<"change-user-password">>), _Lang, XData) ->
AccountString = get_value(<<"accountjid">>, XData),
Password = get_value(<<"password">>, XData),
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
true = ejabberd_auth:user_exists(User, Server),
ejabberd_auth:set_password(User, Server, Password),
{result, undefined};
set_form(From, Host,
?NS_ADMINL(<<"get-user-lastlogin">>), Lang, XData) ->
AccountString = get_value(<<"accountjid">>, XData),
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
FLast = case ejabberd_sm:get_user_resources(User,
Server)
of
[] ->
case get_last_info(User, Server) of
not_found -> tr(Lang, ?T("Never"));
{ok, Timestamp, _Status} ->
Shift = Timestamp,
TimeStamp = {Shift div 1000000, Shift rem 1000000, 0},
{{Year, Month, Day}, {Hour, Minute, Second}} =
calendar:now_to_local_time(TimeStamp),
(str:format("~w-~.2.0w-~.2.0w ~.2.0w:~.2.0w:~.2.0w",
[Year, Month, Day, Hour,
Minute, Second]))
end;
_ -> tr(Lang, ?T("Online"))
end,
{result,
#xdata{type = form,
fields = [?HFIELD(),
?XFIELD('jid-single', ?T("Jabber ID"),
<<"accountjid">>, AccountString),
?XFIELD('text-single', ?T("Last login"),
<<"lastlogin">>, FLast)]}};
set_form(From, Host, ?NS_ADMINL(<<"user-stats">>), Lang,
XData) ->
AccountString = get_value(<<"accountjid">>, XData),
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
Resources = ejabberd_sm:get_user_resources(User,
Server),
IPs1 = [ejabberd_sm:get_user_ip(User, Server, Resource)
|| Resource <- Resources],
IPs = [<<(misc:ip_to_list(IP))/binary, ":",
(integer_to_binary(Port))/binary>>
|| {IP, Port} <- IPs1],
Items = ejabberd_hooks:run_fold(roster_get, Server, [],
[{User, Server}]),
Rostersize = integer_to_binary(erlang:length(Items)),
{result,
#xdata{type = form,
fields = [?HFIELD(),
?XFIELD('jid-single', ?T("Jabber ID"),
<<"accountjid">>, AccountString),
?XFIELD('text-single', ?T("Roster size"),
<<"rostersize">>, Rostersize),
?XMFIELD('text-multi', ?T("IP addresses"),
<<"ipaddresses">>, IPs),
?XMFIELD('text-multi', ?T("Resources"),
<<"onlineresources">>, Resources)]}};
set_form(_From, _Host, _, _Lang, _XData) ->
{error, xmpp:err_service_unavailable()}.
-spec get_value(binary(), xdata()) -> binary().
get_value(Field, XData) ->
hd(get_values(Field, XData)).
-spec get_values(binary(), xdata()) -> [binary()].
get_values(Field, XData) ->
xmpp_util:get_xdata_values(Field, XData).
-spec search_running_node(binary()) -> false | node().
search_running_node(SNode) ->
search_running_node(SNode,
mnesia:system_info(running_db_nodes)).
-spec search_running_node(binary(), [node()]) -> false | node().
search_running_node(_, []) -> false;
search_running_node(SNode, [Node | Nodes]) ->
case atom_to_binary(Node, utf8) of
SNode -> Node;
_ -> search_running_node(SNode, Nodes)
end.
-spec stop_node(jid(), binary(), binary(), restart | stop, xdata()) -> {result, undefined}.
stop_node(From, Host, ENode, Action, XData) ->
Delay = binary_to_integer(get_value(<<"delay">>, XData)),
Subject = case get_values(<<"subject">>, XData) of
[] ->
[];
[S|_] ->
[#xdata_field{var = <<"subject">>, values = [S]}]
end,
Announcement = case get_values(<<"announcement">>, XData) of
[] ->
[];
As ->
[#xdata_field{var = <<"body">>, values = As}]
end,
case Subject ++ Announcement of
[] ->
ok;
Fields ->
Request = #adhoc_command{node = ?NS_ADMINX(<<"announce-allhosts">>),
action = complete,
xdata = #xdata{type = submit,
fields = Fields}},
To = jid:make(Host),
mod_announce:announce_commands(empty, From, To, Request)
end,
Time = timer:seconds(Delay),
Node = misc:binary_to_atom(ENode),
{ok, _} = timer:apply_after(Time, ejabberd_cluster, call, [Node, init, Action, []]),
{result, undefined}.
-spec get_last_info(binary(), binary()) -> {ok, non_neg_integer(), binary()} | not_found.
get_last_info(User, Server) ->
case gen_mod:is_loaded(Server, mod_last) of
true -> mod_last:get_last_info(User, Server);
false -> not_found
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec adhoc_sm_commands(adhoc_command(), jid(), jid(), adhoc_command()) -> adhoc_command() |
{error, stanza_error()}.
adhoc_sm_commands(_Acc, From,
#jid{user = User, server = Server, lserver = LServer},
#adhoc_command{lang = Lang, node = <<"config">>,
action = Action, xdata = XData} = Request) ->
case acl:match_rule(LServer, configure, From) of
deny ->
{error, xmpp:err_forbidden(?T("Access denied by service policy"), Lang)};
allow ->
ActionIsExecute = Action == execute orelse Action == complete,
if Action == cancel ->
xmpp_util:make_adhoc_response(
Request, #adhoc_command{status = canceled});
XData == undefined, ActionIsExecute ->
case get_sm_form(User, Server, <<"config">>, Lang) of
{result, Form} ->
xmpp_util:make_adhoc_response(
Request, #adhoc_command{status = executing,
xdata = Form});
{error, Error} ->
{error, Error}
end;
XData /= undefined, ActionIsExecute ->
set_sm_form(User, Server, <<"config">>, Request);
true ->
Txt = ?T("Unexpected action"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
adhoc_sm_commands(Acc, _From, _To, _Request) -> Acc.
-spec get_sm_form(binary(), binary(), binary(), binary()) -> {result, xdata()} |
{error, stanza_error()}.
get_sm_form(User, Server, <<"config">>, Lang) ->
{result,
#xdata{type = form,
title = <<(tr(Lang, ?T("Administration of ")))/binary, User/binary>>,
fields =
[?HFIELD(),
#xdata_field{
type = 'list-single',
label = tr(Lang, ?T("Action on user")),
var = <<"action">>,
values = [<<"edit">>],
options = [#xdata_option{
label = tr(Lang, ?T("Edit Properties")),
value = <<"edit">>},
#xdata_option{
label = tr(Lang, ?T("Remove User")),
value = <<"remove">>}]},
?XFIELD('text-private', ?T("Password"),
<<"password">>,
ejabberd_auth:get_password_s(User, Server))]}};
get_sm_form(_User, _Server, _Node, _Lang) ->
{error, xmpp:err_service_unavailable()}.
-spec set_sm_form(binary(), binary(), binary(), adhoc_command()) -> adhoc_command() |
{error, stanza_error()}.
set_sm_form(User, Server, <<"config">>,
#adhoc_command{lang = Lang, node = Node,
sid = SessionID, xdata = XData}) ->
Response = #adhoc_command{lang = Lang, node = Node,
sid = SessionID, status = completed},
case xmpp_util:get_xdata_values(<<"action">>, XData) of
[<<"edit">>] ->
case xmpp_util:get_xdata_values(<<"password">>, XData) of
[Password] ->
ejabberd_auth:set_password(User, Server, Password),
xmpp_util:make_adhoc_response(Response);
_ ->
Txt = ?T("No 'password' found in data form"),
{error, xmpp:err_not_acceptable(Txt, Lang)}
end;
[<<"remove">>] ->
ejabberd_auth:remove_user(User, Server),
xmpp_util:make_adhoc_response(Response);
_ ->
Txt = ?T("Incorrect value of 'action' in data form"),
{error, xmpp:err_not_acceptable(Txt, Lang)}
end;
set_sm_form(_User, _Server, _Node, _Request) ->
{error, xmpp:err_service_unavailable()}.
-spec tr(binary(), binary()) -> binary().
tr(Lang, Text) ->
translate:translate(Lang, Text).
mod_options(_) -> [].
mod_doc() ->
#{desc =>
?T("The module provides server configuration functionality via "
"-0050.html"
"[XEP-0050: Ad-Hoc Commands]. This module requires "
"_`mod_adhoc`_ to be loaded.")}.
| null | https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/mod_configure.erl | erlang | ----------------------------------------------------------------------
Purpose : Support for online configuration of ejabberd
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-------------------------------------------------------------------------
| File :
Author : < >
Created : 19 Jan 2003 by < >
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(mod_configure).
-author('').
-protocol({xep, 133, '1.1'}).
-behaviour(gen_mod).
-export([start/2, stop/1, reload/3, get_local_identity/5,
get_local_features/5, get_local_items/5,
adhoc_local_items/4, adhoc_local_commands/4,
get_sm_identity/5, get_sm_features/5, get_sm_items/5,
adhoc_sm_items/4, adhoc_sm_commands/4, mod_options/1,
depends/2, mod_doc/0]).
-include("logger.hrl").
-include_lib("xmpp/include/xmpp.hrl").
-include("ejabberd_sm.hrl").
-include("translate.hrl").
-include_lib("stdlib/include/ms_transform.hrl").
start(Host, _Opts) ->
ejabberd_hooks:add(disco_local_items, Host, ?MODULE,
get_local_items, 50),
ejabberd_hooks:add(disco_local_features, Host, ?MODULE,
get_local_features, 50),
ejabberd_hooks:add(disco_local_identity, Host, ?MODULE,
get_local_identity, 50),
ejabberd_hooks:add(disco_sm_items, Host, ?MODULE,
get_sm_items, 50),
ejabberd_hooks:add(disco_sm_features, Host, ?MODULE,
get_sm_features, 50),
ejabberd_hooks:add(disco_sm_identity, Host, ?MODULE,
get_sm_identity, 50),
ejabberd_hooks:add(adhoc_local_items, Host, ?MODULE,
adhoc_local_items, 50),
ejabberd_hooks:add(adhoc_local_commands, Host, ?MODULE,
adhoc_local_commands, 50),
ejabberd_hooks:add(adhoc_sm_items, Host, ?MODULE,
adhoc_sm_items, 50),
ejabberd_hooks:add(adhoc_sm_commands, Host, ?MODULE,
adhoc_sm_commands, 50),
ok.
stop(Host) ->
ejabberd_hooks:delete(adhoc_sm_commands, Host, ?MODULE,
adhoc_sm_commands, 50),
ejabberd_hooks:delete(adhoc_sm_items, Host, ?MODULE,
adhoc_sm_items, 50),
ejabberd_hooks:delete(adhoc_local_commands, Host,
?MODULE, adhoc_local_commands, 50),
ejabberd_hooks:delete(adhoc_local_items, Host, ?MODULE,
adhoc_local_items, 50),
ejabberd_hooks:delete(disco_sm_identity, Host, ?MODULE,
get_sm_identity, 50),
ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE,
get_sm_features, 50),
ejabberd_hooks:delete(disco_sm_items, Host, ?MODULE,
get_sm_items, 50),
ejabberd_hooks:delete(disco_local_identity, Host,
?MODULE, get_local_identity, 50),
ejabberd_hooks:delete(disco_local_features, Host,
?MODULE, get_local_features, 50),
ejabberd_hooks:delete(disco_local_items, Host, ?MODULE,
get_local_items, 50).
reload(_Host, _NewOpts, _OldOpts) ->
ok.
depends(_Host, _Opts) ->
[{mod_adhoc, hard}, {mod_last, soft}].
-define(INFO_IDENTITY(Category, Type, Name, Lang),
[#identity{category = Category, type = Type, name = tr(Lang, Name)}]).
-define(INFO_COMMAND(Name, Lang),
?INFO_IDENTITY(<<"automation">>, <<"command-node">>,
Name, Lang)).
-define(NODEJID(To, Name, Node),
#disco_item{jid = To, name = tr(Lang, Name), node = Node}).
-define(NODE(Name, Node),
#disco_item{jid = jid:make(Server),
node = Node,
name = tr(Lang, Name)}).
-define(NS_ADMINX(Sub),
<<(?NS_ADMIN)/binary, "#", Sub/binary>>).
-define(NS_ADMINL(Sub),
[<<"http:">>, <<"jabber.org">>, <<"protocol">>,
<<"admin">>, Sub]).
-spec tokenize(binary()) -> [binary()].
tokenize(Node) -> str:tokens(Node, <<"/#">>).
-spec get_sm_identity([identity()], jid(), jid(), binary(), binary()) -> [identity()].
get_sm_identity(Acc, _From, _To, Node, Lang) ->
case Node of
<<"config">> ->
?INFO_COMMAND(?T("Configuration"), Lang);
_ -> Acc
end.
-spec get_local_identity([identity()], jid(), jid(), binary(), binary()) -> [identity()].
get_local_identity(Acc, _From, _To, Node, Lang) ->
LNode = tokenize(Node),
case LNode of
[<<"running nodes">>, ENode] ->
?INFO_IDENTITY(<<"ejabberd">>, <<"node">>, ENode, Lang);
[<<"running nodes">>, _ENode, <<"DB">>] ->
?INFO_COMMAND(?T("Database"), Lang);
[<<"running nodes">>, _ENode, <<"backup">>,
<<"backup">>] ->
?INFO_COMMAND(?T("Backup"), Lang);
[<<"running nodes">>, _ENode, <<"backup">>,
<<"restore">>] ->
?INFO_COMMAND(?T("Restore"), Lang);
[<<"running nodes">>, _ENode, <<"backup">>,
<<"textfile">>] ->
?INFO_COMMAND(?T("Dump to Text File"), Lang);
[<<"running nodes">>, _ENode, <<"import">>,
<<"file">>] ->
?INFO_COMMAND(?T("Import File"), Lang);
[<<"running nodes">>, _ENode, <<"import">>,
<<"dir">>] ->
?INFO_COMMAND(?T("Import Directory"), Lang);
[<<"running nodes">>, _ENode, <<"restart">>] ->
?INFO_COMMAND(?T("Restart Service"), Lang);
[<<"running nodes">>, _ENode, <<"shutdown">>] ->
?INFO_COMMAND(?T("Shut Down Service"), Lang);
?NS_ADMINL(<<"add-user">>) ->
?INFO_COMMAND(?T("Add User"), Lang);
?NS_ADMINL(<<"delete-user">>) ->
?INFO_COMMAND(?T("Delete User"), Lang);
?NS_ADMINL(<<"end-user-session">>) ->
?INFO_COMMAND(?T("End User Session"), Lang);
?NS_ADMINL(<<"get-user-password">>) ->
?INFO_COMMAND(?T("Get User Password"), Lang);
?NS_ADMINL(<<"change-user-password">>) ->
?INFO_COMMAND(?T("Change User Password"), Lang);
?NS_ADMINL(<<"get-user-lastlogin">>) ->
?INFO_COMMAND(?T("Get User Last Login Time"), Lang);
?NS_ADMINL(<<"user-stats">>) ->
?INFO_COMMAND(?T("Get User Statistics"), Lang);
?NS_ADMINL(<<"get-registered-users-list">>) ->
?INFO_COMMAND(?T("Get List of Registered Users"),
Lang);
?NS_ADMINL(<<"get-registered-users-num">>) ->
?INFO_COMMAND(?T("Get Number of Registered Users"),
Lang);
?NS_ADMINL(<<"get-online-users-list">>) ->
?INFO_COMMAND(?T("Get List of Online Users"), Lang);
?NS_ADMINL(<<"get-online-users-num">>) ->
?INFO_COMMAND(?T("Get Number of Online Users"), Lang);
_ -> Acc
end.
-define(INFO_RESULT(Allow, Feats, Lang),
case Allow of
deny -> {error, xmpp:err_forbidden(?T("Access denied by service policy"), Lang)};
allow -> {result, Feats}
end).
-spec get_sm_features(mod_disco:features_acc(), jid(), jid(),
binary(), binary()) -> mod_disco:features_acc().
get_sm_features(Acc, From,
#jid{lserver = LServer} = _To, Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
Allow = acl:match_rule(LServer, configure, From),
case Node of
<<"config">> -> ?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
_ -> Acc
end
end.
-spec get_local_features(mod_disco:features_acc(), jid(), jid(),
binary(), binary()) -> mod_disco:features_acc().
get_local_features(Acc, From,
#jid{lserver = LServer} = _To, Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
LNode = tokenize(Node),
Allow = acl:match_rule(LServer, configure, From),
case LNode of
[<<"config">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"user">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"online users">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"all users">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"all users">>, <<$@, _/binary>>] ->
?INFO_RESULT(Allow, [], Lang);
[<<"outgoing s2s">> | _] -> ?INFO_RESULT(Allow, [], Lang);
[<<"running nodes">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"stopped nodes">>] -> ?INFO_RESULT(Allow, [], Lang);
[<<"running nodes">>, _ENode] ->
?INFO_RESULT(Allow, [?NS_STATS], Lang);
[<<"running nodes">>, _ENode, <<"DB">>] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"running nodes">>, _ENode, <<"backup">>] ->
?INFO_RESULT(Allow, [], Lang);
[<<"running nodes">>, _ENode, <<"backup">>, _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"running nodes">>, _ENode, <<"import">>] ->
?INFO_RESULT(Allow, [], Lang);
[<<"running nodes">>, _ENode, <<"import">>, _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"running nodes">>, _ENode, <<"restart">>] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"running nodes">>, _ENode, <<"shutdown">>] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
[<<"config">>, _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"add-user">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"delete-user">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"end-user-session">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-user-password">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"change-user-password">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-user-lastlogin">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"user-stats">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-registered-users-list">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-registered-users-num">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-online-users-list">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
?NS_ADMINL(<<"get-online-users-num">>) ->
?INFO_RESULT(Allow, [?NS_COMMANDS], Lang);
_ -> Acc
end
end.
-spec adhoc_sm_items(mod_disco:items_acc(),
jid(), jid(), binary()) -> mod_disco:items_acc().
adhoc_sm_items(Acc, From, #jid{lserver = LServer} = To,
Lang) ->
case acl:match_rule(LServer, configure, From) of
allow ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Nodes = [#disco_item{jid = To, node = <<"config">>,
name = tr(Lang, ?T("Configuration"))}],
{result, Items ++ Nodes};
_ -> Acc
end.
-spec get_sm_items(mod_disco:items_acc(), jid(), jid(),
binary(), binary()) -> mod_disco:items_acc().
get_sm_items(Acc, From,
#jid{user = User, server = Server, lserver = LServer} =
To,
Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
case {acl:match_rule(LServer, configure, From), Node} of
{allow, <<"">>} ->
Nodes = [?NODEJID(To, ?T("Configuration"),
<<"config">>),
?NODEJID(To, ?T("User Management"), <<"user">>)],
{result,
Items ++ Nodes ++ get_user_resources(User, Server)};
{allow, <<"config">>} -> {result, []};
{_, <<"config">>} ->
{error, xmpp:err_forbidden(?T("Access denied by service policy"), Lang)};
_ -> Acc
end
end.
-spec get_user_resources(binary(), binary()) -> [disco_item()].
get_user_resources(User, Server) ->
Rs = ejabberd_sm:get_user_resources(User, Server),
lists:map(fun (R) ->
#disco_item{jid = jid:make(User, Server, R),
name = User}
end,
lists:sort(Rs)).
-spec adhoc_local_items(mod_disco:items_acc(),
jid(), jid(), binary()) -> mod_disco:items_acc().
adhoc_local_items(Acc, From,
#jid{lserver = LServer, server = Server} = To, Lang) ->
case acl:match_rule(LServer, configure, From) of
allow ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
PermLev = get_permission_level(From),
Nodes = recursively_get_local_items(PermLev, LServer,
<<"">>, Server, Lang),
Nodes1 = lists:filter(
fun (#disco_item{node = Nd}) ->
F = get_local_features(empty, From, To, Nd, Lang),
case F of
{result, [?NS_COMMANDS]} -> true;
_ -> false
end
end,
Nodes),
{result, Items ++ Nodes1};
_ -> Acc
end.
-spec recursively_get_local_items(global | vhost, binary(), binary(),
binary(), binary()) -> [disco_item()].
recursively_get_local_items(_PermLev, _LServer,
<<"online users">>, _Server, _Lang) ->
[];
recursively_get_local_items(_PermLev, _LServer,
<<"all users">>, _Server, _Lang) ->
[];
recursively_get_local_items(PermLev, LServer, Node,
Server, Lang) ->
LNode = tokenize(Node),
Items = case get_local_items({PermLev, LServer}, LNode,
Server, Lang)
of
{result, Res} -> Res;
{error, _Error} -> []
end,
lists:flatten(
lists:map(
fun(#disco_item{jid = #jid{server = S}, node = Nd} = Item) ->
if (S /= Server) or
(Nd == <<"">>) ->
[];
true ->
[Item,
recursively_get_local_items(
PermLev, LServer, Nd, Server, Lang)]
end
end,
Items)).
-spec get_permission_level(jid()) -> global | vhost.
get_permission_level(JID) ->
case acl:match_rule(global, configure, JID) of
allow -> global;
deny -> vhost
end.
-define(ITEMS_RESULT(Allow, LNode, Fallback),
case Allow of
deny -> Fallback;
allow ->
PermLev = get_permission_level(From),
case get_local_items({PermLev, LServer}, LNode,
jid:encode(To), Lang)
of
{result, Res} -> {result, Res};
{error, Error} -> {error, Error}
end
end).
-spec get_local_items(mod_disco:items_acc(), jid(), jid(),
binary(), binary()) -> mod_disco:items_acc().
get_local_items(Acc, From, #jid{lserver = LServer} = To,
<<"">>, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Allow = acl:match_rule(LServer, configure, From),
case Allow of
deny -> {result, Items};
allow ->
PermLev = get_permission_level(From),
case get_local_items({PermLev, LServer}, [],
jid:encode(To), Lang)
of
{result, Res} -> {result, Items ++ Res};
{error, _Error} -> {result, Items}
end
end
end;
get_local_items(Acc, From, #jid{lserver = LServer} = To,
Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false -> Acc;
_ ->
LNode = tokenize(Node),
Allow = acl:match_rule(LServer, configure, From),
Err = xmpp:err_forbidden(?T("Access denied by service policy"), Lang),
case LNode of
[<<"config">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"user">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"online users">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"all users">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"all users">>, <<$@, _/binary>>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"outgoing s2s">> | _] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"stopped nodes">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"DB">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"backup">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"backup">>, _] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"import">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"import">>, _] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"restart">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"running nodes">>, _ENode, <<"shutdown">>] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
[<<"config">>, _] ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"add-user">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"delete-user">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"end-user-session">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-user-password">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"change-user-password">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-user-lastlogin">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"user-stats">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-registered-users-list">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-registered-users-num">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-online-users-list">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
?NS_ADMINL(<<"get-online-users-num">>) ->
?ITEMS_RESULT(Allow, LNode, {error, Err});
_ -> Acc
end
end.
-spec get_local_items({global | vhost, binary()}, [binary()],
binary(), binary()) -> {result, [disco_item()]} | {error, stanza_error()}.
get_local_items(_Host, [], Server, Lang) ->
{result,
[?NODE(?T("Configuration"), <<"config">>),
?NODE(?T("User Management"), <<"user">>),
?NODE(?T("Online Users"), <<"online users">>),
?NODE(?T("All Users"), <<"all users">>),
?NODE(?T("Outgoing s2s Connections"),
<<"outgoing s2s">>),
?NODE(?T("Running Nodes"), <<"running nodes">>),
?NODE(?T("Stopped Nodes"), <<"stopped nodes">>)]};
get_local_items(_Host, [<<"config">>, _], _Server,
_Lang) ->
{result, []};
get_local_items(_Host, [<<"user">>], Server, Lang) ->
{result,
[?NODE(?T("Add User"), (?NS_ADMINX(<<"add-user">>))),
?NODE(?T("Delete User"),
(?NS_ADMINX(<<"delete-user">>))),
?NODE(?T("End User Session"),
(?NS_ADMINX(<<"end-user-session">>))),
?NODE(?T("Get User Password"),
(?NS_ADMINX(<<"get-user-password">>))),
?NODE(?T("Change User Password"),
(?NS_ADMINX(<<"change-user-password">>))),
?NODE(?T("Get User Last Login Time"),
(?NS_ADMINX(<<"get-user-lastlogin">>))),
?NODE(?T("Get User Statistics"),
(?NS_ADMINX(<<"user-stats">>))),
?NODE(?T("Get List of Registered Users"),
(?NS_ADMINX(<<"get-registered-users-list">>))),
?NODE(?T("Get Number of Registered Users"),
(?NS_ADMINX(<<"get-registered-users-num">>))),
?NODE(?T("Get List of Online Users"),
(?NS_ADMINX(<<"get-online-users-list">>))),
?NODE(?T("Get Number of Online Users"),
(?NS_ADMINX(<<"get-online-users-num">>)))]};
get_local_items(_Host, [<<"http:">> | _], _Server,
_Lang) ->
{result, []};
get_local_items({_, Host}, [<<"online users">>],
_Server, _Lang) ->
{result, get_online_vh_users(Host)};
get_local_items({_, Host}, [<<"all users">>], _Server,
_Lang) ->
{result, get_all_vh_users(Host)};
get_local_items({_, Host},
[<<"all users">>, <<$@, Diap/binary>>], _Server,
_Lang) ->
Users = ejabberd_auth:get_users(Host),
SUsers = lists:sort([{S, U} || {U, S} <- Users]),
try
[S1, S2] = ejabberd_regexp:split(Diap, <<"-">>),
N1 = binary_to_integer(S1),
N2 = binary_to_integer(S2),
Sub = lists:sublist(SUsers, N1, N2 - N1 + 1),
{result, lists:map(
fun({S, U}) ->
#disco_item{jid = jid:make(U, S),
name = <<U/binary, $@, S/binary>>}
end, Sub)}
catch _:_ ->
{error, xmpp:err_not_acceptable()}
end;
get_local_items({_, Host}, [<<"outgoing s2s">>],
_Server, Lang) ->
{result, get_outgoing_s2s(Host, Lang)};
get_local_items({_, Host}, [<<"outgoing s2s">>, To],
_Server, Lang) ->
{result, get_outgoing_s2s(Host, Lang, To)};
get_local_items(_Host, [<<"running nodes">>], Server,
Lang) ->
{result, get_running_nodes(Server, Lang)};
get_local_items(_Host, [<<"stopped nodes">>], _Server,
Lang) ->
{result, get_stopped_nodes(Lang)};
get_local_items({global, _Host},
[<<"running nodes">>, ENode], Server, Lang) ->
{result,
[?NODE(?T("Database"),
<<"running nodes/", ENode/binary, "/DB">>),
?NODE(?T("Backup Management"),
<<"running nodes/", ENode/binary, "/backup">>),
?NODE(?T("Import Users From jabberd14 Spool Files"),
<<"running nodes/", ENode/binary, "/import">>),
?NODE(?T("Restart Service"),
<<"running nodes/", ENode/binary, "/restart">>),
?NODE(?T("Shut Down Service"),
<<"running nodes/", ENode/binary, "/shutdown">>)]};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"DB">>], _Server,
_Lang) ->
{result, []};
get_local_items(_Host,
[<<"running nodes">>, ENode, <<"backup">>], Server,
Lang) ->
{result,
[?NODE(?T("Backup"),
<<"running nodes/", ENode/binary, "/backup/backup">>),
?NODE(?T("Restore"),
<<"running nodes/", ENode/binary, "/backup/restore">>),
?NODE(?T("Dump to Text File"),
<<"running nodes/", ENode/binary,
"/backup/textfile">>)]};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"backup">>, _], _Server,
_Lang) ->
{result, []};
get_local_items(_Host,
[<<"running nodes">>, ENode, <<"import">>], Server,
Lang) ->
{result,
[?NODE(?T("Import File"),
<<"running nodes/", ENode/binary, "/import/file">>),
?NODE(?T("Import Directory"),
<<"running nodes/", ENode/binary, "/import/dir">>)]};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"import">>, _], _Server,
_Lang) ->
{result, []};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"restart">>], _Server,
_Lang) ->
{result, []};
get_local_items(_Host,
[<<"running nodes">>, _ENode, <<"shutdown">>], _Server,
_Lang) ->
{result, []};
get_local_items(_Host, _, _Server, _Lang) ->
{error, xmpp:err_item_not_found()}.
-spec get_online_vh_users(binary()) -> [disco_item()].
get_online_vh_users(Host) ->
USRs = ejabberd_sm:get_vh_session_list(Host),
SURs = lists:sort([{S, U, R} || {U, S, R} <- USRs]),
lists:map(
fun({S, U, R}) ->
#disco_item{jid = jid:make(U, S, R),
name = <<U/binary, "@", S/binary>>}
end, SURs).
-spec get_all_vh_users(binary()) -> [disco_item()].
get_all_vh_users(Host) ->
Users = ejabberd_auth:get_users(Host),
SUsers = lists:sort([{S, U} || {U, S} <- Users]),
case length(SUsers) of
N when N =< 100 ->
lists:map(fun({S, U}) ->
#disco_item{jid = jid:make(U, S),
name = <<U/binary, $@, S/binary>>}
end, SUsers);
N ->
NParts = trunc(math:sqrt(N * 6.17999999999999993783e-1)) + 1,
M = trunc(N / NParts) + 1,
lists:map(
fun (K) ->
L = K + M - 1,
Node = <<"@",
(integer_to_binary(K))/binary,
"-",
(integer_to_binary(L))/binary>>,
{FS, FU} = lists:nth(K, SUsers),
{LS, LU} = if L < N -> lists:nth(L, SUsers);
true -> lists:last(SUsers)
end,
Name = <<FU/binary, "@", FS/binary, " -- ",
LU/binary, "@", LS/binary>>,
#disco_item{jid = jid:make(Host),
node = <<"all users/", Node/binary>>,
name = Name}
end, lists:seq(1, N, M))
end.
-spec get_outgoing_s2s(binary(), binary()) -> [disco_item()].
get_outgoing_s2s(Host, Lang) ->
Connections = ejabberd_s2s:dirty_get_connections(),
DotHost = <<".", Host/binary>>,
TConns = [TH || {FH, TH} <- Connections,
Host == FH orelse str:suffix(DotHost, FH)],
lists:map(
fun (T) ->
Name = str:translate_and_format(Lang, ?T("To ~ts"),[T]),
#disco_item{jid = jid:make(Host),
node = <<"outgoing s2s/", T/binary>>,
name = Name}
end, lists:usort(TConns)).
-spec get_outgoing_s2s(binary(), binary(), binary()) -> [disco_item()].
get_outgoing_s2s(Host, Lang, To) ->
Connections = ejabberd_s2s:dirty_get_connections(),
lists:map(
fun ({F, _T}) ->
Node = <<"outgoing s2s/", To/binary, "/", F/binary>>,
Name = str:translate_and_format(Lang, ?T("From ~ts"), [F]),
#disco_item{jid = jid:make(Host), node = Node, name = Name}
end,
lists:keysort(
1,
lists:filter(fun (E) -> element(2, E) == To end,
Connections))).
-spec get_running_nodes(binary(), binary()) -> [disco_item()].
get_running_nodes(Server, _Lang) ->
DBNodes = mnesia:system_info(running_db_nodes),
lists:map(
fun (N) ->
S = iolist_to_binary(atom_to_list(N)),
#disco_item{jid = jid:make(Server),
node = <<"running nodes/", S/binary>>,
name = S}
end, lists:sort(DBNodes)).
-spec get_stopped_nodes(binary()) -> [disco_item()].
get_stopped_nodes(_Lang) ->
DBNodes = lists:usort(mnesia:system_info(db_nodes) ++
mnesia:system_info(extra_db_nodes))
-- mnesia:system_info(running_db_nodes),
lists:map(
fun (N) ->
S = iolist_to_binary(atom_to_list(N)),
#disco_item{jid = jid:make(ejabberd_config:get_myname()),
node = <<"stopped nodes/", S/binary>>,
name = S}
end, lists:sort(DBNodes)).
-define(COMMANDS_RESULT(LServerOrGlobal, From, To,
Request, Lang),
case acl:match_rule(LServerOrGlobal, configure, From) of
deny -> {error, xmpp:err_forbidden(?T("Access denied by service policy"), Lang)};
allow -> adhoc_local_commands(From, To, Request)
end).
-spec adhoc_local_commands(adhoc_command(), jid(), jid(), adhoc_command()) ->
adhoc_command() | {error, stanza_error()}.
adhoc_local_commands(Acc, From,
#jid{lserver = LServer} = To,
#adhoc_command{node = Node, lang = Lang} = Request) ->
LNode = tokenize(Node),
case LNode of
[<<"running nodes">>, _ENode, <<"DB">>] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"running nodes">>, _ENode, <<"backup">>, _] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"running nodes">>, _ENode, <<"import">>, _] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"running nodes">>, _ENode, <<"restart">>] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"running nodes">>, _ENode, <<"shutdown">>] ->
?COMMANDS_RESULT(global, From, To, Request, Lang);
[<<"config">>, _] ->
?COMMANDS_RESULT(LServer, From, To, Request, Lang);
?NS_ADMINL(_) ->
?COMMANDS_RESULT(LServer, From, To, Request, Lang);
_ -> Acc
end.
-spec adhoc_local_commands(jid(), jid(), adhoc_command()) -> adhoc_command() | {error, stanza_error()}.
adhoc_local_commands(From,
#jid{lserver = LServer} = _To,
#adhoc_command{lang = Lang, node = Node,
sid = SessionID, action = Action,
xdata = XData} = Request) ->
LNode = tokenize(Node),
ActionIsExecute = Action == execute orelse Action == complete,
if Action == cancel ->
#adhoc_command{status = canceled, lang = Lang,
node = Node, sid = SessionID};
XData == undefined, ActionIsExecute ->
case get_form(LServer, LNode, Lang) of
{result, Form} ->
xmpp_util:make_adhoc_response(
Request,
#adhoc_command{status = executing, xdata = Form});
{result, Status, Form} ->
xmpp_util:make_adhoc_response(
Request,
#adhoc_command{status = Status, xdata = Form});
{error, Error} -> {error, Error}
end;
XData /= undefined, ActionIsExecute ->
case set_form(From, LServer, LNode, Lang, XData) of
{result, Res} ->
xmpp_util:make_adhoc_response(
Request,
#adhoc_command{xdata = Res, status = completed});
{ ' EXIT ' , _ } - > { error , xmpp : err_bad_request ( ) } ;
{error, Error} -> {error, Error}
end;
true ->
{error, xmpp:err_bad_request(?T("Unexpected action"), Lang)}
end.
-define(TVFIELD(Type, Var, Val),
#xdata_field{type = Type, var = Var, values = [Val]}).
-define(HFIELD(),
?TVFIELD(hidden, <<"FORM_TYPE">>, (?NS_ADMIN))).
-define(TLFIELD(Type, Label, Var),
#xdata_field{type = Type, label = tr(Lang, Label), var = Var}).
-define(XFIELD(Type, Label, Var, Val),
#xdata_field{type = Type, label = tr(Lang, Label),
var = Var, values = [Val]}).
-define(XMFIELD(Type, Label, Var, Vals),
#xdata_field{type = Type, label = tr(Lang, Label),
var = Var, values = Vals}).
-define(TABLEFIELD(Table, Val),
#xdata_field{
type = 'list-single',
label = iolist_to_binary(atom_to_list(Table)),
var = iolist_to_binary(atom_to_list(Table)),
values = [iolist_to_binary(atom_to_list(Val))],
options = [#xdata_option{label = tr(Lang, ?T("RAM copy")),
value = <<"ram_copies">>},
#xdata_option{label = tr(Lang, ?T("RAM and disc copy")),
value = <<"disc_copies">>},
#xdata_option{label = tr(Lang, ?T("Disc only copy")),
value = <<"disc_only_copies">>},
#xdata_option{label = tr(Lang, ?T("Remote copy")),
value = <<"unknown">>}]}).
-spec get_form(binary(), [binary()], binary()) -> {result, xdata()} |
{result, completed, xdata()} |
{error, stanza_error()}.
get_form(_Host, [<<"running nodes">>, ENode, <<"DB">>],
Lang) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case ejabberd_cluster:call(Node, mnesia, system_info, [tables]) of
{badrpc, Reason} ->
?ERROR_MSG("RPC call mnesia:system_info(tables) on node "
"~ts failed: ~p", [Node, Reason]),
{error, xmpp:err_internal_server_error()};
Tables ->
STables = lists:sort(Tables),
Title = <<(tr(Lang, ?T("Database Tables Configuration at ")))/binary,
ENode/binary>>,
Instr = tr(Lang, ?T("Choose storage type of tables")),
try
Fs = lists:map(
fun(Table) ->
case ejabberd_cluster:call(
Node, mnesia, table_info,
[Table, storage_type]) of
Type when is_atom(Type) ->
?TABLEFIELD(Table, Type)
end
end, STables),
{result, #xdata{title = Title,
type = form,
instructions = [Instr],
fields = [?HFIELD()|Fs]}}
catch _:{case_clause, {badrpc, Reason}} ->
?ERROR_MSG("RPC call mnesia:table_info/2 "
"on node ~ts failed: ~p", [Node, Reason]),
{error, xmpp:err_internal_server_error()}
end
end
end;
get_form(_Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"backup">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Backup to File at ")))/binary, ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to backup file"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to File"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"restore">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Restore Backup from File at ")))/binary,
ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to backup file"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to File"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"textfile">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Dump Backup to Text File at ")))/binary,
ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to text file"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to File"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, ENode, <<"import">>, <<"file">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Import User from File at ")))/binary,
ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to jabberd14 spool file"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to File"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, ENode, <<"import">>, <<"dir">>],
Lang) ->
{result,
#xdata{title = <<(tr(Lang, ?T("Import Users from Dir at ")))/binary,
ENode/binary>>,
type = form,
instructions = [tr(Lang, ?T("Enter path to jabberd14 spool dir"))],
fields = [?HFIELD(),
?XFIELD('text-single', ?T("Path to Dir"),
<<"path">>, <<"">>)]}};
get_form(_Host,
[<<"running nodes">>, _ENode, <<"restart">>], Lang) ->
Make_option =
fun (LabelNum, LabelUnit, Value) ->
#xdata_option{
label = <<LabelNum/binary, (tr(Lang, LabelUnit))/binary>>,
value = Value}
end,
{result,
#xdata{title = tr(Lang, ?T("Restart Service")),
type = form,
fields = [?HFIELD(),
#xdata_field{
type = 'list-single',
label = tr(Lang, ?T("Time delay")),
var = <<"delay">>,
required = true,
options =
[Make_option(<<"">>, <<"immediately">>, <<"1">>),
Make_option(<<"15 ">>, <<"seconds">>, <<"15">>),
Make_option(<<"30 ">>, <<"seconds">>, <<"30">>),
Make_option(<<"60 ">>, <<"seconds">>, <<"60">>),
Make_option(<<"90 ">>, <<"seconds">>, <<"90">>),
Make_option(<<"2 ">>, <<"minutes">>, <<"120">>),
Make_option(<<"3 ">>, <<"minutes">>, <<"180">>),
Make_option(<<"4 ">>, <<"minutes">>, <<"240">>),
Make_option(<<"5 ">>, <<"minutes">>, <<"300">>),
Make_option(<<"10 ">>, <<"minutes">>, <<"600">>),
Make_option(<<"15 ">>, <<"minutes">>, <<"900">>),
Make_option(<<"30 ">>, <<"minutes">>, <<"1800">>)]},
#xdata_field{type = fixed,
label = tr(Lang,
?T("Send announcement to all online users "
"on all hosts"))},
#xdata_field{var = <<"subject">>,
type = 'text-single',
label = tr(Lang, ?T("Subject"))},
#xdata_field{var = <<"announcement">>,
type = 'text-multi',
label = tr(Lang, ?T("Message body"))}]}};
get_form(_Host,
[<<"running nodes">>, _ENode, <<"shutdown">>], Lang) ->
Make_option =
fun (LabelNum, LabelUnit, Value) ->
#xdata_option{
label = <<LabelNum/binary, (tr(Lang, LabelUnit))/binary>>,
value = Value}
end,
{result,
#xdata{title = tr(Lang, ?T("Shut Down Service")),
type = form,
fields = [?HFIELD(),
#xdata_field{
type = 'list-single',
label = tr(Lang, ?T("Time delay")),
var = <<"delay">>,
required = true,
options =
[Make_option(<<"">>, <<"immediately">>, <<"1">>),
Make_option(<<"15 ">>, <<"seconds">>, <<"15">>),
Make_option(<<"30 ">>, <<"seconds">>, <<"30">>),
Make_option(<<"60 ">>, <<"seconds">>, <<"60">>),
Make_option(<<"90 ">>, <<"seconds">>, <<"90">>),
Make_option(<<"2 ">>, <<"minutes">>, <<"120">>),
Make_option(<<"3 ">>, <<"minutes">>, <<"180">>),
Make_option(<<"4 ">>, <<"minutes">>, <<"240">>),
Make_option(<<"5 ">>, <<"minutes">>, <<"300">>),
Make_option(<<"10 ">>, <<"minutes">>, <<"600">>),
Make_option(<<"15 ">>, <<"minutes">>, <<"900">>),
Make_option(<<"30 ">>, <<"minutes">>, <<"1800">>)]},
#xdata_field{type = fixed,
label = tr(Lang,
?T("Send announcement to all online users "
"on all hosts"))},
#xdata_field{var = <<"subject">>,
type = 'text-single',
label = tr(Lang, ?T("Subject"))},
#xdata_field{var = <<"announcement">>,
type = 'text-multi',
label = tr(Lang, ?T("Message body"))}]}};
get_form(_Host, ?NS_ADMINL(<<"add-user">>), Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Add User")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
required = true,
var = <<"accountjid">>},
#xdata_field{type = 'text-private',
label = tr(Lang, ?T("Password")),
required = true,
var = <<"password">>},
#xdata_field{type = 'text-private',
label = tr(Lang, ?T("Password Verification")),
required = true,
var = <<"password-verify">>}]}};
get_form(_Host, ?NS_ADMINL(<<"delete-user">>), Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Delete User")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-multi',
label = tr(Lang, ?T("Jabber ID")),
required = true,
var = <<"accountjids">>}]}};
get_form(_Host, ?NS_ADMINL(<<"end-user-session">>),
Lang) ->
{result,
#xdata{title = tr(Lang, ?T("End User Session")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
required = true,
var = <<"accountjid">>}]}};
get_form(_Host, ?NS_ADMINL(<<"get-user-password">>),
Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Get User Password")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
var = <<"accountjid">>,
required = true}]}};
get_form(_Host, ?NS_ADMINL(<<"change-user-password">>),
Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Change User Password")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
required = true,
var = <<"accountjid">>},
#xdata_field{type = 'text-private',
label = tr(Lang, ?T("Password")),
required = true,
var = <<"password">>}]}};
get_form(_Host, ?NS_ADMINL(<<"get-user-lastlogin">>),
Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Get User Last Login Time")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
var = <<"accountjid">>,
required = true}]}};
get_form(_Host, ?NS_ADMINL(<<"user-stats">>), Lang) ->
{result,
#xdata{title = tr(Lang, ?T("Get User Statistics")),
type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-single',
label = tr(Lang, ?T("Jabber ID")),
var = <<"accountjid">>,
required = true}]}};
get_form(Host, ?NS_ADMINL(<<"get-registered-users-list">>), Lang) ->
Values = [jid:encode(jid:make(U, Host))
|| {U, _} <- ejabberd_auth:get_users(Host)],
{result, completed,
#xdata{type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-multi',
label = tr(Lang, ?T("The list of all users")),
var = <<"registereduserjids">>,
values = Values}]}};
get_form(Host,
?NS_ADMINL(<<"get-registered-users-num">>), Lang) ->
Num = integer_to_binary(ejabberd_auth:count_users(Host)),
{result, completed,
#xdata{type = form,
fields = [?HFIELD(),
#xdata_field{type = 'text-single',
label = tr(Lang, ?T("Number of registered users")),
var = <<"registeredusersnum">>,
values = [Num]}]}};
get_form(Host, ?NS_ADMINL(<<"get-online-users-list">>), Lang) ->
Accounts = [jid:encode(jid:make(U, Host))
|| {U, _, _} <- ejabberd_sm:get_vh_session_list(Host)],
Values = lists:usort(Accounts),
{result, completed,
#xdata{type = form,
fields = [?HFIELD(),
#xdata_field{type = 'jid-multi',
label = tr(Lang, ?T("The list of all online users")),
var = <<"onlineuserjids">>,
values = Values}]}};
get_form(Host, ?NS_ADMINL(<<"get-online-users-num">>),
Lang) ->
Num = integer_to_binary(ejabberd_sm:get_vh_session_number(Host)),
{result, completed,
#xdata{type = form,
fields = [?HFIELD(),
#xdata_field{type = 'text-single',
label = tr(Lang, ?T("Number of online users")),
var = <<"onlineusersnum">>,
values = [Num]}]}};
get_form(_Host, _, _Lang) ->
{error, xmpp:err_service_unavailable()}.
-spec set_form(jid(), binary(), [binary()], binary(), xdata()) -> {result, xdata() | undefined} |
{error, stanza_error()}.
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"DB">>], Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
lists:foreach(
fun(#xdata_field{var = SVar, values = SVals}) ->
Table = misc:binary_to_atom(SVar),
Type = case SVals of
[<<"unknown">>] -> unknown;
[<<"ram_copies">>] -> ram_copies;
[<<"disc_copies">>] -> disc_copies;
[<<"disc_only_copies">>] -> disc_only_copies;
_ -> false
end,
if Type == false -> ok;
Type == unknown ->
mnesia:del_table_copy(Table, Node);
true ->
case mnesia:add_table_copy(Table, Node, Type) of
{aborted, _} ->
mnesia:change_table_copy_type(
Table, Node, Type);
_ -> ok
end
end
end, XData#xdata.fields),
{result, undefined}
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"backup">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
case ejabberd_cluster:call(
Node, mnesia, backup, [binary_to_list(String)],
timer:minutes(10)) of
{badrpc, Reason} ->
?ERROR_MSG("RPC call mnesia:backup(~ts) to node ~ts "
"failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
{error, Reason} ->
?ERROR_MSG("RPC call mnesia:backup(~ts) to node ~ts "
"failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
_ ->
{result, undefined}
end;
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"restore">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
case ejabberd_cluster:call(
Node, ejabberd_admin, restore,
[String], timer:minutes(10)) of
{badrpc, Reason} ->
?ERROR_MSG("RPC call ejabberd_admin:restore(~ts) to node "
"~ts failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
{error, Reason} ->
?ERROR_MSG("RPC call ejabberd_admin:restore(~ts) to node "
"~ts failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
_ ->
{result, undefined}
end;
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"backup">>,
<<"textfile">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
case ejabberd_cluster:call(
Node, ejabberd_admin, dump_to_textfile,
[String], timer:minutes(10)) of
{badrpc, Reason} ->
?ERROR_MSG("RPC call ejabberd_admin:dump_to_textfile(~ts) "
"to node ~ts failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
{error, Reason} ->
?ERROR_MSG("RPC call ejabberd_admin:dump_to_textfile(~ts) "
"to node ~ts failed: ~p", [String, Node, Reason]),
{error, xmpp:err_internal_server_error()};
_ ->
{result, undefined}
end;
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"import">>, <<"file">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
ejabberd_cluster:call(Node, jd2ejd, import_file, [String]),
{result, undefined};
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(_From, _Host,
[<<"running nodes">>, ENode, <<"import">>, <<"dir">>],
Lang, XData) ->
case search_running_node(ENode) of
false ->
Txt = ?T("No running node found"),
{error, xmpp:err_item_not_found(Txt, Lang)};
Node ->
case xmpp_util:get_xdata_values(<<"path">>, XData) of
[] ->
Txt = ?T("No 'path' found in data form"),
{error, xmpp:err_bad_request(Txt, Lang)};
[String] ->
ejabberd_cluster:call(Node, jd2ejd, import_dir, [String]),
{result, undefined};
_ ->
Txt = ?T("Incorrect value of 'path' in data form"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
set_form(From, Host,
[<<"running nodes">>, ENode, <<"restart">>], _Lang,
XData) ->
stop_node(From, Host, ENode, restart, XData);
set_form(From, Host,
[<<"running nodes">>, ENode, <<"shutdown">>], _Lang,
XData) ->
stop_node(From, Host, ENode, stop, XData);
set_form(From, Host, ?NS_ADMINL(<<"add-user">>), _Lang,
XData) ->
AccountString = get_value(<<"accountjid">>, XData),
Password = get_value(<<"password">>, XData),
Password = get_value(<<"password-verify">>, XData),
AccountJID = jid:decode(AccountString),
User = AccountJID#jid.luser,
Server = AccountJID#jid.lserver,
true = lists:member(Server, ejabberd_option:hosts()),
true = Server == Host orelse
get_permission_level(From) == global,
case ejabberd_auth:try_register(User, Server, Password) of
ok -> {result, undefined};
{error, exists} -> {error, xmpp:err_conflict()};
{error, not_allowed} -> {error, xmpp:err_not_allowed()}
end;
set_form(From, Host, ?NS_ADMINL(<<"delete-user">>),
_Lang, XData) ->
AccountStringList = get_values(<<"accountjids">>,
XData),
[_ | _] = AccountStringList,
ASL2 = lists:map(fun (AccountString) ->
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
true = ejabberd_auth:user_exists(User, Server),
{User, Server}
end,
AccountStringList),
[ejabberd_auth:remove_user(User, Server)
|| {User, Server} <- ASL2],
{result, undefined};
set_form(From, Host, ?NS_ADMINL(<<"end-user-session">>),
_Lang, XData) ->
AccountString = get_value(<<"accountjid">>, XData),
JID = jid:decode(AccountString),
LServer = JID#jid.lserver,
true = LServer == Host orelse
get_permission_level(From) == global,
case JID#jid.lresource of
<<>> ->
ejabberd_sm:kick_user(JID#jid.luser, JID#jid.lserver);
R ->
ejabberd_sm:kick_user(JID#jid.luser, JID#jid.lserver, R)
end,
{result, undefined};
set_form(From, Host,
?NS_ADMINL(<<"get-user-password">>), Lang, XData) ->
AccountString = get_value(<<"accountjid">>, XData),
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
Password = ejabberd_auth:get_password(User, Server),
true = is_binary(Password),
{result,
#xdata{type = form,
fields = [?HFIELD(),
?XFIELD('jid-single', ?T("Jabber ID"),
<<"accountjid">>, AccountString),
?XFIELD('text-single', ?T("Password"),
<<"password">>, Password)]}};
set_form(From, Host,
?NS_ADMINL(<<"change-user-password">>), _Lang, XData) ->
AccountString = get_value(<<"accountjid">>, XData),
Password = get_value(<<"password">>, XData),
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
true = ejabberd_auth:user_exists(User, Server),
ejabberd_auth:set_password(User, Server, Password),
{result, undefined};
set_form(From, Host,
?NS_ADMINL(<<"get-user-lastlogin">>), Lang, XData) ->
AccountString = get_value(<<"accountjid">>, XData),
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
FLast = case ejabberd_sm:get_user_resources(User,
Server)
of
[] ->
case get_last_info(User, Server) of
not_found -> tr(Lang, ?T("Never"));
{ok, Timestamp, _Status} ->
Shift = Timestamp,
TimeStamp = {Shift div 1000000, Shift rem 1000000, 0},
{{Year, Month, Day}, {Hour, Minute, Second}} =
calendar:now_to_local_time(TimeStamp),
(str:format("~w-~.2.0w-~.2.0w ~.2.0w:~.2.0w:~.2.0w",
[Year, Month, Day, Hour,
Minute, Second]))
end;
_ -> tr(Lang, ?T("Online"))
end,
{result,
#xdata{type = form,
fields = [?HFIELD(),
?XFIELD('jid-single', ?T("Jabber ID"),
<<"accountjid">>, AccountString),
?XFIELD('text-single', ?T("Last login"),
<<"lastlogin">>, FLast)]}};
set_form(From, Host, ?NS_ADMINL(<<"user-stats">>), Lang,
XData) ->
AccountString = get_value(<<"accountjid">>, XData),
JID = jid:decode(AccountString),
User = JID#jid.luser,
Server = JID#jid.lserver,
true = Server == Host orelse
get_permission_level(From) == global,
Resources = ejabberd_sm:get_user_resources(User,
Server),
IPs1 = [ejabberd_sm:get_user_ip(User, Server, Resource)
|| Resource <- Resources],
IPs = [<<(misc:ip_to_list(IP))/binary, ":",
(integer_to_binary(Port))/binary>>
|| {IP, Port} <- IPs1],
Items = ejabberd_hooks:run_fold(roster_get, Server, [],
[{User, Server}]),
Rostersize = integer_to_binary(erlang:length(Items)),
{result,
#xdata{type = form,
fields = [?HFIELD(),
?XFIELD('jid-single', ?T("Jabber ID"),
<<"accountjid">>, AccountString),
?XFIELD('text-single', ?T("Roster size"),
<<"rostersize">>, Rostersize),
?XMFIELD('text-multi', ?T("IP addresses"),
<<"ipaddresses">>, IPs),
?XMFIELD('text-multi', ?T("Resources"),
<<"onlineresources">>, Resources)]}};
set_form(_From, _Host, _, _Lang, _XData) ->
{error, xmpp:err_service_unavailable()}.
-spec get_value(binary(), xdata()) -> binary().
get_value(Field, XData) ->
hd(get_values(Field, XData)).
-spec get_values(binary(), xdata()) -> [binary()].
get_values(Field, XData) ->
xmpp_util:get_xdata_values(Field, XData).
-spec search_running_node(binary()) -> false | node().
search_running_node(SNode) ->
search_running_node(SNode,
mnesia:system_info(running_db_nodes)).
-spec search_running_node(binary(), [node()]) -> false | node().
search_running_node(_, []) -> false;
search_running_node(SNode, [Node | Nodes]) ->
case atom_to_binary(Node, utf8) of
SNode -> Node;
_ -> search_running_node(SNode, Nodes)
end.
-spec stop_node(jid(), binary(), binary(), restart | stop, xdata()) -> {result, undefined}.
stop_node(From, Host, ENode, Action, XData) ->
Delay = binary_to_integer(get_value(<<"delay">>, XData)),
Subject = case get_values(<<"subject">>, XData) of
[] ->
[];
[S|_] ->
[#xdata_field{var = <<"subject">>, values = [S]}]
end,
Announcement = case get_values(<<"announcement">>, XData) of
[] ->
[];
As ->
[#xdata_field{var = <<"body">>, values = As}]
end,
case Subject ++ Announcement of
[] ->
ok;
Fields ->
Request = #adhoc_command{node = ?NS_ADMINX(<<"announce-allhosts">>),
action = complete,
xdata = #xdata{type = submit,
fields = Fields}},
To = jid:make(Host),
mod_announce:announce_commands(empty, From, To, Request)
end,
Time = timer:seconds(Delay),
Node = misc:binary_to_atom(ENode),
{ok, _} = timer:apply_after(Time, ejabberd_cluster, call, [Node, init, Action, []]),
{result, undefined}.
-spec get_last_info(binary(), binary()) -> {ok, non_neg_integer(), binary()} | not_found.
get_last_info(User, Server) ->
case gen_mod:is_loaded(Server, mod_last) of
true -> mod_last:get_last_info(User, Server);
false -> not_found
end.
-spec adhoc_sm_commands(adhoc_command(), jid(), jid(), adhoc_command()) -> adhoc_command() |
{error, stanza_error()}.
adhoc_sm_commands(_Acc, From,
#jid{user = User, server = Server, lserver = LServer},
#adhoc_command{lang = Lang, node = <<"config">>,
action = Action, xdata = XData} = Request) ->
case acl:match_rule(LServer, configure, From) of
deny ->
{error, xmpp:err_forbidden(?T("Access denied by service policy"), Lang)};
allow ->
ActionIsExecute = Action == execute orelse Action == complete,
if Action == cancel ->
xmpp_util:make_adhoc_response(
Request, #adhoc_command{status = canceled});
XData == undefined, ActionIsExecute ->
case get_sm_form(User, Server, <<"config">>, Lang) of
{result, Form} ->
xmpp_util:make_adhoc_response(
Request, #adhoc_command{status = executing,
xdata = Form});
{error, Error} ->
{error, Error}
end;
XData /= undefined, ActionIsExecute ->
set_sm_form(User, Server, <<"config">>, Request);
true ->
Txt = ?T("Unexpected action"),
{error, xmpp:err_bad_request(Txt, Lang)}
end
end;
adhoc_sm_commands(Acc, _From, _To, _Request) -> Acc.
-spec get_sm_form(binary(), binary(), binary(), binary()) -> {result, xdata()} |
{error, stanza_error()}.
get_sm_form(User, Server, <<"config">>, Lang) ->
{result,
#xdata{type = form,
title = <<(tr(Lang, ?T("Administration of ")))/binary, User/binary>>,
fields =
[?HFIELD(),
#xdata_field{
type = 'list-single',
label = tr(Lang, ?T("Action on user")),
var = <<"action">>,
values = [<<"edit">>],
options = [#xdata_option{
label = tr(Lang, ?T("Edit Properties")),
value = <<"edit">>},
#xdata_option{
label = tr(Lang, ?T("Remove User")),
value = <<"remove">>}]},
?XFIELD('text-private', ?T("Password"),
<<"password">>,
ejabberd_auth:get_password_s(User, Server))]}};
get_sm_form(_User, _Server, _Node, _Lang) ->
{error, xmpp:err_service_unavailable()}.
-spec set_sm_form(binary(), binary(), binary(), adhoc_command()) -> adhoc_command() |
{error, stanza_error()}.
set_sm_form(User, Server, <<"config">>,
#adhoc_command{lang = Lang, node = Node,
sid = SessionID, xdata = XData}) ->
Response = #adhoc_command{lang = Lang, node = Node,
sid = SessionID, status = completed},
case xmpp_util:get_xdata_values(<<"action">>, XData) of
[<<"edit">>] ->
case xmpp_util:get_xdata_values(<<"password">>, XData) of
[Password] ->
ejabberd_auth:set_password(User, Server, Password),
xmpp_util:make_adhoc_response(Response);
_ ->
Txt = ?T("No 'password' found in data form"),
{error, xmpp:err_not_acceptable(Txt, Lang)}
end;
[<<"remove">>] ->
ejabberd_auth:remove_user(User, Server),
xmpp_util:make_adhoc_response(Response);
_ ->
Txt = ?T("Incorrect value of 'action' in data form"),
{error, xmpp:err_not_acceptable(Txt, Lang)}
end;
set_sm_form(_User, _Server, _Node, _Request) ->
{error, xmpp:err_service_unavailable()}.
-spec tr(binary(), binary()) -> binary().
tr(Lang, Text) ->
translate:translate(Lang, Text).
mod_options(_) -> [].
mod_doc() ->
#{desc =>
?T("The module provides server configuration functionality via "
"-0050.html"
"[XEP-0050: Ad-Hoc Commands]. This module requires "
"_`mod_adhoc`_ to be loaded.")}.
|
874d6b5a6af62b9a12654bb4ab6eced68eb94bbeec15eea2c6ce1a118c0f0a23 | realworldocaml/book | coq_lib_name.mli | open Import
(* This file is licensed under The MIT License *)
( c ) MINES ParisTech 2018 - 2019
(* (c) INRIA 2020 *)
Written by :
(* This is in its own file due to dependency issues *)
* A Coq library name is a dot - separated list of Coq module identifiers .
type t
val compare : t -> t -> Ordering.t
* Returns the wrapper name , a dot - separated list of Coq module identifies
val wrapper : t -> string
(** Returns the directory name for a lib name, in this case library name foo.bar
lives in foo/bar *)
val dir : t -> string
val encode : t Dune_lang.Encoder.t
val decode : (Loc.t * t) Dune_lang.Decoder.t
(* to be removed in favor of encode / decode *)
val to_string : t -> string
val pp : t -> t Pp.t
val to_dyn : t -> Dyn.t
module Map : Map.S with type key = t
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_rules/coq_lib_name.mli | ocaml | This file is licensed under The MIT License
(c) INRIA 2020
This is in its own file due to dependency issues
* Returns the directory name for a lib name, in this case library name foo.bar
lives in foo/bar
to be removed in favor of encode / decode | open Import
( c ) MINES ParisTech 2018 - 2019
Written by :
* A Coq library name is a dot - separated list of Coq module identifiers .
type t
val compare : t -> t -> Ordering.t
* Returns the wrapper name , a dot - separated list of Coq module identifies
val wrapper : t -> string
val dir : t -> string
val encode : t Dune_lang.Encoder.t
val decode : (Loc.t * t) Dune_lang.Decoder.t
val to_string : t -> string
val pp : t -> t Pp.t
val to_dyn : t -> Dyn.t
module Map : Map.S with type key = t
|
733ca0b52431ebce434dbeb16e4977b9d32c59a0701c9b6a4e23841ce6fb4af7 | rjnw/sham | stx.rkt | #lang racket
(require racket/generic
(for-template racket racket/syntax))
(require "generics.rkt")
(provide (all-defined-out))
(define to-syntax ->syntax)
converts a list of stx into an actual list syntax
(define (seq->syntax . stxs)
(define fs (flatten (->syntax (flatten stxs))))
#`(#,@fs))
(define (stx-seq . stxs) (stx:seq (flatten stxs)))
(struct stx:seq [stxs]
#:methods gen:stx
[(define (->syntax ss) (seq->syntax (stx:seq-stxs ss)))])
(struct stx:forced-seq [stx]
#:methods gen:stx
[(define (->syntax fs)
(syntax-e (to-syntax (stx:forced-seq-stx fs))))])
(define (stx-define-values vars vals)
#`(define-values #,(to-syntax vars) #,(to-syntax vals)))
(struct stx:def [vars vals]
#:methods gen:stx
[(define (->syntax ds)
(match-define (stx:def vars vals) ds)
(cond
[(list? vars)
#`(define-values #,(to-syntax vars) #,(to-syntax vals))]
[(not (list? vars))
#`(define #,(to-syntax vars) #,(to-syntax vals))]
[else (error 'sham/sam/stx "unknown vars and vals in define: ~a ~a" vars vals)]))])
(struct stx:local-def [type defs body]
#:methods gen:stx
[(define (->syntax sld)
(match-define (stx:local-def type defs body) sld)
(seq->syntax
(to-syntax type)
(apply seq->syntax
(for/list [(def defs)]
TODO check for values
(match def
[(stx:def vars vals) (seq->syntax (to-syntax vars) (to-syntax vals))]
[(cons vars vals) (seq->syntax (to-syntax vars) (to-syntax vals))]
[else (error 'sham/sam/stx "unknown definition for local def ~a" def)])))
(to-syntax body)))])
(struct stx:lam [args body]
#:methods gen:stx
[(define (->syntax sl)
(match-define (stx:lam args body) sl)
#`(λ #,(to-syntax args) #,(to-syntax body)))])
(struct stx:app [op rands]
#:methods gen:stx
[(define (->syntax sa)
(match-define (stx:app op rands) sa)
#`(#,(to-syntax op) . #,(seq->syntax rands)))])
(struct stx:match [inp cases]
#:methods gen:stx
[(define (->syntax sm)
(match-define (stx:match inp cases) sm)
#`(match #,(to-syntax inp) #,@(map seq->syntax cases)))])
(struct stx:qs [s]
#:methods gen:stx
[(define (->syntax qs)
(match-define (stx:qs s) qs)
#`(#,#'quasisyntax #,s))])
(struct stx:uns [s]
#:methods gen:stx
[(define (->syntax qs)
(match-define (stx:uns s) qs)
#`(#,#'unsyntax #,s))])
| null | https://raw.githubusercontent.com/rjnw/sham/6e0524b1eb01bcda83ae7a5be6339da4257c6781/sham-sam/sham/sam/syntax/stx.rkt | racket | #lang racket
(require racket/generic
(for-template racket racket/syntax))
(require "generics.rkt")
(provide (all-defined-out))
(define to-syntax ->syntax)
converts a list of stx into an actual list syntax
(define (seq->syntax . stxs)
(define fs (flatten (->syntax (flatten stxs))))
#`(#,@fs))
(define (stx-seq . stxs) (stx:seq (flatten stxs)))
(struct stx:seq [stxs]
#:methods gen:stx
[(define (->syntax ss) (seq->syntax (stx:seq-stxs ss)))])
(struct stx:forced-seq [stx]
#:methods gen:stx
[(define (->syntax fs)
(syntax-e (to-syntax (stx:forced-seq-stx fs))))])
(define (stx-define-values vars vals)
#`(define-values #,(to-syntax vars) #,(to-syntax vals)))
(struct stx:def [vars vals]
#:methods gen:stx
[(define (->syntax ds)
(match-define (stx:def vars vals) ds)
(cond
[(list? vars)
#`(define-values #,(to-syntax vars) #,(to-syntax vals))]
[(not (list? vars))
#`(define #,(to-syntax vars) #,(to-syntax vals))]
[else (error 'sham/sam/stx "unknown vars and vals in define: ~a ~a" vars vals)]))])
(struct stx:local-def [type defs body]
#:methods gen:stx
[(define (->syntax sld)
(match-define (stx:local-def type defs body) sld)
(seq->syntax
(to-syntax type)
(apply seq->syntax
(for/list [(def defs)]
TODO check for values
(match def
[(stx:def vars vals) (seq->syntax (to-syntax vars) (to-syntax vals))]
[(cons vars vals) (seq->syntax (to-syntax vars) (to-syntax vals))]
[else (error 'sham/sam/stx "unknown definition for local def ~a" def)])))
(to-syntax body)))])
(struct stx:lam [args body]
#:methods gen:stx
[(define (->syntax sl)
(match-define (stx:lam args body) sl)
#`(λ #,(to-syntax args) #,(to-syntax body)))])
(struct stx:app [op rands]
#:methods gen:stx
[(define (->syntax sa)
(match-define (stx:app op rands) sa)
#`(#,(to-syntax op) . #,(seq->syntax rands)))])
(struct stx:match [inp cases]
#:methods gen:stx
[(define (->syntax sm)
(match-define (stx:match inp cases) sm)
#`(match #,(to-syntax inp) #,@(map seq->syntax cases)))])
(struct stx:qs [s]
#:methods gen:stx
[(define (->syntax qs)
(match-define (stx:qs s) qs)
#`(#,#'quasisyntax #,s))])
(struct stx:uns [s]
#:methods gen:stx
[(define (->syntax qs)
(match-define (stx:uns s) qs)
#`(#,#'unsyntax #,s))])
| |
5fbda35412f5f4a1a7b8e1a6937b7c637c587ec964a13ee6d226731deaa1b2e6 | cljdoc/cljdoc | layout.clj | (ns cljdoc.render.layout
"Components to layout cljdoc pages"
(:require [cljdoc.server.routes :as routes]
[cljdoc.config :as config]
[cljdoc.render.assets :as assets]
[cljdoc.render.links :as links]
[cljdoc.util.scm :as scm]
[cljdoc-shared.proj :as proj]
[clojure.string :as string]
[hiccup2.core :as hiccup]
[hiccup.page]))
(defn highlight-js-customization []
[:script
(hiccup/raw
"hljs.configure({ignoreUnescapedHTML: true});
hljs.addPlugin(mergeHTMLPlugin);
hljs.registerLanguage('cljs', function (hljs) { return hljs.getLanguage('clj') });
hljs.highlightAll();")])
(defn highlight-js []
[:div
(apply hiccup.page/include-js (assets/js :highlightjs))
(highlight-js-customization)])
(defn mathjax2-customizations [opts]
[:script {:type "text/x-mathjax-config"}
(hiccup/raw
(->> ["MathJax.Hub.Config({"
(format " showMathMenu: %s," (:show-math-menu opts))
" messageStyle: 'none',"
" tex2jax: {"
" inlineMath: [['\\\\(', '\\\\)']],"
" displayMath: [['\\\\[', '\\\\]']],"
" ignoreClass: 'nostem|nolatexmath'"
" },"
" asciimath2jax: {"
" delimiters: [['\\\\$', '\\\\$']],"
" ignoreClass: 'nostem|noasciimath'"
" },"
" TeX: { equationNumbers: { autoNumber: 'none' },"
" }"
"})"
""
"MathJax.Hub.Register.StartupHook('AsciiMath Jax Ready', function () {"
" MathJax.InputJax.AsciiMath.postfilterHooks.Add(function (data, node) {"
" if ((node = data.script.parentNode) && (node = node.parentNode) && node.classList.contains('stemblock')) {"
" data.math.root.display = 'block'"
" }"
" return data"
" })"
"})"]
(string/join "\n")))])
(defn add-requested-features [features]
(when (:mathjax features)
(list (mathjax2-customizations {:show-math-menu true})
(apply hiccup.page/include-js (assets/js :mathjax)))))
(defn generic-description
"Returns a generic description of a project."
[{:keys [group-id artifact-id version] :as version-entity}]
(format "Documentation for %s v%s on cljdoc." (proj/clojars-id version-entity) version))
(defn description
"Return a string to be used as description meta tag for a given project's documentation pages."
[version-entity]
(str (generic-description version-entity)
" "
"A website that builds and hosts documentation for Clojure/Script libraries."))
(defn artifact-description
"Return a string to be used as description meta tag for a given project's documentation pages.
This description is same as the description in project's pom.xml file."
[version-entity artifact-desc]
(str (proj/clojars-id version-entity) ": " artifact-desc " " (generic-description version-entity)))
(defn no-js-warning
"A small development utility component that will show a warning when
the browser can't retrieve the application's JS sources."
[opts]
[:div.fixed.left-0.right-0.bottom-0.bg-washed-red.code.b--light-red.bw3.ba.dn
{:id "no-js-warning"}
[:script
(hiccup/raw (str "fetch(\"" (get (:static-resources opts) "/cljdoc.js")) "\").then(e => e.status === 200 ? null : document.getElementById('no-js-warning').classList.remove('dn'))")]
[:p.ph4 "Could not find JavaScript assets, please refer to " [:a.fw7.link {:href (links/github-url :running-locally)} "the documentation"] " for how to build JS assets."]])
(defn page [opts contents]
(hiccup/html {:mode :html}
(hiccup.page/doctype :html5)
[:html {}
[:head
[:title (:title-attributes opts) (:title opts)]
[:meta {:charset "utf-8"}]
[:meta {:content (:description opts) :name "description"}]
Google / Search Engine Tags
[:meta {:content (:title opts) :itemprop "name"}]
[:meta {:content (:description opts) :itemprop "description"}]
[:meta {:content (str ""
(get (:static-resources opts) "/cljdoc-logo-beta-square.png"))
:itemprop "image"}]
OpenGraph Meta Tags ( should work for Twitter / Facebook )
;; TODO [:meta {:content "" :property "og:url"}]
[:meta {:content "website" :property "og:type"}]
[:meta {:content (:title opts) :property "og:title"}]
[:meta {:content (:description opts) :property "og:description"}]
Disable image for now ; does n't add much and occupies a lot of space in Slack and similar
;; [:meta {:content (str ""
;; (get (:static-resources opts) "/cljdoc-logo-beta-square.png"))
;; :property "og:image"}]
;; Canonical URL
(when-let [url (:canonical-url opts)]
(assert (string/starts-with? url "/"))
TODO read domain from config
[:link {:rel "icon" :type "image/x-icon" :href "/favicon.ico"}]
Open Search
[:link {:rel "search" :type "application/opensearchdescription+xml"
:href "/opensearch.xml" :title "cljdoc"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]
(apply hiccup.page/include-css (assets/css :tachyons))
(hiccup.page/include-css (get (:static-resources opts) "/cljdoc.css"))]
[:body
[:div.sans-serif
contents]
(when (not= :prod (config/profile))
(no-js-warning opts))
[:div#cljdoc-switcher]
[:script {:src (get (:static-resources opts) "/cljdoc.js")}]
(highlight-js)
(add-requested-features (:page-features opts))]]))
(defn sidebar-title
([title]
(sidebar-title title {:separator-line? true}))
([title {:keys [separator-line?]}]
[:h4.relative.ttu.f7.fw5.mt1.mb2.tracked.gray
(when separator-line?
;; .nl4 and .nr4 are negative margins based on the global padding used in the sidebar
[:hr.absolute.left-0.right-0.nl3.nr3.nl4-ns.nr4-ns.b--solid.b--black-10])
;; again negative margins are used to make the background reach over the text container
[:span.relative.nl2.nr2.ph2.bg-white title]]))
(defn meta-info-dialog []
[:div
[:img#js--meta-icon.ma3.fixed.right-0.bottom-0.bg-white.dn.db-ns.pointer
{:src "-clone.vercel.app/explore/48/357edd"}]
[:div#js--meta-dialog.ma3.pa3.ba.br3.b--blue.bw2.w-20.fixed.right-0.bottom-0.bg-white.dn
[:p.ma0
[:b "cljdoc"]
" is a website building & hosting documentation for Clojure/Script libraries"]
(into [:div.mv3]
(map (fn [[description link]]
[:a.db.link.black.mv1.pv3.tc.br2.pointer
{:href link, :style {:background-color "#ECF2FB"}}
description])
[["Keyboard shortcuts" (routes/url-for :shortcuts)]
["Report a problem" (links/github-url :issues)]
;; ["Recent improvements" "#"] TODO add link once it exists
["cljdoc on GitHub" (links/github-url :home)]]))
[:a#js--meta-close.link.black.fr.pointer
"× close"]]])
(def home-link
[:a {:href "/"}
[:span.link.dib.v-mid.mr3.pv1.ph2.ba.hover-blue.br1.ttu.b.silver.tracked
{:style "font-size:10px"}
"cljdoc"]])
(defn top-bar-generic []
[:nav.pv2.ph3.pv3-ns.ph4-ns.bb.b--black-10.flex.items-center home-link])
(defn top-bar [version-entity scm-url]
[:nav.pv2.ph3.pv3-ns.ph4-ns.bb.b--black-10.flex.items-center.bg-white
[:a.dib.v-mid.link.dim.black.b.f6.mr3 {:href (routes/url-for :artifact/version :path-params version-entity)}
(proj/clojars-id version-entity)]
[:a.dib.v-mid.link.dim.gray.f6.mr3
{:href (routes/url-for :artifact/index :path-params version-entity)}
(:version version-entity)]
home-link
[:div.tr
{:style {:flex-grow 1}}
[:form.dn.dib-ns.mr3 {:action "/api/request-build2" :method "POST"}
[:input.pa2.mr2.br2.ba.outline-0.blue {:type "hidden" :id "project" :name "project" :value (str (:group-id version-entity) "/" (:artifact-id version-entity))}]
[:input.pa2.mr2.br2.ba.outline-0.blue {:type "hidden" :id "version" :name "version" :value (:version version-entity)}]
[:input.f7.white.hover-near-white.outline-0.bn.bg-white {:type "submit" :value "rebuild"}]]
(cond
(and scm-url (scm/http-uri scm-url))
[:a.link.dim.gray.f6.tr
{:href (scm/http-uri scm-url)}
[:img.v-mid.w1.h1.mr2-ns {:src (scm/icon-url scm-url)}]
[:span.v-mid.dib-ns.dn (scm/coordinate (scm/http-uri scm-url))]]
(and scm-url (scm/fs-uri scm-url))
[:span.f6 (scm/fs-uri scm-url)]
:else
[:a.f6.link.blue {:href (links/github-url :userguide/scm-faq)} "SCM info missing"])]])
;; Responsive Layout -----------------------------------------------------------
(def r-main-container
"Everything that's rendered on cljdoc goes into this container.
On desktop screens it fills the viewport forcing child nodes
to scroll. On smaller screens it grows with the content allowing
Safari to properly condense the URL bar when scrolling.
In contrast if the container was fixed on mobile as well Safari
would perceive the scroll events as if the user scrolled in a
smaller portion of the UI.
While `height: 100vh` would also work on desktop screens there are some
known issues around [using viewport height units on mobile](-hoizey.com/2015/02/viewport-height-is-taller-than-the-visible-part-of-the-document-in-some-mobile-browsers.html)."
:div.flex.flex-column.fixed-ns.bottom-0.left-0.right-0.top-0)
(def r-sidebar-container
:nav.js--main-sidebar.w5.pa3.pa4-ns.br.b--black-10.db-ns.dn.overflow-y-scroll.border-box.flex-shrink-0)
(def r-api-sidebar-container
:div.js--namespace-contents-scroll-view.w5.pa3.pa4-ns.br.b--black-10.db-ns.dn.overflow-y-scroll.flex-shrink-0)
(def r-content-container
:div.js--main-scroll-view.db-ns.ph3.pl5-ns.pr4-ns.flex-grow-1.overflow-y-scroll)
(def r-top-bar-container
"Additional wrapping to make the top bar responsive
On small screens we render the top bar and mobile navigation as a
`fixed` div so that the main container can be scrolled without the
navigation being scrolled out of view.
On regular sized screens we use the default positioning setting of
`static` so that the top bar is rendered as a row of the main
container.
The z-index `z-3` setting is necessary to ensure `fixed` elements
appear above other elements"
:div.fixed.top-0.left-0.right-0.static-ns.flex-shrink-0.z-3)
(def mobile-nav-spacer
"Spacer so fixed navigation elements don't overlap content
This is only needed on small screens so `dn-ns` hides it
on non-small screens
The height has been found by trial and error."
[:div.bg-blue.dn-ns.pt4.tc
{:style {:height "5.2rem"}}
TODO render different fun messages for each request
[:span.b.white.mt3 "Liking cljdoc? Tell your friends :D"]])
(defn layout
[{:keys [top-bar
main-sidebar-contents
vars-sidebar-contents
content]}]
[r-main-container
[r-top-bar-container
top-bar
[:div#js--mobile-nav.db.dn-ns]]
mobile-nav-spacer
[:div.flex.flex-row
;; Without min-height: 0 the sidebar and main content area won't
be scrollable in Firefox , see this SO comment :
/#comment76873071_44948158
{:style {:min-height 0}}
(into [r-sidebar-container] main-sidebar-contents)
(when (seq vars-sidebar-contents)
(into [r-api-sidebar-container] vars-sidebar-contents))
;; (when doc-html doc-nav)
[r-content-container content]
(meta-info-dialog)]])
| null | https://raw.githubusercontent.com/cljdoc/cljdoc/81408a436c8099036be1451df012a94dbaf0b4ae/src/cljdoc/render/layout.clj | clojure |
")])
TODO [:meta {:content "" :property "og:url"}]
does n't add much and occupies a lot of space in Slack and similar
[:meta {:content (str ""
(get (:static-resources opts) "/cljdoc-logo-beta-square.png"))
:property "og:image"}]
Canonical URL
.nl4 and .nr4 are negative margins based on the global padding used in the sidebar
again negative margins are used to make the background reach over the text container
["Recent improvements" "#"] TODO add link once it exists
Responsive Layout -----------------------------------------------------------
Without min-height: 0 the sidebar and main content area won't
(when doc-html doc-nav) | (ns cljdoc.render.layout
"Components to layout cljdoc pages"
(:require [cljdoc.server.routes :as routes]
[cljdoc.config :as config]
[cljdoc.render.assets :as assets]
[cljdoc.render.links :as links]
[cljdoc.util.scm :as scm]
[cljdoc-shared.proj :as proj]
[clojure.string :as string]
[hiccup2.core :as hiccup]
[hiccup.page]))
(defn highlight-js-customization []
[:script
(hiccup/raw
(defn highlight-js []
[:div
(apply hiccup.page/include-js (assets/js :highlightjs))
(highlight-js-customization)])
(defn mathjax2-customizations [opts]
[:script {:type "text/x-mathjax-config"}
(hiccup/raw
(->> ["MathJax.Hub.Config({"
(format " showMathMenu: %s," (:show-math-menu opts))
" messageStyle: 'none',"
" tex2jax: {"
" inlineMath: [['\\\\(', '\\\\)']],"
" displayMath: [['\\\\[', '\\\\]']],"
" ignoreClass: 'nostem|nolatexmath'"
" },"
" asciimath2jax: {"
" delimiters: [['\\\\$', '\\\\$']],"
" ignoreClass: 'nostem|noasciimath'"
" },"
" TeX: { equationNumbers: { autoNumber: 'none' },"
" }"
"})"
""
"MathJax.Hub.Register.StartupHook('AsciiMath Jax Ready', function () {"
" MathJax.InputJax.AsciiMath.postfilterHooks.Add(function (data, node) {"
" if ((node = data.script.parentNode) && (node = node.parentNode) && node.classList.contains('stemblock')) {"
" data.math.root.display = 'block'"
" }"
" return data"
" })"
"})"]
(string/join "\n")))])
(defn add-requested-features [features]
(when (:mathjax features)
(list (mathjax2-customizations {:show-math-menu true})
(apply hiccup.page/include-js (assets/js :mathjax)))))
(defn generic-description
"Returns a generic description of a project."
[{:keys [group-id artifact-id version] :as version-entity}]
(format "Documentation for %s v%s on cljdoc." (proj/clojars-id version-entity) version))
(defn description
"Return a string to be used as description meta tag for a given project's documentation pages."
[version-entity]
(str (generic-description version-entity)
" "
"A website that builds and hosts documentation for Clojure/Script libraries."))
(defn artifact-description
"Return a string to be used as description meta tag for a given project's documentation pages.
This description is same as the description in project's pom.xml file."
[version-entity artifact-desc]
(str (proj/clojars-id version-entity) ": " artifact-desc " " (generic-description version-entity)))
(defn no-js-warning
"A small development utility component that will show a warning when
the browser can't retrieve the application's JS sources."
[opts]
[:div.fixed.left-0.right-0.bottom-0.bg-washed-red.code.b--light-red.bw3.ba.dn
{:id "no-js-warning"}
[:script
(hiccup/raw (str "fetch(\"" (get (:static-resources opts) "/cljdoc.js")) "\").then(e => e.status === 200 ? null : document.getElementById('no-js-warning').classList.remove('dn'))")]
[:p.ph4 "Could not find JavaScript assets, please refer to " [:a.fw7.link {:href (links/github-url :running-locally)} "the documentation"] " for how to build JS assets."]])
(defn page [opts contents]
(hiccup/html {:mode :html}
(hiccup.page/doctype :html5)
[:html {}
[:head
[:title (:title-attributes opts) (:title opts)]
[:meta {:charset "utf-8"}]
[:meta {:content (:description opts) :name "description"}]
Google / Search Engine Tags
[:meta {:content (:title opts) :itemprop "name"}]
[:meta {:content (:description opts) :itemprop "description"}]
[:meta {:content (str ""
(get (:static-resources opts) "/cljdoc-logo-beta-square.png"))
:itemprop "image"}]
OpenGraph Meta Tags ( should work for Twitter / Facebook )
[:meta {:content "website" :property "og:type"}]
[:meta {:content (:title opts) :property "og:title"}]
[:meta {:content (:description opts) :property "og:description"}]
(when-let [url (:canonical-url opts)]
(assert (string/starts-with? url "/"))
TODO read domain from config
[:link {:rel "icon" :type "image/x-icon" :href "/favicon.ico"}]
Open Search
[:link {:rel "search" :type "application/opensearchdescription+xml"
:href "/opensearch.xml" :title "cljdoc"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]
(apply hiccup.page/include-css (assets/css :tachyons))
(hiccup.page/include-css (get (:static-resources opts) "/cljdoc.css"))]
[:body
[:div.sans-serif
contents]
(when (not= :prod (config/profile))
(no-js-warning opts))
[:div#cljdoc-switcher]
[:script {:src (get (:static-resources opts) "/cljdoc.js")}]
(highlight-js)
(add-requested-features (:page-features opts))]]))
(defn sidebar-title
([title]
(sidebar-title title {:separator-line? true}))
([title {:keys [separator-line?]}]
[:h4.relative.ttu.f7.fw5.mt1.mb2.tracked.gray
(when separator-line?
[:hr.absolute.left-0.right-0.nl3.nr3.nl4-ns.nr4-ns.b--solid.b--black-10])
[:span.relative.nl2.nr2.ph2.bg-white title]]))
(defn meta-info-dialog []
[:div
[:img#js--meta-icon.ma3.fixed.right-0.bottom-0.bg-white.dn.db-ns.pointer
{:src "-clone.vercel.app/explore/48/357edd"}]
[:div#js--meta-dialog.ma3.pa3.ba.br3.b--blue.bw2.w-20.fixed.right-0.bottom-0.bg-white.dn
[:p.ma0
[:b "cljdoc"]
" is a website building & hosting documentation for Clojure/Script libraries"]
(into [:div.mv3]
(map (fn [[description link]]
[:a.db.link.black.mv1.pv3.tc.br2.pointer
{:href link, :style {:background-color "#ECF2FB"}}
description])
[["Keyboard shortcuts" (routes/url-for :shortcuts)]
["Report a problem" (links/github-url :issues)]
["cljdoc on GitHub" (links/github-url :home)]]))
[:a#js--meta-close.link.black.fr.pointer
"× close"]]])
(def home-link
[:a {:href "/"}
[:span.link.dib.v-mid.mr3.pv1.ph2.ba.hover-blue.br1.ttu.b.silver.tracked
{:style "font-size:10px"}
"cljdoc"]])
(defn top-bar-generic []
[:nav.pv2.ph3.pv3-ns.ph4-ns.bb.b--black-10.flex.items-center home-link])
(defn top-bar [version-entity scm-url]
[:nav.pv2.ph3.pv3-ns.ph4-ns.bb.b--black-10.flex.items-center.bg-white
[:a.dib.v-mid.link.dim.black.b.f6.mr3 {:href (routes/url-for :artifact/version :path-params version-entity)}
(proj/clojars-id version-entity)]
[:a.dib.v-mid.link.dim.gray.f6.mr3
{:href (routes/url-for :artifact/index :path-params version-entity)}
(:version version-entity)]
home-link
[:div.tr
{:style {:flex-grow 1}}
[:form.dn.dib-ns.mr3 {:action "/api/request-build2" :method "POST"}
[:input.pa2.mr2.br2.ba.outline-0.blue {:type "hidden" :id "project" :name "project" :value (str (:group-id version-entity) "/" (:artifact-id version-entity))}]
[:input.pa2.mr2.br2.ba.outline-0.blue {:type "hidden" :id "version" :name "version" :value (:version version-entity)}]
[:input.f7.white.hover-near-white.outline-0.bn.bg-white {:type "submit" :value "rebuild"}]]
(cond
(and scm-url (scm/http-uri scm-url))
[:a.link.dim.gray.f6.tr
{:href (scm/http-uri scm-url)}
[:img.v-mid.w1.h1.mr2-ns {:src (scm/icon-url scm-url)}]
[:span.v-mid.dib-ns.dn (scm/coordinate (scm/http-uri scm-url))]]
(and scm-url (scm/fs-uri scm-url))
[:span.f6 (scm/fs-uri scm-url)]
:else
[:a.f6.link.blue {:href (links/github-url :userguide/scm-faq)} "SCM info missing"])]])
(def r-main-container
"Everything that's rendered on cljdoc goes into this container.
On desktop screens it fills the viewport forcing child nodes
to scroll. On smaller screens it grows with the content allowing
Safari to properly condense the URL bar when scrolling.
In contrast if the container was fixed on mobile as well Safari
would perceive the scroll events as if the user scrolled in a
smaller portion of the UI.
While `height: 100vh` would also work on desktop screens there are some
known issues around [using viewport height units on mobile](-hoizey.com/2015/02/viewport-height-is-taller-than-the-visible-part-of-the-document-in-some-mobile-browsers.html)."
:div.flex.flex-column.fixed-ns.bottom-0.left-0.right-0.top-0)
(def r-sidebar-container
:nav.js--main-sidebar.w5.pa3.pa4-ns.br.b--black-10.db-ns.dn.overflow-y-scroll.border-box.flex-shrink-0)
(def r-api-sidebar-container
:div.js--namespace-contents-scroll-view.w5.pa3.pa4-ns.br.b--black-10.db-ns.dn.overflow-y-scroll.flex-shrink-0)
(def r-content-container
:div.js--main-scroll-view.db-ns.ph3.pl5-ns.pr4-ns.flex-grow-1.overflow-y-scroll)
(def r-top-bar-container
"Additional wrapping to make the top bar responsive
On small screens we render the top bar and mobile navigation as a
`fixed` div so that the main container can be scrolled without the
navigation being scrolled out of view.
On regular sized screens we use the default positioning setting of
`static` so that the top bar is rendered as a row of the main
container.
The z-index `z-3` setting is necessary to ensure `fixed` elements
appear above other elements"
:div.fixed.top-0.left-0.right-0.static-ns.flex-shrink-0.z-3)
(def mobile-nav-spacer
"Spacer so fixed navigation elements don't overlap content
This is only needed on small screens so `dn-ns` hides it
on non-small screens
The height has been found by trial and error."
[:div.bg-blue.dn-ns.pt4.tc
{:style {:height "5.2rem"}}
TODO render different fun messages for each request
[:span.b.white.mt3 "Liking cljdoc? Tell your friends :D"]])
(defn layout
[{:keys [top-bar
main-sidebar-contents
vars-sidebar-contents
content]}]
[r-main-container
[r-top-bar-container
top-bar
[:div#js--mobile-nav.db.dn-ns]]
mobile-nav-spacer
[:div.flex.flex-row
be scrollable in Firefox , see this SO comment :
/#comment76873071_44948158
{:style {:min-height 0}}
(into [r-sidebar-container] main-sidebar-contents)
(when (seq vars-sidebar-contents)
(into [r-api-sidebar-container] vars-sidebar-contents))
[r-content-container content]
(meta-info-dialog)]])
|
c8ba3dc58b37eb4f27c80a7c597df7e68a9e139a188d655d5221d76a0650909b | wardle/pc4 | dmt.clj | (ns com.eldrix.pc4.modules.dmt
"Experimental approach to data downloads, suitable for short-term
requirements for multiple sclerosis disease modifying drug
post-marketing surveillance."
(:require [clojure.data.csv :as csv]
[clojure.data.json :as json]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.java.shell]
[clojure.math :as math]
[clojure.set :as set]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as stest]
[clojure.string :as str]
[clojure.tools.logging.readable :as log]
[com.eldrix.deprivare.core :as deprivare]
[com.eldrix.dmd.core :as dmd]
[com.eldrix.hermes.core :as hermes]
[com.eldrix.pc4.rsdb.db :as db]
[com.eldrix.pc4.codelists :as codelists]
[com.eldrix.pc4.system :as pc4]
[com.eldrix.pc4.rsdb.patients :as patients]
[com.eldrix.pc4.rsdb.projects :as projects]
[com.eldrix.pc4.rsdb.results :as results]
[com.eldrix.pc4.rsdb.users :as users]
[com.wsscode.pathom3.interface.eql :as p.eql]
[honey.sql :as sql]
[next.jdbc.plan :as plan])
(:import (java.time LocalDate LocalDateTime Period)
(java.time.temporal ChronoUnit Temporal)
(java.time.format DateTimeFormatter)
(java.io PushbackReader File)
(java.nio.file Files LinkOption)
(java.nio.file.attribute FileAttribute)))
(def study-master-date
(LocalDate/of 2014 05 01))
(def study-centres
"This defines each logical centre with a list of internal 'projects' providing
a potential hook to create combined cohorts in the future should need arise."
{:cardiff {:projects ["NINFLAMMCARDIFF"] :prefix "CF"}
:cambridge {:projects ["CAMBRIDGEMS"] :prefix "CB"}
:plymouth {:projects ["PLYMOUTH"] :prefix "PL"}})
(s/def ::centre (set (keys study-centres)))
(def study-medications
"A list of interesting drugs for studies of multiple sclerosis.
They are classified as either platform DMTs or highly efficacious DMTs.
We define by the use of the SNOMED CT expression constraint language, usually
on the basis of active ingredients together with ATC codes. "
{:dmf
{:description "Dimethyl fumarate"
:atc "L04AX07"
:brand-names ["Tecfidera"]
:class :platform-dmt
:codelist {:ecl
"(<<24056811000001108|Dimethyl fumarate|) OR (<<12086301000001102|Tecfidera|) OR
(<10363601000001109|UK Product| :10362801000001104|Has specific active ingredient| =<<724035008|Dimethyl fumarate|)"
:atc "L04AX07"}}
:glatiramer
{:description "Glatiramer acetate"
:brand-names ["Copaxone" "Brabio"]
:atc "L03AX13"
:class :platform-dmt
:codelist {:ecl
"<<108754007|Glatiramer| OR <<9246601000001104|Copaxone| OR <<13083901000001102|Brabio| OR <<8261511000001102 OR <<29821211000001101
OR (<10363601000001109|UK Product|:10362801000001104|Has specific active ingredient|=<<108755008|Glatiramer acetate|)"
:atc "L03AX13"}}
:ifn-beta-1a
{:description "Interferon beta 1-a"
:brand-names ["Avonex" "Rebif"]
:atc "L03AB07 NOT L03AB13"
:class :platform-dmt
:codelist {:inclusions {:ecl
"(<<9218501000001109|Avonex| OR <<9322401000001109|Rebif| OR
(<10363601000001109|UK Product|:127489000|Has specific active ingredient|=<<386902004|Interferon beta-1a|))"
:atc "L03AB07"}
:exclusions {:ecl "<<12222201000001108|PLEGRIDY|"
:atc "L03AB13"}}}
:ifn-beta-1b
{:description "Interferon beta 1-b"
:brand-names ["Betaferon®" "Extavia®"]
:atc "L03AB08"
:class :platform-dmt
:codelist {:ecl "(<<9222901000001105|Betaferon|) OR (<<10105201000001101|Extavia|) OR
(<10363601000001109|UK Product|:127489000|Has specific active ingredient|=<<386903009|Interferon beta-1b|)"
:atc "L03AB08"}}
:peg-ifn-beta-1a
{:description "Peginterferon beta 1-a"
:brand-names ["Plegridy®"]
:atc "L03AB13"
:class :platform-dmt
:codelist {:ecl "<<12222201000001108|Plegridy|"
:atc "L03AB13"}}
:teriflunomide
{:description "Teriflunomide"
:brand-names ["Aubagio®"]
:atc "L04AA31"
:class :platform-dmt
:codelist {:ecl "<<703786007|Teriflunomide| OR <<12089801000001100|Aubagio| "
:atc "L04AA31"}}
:rituximab
{:description "Rituximab"
:brand-names ["MabThera®" "Rixathon®" "Riximyo" "Blitzima" "Ritemvia" "Rituneza" "Ruxience" "Truxima"]
:atc "L01XC02"
:class :he-dmt
:codelist {:ecl
(str/join " "
["(<<108809004|Rituximab product|)"
"OR (<10363601000001109|UK Product|:10362801000001104|Has specific active ingredient|=<<386919002|Rituximab|)"
"OR (<<9468801000001107|Mabthera|) OR (<<13058501000001107|Rixathon|)"
"OR (<<226781000001109|Ruxience|) OR (<<13033101000001108|Truxima|)"])
:atc "L01XC02"}}
:ocrelizumab
{:description "Ocrelizumab"
:brand-names ["Ocrevus"]
:atc "L04AA36"
:class :he-dmt
:codelist {:ecl "(<<35058611000001103|Ocrelizumab|) OR (<<13096001000001106|Ocrevus|)"
:atc "L04AA36"}}
:cladribine
{:description "Cladribine"
:brand-names ["Mavenclad"]
:atc "L04AA40"
:class :he-dmt
:codelist {:ecl "<<108800000|Cladribine| OR <<13083101000001100|Mavenclad|"
:atc "L04AA40"}}
:mitoxantrone
{:description "Mitoxantrone"
:brand-names ["Novantrone"]
:atc "L01DB07"
:class :he-dmt
:codelist {:ecl "<<108791001 OR <<9482901000001102"
:atc "L01DB07"}}
:fingolimod
{:description "Fingolimod"
:brand-names ["Gilenya"]
:atc "L04AA27"
:class :he-dmt
:codelist {:ecl "<<715640009 OR <<10975301000001100"
:atc "L04AA27"}}
:natalizumab
{:description "Natalizumab"
:brand-names ["Tysabri"]
:atc "L04AA23"
:class :he-dmt
:codelist {:ecl "<<414804006 OR <<9375201000001103"
:atc "L04AA23"}}
:alemtuzumab
{:description "Alemtuzumab"
:brand-names ["Lemtrada"]
:atc "L04AA34"
:class :he-dmt
:codelist {:ecl "(<<391632007|Alemtuzumab|) OR (<<12091201000001101|Lemtrada|)"
:atc "L04AA34"}}
:statin
{:description "Statins"
:class :other
:codelist {:atc "C10AA"}}
:anti-hypertensive
{:description "Anti-hypertensive"
:class :other
:codelist {:atc "C02"}}
:anti-platelet
{:description "Anti-platelets"
:class :other
:codelist {:atc "B01AC"
:ecl "<<7947003"}}
:anti-coagulant
{:description "Anticoagulants"
:class :other
:codelist {:atc ["B01AA" "B01AF" "B01AE" "B01AD" "B01AX04" "B01AX05"]}}
:proton-pump-inhibitor
{:description "Proton pump inhibitors"
:class :other
:codelist {:atc "A02BC"}}
NB : need to double check the list for LEM - PASS vs LEM - DUS and see if match
{:description "Immunosuppressants"
:class :other
:codelist {:inclusions {:atc ["L04AA" "L04AB" "L04AC" "L04AD" "L04AX"]}
:exclusions {:atc ["L04AA23" "L04AA27" "L04AA31" "L04AA34" "L04AA36" "L04AA40" "L04AX07"]}}}
:anti-retroviral
{:description "Antiretrovirals"
:class :other
:codelist {:inclusions {:atc ["J05AE" "J05AF" "J05AG" "J05AR" "J05AX"]}
:exclusions {:atc ["J05AE11" "J05AE12" "J05AE13"
"J05AF07" "J05AF08" "J05AF10"
"J05AX15" "J05AX65"]}}}
:anti-infectious
{:description "Anti-infectious medications"
:class :other
:codelist {:inclusions {:atc ["J01." "J02." "J03." "J04." "J05."]}
:exclusions {:atc ["J05A."]}}}
:antidepressant
{:description "Anti-depressants"
:class :other
:codelist {:atc "N06A"}}
:benzodiazepine
{:description "Benzodiazepines"
:class :other
:codelist {:atc ["N03AE" "N05BA"]}}
:antiepileptic
{:description "Anti-epileptics"
:class :other
:codelist {:atc "N03A"}}
:antidiabetic
{:description "Anti-diabetic"
:class :other
:codelist {:atc "A10"}}
:nutritional
{:description "Nutritional supplements and vitamins"
:class :other
:codelist {:atc ["A11" "B02B" "B03C"] :ecl "<<9552901000001103"}}})
(def flattened-study-medications
"A flattened sequence of study medications for convenience."
(reduce-kv (fn [acc k v] (conj acc (assoc v :id k))) [] study-medications))
(def study-diagnosis-categories
"These are project specific criteria for diagnostic classification."
{:multiple_sclerosis
{:description "Multiple sclerosis"
:codelist {:ecl "<<24700007"}}
:allergic_reaction
{:description "Any type of allergic reaction, including anaphylaxis"
:codelist {:ecl "<<419076005 OR <<243865006"}}
:cardiovascular
{:description "Cardiovascular disorders"
:codelist {:icd10 ["I"]}}
:cancer
{:description "Cancer, except skin cancers"
:codelist {:inclusions {:icd10 "C"} :exclusions {:icd10 "C44"}}}
:connective_tissue
{:description "Connective tissue disorders"
:codelist {:icd10 ["M45." "M33." "M35.3" "M35.0" "M32." "M34."
"M31.3" "M30.1" "L95." "D89.1" "D69.0" "M31.7" "M30.3"
"M30.0" "M31.6" "I73.0" "M31.4" "M35.2" "M94.1" "M02.3"
"M06.1" "E85.0" "D86."]}}
:endocrine
{:codelist {:icd10 ["E27.1" "E27.2" "E27.4" "E10." "E06.3" "E05.0"]}}
:gastrointestinal
{:codelist {:icd10 ["K75.4" "K90.0" "K50." "K51." "K74.3"]}}
:severe_infection ;; note: also significance based on whether admitted for problem
{:codelist {:icd10 ["A" "B" "U07.1" "U07.2" "U08." "U09." "U10."]}}
:arterial_dissection
{:codelist {:icd10 ["I67.0" "I72.5"]}}
:stroke
{:codelist {:icd10 ["I6"]}}
:angina_or_myocardial_infarction
{:codelist {:icd10 ["I20" "I21" "I22" "I23" "I24" "I25"]}}
:coagulopathy
{:codelist {:icd10 ["D65" "D66" "D67" "D68" "D69" "Y44.2" "Y44.3" "Y44.4" "Y44.5"]}}
:respiratory
{:codelist {:icd10 ["J0" "J1" "J20" "J21" "J22"]}}
:hiv
{:codelist {:icd10 ["B20.", "B21.", "B22.", "B24.", "F02.4" "O98.7" "Z21", "R75"]}}
:autoimmune_disease
{:codelist {:icd10 ["M45." "M33." "M35.3" "M05." "M35.0" "M32." "M34." "M31.3" "M30.1" "L95." "D89.1" "D69.0" "M31.7" "M30.3" "M30.0"
"M31.6" "I73.0" "M31.4" "M35.2" "M94.1" "M02.3" "M06.1" "E85.0" "D86." "E27.1" "E27.2" "E27.4" "E10." "E06.3" "E05.0" "K75.4" "K90.0"
"K50." "K51." "K74.3" "L63." "L10.9" "L40." "L80." "G61.0" "D51.0" "D59.1" "D69.3" "D68." "N02.8" "M31.0" "D76.1"
"I01.2" "I40.8" "I40.9" "I09.0" "G04.0" "E31.0" "I01." "G70.0" "G73.1"]}}
:uncontrolled_hypertension ;; I have used a different definition to the protocol as R03.0 is wrong
{:codelist {:ecl "<<706882009"}} ;; this means 'hypertensive emergency'
:urinary_tract
{:codelist {:icd10 ["N10." "N11." "N12." "N13." "N14." "N15." "N16."]}}
:hair_and_skin
{:codelist {:icd10 ["L63." "L10.9" "L40." "L80.0"]}}
:mental_behavioural
{:codelist {:icd10 ["F"]}}
:epilepsy
{:codelist {:icd10 ["G40"]}}
:other
{:codelist {:icd10 ["G61.0" "D51.0" "D59.1" "D69.3" "D68."
"N02.8" "M31.0" "D76.1"
"M05.3" "I01.2" "I40.8" "I40.9" "I09.0" "G04.0"
"E31.0" "D69.3" "I01." "G70.0" "G73.1"]}}})
(def flattened-study-diagnoses
"A flattened sequence of study diagnoses for convenience."
(reduce-kv (fn [acc k v] (conj acc (assoc v :id k))) [] study-diagnosis-categories))
(defn ^:deprecated make-diagnostic-category-fn
"Returns a function that will test a collection of concept identifiers against the diagnostic categories specified."
[system categories]
(let [codelists (reduce-kv (fn [acc k v] (assoc acc k (codelists/make-codelist system (:codelist v))))
{}
categories)]
(fn [concept-ids]
(reduce-kv (fn [acc k v] (assoc acc k (codelists/member? v concept-ids))) {} codelists))))
(defn expand-codelists [system categories]
(update-vals categories
(fn [{codelist :codelist :as v}]
(assoc v :codes (codelists/expand (codelists/make-codelist system codelist))))))
(defn make-codelist-category-fn
"Creates a function that will return a map of category to boolean, for each
category. "
[system categories]
(let [cats' (expand-codelists system categories)]
(fn [concept-ids]
(reduce-kv (fn [acc k v] (assoc acc k (boolean (some true? (map #(contains? (:codes v) %) concept-ids))))) {} cats'))))
(comment
(def ct-disorders (codelists/make-codelist system {:icd10 ["M45." "M33." "M35.3" "M05." "M35.0" "M32.8" "M34."
"M31.3" "M30.1" "L95." "D89.1" "D69.0" "M31.7" "M30.3"
"M30.0" "M31.6" "I73." "M31.4" "M35.2" "M94.1" "M02.3"
"M06.1" "E85.0" "D86."]}))
(codelists/member? ct-disorders [9631008])
(def diag-cats (make-codelist-category-fn system study-diagnosis-categories))
(diag-cats [9631008 12295008 46635009 34000006 9014002 40956001])
(diag-cats [6204001])
(def codelists (reduce-kv (fn [acc k v] (assoc acc k (codelists/make-codelist system (:codelist v)))) {} study-diagnosis-categories))
codelists
(reduce-kv (fn [acc k v] (assoc acc k (codelists/member? v [9631008 24700007]))) {} codelists)
(map #(hash-map :title (:term %) :release-date (:effectiveTime %)) (hermes/get-release-information (:com.eldrix/hermes system)))
(def calcium-channel-blockers (codelists/make-codelist system {:atc "C08" :exclusions {:atc "C08CA01"}}))
(codelists/member? calcium-channel-blockers [108537001])
(take 2 (map #(:term (hermes/get-fully-specified-name (:com.eldrix/hermes system) %)) (codelists/expand calcium-channel-blockers)))
(codelists/expand (codelists/make-codelist system {:icd10 "G37.3"}))
(codelists/member? (codelists/make-codelist system {:icd10 "I"}) [22298006])
(count (codelists/expand (codelists/make-codelist system {:icd10 "I"})))
(get-in study-diagnosis-categories [:connective-tissue :codelist])
(def cancer (codelists/make-codelist system {:inclusions {:icd10 "C"} :exclusions {:icd10 "C44"}}))
(codelists/disjoint? (codelists/expand cancer) (codelists/expand (codelists/make-codelist system {:icd10 "C44"})))
(defn ps [id] (:term (hermes/get-preferred-synonym (:com.eldrix/hermes system) id "en-GB")))
(map ps (codelists/expand cancer))
(map #(:term (hermes/get-preferred-synonym (:com.eldrix/hermes system) % "en-GB")) (hermes/member-field-prefix (:com.eldrix/hermes system) 447562003 "mapTarget" "C44"))
(vals (hermes/source-historical-associations (:com.eldrix/hermes system) 24700007))
(hermes/get-preferred-synonym (:com.eldrix/hermes system) 445130008 "en-GB"))
(defn make-atc-regexps [{:keys [codelist] :as med}]
(when-let [atc (or (:atc codelist) (get-in codelist [:inclusions :atc]))]
(if (coll? atc)
(mapv #(vector (if (string? %) (re-pattern %) %) (dissoc med :codelist)) atc)
(vector (vector (if (string? atc) (re-pattern atc) atc) (dissoc med :codelist))))))
(def study-medication-atc
"A sequence containing ATC code regexp and study medication class information."
(mapcat make-atc-regexps flattened-study-medications))
(defn get-study-classes [atc]
(keep identity (map (fn [[re-atc med]] (when (re-matches re-atc atc) med)) study-medication-atc)))
(defmulti to-local-date class)
(defmethod to-local-date LocalDateTime [^LocalDateTime x]
(.toLocalDate x))
(defmethod to-local-date LocalDate [x] x)
(defmethod to-local-date nil [_] nil)
(comment
study-medication-atc
(first (get-study-classes "N05BA")))
(defn all-ms-dmts
"Returns a collection of multiple sclerosis disease modifying medications with
SNOMED CT (dm+d) identifiers included. For validation, checks that each
logical set of concepts is disjoint."
[{:com.eldrix/keys [hermes dmd] :as system}]
(let [result (map #(assoc % :codes (codelists/expand (codelists/make-codelist system (:codelist %)))) (remove #(= :other (:class %)) flattened-study-medications))]
(if (apply codelists/disjoint? (map :codes (remove #(= :other (:class %)) result)))
result
(throw (IllegalStateException. "DMT specifications incorrect; sets not disjoint.")))))
(defn all-dmt-identifiers
"Return a set of identifiers for all DMTs"
[system]
(set (apply concat (map :codes (all-ms-dmts system)))))
(defn all-he-dmt-identifiers
"Returns a set of identifiers for all highly-efficacious DMTs"
[system]
(set (apply concat (map :codes (filter #(= :he-dmt (:class %)) (all-ms-dmts system))))))
(defn fetch-most-recent-encounter-date-time [{conn :com.eldrix.rsdb/conn}]
(db/execute-one! conn (sql/format {:select [[:%max.date_time :most_recent_encounter_date_time]]
:from :t_encounter})))
(defn fetch-patients [{conn :com.eldrix.rsdb/conn} patient-ids]
(db/execute! conn (sql/format {:select [:patient_identifier :sex :date_birth :date_death :part1a :part1b :part1c :part2]
:from :t_patient
:left-join [:t_death_certificate [:= :patient_fk :t_patient/id]]
:where [:in :t_patient/patient_identifier patient-ids]})))
(defn addresses-for-patients
"Returns a map of patient identifiers to a collection of sorted addresses."
[{conn :com.eldrix.rsdb/conn} patient-ids]
(group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier :t_address/address1 :t_address/date_from :t_address/date_to :t_address/postcode_raw]
:from [:t_address]
:order-by [[:t_patient/patient_identifier :asc] [:date_to :desc] [:date_from :desc]]
:join [:t_patient [:= :t_patient/id :t_address/patient_fk]]
:where [:in :t_patient/patient_identifier patient-ids]}))))
(defn active-encounters-for-patients
"Returns a map of patient identifiers to a collection of sorted, active encounters.
Encounters are sorted in descending date order."
[{conn :com.eldrix.rsdb/conn} patient-ids]
(group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_encounter/id
:t_encounter/date_time]
:from [:t_encounter]
:join [:t_patient [:= :t_patient/id :t_encounter/patient_fk]]
:order-by [[:t_encounter/date_time :desc]]
:where [:and
[:in :t_patient/patient_identifier patient-ids]
[:<> :t_encounter/is_deleted "true"]]}))))
(defn ms-events-for-patients
"Returns MS events (e.g. relapses) grouped by patient identifier, sorted in descending date order."
[{conn :com.eldrix.rsdb/conn} patient-ids]
(group-by :t_patient/patient_identifier
(->> (db/execute! conn (sql/format
{:select [:t_patient/patient_identifier
:date :source :impact :abbreviation :name]
:from [:t_ms_event]
:join [:t_summary_multiple_sclerosis [:= :t_ms_event/summary_multiple_sclerosis_fk :t_summary_multiple_sclerosis/id]
:t_patient [:= :t_patient/id :t_summary_multiple_sclerosis/patient_fk]]
:left-join [:t_ms_event_type [:= :t_ms_event_type/id :t_ms_event/ms_event_type_fk]]
:order-by [[:t_ms_event/date :desc]]
:where [:in :t_patient/patient_identifier patient-ids]}))
(map #(assoc % :t_ms_event/is_relapse (patients/ms-event-is-relapse? %))))))
(defn jc-virus-for-patients [{conn :com.eldrix.rsdb/conn} patient-ids]
(->> (db/execute! conn (sql/format
{:select [:t_patient/patient_identifier
:date :jc_virus :titre]
:from [:t_result_jc_virus]
:join [:t_patient [:= :t_result_jc_virus/patient_fk :t_patient/id]]
:where [:and
[:<> :t_result_jc_virus/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}))
(map #(update % :t_result_jc_virus/date to-local-date))))
(defn mri-brains-for-patient [conn patient-identifier]
(let [results (->> (results/fetch-mri-brain-results conn nil {:t_patient/patient_identifier patient-identifier})
(map #(assoc % :t_patient/patient_identifier patient-identifier))
results/all-t2-counts
(map results/gad-count-range))
results-by-id (zipmap (map :t_result_mri_brain/id results) results)]
(map #(if-let [compare-id (:t_result_mri_brain/compare_to_result_mri_brain_fk %)]
(assoc % :t_result_mri_brain/compare_to_result_date (:t_result_mri_brain/date (get results-by-id compare-id)))
%) results)))
(defn mri-brains-for-patients [{conn :com.eldrix.rsdb/conn} patient-ids]
(->> (mapcat #(mri-brains-for-patient conn %) patient-ids)))
(defn multiple-sclerosis-onset
"Derive dates of onset based on recorded date of onset, first MS event or date
of diagnosis."
[{conn :com.eldrix.rsdb/conn hermes :com.eldrix/hermes :as system} patient-ids]
(let [ms-diagnoses (set (map :conceptId (hermes/expand-ecl-historic hermes "<<24700007")))
first-ms-events (update-vals (ms-events-for-patients system patient-ids) #(:t_ms_event/date (last %)))
pt-diagnoses (group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_diagnosis/concept_fk
:t_diagnosis/date_diagnosis
:t_diagnosis/date_onset
:t_diagnosis/date_to]
:from [:t_diagnosis]
:join [:t_patient [:= :t_diagnosis/patient_fk :t_patient/id]]
:where [:and
[:in :t_diagnosis/concept_fk ms-diagnoses]
[:in :t_diagnosis/status ["ACTIVE" "INACTIVE_RESOLVED"]]
[:in :t_patient/patient_identifier patient-ids]]})))]
(when-let [dup-diagnoses (seq (reduce-kv (fn [acc k v] (when (> (count v) 1) (assoc acc k v))) {} pt-diagnoses))]
(throw (ex-info "patients with duplicate MS diagnoses" {:duplicates dup-diagnoses})))
(update-vals pt-diagnoses (fn [diags]
(let [diag (first diags)
first-event (get first-ms-events (:t_patient/patient_identifier diag))]
(assoc diag
:has_multiple_sclerosis (boolean diag)
:date_first_event first-event
use first recorded event as onset , or date onset in diagnosis
:calculated-onset (or first-event (:t_diagnosis/date_onset diag))))))))
(defn fetch-patient-diagnoses
[{conn :com.eldrix.rsdb/conn} patient-ids]
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_diagnosis/concept_fk
:t_diagnosis/date_diagnosis
:t_diagnosis/date_onset
:t_diagnosis/date_to]
:from [:t_diagnosis]
:join [:t_patient [:= :t_diagnosis/patient_fk :t_patient/id]]
:where [:and
[:in :t_diagnosis/status ["ACTIVE" "INACTIVE_RESOLVED"]]
[:in :t_patient/patient_identifier patient-ids]]})))
(defn fetch-patient-admissions
[{conn :com.eldrix.rsdb/conn} project-name patient-ids]
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier :t_episode/date_registration :t_episode/date_discharge]
:from [:t_episode]
:join [:t_patient [:= :t_episode/patient_fk :t_patient/id]
:t_project [:= :t_episode/project_fk :t_project/id]]
:where [:and
[:= :t_project/name project-name]
[:in :t_patient/patient_identifier patient-ids]]})))
(defn fetch-smoking-status
[{conn :com.eldrix.rsdb/conn} patient-ids]
(-> (group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_smoking_history/status]
:from [:t_smoking_history]
:join [:t_encounter [:= :t_encounter/id :t_smoking_history/encounter_fk]
:t_patient [:= :t_patient/id :t_encounter/patient_fk]]
:order-by [[:t_encounter/date_time :desc]]
:where [:and
[:<> :t_smoking_history/is_deleted "true"]
[:<> :t_encounter/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]})))
(update-vals first)))
(defn fetch-weight-height
[{conn :com.eldrix.rsdb/conn} patient-ids]
(let [results (-> (group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_form_weight_height/weight_kilogram
:t_form_weight_height/height_metres]
:from [:t_form_weight_height]
:join [:t_encounter [:= :t_encounter/id :t_form_weight_height/encounter_fk]
:t_patient [:= :t_patient/id :t_encounter/patient_fk]]
:order-by [[:t_encounter/date_time :desc]]
:where [:and
[:<> :t_form_weight_height/is_deleted "true"]
[:<> :t_encounter/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}))))]
(update-vals results (fn [forms]
(let [default-ht (first (map :t_form_weight_height/height_metres forms))]
(map #(let [wt (:t_form_weight_height/weight_kilogram %)
ht (or (:t_form_weight_height/height_metres %) default-ht)]
(if (and wt ht) (assoc % :body_mass_index (with-precision 2 (/ wt (* ht ht))))
%)) forms))))))
(defn fetch-form-ms-relapse
"Get a longitudinal record of MS disease activity, results keyed by patient identifier."
[{conn :com.eldrix.rsdb/conn} patient-ids]
(group-by :t_patient/patient_identifier
(db/execute! conn (sql/format
{:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_form_ms_relapse/in_relapse
:t_ms_disease_course/name
:t_form_ms_relapse/activity
:t_form_ms_relapse/progression]
:from [:t_form_ms_relapse]
:join [:t_encounter [:= :t_encounter/id :t_form_ms_relapse/encounter_fk]
:t_patient [:= :t_encounter/patient_fk :t_patient/id]]
:left-join [:t_ms_disease_course [:= :t_ms_disease_course/id :t_form_ms_relapse/ms_disease_course_fk]]
:where [:and
[:<> :t_encounter/is_deleted "true"]
[:<> :t_form_ms_relapse/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}))))
(def convert-edss-score
{"SCORE10_0" 10.0
"SCORE6_5" 6.5
"SCORE1_0" 1.0
"SCORE2_5" 2.5
"SCORE5_5" 5.5
"SCORE9_0" 9.0
"SCORE7_0" 7.0
"SCORE3_0" 3.0
"SCORE5_0" 5.0
"SCORE4_5" 4.5
"SCORE8_5" 8.5
"SCORE7_5" 7.5
"SCORE8_0" 8.0
"SCORE1_5" 1.5
"SCORE6_0" 6.0
"SCORE3_5" 3.5
"SCORE0_0" 0.0
"SCORE4_0" 4.0
"SCORE2_0" 2.0
"SCORE9_5" 9.5
"SCORE_LESS_THAN_4" "<4"})
(defn get-most-recent
"Given a date 'date', find the preceding map in the collection 'coll' within the limit, default 12 weeks."
([coll date-fn ^LocalDate date]
(get-most-recent coll date-fn date (Period/ofWeeks 12)))
([coll date-fn ^LocalDate date ^Period max-period]
(->> coll
(remove #(.isAfter (to-local-date (date-fn %)) date)) ;; remove any entries after our date
(remove #(.isBefore (to-local-date (date-fn %)) (.minus date max-period)))
(sort-by date-fn)
reverse
first)))
(def simplify-ms-disease-course
{"Secondary progressive with relapses" "SPMS"
"Unknown" "UK"
"Primary progressive" "PPMS"
"Secondary progressive" "SPMS"
"Primary progressive with relapses" "PPMS"
"Clinically isolated syndrome" "CIS"
"Relapsing with sequelae" "RRMS"
"Relapsing remitting" "RRMS"})
(defn edss-scores
"EDSS scores for the patients specified, grouped by patient identifier and ordered by date ascending."
[{conn :com.eldrix.rsdb/conn :as system} patient-ids]
(let [form-relapses (fetch-form-ms-relapse system patient-ids)]
(->> (db/execute! conn (sql/format {:union-all
[{:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_form_edss/edss_score
:t_encounter/id]
:from [:t_encounter]
:join [:t_patient [:= :t_patient/id :t_encounter/patient_fk]
:t_form_edss [:= :t_form_edss/encounter_fk :t_encounter/id]]
:where [:and
[:<> :t_form_edss/edss_score nil]
[:<> :t_encounter/is_deleted "true"]
[:<> :t_form_edss/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}
{:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_form_edss_fs/edss_score
:t_encounter/id]
:from [:t_encounter]
:join [:t_patient [:= :t_patient/id :t_encounter/patient_fk]
:t_form_edss_fs [:= :t_form_edss_fs/encounter_fk :t_encounter/id]]
:where [:and
[:<> :t_form_edss_fs/edss_score nil]
[:<> :t_encounter/is_deleted "true"]
[:<> :t_form_edss_fs/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}]}))
(map #(update-keys % {:patient_identifier :t_patient/patient_identifier
:date_time :t_encounter/date_time
:edss_score :t_form_edss/edss_score
:id :t_encounter/id}))
(map #(if-let [form-relapse (get-most-recent (get form-relapses (:t_patient/patient_identifier %)) :t_encounter/date_time (to-local-date (:t_encounter/date_time %)) (Period/ofWeeks 12))]
(merge form-relapse % {:t_form_ms_relapse/date_status_recorded (to-local-date (:t_encounter/date_time form-relapse))})
(assoc % :t_form_ms_relapse/in_relapse false))) ;; if no recent relapse recorded, record as FALSE explicitly.
(map #(assoc % :t_form_edss/edss_score (convert-edss-score (:t_form_edss/edss_score %))
:t_ms_disease_course/type (simplify-ms-disease-course (:t_ms_disease_course/name %))
:t_encounter/date (to-local-date (:t_encounter/date_time %))))
(group-by :t_patient/patient_identifier)
(reduce-kv (fn [acc k v] (assoc acc k (sort-by :t_encounter/date_time v))) {}))))
(defn date-at-edss-4
"Given an ordered sequence of EDSS scores, identify the first that is 4 or
above and not in relapse."
[edss]
(->> edss
(remove :t_form_ms_relapse/in_relapse)
(filter #(number? (:t_form_edss/edss_score %)))
(filter #(>= (:t_form_edss/edss_score %) 4))
first
:t_encounter/date_time))
(defn relapses-between-dates
"Filter the event list for a patient to only include relapse-type events between the two dates specified, inclusive."
[events ^LocalDate from-date ^LocalDate to-date]
(->> events
(filter :t_ms_event/is_relapse)
(filter #(let [date (:t_ms_event/date %)]
(and (or (.isEqual date from-date) (.isAfter date from-date))
(or (.isEqual date to-date) (.isBefore date to-date)))))))
(comment
(get (ms-events-for-patients system [5506]) 5506)
(def d1 (LocalDate/of 2014 1 1))
(relapses-between-dates (get (ms-events-for-patients system [5506]) 5506) (.minusMonths d1 24) d1))
(defn lsoa-for-postcode [{:com.eldrix/keys [clods]} postcode]
(get (com.eldrix.clods.core/fetch-postcode clods postcode) "LSOA11"))
(defn deprivation-decile-for-lsoa [{:com.eldrix/keys [deprivare]} lsoa]
(:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile (deprivare/fetch-lsoa deprivare lsoa)))
(def fetch-max-depriv-rank (memoize deprivare/fetch-max))
(defn deprivation-quartile-for-lsoa [{:com.eldrix/keys [deprivare]} lsoa]
(when-let [data (deprivare/fetch-lsoa deprivare lsoa)]
(let [rank (:uk-composite-imd-2020-mysoc/UK_IMD_E_rank data)
max-rank (fetch-max-depriv-rank deprivare :uk-composite-imd-2020-mysoc/UK_IMD_E_rank)
x (/ rank max-rank)]
(cond
(>= x 3/4) 4
(>= x 2/4) 3
(>= x 1/4) 2
:else 1))))
(defn deprivation-quartile-for-address
"Given an address, determine a deprivation quartile.
We use postal code when possible, but fallback to looking for a stored LSOA
in the 'address1' field if available."
[system {:t_address/keys [address1 postcode_raw]}]
(cond
(not (str/blank? postcode_raw))
(deprivation-quartile-for-lsoa system (lsoa-for-postcode system postcode_raw))
(and (not (str/blank? address1)) (re-matches #"^[E|W]\d*" address1))
(deprivation-quartile-for-lsoa system address1)
:else nil))
(defn deprivation-quartiles-for-patients
"Determine deprivation quartile for the patients specified.
Deprivation indices are calculated based on address history, on the date
specified, or today.
Parameters:
- system : a pc4 'system' containing clods, deprivare and rsdb modules.
- patient-ids : a sequence of patient identifiers for the cohort in question
- on-date : a date to use for all patients, or a map, or function, to
return a date for each patient-id.
If 'on-date' is provided but no date is returned for a given patient-id, no
decile will be returned by design.
Examples:
(deprivation-quartiles-for-patients system [17497 22776] (LocalDate/of 2010 1 1)
(deprivation-quartiles-for-patients system [17497 22776] {17497 (LocalDate/of 2004 1 1)}"
([system patient-ids] (deprivation-quartiles-for-patients system patient-ids (LocalDate/now)))
([system patient-ids on-date]
(let [date-fn (if (ifn? on-date) on-date (constantly on-date))]
(update-vals (addresses-for-patients system patient-ids)
#(->> (when-let [date (date-fn (:t_patient/patient_identifier (first %)))]
(patients/address-for-date % date)) ;; address-for-date will use 'now' if date nil, so wrap
(deprivation-quartile-for-address system))))))
(defn all-recorded-medications [{conn :com.eldrix.rsdb/conn}]
(into #{} (map :t_medication/medication_concept_fk)
(next.jdbc/plan conn
(sql/format {:select-distinct :t_medication/medication_concept_fk
:from :t_medication}))))
(defn convert-product-pack
"Convert a medication that is a type of product pack to the corresponding VMP."
[{:com.eldrix/keys [dmd hermes]} {concept-id :t_medication/medication_concept_fk :as medication}]
(if (or (hermes/subsumed-by? hermes concept-id 8653601000001108)
(hermes/subsumed-by? hermes concept-id 10364001000001104))
(if-let [vmp (first (hermes/get-parent-relationships-of-type hermes concept-id 10362601000001103))]
(assoc medication :t_medication/medication_concept_fk vmp :t_medication/converted_from_pp concept-id)
(if-let [amp (first (hermes/get-parent-relationships-of-type hermes concept-id 10362701000001108))]
(assoc medication :t_medication/medication_concept_fk amp :t_medication/converted_from_pp concept-id)
(throw (ex-info "unable to convert product pack" medication))))
medication))
(defn medications-for-patients [{conn :com.eldrix.rsdb/conn :as system} patient-ids]
(->> (db/execute! conn
(sql/format {:select [:t_patient/patient_identifier
:t_medication/id
:t_medication/medication_concept_fk :t_medication/date_from :t_medication/date_to
:t_medication/reason_for_stopping]
:from [:t_medication :t_patient]
:where [:and
[:= :t_medication/patient_fk :t_patient/id]
[:in :t_patient/patient_identifier patient-ids]
[:<> :t_medication/reason_for_stopping "RECORDED_IN_ERROR"]]}))
(sort-by (juxt :t_patient/patient_identifier :t_medication/date_from))
(map #(convert-product-pack system %))))
(defn make-dmt-lookup [system]
(apply merge (map (fn [dmt] (zipmap (:codes dmt) (repeat {:dmt_class (:class dmt) :dmt (:id dmt) :atc (:atc dmt)}))) (all-ms-dmts system))))
(defn infer-atc-for-non-dmd
"Try to reach a dmd product from a non-dmd product to infer an ATC code.
TODO: improve"
[{:com.eldrix/keys [hermes dmd]} concept-id]
(or (first (keep identity (map #(dmd/atc-for-product dmd %) (hermes/get-child-relationships-of-type hermes concept-id 116680003))))
(first (keep identity (map #(dmd/atc-for-product dmd %) (hermes/get-parent-relationships-of-type hermes concept-id 116680003))))))
(defn fetch-drug
"Return basic information about a drug.
Most products are in the UK dm+d, but not all, so we supplement with data
from SNOMED when possible."
[{:com.eldrix/keys [hermes dmd] :as system} concept-id]
(if-let [product (dmd/fetch-product dmd concept-id)]
(let [atc (or (com.eldrix.dmd.store2/atc-code dmd product)
(infer-atc-for-non-dmd system concept-id))]
(cond-> {:nm (or (:VTM/NM product) (:VMP/NM product) (:AMP/NM product) (:VMPP/NM product) (:AMPP/NM product))}
atc (assoc :atc atc)))
(let [atc (infer-atc-for-non-dmd system concept-id)
term (:term (hermes/get-preferred-synonym hermes concept-id "en-GB"))]
(cond-> {:nm term}
atc (assoc :atc atc)))))
(defn first-he-dmt-after-date
"Given a list of medications for a single patient, return the first
highly-effective medication given after the date specified."
[medications ^LocalDate date]
(->> medications
(filter #(= :he-dmt (:dmt_class %)))
(filter #(or (nil? (:t_medication/date_from %)) (.isAfter (:t_medication/date_from %) date)))
(sort-by :t_medication/date_from)
first))
(defn count-dmts-before
"Returns counts of the specified DMT, or class of DMT, or any DMT, used before the date specified."
([medications ^LocalDate date] (count-dmts-before medications date nil nil))
([medications ^LocalDate date dmt-class] (count-dmts-before medications date dmt-class nil))
([medications ^LocalDate date dmt-class dmt]
(when date
(let [prior-meds (filter #(or (nil? (:t_medication/date_from %)) (.isBefore (:t_medication/date_from %) date)) medications)]
(if-not dmt-class
(count (filter :dmt prior-meds)) ;; return any DMT
(if-not dmt
(count (filter #(= dmt-class (:dmt_class %)) prior-meds)) ;; return any DMT of same class HE vs platform
(count (filter #(= dmt (:dmt %)) prior-meds)))))))) ;; return same DMT
(defn days-between
"Return number of days between dates, or nil, or when-invalid if one date nil."
([^Temporal d1 ^Temporal d2] (days-between d1 d2 nil))
([^Temporal d1 ^Temporal d2 when-invalid]
(if (and d1 d2)
(.between ChronoUnit/DAYS d1 d2)
when-invalid)))
(defn count-dmts [medications]
(->> medications
(keep-indexed (fn [i medication] (cond-> (assoc medication :switch? false)
(> i 0) (assoc :switch? true :switch_from (:dmt (nth medications (dec i)))))))
(map #(assoc %
:exposure_days (days-between (:t_medication/date_from %) (:t_medication/date_to %))
:n_prior_dmts (count-dmts-before medications (:t_medication/date_from %))
:n_prior_platform_dmts (count-dmts-before medications (:t_medication/date_from %) :platform-dmt)
:n_prior_he_dmts (count-dmts-before medications (:t_medication/date_from %) :he-dmt)
:first_use (= 0 (count-dmts-before medications (:t_medication/date_from %) (:dmt_class %) (:dmt %)))))))
(defn patient-raw-dmt-medications
[{conn :com.eldrix.rsdb/conn :as system} patient-ids]
(let [dmt-lookup (make-dmt-lookup system)]
(->> (medications-for-patients system patient-ids)
; (filter #(let [start-date (:t_medication/date_from %)] (or (nil? start-date) (.isAfter (:t_medication/date_from %) study-master-date))))
(map #(merge % (get dmt-lookup (:t_medication/medication_concept_fk %))))
; (filter #(all-he-dmt-identifiers (:t_medication/medication_concept_fk %)))
(filter :dmt)
(group-by :t_patient/patient_identifier))))
(defn patient-dmt-sequential-regimens
"Returns DMT medications grouped by patient, organised by *regimen*.
For simplicity, the regimen is defined as a sequential group of treatments
of the same DMT. This does not work for overlapping regimens, which would need
to be grouped by a unique, and likely manually curated unique identifier
for the regimen. It also does not take into account gaps within the treatment
course. If a patient is listed as having nataluzimab on one date, and another
dose on another date, this will show the date from and to as those two dates.
If the medication date-to is nil, then the last active contact of the patient
is used."
[{conn :com.eldrix.rsdb/conn :as system} patient-ids]
(let [active-encounters (active-encounters-for-patients system patient-ids)
last-contact-dates (update-vals active-encounters #(:t_encounter/date_time (first %)))]
(update-vals
(patient-raw-dmt-medications system patient-ids)
(fn [v]
(->> v
(partition-by :dmt) ;; this partitions every time :dmt changes, which gives us sequential groups of medications
we then simply look at the first , and the last in that group .
end (last %)
date-to (or (:t_medication/date_to end) (to-local-date (get last-contact-dates (:t_patient/patient_identifier (first %)))))]
(if date-to
return a single entry with start date from the first and end date from the last
start)))
count-dmts)))))
(defn cohort-entry-meds
"Return a map of patient id to cohort entry medication.
This is defined as date of first prescription of a HE-DMT after the
defined study date.
This is for the LEM-PASS study. Cohort entry date defined differently for DUS."
[system patient-ids study-date]
(->> (patient-dmt-sequential-regimens system patient-ids)
vals
(map (fn [medications] (first-he-dmt-after-date medications study-date)))
(keep identity)
(map #(vector (:t_patient/patient_identifier %) %))
(into {})))
(defn alemtuzumab-medications
"Returns alemtuzumab medication records for the patients specified.
Returns a map keyed by patient identifier, with a collection of ordered
medications."
[system patient-ids]
(-> (patient-raw-dmt-medications system patient-ids)
(update-vals (fn [meds] (seq (filter #(= (:dmt %) :alemtuzumab) meds))))))
(defn valid-alemtuzumab-record?
"Is this a valid alemtuzumab record?
A record must never more than 5 days between the 'from' date and the 'to' date."
[med]
(let [from (:t_medication/date_from med)
to (:t_medication/date_to med)]
(and from to (> 5 (.between ChronoUnit/DAYS from to)))))
(defn make-daily-infusions [med]
(let [from (:t_medication/date_from med)
to (:t_medication/date_to med)]
(if (valid-alemtuzumab-record? med)
(let [days (.between ChronoUnit/DAYS from to)
dates (map #(.plusDays from %) (range 0 (inc days)))]
(map #(-> med
(assoc :t_medication/date % :valid true)
(dissoc :t_medication/date_from :t_medication/date_to :t_medication/reason_for_stopping)) dates))
(-> med
(assoc :valid false :t_medication/date from)
(dissoc :t_medication/date_from :t_medication/date_to :t_medication/reason_for_stopping)))))
(defn alemtuzumab-infusions
"Returns a map keyed by patient identifier of all infusions of alemtuzumab."
[system patient-ids]
(->> (alemtuzumab-medications system patient-ids)
vals
(remove nil?)
flatten
(map make-daily-infusions)
flatten
(group-by :t_patient/patient_identifier)))
(defn course-and-infusion-rank
"Given a sequence of infusions, generate a 'course-rank' and 'infusion-rank'.
We do this by generating a sequence of tuples that slide over the infusions.
Each tuple contains two items: the prior item and the item.
Returns the sequence of infusions, but with :course-rank and :infusion-rank
properties."
[infusions]
(loop [partitions (partition 2 1 (concat [nil] infusions))
course-rank 1
infusion-rank 1
results []]
(let [[prior item] (vec (first partitions))]
(if-not item
results
(let [new-course? (and (:t_medication/date prior) (:t_medication/date item) (> (.between ChronoUnit/DAYS (:t_medication/date prior) (:t_medication/date item)) 15))
course-rank (if new-course? (inc course-rank) course-rank)
infusion-rank (if new-course? 1 infusion-rank)
item' (assoc item :course-rank course-rank :infusion-rank infusion-rank)]
(recur (rest partitions) course-rank (inc infusion-rank) (conj results item')))))))
(defn ranked-alemtuzumab-infusions
"Returns a map keyed by patient-id of alemtuzumab infusions, with course
and infusion rank included."
[system patient-ids]
(-> (alemtuzumab-infusions system patient-ids)
(update-vals course-and-infusion-rank)))
(defn all-patient-diagnoses [system patient-ids]
(let [diag-fn (make-codelist-category-fn system study-diagnosis-categories)]
(->> (fetch-patient-diagnoses system patient-ids)
(map #(assoc % :icd10 (first (codelists/to-icd10 system [(:t_diagnosis/concept_fk %)]))))
(map #(merge % (diag-fn [(:t_diagnosis/concept_fk %)])))
(map #(assoc % :term (:term (hermes/get-preferred-synonym (:com.eldrix/hermes system) (:t_diagnosis/concept_fk %) "en-GB")))))))
(defn merge-diagnostic-categories
[diagnoses]
(let [categories (keys study-diagnosis-categories)
diagnoses' (map #(select-keys % categories) diagnoses)
all-false (zipmap (keys study-diagnosis-categories) (repeat false))]
(apply merge-with #(or %1 %2) (conj diagnoses' all-false))))
(defn fetch-non-dmt-medications [system patient-ids]
(let [drug-fn (make-codelist-category-fn system study-medications)
all-dmts (all-dmt-identifiers system)
fetch-drug' (memoize fetch-drug)]
(->> (medications-for-patients system patient-ids)
(remove #(all-dmts (:t_medication/medication_concept_fk %)))
(map #(merge %
(fetch-drug' system (:t_medication/medication_concept_fk %))
(drug-fn [(:t_medication/medication_concept_fk %)]))))))
(s/fdef write-table
:args (s/cat :system any?
:table (s/keys :req-un [::filename ::data-fn] :opt-un [::columns ::title-fn])
:centre ::centre
:patient-ids (s/coll-of pos-int?)))
(defn write-table
"Write out a data export table. Parameters:
- system
- table - a map defining the table, to include:
- :filename - filename to use
- :data-fn - function to create data
- :columns - a vector of columns to write; optional
- :title-fn - a function, or map, to convert each column key for output.
- optional, default `name`.
- centre - keyword representing centre
- patient-ids - a sequence of patient identifiers
Injects special properties into each row:
- ::patient-id : a centre prefixed patient identifier
- ::centre : the centre set during export."
[system {:keys [filename data-fn columns title-fn]} centre patient-ids]
(let [make-pt-id #(str (get-in study-centres [centre :prefix]) (format "%06d" %))
rows (->> (data-fn system patient-ids)
(map #(assoc % ::centre (name centre)
::patient-id (make-pt-id (:t_patient/patient_identifier %)))))
columns' (or columns (keys (first rows)))
title-fn' (merge {::patient-id "patient_id" ::centre "centre"} title-fn) ;; add a default column titles
headers (mapv #(name (or (title-fn' %) %)) columns')]
(with-open [writer (io/writer filename)]
(csv/write-csv writer (into [headers] (map (fn [row] (mapv (fn [col] (col row)) columns')) rows))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;
;;;;;;;
;;;;;;;
;;;;;;;
;;;;;;;
;;;;;;;
;;;;;;;
;;;;;;;
(defn fetch-project-patient-identifiers
"Returns patient identifiers for those registered to one of the projects
specified. Discharged patients are *not* included."
[{conn :com.eldrix.rsdb/conn} project-names]
(let [project-ids (set (map #(:t_project/id (projects/project-with-name conn %)) project-names))
child-project-ids (set (mapcat #(projects/all-children-ids conn %) project-ids))
all-project-ids (set/union project-ids child-project-ids)]
(patients/patient-ids-in-projects conn all-project-ids)))
(s/fdef fetch-study-patient-identifiers
:args (s/cat :system any? :centre ::centre))
(defn fetch-study-patient-identifiers
"Returns a collection of patient identifiers for the DMT study."
[system centre]
(let [all-dmts (all-he-dmt-identifiers system)]
(->> (fetch-project-patient-identifiers system (get-in study-centres [centre :projects]))
(medications-for-patients system)
#_(filter #(all-dmts (:t_medication/medication_concept_fk %)))
(map :t_patient/patient_identifier)
set)))
(defn patients-with-more-than-one-death-certificate
[{conn :com.eldrix.rsdb/conn}]
(when-let [patient-fks (seq (plan/select! conn :patient_fk (sql/format {:select [:patient_fk]
:from [:t_death_certificate]
:group-by [:patient_fk]
:having [:> :%count.patient_fk 1]})))]
(patients/pks->identifiers conn patient-fks)))
(defn dmts-recorded-as-product-packs
"Return a sequence of medications in which a DMT has been recorded as a
product pack, rather than VTM, VMP or AMP. "
[system patient-ids]
(let [all-dmts (all-he-dmt-identifiers system)
all-meds (medications-for-patients system patient-ids)]
(->> all-meds
(filter :t_medication/converted_from_pp)
(filter #(all-dmts (:t_medication/medication_concept_fk %))))))
(defn patients-with-local-demographics [system patient-ids]
(map :patient_identifier (next.jdbc.plan/select! (:com.eldrix.rsdb/conn system) [:patient_identifier]
(sql/format {:select :patient_identifier
:from :t_patient
:where [:and
[:in :patient_identifier patient-ids]
[:= :authoritative_demographics "LOCAL"]]}))))
(defn make-metadata [system]
(let [deps (edn/read (PushbackReader. (io/reader "deps.edn")))]
{:data (fetch-most-recent-encounter-date-time system)
:pc4 {:url ""
:sha (str/trim (:out (clojure.java.shell/sh "/bin/sh" "-c" "git rev-parse HEAD")))}
:hermes {:url ""
:version (get-in deps [:deps 'com.eldrix/hermes :mvn/version])
:data (map #(hash-map :title (:term %) :date (:effectiveTime %)) (hermes/get-release-information (:com.eldrix/hermes system)))}
:dmd {:url ""
:version (get-in deps [:deps 'com.eldrix/dmd :mvn/version])
:data {:title "UK Dictionary of Medicines and Devices (dm+d)"
:date (com.eldrix.dmd.core/fetch-release-date (:com.eldrix/dmd system))}}
:codelists {:study-medications study-medications
:study-diagnoses study-diagnosis-categories}}))
(defn make-problem-report [system patient-ids]
{
generate a list of patients with more than one death certificate
:more-than-one-death-certificate
(or (patients-with-more-than-one-death-certificate system) [])
;; generate a list of medications recorded as product packs
:patients-with-dmts-as-product-packs
{:description "This is a list of patients who have their DMT recorded as an AMPP or VMPP, rather
than as a VTM,AMP or VMP. This is simply for internal centre usage, as it does not impact data."
:patients (map :t_patient/patient_identifier (dmts-recorded-as-product-packs system patient-ids))}
;; generate a list of patients in the study without multiple sclerosis
:patients-without-ms-diagnosis
(let [with-ms (set (map :t_patient/patient_identifier (filter :has_multiple_sclerosis (vals (multiple-sclerosis-onset system patient-ids)))))]
(set/difference patient-ids with-ms))
;; generate a list of incorrect alemtuzumab records
:incorrect-alemtuzumab-course-dates
(->> (alemtuzumab-medications system patient-ids)
vals
(remove nil?)
flatten
(remove valid-alemtuzumab-record?))
patients not linked to NHS demographics
:not-linked-nhs-demographics (let [local-patient-ids (patients-with-local-demographics system patient-ids)]
{:description "This is a list of patients who are not linked to NHS Wales' systems for status updates.
This should be 0% for the Cardiff group, and 100% for other centres."
:score (str (math/round (* 100 (/ (count local-patient-ids) (count patient-ids)))) "%")
:patient-ids local-patient-ids})})
(defn update-all
"Applies function 'f' to the values of the keys 'ks' in the map 'm'."
[m ks f]
(reduce (fn [v k] (update v k f)) m ks))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-patients-table
[system patient-ids]
(let [onsets (multiple-sclerosis-onset system patient-ids)
cohort-entry-meds (cohort-entry-meds system patient-ids study-master-date)
cohort-entry-dates (update-vals cohort-entry-meds :t_medication/date_from)
deprivation (deprivation-quartiles-for-patients system patient-ids cohort-entry-dates)
active-encounters (active-encounters-for-patients system patient-ids)
earliest-contacts (update-vals active-encounters #(:t_encounter/date_time (last %)))
latest-contacts (update-vals active-encounters #(:t_encounter/date_time (first %)))
edss (edss-scores system patient-ids)
smoking (fetch-smoking-status system patient-ids)
ms-events (ms-events-for-patients system patient-ids)]
(->> (fetch-patients system patient-ids)
(map #(let [patient-id (:t_patient/patient_identifier %)
cohort-entry-med (get cohort-entry-meds patient-id)
onsets (get onsets patient-id)
onset-date (:calculated-onset onsets)
has-multiple-sclerosis (boolean (:has_multiple_sclerosis onsets))
date-death (when-let [d (:t_patient/date_death %)] (.withDayOfMonth d 15))]
(-> (merge % cohort-entry-med)
(update :t_patient/sex (fnil name ""))
(update :dmt (fnil name ""))
(update :dmt_class (fnil name ""))
(assoc :depriv_quartile (get deprivation patient-id)
:start_follow_up (to-local-date (get earliest-contacts patient-id))
:year_birth (when (:t_patient/date_birth %) (.getYear (:t_patient/date_birth %)))
:date_death date-death
:onset onset-date
:has_multiple_sclerosis has-multiple-sclerosis
:smoking (get-in smoking [patient-id :t_smoking_history/status])
:disease_duration_years (when (and (:t_medication/date_from cohort-entry-med) onset-date)
(.getYears (Period/between ^LocalDate onset-date ^LocalDate (:t_medication/date_from cohort-entry-med))))
calculate most recent non - relapsing EDSS at cohort entry date
(:t_form_edss/edss_score (get-most-recent (remove :t_form_ms_relapse/in_relapse (get edss patient-id)) :t_encounter/date (:t_medication/date_from cohort-entry-med))))
:date_edss_4 (when (:t_medication/date_from cohort-entry-med)
(to-local-date (date-at-edss-4 (get edss patient-id))))
:nc_time_edss_4 (when (:t_medication/date_from cohort-entry-med)
(when-let [date (to-local-date (date-at-edss-4 (get edss patient-id)))]
(when onset-date
(.between ChronoUnit/DAYS onset-date date))))
:nc_relapses (when (:t_medication/date_from cohort-entry-med)
(count (relapses-between-dates (get ms-events patient-id) (.minusYears (:t_medication/date_from cohort-entry-med) 1) (:t_medication/date_from cohort-entry-med))))
:end_follow_up (or date-death (to-local-date (get latest-contacts patient-id))))
(dissoc :t_patient/date_birth)))))))
(def patients-table
{:filename "patients.csv"
:data-fn make-patients-table
:columns [::patient-id
::centre
:t_patient/sex :year_birth :date_death
:depriv_quartile :start_follow_up :end_follow_up
:t_death_certificate/part1a :t_death_certificate/part1b :t_death_certificate/part1c :t_death_certificate/part2
:atc :dmt :dmt_class :t_medication/date_from
:exposure_days
:smoking
:most_recent_edss
:has_multiple_sclerosis
:onset
:date_edss_4
:nc_time_edss_4
:disease_duration_years
:nc_relapses
:n_prior_he_dmts :n_prior_platform_dmts
:first_use :switch?]
:title-fn {:t_medication/date_from "cohort_entry_date"
:switch? "switch"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-patient-identifiers-table [system patient-ids]
(db/execute! (:com.eldrix.rsdb/conn system)
(sql/format {:select [:patient_identifier :stored_pseudonym :t_project/name] :from [:t_episode :t_patient :t_project]
:where [:and [:= :patient_fk :t_patient/id]
[:= :project_fk :t_project/id]
[:in :t_patient/patient_identifier patient-ids]]
:order-by [[:t_patient/id :asc]]})))
(def patient-identifiers-table
{:filename "patient-identifiers.csv"
:data-fn make-patient-identifiers-table
:columns [::patient-id
:t_project/name
:t_episode/stored_pseudonym]})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-raw-dmt-medications-table
[system patient-ids]
(->> (patient-raw-dmt-medications system patient-ids)
vals
(mapcat identity)
(map #(update-all % [:dmt :dmt_class :t_medication/reason_for_stopping] name))))
(def raw-dmt-medications-table
{:filename "patient-raw-dmt-medications.csv"
:data-fn make-raw-dmt-medications-table
:columns [::patient-id
:t_medication/medication_concept_fk
:atc :dmt :dmt_class
:t_medication/date_from :t_medication/date_to
:t_medication/reason_for_stopping]})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-dmt-regimens-table
[system patient-ids]
(->> (patient-dmt-sequential-regimens system patient-ids)
vals
(mapcat identity)
(map #(update-all % [:dmt :dmt_class :switch_from :t_medication/reason_for_stopping] (fnil name "")))))
(def dmt-regimens-table
{:filename "patient-dmt-regimens.csv"
:data-fn make-dmt-regimens-table
:columns [::patient-id
:t_medication/medication_concept_fk
:atc :dmt :dmt-class
:t_medication/date_from :t_medication/date_to :exposure_days
:switch_from :n_prior_platform_dmts :n_prior_he_dmts]
:title-fn {:dmt-class "dmt_class"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn dates-of-anaphylaxis-reactions
"Creates a map containing anaphylaxis diagnoses, keyed by a vector of
patient identifier and date. This is derived from a diagnosis of anaphylaxis
in the problem list.
TODO: Use the t_medication_event table to impute life-threatening events from
the historic record."
[system patient-ids]
(let [anaphylaxis-diagnoses (set (map :conceptId (hermes/expand-ecl-historic (:com.eldrix/hermes system) "<<39579001")))
pt-diagnoses (->> (fetch-patient-diagnoses system patient-ids)
(filter #(anaphylaxis-diagnoses (:t_diagnosis/concept_fk %))))]
(zipmap (map #(vector (:t_patient/patient_identifier %)
(:t_diagnosis/date_onset %)) pt-diagnoses)
pt-diagnoses)))
(defn make-alemtuzumab-infusions
"Create ordered sequence of individual infusions. Each item will include
properties with date, drug, course-rank, infusion-rank and whether that
infusion coincided with an allergic reaction."
[system patient-ids]
(let [anaphylaxis-reactions (dates-of-anaphylaxis-reactions system patient-ids)]
(->> patient-ids
(ranked-alemtuzumab-infusions system)
vals
flatten
(map #(update-all % [:dmt :dmt_class] name))
(map #(assoc % :anaphylaxis (boolean (get anaphylaxis-reactions [(:t_patient/patient_identifier %) (:t_medication/date %)]))))
(sort-by (juxt :t_patient/patient_identifier :course-rank :infusion-rank)))))
(def alemtuzumab-infusions-table
{:filename "alemtuzumab-infusions.csv"
:data-fn make-alemtuzumab-infusions
:columns [::patient-id
:dmt
:t_medication/medication_concept_fk
:atc
:t_medication/date
:valid
:course-rank
:infusion-rank
:anaphylaxis]
:title-fn {:course-rank "course_rank"
:infusion-rank "infusion_rank"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn date-in-range-inclusive?
[^LocalDate date-from ^LocalDate date-to ^LocalDate date]
(when (and date-from date-to date)
(or (.isEqual date date-from)
(.isEqual date date-to)
(and (.isAfter date date-from) (.isBefore date date-to)))))
(defn make-admissions-table
[system patient-ids]
(let [diagnoses (group-by :t_patient/patient_identifier (all-patient-diagnoses system patient-ids))
get-diagnoses (fn [patient-id ^LocalDate date-from ^LocalDate date-to] ;; create a function to fetch a patient's diagnoses within a date range
(->> (get diagnoses patient-id)
(filter #(date-in-range-inclusive? date-from date-to (or (:t_diagnosis/date_diagnosis %) (:t_diagnosis/date_onset %))))))]
(->> (fetch-patient-admissions system "ADMISSION" patient-ids)
(map (fn [{patient-id :t_patient/patient_identifier
:t_episode/keys [date_registration date_discharge] :as admission}]
(-> admission
(assoc :t_episode/duration_days
(when (and date_registration date_discharge)
(.between ChronoUnit/DAYS date_registration date_discharge)))
(merge (merge-diagnostic-categories (get-diagnoses patient-id date_registration date_discharge)))))))))
(comment
(fetch-patient-admissions system "ADMISSION" [17490])
(group-by :t_patient/patient_identifier (all-patient-diagnoses system [17490]))
(time (make-admissions-table system [17490])))
(def admissions-table
{:filename "patient-admissions.csv"
:data-fn make-admissions-table
:columns (into [::patient-id
:t_episode/date_registration
:t_episode/date_discharge
:t_episode/duration_days]
(keys study-diagnosis-categories))
:title-fn {:t_episode/date_registration "date_from"
:t_episode/date_discharge "date_to"
:t_episode/duration_days "duration_days"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-non-dmt-medications
[system patient-ids]
(fetch-non-dmt-medications system patient-ids))
(def non-dmt-medications-table
{:filename "patient-non-dmt-medications.csv"
:data-fn make-non-dmt-medications
:columns [::patient-id :t_medication/medication_concept_fk
:t_medication/date_from :t_medication/date_to :nm :atc
:anti-hypertensive :antidepressant :anti-retroviral :statin :anti-platelet :immunosuppressant
:benzodiazepine :antiepileptic :proton-pump-inhibitor :nutritional :antidiabetic
:anti-coagulant :anti-infectious]
:title-fn {:anti-hypertensive :anti_hypertensive
:anti-retroviral :anti_retroviral
:anti-platelet :anti_platelet
:proton-pump-inhibitor :proton_pump_inhibitor
:anti-coagulant :anti_coagulant
:anti-infectious :anti_infectious}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-ms-events-table [system patient-ids]
(mapcat identity (vals (ms-events-for-patients system patient-ids))))
(def ms-events-table
{:filename "patient-ms-events.csv"
:data-fn make-ms-events-table
:columns [::patient-id
:t_ms_event/date :t_ms_event/impact :t_ms_event_type/abbreviation
:t_ms_event/is_relapse :t_ms_event_type/name]
:title-fn {:t_ms_event_type/abbreviation "type"
:t_ms_event_type/name "description"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def diagnoses-table
{:filename "patient-diagnoses.csv"
:data-fn all-patient-diagnoses
:columns (into [::patient-id
:t_diagnosis/concept_fk
:t_diagnosis/date_onset :t_diagnosis/date_diagnosis :t_diagnosis/date_to
:icd10
:term]
(keys study-diagnosis-categories))})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-edss-table [system patient-ids]
(mapcat identity (vals (edss-scores system patient-ids))))
(def edss-table
{:filename "patient-edss.csv"
:data-fn make-edss-table
:columns [::patient-id :t_encounter/date :t_form_edss/edss_score
:t_ms_disease_course/type :t_ms_disease_course/name
:t_form_ms_relapse/in_relapse :t_form_ms_relapse/date_status_recorded]
:title-fn {:t_ms_disease_course/type "disease_status"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn fetch-results-for-patient [{:com.eldrix.rsdb/keys [conn]} patient-identifier]
(->> (com.eldrix.pc4.rsdb.results/results-for-patient conn patient-identifier)
(map #(assoc % :t_patient/patient_identifier patient-identifier))))
(defn make-results-table [system patient-ids]
(->> (mapcat #(fetch-results-for-patient system %) patient-ids)
(map #(select-keys % [:t_patient/patient_identifier :t_result/date :t_result_type/name]))))
(def results-table
{:filename "patient-results.csv"
:data-fn make-results-table
:columns [::patient-id :t_result/date :t_result_type/name]
:title-fn {:t_result/date "date"
:t_result_type/name "test"}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def observations-missing
"A set of patient pseudonyms with observation data missing"
#{})
(defn observation-missing?
"Returns whether the patient specified has observations missing."
[system patient-id]
(let [pseudonyms (set (map :t_episode/stored_pseudonym
(db/execute! (:com.eldrix.rsdb/conn system)
(sql/format {:select :stored_pseudonym
:from [:t_episode :t_patient]
:where [:and
[:= :t_episode/patient_fk :t_patient/id]
[:= :patient_identifier patient-id]]}))))]
(seq (set/intersection observations-missing pseudonyms))))
(def observations-table
"The observations table is generated by exception reporting. If a patient does
not have an exception filed by the team, then we impute that observations were
performed."
{:filename "patient-obs.csv"
:data-fn (fn [system patient-ids]
(map #(let [not-missing? (not (observation-missing? system %))]
(hash-map :t_patient/patient_identifier %
:pulse not-missing?
:blood_pressure not-missing?))
patient-ids))
:columns [::patient-id :pulse :blood_pressure]})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-weight-height-table [system patient-ids]
(->> (mapcat identity (vals (fetch-weight-height system patient-ids)))
(map #(update % :t_encounter/date_time to-local-date))))
(def weight-height-table
{:filename "patient-weight.csv"
:data-fn make-weight-height-table
:columns [::patient-id :t_encounter/date_time
:t_form_weight_height/weight_kilogram :t_form_weight_height/height_metres
:body_mass_index]
:title-fn {:t_encounter/date_time "date"}})
(def jc-virus-table
{:filename "patient-jc-virus.csv"
:data-fn jc-virus-for-patients
:columns [::patient-id
:t_result_jc_virus/date
:t_result_jc_virus/jc_virus
:t_result_jc_virus/titre]})
(def mri-brain-table
{:filename "patient-mri-brain.csv"
:data-fn mri-brains-for-patients
:columns [::patient-id
:t_result_mri_brain/date
:t_result_mri_brain/id
:t_result_mri_brain/multiple_sclerosis_summary
:t_result_mri_brain/with_gadolinium
:t_result_mri_brain/total_gad_enhancing_lesions
:t_result_mri_brain/gad_range_lower
:t_result_mri_brain/gad_range_upper
:t_result_mri_brain/total_t2_hyperintense
:t_result_mri_brain/t2_range_lower
:t_result_mri_brain/t2_range_upper
:t_result_mri_brain/compare_to_result_mri_brain_fk
:t_result_mri_brain/compare_to_result_date
:t_result_mri_brain/change_t2_hyperintense
:t_result_mri_brain/calc_change_t2]
:title-fn {:t_result_mri_brain/multiple_sclerosis_summary "ms_summary"
:t_result_mri_brain/with_gadolinium "with_gad"
:t_result_mri_brain/total_gad_enhancing_lesions "gad_count"
:t_result_mri_brain/gad_range_lower "gad_lower"
:t_result_mri_brain/gad_range_upper "gad_upper"
:t_result_mri_brain/total_t2_hyperintense "t2_count"
:t_result_mri_brain/t2_range_lower "t2_lower"
:t_result_mri_brain/t2_range_upper "t2_upper"
:t_result_mri_brain/compare_to_result_date "compare_to_date"
:t_result_mri_brain/compare_to_result_mri_brain_fk "compare_to_id"
:t_result_mri_brain/change_t2_hyperintense "t2_change"
:t_result_mri_brain/calc_change_t2 "calc_t2_change"}})
(defn write-local-date [^LocalDate o ^Appendable out _options]
(.append out \")
(.append out (.format (DateTimeFormatter/ISO_DATE) o))
(.append out \"))
(defn write-local-date-time [^LocalDateTime o ^Appendable out _options]
(.append out \")
(.append out (.format (DateTimeFormatter/ISO_DATE_TIME) o))
(.append out \"))
(extend LocalDate json/JSONWriter {:-write write-local-date})
(extend LocalDateTime json/JSONWriter {:-write write-local-date-time})
(def export-tables
[patients-table
patient-identifiers-table
raw-dmt-medications-table
dmt-regimens-table
alemtuzumab-infusions-table
admissions-table
non-dmt-medications-table
ms-events-table
diagnoses-table
edss-table
results-table
weight-height-table
jc-virus-table
mri-brain-table
observations-table])
(s/fdef write-data
:args (s/cat :system any? :centre ::centre))
(defn write-data [system centre]
(let [patient-ids (fetch-study-patient-identifiers system centre)]
(doseq [table export-tables]
(log/info "writing table:" (:filename table))
(write-table system table centre patient-ids))
(log/info "writing metadata")
(with-open [writer (io/writer "metadata.json")]
(json/write (make-metadata system) writer :indent true))
(log/info "writing problem report")
(with-open [writer (io/writer "problems.json")]
(json/write (make-problem-report system patient-ids) writer :indent true))
(log/info "writing medication codes")
(csv/write-csv (io/writer "medication-codes.csv")
(->> (expand-codelists system flattened-study-medications)
(mapcat #(map (fn [concept-id] (vector (:id %) concept-id (:term (hermes/get-fully-specified-name (:com.eldrix/hermes system) concept-id))))
(:codes %)))))
(log/info "writing diagnosis codes")
(csv/write-csv (io/writer "diagnosis-codes.csv")
(->> (expand-codelists system flattened-study-diagnoses)
(mapcat #(map (fn [concept-id] (vector (:id %) concept-id (:term (hermes/get-fully-specified-name (:com.eldrix/hermes system) concept-id))))
(:codes %)))))))
(defn matching-cav-demog?
[{:t_patient/keys [last_name date_birth sex nhs_number] :as pt}
{:wales.nhs.cavuhb.Patient/keys [HOSPITAL_ID LAST_NAME DATE_BIRTH SEX NHS_NO] :as cavpt}]
(let [SEX' (get {"M" :MALE "F" :FEMALE} SEX)]
(boolean (and cavpt HOSPITAL_ID LAST_NAME DATE_BIRTH
(or (nil? NHS_NO) (nil? nhs_number)
(and (.equalsIgnoreCase nhs_number NHS_NO)))
(= DATE_BIRTH date_birth)
(= SEX' sex)
(.equalsIgnoreCase LAST_NAME last_name)))))
(def ^:private demographic-eql
[:t_patient/id
:t_patient/patient_identifier
:t_patient/first_names
:t_patient/last_name :t_patient/nhs_number
:t_patient/date_birth
:t_patient/sex
:t_patient/authoritative_demographics
:t_patient/demographics_authority
:t_patient/authoritative_last_updated
{:t_patient/hospitals [:t_patient_hospital/id
:t_patient_hospital/hospital_fk
:t_patient_hospital/patient_fk
:t_patient_hospital/patient_identifier
:wales.nhs.cavuhb.Patient/HOSPITAL_ID
:wales.nhs.cavuhb.Patient/NHS_NUMBER
:wales.nhs.cavuhb.Patient/LAST_NAME
:wales.nhs.cavuhb.Patient/FIRST_NAMES
:wales.nhs.cavuhb.Patient/DATE_BIRTH
:wales.nhs.cavuhb.Patient/DATE_DEATH
:wales.nhs.cavuhb.Patient/SEX]}])
(defn check-patient-demographics
"Check a single patient's demographics. This will call out to backend live
demographic authorities in order to provide demographic data for the given
patient, so there is an optionally sleep-millis parameter to avoid
denial-of-service attacks if used in batch processes."
[{pathom :pathom/boundary-interface} patient-identifier & {:keys [sleep-millis]}]
(when sleep-millis (Thread/sleep sleep-millis))
(let [ident [:t_patient/patient_identifier patient-identifier]
pt (get (pathom [{ident demographic-eql}]) ident)
pt2 (when pt (update pt
:t_patient/hospitals
(fn [hosps]
(map #(assoc % :demographic-match (matching-cav-demog? pt %)) hosps))))]
(when pt (assoc pt2 :potential-authoritative-demographics
(first (filter :demographic-match (:t_patient/hospitals pt2)))))))
(s/def ::profile keyword?)
(s/def ::export-options (s/keys :req-un [::profile]))
(defn export
"Export research data.
Run as:
```
clj -X com.eldrix.pc4.modules.dmt/export :profile :cvx :centre :cardiff
clj -X com.eldrix.pc4.modules.dmt/export :profile :pc4 :centre :plymouth
clj -X com.eldrix.pc4.modules.dmt/export :profile :dev :centre :cambridge
```
Profile determines the environment in which to use. There are four running
pc4 environments currently:
* dev - development
* nuc - development
* pc4 - Amazon AWS infrastructure
* cvx - NHS Wales infrastructure
Centre determines the choice of projects from which to analyse patients.
* :cardiff
* :plymouth
* :cambridge"
[{:keys [profile centre] :as opts}]
(when-not (s/valid? ::export-options opts)
(throw (ex-info "Invalid options:" (s/explain-data ::export-options opts))))
(let [system (pc4/init profile [:pathom/boundary-interface])]
(write-data system centre)))
(defn make-demography-check [system profile patient-ids]
(->> patient-ids
(patients-with-local-demographics system)
(map #(check-patient-demographics system % :sleep-millis (get {:cvx 500} profile)))
(map #(hash-map
:t_patient/patient_identifier (:t_patient/patient_identifier %)
:first_names (:t_patient/first_names %)
:last_name (:t_patient/last_name %)
:date_birth (:t_patient/date_birth %)
:nhs_number (:t_patient/nhs_number %)
:demog (:t_patient/authoritative_demographics %)
:match_org (get-in % [:potential-authoritative-demographics :t_patient_hospital/hospital_fk])
:crn (get-in % [:potential-authoritative-demographics :t_patient_hospital/patient_identifier])
:cav_match (boolean (get-in % [:potential-authoritative-demographics :demographic-match]))
:cav_crn (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/HOSPITAL_ID])
:cav_nnn (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/NHS_NUMBER])
:cav_dob (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/DATE_BIRTH])
:cav_fname (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/FIRST_NAMES])
:cav_lname (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/LAST_NAME])))))
(defn check-demographics
"Check demographics report. Run as:
```
clj -X com.eldrix.pc4.modules.dmt/check-demographics :profile :cvx :centre :cardiff
```"
[{:keys [profile centre] :as opts}]
(when-not (s/valid? ::export-options opts)
(throw (ex-info "Invalid options:" (s/explain-data ::export-options opts))))
(log/info "check-demographics with " opts)
(let [system (pc4/init profile [:pathom/boundary-interface :wales.nhs.cavuhb/pms])
patient-ids (fetch-study-patient-identifiers system centre)]
(write-table system {:filename "demography-check.csv"
:data-fn (fn [system patient-ids] (make-demography-check system profile patient-ids))}
centre patient-ids)
(pc4/halt! system)))
(defn update-demographic-authority
"Update demographic authorities. Run as:
```
clj -X com.eldrix.pc4.modules.dmt/update-demographic-authority :profile :cvx :centre :cardiff
```"
[{:keys [profile centre] :as opts}]
(when-not (s/valid? ::export-options opts)
(throw (ex-info "Invalid options:" (s/explain-data ::export-options opts))))
(let [system (pc4/init profile [:pathom/boundary-interface :wales.nhs.cavuhb/pms])
patient-ids (fetch-study-patient-identifiers system centre)
patients (->> patient-ids
(patients-with-local-demographics system)
(map #(check-patient-demographics system % :sleep-millis (get {:cvx 500} profile)))
(filter #(get-in % [:potential-authoritative-demographics :demographic-match])))]
(doseq [patient patients]
(patients/set-cav-authoritative-demographics! (:com.eldrix/clods system)
(:com.eldrix.rsdb/conn system)
patient
(:potential-authoritative-demographics patient)))
(pc4/halt! system)))
(defn admission->episode [patient-pk user-id {:wales.nhs.cavuhb.Admission/keys [DATE_FROM DATE_TO] :as admission}]
(when (and admission DATE_FROM DATE_TO)
{:t_episode/patient_fk patient-pk
:t_episode/user_fk user-id
:t_episode/date_registration (.toLocalDate DATE_FROM)
:t_episode/date_discharge (.toLocalDate DATE_TO)}))
(defn admissions-for-patient [system patient-identifier]
(let [ident [:t_patient/patient_identifier patient-identifier]
admissions (p.eql/process (:pathom/env system) [{ident
[:t_patient/id
{:t_patient/demographics_authority
[:wales.nhs.cavuhb.Patient/ADMISSIONS]}]}])
patient-pk (get-in admissions [ident :t_patient/id])
admissions' (get-in admissions [ident :t_patient/demographics_authority :wales.nhs.cavuhb.Patient/ADMISSIONS])]
(map #(admission->episode patient-pk 1 %) admissions')))
(defn update-cav-admissions
"Update admission data from CAVPMS. Run as:
```
clj -X com.eldrix.pc4.modules.dmt/update-cav-admissions :profile :cvx :centre :cardiff
```"
[{:keys [profile centre]}]
(let [system (pc4/init profile [:pathom/boundary-interface :wales.nhs.cavuhb/pms])
project (projects/project-with-name (:com.eldrix.rsdb/conn system) "ADMISSION")
project-id (:t_project/id project)]
(dorun
(->> (fetch-study-patient-identifiers system centre)
(mapcat #(admissions-for-patient system %))
(remove nil?)
(map #(assoc % :t_episode/project_fk project-id))
(map #(projects/register-completed-episode! (:com.eldrix.rsdb/conn system) %))))
(pc4/halt! system)))
(defn update-admissions
[{:keys [profile project-id]}]
(let [{conn :com.eldrix.rsdb/conn :as system} (pc4/init profile [:pathom/boundary-interface :wales.nhs.cavuhb/pms])
admission-project (projects/project-with-name conn "ADMISSION")
project-id' (if (string? project-id) (parse-long project-id) project-id)]
(println "Fetching admissions for project" project-id')
(let [patient-ids (patients/patient-ids-in-projects conn [project-id'])]
(println "Patients in project:" (count patient-ids))
(dorun (->> patient-ids
(map #(do (println "patient:" %) %))
(mapcat #(admissions-for-patient system %))
(remove nil?)
(map #(assoc % :t_episode/project_fk (:t_project/id admission-project)))
(map #(do (println %) %))
(map #(projects/register-completed-episode! conn %)))))
(pc4/halt! system)))
(comment
(def system (pc4/init :cvx [:pathom/boundary-interface :wales.nhs.cavuhb/pms]))
(update-admissions {:profile :cvx :project-id 29}))
(defn matching-filenames
"Return a sequence of filenames from the directory specified, in a map keyed
by the filename."
[dir]
(->> (file-seq (io/as-file dir))
(filter #(.isFile %))
(reduce (fn [acc v] (update acc (.getName v) conj v)) {})))
(defn copy-csv-file
[writer csv-file]
(with-open [reader (io/reader csv-file)]
(->> (csv/read-csv reader)
(csv/write-csv writer))))
(defn append-csv-file
"Write data to writer from the csv-file, removing the first row"
[writer csv-file]
(with-open [reader (io/reader csv-file)]
(->> (csv/read-csv reader)
(rest)
(csv/write-csv writer))))
(defn merge-csv-files
[out files]
(with-open [writer (io/writer out)]
(copy-csv-file writer (first files))
(dorun (map #(append-csv-file writer %) (rest files)))))
(defn merge-matching-data
[dir out-dir]
(let [out-path (.toPath ^File (io/as-file out-dir))
files (->> (matching-filenames dir)
(filter (fn [[filename _files]]
(.endsWith (str/lower-case filename) ".csv"))))]
(println "Writing merged files to" out-path)
(Files/createDirectories out-path (make-array FileAttribute 0))
(dorun (map (fn [[filename csv-files]]
(let [out (.resolve out-path filename)]
(merge-csv-files (.toFile out) csv-files))) files))))
(defn merge-csv
"Merge directories of csv files based on matching filename.
Unfortunately, one must escape strings.
```
clj -X com.eldrix.pc4.modules.dmt/merge-csv :dir '\"/tmp/csv-files\"' :out '\"/tmp/merged\"'
```"
[{:keys [dir out]}]
(merge-matching-data (str dir) (str out)))
;; experimental JSON output
(comment
(def system (pc4/init :dev [:pathom/boundary-interface]))
(def patient-ids (take 100 (fetch-study-patient-identifiers system :cardiff)))
(def patients (fetch-patients system patient-ids))
(def ms-events (ms-events-for-patients system patient-ids))
(def dmt-regimens (group-by :t_patient/patient_identifier (make-dmt-regimens-table system patient-ids)))
(def non-dmt-meds (group-by :t_patient/patient_identifier (fetch-non-dmt-medications system patient-ids)))
(def encounters (active-encounters-for-patients system patient-ids))
(def mri-brains (group-by :t_patient/patient_identifier (mri-brains-for-patients system patient-ids)))
(def edss (edss-scores system patient-ids))
(def diagnoses (group-by :t_patient/patient_identifier (all-patient-diagnoses system patient-ids)))
(def data (map (fn [{:t_patient/keys [patient_identifier] :as patient}]
(assoc patient
:diagnoses (get diagnoses patient_identifier)
:medication (get non-dmt-meds patient_identifier)
:ms-events (get ms-events patient_identifier)
:dmts (get dmt-regimens patient_identifier)
;:encounters (get encounters patient_identifier)
:edss (get edss patient_identifier)
:mri-brain (get mri-brains patient_identifier))) patients))
(with-open [writer (io/writer (io/file "patients.json"))]
(json/write data writer)))
;;;
;;; Write out data
zip all csv files with the metadata.json
;;; zip
(comment
(require '[clojure.spec.test.alpha :as stest])
(stest/instrument)
(def system (pc4/init :dev [:pathom/boundary-interface :wales.nhs.cavuhb/pms]))
(pc4/halt! system)
(time (def a (fetch-project-patient-identifiers system (get-in study-centres [:cardiff :projects]))))
(def patient-ids (fetch-study-patient-identifiers system :cardiff))
(get-in study-centres [:cardiff :projects])
(projects/project-with-name (:com.eldrix.rsdb/conn system) "NINFLAMMCARDIFF")
(time (def b (patients/patient-ids-in-projects (:com.eldrix.rsdb/conn system) #{5} :patient-status #{:FULL :PSEUDONYMOUS :STUB :FAKE :DELETED :MERGED})))
(count b)
(set/difference a b)
(def patient-ids (fetch-study-patient-identifiers system :cardiff))
(count patient-ids)
(take 5 patient-ids)
(tap> (take 5 patient-ids))
(time (write-data system :cardiff))
(write-table system patients-table :cardiff patient-ids)
(write-table system diagnoses-table :cardiff patient-ids)
(spit "metadata.json" (json/write-str (make-metadata system)))
(check-patient-demographics system 14232)
(clojure.pprint/pprint (check-patient-demographics system 13936))
(clojure.pprint/pprint (make-demography-check system :cardiff [13936]))
(check-demographics {:profile :dev :centre :cardiff})
(matching-filenames "/Users/mark/Desktop/lempass")
(merge-matching-data "/Users/mark/Desktop/lempass" "/Users/mark/Desktop/lempass-merged")
(com.eldrix.concierge.wales.cav-pms/fetch-admissions (:wales.nhs.cavuhb/pms system) :crn "A647963")
(def pathom (:pathom/boundary-interface system))
(p.eql/process (:pathom/env system) [{[:t_patient/patient_identifier 93718]
[{:t_patient/demographics_authority
[:wales.nhs.cavuhb.Patient/ADMISSIONS]}]}])
(let [project (projects/project-with-name (:com.eldrix.rsdb/conn system) "ADMISSION")
project-id (:t_project/id project)]
(doseq [episode (remove nil? (mapcat #(admissions-for-patient system %) [93718]))]
(projects/register-completed-episode! (:com.eldrix.rsdb/conn system)
(assoc episode :t_episode/project_fk project-id))))
(mapcat #(admissions-for-patient system %) (take 3 (fetch-study-patient-identifiers system :cardiff)))
(take 5 (fetch-study-patient-identifiers system :cardiff))
(admissions-for-patient system 94967)
(projects/register-completed-episode! (:com.eldrix.rsdb/conn system)
(first (admissions-for-patient system 93718)))
(p.eql/process (:pathom/env system) [{[:t_patient/patient_identifier 94967]
[{:t_patient/demographics_authority
[:wales.nhs.cavuhb.Patient/ADMISSIONS]}]}])
(pathom [{[:t_patient/patient_identifier 78213] demographic-eql}])
(pathom [{[:wales.nhs.cavuhb.Patient/FIRST_FORENAME "Mark"]
[:wales.nhs.cavuhb.Patient/FIRST_FORENAME
:wales.nhs.cavuhb.Patient/FIRST_NAMES]}])
(pathom [{[:wales.nhs.cavuhb.Patient/HOSPITAL_ID "A542488"]
[:wales.nhs.cavuhb.Patient/FIRST_FORENAME
:wales.nhs.cavuhb.Patient/FIRST_NAMES
:wales.nhs.cavuhb.Patient/LAST_NAME]}])
(tap> (pathom [{[:t_patient/patient_identifier 94967]
[:t_patient/id
:t_patient/date_birth
:t_patient/date_death
{`(:t_patient/address {:date ~"2000-06-01"}) [:t_address/date_from
:t_address/date_to
{:uk.gov.ons.nhspd/LSOA-2011 [:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
{ : t_patient / addresses [: t_address / date_from : / date_to : uk.gov.ons/lsoa : uk - composite - imd-2020 - mysoc / UK_IMD_E_pop_decile ] }
:t_patient/sex
:t_patient/status
{:t_patient/surgery [:uk.nhs.ord/name]}
{:t_patient/medications [:t_medication/date_from
:t_medication/date_to
{:t_medication/medication [:info.snomed.Concept/id
{:info.snomed.Concept/preferredDescription [:info.snomed.Description/term]}
:uk.nhs.dmd/NM]}]}]}])))
(comment
(require '[portal.api :as p])
(p/open)
(add-tap #'p/submit)
(pc4/prep :dev)
(def system (pc4/init :dev [:pathom/boundary-interface]))
(integrant.core/halt! system)
(tap> system)
(keys system)
;; get the denominator patient population here....
(def rsdb-conn (:com.eldrix.rsdb/conn system))
(def roles (users/roles-for-user rsdb-conn "ma090906"))
(def manager (#'users/make-authorization-manager' roles))
(def user-projects (set (map :t_project/id (users/projects-with-permission roles :DATA_DOWNLOAD))))
(def requested-projects #{5})
(def patient-ids (patients/patients-in-projects
rsdb-conn
(clojure.set/intersection user-projects requested-projects)))
(count patient-ids)
(take 4 patient-ids)
(def pathom (:pathom/boundary-interface system))
(:pathom/env system)
(def pt (pathom [{[:t_patient/patient_identifier 17490]
[:t_patient/id
:t_patient/date_birth
:t_patient/date_death
{`(:t_patient/address {:date ~"2000-06-01"}) [:t_address/date_from
:t_address/date_to
{:uk.gov.ons.nhspd/LSOA-2011 [:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
{:t_patient/addresses [:t_address/date_from :t_address/date_to :uk.gov.ons/lsoa :uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
:t_patient/sex
:t_patient/status
{:t_patient/surgery [:uk.nhs.ord/name]}
{:t_patient/medications [:t_medication/date_from
:t_medication/date_to
{:t_medication/medication [:info.snomed.Concept/id
:uk.nhs.dmd/NM]}]}]}]))
(tap> pt)
(tap> "Hello World")
(pathom [{[:info.snomed.Concept/id 9246601000001104]
[{:info.snomed.Concept/preferredDescription [:info.snomed.Description/term]}
:uk.nhs.dmd/NM]}])
(def natalizumab (get
(pathom [{[:info.snomed.Concept/id 36030311000001108]
[:uk.nhs.dmd/TYPE
:uk.nhs.dmd/NM
:uk.nhs.dmd/ATC
:uk.nhs.dmd/VPID
:info.snomed.Concept/parentRelationshipIds
{:uk.nhs.dmd/VMPS [:info.snomed.Concept/id
:uk.nhs.dmd/VPID
:uk.nhs.dmd/NM
:uk.nhs.dmd/ATC
:uk.nhs.dmd/BNF]}]}])
[:info.snomed.Concept/id 36030311000001108]))
(def all-rels (apply clojure.set/union (vals (:info.snomed.Concept/parentRelationshipIds natalizumab))))
(map #(:term (com.eldrix.hermes.core/get-preferred-synonym (:com.eldrix/hermes system) % "en-GB")) all-rels)
(tap> natalizumab)
(reduce-kv (fn [m k v] (assoc m k (if (map? v) (dissoc v :com.wsscode.pathom3.connect.runner/attribute-errors) v))) {} natalizumab)
(pathom [{'(info.snomed.Search/search
search UK products
:max-hits 10})
[:info.snomed.Concept/id
:uk.nhs.dmd/NM
:uk.nhs.dmd/TYPE
:info.snomed.Description/term
{:info.snomed.Concept/preferredDescription [:info.snomed.Description/term]}
:info.snomed.Concept/active]}])
(pathom [{'(info.snomed.Search/search {:s "glatiramer acetate"})
[:info.snomed.Concept/id
:info.snomed.Description/term
{:info.snomed.Concept/preferredDescription [:info.snomed.Description/term]}]}])
(pathom [{'(info.snomed.Search/search {:constraint "<<9246601000001104 OR <<108755008"})
[:info.snomed.Concept/id
:info.snomed.Description/term]}])
(def hermes (:com.eldrix/hermes system))
hermes
(require '[com.eldrix.hermes.core :as hermes])
(def dmf (set (map :conceptId (hermes/search hermes {:constraint "(<<24056811000001108|Dimethyl fumarate|) OR (<<12086301000001102|Tecfidera|) OR (<10363601000001109|UK Product| :10362801000001104|Has specific active ingredient| =<<724035008|Dimethyl fumarate|)"}))))
(contains? dmf 12086301000001102)
(contains? dmf 24035111000001108))
| null | https://raw.githubusercontent.com/wardle/pc4/0b38fb7648965232b1ef90fcb4d3f3affc22adf1/pc4-server/src/clj/com/eldrix/pc4/modules/dmt.clj | clojure | note: also significance based on whether admitted for problem
I have used a different definition to the protocol as R03.0 is wrong
this means 'hypertensive emergency'
remove any entries after our date
if no recent relapse recorded, record as FALSE explicitly.
address-for-date will use 'now' if date nil, so wrap
return any DMT
return any DMT of same class HE vs platform
return same DMT
(filter #(let [start-date (:t_medication/date_from %)] (or (nil? start-date) (.isAfter (:t_medication/date_from %) study-master-date))))
(filter #(all-he-dmt-identifiers (:t_medication/medication_concept_fk %)))
this partitions every time :dmt changes, which gives us sequential groups of medications
optional
add a default column titles
generate a list of medications recorded as product packs
generate a list of patients in the study without multiple sclerosis
generate a list of incorrect alemtuzumab records
create a function to fetch a patient's diagnoses within a date range
experimental JSON output
:encounters (get encounters patient_identifier)
Write out data
zip
get the denominator patient population here.... | (ns com.eldrix.pc4.modules.dmt
"Experimental approach to data downloads, suitable for short-term
requirements for multiple sclerosis disease modifying drug
post-marketing surveillance."
(:require [clojure.data.csv :as csv]
[clojure.data.json :as json]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.java.shell]
[clojure.math :as math]
[clojure.set :as set]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as stest]
[clojure.string :as str]
[clojure.tools.logging.readable :as log]
[com.eldrix.deprivare.core :as deprivare]
[com.eldrix.dmd.core :as dmd]
[com.eldrix.hermes.core :as hermes]
[com.eldrix.pc4.rsdb.db :as db]
[com.eldrix.pc4.codelists :as codelists]
[com.eldrix.pc4.system :as pc4]
[com.eldrix.pc4.rsdb.patients :as patients]
[com.eldrix.pc4.rsdb.projects :as projects]
[com.eldrix.pc4.rsdb.results :as results]
[com.eldrix.pc4.rsdb.users :as users]
[com.wsscode.pathom3.interface.eql :as p.eql]
[honey.sql :as sql]
[next.jdbc.plan :as plan])
(:import (java.time LocalDate LocalDateTime Period)
(java.time.temporal ChronoUnit Temporal)
(java.time.format DateTimeFormatter)
(java.io PushbackReader File)
(java.nio.file Files LinkOption)
(java.nio.file.attribute FileAttribute)))
(def study-master-date
(LocalDate/of 2014 05 01))
(def study-centres
"This defines each logical centre with a list of internal 'projects' providing
a potential hook to create combined cohorts in the future should need arise."
{:cardiff {:projects ["NINFLAMMCARDIFF"] :prefix "CF"}
:cambridge {:projects ["CAMBRIDGEMS"] :prefix "CB"}
:plymouth {:projects ["PLYMOUTH"] :prefix "PL"}})
(s/def ::centre (set (keys study-centres)))
(def study-medications
"A list of interesting drugs for studies of multiple sclerosis.
They are classified as either platform DMTs or highly efficacious DMTs.
We define by the use of the SNOMED CT expression constraint language, usually
on the basis of active ingredients together with ATC codes. "
{:dmf
{:description "Dimethyl fumarate"
:atc "L04AX07"
:brand-names ["Tecfidera"]
:class :platform-dmt
:codelist {:ecl
"(<<24056811000001108|Dimethyl fumarate|) OR (<<12086301000001102|Tecfidera|) OR
(<10363601000001109|UK Product| :10362801000001104|Has specific active ingredient| =<<724035008|Dimethyl fumarate|)"
:atc "L04AX07"}}
:glatiramer
{:description "Glatiramer acetate"
:brand-names ["Copaxone" "Brabio"]
:atc "L03AX13"
:class :platform-dmt
:codelist {:ecl
"<<108754007|Glatiramer| OR <<9246601000001104|Copaxone| OR <<13083901000001102|Brabio| OR <<8261511000001102 OR <<29821211000001101
OR (<10363601000001109|UK Product|:10362801000001104|Has specific active ingredient|=<<108755008|Glatiramer acetate|)"
:atc "L03AX13"}}
:ifn-beta-1a
{:description "Interferon beta 1-a"
:brand-names ["Avonex" "Rebif"]
:atc "L03AB07 NOT L03AB13"
:class :platform-dmt
:codelist {:inclusions {:ecl
"(<<9218501000001109|Avonex| OR <<9322401000001109|Rebif| OR
(<10363601000001109|UK Product|:127489000|Has specific active ingredient|=<<386902004|Interferon beta-1a|))"
:atc "L03AB07"}
:exclusions {:ecl "<<12222201000001108|PLEGRIDY|"
:atc "L03AB13"}}}
:ifn-beta-1b
{:description "Interferon beta 1-b"
:brand-names ["Betaferon®" "Extavia®"]
:atc "L03AB08"
:class :platform-dmt
:codelist {:ecl "(<<9222901000001105|Betaferon|) OR (<<10105201000001101|Extavia|) OR
(<10363601000001109|UK Product|:127489000|Has specific active ingredient|=<<386903009|Interferon beta-1b|)"
:atc "L03AB08"}}
:peg-ifn-beta-1a
{:description "Peginterferon beta 1-a"
:brand-names ["Plegridy®"]
:atc "L03AB13"
:class :platform-dmt
:codelist {:ecl "<<12222201000001108|Plegridy|"
:atc "L03AB13"}}
:teriflunomide
{:description "Teriflunomide"
:brand-names ["Aubagio®"]
:atc "L04AA31"
:class :platform-dmt
:codelist {:ecl "<<703786007|Teriflunomide| OR <<12089801000001100|Aubagio| "
:atc "L04AA31"}}
:rituximab
{:description "Rituximab"
:brand-names ["MabThera®" "Rixathon®" "Riximyo" "Blitzima" "Ritemvia" "Rituneza" "Ruxience" "Truxima"]
:atc "L01XC02"
:class :he-dmt
:codelist {:ecl
(str/join " "
["(<<108809004|Rituximab product|)"
"OR (<10363601000001109|UK Product|:10362801000001104|Has specific active ingredient|=<<386919002|Rituximab|)"
"OR (<<9468801000001107|Mabthera|) OR (<<13058501000001107|Rixathon|)"
"OR (<<226781000001109|Ruxience|) OR (<<13033101000001108|Truxima|)"])
:atc "L01XC02"}}
:ocrelizumab
{:description "Ocrelizumab"
:brand-names ["Ocrevus"]
:atc "L04AA36"
:class :he-dmt
:codelist {:ecl "(<<35058611000001103|Ocrelizumab|) OR (<<13096001000001106|Ocrevus|)"
:atc "L04AA36"}}
:cladribine
{:description "Cladribine"
:brand-names ["Mavenclad"]
:atc "L04AA40"
:class :he-dmt
:codelist {:ecl "<<108800000|Cladribine| OR <<13083101000001100|Mavenclad|"
:atc "L04AA40"}}
:mitoxantrone
{:description "Mitoxantrone"
:brand-names ["Novantrone"]
:atc "L01DB07"
:class :he-dmt
:codelist {:ecl "<<108791001 OR <<9482901000001102"
:atc "L01DB07"}}
:fingolimod
{:description "Fingolimod"
:brand-names ["Gilenya"]
:atc "L04AA27"
:class :he-dmt
:codelist {:ecl "<<715640009 OR <<10975301000001100"
:atc "L04AA27"}}
:natalizumab
{:description "Natalizumab"
:brand-names ["Tysabri"]
:atc "L04AA23"
:class :he-dmt
:codelist {:ecl "<<414804006 OR <<9375201000001103"
:atc "L04AA23"}}
:alemtuzumab
{:description "Alemtuzumab"
:brand-names ["Lemtrada"]
:atc "L04AA34"
:class :he-dmt
:codelist {:ecl "(<<391632007|Alemtuzumab|) OR (<<12091201000001101|Lemtrada|)"
:atc "L04AA34"}}
:statin
{:description "Statins"
:class :other
:codelist {:atc "C10AA"}}
:anti-hypertensive
{:description "Anti-hypertensive"
:class :other
:codelist {:atc "C02"}}
:anti-platelet
{:description "Anti-platelets"
:class :other
:codelist {:atc "B01AC"
:ecl "<<7947003"}}
:anti-coagulant
{:description "Anticoagulants"
:class :other
:codelist {:atc ["B01AA" "B01AF" "B01AE" "B01AD" "B01AX04" "B01AX05"]}}
:proton-pump-inhibitor
{:description "Proton pump inhibitors"
:class :other
:codelist {:atc "A02BC"}}
NB : need to double check the list for LEM - PASS vs LEM - DUS and see if match
{:description "Immunosuppressants"
:class :other
:codelist {:inclusions {:atc ["L04AA" "L04AB" "L04AC" "L04AD" "L04AX"]}
:exclusions {:atc ["L04AA23" "L04AA27" "L04AA31" "L04AA34" "L04AA36" "L04AA40" "L04AX07"]}}}
:anti-retroviral
{:description "Antiretrovirals"
:class :other
:codelist {:inclusions {:atc ["J05AE" "J05AF" "J05AG" "J05AR" "J05AX"]}
:exclusions {:atc ["J05AE11" "J05AE12" "J05AE13"
"J05AF07" "J05AF08" "J05AF10"
"J05AX15" "J05AX65"]}}}
:anti-infectious
{:description "Anti-infectious medications"
:class :other
:codelist {:inclusions {:atc ["J01." "J02." "J03." "J04." "J05."]}
:exclusions {:atc ["J05A."]}}}
:antidepressant
{:description "Anti-depressants"
:class :other
:codelist {:atc "N06A"}}
:benzodiazepine
{:description "Benzodiazepines"
:class :other
:codelist {:atc ["N03AE" "N05BA"]}}
:antiepileptic
{:description "Anti-epileptics"
:class :other
:codelist {:atc "N03A"}}
:antidiabetic
{:description "Anti-diabetic"
:class :other
:codelist {:atc "A10"}}
:nutritional
{:description "Nutritional supplements and vitamins"
:class :other
:codelist {:atc ["A11" "B02B" "B03C"] :ecl "<<9552901000001103"}}})
(def flattened-study-medications
"A flattened sequence of study medications for convenience."
(reduce-kv (fn [acc k v] (conj acc (assoc v :id k))) [] study-medications))
(def study-diagnosis-categories
"These are project specific criteria for diagnostic classification."
{:multiple_sclerosis
{:description "Multiple sclerosis"
:codelist {:ecl "<<24700007"}}
:allergic_reaction
{:description "Any type of allergic reaction, including anaphylaxis"
:codelist {:ecl "<<419076005 OR <<243865006"}}
:cardiovascular
{:description "Cardiovascular disorders"
:codelist {:icd10 ["I"]}}
:cancer
{:description "Cancer, except skin cancers"
:codelist {:inclusions {:icd10 "C"} :exclusions {:icd10 "C44"}}}
:connective_tissue
{:description "Connective tissue disorders"
:codelist {:icd10 ["M45." "M33." "M35.3" "M35.0" "M32." "M34."
"M31.3" "M30.1" "L95." "D89.1" "D69.0" "M31.7" "M30.3"
"M30.0" "M31.6" "I73.0" "M31.4" "M35.2" "M94.1" "M02.3"
"M06.1" "E85.0" "D86."]}}
:endocrine
{:codelist {:icd10 ["E27.1" "E27.2" "E27.4" "E10." "E06.3" "E05.0"]}}
:gastrointestinal
{:codelist {:icd10 ["K75.4" "K90.0" "K50." "K51." "K74.3"]}}
{:codelist {:icd10 ["A" "B" "U07.1" "U07.2" "U08." "U09." "U10."]}}
:arterial_dissection
{:codelist {:icd10 ["I67.0" "I72.5"]}}
:stroke
{:codelist {:icd10 ["I6"]}}
:angina_or_myocardial_infarction
{:codelist {:icd10 ["I20" "I21" "I22" "I23" "I24" "I25"]}}
:coagulopathy
{:codelist {:icd10 ["D65" "D66" "D67" "D68" "D69" "Y44.2" "Y44.3" "Y44.4" "Y44.5"]}}
:respiratory
{:codelist {:icd10 ["J0" "J1" "J20" "J21" "J22"]}}
:hiv
{:codelist {:icd10 ["B20.", "B21.", "B22.", "B24.", "F02.4" "O98.7" "Z21", "R75"]}}
:autoimmune_disease
{:codelist {:icd10 ["M45." "M33." "M35.3" "M05." "M35.0" "M32." "M34." "M31.3" "M30.1" "L95." "D89.1" "D69.0" "M31.7" "M30.3" "M30.0"
"M31.6" "I73.0" "M31.4" "M35.2" "M94.1" "M02.3" "M06.1" "E85.0" "D86." "E27.1" "E27.2" "E27.4" "E10." "E06.3" "E05.0" "K75.4" "K90.0"
"K50." "K51." "K74.3" "L63." "L10.9" "L40." "L80." "G61.0" "D51.0" "D59.1" "D69.3" "D68." "N02.8" "M31.0" "D76.1"
"I01.2" "I40.8" "I40.9" "I09.0" "G04.0" "E31.0" "I01." "G70.0" "G73.1"]}}
:urinary_tract
{:codelist {:icd10 ["N10." "N11." "N12." "N13." "N14." "N15." "N16."]}}
:hair_and_skin
{:codelist {:icd10 ["L63." "L10.9" "L40." "L80.0"]}}
:mental_behavioural
{:codelist {:icd10 ["F"]}}
:epilepsy
{:codelist {:icd10 ["G40"]}}
:other
{:codelist {:icd10 ["G61.0" "D51.0" "D59.1" "D69.3" "D68."
"N02.8" "M31.0" "D76.1"
"M05.3" "I01.2" "I40.8" "I40.9" "I09.0" "G04.0"
"E31.0" "D69.3" "I01." "G70.0" "G73.1"]}}})
(def flattened-study-diagnoses
"A flattened sequence of study diagnoses for convenience."
(reduce-kv (fn [acc k v] (conj acc (assoc v :id k))) [] study-diagnosis-categories))
(defn ^:deprecated make-diagnostic-category-fn
"Returns a function that will test a collection of concept identifiers against the diagnostic categories specified."
[system categories]
(let [codelists (reduce-kv (fn [acc k v] (assoc acc k (codelists/make-codelist system (:codelist v))))
{}
categories)]
(fn [concept-ids]
(reduce-kv (fn [acc k v] (assoc acc k (codelists/member? v concept-ids))) {} codelists))))
(defn expand-codelists [system categories]
(update-vals categories
(fn [{codelist :codelist :as v}]
(assoc v :codes (codelists/expand (codelists/make-codelist system codelist))))))
(defn make-codelist-category-fn
"Creates a function that will return a map of category to boolean, for each
category. "
[system categories]
(let [cats' (expand-codelists system categories)]
(fn [concept-ids]
(reduce-kv (fn [acc k v] (assoc acc k (boolean (some true? (map #(contains? (:codes v) %) concept-ids))))) {} cats'))))
(comment
(def ct-disorders (codelists/make-codelist system {:icd10 ["M45." "M33." "M35.3" "M05." "M35.0" "M32.8" "M34."
"M31.3" "M30.1" "L95." "D89.1" "D69.0" "M31.7" "M30.3"
"M30.0" "M31.6" "I73." "M31.4" "M35.2" "M94.1" "M02.3"
"M06.1" "E85.0" "D86."]}))
(codelists/member? ct-disorders [9631008])
(def diag-cats (make-codelist-category-fn system study-diagnosis-categories))
(diag-cats [9631008 12295008 46635009 34000006 9014002 40956001])
(diag-cats [6204001])
(def codelists (reduce-kv (fn [acc k v] (assoc acc k (codelists/make-codelist system (:codelist v)))) {} study-diagnosis-categories))
codelists
(reduce-kv (fn [acc k v] (assoc acc k (codelists/member? v [9631008 24700007]))) {} codelists)
(map #(hash-map :title (:term %) :release-date (:effectiveTime %)) (hermes/get-release-information (:com.eldrix/hermes system)))
(def calcium-channel-blockers (codelists/make-codelist system {:atc "C08" :exclusions {:atc "C08CA01"}}))
(codelists/member? calcium-channel-blockers [108537001])
(take 2 (map #(:term (hermes/get-fully-specified-name (:com.eldrix/hermes system) %)) (codelists/expand calcium-channel-blockers)))
(codelists/expand (codelists/make-codelist system {:icd10 "G37.3"}))
(codelists/member? (codelists/make-codelist system {:icd10 "I"}) [22298006])
(count (codelists/expand (codelists/make-codelist system {:icd10 "I"})))
(get-in study-diagnosis-categories [:connective-tissue :codelist])
(def cancer (codelists/make-codelist system {:inclusions {:icd10 "C"} :exclusions {:icd10 "C44"}}))
(codelists/disjoint? (codelists/expand cancer) (codelists/expand (codelists/make-codelist system {:icd10 "C44"})))
(defn ps [id] (:term (hermes/get-preferred-synonym (:com.eldrix/hermes system) id "en-GB")))
(map ps (codelists/expand cancer))
(map #(:term (hermes/get-preferred-synonym (:com.eldrix/hermes system) % "en-GB")) (hermes/member-field-prefix (:com.eldrix/hermes system) 447562003 "mapTarget" "C44"))
(vals (hermes/source-historical-associations (:com.eldrix/hermes system) 24700007))
(hermes/get-preferred-synonym (:com.eldrix/hermes system) 445130008 "en-GB"))
(defn make-atc-regexps [{:keys [codelist] :as med}]
(when-let [atc (or (:atc codelist) (get-in codelist [:inclusions :atc]))]
(if (coll? atc)
(mapv #(vector (if (string? %) (re-pattern %) %) (dissoc med :codelist)) atc)
(vector (vector (if (string? atc) (re-pattern atc) atc) (dissoc med :codelist))))))
(def study-medication-atc
"A sequence containing ATC code regexp and study medication class information."
(mapcat make-atc-regexps flattened-study-medications))
(defn get-study-classes [atc]
(keep identity (map (fn [[re-atc med]] (when (re-matches re-atc atc) med)) study-medication-atc)))
(defmulti to-local-date class)
(defmethod to-local-date LocalDateTime [^LocalDateTime x]
(.toLocalDate x))
(defmethod to-local-date LocalDate [x] x)
(defmethod to-local-date nil [_] nil)
(comment
study-medication-atc
(first (get-study-classes "N05BA")))
(defn all-ms-dmts
"Returns a collection of multiple sclerosis disease modifying medications with
SNOMED CT (dm+d) identifiers included. For validation, checks that each
logical set of concepts is disjoint."
[{:com.eldrix/keys [hermes dmd] :as system}]
(let [result (map #(assoc % :codes (codelists/expand (codelists/make-codelist system (:codelist %)))) (remove #(= :other (:class %)) flattened-study-medications))]
(if (apply codelists/disjoint? (map :codes (remove #(= :other (:class %)) result)))
result
(throw (IllegalStateException. "DMT specifications incorrect; sets not disjoint.")))))
(defn all-dmt-identifiers
"Return a set of identifiers for all DMTs"
[system]
(set (apply concat (map :codes (all-ms-dmts system)))))
(defn all-he-dmt-identifiers
"Returns a set of identifiers for all highly-efficacious DMTs"
[system]
(set (apply concat (map :codes (filter #(= :he-dmt (:class %)) (all-ms-dmts system))))))
(defn fetch-most-recent-encounter-date-time [{conn :com.eldrix.rsdb/conn}]
(db/execute-one! conn (sql/format {:select [[:%max.date_time :most_recent_encounter_date_time]]
:from :t_encounter})))
(defn fetch-patients [{conn :com.eldrix.rsdb/conn} patient-ids]
(db/execute! conn (sql/format {:select [:patient_identifier :sex :date_birth :date_death :part1a :part1b :part1c :part2]
:from :t_patient
:left-join [:t_death_certificate [:= :patient_fk :t_patient/id]]
:where [:in :t_patient/patient_identifier patient-ids]})))
(defn addresses-for-patients
"Returns a map of patient identifiers to a collection of sorted addresses."
[{conn :com.eldrix.rsdb/conn} patient-ids]
(group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier :t_address/address1 :t_address/date_from :t_address/date_to :t_address/postcode_raw]
:from [:t_address]
:order-by [[:t_patient/patient_identifier :asc] [:date_to :desc] [:date_from :desc]]
:join [:t_patient [:= :t_patient/id :t_address/patient_fk]]
:where [:in :t_patient/patient_identifier patient-ids]}))))
(defn active-encounters-for-patients
"Returns a map of patient identifiers to a collection of sorted, active encounters.
Encounters are sorted in descending date order."
[{conn :com.eldrix.rsdb/conn} patient-ids]
(group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_encounter/id
:t_encounter/date_time]
:from [:t_encounter]
:join [:t_patient [:= :t_patient/id :t_encounter/patient_fk]]
:order-by [[:t_encounter/date_time :desc]]
:where [:and
[:in :t_patient/patient_identifier patient-ids]
[:<> :t_encounter/is_deleted "true"]]}))))
(defn ms-events-for-patients
"Returns MS events (e.g. relapses) grouped by patient identifier, sorted in descending date order."
[{conn :com.eldrix.rsdb/conn} patient-ids]
(group-by :t_patient/patient_identifier
(->> (db/execute! conn (sql/format
{:select [:t_patient/patient_identifier
:date :source :impact :abbreviation :name]
:from [:t_ms_event]
:join [:t_summary_multiple_sclerosis [:= :t_ms_event/summary_multiple_sclerosis_fk :t_summary_multiple_sclerosis/id]
:t_patient [:= :t_patient/id :t_summary_multiple_sclerosis/patient_fk]]
:left-join [:t_ms_event_type [:= :t_ms_event_type/id :t_ms_event/ms_event_type_fk]]
:order-by [[:t_ms_event/date :desc]]
:where [:in :t_patient/patient_identifier patient-ids]}))
(map #(assoc % :t_ms_event/is_relapse (patients/ms-event-is-relapse? %))))))
(defn jc-virus-for-patients [{conn :com.eldrix.rsdb/conn} patient-ids]
(->> (db/execute! conn (sql/format
{:select [:t_patient/patient_identifier
:date :jc_virus :titre]
:from [:t_result_jc_virus]
:join [:t_patient [:= :t_result_jc_virus/patient_fk :t_patient/id]]
:where [:and
[:<> :t_result_jc_virus/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}))
(map #(update % :t_result_jc_virus/date to-local-date))))
(defn mri-brains-for-patient [conn patient-identifier]
(let [results (->> (results/fetch-mri-brain-results conn nil {:t_patient/patient_identifier patient-identifier})
(map #(assoc % :t_patient/patient_identifier patient-identifier))
results/all-t2-counts
(map results/gad-count-range))
results-by-id (zipmap (map :t_result_mri_brain/id results) results)]
(map #(if-let [compare-id (:t_result_mri_brain/compare_to_result_mri_brain_fk %)]
(assoc % :t_result_mri_brain/compare_to_result_date (:t_result_mri_brain/date (get results-by-id compare-id)))
%) results)))
(defn mri-brains-for-patients [{conn :com.eldrix.rsdb/conn} patient-ids]
(->> (mapcat #(mri-brains-for-patient conn %) patient-ids)))
(defn multiple-sclerosis-onset
"Derive dates of onset based on recorded date of onset, first MS event or date
of diagnosis."
[{conn :com.eldrix.rsdb/conn hermes :com.eldrix/hermes :as system} patient-ids]
(let [ms-diagnoses (set (map :conceptId (hermes/expand-ecl-historic hermes "<<24700007")))
first-ms-events (update-vals (ms-events-for-patients system patient-ids) #(:t_ms_event/date (last %)))
pt-diagnoses (group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_diagnosis/concept_fk
:t_diagnosis/date_diagnosis
:t_diagnosis/date_onset
:t_diagnosis/date_to]
:from [:t_diagnosis]
:join [:t_patient [:= :t_diagnosis/patient_fk :t_patient/id]]
:where [:and
[:in :t_diagnosis/concept_fk ms-diagnoses]
[:in :t_diagnosis/status ["ACTIVE" "INACTIVE_RESOLVED"]]
[:in :t_patient/patient_identifier patient-ids]]})))]
(when-let [dup-diagnoses (seq (reduce-kv (fn [acc k v] (when (> (count v) 1) (assoc acc k v))) {} pt-diagnoses))]
(throw (ex-info "patients with duplicate MS diagnoses" {:duplicates dup-diagnoses})))
(update-vals pt-diagnoses (fn [diags]
(let [diag (first diags)
first-event (get first-ms-events (:t_patient/patient_identifier diag))]
(assoc diag
:has_multiple_sclerosis (boolean diag)
:date_first_event first-event
use first recorded event as onset , or date onset in diagnosis
:calculated-onset (or first-event (:t_diagnosis/date_onset diag))))))))
(defn fetch-patient-diagnoses
[{conn :com.eldrix.rsdb/conn} patient-ids]
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_diagnosis/concept_fk
:t_diagnosis/date_diagnosis
:t_diagnosis/date_onset
:t_diagnosis/date_to]
:from [:t_diagnosis]
:join [:t_patient [:= :t_diagnosis/patient_fk :t_patient/id]]
:where [:and
[:in :t_diagnosis/status ["ACTIVE" "INACTIVE_RESOLVED"]]
[:in :t_patient/patient_identifier patient-ids]]})))
(defn fetch-patient-admissions
[{conn :com.eldrix.rsdb/conn} project-name patient-ids]
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier :t_episode/date_registration :t_episode/date_discharge]
:from [:t_episode]
:join [:t_patient [:= :t_episode/patient_fk :t_patient/id]
:t_project [:= :t_episode/project_fk :t_project/id]]
:where [:and
[:= :t_project/name project-name]
[:in :t_patient/patient_identifier patient-ids]]})))
(defn fetch-smoking-status
[{conn :com.eldrix.rsdb/conn} patient-ids]
(-> (group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_smoking_history/status]
:from [:t_smoking_history]
:join [:t_encounter [:= :t_encounter/id :t_smoking_history/encounter_fk]
:t_patient [:= :t_patient/id :t_encounter/patient_fk]]
:order-by [[:t_encounter/date_time :desc]]
:where [:and
[:<> :t_smoking_history/is_deleted "true"]
[:<> :t_encounter/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]})))
(update-vals first)))
(defn fetch-weight-height
[{conn :com.eldrix.rsdb/conn} patient-ids]
(let [results (-> (group-by :t_patient/patient_identifier
(db/execute! conn (sql/format {:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_form_weight_height/weight_kilogram
:t_form_weight_height/height_metres]
:from [:t_form_weight_height]
:join [:t_encounter [:= :t_encounter/id :t_form_weight_height/encounter_fk]
:t_patient [:= :t_patient/id :t_encounter/patient_fk]]
:order-by [[:t_encounter/date_time :desc]]
:where [:and
[:<> :t_form_weight_height/is_deleted "true"]
[:<> :t_encounter/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}))))]
(update-vals results (fn [forms]
(let [default-ht (first (map :t_form_weight_height/height_metres forms))]
(map #(let [wt (:t_form_weight_height/weight_kilogram %)
ht (or (:t_form_weight_height/height_metres %) default-ht)]
(if (and wt ht) (assoc % :body_mass_index (with-precision 2 (/ wt (* ht ht))))
%)) forms))))))
(defn fetch-form-ms-relapse
"Get a longitudinal record of MS disease activity, results keyed by patient identifier."
[{conn :com.eldrix.rsdb/conn} patient-ids]
(group-by :t_patient/patient_identifier
(db/execute! conn (sql/format
{:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_form_ms_relapse/in_relapse
:t_ms_disease_course/name
:t_form_ms_relapse/activity
:t_form_ms_relapse/progression]
:from [:t_form_ms_relapse]
:join [:t_encounter [:= :t_encounter/id :t_form_ms_relapse/encounter_fk]
:t_patient [:= :t_encounter/patient_fk :t_patient/id]]
:left-join [:t_ms_disease_course [:= :t_ms_disease_course/id :t_form_ms_relapse/ms_disease_course_fk]]
:where [:and
[:<> :t_encounter/is_deleted "true"]
[:<> :t_form_ms_relapse/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}))))
(def convert-edss-score
{"SCORE10_0" 10.0
"SCORE6_5" 6.5
"SCORE1_0" 1.0
"SCORE2_5" 2.5
"SCORE5_5" 5.5
"SCORE9_0" 9.0
"SCORE7_0" 7.0
"SCORE3_0" 3.0
"SCORE5_0" 5.0
"SCORE4_5" 4.5
"SCORE8_5" 8.5
"SCORE7_5" 7.5
"SCORE8_0" 8.0
"SCORE1_5" 1.5
"SCORE6_0" 6.0
"SCORE3_5" 3.5
"SCORE0_0" 0.0
"SCORE4_0" 4.0
"SCORE2_0" 2.0
"SCORE9_5" 9.5
"SCORE_LESS_THAN_4" "<4"})
(defn get-most-recent
"Given a date 'date', find the preceding map in the collection 'coll' within the limit, default 12 weeks."
([coll date-fn ^LocalDate date]
(get-most-recent coll date-fn date (Period/ofWeeks 12)))
([coll date-fn ^LocalDate date ^Period max-period]
(->> coll
(remove #(.isBefore (to-local-date (date-fn %)) (.minus date max-period)))
(sort-by date-fn)
reverse
first)))
(def simplify-ms-disease-course
{"Secondary progressive with relapses" "SPMS"
"Unknown" "UK"
"Primary progressive" "PPMS"
"Secondary progressive" "SPMS"
"Primary progressive with relapses" "PPMS"
"Clinically isolated syndrome" "CIS"
"Relapsing with sequelae" "RRMS"
"Relapsing remitting" "RRMS"})
(defn edss-scores
"EDSS scores for the patients specified, grouped by patient identifier and ordered by date ascending."
[{conn :com.eldrix.rsdb/conn :as system} patient-ids]
(let [form-relapses (fetch-form-ms-relapse system patient-ids)]
(->> (db/execute! conn (sql/format {:union-all
[{:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_form_edss/edss_score
:t_encounter/id]
:from [:t_encounter]
:join [:t_patient [:= :t_patient/id :t_encounter/patient_fk]
:t_form_edss [:= :t_form_edss/encounter_fk :t_encounter/id]]
:where [:and
[:<> :t_form_edss/edss_score nil]
[:<> :t_encounter/is_deleted "true"]
[:<> :t_form_edss/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}
{:select [:t_patient/patient_identifier
:t_encounter/date_time
:t_form_edss_fs/edss_score
:t_encounter/id]
:from [:t_encounter]
:join [:t_patient [:= :t_patient/id :t_encounter/patient_fk]
:t_form_edss_fs [:= :t_form_edss_fs/encounter_fk :t_encounter/id]]
:where [:and
[:<> :t_form_edss_fs/edss_score nil]
[:<> :t_encounter/is_deleted "true"]
[:<> :t_form_edss_fs/is_deleted "true"]
[:in :t_patient/patient_identifier patient-ids]]}]}))
(map #(update-keys % {:patient_identifier :t_patient/patient_identifier
:date_time :t_encounter/date_time
:edss_score :t_form_edss/edss_score
:id :t_encounter/id}))
(map #(if-let [form-relapse (get-most-recent (get form-relapses (:t_patient/patient_identifier %)) :t_encounter/date_time (to-local-date (:t_encounter/date_time %)) (Period/ofWeeks 12))]
(merge form-relapse % {:t_form_ms_relapse/date_status_recorded (to-local-date (:t_encounter/date_time form-relapse))})
(map #(assoc % :t_form_edss/edss_score (convert-edss-score (:t_form_edss/edss_score %))
:t_ms_disease_course/type (simplify-ms-disease-course (:t_ms_disease_course/name %))
:t_encounter/date (to-local-date (:t_encounter/date_time %))))
(group-by :t_patient/patient_identifier)
(reduce-kv (fn [acc k v] (assoc acc k (sort-by :t_encounter/date_time v))) {}))))
(defn date-at-edss-4
"Given an ordered sequence of EDSS scores, identify the first that is 4 or
above and not in relapse."
[edss]
(->> edss
(remove :t_form_ms_relapse/in_relapse)
(filter #(number? (:t_form_edss/edss_score %)))
(filter #(>= (:t_form_edss/edss_score %) 4))
first
:t_encounter/date_time))
(defn relapses-between-dates
"Filter the event list for a patient to only include relapse-type events between the two dates specified, inclusive."
[events ^LocalDate from-date ^LocalDate to-date]
(->> events
(filter :t_ms_event/is_relapse)
(filter #(let [date (:t_ms_event/date %)]
(and (or (.isEqual date from-date) (.isAfter date from-date))
(or (.isEqual date to-date) (.isBefore date to-date)))))))
(comment
(get (ms-events-for-patients system [5506]) 5506)
(def d1 (LocalDate/of 2014 1 1))
(relapses-between-dates (get (ms-events-for-patients system [5506]) 5506) (.minusMonths d1 24) d1))
(defn lsoa-for-postcode [{:com.eldrix/keys [clods]} postcode]
(get (com.eldrix.clods.core/fetch-postcode clods postcode) "LSOA11"))
(defn deprivation-decile-for-lsoa [{:com.eldrix/keys [deprivare]} lsoa]
(:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile (deprivare/fetch-lsoa deprivare lsoa)))
(def fetch-max-depriv-rank (memoize deprivare/fetch-max))
(defn deprivation-quartile-for-lsoa [{:com.eldrix/keys [deprivare]} lsoa]
(when-let [data (deprivare/fetch-lsoa deprivare lsoa)]
(let [rank (:uk-composite-imd-2020-mysoc/UK_IMD_E_rank data)
max-rank (fetch-max-depriv-rank deprivare :uk-composite-imd-2020-mysoc/UK_IMD_E_rank)
x (/ rank max-rank)]
(cond
(>= x 3/4) 4
(>= x 2/4) 3
(>= x 1/4) 2
:else 1))))
(defn deprivation-quartile-for-address
"Given an address, determine a deprivation quartile.
We use postal code when possible, but fallback to looking for a stored LSOA
in the 'address1' field if available."
[system {:t_address/keys [address1 postcode_raw]}]
(cond
(not (str/blank? postcode_raw))
(deprivation-quartile-for-lsoa system (lsoa-for-postcode system postcode_raw))
(and (not (str/blank? address1)) (re-matches #"^[E|W]\d*" address1))
(deprivation-quartile-for-lsoa system address1)
:else nil))
(defn deprivation-quartiles-for-patients
"Determine deprivation quartile for the patients specified.
Deprivation indices are calculated based on address history, on the date
specified, or today.
Parameters:
- system : a pc4 'system' containing clods, deprivare and rsdb modules.
- patient-ids : a sequence of patient identifiers for the cohort in question
- on-date : a date to use for all patients, or a map, or function, to
return a date for each patient-id.
If 'on-date' is provided but no date is returned for a given patient-id, no
decile will be returned by design.
Examples:
(deprivation-quartiles-for-patients system [17497 22776] (LocalDate/of 2010 1 1)
(deprivation-quartiles-for-patients system [17497 22776] {17497 (LocalDate/of 2004 1 1)}"
([system patient-ids] (deprivation-quartiles-for-patients system patient-ids (LocalDate/now)))
([system patient-ids on-date]
(let [date-fn (if (ifn? on-date) on-date (constantly on-date))]
(update-vals (addresses-for-patients system patient-ids)
#(->> (when-let [date (date-fn (:t_patient/patient_identifier (first %)))]
(deprivation-quartile-for-address system))))))
(defn all-recorded-medications [{conn :com.eldrix.rsdb/conn}]
(into #{} (map :t_medication/medication_concept_fk)
(next.jdbc/plan conn
(sql/format {:select-distinct :t_medication/medication_concept_fk
:from :t_medication}))))
(defn convert-product-pack
"Convert a medication that is a type of product pack to the corresponding VMP."
[{:com.eldrix/keys [dmd hermes]} {concept-id :t_medication/medication_concept_fk :as medication}]
(if (or (hermes/subsumed-by? hermes concept-id 8653601000001108)
(hermes/subsumed-by? hermes concept-id 10364001000001104))
(if-let [vmp (first (hermes/get-parent-relationships-of-type hermes concept-id 10362601000001103))]
(assoc medication :t_medication/medication_concept_fk vmp :t_medication/converted_from_pp concept-id)
(if-let [amp (first (hermes/get-parent-relationships-of-type hermes concept-id 10362701000001108))]
(assoc medication :t_medication/medication_concept_fk amp :t_medication/converted_from_pp concept-id)
(throw (ex-info "unable to convert product pack" medication))))
medication))
(defn medications-for-patients [{conn :com.eldrix.rsdb/conn :as system} patient-ids]
(->> (db/execute! conn
(sql/format {:select [:t_patient/patient_identifier
:t_medication/id
:t_medication/medication_concept_fk :t_medication/date_from :t_medication/date_to
:t_medication/reason_for_stopping]
:from [:t_medication :t_patient]
:where [:and
[:= :t_medication/patient_fk :t_patient/id]
[:in :t_patient/patient_identifier patient-ids]
[:<> :t_medication/reason_for_stopping "RECORDED_IN_ERROR"]]}))
(sort-by (juxt :t_patient/patient_identifier :t_medication/date_from))
(map #(convert-product-pack system %))))
(defn make-dmt-lookup [system]
(apply merge (map (fn [dmt] (zipmap (:codes dmt) (repeat {:dmt_class (:class dmt) :dmt (:id dmt) :atc (:atc dmt)}))) (all-ms-dmts system))))
(defn infer-atc-for-non-dmd
"Try to reach a dmd product from a non-dmd product to infer an ATC code.
TODO: improve"
[{:com.eldrix/keys [hermes dmd]} concept-id]
(or (first (keep identity (map #(dmd/atc-for-product dmd %) (hermes/get-child-relationships-of-type hermes concept-id 116680003))))
(first (keep identity (map #(dmd/atc-for-product dmd %) (hermes/get-parent-relationships-of-type hermes concept-id 116680003))))))
(defn fetch-drug
"Return basic information about a drug.
Most products are in the UK dm+d, but not all, so we supplement with data
from SNOMED when possible."
[{:com.eldrix/keys [hermes dmd] :as system} concept-id]
(if-let [product (dmd/fetch-product dmd concept-id)]
(let [atc (or (com.eldrix.dmd.store2/atc-code dmd product)
(infer-atc-for-non-dmd system concept-id))]
(cond-> {:nm (or (:VTM/NM product) (:VMP/NM product) (:AMP/NM product) (:VMPP/NM product) (:AMPP/NM product))}
atc (assoc :atc atc)))
(let [atc (infer-atc-for-non-dmd system concept-id)
term (:term (hermes/get-preferred-synonym hermes concept-id "en-GB"))]
(cond-> {:nm term}
atc (assoc :atc atc)))))
(defn first-he-dmt-after-date
"Given a list of medications for a single patient, return the first
highly-effective medication given after the date specified."
[medications ^LocalDate date]
(->> medications
(filter #(= :he-dmt (:dmt_class %)))
(filter #(or (nil? (:t_medication/date_from %)) (.isAfter (:t_medication/date_from %) date)))
(sort-by :t_medication/date_from)
first))
(defn count-dmts-before
"Returns counts of the specified DMT, or class of DMT, or any DMT, used before the date specified."
([medications ^LocalDate date] (count-dmts-before medications date nil nil))
([medications ^LocalDate date dmt-class] (count-dmts-before medications date dmt-class nil))
([medications ^LocalDate date dmt-class dmt]
(when date
(let [prior-meds (filter #(or (nil? (:t_medication/date_from %)) (.isBefore (:t_medication/date_from %) date)) medications)]
(if-not dmt-class
(if-not dmt
(defn days-between
"Return number of days between dates, or nil, or when-invalid if one date nil."
([^Temporal d1 ^Temporal d2] (days-between d1 d2 nil))
([^Temporal d1 ^Temporal d2 when-invalid]
(if (and d1 d2)
(.between ChronoUnit/DAYS d1 d2)
when-invalid)))
(defn count-dmts [medications]
(->> medications
(keep-indexed (fn [i medication] (cond-> (assoc medication :switch? false)
(> i 0) (assoc :switch? true :switch_from (:dmt (nth medications (dec i)))))))
(map #(assoc %
:exposure_days (days-between (:t_medication/date_from %) (:t_medication/date_to %))
:n_prior_dmts (count-dmts-before medications (:t_medication/date_from %))
:n_prior_platform_dmts (count-dmts-before medications (:t_medication/date_from %) :platform-dmt)
:n_prior_he_dmts (count-dmts-before medications (:t_medication/date_from %) :he-dmt)
:first_use (= 0 (count-dmts-before medications (:t_medication/date_from %) (:dmt_class %) (:dmt %)))))))
(defn patient-raw-dmt-medications
[{conn :com.eldrix.rsdb/conn :as system} patient-ids]
(let [dmt-lookup (make-dmt-lookup system)]
(->> (medications-for-patients system patient-ids)
(map #(merge % (get dmt-lookup (:t_medication/medication_concept_fk %))))
(filter :dmt)
(group-by :t_patient/patient_identifier))))
(defn patient-dmt-sequential-regimens
"Returns DMT medications grouped by patient, organised by *regimen*.
For simplicity, the regimen is defined as a sequential group of treatments
of the same DMT. This does not work for overlapping regimens, which would need
to be grouped by a unique, and likely manually curated unique identifier
for the regimen. It also does not take into account gaps within the treatment
course. If a patient is listed as having nataluzimab on one date, and another
dose on another date, this will show the date from and to as those two dates.
If the medication date-to is nil, then the last active contact of the patient
is used."
[{conn :com.eldrix.rsdb/conn :as system} patient-ids]
(let [active-encounters (active-encounters-for-patients system patient-ids)
last-contact-dates (update-vals active-encounters #(:t_encounter/date_time (first %)))]
(update-vals
(patient-raw-dmt-medications system patient-ids)
(fn [v]
(->> v
we then simply look at the first , and the last in that group .
end (last %)
date-to (or (:t_medication/date_to end) (to-local-date (get last-contact-dates (:t_patient/patient_identifier (first %)))))]
(if date-to
return a single entry with start date from the first and end date from the last
start)))
count-dmts)))))
(defn cohort-entry-meds
"Return a map of patient id to cohort entry medication.
This is defined as date of first prescription of a HE-DMT after the
defined study date.
This is for the LEM-PASS study. Cohort entry date defined differently for DUS."
[system patient-ids study-date]
(->> (patient-dmt-sequential-regimens system patient-ids)
vals
(map (fn [medications] (first-he-dmt-after-date medications study-date)))
(keep identity)
(map #(vector (:t_patient/patient_identifier %) %))
(into {})))
(defn alemtuzumab-medications
"Returns alemtuzumab medication records for the patients specified.
Returns a map keyed by patient identifier, with a collection of ordered
medications."
[system patient-ids]
(-> (patient-raw-dmt-medications system patient-ids)
(update-vals (fn [meds] (seq (filter #(= (:dmt %) :alemtuzumab) meds))))))
(defn valid-alemtuzumab-record?
"Is this a valid alemtuzumab record?
A record must never more than 5 days between the 'from' date and the 'to' date."
[med]
(let [from (:t_medication/date_from med)
to (:t_medication/date_to med)]
(and from to (> 5 (.between ChronoUnit/DAYS from to)))))
(defn make-daily-infusions [med]
(let [from (:t_medication/date_from med)
to (:t_medication/date_to med)]
(if (valid-alemtuzumab-record? med)
(let [days (.between ChronoUnit/DAYS from to)
dates (map #(.plusDays from %) (range 0 (inc days)))]
(map #(-> med
(assoc :t_medication/date % :valid true)
(dissoc :t_medication/date_from :t_medication/date_to :t_medication/reason_for_stopping)) dates))
(-> med
(assoc :valid false :t_medication/date from)
(dissoc :t_medication/date_from :t_medication/date_to :t_medication/reason_for_stopping)))))
(defn alemtuzumab-infusions
"Returns a map keyed by patient identifier of all infusions of alemtuzumab."
[system patient-ids]
(->> (alemtuzumab-medications system patient-ids)
vals
(remove nil?)
flatten
(map make-daily-infusions)
flatten
(group-by :t_patient/patient_identifier)))
(defn course-and-infusion-rank
"Given a sequence of infusions, generate a 'course-rank' and 'infusion-rank'.
We do this by generating a sequence of tuples that slide over the infusions.
Each tuple contains two items: the prior item and the item.
Returns the sequence of infusions, but with :course-rank and :infusion-rank
properties."
[infusions]
(loop [partitions (partition 2 1 (concat [nil] infusions))
course-rank 1
infusion-rank 1
results []]
(let [[prior item] (vec (first partitions))]
(if-not item
results
(let [new-course? (and (:t_medication/date prior) (:t_medication/date item) (> (.between ChronoUnit/DAYS (:t_medication/date prior) (:t_medication/date item)) 15))
course-rank (if new-course? (inc course-rank) course-rank)
infusion-rank (if new-course? 1 infusion-rank)
item' (assoc item :course-rank course-rank :infusion-rank infusion-rank)]
(recur (rest partitions) course-rank (inc infusion-rank) (conj results item')))))))
(defn ranked-alemtuzumab-infusions
"Returns a map keyed by patient-id of alemtuzumab infusions, with course
and infusion rank included."
[system patient-ids]
(-> (alemtuzumab-infusions system patient-ids)
(update-vals course-and-infusion-rank)))
(defn all-patient-diagnoses [system patient-ids]
(let [diag-fn (make-codelist-category-fn system study-diagnosis-categories)]
(->> (fetch-patient-diagnoses system patient-ids)
(map #(assoc % :icd10 (first (codelists/to-icd10 system [(:t_diagnosis/concept_fk %)]))))
(map #(merge % (diag-fn [(:t_diagnosis/concept_fk %)])))
(map #(assoc % :term (:term (hermes/get-preferred-synonym (:com.eldrix/hermes system) (:t_diagnosis/concept_fk %) "en-GB")))))))
(defn merge-diagnostic-categories
[diagnoses]
(let [categories (keys study-diagnosis-categories)
diagnoses' (map #(select-keys % categories) diagnoses)
all-false (zipmap (keys study-diagnosis-categories) (repeat false))]
(apply merge-with #(or %1 %2) (conj diagnoses' all-false))))
(defn fetch-non-dmt-medications [system patient-ids]
(let [drug-fn (make-codelist-category-fn system study-medications)
all-dmts (all-dmt-identifiers system)
fetch-drug' (memoize fetch-drug)]
(->> (medications-for-patients system patient-ids)
(remove #(all-dmts (:t_medication/medication_concept_fk %)))
(map #(merge %
(fetch-drug' system (:t_medication/medication_concept_fk %))
(drug-fn [(:t_medication/medication_concept_fk %)]))))))
(s/fdef write-table
:args (s/cat :system any?
:table (s/keys :req-un [::filename ::data-fn] :opt-un [::columns ::title-fn])
:centre ::centre
:patient-ids (s/coll-of pos-int?)))
(defn write-table
"Write out a data export table. Parameters:
- system
- table - a map defining the table, to include:
- :filename - filename to use
- :data-fn - function to create data
- :title-fn - a function, or map, to convert each column key for output.
- optional, default `name`.
- centre - keyword representing centre
- patient-ids - a sequence of patient identifiers
Injects special properties into each row:
- ::patient-id : a centre prefixed patient identifier
- ::centre : the centre set during export."
[system {:keys [filename data-fn columns title-fn]} centre patient-ids]
(let [make-pt-id #(str (get-in study-centres [centre :prefix]) (format "%06d" %))
rows (->> (data-fn system patient-ids)
(map #(assoc % ::centre (name centre)
::patient-id (make-pt-id (:t_patient/patient_identifier %)))))
columns' (or columns (keys (first rows)))
headers (mapv #(name (or (title-fn' %) %)) columns')]
(with-open [writer (io/writer filename)]
(csv/write-csv writer (into [headers] (map (fn [row] (mapv (fn [col] (col row)) columns')) rows))))))
(defn fetch-project-patient-identifiers
"Returns patient identifiers for those registered to one of the projects
specified. Discharged patients are *not* included."
[{conn :com.eldrix.rsdb/conn} project-names]
(let [project-ids (set (map #(:t_project/id (projects/project-with-name conn %)) project-names))
child-project-ids (set (mapcat #(projects/all-children-ids conn %) project-ids))
all-project-ids (set/union project-ids child-project-ids)]
(patients/patient-ids-in-projects conn all-project-ids)))
(s/fdef fetch-study-patient-identifiers
:args (s/cat :system any? :centre ::centre))
(defn fetch-study-patient-identifiers
"Returns a collection of patient identifiers for the DMT study."
[system centre]
(let [all-dmts (all-he-dmt-identifiers system)]
(->> (fetch-project-patient-identifiers system (get-in study-centres [centre :projects]))
(medications-for-patients system)
#_(filter #(all-dmts (:t_medication/medication_concept_fk %)))
(map :t_patient/patient_identifier)
set)))
(defn patients-with-more-than-one-death-certificate
[{conn :com.eldrix.rsdb/conn}]
(when-let [patient-fks (seq (plan/select! conn :patient_fk (sql/format {:select [:patient_fk]
:from [:t_death_certificate]
:group-by [:patient_fk]
:having [:> :%count.patient_fk 1]})))]
(patients/pks->identifiers conn patient-fks)))
(defn dmts-recorded-as-product-packs
"Return a sequence of medications in which a DMT has been recorded as a
product pack, rather than VTM, VMP or AMP. "
[system patient-ids]
(let [all-dmts (all-he-dmt-identifiers system)
all-meds (medications-for-patients system patient-ids)]
(->> all-meds
(filter :t_medication/converted_from_pp)
(filter #(all-dmts (:t_medication/medication_concept_fk %))))))
(defn patients-with-local-demographics [system patient-ids]
(map :patient_identifier (next.jdbc.plan/select! (:com.eldrix.rsdb/conn system) [:patient_identifier]
(sql/format {:select :patient_identifier
:from :t_patient
:where [:and
[:in :patient_identifier patient-ids]
[:= :authoritative_demographics "LOCAL"]]}))))
(defn make-metadata [system]
(let [deps (edn/read (PushbackReader. (io/reader "deps.edn")))]
{:data (fetch-most-recent-encounter-date-time system)
:pc4 {:url ""
:sha (str/trim (:out (clojure.java.shell/sh "/bin/sh" "-c" "git rev-parse HEAD")))}
:hermes {:url ""
:version (get-in deps [:deps 'com.eldrix/hermes :mvn/version])
:data (map #(hash-map :title (:term %) :date (:effectiveTime %)) (hermes/get-release-information (:com.eldrix/hermes system)))}
:dmd {:url ""
:version (get-in deps [:deps 'com.eldrix/dmd :mvn/version])
:data {:title "UK Dictionary of Medicines and Devices (dm+d)"
:date (com.eldrix.dmd.core/fetch-release-date (:com.eldrix/dmd system))}}
:codelists {:study-medications study-medications
:study-diagnoses study-diagnosis-categories}}))
(defn make-problem-report [system patient-ids]
{
generate a list of patients with more than one death certificate
:more-than-one-death-certificate
(or (patients-with-more-than-one-death-certificate system) [])
:patients-with-dmts-as-product-packs
{:description "This is a list of patients who have their DMT recorded as an AMPP or VMPP, rather
than as a VTM,AMP or VMP. This is simply for internal centre usage, as it does not impact data."
:patients (map :t_patient/patient_identifier (dmts-recorded-as-product-packs system patient-ids))}
:patients-without-ms-diagnosis
(let [with-ms (set (map :t_patient/patient_identifier (filter :has_multiple_sclerosis (vals (multiple-sclerosis-onset system patient-ids)))))]
(set/difference patient-ids with-ms))
:incorrect-alemtuzumab-course-dates
(->> (alemtuzumab-medications system patient-ids)
vals
(remove nil?)
flatten
(remove valid-alemtuzumab-record?))
patients not linked to NHS demographics
:not-linked-nhs-demographics (let [local-patient-ids (patients-with-local-demographics system patient-ids)]
{:description "This is a list of patients who are not linked to NHS Wales' systems for status updates.
This should be 0% for the Cardiff group, and 100% for other centres."
:score (str (math/round (* 100 (/ (count local-patient-ids) (count patient-ids)))) "%")
:patient-ids local-patient-ids})})
(defn update-all
"Applies function 'f' to the values of the keys 'ks' in the map 'm'."
[m ks f]
(reduce (fn [v k] (update v k f)) m ks))
(defn make-patients-table
[system patient-ids]
(let [onsets (multiple-sclerosis-onset system patient-ids)
cohort-entry-meds (cohort-entry-meds system patient-ids study-master-date)
cohort-entry-dates (update-vals cohort-entry-meds :t_medication/date_from)
deprivation (deprivation-quartiles-for-patients system patient-ids cohort-entry-dates)
active-encounters (active-encounters-for-patients system patient-ids)
earliest-contacts (update-vals active-encounters #(:t_encounter/date_time (last %)))
latest-contacts (update-vals active-encounters #(:t_encounter/date_time (first %)))
edss (edss-scores system patient-ids)
smoking (fetch-smoking-status system patient-ids)
ms-events (ms-events-for-patients system patient-ids)]
(->> (fetch-patients system patient-ids)
(map #(let [patient-id (:t_patient/patient_identifier %)
cohort-entry-med (get cohort-entry-meds patient-id)
onsets (get onsets patient-id)
onset-date (:calculated-onset onsets)
has-multiple-sclerosis (boolean (:has_multiple_sclerosis onsets))
date-death (when-let [d (:t_patient/date_death %)] (.withDayOfMonth d 15))]
(-> (merge % cohort-entry-med)
(update :t_patient/sex (fnil name ""))
(update :dmt (fnil name ""))
(update :dmt_class (fnil name ""))
(assoc :depriv_quartile (get deprivation patient-id)
:start_follow_up (to-local-date (get earliest-contacts patient-id))
:year_birth (when (:t_patient/date_birth %) (.getYear (:t_patient/date_birth %)))
:date_death date-death
:onset onset-date
:has_multiple_sclerosis has-multiple-sclerosis
:smoking (get-in smoking [patient-id :t_smoking_history/status])
:disease_duration_years (when (and (:t_medication/date_from cohort-entry-med) onset-date)
(.getYears (Period/between ^LocalDate onset-date ^LocalDate (:t_medication/date_from cohort-entry-med))))
calculate most recent non - relapsing EDSS at cohort entry date
(:t_form_edss/edss_score (get-most-recent (remove :t_form_ms_relapse/in_relapse (get edss patient-id)) :t_encounter/date (:t_medication/date_from cohort-entry-med))))
:date_edss_4 (when (:t_medication/date_from cohort-entry-med)
(to-local-date (date-at-edss-4 (get edss patient-id))))
:nc_time_edss_4 (when (:t_medication/date_from cohort-entry-med)
(when-let [date (to-local-date (date-at-edss-4 (get edss patient-id)))]
(when onset-date
(.between ChronoUnit/DAYS onset-date date))))
:nc_relapses (when (:t_medication/date_from cohort-entry-med)
(count (relapses-between-dates (get ms-events patient-id) (.minusYears (:t_medication/date_from cohort-entry-med) 1) (:t_medication/date_from cohort-entry-med))))
:end_follow_up (or date-death (to-local-date (get latest-contacts patient-id))))
(dissoc :t_patient/date_birth)))))))
(def patients-table
{:filename "patients.csv"
:data-fn make-patients-table
:columns [::patient-id
::centre
:t_patient/sex :year_birth :date_death
:depriv_quartile :start_follow_up :end_follow_up
:t_death_certificate/part1a :t_death_certificate/part1b :t_death_certificate/part1c :t_death_certificate/part2
:atc :dmt :dmt_class :t_medication/date_from
:exposure_days
:smoking
:most_recent_edss
:has_multiple_sclerosis
:onset
:date_edss_4
:nc_time_edss_4
:disease_duration_years
:nc_relapses
:n_prior_he_dmts :n_prior_platform_dmts
:first_use :switch?]
:title-fn {:t_medication/date_from "cohort_entry_date"
:switch? "switch"}})
(defn make-patient-identifiers-table [system patient-ids]
(db/execute! (:com.eldrix.rsdb/conn system)
(sql/format {:select [:patient_identifier :stored_pseudonym :t_project/name] :from [:t_episode :t_patient :t_project]
:where [:and [:= :patient_fk :t_patient/id]
[:= :project_fk :t_project/id]
[:in :t_patient/patient_identifier patient-ids]]
:order-by [[:t_patient/id :asc]]})))
(def patient-identifiers-table
{:filename "patient-identifiers.csv"
:data-fn make-patient-identifiers-table
:columns [::patient-id
:t_project/name
:t_episode/stored_pseudonym]})
(defn make-raw-dmt-medications-table
[system patient-ids]
(->> (patient-raw-dmt-medications system patient-ids)
vals
(mapcat identity)
(map #(update-all % [:dmt :dmt_class :t_medication/reason_for_stopping] name))))
(def raw-dmt-medications-table
{:filename "patient-raw-dmt-medications.csv"
:data-fn make-raw-dmt-medications-table
:columns [::patient-id
:t_medication/medication_concept_fk
:atc :dmt :dmt_class
:t_medication/date_from :t_medication/date_to
:t_medication/reason_for_stopping]})
(defn make-dmt-regimens-table
[system patient-ids]
(->> (patient-dmt-sequential-regimens system patient-ids)
vals
(mapcat identity)
(map #(update-all % [:dmt :dmt_class :switch_from :t_medication/reason_for_stopping] (fnil name "")))))
(def dmt-regimens-table
{:filename "patient-dmt-regimens.csv"
:data-fn make-dmt-regimens-table
:columns [::patient-id
:t_medication/medication_concept_fk
:atc :dmt :dmt-class
:t_medication/date_from :t_medication/date_to :exposure_days
:switch_from :n_prior_platform_dmts :n_prior_he_dmts]
:title-fn {:dmt-class "dmt_class"}})
(defn dates-of-anaphylaxis-reactions
"Creates a map containing anaphylaxis diagnoses, keyed by a vector of
patient identifier and date. This is derived from a diagnosis of anaphylaxis
in the problem list.
TODO: Use the t_medication_event table to impute life-threatening events from
the historic record."
[system patient-ids]
(let [anaphylaxis-diagnoses (set (map :conceptId (hermes/expand-ecl-historic (:com.eldrix/hermes system) "<<39579001")))
pt-diagnoses (->> (fetch-patient-diagnoses system patient-ids)
(filter #(anaphylaxis-diagnoses (:t_diagnosis/concept_fk %))))]
(zipmap (map #(vector (:t_patient/patient_identifier %)
(:t_diagnosis/date_onset %)) pt-diagnoses)
pt-diagnoses)))
(defn make-alemtuzumab-infusions
"Create ordered sequence of individual infusions. Each item will include
properties with date, drug, course-rank, infusion-rank and whether that
infusion coincided with an allergic reaction."
[system patient-ids]
(let [anaphylaxis-reactions (dates-of-anaphylaxis-reactions system patient-ids)]
(->> patient-ids
(ranked-alemtuzumab-infusions system)
vals
flatten
(map #(update-all % [:dmt :dmt_class] name))
(map #(assoc % :anaphylaxis (boolean (get anaphylaxis-reactions [(:t_patient/patient_identifier %) (:t_medication/date %)]))))
(sort-by (juxt :t_patient/patient_identifier :course-rank :infusion-rank)))))
(def alemtuzumab-infusions-table
{:filename "alemtuzumab-infusions.csv"
:data-fn make-alemtuzumab-infusions
:columns [::patient-id
:dmt
:t_medication/medication_concept_fk
:atc
:t_medication/date
:valid
:course-rank
:infusion-rank
:anaphylaxis]
:title-fn {:course-rank "course_rank"
:infusion-rank "infusion_rank"}})
(defn date-in-range-inclusive?
[^LocalDate date-from ^LocalDate date-to ^LocalDate date]
(when (and date-from date-to date)
(or (.isEqual date date-from)
(.isEqual date date-to)
(and (.isAfter date date-from) (.isBefore date date-to)))))
(defn make-admissions-table
[system patient-ids]
(let [diagnoses (group-by :t_patient/patient_identifier (all-patient-diagnoses system patient-ids))
(->> (get diagnoses patient-id)
(filter #(date-in-range-inclusive? date-from date-to (or (:t_diagnosis/date_diagnosis %) (:t_diagnosis/date_onset %))))))]
(->> (fetch-patient-admissions system "ADMISSION" patient-ids)
(map (fn [{patient-id :t_patient/patient_identifier
:t_episode/keys [date_registration date_discharge] :as admission}]
(-> admission
(assoc :t_episode/duration_days
(when (and date_registration date_discharge)
(.between ChronoUnit/DAYS date_registration date_discharge)))
(merge (merge-diagnostic-categories (get-diagnoses patient-id date_registration date_discharge)))))))))
(comment
(fetch-patient-admissions system "ADMISSION" [17490])
(group-by :t_patient/patient_identifier (all-patient-diagnoses system [17490]))
(time (make-admissions-table system [17490])))
(def admissions-table
{:filename "patient-admissions.csv"
:data-fn make-admissions-table
:columns (into [::patient-id
:t_episode/date_registration
:t_episode/date_discharge
:t_episode/duration_days]
(keys study-diagnosis-categories))
:title-fn {:t_episode/date_registration "date_from"
:t_episode/date_discharge "date_to"
:t_episode/duration_days "duration_days"}})
(defn make-non-dmt-medications
[system patient-ids]
(fetch-non-dmt-medications system patient-ids))
(def non-dmt-medications-table
{:filename "patient-non-dmt-medications.csv"
:data-fn make-non-dmt-medications
:columns [::patient-id :t_medication/medication_concept_fk
:t_medication/date_from :t_medication/date_to :nm :atc
:anti-hypertensive :antidepressant :anti-retroviral :statin :anti-platelet :immunosuppressant
:benzodiazepine :antiepileptic :proton-pump-inhibitor :nutritional :antidiabetic
:anti-coagulant :anti-infectious]
:title-fn {:anti-hypertensive :anti_hypertensive
:anti-retroviral :anti_retroviral
:anti-platelet :anti_platelet
:proton-pump-inhibitor :proton_pump_inhibitor
:anti-coagulant :anti_coagulant
:anti-infectious :anti_infectious}})
(defn make-ms-events-table [system patient-ids]
(mapcat identity (vals (ms-events-for-patients system patient-ids))))
(def ms-events-table
{:filename "patient-ms-events.csv"
:data-fn make-ms-events-table
:columns [::patient-id
:t_ms_event/date :t_ms_event/impact :t_ms_event_type/abbreviation
:t_ms_event/is_relapse :t_ms_event_type/name]
:title-fn {:t_ms_event_type/abbreviation "type"
:t_ms_event_type/name "description"}})
(def diagnoses-table
{:filename "patient-diagnoses.csv"
:data-fn all-patient-diagnoses
:columns (into [::patient-id
:t_diagnosis/concept_fk
:t_diagnosis/date_onset :t_diagnosis/date_diagnosis :t_diagnosis/date_to
:icd10
:term]
(keys study-diagnosis-categories))})
(defn make-edss-table [system patient-ids]
(mapcat identity (vals (edss-scores system patient-ids))))
(def edss-table
{:filename "patient-edss.csv"
:data-fn make-edss-table
:columns [::patient-id :t_encounter/date :t_form_edss/edss_score
:t_ms_disease_course/type :t_ms_disease_course/name
:t_form_ms_relapse/in_relapse :t_form_ms_relapse/date_status_recorded]
:title-fn {:t_ms_disease_course/type "disease_status"}})
(defn fetch-results-for-patient [{:com.eldrix.rsdb/keys [conn]} patient-identifier]
(->> (com.eldrix.pc4.rsdb.results/results-for-patient conn patient-identifier)
(map #(assoc % :t_patient/patient_identifier patient-identifier))))
(defn make-results-table [system patient-ids]
(->> (mapcat #(fetch-results-for-patient system %) patient-ids)
(map #(select-keys % [:t_patient/patient_identifier :t_result/date :t_result_type/name]))))
(def results-table
{:filename "patient-results.csv"
:data-fn make-results-table
:columns [::patient-id :t_result/date :t_result_type/name]
:title-fn {:t_result/date "date"
:t_result_type/name "test"}})
(def observations-missing
"A set of patient pseudonyms with observation data missing"
#{})
(defn observation-missing?
"Returns whether the patient specified has observations missing."
[system patient-id]
(let [pseudonyms (set (map :t_episode/stored_pseudonym
(db/execute! (:com.eldrix.rsdb/conn system)
(sql/format {:select :stored_pseudonym
:from [:t_episode :t_patient]
:where [:and
[:= :t_episode/patient_fk :t_patient/id]
[:= :patient_identifier patient-id]]}))))]
(seq (set/intersection observations-missing pseudonyms))))
(def observations-table
"The observations table is generated by exception reporting. If a patient does
not have an exception filed by the team, then we impute that observations were
performed."
{:filename "patient-obs.csv"
:data-fn (fn [system patient-ids]
(map #(let [not-missing? (not (observation-missing? system %))]
(hash-map :t_patient/patient_identifier %
:pulse not-missing?
:blood_pressure not-missing?))
patient-ids))
:columns [::patient-id :pulse :blood_pressure]})
(defn make-weight-height-table [system patient-ids]
(->> (mapcat identity (vals (fetch-weight-height system patient-ids)))
(map #(update % :t_encounter/date_time to-local-date))))
(def weight-height-table
{:filename "patient-weight.csv"
:data-fn make-weight-height-table
:columns [::patient-id :t_encounter/date_time
:t_form_weight_height/weight_kilogram :t_form_weight_height/height_metres
:body_mass_index]
:title-fn {:t_encounter/date_time "date"}})
(def jc-virus-table
{:filename "patient-jc-virus.csv"
:data-fn jc-virus-for-patients
:columns [::patient-id
:t_result_jc_virus/date
:t_result_jc_virus/jc_virus
:t_result_jc_virus/titre]})
(def mri-brain-table
{:filename "patient-mri-brain.csv"
:data-fn mri-brains-for-patients
:columns [::patient-id
:t_result_mri_brain/date
:t_result_mri_brain/id
:t_result_mri_brain/multiple_sclerosis_summary
:t_result_mri_brain/with_gadolinium
:t_result_mri_brain/total_gad_enhancing_lesions
:t_result_mri_brain/gad_range_lower
:t_result_mri_brain/gad_range_upper
:t_result_mri_brain/total_t2_hyperintense
:t_result_mri_brain/t2_range_lower
:t_result_mri_brain/t2_range_upper
:t_result_mri_brain/compare_to_result_mri_brain_fk
:t_result_mri_brain/compare_to_result_date
:t_result_mri_brain/change_t2_hyperintense
:t_result_mri_brain/calc_change_t2]
:title-fn {:t_result_mri_brain/multiple_sclerosis_summary "ms_summary"
:t_result_mri_brain/with_gadolinium "with_gad"
:t_result_mri_brain/total_gad_enhancing_lesions "gad_count"
:t_result_mri_brain/gad_range_lower "gad_lower"
:t_result_mri_brain/gad_range_upper "gad_upper"
:t_result_mri_brain/total_t2_hyperintense "t2_count"
:t_result_mri_brain/t2_range_lower "t2_lower"
:t_result_mri_brain/t2_range_upper "t2_upper"
:t_result_mri_brain/compare_to_result_date "compare_to_date"
:t_result_mri_brain/compare_to_result_mri_brain_fk "compare_to_id"
:t_result_mri_brain/change_t2_hyperintense "t2_change"
:t_result_mri_brain/calc_change_t2 "calc_t2_change"}})
(defn write-local-date [^LocalDate o ^Appendable out _options]
(.append out \")
(.append out (.format (DateTimeFormatter/ISO_DATE) o))
(.append out \"))
(defn write-local-date-time [^LocalDateTime o ^Appendable out _options]
(.append out \")
(.append out (.format (DateTimeFormatter/ISO_DATE_TIME) o))
(.append out \"))
(extend LocalDate json/JSONWriter {:-write write-local-date})
(extend LocalDateTime json/JSONWriter {:-write write-local-date-time})
(def export-tables
[patients-table
patient-identifiers-table
raw-dmt-medications-table
dmt-regimens-table
alemtuzumab-infusions-table
admissions-table
non-dmt-medications-table
ms-events-table
diagnoses-table
edss-table
results-table
weight-height-table
jc-virus-table
mri-brain-table
observations-table])
(s/fdef write-data
:args (s/cat :system any? :centre ::centre))
(defn write-data [system centre]
(let [patient-ids (fetch-study-patient-identifiers system centre)]
(doseq [table export-tables]
(log/info "writing table:" (:filename table))
(write-table system table centre patient-ids))
(log/info "writing metadata")
(with-open [writer (io/writer "metadata.json")]
(json/write (make-metadata system) writer :indent true))
(log/info "writing problem report")
(with-open [writer (io/writer "problems.json")]
(json/write (make-problem-report system patient-ids) writer :indent true))
(log/info "writing medication codes")
(csv/write-csv (io/writer "medication-codes.csv")
(->> (expand-codelists system flattened-study-medications)
(mapcat #(map (fn [concept-id] (vector (:id %) concept-id (:term (hermes/get-fully-specified-name (:com.eldrix/hermes system) concept-id))))
(:codes %)))))
(log/info "writing diagnosis codes")
(csv/write-csv (io/writer "diagnosis-codes.csv")
(->> (expand-codelists system flattened-study-diagnoses)
(mapcat #(map (fn [concept-id] (vector (:id %) concept-id (:term (hermes/get-fully-specified-name (:com.eldrix/hermes system) concept-id))))
(:codes %)))))))
(defn matching-cav-demog?
[{:t_patient/keys [last_name date_birth sex nhs_number] :as pt}
{:wales.nhs.cavuhb.Patient/keys [HOSPITAL_ID LAST_NAME DATE_BIRTH SEX NHS_NO] :as cavpt}]
(let [SEX' (get {"M" :MALE "F" :FEMALE} SEX)]
(boolean (and cavpt HOSPITAL_ID LAST_NAME DATE_BIRTH
(or (nil? NHS_NO) (nil? nhs_number)
(and (.equalsIgnoreCase nhs_number NHS_NO)))
(= DATE_BIRTH date_birth)
(= SEX' sex)
(.equalsIgnoreCase LAST_NAME last_name)))))
(def ^:private demographic-eql
[:t_patient/id
:t_patient/patient_identifier
:t_patient/first_names
:t_patient/last_name :t_patient/nhs_number
:t_patient/date_birth
:t_patient/sex
:t_patient/authoritative_demographics
:t_patient/demographics_authority
:t_patient/authoritative_last_updated
{:t_patient/hospitals [:t_patient_hospital/id
:t_patient_hospital/hospital_fk
:t_patient_hospital/patient_fk
:t_patient_hospital/patient_identifier
:wales.nhs.cavuhb.Patient/HOSPITAL_ID
:wales.nhs.cavuhb.Patient/NHS_NUMBER
:wales.nhs.cavuhb.Patient/LAST_NAME
:wales.nhs.cavuhb.Patient/FIRST_NAMES
:wales.nhs.cavuhb.Patient/DATE_BIRTH
:wales.nhs.cavuhb.Patient/DATE_DEATH
:wales.nhs.cavuhb.Patient/SEX]}])
(defn check-patient-demographics
"Check a single patient's demographics. This will call out to backend live
demographic authorities in order to provide demographic data for the given
patient, so there is an optionally sleep-millis parameter to avoid
denial-of-service attacks if used in batch processes."
[{pathom :pathom/boundary-interface} patient-identifier & {:keys [sleep-millis]}]
(when sleep-millis (Thread/sleep sleep-millis))
(let [ident [:t_patient/patient_identifier patient-identifier]
pt (get (pathom [{ident demographic-eql}]) ident)
pt2 (when pt (update pt
:t_patient/hospitals
(fn [hosps]
(map #(assoc % :demographic-match (matching-cav-demog? pt %)) hosps))))]
(when pt (assoc pt2 :potential-authoritative-demographics
(first (filter :demographic-match (:t_patient/hospitals pt2)))))))
(s/def ::profile keyword?)
(s/def ::export-options (s/keys :req-un [::profile]))
(defn export
"Export research data.
Run as:
```
clj -X com.eldrix.pc4.modules.dmt/export :profile :cvx :centre :cardiff
clj -X com.eldrix.pc4.modules.dmt/export :profile :pc4 :centre :plymouth
clj -X com.eldrix.pc4.modules.dmt/export :profile :dev :centre :cambridge
```
Profile determines the environment in which to use. There are four running
pc4 environments currently:
* dev - development
* nuc - development
* pc4 - Amazon AWS infrastructure
* cvx - NHS Wales infrastructure
Centre determines the choice of projects from which to analyse patients.
* :cardiff
* :plymouth
* :cambridge"
[{:keys [profile centre] :as opts}]
(when-not (s/valid? ::export-options opts)
(throw (ex-info "Invalid options:" (s/explain-data ::export-options opts))))
(let [system (pc4/init profile [:pathom/boundary-interface])]
(write-data system centre)))
(defn make-demography-check [system profile patient-ids]
(->> patient-ids
(patients-with-local-demographics system)
(map #(check-patient-demographics system % :sleep-millis (get {:cvx 500} profile)))
(map #(hash-map
:t_patient/patient_identifier (:t_patient/patient_identifier %)
:first_names (:t_patient/first_names %)
:last_name (:t_patient/last_name %)
:date_birth (:t_patient/date_birth %)
:nhs_number (:t_patient/nhs_number %)
:demog (:t_patient/authoritative_demographics %)
:match_org (get-in % [:potential-authoritative-demographics :t_patient_hospital/hospital_fk])
:crn (get-in % [:potential-authoritative-demographics :t_patient_hospital/patient_identifier])
:cav_match (boolean (get-in % [:potential-authoritative-demographics :demographic-match]))
:cav_crn (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/HOSPITAL_ID])
:cav_nnn (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/NHS_NUMBER])
:cav_dob (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/DATE_BIRTH])
:cav_fname (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/FIRST_NAMES])
:cav_lname (get-in % [:potential-authoritative-demographics :wales.nhs.cavuhb.Patient/LAST_NAME])))))
(defn check-demographics
"Check demographics report. Run as:
```
clj -X com.eldrix.pc4.modules.dmt/check-demographics :profile :cvx :centre :cardiff
```"
[{:keys [profile centre] :as opts}]
(when-not (s/valid? ::export-options opts)
(throw (ex-info "Invalid options:" (s/explain-data ::export-options opts))))
(log/info "check-demographics with " opts)
(let [system (pc4/init profile [:pathom/boundary-interface :wales.nhs.cavuhb/pms])
patient-ids (fetch-study-patient-identifiers system centre)]
(write-table system {:filename "demography-check.csv"
:data-fn (fn [system patient-ids] (make-demography-check system profile patient-ids))}
centre patient-ids)
(pc4/halt! system)))
(defn update-demographic-authority
"Update demographic authorities. Run as:
```
clj -X com.eldrix.pc4.modules.dmt/update-demographic-authority :profile :cvx :centre :cardiff
```"
[{:keys [profile centre] :as opts}]
(when-not (s/valid? ::export-options opts)
(throw (ex-info "Invalid options:" (s/explain-data ::export-options opts))))
(let [system (pc4/init profile [:pathom/boundary-interface :wales.nhs.cavuhb/pms])
patient-ids (fetch-study-patient-identifiers system centre)
patients (->> patient-ids
(patients-with-local-demographics system)
(map #(check-patient-demographics system % :sleep-millis (get {:cvx 500} profile)))
(filter #(get-in % [:potential-authoritative-demographics :demographic-match])))]
(doseq [patient patients]
(patients/set-cav-authoritative-demographics! (:com.eldrix/clods system)
(:com.eldrix.rsdb/conn system)
patient
(:potential-authoritative-demographics patient)))
(pc4/halt! system)))
(defn admission->episode [patient-pk user-id {:wales.nhs.cavuhb.Admission/keys [DATE_FROM DATE_TO] :as admission}]
(when (and admission DATE_FROM DATE_TO)
{:t_episode/patient_fk patient-pk
:t_episode/user_fk user-id
:t_episode/date_registration (.toLocalDate DATE_FROM)
:t_episode/date_discharge (.toLocalDate DATE_TO)}))
(defn admissions-for-patient [system patient-identifier]
(let [ident [:t_patient/patient_identifier patient-identifier]
admissions (p.eql/process (:pathom/env system) [{ident
[:t_patient/id
{:t_patient/demographics_authority
[:wales.nhs.cavuhb.Patient/ADMISSIONS]}]}])
patient-pk (get-in admissions [ident :t_patient/id])
admissions' (get-in admissions [ident :t_patient/demographics_authority :wales.nhs.cavuhb.Patient/ADMISSIONS])]
(map #(admission->episode patient-pk 1 %) admissions')))
(defn update-cav-admissions
"Update admission data from CAVPMS. Run as:
```
clj -X com.eldrix.pc4.modules.dmt/update-cav-admissions :profile :cvx :centre :cardiff
```"
[{:keys [profile centre]}]
(let [system (pc4/init profile [:pathom/boundary-interface :wales.nhs.cavuhb/pms])
project (projects/project-with-name (:com.eldrix.rsdb/conn system) "ADMISSION")
project-id (:t_project/id project)]
(dorun
(->> (fetch-study-patient-identifiers system centre)
(mapcat #(admissions-for-patient system %))
(remove nil?)
(map #(assoc % :t_episode/project_fk project-id))
(map #(projects/register-completed-episode! (:com.eldrix.rsdb/conn system) %))))
(pc4/halt! system)))
(defn update-admissions
[{:keys [profile project-id]}]
(let [{conn :com.eldrix.rsdb/conn :as system} (pc4/init profile [:pathom/boundary-interface :wales.nhs.cavuhb/pms])
admission-project (projects/project-with-name conn "ADMISSION")
project-id' (if (string? project-id) (parse-long project-id) project-id)]
(println "Fetching admissions for project" project-id')
(let [patient-ids (patients/patient-ids-in-projects conn [project-id'])]
(println "Patients in project:" (count patient-ids))
(dorun (->> patient-ids
(map #(do (println "patient:" %) %))
(mapcat #(admissions-for-patient system %))
(remove nil?)
(map #(assoc % :t_episode/project_fk (:t_project/id admission-project)))
(map #(do (println %) %))
(map #(projects/register-completed-episode! conn %)))))
(pc4/halt! system)))
(comment
(def system (pc4/init :cvx [:pathom/boundary-interface :wales.nhs.cavuhb/pms]))
(update-admissions {:profile :cvx :project-id 29}))
(defn matching-filenames
"Return a sequence of filenames from the directory specified, in a map keyed
by the filename."
[dir]
(->> (file-seq (io/as-file dir))
(filter #(.isFile %))
(reduce (fn [acc v] (update acc (.getName v) conj v)) {})))
(defn copy-csv-file
[writer csv-file]
(with-open [reader (io/reader csv-file)]
(->> (csv/read-csv reader)
(csv/write-csv writer))))
(defn append-csv-file
"Write data to writer from the csv-file, removing the first row"
[writer csv-file]
(with-open [reader (io/reader csv-file)]
(->> (csv/read-csv reader)
(rest)
(csv/write-csv writer))))
(defn merge-csv-files
[out files]
(with-open [writer (io/writer out)]
(copy-csv-file writer (first files))
(dorun (map #(append-csv-file writer %) (rest files)))))
(defn merge-matching-data
[dir out-dir]
(let [out-path (.toPath ^File (io/as-file out-dir))
files (->> (matching-filenames dir)
(filter (fn [[filename _files]]
(.endsWith (str/lower-case filename) ".csv"))))]
(println "Writing merged files to" out-path)
(Files/createDirectories out-path (make-array FileAttribute 0))
(dorun (map (fn [[filename csv-files]]
(let [out (.resolve out-path filename)]
(merge-csv-files (.toFile out) csv-files))) files))))
(defn merge-csv
"Merge directories of csv files based on matching filename.
Unfortunately, one must escape strings.
```
clj -X com.eldrix.pc4.modules.dmt/merge-csv :dir '\"/tmp/csv-files\"' :out '\"/tmp/merged\"'
```"
[{:keys [dir out]}]
(merge-matching-data (str dir) (str out)))
(comment
(def system (pc4/init :dev [:pathom/boundary-interface]))
(def patient-ids (take 100 (fetch-study-patient-identifiers system :cardiff)))
(def patients (fetch-patients system patient-ids))
(def ms-events (ms-events-for-patients system patient-ids))
(def dmt-regimens (group-by :t_patient/patient_identifier (make-dmt-regimens-table system patient-ids)))
(def non-dmt-meds (group-by :t_patient/patient_identifier (fetch-non-dmt-medications system patient-ids)))
(def encounters (active-encounters-for-patients system patient-ids))
(def mri-brains (group-by :t_patient/patient_identifier (mri-brains-for-patients system patient-ids)))
(def edss (edss-scores system patient-ids))
(def diagnoses (group-by :t_patient/patient_identifier (all-patient-diagnoses system patient-ids)))
(def data (map (fn [{:t_patient/keys [patient_identifier] :as patient}]
(assoc patient
:diagnoses (get diagnoses patient_identifier)
:medication (get non-dmt-meds patient_identifier)
:ms-events (get ms-events patient_identifier)
:dmts (get dmt-regimens patient_identifier)
:edss (get edss patient_identifier)
:mri-brain (get mri-brains patient_identifier))) patients))
(with-open [writer (io/writer (io/file "patients.json"))]
(json/write data writer)))
zip all csv files with the metadata.json
(comment
(require '[clojure.spec.test.alpha :as stest])
(stest/instrument)
(def system (pc4/init :dev [:pathom/boundary-interface :wales.nhs.cavuhb/pms]))
(pc4/halt! system)
(time (def a (fetch-project-patient-identifiers system (get-in study-centres [:cardiff :projects]))))
(def patient-ids (fetch-study-patient-identifiers system :cardiff))
(get-in study-centres [:cardiff :projects])
(projects/project-with-name (:com.eldrix.rsdb/conn system) "NINFLAMMCARDIFF")
(time (def b (patients/patient-ids-in-projects (:com.eldrix.rsdb/conn system) #{5} :patient-status #{:FULL :PSEUDONYMOUS :STUB :FAKE :DELETED :MERGED})))
(count b)
(set/difference a b)
(def patient-ids (fetch-study-patient-identifiers system :cardiff))
(count patient-ids)
(take 5 patient-ids)
(tap> (take 5 patient-ids))
(time (write-data system :cardiff))
(write-table system patients-table :cardiff patient-ids)
(write-table system diagnoses-table :cardiff patient-ids)
(spit "metadata.json" (json/write-str (make-metadata system)))
(check-patient-demographics system 14232)
(clojure.pprint/pprint (check-patient-demographics system 13936))
(clojure.pprint/pprint (make-demography-check system :cardiff [13936]))
(check-demographics {:profile :dev :centre :cardiff})
(matching-filenames "/Users/mark/Desktop/lempass")
(merge-matching-data "/Users/mark/Desktop/lempass" "/Users/mark/Desktop/lempass-merged")
(com.eldrix.concierge.wales.cav-pms/fetch-admissions (:wales.nhs.cavuhb/pms system) :crn "A647963")
(def pathom (:pathom/boundary-interface system))
(p.eql/process (:pathom/env system) [{[:t_patient/patient_identifier 93718]
[{:t_patient/demographics_authority
[:wales.nhs.cavuhb.Patient/ADMISSIONS]}]}])
(let [project (projects/project-with-name (:com.eldrix.rsdb/conn system) "ADMISSION")
project-id (:t_project/id project)]
(doseq [episode (remove nil? (mapcat #(admissions-for-patient system %) [93718]))]
(projects/register-completed-episode! (:com.eldrix.rsdb/conn system)
(assoc episode :t_episode/project_fk project-id))))
(mapcat #(admissions-for-patient system %) (take 3 (fetch-study-patient-identifiers system :cardiff)))
(take 5 (fetch-study-patient-identifiers system :cardiff))
(admissions-for-patient system 94967)
(projects/register-completed-episode! (:com.eldrix.rsdb/conn system)
(first (admissions-for-patient system 93718)))
(p.eql/process (:pathom/env system) [{[:t_patient/patient_identifier 94967]
[{:t_patient/demographics_authority
[:wales.nhs.cavuhb.Patient/ADMISSIONS]}]}])
(pathom [{[:t_patient/patient_identifier 78213] demographic-eql}])
(pathom [{[:wales.nhs.cavuhb.Patient/FIRST_FORENAME "Mark"]
[:wales.nhs.cavuhb.Patient/FIRST_FORENAME
:wales.nhs.cavuhb.Patient/FIRST_NAMES]}])
(pathom [{[:wales.nhs.cavuhb.Patient/HOSPITAL_ID "A542488"]
[:wales.nhs.cavuhb.Patient/FIRST_FORENAME
:wales.nhs.cavuhb.Patient/FIRST_NAMES
:wales.nhs.cavuhb.Patient/LAST_NAME]}])
(tap> (pathom [{[:t_patient/patient_identifier 94967]
[:t_patient/id
:t_patient/date_birth
:t_patient/date_death
{`(:t_patient/address {:date ~"2000-06-01"}) [:t_address/date_from
:t_address/date_to
{:uk.gov.ons.nhspd/LSOA-2011 [:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
{ : t_patient / addresses [: t_address / date_from : / date_to : uk.gov.ons/lsoa : uk - composite - imd-2020 - mysoc / UK_IMD_E_pop_decile ] }
:t_patient/sex
:t_patient/status
{:t_patient/surgery [:uk.nhs.ord/name]}
{:t_patient/medications [:t_medication/date_from
:t_medication/date_to
{:t_medication/medication [:info.snomed.Concept/id
{:info.snomed.Concept/preferredDescription [:info.snomed.Description/term]}
:uk.nhs.dmd/NM]}]}]}])))
(comment
(require '[portal.api :as p])
(p/open)
(add-tap #'p/submit)
(pc4/prep :dev)
(def system (pc4/init :dev [:pathom/boundary-interface]))
(integrant.core/halt! system)
(tap> system)
(keys system)
(def rsdb-conn (:com.eldrix.rsdb/conn system))
(def roles (users/roles-for-user rsdb-conn "ma090906"))
(def manager (#'users/make-authorization-manager' roles))
(def user-projects (set (map :t_project/id (users/projects-with-permission roles :DATA_DOWNLOAD))))
(def requested-projects #{5})
(def patient-ids (patients/patients-in-projects
rsdb-conn
(clojure.set/intersection user-projects requested-projects)))
(count patient-ids)
(take 4 patient-ids)
(def pathom (:pathom/boundary-interface system))
(:pathom/env system)
(def pt (pathom [{[:t_patient/patient_identifier 17490]
[:t_patient/id
:t_patient/date_birth
:t_patient/date_death
{`(:t_patient/address {:date ~"2000-06-01"}) [:t_address/date_from
:t_address/date_to
{:uk.gov.ons.nhspd/LSOA-2011 [:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
:uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
{:t_patient/addresses [:t_address/date_from :t_address/date_to :uk.gov.ons/lsoa :uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile]}
:t_patient/sex
:t_patient/status
{:t_patient/surgery [:uk.nhs.ord/name]}
{:t_patient/medications [:t_medication/date_from
:t_medication/date_to
{:t_medication/medication [:info.snomed.Concept/id
:uk.nhs.dmd/NM]}]}]}]))
(tap> pt)
(tap> "Hello World")
(pathom [{[:info.snomed.Concept/id 9246601000001104]
[{:info.snomed.Concept/preferredDescription [:info.snomed.Description/term]}
:uk.nhs.dmd/NM]}])
(def natalizumab (get
(pathom [{[:info.snomed.Concept/id 36030311000001108]
[:uk.nhs.dmd/TYPE
:uk.nhs.dmd/NM
:uk.nhs.dmd/ATC
:uk.nhs.dmd/VPID
:info.snomed.Concept/parentRelationshipIds
{:uk.nhs.dmd/VMPS [:info.snomed.Concept/id
:uk.nhs.dmd/VPID
:uk.nhs.dmd/NM
:uk.nhs.dmd/ATC
:uk.nhs.dmd/BNF]}]}])
[:info.snomed.Concept/id 36030311000001108]))
(def all-rels (apply clojure.set/union (vals (:info.snomed.Concept/parentRelationshipIds natalizumab))))
(map #(:term (com.eldrix.hermes.core/get-preferred-synonym (:com.eldrix/hermes system) % "en-GB")) all-rels)
(tap> natalizumab)
(reduce-kv (fn [m k v] (assoc m k (if (map? v) (dissoc v :com.wsscode.pathom3.connect.runner/attribute-errors) v))) {} natalizumab)
(pathom [{'(info.snomed.Search/search
search UK products
:max-hits 10})
[:info.snomed.Concept/id
:uk.nhs.dmd/NM
:uk.nhs.dmd/TYPE
:info.snomed.Description/term
{:info.snomed.Concept/preferredDescription [:info.snomed.Description/term]}
:info.snomed.Concept/active]}])
(pathom [{'(info.snomed.Search/search {:s "glatiramer acetate"})
[:info.snomed.Concept/id
:info.snomed.Description/term
{:info.snomed.Concept/preferredDescription [:info.snomed.Description/term]}]}])
(pathom [{'(info.snomed.Search/search {:constraint "<<9246601000001104 OR <<108755008"})
[:info.snomed.Concept/id
:info.snomed.Description/term]}])
(def hermes (:com.eldrix/hermes system))
hermes
(require '[com.eldrix.hermes.core :as hermes])
(def dmf (set (map :conceptId (hermes/search hermes {:constraint "(<<24056811000001108|Dimethyl fumarate|) OR (<<12086301000001102|Tecfidera|) OR (<10363601000001109|UK Product| :10362801000001104|Has specific active ingredient| =<<724035008|Dimethyl fumarate|)"}))))
(contains? dmf 12086301000001102)
(contains? dmf 24035111000001108))
|
88edf20ab0d2e317243d8f3d637ac5ee6bd0dbafdbe3c06d5074b4df0c337431 | valderman/haste-compiler | Storable.hs | -----------------------------------------------------------------------------
-- |
-- Module : Data.Array.Storable
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : experimental
-- Portability : non-portable (uses Data.Array.MArray)
--
-- A storable array is an IO-mutable array which stores its
-- contents in a contiguous memory block living in the C
-- heap. Elements are stored according to the class 'Storable'.
-- You can obtain the pointer to the array contents to manipulate
-- elements from languages like C.
--
-- It is similar to 'Data.Array.IO.IOUArray' but slower.
-- Its advantage is that it's compatible with C.
--
-----------------------------------------------------------------------------
module Data.Array.Storable (
-- * Arrays of 'Storable' things.
data StorableArray index element
+ index type must be in class Ix
+ element type must be in class
-- * Overloaded mutable array interface
-- | Module "Data.Array.MArray" provides the interface of storable arrays.
-- They are instances of class 'MArray' (with the 'IO' monad).
module Data.Array.MArray,
-- * Accessing the pointer to the array contents
withStorableArray, -- :: StorableArray i e -> (Ptr e -> IO a) -> IO a
touchStorableArray, -- :: StorableArray i e -> IO ()
) where
import Data.Array.MArray
import Data.Array.Storable.Internals
| null | https://raw.githubusercontent.com/valderman/haste-compiler/47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8/libraries/ghc-7.10/array/Data/Array/Storable.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Array.Storable
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable (uses Data.Array.MArray)
A storable array is an IO-mutable array which stores its
contents in a contiguous memory block living in the C
heap. Elements are stored according to the class 'Storable'.
You can obtain the pointer to the array contents to manipulate
elements from languages like C.
It is similar to 'Data.Array.IO.IOUArray' but slower.
Its advantage is that it's compatible with C.
---------------------------------------------------------------------------
* Arrays of 'Storable' things.
* Overloaded mutable array interface
| Module "Data.Array.MArray" provides the interface of storable arrays.
They are instances of class 'MArray' (with the 'IO' monad).
* Accessing the pointer to the array contents
:: StorableArray i e -> (Ptr e -> IO a) -> IO a
:: StorableArray i e -> IO () | Copyright : ( c ) The University of Glasgow 2001
module Data.Array.Storable (
data StorableArray index element
+ index type must be in class Ix
+ element type must be in class
module Data.Array.MArray,
) where
import Data.Array.MArray
import Data.Array.Storable.Internals
|
96ddabdf78809c67f3fb83344e976d65ca1cb79d5df28d42f60d7ac74f23c786 | brendanhay/text-manipulate | Main.hs | {-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - type - defaults #
-- Module : Main
Copyright : ( c ) 2014 - 2022 < >
License : This Source Code Form is subject to the terms of
the Mozilla Public License , v. 2.0 .
A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at /.
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
module Main (main) where
import Data.Text (Text)
import Data.Text.Manipulate
import Test.Tasty
import Test.Tasty.HUnit
main :: IO ()
main =
defaultMain $
testGroup
"tests"
[ exampleGroup
"lowerHead"
lowerHead
[ "",
"title cased phrase",
"camelCasedPhrase",
"pascalCasedPhrase",
"snake_cased_phrase",
"spinal-cased-phrase",
"train-Cased-Phrase",
"1-Mixed_string AOK",
"a double--stop__phrase",
"hTML5",
"είναιΥπάρχουν πολλές-Αντίθετα",
"je_obecněÚvodní-Španěl"
],
exampleGroup
"upperHead"
upperHead
[ "",
"Title cased phrase",
"CamelCasedPhrase",
"PascalCasedPhrase",
"Snake_cased_phrase",
"Spinal-cased-phrase",
"Train-Cased-Phrase",
"1-Mixed_string AOK",
"A double--stop__phrase",
"HTML5",
"ΕίναιΥπάρχουν πολλές-Αντίθετα",
"Je_obecněÚvodní-Španěl"
],
exampleGroup
"takeWord"
takeWord
[ "",
"Title",
"camel",
"Pascal",
"snake",
"spinal",
"Train",
"1",
"a",
"HTML5",
"Είναι",
"Je"
],
exampleGroup
"dropWord"
dropWord
[ "",
"cased phrase",
"CasedPhrase",
"CasedPhrase",
"cased_phrase",
"cased-phrase",
"Cased-Phrase",
"Mixed_string AOK",
"double-stop_phrase",
"",
"Υπάρχουν πολλές-Αντίθετα",
"obecněÚvodní-Španěl"
],
exampleGroup
"stripWord"
stripWord
[ Nothing,
Just "cased phrase",
Just "CasedPhrase",
Just "CasedPhrase",
Just "cased_phrase",
Just "cased-phrase",
Just "Cased-Phrase",
Just "Mixed_string AOK",
Just "double-stop_phrase",
Just "",
Just "Υπάρχουν πολλές-Αντίθετα",
Just "obecněÚvodní-Španěl"
],
testGroup
"splitWords"
[],
testGroup
"indentLines"
[],
testGroup
"toAcronym"
[],
testGroup
"toOrdinal"
[ testCase "1st" ("1st" @=? toOrdinal 1),
testCase "2nd" ("2nd" @=? toOrdinal 2),
testCase "3rd" ("3rd" @=? toOrdinal 3),
testCase "4th" ("4th" @=? toOrdinal 4),
testCase "5th" ("5th" @=? toOrdinal 5),
testCase "21st" ("21st" @=? toOrdinal 21),
testCase "33rd" ("33rd" @=? toOrdinal 33),
testCase "102nd" ("102nd" @=? toOrdinal 102),
testCase "203rd" ("203rd" @=? toOrdinal 203)
],
exampleGroup
"toCamel"
toCamel
[ "",
"titleCasedPhrase",
"camelCasedPhrase",
"pascalCasedPhrase",
"snakeCasedPhrase",
"spinalCasedPhrase",
"trainCasedPhrase",
"1MixedStringAOK",
"aDoubleStopPhrase",
"hTML5",
"είναιΥπάρχουνΠολλέςΑντίθετα",
"jeObecněÚvodníŠpaněl"
],
exampleGroup
"toPascal"
toPascal
[ "",
"TitleCasedPhrase",
"CamelCasedPhrase",
"PascalCasedPhrase",
"SnakeCasedPhrase",
"SpinalCasedPhrase",
"TrainCasedPhrase",
"1MixedStringAOK",
"ADoubleStopPhrase",
"HTML5",
"ΕίναιΥπάρχουνΠολλέςΑντίθετα",
"JeObecněÚvodníŠpaněl"
],
exampleGroup
"toSnake"
toSnake
[ "",
"title_cased_phrase",
"camel_cased_phrase",
"pascal_cased_phrase",
"snake_cased_phrase",
"spinal_cased_phrase",
"train_cased_phrase",
"1_mixed_string_aok",
"a_double_stop_phrase",
"html5",
"είναι_υπάρχουν_πολλές_αντίθετα",
"je_obecně_úvodní_španěl"
],
exampleGroup
"toSpinal"
toSpinal
[ "",
"title-cased-phrase",
"camel-cased-phrase",
"pascal-cased-phrase",
"snake-cased-phrase",
"spinal-cased-phrase",
"train-cased-phrase",
"1-mixed-string-aok",
"a-double-stop-phrase",
"html5",
"είναι-υπάρχουν-πολλές-αντίθετα",
"je-obecně-úvodní-španěl"
],
exampleGroup
"toTrain"
toTrain
[ "",
"Title-Cased-Phrase",
"Camel-Cased-Phrase",
"Pascal-Cased-Phrase",
"Snake-Cased-Phrase",
"Spinal-Cased-Phrase",
"Train-Cased-Phrase",
"1-Mixed-String-AOK",
"A-Double-Stop-Phrase",
"HTML5",
"Είναι-Υπάρχουν-Πολλές-Αντίθετα",
"Je-Obecně-Úvodní-Španěl"
],
exampleGroup
"toTitle"
toTitle
[ "",
"Title Cased Phrase",
"Camel Cased Phrase",
"Pascal Cased Phrase",
"Snake Cased Phrase",
"Spinal Cased Phrase",
"Train Cased Phrase",
"1 Mixed String AOK",
"A Double Stop Phrase",
"HTML5",
"Είναι Υπάρχουν Πολλές Αντίθετα",
"Je Obecně Úvodní Španěl"
]
]
exampleGroup :: (Show a, Eq a) => TestName -> (Text -> a) -> [a] -> TestTree
exampleGroup n f = testGroup n . zipWith run reference
where
run (c, x) y = testCase c (f x @=? y)
reference =
[ ("Empty", ""),
("Title", "Title cased phrase"),
("Camel", "camelCasedPhrase"),
("Pascal", "PascalCasedPhrase"),
("Snake", "snake_cased_phrase"),
("Spinal", "spinal-cased-phrase"),
("Train", "Train-Cased-Phrase"),
("Mixed", "1-Mixed_string AOK"),
("Double Stop", "a double--stop__phrase"),
("Acronym", "HTML5"),
("Greek", "ΕίναιΥπάρχουν πολλές-Αντίθετα"),
("Czech", "Je_obecněÚvodní-Španěl")
]
| null | https://raw.githubusercontent.com/brendanhay/text-manipulate/5b21510103a069537ad7b0f3a5b377f7cdb49d2b/test/Main.hs | haskell | # LANGUAGE OverloadedStrings #
Module : Main
you can obtain it at /.
Stability : experimental | # OPTIONS_GHC -fno - warn - type - defaults #
Copyright : ( c ) 2014 - 2022 < >
License : This Source Code Form is subject to the terms of
the Mozilla Public License , v. 2.0 .
A copy of the MPL can be found in the LICENSE file or
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Main (main) where
import Data.Text (Text)
import Data.Text.Manipulate
import Test.Tasty
import Test.Tasty.HUnit
main :: IO ()
main =
defaultMain $
testGroup
"tests"
[ exampleGroup
"lowerHead"
lowerHead
[ "",
"title cased phrase",
"camelCasedPhrase",
"pascalCasedPhrase",
"snake_cased_phrase",
"spinal-cased-phrase",
"train-Cased-Phrase",
"1-Mixed_string AOK",
"a double--stop__phrase",
"hTML5",
"είναιΥπάρχουν πολλές-Αντίθετα",
"je_obecněÚvodní-Španěl"
],
exampleGroup
"upperHead"
upperHead
[ "",
"Title cased phrase",
"CamelCasedPhrase",
"PascalCasedPhrase",
"Snake_cased_phrase",
"Spinal-cased-phrase",
"Train-Cased-Phrase",
"1-Mixed_string AOK",
"A double--stop__phrase",
"HTML5",
"ΕίναιΥπάρχουν πολλές-Αντίθετα",
"Je_obecněÚvodní-Španěl"
],
exampleGroup
"takeWord"
takeWord
[ "",
"Title",
"camel",
"Pascal",
"snake",
"spinal",
"Train",
"1",
"a",
"HTML5",
"Είναι",
"Je"
],
exampleGroup
"dropWord"
dropWord
[ "",
"cased phrase",
"CasedPhrase",
"CasedPhrase",
"cased_phrase",
"cased-phrase",
"Cased-Phrase",
"Mixed_string AOK",
"double-stop_phrase",
"",
"Υπάρχουν πολλές-Αντίθετα",
"obecněÚvodní-Španěl"
],
exampleGroup
"stripWord"
stripWord
[ Nothing,
Just "cased phrase",
Just "CasedPhrase",
Just "CasedPhrase",
Just "cased_phrase",
Just "cased-phrase",
Just "Cased-Phrase",
Just "Mixed_string AOK",
Just "double-stop_phrase",
Just "",
Just "Υπάρχουν πολλές-Αντίθετα",
Just "obecněÚvodní-Španěl"
],
testGroup
"splitWords"
[],
testGroup
"indentLines"
[],
testGroup
"toAcronym"
[],
testGroup
"toOrdinal"
[ testCase "1st" ("1st" @=? toOrdinal 1),
testCase "2nd" ("2nd" @=? toOrdinal 2),
testCase "3rd" ("3rd" @=? toOrdinal 3),
testCase "4th" ("4th" @=? toOrdinal 4),
testCase "5th" ("5th" @=? toOrdinal 5),
testCase "21st" ("21st" @=? toOrdinal 21),
testCase "33rd" ("33rd" @=? toOrdinal 33),
testCase "102nd" ("102nd" @=? toOrdinal 102),
testCase "203rd" ("203rd" @=? toOrdinal 203)
],
exampleGroup
"toCamel"
toCamel
[ "",
"titleCasedPhrase",
"camelCasedPhrase",
"pascalCasedPhrase",
"snakeCasedPhrase",
"spinalCasedPhrase",
"trainCasedPhrase",
"1MixedStringAOK",
"aDoubleStopPhrase",
"hTML5",
"είναιΥπάρχουνΠολλέςΑντίθετα",
"jeObecněÚvodníŠpaněl"
],
exampleGroup
"toPascal"
toPascal
[ "",
"TitleCasedPhrase",
"CamelCasedPhrase",
"PascalCasedPhrase",
"SnakeCasedPhrase",
"SpinalCasedPhrase",
"TrainCasedPhrase",
"1MixedStringAOK",
"ADoubleStopPhrase",
"HTML5",
"ΕίναιΥπάρχουνΠολλέςΑντίθετα",
"JeObecněÚvodníŠpaněl"
],
exampleGroup
"toSnake"
toSnake
[ "",
"title_cased_phrase",
"camel_cased_phrase",
"pascal_cased_phrase",
"snake_cased_phrase",
"spinal_cased_phrase",
"train_cased_phrase",
"1_mixed_string_aok",
"a_double_stop_phrase",
"html5",
"είναι_υπάρχουν_πολλές_αντίθετα",
"je_obecně_úvodní_španěl"
],
exampleGroup
"toSpinal"
toSpinal
[ "",
"title-cased-phrase",
"camel-cased-phrase",
"pascal-cased-phrase",
"snake-cased-phrase",
"spinal-cased-phrase",
"train-cased-phrase",
"1-mixed-string-aok",
"a-double-stop-phrase",
"html5",
"είναι-υπάρχουν-πολλές-αντίθετα",
"je-obecně-úvodní-španěl"
],
exampleGroup
"toTrain"
toTrain
[ "",
"Title-Cased-Phrase",
"Camel-Cased-Phrase",
"Pascal-Cased-Phrase",
"Snake-Cased-Phrase",
"Spinal-Cased-Phrase",
"Train-Cased-Phrase",
"1-Mixed-String-AOK",
"A-Double-Stop-Phrase",
"HTML5",
"Είναι-Υπάρχουν-Πολλές-Αντίθετα",
"Je-Obecně-Úvodní-Španěl"
],
exampleGroup
"toTitle"
toTitle
[ "",
"Title Cased Phrase",
"Camel Cased Phrase",
"Pascal Cased Phrase",
"Snake Cased Phrase",
"Spinal Cased Phrase",
"Train Cased Phrase",
"1 Mixed String AOK",
"A Double Stop Phrase",
"HTML5",
"Είναι Υπάρχουν Πολλές Αντίθετα",
"Je Obecně Úvodní Španěl"
]
]
exampleGroup :: (Show a, Eq a) => TestName -> (Text -> a) -> [a] -> TestTree
exampleGroup n f = testGroup n . zipWith run reference
where
run (c, x) y = testCase c (f x @=? y)
reference =
[ ("Empty", ""),
("Title", "Title cased phrase"),
("Camel", "camelCasedPhrase"),
("Pascal", "PascalCasedPhrase"),
("Snake", "snake_cased_phrase"),
("Spinal", "spinal-cased-phrase"),
("Train", "Train-Cased-Phrase"),
("Mixed", "1-Mixed_string AOK"),
("Double Stop", "a double--stop__phrase"),
("Acronym", "HTML5"),
("Greek", "ΕίναιΥπάρχουν πολλές-Αντίθετα"),
("Czech", "Je_obecněÚvodní-Španěl")
]
|
a67f593a0602770a64d944615b52464351f972aa51a5affe7914fca5ffb77bdb | chrishowejones/blog-film-ratings | template.clj | (ns film-ratings.views.template
(:require [hiccup.page :refer [html5 include-css include-js]]
[hiccup.element :refer [link-to]]
[hiccup.form :as form]))
(defn page
[content]
(html5
[:head
[:meta {:name "viewport" :content "width=device-width, initial-scale=1, shrink-to-fit=no"}]
[:title "Film Ratings"]
(include-css "")
(include-js
"-3.3.1.slim.min.js"
""
"")
[:body
[:div.container-fluid
[:div.navbar.navbar-dark.bg-dark.shadow-sm
[:div.container.d-flex.justify-content-between
[:h1.navbar-brand.align-items-center.text-light "Film Ratings"]
(link-to {:class "py-2 text-light"} "/" "Home")]]
[:section
content]]]]))
(defn labeled-radio [group]
(fn [checked? label]
[:div.form-check.col
(form/radio-button {:class "form-check-input"} group checked? label)
(form/label {:class "form-check-label"} (str "label-" label) (str label))]))
| null | https://raw.githubusercontent.com/chrishowejones/blog-film-ratings/652ca2aec583db4b91e60ef4008b08b388cca80a/src/film_ratings/views/template.clj | clojure | (ns film-ratings.views.template
(:require [hiccup.page :refer [html5 include-css include-js]]
[hiccup.element :refer [link-to]]
[hiccup.form :as form]))
(defn page
[content]
(html5
[:head
[:meta {:name "viewport" :content "width=device-width, initial-scale=1, shrink-to-fit=no"}]
[:title "Film Ratings"]
(include-css "")
(include-js
"-3.3.1.slim.min.js"
""
"")
[:body
[:div.container-fluid
[:div.navbar.navbar-dark.bg-dark.shadow-sm
[:div.container.d-flex.justify-content-between
[:h1.navbar-brand.align-items-center.text-light "Film Ratings"]
(link-to {:class "py-2 text-light"} "/" "Home")]]
[:section
content]]]]))
(defn labeled-radio [group]
(fn [checked? label]
[:div.form-check.col
(form/radio-button {:class "form-check-input"} group checked? label)
(form/label {:class "form-check-label"} (str "label-" label) (str label))]))
| |
8e395be47b149763ea1592af02cecc567d2ef0e7d5ee3f589062f4ab2947f9e5 | AeneasVerif/aeneas | Types.ml | include Charon.Types
| null | https://raw.githubusercontent.com/AeneasVerif/aeneas/d8d661d02cf0068753ae3963156896492dfde50a/compiler/Types.ml | ocaml | include Charon.Types
| |
31fbc7ede31da20261454af61e546409f420a8b1522eb70ae8a2c3271b9186e5 | monadbobo/ocaml-core | monitor.mli | * A monitor is a context that determines what to do when there is an unhandled
exception . Every Async computation runs within the context of some monitor , which ,
when the computation is running , is referred to as the " current " monitor . Monitors
are arranged in a tree -- when a new monitor is created , it is a child of the current
monitor .
One can listen to a monitor using Monitor.errors to learn when the monitor sees an
error .
If a computation raises an unhandled exception , the current monitor does one of two
things . If anyone is listening to the monitor ( i.e. Monitor.errors has been called on
the monitor ) , then the error stream is extended , and the listeners are responsible for
doing something . If no one is " listening " to the monitor , then the exception is
raised to monitor 's parent . The initial monitor , i.e. the root of the monitor tree ,
prints an unhandled - exception message and calls exit 1 .
* * * * * * * * * * * * * * * * NOTE ABOUT THE TOPLEVEL MONITOR * * * * * * * * * * * * * * * *
It is important to note that in the toplevel monitor , exceptions will only be caught
in the async part of a computation . For example , in
upon ( f ( ) ) g
if [ f ] raises , the exception will not go to a monitor ; it will go to the next caml
exception handler on the stack . Any exceptions raised by [ g ] will be caught by the
scheduler and propagated to the toplevel monitor . Because of this it is advised to
always use [ Scheduler.schedule ] or [ Scheduler.within ] . For example ,
Scheduler.within ( fun ( ) - > upon ( f ( ) ) g )
This code will catch an exception in either [ f ] or [ g ] , and propagate it to the
monitor .
This is only relevent to the toplevel monitor because if you create another monitor
and you wish to run code within it you have no choice but to use [ Scheduler.within ] .
[ try_with ] creates its own monitor and uses [ Scheduler.within ] , so it does not have
this problem .
exception. Every Async computation runs within the context of some monitor, which,
when the computation is running, is referred to as the "current" monitor. Monitors
are arranged in a tree -- when a new monitor is created, it is a child of the current
monitor.
One can listen to a monitor using Monitor.errors to learn when the monitor sees an
error.
If a computation raises an unhandled exception, the current monitor does one of two
things. If anyone is listening to the monitor (i.e. Monitor.errors has been called on
the monitor), then the error stream is extended, and the listeners are responsible for
doing something. If no one is "listening" to the monitor, then the exception is
raised to monitor's parent. The initial monitor, i.e. the root of the monitor tree,
prints an unhandled-exception message and calls exit 1.
**************** NOTE ABOUT THE TOPLEVEL MONITOR ****************
It is important to note that in the toplevel monitor, exceptions will only be caught
in the async part of a computation. For example, in
upon (f ()) g
if [f] raises, the exception will not go to a monitor; it will go to the next caml
exception handler on the stack. Any exceptions raised by [g] will be caught by the
scheduler and propagated to the toplevel monitor. Because of this it is advised to
always use [Scheduler.schedule] or [Scheduler.within]. For example,
Scheduler.within (fun () -> upon (f ()) g)
This code will catch an exception in either [f] or [g], and propagate it to the
monitor.
This is only relevent to the toplevel monitor because if you create another monitor
and you wish to run code within it you have no choice but to use [Scheduler.within].
[try_with] creates its own monitor and uses [Scheduler.within], so it does not have
this problem. *)
open Core.Std
type t = Execution_context.t Raw_monitor.t with sexp_of
(** [create ()] returns a new monitor whose parent is the current monitor *)
val create : ?name:string -> unit -> t
(** [name t] returns the name of the monitor, or a unique id if no name was
supplied to [create]. *)
val name : t -> string
(** [current ()] returns the current monitor *)
val current : unit -> t
(** [errors t] returns a stream of all subsequent errors that monitor [t]
sees. *)
val errors : t -> exn Raw_async_stream.t
(** [error t] returns a deferred that becomes defined if the monitor ever
sees an error. Calling [error t] does not count as "listening for errors",
and if no one has called [errors t] to listen, then errors will still be
raised up the monitor tree. *)
val error : t -> exn Deferred.t
(** [extract_exn exn] extracts the exn from an error exn that comes from a monitor.
If it is not supplied such an error exn, it returns the exn itself. *)
val extract_exn : exn -> exn
(** [has_seen_error t] returns true iff the monitor has ever seen an error. *)
val has_seen_error : t -> bool
* [ send_exn t exn ? backtrace ] sends the exception [ exn ] as an error to be handled
monitor [ t ] . By default , the error will not contain a backtrace . However , the caller
can supply one using [ ` This ] , or use [ ` Get ] to request that [ send_exn ] obtain one
using [ Exn.backtrace ( ) ] .
monitor [t]. By default, the error will not contain a backtrace. However, the caller
can supply one using [`This], or use [`Get] to request that [send_exn] obtain one
using [Exn.backtrace ()]. *)
val send_exn : t -> ?backtrace:[ `Get | `This of string ] -> exn -> unit
(** [try_with f] schedules [f ()] to run in a monitor and returns the result as [Ok x] if
[f] finishes normally, or returns [Error e] if there is some error. Once a result is
returned, any subsequent errors raised by [f ()] are ignored. [try_with] always
returns a deferred immediately and does not raise.
The [name] argument is used to give a name to the monitor the computation will be
running in. This name will appear when printing errors. *)
val try_with
: ?name : string
-> (unit -> 'a Deferred.t)
-> ('a, exn) Result.t Deferred.t
(** [try_with_raise_rest f] is the same as [try_with f], except that subsequent errors
raised by [f ()] are reraised to the monitor that called [try_with_raise_rest]. *)
val try_with_raise_rest
: ?name : string
-> (unit -> 'a Deferred.t)
-> ('a, exn) Result.t Deferred.t
(** [handle_errors ?name f handler] runs [f ()] inside a new monitor with the optionally
supplied name, and calls [handler error] on every error raised to that monitor. Any
error raised by [handler] goes to the monitor in effect when [handle_errors] was
called. *)
val handle_errors
: ?name:string
-> (unit -> 'a Deferred.t)
-> (exn -> unit)
-> 'a Deferred.t
(** [catch_stream ?name f] runs [f ()] inside a new monitor [m] and returns the stream of
errors raised to [m]. *)
val catch_stream : ?name:string -> (unit -> unit) -> exn Raw_async_stream.t
* [ catch ? name f ] runs [ f ( ) ] inside a new monitor [ m ] and returns the first error
raised to [ m ] .
raised to [m]. *)
val catch : ?name:string -> (unit -> unit) -> exn Deferred.t
(** [protect f ~finally] runs [f ()] and then [finally] regardless of the success
or failure of [f]. Re-raises any exception thrown by [f] or returns whatever
[f] returned.
The [name] argument is used to give a name to the monitor the computation
will be running in. This name will appear when printing the errors. *)
val protect
: ?name : string
-> (unit -> 'a Deferred.t)
-> finally:(unit -> unit Deferred.t) -> 'a Deferred.t
val main : t
module Exported_for_scheduler : sig
type 'a with_options =
?block_group:Block_group.t
-> ?monitor:t
-> ?priority:Priority.t
-> 'a
val within' : ((unit -> 'a Deferred.t) -> 'a Deferred.t) with_options
val within : ((unit -> unit ) -> unit ) with_options
val within_v : ((unit -> 'a ) -> 'a option ) with_options
val schedule' : ((unit -> 'a Deferred.t) -> 'a Deferred.t) with_options
val schedule : ((unit -> unit ) -> unit ) with_options
val within_context : Execution_context.t -> (unit -> 'a) -> ('a, unit) Result.t
end
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/async/core/lib/monitor.mli | ocaml | * [create ()] returns a new monitor whose parent is the current monitor
* [name t] returns the name of the monitor, or a unique id if no name was
supplied to [create].
* [current ()] returns the current monitor
* [errors t] returns a stream of all subsequent errors that monitor [t]
sees.
* [error t] returns a deferred that becomes defined if the monitor ever
sees an error. Calling [error t] does not count as "listening for errors",
and if no one has called [errors t] to listen, then errors will still be
raised up the monitor tree.
* [extract_exn exn] extracts the exn from an error exn that comes from a monitor.
If it is not supplied such an error exn, it returns the exn itself.
* [has_seen_error t] returns true iff the monitor has ever seen an error.
* [try_with f] schedules [f ()] to run in a monitor and returns the result as [Ok x] if
[f] finishes normally, or returns [Error e] if there is some error. Once a result is
returned, any subsequent errors raised by [f ()] are ignored. [try_with] always
returns a deferred immediately and does not raise.
The [name] argument is used to give a name to the monitor the computation will be
running in. This name will appear when printing errors.
* [try_with_raise_rest f] is the same as [try_with f], except that subsequent errors
raised by [f ()] are reraised to the monitor that called [try_with_raise_rest].
* [handle_errors ?name f handler] runs [f ()] inside a new monitor with the optionally
supplied name, and calls [handler error] on every error raised to that monitor. Any
error raised by [handler] goes to the monitor in effect when [handle_errors] was
called.
* [catch_stream ?name f] runs [f ()] inside a new monitor [m] and returns the stream of
errors raised to [m].
* [protect f ~finally] runs [f ()] and then [finally] regardless of the success
or failure of [f]. Re-raises any exception thrown by [f] or returns whatever
[f] returned.
The [name] argument is used to give a name to the monitor the computation
will be running in. This name will appear when printing the errors. | * A monitor is a context that determines what to do when there is an unhandled
exception . Every Async computation runs within the context of some monitor , which ,
when the computation is running , is referred to as the " current " monitor . Monitors
are arranged in a tree -- when a new monitor is created , it is a child of the current
monitor .
One can listen to a monitor using Monitor.errors to learn when the monitor sees an
error .
If a computation raises an unhandled exception , the current monitor does one of two
things . If anyone is listening to the monitor ( i.e. Monitor.errors has been called on
the monitor ) , then the error stream is extended , and the listeners are responsible for
doing something . If no one is " listening " to the monitor , then the exception is
raised to monitor 's parent . The initial monitor , i.e. the root of the monitor tree ,
prints an unhandled - exception message and calls exit 1 .
* * * * * * * * * * * * * * * * NOTE ABOUT THE TOPLEVEL MONITOR * * * * * * * * * * * * * * * *
It is important to note that in the toplevel monitor , exceptions will only be caught
in the async part of a computation . For example , in
upon ( f ( ) ) g
if [ f ] raises , the exception will not go to a monitor ; it will go to the next caml
exception handler on the stack . Any exceptions raised by [ g ] will be caught by the
scheduler and propagated to the toplevel monitor . Because of this it is advised to
always use [ Scheduler.schedule ] or [ Scheduler.within ] . For example ,
Scheduler.within ( fun ( ) - > upon ( f ( ) ) g )
This code will catch an exception in either [ f ] or [ g ] , and propagate it to the
monitor .
This is only relevent to the toplevel monitor because if you create another monitor
and you wish to run code within it you have no choice but to use [ Scheduler.within ] .
[ try_with ] creates its own monitor and uses [ Scheduler.within ] , so it does not have
this problem .
exception. Every Async computation runs within the context of some monitor, which,
when the computation is running, is referred to as the "current" monitor. Monitors
are arranged in a tree -- when a new monitor is created, it is a child of the current
monitor.
One can listen to a monitor using Monitor.errors to learn when the monitor sees an
error.
If a computation raises an unhandled exception, the current monitor does one of two
things. If anyone is listening to the monitor (i.e. Monitor.errors has been called on
the monitor), then the error stream is extended, and the listeners are responsible for
doing something. If no one is "listening" to the monitor, then the exception is
raised to monitor's parent. The initial monitor, i.e. the root of the monitor tree,
prints an unhandled-exception message and calls exit 1.
**************** NOTE ABOUT THE TOPLEVEL MONITOR ****************
It is important to note that in the toplevel monitor, exceptions will only be caught
in the async part of a computation. For example, in
upon (f ()) g
if [f] raises, the exception will not go to a monitor; it will go to the next caml
exception handler on the stack. Any exceptions raised by [g] will be caught by the
scheduler and propagated to the toplevel monitor. Because of this it is advised to
always use [Scheduler.schedule] or [Scheduler.within]. For example,
Scheduler.within (fun () -> upon (f ()) g)
This code will catch an exception in either [f] or [g], and propagate it to the
monitor.
This is only relevent to the toplevel monitor because if you create another monitor
and you wish to run code within it you have no choice but to use [Scheduler.within].
[try_with] creates its own monitor and uses [Scheduler.within], so it does not have
this problem. *)
open Core.Std
type t = Execution_context.t Raw_monitor.t with sexp_of
val create : ?name:string -> unit -> t
val name : t -> string
val current : unit -> t
val errors : t -> exn Raw_async_stream.t
val error : t -> exn Deferred.t
val extract_exn : exn -> exn
val has_seen_error : t -> bool
* [ send_exn t exn ? backtrace ] sends the exception [ exn ] as an error to be handled
monitor [ t ] . By default , the error will not contain a backtrace . However , the caller
can supply one using [ ` This ] , or use [ ` Get ] to request that [ send_exn ] obtain one
using [ Exn.backtrace ( ) ] .
monitor [t]. By default, the error will not contain a backtrace. However, the caller
can supply one using [`This], or use [`Get] to request that [send_exn] obtain one
using [Exn.backtrace ()]. *)
val send_exn : t -> ?backtrace:[ `Get | `This of string ] -> exn -> unit
val try_with
: ?name : string
-> (unit -> 'a Deferred.t)
-> ('a, exn) Result.t Deferred.t
val try_with_raise_rest
: ?name : string
-> (unit -> 'a Deferred.t)
-> ('a, exn) Result.t Deferred.t
val handle_errors
: ?name:string
-> (unit -> 'a Deferred.t)
-> (exn -> unit)
-> 'a Deferred.t
val catch_stream : ?name:string -> (unit -> unit) -> exn Raw_async_stream.t
* [ catch ? name f ] runs [ f ( ) ] inside a new monitor [ m ] and returns the first error
raised to [ m ] .
raised to [m]. *)
val catch : ?name:string -> (unit -> unit) -> exn Deferred.t
val protect
: ?name : string
-> (unit -> 'a Deferred.t)
-> finally:(unit -> unit Deferred.t) -> 'a Deferred.t
val main : t
module Exported_for_scheduler : sig
type 'a with_options =
?block_group:Block_group.t
-> ?monitor:t
-> ?priority:Priority.t
-> 'a
val within' : ((unit -> 'a Deferred.t) -> 'a Deferred.t) with_options
val within : ((unit -> unit ) -> unit ) with_options
val within_v : ((unit -> 'a ) -> 'a option ) with_options
val schedule' : ((unit -> 'a Deferred.t) -> 'a Deferred.t) with_options
val schedule : ((unit -> unit ) -> unit ) with_options
val within_context : Execution_context.t -> (unit -> 'a) -> ('a, unit) Result.t
end
|
9a183ab0713c55ba1b42c671afff2ab002a9700dccd0c108aff19189362ebe26 | argp/bap | oUnit.mli | (***********************************************************************)
(* The OUnit library *)
(* *)
Copyright ( C ) 2002 - 2008 Maas - Maarten Zeeman .
Copyright ( C ) 2010 OCamlCore SARL
(* *)
(* See LICENSE for details. *)
(***********************************************************************)
* Unit test building blocks
@author @author
@author Maas-Maarten Zeeman
@author Sylvain Le Gall
*)
* { 2 Assertions }
Assertions are the basic building blocks of unittests .
Assertions are the basic building blocks of unittests. *)
(** Signals a failure. This will raise an exception with the specified
string.
@raise Failure signal a failure *)
val assert_failure : string -> 'a
(** Signals a failure when bool is false. The string identifies the
failure.
@raise Failure signal a failure *)
val assert_bool : string -> bool -> unit
(** Shorthand for assert_bool
@raise Failure to signal a failure *)
val ( @? ) : string -> bool -> unit
(** Signals a failure when the string is non-empty. The string identifies the
failure.
@raise Failure signal a failure *)
val assert_string : string -> unit
(** [assert_command prg args] Run the command provided.
@param exit_code expected exit code
@param sinput provide this [char Stream.t] as input of the process
@param foutput run this function on output, it can contains an
[assert_equal] to check it
@param use_stderr redirect [stderr] to [stdout]
@param env Unix environment
@param verbose if a failure arise, dump stdout/stderr of the process to stderr
@since 1.1.0
*)
val assert_command :
?exit_code:Unix.process_status ->
?sinput:char Stream.t ->
?foutput:(char Stream.t -> unit) ->
?use_stderr:bool ->
?env:string array ->
?verbose:bool ->
string -> string list -> unit
* [ assert_equal expected real ] Compares two values , when they are not equal a
failure is signaled .
@param cmp customize function to compare , default is [ =]
@param printer value printer , do n't print value otherwise
@param pp_diff if not equal , ask a custom display of the difference
using [ diff fmt exp real ] where [ fmt ] is the formatter to use
@param msg custom message to identify the failure
@raise Failure signal a failure
@version 1.1.0
failure is signaled.
@param cmp customize function to compare, default is [=]
@param printer value printer, don't print value otherwise
@param pp_diff if not equal, ask a custom display of the difference
using [diff fmt exp real] where [fmt] is the formatter to use
@param msg custom message to identify the failure
@raise Failure signal a failure
@version 1.1.0
*)
val assert_equal :
?cmp:('a -> 'a -> bool) ->
?printer:('a -> string) ->
?pp_diff:(Format.formatter -> ('a * 'a) -> unit) ->
?msg:string -> 'a -> 'a -> unit
(** Asserts if the expected exception was raised.
@param msg identify the failure
@raise Failure description *)
val assert_raises : ?msg:string -> exn -> (unit -> 'a) -> unit
* { 2 Skipping tests }
In certain condition test can be written but there is no point running it , because they
are not significant ( missing OS features for example ) . In this case this is not a failure
nor a success . Following functions allow you to escape test , just as assertion but without
the same error status .
A test skipped is counted as success . A test todo is counted as failure .
In certain condition test can be written but there is no point running it, because they
are not significant (missing OS features for example). In this case this is not a failure
nor a success. Following functions allow you to escape test, just as assertion but without
the same error status.
A test skipped is counted as success. A test todo is counted as failure.
*)
(** [skip cond msg] If [cond] is true, skip the test for the reason explain in [msg].
For example [skip_if (Sys.os_type = "Win32") "Test a doesn't run on windows"].
@since 1.0.3
*)
val skip_if : bool -> string -> unit
(** The associated test is still to be done, for the reason given.
@since 1.0.3
*)
val todo : string -> unit
(** {2 Compare Functions} *)
(** Compare floats up to a given relative error.
@param epsilon if the difference is smaller [epsilon] values are equal
*)
val cmp_float : ?epsilon:float -> float -> float -> bool
* { 2 Bracket }
A bracket is a functional implementation of the commonly used
setUp and tearDown feature in unittests . It can be used like this :
[ " MyTestCase " > : : ( bracket test_set_up test_fun test_tear_down ) ]
A bracket is a functional implementation of the commonly used
setUp and tearDown feature in unittests. It can be used like this:
["MyTestCase" >:: (bracket test_set_up test_fun test_tear_down)]
*)
* [ bracket set_up test tear_down ] The [ set_up ] function runs first , then
the [ test ] function runs and at the end [ tear_down ] runs . The
[ tear_down ] function runs even if the [ test ] failed and help to clean
the environment .
the [test] function runs and at the end [tear_down] runs. The
[tear_down] function runs even if the [test] failed and help to clean
the environment.
*)
val bracket: (unit -> 'a) -> ('a -> unit) -> ('a -> unit) -> unit -> unit
(** [bracket_tmpfile test] The [test] function takes a temporary filename
and matching output channel as arguments. The temporary file is created
before the test and removed after the test.
@param prefix see [Filename.open_temp_file]
@param suffix see [Filename.open_temp_file]
@param mode see [Filename.open_temp_file]
@since 1.1.0
*)
val bracket_tmpfile:
?prefix:string ->
?suffix:string ->
?mode:open_flag list ->
((string * out_channel) -> unit) -> unit -> unit
* { 2 Constructing Tests }
(** The type of test function *)
type test_fun = unit -> unit
(** The type of tests *)
type test =
TestCase of test_fun
| TestList of test list
| TestLabel of string * test
(** Create a TestLabel for a test *)
val (>:) : string -> test -> test
* Create a TestLabel for a TestCase
val (>::) : string -> test_fun -> test
* Create a TestLabel for a TestList
val (>:::) : string -> test list -> test
* Some shorthands which allows easy test construction .
Examples :
- [ " " > : ( ) ) ) ] = >
[ TestLabel("test2 " , ( ) ) ) ) ]
- [ " test2 " > : : ( fun _ - > ( ) ) ] = >
[ TestLabel("test2 " , ( ) ) ) ) ]
- [ " test - suite " > : : : [ " test2 " > : : ( fun _ - > ( ) ) ; ] ] = >
[ TestLabel("test - suite " , TestSuite([TestLabel("test2 " , ( ) ) ) ) ] ) ) ]
Examples:
- ["test1" >: TestCase((fun _ -> ()))] =>
[TestLabel("test2", TestCase((fun _ -> ())))]
- ["test2" >:: (fun _ -> ())] =>
[TestLabel("test2", TestCase((fun _ -> ())))]
- ["test-suite" >::: ["test2" >:: (fun _ -> ());]] =>
[TestLabel("test-suite", TestSuite([TestLabel("test2", TestCase((fun _ -> ())))]))]
*)
(** [test_decorate g tst] Apply [g] to test function contains in [tst] tree.
@since 1.0.3
*)
val test_decorate : (test_fun -> test_fun) -> test -> test
(** [test_filter paths tst] Filter test based on their path string representation.
@param skip] if set, just use [skip_if] for the matching tests.
@since 1.0.3
*)
val test_filter : ?skip:bool -> string list -> test -> test option
* { 2 Retrieve Information from Tests }
(** Returns the number of available test cases *)
val test_case_count : test -> int
(** Types which represent the path of a test *)
type node = ListItem of int | Label of string
type path = node list (** The path to the test (in reverse order). *)
(** Make a string from a node *)
val string_of_node : node -> string
(** Make a string from a path. The path will be reversed before it is
tranlated into a string *)
val string_of_path : path -> string
(** Returns a list with paths of the test *)
val test_case_paths : test -> path list
(** {2 Performing Tests} *)
(** The possible results of a test *)
type test_result =
RSuccess of path
| RFailure of path * string
| RError of path * string
| RSkip of path * string
| RTodo of path * string
(** Events which occur during a test run *)
type test_event =
EStart of path
| EEnd of path
| EResult of test_result
(** Perform the test, allows you to build your own test runner *)
val perform_test : (test_event -> 'a) -> test -> test_result list
(** A simple text based test runner. It prints out information
during the test.
@param verbose print verbose message
*)
val run_test_tt : ?verbose:bool -> test -> test_result list
(** Main version of the text based test runner. It reads the supplied command
line arguments to set the verbose level and limit the number of test to
run.
@param arg_specs add extra command line arguments
@param set_verbose call a function to set verbosity
@version 1.1.0
*)
val run_test_tt_main :
?arg_specs:(Arg.key * Arg.spec * Arg.doc) list ->
?set_verbose:(bool -> unit) ->
test -> test_result list
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ounit/src/oUnit.mli | ocaml | *********************************************************************
The OUnit library
See LICENSE for details.
*********************************************************************
* Signals a failure. This will raise an exception with the specified
string.
@raise Failure signal a failure
* Signals a failure when bool is false. The string identifies the
failure.
@raise Failure signal a failure
* Shorthand for assert_bool
@raise Failure to signal a failure
* Signals a failure when the string is non-empty. The string identifies the
failure.
@raise Failure signal a failure
* [assert_command prg args] Run the command provided.
@param exit_code expected exit code
@param sinput provide this [char Stream.t] as input of the process
@param foutput run this function on output, it can contains an
[assert_equal] to check it
@param use_stderr redirect [stderr] to [stdout]
@param env Unix environment
@param verbose if a failure arise, dump stdout/stderr of the process to stderr
@since 1.1.0
* Asserts if the expected exception was raised.
@param msg identify the failure
@raise Failure description
* [skip cond msg] If [cond] is true, skip the test for the reason explain in [msg].
For example [skip_if (Sys.os_type = "Win32") "Test a doesn't run on windows"].
@since 1.0.3
* The associated test is still to be done, for the reason given.
@since 1.0.3
* {2 Compare Functions}
* Compare floats up to a given relative error.
@param epsilon if the difference is smaller [epsilon] values are equal
* [bracket_tmpfile test] The [test] function takes a temporary filename
and matching output channel as arguments. The temporary file is created
before the test and removed after the test.
@param prefix see [Filename.open_temp_file]
@param suffix see [Filename.open_temp_file]
@param mode see [Filename.open_temp_file]
@since 1.1.0
* The type of test function
* The type of tests
* Create a TestLabel for a test
* [test_decorate g tst] Apply [g] to test function contains in [tst] tree.
@since 1.0.3
* [test_filter paths tst] Filter test based on their path string representation.
@param skip] if set, just use [skip_if] for the matching tests.
@since 1.0.3
* Returns the number of available test cases
* Types which represent the path of a test
* The path to the test (in reverse order).
* Make a string from a node
* Make a string from a path. The path will be reversed before it is
tranlated into a string
* Returns a list with paths of the test
* {2 Performing Tests}
* The possible results of a test
* Events which occur during a test run
* Perform the test, allows you to build your own test runner
* A simple text based test runner. It prints out information
during the test.
@param verbose print verbose message
* Main version of the text based test runner. It reads the supplied command
line arguments to set the verbose level and limit the number of test to
run.
@param arg_specs add extra command line arguments
@param set_verbose call a function to set verbosity
@version 1.1.0
| Copyright ( C ) 2002 - 2008 Maas - Maarten Zeeman .
Copyright ( C ) 2010 OCamlCore SARL
* Unit test building blocks
@author @author
@author Maas-Maarten Zeeman
@author Sylvain Le Gall
*)
* { 2 Assertions }
Assertions are the basic building blocks of unittests .
Assertions are the basic building blocks of unittests. *)
val assert_failure : string -> 'a
val assert_bool : string -> bool -> unit
val ( @? ) : string -> bool -> unit
val assert_string : string -> unit
val assert_command :
?exit_code:Unix.process_status ->
?sinput:char Stream.t ->
?foutput:(char Stream.t -> unit) ->
?use_stderr:bool ->
?env:string array ->
?verbose:bool ->
string -> string list -> unit
* [ assert_equal expected real ] Compares two values , when they are not equal a
failure is signaled .
@param cmp customize function to compare , default is [ =]
@param printer value printer , do n't print value otherwise
@param pp_diff if not equal , ask a custom display of the difference
using [ diff fmt exp real ] where [ fmt ] is the formatter to use
@param msg custom message to identify the failure
@raise Failure signal a failure
@version 1.1.0
failure is signaled.
@param cmp customize function to compare, default is [=]
@param printer value printer, don't print value otherwise
@param pp_diff if not equal, ask a custom display of the difference
using [diff fmt exp real] where [fmt] is the formatter to use
@param msg custom message to identify the failure
@raise Failure signal a failure
@version 1.1.0
*)
val assert_equal :
?cmp:('a -> 'a -> bool) ->
?printer:('a -> string) ->
?pp_diff:(Format.formatter -> ('a * 'a) -> unit) ->
?msg:string -> 'a -> 'a -> unit
val assert_raises : ?msg:string -> exn -> (unit -> 'a) -> unit
* { 2 Skipping tests }
In certain condition test can be written but there is no point running it , because they
are not significant ( missing OS features for example ) . In this case this is not a failure
nor a success . Following functions allow you to escape test , just as assertion but without
the same error status .
A test skipped is counted as success . A test todo is counted as failure .
In certain condition test can be written but there is no point running it, because they
are not significant (missing OS features for example). In this case this is not a failure
nor a success. Following functions allow you to escape test, just as assertion but without
the same error status.
A test skipped is counted as success. A test todo is counted as failure.
*)
val skip_if : bool -> string -> unit
val todo : string -> unit
val cmp_float : ?epsilon:float -> float -> float -> bool
* { 2 Bracket }
A bracket is a functional implementation of the commonly used
setUp and tearDown feature in unittests . It can be used like this :
[ " MyTestCase " > : : ( bracket test_set_up test_fun test_tear_down ) ]
A bracket is a functional implementation of the commonly used
setUp and tearDown feature in unittests. It can be used like this:
["MyTestCase" >:: (bracket test_set_up test_fun test_tear_down)]
*)
* [ bracket set_up test tear_down ] The [ set_up ] function runs first , then
the [ test ] function runs and at the end [ tear_down ] runs . The
[ tear_down ] function runs even if the [ test ] failed and help to clean
the environment .
the [test] function runs and at the end [tear_down] runs. The
[tear_down] function runs even if the [test] failed and help to clean
the environment.
*)
val bracket: (unit -> 'a) -> ('a -> unit) -> ('a -> unit) -> unit -> unit
val bracket_tmpfile:
?prefix:string ->
?suffix:string ->
?mode:open_flag list ->
((string * out_channel) -> unit) -> unit -> unit
* { 2 Constructing Tests }
type test_fun = unit -> unit
type test =
TestCase of test_fun
| TestList of test list
| TestLabel of string * test
val (>:) : string -> test -> test
* Create a TestLabel for a TestCase
val (>::) : string -> test_fun -> test
* Create a TestLabel for a TestList
val (>:::) : string -> test list -> test
* Some shorthands which allows easy test construction .
Examples :
- [ " " > : ( ) ) ) ] = >
[ TestLabel("test2 " , ( ) ) ) ) ]
- [ " test2 " > : : ( fun _ - > ( ) ) ] = >
[ TestLabel("test2 " , ( ) ) ) ) ]
- [ " test - suite " > : : : [ " test2 " > : : ( fun _ - > ( ) ) ; ] ] = >
[ TestLabel("test - suite " , TestSuite([TestLabel("test2 " , ( ) ) ) ) ] ) ) ]
Examples:
- ["test1" >: TestCase((fun _ -> ()))] =>
[TestLabel("test2", TestCase((fun _ -> ())))]
- ["test2" >:: (fun _ -> ())] =>
[TestLabel("test2", TestCase((fun _ -> ())))]
- ["test-suite" >::: ["test2" >:: (fun _ -> ());]] =>
[TestLabel("test-suite", TestSuite([TestLabel("test2", TestCase((fun _ -> ())))]))]
*)
val test_decorate : (test_fun -> test_fun) -> test -> test
val test_filter : ?skip:bool -> string list -> test -> test option
* { 2 Retrieve Information from Tests }
val test_case_count : test -> int
type node = ListItem of int | Label of string
val string_of_node : node -> string
val string_of_path : path -> string
val test_case_paths : test -> path list
type test_result =
RSuccess of path
| RFailure of path * string
| RError of path * string
| RSkip of path * string
| RTodo of path * string
type test_event =
EStart of path
| EEnd of path
| EResult of test_result
val perform_test : (test_event -> 'a) -> test -> test_result list
val run_test_tt : ?verbose:bool -> test -> test_result list
val run_test_tt_main :
?arg_specs:(Arg.key * Arg.spec * Arg.doc) list ->
?set_verbose:(bool -> unit) ->
test -> test_result list
|
fdf8d10f976b7a4d302edae73d140b59ed76dc2412ef1bc8989ac3a419b15505 | fakedata-haskell/fakedata | CaTextSpec.hs | # LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
module CaTextSpec where
import Data.Text (Text)
import qualified Data.Text as T
import Faker hiding (defaultFakerSettings)
import qualified Faker.Color as CL
import Faker.Combinators (listOf)
import qualified Faker.Name as NA
import Test.Hspec
import TestImport
isText :: Text -> Bool
isText x = T.length x >= 1
isTexts :: [Text] -> Bool
isTexts xs = and $ map isText xs
fakerSettings :: FakerSettings
fakerSettings = setLocale "ca" defaultFakerSettings
verifyFakes :: [Fake Text] -> IO [Bool]
verifyFakes funs = do
let fs :: [IO Text] = map (generateWithSettings fakerSettings) funs
gs :: [IO Bool] = map (\f -> isText <$> f) fs
sequence gs
verifyDistributeFakes :: [Fake Text] -> IO [Bool]
verifyDistributeFakes funs = do
let fs :: [IO [Text]] =
map (generateWithSettings fakerSettings) $ map (listOf 100) funs
gs :: [IO Bool] = map (\f -> isTexts <$> f) fs
sequence gs
spec :: Spec
spec = do
describe "TextSpec" $ do
it "ca CAT Locale" $ do
let functions :: [Fake Text] =
[NA.firstName, NA.lastName, NA.name, NA.nameWithMiddle, CL.name]
bools <- verifyDistributeFakes functions
(and bools) `shouldBe` True
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/e6fbc16cfa27b2d17aa449ea8140788196ca135b/test/CaTextSpec.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE ScopedTypeVariables #
module CaTextSpec where
import Data.Text (Text)
import qualified Data.Text as T
import Faker hiding (defaultFakerSettings)
import qualified Faker.Color as CL
import Faker.Combinators (listOf)
import qualified Faker.Name as NA
import Test.Hspec
import TestImport
isText :: Text -> Bool
isText x = T.length x >= 1
isTexts :: [Text] -> Bool
isTexts xs = and $ map isText xs
fakerSettings :: FakerSettings
fakerSettings = setLocale "ca" defaultFakerSettings
verifyFakes :: [Fake Text] -> IO [Bool]
verifyFakes funs = do
let fs :: [IO Text] = map (generateWithSettings fakerSettings) funs
gs :: [IO Bool] = map (\f -> isText <$> f) fs
sequence gs
verifyDistributeFakes :: [Fake Text] -> IO [Bool]
verifyDistributeFakes funs = do
let fs :: [IO [Text]] =
map (generateWithSettings fakerSettings) $ map (listOf 100) funs
gs :: [IO Bool] = map (\f -> isTexts <$> f) fs
sequence gs
spec :: Spec
spec = do
describe "TextSpec" $ do
it "ca CAT Locale" $ do
let functions :: [Fake Text] =
[NA.firstName, NA.lastName, NA.name, NA.nameWithMiddle, CL.name]
bools <- verifyDistributeFakes functions
(and bools) `shouldBe` True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.