_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
8eaa9d5fa5348983d948e2cc96f2d72d9b52d8c2b787248206456af7334ae562
dbuenzli/fut
lwtleak.ml
(* Immediate, easy *) let rec loop n = if n = 0 then Lwt.return () else Lwt.(return (pred n) >>= loop) (* Not immediate, link trick *) let queue = Queue.create () let yield () = let t, w = Lwt.wait () in Queue.push w queue; t let rec loop n = (* proxy *) if n = 0 then Lwt.return () else Lwt.(yield () >>= fun () -> loop (n - 1)) let rec run () = match try Some (Queue.take queue) with Queue.Empty -> None with | None -> () | Some w -> Lwt.wakeup w (); run () Cancel let t = fst (Lwt.wait ()) let rec loop n = if n = 0 then Lwt.return () else Lwt.(pick [ map succ t; return (pred n) ] >>= loop) (* Cancel bis, this doesn't do what I expect because pick cancels [t], which means that the whole thing may fail with cancel, because pick may return the cancelled one. *) let t = fst (Lwt.task ()) let rec loop n = if n = 0 then Lwt.return () else Lwt.(pick [ map succ t; return (pred n) ] >>= loop) (* leaks *) let t = fst (Lwt.task ()) let rec loop n = if n = 0 then Lwt.return () else Lwt.(choose [ map succ t; return (pred n) ] >>= loop)
null
https://raw.githubusercontent.com/dbuenzli/fut/907de63df12815f2df2cb796baa7fa37ac2758d4/attic/lwtleak.ml
ocaml
Immediate, easy Not immediate, link trick proxy Cancel bis, this doesn't do what I expect because pick cancels [t], which means that the whole thing may fail with cancel, because pick may return the cancelled one. leaks
let rec loop n = if n = 0 then Lwt.return () else Lwt.(return (pred n) >>= loop) let queue = Queue.create () let yield () = let t, w = Lwt.wait () in Queue.push w queue; t if n = 0 then Lwt.return () else Lwt.(yield () >>= fun () -> loop (n - 1)) let rec run () = match try Some (Queue.take queue) with Queue.Empty -> None with | None -> () | Some w -> Lwt.wakeup w (); run () Cancel let t = fst (Lwt.wait ()) let rec loop n = if n = 0 then Lwt.return () else Lwt.(pick [ map succ t; return (pred n) ] >>= loop) let t = fst (Lwt.task ()) let rec loop n = if n = 0 then Lwt.return () else Lwt.(pick [ map succ t; return (pred n) ] >>= loop) let t = fst (Lwt.task ()) let rec loop n = if n = 0 then Lwt.return () else Lwt.(choose [ map succ t; return (pred n) ] >>= loop)
a308f2961bd440ca4a0881d59da23897a1ac2544812918f46f3c2140df728c65
well-typed-lightbulbs/ocaml-esp32
lib2235.ml
module A2235 = A2235
null
https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/testsuite/tests/no-alias-deps/lib2235.ml
ocaml
module A2235 = A2235
c9b4c2d9c514cb600737dd49d02c485170684ec41654f4762b8db6571713031d
Kappa-Dev/KappaTools
replay.mli
(******************************************************************************) (* _ __ * The Kappa Language *) | |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF (* | ' / *********************************************************************) (* | . \ * This file is distributed under the terms of the *) (* |_|\_\ * GNU Lesser General Public License Version 3 *) (******************************************************************************) (** Utilities to make mixtures from traces *) type state = { graph : Edges.t; time : float; event : int; connected_components : Agent.SetMap.Set.t Mods.IntMap.t option; } type summary = { unary_distances : (int * int) option; } val init_state : with_connected_components:bool -> state val do_step : Signature.s -> state -> Trace.step -> state * summary * @return the new state and , if the step was an unary instance of a binary rule , the i d of the rule and the distance between its 2 connected patterns . binary rule, the id of the rule and the distance between its 2 connected patterns. *) val is_step_triggerable : state -> Trace.step -> bool (** determines whether or not a step can be applied from a given state. *) val is_step_triggerable_on_edges : Edges.t -> Trace.step -> bool * same function but takes a graph of type Edges.t directly . val tests_pass_on : Edges.t -> Instantiation.concrete Instantiation.test list list -> bool (** exported for convenience. *) val cc_of_state : debugMode:bool -> state -> Pattern.PreEnv.t -> Pattern.PreEnv.t * ((int*int) list * Pattern.cc * Pattern.id) list
null
https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/core/simulation/replay.mli
ocaml
**************************************************************************** _ __ * The Kappa Language | ' / ******************************************************************** | . \ * This file is distributed under the terms of the |_|\_\ * GNU Lesser General Public License Version 3 **************************************************************************** * Utilities to make mixtures from traces * determines whether or not a step can be applied from a given state. * exported for convenience.
| |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF type state = { graph : Edges.t; time : float; event : int; connected_components : Agent.SetMap.Set.t Mods.IntMap.t option; } type summary = { unary_distances : (int * int) option; } val init_state : with_connected_components:bool -> state val do_step : Signature.s -> state -> Trace.step -> state * summary * @return the new state and , if the step was an unary instance of a binary rule , the i d of the rule and the distance between its 2 connected patterns . binary rule, the id of the rule and the distance between its 2 connected patterns. *) val is_step_triggerable : state -> Trace.step -> bool val is_step_triggerable_on_edges : Edges.t -> Trace.step -> bool * same function but takes a graph of type Edges.t directly . val tests_pass_on : Edges.t -> Instantiation.concrete Instantiation.test list list -> bool val cc_of_state : debugMode:bool -> state -> Pattern.PreEnv.t -> Pattern.PreEnv.t * ((int*int) list * Pattern.cc * Pattern.id) list
47c5cf2bc7fe615e598996e34f4e7d61418160d43cfed0bc690475c844730bc3
paurkedal/batyr
caching.ml
Copyright ( C ) 2013 - -2022 Petter A. Urkedal < > * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. *) let section = Lwt_log.Section.make "batyr.cache" let cache_hertz = Int64.to_float ExtUnix.Specific.(sysconf CLK_TCK) let cache_second = 1.0 /. cache_hertz let cache_metric = let current_time () = let tms = Unix.times () in Unix.(tms.tms_utime +. tms.tms_stime) in let current_memory_pressure = 1 GHz / 1 Gword let report cs = let open Prime_cache_metric in Lwt_log.ign_debug_f ~section "Beacon collection: time = %g; p = %g; n_live = %d; n_dead = %d" cs.cs_time cs.cs_memory_pressure cs.cs_live_count cs.cs_dead_count in Prime_cache_metric.create ~current_time ~current_memory_pressure ~report () module Beacon = Prime_beacon.Make (struct let cache_metric = cache_metric end) module Grade = struct let basic = 1e-3 *. cache_second let basic_reduce n = basic *. float_of_int (n + 1) let from_size_and_cost size cost = basic +. float_of_int cost /. float_of_int (size + Beacon.overhead) end module type HASHABLE_WITH_BEACON = sig type t val equal : t -> t -> bool val hash : t -> int val beacon : t -> Beacon.t end module type HASHED_CACHE = sig type data type t val create : int -> t val add : t -> data -> unit val remove : t -> data -> unit val merge : t -> data -> data val find : t -> data -> data val mem : t -> data -> bool val card : t -> int val iter : (data -> unit) -> t -> unit val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a end module Cache_of_hashable (X : HASHABLE_WITH_BEACON) = struct include Weak.Make (X) let charge x = Beacon.charge (X.beacon x) let charged x = charge x; x let add ws x = if not (mem ws x) then (charge x; add ws x) let merge ws x = charged (merge ws x) let find ws x = charged (find ws x) let card = count end module type BIJECTION_WITH_BEACON = sig type domain type codomain val f : domain -> codomain val f_inv : codomain -> domain val beacon : domain -> Beacon.t end module type BIJECTION_CACHE = sig include HASHED_CACHE type key val merge_key : t -> key -> data val find_key : t -> key -> data val mem_key : t -> key -> bool end module Cache_of_bijection (X : BIJECTION_WITH_BEACON) = struct include Weak.Make (struct type t = X.domain let equal x0 x1 = X.f x0 = X.f x1 let hash x = Hashtbl.hash (X.f x) end) type key = X.codomain let charge x = Beacon.charge (X.beacon x) let charged x = charge x; x let add ws x = if not (mem ws x) then (charge x; add ws x) let merge ws x = charged (merge ws x) let merge_key ws y = merge ws (X.f_inv y) let find ws x = charged (find ws x) let find_key ws y = find ws (X.f_inv y) let mem_key ws y = mem ws (X.f_inv y) let card = count end module Cache_of_physical_bijection (X : BIJECTION_WITH_BEACON) = struct include Weak.Make (struct type t = X.domain let equal x0 x1 = X.f x0 == X.f x1 let hash x = Hashtbl.hash (X.f x) end) type key = X.codomain let charge x = Beacon.charge (X.beacon x) let charged x = charge x; x let add ws x = if not (mem ws x) then (charge x; add ws x) let merge ws x = charged (merge ws x) let merge_key ws y = merge ws (X.f_inv y) let find ws x = charged (find ws x) let find_key ws y = find ws (X.f_inv y) let mem_key ws y = mem ws (X.f_inv y) let card = count end
null
https://raw.githubusercontent.com/paurkedal/batyr/814791b6ce6476b79ecddc12b7d28fa4d23dc591/batyr-core/lib/caching.ml
ocaml
Copyright ( C ) 2013 - -2022 Petter A. Urkedal < > * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. *) let section = Lwt_log.Section.make "batyr.cache" let cache_hertz = Int64.to_float ExtUnix.Specific.(sysconf CLK_TCK) let cache_second = 1.0 /. cache_hertz let cache_metric = let current_time () = let tms = Unix.times () in Unix.(tms.tms_utime +. tms.tms_stime) in let current_memory_pressure = 1 GHz / 1 Gword let report cs = let open Prime_cache_metric in Lwt_log.ign_debug_f ~section "Beacon collection: time = %g; p = %g; n_live = %d; n_dead = %d" cs.cs_time cs.cs_memory_pressure cs.cs_live_count cs.cs_dead_count in Prime_cache_metric.create ~current_time ~current_memory_pressure ~report () module Beacon = Prime_beacon.Make (struct let cache_metric = cache_metric end) module Grade = struct let basic = 1e-3 *. cache_second let basic_reduce n = basic *. float_of_int (n + 1) let from_size_and_cost size cost = basic +. float_of_int cost /. float_of_int (size + Beacon.overhead) end module type HASHABLE_WITH_BEACON = sig type t val equal : t -> t -> bool val hash : t -> int val beacon : t -> Beacon.t end module type HASHED_CACHE = sig type data type t val create : int -> t val add : t -> data -> unit val remove : t -> data -> unit val merge : t -> data -> data val find : t -> data -> data val mem : t -> data -> bool val card : t -> int val iter : (data -> unit) -> t -> unit val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a end module Cache_of_hashable (X : HASHABLE_WITH_BEACON) = struct include Weak.Make (X) let charge x = Beacon.charge (X.beacon x) let charged x = charge x; x let add ws x = if not (mem ws x) then (charge x; add ws x) let merge ws x = charged (merge ws x) let find ws x = charged (find ws x) let card = count end module type BIJECTION_WITH_BEACON = sig type domain type codomain val f : domain -> codomain val f_inv : codomain -> domain val beacon : domain -> Beacon.t end module type BIJECTION_CACHE = sig include HASHED_CACHE type key val merge_key : t -> key -> data val find_key : t -> key -> data val mem_key : t -> key -> bool end module Cache_of_bijection (X : BIJECTION_WITH_BEACON) = struct include Weak.Make (struct type t = X.domain let equal x0 x1 = X.f x0 = X.f x1 let hash x = Hashtbl.hash (X.f x) end) type key = X.codomain let charge x = Beacon.charge (X.beacon x) let charged x = charge x; x let add ws x = if not (mem ws x) then (charge x; add ws x) let merge ws x = charged (merge ws x) let merge_key ws y = merge ws (X.f_inv y) let find ws x = charged (find ws x) let find_key ws y = find ws (X.f_inv y) let mem_key ws y = mem ws (X.f_inv y) let card = count end module Cache_of_physical_bijection (X : BIJECTION_WITH_BEACON) = struct include Weak.Make (struct type t = X.domain let equal x0 x1 = X.f x0 == X.f x1 let hash x = Hashtbl.hash (X.f x) end) type key = X.codomain let charge x = Beacon.charge (X.beacon x) let charged x = charge x; x let add ws x = if not (mem ws x) then (charge x; add ws x) let merge ws x = charged (merge ws x) let merge_key ws y = merge ws (X.f_inv y) let find ws x = charged (find ws x) let find_key ws y = find ws (X.f_inv y) let mem_key ws y = mem ws (X.f_inv y) let card = count end
9873ea4e3007a1b9b81bb183c2036665ef226e9a158f3c7db61a3f26dbf1d649
reagent-project/reagent
testreagent.cljs
(ns reagenttest.testreagent (:require [clojure.test :as t :refer-macros [is deftest testing]] [react :as react] [reagent.ratom :as rv :refer [reaction]] [reagent.debug :as debug :refer [dev?]] [reagent.core :as r] [reagent.dom :as rdom] [reagent.dom.client :as rdomc] [reagent.dom.server :as server] [reagent.impl.component :as comp] [reagent.impl.template :as tmpl] [reagenttest.utils :as u :refer [with-mounted-component as-string]] [clojure.string :as string] [goog.string :as gstr] [goog.object :as gobj] [prop-types :as prop-types])) (t/use-fixtures :once {:before (fn [] (set! rv/debug true)) :after (fn [] (set! rv/debug false))}) (u/deftest ^:dom really-simple-test (let [ran (r/atom 0) really-simple (fn [] (swap! ran inc) [:div "div in really-simple"])] (with-mounted-component [really-simple nil nil] (fn [c div] (is (= 1 @ran)) (is (= "div in really-simple" (.-innerText div))))))) (u/deftest ^:dom test-simple-callback (let [ran (r/atom 0) comp (r/create-class {:component-did-mount #(swap! ran inc) :render (fn [this] (let [props (r/props this)] (is (map? props)) (is (= props ((r/argv this) 1))) (is (= 1 (first (r/children this)))) (is (= 1 (count (r/children this)))) (swap! ran inc) [:div (str "hi " (:foo props) ".")]))})] (with-mounted-component [comp {:foo "you"} 1] (fn [C div] (swap! ran inc) (is (= "hi you." (.-innerText div))) (is (= 3 @ran)))))) (u/deftest ^:dom test-state-change (let [ran (r/atom 0) self (r/atom nil) comp (r/create-class {:get-initial-state (fn [] {:foo "initial"}) :reagent-render (fn [] (let [this (r/current-component)] (reset! self this) (swap! ran inc) [:div (str "hi " (:foo (r/state this)))]))})] (with-mounted-component [comp] (fn [C div] (swap! ran inc) (is (= "hi initial" (.-innerText div))) (r/replace-state @self {:foo "there"}) (r/state @self) (r/flush) (is (= "hi there" (.-innerText div))) (r/set-state @self {:foo "you"}) (r/flush) (is (= "hi you" (.-innerText div))))) (is (= 4 @ran)))) (u/deftest ^:dom test-ratom-change (let [compiler u/*test-compiler* ran (r/atom 0) runs (rv/running) val (r/atom 0) secval (r/atom 0) v1-ran (atom 0) v1 (reaction (swap! v1-ran inc) @val) comp (fn [] (swap! ran inc) [:div (str "val " @v1 " " @val " " @secval)])] (t/async done (u/with-mounted-component-async [comp] (fn [] (r/next-tick (fn [] (r/next-tick (fn [] (is (= runs (rv/running))) (is (= 2 @ran)) (done)))))) compiler (fn [C div done] (r/flush) (is (not= runs (rv/running))) (is (= "val 0 0 0" (.-innerText div))) (is (= 1 @ran)) (reset! secval 1) (reset! secval 0) (reset! val 1) (reset! val 2) (reset! val 1) (is (= 1 @ran)) (is (= 1 @v1-ran)) (r/flush) (is (= "val 1 1 0" (.-innerText div))) (is (= 2 @ran) "ran once more") (is (= 2 @v1-ran)) ;; should not be rendered (reset! val 1) (is (= 2 @v1-ran)) (r/flush) (is (= 2 @v1-ran)) (is (= "val 1 1 0" (.-innerText div))) (is (= 2 @ran) "did not run") (done)))))) (u/deftest ^:dom batched-update-test [] (let [ran (r/atom 0) v1 (r/atom 0) v2 (r/atom 0) c2 (fn [{val :val}] (swap! ran inc) (is (= val @v1)) [:div @v2]) c1 (fn [] (swap! ran inc) [:div @v1 [c2 {:val @v1}]])] (with-mounted-component [c1] (fn [c div] (r/flush) (is (= 2 @ran)) (swap! v2 inc) (is (= 2 @ran)) (r/flush) (is (= 3 @ran)) (swap! v1 inc) (r/flush) (is (= 5 @ran)) ;; TODO: Failing on optimized build ( swap ! v2 inc ) ( swap ! v1 inc ) ; (r/flush) ; (is (= 7 @ran)) ( swap ! v1 inc ) ( swap ! v1 inc ) ( swap ! v2 inc ) ; (r/flush) ; (is (= 9 @ran)) )))) (u/deftest ^:dom init-state-test (let [ran (r/atom 0) really-simple (fn [] (let [this (r/current-component)] (swap! ran inc) (r/set-state this {:foo "foobar"}) (fn [] [:div (str "this is " (:foo (r/state this)))])))] (with-mounted-component [really-simple nil nil] (fn [c div] (swap! ran inc) (is (= "this is foobar" (.-innerText div))))) (is (= 2 @ran)))) (u/deftest ^:dom should-update-test (let [parent-ran (r/atom 0) child-ran (r/atom 0) child-props (r/atom nil) f (fn []) f1 (fn []) child (fn [p] (swap! child-ran inc) [:div (:val p)]) parent (fn [] (swap! parent-ran inc) [:div "child-foo" [child @child-props]])] (with-mounted-component [parent nil nil] (fn [c div] (r/flush) (is (= 1 @child-ran)) (is (= "child-foo" (.-innerText div))) (reset! child-props {:style {:display :none}}) (r/flush) (is (= 2 @child-ran)) (reset! child-props {:style {:display :none}}) (r/flush) (is (= 2 @child-ran) "keyw is equal") (reset! child-props {:class :foo}) (r/flush) (r/flush) (is (= 3 @child-ran)) (reset! child-props {:class :foo}) (r/flush) (r/flush) (is (= 3 @child-ran)) (reset! child-props {:class 'foo}) (r/flush) (is (= 4 @child-ran) "symbols are different from keyw") (reset! child-props {:class 'foo}) (r/flush) (is (= 4 @child-ran) "symbols are equal") (reset! child-props {:style {:color 'red}}) (r/flush) (is (= 5 @child-ran)) (reset! child-props {:on-change (r/partial f)}) (r/flush) (is (= 6 @child-ran)) (reset! child-props {:on-change (r/partial f)}) (r/flush) (is (= 6 @child-ran)) (reset! child-props {:on-change (r/partial f1)}) (r/flush) (is (= 7 @child-ran)))))) (u/deftest ^:dom dirty-test (let [ran (r/atom 0) state (r/atom 0) really-simple (fn [] (swap! ran inc) (if (= 1 @state) (reset! state 3)) [:div (str "state=" @state)])] (with-mounted-component [really-simple nil nil] (fn [c div] (is (= 1 @ran)) (is (= "state=0" (.-innerText div))) (reset! state 1) (r/flush) (is (= 2 @ran)) (is (= "state=3" (.-innerText div))))) (is (= 2 @ran)))) (u/deftest to-string-test [] (let [comp (fn [props] [:div (str "i am " (:foo props))])] (is (= "<div>i am foobar</div>" (as-string [comp {:foo "foobar"}]))))) (u/deftest data-aria-test [] (is (= "<div data-foo=\"x\"></div>" (as-string [:div {:data-foo "x"}]))) (is (= "<div aria-labelledby=\"x\"></div>" (as-string [:div {:aria-labelledby "x"}]))) ;; Skip test: produces warning in new React ;; (is (not (re-find #"enctype" ;; (as-string [:div {"enc-type" "x"}]))) ;; "Strings are passed through to React.") FIXME : For some reason UMD module returns everything in ;; lowercase, and CommonJS with upper T (is (re-find #"enc[tT]ype" (as-string [:div {"encType" "x"}])) "Strings are passed through to React, and have to be camelcase.") (is (re-find #"enc[tT]ype" (as-string [:div {:enc-type "x"}])) "Strings are passed through to React, and have to be camelcase.")) (u/deftest dynamic-id-class [] (is (re-find #"id=.foo" (as-string [:div#foo {:class "bar"}]))) (is (= "<div class=\"foo bar\"></div>" (as-string [:div.foo {:class "bar"}]))) (is (= "<div class=\"foo bar\"></div>" (as-string [:div.foo.bar]))) (is (= "<div class=\"foo bar\"></div>" (as-string [:div.foo {:className "bar"}]))) (is (= "<div class=\"foo bar\"></div>" (as-string [:div {:className "foo bar"}]))) (is (re-find #"id=.foo" (as-string [:div#foo.foo.bar]))) (is (re-find #"class=.xxx bar" (as-string [:div#foo.xxx.bar]))) (is (re-find #"id=.foo" (as-string [:div.bar {:id "foo"}]))) (is (re-find #"id=.foo" (as-string [:div.bar.xxx {:id "foo"}]))) (is (= "<div id=\"foo\"></div>" (as-string [:div#bar {:id "foo"}])) "Dynamic id overwrites static")) (defmulti my-div :type) (defmethod my-div :fooish [child] [:div.foo (:content child)]) (defmethod my-div :barish [child] [:div.bar (:content child)]) (u/deftest ifn-component [] (let [comp {:foo [:div "foodiv"] :bar [:div "bardiv"]}] (is (= "<div><div>foodiv</div></div>" (as-string [:div [comp :foo]]))) (is (= "<div><div>bardiv</div></div>" (as-string [:div [comp :bar]]))) (is (= "<div class=\"foo\">inner</div>" (as-string [my-div {:type :fooish :content "inner"}]))))) (u/deftest symbol-string-tag [] (is (= "<div>foobar</div>" (as-string ['div "foobar"]))) (is (= "<div>foobar</div>" (as-string ["div" "foobar"]))) (is (= "<div id=\"foo\">x</div>" (as-string ['div#foo "x"]))) (is (= "<div id=\"foo\">x</div>" (as-string ["div#foo" "x"]))) (is (= "<div class=\"foo bar\"></div>" (as-string ['div.foo {:class "bar"}]))) (is (= "<div class=\"foo bar\"></div>" (as-string ["div.foo.bar"]))) (is (re-find #"id=.foo" (as-string ['div#foo.foo.bar])))) (deftest partial-test [] (let [p1 (r/partial vector 1 2)] (is (= [1 2 3] (p1 3))) (is (= p1 (r/partial vector 1 2))) (is (ifn? p1)) (is (= (r/partial vector 1 2) p1)) (is (not= p1 (r/partial vector 1 3))) (is (= (hash p1) (hash (r/partial vector 1 2)))))) (u/deftest test-null-component (let [null-comp (fn [do-show] (when do-show [:div "div in test-null-component"]))] (is (= "" (as-string [null-comp false]))) (is (= "<div>div in test-null-component</div>" (as-string [null-comp true]))))) (u/deftest test-string (is (= "<div>foo</div>" (server/render-to-string [:div "foo"] u/*test-compiler*))) (is (= "<div><p>foo</p></div>" (server/render-to-string [:div [:p "foo"]] u/*test-compiler*)))) (u/deftest test-static-markup (is (= "<div>foo</div>" (as-string [:div "foo"]))) (is (= "<div class=\"bar\"><p>foo</p></div>" (as-string [:div.bar [:p "foo"]]))) (is (= "<div class=\"bar\"><p>foobar</p></div>" (as-string [:div.bar {:dangerously-set-inner-HTML {:__html "<p>foobar</p>"}}])))) (u/deftest ^:dom test-return-class (let [ran (r/atom 0) top-ran (r/atom 0) comp (fn [] (swap! top-ran inc) (r/create-class {:component-did-mount #(swap! ran inc) :render (fn [this] (let [props (r/props this)] (is (map? props)) (is (= props ((r/argv this) 1))) (is (= 1 (first (r/children this)))) (is (= 1 (count (r/children this)))) (swap! ran inc) [:div (str "hi " (:foo props) ".")]))})) prop (r/atom {:foo "you"}) parent (fn [] [comp @prop 1])] (with-mounted-component [parent] (fn [C div] (swap! ran inc) (is (= "hi you." (.-innerText div))) (is (= 1 @top-ran)) (is (= 3 @ran)) (swap! prop assoc :foo "me") (r/flush) (is (= "hi me." (.-innerText div))) (is (= 1 @top-ran)) (is (= 4 @ran)))))) (u/deftest ^:dom test-return-class-fn (let [ran (r/atom 0) top-ran (r/atom 0) comp (fn [] (swap! top-ran inc) (r/create-class {:component-did-mount #(swap! ran inc) :reagent-render (fn [p a] (is (= 1 a)) (swap! ran inc) [:div (str "hi " (:foo p) ".")])})) prop (r/atom {:foo "you"}) parent (fn [] [comp @prop 1])] (with-mounted-component [parent] (fn [C div] (swap! ran inc) (is (= "hi you." (.-innerText div))) (is (= 1 @top-ran)) (is (= 3 @ran)) (swap! prop assoc :foo "me") (r/flush) (is (= "hi me." (.-innerText div))) (is (= 1 @top-ran)) (is (= 4 @ran)))))) (u/deftest test-create-element (let [ae r/as-element ce r/create-element rstr #(as-string %)] (is (= (rstr (ce "div")) (rstr (ae [:div])))) (is (= (rstr (ce "div" nil)) (rstr (ae [:div])))) (is (= (rstr (ce "div" nil "foo")) (rstr (ae [:div "foo"])))) (is (= (rstr (ce "div" nil "foo" "bar")) (rstr (ae [:div "foo" "bar"])))) (is (= (rstr (ce "div" nil "foo" "bar" "foobar")) (rstr (ae [:div "foo" "bar" "foobar"])))) (is (= (rstr (ce "div" #js{:className "foo"} "bar")) (rstr (ae [:div.foo "bar"])))) (is (= (rstr (ce "div" nil (ce "div" nil "foo"))) (rstr (ae [:div [:div "foo"]])))) (is (= (rstr (ce "div" nil (ae [:div "foo"]))) (rstr (ae [:div [:div "foo"]])))) (is (= (rstr (ae [:div (ce "div" nil "foo")])) (rstr (ae [:div [:div "foo"]])))))) (def ndiv (let [cmp (fn [])] (gobj/extend (.-prototype cmp) (.-prototype react/Component) #js {:render (fn [] (this-as this (r/create-element "div" #js {:className (.. this -props -className)} (.. this -props -children))))}) (gobj/extend cmp react/Component) cmp)) (u/deftest test-adapt-class (let [d1 (r/adapt-react-class ndiv) d2 (r/adapt-react-class "div") rstr #(as-string %)] (is (= (rstr [:div]) (rstr [d1]))) (is (= (rstr [:div "a"]) (rstr [d1 "a"]))) (is (= (rstr [:div "a" "b"]) (rstr [d1 "a" "b"]))) (is (= (rstr [:div.foo "a"]) (rstr [d1 {:class "foo"} "a"]))) (is (= (rstr [:div "a" "b" [:div "c"]]) (rstr [d1 "a" "b" [:div "c"]]))) (is (= (rstr [:div]) (rstr [d2]))) (is (= (rstr [:div "a"]) (rstr [d2 "a"]))) (is (= (rstr [:div "a" "b"]) (rstr [d2 "a" "b"]))) (is (= (rstr [:div.foo "a"]) (rstr [d2 {:class "foo"} "a"]))) (is (= (rstr [:div "a" "b" [:div "c"]]) (rstr [d2 "a" "b" [:div "c"]]))))) (u/deftest test-adapt-class-2 (let [d1 ndiv d2 "div" rstr #(as-string %)] (is (= (rstr [:div]) (rstr [:> d1]))) (is (= (rstr [:div "a"]) (rstr [:> d1 "a"]))) (is (= (rstr [:div "a" "b"]) (rstr [:> d1 "a" "b"]))) (is (= (rstr [:div.foo "a"]) (rstr [:> d1 {:class "foo"} "a"]))) (is (= (rstr [:div "a" "b" [:div "c"]]) (rstr [:> d1 "a" "b" [:div "c"]]))) (is (= (rstr [:div]) (rstr [:> d2]))) (is (= (rstr [:div "a"]) (rstr [:> d2 "a"]))) (is (= (rstr [:div "a" "b"]) (rstr [:> d2 "a" "b"]))) (is (= (rstr [:div.foo "a"]) (rstr [:> d2 {:class "foo"} "a"]))) (is (= (rstr [:div "a" "b" [:div "c"]]) (rstr [:> d2 "a" "b" [:div "c"]]))))) (deftest ^:dom create-element-shortcut-test (let [p (atom nil) comp (fn [props] (reset! p props) (r/as-element [:div "a" (.-children props)]))] (with-mounted-component [:r> comp #js {:foo {:bar "x"}} [:p "bar"]] (fn [c div] (is (= {:bar "x"} (gobj/get @p "foo"))) (is (= "<div>a<p>bar</p></div>" (.-innerHTML div))))))) (deftest ^:dom shortcut-key-warning ;; TODO: Test create-element with key prop (let [w (debug/track-warnings #(with-mounted-component [:div (list [:> "div" {:key 1} "a"] [:> "div" {:key 2} "b"])] (fn [c div])))] (is (empty? (:warn w)))) (let [w (debug/track-warnings #(with-mounted-component [:div (list [:r> "div" #js {:key 1} "a"] [:r> "div" #js {:key 2} "b"])] (fn [c div])))] (is (empty? (:warn w)))) (let [f (fn [props c] [:div props c]) w (debug/track-warnings #(with-mounted-component [:div (list [:f> f {:key 1} "a"] [:f> f {:key 2} "b"])] (fn [c div])))] (is (empty? (:warn w))))) (u/deftest test-reactize-component (let [ae r/as-element ce r/create-element rstr #(as-string %) a (atom nil) c1r (fn reactize [p & args] (reset! a args) [:p "p:" (:a p) (:children p)]) c1 (r/reactify-component c1r u/*test-compiler*)] (is (= (rstr (ce c1 #js{:a "a"})) (rstr [:p "p:a"]))) (is (= nil @a)) (is (= (rstr (ce c1 #js{:a nil})) (rstr [:p "p:"]))) (is (= (rstr (ce c1 nil)) (rstr [:p "p:"]))) (is (= (rstr (ce c1 #js{:a "a"} (ae [:b "b"]))) (rstr [:p "p:a" [:b "b"]]))) (is (= nil @a)) (is (= (rstr (ce c1 #js{:a "a"} (ae [:b "b"]) (ae [:i "i"]))) (rstr [:p "p:a" [:b "b"] [:i "i"]]))) (is (= nil @a)))) (u/deftest ^:dom test-keys (let [a nil ;; (r/atom "a") c (fn key-tester [] [:div (for [i (range 3)] ^{:key i} [:p i (some-> a deref)]) (for [i (range 3)] [:p {:key i} i (some-> a deref)])]) w (debug/track-warnings #(with-mounted-component [c] (fn [c div])))] (is (empty? (:warn w)))) (testing "Check warning text can be produced even if hiccup contains function literals" (let [c (fn key-tester [] [:div (for [i (range 3)] ^{:key nil} [:button {:on-click #(js/console.log %)}])]) w (debug/track-warnings (u/wrap-capture-console-error #(with-mounted-component [c] (fn [c div]))))] (if (dev?) (is (re-find #"Warning: Every element in a seq should have a unique :key: \(\[:button \{:on-click #object\[Function\]\}\] \[:button \{:on-click #object\[Function\]\}\] \[:button \{:on-click #object\[Function\]\}\]\)\n \(in reagenttest.testreagent.key_tester\)" (first (:warn w)))))))) (u/deftest test-extended-syntax (is (= "<p><b>foo</b></p>" (as-string [:p>b "foo"]))) (is (= (as-string [:p.foo [:b "x"]]) (as-string [:p.foo>b "x"]))) (is (= (as-string [:div.foo [:p.bar.foo [:b.foobar "xy"]]]) (as-string [:div.foo>p.bar.foo>b.foobar "xy"]))) (is (= (as-string [:div.foo [:p.bar.foo [:b.foobar "xy"]]]) (as-string [:div.foo>p.bar.foo>b.foobar {} "xy"]))) (is (= (as-string [:div [:p.bar.foo [:a.foobar {:href "href"} "xy"]]]) (as-string [:div>p.bar.foo>a.foobar {:href "href"} "xy"])))) (deftest ^:dom extended-syntax-metadata (let [comp (fn [] [:div (for [k [1 2]] ^{:key k} [:div>div "a"])])] (with-mounted-component [comp] (fn [c div] ;; Just make sure this doesn't print a debug message )))) (u/deftest test-class-from-collection (is (= (as-string [:p {:class "a b c d"}]) (as-string [:p {:class ["a" "b" "c" "d"]}]))) (is (= (as-string [:p {:class "a b c"}]) (as-string [:p {:class ["a" nil "b" false "c" nil]}]))) (is (= (as-string [:p {:class "a b c"}]) (as-string [:p {:class '("a" "b" "c")}]))) (is (= (as-string [:p {:class "a b c"}]) (as-string [:p {:class #{"a" "b" "c"}}])))) (u/deftest class-different-types (testing "named values are supported" (is (= (as-string [:p {:class "a"}]) (as-string [:p {:class :a}]))) (is (= (as-string [:p {:class "a b"}]) (as-string [:p.a {:class :b}]))) (is (= (as-string [:p {:class "a b"}]) (as-string [:p.a {:class 'b}]))) (is (= (as-string [:p {:class "a b"}]) (as-string [:p {:class [:a :b]}]))) (is (= (as-string [:p {:class "a b"}]) (as-string [:p {:class ['a :b]}])))) (testing "non-named values like numbers" (is (= (as-string [:p {:class "1 b"}]) (as-string [:p {:class [1 :b]}])))) (testing "falsey values are filtered from collections" (is (= (as-string [:p {:class "a b"}]) (as-string [:p {:class [:a :b false nil]}]))))) ;; Class component only (deftest ^:dom test-force-update (let [v (atom {:v1 0 :v2 0}) comps (atom {}) c1 (fn [] (swap! comps assoc :c1 (r/current-component)) [:p "" (swap! v update-in [:v1] inc)]) c2 (fn [] (swap! comps assoc :c2 (r/current-component)) [:div "" (swap! v update-in [:v2] inc) [c1]]) state (r/atom 0) spy (r/atom 0) t (fn [] @state) t1 (fn [] @(r/track t)) c3 (fn [] (swap! comps assoc :c3 (r/current-component)) [:div "" (reset! spy @(r/track t1))])] (with-mounted-component [c2] (fn [c div] (is (= {:v1 1 :v2 1} @v)) (r/force-update (:c2 @comps)) (is (= {:v1 1 :v2 2} @v)) (r/force-update (:c1 @comps)) (is (= {:v1 2 :v2 2} @v)) (r/force-update (:c2 @comps) true) (is (= {:v1 3 :v2 3} @v)))) (with-mounted-component [c3] (fn [c] (is (= 0 @spy)) (swap! state inc) (is (= 0 @spy)) (r/force-update (:c3 @comps)) (is (= 1 @spy)))))) ;; Class component only (deftest ^:dom test-component-path (let [a (atom nil) tc (r/create-class {:display-name "atestcomponent" :render (fn [] (let [c (r/current-component)] (reset! a (comp/component-name c)) [:div]))})] (with-mounted-component [tc] (fn [c] (is (seq @a)) (is (re-find #"atestcomponent" @a) "component-path should work"))))) (u/deftest test-sorted-map-key (let [c1 (fn [map] [:div (map 1)]) c2 (fn [] [c1 (sorted-map 1 "foo" 2 "bar")])] (is (= "<div>foo</div>" (as-string [c2]))))) (u/deftest ^:dom basic-with-let (let [compiler u/*test-compiler* n1 (atom 0) n2 (atom 0) n3 (atom 0) val (r/atom 0) c (fn [] (r/with-let [v (swap! n1 inc)] (swap! n2 inc) [:div @val] (finally (swap! n3 inc))))] ;; With functional components, effect cleanup ( which calls dispose ) happens ;; async after unmount. (t/async done (u/with-mounted-component-async [c] (fn [] (r/next-tick (fn [] (r/next-tick (fn [] (is (= [1 2 1] [@n1 @n2 @n3])) (done)))))) compiler (fn [_ div done] (is (= [1 1 0] [@n1 @n2 @n3])) (swap! val inc) (is (= [1 1 0] [@n1 @n2 @n3])) (r/flush) (is (= [1 2 0] [@n1 @n2 @n3])) (done)))))) (u/deftest ^:dom with-let-destroy-only (let [compiler u/*test-compiler* n1 (atom 0) n2 (atom 0) c (fn [] (r/with-let [] (swap! n1 inc) [:div] (finally (swap! n2 inc))))] (t/async done (u/with-mounted-component-async [c] Wait 2 animation frames for useEffect cleanup to be called . (fn [] (r/next-tick (fn [] (r/next-tick (fn [] (is (= [1 1] [@n1 @n2])) (done)))))) compiler (fn [_ div done] (is (= [1 0] [@n1 @n2])) (done)))))) (u/deftest ^:dom with-let-arg (let [a (atom 0) s (r/atom "foo") f (fn [x] (r/with-let [] (reset! a x) [:div x])) c (fn [] (r/with-let [] [f @s]))] (with-mounted-component [c] (fn [_ div] (is (= "foo" @a)) (reset! s "bar") (r/flush) (is (= "bar" @a)))))) (u/deftest with-let-non-reactive (let [n1 (atom 0) n2 (atom 0) n3 (atom 0) c (fn [] (r/with-let [a (swap! n1 inc)] (swap! n2 inc) [:div a] (finally (swap! n3 inc))))] (is (= (as-string [c]) (as-string [:div 1]))) (is (= [1 1 1] [@n1 @n2 @n3])))) (u/deftest ^:dom lifecycle (let [n1 (atom 0) t (atom 0) res (atom {}) add-args (fn [key args] (swap! res assoc key {:at (swap! n1 inc) :args (vec args)})) render (fn [& args] (this-as c (is (= c (r/current-component)))) (add-args :render args) [:div "" (first args)]) render2 (fn [& args] (add-args :render args) [:div "" (first args)]) ls {:get-initial-state (fn [& args] (reset! t (first args)) (add-args :initial-state args) {:foo "bar"}) :UNSAFE_component-will-mount (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-mount args)) :component-did-mount (fn [& args] (this-as c (is (= c (first args)))) (add-args :did-mount args)) :should-component-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :should-update args) true) :UNSAFE_component-will-receive-props (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-receive args)) :UNSAFE_component-will-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-update args)) :component-did-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :did-update args)) :component-will-unmount (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-unmount args))} c1 (r/create-class (assoc ls :reagent-render render)) defarg ["a" "b"] arg (r/atom defarg) comp (atom c1) c2 (fn [] (apply vector @comp @arg)) cnative (fn [] (into [:> @comp] @arg)) check (fn [] (is (= {:at 1 :args [@t]} (:initial-state @res))) (is (= {:at 2 :args [@t]} (:will-mount @res))) (is (= {:at 3 :args ["a" "b"]} (:render @res))) (is (= {:at 4 :args [@t]} (:did-mount @res))) (reset! arg ["a" "c"]) (r/flush) (is (= {:at 5 :args [@t [@comp "a" "c"]]} (:will-receive @res))) (is (= {:at 6 :args [@t [@comp "a" "b"] [@comp "a" "c"]]} (:should-update @res))) (is (= {:at 7 :args [@t [@comp "a" "c"] {:foo "bar"}]} (:will-update @res))) (is (= {:at 8 :args ["a" "c"]} (:render @res))) (is (= {:at 9 :args [@t [@comp "a" "b"] {:foo "bar"} nil]} (:did-update @res))))] (with-mounted-component [c2] u/*test-compiler* check) (is (= {:at 10 :args [@t]} (:will-unmount @res))) (reset! comp (with-meta render2 ls)) (reset! arg defarg) (reset! n1 0) (with-mounted-component [c2] nil check) (is (= {:at 10 :args [@t]} (:will-unmount @res))))) (u/deftest ^:dom lifecycle-native (let [n1 (atom 0) t (atom 0) res (atom {}) oldprops (atom nil) newprops (atom nil) add-args (fn [key args] (swap! res assoc key {:at (swap! n1 inc) :args (vec args)})) render (fn [& args] (this-as c (when @newprops (is (= (first args) @newprops)) (is (= (r/props c) @newprops))) (is (= c (r/current-component))) (is (= (first args) (r/props c))) (add-args :render {:children (r/children c)}) [:div "" (first args)])) ls {:get-initial-state (fn [& args] (reset! t (first args)) (reset! oldprops (-> args first r/props)) (add-args :initial-state args) {:foo "bar"}) :UNSAFE_component-will-mount (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-mount args)) :component-did-mount (fn [& args] (this-as c (is (= c (first args)))) (add-args :did-mount args)) :should-component-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :should-update args) true) :UNSAFE_component-will-receive-props (fn [& args] (reset! newprops (-> args second second)) (this-as c (is (= c (first args))) (add-args :will-receive (into [(dissoc (r/props c) :children)] (:children (r/props c)))))) :UNSAFE_component-will-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-update args)) :component-did-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :did-update args)) :component-will-unmount (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-unmount args))} c1 (r/create-class (assoc ls :reagent-render render)) defarg [{:foo "bar"} "a" "b"] arg (r/atom defarg) comp (atom c1) cnative (fn [] (into [:> @comp] @arg)) check (fn [] (is (= {:at 1 :args [@t]} (:initial-state @res))) (is (= {:at 2 :args [@t]} (:will-mount @res))) (is (= {:at 3 :args [[:children ["a" "b"]]]} (:render @res))) (is (= {:at 4 :args [@t]} (:did-mount @res))) (reset! arg [{:f "oo"} "a" "c"]) (r/flush) (is (= {:at 5 :args [{:foo "bar"} "a" "b"]} (:will-receive @res))) (let [a (:should-update @res) {at :at [this oldv newv] :args} a] (is (= 6 at)) (is (= 3 (count (:args a)))) (is (= (js->clj [@comp @oldprops]) (js->clj oldv))) (is (= [@comp @newprops] newv))) (let [a (:will-update @res) {at :at [this newv] :args} a] (is (= 7 at)) (is (= [@comp @newprops] newv))) (is (= {:at 8 :args [[:children ["a" "c"]]]} (:render @res))) (let [a (:did-update @res) {at :at [this oldv] :args} a] (is (= 9 at)) (is (= [@comp @oldprops] oldv))))] (with-mounted-component [cnative] check) (is (= {:at 10 :args [@t]} (:will-unmount @res))))) (defn foo [] [:div]) (u/deftest ^:dom test-err-messages (when (dev?) (is (thrown-with-msg? :default #"Hiccup form should not be empty: \[]" (as-string []))) (is (thrown-with-msg? :default #"Invalid Hiccup tag: \[:>div \[reagenttest.testreagent.foo]]" (as-string [:>div [foo]]))) (is (thrown-with-msg? :default #"Invalid Hiccup form: \[23]" (as-string [23]))) This used to be asserted by Reagent , but because it is hard to validate components , now we just trust React will validate elements . ; (is (thrown-with-msg? ; :default #"Expected React component in: \[:> \[:div]]" ; (rstr [:> [:div]]))) ;; This is from React.createElement ;; NOTE: browser-npm uses production cjs bundle for now which only shows ;; the minified error (debug/track-warnings (u/wrap-capture-console-error #(is (thrown-with-msg? :default #"(Element type is invalid:|Minified React error)" (as-string [:> [:div]]))))) (is (thrown-with-msg? :default #"Invalid tag: 'p.'" (as-string [:p.]))) (let [comp1 (fn comp1 [x] x) comp2 (fn comp2 [x] [comp1 x]) comp3 (fn comp3 [] (r/with-let [a (r/atom "foo")] [:div (for [i (range 0 1)] ^{:key i} [:p @a])])) comp4 (fn comp4 [] (for [i (range 0 1)] [:p "foo"])) nat (let [cmp (fn [])] (gobj/extend (.-prototype cmp) (.-prototype react/Component) #js {:render (fn [])}) (gobj/extend cmp react/Component) cmp) compiler u/*test-compiler* rend (fn [x] (with-mounted-component x compiler identity))] Error is orginally caused by , so only that is shown in the error (let [e (debug/track-warnings (u/wrap-capture-window-error (u/wrap-capture-console-error #(is (thrown-with-msg? :default #"Invalid tag: 'div.' \(in reagenttest.testreagent.comp1\)" (rend [comp2 [:div. "foo"]]))))))] (is (re-find #"The above error occurred in the <reagenttest\.testreagent\.comp1> component:" (first (:error e))))) (let [e (debug/track-warnings (u/wrap-capture-window-error (u/wrap-capture-console-error #(is (thrown-with-msg? :default #"Invalid tag: 'div.' \(in reagenttest.testreagent.comp1\)" (rend [comp1 [:div. "foo"]]))))))] (is (re-find #"The above error occurred in the <reagenttest\.testreagent\.comp1> component:" (first (:error e))))) (let [e (debug/track-warnings #(r/as-element [nat] compiler))] (is (re-find #"Using native React classes directly" (-> e :warn first)))) (let [e (debug/track-warnings #(rend [comp3]))] (is (re-find #"Reactive deref not supported" (-> e :warn first)))) (let [e (debug/track-warnings #(r/as-element (comp4) compiler))] (is (re-find #"Every element in a seq should have a unique :key" (-> e :warn first))))))) (u/deftest ^:dom test-error-boundary (let [error (r/atom nil) info (r/atom nil) error-boundary (fn error-boundary [comp] (r/create-class {:component-did-catch (fn [this e i] (reset! info i)) :get-derived-state-from-error (fn [e] (reset! error e) #js {}) :reagent-render (fn [comp] (if @error [:div "Something went wrong."] comp))})) comp1 (fn comp1 [] (throw (js/Error. "Test error"))) comp2 (fn comp2 [] [comp1])] (debug/track-warnings (u/wrap-capture-window-error (u/wrap-capture-console-error #(with-mounted-component [error-boundary [comp2]] (fn [c div] (r/flush) (is (= "Test error" (.-message @error))) (is (re-find #"Something went wrong\." (.-innerHTML div))) (if (dev?) (is (re-find #"^\n at reagenttest.testreagent.comp1 \([^)]*\)\n at reagenttest.testreagent.comp2 \([^)]*\)\n at reagent[0-9]+ \([^)]*\)\n at reagenttest.testreagent.error_boundary \([^)]*\)" (.-componentStack ^js @info))) Names are completely manged on adv compilation (is (re-find #"^\n at .* \([^)]*\)\n at .* \([^)]*\)\n at .* \([^)]*\)\n at .+ \([^)]*\)" (.-componentStack ^js @info))))))))))) #_{:clj-kondo/ignore [:deprecated-var]} (u/deftest ^:dom test-dom-node (let [node (atom nil) ref (atom nil) comp (r/create-class {:reagent-render (fn test-dom [] [:div {:ref #(reset! ref %)} "foobar"]) :component-did-mount (fn [this] (reset! node (rdom/dom-node this)))})] (with-mounted-component [comp] (fn [c div] (is (= "foobar" (.-innerHTML @ref))) (is (= "foobar" (.-innerHTML @node))) (is (identical? @ref @node)))))) (u/deftest test-empty-input (is (= "<div><input/></div>" (as-string [:div [:input]])))) (u/deftest test-object-children (is (= "<p>foo bar1</p>" (as-string [:p 'foo " " :bar nil 1]))) (is (= "<p>#object[reagent.ratom.RAtom {:val 1}]</p>" (as-string [:p (r/atom 1)])))) (u/deftest ^:dom test-after-render (let [spy (atom 0) val (atom 0) exp (atom 0) node (atom nil) state (r/atom 0) comp (fn [] (let [old @spy] (r/after-render (fn [] (is (= "DIV" (.-tagName @node))) (swap! spy inc))) (is (= @spy old)) (is (= @exp @val)) [:div {:ref #(reset! node %)} @state]))] (with-mounted-component [comp] (fn [c div] (r/flush) (is (= 1 @spy)) (swap! state inc) (is (= 1 @spy)) (r/next-tick #(swap! val inc)) (reset! exp 1) (is (= 0 @val)) (r/flush) (is (= 1 @val)) (is (= 2 @spy)) ;; FIXME: c is nil because render call doesn't return anything ; (r/force-update c) ( is (= 3 ) ) ; (r/next-tick #(reset! spy 0)) ( is (= 3 ) ) ; (r/flush) ( is (= 0 ) ) )) (is (= nil @node)))) (u/deftest style-property-names-are-camel-cased (is (= "<div style=\"text-align:center\">foo</div>" (as-string [:div {:style {:text-align "center"}} "foo"])))) (u/deftest custom-element-class-prop (is (= "<custom-element class=\"foobar\">foo</custom-element>" (as-string [:custom-element {:class "foobar"} "foo"]))) (is (= "<custom-element class=\"foobar\">foo</custom-element>" (as-string [:custom-element.foobar "foo"])))) (u/deftest html-entities (testing "entity numbers can be unescaped always" (is (= "<i> </i>" (as-string [:i (gstr/unescapeEntities "&#160;")]))))) (u/deftest ^:dom html-entities-dom (testing "When DOM is available, all named entities can be unescaped" (is (= "<i> </i>" (as-string [:i (gstr/unescapeEntities "&nbsp;")]))))) (defn context-wrapper [] (r/create-class {:get-child-context (fn [] (this-as this #js {:foo "bar"})) :child-context-types #js {:foo prop-types/string.isRequired} :reagent-render (fn [child] [:div "parent," child])})) (defn context-child [] (r/create-class {:context-types #js {:foo prop-types/string.isRequired} :reagent-render (fn [] (let [this (r/current-component)] Context property name is not mangled , so need to use gobj / get to access property by string name ;; React extern handles context name. [:div "child," (gobj/get (.-context this) "foo")]))})) ;; Class component only (deftest ^:dom context-test (with-mounted-component [context-wrapper [context-child]] nil (fn [c div] (is (= "parent,child,bar" (.-innerText div)))))) (u/deftest test-fragments (testing "Fragment as array" (let [compiler u/*test-compiler* comp (fn comp1 [] #js [(r/as-element [:div "hello"] compiler) (r/as-element [:div "world"] compiler)])] (is (= "<div>hello</div><div>world</div>" (as-string [comp])))))) ;; In bundle version, the names aren't optimized. ;; In node module processed versions, names probably are optimized. (defonce my-context ^js/MyContext (react/createContext "default")) (def Provider (.-Provider my-context)) (def Consumer (.-Consumer my-context)) (u/deftest new-context-test (is (= "<div>Context: foo</div>" (as-string (r/create-element Provider #js {:value "foo"} (r/create-element Consumer #js {} (fn [v] (r/as-element [:div "Context: " v]))))))) (testing "context default value works" (is (= "<div>Context: default</div>" (as-string (r/create-element Consumer #js {} (fn [v] (r/as-element [:div "Context: " v]))))))) (testing "context works with adapt-react-class" (let [provider (r/adapt-react-class Provider) consumer (r/adapt-react-class Consumer)] (is (= "<div>Context: bar</div>" (as-string [provider {:value "bar"} [consumer {} (fn [v] (r/as-element [:div "Context: " v]))]]))))) (testing "context works with :>" (is (= "<div>Context: bar</div>" (as-string [:> Provider {:value "bar"} [:> Consumer {} (fn [v] (r/as-element [:div "Context: " v]))]])))) (testing "static contextType" (let [comp (r/create-class {:context-type my-context :reagent-render (fn [] (this-as this (r/as-element [:div "Context: " (.-context this)])))})] (is (= "<div>Context: default</div>" (as-string [comp]))))) (testing "useContext hook" (let [comp (fn [v] (let [v (react/useContext my-context)] [:div "Context: " v]))] (is (= "<div>Context: foo</div>" (as-string [:r> Provider #js {:value "foo"} [:f> comp]])))))) (u/deftest ^:dom on-failed-prop-comparison-in-should-update-swallow-exception-and-do-not-update-component (let [prop (r/atom {:todos 1}) component-was-updated (atom false) error-thrown-after-updating-props (atom false) component-class (r/create-class {:reagent-render (fn [& args] [:div (str (first args))]) :component-did-update (fn [& args] (reset! component-was-updated true))}) component (fn [] [component-class @prop])] (when (dev?) (let [e (debug/track-warnings #(with-mounted-component [component] (fn [c div] (reset! prop (sorted-map 1 2)) (try (r/flush) (catch :default e (reset! error-thrown-after-updating-props true))) (is (not @component-was-updated)) (is (not @error-thrown-after-updating-props)))))] (is (re-find #"Warning: Exception thrown while comparing argv's in shouldComponentUpdate:" (first (:warn e)))))))) (u/deftest ^:dom get-derived-state-from-props-test (let [prop (r/atom 0) ;; Usually one can use Cljs object as React state. However, getDerivedStateFromProps implementation in React uses ;; Object.assign to merge current state and partial state returned ;; from the method, so the state has to be plain old object. pure-component (r/create-class {:constructor (fn [this] (set! (.-state this) #js {})) :get-derived-state-from-props (fn [props state] ;; "Expensive" calculation based on the props #js {:v (string/join " " (repeat (inc (:value props)) "foo"))}) :render (fn [this] (r/as-element [:p "Value " (gobj/get (.-state this) "v")]))}) component (fn [] [pure-component {:value @prop}])] (with-mounted-component [component] (fn [c div] (is (= "Value foo" (.-innerText div))) (swap! prop inc) (r/flush) (is (= "Value foo foo" (.-innerText div))))))) (u/deftest ^:dom get-derived-state-from-error-test (let [prop (r/atom 0) component (r/create-class {:constructor (fn [this props] (set! (.-state this) #js {:hasError false})) :get-derived-state-from-error (fn [error] #js {:hasError true}) :component-did-catch (fn [this e info]) :render (fn [^js/React.Component this] (r/as-element (if (.-hasError (.-state this)) [:p "Error"] (into [:<>] (r/children this)))))}) bad-component (fn [] (if (= 0 @prop) [:div "Ok"] (throw (js/Error. "foo"))))] (u/wrap-capture-window-error (u/wrap-capture-console-error #(with-mounted-component [component [bad-component]] (fn [c div] (is (= "Ok" (.-innerText div))) (swap! prop inc) (r/flush) (is (= "Error" (.-innerText div))))))))) (u/deftest ^:dom get-snapshot-before-update-test (let [ref (react/createRef) prop (r/atom 0) did-update (atom nil) component (r/create-class {:get-snapshot-before-update (fn [this [_ prev-props] prev-state] {:height (.. ref -current -scrollHeight)}) :component-did-update (fn [this [_ prev-props] prev-state snapshot] (reset! did-update snapshot)) :render (fn [this] (r/as-element [:div {:ref ref :style {:height "20px"}} "foo"]))}) component-2 (fn [] [component {:value @prop}])] (with-mounted-component [component-2] (fn [c div] Attach to DOM to get real height value (.appendChild js/document.body div) (is (= "foo" (.-innerText div))) (swap! prop inc) (r/flush) (is (= {:height 20} @did-update)) (.removeChild js/document.body div))))) (u/deftest ^:dom issue-462-test (let [val (r/atom 0) render (atom 0) a (fn issue-462-a [nr] (swap! render inc) [:h1 "Value " nr]) b (fn issue-462-b [] [:div ^{:key @val} [a @val]]) c (fn issue-462-c [] ^{:key @val} [b])] (with-mounted-component [c] (fn [c div] (is (= 1 @render)) (reset! val 1) (r/flush) (is (= 2 @render)) (reset! val 0) (r/flush) (is (= 3 @render)))))) (deftest ^:dom functional-component-poc-simple (let [c (fn [x] [:span "Hello " x])] (testing ":f>" (with-mounted-component [:f> c "foo"] u/class-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Hello foo" (.-innerText div)))))) (testing "compiler options" (with-mounted-component [c "foo"] u/fn-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Hello foo" (.-innerText div)))))) (testing "setting default compiler" (try (r/set-default-compiler! u/fn-compiler) (with-mounted-component [c "foo"] nil (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Hello foo" (.-innerText div))))) (finally (r/set-default-compiler! nil)))))) (deftest ^:dom functional-component-poc-state-hook (let [;; Probably not the best idea to keep ;; refernce to state hook update fn, but ;; works for testing. set-count! (atom nil) c (fn [x] (let [[c set-count] (react/useState x)] (reset! set-count! set-count) [:span "Count " c]))] (with-mounted-component [c 5] u/fn-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Count 5" (.-innerText div))) (@set-count! 6) (is (= "Count 6" (.-innerText div))))))) (deftest ^:dom functional-component-poc-ratom (let [count (r/atom 5) c (fn [x] [:span "Count " @count])] (with-mounted-component [c 5] u/fn-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Count 5" (.-innerText div))) (reset! count 6) (r/flush) (is (= "Count 6" (.-innerText div))) TODO : Test that component RAtom is disposed )))) (deftest ^:dom functional-component-poc-ratom-state-hook (let [r-count (r/atom 3) set-count! (atom nil) c (fn [x] (let [[c set-count] (react/useState x)] (reset! set-count! set-count) [:span "Counts " @r-count " " c]))] (with-mounted-component [c 15] u/fn-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Counts 3 15" (.-innerText div))) (reset! r-count 6) (r/flush) (is (= "Counts 6 15" (.-innerText div))) (@set-count! 17) (is (= "Counts 6 17" (.-innerText div))) )))) (u/deftest ^:dom test-input-el-ref (let [ref-1 (atom nil) ref-1-fn #(reset! ref-1 %) ref-2 (react/createRef) c (fn [x] [:div [:input {:ref ref-1-fn :value nil :on-change (fn [_])}] [:input {:ref ref-2 :value nil :on-change (fn [_])}]])] (with-mounted-component [c] (fn [c div] (is (some? @ref-1)) (is (some? (.-current ref-2))) )))) (deftest test-element-key (is (= "0" (.-key (r/as-element [:div {:key 0}])))) (is (= "0" (.-key (r/as-element ^{:key 0} [:div])))) (is (= "0" (.-key (r/as-element [:input {:key 0}])))) (is (= "0" (.-key (r/as-element ^{:key 0} [:input])))) ) ;; Note: you still pretty much need to access the impl.template namespace to ;; implement your own parse-tag (defn parse-tag [hiccup-tag] (let [[tag id className] (->> hiccup-tag name (re-matches tmpl/re-tag) next) ;; For testing, prefix class names with foo_ className (when-not (nil? className) (->> (string/split className #"\.") (map (fn [s] (str "foo_" s))) (string/join " ")))] (assert tag (str "Invalid tag: '" hiccup-tag "'" (comp/comp-name))) (tmpl/->HiccupTag tag id className ;; Custom element names must contain hyphen ;; -elements/#custom-elements-core-concepts (not= -1 (.indexOf tag "-"))))) (def tag-name-cache #js {}) (defn cached-parse [this x _] (if-some [s (tmpl/cache-get tag-name-cache x)] s (let [v (parse-tag x)] (gobj/set tag-name-cache x v) v))) (deftest parse-tag-test (let [compiler (r/create-compiler {:parse-tag cached-parse})] (gobj/clear tag-name-cache) (is (= "<div class=\"foo_asd foo_xyz bar\"></div>" (server/render-to-static-markup [:div.asd.xyz {:class "bar"}] compiler))))) (deftest ^:dom react-18-test (when (>= (js/parseInt react/version) 18) (let [div (.createElement js/document "div") root (rdomc/create-root div) i (r/atom 0) ran (atom 0) test-wrap (fn [check-fn el] (react/useEffect (fn [] (check-fn) js/undefined) #js []) el) really-simple (fn [] (swap! ran inc) [:div "foo " @i])] (u/async ;; TODO: Create helper to render to div and check after initial render ;; is done. (js/Promise. (fn [resolve reject] (rdomc/render root [:f> test-wrap (fn [] (is (= "foo 0" (.-innerText div))) (is (= 1 @ran)) (swap! i inc) Wait for Reagent to flush ratom queue . (r/after-render (fn [] ;; NOTE: React act isn't usable as it isn't available on production bundles. ;; Wait 16ms, this is probably enough for ;; React to render the results. (js/setTimeout (fn [] (is (= "foo 1" (.-innerText div))) (is (= 2 @ran)) (resolve)) 16)))) [really-simple]] u/fn-compiler)))))))
null
https://raw.githubusercontent.com/reagent-project/reagent/ce80585e9aebe0a6df09bda1530773aa512f6103/test/reagenttest/testreagent.cljs
clojure
should not be rendered TODO: Failing on optimized build (r/flush) (is (= 7 @ran)) (r/flush) (is (= 9 @ran)) Skip test: produces warning in new React (is (not (re-find #"enctype" (as-string [:div {"enc-type" "x"}]))) "Strings are passed through to React.") lowercase, and CommonJS with upper T TODO: Test create-element with key prop (r/atom "a") Just make sure this doesn't print a debug message Class component only Class component only With functional components, async after unmount. (is (thrown-with-msg? :default #"Expected React component in: \[:> \[:div]]" (rstr [:> [:div]]))) This is from React.createElement NOTE: browser-npm uses production cjs bundle for now which only shows the minified error FIXME: c is nil because render call doesn't return anything (r/force-update c) (r/next-tick #(reset! spy 0)) (r/flush) React extern handles context name. Class component only In bundle version, the names aren't optimized. In node module processed versions, names probably are optimized. Usually one can use Cljs object as React state. However, Object.assign to merge current state and partial state returned from the method, so the state has to be plain old object. "Expensive" calculation based on the props Probably not the best idea to keep refernce to state hook update fn, but works for testing. Note: you still pretty much need to access the impl.template namespace to implement your own parse-tag For testing, prefix class names with foo_ Custom element names must contain hyphen -elements/#custom-elements-core-concepts TODO: Create helper to render to div and check after initial render is done. NOTE: React act isn't usable as it isn't available on production bundles. Wait 16ms, this is probably enough for React to render the results.
(ns reagenttest.testreagent (:require [clojure.test :as t :refer-macros [is deftest testing]] [react :as react] [reagent.ratom :as rv :refer [reaction]] [reagent.debug :as debug :refer [dev?]] [reagent.core :as r] [reagent.dom :as rdom] [reagent.dom.client :as rdomc] [reagent.dom.server :as server] [reagent.impl.component :as comp] [reagent.impl.template :as tmpl] [reagenttest.utils :as u :refer [with-mounted-component as-string]] [clojure.string :as string] [goog.string :as gstr] [goog.object :as gobj] [prop-types :as prop-types])) (t/use-fixtures :once {:before (fn [] (set! rv/debug true)) :after (fn [] (set! rv/debug false))}) (u/deftest ^:dom really-simple-test (let [ran (r/atom 0) really-simple (fn [] (swap! ran inc) [:div "div in really-simple"])] (with-mounted-component [really-simple nil nil] (fn [c div] (is (= 1 @ran)) (is (= "div in really-simple" (.-innerText div))))))) (u/deftest ^:dom test-simple-callback (let [ran (r/atom 0) comp (r/create-class {:component-did-mount #(swap! ran inc) :render (fn [this] (let [props (r/props this)] (is (map? props)) (is (= props ((r/argv this) 1))) (is (= 1 (first (r/children this)))) (is (= 1 (count (r/children this)))) (swap! ran inc) [:div (str "hi " (:foo props) ".")]))})] (with-mounted-component [comp {:foo "you"} 1] (fn [C div] (swap! ran inc) (is (= "hi you." (.-innerText div))) (is (= 3 @ran)))))) (u/deftest ^:dom test-state-change (let [ran (r/atom 0) self (r/atom nil) comp (r/create-class {:get-initial-state (fn [] {:foo "initial"}) :reagent-render (fn [] (let [this (r/current-component)] (reset! self this) (swap! ran inc) [:div (str "hi " (:foo (r/state this)))]))})] (with-mounted-component [comp] (fn [C div] (swap! ran inc) (is (= "hi initial" (.-innerText div))) (r/replace-state @self {:foo "there"}) (r/state @self) (r/flush) (is (= "hi there" (.-innerText div))) (r/set-state @self {:foo "you"}) (r/flush) (is (= "hi you" (.-innerText div))))) (is (= 4 @ran)))) (u/deftest ^:dom test-ratom-change (let [compiler u/*test-compiler* ran (r/atom 0) runs (rv/running) val (r/atom 0) secval (r/atom 0) v1-ran (atom 0) v1 (reaction (swap! v1-ran inc) @val) comp (fn [] (swap! ran inc) [:div (str "val " @v1 " " @val " " @secval)])] (t/async done (u/with-mounted-component-async [comp] (fn [] (r/next-tick (fn [] (r/next-tick (fn [] (is (= runs (rv/running))) (is (= 2 @ran)) (done)))))) compiler (fn [C div done] (r/flush) (is (not= runs (rv/running))) (is (= "val 0 0 0" (.-innerText div))) (is (= 1 @ran)) (reset! secval 1) (reset! secval 0) (reset! val 1) (reset! val 2) (reset! val 1) (is (= 1 @ran)) (is (= 1 @v1-ran)) (r/flush) (is (= "val 1 1 0" (.-innerText div))) (is (= 2 @ran) "ran once more") (is (= 2 @v1-ran)) (reset! val 1) (is (= 2 @v1-ran)) (r/flush) (is (= 2 @v1-ran)) (is (= "val 1 1 0" (.-innerText div))) (is (= 2 @ran) "did not run") (done)))))) (u/deftest ^:dom batched-update-test [] (let [ran (r/atom 0) v1 (r/atom 0) v2 (r/atom 0) c2 (fn [{val :val}] (swap! ran inc) (is (= val @v1)) [:div @v2]) c1 (fn [] (swap! ran inc) [:div @v1 [c2 {:val @v1}]])] (with-mounted-component [c1] (fn [c div] (r/flush) (is (= 2 @ran)) (swap! v2 inc) (is (= 2 @ran)) (r/flush) (is (= 3 @ran)) (swap! v1 inc) (r/flush) (is (= 5 @ran)) ( swap ! v2 inc ) ( swap ! v1 inc ) ( swap ! v1 inc ) ( swap ! v1 inc ) ( swap ! v2 inc ) )))) (u/deftest ^:dom init-state-test (let [ran (r/atom 0) really-simple (fn [] (let [this (r/current-component)] (swap! ran inc) (r/set-state this {:foo "foobar"}) (fn [] [:div (str "this is " (:foo (r/state this)))])))] (with-mounted-component [really-simple nil nil] (fn [c div] (swap! ran inc) (is (= "this is foobar" (.-innerText div))))) (is (= 2 @ran)))) (u/deftest ^:dom should-update-test (let [parent-ran (r/atom 0) child-ran (r/atom 0) child-props (r/atom nil) f (fn []) f1 (fn []) child (fn [p] (swap! child-ran inc) [:div (:val p)]) parent (fn [] (swap! parent-ran inc) [:div "child-foo" [child @child-props]])] (with-mounted-component [parent nil nil] (fn [c div] (r/flush) (is (= 1 @child-ran)) (is (= "child-foo" (.-innerText div))) (reset! child-props {:style {:display :none}}) (r/flush) (is (= 2 @child-ran)) (reset! child-props {:style {:display :none}}) (r/flush) (is (= 2 @child-ran) "keyw is equal") (reset! child-props {:class :foo}) (r/flush) (r/flush) (is (= 3 @child-ran)) (reset! child-props {:class :foo}) (r/flush) (r/flush) (is (= 3 @child-ran)) (reset! child-props {:class 'foo}) (r/flush) (is (= 4 @child-ran) "symbols are different from keyw") (reset! child-props {:class 'foo}) (r/flush) (is (= 4 @child-ran) "symbols are equal") (reset! child-props {:style {:color 'red}}) (r/flush) (is (= 5 @child-ran)) (reset! child-props {:on-change (r/partial f)}) (r/flush) (is (= 6 @child-ran)) (reset! child-props {:on-change (r/partial f)}) (r/flush) (is (= 6 @child-ran)) (reset! child-props {:on-change (r/partial f1)}) (r/flush) (is (= 7 @child-ran)))))) (u/deftest ^:dom dirty-test (let [ran (r/atom 0) state (r/atom 0) really-simple (fn [] (swap! ran inc) (if (= 1 @state) (reset! state 3)) [:div (str "state=" @state)])] (with-mounted-component [really-simple nil nil] (fn [c div] (is (= 1 @ran)) (is (= "state=0" (.-innerText div))) (reset! state 1) (r/flush) (is (= 2 @ran)) (is (= "state=3" (.-innerText div))))) (is (= 2 @ran)))) (u/deftest to-string-test [] (let [comp (fn [props] [:div (str "i am " (:foo props))])] (is (= "<div>i am foobar</div>" (as-string [comp {:foo "foobar"}]))))) (u/deftest data-aria-test [] (is (= "<div data-foo=\"x\"></div>" (as-string [:div {:data-foo "x"}]))) (is (= "<div aria-labelledby=\"x\"></div>" (as-string [:div {:aria-labelledby "x"}]))) FIXME : For some reason UMD module returns everything in (is (re-find #"enc[tT]ype" (as-string [:div {"encType" "x"}])) "Strings are passed through to React, and have to be camelcase.") (is (re-find #"enc[tT]ype" (as-string [:div {:enc-type "x"}])) "Strings are passed through to React, and have to be camelcase.")) (u/deftest dynamic-id-class [] (is (re-find #"id=.foo" (as-string [:div#foo {:class "bar"}]))) (is (= "<div class=\"foo bar\"></div>" (as-string [:div.foo {:class "bar"}]))) (is (= "<div class=\"foo bar\"></div>" (as-string [:div.foo.bar]))) (is (= "<div class=\"foo bar\"></div>" (as-string [:div.foo {:className "bar"}]))) (is (= "<div class=\"foo bar\"></div>" (as-string [:div {:className "foo bar"}]))) (is (re-find #"id=.foo" (as-string [:div#foo.foo.bar]))) (is (re-find #"class=.xxx bar" (as-string [:div#foo.xxx.bar]))) (is (re-find #"id=.foo" (as-string [:div.bar {:id "foo"}]))) (is (re-find #"id=.foo" (as-string [:div.bar.xxx {:id "foo"}]))) (is (= "<div id=\"foo\"></div>" (as-string [:div#bar {:id "foo"}])) "Dynamic id overwrites static")) (defmulti my-div :type) (defmethod my-div :fooish [child] [:div.foo (:content child)]) (defmethod my-div :barish [child] [:div.bar (:content child)]) (u/deftest ifn-component [] (let [comp {:foo [:div "foodiv"] :bar [:div "bardiv"]}] (is (= "<div><div>foodiv</div></div>" (as-string [:div [comp :foo]]))) (is (= "<div><div>bardiv</div></div>" (as-string [:div [comp :bar]]))) (is (= "<div class=\"foo\">inner</div>" (as-string [my-div {:type :fooish :content "inner"}]))))) (u/deftest symbol-string-tag [] (is (= "<div>foobar</div>" (as-string ['div "foobar"]))) (is (= "<div>foobar</div>" (as-string ["div" "foobar"]))) (is (= "<div id=\"foo\">x</div>" (as-string ['div#foo "x"]))) (is (= "<div id=\"foo\">x</div>" (as-string ["div#foo" "x"]))) (is (= "<div class=\"foo bar\"></div>" (as-string ['div.foo {:class "bar"}]))) (is (= "<div class=\"foo bar\"></div>" (as-string ["div.foo.bar"]))) (is (re-find #"id=.foo" (as-string ['div#foo.foo.bar])))) (deftest partial-test [] (let [p1 (r/partial vector 1 2)] (is (= [1 2 3] (p1 3))) (is (= p1 (r/partial vector 1 2))) (is (ifn? p1)) (is (= (r/partial vector 1 2) p1)) (is (not= p1 (r/partial vector 1 3))) (is (= (hash p1) (hash (r/partial vector 1 2)))))) (u/deftest test-null-component (let [null-comp (fn [do-show] (when do-show [:div "div in test-null-component"]))] (is (= "" (as-string [null-comp false]))) (is (= "<div>div in test-null-component</div>" (as-string [null-comp true]))))) (u/deftest test-string (is (= "<div>foo</div>" (server/render-to-string [:div "foo"] u/*test-compiler*))) (is (= "<div><p>foo</p></div>" (server/render-to-string [:div [:p "foo"]] u/*test-compiler*)))) (u/deftest test-static-markup (is (= "<div>foo</div>" (as-string [:div "foo"]))) (is (= "<div class=\"bar\"><p>foo</p></div>" (as-string [:div.bar [:p "foo"]]))) (is (= "<div class=\"bar\"><p>foobar</p></div>" (as-string [:div.bar {:dangerously-set-inner-HTML {:__html "<p>foobar</p>"}}])))) (u/deftest ^:dom test-return-class (let [ran (r/atom 0) top-ran (r/atom 0) comp (fn [] (swap! top-ran inc) (r/create-class {:component-did-mount #(swap! ran inc) :render (fn [this] (let [props (r/props this)] (is (map? props)) (is (= props ((r/argv this) 1))) (is (= 1 (first (r/children this)))) (is (= 1 (count (r/children this)))) (swap! ran inc) [:div (str "hi " (:foo props) ".")]))})) prop (r/atom {:foo "you"}) parent (fn [] [comp @prop 1])] (with-mounted-component [parent] (fn [C div] (swap! ran inc) (is (= "hi you." (.-innerText div))) (is (= 1 @top-ran)) (is (= 3 @ran)) (swap! prop assoc :foo "me") (r/flush) (is (= "hi me." (.-innerText div))) (is (= 1 @top-ran)) (is (= 4 @ran)))))) (u/deftest ^:dom test-return-class-fn (let [ran (r/atom 0) top-ran (r/atom 0) comp (fn [] (swap! top-ran inc) (r/create-class {:component-did-mount #(swap! ran inc) :reagent-render (fn [p a] (is (= 1 a)) (swap! ran inc) [:div (str "hi " (:foo p) ".")])})) prop (r/atom {:foo "you"}) parent (fn [] [comp @prop 1])] (with-mounted-component [parent] (fn [C div] (swap! ran inc) (is (= "hi you." (.-innerText div))) (is (= 1 @top-ran)) (is (= 3 @ran)) (swap! prop assoc :foo "me") (r/flush) (is (= "hi me." (.-innerText div))) (is (= 1 @top-ran)) (is (= 4 @ran)))))) (u/deftest test-create-element (let [ae r/as-element ce r/create-element rstr #(as-string %)] (is (= (rstr (ce "div")) (rstr (ae [:div])))) (is (= (rstr (ce "div" nil)) (rstr (ae [:div])))) (is (= (rstr (ce "div" nil "foo")) (rstr (ae [:div "foo"])))) (is (= (rstr (ce "div" nil "foo" "bar")) (rstr (ae [:div "foo" "bar"])))) (is (= (rstr (ce "div" nil "foo" "bar" "foobar")) (rstr (ae [:div "foo" "bar" "foobar"])))) (is (= (rstr (ce "div" #js{:className "foo"} "bar")) (rstr (ae [:div.foo "bar"])))) (is (= (rstr (ce "div" nil (ce "div" nil "foo"))) (rstr (ae [:div [:div "foo"]])))) (is (= (rstr (ce "div" nil (ae [:div "foo"]))) (rstr (ae [:div [:div "foo"]])))) (is (= (rstr (ae [:div (ce "div" nil "foo")])) (rstr (ae [:div [:div "foo"]])))))) (def ndiv (let [cmp (fn [])] (gobj/extend (.-prototype cmp) (.-prototype react/Component) #js {:render (fn [] (this-as this (r/create-element "div" #js {:className (.. this -props -className)} (.. this -props -children))))}) (gobj/extend cmp react/Component) cmp)) (u/deftest test-adapt-class (let [d1 (r/adapt-react-class ndiv) d2 (r/adapt-react-class "div") rstr #(as-string %)] (is (= (rstr [:div]) (rstr [d1]))) (is (= (rstr [:div "a"]) (rstr [d1 "a"]))) (is (= (rstr [:div "a" "b"]) (rstr [d1 "a" "b"]))) (is (= (rstr [:div.foo "a"]) (rstr [d1 {:class "foo"} "a"]))) (is (= (rstr [:div "a" "b" [:div "c"]]) (rstr [d1 "a" "b" [:div "c"]]))) (is (= (rstr [:div]) (rstr [d2]))) (is (= (rstr [:div "a"]) (rstr [d2 "a"]))) (is (= (rstr [:div "a" "b"]) (rstr [d2 "a" "b"]))) (is (= (rstr [:div.foo "a"]) (rstr [d2 {:class "foo"} "a"]))) (is (= (rstr [:div "a" "b" [:div "c"]]) (rstr [d2 "a" "b" [:div "c"]]))))) (u/deftest test-adapt-class-2 (let [d1 ndiv d2 "div" rstr #(as-string %)] (is (= (rstr [:div]) (rstr [:> d1]))) (is (= (rstr [:div "a"]) (rstr [:> d1 "a"]))) (is (= (rstr [:div "a" "b"]) (rstr [:> d1 "a" "b"]))) (is (= (rstr [:div.foo "a"]) (rstr [:> d1 {:class "foo"} "a"]))) (is (= (rstr [:div "a" "b" [:div "c"]]) (rstr [:> d1 "a" "b" [:div "c"]]))) (is (= (rstr [:div]) (rstr [:> d2]))) (is (= (rstr [:div "a"]) (rstr [:> d2 "a"]))) (is (= (rstr [:div "a" "b"]) (rstr [:> d2 "a" "b"]))) (is (= (rstr [:div.foo "a"]) (rstr [:> d2 {:class "foo"} "a"]))) (is (= (rstr [:div "a" "b" [:div "c"]]) (rstr [:> d2 "a" "b" [:div "c"]]))))) (deftest ^:dom create-element-shortcut-test (let [p (atom nil) comp (fn [props] (reset! p props) (r/as-element [:div "a" (.-children props)]))] (with-mounted-component [:r> comp #js {:foo {:bar "x"}} [:p "bar"]] (fn [c div] (is (= {:bar "x"} (gobj/get @p "foo"))) (is (= "<div>a<p>bar</p></div>" (.-innerHTML div))))))) (deftest ^:dom shortcut-key-warning (let [w (debug/track-warnings #(with-mounted-component [:div (list [:> "div" {:key 1} "a"] [:> "div" {:key 2} "b"])] (fn [c div])))] (is (empty? (:warn w)))) (let [w (debug/track-warnings #(with-mounted-component [:div (list [:r> "div" #js {:key 1} "a"] [:r> "div" #js {:key 2} "b"])] (fn [c div])))] (is (empty? (:warn w)))) (let [f (fn [props c] [:div props c]) w (debug/track-warnings #(with-mounted-component [:div (list [:f> f {:key 1} "a"] [:f> f {:key 2} "b"])] (fn [c div])))] (is (empty? (:warn w))))) (u/deftest test-reactize-component (let [ae r/as-element ce r/create-element rstr #(as-string %) a (atom nil) c1r (fn reactize [p & args] (reset! a args) [:p "p:" (:a p) (:children p)]) c1 (r/reactify-component c1r u/*test-compiler*)] (is (= (rstr (ce c1 #js{:a "a"})) (rstr [:p "p:a"]))) (is (= nil @a)) (is (= (rstr (ce c1 #js{:a nil})) (rstr [:p "p:"]))) (is (= (rstr (ce c1 nil)) (rstr [:p "p:"]))) (is (= (rstr (ce c1 #js{:a "a"} (ae [:b "b"]))) (rstr [:p "p:a" [:b "b"]]))) (is (= nil @a)) (is (= (rstr (ce c1 #js{:a "a"} (ae [:b "b"]) (ae [:i "i"]))) (rstr [:p "p:a" [:b "b"] [:i "i"]]))) (is (= nil @a)))) (u/deftest ^:dom test-keys c (fn key-tester [] [:div (for [i (range 3)] ^{:key i} [:p i (some-> a deref)]) (for [i (range 3)] [:p {:key i} i (some-> a deref)])]) w (debug/track-warnings #(with-mounted-component [c] (fn [c div])))] (is (empty? (:warn w)))) (testing "Check warning text can be produced even if hiccup contains function literals" (let [c (fn key-tester [] [:div (for [i (range 3)] ^{:key nil} [:button {:on-click #(js/console.log %)}])]) w (debug/track-warnings (u/wrap-capture-console-error #(with-mounted-component [c] (fn [c div]))))] (if (dev?) (is (re-find #"Warning: Every element in a seq should have a unique :key: \(\[:button \{:on-click #object\[Function\]\}\] \[:button \{:on-click #object\[Function\]\}\] \[:button \{:on-click #object\[Function\]\}\]\)\n \(in reagenttest.testreagent.key_tester\)" (first (:warn w)))))))) (u/deftest test-extended-syntax (is (= "<p><b>foo</b></p>" (as-string [:p>b "foo"]))) (is (= (as-string [:p.foo [:b "x"]]) (as-string [:p.foo>b "x"]))) (is (= (as-string [:div.foo [:p.bar.foo [:b.foobar "xy"]]]) (as-string [:div.foo>p.bar.foo>b.foobar "xy"]))) (is (= (as-string [:div.foo [:p.bar.foo [:b.foobar "xy"]]]) (as-string [:div.foo>p.bar.foo>b.foobar {} "xy"]))) (is (= (as-string [:div [:p.bar.foo [:a.foobar {:href "href"} "xy"]]]) (as-string [:div>p.bar.foo>a.foobar {:href "href"} "xy"])))) (deftest ^:dom extended-syntax-metadata (let [comp (fn [] [:div (for [k [1 2]] ^{:key k} [:div>div "a"])])] (with-mounted-component [comp] (fn [c div] )))) (u/deftest test-class-from-collection (is (= (as-string [:p {:class "a b c d"}]) (as-string [:p {:class ["a" "b" "c" "d"]}]))) (is (= (as-string [:p {:class "a b c"}]) (as-string [:p {:class ["a" nil "b" false "c" nil]}]))) (is (= (as-string [:p {:class "a b c"}]) (as-string [:p {:class '("a" "b" "c")}]))) (is (= (as-string [:p {:class "a b c"}]) (as-string [:p {:class #{"a" "b" "c"}}])))) (u/deftest class-different-types (testing "named values are supported" (is (= (as-string [:p {:class "a"}]) (as-string [:p {:class :a}]))) (is (= (as-string [:p {:class "a b"}]) (as-string [:p.a {:class :b}]))) (is (= (as-string [:p {:class "a b"}]) (as-string [:p.a {:class 'b}]))) (is (= (as-string [:p {:class "a b"}]) (as-string [:p {:class [:a :b]}]))) (is (= (as-string [:p {:class "a b"}]) (as-string [:p {:class ['a :b]}])))) (testing "non-named values like numbers" (is (= (as-string [:p {:class "1 b"}]) (as-string [:p {:class [1 :b]}])))) (testing "falsey values are filtered from collections" (is (= (as-string [:p {:class "a b"}]) (as-string [:p {:class [:a :b false nil]}]))))) (deftest ^:dom test-force-update (let [v (atom {:v1 0 :v2 0}) comps (atom {}) c1 (fn [] (swap! comps assoc :c1 (r/current-component)) [:p "" (swap! v update-in [:v1] inc)]) c2 (fn [] (swap! comps assoc :c2 (r/current-component)) [:div "" (swap! v update-in [:v2] inc) [c1]]) state (r/atom 0) spy (r/atom 0) t (fn [] @state) t1 (fn [] @(r/track t)) c3 (fn [] (swap! comps assoc :c3 (r/current-component)) [:div "" (reset! spy @(r/track t1))])] (with-mounted-component [c2] (fn [c div] (is (= {:v1 1 :v2 1} @v)) (r/force-update (:c2 @comps)) (is (= {:v1 1 :v2 2} @v)) (r/force-update (:c1 @comps)) (is (= {:v1 2 :v2 2} @v)) (r/force-update (:c2 @comps) true) (is (= {:v1 3 :v2 3} @v)))) (with-mounted-component [c3] (fn [c] (is (= 0 @spy)) (swap! state inc) (is (= 0 @spy)) (r/force-update (:c3 @comps)) (is (= 1 @spy)))))) (deftest ^:dom test-component-path (let [a (atom nil) tc (r/create-class {:display-name "atestcomponent" :render (fn [] (let [c (r/current-component)] (reset! a (comp/component-name c)) [:div]))})] (with-mounted-component [tc] (fn [c] (is (seq @a)) (is (re-find #"atestcomponent" @a) "component-path should work"))))) (u/deftest test-sorted-map-key (let [c1 (fn [map] [:div (map 1)]) c2 (fn [] [c1 (sorted-map 1 "foo" 2 "bar")])] (is (= "<div>foo</div>" (as-string [c2]))))) (u/deftest ^:dom basic-with-let (let [compiler u/*test-compiler* n1 (atom 0) n2 (atom 0) n3 (atom 0) val (r/atom 0) c (fn [] (r/with-let [v (swap! n1 inc)] (swap! n2 inc) [:div @val] (finally (swap! n3 inc))))] effect cleanup ( which calls dispose ) happens (t/async done (u/with-mounted-component-async [c] (fn [] (r/next-tick (fn [] (r/next-tick (fn [] (is (= [1 2 1] [@n1 @n2 @n3])) (done)))))) compiler (fn [_ div done] (is (= [1 1 0] [@n1 @n2 @n3])) (swap! val inc) (is (= [1 1 0] [@n1 @n2 @n3])) (r/flush) (is (= [1 2 0] [@n1 @n2 @n3])) (done)))))) (u/deftest ^:dom with-let-destroy-only (let [compiler u/*test-compiler* n1 (atom 0) n2 (atom 0) c (fn [] (r/with-let [] (swap! n1 inc) [:div] (finally (swap! n2 inc))))] (t/async done (u/with-mounted-component-async [c] Wait 2 animation frames for useEffect cleanup to be called . (fn [] (r/next-tick (fn [] (r/next-tick (fn [] (is (= [1 1] [@n1 @n2])) (done)))))) compiler (fn [_ div done] (is (= [1 0] [@n1 @n2])) (done)))))) (u/deftest ^:dom with-let-arg (let [a (atom 0) s (r/atom "foo") f (fn [x] (r/with-let [] (reset! a x) [:div x])) c (fn [] (r/with-let [] [f @s]))] (with-mounted-component [c] (fn [_ div] (is (= "foo" @a)) (reset! s "bar") (r/flush) (is (= "bar" @a)))))) (u/deftest with-let-non-reactive (let [n1 (atom 0) n2 (atom 0) n3 (atom 0) c (fn [] (r/with-let [a (swap! n1 inc)] (swap! n2 inc) [:div a] (finally (swap! n3 inc))))] (is (= (as-string [c]) (as-string [:div 1]))) (is (= [1 1 1] [@n1 @n2 @n3])))) (u/deftest ^:dom lifecycle (let [n1 (atom 0) t (atom 0) res (atom {}) add-args (fn [key args] (swap! res assoc key {:at (swap! n1 inc) :args (vec args)})) render (fn [& args] (this-as c (is (= c (r/current-component)))) (add-args :render args) [:div "" (first args)]) render2 (fn [& args] (add-args :render args) [:div "" (first args)]) ls {:get-initial-state (fn [& args] (reset! t (first args)) (add-args :initial-state args) {:foo "bar"}) :UNSAFE_component-will-mount (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-mount args)) :component-did-mount (fn [& args] (this-as c (is (= c (first args)))) (add-args :did-mount args)) :should-component-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :should-update args) true) :UNSAFE_component-will-receive-props (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-receive args)) :UNSAFE_component-will-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-update args)) :component-did-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :did-update args)) :component-will-unmount (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-unmount args))} c1 (r/create-class (assoc ls :reagent-render render)) defarg ["a" "b"] arg (r/atom defarg) comp (atom c1) c2 (fn [] (apply vector @comp @arg)) cnative (fn [] (into [:> @comp] @arg)) check (fn [] (is (= {:at 1 :args [@t]} (:initial-state @res))) (is (= {:at 2 :args [@t]} (:will-mount @res))) (is (= {:at 3 :args ["a" "b"]} (:render @res))) (is (= {:at 4 :args [@t]} (:did-mount @res))) (reset! arg ["a" "c"]) (r/flush) (is (= {:at 5 :args [@t [@comp "a" "c"]]} (:will-receive @res))) (is (= {:at 6 :args [@t [@comp "a" "b"] [@comp "a" "c"]]} (:should-update @res))) (is (= {:at 7 :args [@t [@comp "a" "c"] {:foo "bar"}]} (:will-update @res))) (is (= {:at 8 :args ["a" "c"]} (:render @res))) (is (= {:at 9 :args [@t [@comp "a" "b"] {:foo "bar"} nil]} (:did-update @res))))] (with-mounted-component [c2] u/*test-compiler* check) (is (= {:at 10 :args [@t]} (:will-unmount @res))) (reset! comp (with-meta render2 ls)) (reset! arg defarg) (reset! n1 0) (with-mounted-component [c2] nil check) (is (= {:at 10 :args [@t]} (:will-unmount @res))))) (u/deftest ^:dom lifecycle-native (let [n1 (atom 0) t (atom 0) res (atom {}) oldprops (atom nil) newprops (atom nil) add-args (fn [key args] (swap! res assoc key {:at (swap! n1 inc) :args (vec args)})) render (fn [& args] (this-as c (when @newprops (is (= (first args) @newprops)) (is (= (r/props c) @newprops))) (is (= c (r/current-component))) (is (= (first args) (r/props c))) (add-args :render {:children (r/children c)}) [:div "" (first args)])) ls {:get-initial-state (fn [& args] (reset! t (first args)) (reset! oldprops (-> args first r/props)) (add-args :initial-state args) {:foo "bar"}) :UNSAFE_component-will-mount (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-mount args)) :component-did-mount (fn [& args] (this-as c (is (= c (first args)))) (add-args :did-mount args)) :should-component-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :should-update args) true) :UNSAFE_component-will-receive-props (fn [& args] (reset! newprops (-> args second second)) (this-as c (is (= c (first args))) (add-args :will-receive (into [(dissoc (r/props c) :children)] (:children (r/props c)))))) :UNSAFE_component-will-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-update args)) :component-did-update (fn [& args] (this-as c (is (= c (first args)))) (add-args :did-update args)) :component-will-unmount (fn [& args] (this-as c (is (= c (first args)))) (add-args :will-unmount args))} c1 (r/create-class (assoc ls :reagent-render render)) defarg [{:foo "bar"} "a" "b"] arg (r/atom defarg) comp (atom c1) cnative (fn [] (into [:> @comp] @arg)) check (fn [] (is (= {:at 1 :args [@t]} (:initial-state @res))) (is (= {:at 2 :args [@t]} (:will-mount @res))) (is (= {:at 3 :args [[:children ["a" "b"]]]} (:render @res))) (is (= {:at 4 :args [@t]} (:did-mount @res))) (reset! arg [{:f "oo"} "a" "c"]) (r/flush) (is (= {:at 5 :args [{:foo "bar"} "a" "b"]} (:will-receive @res))) (let [a (:should-update @res) {at :at [this oldv newv] :args} a] (is (= 6 at)) (is (= 3 (count (:args a)))) (is (= (js->clj [@comp @oldprops]) (js->clj oldv))) (is (= [@comp @newprops] newv))) (let [a (:will-update @res) {at :at [this newv] :args} a] (is (= 7 at)) (is (= [@comp @newprops] newv))) (is (= {:at 8 :args [[:children ["a" "c"]]]} (:render @res))) (let [a (:did-update @res) {at :at [this oldv] :args} a] (is (= 9 at)) (is (= [@comp @oldprops] oldv))))] (with-mounted-component [cnative] check) (is (= {:at 10 :args [@t]} (:will-unmount @res))))) (defn foo [] [:div]) (u/deftest ^:dom test-err-messages (when (dev?) (is (thrown-with-msg? :default #"Hiccup form should not be empty: \[]" (as-string []))) (is (thrown-with-msg? :default #"Invalid Hiccup tag: \[:>div \[reagenttest.testreagent.foo]]" (as-string [:>div [foo]]))) (is (thrown-with-msg? :default #"Invalid Hiccup form: \[23]" (as-string [23]))) This used to be asserted by Reagent , but because it is hard to validate components , now we just trust React will validate elements . (debug/track-warnings (u/wrap-capture-console-error #(is (thrown-with-msg? :default #"(Element type is invalid:|Minified React error)" (as-string [:> [:div]]))))) (is (thrown-with-msg? :default #"Invalid tag: 'p.'" (as-string [:p.]))) (let [comp1 (fn comp1 [x] x) comp2 (fn comp2 [x] [comp1 x]) comp3 (fn comp3 [] (r/with-let [a (r/atom "foo")] [:div (for [i (range 0 1)] ^{:key i} [:p @a])])) comp4 (fn comp4 [] (for [i (range 0 1)] [:p "foo"])) nat (let [cmp (fn [])] (gobj/extend (.-prototype cmp) (.-prototype react/Component) #js {:render (fn [])}) (gobj/extend cmp react/Component) cmp) compiler u/*test-compiler* rend (fn [x] (with-mounted-component x compiler identity))] Error is orginally caused by , so only that is shown in the error (let [e (debug/track-warnings (u/wrap-capture-window-error (u/wrap-capture-console-error #(is (thrown-with-msg? :default #"Invalid tag: 'div.' \(in reagenttest.testreagent.comp1\)" (rend [comp2 [:div. "foo"]]))))))] (is (re-find #"The above error occurred in the <reagenttest\.testreagent\.comp1> component:" (first (:error e))))) (let [e (debug/track-warnings (u/wrap-capture-window-error (u/wrap-capture-console-error #(is (thrown-with-msg? :default #"Invalid tag: 'div.' \(in reagenttest.testreagent.comp1\)" (rend [comp1 [:div. "foo"]]))))))] (is (re-find #"The above error occurred in the <reagenttest\.testreagent\.comp1> component:" (first (:error e))))) (let [e (debug/track-warnings #(r/as-element [nat] compiler))] (is (re-find #"Using native React classes directly" (-> e :warn first)))) (let [e (debug/track-warnings #(rend [comp3]))] (is (re-find #"Reactive deref not supported" (-> e :warn first)))) (let [e (debug/track-warnings #(r/as-element (comp4) compiler))] (is (re-find #"Every element in a seq should have a unique :key" (-> e :warn first))))))) (u/deftest ^:dom test-error-boundary (let [error (r/atom nil) info (r/atom nil) error-boundary (fn error-boundary [comp] (r/create-class {:component-did-catch (fn [this e i] (reset! info i)) :get-derived-state-from-error (fn [e] (reset! error e) #js {}) :reagent-render (fn [comp] (if @error [:div "Something went wrong."] comp))})) comp1 (fn comp1 [] (throw (js/Error. "Test error"))) comp2 (fn comp2 [] [comp1])] (debug/track-warnings (u/wrap-capture-window-error (u/wrap-capture-console-error #(with-mounted-component [error-boundary [comp2]] (fn [c div] (r/flush) (is (= "Test error" (.-message @error))) (is (re-find #"Something went wrong\." (.-innerHTML div))) (if (dev?) (is (re-find #"^\n at reagenttest.testreagent.comp1 \([^)]*\)\n at reagenttest.testreagent.comp2 \([^)]*\)\n at reagent[0-9]+ \([^)]*\)\n at reagenttest.testreagent.error_boundary \([^)]*\)" (.-componentStack ^js @info))) Names are completely manged on adv compilation (is (re-find #"^\n at .* \([^)]*\)\n at .* \([^)]*\)\n at .* \([^)]*\)\n at .+ \([^)]*\)" (.-componentStack ^js @info))))))))))) #_{:clj-kondo/ignore [:deprecated-var]} (u/deftest ^:dom test-dom-node (let [node (atom nil) ref (atom nil) comp (r/create-class {:reagent-render (fn test-dom [] [:div {:ref #(reset! ref %)} "foobar"]) :component-did-mount (fn [this] (reset! node (rdom/dom-node this)))})] (with-mounted-component [comp] (fn [c div] (is (= "foobar" (.-innerHTML @ref))) (is (= "foobar" (.-innerHTML @node))) (is (identical? @ref @node)))))) (u/deftest test-empty-input (is (= "<div><input/></div>" (as-string [:div [:input]])))) (u/deftest test-object-children (is (= "<p>foo bar1</p>" (as-string [:p 'foo " " :bar nil 1]))) (is (= "<p>#object[reagent.ratom.RAtom {:val 1}]</p>" (as-string [:p (r/atom 1)])))) (u/deftest ^:dom test-after-render (let [spy (atom 0) val (atom 0) exp (atom 0) node (atom nil) state (r/atom 0) comp (fn [] (let [old @spy] (r/after-render (fn [] (is (= "DIV" (.-tagName @node))) (swap! spy inc))) (is (= @spy old)) (is (= @exp @val)) [:div {:ref #(reset! node %)} @state]))] (with-mounted-component [comp] (fn [c div] (r/flush) (is (= 1 @spy)) (swap! state inc) (is (= 1 @spy)) (r/next-tick #(swap! val inc)) (reset! exp 1) (is (= 0 @val)) (r/flush) (is (= 1 @val)) (is (= 2 @spy)) ( is (= 3 ) ) ( is (= 3 ) ) ( is (= 0 ) ) )) (is (= nil @node)))) (u/deftest style-property-names-are-camel-cased (is (= "<div style=\"text-align:center\">foo</div>" (as-string [:div {:style {:text-align "center"}} "foo"])))) (u/deftest custom-element-class-prop (is (= "<custom-element class=\"foobar\">foo</custom-element>" (as-string [:custom-element {:class "foobar"} "foo"]))) (is (= "<custom-element class=\"foobar\">foo</custom-element>" (as-string [:custom-element.foobar "foo"])))) (u/deftest html-entities (testing "entity numbers can be unescaped always" (is (= "<i> </i>" (as-string [:i (gstr/unescapeEntities "&#160;")]))))) (u/deftest ^:dom html-entities-dom (testing "When DOM is available, all named entities can be unescaped" (is (= "<i> </i>" (as-string [:i (gstr/unescapeEntities "&nbsp;")]))))) (defn context-wrapper [] (r/create-class {:get-child-context (fn [] (this-as this #js {:foo "bar"})) :child-context-types #js {:foo prop-types/string.isRequired} :reagent-render (fn [child] [:div "parent," child])})) (defn context-child [] (r/create-class {:context-types #js {:foo prop-types/string.isRequired} :reagent-render (fn [] (let [this (r/current-component)] Context property name is not mangled , so need to use gobj / get to access property by string name [:div "child," (gobj/get (.-context this) "foo")]))})) (deftest ^:dom context-test (with-mounted-component [context-wrapper [context-child]] nil (fn [c div] (is (= "parent,child,bar" (.-innerText div)))))) (u/deftest test-fragments (testing "Fragment as array" (let [compiler u/*test-compiler* comp (fn comp1 [] #js [(r/as-element [:div "hello"] compiler) (r/as-element [:div "world"] compiler)])] (is (= "<div>hello</div><div>world</div>" (as-string [comp])))))) (defonce my-context ^js/MyContext (react/createContext "default")) (def Provider (.-Provider my-context)) (def Consumer (.-Consumer my-context)) (u/deftest new-context-test (is (= "<div>Context: foo</div>" (as-string (r/create-element Provider #js {:value "foo"} (r/create-element Consumer #js {} (fn [v] (r/as-element [:div "Context: " v]))))))) (testing "context default value works" (is (= "<div>Context: default</div>" (as-string (r/create-element Consumer #js {} (fn [v] (r/as-element [:div "Context: " v]))))))) (testing "context works with adapt-react-class" (let [provider (r/adapt-react-class Provider) consumer (r/adapt-react-class Consumer)] (is (= "<div>Context: bar</div>" (as-string [provider {:value "bar"} [consumer {} (fn [v] (r/as-element [:div "Context: " v]))]]))))) (testing "context works with :>" (is (= "<div>Context: bar</div>" (as-string [:> Provider {:value "bar"} [:> Consumer {} (fn [v] (r/as-element [:div "Context: " v]))]])))) (testing "static contextType" (let [comp (r/create-class {:context-type my-context :reagent-render (fn [] (this-as this (r/as-element [:div "Context: " (.-context this)])))})] (is (= "<div>Context: default</div>" (as-string [comp]))))) (testing "useContext hook" (let [comp (fn [v] (let [v (react/useContext my-context)] [:div "Context: " v]))] (is (= "<div>Context: foo</div>" (as-string [:r> Provider #js {:value "foo"} [:f> comp]])))))) (u/deftest ^:dom on-failed-prop-comparison-in-should-update-swallow-exception-and-do-not-update-component (let [prop (r/atom {:todos 1}) component-was-updated (atom false) error-thrown-after-updating-props (atom false) component-class (r/create-class {:reagent-render (fn [& args] [:div (str (first args))]) :component-did-update (fn [& args] (reset! component-was-updated true))}) component (fn [] [component-class @prop])] (when (dev?) (let [e (debug/track-warnings #(with-mounted-component [component] (fn [c div] (reset! prop (sorted-map 1 2)) (try (r/flush) (catch :default e (reset! error-thrown-after-updating-props true))) (is (not @component-was-updated)) (is (not @error-thrown-after-updating-props)))))] (is (re-find #"Warning: Exception thrown while comparing argv's in shouldComponentUpdate:" (first (:warn e)))))))) (u/deftest ^:dom get-derived-state-from-props-test (let [prop (r/atom 0) getDerivedStateFromProps implementation in React uses pure-component (r/create-class {:constructor (fn [this] (set! (.-state this) #js {})) :get-derived-state-from-props (fn [props state] #js {:v (string/join " " (repeat (inc (:value props)) "foo"))}) :render (fn [this] (r/as-element [:p "Value " (gobj/get (.-state this) "v")]))}) component (fn [] [pure-component {:value @prop}])] (with-mounted-component [component] (fn [c div] (is (= "Value foo" (.-innerText div))) (swap! prop inc) (r/flush) (is (= "Value foo foo" (.-innerText div))))))) (u/deftest ^:dom get-derived-state-from-error-test (let [prop (r/atom 0) component (r/create-class {:constructor (fn [this props] (set! (.-state this) #js {:hasError false})) :get-derived-state-from-error (fn [error] #js {:hasError true}) :component-did-catch (fn [this e info]) :render (fn [^js/React.Component this] (r/as-element (if (.-hasError (.-state this)) [:p "Error"] (into [:<>] (r/children this)))))}) bad-component (fn [] (if (= 0 @prop) [:div "Ok"] (throw (js/Error. "foo"))))] (u/wrap-capture-window-error (u/wrap-capture-console-error #(with-mounted-component [component [bad-component]] (fn [c div] (is (= "Ok" (.-innerText div))) (swap! prop inc) (r/flush) (is (= "Error" (.-innerText div))))))))) (u/deftest ^:dom get-snapshot-before-update-test (let [ref (react/createRef) prop (r/atom 0) did-update (atom nil) component (r/create-class {:get-snapshot-before-update (fn [this [_ prev-props] prev-state] {:height (.. ref -current -scrollHeight)}) :component-did-update (fn [this [_ prev-props] prev-state snapshot] (reset! did-update snapshot)) :render (fn [this] (r/as-element [:div {:ref ref :style {:height "20px"}} "foo"]))}) component-2 (fn [] [component {:value @prop}])] (with-mounted-component [component-2] (fn [c div] Attach to DOM to get real height value (.appendChild js/document.body div) (is (= "foo" (.-innerText div))) (swap! prop inc) (r/flush) (is (= {:height 20} @did-update)) (.removeChild js/document.body div))))) (u/deftest ^:dom issue-462-test (let [val (r/atom 0) render (atom 0) a (fn issue-462-a [nr] (swap! render inc) [:h1 "Value " nr]) b (fn issue-462-b [] [:div ^{:key @val} [a @val]]) c (fn issue-462-c [] ^{:key @val} [b])] (with-mounted-component [c] (fn [c div] (is (= 1 @render)) (reset! val 1) (r/flush) (is (= 2 @render)) (reset! val 0) (r/flush) (is (= 3 @render)))))) (deftest ^:dom functional-component-poc-simple (let [c (fn [x] [:span "Hello " x])] (testing ":f>" (with-mounted-component [:f> c "foo"] u/class-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Hello foo" (.-innerText div)))))) (testing "compiler options" (with-mounted-component [c "foo"] u/fn-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Hello foo" (.-innerText div)))))) (testing "setting default compiler" (try (r/set-default-compiler! u/fn-compiler) (with-mounted-component [c "foo"] nil (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Hello foo" (.-innerText div))))) (finally (r/set-default-compiler! nil)))))) (deftest ^:dom functional-component-poc-state-hook set-count! (atom nil) c (fn [x] (let [[c set-count] (react/useState x)] (reset! set-count! set-count) [:span "Count " c]))] (with-mounted-component [c 5] u/fn-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Count 5" (.-innerText div))) (@set-count! 6) (is (= "Count 6" (.-innerText div))))))) (deftest ^:dom functional-component-poc-ratom (let [count (r/atom 5) c (fn [x] [:span "Count " @count])] (with-mounted-component [c 5] u/fn-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Count 5" (.-innerText div))) (reset! count 6) (r/flush) (is (= "Count 6" (.-innerText div))) TODO : Test that component RAtom is disposed )))) (deftest ^:dom functional-component-poc-ratom-state-hook (let [r-count (r/atom 3) set-count! (atom nil) c (fn [x] (let [[c set-count] (react/useState x)] (reset! set-count! set-count) [:span "Counts " @r-count " " c]))] (with-mounted-component [c 15] u/fn-compiler (fn [c div] (is (nil? c) "Render returns nil for stateless components") (is (= "Counts 3 15" (.-innerText div))) (reset! r-count 6) (r/flush) (is (= "Counts 6 15" (.-innerText div))) (@set-count! 17) (is (= "Counts 6 17" (.-innerText div))) )))) (u/deftest ^:dom test-input-el-ref (let [ref-1 (atom nil) ref-1-fn #(reset! ref-1 %) ref-2 (react/createRef) c (fn [x] [:div [:input {:ref ref-1-fn :value nil :on-change (fn [_])}] [:input {:ref ref-2 :value nil :on-change (fn [_])}]])] (with-mounted-component [c] (fn [c div] (is (some? @ref-1)) (is (some? (.-current ref-2))) )))) (deftest test-element-key (is (= "0" (.-key (r/as-element [:div {:key 0}])))) (is (= "0" (.-key (r/as-element ^{:key 0} [:div])))) (is (= "0" (.-key (r/as-element [:input {:key 0}])))) (is (= "0" (.-key (r/as-element ^{:key 0} [:input])))) ) (defn parse-tag [hiccup-tag] (let [[tag id className] (->> hiccup-tag name (re-matches tmpl/re-tag) next) className (when-not (nil? className) (->> (string/split className #"\.") (map (fn [s] (str "foo_" s))) (string/join " ")))] (assert tag (str "Invalid tag: '" hiccup-tag "'" (comp/comp-name))) (tmpl/->HiccupTag tag id className (not= -1 (.indexOf tag "-"))))) (def tag-name-cache #js {}) (defn cached-parse [this x _] (if-some [s (tmpl/cache-get tag-name-cache x)] s (let [v (parse-tag x)] (gobj/set tag-name-cache x v) v))) (deftest parse-tag-test (let [compiler (r/create-compiler {:parse-tag cached-parse})] (gobj/clear tag-name-cache) (is (= "<div class=\"foo_asd foo_xyz bar\"></div>" (server/render-to-static-markup [:div.asd.xyz {:class "bar"}] compiler))))) (deftest ^:dom react-18-test (when (>= (js/parseInt react/version) 18) (let [div (.createElement js/document "div") root (rdomc/create-root div) i (r/atom 0) ran (atom 0) test-wrap (fn [check-fn el] (react/useEffect (fn [] (check-fn) js/undefined) #js []) el) really-simple (fn [] (swap! ran inc) [:div "foo " @i])] (u/async (js/Promise. (fn [resolve reject] (rdomc/render root [:f> test-wrap (fn [] (is (= "foo 0" (.-innerText div))) (is (= 1 @ran)) (swap! i inc) Wait for Reagent to flush ratom queue . (r/after-render (fn [] (js/setTimeout (fn [] (is (= "foo 1" (.-innerText div))) (is (= 2 @ran)) (resolve)) 16)))) [really-simple]] u/fn-compiler)))))))
53417d9ab082b46a8f23d3c6785a6563238c3d13eac3da54755f91d08a93b6c2
clj-commons/iapetos
standalone.clj
(ns iapetos.standalone (:require [iapetos.collector.ring :as ring] [clojure.java.io :as io]) (:import [com.sun.net.httpserver HttpHandler HttpServer HttpExchange] [java.net InetSocketAddress])) # # Handler (defn- write-headers! [^HttpExchange e {:keys [status headers ^bytes body]}] (let [h (.getResponseHeaders e) content-length (alength body)] (doseq [[header value] headers] (.set h (str header) (str value))) (.set h "Content-Length" (str content-length)) (.sendResponseHeaders e (int status) content-length))) (defn- write-body! [^HttpExchange e {:keys [^bytes body]}] (with-open [out (.getResponseBody e)] (.write out body) (.flush out))) (defn- plain-response [status & text] {:status status :headers {"Content-Type" "text/plain; charset=UTF-8"} :body (apply str text)}) (defn- write-response! [^HttpExchange e registry path] (with-open [_ e] (let [request-method (.getRequestMethod e) request-path (.getPath (.getRequestURI e)) response (-> (try (cond (not= request-path path) (plain-response 404 "Not found: " request-path) (not= request-method "GET") (plain-response 405 "Method not allowed: " request-method) :else (ring/metrics-response registry)) (catch Throwable t (plain-response 500 (pr-str t)))) (update :body #(.getBytes ^String % "UTF-8")))] (doto e (write-headers! response) (write-body! response))))) (defn- metrics-handler [registry path] (reify HttpHandler (handle [_ e] (write-response! e registry path)))) ;; ## Server (defn metrics-server "Expose the metrics contained within the given collector registry using the given port and path. Returns a handle on the standalone server, implementing `java.io.Closeable`." ^java.io.Closeable [registry & [{:keys [^long port ^String path ^long queue-size ^java.util.concurrent.ExecutorService executor] :or {port 8080, path "/metrics" queue-size 5}}]] (let [handler (metrics-handler registry path) server (doto (HttpServer/create) (.bind (InetSocketAddress. port) queue-size) (.createContext "/" handler) (.setExecutor executor) (.start)) address (.getAddress server) data {:address address :port (.getPort address) :host (.getHostString address)}] (reify Object clojure.lang.ILookup (valAt [_ k default] (get data k default)) (valAt [this k] (get data k)) java.util.Map (keySet [_] (.keySet ^java.util.Map data)) (entrySet [_] (.entrySet ^java.util.Map data)) (values [_] (vals data)) (isEmpty [_] false) (size [_] (count data)) (get [_ k] (get data k)) java.io.Closeable (close [_] (.stop server 0)))))
null
https://raw.githubusercontent.com/clj-commons/iapetos/0fecedaf8454e17e41b05e0e14754a311b9f4ce2/src/iapetos/standalone.clj
clojure
## Server
(ns iapetos.standalone (:require [iapetos.collector.ring :as ring] [clojure.java.io :as io]) (:import [com.sun.net.httpserver HttpHandler HttpServer HttpExchange] [java.net InetSocketAddress])) # # Handler (defn- write-headers! [^HttpExchange e {:keys [status headers ^bytes body]}] (let [h (.getResponseHeaders e) content-length (alength body)] (doseq [[header value] headers] (.set h (str header) (str value))) (.set h "Content-Length" (str content-length)) (.sendResponseHeaders e (int status) content-length))) (defn- write-body! [^HttpExchange e {:keys [^bytes body]}] (with-open [out (.getResponseBody e)] (.write out body) (.flush out))) (defn- plain-response [status & text] {:status status :headers {"Content-Type" "text/plain; charset=UTF-8"} :body (apply str text)}) (defn- write-response! [^HttpExchange e registry path] (with-open [_ e] (let [request-method (.getRequestMethod e) request-path (.getPath (.getRequestURI e)) response (-> (try (cond (not= request-path path) (plain-response 404 "Not found: " request-path) (not= request-method "GET") (plain-response 405 "Method not allowed: " request-method) :else (ring/metrics-response registry)) (catch Throwable t (plain-response 500 (pr-str t)))) (update :body #(.getBytes ^String % "UTF-8")))] (doto e (write-headers! response) (write-body! response))))) (defn- metrics-handler [registry path] (reify HttpHandler (handle [_ e] (write-response! e registry path)))) (defn metrics-server "Expose the metrics contained within the given collector registry using the given port and path. Returns a handle on the standalone server, implementing `java.io.Closeable`." ^java.io.Closeable [registry & [{:keys [^long port ^String path ^long queue-size ^java.util.concurrent.ExecutorService executor] :or {port 8080, path "/metrics" queue-size 5}}]] (let [handler (metrics-handler registry path) server (doto (HttpServer/create) (.bind (InetSocketAddress. port) queue-size) (.createContext "/" handler) (.setExecutor executor) (.start)) address (.getAddress server) data {:address address :port (.getPort address) :host (.getHostString address)}] (reify Object clojure.lang.ILookup (valAt [_ k default] (get data k default)) (valAt [this k] (get data k)) java.util.Map (keySet [_] (.keySet ^java.util.Map data)) (entrySet [_] (.entrySet ^java.util.Map data)) (values [_] (vals data)) (isEmpty [_] false) (size [_] (count data)) (get [_ k] (get data k)) java.io.Closeable (close [_] (.stop server 0)))))
7f1a38c7a71e2eacb6175f6b7d72ff02859ab1f00728d2c2aace52f494436eb9
webcrank/webcrank.hs
HLint.hs
import "hint" HLint.Default import "hint" HLint.Generalise ignore "Use import/export shortcut"
null
https://raw.githubusercontent.com/webcrank/webcrank.hs/c611a12ea129383823cc627405819537c31730e4/HLint.hs
haskell
import "hint" HLint.Default import "hint" HLint.Generalise ignore "Use import/export shortcut"
bd66cbdf49d13a8e154c33d0fdd5e3e4687c1f293a0dbfbe5ec79239d9c188fa
webmachine/webmachine
webmachine_resource.erl
@author < > @author < > 2007 - 2014 Basho Technologies %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and %% limitations under the License. -module(webmachine_resource). -author('Justin Sheehy <>'). -author('Andy Gross <>'). -export([new/3, wrap/2]). -export([do/3,log_d/2,stop/1]). -include("wm_compat.hrl"). -include("wm_resource.hrl"). -include("wm_reqdata.hrl"). -include("wm_reqstate.hrl"). -type t() :: #wm_resource{}. -export_type([t/0]). -define(CALLBACK_ARITY, 2). new(R_Mod, R_ModState, R_Trace) -> case erlang:module_loaded(R_Mod) of false -> code:ensure_loaded(R_Mod); true -> ok end, #wm_resource{ module = R_Mod, modstate = R_ModState, trace = R_Trace }. default(service_available) -> true; default(resource_exists) -> true; default(is_authorized) -> true; default(forbidden) -> false; default(allow_missing_post) -> false; default(malformed_request) -> false; default(uri_too_long) -> false; default(known_content_type) -> true; default(valid_content_headers) -> true; default(valid_entity_length) -> true; default(options) -> []; default(allowed_methods) -> ['GET', 'HEAD']; default(known_methods) -> ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT', 'OPTIONS']; default(content_types_provided) -> [{"text/html", to_html}]; default(content_types_accepted) -> []; default(delete_resource) -> false; default(delete_completed) -> true; default(post_is_create) -> false; default(create_path) -> undefined; default(base_uri) -> undefined; default(process_post) -> false; default(language_available) -> true; default(charsets_provided) -> no_charset; % this atom causes charset-negotation to short-circuit % the default setting is needed for non-charset responses such as image/png % an example of how one might do actual negotiation [ { " iso-8859 - 1 " , fun(X ) - > X end } , { " utf-8 " , } ] ; default(encodings_provided) -> [{"identity", fun(X) -> X end}]; % this is handy for auto-gzip of GET-only resources: [ { " identity " , fun(X ) - > X end } , { " gzip " , fun(X ) - > zlib : gzip(X ) end } ] ; default(variances) -> []; default(is_conflict) -> false; default(multiple_choices) -> false; default(previously_existed) -> false; default(moved_permanently) -> false; default(moved_temporarily) -> false; default(last_modified) -> undefined; default(expires) -> undefined; default(generate_etag) -> undefined; default(finish_request) -> true; default(validate_content_checksum) -> not_validated; default(_) -> no_default. -spec wrap(module(), [any()]) -> {ok, t()} | {stop, bad_init_arg}. wrap(Mod, Args) -> case Mod:init(Args) of {ok, ModState} -> {ok, webmachine_resource:new(Mod, ModState, false)}; {{trace, Dir}, ModState} -> {ok, File} = open_log_file(Dir, Mod), log_decision(File, v3b14), log_call(File, attempt, Mod, init, Args), log_call(File, result, Mod, init, {{trace, Dir}, ModState}), {ok, webmachine_resource:new(Mod, ModState, File)}; _ -> {stop, bad_init_arg} end. do(#wm_resource{}=Res, Fun, ReqProps) -> do(Fun, ReqProps, Res); do(Fun, ReqProps, #wm_resource{ module=R_Mod, trace=R_Trace }=Req) when is_atom(Fun) andalso is_list(ReqProps) -> case lists:keyfind(reqstate, 1, ReqProps) of false -> RState0 = undefined; {reqstate, RState0} -> ok end, put(tmp_reqstate, empty), {Reply, ReqData, NewModState} = handle_wm_call(Fun, (RState0#wm_reqstate.reqdata)#wm_reqdata{wm_state=RState0}, Req), ReqState = case get(tmp_reqstate) of empty -> RState0; X -> X end, %% Do not need the embedded state anymore TrimData = ReqData#wm_reqdata{wm_state=undefined}, {Reply, webmachine_resource:new(R_Mod, NewModState, R_Trace), ReqState#wm_reqstate{reqdata=TrimData}}. handle_wm_call(Fun, ReqData, #wm_resource{ module=R_Mod, modstate=R_ModState, trace=R_Trace }=Req) -> case default(Fun) of no_default -> resource_call(Fun, ReqData, Req); Default -> case erlang:function_exported(R_Mod, Fun, ?CALLBACK_ARITY) of true -> resource_call(Fun, ReqData, Req); false -> if is_pid(R_Trace) -> log_call(R_Trace, not_exported, R_Mod, Fun, [ReqData, R_ModState]); true -> ok end, {Default, ReqData, R_ModState} end end. trim_trace([{M,F,[RD = #wm_reqdata{},S],_}|STRest]) -> TrimState = (RD#wm_reqdata.wm_state)#wm_reqstate{reqdata='REQDATA'}, TrimRD = RD#wm_reqdata{wm_state=TrimState}, [{M,F,[TrimRD,S]}|STRest]; trim_trace(X) -> X. resource_call(F, ReqData, #wm_resource{ module=R_Mod, modstate=R_ModState, trace=R_Trace }) -> case R_Trace of false -> nop; _ -> log_call(R_Trace, attempt, R_Mod, F, [ReqData, R_ModState]) end, Result = try %% Note: the argument list must match the definition of CALLBACK_ARITY apply(R_Mod, F, [ReqData, R_ModState]) catch ?STPATTERN(throw:{webmachine_recv_error,_}=Error) -> Location = find_call(R_Mod, F, ?STACKTRACE), {{error, {throw, Error, Location}}, ReqData, R_ModState}; ?STPATTERN(C:R) -> Reason = {C, R, trim_trace(?STACKTRACE)}, {{error, Reason}, ReqData, R_ModState} end, case R_Trace of false -> nop; _ -> log_call(R_Trace, result, R_Mod, F, Result) end, Result. find_call(Mod, Fun, [{Mod, Fun, ?CALLBACK_ARITY, _}=Call|_]) -> Call; find_call(Mod, Fun, [_|Rest]) -> find_call(Mod, Fun, Rest); find_call(Mod, Fun, []) -> {Mod, Fun, ?CALLBACK_ARITY, []}. log_d(#wm_resource{}=Res, DecisionID) -> log_d(DecisionID, Res); log_d(DecisionID, #wm_resource{ trace=R_Trace }) -> case R_Trace of false -> nop; _ -> log_decision(R_Trace, DecisionID) end. stop(#wm_resource{trace=R_Trace}) -> close_log_file(R_Trace). log_call(File, Type, M, F, Data) -> io:format(File, "{~p, ~p, ~p,~n ~p}.~n", [Type, M, F, escape_trace_data(Data)]). escape_trace_data(Fun) when is_function(Fun) -> {'WMTRACE_ESCAPED_FUN', [erlang:fun_info(Fun, module), erlang:fun_info(Fun, name), erlang:fun_info(Fun, arity), erlang:fun_info(Fun, type)]}; escape_trace_data(Pid) when is_pid(Pid) -> {'WMTRACE_ESCAPED_PID', pid_to_list(Pid)}; escape_trace_data(Port) when is_port(Port) -> {'WMTRACE_ESCAPED_PORT', erlang:port_to_list(Port)}; escape_trace_data(List) when is_list(List) -> escape_trace_list(List, []); escape_trace_data(R=#wm_reqstate{}) -> list_to_tuple( escape_trace_data( tuple_to_list(R#wm_reqstate{reqdata='WMTRACE_NESTED_REQDATA'}))); escape_trace_data(Tuple) when is_tuple(Tuple) -> list_to_tuple(escape_trace_data(tuple_to_list(Tuple))); escape_trace_data(Other) -> case code:ensure_loaded(maps) of {module, _Maps} -> case is_map(Other) of true -> %% TODO: replace with maps comprehension when implemented %% #{escape_trace_data(K), escape_trace_data(V) || K := V <- Other} Fun = fun(K, V, Acc) -> maps:put(escape_trace_data(K), escape_trace_data(V), Acc) end, maps:fold(Fun, maps:new(), Other); _ -> Other end; {error, _What} -> Other end. escape_trace_list([Head|Tail], Acc) -> escape_trace_list(Tail, [escape_trace_data(Head)|Acc]); escape_trace_list([], Acc) -> %% proper, nil-terminated list lists:reverse(Acc); escape_trace_list(Final, Acc) -> %% non-nil-terminated list, like the dict module uses lists:reverse(tl(Acc))++[hd(Acc)|escape_trace_data(Final)]. log_decision(File, DecisionID) -> io:format(File, "{decision, ~p}.~n", [DecisionID]). open_log_file(Dir, Mod) -> Now = {_,_,US} = os:timestamp(), {{Y,M,D},{H,I,S}} = calendar:now_to_universal_time(Now), Filename = io_lib:format( "~s/~p-~4..0B-~2..0B-~2..0B" "-~2..0B-~2..0B-~2..0B.~6..0B.wmtrace", [Dir, Mod, Y, M, D, H, I, S, US]), file:open(Filename, [write]). close_log_file(File) when is_pid(File) -> file:close(File); close_log_file(_) -> ok.
null
https://raw.githubusercontent.com/webmachine/webmachine/33f83f5db0d3a578ef607d4d5aecabeb9ba2cdf0/src/webmachine_resource.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. limitations under the License. this atom causes charset-negotation to short-circuit the default setting is needed for non-charset responses such as image/png an example of how one might do actual negotiation this is handy for auto-gzip of GET-only resources: Do not need the embedded state anymore Note: the argument list must match the definition of CALLBACK_ARITY TODO: replace with maps comprehension when implemented #{escape_trace_data(K), escape_trace_data(V) || K := V <- Other} proper, nil-terminated list non-nil-terminated list, like the dict module uses
@author < > @author < > 2007 - 2014 Basho Technologies Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , See the License for the specific language governing permissions and -module(webmachine_resource). -author('Justin Sheehy <>'). -author('Andy Gross <>'). -export([new/3, wrap/2]). -export([do/3,log_d/2,stop/1]). -include("wm_compat.hrl"). -include("wm_resource.hrl"). -include("wm_reqdata.hrl"). -include("wm_reqstate.hrl"). -type t() :: #wm_resource{}. -export_type([t/0]). -define(CALLBACK_ARITY, 2). new(R_Mod, R_ModState, R_Trace) -> case erlang:module_loaded(R_Mod) of false -> code:ensure_loaded(R_Mod); true -> ok end, #wm_resource{ module = R_Mod, modstate = R_ModState, trace = R_Trace }. default(service_available) -> true; default(resource_exists) -> true; default(is_authorized) -> true; default(forbidden) -> false; default(allow_missing_post) -> false; default(malformed_request) -> false; default(uri_too_long) -> false; default(known_content_type) -> true; default(valid_content_headers) -> true; default(valid_entity_length) -> true; default(options) -> []; default(allowed_methods) -> ['GET', 'HEAD']; default(known_methods) -> ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT', 'OPTIONS']; default(content_types_provided) -> [{"text/html", to_html}]; default(content_types_accepted) -> []; default(delete_resource) -> false; default(delete_completed) -> true; default(post_is_create) -> false; default(create_path) -> undefined; default(base_uri) -> undefined; default(process_post) -> false; default(language_available) -> true; default(charsets_provided) -> [ { " iso-8859 - 1 " , fun(X ) - > X end } , { " utf-8 " , } ] ; default(encodings_provided) -> [{"identity", fun(X) -> X end}]; [ { " identity " , fun(X ) - > X end } , { " gzip " , fun(X ) - > zlib : gzip(X ) end } ] ; default(variances) -> []; default(is_conflict) -> false; default(multiple_choices) -> false; default(previously_existed) -> false; default(moved_permanently) -> false; default(moved_temporarily) -> false; default(last_modified) -> undefined; default(expires) -> undefined; default(generate_etag) -> undefined; default(finish_request) -> true; default(validate_content_checksum) -> not_validated; default(_) -> no_default. -spec wrap(module(), [any()]) -> {ok, t()} | {stop, bad_init_arg}. wrap(Mod, Args) -> case Mod:init(Args) of {ok, ModState} -> {ok, webmachine_resource:new(Mod, ModState, false)}; {{trace, Dir}, ModState} -> {ok, File} = open_log_file(Dir, Mod), log_decision(File, v3b14), log_call(File, attempt, Mod, init, Args), log_call(File, result, Mod, init, {{trace, Dir}, ModState}), {ok, webmachine_resource:new(Mod, ModState, File)}; _ -> {stop, bad_init_arg} end. do(#wm_resource{}=Res, Fun, ReqProps) -> do(Fun, ReqProps, Res); do(Fun, ReqProps, #wm_resource{ module=R_Mod, trace=R_Trace }=Req) when is_atom(Fun) andalso is_list(ReqProps) -> case lists:keyfind(reqstate, 1, ReqProps) of false -> RState0 = undefined; {reqstate, RState0} -> ok end, put(tmp_reqstate, empty), {Reply, ReqData, NewModState} = handle_wm_call(Fun, (RState0#wm_reqstate.reqdata)#wm_reqdata{wm_state=RState0}, Req), ReqState = case get(tmp_reqstate) of empty -> RState0; X -> X end, TrimData = ReqData#wm_reqdata{wm_state=undefined}, {Reply, webmachine_resource:new(R_Mod, NewModState, R_Trace), ReqState#wm_reqstate{reqdata=TrimData}}. handle_wm_call(Fun, ReqData, #wm_resource{ module=R_Mod, modstate=R_ModState, trace=R_Trace }=Req) -> case default(Fun) of no_default -> resource_call(Fun, ReqData, Req); Default -> case erlang:function_exported(R_Mod, Fun, ?CALLBACK_ARITY) of true -> resource_call(Fun, ReqData, Req); false -> if is_pid(R_Trace) -> log_call(R_Trace, not_exported, R_Mod, Fun, [ReqData, R_ModState]); true -> ok end, {Default, ReqData, R_ModState} end end. trim_trace([{M,F,[RD = #wm_reqdata{},S],_}|STRest]) -> TrimState = (RD#wm_reqdata.wm_state)#wm_reqstate{reqdata='REQDATA'}, TrimRD = RD#wm_reqdata{wm_state=TrimState}, [{M,F,[TrimRD,S]}|STRest]; trim_trace(X) -> X. resource_call(F, ReqData, #wm_resource{ module=R_Mod, modstate=R_ModState, trace=R_Trace }) -> case R_Trace of false -> nop; _ -> log_call(R_Trace, attempt, R_Mod, F, [ReqData, R_ModState]) end, Result = try apply(R_Mod, F, [ReqData, R_ModState]) catch ?STPATTERN(throw:{webmachine_recv_error,_}=Error) -> Location = find_call(R_Mod, F, ?STACKTRACE), {{error, {throw, Error, Location}}, ReqData, R_ModState}; ?STPATTERN(C:R) -> Reason = {C, R, trim_trace(?STACKTRACE)}, {{error, Reason}, ReqData, R_ModState} end, case R_Trace of false -> nop; _ -> log_call(R_Trace, result, R_Mod, F, Result) end, Result. find_call(Mod, Fun, [{Mod, Fun, ?CALLBACK_ARITY, _}=Call|_]) -> Call; find_call(Mod, Fun, [_|Rest]) -> find_call(Mod, Fun, Rest); find_call(Mod, Fun, []) -> {Mod, Fun, ?CALLBACK_ARITY, []}. log_d(#wm_resource{}=Res, DecisionID) -> log_d(DecisionID, Res); log_d(DecisionID, #wm_resource{ trace=R_Trace }) -> case R_Trace of false -> nop; _ -> log_decision(R_Trace, DecisionID) end. stop(#wm_resource{trace=R_Trace}) -> close_log_file(R_Trace). log_call(File, Type, M, F, Data) -> io:format(File, "{~p, ~p, ~p,~n ~p}.~n", [Type, M, F, escape_trace_data(Data)]). escape_trace_data(Fun) when is_function(Fun) -> {'WMTRACE_ESCAPED_FUN', [erlang:fun_info(Fun, module), erlang:fun_info(Fun, name), erlang:fun_info(Fun, arity), erlang:fun_info(Fun, type)]}; escape_trace_data(Pid) when is_pid(Pid) -> {'WMTRACE_ESCAPED_PID', pid_to_list(Pid)}; escape_trace_data(Port) when is_port(Port) -> {'WMTRACE_ESCAPED_PORT', erlang:port_to_list(Port)}; escape_trace_data(List) when is_list(List) -> escape_trace_list(List, []); escape_trace_data(R=#wm_reqstate{}) -> list_to_tuple( escape_trace_data( tuple_to_list(R#wm_reqstate{reqdata='WMTRACE_NESTED_REQDATA'}))); escape_trace_data(Tuple) when is_tuple(Tuple) -> list_to_tuple(escape_trace_data(tuple_to_list(Tuple))); escape_trace_data(Other) -> case code:ensure_loaded(maps) of {module, _Maps} -> case is_map(Other) of true -> Fun = fun(K, V, Acc) -> maps:put(escape_trace_data(K), escape_trace_data(V), Acc) end, maps:fold(Fun, maps:new(), Other); _ -> Other end; {error, _What} -> Other end. escape_trace_list([Head|Tail], Acc) -> escape_trace_list(Tail, [escape_trace_data(Head)|Acc]); escape_trace_list([], Acc) -> lists:reverse(Acc); escape_trace_list(Final, Acc) -> lists:reverse(tl(Acc))++[hd(Acc)|escape_trace_data(Final)]. log_decision(File, DecisionID) -> io:format(File, "{decision, ~p}.~n", [DecisionID]). open_log_file(Dir, Mod) -> Now = {_,_,US} = os:timestamp(), {{Y,M,D},{H,I,S}} = calendar:now_to_universal_time(Now), Filename = io_lib:format( "~s/~p-~4..0B-~2..0B-~2..0B" "-~2..0B-~2..0B-~2..0B.~6..0B.wmtrace", [Dir, Mod, Y, M, D, H, I, S, US]), file:open(Filename, [write]). close_log_file(File) when is_pid(File) -> file:close(File); close_log_file(_) -> ok.
da0c914e495d5638730a29ce132f5de8c89d6d39fcbf394d81e1b312d533c3aa
chrovis/cljam
gzi_test.clj
(ns cljam.io.util.bgzf.gzi-test (:require [clojure.test :refer [deftest is are]] [cljam.test-common :as common] [cljam.io.util.bgzf.gzi :as gzi])) (def ^:private medium-fa-bgz-gzi (sorted-map 0 0, 65280 21483, 130560 43102, 195840 64763, 261120 85797, 326400 106765, 391680 128189, 456960 149697)) (deftest read-gzi (is (= medium-fa-bgz-gzi (gzi/read-gzi common/medium-fa-bgz-gzi-file)))) (deftest uncomp->comp (are [?uncomp ?comp] (= ?comp (gzi/uncomp->comp medium-fa-bgz-gzi ?uncomp)) 0 0 1 1 65279 65279 65280 (bit-shift-left 21483 16) 456961 (inc (bit-shift-left 149697 16)))) (deftest comp->uncomp (are [?comp ?uncomp] (= ?uncomp (gzi/comp->uncomp medium-fa-bgz-gzi ?comp)) 0 0 1 1 21482 21482 65279 65279 (bit-shift-left 21483 16) 65280 (bit-shift-left 149697 16) 456960 (inc (bit-shift-left 149697 16)) 456961))
null
https://raw.githubusercontent.com/chrovis/cljam/2b8e7386765be8efdbbbb4f18dbc52447f4a08af/test/cljam/io/util/bgzf/gzi_test.clj
clojure
(ns cljam.io.util.bgzf.gzi-test (:require [clojure.test :refer [deftest is are]] [cljam.test-common :as common] [cljam.io.util.bgzf.gzi :as gzi])) (def ^:private medium-fa-bgz-gzi (sorted-map 0 0, 65280 21483, 130560 43102, 195840 64763, 261120 85797, 326400 106765, 391680 128189, 456960 149697)) (deftest read-gzi (is (= medium-fa-bgz-gzi (gzi/read-gzi common/medium-fa-bgz-gzi-file)))) (deftest uncomp->comp (are [?uncomp ?comp] (= ?comp (gzi/uncomp->comp medium-fa-bgz-gzi ?uncomp)) 0 0 1 1 65279 65279 65280 (bit-shift-left 21483 16) 456961 (inc (bit-shift-left 149697 16)))) (deftest comp->uncomp (are [?comp ?uncomp] (= ?uncomp (gzi/comp->uncomp medium-fa-bgz-gzi ?comp)) 0 0 1 1 21482 21482 65279 65279 (bit-shift-left 21483 16) 65280 (bit-shift-left 149697 16) 456960 (inc (bit-shift-left 149697 16)) 456961))
b34ed7a2b3b62bbb24a290d731ed5df1c0a3e499ab5fcd5a9b4f581146ef5a6a
zudov/haskell-comark
Prim.hs
# LANGUAGE RecordWildCards # {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} module Comark.ParserCombinators.Prim ( Position(..) , Parser() , runParser , ParserState() , ParseError(..) , withConsumed , consumedBy , string , (<?>) , runParserWithUnconsumed , getPosition , setPosition , satisfy , peekChar , peekLastChar , replacing , endOfInput , takeWhile , takeWhile1 , untilTheEnd , skip , skipWhile , skipWhile1 , stringCaseless , scan , lookAhead , notFollowedBy ) where import Control.Applicative import Control.Monad import Data.String import Data.Text (Text) import qualified Data.Text as Text import Prelude hiding (takeWhile) data Position = Position { line :: Int , column :: Int , point :: Int } deriving (Ord, Eq) instance Show Position where show (Position ln cn pn) = concat ["line ", show ln, " column ", show cn, " point ", show pn] data ParseError = ParseError { parseErrorPosition :: Position , parseErrorReason :: String } deriving (Show) data ParserState = ParserState { subject :: Text , position :: Position , lastChar :: Maybe Char } advance :: ParserState -> Text -> ParserState advance = Text.foldl' go where go :: ParserState -> Char -> ParserState go st c = ParserState { subject = Text.drop 1 (subject st) , position = case c of '\n' -> Position { line = line (position st) + 1 , column = 1 , point = point (position st) + 1 } _ -> Position { line = line (position st) , column = column (position st) + 1 , point = point (position st) + 1 } , lastChar = Just c } newtype Parser a = Parser { evalParser :: ParserState -> Either ParseError (ParserState, a) } -- | Returns the text that was consumed by a parser alongside with its result withConsumed :: Parser a -> Parser (a,Text) withConsumed p = Parser $ \st -> case (evalParser p) st of Left err -> Left err Right (st', res) -> let consumedLength = point (position st') - point (position st) in Right (st', (res, Text.take consumedLength (subject st))) consumedBy :: Parser a -> Parser Text consumedBy = fmap snd . withConsumed instance Functor Parser where fmap f (Parser g) = Parser $ \st -> case g st of Right (st', x) -> Right (st', f x) Left e -> Left e # INLINE fmap # instance Applicative Parser where pure x = Parser $ \st -> Right (st, x) (Parser f) <*> (Parser g) = Parser $ \st -> case f st of Left e -> Left e Right (st', h) -> case g st' of Right (st'', x) -> Right (st'', h x) Left e -> Left e # INLINE pure # {-# INLINE (<*>) #-} instance Alternative Parser where empty = Parser $ \st -> Left $ ParseError (position st) "(empty)" (Parser f) <|> (Parser g) = Parser $ \st -> case f st of Right res -> Right res Left (ParseError pos msg) -> case g st of Right res -> Right res Left (ParseError pos' msg') -> Left $ case () of -- return error for farthest match _ | pos' > pos -> ParseError pos' msg' | pos' < pos -> ParseError pos msg | otherwise {- pos' == pos -} -> ParseError pos (msg ++ " or " ++ msg') {-# INLINE empty #-} {-# INLINE (<|>) #-} instance Monad Parser where return x = Parser $ \st -> Right (st, x) fail e = Parser $ \st -> Left $ ParseError (position st) e p >>= g = Parser $ \st -> case evalParser p st of Left e -> Left e Right (st',x) -> evalParser (g x) st' # INLINE return # {-# INLINE (>>=) #-} instance MonadPlus Parser where mzero = Parser $ \st -> Left $ ParseError (position st) "(mzero)" mplus p1 p2 = Parser $ \st -> case evalParser p1 st of Right res -> Right res Left _ -> evalParser p2 st # INLINE mzero # # INLINE mplus # instance (a ~ Text) => IsString (Parser a) where fromString = string . Text.pack string :: Text -> Parser Text string s = Parser $ \st -> if s `Text.isPrefixOf` (subject st) then success (advance st s) s else failure st "string" # INLINE string # failure :: ParserState -> String -> Either ParseError (ParserState, a) failure st msg = Left $ ParseError (position st) msg # INLINE failure # success :: ParserState -> a -> Either ParseError (ParserState, a) success st x = Right (st, x) # INLINE success # (<?>) :: Parser a -> String -> Parser a p <?> msg = Parser $ \st -> let startpos = position st in case evalParser p st of Left (ParseError _ _) -> Left $ ParseError startpos msg Right r -> Right r {-# INLINE (<?>) #-} infixl 5 <?> runParser :: Parser a -> Text -> Either ParseError a runParser p t = fmap snd $ evalParser p ParserState { subject = t , position = Position 1 1 1 , lastChar = Nothing } runParserWithUnconsumed :: Parser a -> Text -> Either ParseError (a,Text) runParserWithUnconsumed p t = fmap (\(st,res) -> (res, subject st)) $ evalParser p ParserState { subject = t , position = Position 1 1 1 , lastChar = Nothing } getState :: Parser ParserState getState = Parser (\st -> success st st) getPosition :: Parser Position getPosition = position <$> getState # INLINE getPosition # satisfy :: (Char -> Bool) -> Parser Char satisfy f = Parser g where g st = case Text.uncons (subject st) of Just (c, _) | f c -> success (advance st (Text.singleton c)) c _ -> failure st "character meeting condition" {-# INLINE satisfy #-} -- | Get the next character without consuming it. peekChar :: Parser (Maybe Char) peekChar = maybeHead . subject <$> getState where maybeHead = fmap fst . Text.uncons # INLINE peekChar # -- | Get the last consumed character. peekLastChar :: Parser (Maybe Char) peekLastChar = lastChar <$> getState # INLINE peekLastChar # -- | Takes a parser that returns a 'Text', runs that -- parser consuming some input and then prepends the -- result to the rest of subject. replacing :: Parser Text -> Parser () replacing p = do s0 <- getState t <- p s1Subject <- subject <$> getState Parser $ \_ -> success s0 { subject = Text.append t s1Subject } () endOfInput :: Parser () endOfInput = Parser $ \st -> if Text.null (subject st) then success st () else failure st "end of input" # INLINE endOfInput # -- note: this does not actually change the position in the subject; it only changes what column counts as column It is intended -- to be used in cases where we're parsing a partial line but need to -- have accurate column information. setPosition :: Position -> Parser () setPosition pos = Parser $ \st -> success st{ position = pos } () # INLINE setPosition # takeWhile :: (Char -> Bool) -> Parser Text takeWhile f = Parser $ \st -> let t = Text.takeWhile f (subject st) in success (advance st t) t # INLINE takeWhile # takeWhile1 :: (Char -> Bool) -> Parser Text takeWhile1 f = Parser $ \st -> case Text.takeWhile f (subject st) of t | Text.null t -> failure st "characters satisfying condition" | otherwise -> success (advance st t) t # INLINE takeWhile1 # -- | Consumes all the available input (until endOfInput) and returns it. untilTheEnd :: Parser Text untilTheEnd = Parser $ \st -> success (advance st (subject st)) (subject st) # INLINE untilTheEnd # skip :: (Char -> Bool) -> Parser () skip f = Parser $ \st -> case Text.uncons (subject st) of Just (c,_) | f c -> success (advance st (Text.singleton c)) () _ -> failure st "character satisfying condition" # INLINE skip # skipWhile :: (Char -> Bool) -> Parser () skipWhile f = Parser $ \st -> let t' = Text.takeWhile f (subject st) in success (advance st t') () # INLINE skipWhile # skipWhile1 :: (Char -> Bool) -> Parser () skipWhile1 f = Parser $ \st -> case Text.takeWhile f (subject st) of t' | Text.null t' -> failure st "characters satisfying condition" | otherwise -> success (advance st t') () # INLINE skipWhile1 # stringCaseless :: Text -> Parser Text stringCaseless (Text.toCaseFold -> s) = Parser $ \st -> if Text.toCaseFold s `Text.isPrefixOf` Text.toCaseFold (subject st) then success (advance st s) s else failure st "stringCaseless" # INLINE stringCaseless # scan :: s -> (s -> Char -> Maybe s) -> Parser Text scan s0 f = Parser $ go s0 [] where go s cs st = case Text.uncons (subject st) of Nothing -> finish st cs Just (c, _) -> case f s c of Just s' -> go s' (c:cs) (advance st (Text.singleton c)) Nothing -> finish st cs finish st cs = success st (Text.pack (reverse cs)) # INLINE scan # lookAhead :: Parser a -> Parser a lookAhead p = Parser $ \st -> either (const (failure st "lookAhead")) (success st . snd) (evalParser p st) # INLINE lookAhead # notFollowedBy :: Parser a -> Parser () notFollowedBy p = Parser $ \st -> either (const (success st ())) (const (failure st "notFollowedBy")) (evalParser p st) # INLINE notFollowedBy #
null
https://raw.githubusercontent.com/zudov/haskell-comark/b84cf1d5623008673402da3a5353bdc5891d3a75/comark-parser/src/Comark/ParserCombinators/Prim.hs
haskell
# LANGUAGE TypeFamilies # # LANGUAGE ViewPatterns # | Returns the text that was consumed by a parser alongside with its result # INLINE (<*>) # return error for farthest match pos' == pos # INLINE empty # # INLINE (<|>) # # INLINE (>>=) # # INLINE (<?>) # # INLINE satisfy # | Get the next character without consuming it. | Get the last consumed character. | Takes a parser that returns a 'Text', runs that parser consuming some input and then prepends the result to the rest of subject. note: this does not actually change the position in the subject; to be used in cases where we're parsing a partial line but need to have accurate column information. | Consumes all the available input (until endOfInput) and returns it.
# LANGUAGE RecordWildCards # module Comark.ParserCombinators.Prim ( Position(..) , Parser() , runParser , ParserState() , ParseError(..) , withConsumed , consumedBy , string , (<?>) , runParserWithUnconsumed , getPosition , setPosition , satisfy , peekChar , peekLastChar , replacing , endOfInput , takeWhile , takeWhile1 , untilTheEnd , skip , skipWhile , skipWhile1 , stringCaseless , scan , lookAhead , notFollowedBy ) where import Control.Applicative import Control.Monad import Data.String import Data.Text (Text) import qualified Data.Text as Text import Prelude hiding (takeWhile) data Position = Position { line :: Int , column :: Int , point :: Int } deriving (Ord, Eq) instance Show Position where show (Position ln cn pn) = concat ["line ", show ln, " column ", show cn, " point ", show pn] data ParseError = ParseError { parseErrorPosition :: Position , parseErrorReason :: String } deriving (Show) data ParserState = ParserState { subject :: Text , position :: Position , lastChar :: Maybe Char } advance :: ParserState -> Text -> ParserState advance = Text.foldl' go where go :: ParserState -> Char -> ParserState go st c = ParserState { subject = Text.drop 1 (subject st) , position = case c of '\n' -> Position { line = line (position st) + 1 , column = 1 , point = point (position st) + 1 } _ -> Position { line = line (position st) , column = column (position st) + 1 , point = point (position st) + 1 } , lastChar = Just c } newtype Parser a = Parser { evalParser :: ParserState -> Either ParseError (ParserState, a) } withConsumed :: Parser a -> Parser (a,Text) withConsumed p = Parser $ \st -> case (evalParser p) st of Left err -> Left err Right (st', res) -> let consumedLength = point (position st') - point (position st) in Right (st', (res, Text.take consumedLength (subject st))) consumedBy :: Parser a -> Parser Text consumedBy = fmap snd . withConsumed instance Functor Parser where fmap f (Parser g) = Parser $ \st -> case g st of Right (st', x) -> Right (st', f x) Left e -> Left e # INLINE fmap # instance Applicative Parser where pure x = Parser $ \st -> Right (st, x) (Parser f) <*> (Parser g) = Parser $ \st -> case f st of Left e -> Left e Right (st', h) -> case g st' of Right (st'', x) -> Right (st'', h x) Left e -> Left e # INLINE pure # instance Alternative Parser where empty = Parser $ \st -> Left $ ParseError (position st) "(empty)" (Parser f) <|> (Parser g) = Parser $ \st -> case f st of Right res -> Right res Left (ParseError pos msg) -> case g st of Right res -> Right res Left (ParseError pos' msg') -> Left $ case () of _ | pos' > pos -> ParseError pos' msg' | pos' < pos -> ParseError pos msg -> ParseError pos (msg ++ " or " ++ msg') instance Monad Parser where return x = Parser $ \st -> Right (st, x) fail e = Parser $ \st -> Left $ ParseError (position st) e p >>= g = Parser $ \st -> case evalParser p st of Left e -> Left e Right (st',x) -> evalParser (g x) st' # INLINE return # instance MonadPlus Parser where mzero = Parser $ \st -> Left $ ParseError (position st) "(mzero)" mplus p1 p2 = Parser $ \st -> case evalParser p1 st of Right res -> Right res Left _ -> evalParser p2 st # INLINE mzero # # INLINE mplus # instance (a ~ Text) => IsString (Parser a) where fromString = string . Text.pack string :: Text -> Parser Text string s = Parser $ \st -> if s `Text.isPrefixOf` (subject st) then success (advance st s) s else failure st "string" # INLINE string # failure :: ParserState -> String -> Either ParseError (ParserState, a) failure st msg = Left $ ParseError (position st) msg # INLINE failure # success :: ParserState -> a -> Either ParseError (ParserState, a) success st x = Right (st, x) # INLINE success # (<?>) :: Parser a -> String -> Parser a p <?> msg = Parser $ \st -> let startpos = position st in case evalParser p st of Left (ParseError _ _) -> Left $ ParseError startpos msg Right r -> Right r infixl 5 <?> runParser :: Parser a -> Text -> Either ParseError a runParser p t = fmap snd $ evalParser p ParserState { subject = t , position = Position 1 1 1 , lastChar = Nothing } runParserWithUnconsumed :: Parser a -> Text -> Either ParseError (a,Text) runParserWithUnconsumed p t = fmap (\(st,res) -> (res, subject st)) $ evalParser p ParserState { subject = t , position = Position 1 1 1 , lastChar = Nothing } getState :: Parser ParserState getState = Parser (\st -> success st st) getPosition :: Parser Position getPosition = position <$> getState # INLINE getPosition # satisfy :: (Char -> Bool) -> Parser Char satisfy f = Parser g where g st = case Text.uncons (subject st) of Just (c, _) | f c -> success (advance st (Text.singleton c)) c _ -> failure st "character meeting condition" peekChar :: Parser (Maybe Char) peekChar = maybeHead . subject <$> getState where maybeHead = fmap fst . Text.uncons # INLINE peekChar # peekLastChar :: Parser (Maybe Char) peekLastChar = lastChar <$> getState # INLINE peekLastChar # replacing :: Parser Text -> Parser () replacing p = do s0 <- getState t <- p s1Subject <- subject <$> getState Parser $ \_ -> success s0 { subject = Text.append t s1Subject } () endOfInput :: Parser () endOfInput = Parser $ \st -> if Text.null (subject st) then success st () else failure st "end of input" # INLINE endOfInput # it only changes what column counts as column It is intended setPosition :: Position -> Parser () setPosition pos = Parser $ \st -> success st{ position = pos } () # INLINE setPosition # takeWhile :: (Char -> Bool) -> Parser Text takeWhile f = Parser $ \st -> let t = Text.takeWhile f (subject st) in success (advance st t) t # INLINE takeWhile # takeWhile1 :: (Char -> Bool) -> Parser Text takeWhile1 f = Parser $ \st -> case Text.takeWhile f (subject st) of t | Text.null t -> failure st "characters satisfying condition" | otherwise -> success (advance st t) t # INLINE takeWhile1 # untilTheEnd :: Parser Text untilTheEnd = Parser $ \st -> success (advance st (subject st)) (subject st) # INLINE untilTheEnd # skip :: (Char -> Bool) -> Parser () skip f = Parser $ \st -> case Text.uncons (subject st) of Just (c,_) | f c -> success (advance st (Text.singleton c)) () _ -> failure st "character satisfying condition" # INLINE skip # skipWhile :: (Char -> Bool) -> Parser () skipWhile f = Parser $ \st -> let t' = Text.takeWhile f (subject st) in success (advance st t') () # INLINE skipWhile # skipWhile1 :: (Char -> Bool) -> Parser () skipWhile1 f = Parser $ \st -> case Text.takeWhile f (subject st) of t' | Text.null t' -> failure st "characters satisfying condition" | otherwise -> success (advance st t') () # INLINE skipWhile1 # stringCaseless :: Text -> Parser Text stringCaseless (Text.toCaseFold -> s) = Parser $ \st -> if Text.toCaseFold s `Text.isPrefixOf` Text.toCaseFold (subject st) then success (advance st s) s else failure st "stringCaseless" # INLINE stringCaseless # scan :: s -> (s -> Char -> Maybe s) -> Parser Text scan s0 f = Parser $ go s0 [] where go s cs st = case Text.uncons (subject st) of Nothing -> finish st cs Just (c, _) -> case f s c of Just s' -> go s' (c:cs) (advance st (Text.singleton c)) Nothing -> finish st cs finish st cs = success st (Text.pack (reverse cs)) # INLINE scan # lookAhead :: Parser a -> Parser a lookAhead p = Parser $ \st -> either (const (failure st "lookAhead")) (success st . snd) (evalParser p st) # INLINE lookAhead # notFollowedBy :: Parser a -> Parser () notFollowedBy p = Parser $ \st -> either (const (success st ())) (const (failure st "notFollowedBy")) (evalParser p st) # INLINE notFollowedBy #
0dd469704823d7192bbdcace60458965fd055aa48d9b59fc5bea5f5a017cf4a4
jakemcc/sicp-study
ex4_47.clj
(ns ex4-37) My initial reaction is that change ; does improve the efficiency. It seems to me that because the first ' require check is ; done earlier (only after i and j have been picked, k is still ; unpicked) that the work of chosing a k will not always be done. ; Not doing the work to pick k would cut down on the number of ; possibilities that need to be checked and hence cause an efficiency ; gain
null
https://raw.githubusercontent.com/jakemcc/sicp-study/3b9e3d6c8cc30ad92b0d9bbcbbbfe36a8413f89d/clojure/section4.3/src/ex4_47.clj
clojure
does improve the efficiency. done earlier (only after i and j have been picked, k is still unpicked) that the work of chosing a k will not always be done. Not doing the work to pick k would cut down on the number of possibilities that need to be checked and hence cause an efficiency gain
(ns ex4-37) My initial reaction is that change It seems to me that because the first ' require check is
60d3ddae6ab0e3637c4d7db20d0e1a90e835796190d42d7c174df51c1d3ad45e
jyh/metaprl
m_ir_ast.ml
doc <:doc< @spelling{AST compilable} @module[M_ir_ast] @docoff Convert AST to IR. We name all intermediate computations. @begin[license] Copyright (C) 2003 Adam Granicz, Caltech 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., 675 Mass Ave, Cambridge, MA 02139, USA. Author: Adam Granicz @email{} @end[license] @docon @parents >> extends Base_theory extends M_ast extends M_ir doc docoff open Basic_tactics open Base_meta open M_util doc terms declare IR{'e} declare IR{'e1; v. 'e2['v]} declare IR{'args; 'f; v. 'e['v]} declare IR_size{'tuple; 'init : MetaNum} doc docoff dform ir_df1 : IR{'e} = keyword["IR["] slot{'e} `"]" dform ir_df2 : IR{'e1; v. 'e2} = keyword["IR "] slot{'v} `" = " slot{'e1} keyword[" in"] hspace slot{'e2} dform ir_df3 : IR{'args; 'f; v. 'e2} = keyword["IR "] slot{'v} `" = " slot{'f} `"(" slot{'args} `")" keyword[" in"] hspace slot{'e2} dform ir_df4 : IR_size{'tuple; 'init} = keyword["SIZE_OF["] slot{'tuple} `", " slot{'init} `"]" (************************************************************************ * REDUCTION RESOURCE * ************************************************************************) doc <:doc< @resources @bf{The @Comment!resource[ir_resource]} The @tt[ir] resource provides a generic method for naming intermediate values. The @conv[irC] conversion can be used to apply this evaluator. The implementation of the @tt[ir_resource] and the @tt[irC] conversion rely on tables to store the shape of redices, together with the conversions for the reduction. @docoff >> let resource (term * conv, conv) ir = table_resource_info extract_data let process_ir_resource_rw_annotation = redex_and_conv_of_rw_annotation "ir" doc <:doc< Convert AST operators. >> prim_rw ir_add_op {| ir |} : IR{AstAddOp} <--> AddOp prim_rw ir_sub_op {| ir |} : IR{AstSubOp} <--> SubOp prim_rw ir_mul_op {| ir |} : IR{AstMulOp} <--> MulOp prim_rw ir_div_op {| ir |} : IR{AstDivOp} <--> DivOp prim_rw ir_le_op {| ir |} : IR{AstLeOp} <--> LeOp prim_rw ir_lt_op {| ir |} : IR{AstLtOp} <--> LtOp prim_rw ir_ge_op {| ir |} : IR{AstGeOp} <--> GeOp prim_rw ir_gt_op {| ir |} : IR{AstGtOp} <--> GtOp prim_rw ir_eq_op {| ir |} : IR{AstEqOp} <--> EqOp prim_rw ir_neq_op {| ir |} : IR{AstNeqOp} <--> NeqOp doc <:doc< Translating simple expressions. >> prim_rw ir_num {| ir |} : IR{IntExpr[i:n]; v. 'e['v]} <--> 'e[AtomInt[i:n]] prim_rw ir_bool1 {| ir |} : IR{TrueExpr; v. 'e['v]} <--> 'e[AtomTrue] prim_rw ir_bool2 {| ir |} : IR{FalseExpr; v. 'e['v]} <--> 'e[AtomFalse] prim_rw ir_var {| ir |} : IR{VarExpr{'v}; v2. 'e['v2]} <--> 'e[AtomVar{'v}] doc <:doc< Translating simple operations. >> prim_rw ir_binop {| ir |} : IR{BinopExpr{'op; 'e1; 'e2}; v. 'e['v]} <--> IR{'e1; v1. IR{'e2; v2. 'e[AtomBinop{IR{'op}; 'v1; 'v2}]}} prim_rw ir_relop {| ir |} : IR{RelopExpr{'op; 'e1; 'e2}; v. 'e['v]} <--> IR{'e1; v1. IR{'e2; v2. 'e[AtomRelop{IR{'op}; 'v1; 'v2}]}} doc <:doc< Translating a function in a let definition. >> prim_rw ir_fun_lambda {| ir |} : IR{FunLambdaExpr{v1. 'body['v1]}; v2. 'e['v2]} <--> AtomFun{v1. IR{'body['v1]; v2. 'e['v2]}} doc <:doc< Translating an unnamed function. >> prim_rw ir_lambda {| ir |} : IR{LambdaExpr{v1. 'body['v1]}; v2. 'e['v2]} <--> LetRec{R. Fields{ FunDef{Label["g":s]; AtomFun{v1. IR{'body['v1]; v3. Return{'v3}}}; (**) EndDef}}; R. LetFun{'R; Label["g":s]; g. 'e[AtomVar{'g}]}} doc <:doc< Translating an if expression. >> prim_rw ir_if {| ir |} : IR{IfExpr{'e1; 'e2; 'e3}; v. 'e['v]} <--> LetRec{R. Fields{ FunDef{Label["g":s]; AtomFun{v. 'e[AtomVar{'v}]}; (* ? *) EndDef}}; R. LetFun{'R; Label["g":s]; g. IR{'e1; v1. If{'v1; IR{'e2; v2. TailCall{AtomVar{'g}; ArgCons{'v2; ArgNil}}}; IR{'e3; v3. TailCall{AtomVar{'g}; ArgCons{'v3; ArgNil}}}}}}} doc <:doc< Translating recursive functions. >> prim_rw ir_let_rec {| ir |} : IR{AstLetRec{R. 'bodies['R]; R. 'e1['R]}; v. 'e2['v]} <--> LetRec{R. IR{'bodies['R]}; R. IR{'e1['R]; v. 'e2['v]}} prim_rw ir_fields {| ir |} : IR{AstFields{'fields}} <--> Fields{IR{'fields}} prim_rw ir_label {| ir |} : IR{AstLabel[t:s]} <--> Label[t:s] prim_rw ir_fun_def {| ir |} : IR{AstFunDef{'label; 'e; 'rest}} <--> FunDef{IR{'label}; IR{'e; v. Return{'v}}; IR{'rest}} (**) prim_rw ir_end_def {| ir |} : IR{AstEndDef} <--> EndDef prim_rw ir_let_fun {| ir |} : IR{AstLetFun{'R; 'label; f. 'e['f]}; v. 'cont['v]} <--> LetFun{'R; IR{'label}; f. IR{'e['f]; v. 'cont['v]}} doc <:doc< Translating a let variable definition. >> prim_rw ir_let_var {| ir |} : IR{LetVarExpr{'e1; v. 'e2['v]}; v2. 'e3['v2]} <--> IR{'e1; v1. LetAtom{'v1; v. IR{'e2['v]; v2. 'e3['v2]}}} doc <:doc< Translating a function application. >> prim_rw ir_apply {| ir |} : IR{ApplyExpr{'fe; 'args}; v. 'e['v]} <--> IR{'fe; f. IR{'args; 'f; v. 'e['v]}} doc <:doc< Translating a list of arguments. >> prim_rw ir_arg_cons {| ir |} : IR{AstArgCons{'hd; 'tl}; 'f; v. 'e['v]} <--> IR{'hd; v1. LetApply{'f; 'v1; v2. IR{'tl; AtomVar{'v2}; v. 'e['v]}}} prim_rw ir_arg_nil {| ir |} : IR{AstArgNil; 'f; v. 'e['v]} <--> 'e['f] doc <:doc< Tuples. We use Base_meta arithmetic to figure out the size of a tuple. >> declare succ{'e : MetaNum} : MetaNum prim_rw ir_alloc_tuple_cons {| ir |} : IR{AstAllocTupleCons{'e; 'rest}; v. 'e2['v]} <--> IR{'e; v1. IR{'rest; v2. 'e2[AllocTupleCons{'v1; 'v2}]}} prim_rw ir_alloc_tuple_nil {| ir |} : IR{AstAllocTupleNil; v. 'e['v]} <--> 'e[AllocTupleNil] prim_rw ir_tuple {| ir |} : IR{TupleExpr{'tuple}; v. 'e['v]} <--> IR{'tuple; v. LetTuple{IR_size{'tuple; meta_num[0:n]}; 'v; v2. 'e[AtomVar{'v2}]}} (* Tuple size computations *) prim_rw ir_size1 {| ir |} : IR_size{AstAllocTupleCons{'e; 'rest}; 'count} <--> IR_size{'rest; succ{'count}} prim_rw ir_size2 {| ir |} : IR_size{'AstAllotTupleNil; meta_num[n:n]} <--> Length[n:n] prim_rw reduce_succ {| ir |} : succ{meta_num[n:n]} <--> meta_sum[n:n, 1:n] let resource ir += [ <<meta_sum[i1:n, i2:n]>>, reduce_meta_sum] doc <:doc< Subscripting. >> prim_rw ir_subscript_expr {| ir |} : IR{SubscriptExpr{'e1; 'e2}; v. 'e['v]} <--> IR{'e1; v1. IR{'e2; v2. LetSubscript{'v1; 'v2; v. 'e[AtomVar{'v}]}}} doc <:doc< Assignments. They are *always* followed by an expression. >> prim_rw ir_assign_expr {| ir |} : IR{AssignExpr{'e1; 'e2; 'e3; 'e4}; v. 'e['v]} <--> IR{'e1; v1. IR{'e2; v2. IR{'e3; v3. SetSubscript{'v1; 'v2; 'v3; IR{'e4; v. 'e['v]}}}}} doc <:doc< Some optimizations. >> prim_rw opt_let_var {| ir |} : LetAtom{AtomVar{'v1}; v2. 'e['v2]} <--> 'e['v1] (* *) doc <:doc< A program is compilable if it can be converted to an atom that is the return value of the program. >> prim prog_ir : sequent { <H> >- compilable{IR{'e; v. Return{'v}}} } --> sequent { <H> >- compilable{AST{'e}} } (* * Top-level conversion and tactic. *) let irTopC_env e = get_resource_arg (env_arg e) get_ir_resource let irTopC = funC irTopC_env let irC = repeatC (sweepDnC irTopC) let irT = prog_ir thenT rw irC 0 (* * -*- * Local Variables: * Caml-master: "compile" * End: * -*- *)
null
https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/experimental/compile/m_ir_ast.ml
ocaml
*********************************************************************** * REDUCTION RESOURCE * *********************************************************************** ? Tuple size computations * Top-level conversion and tactic. * -*- * Local Variables: * Caml-master: "compile" * End: * -*-
doc <:doc< @spelling{AST compilable} @module[M_ir_ast] @docoff Convert AST to IR. We name all intermediate computations. @begin[license] Copyright (C) 2003 Adam Granicz, Caltech 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., 675 Mass Ave, Cambridge, MA 02139, USA. Author: Adam Granicz @email{} @end[license] @docon @parents >> extends Base_theory extends M_ast extends M_ir doc docoff open Basic_tactics open Base_meta open M_util doc terms declare IR{'e} declare IR{'e1; v. 'e2['v]} declare IR{'args; 'f; v. 'e['v]} declare IR_size{'tuple; 'init : MetaNum} doc docoff dform ir_df1 : IR{'e} = keyword["IR["] slot{'e} `"]" dform ir_df2 : IR{'e1; v. 'e2} = keyword["IR "] slot{'v} `" = " slot{'e1} keyword[" in"] hspace slot{'e2} dform ir_df3 : IR{'args; 'f; v. 'e2} = keyword["IR "] slot{'v} `" = " slot{'f} `"(" slot{'args} `")" keyword[" in"] hspace slot{'e2} dform ir_df4 : IR_size{'tuple; 'init} = keyword["SIZE_OF["] slot{'tuple} `", " slot{'init} `"]" doc <:doc< @resources @bf{The @Comment!resource[ir_resource]} The @tt[ir] resource provides a generic method for naming intermediate values. The @conv[irC] conversion can be used to apply this evaluator. The implementation of the @tt[ir_resource] and the @tt[irC] conversion rely on tables to store the shape of redices, together with the conversions for the reduction. @docoff >> let resource (term * conv, conv) ir = table_resource_info extract_data let process_ir_resource_rw_annotation = redex_and_conv_of_rw_annotation "ir" doc <:doc< Convert AST operators. >> prim_rw ir_add_op {| ir |} : IR{AstAddOp} <--> AddOp prim_rw ir_sub_op {| ir |} : IR{AstSubOp} <--> SubOp prim_rw ir_mul_op {| ir |} : IR{AstMulOp} <--> MulOp prim_rw ir_div_op {| ir |} : IR{AstDivOp} <--> DivOp prim_rw ir_le_op {| ir |} : IR{AstLeOp} <--> LeOp prim_rw ir_lt_op {| ir |} : IR{AstLtOp} <--> LtOp prim_rw ir_ge_op {| ir |} : IR{AstGeOp} <--> GeOp prim_rw ir_gt_op {| ir |} : IR{AstGtOp} <--> GtOp prim_rw ir_eq_op {| ir |} : IR{AstEqOp} <--> EqOp prim_rw ir_neq_op {| ir |} : IR{AstNeqOp} <--> NeqOp doc <:doc< Translating simple expressions. >> prim_rw ir_num {| ir |} : IR{IntExpr[i:n]; v. 'e['v]} <--> 'e[AtomInt[i:n]] prim_rw ir_bool1 {| ir |} : IR{TrueExpr; v. 'e['v]} <--> 'e[AtomTrue] prim_rw ir_bool2 {| ir |} : IR{FalseExpr; v. 'e['v]} <--> 'e[AtomFalse] prim_rw ir_var {| ir |} : IR{VarExpr{'v}; v2. 'e['v2]} <--> 'e[AtomVar{'v}] doc <:doc< Translating simple operations. >> prim_rw ir_binop {| ir |} : IR{BinopExpr{'op; 'e1; 'e2}; v. 'e['v]} <--> IR{'e1; v1. IR{'e2; v2. 'e[AtomBinop{IR{'op}; 'v1; 'v2}]}} prim_rw ir_relop {| ir |} : IR{RelopExpr{'op; 'e1; 'e2}; v. 'e['v]} <--> IR{'e1; v1. IR{'e2; v2. 'e[AtomRelop{IR{'op}; 'v1; 'v2}]}} doc <:doc< Translating a function in a let definition. >> prim_rw ir_fun_lambda {| ir |} : IR{FunLambdaExpr{v1. 'body['v1]}; v2. 'e['v2]} <--> AtomFun{v1. IR{'body['v1]; v2. 'e['v2]}} doc <:doc< Translating an unnamed function. >> prim_rw ir_lambda {| ir |} : IR{LambdaExpr{v1. 'body['v1]}; v2. 'e['v2]} <--> LetRec{R. Fields{ FunDef{Label["g":s]; AtomFun{v1. IR{'body['v1]; v3. EndDef}}; R. LetFun{'R; Label["g":s]; g. 'e[AtomVar{'g}]}} doc <:doc< Translating an if expression. >> prim_rw ir_if {| ir |} : IR{IfExpr{'e1; 'e2; 'e3}; v. 'e['v]} <--> LetRec{R. Fields{ EndDef}}; R. LetFun{'R; Label["g":s]; g. IR{'e1; v1. If{'v1; IR{'e2; v2. TailCall{AtomVar{'g}; ArgCons{'v2; ArgNil}}}; IR{'e3; v3. TailCall{AtomVar{'g}; ArgCons{'v3; ArgNil}}}}}}} doc <:doc< Translating recursive functions. >> prim_rw ir_let_rec {| ir |} : IR{AstLetRec{R. 'bodies['R]; R. 'e1['R]}; v. 'e2['v]} <--> LetRec{R. IR{'bodies['R]}; R. IR{'e1['R]; v. 'e2['v]}} prim_rw ir_fields {| ir |} : IR{AstFields{'fields}} <--> Fields{IR{'fields}} prim_rw ir_label {| ir |} : IR{AstLabel[t:s]} <--> Label[t:s] prim_rw ir_fun_def {| ir |} : IR{AstFunDef{'label; 'e; 'rest}} <--> prim_rw ir_end_def {| ir |} : IR{AstEndDef} <--> EndDef prim_rw ir_let_fun {| ir |} : IR{AstLetFun{'R; 'label; f. 'e['f]}; v. 'cont['v]} <--> LetFun{'R; IR{'label}; f. IR{'e['f]; v. 'cont['v]}} doc <:doc< Translating a let variable definition. >> prim_rw ir_let_var {| ir |} : IR{LetVarExpr{'e1; v. 'e2['v]}; v2. 'e3['v2]} <--> IR{'e1; v1. LetAtom{'v1; v. IR{'e2['v]; v2. 'e3['v2]}}} doc <:doc< Translating a function application. >> prim_rw ir_apply {| ir |} : IR{ApplyExpr{'fe; 'args}; v. 'e['v]} <--> IR{'fe; f. IR{'args; 'f; v. 'e['v]}} doc <:doc< Translating a list of arguments. >> prim_rw ir_arg_cons {| ir |} : IR{AstArgCons{'hd; 'tl}; 'f; v. 'e['v]} <--> IR{'hd; v1. LetApply{'f; 'v1; v2. IR{'tl; AtomVar{'v2}; v. 'e['v]}}} prim_rw ir_arg_nil {| ir |} : IR{AstArgNil; 'f; v. 'e['v]} <--> 'e['f] doc <:doc< Tuples. We use Base_meta arithmetic to figure out the size of a tuple. >> declare succ{'e : MetaNum} : MetaNum prim_rw ir_alloc_tuple_cons {| ir |} : IR{AstAllocTupleCons{'e; 'rest}; v. 'e2['v]} <--> IR{'e; v1. IR{'rest; v2. 'e2[AllocTupleCons{'v1; 'v2}]}} prim_rw ir_alloc_tuple_nil {| ir |} : IR{AstAllocTupleNil; v. 'e['v]} <--> 'e[AllocTupleNil] prim_rw ir_tuple {| ir |} : IR{TupleExpr{'tuple}; v. 'e['v]} <--> IR{'tuple; v. LetTuple{IR_size{'tuple; meta_num[0:n]}; 'v; v2. 'e[AtomVar{'v2}]}} prim_rw ir_size1 {| ir |} : IR_size{AstAllocTupleCons{'e; 'rest}; 'count} <--> IR_size{'rest; succ{'count}} prim_rw ir_size2 {| ir |} : IR_size{'AstAllotTupleNil; meta_num[n:n]} <--> Length[n:n] prim_rw reduce_succ {| ir |} : succ{meta_num[n:n]} <--> meta_sum[n:n, 1:n] let resource ir += [ <<meta_sum[i1:n, i2:n]>>, reduce_meta_sum] doc <:doc< Subscripting. >> prim_rw ir_subscript_expr {| ir |} : IR{SubscriptExpr{'e1; 'e2}; v. 'e['v]} <--> IR{'e1; v1. IR{'e2; v2. LetSubscript{'v1; 'v2; v. 'e[AtomVar{'v}]}}} doc <:doc< Assignments. They are *always* followed by an expression. >> prim_rw ir_assign_expr {| ir |} : IR{AssignExpr{'e1; 'e2; 'e3; 'e4}; v. 'e['v]} <--> IR{'e1; v1. IR{'e2; v2. IR{'e3; v3. SetSubscript{'v1; 'v2; 'v3; IR{'e4; v. 'e['v]}}}}} doc <:doc< Some optimizations. >> prim_rw opt_let_var {| ir |} : LetAtom{AtomVar{'v1}; v2. 'e['v2]} <--> 'e['v1] doc <:doc< A program is compilable if it can be converted to an atom that is the return value of the program. >> prim prog_ir : sequent { <H> >- compilable{IR{'e; v. Return{'v}}} } --> sequent { <H> >- compilable{AST{'e}} } let irTopC_env e = get_resource_arg (env_arg e) get_ir_resource let irTopC = funC irTopC_env let irC = repeatC (sweepDnC irTopC) let irT = prog_ir thenT rw irC 0
13755b09499888697500625f0f5f641baf6aea842afd73b19399f08b096a89dc
emqx/emqx
emqx_license_cli_SUITE.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %%-------------------------------------------------------------------- -module(emqx_license_cli_SUITE). -compile(nowarn_export_all). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). all() -> emqx_common_test_helpers:all(?MODULE). init_per_suite(Config) -> _ = application:load(emqx_conf), emqx_config:save_schema_mod_and_names(emqx_license_schema), emqx_common_test_helpers:start_apps([emqx_license], fun set_special_configs/1), Config. end_per_suite(_) -> emqx_common_test_helpers:stop_apps([emqx_license]), ok. init_per_testcase(_Case, Config) -> {ok, _} = emqx_cluster_rpc:start_link(node(), emqx_cluster_rpc, 1000), Config. end_per_testcase(_Case, _Config) -> ok. set_special_configs(emqx_license) -> Config = #{key => emqx_license_test_lib:default_license()}, emqx_config:put([license], Config), RawConfig = #{<<"key">> => emqx_license_test_lib:default_license()}, emqx_config:put_raw([<<"license">>], RawConfig); set_special_configs(_) -> ok. %%------------------------------------------------------------------------------ %% Tests %%------------------------------------------------------------------------------ t_help(_Config) -> _ = emqx_license_cli:license([]). t_info(_Config) -> _ = emqx_license_cli:license(["info"]). t_update(_Config) -> LicenseValue = emqx_license_test_lib:default_license(), _ = emqx_license_cli:license(["update", LicenseValue]), _ = emqx_license_cli:license(["reload"]), _ = emqx_license_cli:license(["update", "Invalid License Value"]).
null
https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/lib-ee/emqx_license/test/emqx_license_cli_SUITE.erl
erlang
-------------------------------------------------------------------- -------------------------------------------------------------------- ------------------------------------------------------------------------------ Tests ------------------------------------------------------------------------------
Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . -module(emqx_license_cli_SUITE). -compile(nowarn_export_all). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). all() -> emqx_common_test_helpers:all(?MODULE). init_per_suite(Config) -> _ = application:load(emqx_conf), emqx_config:save_schema_mod_and_names(emqx_license_schema), emqx_common_test_helpers:start_apps([emqx_license], fun set_special_configs/1), Config. end_per_suite(_) -> emqx_common_test_helpers:stop_apps([emqx_license]), ok. init_per_testcase(_Case, Config) -> {ok, _} = emqx_cluster_rpc:start_link(node(), emqx_cluster_rpc, 1000), Config. end_per_testcase(_Case, _Config) -> ok. set_special_configs(emqx_license) -> Config = #{key => emqx_license_test_lib:default_license()}, emqx_config:put([license], Config), RawConfig = #{<<"key">> => emqx_license_test_lib:default_license()}, emqx_config:put_raw([<<"license">>], RawConfig); set_special_configs(_) -> ok. t_help(_Config) -> _ = emqx_license_cli:license([]). t_info(_Config) -> _ = emqx_license_cli:license(["info"]). t_update(_Config) -> LicenseValue = emqx_license_test_lib:default_license(), _ = emqx_license_cli:license(["update", LicenseValue]), _ = emqx_license_cli:license(["reload"]), _ = emqx_license_cli:license(["update", "Invalid License Value"]).
595c6aabadab16c1cff8a20bae1fa2fe90cec72c9ad77b0308f8e8d3773ff3e4
ocaml-multicore/tezos
environment_cache.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2021 Nomadic Labs , < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) type size = int type index = int type identifier = string type key = {identifier : identifier; cache_index : index} let key_encoding = Data_encoding.( conv (fun key -> (key.identifier, key.cache_index)) (fun (identifier, cache_index) -> {identifier; cache_index}) (tup2 string int16)) module Key = struct type t = key let compare k1 k2 = String.compare k1.identifier k2.identifier end module KeyMap = Map.Make (Key) module KeySet = Set.Make (Key) type value_metadata = {size : int; birth : int64; cache_nonce : Bytes.t} let value_metadata_encoding : value_metadata Data_encoding.t = Data_encoding.( conv (fun entry -> (entry.size, entry.birth, entry.cache_nonce)) (fun (size, birth, cache_nonce) -> {size; birth; cache_nonce}) (tup3 int31 int64 Variable.bytes)) let pp_entry ppf (entry : value_metadata) = Format.fprintf ppf "%d/%Ld/%a" entry.size entry.birth Hex.pp (Hex.of_bytes entry.cache_nonce) let equal_value_metadata m1 m2 = m1.size = m2.size && m1.birth = m2.birth && Bytes.equal m1.cache_nonce m2.cache_nonce module Int64Map = Map.Make (Int64) type 'a cache = { (* Each cache has a handle in the context caches. *) index : index; (* [map] collects the cache entries. *) map : ('a * value_metadata) KeyMap.t; (* [lru] maintains a fast index from [birth] to entries. In particular, it provides a logarithmic access to the Least Recently Used entry. *) lru : key Int64Map.t; (* [size] is the sum of all entry sizes. *) size : int; (* [limit] is the maximal size of the cache in memory. This [limit] MUST be greater than any entry size added in cache. This assumption is used for the correctness of the implementation. We enforce this property by preventing any too large entry from entering the cache. Similarly, we enforce the invariant that no entry of null size can enter the cache. *) limit : int; [ counter ] is the maximal age of entries that have been inserted in the cache since its creation . Assuming 100_000 new entries per second , [ counter ] will not overflow before ~3 million years . in the cache since its creation. Assuming 100_000 new entries per second, [counter] will not overflow before ~3 million years. *) counter : int64; (* [removed_entries] maintains the keys removed since last synchronization. *) removed_entries : KeySet.t; (* [entries_removals] maintains the last numbers of entries removal per block. This list cannot be longer than [entries_removals_window_width]. *) entries_removals : int list; } type 'a t = 'a cache FunctionalArray.t option let string_of_key {identifier; _} = identifier let pp_cache fmt {index; map; size; limit; counter; _} = Format.fprintf fmt "@[<v 0>Index: %d@,Cardinal: %d@,Size limit: %d@,Size: %d@,Counter: %Ld%a@]" index (KeyMap.cardinal map) limit size counter (fun ppf map -> KeyMap.iter (fun k (_, entry) -> Format.fprintf ppf "@,Element %s: %a" (string_of_key k) pp_entry entry) map) map let invalid_arg_with_callstack msg = let cs = Printexc.get_callstack 15 in Format.kasprintf invalid_arg "Internal error: %s\nCall stack:\n%s\n" msg (Printexc.raw_backtrace_to_string cs) let with_caches cache f = match cache with | None -> invalid_arg_with_callstack "uninitialized caches" | Some caches -> f caches let cache_of_index t index = with_caches t (fun caches -> FunctionalArray.get caches index) let cache_of_key caches key = cache_of_index caches key.cache_index let lookup_entry cache key = KeyMap.find key cache.map let lookup_value cache key = match lookup_entry cache key with Some (e, _) -> Some e | None -> None let lookup t key = lookup_entry (cache_of_key t key) key let update_cache_with t index cache = with_caches t (fun caches -> Some (FunctionalArray.set caches index cache)) let empty_cache = { index = -1; map = KeyMap.empty; lru = Int64Map.empty; size = 0; counter = 0L; removed_entries = KeySet.empty; entries_removals = []; limit = -1; } let make_caches (layout : size list) = List.iter (fun size -> if size < 0 then invalid_arg_with_callstack "sizes in layout must be nonnegative") layout ; let default = FunctionalArray.make (List.length layout) empty_cache in let folder index array limit = FunctionalArray.set array index {empty_cache with limit; index} in List.fold_left_i folder default layout (* When an entry is fresh, it is assigned a [fresh_entry_nonce]. The actual nonce for this entry will be known only when its block is finalized: it is only in function [sync] that [fresh_entry_nonce] is substituted by a valid [nonce]. *) let fresh_entry_nonce = Bytes.of_string "__FRESH_ENTRY_NONCE__" let remove_cache_entry cache key entry = { cache with map = KeyMap.remove key cache.map; size = cache.size - entry.size; lru = Int64Map.remove entry.birth cache.lru; removed_entries = KeySet.add key cache.removed_entries; } (* The dean is the oldest entry. The complexity of this operation is logarithmic in the number of entries in the cache. Along a given chain, [dean cache] only increases. *) let dean cache : (int64 * key) option = Int64Map.min_binding cache.lru let remove_dean cache = match dean cache with | None -> (* This case is unreachable because [remove_dean] is always called by [enforce_size_limit] with a nonempty cache. *) cache | Some (_, key) -> ( match KeyMap.find key cache.map with | None -> assert false (* because [lru] must point to keys that are in [map]. *) | Some (_, entry) -> remove_cache_entry cache key entry) let rec enforce_size_limit cache = if cache.size > cache.limit then remove_dean cache (* [size] has decreased strictly because if size > limit, then the cache cannot be empty. Hence, this recursive call will converge. *) |> enforce_size_limit else cache let insert_cache_entry cache key ((_, {size; birth; _}) as entry) = { cache with map = KeyMap.add key entry cache.map; size = cache.size + size; counter = max cache.counter birth; lru = Int64Map.add birth key cache.lru; removed_entries = KeySet.remove key cache.removed_entries; } |> enforce_size_limit let insert_cache cache key value size cache_nonce = (* Conforming to entry size invariant: we need this size to be strictly positive. *) let size = max 1 size in let entry = {size; birth = Int64.add cache.counter 1L; cache_nonce} in insert_cache_entry cache key (value, entry) let update_cache cache key entry = let cache = match lookup_entry cache key with | None -> cache | Some (_, old_entry) -> remove_cache_entry cache key old_entry in match entry with | None -> cache | Some (entry, size) -> insert_cache cache key entry size fresh_entry_nonce let update t key entry = let cache = cache_of_key t key in update_cache_with t key.cache_index (update_cache cache key entry) (* We maintain the number of entries removal for the last [entries_removals_window_width] blocks to determine the life expectancy of cache entries. *) let entries_removals_window_width = 5 let median_entries_removals cache = let median l = List.(nth (sort Int.compare l) (length l / 2)) in match median cache.entries_removals with None -> 0 | Some x -> x let uninitialised = None let key_of_identifier ~cache_index identifier = {identifier; cache_index} let identifier_of_key {identifier; _} = identifier let pp fmt = function | None -> Format.fprintf fmt "Unitialised cache" | Some caches -> FunctionalArray.iter (pp_cache fmt) caches let find t key = lookup_value (cache_of_key t key) key let compatible_layout t layout = with_caches t (fun caches -> Compare.List_length_with.(layout = FunctionalArray.length caches) && List.fold_left_i (fun idx r len -> r && (FunctionalArray.get caches idx).limit = len) true layout) let from_layout layout = Some (make_caches layout) let future_cache_expectation t ~time_in_blocks = Some (with_caches t (fun caches -> FunctionalArray.map (fun cache -> let oldness = time_in_blocks * median_entries_removals cache in Utils.fold_n_times oldness remove_dean cache) caches)) let record_entries_removals cache = let entries_removals = if List.compare_length_with cache.entries_removals entries_removals_window_width >= 0 then match cache.entries_removals with | [] -> assert false | _ :: entries_removals -> entries_removals else cache.entries_removals in let entries_removals = entries_removals @ [KeySet.cardinal cache.removed_entries] in {cache with entries_removals; removed_entries = KeySet.empty} (* [update_entry ctxt cache key entry nonce] stores the [entry] identified by [key] in a [cache] of the context. Each fresh entry is marked with the [nonce] to characterize the block that has introduced it. *) let update_entry entry nonce = let element_nonce = if Bytes.equal entry.cache_nonce fresh_entry_nonce then nonce else entry.cache_nonce in {entry with cache_nonce = element_nonce} (* [finalize_cache ctxt cache nonce] sets the cache nonce for the new entries. This function returns the cache for the next block. *) let finalize_cache ({map; _} as cache) nonce = let map = KeyMap.map (fun (e, entry) -> (e, update_entry entry nonce)) map in let metamap = KeyMap.map snd map in ({cache with map}, metamap) * A subcache has a domain composed of : - [ keys ] to restore the in - memory representation of the subcache at loading time ; - [ counter ] to restart the generation of " birth dates " for new entries at the right counter . [ counter ] is important because restarting from [ 0 ] does not work . Indeed , a baker that reloads the cache from the domain must be able to reconstruct the exact same cache as the validator . The validator maintains a cache in memory by inheriting it from the predecessor block : hence its counter is never reset . A subcache has a domain composed of: - [keys] to restore the in-memory representation of the subcache at loading time ; - [counter] to restart the generation of "birth dates" for new entries at the right counter. [counter] is important because restarting from [0] does not work. Indeed, a baker that reloads the cache from the domain must be able to reconstruct the exact same cache as the validator. The validator maintains a cache in memory by inheriting it from the predecessor block: hence its counter is never reset. *) type subcache_domain = {keys : value_metadata KeyMap.t; counter : int64} type domain = subcache_domain list let sync_cache cache ~cache_nonce = let cache = enforce_size_limit cache in let cache = record_entries_removals cache in let (cache, new_entries) = finalize_cache cache cache_nonce in (cache, {keys = new_entries; counter = cache.counter}) let subcache_keys_encoding : value_metadata KeyMap.t Data_encoding.t = Data_encoding.( conv KeyMap.bindings (fun b -> KeyMap.of_seq (List.to_seq b)) (list (dynamic_size (tup2 key_encoding value_metadata_encoding)))) let subcache_domain_encoding : subcache_domain Data_encoding.t = Data_encoding.( conv (fun {keys; counter} -> (keys, counter)) (fun (keys, counter) -> {keys; counter}) (obj2 (req "keys" subcache_keys_encoding) (req "counter" int64))) let domain_encoding : domain Data_encoding.t = Data_encoding.(list subcache_domain_encoding) let equal_subdomain s1 s2 = s1.counter = s2.counter && KeyMap.equal equal_value_metadata s1.keys s2.keys let empty_domain = List.is_empty let sync t ~cache_nonce = with_caches t @@ fun caches -> FunctionalArray.fold_map (fun acc cache -> let (cache, domain) = sync_cache cache ~cache_nonce in (domain :: acc, cache)) caches [] empty_cache |> fun (rev_domains, caches) -> (Some caches, List.rev rev_domains) let update_cache_key t key value meta = with_caches t @@ fun caches -> let cache = FunctionalArray.get caches key.cache_index in let cache = insert_cache_entry cache key (value, meta) in update_cache_with t key.cache_index cache let clear_cache cache = { index = cache.index; limit = cache.limit; map = KeyMap.empty; size = 0; counter = 0L; lru = Int64Map.empty; entries_removals = []; removed_entries = KeySet.empty; } let clear t = Some (with_caches t (fun caches -> FunctionalArray.map clear_cache caches)) let from_cache initial domain ~value_of_key = let domain' = Array.of_list domain in let cache = with_caches (clear initial) @@ fun caches -> FunctionalArray.mapi (fun i (cache : 'a cache) -> if i = -1 then cache else if i >= Array.length domain' then (* By precondition: the layout of [domain] and [initial] must be the same. *) invalid_arg_with_callstack "invalid usage of from_cache" else let subdomain = domain'.(i) in {cache with counter = subdomain.counter}) caches in let fold_cache_keys subdomain cache = KeyMap.fold_es (fun key entry cache -> (match lookup initial key with | None -> value_of_key key | Some (value, entry') -> if Bytes.equal entry.cache_nonce entry'.cache_nonce then return value else value_of_key key) >>=? fun value -> return (update_cache_key cache key value entry)) subdomain.keys cache in List.fold_left_es (fun cache subdomain -> fold_cache_keys subdomain cache) (Some cache) domain let number_of_caches t = with_caches t FunctionalArray.length let on_cache t cache_index f = if cache_index < number_of_caches t && cache_index >= 0 then Some (f (cache_of_index t cache_index)) else None let cache_size t ~cache_index = on_cache t cache_index @@ fun cache -> cache.size let cache_size_limit t ~cache_index = on_cache t cache_index @@ fun cache -> cache.limit let list_keys t ~cache_index = on_cache t cache_index @@ fun cache -> let xs = KeyMap.fold (fun k (_, {size; birth; _}) acc -> (k, size, birth) :: acc) cache.map [] in xs |> List.sort (fun (_, _, b1) (_, _, b2) -> Int64.compare b1 b2) |> List.map (fun (k, s, _) -> (k, s)) let key_rank ctxt key = let cache = cache_of_key ctxt key in let rec length_until x n = function | [] -> Some n | y :: ys -> if Key.compare x y = 0 then Some n else length_until x (n + 1) ys in if not @@ KeyMap.mem key cache.map then None else Int64Map.bindings cache.lru |> List.map snd |> length_until key 0 module Internal_for_tests = struct let equal_domain d1 d2 = List.equal equal_subdomain d1 d2 end
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/lib_protocol_environment/environment_cache.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** Each cache has a handle in the context caches. [map] collects the cache entries. [lru] maintains a fast index from [birth] to entries. In particular, it provides a logarithmic access to the Least Recently Used entry. [size] is the sum of all entry sizes. [limit] is the maximal size of the cache in memory. This [limit] MUST be greater than any entry size added in cache. This assumption is used for the correctness of the implementation. We enforce this property by preventing any too large entry from entering the cache. Similarly, we enforce the invariant that no entry of null size can enter the cache. [removed_entries] maintains the keys removed since last synchronization. [entries_removals] maintains the last numbers of entries removal per block. This list cannot be longer than [entries_removals_window_width]. When an entry is fresh, it is assigned a [fresh_entry_nonce]. The actual nonce for this entry will be known only when its block is finalized: it is only in function [sync] that [fresh_entry_nonce] is substituted by a valid [nonce]. The dean is the oldest entry. The complexity of this operation is logarithmic in the number of entries in the cache. Along a given chain, [dean cache] only increases. This case is unreachable because [remove_dean] is always called by [enforce_size_limit] with a nonempty cache. because [lru] must point to keys that are in [map]. [size] has decreased strictly because if size > limit, then the cache cannot be empty. Hence, this recursive call will converge. Conforming to entry size invariant: we need this size to be strictly positive. We maintain the number of entries removal for the last [entries_removals_window_width] blocks to determine the life expectancy of cache entries. [update_entry ctxt cache key entry nonce] stores the [entry] identified by [key] in a [cache] of the context. Each fresh entry is marked with the [nonce] to characterize the block that has introduced it. [finalize_cache ctxt cache nonce] sets the cache nonce for the new entries. This function returns the cache for the next block. By precondition: the layout of [domain] and [initial] must be the same.
Copyright ( c ) 2021 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING type size = int type index = int type identifier = string type key = {identifier : identifier; cache_index : index} let key_encoding = Data_encoding.( conv (fun key -> (key.identifier, key.cache_index)) (fun (identifier, cache_index) -> {identifier; cache_index}) (tup2 string int16)) module Key = struct type t = key let compare k1 k2 = String.compare k1.identifier k2.identifier end module KeyMap = Map.Make (Key) module KeySet = Set.Make (Key) type value_metadata = {size : int; birth : int64; cache_nonce : Bytes.t} let value_metadata_encoding : value_metadata Data_encoding.t = Data_encoding.( conv (fun entry -> (entry.size, entry.birth, entry.cache_nonce)) (fun (size, birth, cache_nonce) -> {size; birth; cache_nonce}) (tup3 int31 int64 Variable.bytes)) let pp_entry ppf (entry : value_metadata) = Format.fprintf ppf "%d/%Ld/%a" entry.size entry.birth Hex.pp (Hex.of_bytes entry.cache_nonce) let equal_value_metadata m1 m2 = m1.size = m2.size && m1.birth = m2.birth && Bytes.equal m1.cache_nonce m2.cache_nonce module Int64Map = Map.Make (Int64) type 'a cache = { index : index; map : ('a * value_metadata) KeyMap.t; lru : key Int64Map.t; size : int; limit : int; [ counter ] is the maximal age of entries that have been inserted in the cache since its creation . Assuming 100_000 new entries per second , [ counter ] will not overflow before ~3 million years . in the cache since its creation. Assuming 100_000 new entries per second, [counter] will not overflow before ~3 million years. *) counter : int64; removed_entries : KeySet.t; entries_removals : int list; } type 'a t = 'a cache FunctionalArray.t option let string_of_key {identifier; _} = identifier let pp_cache fmt {index; map; size; limit; counter; _} = Format.fprintf fmt "@[<v 0>Index: %d@,Cardinal: %d@,Size limit: %d@,Size: %d@,Counter: %Ld%a@]" index (KeyMap.cardinal map) limit size counter (fun ppf map -> KeyMap.iter (fun k (_, entry) -> Format.fprintf ppf "@,Element %s: %a" (string_of_key k) pp_entry entry) map) map let invalid_arg_with_callstack msg = let cs = Printexc.get_callstack 15 in Format.kasprintf invalid_arg "Internal error: %s\nCall stack:\n%s\n" msg (Printexc.raw_backtrace_to_string cs) let with_caches cache f = match cache with | None -> invalid_arg_with_callstack "uninitialized caches" | Some caches -> f caches let cache_of_index t index = with_caches t (fun caches -> FunctionalArray.get caches index) let cache_of_key caches key = cache_of_index caches key.cache_index let lookup_entry cache key = KeyMap.find key cache.map let lookup_value cache key = match lookup_entry cache key with Some (e, _) -> Some e | None -> None let lookup t key = lookup_entry (cache_of_key t key) key let update_cache_with t index cache = with_caches t (fun caches -> Some (FunctionalArray.set caches index cache)) let empty_cache = { index = -1; map = KeyMap.empty; lru = Int64Map.empty; size = 0; counter = 0L; removed_entries = KeySet.empty; entries_removals = []; limit = -1; } let make_caches (layout : size list) = List.iter (fun size -> if size < 0 then invalid_arg_with_callstack "sizes in layout must be nonnegative") layout ; let default = FunctionalArray.make (List.length layout) empty_cache in let folder index array limit = FunctionalArray.set array index {empty_cache with limit; index} in List.fold_left_i folder default layout let fresh_entry_nonce = Bytes.of_string "__FRESH_ENTRY_NONCE__" let remove_cache_entry cache key entry = { cache with map = KeyMap.remove key cache.map; size = cache.size - entry.size; lru = Int64Map.remove entry.birth cache.lru; removed_entries = KeySet.add key cache.removed_entries; } let dean cache : (int64 * key) option = Int64Map.min_binding cache.lru let remove_dean cache = match dean cache with | None -> cache | Some (_, key) -> ( match KeyMap.find key cache.map with | None -> assert false | Some (_, entry) -> remove_cache_entry cache key entry) let rec enforce_size_limit cache = if cache.size > cache.limit then remove_dean cache |> enforce_size_limit else cache let insert_cache_entry cache key ((_, {size; birth; _}) as entry) = { cache with map = KeyMap.add key entry cache.map; size = cache.size + size; counter = max cache.counter birth; lru = Int64Map.add birth key cache.lru; removed_entries = KeySet.remove key cache.removed_entries; } |> enforce_size_limit let insert_cache cache key value size cache_nonce = let size = max 1 size in let entry = {size; birth = Int64.add cache.counter 1L; cache_nonce} in insert_cache_entry cache key (value, entry) let update_cache cache key entry = let cache = match lookup_entry cache key with | None -> cache | Some (_, old_entry) -> remove_cache_entry cache key old_entry in match entry with | None -> cache | Some (entry, size) -> insert_cache cache key entry size fresh_entry_nonce let update t key entry = let cache = cache_of_key t key in update_cache_with t key.cache_index (update_cache cache key entry) let entries_removals_window_width = 5 let median_entries_removals cache = let median l = List.(nth (sort Int.compare l) (length l / 2)) in match median cache.entries_removals with None -> 0 | Some x -> x let uninitialised = None let key_of_identifier ~cache_index identifier = {identifier; cache_index} let identifier_of_key {identifier; _} = identifier let pp fmt = function | None -> Format.fprintf fmt "Unitialised cache" | Some caches -> FunctionalArray.iter (pp_cache fmt) caches let find t key = lookup_value (cache_of_key t key) key let compatible_layout t layout = with_caches t (fun caches -> Compare.List_length_with.(layout = FunctionalArray.length caches) && List.fold_left_i (fun idx r len -> r && (FunctionalArray.get caches idx).limit = len) true layout) let from_layout layout = Some (make_caches layout) let future_cache_expectation t ~time_in_blocks = Some (with_caches t (fun caches -> FunctionalArray.map (fun cache -> let oldness = time_in_blocks * median_entries_removals cache in Utils.fold_n_times oldness remove_dean cache) caches)) let record_entries_removals cache = let entries_removals = if List.compare_length_with cache.entries_removals entries_removals_window_width >= 0 then match cache.entries_removals with | [] -> assert false | _ :: entries_removals -> entries_removals else cache.entries_removals in let entries_removals = entries_removals @ [KeySet.cardinal cache.removed_entries] in {cache with entries_removals; removed_entries = KeySet.empty} let update_entry entry nonce = let element_nonce = if Bytes.equal entry.cache_nonce fresh_entry_nonce then nonce else entry.cache_nonce in {entry with cache_nonce = element_nonce} let finalize_cache ({map; _} as cache) nonce = let map = KeyMap.map (fun (e, entry) -> (e, update_entry entry nonce)) map in let metamap = KeyMap.map snd map in ({cache with map}, metamap) * A subcache has a domain composed of : - [ keys ] to restore the in - memory representation of the subcache at loading time ; - [ counter ] to restart the generation of " birth dates " for new entries at the right counter . [ counter ] is important because restarting from [ 0 ] does not work . Indeed , a baker that reloads the cache from the domain must be able to reconstruct the exact same cache as the validator . The validator maintains a cache in memory by inheriting it from the predecessor block : hence its counter is never reset . A subcache has a domain composed of: - [keys] to restore the in-memory representation of the subcache at loading time ; - [counter] to restart the generation of "birth dates" for new entries at the right counter. [counter] is important because restarting from [0] does not work. Indeed, a baker that reloads the cache from the domain must be able to reconstruct the exact same cache as the validator. The validator maintains a cache in memory by inheriting it from the predecessor block: hence its counter is never reset. *) type subcache_domain = {keys : value_metadata KeyMap.t; counter : int64} type domain = subcache_domain list let sync_cache cache ~cache_nonce = let cache = enforce_size_limit cache in let cache = record_entries_removals cache in let (cache, new_entries) = finalize_cache cache cache_nonce in (cache, {keys = new_entries; counter = cache.counter}) let subcache_keys_encoding : value_metadata KeyMap.t Data_encoding.t = Data_encoding.( conv KeyMap.bindings (fun b -> KeyMap.of_seq (List.to_seq b)) (list (dynamic_size (tup2 key_encoding value_metadata_encoding)))) let subcache_domain_encoding : subcache_domain Data_encoding.t = Data_encoding.( conv (fun {keys; counter} -> (keys, counter)) (fun (keys, counter) -> {keys; counter}) (obj2 (req "keys" subcache_keys_encoding) (req "counter" int64))) let domain_encoding : domain Data_encoding.t = Data_encoding.(list subcache_domain_encoding) let equal_subdomain s1 s2 = s1.counter = s2.counter && KeyMap.equal equal_value_metadata s1.keys s2.keys let empty_domain = List.is_empty let sync t ~cache_nonce = with_caches t @@ fun caches -> FunctionalArray.fold_map (fun acc cache -> let (cache, domain) = sync_cache cache ~cache_nonce in (domain :: acc, cache)) caches [] empty_cache |> fun (rev_domains, caches) -> (Some caches, List.rev rev_domains) let update_cache_key t key value meta = with_caches t @@ fun caches -> let cache = FunctionalArray.get caches key.cache_index in let cache = insert_cache_entry cache key (value, meta) in update_cache_with t key.cache_index cache let clear_cache cache = { index = cache.index; limit = cache.limit; map = KeyMap.empty; size = 0; counter = 0L; lru = Int64Map.empty; entries_removals = []; removed_entries = KeySet.empty; } let clear t = Some (with_caches t (fun caches -> FunctionalArray.map clear_cache caches)) let from_cache initial domain ~value_of_key = let domain' = Array.of_list domain in let cache = with_caches (clear initial) @@ fun caches -> FunctionalArray.mapi (fun i (cache : 'a cache) -> if i = -1 then cache else if i >= Array.length domain' then invalid_arg_with_callstack "invalid usage of from_cache" else let subdomain = domain'.(i) in {cache with counter = subdomain.counter}) caches in let fold_cache_keys subdomain cache = KeyMap.fold_es (fun key entry cache -> (match lookup initial key with | None -> value_of_key key | Some (value, entry') -> if Bytes.equal entry.cache_nonce entry'.cache_nonce then return value else value_of_key key) >>=? fun value -> return (update_cache_key cache key value entry)) subdomain.keys cache in List.fold_left_es (fun cache subdomain -> fold_cache_keys subdomain cache) (Some cache) domain let number_of_caches t = with_caches t FunctionalArray.length let on_cache t cache_index f = if cache_index < number_of_caches t && cache_index >= 0 then Some (f (cache_of_index t cache_index)) else None let cache_size t ~cache_index = on_cache t cache_index @@ fun cache -> cache.size let cache_size_limit t ~cache_index = on_cache t cache_index @@ fun cache -> cache.limit let list_keys t ~cache_index = on_cache t cache_index @@ fun cache -> let xs = KeyMap.fold (fun k (_, {size; birth; _}) acc -> (k, size, birth) :: acc) cache.map [] in xs |> List.sort (fun (_, _, b1) (_, _, b2) -> Int64.compare b1 b2) |> List.map (fun (k, s, _) -> (k, s)) let key_rank ctxt key = let cache = cache_of_key ctxt key in let rec length_until x n = function | [] -> Some n | y :: ys -> if Key.compare x y = 0 then Some n else length_until x (n + 1) ys in if not @@ KeyMap.mem key cache.map then None else Int64Map.bindings cache.lru |> List.map snd |> length_until key 0 module Internal_for_tests = struct let equal_domain d1 d2 = List.equal equal_subdomain d1 d2 end
80b70c780dbabffa632a1f3c94b20d343ecc22d7bfb9f7a1065b0c797241196e
grin-compiler/ghc-wpc-sample-programs
EPUB.hs
# LANGUAGE TupleSections # {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} | Module : Text . Pandoc . Readers . EPUB Copyright : Copyright ( C ) 2014 - 2020 License : GNU GPL , version 2 or above Maintainer : < > Stability : alpha Portability : portable Conversion of EPUB to ' Pandoc ' document . Module : Text.Pandoc.Readers.EPUB Copyright : Copyright (C) 2014-2020 Matthew Pickering License : GNU GPL, version 2 or above Maintainer : John MacFarlane <> Stability : alpha Portability : portable Conversion of EPUB to 'Pandoc' document. -} module Text.Pandoc.Readers.EPUB (readEPUB) where import Codec.Archive.Zip (Archive (..), Entry, findEntryByPath, fromEntry, toArchiveOrFail) import Control.DeepSeq (NFData, deepseq) import Control.Monad (guard, liftM, liftM2, mplus) import Control.Monad.Except (throwError) import qualified Data.ByteString.Lazy as BL (ByteString) import Data.List (isInfixOf) import qualified Data.Text as T import qualified Data.Map as M (Map, elems, fromList, lookup) import Data.Maybe (fromMaybe, mapMaybe) import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import Network.URI (unEscapeString) import System.FilePath (dropFileName, dropFileName, normalise, splitFileName, takeFileName, (</>)) import qualified Text.Pandoc.Builder as B import Text.Pandoc.Class.PandocMonad (PandocMonad, insertMedia) import Text.Pandoc.Definition hiding (Attr) import Text.Pandoc.Error import Text.Pandoc.Extensions (Extension (Ext_raw_html), enableExtension) import Text.Pandoc.MIME (MimeType) import Text.Pandoc.Options (ReaderOptions (..)) import Text.Pandoc.Readers.HTML (readHtml) import Text.Pandoc.Shared (addMetaField, collapseFilePath, escapeURI) import qualified Text.Pandoc.UTF8 as UTF8 (toStringLazy) import Text.Pandoc.Walk (query, walk) import Text.XML.Light type Items = M.Map String (FilePath, MimeType) readEPUB :: PandocMonad m => ReaderOptions -> BL.ByteString -> m Pandoc readEPUB opts bytes = case toArchiveOrFail bytes of Right archive -> archiveToEPUB opts archive Left _ -> throwError $ PandocParseError "Couldn't extract ePub file" -- runEPUB :: Except PandocError a -> Either PandocError a -- runEPUB = runExcept -- Note that internal reference are aggressively normalised so that all ids -- are of the form "filename#id" -- archiveToEPUB :: (PandocMonad m) => ReaderOptions -> Archive -> m Pandoc archiveToEPUB os archive = do -- root is path to folder with manifest file in (root, content) <- getManifest archive (coverId, meta) <- parseMeta content (cover, items) <- parseManifest content coverId -- No need to collapse here as the image path is from the manifest file let coverDoc = maybe mempty imageToPandoc cover spine <- parseSpine items content let escapedSpine = map (escapeURI . T.pack . takeFileName . fst) spine Pandoc _ bs <- foldM' (\a b -> ((a <>) . walk (prependHash escapedSpine)) `liftM` parseSpineElem root b) mempty spine let ast = coverDoc <> Pandoc meta bs fetchImages (M.elems items) root archive ast return ast where os' = os {readerExtensions = enableExtension Ext_raw_html (readerExtensions os)} parseSpineElem :: PandocMonad m => FilePath -> (FilePath, MimeType) -> m Pandoc parseSpineElem (normalise -> r) (normalise -> path, mime) = do doc <- mimeToReader mime r path let docSpan = B.doc $ B.para $ B.spanWith (T.pack $ takeFileName path, [], []) mempty return $ docSpan <> doc mimeToReader :: PandocMonad m => MimeType -> FilePath -> FilePath -> m Pandoc mimeToReader "application/xhtml+xml" (unEscapeString -> root) (unEscapeString -> path) = do fname <- findEntryByPathE (root </> path) archive html <- readHtml os' . TL.toStrict . TL.decodeUtf8 $ fromEntry fname return $ fixInternalReferences path html mimeToReader s _ (unEscapeString -> path) | s `elem` imageMimes = return $ imageToPandoc path | otherwise = return mempty -- paths should be absolute when this function is called -- renameImages should do this fetchImages :: PandocMonad m => [(FilePath, MimeType)] -> FilePath -- ^ Root -> Archive -> Pandoc -> m () fetchImages mimes root arc (query iq -> links) = mapM_ (uncurry3 insertMedia) (mapMaybe getEntry links) where getEntry link = let abslink = normalise (unEscapeString (root </> link)) in (link , lookup link mimes, ) . fromEntry <$> findEntryByPath abslink arc iq :: Inline -> [FilePath] iq (Image _ _ (url, _)) = [T.unpack url] iq _ = [] -- Remove relative paths renameImages :: FilePath -> Inline -> Inline renameImages root img@(Image attr a (url, b)) | "data:" `T.isPrefixOf` url = img | otherwise = Image attr a ( T.pack $ collapseFilePath (root </> T.unpack url) , b) renameImages _ x = x imageToPandoc :: FilePath -> Pandoc imageToPandoc s = B.doc . B.para $ B.image (T.pack s) "" mempty imageMimes :: [MimeType] imageMimes = ["image/gif", "image/jpeg", "image/png"] type CoverId = String type CoverImage = FilePath parseManifest :: (PandocMonad m) => Element -> Maybe CoverId -> m (Maybe CoverImage, Items) parseManifest content coverId = do manifest <- findElementE (dfName "manifest") content let items = findChildren (dfName "item") manifest r <- mapM parseItem items let cover = findAttr (emptyName "href") =<< filterChild findCover manifest return (cover `mplus` coverId, M.fromList r) where findCover e = maybe False (isInfixOf "cover-image") (findAttr (emptyName "properties") e) || fromMaybe False (liftM2 (==) coverId (findAttr (emptyName "id") e)) parseItem e = do uid <- findAttrE (emptyName "id") e href <- findAttrE (emptyName "href") e mime <- findAttrE (emptyName "media-type") e return (uid, (href, T.pack mime)) parseSpine :: PandocMonad m => Items -> Element -> m [(FilePath, MimeType)] parseSpine is e = do spine <- findElementE (dfName "spine") e let itemRefs = findChildren (dfName "itemref") spine mapM (mkE "parseSpine" . flip M.lookup is) $ mapMaybe parseItemRef itemRefs where parseItemRef ref = do let linear = maybe True (== "yes") (findAttr (emptyName "linear") ref) guard linear findAttr (emptyName "idref") ref parseMeta :: PandocMonad m => Element -> m (Maybe CoverId, Meta) parseMeta content = do meta <- findElementE (dfName "metadata") content let dcspace (QName _ (Just "/") (Just "dc")) = True dcspace _ = False let dcs = filterChildrenName dcspace meta let r = foldr parseMetaItem nullMeta dcs let coverId = findAttr (emptyName "content") =<< filterChild findCover meta return (coverId, r) where findCover e = findAttr (emptyName "name") e == Just "cover" -- -publications.html#sec-metadata-elem parseMetaItem :: Element -> Meta -> Meta parseMetaItem e@(stripNamespace . elName -> field) meta = addMetaField (renameMeta field) (B.str $ T.pack $ strContent e) meta renameMeta :: String -> T.Text renameMeta "creator" = "author" renameMeta s = T.pack s getManifest :: PandocMonad m => Archive -> m (String, Element) getManifest archive = do metaEntry <- findEntryByPathE ("META-INF" </> "container.xml") archive docElem <- (parseXMLDocE . UTF8.toStringLazy . fromEntry) metaEntry let namespaces = mapMaybe attrToNSPair (elAttribs docElem) ns <- mkE "xmlns not in namespaces" (lookup "xmlns" namespaces) as <- fmap (map attrToPair . elAttribs) (findElementE (QName "rootfile" (Just ns) Nothing) docElem) manifestFile <- mkE "Root not found" (lookup "full-path" as) let rootdir = dropFileName manifestFile --mime <- lookup "media-type" as manifest <- findEntryByPathE manifestFile archive fmap ((,) rootdir) (parseXMLDocE . UTF8.toStringLazy . fromEntry $ manifest) Fixup fixInternalReferences :: FilePath -> Pandoc -> Pandoc fixInternalReferences pathToFile = walk (renameImages root) . walk (fixBlockIRs filename) . walk (fixInlineIRs filename) where (root, T.unpack . escapeURI . T.pack -> filename) = splitFileName pathToFile fixInlineIRs :: String -> Inline -> Inline fixInlineIRs s (Span as v) = Span (fixAttrs s as) v fixInlineIRs s (Code as code) = Code (fixAttrs s as) code fixInlineIRs s (Link as is (T.uncons -> Just ('#', url), tit)) = Link (fixAttrs s as) is (addHash s url, tit) fixInlineIRs s (Link as is t) = Link (fixAttrs s as) is t fixInlineIRs _ v = v prependHash :: [T.Text] -> Inline -> Inline prependHash ps l@(Link attr is (url, tit)) | or [s `T.isPrefixOf` url | s <- ps] = Link attr is ("#" <> url, tit) | otherwise = l prependHash _ i = i fixBlockIRs :: String -> Block -> Block fixBlockIRs s (Div as b) = Div (fixAttrs s as) b fixBlockIRs s (Header i as b) = Header i (fixAttrs s as) b fixBlockIRs s (CodeBlock as code) = CodeBlock (fixAttrs s as) code fixBlockIRs _ b = b fixAttrs :: FilePath -> B.Attr -> B.Attr fixAttrs s (ident, cs, kvs) = (addHash s ident, filter (not . T.null) cs, removeEPUBAttrs kvs) addHash :: String -> T.Text -> T.Text addHash _ "" = "" addHash s ident = T.pack (takeFileName s) <> "#" <> ident removeEPUBAttrs :: [(T.Text, T.Text)] -> [(T.Text, T.Text)] removeEPUBAttrs kvs = filter (not . isEPUBAttr) kvs isEPUBAttr :: (T.Text, a) -> Bool isEPUBAttr (k, _) = "epub:" `T.isPrefixOf` k Library -- Strict version of foldM foldM' :: (Monad m, NFData a) => (a -> b -> m a) -> a -> [b] -> m a foldM' _ z [] = return z foldM' f z (x:xs) = do z' <- f z x z' `deepseq` foldM' f z' xs uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (a, b, c) = f a b c -- Utility stripNamespace :: QName -> String stripNamespace (QName v _ _) = v attrToNSPair :: Attr -> Maybe (String, String) attrToNSPair (Attr (QName "xmlns" _ _) val) = Just ("xmlns", val) attrToNSPair _ = Nothing attrToPair :: Attr -> (String, String) attrToPair (Attr (QName name _ _) val) = (name, val) defaultNameSpace :: Maybe String defaultNameSpace = Just "" dfName :: String -> QName dfName s = QName s defaultNameSpace Nothing emptyName :: String -> QName emptyName s = QName s Nothing Nothing -- Convert Maybe interface to Either findAttrE :: PandocMonad m => QName -> Element -> m String findAttrE q e = mkE "findAttr" $ findAttr q e findEntryByPathE :: PandocMonad m => FilePath -> Archive -> m Entry findEntryByPathE (normalise . unEscapeString -> path) a = mkE ("No entry on path: " ++ path) $ findEntryByPath path a parseXMLDocE :: PandocMonad m => String -> m Element parseXMLDocE doc = mkE "Unable to parse XML doc" $ parseXMLDoc doc findElementE :: PandocMonad m => QName -> Element -> m Element findElementE e x = mkE ("Unable to find element: " ++ show e) $ findElement e x mkE :: PandocMonad m => String -> Maybe a -> m a mkE s = maybe (throwError . PandocParseError $ T.pack s) return
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/pandoc-11df2a3c0f2b1b8e351ad8caaa7cdf583e1b3b2e/src/Text/Pandoc/Readers/EPUB.hs
haskell
# LANGUAGE ViewPatterns # # LANGUAGE OverloadedStrings # runEPUB :: Except PandocError a -> Either PandocError a runEPUB = runExcept Note that internal reference are aggressively normalised so that all ids are of the form "filename#id" root is path to folder with manifest file in No need to collapse here as the image path is from the manifest file paths should be absolute when this function is called renameImages should do this ^ Root Remove relative paths -publications.html#sec-metadata-elem mime <- lookup "media-type" as Strict version of foldM Utility Convert Maybe interface to Either
# LANGUAGE TupleSections # | Module : Text . Pandoc . Readers . EPUB Copyright : Copyright ( C ) 2014 - 2020 License : GNU GPL , version 2 or above Maintainer : < > Stability : alpha Portability : portable Conversion of EPUB to ' Pandoc ' document . Module : Text.Pandoc.Readers.EPUB Copyright : Copyright (C) 2014-2020 Matthew Pickering License : GNU GPL, version 2 or above Maintainer : John MacFarlane <> Stability : alpha Portability : portable Conversion of EPUB to 'Pandoc' document. -} module Text.Pandoc.Readers.EPUB (readEPUB) where import Codec.Archive.Zip (Archive (..), Entry, findEntryByPath, fromEntry, toArchiveOrFail) import Control.DeepSeq (NFData, deepseq) import Control.Monad (guard, liftM, liftM2, mplus) import Control.Monad.Except (throwError) import qualified Data.ByteString.Lazy as BL (ByteString) import Data.List (isInfixOf) import qualified Data.Text as T import qualified Data.Map as M (Map, elems, fromList, lookup) import Data.Maybe (fromMaybe, mapMaybe) import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import Network.URI (unEscapeString) import System.FilePath (dropFileName, dropFileName, normalise, splitFileName, takeFileName, (</>)) import qualified Text.Pandoc.Builder as B import Text.Pandoc.Class.PandocMonad (PandocMonad, insertMedia) import Text.Pandoc.Definition hiding (Attr) import Text.Pandoc.Error import Text.Pandoc.Extensions (Extension (Ext_raw_html), enableExtension) import Text.Pandoc.MIME (MimeType) import Text.Pandoc.Options (ReaderOptions (..)) import Text.Pandoc.Readers.HTML (readHtml) import Text.Pandoc.Shared (addMetaField, collapseFilePath, escapeURI) import qualified Text.Pandoc.UTF8 as UTF8 (toStringLazy) import Text.Pandoc.Walk (query, walk) import Text.XML.Light type Items = M.Map String (FilePath, MimeType) readEPUB :: PandocMonad m => ReaderOptions -> BL.ByteString -> m Pandoc readEPUB opts bytes = case toArchiveOrFail bytes of Right archive -> archiveToEPUB opts archive Left _ -> throwError $ PandocParseError "Couldn't extract ePub file" archiveToEPUB :: (PandocMonad m) => ReaderOptions -> Archive -> m Pandoc archiveToEPUB os archive = do (root, content) <- getManifest archive (coverId, meta) <- parseMeta content (cover, items) <- parseManifest content coverId let coverDoc = maybe mempty imageToPandoc cover spine <- parseSpine items content let escapedSpine = map (escapeURI . T.pack . takeFileName . fst) spine Pandoc _ bs <- foldM' (\a b -> ((a <>) . walk (prependHash escapedSpine)) `liftM` parseSpineElem root b) mempty spine let ast = coverDoc <> Pandoc meta bs fetchImages (M.elems items) root archive ast return ast where os' = os {readerExtensions = enableExtension Ext_raw_html (readerExtensions os)} parseSpineElem :: PandocMonad m => FilePath -> (FilePath, MimeType) -> m Pandoc parseSpineElem (normalise -> r) (normalise -> path, mime) = do doc <- mimeToReader mime r path let docSpan = B.doc $ B.para $ B.spanWith (T.pack $ takeFileName path, [], []) mempty return $ docSpan <> doc mimeToReader :: PandocMonad m => MimeType -> FilePath -> FilePath -> m Pandoc mimeToReader "application/xhtml+xml" (unEscapeString -> root) (unEscapeString -> path) = do fname <- findEntryByPathE (root </> path) archive html <- readHtml os' . TL.toStrict . TL.decodeUtf8 $ fromEntry fname return $ fixInternalReferences path html mimeToReader s _ (unEscapeString -> path) | s `elem` imageMimes = return $ imageToPandoc path | otherwise = return mempty fetchImages :: PandocMonad m => [(FilePath, MimeType)] -> Archive -> Pandoc -> m () fetchImages mimes root arc (query iq -> links) = mapM_ (uncurry3 insertMedia) (mapMaybe getEntry links) where getEntry link = let abslink = normalise (unEscapeString (root </> link)) in (link , lookup link mimes, ) . fromEntry <$> findEntryByPath abslink arc iq :: Inline -> [FilePath] iq (Image _ _ (url, _)) = [T.unpack url] iq _ = [] renameImages :: FilePath -> Inline -> Inline renameImages root img@(Image attr a (url, b)) | "data:" `T.isPrefixOf` url = img | otherwise = Image attr a ( T.pack $ collapseFilePath (root </> T.unpack url) , b) renameImages _ x = x imageToPandoc :: FilePath -> Pandoc imageToPandoc s = B.doc . B.para $ B.image (T.pack s) "" mempty imageMimes :: [MimeType] imageMimes = ["image/gif", "image/jpeg", "image/png"] type CoverId = String type CoverImage = FilePath parseManifest :: (PandocMonad m) => Element -> Maybe CoverId -> m (Maybe CoverImage, Items) parseManifest content coverId = do manifest <- findElementE (dfName "manifest") content let items = findChildren (dfName "item") manifest r <- mapM parseItem items let cover = findAttr (emptyName "href") =<< filterChild findCover manifest return (cover `mplus` coverId, M.fromList r) where findCover e = maybe False (isInfixOf "cover-image") (findAttr (emptyName "properties") e) || fromMaybe False (liftM2 (==) coverId (findAttr (emptyName "id") e)) parseItem e = do uid <- findAttrE (emptyName "id") e href <- findAttrE (emptyName "href") e mime <- findAttrE (emptyName "media-type") e return (uid, (href, T.pack mime)) parseSpine :: PandocMonad m => Items -> Element -> m [(FilePath, MimeType)] parseSpine is e = do spine <- findElementE (dfName "spine") e let itemRefs = findChildren (dfName "itemref") spine mapM (mkE "parseSpine" . flip M.lookup is) $ mapMaybe parseItemRef itemRefs where parseItemRef ref = do let linear = maybe True (== "yes") (findAttr (emptyName "linear") ref) guard linear findAttr (emptyName "idref") ref parseMeta :: PandocMonad m => Element -> m (Maybe CoverId, Meta) parseMeta content = do meta <- findElementE (dfName "metadata") content let dcspace (QName _ (Just "/") (Just "dc")) = True dcspace _ = False let dcs = filterChildrenName dcspace meta let r = foldr parseMetaItem nullMeta dcs let coverId = findAttr (emptyName "content") =<< filterChild findCover meta return (coverId, r) where findCover e = findAttr (emptyName "name") e == Just "cover" parseMetaItem :: Element -> Meta -> Meta parseMetaItem e@(stripNamespace . elName -> field) meta = addMetaField (renameMeta field) (B.str $ T.pack $ strContent e) meta renameMeta :: String -> T.Text renameMeta "creator" = "author" renameMeta s = T.pack s getManifest :: PandocMonad m => Archive -> m (String, Element) getManifest archive = do metaEntry <- findEntryByPathE ("META-INF" </> "container.xml") archive docElem <- (parseXMLDocE . UTF8.toStringLazy . fromEntry) metaEntry let namespaces = mapMaybe attrToNSPair (elAttribs docElem) ns <- mkE "xmlns not in namespaces" (lookup "xmlns" namespaces) as <- fmap (map attrToPair . elAttribs) (findElementE (QName "rootfile" (Just ns) Nothing) docElem) manifestFile <- mkE "Root not found" (lookup "full-path" as) let rootdir = dropFileName manifestFile manifest <- findEntryByPathE manifestFile archive fmap ((,) rootdir) (parseXMLDocE . UTF8.toStringLazy . fromEntry $ manifest) Fixup fixInternalReferences :: FilePath -> Pandoc -> Pandoc fixInternalReferences pathToFile = walk (renameImages root) . walk (fixBlockIRs filename) . walk (fixInlineIRs filename) where (root, T.unpack . escapeURI . T.pack -> filename) = splitFileName pathToFile fixInlineIRs :: String -> Inline -> Inline fixInlineIRs s (Span as v) = Span (fixAttrs s as) v fixInlineIRs s (Code as code) = Code (fixAttrs s as) code fixInlineIRs s (Link as is (T.uncons -> Just ('#', url), tit)) = Link (fixAttrs s as) is (addHash s url, tit) fixInlineIRs s (Link as is t) = Link (fixAttrs s as) is t fixInlineIRs _ v = v prependHash :: [T.Text] -> Inline -> Inline prependHash ps l@(Link attr is (url, tit)) | or [s `T.isPrefixOf` url | s <- ps] = Link attr is ("#" <> url, tit) | otherwise = l prependHash _ i = i fixBlockIRs :: String -> Block -> Block fixBlockIRs s (Div as b) = Div (fixAttrs s as) b fixBlockIRs s (Header i as b) = Header i (fixAttrs s as) b fixBlockIRs s (CodeBlock as code) = CodeBlock (fixAttrs s as) code fixBlockIRs _ b = b fixAttrs :: FilePath -> B.Attr -> B.Attr fixAttrs s (ident, cs, kvs) = (addHash s ident, filter (not . T.null) cs, removeEPUBAttrs kvs) addHash :: String -> T.Text -> T.Text addHash _ "" = "" addHash s ident = T.pack (takeFileName s) <> "#" <> ident removeEPUBAttrs :: [(T.Text, T.Text)] -> [(T.Text, T.Text)] removeEPUBAttrs kvs = filter (not . isEPUBAttr) kvs isEPUBAttr :: (T.Text, a) -> Bool isEPUBAttr (k, _) = "epub:" `T.isPrefixOf` k Library foldM' :: (Monad m, NFData a) => (a -> b -> m a) -> a -> [b] -> m a foldM' _ z [] = return z foldM' f z (x:xs) = do z' <- f z x z' `deepseq` foldM' f z' xs uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (a, b, c) = f a b c stripNamespace :: QName -> String stripNamespace (QName v _ _) = v attrToNSPair :: Attr -> Maybe (String, String) attrToNSPair (Attr (QName "xmlns" _ _) val) = Just ("xmlns", val) attrToNSPair _ = Nothing attrToPair :: Attr -> (String, String) attrToPair (Attr (QName name _ _) val) = (name, val) defaultNameSpace :: Maybe String defaultNameSpace = Just "" dfName :: String -> QName dfName s = QName s defaultNameSpace Nothing emptyName :: String -> QName emptyName s = QName s Nothing Nothing findAttrE :: PandocMonad m => QName -> Element -> m String findAttrE q e = mkE "findAttr" $ findAttr q e findEntryByPathE :: PandocMonad m => FilePath -> Archive -> m Entry findEntryByPathE (normalise . unEscapeString -> path) a = mkE ("No entry on path: " ++ path) $ findEntryByPath path a parseXMLDocE :: PandocMonad m => String -> m Element parseXMLDocE doc = mkE "Unable to parse XML doc" $ parseXMLDoc doc findElementE :: PandocMonad m => QName -> Element -> m Element findElementE e x = mkE ("Unable to find element: " ++ show e) $ findElement e x mkE :: PandocMonad m => String -> Maybe a -> m a mkE s = maybe (throwError . PandocParseError $ T.pack s) return
7103ea57af2902a5b6c33646c2bdbb397b18697bbfc2f64c3f1dc451e4f8a5b3
wireapp/wire-server
UserSpec.hs
# LANGUAGE QuasiQuotes # -- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. module Test.Class.UserSpec ( spec, ) where import Data.ByteString.Lazy (ByteString) import Network.Wai (Application) import Servant (Proxy (Proxy)) import Servant.API.Generic import Test.Hspec import Test.Hspec.Wai hiding (patch, post, put, shouldRespondWith) import Web.Scim.Server (UserAPI, mkapp, userServer) import Web.Scim.Server.Mock import Web.Scim.Test.Util app :: IO Application app = do storage <- emptyTestStorage let auth = Just "authorized" pure $ mkapp @Mock (Proxy @(UserAPI Mock)) (toServant (userServer auth)) (nt storage) spec :: Spec spec = with app $ do describe "GET & POST /Users" $ do it "responds with [] in empty environment" $ do get "/" `shouldRespondWith` emptyList it "can insert then retrieve stored Users" $ do post "/" newBarbara `shouldRespondWith` 201 post "/" newJim `shouldRespondWith` 201 get "/" `shouldRespondWith` allUsers describe "filtering" $ do it "can filter by username" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=userName eq \"bjensen\"" `shouldRespondWith` onlyBarbara it "is case-insensitive regarding syntax" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=USERName EQ \"bjensen\"" `shouldRespondWith` onlyBarbara it "is case-insensitive regarding usernames" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=userName eq \"BJensen\"" `shouldRespondWith` onlyBarbara it "handles malformed filter syntax" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=userName eqq \"bjensen\"" `shouldRespondWith` 400 -- TODO: would be nice to check the error message as well it "handles type errors in comparisons" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=userName eq true" `shouldRespondWith` 400 describe "GET /Users/:id" $ do it "responds with 404 for unknown user" $ do get "/9999" `shouldRespondWith` 404 FUTUREWORK : currently it returns 404 : -- -servant/servant/issues/1155 xit "responds with 401 for unparseable user ID" $ do get "/unparseable" `shouldRespondWith` 401 it "retrieves stored user" $ do post "/" newBarbara `shouldRespondWith` 201 the test implementation stores users with uid [ 0,1 .. n-1 ] get "/0" `shouldRespondWith` barbara describe "PUT /Users/:id" $ do it "overwrites the user" $ do post "/" newBarbara `shouldRespondWith` 201 put "/0" barbUpdate0 `shouldRespondWith` updatedBarb0 it "does not create new users" $ do post "/" newBarbara `shouldRespondWith` 201 put "/9999" newBarbara `shouldRespondWith` 404 -- TODO(arianvp): Perhaps we want to make this an acceptance spec. describe "PATCH /Users/:id" $ do describe "Add" $ do -- TODO(arianvp): Implement and test multi-value fields properly -- TODO(arianvp): We need to merge multi-value fields, but not supported yet -- TODO(arianvp): Add and Replace tests currently identical, because of lack of multi-value it "adds all fields if no target" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" smallUser -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Add", "value": { "userName": "arian", "displayName": "arian" } }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "arian", "displayName": "arian", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "adds fields if they didn't exist yet" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" smallUser -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Add", "path": "displayName", "value": "arian" }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "bjensen", "displayName": "arian", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "replaces individual simple fields" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" smallUser -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Add", "path": "userName", "value": "arian" }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "arian", "displayName": "bjensen2", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } TODO(arianvp ): I think this is better done with quickcheck test . -- Generate some adds, replaces, removes and then an invalid one However, -- for this we need to be able to generate valid patches but a patch does -- not limit by type what fields it lenses in to. It is a very untyped -- thingy currently. it "PatchOp is atomic. Either fully applies or not at all" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" smallUser -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Add", "path": "userName", "value": "arian" }, { "op": "Add", "path": "displayName", "value": 5 }]}|] `shouldRespondWith` 400 get "/0" `shouldRespondWith` smallUserGet {matchStatus = 200} describe "Replace" $ do -- TODO(arianvp): Implement and test multi-value fields properly it "adds all fields if no target" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" smallUser -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "value": { "userName": "arian", "displayName": "arian" } }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "arian", "displayName": "arian", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "adds fields if they didn't exist yet" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" smallUser -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "path": "displayName", "value": "arian" }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "bjensen", "displayName": "arian", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "replaces individual simple fields" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" smallUser -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "path": "userName", "value": "arian" }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "arian", "displayName": "bjensen2", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "PatchOp is atomic. Either fully applies or not at all" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" smallUser -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "path": "userName", "value": "arian" }, { "op": "Replace", "path": "displayName", "value": 5 }]}|] `shouldRespondWith` 400 get "/0" `shouldRespondWith` smallUserGet {matchStatus = 200} describe "Remove" $ do it "fails if no target" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" barbUpdate0 -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Remove" }] }|] `shouldRespondWith` [scim|{ "scimType":"noTarget","status":"400","schemas":["urn:ietf:params:scim:api:messages:2.0:Error"] }|] { matchStatus = 400 } it "fails if removing immutable" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" barbUpdate0 -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Remove", "path": "userName"}] }|] `shouldRespondWith` [scim|{ "scimType":"mutability","status":"400","schemas":["urn:ietf:params:scim:api:messages:2.0:Error"] }|] { matchStatus = 400 } it "deletes the specified attribute" $ do post "/" newBarbara `shouldRespondWith` 201 _ <- put "/0" smallUser -- reset patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Remove", "path": "displayName"}] }|] `shouldRespondWith` [scim|{ "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "bjensen", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } }|] { matchStatus = 200 } describe "DELETE /Users/:id" $ do it "responds with 404 for unknown user" $ do delete "/9999" `shouldRespondWith` 404 it "deletes a stored user" $ do post "/" newBarbara `shouldRespondWith` 201 delete "/0" `shouldRespondWith` 204 -- user should be gone get "/0" `shouldRespondWith` 404 delete "/0" `shouldRespondWith` 404 smallUser :: ByteString smallUser = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "displayName": "bjensen2" }|] smallUserGet :: ResponseMatcher smallUserGet = [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "bjensen", "displayName": "bjensen2", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] newBarbara :: ByteString newBarbara = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "externalId":"bjensen", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara" } }|] newJim :: ByteString newJim = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"jim", "externalId":"jim", "name":{ "formatted":"Jim", "familyName":"", "givenName":"Jim" } }|] barbara :: ResponseMatcher barbara = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "name": { "givenName":"Barbara", "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen" }, "id":"0", "externalId":"bjensen", "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }|] allUsers :: ResponseMatcher allUsers = [scim| { "schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "totalResults": 2, "itemsPerPage": 2, "startIndex": 1, "Resources": [{ "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "externalId":"bjensen", "id" : "0", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara" }, "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }, { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"jim", "externalId":"jim", "id" : "1", "name":{ "formatted":"Jim", "familyName":"", "givenName":"Jim" }, "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }] }|] onlyBarbara :: ResponseMatcher onlyBarbara = [scim| { "schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "totalResults": 1, "itemsPerPage": 1, "startIndex": 1, "Resources": [{ "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "externalId":"bjensen", "id" : "0", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara" }, "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }] }|] source : #section-3.5.1 ( p. 30 ) barbUpdate0 :: ByteString barbUpdate0 = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "id":"0", "userName":"bjensen", "externalId":"bjensen", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara", "middleName":"Jane" }, "roles":[], "emails":[ { "value":"" }, { "value":"" } ] }|] updatedBarb0 :: ResponseMatcher updatedBarb0 = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "id":"0", "userName":"bjensen", "externalId":"bjensen", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara", "middleName":"Jane" }, "emails":[ { "value":"" }, { "value":"" } ], "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }|] emptyList :: ResponseMatcher emptyList = [scim| { "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "Resources":[], "totalResults":0, "itemsPerPage":0, "startIndex":1 }|]
null
https://raw.githubusercontent.com/wireapp/wire-server/09cfa0e602321ef753f771a7171ba6c39b5ac976/libs/hscim/test/Test/Class/UserSpec.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. with this program. If not, see </>. TODO: would be nice to check the error message as well -servant/servant/issues/1155 TODO(arianvp): Perhaps we want to make this an acceptance spec. TODO(arianvp): Implement and test multi-value fields properly TODO(arianvp): We need to merge multi-value fields, but not supported yet TODO(arianvp): Add and Replace tests currently identical, because of lack of multi-value reset reset reset Generate some adds, replaces, removes and then an invalid one However, for this we need to be able to generate valid patches but a patch does not limit by type what fields it lenses in to. It is a very untyped thingy currently. reset TODO(arianvp): Implement and test multi-value fields properly reset reset reset reset reset reset reset user should be gone
# LANGUAGE QuasiQuotes # Copyright ( C ) 2022 Wire Swiss GmbH < > the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along module Test.Class.UserSpec ( spec, ) where import Data.ByteString.Lazy (ByteString) import Network.Wai (Application) import Servant (Proxy (Proxy)) import Servant.API.Generic import Test.Hspec import Test.Hspec.Wai hiding (patch, post, put, shouldRespondWith) import Web.Scim.Server (UserAPI, mkapp, userServer) import Web.Scim.Server.Mock import Web.Scim.Test.Util app :: IO Application app = do storage <- emptyTestStorage let auth = Just "authorized" pure $ mkapp @Mock (Proxy @(UserAPI Mock)) (toServant (userServer auth)) (nt storage) spec :: Spec spec = with app $ do describe "GET & POST /Users" $ do it "responds with [] in empty environment" $ do get "/" `shouldRespondWith` emptyList it "can insert then retrieve stored Users" $ do post "/" newBarbara `shouldRespondWith` 201 post "/" newJim `shouldRespondWith` 201 get "/" `shouldRespondWith` allUsers describe "filtering" $ do it "can filter by username" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=userName eq \"bjensen\"" `shouldRespondWith` onlyBarbara it "is case-insensitive regarding syntax" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=USERName EQ \"bjensen\"" `shouldRespondWith` onlyBarbara it "is case-insensitive regarding usernames" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=userName eq \"BJensen\"" `shouldRespondWith` onlyBarbara it "handles malformed filter syntax" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=userName eqq \"bjensen\"" `shouldRespondWith` 400 it "handles type errors in comparisons" $ do post "/" newBarbara `shouldRespondWith` 201 get "/?filter=userName eq true" `shouldRespondWith` 400 describe "GET /Users/:id" $ do it "responds with 404 for unknown user" $ do get "/9999" `shouldRespondWith` 404 FUTUREWORK : currently it returns 404 : xit "responds with 401 for unparseable user ID" $ do get "/unparseable" `shouldRespondWith` 401 it "retrieves stored user" $ do post "/" newBarbara `shouldRespondWith` 201 the test implementation stores users with uid [ 0,1 .. n-1 ] get "/0" `shouldRespondWith` barbara describe "PUT /Users/:id" $ do it "overwrites the user" $ do post "/" newBarbara `shouldRespondWith` 201 put "/0" barbUpdate0 `shouldRespondWith` updatedBarb0 it "does not create new users" $ do post "/" newBarbara `shouldRespondWith` 201 put "/9999" newBarbara `shouldRespondWith` 404 describe "PATCH /Users/:id" $ do describe "Add" $ do it "adds all fields if no target" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Add", "value": { "userName": "arian", "displayName": "arian" } }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "arian", "displayName": "arian", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "adds fields if they didn't exist yet" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Add", "path": "displayName", "value": "arian" }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "bjensen", "displayName": "arian", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "replaces individual simple fields" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Add", "path": "userName", "value": "arian" }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "arian", "displayName": "bjensen2", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } TODO(arianvp ): I think this is better done with quickcheck test . it "PatchOp is atomic. Either fully applies or not at all" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Add", "path": "userName", "value": "arian" }, { "op": "Add", "path": "displayName", "value": 5 }]}|] `shouldRespondWith` 400 get "/0" `shouldRespondWith` smallUserGet {matchStatus = 200} describe "Replace" $ do it "adds all fields if no target" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "value": { "userName": "arian", "displayName": "arian" } }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "arian", "displayName": "arian", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "adds fields if they didn't exist yet" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "path": "displayName", "value": "arian" }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "bjensen", "displayName": "arian", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "replaces individual simple fields" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "path": "userName", "value": "arian" }] }|] `shouldRespondWith` [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "arian", "displayName": "bjensen2", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] { matchStatus = 200 } it "PatchOp is atomic. Either fully applies or not at all" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "path": "userName", "value": "arian" }, { "op": "Replace", "path": "displayName", "value": 5 }]}|] `shouldRespondWith` 400 get "/0" `shouldRespondWith` smallUserGet {matchStatus = 200} describe "Remove" $ do it "fails if no target" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Remove" }] }|] `shouldRespondWith` [scim|{ "scimType":"noTarget","status":"400","schemas":["urn:ietf:params:scim:api:messages:2.0:Error"] }|] { matchStatus = 400 } it "fails if removing immutable" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Remove", "path": "userName"}] }|] `shouldRespondWith` [scim|{ "scimType":"mutability","status":"400","schemas":["urn:ietf:params:scim:api:messages:2.0:Error"] }|] { matchStatus = 400 } it "deletes the specified attribute" $ do post "/" newBarbara `shouldRespondWith` 201 patch "/0" [scim|{ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Remove", "path": "displayName"}] }|] `shouldRespondWith` [scim|{ "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "bjensen", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } }|] { matchStatus = 200 } describe "DELETE /Users/:id" $ do it "responds with 404 for unknown user" $ do delete "/9999" `shouldRespondWith` 404 it "deletes a stored user" $ do post "/" newBarbara `shouldRespondWith` 201 delete "/0" `shouldRespondWith` 204 get "/0" `shouldRespondWith` 404 delete "/0" `shouldRespondWith` 404 smallUser :: ByteString smallUser = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "displayName": "bjensen2" }|] smallUserGet :: ResponseMatcher smallUserGet = [scim| { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "userName": "bjensen", "displayName": "bjensen2", "id": "0", "meta": { "resourceType": "User", "location": "", "created": "2018-01-01T00:00:00Z", "version": "W/\"testVersion\"", "lastModified": "2018-01-01T00:00:00Z" } } |] newBarbara :: ByteString newBarbara = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "externalId":"bjensen", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara" } }|] newJim :: ByteString newJim = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"jim", "externalId":"jim", "name":{ "formatted":"Jim", "familyName":"", "givenName":"Jim" } }|] barbara :: ResponseMatcher barbara = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "name": { "givenName":"Barbara", "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen" }, "id":"0", "externalId":"bjensen", "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }|] allUsers :: ResponseMatcher allUsers = [scim| { "schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "totalResults": 2, "itemsPerPage": 2, "startIndex": 1, "Resources": [{ "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "externalId":"bjensen", "id" : "0", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara" }, "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }, { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"jim", "externalId":"jim", "id" : "1", "name":{ "formatted":"Jim", "familyName":"", "givenName":"Jim" }, "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }] }|] onlyBarbara :: ResponseMatcher onlyBarbara = [scim| { "schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "totalResults": 1, "itemsPerPage": 1, "startIndex": 1, "Resources": [{ "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "userName":"bjensen", "externalId":"bjensen", "id" : "0", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara" }, "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }] }|] source : #section-3.5.1 ( p. 30 ) barbUpdate0 :: ByteString barbUpdate0 = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "id":"0", "userName":"bjensen", "externalId":"bjensen", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara", "middleName":"Jane" }, "roles":[], "emails":[ { "value":"" }, { "value":"" } ] }|] updatedBarb0 :: ResponseMatcher updatedBarb0 = [scim| { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"], "id":"0", "userName":"bjensen", "externalId":"bjensen", "name":{ "formatted":"Ms. Barbara J Jensen III", "familyName":"Jensen", "givenName":"Barbara", "middleName":"Jane" }, "emails":[ { "value":"" }, { "value":"" } ], "meta":{ "resourceType":"User", "location":"", "created":"2018-01-01T00:00:00Z", "version":"W/\"testVersion\"", "lastModified":"2018-01-01T00:00:00Z" } }|] emptyList :: ResponseMatcher emptyList = [scim| { "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "Resources":[], "totalResults":0, "itemsPerPage":0, "startIndex":1 }|]
76ce7eb3173eb4b4c74434b1ac0c86904031995aae70e43c6bb35947e2d6e152
LCBH/UKano
terms.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * , , and * * * * Copyright ( C ) INRIA , CNRS 2000 - 2020 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * Bruno Blanchet, Vincent Cheval, and Marc Sylvestre * * * * Copyright (C) INRIA, CNRS 2000-2020 * * * *************************************************************) 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 ( in file LICENSE ) . 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA 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 (in file LICENSE). 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) open Parsing_helper open Types (* Basic functions for list. *) let rec split_list size = function | q when size = 0 -> [], q | [] -> Parsing_helper.internal_error "[terms.ml >> split_list] Wrong parameter." | t::q -> let (l1,l2) = split_list (size-1) q in (t::l1,l2) [ s sub ] is true when the string [ s ] ends with [ sub ] let ends_with s sub = let l_s = String.length s in let l_sub = String.length sub in (l_s >= l_sub) && (String.sub s (l_s - l_sub) l_sub = sub) (* [starts_with s sub] is true when the string [s] starts with [sub] *) let starts_with s sub = let l_s = String.length s in let l_sub = String.length sub in (l_s >= l_sub) && (String.sub s 0 l_sub = sub) (* TO DO The current code works, but in principle, it would be nicer if [tuple_taple] was a field in [t_pi_state/t_horn_state], to avoid keeping tuple functions when they are no longer useful. That would probably complicate the code, however. *) let tuple_table = Hashtbl.create 1 let get_tuple_fun tl = let tl = if Param.get_ignore_types() then List.map (fun t -> Param.any_type) tl else tl in try Hashtbl.find tuple_table tl with Not_found -> let r = { f_name = Fixed ""; f_type = tl, Param.bitstring_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } in Hashtbl.add tuple_table tl r; r let get_term_type = function Var b -> b.btype | FunApp(f,_) -> snd f.f_type let equal_types t1 t2 = (Param.get_ignore_types()) || t1 == t2 (* Get the type of a pattern *) let get_pat_type = function PatVar b -> b.btype | PatTuple (f,l) -> snd f.f_type | PatEqual t -> get_term_type t let get_format_type = function FVar b -> b.btype | FAny b -> b.btype | FFunApp(f,_) -> snd f.f_type let term_of_pattern_variable = function | PatVar(v) -> Var(v) | _ -> internal_error "[term_of_pattern_variable] The pattern must be a variable" let rec copy_n n v = if n <= 0 then [] else v :: (copy_n (n-1) v) let rec tl_to_string sep = function [] -> "" | [a] -> a.tname | (a::l) -> a.tname ^ sep ^ (tl_to_string sep l) let rec eq_lists l1 l2 = match l1,l2 with [],[] -> true | a1::q1,a2::q2 -> (a1 == a2) && (eq_lists q1 q2) | _,_ -> false These functions are used to guarantee the freshness of new identifiers Each identifier is represented by a pair ( s , n ): - if n = 0 , then ( s , n ) is displayed s - otherwise , ( s , n ) is displayed s_n Invariant : n has at most 9 digits ( supports one billion of variables ) ; when n = 0 , s is never of the form N_xxx where xxx is a non - zero number of at most 9 digits . This guarantees that for each identifier , ( s , n ) is unique . We guarantee the freshness by changing the value of n Each identifier is represented by a pair (s,n): - if n = 0, then (s,n) is displayed s - otherwise, (s,n) is displayed s_n Invariant: n has at most 9 digits (supports one billion of variables); when n = 0, s is never of the form N_xxx where xxx is a non-zero number of at most 9 digits. This guarantees that for each identifier, (s,n) is unique. We guarantee the freshness by changing the value of n *) [ get_id_n s ] converts [ s ] into a pair [ ( ) ] displayed [ s ] let get_id_n s = let l = String.length s in if '0' <= s.[l-1] && s.[l-1] <= '9' then let rec underscore_number n = if (n > 0) && (l-n<=10) then if s.[n] = '_' then n else if '0' <= s.[n] && s.[n] <= '9' then underscore_number (n-1) else raise Not_found else raise Not_found in try let pos_underscore = underscore_number (l-2) in if s.[pos_underscore+1] = '0' then raise Not_found; let n' = int_of_string (String.sub s (pos_underscore+1) (l-pos_underscore-1)) in let s' = String.sub s 0 pos_underscore in (* print_string (s ^ " split into " ^ s' ^ " " ^ (string_of_int n') ^ "\n"); *) (s',n') with Not_found -> (* s does not end with _xxx *) (s,0) else (s,0) (* Counter incremented to generate fresh variable names *) let var_idx = ref 0 (* The maximum xxx such N_xxx occurs and xxx does not come from var_idx *) let max_source_idx = ref 0 (* Set of pairs (s,n) used, stored in a hash table. All pairs (_,n) where 0 < n <= !var_idx are considered as always used, so we need not add them to the hash table. All pairs (s,n) in [used_ids] satisfy [n <= !max_source_idx] *) let used_ids = Hashtbl.create 7 Clear used_ids . Used to reload a file in proverif interact mode let init_used_ids () = Hashtbl.clear used_ids (* [record_id s id ext] records the identifier [s] so that it will not be reused elsewhere. [record_id] must be called only before calls to [fresh_id] or [new_var_name], so that [s] cannot collide with an identifier generated by [fresh_id] or [new_var_name]. [id] is the conversion of [s] into a pair (string, int) by [get_id_n]. Moreover, !var_idx = 0, there are no pairs (_,n) with 0 < n <= !var_idx, so the used pairs are exactly those in the hash table used_ids. *) let record_id s ((_,n) as s_n) ext = if n > !max_source_idx then max_source_idx := n; if Hashtbl.mem used_ids s_n then input_error ("identifier " ^ s ^ " already defined (as a free name, a function, a predicate, a type, an event, or a table)") ext else Hashtbl.add used_ids s_n () (*************************************************** Basic functions for constraints ****************************************************) let exists_constraints f constra = List.exists (List.exists (fun (t1,t2) -> f t1 || f t2)) constra.neq || List.exists f constra.is_nat || List.exists f constra.is_not_nat || List.exists (fun (t1,_,t2) -> f t1 || f t2) constra.geq let map_constraints f constra = { neq = (List.map (List.map (fun (t1,t2) -> f t1, f t2)) constra.neq); is_nat = (List.map f constra.is_nat); is_not_nat = (List.map f constra.is_not_nat); geq = (List.map (fun (t1,n,t2) -> (f t1, n, f t2)) constra.geq) } let iter_constraints f constra = List.iter (List.iter (fun (t1,t2) -> f t1; f t2)) constra.neq; List.iter f constra.is_nat; List.iter f constra.is_not_nat; List.iter (fun (t1,_,t2) -> f t1; f t2) constra.geq let true_constraints = { neq = []; is_nat = []; is_not_nat = []; geq = [] } let constraints_of_neq t1 t2 = { neq = [[t1,t2]]; is_nat = []; is_not_nat = []; geq = [] } let constraints_of_is_nat t = { neq = []; is_nat = [t]; is_not_nat = []; geq = [] } let constraints_of_is_not_nat t = { neq = []; is_nat = []; is_not_nat = [t]; geq = [] } let constraints_of_geq t1 t2 = { neq = []; is_nat = []; is_not_nat = []; geq = [t1,0,t2] } let is_true_constraints c = c.neq == [] && c.is_nat == [] && c.is_not_nat == [] && c.geq == [] let wedge_constraints c1 c2 = { neq = c1.neq @ c2.neq; is_nat = c1.is_nat @ c2.is_nat; is_not_nat = c1.is_not_nat @ c2.is_not_nat; geq = c1.geq @ c2.geq } (*************************************************** Function for Var ****************************************************) (* [new_var_name s] creates a fresh pair [(s,n)] using [!var_idx]. *) let rec new_var_name s = incr var_idx; let n = !var_idx in if (n <= !max_source_idx) && (Hashtbl.mem used_ids (s,n)) then new_var_name s else (s,n) let id_n2id (s,n) = if n = 0 then s else s ^ "_" ^ (string_of_int n) [ fresh_id_n s ] creates a fresh pair [ ( ) ] corresponding to identifier [ s ] . identifier [s]. *) let fresh_id_n s = let (s',_) = get_id_n s in new_var_name s' (* [fresh_id s] creates a fresh identifier [s'] corresponding to identifier [s]. *) let fresh_id s = id_n2id (fresh_id_n s) let new_id ?(orig=true) s = let (s',n) = fresh_id_n s in { orig_name = if orig then s else ""; name = s'; idx = n; display = None } let copy_id ?(orig=true) id = let (s',n) = new_var_name id.name in { orig_name = if orig then id.orig_name else ""; name = s'; idx = n; display = None } let string_of_id id = id_n2id (id.name, id.idx) (* [new_var s t] creates a fresh variable with name [s] and type [t] *) let new_var ?orig ?(may_fail=false) s t = let s0 = if may_fail then if s = "" then "@mayfail" else "@mayfail_" ^ s else s in { vname = new_id ?orig s0; unfailing = may_fail; btype = t; link = NoLink } [ copy_var v ] creates a fresh variable with the same sname and type as [ v ] Invariant : if vname = 0 , then sname never contains N_xxx where xxx is a non - zero number of at most 9 digits . As a consequence , we do n't need to split v.sname using fresh_id_n . Invariant: if vname = 0, then sname never contains N_xxx where xxx is a non-zero number of at most 9 digits. As a consequence, we don't need to split v.sname using fresh_id_n. *) let copy_var ?(rename=true) ?orig v = { vname = if rename then copy_id ?orig v.vname else v.vname; unfailing = v.unfailing; btype = v.btype; link = NoLink } (* [new_var_def t] creates a fresh variable with a default name and type [t] *) let new_var_def ?may_fail t = new_var ~orig:false ?may_fail Param.def_var_name t let new_var_def_term ?may_fail t = Var (new_var_def ?may_fail t) (* [val_gen tl] creates new variables of types [tl] and returns them in a list *) let var_gen tl = List.map new_var_def_term tl let get_fsymb_basename f = match f.f_name with Fixed s -> s | Renamable id -> id.name let get_fsymb_origname f = match f.f_name with Fixed s -> s | Renamable id -> id.orig_name (* [occurs_var v t] determines whether the variable [v] occurs in the term [t] *) let rec occurs_var v = function Var v' -> v == v' | FunApp(f,l) -> List.exists (occurs_var v) l let rec occurs_var_format v = function FVar v' | FAny v' -> v == v' | FFunApp(f,l) -> List.exists (occurs_var_format v) l let occurs_var_fact v = function Pred(_,l) -> List.exists (occurs_var v) l let occurs_var_constraints v constra = exists_constraints (occurs_var v) constra (* [occurs_vars_all bl t] returns true when all variables occuring in [t] are in [bl]. *) let rec occurs_vars_all bl = function | Var v -> List.exists (fun v' -> v == v') bl | FunApp(_,l) -> List.for_all (occurs_vars_all bl) l (* [occurs_f f t] determines whether the function symbol [f] occurs in the term [t] *) let rec occurs_f f = function Var _ -> false | FunApp(f',l) -> (f == f') || (List.exists (occurs_f f) l) let rec occurs_f_pat f = function PatVar v -> false | PatTuple (_,l) -> List.exists (occurs_f_pat f) l | PatEqual t -> occurs_f f t let occurs_f_fact f = function Pred(_,l) -> List.exists (occurs_f f) l let occurs_f_constra f constra = exists_constraints (occurs_f f) constra let is_may_fail_term = function | FunApp(f,[]) when f.f_cat = Failure -> true | Var(v) when v.unfailing -> true | _ -> false let is_unfailing_var = function | Var(v) when v.unfailing -> true | _ -> false let is_failure = function | FunApp(f,[]) when f.f_cat = Failure -> true | _ -> false (* Equality tests *) let is_sub_predicate p1 p2 = match p1.p_info, p2.p_info with | [Attacker(n1,typ1)], [Attacker(n2,typ2)] | [AttackerBin(n1,typ1)], [AttackerBin(n2,typ2)] -> n1 >= n2 && equal_types typ1 typ2 | [Table(n1)], [Table(n2)] | [TableBin(n1)], [TableBin(n2)] -> n1 >= n2 | _, _ -> p1 == p2 let rec equal_terms t1 t2 = match (t1,t2) with | (FunApp(f1,l1), FunApp(f2,l2)) -> (f1 == f2) && (List.for_all2 equal_terms l1 l2) | (Var v1, Var v2) -> v1 == v2 | (_,_) -> false (* [same_term_lists pub1 pub2] returns [true] if and only if [pub1] and [pub2] contains the same terms. *) let same_term_lists pub1 pub2 = List.length pub1 == List.length pub2 && List.for_all (fun t -> List.exists (equal_terms t) pub2) pub1 && List.for_all (fun t -> List.exists (equal_terms t) pub1) pub2 let rec equal_formats t1 t2 = match (t1,t2) with | FVar v1, FVar v2 | FAny v1, FAny v2 -> v1 == v2 | FFunApp(f1,args1), FFunApp(f2,args2) -> f1 == f2 && List.for_all2 equal_formats args1 args2 | _ -> false let equal_fact_formats (p1,args1) (p2,args2) = p1 == p2 && List.for_all2 equal_formats args1 args2 let equal_facts f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2, t2) -> (chann1 == chann2) && (List.for_all2 equal_terms t1 t2) let equal_facts_phase_geq f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2, t2) -> (is_sub_predicate chann1 chann2) && (List.for_all2 equal_terms t1 t2) (* Copy and cleanup *) let current_bound_vars = ref [] let link v l = (* Check that message variables are linked only to messages, not to fail or to may-fail variables *) if not v.unfailing then begin match l with VLink v' -> assert (not v'.unfailing) | TLink t -> begin match t with Var v' -> assert (not v'.unfailing) | FunApp(f, _) -> assert (f.f_cat != Failure) end | TLink2 _ -> TLink2 is not used with function link assert false | NoLink -> (* NoLink should not be used with function link, it is set by cleanup *) assert false | FLink _ | PGLink _ -> () end; (* Check that types are correct, when they are not ignored *) begin match l with VLink v' -> assert (equal_types v.btype v'.btype) | TLink t -> assert (equal_types v.btype (get_term_type t)) | _ -> () end; current_bound_vars := v :: (!current_bound_vars); v.link <- l let link_var t l = match t with |Var(v) -> link v l |_ -> internal_error "[link_var] The term must be a variable" let cleanup () = List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := [] let auto_cleanup f = let tmp_bound_vars = !current_bound_vars in current_bound_vars := []; try let r = f () in List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := tmp_bound_vars; r with x -> List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := tmp_bound_vars; raise x We could also define the following functions instead of cleanup : let in_auto_cleanup = ref false let link v l = if not ( ! in_auto_cleanup ) then Parsing_helper.internal_error " should be in auto_cleanup to use link " ; current_bound_vars : = v : : ( ! current_bound_vars ) ; v.link < - l let auto_cleanup f = let tmp_in_auto_cleanup = ! in_auto_cleanup in in_auto_cleanup : = true ; let tmp_bound_vars = ! current_bound_vars in current_bound_vars : = [ ] ; try let r = f ( ) in List.iter ( fun v - > v.link < - NoLink ) ( ! current_bound_vars ) ; current_bound_vars : = tmp_bound_vars ; in_auto_cleanup : = tmp_in_auto_cleanup ; r with x - > List.iter ( fun v - > v.link < - NoLink ) ( ! current_bound_vars ) ; current_bound_vars : = tmp_bound_vars ; in_auto_cleanup : = tmp_in_auto_cleanup ; raise x Use auto_cleanup ( fun ( ) - > ... ) instead of let tmp_bound_vars = ! current_bound_vars in current_bound_vars : = [ ] ; ... cleanup ( ) ; current_bound_vars : = tmp_bound_vars and of if ! current_bound_vars ! = [ ] then Parsing_helper.internal_error " ... " ; ... cleanup ( ) This would be a better programming style , but this conflicts with the way the function Rules.build_rules_eq is written ... and would probably also slow down a bit the system . let in_auto_cleanup = ref false let link v l = if not (!in_auto_cleanup) then Parsing_helper.internal_error "should be in auto_cleanup to use link"; current_bound_vars := v :: (!current_bound_vars); v.link <- l let auto_cleanup f = let tmp_in_auto_cleanup = !in_auto_cleanup in in_auto_cleanup := true; let tmp_bound_vars = !current_bound_vars in current_bound_vars := []; try let r = f () in List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := tmp_bound_vars; in_auto_cleanup := tmp_in_auto_cleanup; r with x -> List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := tmp_bound_vars; in_auto_cleanup := tmp_in_auto_cleanup; raise x Use auto_cleanup (fun () -> ...) instead of let tmp_bound_vars = !current_bound_vars in current_bound_vars := []; ... cleanup(); current_bound_vars := tmp_bound_vars and of if !current_bound_vars != [] then Parsing_helper.internal_error "..."; ... cleanup() This would be a better programming style, but this conflicts with the way the function Rules.build_rules_eq is written... and would probably also slow down a bit the system. *) (*************************************************** Functions for General Variables ****************************************************) let new_gen_var t may_fail = let f_cat = if may_fail then General_mayfail_var else General_var in let name = (if !Param.tulafale != 1 then "@gen" else "gen") ^ (if may_fail then "mf" else "") in { f_name = Renamable (new_id ~orig:false name); f_type = [], t; f_cat = f_cat; f_initial_cat = f_cat; f_private = true; f_options = 0 } let rec generalize_vars_not_in vlist = function Var v -> begin if List.memq v vlist then Var v else match v.link with | NoLink -> let v' = FunApp(new_gen_var v.btype v.unfailing, []) in link v (TLink v'); v' | TLink l -> l | _ -> internal_error "Unexpected link in generalize_vars" end | FunApp(f, l) -> FunApp(f, List.map (generalize_vars_not_in vlist) l) let rec generalize_vars_in vlist = function Var v -> begin if not (List.memq v vlist) then Var v else match v.link with NoLink -> let v' = FunApp(new_gen_var v.btype v.unfailing, []) in link v (TLink v'); v' | TLink l -> l | _ -> internal_error "Unexpected link in generalize_vars" end | FunApp(f, l) -> FunApp(f, List.map (generalize_vars_in vlist) l) (*************************************************** Copy term functions ****************************************************) let rec copy_term = function | FunApp(f,l) -> FunApp(f, List.map copy_term l) | Var v -> match v.link with NoLink -> let r = copy_var v in link v (VLink r); Var r | VLink l -> Var l | _ -> internal_error "Unexpected link in copy_term" let copy_fact = function Pred(chann, t) -> Pred(chann, List.map copy_term t) let copy_constra c = map_constraints copy_term c let copy_rule (hyp,concl,hist,constra) = let tmp_bound = !current_bound_vars in current_bound_vars := []; let r = (List.map copy_fact hyp, copy_fact concl, hist, copy_constra constra) in cleanup(); current_bound_vars := tmp_bound; r let copy_red (left_list, right, side_c) = assert (!current_bound_vars == []); let left_list' = List.map copy_term left_list in let right' = copy_term right in let side_c' = copy_constra side_c in cleanup(); (left_list', right', side_c') Unification exception Unify let rec occur_check v t = match t with Var v' -> begin if v == v' then raise Unify; match v'.link with NoLink -> () | TLink t' -> occur_check v t' | _ -> internal_error "unexpected link in occur_check" end | (FunApp(_,l)) -> List.iter (occur_check v) l let term_string = function FunApp(f,l) -> let name = match f.f_name with Fixed s -> s | Renamable id -> string_of_id id in if l = [] then name else name ^ "(...)" | Var(b) -> string_of_id b.vname let rec unify t1 t2 = Commented out this typing checking test for speed if not ( Param.get_ignore_types ( ) ) then begin if get_term_type t1 ! = get_term_type t2 then Parsing_helper.internal_error ( " Type error in unify : " ^ ( term_string t1 ) ^ " has type " ^ ( get_term_type t1).tname ^ " while " ^ ( term_string t2 ) ^ " has type " ^ ( get_term_type t2).tname ) end ; if not (Param.get_ignore_types()) then begin if get_term_type t1 != get_term_type t2 then Parsing_helper.internal_error ("Type error in unify: " ^ (term_string t1) ^ " has type " ^ (get_term_type t1).tname ^ " while " ^ (term_string t2) ^ " has type " ^ (get_term_type t2).tname) end; *) match (t1,t2) with (Var v, Var v') when v == v' -> () | (Var v, _) -> begin match v.link with | NoLink -> begin match t2 with | Var {link = TLink t2'} -> unify t1 t2' | Var v' when v.unfailing -> link v (TLink t2) | Var v' when v'.unfailing -> link v' (TLink t1) | FunApp (f_symb,_) when f_symb.f_cat = Failure && v.unfailing = false -> raise Unify | Var v' when v'.vname.name = Param.def_var_name -> link v' (TLink t1) | _ -> occur_check v t2; link v (TLink t2) end | TLink t1' -> unify t1' t2 | _ -> internal_error "Unexpected link in unify 1" end | (FunApp(f_symb,_), Var v) -> begin match v.link with NoLink -> if v.unfailing = false && f_symb.f_cat = Failure then raise Unify else begin occur_check v t1; link v (TLink t1) end | TLink t2' -> unify t1 t2' | _ -> internal_error "Unexpected link in unify 2" end | (FunApp(f1, l1), FunApp(f2,l2)) -> if f1 != f2 then raise Unify; List.iter2 unify l1 l2 let unify_facts f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2,t2) -> if chann1 != chann2 then raise Unify; List.iter2 unify t1 t2 let unify_facts_phase f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2,t2) -> if not (is_sub_predicate chann1 chann2) then raise Unify; List.iter2 unify t1 t2 let unify_facts_phase_leq f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2,t2) -> if not (is_sub_predicate chann2 chann1) then raise Unify; List.iter2 unify t1 t2 let rec copy_term2 = function | FunApp(f,l) -> FunApp(f, List.map copy_term2 l) | Var v -> match v.link with | NoLink -> let r = copy_var v in link v (VLink r); Var r | TLink l -> copy_term2 l | VLink r -> Var r | _ -> internal_error "unexpected link in copy_term2" let copy_fact2 = function Pred(chann, t) -> Pred(chann, List.map copy_term2 t) let rec copy_constra2 c = map_constraints copy_term2 c let copy_rule2 (hyp, concl, hist, constra) = let tmp_bound = !current_bound_vars in current_bound_vars := []; let r = (List.map copy_fact2 hyp, copy_fact2 concl, hist, copy_constra2 constra) in cleanup(); current_bound_vars := tmp_bound; r let copy_rule2_no_cleanup (hyp, concl, hist, constra) = (List.map copy_fact2 hyp, copy_fact2 concl, hist, copy_constra2 constra) let copy_ordered_rule2 ord_rule = let rule = copy_rule2 ord_rule.rule in { ord_rule with rule = rule } let copy_occurrence2 = function | None -> None | Some t -> Some (copy_term2 t) let copy_event2 = function Pitypes.QSEvent(b,ord_fun,occ,t) -> Pitypes.QSEvent(b, ord_fun,copy_occurrence2 occ,copy_term2 t) | Pitypes.QSEvent2(t1,t2) -> Pitypes.QSEvent2(copy_term2 t1, copy_term2 t2) | Pitypes.QFact(p,ord_fun,tl) -> Pitypes.QFact(p,ord_fun,List.map copy_term2 tl) | Pitypes.QNeq(t1,t2) -> Pitypes.QNeq(copy_term2 t1, copy_term2 t2) | Pitypes.QEq(t1,t2) -> Pitypes.QEq(copy_term2 t1, copy_term2 t2) | Pitypes.QGeq(t1,t2) -> Pitypes.QGeq(copy_term2 t1, copy_term2 t2) | Pitypes.QIsNat(t) -> Pitypes.QIsNat(copy_term2 t) let rec copy_realquery2 = function Pitypes.Before(el, concl_q) -> Pitypes.Before(List.map copy_event2 el, copy_conclusion_query2 concl_q) and copy_conclusion_query2 = function | Pitypes.QTrue -> Pitypes.QTrue | Pitypes.QFalse -> Pitypes.QFalse | Pitypes.QEvent e -> Pitypes.QEvent(copy_event2 e) | Pitypes.NestedQuery q -> Pitypes.NestedQuery (copy_realquery2 q) | Pitypes.QAnd(concl1,concl2) -> Pitypes.QAnd(copy_conclusion_query2 concl1,copy_conclusion_query2 concl2) | Pitypes.QOr(concl1,concl2) -> Pitypes.QOr(copy_conclusion_query2 concl1,copy_conclusion_query2 concl2) (* Matching *) exception NoMatch let rec match_terms t1 t2 = Commented out this typing checking test for speed if not ( Param.get_ignore_types ( ) ) then begin if get_term_type t1 ! = get_term_type t2 then Parsing_helper.internal_error ( " Type error in match_terms : " ^ ( term_string t1 ) ^ " has type " ^ ( get_term_type t1).tname ^ " while " ^ ( term_string t2 ) ^ " has type " ^ ( get_term_type t2).tname ) end ; if not (Param.get_ignore_types()) then begin if get_term_type t1 != get_term_type t2 then Parsing_helper.internal_error ("Type error in match_terms: " ^ (term_string t1) ^ " has type " ^ (get_term_type t1).tname ^ " while " ^ (term_string t2) ^ " has type " ^ (get_term_type t2).tname) end; *) match (t1,t2) with (Var v), t -> begin match v.link with NoLink -> if v.unfailing then link v (TLink t) else begin match t with | Var v' when v'.unfailing -> raise NoMatch | FunApp(f_symb,_) when f_symb.f_cat = Failure -> raise NoMatch | _ -> link v (TLink t) end | TLink t' -> if not (equal_terms t t') then raise NoMatch | _ -> internal_error "Bad link in match_terms" end | (FunApp (f1,l1')), (FunApp (f2,l2')) -> if f1 != f2 then raise NoMatch; List.iter2 match_terms l1' l2' | _,_ -> raise NoMatch let match_facts f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2, t2) -> if chann1 != chann2 then raise NoMatch; List.iter2 match_terms t1 t2 Same as match_facts except that f1 of phase n can be matched with f2 of phase m with n > = m when they are attacker facts . Used to apply Lemmas . Used to apply Lemmas. *) let match_facts_phase_geq f1 f2 = match f1,f2 with | Pred(p1,t1), Pred(p2, t2) -> if not (is_sub_predicate p1 p2) then raise NoMatch; List.iter2 match_terms t1 t2 let match_facts_phase_leq f1 f2 = match f1,f2 with | Pred(p1,t1), Pred(p2, t2) -> if not (is_sub_predicate p2 p1) then raise NoMatch; List.iter2 match_terms t1 t2 let matchafact finst fgen = assert (!current_bound_vars == []); try match_facts fgen finst; cleanup(); true with NoMatch -> cleanup(); false (* [occurs_test_loop seen_vars v t] returns true when variable [v] occurs in term [t], following links inside terms. It uses the list [seen_vars] to avoid loops. [seen_vars] should be initialized to [ref []]. *) let rec occurs_test_loop seen_vars v t = match t with Var v' -> begin if List.memq v' (!seen_vars) then false else begin seen_vars := v' :: (!seen_vars); if v == v' then true else match v'.link with NoLink -> false | TLink t' -> occurs_test_loop seen_vars v t' | _ -> internal_error "unexpected link in occur_check" end end | FunApp(_,l) -> List.exists (occurs_test_loop seen_vars v) l let matchafactstrict finst fgen = assert (!current_bound_vars == []); try match_facts fgen finst; (* If a variable v is instantiated in the match into a term that is not a variable and that contains v, then by repeated resolution, the term will be instantiated into an infinite number of different terms obtained by iterating the substitution. We should adjust the selection function to avoid this non-termination. *) if List.exists (fun v -> match v.link with | TLink (Var _) -> false | TLink t -> occurs_test_loop (ref []) v t | _ -> false) (!current_bound_vars) then begin cleanup(); true end else begin cleanup(); false end with NoMatch -> cleanup(); false (* Size *) let rec term_size = function Var _ -> 0 | FunApp(f, l) -> 1 + term_list_size l and term_list_size = function [] -> 0 | a::l -> term_size a + term_list_size l let fact_size = function Pred(_, tl) -> 1 + term_list_size tl (* [replace_f_var vl t] replaces names in t according to the association list vl. That is, vl is a reference to a list of pairs (f_i, v_i) where f_i is a (nullary) function symbol and v_i is a variable. Each f_i is replaced with v_i in t. If an f_i in general_vars occurs in t, a new entry is added to the association list vl, and f_i is replaced accordingly. *) let rec replace_f_var vl = function | Var v2 -> Var v2 | FunApp(f2,[]) -> begin try Var (List.assq f2 (!vl)) with Not_found -> if f2.f_cat = General_var then begin let v = new_var ~orig:false (if !Param.tulafale != 1 then "@gen" else "gen") (snd f2.f_type) in vl := (f2, v) :: (!vl); Var v end else if f2.f_cat = General_mayfail_var then begin let v = new_var ~orig:false ~may_fail:true (if !Param.tulafale != 1 then "@genmf" else "genmf") (snd f2.f_type) in vl := (f2, v) :: (!vl); Var v end else FunApp(f2,[]) end | FunApp(f2,l) -> FunApp(f2, List.map (replace_f_var vl) l) (* [rev_assoc v2 vl] looks for v2 in the association list vl. That is, vl is a list of pairs (f_i, v_i) where f_i is a (nullary) function symbol and v_i is a variable. If v2 is a v_i, then it returns f_i[], otherwise it returns v2 unchanged. *) let rec rev_assoc v2 = function [] -> Var v2 | ((f,v)::l) -> if v2 == v then FunApp(f,[]) else rev_assoc v2 l (* [follow_link var_case t] follows links stored in variables in t and returns the resulting term. Variables are translated by the function [var_case] *) let rec follow_link var_case = function Var v -> begin match v.link with TLink t -> follow_link var_case t | NoLink -> var_case v | _ -> Parsing_helper.internal_error "unexpected link in follow_link" end | FunApp(f,l) -> FunApp(f, List.map (follow_link var_case) l) (* [replace_name f t t'] replaces all occurrences of the name f (ie f[]) with t in t' *) let rec replace_name f t = function Var v -> Var v | FunApp(f',[]) -> if f' == f then t else FunApp(f',[]) | FunApp(f',l') -> FunApp(f', List.map (replace_name f t) l') (* Return true when the term contains a variable *) let rec has_vars = function Var _ -> true | FunApp(f, l) -> List.exists has_vars l (* List of variables *) let rec get_vars vlist = function Var v -> if not (List.memq v (!vlist)) then vlist := v :: (!vlist) | FunApp(_,l) -> List.iter (get_vars vlist) l let get_vars_constra vlist c = iter_constraints (get_vars vlist) c let get_vars_fact vlist = function Pred(_,l) -> List.iter (get_vars vlist) l let rec get_vars_pat accu = function PatVar b -> b::accu | PatTuple(f,l) -> List.fold_left get_vars_pat accu l | PatEqual t -> accu (* Copy of terms and constraints after matching *) let rec copy_term3 = function | FunApp(f,l) -> FunApp(f, List.map copy_term3 l) | Var v -> match v.link with NoLink -> Var v | TLink l -> l | _ -> internal_error "unexpected link in copy_term3" let copy_fact3 = function Pred(p,l) -> Pred(p, List.map copy_term3 l) let rec copy_constra3 c = map_constraints copy_term3 c [ copy_term4 ] follows links [ ] recursively , but does not rename variables but does not rename variables *) let rec copy_term4 = function | FunApp(f,l) -> FunApp(f, List.map copy_term4 l) | Var v -> match v.link with NoLink -> Var v | TLink l -> copy_term4 l | _ -> internal_error "unexpected link in copy_term4" let copy_fact4 = function | Pred(p,args) -> Pred(p,List.map copy_term4 args) let copy_constra4 c = map_constraints copy_term4 c (* Do not select Out facts, blocking facts, or pred_TUPLE(vars) *) let is_var = function Var _ -> true | _ -> false let unsel_set = ref ([] : fact list) let add_unsel f = unsel_set := f :: (!unsel_set) let is_unselectable = function Pred(p,pl) as f -> (p.p_prop land Param.pred_BLOCKING != 0) || (p.p_prop land Param.pred_TUPLE != 0 && p.p_prop land Param.pred_TUPLE_SELECT = 0 && List.for_all is_var pl) || (List.exists (function f' -> try auto_cleanup (fun () -> unify_facts f f'); true with Unify -> false ) (!unsel_set)) (* Helper functions for decomposition of tuples *) let rec reorganize_list l = let rec get_first = function [] -> ([], []) | (a ::l)::l' -> let (firstl, rest) = get_first l' in (a :: firstl, l :: rest) | [] :: _ -> internal_error "unexpected case in reorganize_list" in match l with [] :: _ -> [] | _ -> let (firstl, rest) = get_first l in firstl :: (reorganize_list rest) let fun_app f = function FunApp(f',l) when f == f' -> l | _ -> raise Not_found let reorganize_fun_app f l0 = reorganize_list (List.map (fun_app f) l0) let get_session_id_from_occurrence = function | Var _ -> Parsing_helper.internal_error "The term should be an occurrence name, hence a function application" | FunApp(n,args) -> try let i = List.find (fun t -> get_term_type t == Param.sid_type) args in Some i with Not_found -> None (********************************************* Definition of several functions **********************************************) (* Choice *) (* biprocesses to processes *) let rec has_choice = function Var _ -> false | FunApp(f,l) -> (f.f_cat == Choice) || (List.exists has_choice l) let rec has_choice_format = function | FVar _ | FAny _ -> false | FFunApp(f,l) -> (f.f_cat == Choice) || (List.exists has_choice_format l) let rec has_choice_pat = function PatVar _ -> false | PatTuple(_,l) -> List.exists has_choice_pat l | PatEqual t -> has_choice t Functions to choose one side let rec choice_in_term n = function (Var _) as t -> t | FunApp(f, [t1; t2]) when f.f_cat == Choice -> choice_in_term n (if n = 1 then t1 else t2) | FunApp(f, l) -> FunApp(f, List.map (choice_in_term n) l) let choice_in_fact n = function | Pred(p,args) -> Pred(p,List.map (choice_in_term n) args) let rec choice_in_pat n = function (PatVar _) as pat -> pat | PatTuple(f,l) -> PatTuple(f, List.map (choice_in_pat n) l) | PatEqual t -> PatEqual (choice_in_term n t) (* [choice_in_proc p] Return the process p without all the choices in terms that might be present *) let rec choice_in_proc n = function | Nil -> Nil | Par(p, q) -> Par(choice_in_proc n p, choice_in_proc n q) | Repl(p, occ) -> Repl(choice_in_proc n p, occ) | Restr(f, args, p, occ) -> Restr(f, args, choice_in_proc n p, occ) | Test(t, p, q, occ) -> Test (choice_in_term n t, choice_in_proc n p, choice_in_proc n q, occ) | Input(t, pat, p, occ) -> Input(choice_in_term n t, choice_in_pat n pat, choice_in_proc n p, occ) | Output(t, t', p, occ) -> Output(choice_in_term n t, choice_in_term n t', choice_in_proc n p, occ) | Let(pat, t, p, q, occ) -> Let(choice_in_pat n pat, choice_in_term n t, choice_in_proc n p, choice_in_proc n q, occ) | LetFilter(bl, f, p, q, occ) -> LetFilter(bl, choice_in_fact n f, choice_in_proc n p, choice_in_proc n q, occ) | Event(t, args, p, occ) -> Event(choice_in_term n t, args, choice_in_proc n p, occ) | Insert(t, p, occ) -> Insert(choice_in_term n t, choice_in_proc n p, occ) | Get(pat, t, p, q, occ) -> Get(choice_in_pat n pat, choice_in_term n t, choice_in_proc n p, choice_in_proc n q, occ) | Phase(i, p, occ) -> Phase(i, choice_in_proc n p, occ) | Barrier(i, s, p, occ) -> Barrier(i, s, choice_in_proc n p, occ) | AnnBarrier(i, so, f, f', btl, p, occ) -> AnnBarrier(i, so, f, f', List.map (fun (b, t) -> (b, choice_in_term n t)) btl, choice_in_proc n p, occ) | NamedProcess(s, tl, p) -> NamedProcess(s, List.map (choice_in_term n) tl, choice_in_proc n p) let make_choice t1 t2 = let ty1 = get_term_type t1 and ty2 = get_term_type t2 in if (Param.get_ignore_types()) || (ty1 == ty2) then FunApp(Param.choice_fun ty1, [t1;t2]) else Parsing_helper.internal_error "[Terms.make_choice] This should be the same type" (* Failure Constants *) let get_fail_symb = Param.memo_type (fun ty -> let name = "fail-"^ty.tname in { f_name = Fixed name; f_type = [], ty; f_cat = Failure; f_initial_cat = Failure; f_private = false; f_options = 0 }) let get_fail_term ty = FunApp(get_fail_symb ty, []) let fail_bool() = get_fail_term Param.bool_type fail_bool must be recomputed once Param.ignore_types is correctly set Boolean Constants let true_cst = { f_name = Fixed "true"; f_type = [], Param.bool_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } let false_cst = { f_name = Fixed "false"; f_type = [], Param.bool_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } let true_term = FunApp(true_cst, []) let false_term = FunApp(false_cst, []) Integer constants and functions let zero_cst = { f_name = Fixed "0"; f_type = [], Param.nat_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } let zero_term = FunApp(zero_cst,[]) let fail_nat() = get_fail_term Param.nat_type fail_nat must be recomputed once Param.ignore_types is correctly set let succ_fun = { f_name = Fixed "+"; f_type = [Param.nat_type], Param.nat_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } let rec sum_nat_term t = function | 0 -> t | k -> FunApp(succ_fun,[sum_nat_term t (k-1)]) let generate_nat = sum_nat_term (FunApp(zero_cst,[])) let minus_fun = Param.memo (fun i -> if i <= 0 then Parsing_helper.internal_error "[terms.ml >> minus_fun] Index should be bigger than 0."; let x = new_var_def_term Param.nat_type in let y = FunApp(new_gen_var Param.nat_type false,[]) in let semantics = Red [ [sum_nat_term x i], x, true_constraints; [x], fail_nat(), (constraints_of_neq x (sum_nat_term y i)) ; [fail_nat()], fail_nat(), true_constraints ] in { f_name = Fixed ("- "^(string_of_int i)); f_type = [Param.nat_type], Param.nat_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } ) let is_nat_ref = ref None let is_nat_fun () = match !is_nat_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type in let semantics = Red [ [x], true_term, (constraints_of_is_nat x); [x], false_term, (constraints_of_is_not_nat x); [fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "is_nat"; f_type = [Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in is_nat_ref := Some f; f let greater_ref = ref None let greater_fun () = match !greater_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type and y = new_var_def_term Param.nat_type and u = new_var_def_term ~may_fail:true Param.nat_type in let semantics = Red [ [x;y], true_term, (constraints_of_geq x (FunApp(succ_fun,[y]))); [x;y], false_term, (constraints_of_geq y x); [x;y], fail_bool(), (constraints_of_is_not_nat x); [x;y], fail_bool(), (constraints_of_is_not_nat y); [fail_nat();u], fail_bool(), true_constraints; [x;fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed ">"; f_type = [Param.nat_type;Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in greater_ref := Some f; f let geq_ref = ref None let geq_fun () = match !geq_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type and y = new_var_def_term Param.nat_type and u = new_var_def_term ~may_fail:true Param.nat_type in let semantics = Red [ [x;y], true_term, (constraints_of_geq x y); [x;y], false_term, (constraints_of_geq y (FunApp(succ_fun,[x]))); [x;y], fail_bool(), (constraints_of_is_not_nat x); [x;y], fail_bool(), (constraints_of_is_not_nat y); [fail_nat();u], fail_bool(), true_constraints; [x;fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed ">="; f_type = [Param.nat_type;Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in geq_ref := Some f; f let less_ref = ref None let less_fun () = match !less_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type and y = new_var_def_term Param.nat_type and u = new_var_def_term ~may_fail:true Param.nat_type in let semantics = Red [ [y;x], true_term, (constraints_of_geq x (FunApp(succ_fun,[y]))); [y;x], false_term, (constraints_of_geq y x); [y;x], fail_bool(), (constraints_of_is_not_nat x); [y;x], fail_bool(), (constraints_of_is_not_nat y); [fail_nat();u], fail_bool(), true_constraints; [x;fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "<"; f_type = [Param.nat_type;Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in less_ref := Some f; f let leq_ref = ref None let leq_fun () = match !leq_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type and y = new_var_def_term Param.nat_type and u = new_var_def_term ~may_fail:true Param.nat_type in let semantics = Red [ [y;x], true_term, (constraints_of_geq x y); [y;x], false_term, (constraints_of_geq y (FunApp(succ_fun,[x]))); [y;x], fail_bool(), (constraints_of_is_not_nat x); [y;x], fail_bool(), (constraints_of_is_not_nat y); [fail_nat();u], fail_bool(), true_constraints; [x;fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "<="; f_type = [Param.nat_type;Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in leq_ref := Some f; f let rec is_syntactic_natural_number = function | FunApp(f,[]) when f == zero_cst -> true | FunApp(f,[t]) when f == succ_fun -> is_syntactic_natural_number t | _ -> false (* is_true destructor: returns true when its argument is true, fails otherwise *) let is_true_ref = ref None let is_true_fun() = match !is_true_ref with Some f -> f | None -> let x = new_var_def_term Param.bool_type in let semantics = Red [ [true_term], true_term, true_constraints; [x], fail_bool(), (constraints_of_neq x true_term); [fail_bool()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "is-true"; f_type = [Param.bool_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in is_true_ref := Some f; f (* Boolean Functions *) let equal_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and y = new_var_def_term ty and u = new_var_def_term ~may_fail:true ty and fail = get_fail_term ty in let semantics = Red [ [x;x], true_term, true_constraints; [x;y], false_term, (constraints_of_neq x y); [fail;u], fail_bool(), true_constraints; [x;fail], fail_bool(), true_constraints ] in { f_name = Fixed "="; f_type = [ty;ty], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 }) let diff_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and y = new_var_def_term ty and u = new_var_def_term ~may_fail:true ty and fail = get_fail_term ty in let semantics = Red [ [x;x], false_term, true_constraints; [x;y], true_term, (constraints_of_neq x y); [fail;u], fail_bool(), true_constraints; [x;fail], fail_bool(), true_constraints ] in { f_name = Fixed "<>"; f_type = [ty;ty], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 }) let and_ref = ref None let and_fun() = match !and_ref with Some f ->f | None -> let u = new_var_def_term ~may_fail:true Param.bool_type and x = new_var_def_term Param.bool_type in let semantics = Red [ When the first conjunct is " false " , the second conjunct is not evaluated , so the conjunction is " false " even if the second conjunct fails so the conjunction is "false" even if the second conjunct fails *) [true_term; u], u, true_constraints; [x;u], false_term, (constraints_of_neq x true_term); [fail_bool(); u], fail_bool(), true_constraints ] in let f = { f_name = Fixed "&&"; f_type = [Param.bool_type; Param.bool_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in and_ref := Some f; f let or_ref = ref None let or_fun() = match !or_ref with Some f -> f | None -> let u = new_var_def_term ~may_fail:true Param.bool_type and x = new_var_def_term Param.bool_type in let semantics = Red [ When the first disjunct is " true " , the second disjunct is not evaluated , so the disjunction is " true " even if the second disjunct fails so the disjunction is "true" even if the second disjunct fails *) [true_term; u], true_term, true_constraints; [x;u], u, (constraints_of_neq x true_term); [fail_bool(); u], fail_bool(), true_constraints ] in let f = { f_name = Fixed "||"; f_type = [Param.bool_type; Param.bool_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in or_ref := Some f; f let not_ref = ref None let not_fun() = match !not_ref with Some f -> f | None -> let x = new_var_def_term Param.bool_type in let semantics = Red [ [true_term], false_term, true_constraints; [x], true_term, (constraints_of_neq x true_term); [fail_bool()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "not"; f_type = [Param.bool_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in not_ref := Some f; f (* [make_not a] returns the negation of the term [a] *) let make_not a = let not_fun = not_fun() in match a with FunApp(f, [a']) when f == not_fun -> a' | _ -> FunApp(not_fun, [a]) [ and_list l ] returns the conjunction of the terms in [ l ] let rec and_list = function [] -> true_term | [a] -> a | a::l -> FunApp(and_fun(), [a; and_list l]) (* [or_not_list l] returns the disjunction of the negation of the terms in [l] *) let rec or_not_list = function [] -> false_term | [a] -> make_not a | a::l -> FunApp(or_fun(), [make_not a; or_not_list l]) (* The Let in else operators *) let glet_constant_fun = Param.memo_type (fun ty -> { f_name = Fixed "caught-fail"; f_type = [],ty; f_cat = Tuple; f_initial_cat = Tuple; f_private = true; f_options = 0 }) let glet_constant_never_fail_fun = Param.memo_type (fun ty -> { f_name = Fixed "never-fail"; f_type = [],ty; f_cat = Tuple; f_initial_cat = Tuple; f_private = true; f_options = 0 }) let glet_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and fail = get_fail_term ty and c_o = glet_constant_fun ty in let semantics = Red [ [x], x, true_constraints; [fail], FunApp(c_o,[]), true_constraints ] in { f_name = Fixed "catch-fail"; f_type = [ty], ty; f_cat = semantics; f_initial_cat = semantics; f_private = true; f_options = 0 }) (* The success operators *) let success_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and fail = get_fail_term ty in let semantics = Red [ [x], true_term, true_constraints; [fail], false_term, true_constraints ] in { f_name = Fixed "success?"; f_type = [ty], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } ) let not_caught_fail_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and c_o = glet_constant_fun ty and fail = get_fail_term ty in let semantics = Red [ [x], true_term, (constraints_of_neq x (FunApp(c_o,[]))); [FunApp(c_o,[])], false_term, true_constraints; [fail], fail_bool(), true_constraints ] in { f_name = Fixed "not-caught-fail"; f_type = [ty], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = true; f_options = 0 } ) let gtest_fun = Param.memo_type (fun ty -> let u = new_var_def_term ~may_fail:true ty and v = new_var_def_term ~may_fail:true ty and x = new_var_def_term Param.bool_type and fail = get_fail_term ty in let semantics = Red [ [true_term;u;v], u, true_constraints; [x;u;v], v, (constraints_of_neq x true_term); [fail_bool();u;v], fail, true_constraints ] in { f_name = Fixed "if-then-else"; f_type = [Param.bool_type;ty;ty], ty; f_cat = semantics; f_initial_cat = semantics; f_private = true; f_options = 0 }) (* The projection operator *) let complete_semantics_constructors type_arg type_result = let var_fail_list = List.map (new_var_def_term ~may_fail:true) type_arg and var_list = List.map new_var_def_term type_arg and fail_list = List.map get_fail_term type_arg and fail_result = get_fail_term type_result in let rec sub_complete var_list var_fail_list fail_list = match var_list, var_fail_list, fail_list with | [], [], [] -> [] | x::var_l, _::var_fl, fail::fail_l -> let prev_list = sub_complete var_l var_fl fail_l in (fail::var_fl)::(List.map (fun l -> x::l) prev_list) | _,_,_ -> internal_error "The three lists should have the same size" in List.map (fun l -> l, fail_result,true_constraints) (sub_complete var_list var_fail_list fail_list) let red_rules_constructor f = let vars1 = var_gen (fst f.f_type) in (vars1, FunApp(f, vars1),true_constraints) :: (complete_semantics_constructors (fst f.f_type) (snd f.f_type)) let red_rules_fun f = match f.f_cat with Eq red_rules -> (red_rules_constructor f) @ (List.map (fun (lhs,rhs) -> (lhs, rhs, true_constraints)) red_rules) | Red red_rules -> red_rules | Name _ -> [([],FunApp(f,[]),true_constraints)] This is ok because this function is called either not with names ( calls from Pitransl / Pitranslweak and from TermsEq.close_term_destr_eq when it is used on clauses that define LetFilter predicates ) or only with names from processes ( calls from TermsEq.close_term_destr_eq that come from Simplify ) . We never have name function symbols here . either not with names (calls from Pitransl/Pitranslweak and from TermsEq.close_term_destr_eq when it is used on clauses that define LetFilter predicates) or only with names from processes (calls from TermsEq.close_term_destr_eq that come from Simplify). We never have name function symbols here. *) | _ -> red_rules_constructor f let get_function_name f = match f.f_cat, f.f_name with Tuple, Fixed "" -> let arity = List.length (fst f.f_type) in if (arity = 0) || (Param.get_ignore_types()) then (string_of_int arity) ^ "-tuple" else (tl_to_string "-" (fst f.f_type)) ^ "-tuple" | _, Fixed s -> s | _ -> Parsing_helper.internal_error "get_function_name expects function with fixed name" let projection_fun = Param.memo (fun (f_symb,i) -> if f_symb.f_cat <> Tuple then internal_error "[Terms.projection_fun] This should be a tuple"; if f_symb == succ_fun then minus_fun 1 else let type_list = fst f_symb.f_type in let type_result = snd f_symb.f_type in let var_list = var_gen type_list and gen_var_list = List.map (fun ty -> FunApp(new_gen_var ty false,[])) type_list and x = new_var_def_term type_result and ieme_type = List.nth type_list (i-1) in let fail = get_fail_term type_result and fail' = get_fail_term ieme_type in let semantics = Red [ [FunApp(f_symb,var_list)], List.nth var_list (i-1), true_constraints; [x], fail', (constraints_of_neq x (FunApp(f_symb,gen_var_list))); [fail], fail', true_constraints ] in let name = Printf.sprintf "%d-proj-%s" i (get_function_name f_symb) in { f_name = Fixed name; f_type = [type_result], ieme_type; f_cat = semantics; f_initial_cat = semantics; f_private = f_symb.f_private; f_options = 0 }) (* [get_all_projection_fun tuple_symb] returns the list of projection functions corresponding to the tuple function [tuple_symb] *) let get_all_projection_fun tuple_symb = let rec sub_get_proj n l = match l with | [] -> [] | _::q -> (projection_fun (tuple_symb,n))::(sub_get_proj (n+1) q) in sub_get_proj 1 (fst tuple_symb.f_type) (* [clauses_for_function clauses_for_red_rules f] generates clauses for a function [f], given a function [clauses_for_red_rules] such that [clauses_for_red_rules f red_rules] generates clauses for function that has rewrite rules [red_rules]. (For constructors, the rewrite rules f(...fail...) -> fail are omitted from [red_rules]. The function [clauses_for_red_rules] must take this point into account. In practice, this is easy because the clauses that come from f(...fail...) -> fail are useless. This however needs to be justified in each case.) *) let rec clauses_for_function clauses_for_red_rules f = if (not f.f_private) && (* Don't generate clauses for type converter functions when we ignore types (These functions disappear.) *) (not ((f.f_options land Param.fun_TYPECONVERTER != 0) && (Param.get_ignore_types()))) then match f.f_cat with Eq red_rules -> let vars1 = var_gen (fst f.f_type) in let red_rules = (vars1, FunApp(f, vars1),true_constraints) :: (List.map (fun (lhs,rhs) -> (lhs, rhs, true_constraints)) red_rules) in clauses_for_red_rules f red_rules | Red red_rules -> clauses_for_red_rules f red_rules | Tuple -> (* For tuple constructor *) let vars1 = var_gen (fst f.f_type) in clauses_for_red_rules f [(vars1, FunApp(f, vars1),true_constraints)]; (* For corresponding projections *) List.iter (clauses_for_function clauses_for_red_rules) (get_all_projection_fun f) | _ -> () (* Names *) let new_name_fun = Param.memo_type (fun t -> let cat = Name { prev_inputs = None; prev_inputs_meaning = [MAttSid] } in let name = "new-name" ^ (Param.get_type_suffix t) in { f_name = Renamable (new_id name); f_type = [Param.sid_type], t; f_cat = cat; f_initial_cat = cat; f_private = false; f_options = 0 }) (********************************************* Occurrences **********************************************) let occ_count = ref 0 let reset_occurrence () = occ_count := 0 let new_occurrence ?(precise=false) () = incr occ_count; { occ = !occ_count; precise = precise } let rec put_lets p = function [] -> p | (v,t)::l -> put_lets (Let(PatVar v,t,p,Nil,new_occurrence())) l (********************************************* New names **********************************************) let create_name_internal name ty is_private = let cat = Name { prev_inputs = None; prev_inputs_meaning = [] } in { f_name = name; f_type = ty; f_cat = cat; f_initial_cat = cat; f_private = is_private; f_options = 0 } let create_name ?(allow_rename=true) ?orig s ty is_private = let name = if allow_rename then Renamable (new_id ?orig s) else Fixed s in create_name_internal name ty is_private let copy_name ?orig n arg_type = let name = match n.f_name with Fixed s -> Parsing_helper.internal_error "Should only copy names that can be renamed" | Renamable id -> Renamable (copy_id ?orig id) in create_name_internal name (arg_type, snd n.f_type) n.f_private (********************************************** Rewrite rules for destructors with otherwise ***********************************************) exception True_inequality exception False_inequality let generate_destructor_with_side_cond prev_args lht_list rht ext = (* Given an inequality [for all (may-fail variabless in uni_term_list), term_list <> uni_term_list], [remove_uni_fail_var] returns [(l1,l2)] representing an inequality [l1 <> l2] equivalent to the initial inequality, by removing the may-fail variables. *) let rec remove_uni_fail_var term_list uni_term_list = match term_list, uni_term_list with | [],[] -> [],[] | [],_ | _,[] -> internal_error "The two lists should have the same length" | t::q, Var(v)::uq when v.unfailing -> begin match v.link with | NoLink -> link v (TLink t); remove_uni_fail_var q uq | TLink t' -> let (list_left,list_right) = remove_uni_fail_var q uq in (t::list_left,t'::list_right) | _ -> internal_error "Unexpected link" end | t::q,ut::uq -> let (list_left,list_right) = remove_uni_fail_var q uq in (t::list_left,ut::list_right) in When [ prev_args = ( a1, ... ,an ) ] is the list of arguments of the previous rewrite rules , [ generalize_prev_args ] builds returns a list of pairs [ ( li , ' ) ] representing the inequality [ \wedge_i li < > li ' ] equivalent to the inequality [ \wedge_i forall ( variables in ai ) , lht_list < > ai ] . The returned inequalities do not contain general may - fail variables ( thanks to remove_uni_fail_var ) , but may contain may - fail variables . These variables will be removed in the next steps by case distinctions . rewrite rules, [generalize_prev_args] builds returns a list of pairs [(li,li')] representing the inequality [\wedge_i li <> li'] equivalent to the inequality [\wedge_i forall (variables in ai), lht_list <> ai]. The returned inequalities do not contain general may-fail variables (thanks to remove_uni_fail_var), but may contain may-fail variables. These variables will be removed in the next steps by case distinctions. *) let rec generalize_prev_args prev_args = match prev_args with | [] -> [] | term_list::q -> (* Get the variables *) let vars = ref [] in List.iter (get_vars vars) term_list; (* Remove the may-fail variables *) let message_var_list = List.filter (fun v -> not (v.unfailing)) !vars in the variables let term_list' = auto_cleanup (fun () -> List.map (generalize_vars_in message_var_list) term_list ) in (* Remove the universal may-fail variables *) let (lterms_left,lterms_right) = auto_cleanup (fun () -> remove_uni_fail_var lht_list term_list' ) in (lterms_left,lterms_right)::(generalize_prev_args q) in let rec get_may_fail_vars varsl term = match term with | Var(v) -> begin match v.link with | NoLink -> if v.unfailing && not (List.memq v (!varsl)) then varsl := v :: (!varsl) | TLink(t) -> get_may_fail_vars varsl t | _ -> internal_error "Unexpected link" end | FunApp(_,l) -> List.iter (get_may_fail_vars varsl) l in let rec simplify_one_neq term_left term_right = match term_left,term_right with | Var(vl),Var(vr) when vl==vr -> raise False_inequality | FunApp(f,_), FunApp(f',_) when f.f_cat = Failure && f'.f_cat = Failure -> raise False_inequality | Var({link = TLink tl}),tr -> simplify_one_neq tl tr | tl, Var({link = TLink tr}) -> simplify_one_neq tl tr | Var(v),FunApp(f,_) when v.unfailing = false && f.f_cat = Failure -> raise True_inequality | FunApp(f,_), Var(v) when v.unfailing = false && f.f_cat = Failure -> raise True_inequality | FunApp(f,_),FunApp(f',_) when f'.f_cat = Failure -> raise True_inequality | FunApp(f,_),FunApp(f',_) when f.f_cat = Failure -> raise True_inequality | _,_ -> term_left,term_right in let simplify_neq lterm_left lterm_right = List.fold_left2 (fun (neql,neqr) term_left term_right -> try let term_left',term_right' = simplify_one_neq term_left term_right in (term_left'::neql),(term_right'::neqr) with | False_inequality -> (neql,neqr) ) ([],[]) lterm_left lterm_right in let destructors = ref [] in let rec remove_may_fail_term_neq list_neq = (* Simplify Neq *) let list_neq' = List.fold_left (fun lneq (lterm_left,lterm_right) -> try let (lterm_left', lterm_right') = simplify_neq lterm_left lterm_right in if lterm_left' = [] then raise False_inequality; (lterm_left', lterm_right')::lneq with True_inequality -> lneq ) [] list_neq in (* Get the may_fail_variables *) let vars = ref [] in List.iter (fun (lleft,lright) -> List.iter (get_may_fail_vars vars) lleft; List.iter (get_may_fail_vars vars) lright ) list_neq'; let may_fail_var_list = !vars in if may_fail_var_list = [] then (* If no more may-fail variables in inequalities then return the destructor *) auto_cleanup (fun () -> let rht' = copy_term2 rht and lht' = List.map copy_term2 lht_list and side_neq = List.map (fun (left_l, right_l) -> let left_l' = List.map copy_term2 left_l and right_l' = List.map copy_term2 right_l in let type_list = List.map get_term_type left_l' in let tuple_symb = get_tuple_fun type_list in [FunApp(tuple_symb,left_l'),FunApp(tuple_symb,right_l')] ) list_neq' in let side_c = { neq = side_neq; is_nat = []; is_not_nat = []; geq = [] } in (* Check the variables of the right hand terms *) let var_list_rht = ref [] in get_vars var_list_rht rht'; if not (List.for_all (fun v -> List.exists (occurs_var v) lht') (!var_list_rht)) then Parsing_helper.input_error "All variables of the right-hand side of a \"reduc\" definition\nshould also occur in the left-hand side" ext; destructors := (lht',rht',side_c)::!destructors ) else begin let mf_var = List.hd may_fail_var_list in (* Replace the may-fail variable by Fail *) auto_cleanup (fun () -> let fail = get_fail_term mf_var.btype in link mf_var (TLink fail); try remove_may_fail_term_neq list_neq' with | False_inequality -> () ); (* Replace the may-fail variable by a message variable *) auto_cleanup (fun () -> let x = new_var_def_term mf_var.btype in link mf_var (TLink x); try remove_may_fail_term_neq list_neq' with | False_inequality -> () ) end in let list_side_c = generalize_prev_args prev_args in remove_may_fail_term_neq list_side_c; !destructors (* Combined query goal *) let rec fact_list_of_combined_conclusion pl args = match pl with | [] -> if args <> [] then Parsing_helper.internal_error "[reduction_helper.ml >> fact_list_of_combined_conclusion] Conclusion does not match the query."; [] | p :: q_pl -> let nb_args = List.length p.p_type in let args_p, rest_args = split_list nb_args args in Pred(p,args_p)::(fact_list_of_combined_conclusion q_pl rest_args) let fact_list_of_conclusion = function | Pred({ p_info = [Combined pl]; _ }, args) -> fact_list_of_combined_conclusion pl args | pred -> [pred]
null
https://raw.githubusercontent.com/LCBH/UKano/13c046ddaca48b45d3652c3ea08e21599e051527/proverif2.01/src/terms.ml
ocaml
Basic functions for list. [starts_with s sub] is true when the string [s] starts with [sub] TO DO The current code works, but in principle, it would be nicer if [tuple_taple] was a field in [t_pi_state/t_horn_state], to avoid keeping tuple functions when they are no longer useful. That would probably complicate the code, however. Get the type of a pattern print_string (s ^ " split into " ^ s' ^ " " ^ (string_of_int n') ^ "\n"); s does not end with _xxx Counter incremented to generate fresh variable names The maximum xxx such N_xxx occurs and xxx does not come from var_idx Set of pairs (s,n) used, stored in a hash table. All pairs (_,n) where 0 < n <= !var_idx are considered as always used, so we need not add them to the hash table. All pairs (s,n) in [used_ids] satisfy [n <= !max_source_idx] [record_id s id ext] records the identifier [s] so that it will not be reused elsewhere. [record_id] must be called only before calls to [fresh_id] or [new_var_name], so that [s] cannot collide with an identifier generated by [fresh_id] or [new_var_name]. [id] is the conversion of [s] into a pair (string, int) by [get_id_n]. Moreover, !var_idx = 0, there are no pairs (_,n) with 0 < n <= !var_idx, so the used pairs are exactly those in the hash table used_ids. ************************************************** Basic functions for constraints *************************************************** ************************************************** Function for Var *************************************************** [new_var_name s] creates a fresh pair [(s,n)] using [!var_idx]. [fresh_id s] creates a fresh identifier [s'] corresponding to identifier [s]. [new_var s t] creates a fresh variable with name [s] and type [t] [new_var_def t] creates a fresh variable with a default name and type [t] [val_gen tl] creates new variables of types [tl] and returns them in a list [occurs_var v t] determines whether the variable [v] occurs in the term [t] [occurs_vars_all bl t] returns true when all variables occuring in [t] are in [bl]. [occurs_f f t] determines whether the function symbol [f] occurs in the term [t] Equality tests [same_term_lists pub1 pub2] returns [true] if and only if [pub1] and [pub2] contains the same terms. Copy and cleanup Check that message variables are linked only to messages, not to fail or to may-fail variables NoLink should not be used with function link, it is set by cleanup Check that types are correct, when they are not ignored ************************************************** Functions for General Variables *************************************************** ************************************************** Copy term functions *************************************************** Matching [occurs_test_loop seen_vars v t] returns true when variable [v] occurs in term [t], following links inside terms. It uses the list [seen_vars] to avoid loops. [seen_vars] should be initialized to [ref []]. If a variable v is instantiated in the match into a term that is not a variable and that contains v, then by repeated resolution, the term will be instantiated into an infinite number of different terms obtained by iterating the substitution. We should adjust the selection function to avoid this non-termination. Size [replace_f_var vl t] replaces names in t according to the association list vl. That is, vl is a reference to a list of pairs (f_i, v_i) where f_i is a (nullary) function symbol and v_i is a variable. Each f_i is replaced with v_i in t. If an f_i in general_vars occurs in t, a new entry is added to the association list vl, and f_i is replaced accordingly. [rev_assoc v2 vl] looks for v2 in the association list vl. That is, vl is a list of pairs (f_i, v_i) where f_i is a (nullary) function symbol and v_i is a variable. If v2 is a v_i, then it returns f_i[], otherwise it returns v2 unchanged. [follow_link var_case t] follows links stored in variables in t and returns the resulting term. Variables are translated by the function [var_case] [replace_name f t t'] replaces all occurrences of the name f (ie f[]) with t in t' Return true when the term contains a variable List of variables Copy of terms and constraints after matching Do not select Out facts, blocking facts, or pred_TUPLE(vars) Helper functions for decomposition of tuples ******************************************** Definition of several functions ********************************************* Choice biprocesses to processes [choice_in_proc p] Return the process p without all the choices in terms that might be present Failure Constants is_true destructor: returns true when its argument is true, fails otherwise Boolean Functions [make_not a] returns the negation of the term [a] [or_not_list l] returns the disjunction of the negation of the terms in [l] The Let in else operators The success operators The projection operator [get_all_projection_fun tuple_symb] returns the list of projection functions corresponding to the tuple function [tuple_symb] [clauses_for_function clauses_for_red_rules f] generates clauses for a function [f], given a function [clauses_for_red_rules] such that [clauses_for_red_rules f red_rules] generates clauses for function that has rewrite rules [red_rules]. (For constructors, the rewrite rules f(...fail...) -> fail are omitted from [red_rules]. The function [clauses_for_red_rules] must take this point into account. In practice, this is easy because the clauses that come from f(...fail...) -> fail are useless. This however needs to be justified in each case.) Don't generate clauses for type converter functions when we ignore types (These functions disappear.) For tuple constructor For corresponding projections Names ******************************************** Occurrences ********************************************* ******************************************** New names ********************************************* ********************************************* Rewrite rules for destructors with otherwise ********************************************** Given an inequality [for all (may-fail variabless in uni_term_list), term_list <> uni_term_list], [remove_uni_fail_var] returns [(l1,l2)] representing an inequality [l1 <> l2] equivalent to the initial inequality, by removing the may-fail variables. Get the variables Remove the may-fail variables Remove the universal may-fail variables Simplify Neq Get the may_fail_variables If no more may-fail variables in inequalities then return the destructor Check the variables of the right hand terms Replace the may-fail variable by Fail Replace the may-fail variable by a message variable Combined query goal
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * , , and * * * * Copyright ( C ) INRIA , CNRS 2000 - 2020 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * Bruno Blanchet, Vincent Cheval, and Marc Sylvestre * * * * Copyright (C) INRIA, CNRS 2000-2020 * * * *************************************************************) 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 ( in file LICENSE ) . 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA 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 (in file LICENSE). 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) open Parsing_helper open Types let rec split_list size = function | q when size = 0 -> [], q | [] -> Parsing_helper.internal_error "[terms.ml >> split_list] Wrong parameter." | t::q -> let (l1,l2) = split_list (size-1) q in (t::l1,l2) [ s sub ] is true when the string [ s ] ends with [ sub ] let ends_with s sub = let l_s = String.length s in let l_sub = String.length sub in (l_s >= l_sub) && (String.sub s (l_s - l_sub) l_sub = sub) let starts_with s sub = let l_s = String.length s in let l_sub = String.length sub in (l_s >= l_sub) && (String.sub s 0 l_sub = sub) let tuple_table = Hashtbl.create 1 let get_tuple_fun tl = let tl = if Param.get_ignore_types() then List.map (fun t -> Param.any_type) tl else tl in try Hashtbl.find tuple_table tl with Not_found -> let r = { f_name = Fixed ""; f_type = tl, Param.bitstring_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } in Hashtbl.add tuple_table tl r; r let get_term_type = function Var b -> b.btype | FunApp(f,_) -> snd f.f_type let equal_types t1 t2 = (Param.get_ignore_types()) || t1 == t2 let get_pat_type = function PatVar b -> b.btype | PatTuple (f,l) -> snd f.f_type | PatEqual t -> get_term_type t let get_format_type = function FVar b -> b.btype | FAny b -> b.btype | FFunApp(f,_) -> snd f.f_type let term_of_pattern_variable = function | PatVar(v) -> Var(v) | _ -> internal_error "[term_of_pattern_variable] The pattern must be a variable" let rec copy_n n v = if n <= 0 then [] else v :: (copy_n (n-1) v) let rec tl_to_string sep = function [] -> "" | [a] -> a.tname | (a::l) -> a.tname ^ sep ^ (tl_to_string sep l) let rec eq_lists l1 l2 = match l1,l2 with [],[] -> true | a1::q1,a2::q2 -> (a1 == a2) && (eq_lists q1 q2) | _,_ -> false These functions are used to guarantee the freshness of new identifiers Each identifier is represented by a pair ( s , n ): - if n = 0 , then ( s , n ) is displayed s - otherwise , ( s , n ) is displayed s_n Invariant : n has at most 9 digits ( supports one billion of variables ) ; when n = 0 , s is never of the form N_xxx where xxx is a non - zero number of at most 9 digits . This guarantees that for each identifier , ( s , n ) is unique . We guarantee the freshness by changing the value of n Each identifier is represented by a pair (s,n): - if n = 0, then (s,n) is displayed s - otherwise, (s,n) is displayed s_n Invariant: n has at most 9 digits (supports one billion of variables); when n = 0, s is never of the form N_xxx where xxx is a non-zero number of at most 9 digits. This guarantees that for each identifier, (s,n) is unique. We guarantee the freshness by changing the value of n *) [ get_id_n s ] converts [ s ] into a pair [ ( ) ] displayed [ s ] let get_id_n s = let l = String.length s in if '0' <= s.[l-1] && s.[l-1] <= '9' then let rec underscore_number n = if (n > 0) && (l-n<=10) then if s.[n] = '_' then n else if '0' <= s.[n] && s.[n] <= '9' then underscore_number (n-1) else raise Not_found else raise Not_found in try let pos_underscore = underscore_number (l-2) in if s.[pos_underscore+1] = '0' then raise Not_found; let n' = int_of_string (String.sub s (pos_underscore+1) (l-pos_underscore-1)) in let s' = String.sub s 0 pos_underscore in (s',n') with Not_found -> (s,0) else (s,0) let var_idx = ref 0 let max_source_idx = ref 0 let used_ids = Hashtbl.create 7 Clear used_ids . Used to reload a file in proverif interact mode let init_used_ids () = Hashtbl.clear used_ids let record_id s ((_,n) as s_n) ext = if n > !max_source_idx then max_source_idx := n; if Hashtbl.mem used_ids s_n then input_error ("identifier " ^ s ^ " already defined (as a free name, a function, a predicate, a type, an event, or a table)") ext else Hashtbl.add used_ids s_n () let exists_constraints f constra = List.exists (List.exists (fun (t1,t2) -> f t1 || f t2)) constra.neq || List.exists f constra.is_nat || List.exists f constra.is_not_nat || List.exists (fun (t1,_,t2) -> f t1 || f t2) constra.geq let map_constraints f constra = { neq = (List.map (List.map (fun (t1,t2) -> f t1, f t2)) constra.neq); is_nat = (List.map f constra.is_nat); is_not_nat = (List.map f constra.is_not_nat); geq = (List.map (fun (t1,n,t2) -> (f t1, n, f t2)) constra.geq) } let iter_constraints f constra = List.iter (List.iter (fun (t1,t2) -> f t1; f t2)) constra.neq; List.iter f constra.is_nat; List.iter f constra.is_not_nat; List.iter (fun (t1,_,t2) -> f t1; f t2) constra.geq let true_constraints = { neq = []; is_nat = []; is_not_nat = []; geq = [] } let constraints_of_neq t1 t2 = { neq = [[t1,t2]]; is_nat = []; is_not_nat = []; geq = [] } let constraints_of_is_nat t = { neq = []; is_nat = [t]; is_not_nat = []; geq = [] } let constraints_of_is_not_nat t = { neq = []; is_nat = []; is_not_nat = [t]; geq = [] } let constraints_of_geq t1 t2 = { neq = []; is_nat = []; is_not_nat = []; geq = [t1,0,t2] } let is_true_constraints c = c.neq == [] && c.is_nat == [] && c.is_not_nat == [] && c.geq == [] let wedge_constraints c1 c2 = { neq = c1.neq @ c2.neq; is_nat = c1.is_nat @ c2.is_nat; is_not_nat = c1.is_not_nat @ c2.is_not_nat; geq = c1.geq @ c2.geq } let rec new_var_name s = incr var_idx; let n = !var_idx in if (n <= !max_source_idx) && (Hashtbl.mem used_ids (s,n)) then new_var_name s else (s,n) let id_n2id (s,n) = if n = 0 then s else s ^ "_" ^ (string_of_int n) [ fresh_id_n s ] creates a fresh pair [ ( ) ] corresponding to identifier [ s ] . identifier [s]. *) let fresh_id_n s = let (s',_) = get_id_n s in new_var_name s' let fresh_id s = id_n2id (fresh_id_n s) let new_id ?(orig=true) s = let (s',n) = fresh_id_n s in { orig_name = if orig then s else ""; name = s'; idx = n; display = None } let copy_id ?(orig=true) id = let (s',n) = new_var_name id.name in { orig_name = if orig then id.orig_name else ""; name = s'; idx = n; display = None } let string_of_id id = id_n2id (id.name, id.idx) let new_var ?orig ?(may_fail=false) s t = let s0 = if may_fail then if s = "" then "@mayfail" else "@mayfail_" ^ s else s in { vname = new_id ?orig s0; unfailing = may_fail; btype = t; link = NoLink } [ copy_var v ] creates a fresh variable with the same sname and type as [ v ] Invariant : if vname = 0 , then sname never contains N_xxx where xxx is a non - zero number of at most 9 digits . As a consequence , we do n't need to split v.sname using fresh_id_n . Invariant: if vname = 0, then sname never contains N_xxx where xxx is a non-zero number of at most 9 digits. As a consequence, we don't need to split v.sname using fresh_id_n. *) let copy_var ?(rename=true) ?orig v = { vname = if rename then copy_id ?orig v.vname else v.vname; unfailing = v.unfailing; btype = v.btype; link = NoLink } let new_var_def ?may_fail t = new_var ~orig:false ?may_fail Param.def_var_name t let new_var_def_term ?may_fail t = Var (new_var_def ?may_fail t) let var_gen tl = List.map new_var_def_term tl let get_fsymb_basename f = match f.f_name with Fixed s -> s | Renamable id -> id.name let get_fsymb_origname f = match f.f_name with Fixed s -> s | Renamable id -> id.orig_name let rec occurs_var v = function Var v' -> v == v' | FunApp(f,l) -> List.exists (occurs_var v) l let rec occurs_var_format v = function FVar v' | FAny v' -> v == v' | FFunApp(f,l) -> List.exists (occurs_var_format v) l let occurs_var_fact v = function Pred(_,l) -> List.exists (occurs_var v) l let occurs_var_constraints v constra = exists_constraints (occurs_var v) constra let rec occurs_vars_all bl = function | Var v -> List.exists (fun v' -> v == v') bl | FunApp(_,l) -> List.for_all (occurs_vars_all bl) l let rec occurs_f f = function Var _ -> false | FunApp(f',l) -> (f == f') || (List.exists (occurs_f f) l) let rec occurs_f_pat f = function PatVar v -> false | PatTuple (_,l) -> List.exists (occurs_f_pat f) l | PatEqual t -> occurs_f f t let occurs_f_fact f = function Pred(_,l) -> List.exists (occurs_f f) l let occurs_f_constra f constra = exists_constraints (occurs_f f) constra let is_may_fail_term = function | FunApp(f,[]) when f.f_cat = Failure -> true | Var(v) when v.unfailing -> true | _ -> false let is_unfailing_var = function | Var(v) when v.unfailing -> true | _ -> false let is_failure = function | FunApp(f,[]) when f.f_cat = Failure -> true | _ -> false let is_sub_predicate p1 p2 = match p1.p_info, p2.p_info with | [Attacker(n1,typ1)], [Attacker(n2,typ2)] | [AttackerBin(n1,typ1)], [AttackerBin(n2,typ2)] -> n1 >= n2 && equal_types typ1 typ2 | [Table(n1)], [Table(n2)] | [TableBin(n1)], [TableBin(n2)] -> n1 >= n2 | _, _ -> p1 == p2 let rec equal_terms t1 t2 = match (t1,t2) with | (FunApp(f1,l1), FunApp(f2,l2)) -> (f1 == f2) && (List.for_all2 equal_terms l1 l2) | (Var v1, Var v2) -> v1 == v2 | (_,_) -> false let same_term_lists pub1 pub2 = List.length pub1 == List.length pub2 && List.for_all (fun t -> List.exists (equal_terms t) pub2) pub1 && List.for_all (fun t -> List.exists (equal_terms t) pub1) pub2 let rec equal_formats t1 t2 = match (t1,t2) with | FVar v1, FVar v2 | FAny v1, FAny v2 -> v1 == v2 | FFunApp(f1,args1), FFunApp(f2,args2) -> f1 == f2 && List.for_all2 equal_formats args1 args2 | _ -> false let equal_fact_formats (p1,args1) (p2,args2) = p1 == p2 && List.for_all2 equal_formats args1 args2 let equal_facts f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2, t2) -> (chann1 == chann2) && (List.for_all2 equal_terms t1 t2) let equal_facts_phase_geq f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2, t2) -> (is_sub_predicate chann1 chann2) && (List.for_all2 equal_terms t1 t2) let current_bound_vars = ref [] let link v l = if not v.unfailing then begin match l with VLink v' -> assert (not v'.unfailing) | TLink t -> begin match t with Var v' -> assert (not v'.unfailing) | FunApp(f, _) -> assert (f.f_cat != Failure) end | TLink2 _ -> TLink2 is not used with function link assert false | NoLink -> assert false | FLink _ | PGLink _ -> () end; begin match l with VLink v' -> assert (equal_types v.btype v'.btype) | TLink t -> assert (equal_types v.btype (get_term_type t)) | _ -> () end; current_bound_vars := v :: (!current_bound_vars); v.link <- l let link_var t l = match t with |Var(v) -> link v l |_ -> internal_error "[link_var] The term must be a variable" let cleanup () = List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := [] let auto_cleanup f = let tmp_bound_vars = !current_bound_vars in current_bound_vars := []; try let r = f () in List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := tmp_bound_vars; r with x -> List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := tmp_bound_vars; raise x We could also define the following functions instead of cleanup : let in_auto_cleanup = ref false let link v l = if not ( ! in_auto_cleanup ) then Parsing_helper.internal_error " should be in auto_cleanup to use link " ; current_bound_vars : = v : : ( ! current_bound_vars ) ; v.link < - l let auto_cleanup f = let tmp_in_auto_cleanup = ! in_auto_cleanup in in_auto_cleanup : = true ; let tmp_bound_vars = ! current_bound_vars in current_bound_vars : = [ ] ; try let r = f ( ) in List.iter ( fun v - > v.link < - NoLink ) ( ! current_bound_vars ) ; current_bound_vars : = tmp_bound_vars ; in_auto_cleanup : = tmp_in_auto_cleanup ; r with x - > List.iter ( fun v - > v.link < - NoLink ) ( ! current_bound_vars ) ; current_bound_vars : = tmp_bound_vars ; in_auto_cleanup : = tmp_in_auto_cleanup ; raise x Use auto_cleanup ( fun ( ) - > ... ) instead of let tmp_bound_vars = ! current_bound_vars in current_bound_vars : = [ ] ; ... cleanup ( ) ; current_bound_vars : = tmp_bound_vars and of if ! current_bound_vars ! = [ ] then Parsing_helper.internal_error " ... " ; ... cleanup ( ) This would be a better programming style , but this conflicts with the way the function Rules.build_rules_eq is written ... and would probably also slow down a bit the system . let in_auto_cleanup = ref false let link v l = if not (!in_auto_cleanup) then Parsing_helper.internal_error "should be in auto_cleanup to use link"; current_bound_vars := v :: (!current_bound_vars); v.link <- l let auto_cleanup f = let tmp_in_auto_cleanup = !in_auto_cleanup in in_auto_cleanup := true; let tmp_bound_vars = !current_bound_vars in current_bound_vars := []; try let r = f () in List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := tmp_bound_vars; in_auto_cleanup := tmp_in_auto_cleanup; r with x -> List.iter (fun v -> v.link <- NoLink) (!current_bound_vars); current_bound_vars := tmp_bound_vars; in_auto_cleanup := tmp_in_auto_cleanup; raise x Use auto_cleanup (fun () -> ...) instead of let tmp_bound_vars = !current_bound_vars in current_bound_vars := []; ... cleanup(); current_bound_vars := tmp_bound_vars and of if !current_bound_vars != [] then Parsing_helper.internal_error "..."; ... cleanup() This would be a better programming style, but this conflicts with the way the function Rules.build_rules_eq is written... and would probably also slow down a bit the system. *) let new_gen_var t may_fail = let f_cat = if may_fail then General_mayfail_var else General_var in let name = (if !Param.tulafale != 1 then "@gen" else "gen") ^ (if may_fail then "mf" else "") in { f_name = Renamable (new_id ~orig:false name); f_type = [], t; f_cat = f_cat; f_initial_cat = f_cat; f_private = true; f_options = 0 } let rec generalize_vars_not_in vlist = function Var v -> begin if List.memq v vlist then Var v else match v.link with | NoLink -> let v' = FunApp(new_gen_var v.btype v.unfailing, []) in link v (TLink v'); v' | TLink l -> l | _ -> internal_error "Unexpected link in generalize_vars" end | FunApp(f, l) -> FunApp(f, List.map (generalize_vars_not_in vlist) l) let rec generalize_vars_in vlist = function Var v -> begin if not (List.memq v vlist) then Var v else match v.link with NoLink -> let v' = FunApp(new_gen_var v.btype v.unfailing, []) in link v (TLink v'); v' | TLink l -> l | _ -> internal_error "Unexpected link in generalize_vars" end | FunApp(f, l) -> FunApp(f, List.map (generalize_vars_in vlist) l) let rec copy_term = function | FunApp(f,l) -> FunApp(f, List.map copy_term l) | Var v -> match v.link with NoLink -> let r = copy_var v in link v (VLink r); Var r | VLink l -> Var l | _ -> internal_error "Unexpected link in copy_term" let copy_fact = function Pred(chann, t) -> Pred(chann, List.map copy_term t) let copy_constra c = map_constraints copy_term c let copy_rule (hyp,concl,hist,constra) = let tmp_bound = !current_bound_vars in current_bound_vars := []; let r = (List.map copy_fact hyp, copy_fact concl, hist, copy_constra constra) in cleanup(); current_bound_vars := tmp_bound; r let copy_red (left_list, right, side_c) = assert (!current_bound_vars == []); let left_list' = List.map copy_term left_list in let right' = copy_term right in let side_c' = copy_constra side_c in cleanup(); (left_list', right', side_c') Unification exception Unify let rec occur_check v t = match t with Var v' -> begin if v == v' then raise Unify; match v'.link with NoLink -> () | TLink t' -> occur_check v t' | _ -> internal_error "unexpected link in occur_check" end | (FunApp(_,l)) -> List.iter (occur_check v) l let term_string = function FunApp(f,l) -> let name = match f.f_name with Fixed s -> s | Renamable id -> string_of_id id in if l = [] then name else name ^ "(...)" | Var(b) -> string_of_id b.vname let rec unify t1 t2 = Commented out this typing checking test for speed if not ( Param.get_ignore_types ( ) ) then begin if get_term_type t1 ! = get_term_type t2 then Parsing_helper.internal_error ( " Type error in unify : " ^ ( term_string t1 ) ^ " has type " ^ ( get_term_type t1).tname ^ " while " ^ ( term_string t2 ) ^ " has type " ^ ( get_term_type t2).tname ) end ; if not (Param.get_ignore_types()) then begin if get_term_type t1 != get_term_type t2 then Parsing_helper.internal_error ("Type error in unify: " ^ (term_string t1) ^ " has type " ^ (get_term_type t1).tname ^ " while " ^ (term_string t2) ^ " has type " ^ (get_term_type t2).tname) end; *) match (t1,t2) with (Var v, Var v') when v == v' -> () | (Var v, _) -> begin match v.link with | NoLink -> begin match t2 with | Var {link = TLink t2'} -> unify t1 t2' | Var v' when v.unfailing -> link v (TLink t2) | Var v' when v'.unfailing -> link v' (TLink t1) | FunApp (f_symb,_) when f_symb.f_cat = Failure && v.unfailing = false -> raise Unify | Var v' when v'.vname.name = Param.def_var_name -> link v' (TLink t1) | _ -> occur_check v t2; link v (TLink t2) end | TLink t1' -> unify t1' t2 | _ -> internal_error "Unexpected link in unify 1" end | (FunApp(f_symb,_), Var v) -> begin match v.link with NoLink -> if v.unfailing = false && f_symb.f_cat = Failure then raise Unify else begin occur_check v t1; link v (TLink t1) end | TLink t2' -> unify t1 t2' | _ -> internal_error "Unexpected link in unify 2" end | (FunApp(f1, l1), FunApp(f2,l2)) -> if f1 != f2 then raise Unify; List.iter2 unify l1 l2 let unify_facts f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2,t2) -> if chann1 != chann2 then raise Unify; List.iter2 unify t1 t2 let unify_facts_phase f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2,t2) -> if not (is_sub_predicate chann1 chann2) then raise Unify; List.iter2 unify t1 t2 let unify_facts_phase_leq f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2,t2) -> if not (is_sub_predicate chann2 chann1) then raise Unify; List.iter2 unify t1 t2 let rec copy_term2 = function | FunApp(f,l) -> FunApp(f, List.map copy_term2 l) | Var v -> match v.link with | NoLink -> let r = copy_var v in link v (VLink r); Var r | TLink l -> copy_term2 l | VLink r -> Var r | _ -> internal_error "unexpected link in copy_term2" let copy_fact2 = function Pred(chann, t) -> Pred(chann, List.map copy_term2 t) let rec copy_constra2 c = map_constraints copy_term2 c let copy_rule2 (hyp, concl, hist, constra) = let tmp_bound = !current_bound_vars in current_bound_vars := []; let r = (List.map copy_fact2 hyp, copy_fact2 concl, hist, copy_constra2 constra) in cleanup(); current_bound_vars := tmp_bound; r let copy_rule2_no_cleanup (hyp, concl, hist, constra) = (List.map copy_fact2 hyp, copy_fact2 concl, hist, copy_constra2 constra) let copy_ordered_rule2 ord_rule = let rule = copy_rule2 ord_rule.rule in { ord_rule with rule = rule } let copy_occurrence2 = function | None -> None | Some t -> Some (copy_term2 t) let copy_event2 = function Pitypes.QSEvent(b,ord_fun,occ,t) -> Pitypes.QSEvent(b, ord_fun,copy_occurrence2 occ,copy_term2 t) | Pitypes.QSEvent2(t1,t2) -> Pitypes.QSEvent2(copy_term2 t1, copy_term2 t2) | Pitypes.QFact(p,ord_fun,tl) -> Pitypes.QFact(p,ord_fun,List.map copy_term2 tl) | Pitypes.QNeq(t1,t2) -> Pitypes.QNeq(copy_term2 t1, copy_term2 t2) | Pitypes.QEq(t1,t2) -> Pitypes.QEq(copy_term2 t1, copy_term2 t2) | Pitypes.QGeq(t1,t2) -> Pitypes.QGeq(copy_term2 t1, copy_term2 t2) | Pitypes.QIsNat(t) -> Pitypes.QIsNat(copy_term2 t) let rec copy_realquery2 = function Pitypes.Before(el, concl_q) -> Pitypes.Before(List.map copy_event2 el, copy_conclusion_query2 concl_q) and copy_conclusion_query2 = function | Pitypes.QTrue -> Pitypes.QTrue | Pitypes.QFalse -> Pitypes.QFalse | Pitypes.QEvent e -> Pitypes.QEvent(copy_event2 e) | Pitypes.NestedQuery q -> Pitypes.NestedQuery (copy_realquery2 q) | Pitypes.QAnd(concl1,concl2) -> Pitypes.QAnd(copy_conclusion_query2 concl1,copy_conclusion_query2 concl2) | Pitypes.QOr(concl1,concl2) -> Pitypes.QOr(copy_conclusion_query2 concl1,copy_conclusion_query2 concl2) exception NoMatch let rec match_terms t1 t2 = Commented out this typing checking test for speed if not ( Param.get_ignore_types ( ) ) then begin if get_term_type t1 ! = get_term_type t2 then Parsing_helper.internal_error ( " Type error in match_terms : " ^ ( term_string t1 ) ^ " has type " ^ ( get_term_type t1).tname ^ " while " ^ ( term_string t2 ) ^ " has type " ^ ( get_term_type t2).tname ) end ; if not (Param.get_ignore_types()) then begin if get_term_type t1 != get_term_type t2 then Parsing_helper.internal_error ("Type error in match_terms: " ^ (term_string t1) ^ " has type " ^ (get_term_type t1).tname ^ " while " ^ (term_string t2) ^ " has type " ^ (get_term_type t2).tname) end; *) match (t1,t2) with (Var v), t -> begin match v.link with NoLink -> if v.unfailing then link v (TLink t) else begin match t with | Var v' when v'.unfailing -> raise NoMatch | FunApp(f_symb,_) when f_symb.f_cat = Failure -> raise NoMatch | _ -> link v (TLink t) end | TLink t' -> if not (equal_terms t t') then raise NoMatch | _ -> internal_error "Bad link in match_terms" end | (FunApp (f1,l1')), (FunApp (f2,l2')) -> if f1 != f2 then raise NoMatch; List.iter2 match_terms l1' l2' | _,_ -> raise NoMatch let match_facts f1 f2 = match (f1,f2) with Pred(chann1, t1),Pred(chann2, t2) -> if chann1 != chann2 then raise NoMatch; List.iter2 match_terms t1 t2 Same as match_facts except that f1 of phase n can be matched with f2 of phase m with n > = m when they are attacker facts . Used to apply Lemmas . Used to apply Lemmas. *) let match_facts_phase_geq f1 f2 = match f1,f2 with | Pred(p1,t1), Pred(p2, t2) -> if not (is_sub_predicate p1 p2) then raise NoMatch; List.iter2 match_terms t1 t2 let match_facts_phase_leq f1 f2 = match f1,f2 with | Pred(p1,t1), Pred(p2, t2) -> if not (is_sub_predicate p2 p1) then raise NoMatch; List.iter2 match_terms t1 t2 let matchafact finst fgen = assert (!current_bound_vars == []); try match_facts fgen finst; cleanup(); true with NoMatch -> cleanup(); false let rec occurs_test_loop seen_vars v t = match t with Var v' -> begin if List.memq v' (!seen_vars) then false else begin seen_vars := v' :: (!seen_vars); if v == v' then true else match v'.link with NoLink -> false | TLink t' -> occurs_test_loop seen_vars v t' | _ -> internal_error "unexpected link in occur_check" end end | FunApp(_,l) -> List.exists (occurs_test_loop seen_vars v) l let matchafactstrict finst fgen = assert (!current_bound_vars == []); try match_facts fgen finst; if List.exists (fun v -> match v.link with | TLink (Var _) -> false | TLink t -> occurs_test_loop (ref []) v t | _ -> false) (!current_bound_vars) then begin cleanup(); true end else begin cleanup(); false end with NoMatch -> cleanup(); false let rec term_size = function Var _ -> 0 | FunApp(f, l) -> 1 + term_list_size l and term_list_size = function [] -> 0 | a::l -> term_size a + term_list_size l let fact_size = function Pred(_, tl) -> 1 + term_list_size tl let rec replace_f_var vl = function | Var v2 -> Var v2 | FunApp(f2,[]) -> begin try Var (List.assq f2 (!vl)) with Not_found -> if f2.f_cat = General_var then begin let v = new_var ~orig:false (if !Param.tulafale != 1 then "@gen" else "gen") (snd f2.f_type) in vl := (f2, v) :: (!vl); Var v end else if f2.f_cat = General_mayfail_var then begin let v = new_var ~orig:false ~may_fail:true (if !Param.tulafale != 1 then "@genmf" else "genmf") (snd f2.f_type) in vl := (f2, v) :: (!vl); Var v end else FunApp(f2,[]) end | FunApp(f2,l) -> FunApp(f2, List.map (replace_f_var vl) l) let rec rev_assoc v2 = function [] -> Var v2 | ((f,v)::l) -> if v2 == v then FunApp(f,[]) else rev_assoc v2 l let rec follow_link var_case = function Var v -> begin match v.link with TLink t -> follow_link var_case t | NoLink -> var_case v | _ -> Parsing_helper.internal_error "unexpected link in follow_link" end | FunApp(f,l) -> FunApp(f, List.map (follow_link var_case) l) let rec replace_name f t = function Var v -> Var v | FunApp(f',[]) -> if f' == f then t else FunApp(f',[]) | FunApp(f',l') -> FunApp(f', List.map (replace_name f t) l') let rec has_vars = function Var _ -> true | FunApp(f, l) -> List.exists has_vars l let rec get_vars vlist = function Var v -> if not (List.memq v (!vlist)) then vlist := v :: (!vlist) | FunApp(_,l) -> List.iter (get_vars vlist) l let get_vars_constra vlist c = iter_constraints (get_vars vlist) c let get_vars_fact vlist = function Pred(_,l) -> List.iter (get_vars vlist) l let rec get_vars_pat accu = function PatVar b -> b::accu | PatTuple(f,l) -> List.fold_left get_vars_pat accu l | PatEqual t -> accu let rec copy_term3 = function | FunApp(f,l) -> FunApp(f, List.map copy_term3 l) | Var v -> match v.link with NoLink -> Var v | TLink l -> l | _ -> internal_error "unexpected link in copy_term3" let copy_fact3 = function Pred(p,l) -> Pred(p, List.map copy_term3 l) let rec copy_constra3 c = map_constraints copy_term3 c [ copy_term4 ] follows links [ ] recursively , but does not rename variables but does not rename variables *) let rec copy_term4 = function | FunApp(f,l) -> FunApp(f, List.map copy_term4 l) | Var v -> match v.link with NoLink -> Var v | TLink l -> copy_term4 l | _ -> internal_error "unexpected link in copy_term4" let copy_fact4 = function | Pred(p,args) -> Pred(p,List.map copy_term4 args) let copy_constra4 c = map_constraints copy_term4 c let is_var = function Var _ -> true | _ -> false let unsel_set = ref ([] : fact list) let add_unsel f = unsel_set := f :: (!unsel_set) let is_unselectable = function Pred(p,pl) as f -> (p.p_prop land Param.pred_BLOCKING != 0) || (p.p_prop land Param.pred_TUPLE != 0 && p.p_prop land Param.pred_TUPLE_SELECT = 0 && List.for_all is_var pl) || (List.exists (function f' -> try auto_cleanup (fun () -> unify_facts f f'); true with Unify -> false ) (!unsel_set)) let rec reorganize_list l = let rec get_first = function [] -> ([], []) | (a ::l)::l' -> let (firstl, rest) = get_first l' in (a :: firstl, l :: rest) | [] :: _ -> internal_error "unexpected case in reorganize_list" in match l with [] :: _ -> [] | _ -> let (firstl, rest) = get_first l in firstl :: (reorganize_list rest) let fun_app f = function FunApp(f',l) when f == f' -> l | _ -> raise Not_found let reorganize_fun_app f l0 = reorganize_list (List.map (fun_app f) l0) let get_session_id_from_occurrence = function | Var _ -> Parsing_helper.internal_error "The term should be an occurrence name, hence a function application" | FunApp(n,args) -> try let i = List.find (fun t -> get_term_type t == Param.sid_type) args in Some i with Not_found -> None let rec has_choice = function Var _ -> false | FunApp(f,l) -> (f.f_cat == Choice) || (List.exists has_choice l) let rec has_choice_format = function | FVar _ | FAny _ -> false | FFunApp(f,l) -> (f.f_cat == Choice) || (List.exists has_choice_format l) let rec has_choice_pat = function PatVar _ -> false | PatTuple(_,l) -> List.exists has_choice_pat l | PatEqual t -> has_choice t Functions to choose one side let rec choice_in_term n = function (Var _) as t -> t | FunApp(f, [t1; t2]) when f.f_cat == Choice -> choice_in_term n (if n = 1 then t1 else t2) | FunApp(f, l) -> FunApp(f, List.map (choice_in_term n) l) let choice_in_fact n = function | Pred(p,args) -> Pred(p,List.map (choice_in_term n) args) let rec choice_in_pat n = function (PatVar _) as pat -> pat | PatTuple(f,l) -> PatTuple(f, List.map (choice_in_pat n) l) | PatEqual t -> PatEqual (choice_in_term n t) let rec choice_in_proc n = function | Nil -> Nil | Par(p, q) -> Par(choice_in_proc n p, choice_in_proc n q) | Repl(p, occ) -> Repl(choice_in_proc n p, occ) | Restr(f, args, p, occ) -> Restr(f, args, choice_in_proc n p, occ) | Test(t, p, q, occ) -> Test (choice_in_term n t, choice_in_proc n p, choice_in_proc n q, occ) | Input(t, pat, p, occ) -> Input(choice_in_term n t, choice_in_pat n pat, choice_in_proc n p, occ) | Output(t, t', p, occ) -> Output(choice_in_term n t, choice_in_term n t', choice_in_proc n p, occ) | Let(pat, t, p, q, occ) -> Let(choice_in_pat n pat, choice_in_term n t, choice_in_proc n p, choice_in_proc n q, occ) | LetFilter(bl, f, p, q, occ) -> LetFilter(bl, choice_in_fact n f, choice_in_proc n p, choice_in_proc n q, occ) | Event(t, args, p, occ) -> Event(choice_in_term n t, args, choice_in_proc n p, occ) | Insert(t, p, occ) -> Insert(choice_in_term n t, choice_in_proc n p, occ) | Get(pat, t, p, q, occ) -> Get(choice_in_pat n pat, choice_in_term n t, choice_in_proc n p, choice_in_proc n q, occ) | Phase(i, p, occ) -> Phase(i, choice_in_proc n p, occ) | Barrier(i, s, p, occ) -> Barrier(i, s, choice_in_proc n p, occ) | AnnBarrier(i, so, f, f', btl, p, occ) -> AnnBarrier(i, so, f, f', List.map (fun (b, t) -> (b, choice_in_term n t)) btl, choice_in_proc n p, occ) | NamedProcess(s, tl, p) -> NamedProcess(s, List.map (choice_in_term n) tl, choice_in_proc n p) let make_choice t1 t2 = let ty1 = get_term_type t1 and ty2 = get_term_type t2 in if (Param.get_ignore_types()) || (ty1 == ty2) then FunApp(Param.choice_fun ty1, [t1;t2]) else Parsing_helper.internal_error "[Terms.make_choice] This should be the same type" let get_fail_symb = Param.memo_type (fun ty -> let name = "fail-"^ty.tname in { f_name = Fixed name; f_type = [], ty; f_cat = Failure; f_initial_cat = Failure; f_private = false; f_options = 0 }) let get_fail_term ty = FunApp(get_fail_symb ty, []) let fail_bool() = get_fail_term Param.bool_type fail_bool must be recomputed once Param.ignore_types is correctly set Boolean Constants let true_cst = { f_name = Fixed "true"; f_type = [], Param.bool_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } let false_cst = { f_name = Fixed "false"; f_type = [], Param.bool_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } let true_term = FunApp(true_cst, []) let false_term = FunApp(false_cst, []) Integer constants and functions let zero_cst = { f_name = Fixed "0"; f_type = [], Param.nat_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } let zero_term = FunApp(zero_cst,[]) let fail_nat() = get_fail_term Param.nat_type fail_nat must be recomputed once Param.ignore_types is correctly set let succ_fun = { f_name = Fixed "+"; f_type = [Param.nat_type], Param.nat_type; f_cat = Tuple; f_initial_cat = Tuple; f_private = false; f_options = 0 } let rec sum_nat_term t = function | 0 -> t | k -> FunApp(succ_fun,[sum_nat_term t (k-1)]) let generate_nat = sum_nat_term (FunApp(zero_cst,[])) let minus_fun = Param.memo (fun i -> if i <= 0 then Parsing_helper.internal_error "[terms.ml >> minus_fun] Index should be bigger than 0."; let x = new_var_def_term Param.nat_type in let y = FunApp(new_gen_var Param.nat_type false,[]) in let semantics = Red [ [sum_nat_term x i], x, true_constraints; [x], fail_nat(), (constraints_of_neq x (sum_nat_term y i)) ; [fail_nat()], fail_nat(), true_constraints ] in { f_name = Fixed ("- "^(string_of_int i)); f_type = [Param.nat_type], Param.nat_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } ) let is_nat_ref = ref None let is_nat_fun () = match !is_nat_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type in let semantics = Red [ [x], true_term, (constraints_of_is_nat x); [x], false_term, (constraints_of_is_not_nat x); [fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "is_nat"; f_type = [Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in is_nat_ref := Some f; f let greater_ref = ref None let greater_fun () = match !greater_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type and y = new_var_def_term Param.nat_type and u = new_var_def_term ~may_fail:true Param.nat_type in let semantics = Red [ [x;y], true_term, (constraints_of_geq x (FunApp(succ_fun,[y]))); [x;y], false_term, (constraints_of_geq y x); [x;y], fail_bool(), (constraints_of_is_not_nat x); [x;y], fail_bool(), (constraints_of_is_not_nat y); [fail_nat();u], fail_bool(), true_constraints; [x;fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed ">"; f_type = [Param.nat_type;Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in greater_ref := Some f; f let geq_ref = ref None let geq_fun () = match !geq_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type and y = new_var_def_term Param.nat_type and u = new_var_def_term ~may_fail:true Param.nat_type in let semantics = Red [ [x;y], true_term, (constraints_of_geq x y); [x;y], false_term, (constraints_of_geq y (FunApp(succ_fun,[x]))); [x;y], fail_bool(), (constraints_of_is_not_nat x); [x;y], fail_bool(), (constraints_of_is_not_nat y); [fail_nat();u], fail_bool(), true_constraints; [x;fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed ">="; f_type = [Param.nat_type;Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in geq_ref := Some f; f let less_ref = ref None let less_fun () = match !less_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type and y = new_var_def_term Param.nat_type and u = new_var_def_term ~may_fail:true Param.nat_type in let semantics = Red [ [y;x], true_term, (constraints_of_geq x (FunApp(succ_fun,[y]))); [y;x], false_term, (constraints_of_geq y x); [y;x], fail_bool(), (constraints_of_is_not_nat x); [y;x], fail_bool(), (constraints_of_is_not_nat y); [fail_nat();u], fail_bool(), true_constraints; [x;fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "<"; f_type = [Param.nat_type;Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in less_ref := Some f; f let leq_ref = ref None let leq_fun () = match !leq_ref with | Some f -> f | None -> let x = new_var_def_term Param.nat_type and y = new_var_def_term Param.nat_type and u = new_var_def_term ~may_fail:true Param.nat_type in let semantics = Red [ [y;x], true_term, (constraints_of_geq x y); [y;x], false_term, (constraints_of_geq y (FunApp(succ_fun,[x]))); [y;x], fail_bool(), (constraints_of_is_not_nat x); [y;x], fail_bool(), (constraints_of_is_not_nat y); [fail_nat();u], fail_bool(), true_constraints; [x;fail_nat()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "<="; f_type = [Param.nat_type;Param.nat_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in leq_ref := Some f; f let rec is_syntactic_natural_number = function | FunApp(f,[]) when f == zero_cst -> true | FunApp(f,[t]) when f == succ_fun -> is_syntactic_natural_number t | _ -> false let is_true_ref = ref None let is_true_fun() = match !is_true_ref with Some f -> f | None -> let x = new_var_def_term Param.bool_type in let semantics = Red [ [true_term], true_term, true_constraints; [x], fail_bool(), (constraints_of_neq x true_term); [fail_bool()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "is-true"; f_type = [Param.bool_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in is_true_ref := Some f; f let equal_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and y = new_var_def_term ty and u = new_var_def_term ~may_fail:true ty and fail = get_fail_term ty in let semantics = Red [ [x;x], true_term, true_constraints; [x;y], false_term, (constraints_of_neq x y); [fail;u], fail_bool(), true_constraints; [x;fail], fail_bool(), true_constraints ] in { f_name = Fixed "="; f_type = [ty;ty], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 }) let diff_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and y = new_var_def_term ty and u = new_var_def_term ~may_fail:true ty and fail = get_fail_term ty in let semantics = Red [ [x;x], false_term, true_constraints; [x;y], true_term, (constraints_of_neq x y); [fail;u], fail_bool(), true_constraints; [x;fail], fail_bool(), true_constraints ] in { f_name = Fixed "<>"; f_type = [ty;ty], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 }) let and_ref = ref None let and_fun() = match !and_ref with Some f ->f | None -> let u = new_var_def_term ~may_fail:true Param.bool_type and x = new_var_def_term Param.bool_type in let semantics = Red [ When the first conjunct is " false " , the second conjunct is not evaluated , so the conjunction is " false " even if the second conjunct fails so the conjunction is "false" even if the second conjunct fails *) [true_term; u], u, true_constraints; [x;u], false_term, (constraints_of_neq x true_term); [fail_bool(); u], fail_bool(), true_constraints ] in let f = { f_name = Fixed "&&"; f_type = [Param.bool_type; Param.bool_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in and_ref := Some f; f let or_ref = ref None let or_fun() = match !or_ref with Some f -> f | None -> let u = new_var_def_term ~may_fail:true Param.bool_type and x = new_var_def_term Param.bool_type in let semantics = Red [ When the first disjunct is " true " , the second disjunct is not evaluated , so the disjunction is " true " even if the second disjunct fails so the disjunction is "true" even if the second disjunct fails *) [true_term; u], true_term, true_constraints; [x;u], u, (constraints_of_neq x true_term); [fail_bool(); u], fail_bool(), true_constraints ] in let f = { f_name = Fixed "||"; f_type = [Param.bool_type; Param.bool_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in or_ref := Some f; f let not_ref = ref None let not_fun() = match !not_ref with Some f -> f | None -> let x = new_var_def_term Param.bool_type in let semantics = Red [ [true_term], false_term, true_constraints; [x], true_term, (constraints_of_neq x true_term); [fail_bool()], fail_bool(), true_constraints ] in let f = { f_name = Fixed "not"; f_type = [Param.bool_type], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } in not_ref := Some f; f let make_not a = let not_fun = not_fun() in match a with FunApp(f, [a']) when f == not_fun -> a' | _ -> FunApp(not_fun, [a]) [ and_list l ] returns the conjunction of the terms in [ l ] let rec and_list = function [] -> true_term | [a] -> a | a::l -> FunApp(and_fun(), [a; and_list l]) let rec or_not_list = function [] -> false_term | [a] -> make_not a | a::l -> FunApp(or_fun(), [make_not a; or_not_list l]) let glet_constant_fun = Param.memo_type (fun ty -> { f_name = Fixed "caught-fail"; f_type = [],ty; f_cat = Tuple; f_initial_cat = Tuple; f_private = true; f_options = 0 }) let glet_constant_never_fail_fun = Param.memo_type (fun ty -> { f_name = Fixed "never-fail"; f_type = [],ty; f_cat = Tuple; f_initial_cat = Tuple; f_private = true; f_options = 0 }) let glet_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and fail = get_fail_term ty and c_o = glet_constant_fun ty in let semantics = Red [ [x], x, true_constraints; [fail], FunApp(c_o,[]), true_constraints ] in { f_name = Fixed "catch-fail"; f_type = [ty], ty; f_cat = semantics; f_initial_cat = semantics; f_private = true; f_options = 0 }) let success_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and fail = get_fail_term ty in let semantics = Red [ [x], true_term, true_constraints; [fail], false_term, true_constraints ] in { f_name = Fixed "success?"; f_type = [ty], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = false; f_options = 0 } ) let not_caught_fail_fun = Param.memo_type (fun ty -> let x = new_var_def_term ty and c_o = glet_constant_fun ty and fail = get_fail_term ty in let semantics = Red [ [x], true_term, (constraints_of_neq x (FunApp(c_o,[]))); [FunApp(c_o,[])], false_term, true_constraints; [fail], fail_bool(), true_constraints ] in { f_name = Fixed "not-caught-fail"; f_type = [ty], Param.bool_type; f_cat = semantics; f_initial_cat = semantics; f_private = true; f_options = 0 } ) let gtest_fun = Param.memo_type (fun ty -> let u = new_var_def_term ~may_fail:true ty and v = new_var_def_term ~may_fail:true ty and x = new_var_def_term Param.bool_type and fail = get_fail_term ty in let semantics = Red [ [true_term;u;v], u, true_constraints; [x;u;v], v, (constraints_of_neq x true_term); [fail_bool();u;v], fail, true_constraints ] in { f_name = Fixed "if-then-else"; f_type = [Param.bool_type;ty;ty], ty; f_cat = semantics; f_initial_cat = semantics; f_private = true; f_options = 0 }) let complete_semantics_constructors type_arg type_result = let var_fail_list = List.map (new_var_def_term ~may_fail:true) type_arg and var_list = List.map new_var_def_term type_arg and fail_list = List.map get_fail_term type_arg and fail_result = get_fail_term type_result in let rec sub_complete var_list var_fail_list fail_list = match var_list, var_fail_list, fail_list with | [], [], [] -> [] | x::var_l, _::var_fl, fail::fail_l -> let prev_list = sub_complete var_l var_fl fail_l in (fail::var_fl)::(List.map (fun l -> x::l) prev_list) | _,_,_ -> internal_error "The three lists should have the same size" in List.map (fun l -> l, fail_result,true_constraints) (sub_complete var_list var_fail_list fail_list) let red_rules_constructor f = let vars1 = var_gen (fst f.f_type) in (vars1, FunApp(f, vars1),true_constraints) :: (complete_semantics_constructors (fst f.f_type) (snd f.f_type)) let red_rules_fun f = match f.f_cat with Eq red_rules -> (red_rules_constructor f) @ (List.map (fun (lhs,rhs) -> (lhs, rhs, true_constraints)) red_rules) | Red red_rules -> red_rules | Name _ -> [([],FunApp(f,[]),true_constraints)] This is ok because this function is called either not with names ( calls from Pitransl / Pitranslweak and from TermsEq.close_term_destr_eq when it is used on clauses that define LetFilter predicates ) or only with names from processes ( calls from TermsEq.close_term_destr_eq that come from Simplify ) . We never have name function symbols here . either not with names (calls from Pitransl/Pitranslweak and from TermsEq.close_term_destr_eq when it is used on clauses that define LetFilter predicates) or only with names from processes (calls from TermsEq.close_term_destr_eq that come from Simplify). We never have name function symbols here. *) | _ -> red_rules_constructor f let get_function_name f = match f.f_cat, f.f_name with Tuple, Fixed "" -> let arity = List.length (fst f.f_type) in if (arity = 0) || (Param.get_ignore_types()) then (string_of_int arity) ^ "-tuple" else (tl_to_string "-" (fst f.f_type)) ^ "-tuple" | _, Fixed s -> s | _ -> Parsing_helper.internal_error "get_function_name expects function with fixed name" let projection_fun = Param.memo (fun (f_symb,i) -> if f_symb.f_cat <> Tuple then internal_error "[Terms.projection_fun] This should be a tuple"; if f_symb == succ_fun then minus_fun 1 else let type_list = fst f_symb.f_type in let type_result = snd f_symb.f_type in let var_list = var_gen type_list and gen_var_list = List.map (fun ty -> FunApp(new_gen_var ty false,[])) type_list and x = new_var_def_term type_result and ieme_type = List.nth type_list (i-1) in let fail = get_fail_term type_result and fail' = get_fail_term ieme_type in let semantics = Red [ [FunApp(f_symb,var_list)], List.nth var_list (i-1), true_constraints; [x], fail', (constraints_of_neq x (FunApp(f_symb,gen_var_list))); [fail], fail', true_constraints ] in let name = Printf.sprintf "%d-proj-%s" i (get_function_name f_symb) in { f_name = Fixed name; f_type = [type_result], ieme_type; f_cat = semantics; f_initial_cat = semantics; f_private = f_symb.f_private; f_options = 0 }) let get_all_projection_fun tuple_symb = let rec sub_get_proj n l = match l with | [] -> [] | _::q -> (projection_fun (tuple_symb,n))::(sub_get_proj (n+1) q) in sub_get_proj 1 (fst tuple_symb.f_type) let rec clauses_for_function clauses_for_red_rules f = if (not f.f_private) && (not ((f.f_options land Param.fun_TYPECONVERTER != 0) && (Param.get_ignore_types()))) then match f.f_cat with Eq red_rules -> let vars1 = var_gen (fst f.f_type) in let red_rules = (vars1, FunApp(f, vars1),true_constraints) :: (List.map (fun (lhs,rhs) -> (lhs, rhs, true_constraints)) red_rules) in clauses_for_red_rules f red_rules | Red red_rules -> clauses_for_red_rules f red_rules | Tuple -> let vars1 = var_gen (fst f.f_type) in clauses_for_red_rules f [(vars1, FunApp(f, vars1),true_constraints)]; List.iter (clauses_for_function clauses_for_red_rules) (get_all_projection_fun f) | _ -> () let new_name_fun = Param.memo_type (fun t -> let cat = Name { prev_inputs = None; prev_inputs_meaning = [MAttSid] } in let name = "new-name" ^ (Param.get_type_suffix t) in { f_name = Renamable (new_id name); f_type = [Param.sid_type], t; f_cat = cat; f_initial_cat = cat; f_private = false; f_options = 0 }) let occ_count = ref 0 let reset_occurrence () = occ_count := 0 let new_occurrence ?(precise=false) () = incr occ_count; { occ = !occ_count; precise = precise } let rec put_lets p = function [] -> p | (v,t)::l -> put_lets (Let(PatVar v,t,p,Nil,new_occurrence())) l let create_name_internal name ty is_private = let cat = Name { prev_inputs = None; prev_inputs_meaning = [] } in { f_name = name; f_type = ty; f_cat = cat; f_initial_cat = cat; f_private = is_private; f_options = 0 } let create_name ?(allow_rename=true) ?orig s ty is_private = let name = if allow_rename then Renamable (new_id ?orig s) else Fixed s in create_name_internal name ty is_private let copy_name ?orig n arg_type = let name = match n.f_name with Fixed s -> Parsing_helper.internal_error "Should only copy names that can be renamed" | Renamable id -> Renamable (copy_id ?orig id) in create_name_internal name (arg_type, snd n.f_type) n.f_private exception True_inequality exception False_inequality let generate_destructor_with_side_cond prev_args lht_list rht ext = let rec remove_uni_fail_var term_list uni_term_list = match term_list, uni_term_list with | [],[] -> [],[] | [],_ | _,[] -> internal_error "The two lists should have the same length" | t::q, Var(v)::uq when v.unfailing -> begin match v.link with | NoLink -> link v (TLink t); remove_uni_fail_var q uq | TLink t' -> let (list_left,list_right) = remove_uni_fail_var q uq in (t::list_left,t'::list_right) | _ -> internal_error "Unexpected link" end | t::q,ut::uq -> let (list_left,list_right) = remove_uni_fail_var q uq in (t::list_left,ut::list_right) in When [ prev_args = ( a1, ... ,an ) ] is the list of arguments of the previous rewrite rules , [ generalize_prev_args ] builds returns a list of pairs [ ( li , ' ) ] representing the inequality [ \wedge_i li < > li ' ] equivalent to the inequality [ \wedge_i forall ( variables in ai ) , lht_list < > ai ] . The returned inequalities do not contain general may - fail variables ( thanks to remove_uni_fail_var ) , but may contain may - fail variables . These variables will be removed in the next steps by case distinctions . rewrite rules, [generalize_prev_args] builds returns a list of pairs [(li,li')] representing the inequality [\wedge_i li <> li'] equivalent to the inequality [\wedge_i forall (variables in ai), lht_list <> ai]. The returned inequalities do not contain general may-fail variables (thanks to remove_uni_fail_var), but may contain may-fail variables. These variables will be removed in the next steps by case distinctions. *) let rec generalize_prev_args prev_args = match prev_args with | [] -> [] | term_list::q -> let vars = ref [] in List.iter (get_vars vars) term_list; let message_var_list = List.filter (fun v -> not (v.unfailing)) !vars in the variables let term_list' = auto_cleanup (fun () -> List.map (generalize_vars_in message_var_list) term_list ) in let (lterms_left,lterms_right) = auto_cleanup (fun () -> remove_uni_fail_var lht_list term_list' ) in (lterms_left,lterms_right)::(generalize_prev_args q) in let rec get_may_fail_vars varsl term = match term with | Var(v) -> begin match v.link with | NoLink -> if v.unfailing && not (List.memq v (!varsl)) then varsl := v :: (!varsl) | TLink(t) -> get_may_fail_vars varsl t | _ -> internal_error "Unexpected link" end | FunApp(_,l) -> List.iter (get_may_fail_vars varsl) l in let rec simplify_one_neq term_left term_right = match term_left,term_right with | Var(vl),Var(vr) when vl==vr -> raise False_inequality | FunApp(f,_), FunApp(f',_) when f.f_cat = Failure && f'.f_cat = Failure -> raise False_inequality | Var({link = TLink tl}),tr -> simplify_one_neq tl tr | tl, Var({link = TLink tr}) -> simplify_one_neq tl tr | Var(v),FunApp(f,_) when v.unfailing = false && f.f_cat = Failure -> raise True_inequality | FunApp(f,_), Var(v) when v.unfailing = false && f.f_cat = Failure -> raise True_inequality | FunApp(f,_),FunApp(f',_) when f'.f_cat = Failure -> raise True_inequality | FunApp(f,_),FunApp(f',_) when f.f_cat = Failure -> raise True_inequality | _,_ -> term_left,term_right in let simplify_neq lterm_left lterm_right = List.fold_left2 (fun (neql,neqr) term_left term_right -> try let term_left',term_right' = simplify_one_neq term_left term_right in (term_left'::neql),(term_right'::neqr) with | False_inequality -> (neql,neqr) ) ([],[]) lterm_left lterm_right in let destructors = ref [] in let rec remove_may_fail_term_neq list_neq = let list_neq' = List.fold_left (fun lneq (lterm_left,lterm_right) -> try let (lterm_left', lterm_right') = simplify_neq lterm_left lterm_right in if lterm_left' = [] then raise False_inequality; (lterm_left', lterm_right')::lneq with True_inequality -> lneq ) [] list_neq in let vars = ref [] in List.iter (fun (lleft,lright) -> List.iter (get_may_fail_vars vars) lleft; List.iter (get_may_fail_vars vars) lright ) list_neq'; let may_fail_var_list = !vars in if may_fail_var_list = [] then auto_cleanup (fun () -> let rht' = copy_term2 rht and lht' = List.map copy_term2 lht_list and side_neq = List.map (fun (left_l, right_l) -> let left_l' = List.map copy_term2 left_l and right_l' = List.map copy_term2 right_l in let type_list = List.map get_term_type left_l' in let tuple_symb = get_tuple_fun type_list in [FunApp(tuple_symb,left_l'),FunApp(tuple_symb,right_l')] ) list_neq' in let side_c = { neq = side_neq; is_nat = []; is_not_nat = []; geq = [] } in let var_list_rht = ref [] in get_vars var_list_rht rht'; if not (List.for_all (fun v -> List.exists (occurs_var v) lht') (!var_list_rht)) then Parsing_helper.input_error "All variables of the right-hand side of a \"reduc\" definition\nshould also occur in the left-hand side" ext; destructors := (lht',rht',side_c)::!destructors ) else begin let mf_var = List.hd may_fail_var_list in auto_cleanup (fun () -> let fail = get_fail_term mf_var.btype in link mf_var (TLink fail); try remove_may_fail_term_neq list_neq' with | False_inequality -> () ); auto_cleanup (fun () -> let x = new_var_def_term mf_var.btype in link mf_var (TLink x); try remove_may_fail_term_neq list_neq' with | False_inequality -> () ) end in let list_side_c = generalize_prev_args prev_args in remove_may_fail_term_neq list_side_c; !destructors let rec fact_list_of_combined_conclusion pl args = match pl with | [] -> if args <> [] then Parsing_helper.internal_error "[reduction_helper.ml >> fact_list_of_combined_conclusion] Conclusion does not match the query."; [] | p :: q_pl -> let nb_args = List.length p.p_type in let args_p, rest_args = split_list nb_args args in Pred(p,args_p)::(fact_list_of_combined_conclusion q_pl rest_args) let fact_list_of_conclusion = function | Pred({ p_info = [Combined pl]; _ }, args) -> fact_list_of_combined_conclusion pl args | pred -> [pred]
df81cdc5b0895d2490b712ac48d108a38932d68567bdb525c8fb406ceafe7663
kerneis/cpc
myocamlbuild.ml
open Ocamlbuild_plugin ;; open Command ;; open Pathname ;; open Outcome ;; let find_modules builder mllib = let dirs = include_dirs_of (dirname mllib) in let modules = string_list_of_file mllib in let make_candidates m = List.map (expand_module dirs m) [["cmi"]; ["cmx"]; ["mli"; "inferred.mli"]] in let dependencies = List.flatten (List.map make_candidates modules) in let build_result = builder dependencies in let built_files = List.filter_opt (function Good file -> Some (!Options.build_dir/file) | Bad _ -> None) build_result in String.concat " " built_files ;; let cil_version = try Printf.sprintf "(version %s)" (Sys.getenv "CIL_VERSION") with Not_found -> "" ;; dispatch begin function | After_rules -> (* the main CIL library *) ocaml_lib "src/cil"; (* residual reliance on make to build some OCaml source files *) let make target = let basename = Pathname.basename target in rule ("make " ^ target) ~dep: "Makefile" ~prod: basename (fun _ _ -> Cmd (S [A "make"; A "-C"; P ".."; P ("_build" / target)])) in make "feature_config.ml"; make "machdep.ml"; (* Build an list of files to install with ocamlfind *) rule "%.mllib -> %.libfiles" ~dep: "%.mllib" ~prod: "%.libfiles" (fun env builder -> Echo ( [find_modules builder (env "%.mllib")], (env "%.libfiles"))); (* Flags for ocamldoc *) flag ["ocaml";"doc"] (S [ A "-stars"; A "-hide"; A "Pervasives"; A "-t" ; A (Printf.sprintf "CIL API Documentation %s" cil_version); ]); | _ -> () end ;;
null
https://raw.githubusercontent.com/kerneis/cpc/0ca695d25e58dadbd92639162338a06a517875d9/myocamlbuild.ml
ocaml
the main CIL library residual reliance on make to build some OCaml source files Build an list of files to install with ocamlfind Flags for ocamldoc
open Ocamlbuild_plugin ;; open Command ;; open Pathname ;; open Outcome ;; let find_modules builder mllib = let dirs = include_dirs_of (dirname mllib) in let modules = string_list_of_file mllib in let make_candidates m = List.map (expand_module dirs m) [["cmi"]; ["cmx"]; ["mli"; "inferred.mli"]] in let dependencies = List.flatten (List.map make_candidates modules) in let build_result = builder dependencies in let built_files = List.filter_opt (function Good file -> Some (!Options.build_dir/file) | Bad _ -> None) build_result in String.concat " " built_files ;; let cil_version = try Printf.sprintf "(version %s)" (Sys.getenv "CIL_VERSION") with Not_found -> "" ;; dispatch begin function | After_rules -> ocaml_lib "src/cil"; let make target = let basename = Pathname.basename target in rule ("make " ^ target) ~dep: "Makefile" ~prod: basename (fun _ _ -> Cmd (S [A "make"; A "-C"; P ".."; P ("_build" / target)])) in make "feature_config.ml"; make "machdep.ml"; rule "%.mllib -> %.libfiles" ~dep: "%.mllib" ~prod: "%.libfiles" (fun env builder -> Echo ( [find_modules builder (env "%.mllib")], (env "%.libfiles"))); flag ["ocaml";"doc"] (S [ A "-stars"; A "-hide"; A "Pervasives"; A "-t" ; A (Printf.sprintf "CIL API Documentation %s" cil_version); ]); | _ -> () end ;;
cd36fb71d728aff71f2f72b15a6348eb8d0e06410299353f44c941c8c75b61ab
Opetushallitus/ataru
tutu_payment_subs.cljs
(ns ataru.virkailija.application.tutu-payment.tutu-payment-subs (:require [cljs-time.core :as time] [cljs-time.format :as format] [clojure.string :as string] [re-frame.core :as re-frame])) (re-frame.core/reg-sub :tutu-payment/tutu-form? (fn [_ [_ key]] (let [tutu-forms (string/split (aget js/config "tutu-payment-form-keys") #",")] (boolean (and (not-empty tutu-forms) (some #(= key %) tutu-forms)))))) (re-frame.core/reg-sub :tutu-payment/show-review-ui? (fn [db _] (let [current-form (get-in db [:application :selected-application-and-form :form :key]) tutu-forms (string/split (aget js/config "tutu-payment-form-keys") #",")] (boolean (and (not-empty tutu-forms) (some #(= current-form %) tutu-forms)))))) (re-frame.core/reg-sub :tutu-payment/tutu-form-selected? (fn [db _] (let [selected-form (get-in db [:application :selected-form-key]) tutu-forms (string/split (aget js/config "tutu-payment-form-keys") #",")] (boolean (and (not-empty tutu-forms) (some #(= selected-form %) tutu-forms)))))) (re-frame/reg-sub :tutu-payment/note-input (fn [db [_ application-key]] (or (get-in db [:tutu-payment :inputs application-key :note]) ""))) (re-frame/reg-sub :tutu-payment/duedate-input (fn [db [_ application-key]] (or (get-in db [:tutu-payment :inputs application-key :due_date]) (get-in db [:tutu-payment :applications application-key :decision :due_date]) (let [date (time/from-now (time/days 14))] (format/unparse (format/formatters :date) date))))) (re-frame/reg-sub :tutu-payment/amount-input (fn [db [_ application-key]] (or (get-in db [:tutu-payment :inputs application-key :amount]) (get-in db [:tutu-payment :applications application-key :decision :amount]) ""))) (re-frame/reg-sub :tutu-payment/inputs-filled? (fn [[_ application-key]] [(re-frame/subscribe [:state-query [:tutu-payment :inputs application-key]]) (re-frame/subscribe [:state-query [:tutu-payment :applications application-key :decision :amount]]) (re-frame/subscribe [:tutu-payment/duedate-input])]) (fn [[{:keys [note amount]} decision-amount due_date]] (let [amount (or amount decision-amount)] (and (string? amount) (some? (re-matches #"\d{1,5}([.]\d{1,2})?" amount)) (string? note) (not (-> note string/trim string/blank?)) (some? due_date))))) (re-frame/reg-sub :tutu-payment/payments (fn [db [_ application-key]] (get-in db [:tutu-payment :applications application-key])))
null
https://raw.githubusercontent.com/Opetushallitus/ataru/6483ad9d7045b7c7244b83a4483189784db07b79/src/cljs/ataru/virkailija/application/tutu_payment/tutu_payment_subs.cljs
clojure
(ns ataru.virkailija.application.tutu-payment.tutu-payment-subs (:require [cljs-time.core :as time] [cljs-time.format :as format] [clojure.string :as string] [re-frame.core :as re-frame])) (re-frame.core/reg-sub :tutu-payment/tutu-form? (fn [_ [_ key]] (let [tutu-forms (string/split (aget js/config "tutu-payment-form-keys") #",")] (boolean (and (not-empty tutu-forms) (some #(= key %) tutu-forms)))))) (re-frame.core/reg-sub :tutu-payment/show-review-ui? (fn [db _] (let [current-form (get-in db [:application :selected-application-and-form :form :key]) tutu-forms (string/split (aget js/config "tutu-payment-form-keys") #",")] (boolean (and (not-empty tutu-forms) (some #(= current-form %) tutu-forms)))))) (re-frame.core/reg-sub :tutu-payment/tutu-form-selected? (fn [db _] (let [selected-form (get-in db [:application :selected-form-key]) tutu-forms (string/split (aget js/config "tutu-payment-form-keys") #",")] (boolean (and (not-empty tutu-forms) (some #(= selected-form %) tutu-forms)))))) (re-frame/reg-sub :tutu-payment/note-input (fn [db [_ application-key]] (or (get-in db [:tutu-payment :inputs application-key :note]) ""))) (re-frame/reg-sub :tutu-payment/duedate-input (fn [db [_ application-key]] (or (get-in db [:tutu-payment :inputs application-key :due_date]) (get-in db [:tutu-payment :applications application-key :decision :due_date]) (let [date (time/from-now (time/days 14))] (format/unparse (format/formatters :date) date))))) (re-frame/reg-sub :tutu-payment/amount-input (fn [db [_ application-key]] (or (get-in db [:tutu-payment :inputs application-key :amount]) (get-in db [:tutu-payment :applications application-key :decision :amount]) ""))) (re-frame/reg-sub :tutu-payment/inputs-filled? (fn [[_ application-key]] [(re-frame/subscribe [:state-query [:tutu-payment :inputs application-key]]) (re-frame/subscribe [:state-query [:tutu-payment :applications application-key :decision :amount]]) (re-frame/subscribe [:tutu-payment/duedate-input])]) (fn [[{:keys [note amount]} decision-amount due_date]] (let [amount (or amount decision-amount)] (and (string? amount) (some? (re-matches #"\d{1,5}([.]\d{1,2})?" amount)) (string? note) (not (-> note string/trim string/blank?)) (some? due_date))))) (re-frame/reg-sub :tutu-payment/payments (fn [db [_ application-key]] (get-in db [:tutu-payment :applications application-key])))
5c12630e88643874ea1ad79d73627852c29f0ff2e173e80a5005bfe9fb2eb2b8
jaspervdj/redis-simple
Simple.hs
| This module is meant to make working with redis in Haskell more simple . It -- is a small layer above the full-blown @redis@ package. -- -- It only supports a small subset of the redis features. -- # LANGUAGE OverloadedStrings , module Database.Redis.Simple ( -- * Type for keys Key (..) -- * Working with simple key-value pairs , itemGet , itemExists , itemSet , itemDelete -- * Working with sets , setAdd , setRemove , setContains , setFindAll -- * Working with lists , listRightPush , listIndex ) where import Control.Applicative ((<$>)) import Data.Maybe (catMaybes) import Data.Monoid (Monoid) import Data.ByteString (ByteString) import GHC.Exts (IsString) import Data.Binary (Binary, encode, decode) import Database.Redis.Redis -- | Type for a key in the key-value store -- newtype Key = Key {unKey :: ByteString} deriving (Show, Eq, Ord, IsString, Monoid, Binary) -- | Gets an item from the database -- itemGet :: Binary a => Redis -- ^ Redis handle -> Key -- ^ Key of the value to get -> IO (Maybe a) -- ^ Resulting value itemGet redis (Key key) = do reply <- get redis key return $ case reply of RBulk (Just r) -> Just $ decode r _ -> Nothing -- | Checks if an item with a given key exists -- itemExists :: Redis -- ^ Redis handle -> Key -- ^ Key to test -> IO Bool -- ^ If the key exists itemExists redis (Key key) = do reply <- exists redis key return $ case reply of RInt 1 -> True _ -> False -- | Set an item in the database -- itemSet :: Binary a => Redis -- ^ Redis handle -> Key -- ^ Key -> a -- ^ Value -> IO () -- ^ No result itemSet redis (Key key) item = do _ <- set redis key (encode item) return () -- | Delete an item in the database -- itemDelete :: Redis -- ^ Redis handle -> Key -- ^ Key -> IO () -- ^ No result itemDelete redis (Key key) = do _ <- del redis key return () -- | Add an item to a redis set -- setAdd :: Binary a => Redis -- ^ Redis handle -> Key -- ^ Key of the set -> a -- ^ Item to add to the set -> IO () -- ^ No result setAdd redis (Key s) m = do _ <- sadd redis s $ encode m return () -- | Remove an item from a redis set -- setRemove :: Binary a => Redis -- ^ Redis handle -> Key -- ^ Key of the set -> a -- ^ Item to remove from the set -> IO () -- ^ No result setRemove redis (Key s) m = do _ <- srem redis s $ encode m return () -- | Check if a set contains a certain item -- setContains :: Binary a => Redis -- ^ Redis handle -> Key -- ^ Key of the set -> a -- ^ Item to check for -> IO Bool -- ^ If the item is present in the set setContains redis (Key s) m = do reply <- sismember redis s $ encode m return $ case reply of RInt 1 -> True _ -> False -- | Get all items from a set -- setFindAll :: Binary a => Redis -- ^ Redis handle -> Key -- ^ Key of the set -> IO [a] -- ^ All items in the set setFindAll redis (Key s) = do reply <- smembers redis s case reply of RMulti (Just replies) -> return $ catMaybes $ flip map replies $ \r -> case r of RBulk i -> decode <$> i _ -> Nothing _ -> return [] -- | Right push an item to a redis list -- listRightPush :: Binary a => Redis -- ^ Redis handle -> Key -- ^ Key of the list -> a -- ^ Item to push to the list -> IO () -- ^ No result listRightPush redis (Key s) m = do _ <- rpush redis s $ encode m return () listIndex :: Binary a => Redis -- ^ Redis handle -> Key -- ^ Key of the list -> Int -- ^ Index -> IO (Maybe a) -- ^ Resulting value listIndex redis (Key key) idx = do reply <- lindex redis key idx return $ case reply of RBulk (Just r) -> Just $ decode r _ -> Nothing
null
https://raw.githubusercontent.com/jaspervdj/redis-simple/cf5fd568b5daa70c64b6be63fa073895c0146c1f/Database/Redis/Simple.hs
haskell
is a small layer above the full-blown @redis@ package. It only supports a small subset of the redis features. * Type for keys * Working with simple key-value pairs * Working with sets * Working with lists | Type for a key in the key-value store | Gets an item from the database ^ Redis handle ^ Key of the value to get ^ Resulting value | Checks if an item with a given key exists ^ Redis handle ^ Key to test ^ If the key exists | Set an item in the database ^ Redis handle ^ Key ^ Value ^ No result | Delete an item in the database ^ Redis handle ^ Key ^ No result | Add an item to a redis set ^ Redis handle ^ Key of the set ^ Item to add to the set ^ No result | Remove an item from a redis set ^ Redis handle ^ Key of the set ^ Item to remove from the set ^ No result | Check if a set contains a certain item ^ Redis handle ^ Key of the set ^ Item to check for ^ If the item is present in the set | Get all items from a set ^ Redis handle ^ Key of the set ^ All items in the set | Right push an item to a redis list ^ Redis handle ^ Key of the list ^ Item to push to the list ^ No result ^ Redis handle ^ Key of the list ^ Index ^ Resulting value
| This module is meant to make working with redis in Haskell more simple . It # LANGUAGE OverloadedStrings , module Database.Redis.Simple Key (..) , itemGet , itemExists , itemSet , itemDelete , setAdd , setRemove , setContains , setFindAll , listRightPush , listIndex ) where import Control.Applicative ((<$>)) import Data.Maybe (catMaybes) import Data.Monoid (Monoid) import Data.ByteString (ByteString) import GHC.Exts (IsString) import Data.Binary (Binary, encode, decode) import Database.Redis.Redis newtype Key = Key {unKey :: ByteString} deriving (Show, Eq, Ord, IsString, Monoid, Binary) itemGet :: Binary a itemGet redis (Key key) = do reply <- get redis key return $ case reply of RBulk (Just r) -> Just $ decode r _ -> Nothing itemExists redis (Key key) = do reply <- exists redis key return $ case reply of RInt 1 -> True _ -> False itemSet :: Binary a itemSet redis (Key key) item = do _ <- set redis key (encode item) return () itemDelete redis (Key key) = do _ <- del redis key return () setAdd :: Binary a setAdd redis (Key s) m = do _ <- sadd redis s $ encode m return () setRemove :: Binary a setRemove redis (Key s) m = do _ <- srem redis s $ encode m return () setContains :: Binary a setContains redis (Key s) m = do reply <- sismember redis s $ encode m return $ case reply of RInt 1 -> True _ -> False setFindAll :: Binary a setFindAll redis (Key s) = do reply <- smembers redis s case reply of RMulti (Just replies) -> return $ catMaybes $ flip map replies $ \r -> case r of RBulk i -> decode <$> i _ -> Nothing _ -> return [] listRightPush :: Binary a listRightPush redis (Key s) m = do _ <- rpush redis s $ encode m return () listIndex :: Binary a listIndex redis (Key key) idx = do reply <- lindex redis key idx return $ case reply of RBulk (Just r) -> Just $ decode r _ -> Nothing
326e40771b757155ae9eaeb87d65a0eaa2e2629918bc23a145a2456d2e3910f7
nutanix/papiea-clj
core_test.clj
(ns papiea.core-test (:require [clojure.test :refer :all]))
null
https://raw.githubusercontent.com/nutanix/papiea-clj/dd842703cf034d93b8651542892c7bd4ac204e29/test/papiea/core_test.clj
clojure
(ns papiea.core-test (:require [clojure.test :refer :all]))
4b77f6250a6146eca05d7ddd9f2bd89c6b4d796db6809d0fd5e3ac42b2a1bbe6
diffusionkinetics/open
Run.hs
| Running models Before invoking ` runStan ` , you must specify where to find the [ cmdstan]( - stan.org / interfaces / cmdstan ) install directory . Either set the CMDSTAN_HOME environment variable or symlink or use ` /opt / stan ` Simple MCMC sampling : @ runStan myModel myData sample @ Changing sampling parameters : @ runStan myModel myData sample { numSamples = 10000 } @ Optimizing : @ runStan optimize @ Optimizing with Newton 's method : @ runStan optimize { method = Newton } @ Running Stan models Before invoking `runStan`, you must specify where to find the [cmdstan](-stan.org/interfaces/cmdstan) install directory. Either set the CMDSTAN_HOME environment variable or symlink or use `/opt/stan` Simple MCMC sampling: @ runStan myModel myData sample @ Changing sampling parameters: @ runStan myModel myData sample { numSamples = 10000 } @ Optimizing: @ runStan myModel myData optimize @ Optimizing with Newton's method: @ runStan myModel myData optimize {method = Newton} @ -} # LANGUAGE TypeFamilies # module Stan.Run (runStan, runStanFile, Sample (..), Optimize (..), sample, optimize, StanMethod (..), OptMethod (..)) where import Stan.Data import Stan.AST import Stan.AST.Pretty import System.Directory import System.FilePath import System.Environment import Data.Hashable import System.Process import Control.Monad (unless) import Data.List (transpose) import Data.Char (toLower) import qualified Data.Map.Strict as Map import System.Exit import System.Random (randomRIO) import Data.Foldable (toList) -- | Parameters for the sample method. runStan called with this method will return @Map . Map String [ Double]@ , with one element in each list per sample from the MCMC chain data Sample = Sample { numIterations :: Int , numWarmup :: Int , thin :: Int } -- | Parameters for the optimise method. runStan called with this method will return @Map . Map String Double@ data Optimize = Optimize { iterations :: Int , method :: OptMethod } data OptMethod = BFGS | LBFGS | Newton deriving (Show, Eq) | Default value for Sample -- call with the " sample " method sample :: Sample sample = Sample 1000 1000 1 | Default value for Optimize -- call with the " optimize " method optimize :: Optimize optimize = Optimize 2000 LBFGS | The class of stan inference methods class StanMethod a where type StanReturns a runStanFiles :: FilePath -> FilePath -> a -> IO (StanReturns a) instance StanMethod Sample where type StanReturns Sample = Map.Map String [Double] runStanFiles mdlNm dataFile (Sample ns nw thn) = do outFl <- fmap (\i -> concat ["out", show i, ".csv"]) $ randomRIO (1::Int, 99999999) let optArg = toArgs [ ("num_samples", show ns) , ("num_warmup", show nw) , ("thin", show thn) ] cmd = concat ["./", mdlNm, " sample ", optArg, " data file=", dataFile, " output file=", outFl," 1>&2" ] ExitSuccess <- system cmd readStanSampleOutput outFl instance StanMethod Optimize where type StanReturns Optimize = Map.Map String Double runStanFiles mdlNm dataFile (Optimize iter meth) = do outFl <- fmap (\i -> concat ["out", show i, ".csv"]) $ randomRIO (1::Int, 99999999) let optArg = toArgs [ ("iter", show iter) , ("algorithm", map toLower $ show meth) ] cmd = concat ["./", mdlNm, " optimize ", optArg, " data file=", dataFile, " output file=", outFl," 1>&2" ] ExitSuccess <- system cmd readStanOptimizeOutput outFl toArgs :: [(String, String)] -> String toArgs = unwords . map f where f (k,v) = k ++ "=" ++ v | Run a stan model runStan :: StanMethod a ^ The model ^ The data file , written using . Data -> a -- ^ the method to run with -> IO (StanReturns a) -- ^ the output from that method runStan stans sData meth = do stTmpDir <- getStanTempDirectory dataFile <- writeStanDataFile stTmpDir sData mdlNm <- compileStanModel stTmpDir stans withCurrentDirectory stTmpDir $ do runStanFiles mdlNm dataFile meth | Run a stan file runStanFile :: StanMethod a ^ The model ^ The data file , written using . Data -> a -- ^ the method to run with -> IO (StanReturns a) -- ^ the output from that method runStanFile stans sData meth = do stTmpDir <- getStanTempDirectory dataFile <- writeStanDataFile stTmpDir sData let mdlNm' = 's': (show $ abs $ hash stans) mdlNm <- compileStanFile stTmpDir mdlNm' stans withCurrentDirectory stTmpDir $ do runStanFiles mdlNm dataFile meth compileStanModel :: FilePath -> [Stan] -> IO FilePath compileStanModel stTmpDir ss = do let mdlNm = 's': (show $ abs $ hash ss) compileStanFile stTmpDir mdlNm $ ppStans ss compileStanFile :: FilePath -> String -> String -> IO FilePath compileStanFile stTmpDir mdlNm stanFl = do let stanFile = stTmpDir </> mdlNm <.> "stan" ex <- doesFileExist (stTmpDir </> mdlNm) unless ex $ do writeFile stanFile stanFl standir <- findStanDir withCurrentDirectory standir $ do let cmd = "make " ++ stTmpDir </> mdlNm _ <- system cmd return () return mdlNm getStanTempDirectory :: IO FilePath getStanTempDirectory = do tmp <- getTemporaryDirectory let stTmpDir = tmp </> "stanhs" createDirectoryIfMissing False stTmpDir return stTmpDir writeStanDataFile :: FilePath -> StanData -> IO FilePath writeStanDataFile dir sData = do let dataLines = dumpEnv sData let dataNm = 'd': (show $ abs $ hash dataLines) dataFile = dir </> dataNm <.> "data.R" writeFile dataFile $ unlines dataLines return $ dataNm <.> "data.R" |Try to find the CmdStan installation directory , or die findStanDir :: IO FilePath findStanDir = do sdenv <- lookupEnv "CMDSTAN_HOME" case sdenv of Just sd -> return sd Nothing -> do ex <- doesDirectoryExist "/opt/stan" if ex then return "/opt/stan" else die "Environment variable CMDSTAN_HOME or /opt/stan must point to Stan install directory" readStanSampleOutput :: FilePath -> IO (Map.Map String [Double]) readStanSampleOutput fp = do (hdrs, samples) <- rawStanOutput fp return $ Map.fromList $ zip hdrs $ transpose samples readStanOptimizeOutput :: FilePath -> IO (Map.Map String Double) readStanOptimizeOutput fp = do (hdrs, [samples]) <- rawStanOutput fp return $ Map.fromList $ zip hdrs samples rawStanOutput :: FilePath -> IO ([String], [[Double]]) rawStanOutput fp = do let noHash ('#':_) = False noHash _ = True (hdrLn:lns) <- fmap (filter noHash . lines) $ readFile fp let hdrs = splitBy ',' hdrLn samples = map (map read . splitBy ',') lns return (hdrs, samples) splitBy :: Char -> String -> [String] splitBy delimiter = foldr f [[]] where f c l@(x:xs) | c == delimiter = []:l | otherwise = (c:x):xs
null
https://raw.githubusercontent.com/diffusionkinetics/open/673d9a4a099abd9035ccc21e37d8e614a45a1901/stanhs/lib/Stan/Run.hs
haskell
| Parameters for the sample method. | Parameters for the optimise method. call with the " sample " method call with the " optimize " method ^ the method to run with ^ the output from that method ^ the method to run with ^ the output from that method
| Running models Before invoking ` runStan ` , you must specify where to find the [ cmdstan]( - stan.org / interfaces / cmdstan ) install directory . Either set the CMDSTAN_HOME environment variable or symlink or use ` /opt / stan ` Simple MCMC sampling : @ runStan myModel myData sample @ Changing sampling parameters : @ runStan myModel myData sample { numSamples = 10000 } @ Optimizing : @ runStan optimize @ Optimizing with Newton 's method : @ runStan optimize { method = Newton } @ Running Stan models Before invoking `runStan`, you must specify where to find the [cmdstan](-stan.org/interfaces/cmdstan) install directory. Either set the CMDSTAN_HOME environment variable or symlink or use `/opt/stan` Simple MCMC sampling: @ runStan myModel myData sample @ Changing sampling parameters: @ runStan myModel myData sample { numSamples = 10000 } @ Optimizing: @ runStan myModel myData optimize @ Optimizing with Newton's method: @ runStan myModel myData optimize {method = Newton} @ -} # LANGUAGE TypeFamilies # module Stan.Run (runStan, runStanFile, Sample (..), Optimize (..), sample, optimize, StanMethod (..), OptMethod (..)) where import Stan.Data import Stan.AST import Stan.AST.Pretty import System.Directory import System.FilePath import System.Environment import Data.Hashable import System.Process import Control.Monad (unless) import Data.List (transpose) import Data.Char (toLower) import qualified Data.Map.Strict as Map import System.Exit import System.Random (randomRIO) import Data.Foldable (toList) runStan called with this method will return @Map . Map String [ Double]@ , with one element in each list per sample from the MCMC chain data Sample = Sample { numIterations :: Int , numWarmup :: Int , thin :: Int } runStan called with this method will return @Map . Map String Double@ data Optimize = Optimize { iterations :: Int , method :: OptMethod } data OptMethod = BFGS | LBFGS | Newton deriving (Show, Eq) sample :: Sample sample = Sample 1000 1000 1 optimize :: Optimize optimize = Optimize 2000 LBFGS | The class of stan inference methods class StanMethod a where type StanReturns a runStanFiles :: FilePath -> FilePath -> a -> IO (StanReturns a) instance StanMethod Sample where type StanReturns Sample = Map.Map String [Double] runStanFiles mdlNm dataFile (Sample ns nw thn) = do outFl <- fmap (\i -> concat ["out", show i, ".csv"]) $ randomRIO (1::Int, 99999999) let optArg = toArgs [ ("num_samples", show ns) , ("num_warmup", show nw) , ("thin", show thn) ] cmd = concat ["./", mdlNm, " sample ", optArg, " data file=", dataFile, " output file=", outFl," 1>&2" ] ExitSuccess <- system cmd readStanSampleOutput outFl instance StanMethod Optimize where type StanReturns Optimize = Map.Map String Double runStanFiles mdlNm dataFile (Optimize iter meth) = do outFl <- fmap (\i -> concat ["out", show i, ".csv"]) $ randomRIO (1::Int, 99999999) let optArg = toArgs [ ("iter", show iter) , ("algorithm", map toLower $ show meth) ] cmd = concat ["./", mdlNm, " optimize ", optArg, " data file=", dataFile, " output file=", outFl," 1>&2" ] ExitSuccess <- system cmd readStanOptimizeOutput outFl toArgs :: [(String, String)] -> String toArgs = unwords . map f where f (k,v) = k ++ "=" ++ v | Run a stan model runStan :: StanMethod a ^ The model ^ The data file , written using . Data runStan stans sData meth = do stTmpDir <- getStanTempDirectory dataFile <- writeStanDataFile stTmpDir sData mdlNm <- compileStanModel stTmpDir stans withCurrentDirectory stTmpDir $ do runStanFiles mdlNm dataFile meth | Run a stan file runStanFile :: StanMethod a ^ The model ^ The data file , written using . Data runStanFile stans sData meth = do stTmpDir <- getStanTempDirectory dataFile <- writeStanDataFile stTmpDir sData let mdlNm' = 's': (show $ abs $ hash stans) mdlNm <- compileStanFile stTmpDir mdlNm' stans withCurrentDirectory stTmpDir $ do runStanFiles mdlNm dataFile meth compileStanModel :: FilePath -> [Stan] -> IO FilePath compileStanModel stTmpDir ss = do let mdlNm = 's': (show $ abs $ hash ss) compileStanFile stTmpDir mdlNm $ ppStans ss compileStanFile :: FilePath -> String -> String -> IO FilePath compileStanFile stTmpDir mdlNm stanFl = do let stanFile = stTmpDir </> mdlNm <.> "stan" ex <- doesFileExist (stTmpDir </> mdlNm) unless ex $ do writeFile stanFile stanFl standir <- findStanDir withCurrentDirectory standir $ do let cmd = "make " ++ stTmpDir </> mdlNm _ <- system cmd return () return mdlNm getStanTempDirectory :: IO FilePath getStanTempDirectory = do tmp <- getTemporaryDirectory let stTmpDir = tmp </> "stanhs" createDirectoryIfMissing False stTmpDir return stTmpDir writeStanDataFile :: FilePath -> StanData -> IO FilePath writeStanDataFile dir sData = do let dataLines = dumpEnv sData let dataNm = 'd': (show $ abs $ hash dataLines) dataFile = dir </> dataNm <.> "data.R" writeFile dataFile $ unlines dataLines return $ dataNm <.> "data.R" |Try to find the CmdStan installation directory , or die findStanDir :: IO FilePath findStanDir = do sdenv <- lookupEnv "CMDSTAN_HOME" case sdenv of Just sd -> return sd Nothing -> do ex <- doesDirectoryExist "/opt/stan" if ex then return "/opt/stan" else die "Environment variable CMDSTAN_HOME or /opt/stan must point to Stan install directory" readStanSampleOutput :: FilePath -> IO (Map.Map String [Double]) readStanSampleOutput fp = do (hdrs, samples) <- rawStanOutput fp return $ Map.fromList $ zip hdrs $ transpose samples readStanOptimizeOutput :: FilePath -> IO (Map.Map String Double) readStanOptimizeOutput fp = do (hdrs, [samples]) <- rawStanOutput fp return $ Map.fromList $ zip hdrs samples rawStanOutput :: FilePath -> IO ([String], [[Double]]) rawStanOutput fp = do let noHash ('#':_) = False noHash _ = True (hdrLn:lns) <- fmap (filter noHash . lines) $ readFile fp let hdrs = splitBy ',' hdrLn samples = map (map read . splitBy ',') lns return (hdrs, samples) splitBy :: Char -> String -> [String] splitBy delimiter = foldr f [[]] where f c l@(x:xs) | c == delimiter = []:l | otherwise = (c:x):xs
2a9e399201e8fca12c892d1e4502ef4537c2c54765b2a11bc2b8552e94bd3653
s-cerevisiae/leetcode-racket
17-letter-combinations-of-a-phone-number.rkt
#lang racket (define letter-map #hash((#\2 . (#\a #\b #\c)) (#\3 . (#\d #\e #\f)) (#\4 . (#\g #\h #\i)) (#\5 . (#\j #\k #\l)) (#\6 . (#\m #\n #\o)) (#\7 . (#\p #\q #\r #\s)) (#\8 . (#\t #\u #\v)) (#\9 . (#\w #\x #\y #\z)))) (define/contract (letter-combinations digits) (-> string? (listof string?)) (if (zero? (string-length digits)) '() (map list->string (combine (string->list digits))))) (define (combine ns) (define (get-letters n) (hash-ref letter-map n)) (if (null? ns) '(()) (for*/list ([rest-combinations (combine (cdr ns))] [current-letter (get-letters (car ns))]) (cons current-letter rest-combinations))))
null
https://raw.githubusercontent.com/s-cerevisiae/leetcode-racket/a81da53755debd5efec2d95f7c311d230ac5b3f4/17-letter-combinations-of-a-phone-number.rkt
racket
#lang racket (define letter-map #hash((#\2 . (#\a #\b #\c)) (#\3 . (#\d #\e #\f)) (#\4 . (#\g #\h #\i)) (#\5 . (#\j #\k #\l)) (#\6 . (#\m #\n #\o)) (#\7 . (#\p #\q #\r #\s)) (#\8 . (#\t #\u #\v)) (#\9 . (#\w #\x #\y #\z)))) (define/contract (letter-combinations digits) (-> string? (listof string?)) (if (zero? (string-length digits)) '() (map list->string (combine (string->list digits))))) (define (combine ns) (define (get-letters n) (hash-ref letter-map n)) (if (null? ns) '(()) (for*/list ([rest-combinations (combine (cdr ns))] [current-letter (get-letters (car ns))]) (cons current-letter rest-combinations))))
c8b02598e0245a82ad097ad9dcc66442171a9b5878a9a7d662ae1b7888587d47
coq/coq
evar_kinds.ml
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) * GNU Lesser General Public License Version 2.1 (* * (see LICENSE file for the text of the license) *) (************************************************************************) open Names (** The kinds of existential variable *) (** Should the obligation be defined (opaque or transparent (default)) or defined transparent and expanded in the term? *) type obligation_definition_status = Define of bool | Expand type matching_var_kind = FirstOrderPatVar of Id.t | SecondOrderPatVar of Id.t type subevar_kind = Domain | Codomain | Body maybe this should be a Projection.t type record_field = { fieldname : Constant.t; recordname : Names.inductive } type question_mark = { qm_obligation: obligation_definition_status; qm_name: Name.t; qm_record_field: record_field option; } let default_question_mark = { qm_obligation=Define true; qm_name=Anonymous; qm_record_field=None; } type t = | ImplicitArg of GlobRef.t * (int * Id.t option) * bool (** Force inference *) | BinderType of Name.t | EvarType of Id.t option * Evar.t (* type of an optionally named evar *) | NamedHole of Id.t (* coming from some ?[id] syntax *) | QuestionMark of question_mark | CasesType of bool (* true = a subterm of the type *) | InternalHole | TomatchTypeParameter of inductive * int | GoalEvar | ImpossibleCase | MatchingVar of matching_var_kind | VarInstance of Id.t | SubEvar of subevar_kind option * Evar.t
null
https://raw.githubusercontent.com/coq/coq/110921a449fcb830ec2a1cd07e3acc32319feae6/engine/evar_kinds.ml
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** * The kinds of existential variable * Should the obligation be defined (opaque or transparent (default)) or defined transparent and expanded in the term? * Force inference type of an optionally named evar coming from some ?[id] syntax true = a subterm of the type
v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 open Names type obligation_definition_status = Define of bool | Expand type matching_var_kind = FirstOrderPatVar of Id.t | SecondOrderPatVar of Id.t type subevar_kind = Domain | Codomain | Body maybe this should be a Projection.t type record_field = { fieldname : Constant.t; recordname : Names.inductive } type question_mark = { qm_obligation: obligation_definition_status; qm_name: Name.t; qm_record_field: record_field option; } let default_question_mark = { qm_obligation=Define true; qm_name=Anonymous; qm_record_field=None; } type t = | ImplicitArg of GlobRef.t * (int * Id.t option) | BinderType of Name.t | QuestionMark of question_mark | InternalHole | TomatchTypeParameter of inductive * int | GoalEvar | ImpossibleCase | MatchingVar of matching_var_kind | VarInstance of Id.t | SubEvar of subevar_kind option * Evar.t
6647a72cc32b5f1e14382842d347cf46b473a164b2e7d65d8eab2f61cea25ea3
dmiller/clr.core.async
timers_test.clj
(ns clojure.core.async.timers-test (:require [clojure.test :refer :all] [clojure.core.async.impl.timers :refer :all] [clojure.core.async :as async]) DM : Added (deftest timeout-interval-test System / currentTimeMillis test-timeout (timeout 500)] (is (<= (+ start-stamp 500) (do (async/<!! test-timeout) System / currentTimeMillis "Reading from a timeout channel does not complete until the specified milliseconds have elapsed."))) (defn pause [ms] (System.Threading.Thread/Sleep ms)) (deftest timeout-ordering-test (let [test-atom (atom []) timeout-channels [(timeout 8000) (timeout 6000) (timeout 7000) (timeout 5000)] threads (doall (for [i (range 4)] (doto (Thread. (gen-delegate ThreadStart [] (do (async/<!! (timeout-channels i)) ;;; Add gen-delegate, remove # (swap! test-atom conj i)))) (.Start))))] ;;; .Start (doseq [thread threads] (.Join ^Thread thread)) ;;; .join (is (= @test-atom [3 1 2 0]) "Timeouts close in order determined by their delays, not in order determined by their creation.")))
null
https://raw.githubusercontent.com/dmiller/clr.core.async/bb861242531cdd6ba727283bf3ddee73db1e1c2d/test/clojure/clojure/core/async/timers_test.clj
clojure
Add gen-delegate, remove # .Start .join
(ns clojure.core.async.timers-test (:require [clojure.test :refer :all] [clojure.core.async.impl.timers :refer :all] [clojure.core.async :as async]) DM : Added (deftest timeout-interval-test System / currentTimeMillis test-timeout (timeout 500)] (is (<= (+ start-stamp 500) (do (async/<!! test-timeout) System / currentTimeMillis "Reading from a timeout channel does not complete until the specified milliseconds have elapsed."))) (defn pause [ms] (System.Threading.Thread/Sleep ms)) (deftest timeout-ordering-test (let [test-atom (atom []) timeout-channels [(timeout 8000) (timeout 6000) (timeout 7000) (timeout 5000)] threads (doall (for [i (range 4)] (doto (Thread. (gen-delegate ThreadStart [] (swap! test-atom conj i)))) (doseq [thread threads] (is (= @test-atom [3 1 2 0]) "Timeouts close in order determined by their delays, not in order determined by their creation.")))
6fdc1ac52773a0acba9aad21868b8cafde16ea7a7190c9e973966de169a0b7fe
fission-codes/fission
Ownership.hs
module Fission.Web.Server.Ownership ( module Fission.Web.Server.Ownership.Class , isOwnedBy ) where import Prelude import Fission.Web.Server.Models import Fission.Web.Server.Ownership.Class isOwnedBy :: Owned item => UserId -> item -> Bool isOwnedBy userId item = userId == ownerId item
null
https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-web-server/library/Fission/Web/Server/Ownership.hs
haskell
module Fission.Web.Server.Ownership ( module Fission.Web.Server.Ownership.Class , isOwnedBy ) where import Prelude import Fission.Web.Server.Models import Fission.Web.Server.Ownership.Class isOwnedBy :: Owned item => UserId -> item -> Bool isOwnedBy userId item = userId == ownerId item
0ae73779703d687abf97ce9ae2998c7c145ea5615b4c9efdc94238f52a5d74ff
mu-chaco/ReWire
Main.hs
module Main (main) where import qualified ReWire.Main as M import Control.Monad (unless, msum) import Data.List (isSuffixOf) import Data.Maybe (fromMaybe) import System.Console.GetOpt (getOpt, usageInfo, OptDescr (..), ArgOrder (..), ArgDescr (..)) import System.Directory (listDirectory, setCurrentDirectory) import System.Environment (getArgs) import System.Environment (withArgs) import System.Exit (exitFailure) import System.FilePath ((</>), (-<.>), takeBaseName, takeDirectory) import System.IO (hPutStr, hPutStrLn, stderr) import System.Process (callCommand) import Test.Framework (defaultMainWithArgs, testGroup, Test) import Test.Framework.Providers.HUnit (testCase) import Paths_ReWire (getDataFileName) data Flag = FlagV | FlagNoGhdl | FlagNoGhc | FlagNoDTypes | FlagChecker String deriving (Eq, Show) options :: [OptDescr Flag] options = [ Option ['v'] ["verbose"] (NoArg FlagV) "More verbose output." , Option [] ["no-ghdl"] (NoArg FlagNoGhdl) "Disable verification of output VHDL with 'ghdl -s' (which requires 'ghdl' in $PATH)." , Option [] ["no-ghc"] (NoArg FlagNoGhdl) "Disable running tests through ghc." , Option [] ["no-dtypes"] (NoArg FlagNoDTypes) "Disable extra type-checking passes." , Option [] ["vhdl-checker"] (ReqArg FlagChecker "command") "Set the command to use for checking generated VHDL (default: 'ghdl -s')." ] testCompiler :: [Flag] -> FilePath -> [Test] testCompiler flags fn = [testCase (takeBaseName fn) $ do setCurrentDirectory $ takeDirectory fn withArgs (fn : extraFlags) M.main ] ++ if FlagNoGhdl `elem` flags then [] else [testCase (takeBaseName fn ++ " (" ++ checker ++ ")") $ do setCurrentDirectory $ takeDirectory fn callCommand $ checker ++ " " ++ fn -<.> "vhdl" ] ++ if FlagNoGhc `elem` flags then [] else [testCase (takeBaseName fn ++ " (stack ghc)") $ do setCurrentDirectory $ takeDirectory fn callCommand $ "stack ghc " ++ fn ] where extraFlags :: [String] extraFlags = if FlagNoDTypes `elem` flags then [] else ["--dtypes"] ++ if FlagV `elem` flags then ["-v"] else [] checker :: String checker = fromMaybe "ghdl -s" $ msum $ flip map flags $ \ case FlagChecker c -> Just $ sq c _ -> Nothing sq :: String -> String sq = \ case '"' : s | last s == '"' -> init s '\'' : s | last s == '\'' -> init s s -> s getTests :: [Flag] -> FilePath -> IO Test getTests flags dirName = do dir <- getDataFileName ("tests" </> dirName) files <- map (dir </>) . filter (".hs" `isSuffixOf`) <$> listDirectory dir pure $ testGroup dirName $ concatMap (testCompiler flags) files exitUsage :: IO () exitUsage = hPutStr stderr (usageInfo "Usage: rwc-test [OPTION...]" options) >> exitFailure main :: IO () main = do (flags, testDirs, errs) <- getOpt Permute options <$> getArgs let testDirs' = if null testDirs then ["regression", "integration"] else testDirs unless (null errs) $ do mapM_ (hPutStrLn stderr) errs exitUsage tests <- mapM (getTests flags) testDirs' defaultMainWithArgs tests []
null
https://raw.githubusercontent.com/mu-chaco/ReWire/b04686a4cd6cb36ca9976a4b6c42bc195ce69462/src/rwc-test/Main.hs
haskell
module Main (main) where import qualified ReWire.Main as M import Control.Monad (unless, msum) import Data.List (isSuffixOf) import Data.Maybe (fromMaybe) import System.Console.GetOpt (getOpt, usageInfo, OptDescr (..), ArgOrder (..), ArgDescr (..)) import System.Directory (listDirectory, setCurrentDirectory) import System.Environment (getArgs) import System.Environment (withArgs) import System.Exit (exitFailure) import System.FilePath ((</>), (-<.>), takeBaseName, takeDirectory) import System.IO (hPutStr, hPutStrLn, stderr) import System.Process (callCommand) import Test.Framework (defaultMainWithArgs, testGroup, Test) import Test.Framework.Providers.HUnit (testCase) import Paths_ReWire (getDataFileName) data Flag = FlagV | FlagNoGhdl | FlagNoGhc | FlagNoDTypes | FlagChecker String deriving (Eq, Show) options :: [OptDescr Flag] options = [ Option ['v'] ["verbose"] (NoArg FlagV) "More verbose output." , Option [] ["no-ghdl"] (NoArg FlagNoGhdl) "Disable verification of output VHDL with 'ghdl -s' (which requires 'ghdl' in $PATH)." , Option [] ["no-ghc"] (NoArg FlagNoGhdl) "Disable running tests through ghc." , Option [] ["no-dtypes"] (NoArg FlagNoDTypes) "Disable extra type-checking passes." , Option [] ["vhdl-checker"] (ReqArg FlagChecker "command") "Set the command to use for checking generated VHDL (default: 'ghdl -s')." ] testCompiler :: [Flag] -> FilePath -> [Test] testCompiler flags fn = [testCase (takeBaseName fn) $ do setCurrentDirectory $ takeDirectory fn withArgs (fn : extraFlags) M.main ] ++ if FlagNoGhdl `elem` flags then [] else [testCase (takeBaseName fn ++ " (" ++ checker ++ ")") $ do setCurrentDirectory $ takeDirectory fn callCommand $ checker ++ " " ++ fn -<.> "vhdl" ] ++ if FlagNoGhc `elem` flags then [] else [testCase (takeBaseName fn ++ " (stack ghc)") $ do setCurrentDirectory $ takeDirectory fn callCommand $ "stack ghc " ++ fn ] where extraFlags :: [String] extraFlags = if FlagNoDTypes `elem` flags then [] else ["--dtypes"] ++ if FlagV `elem` flags then ["-v"] else [] checker :: String checker = fromMaybe "ghdl -s" $ msum $ flip map flags $ \ case FlagChecker c -> Just $ sq c _ -> Nothing sq :: String -> String sq = \ case '"' : s | last s == '"' -> init s '\'' : s | last s == '\'' -> init s s -> s getTests :: [Flag] -> FilePath -> IO Test getTests flags dirName = do dir <- getDataFileName ("tests" </> dirName) files <- map (dir </>) . filter (".hs" `isSuffixOf`) <$> listDirectory dir pure $ testGroup dirName $ concatMap (testCompiler flags) files exitUsage :: IO () exitUsage = hPutStr stderr (usageInfo "Usage: rwc-test [OPTION...]" options) >> exitFailure main :: IO () main = do (flags, testDirs, errs) <- getOpt Permute options <$> getArgs let testDirs' = if null testDirs then ["regression", "integration"] else testDirs unless (null errs) $ do mapM_ (hPutStrLn stderr) errs exitUsage tests <- mapM (getTests flags) testDirs' defaultMainWithArgs tests []
00dbeda2eb65065f4ab6ac76d2dabe025f402e7632af418b6a956e1b551d2ab5
tweag/webauthn
Encoding.hs
# LANGUAGE DataKinds # module Encoding (spec) where import Control.Monad.Reader (runReaderT) import Crypto.WebAuthn.AttestationStatementFormat (allSupportedFormats) import Crypto.WebAuthn.Encoding.Binary (encodeRawCredential) import Crypto.WebAuthn.Encoding.Internal.WebAuthnJson (Decode (decode), Encode (encode)) import qualified Crypto.WebAuthn.Model as M import Spec.Types () import Test.Hspec (Expectation, SpecWith, describe, expectationFailure, shouldBe) import Test.Hspec.QuickCheck (prop) spec :: SpecWith () spec = do describe "PublicKeyCredentialCreationOptions" $ prop "can be roundtripped" prop_creationOptionsRoundtrip describe "PublicKeyCredentialRequestOptions" $ prop "can be roundtripped" prop_requestOptionsRoundtrip describe "CreatedPublicKeyCredential" $ prop "can be roundtripped" prop_createdCredentialRoundtrip describe "RequestedPublicKeyCredential" $ prop "can be roundtripped" prop_requestedCredentialRoundtrip prop_creationOptionsRoundtrip :: M.CredentialOptions 'M.Registration -> Expectation prop_creationOptionsRoundtrip options = do let encoded = encode options case decode encoded of Right decoded -> decoded `shouldBe` options Left err -> expectationFailure $ show err prop_requestOptionsRoundtrip :: M.CredentialOptions 'M.Authentication -> Expectation prop_requestOptionsRoundtrip options = do let encoded = encode options case decode encoded of Right decoded -> decoded `shouldBe` options Left err -> expectationFailure $ show err prop_createdCredentialRoundtrip :: M.Credential 'M.Registration 'False -> Expectation prop_createdCredentialRoundtrip options = do let withRaw = encodeRawCredential options encoded = encode withRaw case runReaderT (decode encoded) allSupportedFormats of Right decoded -> do decoded `shouldBe` withRaw Left err -> expectationFailure $ show err prop_requestedCredentialRoundtrip :: M.Credential 'M.Authentication 'False -> Expectation prop_requestedCredentialRoundtrip options = do let withRaw = encodeRawCredential options encoded = encode withRaw case decode encoded of Right decoded -> do decoded `shouldBe` withRaw Left err -> expectationFailure $ show err
null
https://raw.githubusercontent.com/tweag/webauthn/349a2b408a79107d9f07c017b72b03c9c306e5fa/tests/Encoding.hs
haskell
# LANGUAGE DataKinds # module Encoding (spec) where import Control.Monad.Reader (runReaderT) import Crypto.WebAuthn.AttestationStatementFormat (allSupportedFormats) import Crypto.WebAuthn.Encoding.Binary (encodeRawCredential) import Crypto.WebAuthn.Encoding.Internal.WebAuthnJson (Decode (decode), Encode (encode)) import qualified Crypto.WebAuthn.Model as M import Spec.Types () import Test.Hspec (Expectation, SpecWith, describe, expectationFailure, shouldBe) import Test.Hspec.QuickCheck (prop) spec :: SpecWith () spec = do describe "PublicKeyCredentialCreationOptions" $ prop "can be roundtripped" prop_creationOptionsRoundtrip describe "PublicKeyCredentialRequestOptions" $ prop "can be roundtripped" prop_requestOptionsRoundtrip describe "CreatedPublicKeyCredential" $ prop "can be roundtripped" prop_createdCredentialRoundtrip describe "RequestedPublicKeyCredential" $ prop "can be roundtripped" prop_requestedCredentialRoundtrip prop_creationOptionsRoundtrip :: M.CredentialOptions 'M.Registration -> Expectation prop_creationOptionsRoundtrip options = do let encoded = encode options case decode encoded of Right decoded -> decoded `shouldBe` options Left err -> expectationFailure $ show err prop_requestOptionsRoundtrip :: M.CredentialOptions 'M.Authentication -> Expectation prop_requestOptionsRoundtrip options = do let encoded = encode options case decode encoded of Right decoded -> decoded `shouldBe` options Left err -> expectationFailure $ show err prop_createdCredentialRoundtrip :: M.Credential 'M.Registration 'False -> Expectation prop_createdCredentialRoundtrip options = do let withRaw = encodeRawCredential options encoded = encode withRaw case runReaderT (decode encoded) allSupportedFormats of Right decoded -> do decoded `shouldBe` withRaw Left err -> expectationFailure $ show err prop_requestedCredentialRoundtrip :: M.Credential 'M.Authentication 'False -> Expectation prop_requestedCredentialRoundtrip options = do let withRaw = encodeRawCredential options encoded = encode withRaw case decode encoded of Right decoded -> do decoded `shouldBe` withRaw Left err -> expectationFailure $ show err
e2bca1b0cc034141e2af099215427a5a5a9c08835757d51f2cd0a01df55853a4
esl/MongooseIM
mod_mam_rdbms_prefs.erl
%%%------------------------------------------------------------------- @author Michael < > ( C ) 2013 , Uvarov Michael @doc A backend for storing MAM preferencies using RDBMS . %%% @end %%%------------------------------------------------------------------- -module(mod_mam_rdbms_prefs). %% ---------------------------------------------------------------------- %% Exports %% gen_mod handlers -behaviour(gen_mod). -export([start/2, stop/1, hooks/1, supported_features/0]). MAM hook handlers -behaviour(ejabberd_gen_mam_prefs). -export([get_behaviour/3, get_prefs/3, set_prefs/3, remove_archive/3]). -import(mongoose_rdbms, [prepare/4]). -include("mongoose.hrl"). -include("jlib.hrl"). -include_lib("exml/include/exml.hrl"). %% ---------------------------------------------------------------------- %% gen_mod callbacks %% Starting and stopping functions for users' archives -spec start(mongooseim:host_type(), _) -> ok. start(HostType, _Opts) -> prepare_queries(HostType), ok. -spec stop(mongooseim:host_type()) -> ok. stop(_HostType) -> ok. -spec supported_features() -> [atom()]. supported_features() -> [dynamic_domains]. hooks(HostType) -> PM = gen_mod:get_module_opt(HostType, ?MODULE, pm, false), MUC = gen_mod:get_module_opt(HostType, ?MODULE, muc, false), maybe_pm_hooks(PM, HostType) ++ maybe_muc_hooks(MUC, HostType). maybe_pm_hooks(true, HostType) -> pm_hooks(HostType); maybe_pm_hooks(false, _HostType) -> []. maybe_muc_hooks(true, HostType) -> muc_hooks(HostType); maybe_muc_hooks(false, _HostType) -> []. pm_hooks(HostType) -> [{mam_get_behaviour, HostType, fun ?MODULE:get_behaviour/3, #{}, 50}, {mam_get_prefs, HostType, fun ?MODULE:get_prefs/3, #{}, 50}, {mam_set_prefs, HostType, fun ?MODULE:set_prefs/3, #{}, 50}, {mam_remove_archive, HostType, fun ?MODULE:remove_archive/3, #{}, 50}]. muc_hooks(HostType) -> [{mam_muc_get_behaviour, HostType, fun ?MODULE:get_behaviour/3, #{}, 50}, {mam_muc_get_prefs, HostType, fun ?MODULE:get_prefs/3, #{}, 50}, {mam_muc_set_prefs, HostType, fun ?MODULE:set_prefs/3, #{}, 50}, {mam_muc_remove_archive, HostType, fun ?MODULE:remove_archive/3, #{}, 50}]. %% Prepared queries prepare_queries(HostType) -> prepare(mam_prefs_insert, mam_config, [user_id, remote_jid, behaviour], <<"INSERT INTO mam_config(user_id, remote_jid, behaviour) " "VALUES (?, ?, ?)">>), prepare(mam_prefs_select, mam_config, [user_id], <<"SELECT remote_jid, behaviour " "FROM mam_config WHERE user_id=?">>), prepare(mam_prefs_select_behaviour, mam_config, [user_id, remote_jid], <<"SELECT remote_jid, behaviour " "FROM mam_config " "WHERE user_id=? " "AND (remote_jid='' OR remote_jid=?)">>), prepare(mam_prefs_select_behaviour2, mam_config, [user_id, remote_jid, remote_jid], <<"SELECT remote_jid, behaviour " "FROM mam_config " "WHERE user_id=? " "AND (remote_jid='' OR remote_jid=? OR remote_jid=?)">>), OrdBy = order_by_remote_jid_in_delete(HostType), prepare(mam_prefs_delete, mam_config, [user_id], <<"DELETE FROM mam_config WHERE user_id=?", OrdBy/binary>>), ok. order_by_remote_jid_in_delete(HostType) -> case mongoose_rdbms:db_engine(HostType) of mysql -> <<" ORDER BY remote_jid">>; _ -> <<>> end. %% ---------------------------------------------------------------------- Internal functions and callbacks -spec get_behaviour(Acc, Params, Extra) -> {ok, Acc} when Acc :: mod_mam:archive_behaviour(), Params :: ejabberd_gen_mam_prefs:get_behaviour_params(), Extra :: gen_hook:extra(). get_behaviour(DefaultBehaviour, #{archive_id := UserID, remote := RemJID}, #{host_type := HostType}) when is_integer(UserID) -> RemLJID = jid:to_lower(RemJID), BRemLBareJID = jid:to_bare_binary(RemLJID), BRemLJID = jid:to_binary(RemLJID), case query_behaviour(HostType, UserID, BRemLJID, BRemLBareJID) of {selected, []} -> {ok, DefaultBehaviour}; {selected, RemoteJid2Behaviour} -> DbBehaviour = choose_behaviour(BRemLJID, BRemLBareJID, RemoteJid2Behaviour), {ok, decode_behaviour(DbBehaviour)} end. -spec choose_behaviour(binary(), binary(), [{binary(), binary()}]) -> binary(). choose_behaviour(BRemLJID, BRemLBareJID, RemoteJid2Behaviour) -> case lists:keyfind(BRemLJID, 1, RemoteJid2Behaviour) of {_, Behaviour} -> Behaviour; false -> case lists:keyfind(BRemLBareJID, 1, RemoteJid2Behaviour) of {_, Behaviour} -> Behaviour; false -> Only one key remains {_, Behaviour} = lists:keyfind(<<>>, 1, RemoteJid2Behaviour), Behaviour end end. -spec set_prefs(Acc, Params, Extra) -> {ok, Acc} when Acc :: term(), Params :: ejabberd_gen_mam_prefs:set_prefs_params(), Extra :: gen_hook:extra(). set_prefs(_Result, #{archive_id := UserID, default_mode := DefaultMode, always_jids := AlwaysJIDs, never_jids := NeverJIDs}, #{host_type := HostType}) -> try {ok, set_prefs1(HostType, UserID, DefaultMode, AlwaysJIDs, NeverJIDs)} catch _Type:Error -> {ok, {error, Error}} end. set_prefs1(HostType, UserID, DefaultMode, AlwaysJIDs, NeverJIDs) -> Rows = prefs_to_rows(UserID, DefaultMode, AlwaysJIDs, NeverJIDs), %% MySQL sometimes aborts transaction with reason: %% "Deadlock found when trying to get lock; try restarting transaction" mongoose_rdbms:transaction_with_delayed_retry(HostType, fun() -> {updated, _} = mongoose_rdbms:execute(HostType, mam_prefs_delete, [UserID]), [{updated, 1} = mongoose_rdbms:execute(HostType, mam_prefs_insert, Row) || Row <- Rows], ok end, #{user_id => UserID, retries => 5, delay => 100}), ok. -spec get_prefs(Acc, Params, Extra) -> {ok, Acc} when Acc :: mod_mam:preference(), Params :: ejabberd_gen_mam_prefs:get_prefs_params(), Extra :: gen_hook:extra(). get_prefs({GlobalDefaultMode, _, _}, #{archive_id := UserID}, #{host_type := HostType}) -> {selected, Rows} = mongoose_rdbms:execute(HostType, mam_prefs_select, [UserID]), {ok, decode_prefs_rows(Rows, GlobalDefaultMode, [], [])}. -spec remove_archive(Acc, Params, Extra) -> {ok, Acc} when Acc :: term(), Params :: #{archive_id := mod_mam:archive_id() | undefined, owner => jid:jid(), room => jid:jid()}, Extra :: gen_hook:extra(). remove_archive(Acc, #{archive_id := UserID}, #{host_type := HostType}) -> remove_archive(HostType, UserID), {ok, Acc}. remove_archive(HostType, UserID) -> {updated, _} = mongoose_rdbms:execute(HostType, mam_prefs_delete, [UserID]). -spec query_behaviour(HostType :: mongooseim:host_type(), UserID :: non_neg_integer(), BRemLJID :: binary(), BRemLBareJID :: binary() ) -> any(). query_behaviour(HostType, UserID, BRemLJID, BRemLJID) -> mongoose_rdbms:execute(HostType, mam_prefs_select_behaviour, [UserID, BRemLJID]); %% check just bare jid query_behaviour(HostType, UserID, BRemLJID, BRemLBareJID) -> mongoose_rdbms:execute(HostType, mam_prefs_select_behaviour2, [UserID, BRemLJID, BRemLBareJID]). %% ---------------------------------------------------------------------- %% Helpers -spec encode_behaviour(always | never | roster) -> binary(). encode_behaviour(roster) -> <<"R">>; encode_behaviour(always) -> <<"A">>; encode_behaviour(never) -> <<"N">>. -spec decode_behaviour(binary()) -> always | never | roster. decode_behaviour(<<"R">>) -> roster; decode_behaviour(<<"A">>) -> always; decode_behaviour(<<"N">>) -> never. prefs_to_rows(UserID, DefaultMode, AlwaysJIDs, NeverJIDs) -> AlwaysRows = [[UserID, JID, encode_behaviour(always)] || JID <- AlwaysJIDs], NeverRows = [[UserID, JID, encode_behaviour(never)] || JID <- NeverJIDs], DefaultRow = [UserID, <<>>, encode_behaviour(DefaultMode)], %% Lock keys in the same order to avoid deadlock [DefaultRow|lists:sort(AlwaysRows ++ NeverRows)]. -spec decode_prefs_rows([{binary() | jid:jid(), binary()}], DefaultMode :: mod_mam:archive_behaviour(), AlwaysJIDs :: [jid:literal_jid()], NeverJIDs :: [jid:literal_jid()]) -> {mod_mam:archive_behaviour(), [jid:literal_jid()], [jid:literal_jid()]}. decode_prefs_rows([{<<>>, Behaviour}|Rows], _DefaultMode, AlwaysJIDs, NeverJIDs) -> decode_prefs_rows(Rows, decode_behaviour(Behaviour), AlwaysJIDs, NeverJIDs); decode_prefs_rows([{JID, <<"A">>}|Rows], DefaultMode, AlwaysJIDs, NeverJIDs) -> decode_prefs_rows(Rows, DefaultMode, [JID|AlwaysJIDs], NeverJIDs); decode_prefs_rows([{JID, <<"N">>}|Rows], DefaultMode, AlwaysJIDs, NeverJIDs) -> decode_prefs_rows(Rows, DefaultMode, AlwaysJIDs, [JID|NeverJIDs]); decode_prefs_rows([], DefaultMode, AlwaysJIDs, NeverJIDs) -> {DefaultMode, AlwaysJIDs, NeverJIDs}.
null
https://raw.githubusercontent.com/esl/MongooseIM/7b91117c0ec1018e3f847da9cfabdd89c50d358b/src/mam/mod_mam_rdbms_prefs.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- ---------------------------------------------------------------------- Exports gen_mod handlers ---------------------------------------------------------------------- gen_mod callbacks Starting and stopping functions for users' archives Prepared queries ---------------------------------------------------------------------- MySQL sometimes aborts transaction with reason: "Deadlock found when trying to get lock; try restarting transaction" check just bare jid ---------------------------------------------------------------------- Helpers Lock keys in the same order to avoid deadlock
@author Michael < > ( C ) 2013 , Uvarov Michael @doc A backend for storing MAM preferencies using RDBMS . -module(mod_mam_rdbms_prefs). -behaviour(gen_mod). -export([start/2, stop/1, hooks/1, supported_features/0]). MAM hook handlers -behaviour(ejabberd_gen_mam_prefs). -export([get_behaviour/3, get_prefs/3, set_prefs/3, remove_archive/3]). -import(mongoose_rdbms, [prepare/4]). -include("mongoose.hrl"). -include("jlib.hrl"). -include_lib("exml/include/exml.hrl"). -spec start(mongooseim:host_type(), _) -> ok. start(HostType, _Opts) -> prepare_queries(HostType), ok. -spec stop(mongooseim:host_type()) -> ok. stop(_HostType) -> ok. -spec supported_features() -> [atom()]. supported_features() -> [dynamic_domains]. hooks(HostType) -> PM = gen_mod:get_module_opt(HostType, ?MODULE, pm, false), MUC = gen_mod:get_module_opt(HostType, ?MODULE, muc, false), maybe_pm_hooks(PM, HostType) ++ maybe_muc_hooks(MUC, HostType). maybe_pm_hooks(true, HostType) -> pm_hooks(HostType); maybe_pm_hooks(false, _HostType) -> []. maybe_muc_hooks(true, HostType) -> muc_hooks(HostType); maybe_muc_hooks(false, _HostType) -> []. pm_hooks(HostType) -> [{mam_get_behaviour, HostType, fun ?MODULE:get_behaviour/3, #{}, 50}, {mam_get_prefs, HostType, fun ?MODULE:get_prefs/3, #{}, 50}, {mam_set_prefs, HostType, fun ?MODULE:set_prefs/3, #{}, 50}, {mam_remove_archive, HostType, fun ?MODULE:remove_archive/3, #{}, 50}]. muc_hooks(HostType) -> [{mam_muc_get_behaviour, HostType, fun ?MODULE:get_behaviour/3, #{}, 50}, {mam_muc_get_prefs, HostType, fun ?MODULE:get_prefs/3, #{}, 50}, {mam_muc_set_prefs, HostType, fun ?MODULE:set_prefs/3, #{}, 50}, {mam_muc_remove_archive, HostType, fun ?MODULE:remove_archive/3, #{}, 50}]. prepare_queries(HostType) -> prepare(mam_prefs_insert, mam_config, [user_id, remote_jid, behaviour], <<"INSERT INTO mam_config(user_id, remote_jid, behaviour) " "VALUES (?, ?, ?)">>), prepare(mam_prefs_select, mam_config, [user_id], <<"SELECT remote_jid, behaviour " "FROM mam_config WHERE user_id=?">>), prepare(mam_prefs_select_behaviour, mam_config, [user_id, remote_jid], <<"SELECT remote_jid, behaviour " "FROM mam_config " "WHERE user_id=? " "AND (remote_jid='' OR remote_jid=?)">>), prepare(mam_prefs_select_behaviour2, mam_config, [user_id, remote_jid, remote_jid], <<"SELECT remote_jid, behaviour " "FROM mam_config " "WHERE user_id=? " "AND (remote_jid='' OR remote_jid=? OR remote_jid=?)">>), OrdBy = order_by_remote_jid_in_delete(HostType), prepare(mam_prefs_delete, mam_config, [user_id], <<"DELETE FROM mam_config WHERE user_id=?", OrdBy/binary>>), ok. order_by_remote_jid_in_delete(HostType) -> case mongoose_rdbms:db_engine(HostType) of mysql -> <<" ORDER BY remote_jid">>; _ -> <<>> end. Internal functions and callbacks -spec get_behaviour(Acc, Params, Extra) -> {ok, Acc} when Acc :: mod_mam:archive_behaviour(), Params :: ejabberd_gen_mam_prefs:get_behaviour_params(), Extra :: gen_hook:extra(). get_behaviour(DefaultBehaviour, #{archive_id := UserID, remote := RemJID}, #{host_type := HostType}) when is_integer(UserID) -> RemLJID = jid:to_lower(RemJID), BRemLBareJID = jid:to_bare_binary(RemLJID), BRemLJID = jid:to_binary(RemLJID), case query_behaviour(HostType, UserID, BRemLJID, BRemLBareJID) of {selected, []} -> {ok, DefaultBehaviour}; {selected, RemoteJid2Behaviour} -> DbBehaviour = choose_behaviour(BRemLJID, BRemLBareJID, RemoteJid2Behaviour), {ok, decode_behaviour(DbBehaviour)} end. -spec choose_behaviour(binary(), binary(), [{binary(), binary()}]) -> binary(). choose_behaviour(BRemLJID, BRemLBareJID, RemoteJid2Behaviour) -> case lists:keyfind(BRemLJID, 1, RemoteJid2Behaviour) of {_, Behaviour} -> Behaviour; false -> case lists:keyfind(BRemLBareJID, 1, RemoteJid2Behaviour) of {_, Behaviour} -> Behaviour; false -> Only one key remains {_, Behaviour} = lists:keyfind(<<>>, 1, RemoteJid2Behaviour), Behaviour end end. -spec set_prefs(Acc, Params, Extra) -> {ok, Acc} when Acc :: term(), Params :: ejabberd_gen_mam_prefs:set_prefs_params(), Extra :: gen_hook:extra(). set_prefs(_Result, #{archive_id := UserID, default_mode := DefaultMode, always_jids := AlwaysJIDs, never_jids := NeverJIDs}, #{host_type := HostType}) -> try {ok, set_prefs1(HostType, UserID, DefaultMode, AlwaysJIDs, NeverJIDs)} catch _Type:Error -> {ok, {error, Error}} end. set_prefs1(HostType, UserID, DefaultMode, AlwaysJIDs, NeverJIDs) -> Rows = prefs_to_rows(UserID, DefaultMode, AlwaysJIDs, NeverJIDs), mongoose_rdbms:transaction_with_delayed_retry(HostType, fun() -> {updated, _} = mongoose_rdbms:execute(HostType, mam_prefs_delete, [UserID]), [{updated, 1} = mongoose_rdbms:execute(HostType, mam_prefs_insert, Row) || Row <- Rows], ok end, #{user_id => UserID, retries => 5, delay => 100}), ok. -spec get_prefs(Acc, Params, Extra) -> {ok, Acc} when Acc :: mod_mam:preference(), Params :: ejabberd_gen_mam_prefs:get_prefs_params(), Extra :: gen_hook:extra(). get_prefs({GlobalDefaultMode, _, _}, #{archive_id := UserID}, #{host_type := HostType}) -> {selected, Rows} = mongoose_rdbms:execute(HostType, mam_prefs_select, [UserID]), {ok, decode_prefs_rows(Rows, GlobalDefaultMode, [], [])}. -spec remove_archive(Acc, Params, Extra) -> {ok, Acc} when Acc :: term(), Params :: #{archive_id := mod_mam:archive_id() | undefined, owner => jid:jid(), room => jid:jid()}, Extra :: gen_hook:extra(). remove_archive(Acc, #{archive_id := UserID}, #{host_type := HostType}) -> remove_archive(HostType, UserID), {ok, Acc}. remove_archive(HostType, UserID) -> {updated, _} = mongoose_rdbms:execute(HostType, mam_prefs_delete, [UserID]). -spec query_behaviour(HostType :: mongooseim:host_type(), UserID :: non_neg_integer(), BRemLJID :: binary(), BRemLBareJID :: binary() ) -> any(). query_behaviour(HostType, UserID, BRemLJID, BRemLJID) -> mongoose_rdbms:execute(HostType, mam_prefs_select_behaviour, query_behaviour(HostType, UserID, BRemLJID, BRemLBareJID) -> mongoose_rdbms:execute(HostType, mam_prefs_select_behaviour2, [UserID, BRemLJID, BRemLBareJID]). -spec encode_behaviour(always | never | roster) -> binary(). encode_behaviour(roster) -> <<"R">>; encode_behaviour(always) -> <<"A">>; encode_behaviour(never) -> <<"N">>. -spec decode_behaviour(binary()) -> always | never | roster. decode_behaviour(<<"R">>) -> roster; decode_behaviour(<<"A">>) -> always; decode_behaviour(<<"N">>) -> never. prefs_to_rows(UserID, DefaultMode, AlwaysJIDs, NeverJIDs) -> AlwaysRows = [[UserID, JID, encode_behaviour(always)] || JID <- AlwaysJIDs], NeverRows = [[UserID, JID, encode_behaviour(never)] || JID <- NeverJIDs], DefaultRow = [UserID, <<>>, encode_behaviour(DefaultMode)], [DefaultRow|lists:sort(AlwaysRows ++ NeverRows)]. -spec decode_prefs_rows([{binary() | jid:jid(), binary()}], DefaultMode :: mod_mam:archive_behaviour(), AlwaysJIDs :: [jid:literal_jid()], NeverJIDs :: [jid:literal_jid()]) -> {mod_mam:archive_behaviour(), [jid:literal_jid()], [jid:literal_jid()]}. decode_prefs_rows([{<<>>, Behaviour}|Rows], _DefaultMode, AlwaysJIDs, NeverJIDs) -> decode_prefs_rows(Rows, decode_behaviour(Behaviour), AlwaysJIDs, NeverJIDs); decode_prefs_rows([{JID, <<"A">>}|Rows], DefaultMode, AlwaysJIDs, NeverJIDs) -> decode_prefs_rows(Rows, DefaultMode, [JID|AlwaysJIDs], NeverJIDs); decode_prefs_rows([{JID, <<"N">>}|Rows], DefaultMode, AlwaysJIDs, NeverJIDs) -> decode_prefs_rows(Rows, DefaultMode, AlwaysJIDs, [JID|NeverJIDs]); decode_prefs_rows([], DefaultMode, AlwaysJIDs, NeverJIDs) -> {DefaultMode, AlwaysJIDs, NeverJIDs}.
c9475920d3f5dc15f91528e80175f29a0220ec256c9c021ad7e021919e8fcaa6
tpapp/cl-random
multivariate.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Coding : utf-8 -*- (in-package #:cl-random-tests) (deftestsuite multivariate-tests (cl-random-tests) ()) ;;; multivariate normal (addtest (multivariate-tests) multivariate-normal-pdf (let* ((a (dense 'lla-double (1 2) (3 4))) (v (mm t a)) (rv (r-multivariate-normal (vec 'lla-double 1 1) v)) (*lift-equality-test* (lambda (a b) (<= (abs (- a b)) 1d-6)))) ;; (ensure-same (cl-random::log-pdf-constant rv) ( - ( * ( v ) -0.5 ) ( log ( * 2 pi ) ) ) ) (ensure-same (pdf rv (vec 'lla-double 1 2)) 0.02279933) (ensure-same (pdf rv (vec 'lla-double 3 4)) 0.061975))) (addtest (multivariate-tests) multivariate-normal-draws (let ((rv (r-multivariate-normal (vec 'lla-double 1 2) (mm t (dense 'lla-double (1 2) (3 4)))))) (same-sample-mean-variance rv :n 100000))) ;; (time ( bind ( ( mean ( clo ' lla - double 3 4 ) ) ;; (variance (clo :hermitian 'lla-double ;; 3 0.5 :/ 0.5 2 ) ) ;; (rv (make-instance 'mv-normal :mean mean :variance variance)) ( matrix ( collect - rows 100000 ( lambda ( ) ( draw rv ) ) ' dense - matrix ) ) ;; ((:values sample-mean sample-variance) ;; (column-mean-variances matrix))) ;; (values sample-mean ;; sample-variance))) ;;; multivariate t (addtest (multivariate-tests) multivariate-t-pdf (let* ((sigma (mm t (dense 'lla-double (1 2) (3 4)))) (rv (r-multivariate-t (vec 'lla-double 0 0) sigma 8)) (*lift-equality-test* (lambda (a b) (<= (abs (- a b)) 1d-6)))) (ensure-same (log-pdf rv (vec 'lla-double 0 0)) -2.531024) (ensure-same (log-pdf rv (vec 'lla-double 1 2)) -3.119939) (ensure-same (pdf rv (vec 'lla-double 3 4)) 0.04415984))) (addtest (multivariate-tests) multivariate-normal-draws (let ((rv (r-multivariate-t (vec 'lla-double 1 2) (mm t (dense 'lla-double (1 2) (3 4))) 4d0))) (same-sample-mean-variance rv :n 100000))) ;; (time ;; (bind ((mean (clo 3 4)) ;; (sigma (clo :hermitian ;; 1 0.5 :/ 0.5 1 ) ) ( rv ( make - instance ' mv - t : mean mean : sigma sigma : nu 10 ) ) ( matrix ( collect - rows 100000 ( lambda ( ) ( draw rv ) ) ' dense - matrix ) ) ;; ((:values sample-mean sample-variance) ;; (column-mean-variances matrix))) ;; (values sample-mean ;; sample-variance))) ;; ;;; !!! Currently, results from the code below are just "eyeballed", ;; ;;; they need to be incorporated into the unit testing framework ; ; ; -- Tamas ;; ;;; Wishart (addtest (multivariate-tests) wishart-draws (let* ((rv (r-wishart 7 (mm (dense 'lla-double (1 2) (3 4)) t))) (sample (generate-array 50000 (compose #'as-array (generator rv)))) (sample-mean (mean sample))) (ensure (< (relative-difference sample-mean (mean rv)) 0.01)))) (addtest (multivariate-tests) inverse-wishart-draws (let* ((rv (r-inverse-wishart 7 (mm (dense 'lla-double (1 2) (3 4)) t))) (sample (generate-array 50000 (compose #'as-array (generator rv)))) (sample-mean (mean sample))) (ensure (< (relative-difference sample-mean (mean rv)) 0.01)) (values sample-mean (mean rv)))) ( mean ( vector ( draw ( r - inverse - wishart 7 ( ( dense ' lla - double ( 1 2 ) ( 3 4 ) ) ;; t))))) ( bind ( ( nu 400 ) ( S ( mm t ( clo : dense 1 2 :/ 3 4 ) ) ) ( ( make - instance ' wishart : nu nu : scale S ) ) ( draws ( xcollect 10000 ( lambda ( ) ( as ' numeric - vector ( draw rv ) ) ) ) ) ;; ((:values mean variance) (matrix-mean-variance draws))) ( defparameter * rv * ) ( x - rel - diff ( mean ) ( reshape mean 2 2 ) ) ) ; ; ( values ( x- ( reshape mean 2 2 ) ( mean ) ) ; ; ( xmap t # ' abs ( mean ) ) ) ) ; ; ; Inverse Wishart ;; (bind ((nu 500) ( S ( mm t ( x * 1000 ( clo : dense 1 2 :/ 9 4 ) ) ) ) ( ( make - instance ' inverse - wishart : nu nu : inverse - scale S ) ) ( draws ( xcollect 10000 ( lambda ( ) ( as ' numeric - vector ( draw rv ) ) ) ) ) ;; ((:values mean variance) (matrix-mean-variance draws))) ( x - rel - diff ( mean ) ( reshape mean 2 2 ) ) )
null
https://raw.githubusercontent.com/tpapp/cl-random/5bb65911037f95a4260bd29a594a09df3849f4ea/tests/multivariate.lisp
lisp
Syntax : ANSI - Common - Lisp ; Coding : utf-8 -*- multivariate normal (ensure-same (cl-random::log-pdf-constant rv) (time (variance (clo :hermitian 'lla-double 3 0.5 :/ (rv (make-instance 'mv-normal :mean mean :variance variance)) ((:values sample-mean sample-variance) (column-mean-variances matrix))) (values sample-mean sample-variance))) multivariate t (time (bind ((mean (clo 3 4)) (sigma (clo :hermitian 1 0.5 :/ ((:values sample-mean sample-variance) (column-mean-variances matrix))) (values sample-mean sample-variance))) ;;; !!! Currently, results from the code below are just "eyeballed", ;;; they need to be incorporated into the unit testing framework ; ; -- Tamas ;;; Wishart t))))) ((:values mean variance) (matrix-mean-variance draws))) ; ( values ( x- ( reshape mean 2 2 ) ( mean ) ) ; ( xmap t # ' abs ( mean ) ) ) ) ; ; Inverse Wishart (bind ((nu 500) ((:values mean variance) (matrix-mean-variance draws)))
(in-package #:cl-random-tests) (deftestsuite multivariate-tests (cl-random-tests) ()) (addtest (multivariate-tests) multivariate-normal-pdf (let* ((a (dense 'lla-double (1 2) (3 4))) (v (mm t a)) (rv (r-multivariate-normal (vec 'lla-double 1 1) v)) (*lift-equality-test* (lambda (a b) (<= (abs (- a b)) 1d-6)))) ( - ( * ( v ) -0.5 ) ( log ( * 2 pi ) ) ) ) (ensure-same (pdf rv (vec 'lla-double 1 2)) 0.02279933) (ensure-same (pdf rv (vec 'lla-double 3 4)) 0.061975))) (addtest (multivariate-tests) multivariate-normal-draws (let ((rv (r-multivariate-normal (vec 'lla-double 1 2) (mm t (dense 'lla-double (1 2) (3 4)))))) (same-sample-mean-variance rv :n 100000))) ( bind ( ( mean ( clo ' lla - double 3 4 ) ) 0.5 2 ) ) ( matrix ( collect - rows 100000 ( lambda ( ) ( draw rv ) ) ' dense - matrix ) ) (addtest (multivariate-tests) multivariate-t-pdf (let* ((sigma (mm t (dense 'lla-double (1 2) (3 4)))) (rv (r-multivariate-t (vec 'lla-double 0 0) sigma 8)) (*lift-equality-test* (lambda (a b) (<= (abs (- a b)) 1d-6)))) (ensure-same (log-pdf rv (vec 'lla-double 0 0)) -2.531024) (ensure-same (log-pdf rv (vec 'lla-double 1 2)) -3.119939) (ensure-same (pdf rv (vec 'lla-double 3 4)) 0.04415984))) (addtest (multivariate-tests) multivariate-normal-draws (let ((rv (r-multivariate-t (vec 'lla-double 1 2) (mm t (dense 'lla-double (1 2) (3 4))) 4d0))) (same-sample-mean-variance rv :n 100000))) 0.5 1 ) ) ( rv ( make - instance ' mv - t : mean mean : sigma sigma : nu 10 ) ) ( matrix ( collect - rows 100000 ( lambda ( ) ( draw rv ) ) ' dense - matrix ) ) (addtest (multivariate-tests) wishart-draws (let* ((rv (r-wishart 7 (mm (dense 'lla-double (1 2) (3 4)) t))) (sample (generate-array 50000 (compose #'as-array (generator rv)))) (sample-mean (mean sample))) (ensure (< (relative-difference sample-mean (mean rv)) 0.01)))) (addtest (multivariate-tests) inverse-wishart-draws (let* ((rv (r-inverse-wishart 7 (mm (dense 'lla-double (1 2) (3 4)) t))) (sample (generate-array 50000 (compose #'as-array (generator rv)))) (sample-mean (mean sample))) (ensure (< (relative-difference sample-mean (mean rv)) 0.01)) (values sample-mean (mean rv)))) ( mean ( vector ( draw ( r - inverse - wishart 7 ( ( dense ' lla - double ( 1 2 ) ( 3 4 ) ) ( bind ( ( nu 400 ) ( S ( mm t ( clo : dense 1 2 :/ 3 4 ) ) ) ( ( make - instance ' wishart : nu nu : scale S ) ) ( draws ( xcollect 10000 ( lambda ( ) ( as ' numeric - vector ( draw rv ) ) ) ) ) ( defparameter * rv * ) ( x - rel - diff ( mean ) ( reshape mean 2 2 ) ) ) ( S ( mm t ( x * 1000 ( clo : dense 1 2 :/ 9 4 ) ) ) ) ( ( make - instance ' inverse - wishart : nu nu : inverse - scale S ) ) ( draws ( xcollect 10000 ( lambda ( ) ( as ' numeric - vector ( draw rv ) ) ) ) ) ( x - rel - diff ( mean ) ( reshape mean 2 2 ) ) )
d16e9ed5732f9b46d326b1a84a37075b53b80a528c26cbd09d9eb85080043f91
racket/eopl
reader.rkt
#lang s-exp syntax/module-reader eopl #:language-info '#(scheme/language-info get-info #f)
null
https://raw.githubusercontent.com/racket/eopl/43575d6e95dc34ca6e49b305180f696565e16e0f/lang/reader.rkt
racket
#lang s-exp syntax/module-reader eopl #:language-info '#(scheme/language-info get-info #f)
2e5ccb4c4ff960cd67167699089edb60a0ebb0717b8f2733500ed6da4069899f
cgoldammer/haskell-chess
LogicTest.hs
module LogicTest (logicTests) where import Control.Lens hiding ((.=)) import Test.HUnit import qualified Data.Set as S import qualified Data.Text as Te import Data.Maybe import qualified Data.Either.Combinators as EitherC import Chess.Algorithms import Chess.Board import Chess.Logic rookPosition = Field A R1 possibleRookMoves = ["A2", "A7", "B1", "H1"] impossibleRookMoves = ["A1", "B2"] allRookMoves = concat $ pieceFields $ PieceField Rook White rookPosition knightPosition = Field A R1 possibleKnightMoves = ["B3", "C2"] impossibleKnightMoves = ["A1", "B2"] allKnightMoves = concat $ pieceFields $ PieceField Knight White knightPosition bishopPosition = Field B R2 possibleBishopMoves = ["A1", "C3", "C1", "H8"] impossibleBishopMoves = ["B1", "B2"] allBishopMoves = concat $ pieceFields $ PieceField Bishop White bishopPosition intersect :: Ord a => [a] -> [a] -> S.Set a intersect l1 l2 = S.intersection (S.fromList l1) (S.fromList l2) testFromString :: String -> [String] -> [String] -> [Field] -> [Test] testFromString name possible impossible all = testPossible name posPossible posImpossible all where [posPossible, posImpossible] = fmap (\strings -> (catMaybes (fmap stringToField strings))) [possible, impossible] testPossible :: (Ord a, Show a) => String -> [a] -> [a] -> [a] -> [Test] testPossible name possible impossible all = [testPossible, testImpossible] where testPossible = TestCase (assertBool possibleMessage conditionPossible) testImpossible = TestCase (assertBool impossibleMessage conditionImpossible) conditionPossible = length intersectionPossible == length possible conditionImpossible = length intersectionImpossible == 0 [intersectionPossible, intersectionImpossible] = fmap (\v -> intersect v all) [possible, impossible] possibleMessage = name ++ " possible moves: " ++ (show possible) impossibleMessage = name ++ " impossible moves: " ++ (show intersectionPossible) knightTests = testFromString "knight" possibleKnightMoves impossibleKnightMoves allKnightMoves rookTests = testFromString "rook" possibleRookMoves impossibleRookMoves allRookMoves bishopTests = testFromString "bishop" possibleBishopMoves impossibleBishopMoves allBishopMoves possibleTests = knightTests ++ rookTests ++ bishopTests matePositions = [["WKA1", "BQA2", "BKA3"], ["WKA1", "BRA8", "BRB8", "BKC8"]] nonMatePositions = [["WKA1", "BRA8", "BRB8", "BKB4"]] mateTest gs = TestCase (assertBool mateMessage (isMate gs)) where mateMessage = "This should be mate, but isn't: " ++ (show gs) nonMateTest gs = TestCase (assertBool mateMessage (not (isMate gs))) where mateMessage = "This should not be mate, but is: " ++ (show gs) toGameState :: Position -> GameState toGameState ps = defaultGameState ps White toGameStateNoCastle :: Position -> GameState toGameStateNoCastle ps = defaultGameStateNoCastle ps White mates = fmap toGameStateNoCastle $ catMaybes (fmap stringToPosition matePositions) nonMates = fmap toGameStateNoCastle $ catMaybes (fmap stringToPosition nonMatePositions) allNextFields = [] movesTest expected ps = TestCase (assertBool errorMessage (movesCalculated == movesExpected)) where movesCalculated = S.fromList $ allLegalMoves ps movesExpected = S.fromList expected errorMessage = "Position: " ++ show ps ++ " Expected: " ++ show movesExpected ++ " but got: " ++ show movesCalculated movesTests = fmap (\m -> ("No moves in " ++ show m) ~: movesTest allNextFields m) mates mateTests = fmap mateTest mates ++ fmap nonMateTest nonMates conditionHolds :: (GameState -> Bool) -> String -> GameState -> Test conditionHolds fn name gs = TestCase (assertBool (name ++ ": " ++ show gs) (fn gs)) checkTests = fmap (conditionHolds inCheck "Should be in check, but isn't") (mates ++ nonMates) isCheckTests = fmap (conditionHolds (not . isChecking) "Should not be checking, but is") (mates ++ nonMates) oppMoves :: [Field] oppMoves = fmap ((view moveTo) . snd) $ allOpponentMoves $ mates !! 0 oppMoveTest = TestCase $ assertBool (show oppMoves) ((fromJust (stringToField "A1")) `elem` oppMoves) pawnPosition = ["WKA1", "WPE4", "WPD2", "WPC2", "BKA8", "BPD4", "BPD5"] pawnP = catMaybes (fmap stringToPieceField pawnPosition) whiteGS = defaultGameState pawnP White pawnTestWhite = testFromString "white pawns" ["C3", "C4", "D3", "E5", "D5"] [] $ pawnToFields whiteGS blackGS = invertGameStateColor whiteGS pawnTestBlack = testFromString "black pawns" ["E4", "D3"] ["E3"] $ pawnToFields blackGS blackGSEP = GameState pawnP Black castleNone (Just (Field E R3)) 0 1 pawnTestBlackEP = testFromString "black pawns" ["E4", "D3", "E3"] [] $ pawnToFields blackGSEP promotePos = catMaybes $ fmap stringToPieceField ["WKA1", "WPE7", "BKA8", "BRF8", "WKE8"] promoteGS = defaultGameState promotePos White expectedPawnMoves = [PromotionMove (Field E R7) (Field F R8) piece | piece <- allNonKingFullPieces] allPawnMoves = pawnToMoves promoteGS pawnTestPromote = testPossible "promotion" expectedPawnMoves [] allPawnMoves pawnToFields :: GameState -> [Field] pawnToFields gs = fmap (view moveTo) $ pawnToMoves gs pawnToMoves :: GameState -> [Move] pawnToMoves gs = [mv | (_, mv) <- allLegalMoves gs, (mv ^. moveFrom) `elem` (getPositions gs Pawn)] pawnTests = TestList [ "white" ~: pawnTestWhite , "black" ~: pawnTestBlack , "en passant" ~: pawnTestBlackEP , "promote" ~: pawnTestPromote] -- all castling combinations should be possible, thus depend on the gamestate castling rights. posCastleBoth = fromJust $ stringToPosition ["WRA1", "WKE1", "WRH1", "BKG8"] gsCastleBoth = toGameState posCastleBoth testCastleBoth = TestCase $ assertEqual error (S.fromList movesExpected) intersection where error = "Both castling moves should be possible for white" intersection = intersect possible movesExpected possible = allLegalMoves gsCastleBoth movesExpected = catMaybes $ fmap (stringToMove gsCastleBoth) ["E1C1", "E1G1"] posCastleBothBlack = fromJust $ stringToPosition ["WKE1", "BKE8", "BKA8", "BRH8"] gsCastleBothBlack = invertGameStateColor $ toGameState posCastleBothBlack testCastleBothBlack = TestCase $ assertEqual error (S.fromList movesExpected) intersection where error = "Both castling moves should be possible for black" intersection = intersect possible movesExpected possible = allLegalMoves gsCastleBothBlack movesExpected = catMaybes $ fmap (stringToMove gsCastleBothBlack) ["E8C8", "E8G8"] castleDestroyedData = [ ( " A1D1 " , CastlingData True False ) , ( " H1H2 " , CastlingData False True ) ] testCastleDestroyed move expectedState = TestCase $ assertEqual error expectedState actualState -- where error = "Moving a rook should destroy castling rights on that side" -- gsNew = after white castles kingside ( queenside ) , the rook is on f1 ( c1 ) testRookField mv expectedField = TestCase $ assertEqual error (S.fromList expectedFields) intersection where error = "Rook expected on: " expectedFields = [fromJust (stringToField expectedField)] intersection = intersect fields expectedFields gsAfterCastle = uncurry (move gsCastleBoth) $ fromJust (stringToMove gsCastleBoth mv) fields = fmap (view pfField) $ gsAfterCastle ^. gsPosition testRookFields = [ testRookField "E1G1" "F1" , testRookField "E1C1" "C1"] gsWithCastling :: Position -> Color -> CastlingRights -> GameState gsWithCastling ps color cr = GameState ps color cr Nothing 0 1 testCastleSide cr mv = TestCase $ assertEqual error (S.fromList movesExpected) intersection where error = "Exactly one castle should be possible" ++ show gsCastleOne ++ " | All moves: " ++ show kingFields movesExpected = fmap snd $ catMaybes $ fmap (stringToMove gsCastleOne) [mv] gsCastleOne = gsWithCastling posCastleBoth White cr possible = fmap snd $ allLegalMoves gsCastleOne intersection = intersect possible movesExpected kingFields = fmap ((view moveTo) . snd) $ filter (\m -> fst m == King) $ allLegalMoves gsCastleOne crKing = PlayerData (CastlingData True False) (CastlingData False False) crQueen = PlayerData (CastlingData False True) (CastlingData False False) testCastleOneSide = [ testCastleSide crKing "E1G1", testCastleSide crQueen "E1C1"] Queenside castling is allowed , kingside castling is not ( because of rook on f8 ) posCastleQueen = fromJust $ stringToPosition ["WRA1", "WKE1", "WRH1", "BKG8", "BRF8"] gsCastleQueen = toGameState posCastleBoth testCastleQueen = TestCase $ assertEqual error (S.fromList movesExpected) intersection where error = "Only queenside castle should be possible" intersection = intersect possible movesExpected possible = fmap snd $ allLegalMoves gsCastleQueen movesExpected = fmap snd $ catMaybes $ fmap (stringToMove gsCastleQueen) ["E1C1"] testLosesRight mvs mvExpected = TestCase $ assertEqual error movesExpected difference where error = "Check that some castling rights are lost after moving: " ++ show mvs movesExpected = S.fromList $ catMaybes $ fmap (stringToMove gsCastleBoth) mvExpected difference = S.difference movesBefore movesAfter movesAfter = S.fromList $ allLegalMoves newState movesBefore = S.fromList $ allLegalMoves gsCastleBoth newState = newStateFromMoves gsCastleBoth mvs testsLosesRight = [ testLosesRight ["E1F1", "G8F8", "F1E1", "F8G8"] ["E1G1", "E1C1"] , testLosesRight ["A1A2", "G8F8", "A2A1", "F8G8"] ["E1C1"] , testLosesRight ["H1H2", "G8F8", "H2H1", "F8G8"] ["E1G1"]] -- After a promotion, the initial pawn disappears stringToGs = toGameStateNoCastle . fromJust . stringToPosition -- White to move can take ep iff the gamestate has an ep pawn on e5. If it 's black 's move , white can take ep on c6 ( and only c6 ) iff black plays c5 . gsEp = stringToGs ["WKA1", "BKA8", "WPC2", "WPE2", "BPD4"] testEp mvs mvExpected error = TestCase $ assertEqual error (S.fromList movesExpected) intersection where movesExpected = catMaybes $ fmap (stringToMove newState) mvExpected -- [Move] intersection = intersect possible movesExpected possible = filter (\mp -> fst mp == Pawn) $ allLegalMoves newState newState = newStateFromMoves gsEp mvs testsEp = [ testEp ["C2C4"] ["D4D3", "D4C3"] "Can take the c-pawn en passant" , testEp ["E2E4"] ["D4D3", "D4E3"] "Can take the d-pawn en passant" , testEp ["E2E4", "A8B8", "A1B1"] ["D4D3"] "Cannot take the c-pawn after intermediate moves"] ownPieces :: GameState -> Piece -> [Field] ownPieces gs p = fmap (view pfField) $ filter ((==p) . (view pfPiece)) $ ownPieceFields gs newStateFromMoves :: GameState -> [String] -> GameState newStateFromMoves gs mvs = last $ gameStates $ fromJust $ EitherC.rightToMaybe game where game = gameFromString stringToMove gs mvs fieldsFromString s = fmap (fromJust . stringToField) s testEpDisappears = TestCase $ assertEqual error intersection (S.fromList whiteFields) where intersection = intersect whiteFields fieldsExpected newState = newStateFromMoves gsEp ["C2C4", "D4C3"] whiteFields = ownPieces newState Pawn fieldsExpected = fieldsFromString ["E2"] error = "Pawn that is taken ep disappears - incorrect GameState: " ++ show newState gsPromote = stringToGs ["WKA1", "BKA8", "WPG7"] testPromotionPawnDisappears = TestCase $ assertEqual error (S.fromList fieldsExpected) intersection where intersection = intersect whiteFields fieldsExpected newState = invertGameStateColor $ newStateFromMoves gsPromote ["G7G8N"] whiteFields = ownPieces newState Pawn fieldsExpected = [] error = "Pawn that promotes disappears" ++ show newState testPromotionNewPiece = TestCase $ assertEqual error (S.fromList fieldsExpected) intersection where intersection = intersect whiteFields fieldsExpected newState = invertGameStateColor $ newStateFromMoves gsPromote ["G7G8N"] whiteFields = ownPieces newState Knight fieldsExpected = fieldsFromString ["G8"] error = "New knight has appeared: " ++ show newState -- You can promote by taking. gsPromoteTake = stringToGs ["WKA1", "BKA8", "WPG7", "BNH8"] testPromotionTake = TestCase $ assertEqual error (S.fromList fieldsExpected) intersection where intersection = intersect whiteFields fieldsExpected newState = newStateFromMoves gsPromoteTake ["G7H8N"] whiteFields = ownPieces newState Knight fieldsExpected = fieldsFromString [] error = "The knight should be taken: " ++ show newState legalMoveData = [ (["WKA1", "BKA8"], ["A1A2", "A1B1", "A1B2"], ["A1B3"]) , (["WKA1", "BKA8", "BRB7"], ["A1A2"], ["A1B2"]) , (["WKA1", "BKA8", "WQA2", "BRA7"], ["A2A3"], ["A1A2", "A2B2", "A2A8"]) , (["WKA1", "BKA8", "WQB2", "BRA7"], ["B2A3"], ["B2B3", "B2A1"]) , (["WKA1", "BKA8", "BRA7", "BBH8"], ["A1B1"], ["A1B2", "A1B2"]) , (["WKA1", "BKA8", "BBE3", "WPD2", "WPE2"], ["D2E3"], ["E2E3", "E2E4"]) , (["WKA1", "BKA8", "BRA7", "WPA3", "BPB4"], ["A3A4"], ["A3B4"])] legalMoveTest gsString legalMoves = (S.fromList expected) ~=? actual where actual = intersect expected legal gs = stringToGs gsString expected = fmap (snd . fromJust . (stringToMove gs)) legalMoves legal = fmap snd $ allLegalMoves gs illegalMoveTest gsString illegalMoves = expected ~=? actual where expected = fmap (snd . fromJust . (stringToMove gs)) illegalMoves gs = stringToGs gsString legalMoves = fmap snd $ allLegalMoves gs actual = filter (\m -> not (m `elem` legalMoves)) expected fensToConvert = [ "fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" , "fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1" , "fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b kq - 0 1" , "fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b - - 20 1" , "fen rnbqkbnr/ppp2ppp/4p3/3pP3/8/8/PPPP1PPP/RNBQKBNR w KQkq d6 1 1"] -- If I take a fen, convert it to a gamestate, and then back to a fen, I should get the -- initial fen back. fenDoubleConvertTest f = Just f ~=? fmap gameStateToFen (fenToGameState f) fenDoubleConvertTests = TestList $ fmap fenDoubleConvertTest fensToConvert legalMoveTests = ["Test legal moves are right" ~: legalMoveTest f s | (f, s, _) <- legalMoveData] illegalMoveTests = ["Test illegal moves are right" ~: illegalMoveTest f t | (f, _, t) <- legalMoveData] singleTests = [ "Opponent Move test" ~: oppMoveTest , "Pawn that is taken en passant disappears" ~: testEpDisappears , "Castling Queen" ~: testCastleQueen , "Castling Both black" ~: testCastleBothBlack , "Pawn that promotes disappears" ~: testPromotionPawnDisappears , "Promoting pawn creates piece" ~: testPromotionNewPiece , "Promoting can happen by taking" ~: testPromotionTake , "Castling Both" ~: testCastleBoth] logicTests = TestList [ "Check tests" ~: checkTests , "is check tests" ~: isCheckTests , "mate tests" ~: mateTests , "pawn tests" ~: pawnTests , "single tests" ~: singleTests , "castle one side" ~: testCastleOneSide , "rook fields" ~: testRookFields , "losing castling rights" ~: testsLosesRight , "En passant" ~: testsEp , "Legal moves" ~: legalMoveTests , "illegal moves" ~: illegalMoveTests , "moves" ~: movesTests , "possible" ~: possibleTests , "fen double conversion" ~: fenDoubleConvertTests ]
null
https://raw.githubusercontent.com/cgoldammer/haskell-chess/6611a29db74e80ca10f1b3122495a0f83abcb337/test/LogicTest.hs
haskell
all castling combinations should be possible, thus depend on the gamestate castling rights. where error = "Moving a rook should destroy castling rights on that side" gsNew = After a promotion, the initial pawn disappears White to move can take ep iff the gamestate has an ep pawn on e5. [Move] You can promote by taking. If I take a fen, convert it to a gamestate, and then back to a fen, I should get the initial fen back.
module LogicTest (logicTests) where import Control.Lens hiding ((.=)) import Test.HUnit import qualified Data.Set as S import qualified Data.Text as Te import Data.Maybe import qualified Data.Either.Combinators as EitherC import Chess.Algorithms import Chess.Board import Chess.Logic rookPosition = Field A R1 possibleRookMoves = ["A2", "A7", "B1", "H1"] impossibleRookMoves = ["A1", "B2"] allRookMoves = concat $ pieceFields $ PieceField Rook White rookPosition knightPosition = Field A R1 possibleKnightMoves = ["B3", "C2"] impossibleKnightMoves = ["A1", "B2"] allKnightMoves = concat $ pieceFields $ PieceField Knight White knightPosition bishopPosition = Field B R2 possibleBishopMoves = ["A1", "C3", "C1", "H8"] impossibleBishopMoves = ["B1", "B2"] allBishopMoves = concat $ pieceFields $ PieceField Bishop White bishopPosition intersect :: Ord a => [a] -> [a] -> S.Set a intersect l1 l2 = S.intersection (S.fromList l1) (S.fromList l2) testFromString :: String -> [String] -> [String] -> [Field] -> [Test] testFromString name possible impossible all = testPossible name posPossible posImpossible all where [posPossible, posImpossible] = fmap (\strings -> (catMaybes (fmap stringToField strings))) [possible, impossible] testPossible :: (Ord a, Show a) => String -> [a] -> [a] -> [a] -> [Test] testPossible name possible impossible all = [testPossible, testImpossible] where testPossible = TestCase (assertBool possibleMessage conditionPossible) testImpossible = TestCase (assertBool impossibleMessage conditionImpossible) conditionPossible = length intersectionPossible == length possible conditionImpossible = length intersectionImpossible == 0 [intersectionPossible, intersectionImpossible] = fmap (\v -> intersect v all) [possible, impossible] possibleMessage = name ++ " possible moves: " ++ (show possible) impossibleMessage = name ++ " impossible moves: " ++ (show intersectionPossible) knightTests = testFromString "knight" possibleKnightMoves impossibleKnightMoves allKnightMoves rookTests = testFromString "rook" possibleRookMoves impossibleRookMoves allRookMoves bishopTests = testFromString "bishop" possibleBishopMoves impossibleBishopMoves allBishopMoves possibleTests = knightTests ++ rookTests ++ bishopTests matePositions = [["WKA1", "BQA2", "BKA3"], ["WKA1", "BRA8", "BRB8", "BKC8"]] nonMatePositions = [["WKA1", "BRA8", "BRB8", "BKB4"]] mateTest gs = TestCase (assertBool mateMessage (isMate gs)) where mateMessage = "This should be mate, but isn't: " ++ (show gs) nonMateTest gs = TestCase (assertBool mateMessage (not (isMate gs))) where mateMessage = "This should not be mate, but is: " ++ (show gs) toGameState :: Position -> GameState toGameState ps = defaultGameState ps White toGameStateNoCastle :: Position -> GameState toGameStateNoCastle ps = defaultGameStateNoCastle ps White mates = fmap toGameStateNoCastle $ catMaybes (fmap stringToPosition matePositions) nonMates = fmap toGameStateNoCastle $ catMaybes (fmap stringToPosition nonMatePositions) allNextFields = [] movesTest expected ps = TestCase (assertBool errorMessage (movesCalculated == movesExpected)) where movesCalculated = S.fromList $ allLegalMoves ps movesExpected = S.fromList expected errorMessage = "Position: " ++ show ps ++ " Expected: " ++ show movesExpected ++ " but got: " ++ show movesCalculated movesTests = fmap (\m -> ("No moves in " ++ show m) ~: movesTest allNextFields m) mates mateTests = fmap mateTest mates ++ fmap nonMateTest nonMates conditionHolds :: (GameState -> Bool) -> String -> GameState -> Test conditionHolds fn name gs = TestCase (assertBool (name ++ ": " ++ show gs) (fn gs)) checkTests = fmap (conditionHolds inCheck "Should be in check, but isn't") (mates ++ nonMates) isCheckTests = fmap (conditionHolds (not . isChecking) "Should not be checking, but is") (mates ++ nonMates) oppMoves :: [Field] oppMoves = fmap ((view moveTo) . snd) $ allOpponentMoves $ mates !! 0 oppMoveTest = TestCase $ assertBool (show oppMoves) ((fromJust (stringToField "A1")) `elem` oppMoves) pawnPosition = ["WKA1", "WPE4", "WPD2", "WPC2", "BKA8", "BPD4", "BPD5"] pawnP = catMaybes (fmap stringToPieceField pawnPosition) whiteGS = defaultGameState pawnP White pawnTestWhite = testFromString "white pawns" ["C3", "C4", "D3", "E5", "D5"] [] $ pawnToFields whiteGS blackGS = invertGameStateColor whiteGS pawnTestBlack = testFromString "black pawns" ["E4", "D3"] ["E3"] $ pawnToFields blackGS blackGSEP = GameState pawnP Black castleNone (Just (Field E R3)) 0 1 pawnTestBlackEP = testFromString "black pawns" ["E4", "D3", "E3"] [] $ pawnToFields blackGSEP promotePos = catMaybes $ fmap stringToPieceField ["WKA1", "WPE7", "BKA8", "BRF8", "WKE8"] promoteGS = defaultGameState promotePos White expectedPawnMoves = [PromotionMove (Field E R7) (Field F R8) piece | piece <- allNonKingFullPieces] allPawnMoves = pawnToMoves promoteGS pawnTestPromote = testPossible "promotion" expectedPawnMoves [] allPawnMoves pawnToFields :: GameState -> [Field] pawnToFields gs = fmap (view moveTo) $ pawnToMoves gs pawnToMoves :: GameState -> [Move] pawnToMoves gs = [mv | (_, mv) <- allLegalMoves gs, (mv ^. moveFrom) `elem` (getPositions gs Pawn)] pawnTests = TestList [ "white" ~: pawnTestWhite , "black" ~: pawnTestBlack , "en passant" ~: pawnTestBlackEP , "promote" ~: pawnTestPromote] posCastleBoth = fromJust $ stringToPosition ["WRA1", "WKE1", "WRH1", "BKG8"] gsCastleBoth = toGameState posCastleBoth testCastleBoth = TestCase $ assertEqual error (S.fromList movesExpected) intersection where error = "Both castling moves should be possible for white" intersection = intersect possible movesExpected possible = allLegalMoves gsCastleBoth movesExpected = catMaybes $ fmap (stringToMove gsCastleBoth) ["E1C1", "E1G1"] posCastleBothBlack = fromJust $ stringToPosition ["WKE1", "BKE8", "BKA8", "BRH8"] gsCastleBothBlack = invertGameStateColor $ toGameState posCastleBothBlack testCastleBothBlack = TestCase $ assertEqual error (S.fromList movesExpected) intersection where error = "Both castling moves should be possible for black" intersection = intersect possible movesExpected possible = allLegalMoves gsCastleBothBlack movesExpected = catMaybes $ fmap (stringToMove gsCastleBothBlack) ["E8C8", "E8G8"] castleDestroyedData = [ ( " A1D1 " , CastlingData True False ) , ( " H1H2 " , CastlingData False True ) ] testCastleDestroyed move expectedState = TestCase $ assertEqual error expectedState actualState after white castles kingside ( queenside ) , the rook is on f1 ( c1 ) testRookField mv expectedField = TestCase $ assertEqual error (S.fromList expectedFields) intersection where error = "Rook expected on: " expectedFields = [fromJust (stringToField expectedField)] intersection = intersect fields expectedFields gsAfterCastle = uncurry (move gsCastleBoth) $ fromJust (stringToMove gsCastleBoth mv) fields = fmap (view pfField) $ gsAfterCastle ^. gsPosition testRookFields = [ testRookField "E1G1" "F1" , testRookField "E1C1" "C1"] gsWithCastling :: Position -> Color -> CastlingRights -> GameState gsWithCastling ps color cr = GameState ps color cr Nothing 0 1 testCastleSide cr mv = TestCase $ assertEqual error (S.fromList movesExpected) intersection where error = "Exactly one castle should be possible" ++ show gsCastleOne ++ " | All moves: " ++ show kingFields movesExpected = fmap snd $ catMaybes $ fmap (stringToMove gsCastleOne) [mv] gsCastleOne = gsWithCastling posCastleBoth White cr possible = fmap snd $ allLegalMoves gsCastleOne intersection = intersect possible movesExpected kingFields = fmap ((view moveTo) . snd) $ filter (\m -> fst m == King) $ allLegalMoves gsCastleOne crKing = PlayerData (CastlingData True False) (CastlingData False False) crQueen = PlayerData (CastlingData False True) (CastlingData False False) testCastleOneSide = [ testCastleSide crKing "E1G1", testCastleSide crQueen "E1C1"] Queenside castling is allowed , kingside castling is not ( because of rook on f8 ) posCastleQueen = fromJust $ stringToPosition ["WRA1", "WKE1", "WRH1", "BKG8", "BRF8"] gsCastleQueen = toGameState posCastleBoth testCastleQueen = TestCase $ assertEqual error (S.fromList movesExpected) intersection where error = "Only queenside castle should be possible" intersection = intersect possible movesExpected possible = fmap snd $ allLegalMoves gsCastleQueen movesExpected = fmap snd $ catMaybes $ fmap (stringToMove gsCastleQueen) ["E1C1"] testLosesRight mvs mvExpected = TestCase $ assertEqual error movesExpected difference where error = "Check that some castling rights are lost after moving: " ++ show mvs movesExpected = S.fromList $ catMaybes $ fmap (stringToMove gsCastleBoth) mvExpected difference = S.difference movesBefore movesAfter movesAfter = S.fromList $ allLegalMoves newState movesBefore = S.fromList $ allLegalMoves gsCastleBoth newState = newStateFromMoves gsCastleBoth mvs testsLosesRight = [ testLosesRight ["E1F1", "G8F8", "F1E1", "F8G8"] ["E1G1", "E1C1"] , testLosesRight ["A1A2", "G8F8", "A2A1", "F8G8"] ["E1C1"] , testLosesRight ["H1H2", "G8F8", "H2H1", "F8G8"] ["E1G1"]] stringToGs = toGameStateNoCastle . fromJust . stringToPosition If it 's black 's move , white can take ep on c6 ( and only c6 ) iff black plays c5 . gsEp = stringToGs ["WKA1", "BKA8", "WPC2", "WPE2", "BPD4"] testEp mvs mvExpected error = TestCase $ assertEqual error (S.fromList movesExpected) intersection intersection = intersect possible movesExpected possible = filter (\mp -> fst mp == Pawn) $ allLegalMoves newState newState = newStateFromMoves gsEp mvs testsEp = [ testEp ["C2C4"] ["D4D3", "D4C3"] "Can take the c-pawn en passant" , testEp ["E2E4"] ["D4D3", "D4E3"] "Can take the d-pawn en passant" , testEp ["E2E4", "A8B8", "A1B1"] ["D4D3"] "Cannot take the c-pawn after intermediate moves"] ownPieces :: GameState -> Piece -> [Field] ownPieces gs p = fmap (view pfField) $ filter ((==p) . (view pfPiece)) $ ownPieceFields gs newStateFromMoves :: GameState -> [String] -> GameState newStateFromMoves gs mvs = last $ gameStates $ fromJust $ EitherC.rightToMaybe game where game = gameFromString stringToMove gs mvs fieldsFromString s = fmap (fromJust . stringToField) s testEpDisappears = TestCase $ assertEqual error intersection (S.fromList whiteFields) where intersection = intersect whiteFields fieldsExpected newState = newStateFromMoves gsEp ["C2C4", "D4C3"] whiteFields = ownPieces newState Pawn fieldsExpected = fieldsFromString ["E2"] error = "Pawn that is taken ep disappears - incorrect GameState: " ++ show newState gsPromote = stringToGs ["WKA1", "BKA8", "WPG7"] testPromotionPawnDisappears = TestCase $ assertEqual error (S.fromList fieldsExpected) intersection where intersection = intersect whiteFields fieldsExpected newState = invertGameStateColor $ newStateFromMoves gsPromote ["G7G8N"] whiteFields = ownPieces newState Pawn fieldsExpected = [] error = "Pawn that promotes disappears" ++ show newState testPromotionNewPiece = TestCase $ assertEqual error (S.fromList fieldsExpected) intersection where intersection = intersect whiteFields fieldsExpected newState = invertGameStateColor $ newStateFromMoves gsPromote ["G7G8N"] whiteFields = ownPieces newState Knight fieldsExpected = fieldsFromString ["G8"] error = "New knight has appeared: " ++ show newState gsPromoteTake = stringToGs ["WKA1", "BKA8", "WPG7", "BNH8"] testPromotionTake = TestCase $ assertEqual error (S.fromList fieldsExpected) intersection where intersection = intersect whiteFields fieldsExpected newState = newStateFromMoves gsPromoteTake ["G7H8N"] whiteFields = ownPieces newState Knight fieldsExpected = fieldsFromString [] error = "The knight should be taken: " ++ show newState legalMoveData = [ (["WKA1", "BKA8"], ["A1A2", "A1B1", "A1B2"], ["A1B3"]) , (["WKA1", "BKA8", "BRB7"], ["A1A2"], ["A1B2"]) , (["WKA1", "BKA8", "WQA2", "BRA7"], ["A2A3"], ["A1A2", "A2B2", "A2A8"]) , (["WKA1", "BKA8", "WQB2", "BRA7"], ["B2A3"], ["B2B3", "B2A1"]) , (["WKA1", "BKA8", "BRA7", "BBH8"], ["A1B1"], ["A1B2", "A1B2"]) , (["WKA1", "BKA8", "BBE3", "WPD2", "WPE2"], ["D2E3"], ["E2E3", "E2E4"]) , (["WKA1", "BKA8", "BRA7", "WPA3", "BPB4"], ["A3A4"], ["A3B4"])] legalMoveTest gsString legalMoves = (S.fromList expected) ~=? actual where actual = intersect expected legal gs = stringToGs gsString expected = fmap (snd . fromJust . (stringToMove gs)) legalMoves legal = fmap snd $ allLegalMoves gs illegalMoveTest gsString illegalMoves = expected ~=? actual where expected = fmap (snd . fromJust . (stringToMove gs)) illegalMoves gs = stringToGs gsString legalMoves = fmap snd $ allLegalMoves gs actual = filter (\m -> not (m `elem` legalMoves)) expected fensToConvert = [ "fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" , "fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1" , "fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b kq - 0 1" , "fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b - - 20 1" , "fen rnbqkbnr/ppp2ppp/4p3/3pP3/8/8/PPPP1PPP/RNBQKBNR w KQkq d6 1 1"] fenDoubleConvertTest f = Just f ~=? fmap gameStateToFen (fenToGameState f) fenDoubleConvertTests = TestList $ fmap fenDoubleConvertTest fensToConvert legalMoveTests = ["Test legal moves are right" ~: legalMoveTest f s | (f, s, _) <- legalMoveData] illegalMoveTests = ["Test illegal moves are right" ~: illegalMoveTest f t | (f, _, t) <- legalMoveData] singleTests = [ "Opponent Move test" ~: oppMoveTest , "Pawn that is taken en passant disappears" ~: testEpDisappears , "Castling Queen" ~: testCastleQueen , "Castling Both black" ~: testCastleBothBlack , "Pawn that promotes disappears" ~: testPromotionPawnDisappears , "Promoting pawn creates piece" ~: testPromotionNewPiece , "Promoting can happen by taking" ~: testPromotionTake , "Castling Both" ~: testCastleBoth] logicTests = TestList [ "Check tests" ~: checkTests , "is check tests" ~: isCheckTests , "mate tests" ~: mateTests , "pawn tests" ~: pawnTests , "single tests" ~: singleTests , "castle one side" ~: testCastleOneSide , "rook fields" ~: testRookFields , "losing castling rights" ~: testsLosesRight , "En passant" ~: testsEp , "Legal moves" ~: legalMoveTests , "illegal moves" ~: illegalMoveTests , "moves" ~: movesTests , "possible" ~: possibleTests , "fen double conversion" ~: fenDoubleConvertTests ]
8a2bdeafcca7444b195208dd9df3686a4b42717056cdb6f465239a2bbe6aa428
NorfairKing/smos
TH.hs
# LANGUAGE QuasiQuotes # module Smos.Docs.Site.Casts.TH where import Control.Monad import Instances.TH.Lift () import Language.Haskell.TH import Language.Haskell.TH.Syntax import Path import Path.IO import Smos.Docs.Site.Constants import System.Exit import System.IO import System.Process.Typed import Yesod.EmbeddedStatic # ANN module ( " HLint : ignore Reduce duplication " : : String ) # mkCasts :: Q [Dec] mkCasts = do specs <- runIO $ do cs <- resolveDir' "content/casts" fs <- snd <$> listDirRecur cs pure $ filter ((== Just ".yaml") . fileExtension) fs mapM_ (qAddDependentFile . fromAbsFile) specs tups <- runIO $ ensureCasts specs mapM_ (qAddDependentFile . snd) tups mkEmbeddedStatic development "casts" $ map (uncurry embedFileAt) tups ensureCasts :: [Path Abs File] -> IO [(String, FilePath)] ensureCasts specFiles = do hSetBuffering stdout LineBuffering -- To make sure the lines come out ok. hSetBuffering stderr LineBuffering mAutorecorderExecutable <- findExecutable [relfile|autorecorder|] forM specFiles $ \specFile -> do outputFile <- replaceExtension ".cast" specFile alreadyExists <- doesFileExist outputFile if alreadyExists then putStrLn $ unwords [ "Not casting because the cast already exists:", fromAbsFile outputFile ] else do case mAutorecorderExecutable of Nothing -> die "The autorecorder executable is not found. You can install it from ." Just autorecorderExecutable -> do putStrLn $ "Casting " <> fromAbsFile specFile let cmd = fromAbsFile autorecorderExecutable let args = [fromAbsFile specFile, fromAbsFile outputFile, "--progress"] putStrLn $ unwords $ cmd : map show args runProcess_ $ setStderr inherit $ setStdout inherit $ proc cmd args putStrLn $ "Done casting " <> fromAbsFile specFile pure (fromRelFile (filename outputFile), fromAbsFile outputFile)
null
https://raw.githubusercontent.com/NorfairKing/smos/f0d76460eff4c1270fd0ddd5ac6face76f6342b1/smos-docs-site/src/Smos/Docs/Site/Casts/TH.hs
haskell
To make sure the lines come out ok.
# LANGUAGE QuasiQuotes # module Smos.Docs.Site.Casts.TH where import Control.Monad import Instances.TH.Lift () import Language.Haskell.TH import Language.Haskell.TH.Syntax import Path import Path.IO import Smos.Docs.Site.Constants import System.Exit import System.IO import System.Process.Typed import Yesod.EmbeddedStatic # ANN module ( " HLint : ignore Reduce duplication " : : String ) # mkCasts :: Q [Dec] mkCasts = do specs <- runIO $ do cs <- resolveDir' "content/casts" fs <- snd <$> listDirRecur cs pure $ filter ((== Just ".yaml") . fileExtension) fs mapM_ (qAddDependentFile . fromAbsFile) specs tups <- runIO $ ensureCasts specs mapM_ (qAddDependentFile . snd) tups mkEmbeddedStatic development "casts" $ map (uncurry embedFileAt) tups ensureCasts :: [Path Abs File] -> IO [(String, FilePath)] ensureCasts specFiles = do hSetBuffering stderr LineBuffering mAutorecorderExecutable <- findExecutable [relfile|autorecorder|] forM specFiles $ \specFile -> do outputFile <- replaceExtension ".cast" specFile alreadyExists <- doesFileExist outputFile if alreadyExists then putStrLn $ unwords [ "Not casting because the cast already exists:", fromAbsFile outputFile ] else do case mAutorecorderExecutable of Nothing -> die "The autorecorder executable is not found. You can install it from ." Just autorecorderExecutable -> do putStrLn $ "Casting " <> fromAbsFile specFile let cmd = fromAbsFile autorecorderExecutable let args = [fromAbsFile specFile, fromAbsFile outputFile, "--progress"] putStrLn $ unwords $ cmd : map show args runProcess_ $ setStderr inherit $ setStdout inherit $ proc cmd args putStrLn $ "Done casting " <> fromAbsFile specFile pure (fromRelFile (filename outputFile), fromAbsFile outputFile)
c3983f7ad8418f4d8e8ace06d3e9f72a15c8b7d6765cd9d93b247fbcc1f1255c
spawnfest/eep49ers
wxFontPickerCtrl.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2020 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% This file is generated DO NOT EDIT -module(wxFontPickerCtrl). -include("wxe.hrl"). -export([create/3,create/4,destroy/1,getMaxPointSize/1,getSelectedFont/1,new/0, new/2,new/3,setMaxPointSize/2,setSelectedFont/2]). %% inherited exports -export([cacheBestSize/2,canSetTransparent/1,captureMouse/1,center/1,center/2, centerOnParent/1,centerOnParent/2,centre/1,centre/2,centreOnParent/1, centreOnParent/2,clearBackground/1,clientToScreen/2,clientToScreen/3, close/1,close/2,connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, dragAcceptFiles/2,enable/1,enable/2,findWindow/2,fit/1,fitInside/1, freeze/1,getAcceleratorTable/1,getBackgroundColour/1,getBackgroundStyle/1, getBestSize/1,getCaret/1,getCharHeight/1,getCharWidth/1,getChildren/1, getClientSize/1,getContainingSizer/1,getContentScaleFactor/1,getCursor/1, getDPI/1,getDPIScaleFactor/1,getDropTarget/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getInternalMargin/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1, getParent/1,getPickerCtrlProportion/1,getPosition/1,getRect/1,getScreenPosition/1, getScreenRect/1,getScrollPos/2,getScrollRange/2,getScrollThumb/2, getSize/1,getSizer/1,getTextCtrl/1,getTextCtrlProportion/1,getTextExtent/2, getTextExtent/3,getThemeEnabled/1,getToolTip/1,getUpdateRegion/1, getVirtualSize/1,getWindowStyleFlag/1,getWindowVariant/1,hasCapture/1, hasScrollbar/2,hasTextCtrl/1,hasTransparentBackground/1,hide/1,inheritAttributes/1, initDialog/1,invalidateBestSize/1,isDoubleBuffered/1,isEnabled/1, isExposed/2,isExposed/3,isExposed/5,isFrozen/1,isPickerCtrlGrowable/1, isRetained/1,isShown/1,isShownOnScreen/1,isTextCtrlGrowable/1,isTopLevel/1, layout/1,lineDown/1,lineUp/1,lower/1,move/2,move/3,move/4,moveAfterInTabOrder/2, moveBeforeInTabOrder/2,navigate/1,navigate/2,pageDown/1,pageUp/1,parent_class/1, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDoubleBuffered/2,setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1, setFont/2,setForegroundColour/2,setHelpText/2,setId/2,setInternalMargin/2, setLabel/2,setMaxSize/2,setMinSize/2,setName/2,setOwnBackgroundColour/2, setOwnFont/2,setOwnForegroundColour/2,setPalette/2,setPickerCtrlGrowable/1, setPickerCtrlGrowable/2,setPickerCtrlProportion/2,setScrollPos/3, setScrollPos/4,setScrollbar/5,setScrollbar/6,setSize/2,setSize/3,setSize/5, setSize/6,setSizeHints/2,setSizeHints/3,setSizeHints/4,setSizer/2, setSizer/3,setSizerAndFit/2,setSizerAndFit/3,setTextCtrlGrowable/1, setTextCtrlGrowable/2,setTextCtrlProportion/2,setThemeEnabled/2, setToolTip/2,setTransparent/2,setVirtualSize/2,setVirtualSize/3,setWindowStyle/2, setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1,show/1, show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1,update/1, updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). -type wxFontPickerCtrl() :: wx:wx_object(). -export_type([wxFontPickerCtrl/0]). %% @hidden parent_class(wxPickerBase) -> true; parent_class(wxControl) -> true; parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). %% @doc See <a href="#wxfontpickerctrlwxfontpickerctrl">external documentation</a>. -spec new() -> wxFontPickerCtrl(). new() -> wxe_util:queue_cmd(?get_env(), ?wxFontPickerCtrl_new_0), wxe_util:rec(?wxFontPickerCtrl_new_0). @equiv new(Parent , Id , [ ] ) -spec new(Parent, Id) -> wxFontPickerCtrl() when Parent::wxWindow:wxWindow(), Id::integer(). new(Parent,Id) when is_record(Parent, wx_ref),is_integer(Id) -> new(Parent,Id, []). %% @doc See <a href="#wxfontpickerctrlwxfontpickerctrl">external documentation</a>. -spec new(Parent, Id, [Option]) -> wxFontPickerCtrl() when Parent::wxWindow:wxWindow(), Id::integer(), Option :: {'initial', wxFont:wxFont()} | {'pos', {X::integer(), Y::integer()}} | {'size', {W::integer(), H::integer()}} | {'style', integer()} | {'validator', wx:wx_object()}. new(#wx_ref{type=ParentT}=Parent,Id, Options) when is_integer(Id),is_list(Options) -> ?CLASS(ParentT,wxWindow), MOpts = fun({initial, #wx_ref{type=InitialT}} = Arg) -> ?CLASS(InitialT,wxFont),Arg; ({pos, {_posX,_posY}} = Arg) -> Arg; ({size, {_sizeW,_sizeH}} = Arg) -> Arg; ({style, _style} = Arg) -> Arg; ({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg; (BadOpt) -> erlang:error({badoption, BadOpt}) end, Opts = lists:map(MOpts, Options), wxe_util:queue_cmd(Parent,Id, Opts,?get_env(),?wxFontPickerCtrl_new_3), wxe_util:rec(?wxFontPickerCtrl_new_3). %% @equiv create(This,Parent,Id, []) -spec create(This, Parent, Id) -> boolean() when This::wxFontPickerCtrl(), Parent::wxWindow:wxWindow(), Id::integer(). create(This,Parent,Id) when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id) -> create(This,Parent,Id, []). %% @doc See <a href="#wxfontpickerctrlcreate">external documentation</a>. -spec create(This, Parent, Id, [Option]) -> boolean() when This::wxFontPickerCtrl(), Parent::wxWindow:wxWindow(), Id::integer(), Option :: {'initial', wxFont:wxFont()} | {'pos', {X::integer(), Y::integer()}} | {'size', {W::integer(), H::integer()}} | {'style', integer()} | {'validator', wx:wx_object()}. create(#wx_ref{type=ThisT}=This,#wx_ref{type=ParentT}=Parent,Id, Options) when is_integer(Id),is_list(Options) -> ?CLASS(ThisT,wxFontPickerCtrl), ?CLASS(ParentT,wxWindow), MOpts = fun({initial, #wx_ref{type=InitialT}} = Arg) -> ?CLASS(InitialT,wxFont),Arg; ({pos, {_posX,_posY}} = Arg) -> Arg; ({size, {_sizeW,_sizeH}} = Arg) -> Arg; ({style, _style} = Arg) -> Arg; ({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg; (BadOpt) -> erlang:error({badoption, BadOpt}) end, Opts = lists:map(MOpts, Options), wxe_util:queue_cmd(This,Parent,Id, Opts,?get_env(),?wxFontPickerCtrl_Create), wxe_util:rec(?wxFontPickerCtrl_Create). %% @doc See <a href="#wxfontpickerctrlgetselectedfont">external documentation</a>. -spec getSelectedFont(This) -> wxFont:wxFont() when This::wxFontPickerCtrl(). getSelectedFont(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxFontPickerCtrl), wxe_util:queue_cmd(This,?get_env(),?wxFontPickerCtrl_GetSelectedFont), wxe_util:rec(?wxFontPickerCtrl_GetSelectedFont). %% @doc See <a href="#wxfontpickerctrlsetselectedfont">external documentation</a>. -spec setSelectedFont(This, Font) -> 'ok' when This::wxFontPickerCtrl(), Font::wxFont:wxFont(). setSelectedFont(#wx_ref{type=ThisT}=This,#wx_ref{type=FontT}=Font) -> ?CLASS(ThisT,wxFontPickerCtrl), ?CLASS(FontT,wxFont), wxe_util:queue_cmd(This,Font,?get_env(),?wxFontPickerCtrl_SetSelectedFont). %% @doc See <a href="#wxfontpickerctrlgetmaxpointsize">external documentation</a>. -spec getMaxPointSize(This) -> integer() when This::wxFontPickerCtrl(). getMaxPointSize(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxFontPickerCtrl), wxe_util:queue_cmd(This,?get_env(),?wxFontPickerCtrl_GetMaxPointSize), wxe_util:rec(?wxFontPickerCtrl_GetMaxPointSize). %% @doc See <a href="#wxfontpickerctrlsetmaxpointsize">external documentation</a>. -spec setMaxPointSize(This, Max) -> 'ok' when This::wxFontPickerCtrl(), Max::integer(). setMaxPointSize(#wx_ref{type=ThisT}=This,Max) when is_integer(Max) -> ?CLASS(ThisT,wxFontPickerCtrl), wxe_util:queue_cmd(This,Max,?get_env(),?wxFontPickerCtrl_SetMaxPointSize). %% @doc Destroys this object, do not use object again -spec destroy(This::wxFontPickerCtrl()) -> 'ok'. destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxFontPickerCtrl), wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT), ok. From wxPickerBase %% @hidden isPickerCtrlGrowable(This) -> wxPickerBase:isPickerCtrlGrowable(This). %% @hidden setTextCtrlGrowable(This, Options) -> wxPickerBase:setTextCtrlGrowable(This, Options). %% @hidden setTextCtrlGrowable(This) -> wxPickerBase:setTextCtrlGrowable(This). %% @hidden setPickerCtrlGrowable(This, Options) -> wxPickerBase:setPickerCtrlGrowable(This, Options). %% @hidden setPickerCtrlGrowable(This) -> wxPickerBase:setPickerCtrlGrowable(This). %% @hidden isTextCtrlGrowable(This) -> wxPickerBase:isTextCtrlGrowable(This). %% @hidden getTextCtrl(This) -> wxPickerBase:getTextCtrl(This). %% @hidden hasTextCtrl(This) -> wxPickerBase:hasTextCtrl(This). %% @hidden getPickerCtrlProportion(This) -> wxPickerBase:getPickerCtrlProportion(This). %% @hidden getTextCtrlProportion(This) -> wxPickerBase:getTextCtrlProportion(This). %% @hidden setPickerCtrlProportion(This,Prop) -> wxPickerBase:setPickerCtrlProportion(This,Prop). %% @hidden setTextCtrlProportion(This,Prop) -> wxPickerBase:setTextCtrlProportion(This,Prop). %% @hidden getInternalMargin(This) -> wxPickerBase:getInternalMargin(This). %% @hidden setInternalMargin(This,Margin) -> wxPickerBase:setInternalMargin(This,Margin). %% From wxControl %% @hidden setLabel(This,Label) -> wxControl:setLabel(This,Label). %% @hidden getLabel(This) -> wxControl:getLabel(This). %% From wxWindow %% @hidden getDPI(This) -> wxWindow:getDPI(This). %% @hidden getContentScaleFactor(This) -> wxWindow:getContentScaleFactor(This). %% @hidden setDoubleBuffered(This,On) -> wxWindow:setDoubleBuffered(This,On). %% @hidden isDoubleBuffered(This) -> wxWindow:isDoubleBuffered(This). %% @hidden canSetTransparent(This) -> wxWindow:canSetTransparent(This). %% @hidden setTransparent(This,Alpha) -> wxWindow:setTransparent(This,Alpha). %% @hidden warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). %% @hidden validate(This) -> wxWindow:validate(This). %% @hidden updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). %% @hidden updateWindowUI(This) -> wxWindow:updateWindowUI(This). %% @hidden update(This) -> wxWindow:update(This). %% @hidden transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). %% @hidden transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). %% @hidden thaw(This) -> wxWindow:thaw(This). %% @hidden show(This, Options) -> wxWindow:show(This, Options). %% @hidden show(This) -> wxWindow:show(This). %% @hidden shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). %% @hidden setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). %% @hidden setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). %% @hidden setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). %% @hidden setVirtualSize(This,Width,Height) -> wxWindow:setVirtualSize(This,Width,Height). %% @hidden setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). %% @hidden setToolTip(This,TipString) -> wxWindow:setToolTip(This,TipString). %% @hidden setThemeEnabled(This,Enable) -> wxWindow:setThemeEnabled(This,Enable). %% @hidden setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). %% @hidden setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). %% @hidden setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). %% @hidden setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). %% @hidden setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). %% @hidden setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). %% @hidden setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). %% @hidden setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). %% @hidden setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). %% @hidden setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). %% @hidden setSize(This,Rect) -> wxWindow:setSize(This,Rect). %% @hidden setScrollPos(This,Orientation,Pos, Options) -> wxWindow:setScrollPos(This,Orientation,Pos, Options). %% @hidden setScrollPos(This,Orientation,Pos) -> wxWindow:setScrollPos(This,Orientation,Pos). %% @hidden setScrollbar(This,Orientation,Position,ThumbSize,Range, Options) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range, Options). %% @hidden setScrollbar(This,Orientation,Position,ThumbSize,Range) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range). %% @hidden setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). %% @hidden setName(This,Name) -> wxWindow:setName(This,Name). %% @hidden setId(This,Winid) -> wxWindow:setId(This,Winid). %% @hidden setHelpText(This,HelpText) -> wxWindow:setHelpText(This,HelpText). %% @hidden setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). %% @hidden setFont(This,Font) -> wxWindow:setFont(This,Font). %% @hidden setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). %% @hidden setFocus(This) -> wxWindow:setFocus(This). %% @hidden setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). %% @hidden setDropTarget(This,Target) -> wxWindow:setDropTarget(This,Target). %% @hidden setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). %% @hidden setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). %% @hidden setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). %% @hidden setMinSize(This,Size) -> wxWindow:setMinSize(This,Size). %% @hidden setMaxSize(This,Size) -> wxWindow:setMaxSize(This,Size). %% @hidden setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). %% @hidden setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). %% @hidden setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). %% @hidden setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). %% @hidden setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). %% @hidden setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). %% @hidden setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). %% @hidden setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). %% @hidden setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). %% @hidden scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). %% @hidden scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). %% @hidden scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). %% @hidden scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). %% @hidden screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). %% @hidden screenToClient(This) -> wxWindow:screenToClient(This). %% @hidden reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). %% @hidden removeChild(This,Child) -> wxWindow:removeChild(This,Child). %% @hidden releaseMouse(This) -> wxWindow:releaseMouse(This). %% @hidden refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). %% @hidden refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). %% @hidden refresh(This, Options) -> wxWindow:refresh(This, Options). %% @hidden refresh(This) -> wxWindow:refresh(This). %% @hidden raise(This) -> wxWindow:raise(This). %% @hidden popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). %% @hidden popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). %% @hidden popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). %% @hidden pageUp(This) -> wxWindow:pageUp(This). %% @hidden pageDown(This) -> wxWindow:pageDown(This). %% @hidden navigate(This, Options) -> wxWindow:navigate(This, Options). %% @hidden navigate(This) -> wxWindow:navigate(This). %% @hidden moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). %% @hidden moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). %% @hidden move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). %% @hidden move(This,X,Y) -> wxWindow:move(This,X,Y). %% @hidden move(This,Pt) -> wxWindow:move(This,Pt). %% @hidden lower(This) -> wxWindow:lower(This). %% @hidden lineUp(This) -> wxWindow:lineUp(This). %% @hidden lineDown(This) -> wxWindow:lineDown(This). %% @hidden layout(This) -> wxWindow:layout(This). %% @hidden isShownOnScreen(This) -> wxWindow:isShownOnScreen(This). %% @hidden isTopLevel(This) -> wxWindow:isTopLevel(This). %% @hidden isShown(This) -> wxWindow:isShown(This). %% @hidden isRetained(This) -> wxWindow:isRetained(This). %% @hidden isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). %% @hidden isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). %% @hidden isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). %% @hidden isEnabled(This) -> wxWindow:isEnabled(This). %% @hidden isFrozen(This) -> wxWindow:isFrozen(This). %% @hidden invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). %% @hidden initDialog(This) -> wxWindow:initDialog(This). %% @hidden inheritAttributes(This) -> wxWindow:inheritAttributes(This). %% @hidden hide(This) -> wxWindow:hide(This). %% @hidden hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). %% @hidden hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). %% @hidden hasCapture(This) -> wxWindow:hasCapture(This). %% @hidden getWindowVariant(This) -> wxWindow:getWindowVariant(This). %% @hidden getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). %% @hidden getVirtualSize(This) -> wxWindow:getVirtualSize(This). %% @hidden getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). %% @hidden getToolTip(This) -> wxWindow:getToolTip(This). %% @hidden getThemeEnabled(This) -> wxWindow:getThemeEnabled(This). %% @hidden getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). %% @hidden getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). %% @hidden getSizer(This) -> wxWindow:getSizer(This). %% @hidden getSize(This) -> wxWindow:getSize(This). %% @hidden getScrollThumb(This,Orientation) -> wxWindow:getScrollThumb(This,Orientation). %% @hidden getScrollRange(This,Orientation) -> wxWindow:getScrollRange(This,Orientation). %% @hidden getScrollPos(This,Orientation) -> wxWindow:getScrollPos(This,Orientation). %% @hidden getScreenRect(This) -> wxWindow:getScreenRect(This). %% @hidden getScreenPosition(This) -> wxWindow:getScreenPosition(This). %% @hidden getRect(This) -> wxWindow:getRect(This). %% @hidden getPosition(This) -> wxWindow:getPosition(This). %% @hidden getParent(This) -> wxWindow:getParent(This). %% @hidden getName(This) -> wxWindow:getName(This). %% @hidden getMinSize(This) -> wxWindow:getMinSize(This). %% @hidden getMaxSize(This) -> wxWindow:getMaxSize(This). %% @hidden getId(This) -> wxWindow:getId(This). %% @hidden getHelpText(This) -> wxWindow:getHelpText(This). %% @hidden getHandle(This) -> wxWindow:getHandle(This). %% @hidden getGrandParent(This) -> wxWindow:getGrandParent(This). %% @hidden getForegroundColour(This) -> wxWindow:getForegroundColour(This). %% @hidden getFont(This) -> wxWindow:getFont(This). %% @hidden getExtraStyle(This) -> wxWindow:getExtraStyle(This). %% @hidden getDPIScaleFactor(This) -> wxWindow:getDPIScaleFactor(This). %% @hidden getDropTarget(This) -> wxWindow:getDropTarget(This). %% @hidden getCursor(This) -> wxWindow:getCursor(This). %% @hidden getContainingSizer(This) -> wxWindow:getContainingSizer(This). %% @hidden getClientSize(This) -> wxWindow:getClientSize(This). %% @hidden getChildren(This) -> wxWindow:getChildren(This). %% @hidden getCharWidth(This) -> wxWindow:getCharWidth(This). %% @hidden getCharHeight(This) -> wxWindow:getCharHeight(This). %% @hidden getCaret(This) -> wxWindow:getCaret(This). %% @hidden getBestSize(This) -> wxWindow:getBestSize(This). %% @hidden getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). %% @hidden getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). %% @hidden getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). %% @hidden freeze(This) -> wxWindow:freeze(This). %% @hidden fitInside(This) -> wxWindow:fitInside(This). %% @hidden fit(This) -> wxWindow:fit(This). %% @hidden findWindow(This,Id) -> wxWindow:findWindow(This,Id). %% @hidden enable(This, Options) -> wxWindow:enable(This, Options). %% @hidden enable(This) -> wxWindow:enable(This). %% @hidden dragAcceptFiles(This,Accept) -> wxWindow:dragAcceptFiles(This,Accept). %% @hidden disable(This) -> wxWindow:disable(This). %% @hidden destroyChildren(This) -> wxWindow:destroyChildren(This). %% @hidden convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). %% @hidden convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). %% @hidden close(This, Options) -> wxWindow:close(This, Options). %% @hidden close(This) -> wxWindow:close(This). %% @hidden clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). %% @hidden clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). %% @hidden clearBackground(This) -> wxWindow:clearBackground(This). %% @hidden centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). %% @hidden centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). %% @hidden centreOnParent(This) -> wxWindow:centreOnParent(This). %% @hidden centerOnParent(This) -> wxWindow:centerOnParent(This). %% @hidden centre(This, Options) -> wxWindow:centre(This, Options). %% @hidden center(This, Options) -> wxWindow:center(This, Options). %% @hidden centre(This) -> wxWindow:centre(This). %% @hidden center(This) -> wxWindow:center(This). %% @hidden captureMouse(This) -> wxWindow:captureMouse(This). %% @hidden cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). %% From wxEvtHandler %% @hidden disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). %% @hidden disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). %% @hidden disconnect(This) -> wxEvtHandler:disconnect(This). %% @hidden connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). %% @hidden connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxFontPickerCtrl.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% This file is generated DO NOT EDIT inherited exports @hidden @doc See <a href="#wxfontpickerctrlwxfontpickerctrl">external documentation</a>. @doc See <a href="#wxfontpickerctrlwxfontpickerctrl">external documentation</a>. @equiv create(This,Parent,Id, []) @doc See <a href="#wxfontpickerctrlcreate">external documentation</a>. @doc See <a href="#wxfontpickerctrlgetselectedfont">external documentation</a>. @doc See <a href="#wxfontpickerctrlsetselectedfont">external documentation</a>. @doc See <a href="#wxfontpickerctrlgetmaxpointsize">external documentation</a>. @doc See <a href="#wxfontpickerctrlsetmaxpointsize">external documentation</a>. @doc Destroys this object, do not use object again @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden From wxControl @hidden @hidden From wxWindow @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden From wxEvtHandler @hidden @hidden @hidden @hidden @hidden
Copyright Ericsson AB 2008 - 2020 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(wxFontPickerCtrl). -include("wxe.hrl"). -export([create/3,create/4,destroy/1,getMaxPointSize/1,getSelectedFont/1,new/0, new/2,new/3,setMaxPointSize/2,setSelectedFont/2]). -export([cacheBestSize/2,canSetTransparent/1,captureMouse/1,center/1,center/2, centerOnParent/1,centerOnParent/2,centre/1,centre/2,centreOnParent/1, centreOnParent/2,clearBackground/1,clientToScreen/2,clientToScreen/3, close/1,close/2,connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, dragAcceptFiles/2,enable/1,enable/2,findWindow/2,fit/1,fitInside/1, freeze/1,getAcceleratorTable/1,getBackgroundColour/1,getBackgroundStyle/1, getBestSize/1,getCaret/1,getCharHeight/1,getCharWidth/1,getChildren/1, getClientSize/1,getContainingSizer/1,getContentScaleFactor/1,getCursor/1, getDPI/1,getDPIScaleFactor/1,getDropTarget/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getInternalMargin/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1, getParent/1,getPickerCtrlProportion/1,getPosition/1,getRect/1,getScreenPosition/1, getScreenRect/1,getScrollPos/2,getScrollRange/2,getScrollThumb/2, getSize/1,getSizer/1,getTextCtrl/1,getTextCtrlProportion/1,getTextExtent/2, getTextExtent/3,getThemeEnabled/1,getToolTip/1,getUpdateRegion/1, getVirtualSize/1,getWindowStyleFlag/1,getWindowVariant/1,hasCapture/1, hasScrollbar/2,hasTextCtrl/1,hasTransparentBackground/1,hide/1,inheritAttributes/1, initDialog/1,invalidateBestSize/1,isDoubleBuffered/1,isEnabled/1, isExposed/2,isExposed/3,isExposed/5,isFrozen/1,isPickerCtrlGrowable/1, isRetained/1,isShown/1,isShownOnScreen/1,isTextCtrlGrowable/1,isTopLevel/1, layout/1,lineDown/1,lineUp/1,lower/1,move/2,move/3,move/4,moveAfterInTabOrder/2, moveBeforeInTabOrder/2,navigate/1,navigate/2,pageDown/1,pageUp/1,parent_class/1, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDoubleBuffered/2,setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1, setFont/2,setForegroundColour/2,setHelpText/2,setId/2,setInternalMargin/2, setLabel/2,setMaxSize/2,setMinSize/2,setName/2,setOwnBackgroundColour/2, setOwnFont/2,setOwnForegroundColour/2,setPalette/2,setPickerCtrlGrowable/1, setPickerCtrlGrowable/2,setPickerCtrlProportion/2,setScrollPos/3, setScrollPos/4,setScrollbar/5,setScrollbar/6,setSize/2,setSize/3,setSize/5, setSize/6,setSizeHints/2,setSizeHints/3,setSizeHints/4,setSizer/2, setSizer/3,setSizerAndFit/2,setSizerAndFit/3,setTextCtrlGrowable/1, setTextCtrlGrowable/2,setTextCtrlProportion/2,setThemeEnabled/2, setToolTip/2,setTransparent/2,setVirtualSize/2,setVirtualSize/3,setWindowStyle/2, setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1,show/1, show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1,update/1, updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). -type wxFontPickerCtrl() :: wx:wx_object(). -export_type([wxFontPickerCtrl/0]). parent_class(wxPickerBase) -> true; parent_class(wxControl) -> true; parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). -spec new() -> wxFontPickerCtrl(). new() -> wxe_util:queue_cmd(?get_env(), ?wxFontPickerCtrl_new_0), wxe_util:rec(?wxFontPickerCtrl_new_0). @equiv new(Parent , Id , [ ] ) -spec new(Parent, Id) -> wxFontPickerCtrl() when Parent::wxWindow:wxWindow(), Id::integer(). new(Parent,Id) when is_record(Parent, wx_ref),is_integer(Id) -> new(Parent,Id, []). -spec new(Parent, Id, [Option]) -> wxFontPickerCtrl() when Parent::wxWindow:wxWindow(), Id::integer(), Option :: {'initial', wxFont:wxFont()} | {'pos', {X::integer(), Y::integer()}} | {'size', {W::integer(), H::integer()}} | {'style', integer()} | {'validator', wx:wx_object()}. new(#wx_ref{type=ParentT}=Parent,Id, Options) when is_integer(Id),is_list(Options) -> ?CLASS(ParentT,wxWindow), MOpts = fun({initial, #wx_ref{type=InitialT}} = Arg) -> ?CLASS(InitialT,wxFont),Arg; ({pos, {_posX,_posY}} = Arg) -> Arg; ({size, {_sizeW,_sizeH}} = Arg) -> Arg; ({style, _style} = Arg) -> Arg; ({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg; (BadOpt) -> erlang:error({badoption, BadOpt}) end, Opts = lists:map(MOpts, Options), wxe_util:queue_cmd(Parent,Id, Opts,?get_env(),?wxFontPickerCtrl_new_3), wxe_util:rec(?wxFontPickerCtrl_new_3). -spec create(This, Parent, Id) -> boolean() when This::wxFontPickerCtrl(), Parent::wxWindow:wxWindow(), Id::integer(). create(This,Parent,Id) when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id) -> create(This,Parent,Id, []). -spec create(This, Parent, Id, [Option]) -> boolean() when This::wxFontPickerCtrl(), Parent::wxWindow:wxWindow(), Id::integer(), Option :: {'initial', wxFont:wxFont()} | {'pos', {X::integer(), Y::integer()}} | {'size', {W::integer(), H::integer()}} | {'style', integer()} | {'validator', wx:wx_object()}. create(#wx_ref{type=ThisT}=This,#wx_ref{type=ParentT}=Parent,Id, Options) when is_integer(Id),is_list(Options) -> ?CLASS(ThisT,wxFontPickerCtrl), ?CLASS(ParentT,wxWindow), MOpts = fun({initial, #wx_ref{type=InitialT}} = Arg) -> ?CLASS(InitialT,wxFont),Arg; ({pos, {_posX,_posY}} = Arg) -> Arg; ({size, {_sizeW,_sizeH}} = Arg) -> Arg; ({style, _style} = Arg) -> Arg; ({validator, #wx_ref{type=ValidatorT}} = Arg) -> ?CLASS(ValidatorT,wx),Arg; (BadOpt) -> erlang:error({badoption, BadOpt}) end, Opts = lists:map(MOpts, Options), wxe_util:queue_cmd(This,Parent,Id, Opts,?get_env(),?wxFontPickerCtrl_Create), wxe_util:rec(?wxFontPickerCtrl_Create). -spec getSelectedFont(This) -> wxFont:wxFont() when This::wxFontPickerCtrl(). getSelectedFont(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxFontPickerCtrl), wxe_util:queue_cmd(This,?get_env(),?wxFontPickerCtrl_GetSelectedFont), wxe_util:rec(?wxFontPickerCtrl_GetSelectedFont). -spec setSelectedFont(This, Font) -> 'ok' when This::wxFontPickerCtrl(), Font::wxFont:wxFont(). setSelectedFont(#wx_ref{type=ThisT}=This,#wx_ref{type=FontT}=Font) -> ?CLASS(ThisT,wxFontPickerCtrl), ?CLASS(FontT,wxFont), wxe_util:queue_cmd(This,Font,?get_env(),?wxFontPickerCtrl_SetSelectedFont). -spec getMaxPointSize(This) -> integer() when This::wxFontPickerCtrl(). getMaxPointSize(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxFontPickerCtrl), wxe_util:queue_cmd(This,?get_env(),?wxFontPickerCtrl_GetMaxPointSize), wxe_util:rec(?wxFontPickerCtrl_GetMaxPointSize). -spec setMaxPointSize(This, Max) -> 'ok' when This::wxFontPickerCtrl(), Max::integer(). setMaxPointSize(#wx_ref{type=ThisT}=This,Max) when is_integer(Max) -> ?CLASS(ThisT,wxFontPickerCtrl), wxe_util:queue_cmd(This,Max,?get_env(),?wxFontPickerCtrl_SetMaxPointSize). -spec destroy(This::wxFontPickerCtrl()) -> 'ok'. destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxFontPickerCtrl), wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT), ok. From wxPickerBase isPickerCtrlGrowable(This) -> wxPickerBase:isPickerCtrlGrowable(This). setTextCtrlGrowable(This, Options) -> wxPickerBase:setTextCtrlGrowable(This, Options). setTextCtrlGrowable(This) -> wxPickerBase:setTextCtrlGrowable(This). setPickerCtrlGrowable(This, Options) -> wxPickerBase:setPickerCtrlGrowable(This, Options). setPickerCtrlGrowable(This) -> wxPickerBase:setPickerCtrlGrowable(This). isTextCtrlGrowable(This) -> wxPickerBase:isTextCtrlGrowable(This). getTextCtrl(This) -> wxPickerBase:getTextCtrl(This). hasTextCtrl(This) -> wxPickerBase:hasTextCtrl(This). getPickerCtrlProportion(This) -> wxPickerBase:getPickerCtrlProportion(This). getTextCtrlProportion(This) -> wxPickerBase:getTextCtrlProportion(This). setPickerCtrlProportion(This,Prop) -> wxPickerBase:setPickerCtrlProportion(This,Prop). setTextCtrlProportion(This,Prop) -> wxPickerBase:setTextCtrlProportion(This,Prop). getInternalMargin(This) -> wxPickerBase:getInternalMargin(This). setInternalMargin(This,Margin) -> wxPickerBase:setInternalMargin(This,Margin). setLabel(This,Label) -> wxControl:setLabel(This,Label). getLabel(This) -> wxControl:getLabel(This). getDPI(This) -> wxWindow:getDPI(This). getContentScaleFactor(This) -> wxWindow:getContentScaleFactor(This). setDoubleBuffered(This,On) -> wxWindow:setDoubleBuffered(This,On). isDoubleBuffered(This) -> wxWindow:isDoubleBuffered(This). canSetTransparent(This) -> wxWindow:canSetTransparent(This). setTransparent(This,Alpha) -> wxWindow:setTransparent(This,Alpha). warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). validate(This) -> wxWindow:validate(This). updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). updateWindowUI(This) -> wxWindow:updateWindowUI(This). update(This) -> wxWindow:update(This). transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). thaw(This) -> wxWindow:thaw(This). show(This, Options) -> wxWindow:show(This, Options). show(This) -> wxWindow:show(This). shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). setVirtualSize(This,Width,Height) -> wxWindow:setVirtualSize(This,Width,Height). setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). setToolTip(This,TipString) -> wxWindow:setToolTip(This,TipString). setThemeEnabled(This,Enable) -> wxWindow:setThemeEnabled(This,Enable). setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). setSize(This,Rect) -> wxWindow:setSize(This,Rect). setScrollPos(This,Orientation,Pos, Options) -> wxWindow:setScrollPos(This,Orientation,Pos, Options). setScrollPos(This,Orientation,Pos) -> wxWindow:setScrollPos(This,Orientation,Pos). setScrollbar(This,Orientation,Position,ThumbSize,Range, Options) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range, Options). setScrollbar(This,Orientation,Position,ThumbSize,Range) -> wxWindow:setScrollbar(This,Orientation,Position,ThumbSize,Range). setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). setName(This,Name) -> wxWindow:setName(This,Name). setId(This,Winid) -> wxWindow:setId(This,Winid). setHelpText(This,HelpText) -> wxWindow:setHelpText(This,HelpText). setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). setFont(This,Font) -> wxWindow:setFont(This,Font). setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). setFocus(This) -> wxWindow:setFocus(This). setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). setDropTarget(This,Target) -> wxWindow:setDropTarget(This,Target). setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). setMinSize(This,Size) -> wxWindow:setMinSize(This,Size). setMaxSize(This,Size) -> wxWindow:setMaxSize(This,Size). setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). screenToClient(This) -> wxWindow:screenToClient(This). reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). removeChild(This,Child) -> wxWindow:removeChild(This,Child). releaseMouse(This) -> wxWindow:releaseMouse(This). refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). refresh(This, Options) -> wxWindow:refresh(This, Options). refresh(This) -> wxWindow:refresh(This). raise(This) -> wxWindow:raise(This). popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). pageUp(This) -> wxWindow:pageUp(This). pageDown(This) -> wxWindow:pageDown(This). navigate(This, Options) -> wxWindow:navigate(This, Options). navigate(This) -> wxWindow:navigate(This). moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). move(This,X,Y) -> wxWindow:move(This,X,Y). move(This,Pt) -> wxWindow:move(This,Pt). lower(This) -> wxWindow:lower(This). lineUp(This) -> wxWindow:lineUp(This). lineDown(This) -> wxWindow:lineDown(This). layout(This) -> wxWindow:layout(This). isShownOnScreen(This) -> wxWindow:isShownOnScreen(This). isTopLevel(This) -> wxWindow:isTopLevel(This). isShown(This) -> wxWindow:isShown(This). isRetained(This) -> wxWindow:isRetained(This). isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). isEnabled(This) -> wxWindow:isEnabled(This). isFrozen(This) -> wxWindow:isFrozen(This). invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). initDialog(This) -> wxWindow:initDialog(This). inheritAttributes(This) -> wxWindow:inheritAttributes(This). hide(This) -> wxWindow:hide(This). hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). hasCapture(This) -> wxWindow:hasCapture(This). getWindowVariant(This) -> wxWindow:getWindowVariant(This). getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). getVirtualSize(This) -> wxWindow:getVirtualSize(This). getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). getToolTip(This) -> wxWindow:getToolTip(This). getThemeEnabled(This) -> wxWindow:getThemeEnabled(This). getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). getSizer(This) -> wxWindow:getSizer(This). getSize(This) -> wxWindow:getSize(This). getScrollThumb(This,Orientation) -> wxWindow:getScrollThumb(This,Orientation). getScrollRange(This,Orientation) -> wxWindow:getScrollRange(This,Orientation). getScrollPos(This,Orientation) -> wxWindow:getScrollPos(This,Orientation). getScreenRect(This) -> wxWindow:getScreenRect(This). getScreenPosition(This) -> wxWindow:getScreenPosition(This). getRect(This) -> wxWindow:getRect(This). getPosition(This) -> wxWindow:getPosition(This). getParent(This) -> wxWindow:getParent(This). getName(This) -> wxWindow:getName(This). getMinSize(This) -> wxWindow:getMinSize(This). getMaxSize(This) -> wxWindow:getMaxSize(This). getId(This) -> wxWindow:getId(This). getHelpText(This) -> wxWindow:getHelpText(This). getHandle(This) -> wxWindow:getHandle(This). getGrandParent(This) -> wxWindow:getGrandParent(This). getForegroundColour(This) -> wxWindow:getForegroundColour(This). getFont(This) -> wxWindow:getFont(This). getExtraStyle(This) -> wxWindow:getExtraStyle(This). getDPIScaleFactor(This) -> wxWindow:getDPIScaleFactor(This). getDropTarget(This) -> wxWindow:getDropTarget(This). getCursor(This) -> wxWindow:getCursor(This). getContainingSizer(This) -> wxWindow:getContainingSizer(This). getClientSize(This) -> wxWindow:getClientSize(This). getChildren(This) -> wxWindow:getChildren(This). getCharWidth(This) -> wxWindow:getCharWidth(This). getCharHeight(This) -> wxWindow:getCharHeight(This). getCaret(This) -> wxWindow:getCaret(This). getBestSize(This) -> wxWindow:getBestSize(This). getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). freeze(This) -> wxWindow:freeze(This). fitInside(This) -> wxWindow:fitInside(This). fit(This) -> wxWindow:fit(This). findWindow(This,Id) -> wxWindow:findWindow(This,Id). enable(This, Options) -> wxWindow:enable(This, Options). enable(This) -> wxWindow:enable(This). dragAcceptFiles(This,Accept) -> wxWindow:dragAcceptFiles(This,Accept). disable(This) -> wxWindow:disable(This). destroyChildren(This) -> wxWindow:destroyChildren(This). convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). close(This, Options) -> wxWindow:close(This, Options). close(This) -> wxWindow:close(This). clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). clearBackground(This) -> wxWindow:clearBackground(This). centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). centreOnParent(This) -> wxWindow:centreOnParent(This). centerOnParent(This) -> wxWindow:centerOnParent(This). centre(This, Options) -> wxWindow:centre(This, Options). center(This, Options) -> wxWindow:center(This, Options). centre(This) -> wxWindow:centre(This). center(This) -> wxWindow:center(This). captureMouse(This) -> wxWindow:captureMouse(This). cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). disconnect(This) -> wxEvtHandler:disconnect(This). connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
72a3e6560a211f00776beb8f531f1b266a5dbffed14299b0aff61d3fdcbd3df5
input-output-hk/ouroboros-network
Serialisation.hs
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # OPTIONS_GHC -Wno - orphans # module Ouroboros.Consensus.Shelley.Node.Serialisation () where import Control.Exception (Exception, throw) import qualified Data.ByteString.Lazy as Lazy import Data.Typeable (Typeable) import Cardano.Ledger.Binary (fromCBOR, toCBOR) import Cardano.Ledger.Core (fromEraCBOR, toEraCBOR) import Codec.Serialise (decode, encode) import Ouroboros.Network.Block (Serialised, unwrapCBORinCBOR, wrapCBORinCBOR) import Ouroboros.Consensus.Block import Ouroboros.Consensus.HeaderValidation import Ouroboros.Consensus.Ledger.SupportsMempool (GenTxId) import Ouroboros.Consensus.Node.Run import Ouroboros.Consensus.Node.Serialisation import Ouroboros.Consensus.Storage.Serialisation import qualified Cardano.Ledger.Shelley.API as SL import qualified Cardano.Protocol.TPraos.API as SL import Ouroboros.Consensus.Protocol.Praos (PraosState) import qualified Ouroboros.Consensus.Protocol.Praos as Praos import Ouroboros.Consensus.Protocol.TPraos import Ouroboros.Consensus.Shelley.Eras import Ouroboros.Consensus.Shelley.Ledger import Ouroboros.Consensus.Shelley.Ledger.NetworkProtocolVersion () import Ouroboros.Consensus.Shelley.Protocol.Abstract (pHeaderBlockSize, pHeaderSize) ------------------------------------------------------------------------------ EncodeDisk & DecodeDisk ------------------------------------------------------------------------------ EncodeDisk & DecodeDisk -------------------------------------------------------------------------------} instance ShelleyCompatible proto era => HasBinaryBlockInfo (ShelleyBlock proto era) where getBinaryBlockInfo = shelleyBinaryBlockInfo instance ShelleyCompatible proto era => SerialiseDiskConstraints (ShelleyBlock proto era) instance ShelleyCompatible proto era => EncodeDisk (ShelleyBlock proto era) (ShelleyBlock proto era) where encodeDisk _ = encodeShelleyBlock instance ShelleyCompatible proto era => DecodeDisk (ShelleyBlock proto era) (Lazy.ByteString -> ShelleyBlock proto era) where decodeDisk _ = decodeShelleyBlock instance ShelleyCompatible proto era => EncodeDisk (ShelleyBlock proto era) (Header (ShelleyBlock proto era)) where encodeDisk _ = encodeShelleyHeader instance ShelleyCompatible proto era => DecodeDisk (ShelleyBlock proto era) (Lazy.ByteString -> Header (ShelleyBlock proto era)) where decodeDisk _ = decodeShelleyHeader instance ShelleyCompatible proto era => EncodeDisk (ShelleyBlock proto era) (LedgerState (ShelleyBlock proto era)) where encodeDisk _ = encodeShelleyLedgerState instance ShelleyCompatible proto era => DecodeDisk (ShelleyBlock proto era) (LedgerState (ShelleyBlock proto era)) where decodeDisk _ = decodeShelleyLedgerState | @'ChainDepState ' ( ' BlockProtocol ' ( ' ' era))@ instance (ShelleyCompatible proto era, EraCrypto era ~ c, SL.PraosCrypto c) => EncodeDisk (ShelleyBlock proto era) (TPraosState c) where encodeDisk _ = encode | @'ChainDepState ' ( ' BlockProtocol ' ( ' ' era))@ instance (ShelleyCompatible proto era, EraCrypto era ~ c, SL.PraosCrypto c) => DecodeDisk (ShelleyBlock proto era) (TPraosState c) where decodeDisk _ = decode instance (ShelleyCompatible proto era, EraCrypto era ~ c, Praos.PraosCrypto c) => EncodeDisk (ShelleyBlock proto era) (PraosState c) where encodeDisk _ = encode | @'ChainDepState ' ( ' BlockProtocol ' ( ' ' era))@ instance (ShelleyCompatible proto era, EraCrypto era ~ c, Praos.PraosCrypto c) => DecodeDisk (ShelleyBlock proto era) (PraosState c) where decodeDisk _ = decode instance ShelleyCompatible proto era => EncodeDisk (ShelleyBlock proto era) (AnnTip (ShelleyBlock proto era)) where encodeDisk _ = encodeShelleyAnnTip instance ShelleyCompatible proto era => DecodeDisk (ShelleyBlock proto era) (AnnTip (ShelleyBlock proto era)) where decodeDisk _ = decodeShelleyAnnTip ------------------------------------------------------------------------------ SerialiseNodeToNode ------------------------------------------------------------------------------ SerialiseNodeToNode -------------------------------------------------------------------------------} instance ShelleyCompatible proto era => SerialiseNodeToNodeConstraints (ShelleyBlock proto era) where estimateBlockSize hdr = overhead + hdrSize + bodySize where The maximum block size is 65536 , the CBOR - in - CBOR tag for this block -- is: -- -- > D8 18 # tag(24) -- > 1A 00010000 # bytes(65536) -- Which is 7 bytes , enough for up to 4294967295 bytes . overhead = 7 {- CBOR-in-CBOR -} + 1 {- encodeListLen -} bodySize = fromIntegral . pHeaderBlockSize . shelleyHeaderRaw $ hdr hdrSize = fromIntegral . pHeaderSize . shelleyHeaderRaw $ hdr -- | CBOR-in-CBOR for the annotation. This also makes it compatible with the -- wrapped ('Serialised') variant. instance ShelleyCompatible proto era => SerialiseNodeToNode (ShelleyBlock proto era) (ShelleyBlock proto era) where encodeNodeToNode _ _ = wrapCBORinCBOR encodeShelleyBlock decodeNodeToNode _ _ = unwrapCBORinCBOR decodeShelleyBlock -- | 'Serialised' uses CBOR-in-CBOR by default. instance SerialiseNodeToNode (ShelleyBlock proto era) (Serialised (ShelleyBlock proto era)) -- Default instance -- | CBOR-in-CBOR to be compatible with the wrapped ('Serialised') variant. instance ShelleyCompatible proto era => SerialiseNodeToNode (ShelleyBlock proto era) (Header (ShelleyBlock proto era)) where encodeNodeToNode _ _ = wrapCBORinCBOR encodeShelleyHeader decodeNodeToNode _ _ = unwrapCBORinCBOR decodeShelleyHeader -- | We use CBOR-in-CBOR instance SerialiseNodeToNode (ShelleyBlock proto era) (SerialisedHeader (ShelleyBlock proto era)) where encodeNodeToNode _ _ = encodeTrivialSerialisedHeader decodeNodeToNode _ _ = decodeTrivialSerialisedHeader -- | The @To/FromCBOR@ instances defined in @cardano-ledger@ use -- CBOR-in-CBOR to get the annotation. instance ShelleyCompatible proto era => SerialiseNodeToNode (ShelleyBlock proto era) (GenTx (ShelleyBlock proto era)) where encodeNodeToNode _ _ = toCBOR decodeNodeToNode _ _ = fromCBOR instance ShelleyCompatible proto era => SerialiseNodeToNode (ShelleyBlock proto era) (GenTxId (ShelleyBlock proto era)) where encodeNodeToNode _ _ = toEraCBOR @era decodeNodeToNode _ _ = fromEraCBOR @era {------------------------------------------------------------------------------- SerialiseNodeToClient -------------------------------------------------------------------------------} -- | Exception thrown in the encoders data ShelleyEncoderException era proto = -- | A query was submitted that is not supported by the given -- 'ShelleyNodeToClientVersion'. ShelleyEncoderUnsupportedQuery (SomeSecond BlockQuery (ShelleyBlock proto era)) ShelleyNodeToClientVersion deriving (Show) instance (Typeable era, Typeable proto) => Exception (ShelleyEncoderException era proto) instance ShelleyCompatible proto era => SerialiseNodeToClientConstraints (ShelleyBlock proto era) -- | CBOR-in-CBOR for the annotation. This also makes it compatible with the -- wrapped ('Serialised') variant. instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) (ShelleyBlock proto era) where encodeNodeToClient _ _ = wrapCBORinCBOR encodeShelleyBlock decodeNodeToClient _ _ = unwrapCBORinCBOR decodeShelleyBlock -- | 'Serialised' uses CBOR-in-CBOR by default. instance SerialiseNodeToClient (ShelleyBlock proto era) (Serialised (ShelleyBlock proto era)) -- Default instance -- | Uses CBOR-in-CBOR in the @To/FromCBOR@ instances to get the annotation. instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) (GenTx (ShelleyBlock proto era)) where encodeNodeToClient _ _ = toCBOR decodeNodeToClient _ _ = fromCBOR instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) (GenTxId (ShelleyBlock proto era)) where encodeNodeToClient _ _ = toEraCBOR @era decodeNodeToClient _ _ = fromEraCBOR @era | @'ApplyTxErr ' ' ( era)'@ instance ShelleyBasedEra era => SerialiseNodeToClient (ShelleyBlock proto era) (SL.ApplyTxError era) where encodeNodeToClient _ _ = toEraCBOR @era decodeNodeToClient _ _ = fromEraCBOR @era instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) (SomeSecond BlockQuery (ShelleyBlock proto era)) where encodeNodeToClient _ version (SomeSecond q) | querySupportedVersion q version = encodeShelleyQuery q | otherwise = throw $ ShelleyEncoderUnsupportedQuery (SomeSecond q) version decodeNodeToClient _ _ = decodeShelleyQuery instance ShelleyCompatible proto era => SerialiseResult (ShelleyBlock proto era) (BlockQuery (ShelleyBlock proto era)) where encodeResult _ _ = encodeShelleyResult decodeResult _ _ = decodeShelleyResult instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) SlotNo where encodeNodeToClient _ _ = toCBOR decodeNodeToClient _ _ = fromCBOR ------------------------------------------------------------------------------ HFC support Since ' NestedCtxt ' for is trivial , these instances can use defaults . ------------------------------------------------------------------------------ HFC support Since 'NestedCtxt' for Shelley is trivial, these instances can use defaults. -------------------------------------------------------------------------------} instance ShelleyBasedEra era => ReconstructNestedCtxt Header (ShelleyBlock proto era) instance ShelleyBasedEra era => EncodeDiskDepIx (NestedCtxt Header) (ShelleyBlock proto era) instance ShelleyCompatible proto era => EncodeDiskDep (NestedCtxt Header) (ShelleyBlock proto era) instance ShelleyBasedEra era => DecodeDiskDepIx (NestedCtxt Header) (ShelleyBlock proto era) instance ShelleyCompatible proto era => DecodeDiskDep (NestedCtxt Header) (ShelleyBlock proto era)
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/17889be3e1b6d9b5ee86022b91729837051e6fbb/ouroboros-consensus-shelley/src/Ouroboros/Consensus/Shelley/Node/Serialisation.hs
haskell
# LANGUAGE ScopedTypeVariables # ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} is: > D8 18 # tag(24) > 1A 00010000 # bytes(65536) CBOR-in-CBOR encodeListLen | CBOR-in-CBOR for the annotation. This also makes it compatible with the wrapped ('Serialised') variant. | 'Serialised' uses CBOR-in-CBOR by default. Default instance | CBOR-in-CBOR to be compatible with the wrapped ('Serialised') variant. | We use CBOR-in-CBOR | The @To/FromCBOR@ instances defined in @cardano-ledger@ use CBOR-in-CBOR to get the annotation. ------------------------------------------------------------------------------ SerialiseNodeToClient ------------------------------------------------------------------------------ | Exception thrown in the encoders | A query was submitted that is not supported by the given 'ShelleyNodeToClientVersion'. | CBOR-in-CBOR for the annotation. This also makes it compatible with the wrapped ('Serialised') variant. | 'Serialised' uses CBOR-in-CBOR by default. Default instance | Uses CBOR-in-CBOR in the @To/FromCBOR@ instances to get the annotation. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------}
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # OPTIONS_GHC -Wno - orphans # module Ouroboros.Consensus.Shelley.Node.Serialisation () where import Control.Exception (Exception, throw) import qualified Data.ByteString.Lazy as Lazy import Data.Typeable (Typeable) import Cardano.Ledger.Binary (fromCBOR, toCBOR) import Cardano.Ledger.Core (fromEraCBOR, toEraCBOR) import Codec.Serialise (decode, encode) import Ouroboros.Network.Block (Serialised, unwrapCBORinCBOR, wrapCBORinCBOR) import Ouroboros.Consensus.Block import Ouroboros.Consensus.HeaderValidation import Ouroboros.Consensus.Ledger.SupportsMempool (GenTxId) import Ouroboros.Consensus.Node.Run import Ouroboros.Consensus.Node.Serialisation import Ouroboros.Consensus.Storage.Serialisation import qualified Cardano.Ledger.Shelley.API as SL import qualified Cardano.Protocol.TPraos.API as SL import Ouroboros.Consensus.Protocol.Praos (PraosState) import qualified Ouroboros.Consensus.Protocol.Praos as Praos import Ouroboros.Consensus.Protocol.TPraos import Ouroboros.Consensus.Shelley.Eras import Ouroboros.Consensus.Shelley.Ledger import Ouroboros.Consensus.Shelley.Ledger.NetworkProtocolVersion () import Ouroboros.Consensus.Shelley.Protocol.Abstract (pHeaderBlockSize, pHeaderSize) EncodeDisk & DecodeDisk EncodeDisk & DecodeDisk instance ShelleyCompatible proto era => HasBinaryBlockInfo (ShelleyBlock proto era) where getBinaryBlockInfo = shelleyBinaryBlockInfo instance ShelleyCompatible proto era => SerialiseDiskConstraints (ShelleyBlock proto era) instance ShelleyCompatible proto era => EncodeDisk (ShelleyBlock proto era) (ShelleyBlock proto era) where encodeDisk _ = encodeShelleyBlock instance ShelleyCompatible proto era => DecodeDisk (ShelleyBlock proto era) (Lazy.ByteString -> ShelleyBlock proto era) where decodeDisk _ = decodeShelleyBlock instance ShelleyCompatible proto era => EncodeDisk (ShelleyBlock proto era) (Header (ShelleyBlock proto era)) where encodeDisk _ = encodeShelleyHeader instance ShelleyCompatible proto era => DecodeDisk (ShelleyBlock proto era) (Lazy.ByteString -> Header (ShelleyBlock proto era)) where decodeDisk _ = decodeShelleyHeader instance ShelleyCompatible proto era => EncodeDisk (ShelleyBlock proto era) (LedgerState (ShelleyBlock proto era)) where encodeDisk _ = encodeShelleyLedgerState instance ShelleyCompatible proto era => DecodeDisk (ShelleyBlock proto era) (LedgerState (ShelleyBlock proto era)) where decodeDisk _ = decodeShelleyLedgerState | @'ChainDepState ' ( ' BlockProtocol ' ( ' ' era))@ instance (ShelleyCompatible proto era, EraCrypto era ~ c, SL.PraosCrypto c) => EncodeDisk (ShelleyBlock proto era) (TPraosState c) where encodeDisk _ = encode | @'ChainDepState ' ( ' BlockProtocol ' ( ' ' era))@ instance (ShelleyCompatible proto era, EraCrypto era ~ c, SL.PraosCrypto c) => DecodeDisk (ShelleyBlock proto era) (TPraosState c) where decodeDisk _ = decode instance (ShelleyCompatible proto era, EraCrypto era ~ c, Praos.PraosCrypto c) => EncodeDisk (ShelleyBlock proto era) (PraosState c) where encodeDisk _ = encode | @'ChainDepState ' ( ' BlockProtocol ' ( ' ' era))@ instance (ShelleyCompatible proto era, EraCrypto era ~ c, Praos.PraosCrypto c) => DecodeDisk (ShelleyBlock proto era) (PraosState c) where decodeDisk _ = decode instance ShelleyCompatible proto era => EncodeDisk (ShelleyBlock proto era) (AnnTip (ShelleyBlock proto era)) where encodeDisk _ = encodeShelleyAnnTip instance ShelleyCompatible proto era => DecodeDisk (ShelleyBlock proto era) (AnnTip (ShelleyBlock proto era)) where decodeDisk _ = decodeShelleyAnnTip SerialiseNodeToNode SerialiseNodeToNode instance ShelleyCompatible proto era => SerialiseNodeToNodeConstraints (ShelleyBlock proto era) where estimateBlockSize hdr = overhead + hdrSize + bodySize where The maximum block size is 65536 , the CBOR - in - CBOR tag for this block Which is 7 bytes , enough for up to 4294967295 bytes . bodySize = fromIntegral . pHeaderBlockSize . shelleyHeaderRaw $ hdr hdrSize = fromIntegral . pHeaderSize . shelleyHeaderRaw $ hdr instance ShelleyCompatible proto era => SerialiseNodeToNode (ShelleyBlock proto era) (ShelleyBlock proto era) where encodeNodeToNode _ _ = wrapCBORinCBOR encodeShelleyBlock decodeNodeToNode _ _ = unwrapCBORinCBOR decodeShelleyBlock instance SerialiseNodeToNode (ShelleyBlock proto era) (Serialised (ShelleyBlock proto era)) instance ShelleyCompatible proto era => SerialiseNodeToNode (ShelleyBlock proto era) (Header (ShelleyBlock proto era)) where encodeNodeToNode _ _ = wrapCBORinCBOR encodeShelleyHeader decodeNodeToNode _ _ = unwrapCBORinCBOR decodeShelleyHeader instance SerialiseNodeToNode (ShelleyBlock proto era) (SerialisedHeader (ShelleyBlock proto era)) where encodeNodeToNode _ _ = encodeTrivialSerialisedHeader decodeNodeToNode _ _ = decodeTrivialSerialisedHeader instance ShelleyCompatible proto era => SerialiseNodeToNode (ShelleyBlock proto era) (GenTx (ShelleyBlock proto era)) where encodeNodeToNode _ _ = toCBOR decodeNodeToNode _ _ = fromCBOR instance ShelleyCompatible proto era => SerialiseNodeToNode (ShelleyBlock proto era) (GenTxId (ShelleyBlock proto era)) where encodeNodeToNode _ _ = toEraCBOR @era decodeNodeToNode _ _ = fromEraCBOR @era data ShelleyEncoderException era proto = ShelleyEncoderUnsupportedQuery (SomeSecond BlockQuery (ShelleyBlock proto era)) ShelleyNodeToClientVersion deriving (Show) instance (Typeable era, Typeable proto) => Exception (ShelleyEncoderException era proto) instance ShelleyCompatible proto era => SerialiseNodeToClientConstraints (ShelleyBlock proto era) instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) (ShelleyBlock proto era) where encodeNodeToClient _ _ = wrapCBORinCBOR encodeShelleyBlock decodeNodeToClient _ _ = unwrapCBORinCBOR decodeShelleyBlock instance SerialiseNodeToClient (ShelleyBlock proto era) (Serialised (ShelleyBlock proto era)) instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) (GenTx (ShelleyBlock proto era)) where encodeNodeToClient _ _ = toCBOR decodeNodeToClient _ _ = fromCBOR instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) (GenTxId (ShelleyBlock proto era)) where encodeNodeToClient _ _ = toEraCBOR @era decodeNodeToClient _ _ = fromEraCBOR @era | @'ApplyTxErr ' ' ( era)'@ instance ShelleyBasedEra era => SerialiseNodeToClient (ShelleyBlock proto era) (SL.ApplyTxError era) where encodeNodeToClient _ _ = toEraCBOR @era decodeNodeToClient _ _ = fromEraCBOR @era instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) (SomeSecond BlockQuery (ShelleyBlock proto era)) where encodeNodeToClient _ version (SomeSecond q) | querySupportedVersion q version = encodeShelleyQuery q | otherwise = throw $ ShelleyEncoderUnsupportedQuery (SomeSecond q) version decodeNodeToClient _ _ = decodeShelleyQuery instance ShelleyCompatible proto era => SerialiseResult (ShelleyBlock proto era) (BlockQuery (ShelleyBlock proto era)) where encodeResult _ _ = encodeShelleyResult decodeResult _ _ = decodeShelleyResult instance ShelleyCompatible proto era => SerialiseNodeToClient (ShelleyBlock proto era) SlotNo where encodeNodeToClient _ _ = toCBOR decodeNodeToClient _ _ = fromCBOR HFC support Since ' NestedCtxt ' for is trivial , these instances can use defaults . HFC support Since 'NestedCtxt' for Shelley is trivial, these instances can use defaults. instance ShelleyBasedEra era => ReconstructNestedCtxt Header (ShelleyBlock proto era) instance ShelleyBasedEra era => EncodeDiskDepIx (NestedCtxt Header) (ShelleyBlock proto era) instance ShelleyCompatible proto era => EncodeDiskDep (NestedCtxt Header) (ShelleyBlock proto era) instance ShelleyBasedEra era => DecodeDiskDepIx (NestedCtxt Header) (ShelleyBlock proto era) instance ShelleyCompatible proto era => DecodeDiskDep (NestedCtxt Header) (ShelleyBlock proto era)
7ce85e0a7d0337317103f0d9fabc30a0f795759e6ac1b5ec2de1692942a2fce9
vyorkin/tiger
escape.ml
open Core_kernel module S = Symbol module ST = Symbol_table type value = { (* Depth (nesting level) of the function that contains the variable declaration *) depth : int; (* If [true] then variable escapes *) escapes : bool ref; } (* Environment that maps variables to pairs of depth and a reference to a boolean flag indicating if a particular variable escapes *) module Table = struct include Map.Make (Symbol) end type env = { table : value Table.t; depth : int } In general , variable escapes if : - it is passed by reference - it is accessed from a nested function - its address is taken ( using C 's " & " operator ) - it is passed by reference - it is accessed from a nested function - its address is taken (using C's "&" operator) *) (* Whenever a variable or formal-parameter declaration [a] is found at static function-nesting [depth] then a new binding { depth; escapes = true } is entered into the environment. This new environment is used in processing expressions within the scope of the variable. Then whenever this var or formal-parameter [a] is used at depth > d (which means that it escapes), then our [escape] is set to [true] in the environment *) let traverse_prog expr = let open Syntax in let rec tr_expr expr ~env = match expr with | Var var -> tr_var var ~env | Call (_, args) -> tr_exprs args ~env | Op (l, _, r) -> tr_op l r ~env | Record (_, fields) -> tr_record fields ~env | Seq exprs -> tr_exprs exprs ~env | Assign (var, expr) -> tr_assign var expr ~env | If (cond, t, f) -> tr_cond cond t f ~env | While (cond, body) -> tr_while cond body ~env | For (var, lo, hi, body, escapes) -> tr_for var lo hi body escapes ~env | Let (decs, body) -> tr_let decs body ~env | Array (_, size, body) -> tr_array size body ~env | Nil _ | Int _ | String _ | Break _ -> () and tr_exprs exprs ~env = List.iter exprs ~f:(fun e -> tr_expr e.L.value ~env) and tr_op l r ~env = tr_expr l.L.value ~env; tr_expr r.L.value ~env and tr_record fields ~env = fields |> List.map ~f:snd |> tr_exprs ~env and tr_assign var expr ~env = tr_var var ~env; tr_expr expr.L.value ~env and tr_cond cond t f ~env = tr_expr cond.L.value ~env; tr_expr t.L.value ~env; ignore @@ Option.map f ~f:(fun e -> tr_expr e.L.value ~env) and tr_while cond body ~env = tr_expr cond.L.value ~env; tr_expr body.L.value ~env; and tr_for var lo hi body escapes ~env = tr_expr lo.L.value ~env:env; tr_expr hi.L.value ~env:env; (* Add iterator var to the env *) let data = { depth = env.depth; escapes } in let table' = Table.set env.table ~key:var.L.value ~data in let env' = { env with table = table' } in tr_expr body.L.value ~env:env' and tr_var var ~env = match var.L.value with | SimpleVar sym -> (match Table.find env.table sym.L.value with | Some v -> (* If we're deeper than the depth at which variable was defined then it is considered as escaping *) if env.depth > v.depth then begin v.escapes := true; Trace.Escaping.escapes sym env.depth end | None -> ()) | FieldVar (var, _) -> tr_var var ~env | SubscriptVar (var, expr) -> tr_var var ~env; tr_expr expr.L.value ~env and tr_let decs body ~env = (* Update env according to declarations *) let env' = tr_decs decs ~env in (* Then translate the body expression using the new augmented environments *) tr_expr body.L.value ~env:env' and tr_array size body ~env = tr_expr size.L.value ~env; tr_expr body.L.value ~env and tr_decs decs ~env = List.fold_left decs ~f:(fun env dec -> tr_dec dec ~env) ~init:env and tr_dec ~env = function | TypeDec _ -> env | VarDec var_dec -> tr_var_dec var_dec ~env | FunDec fun_decs -> tr_fun_decs fun_decs ~env and tr_var_dec var ~env = let data = { depth = env.depth; escapes = var.L.value.escapes } in let key = L.(var.value.var_name.value) in let table' = Table.set env.table ~key ~data in { env with table = table' } and tr_fun_decs decs ~env = List.fold_left decs ~f:(fun env dec -> tr_fun_dec dec.L.value ~env) ~init:env and tr_fun_dec dec ~env = let depth = env.depth + 1 in let add_arg table (arg : field) = let data = { depth; escapes = arg.escapes } in Table.set table ~key:arg.name.L.value ~data in let table' = List.fold_left dec.params ~f:add_arg ~init:env.table in let env' = { table = table'; depth } in tr_expr dec.body.L.value ~env:env'; env in let env = { table = Table.empty; depth = 0 } in tr_expr expr ~env This phase must occur before semantic analysis begins , since [ Semant ] module needs to know whether a variable escapes immediately upon seeing that var for the first time since [Semant] module needs to know whether a variable escapes immediately upon seeing that var for the first time *)
null
https://raw.githubusercontent.com/vyorkin/tiger/54dd179c1cd291df42f7894abce3ee9064e18def/chapter6/lib/escape.ml
ocaml
Depth (nesting level) of the function that contains the variable declaration If [true] then variable escapes Environment that maps variables to pairs of depth and a reference to a boolean flag indicating if a particular variable escapes Whenever a variable or formal-parameter declaration [a] is found at static function-nesting [depth] then a new binding { depth; escapes = true } is entered into the environment. This new environment is used in processing expressions within the scope of the variable. Then whenever this var or formal-parameter [a] is used at depth > d (which means that it escapes), then our [escape] is set to [true] in the environment Add iterator var to the env If we're deeper than the depth at which variable was defined then it is considered as escaping Update env according to declarations Then translate the body expression using the new augmented environments
open Core_kernel module S = Symbol module ST = Symbol_table type value = { depth : int; escapes : bool ref; } module Table = struct include Map.Make (Symbol) end type env = { table : value Table.t; depth : int } In general , variable escapes if : - it is passed by reference - it is accessed from a nested function - its address is taken ( using C 's " & " operator ) - it is passed by reference - it is accessed from a nested function - its address is taken (using C's "&" operator) *) let traverse_prog expr = let open Syntax in let rec tr_expr expr ~env = match expr with | Var var -> tr_var var ~env | Call (_, args) -> tr_exprs args ~env | Op (l, _, r) -> tr_op l r ~env | Record (_, fields) -> tr_record fields ~env | Seq exprs -> tr_exprs exprs ~env | Assign (var, expr) -> tr_assign var expr ~env | If (cond, t, f) -> tr_cond cond t f ~env | While (cond, body) -> tr_while cond body ~env | For (var, lo, hi, body, escapes) -> tr_for var lo hi body escapes ~env | Let (decs, body) -> tr_let decs body ~env | Array (_, size, body) -> tr_array size body ~env | Nil _ | Int _ | String _ | Break _ -> () and tr_exprs exprs ~env = List.iter exprs ~f:(fun e -> tr_expr e.L.value ~env) and tr_op l r ~env = tr_expr l.L.value ~env; tr_expr r.L.value ~env and tr_record fields ~env = fields |> List.map ~f:snd |> tr_exprs ~env and tr_assign var expr ~env = tr_var var ~env; tr_expr expr.L.value ~env and tr_cond cond t f ~env = tr_expr cond.L.value ~env; tr_expr t.L.value ~env; ignore @@ Option.map f ~f:(fun e -> tr_expr e.L.value ~env) and tr_while cond body ~env = tr_expr cond.L.value ~env; tr_expr body.L.value ~env; and tr_for var lo hi body escapes ~env = tr_expr lo.L.value ~env:env; tr_expr hi.L.value ~env:env; let data = { depth = env.depth; escapes } in let table' = Table.set env.table ~key:var.L.value ~data in let env' = { env with table = table' } in tr_expr body.L.value ~env:env' and tr_var var ~env = match var.L.value with | SimpleVar sym -> (match Table.find env.table sym.L.value with | Some v -> if env.depth > v.depth then begin v.escapes := true; Trace.Escaping.escapes sym env.depth end | None -> ()) | FieldVar (var, _) -> tr_var var ~env | SubscriptVar (var, expr) -> tr_var var ~env; tr_expr expr.L.value ~env and tr_let decs body ~env = let env' = tr_decs decs ~env in tr_expr body.L.value ~env:env' and tr_array size body ~env = tr_expr size.L.value ~env; tr_expr body.L.value ~env and tr_decs decs ~env = List.fold_left decs ~f:(fun env dec -> tr_dec dec ~env) ~init:env and tr_dec ~env = function | TypeDec _ -> env | VarDec var_dec -> tr_var_dec var_dec ~env | FunDec fun_decs -> tr_fun_decs fun_decs ~env and tr_var_dec var ~env = let data = { depth = env.depth; escapes = var.L.value.escapes } in let key = L.(var.value.var_name.value) in let table' = Table.set env.table ~key ~data in { env with table = table' } and tr_fun_decs decs ~env = List.fold_left decs ~f:(fun env dec -> tr_fun_dec dec.L.value ~env) ~init:env and tr_fun_dec dec ~env = let depth = env.depth + 1 in let add_arg table (arg : field) = let data = { depth; escapes = arg.escapes } in Table.set table ~key:arg.name.L.value ~data in let table' = List.fold_left dec.params ~f:add_arg ~init:env.table in let env' = { table = table'; depth } in tr_expr dec.body.L.value ~env:env'; env in let env = { table = Table.empty; depth = 0 } in tr_expr expr ~env This phase must occur before semantic analysis begins , since [ Semant ] module needs to know whether a variable escapes immediately upon seeing that var for the first time since [Semant] module needs to know whether a variable escapes immediately upon seeing that var for the first time *)
c054f91c65353b81af6c9d05c60fe3713ec16c31fe490d5aa5ae28200b3f7387
EarnestResearch/honeycomb-haskell
RIO.hs
# LANGUAGE CPP # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE NoImplicitPrelude # {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # -- | Module : Servant . Server . Honeycomb . RIO Description : Honeycomb - based tracing for Servant applications using the RIO monad Copyright : ( c ) 2020 Earnest Research -- License : Apache-2 -- Maintainer : -- Stability : alpha -- Portability : POSIX module Servant.Server.Honeycomb.RIO ( traceServerRIO, traceServerRIOWithContext, genericTraceServerRIO, genericTraceServerWithContextRIO, ) where import Control.Monad.Except (ExceptT (..)) import Data.Kind (Type) import qualified Honeycomb.Trace as HC import Network.Wai.Honeycomb.Servant import Network.Wai.UnliftIO (liftApplication, runApplicationT) import RIO hiding (Handler) import Servant import Servant.API.Generic (AsApi, GenericServant, ToServant, ToServantApi) import Servant.Server.Generic import Servant.Server.Honeycomb #if MIN_VERSION_servant_server(0,18,0) import Servant.Server.Internal.ErrorFormatter (DefaultErrorFormatters, ErrorFormatters) #endif import Servant.Honeycomb (HasRequestInfo) | Trace a RIO - based Servant service with Honeycomb . -- Each request is placed in a trace , and reported to Honeycomb . -- The current span context is also available within the service, so -- it may be used to pass tracing information downstream to further -- services. traceServerRIO :: ( HC.HasHoney env, HC.HasSpanContext env, HasServer api '[], HasRequestInfo api ) => -- | Proxy representing Servant API Proxy api -> -- | Honeycomb service name HC.ServiceName -> HC.SpanName -> | Implementation of service ( in RIO monad ) ServerT api (RIO env) -> RIO env Application traceServerRIO proxy service spanName app = traceServer proxy service spanName app runService traceServerRIOWithContext :: ( HC.HasHoney env, HC.HasSpanContext env, HasServer api ctx, #if MIN_VERSION_servant_server(0,18,0) HasContextEntry (ctx .++ DefaultErrorFormatters) ErrorFormatters, #endif HasRequestInfo api ) => Context ctx -> -- | Proxy representing Servant API Proxy api -> -- | Honeycomb service name HC.ServiceName -> HC.SpanName -> | Implementation of service ( in RIO monad ) ServerT api (RIO env) -> RIO env Application traceServerRIOWithContext context proxy service spanName app = traceServerWithContext context proxy service spanName app runService genericTraceServerRIO :: forall (routes :: Type -> Type) (env :: Type) (api :: Type). ( HC.HasHoney env, HC.HasSpanContext env, HasRequestInfo api, GenericServant routes (AsServerT (RIO env)), GenericServant routes AsApi, HasServer (ToServantApi routes) '[], ServerT (ToServantApi routes) (RIO env) ~ ToServant routes (AsServerT (RIO env)) ) => Proxy api -> HC.ServiceName -> HC.SpanName -> routes (AsServerT (RIO env)) -> RIO env Application genericTraceServerRIO api service spanName routes = do env <- ask runApplicationT . traceApplicationT api service spanName . liftApplication $ genericServeT (runService env) routes genericTraceServerWithContextRIO :: forall (routes :: Type -> Type) (ctx :: [Type]) (env :: Type) (api :: Type). ( HC.HasHoney env, HC.HasSpanContext env, HasRequestInfo api, GenericServant routes (AsServerT (RIO env)), GenericServant routes AsApi, HasServer (ToServantApi routes) ctx, #if MIN_VERSION_servant_server(0,18,0) HasContextEntry (ctx .++ DefaultErrorFormatters) ErrorFormatters, #endif ServerT (ToServantApi routes) (RIO env) ~ ToServant routes (AsServerT (RIO env)) ) => Context ctx -> Proxy api -> HC.ServiceName -> HC.SpanName -> routes (AsServerT (RIO env)) -> RIO env Application genericTraceServerWithContextRIO context api service spanName routes = do env <- ask runApplicationT . traceApplicationT api service spanName . liftApplication $ genericServeTWithContext (runService env) routes context runService :: env -> RIO env a -> Handler a runService env inner = Handler . ExceptT . try $ runRIO env inner
null
https://raw.githubusercontent.com/EarnestResearch/honeycomb-haskell/7b3ad1cb7b89ba0c2348f2cd2a1f9c641cfe00f9/honeycomb-servant-server-rio/src/Servant/Server/Honeycomb/RIO.hs
haskell
# LANGUAGE RankNTypes # | License : Apache-2 Maintainer : Stability : alpha Portability : POSIX The current span context is also available within the service, so it may be used to pass tracing information downstream to further services. | Proxy representing Servant API | Honeycomb service name | Proxy representing Servant API | Honeycomb service name
# LANGUAGE CPP # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE NoImplicitPrelude # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # Module : Servant . Server . Honeycomb . RIO Description : Honeycomb - based tracing for Servant applications using the RIO monad Copyright : ( c ) 2020 Earnest Research module Servant.Server.Honeycomb.RIO ( traceServerRIO, traceServerRIOWithContext, genericTraceServerRIO, genericTraceServerWithContextRIO, ) where import Control.Monad.Except (ExceptT (..)) import Data.Kind (Type) import qualified Honeycomb.Trace as HC import Network.Wai.Honeycomb.Servant import Network.Wai.UnliftIO (liftApplication, runApplicationT) import RIO hiding (Handler) import Servant import Servant.API.Generic (AsApi, GenericServant, ToServant, ToServantApi) import Servant.Server.Generic import Servant.Server.Honeycomb #if MIN_VERSION_servant_server(0,18,0) import Servant.Server.Internal.ErrorFormatter (DefaultErrorFormatters, ErrorFormatters) #endif import Servant.Honeycomb (HasRequestInfo) | Trace a RIO - based Servant service with Honeycomb . Each request is placed in a trace , and reported to Honeycomb . traceServerRIO :: ( HC.HasHoney env, HC.HasSpanContext env, HasServer api '[], HasRequestInfo api ) => Proxy api -> HC.ServiceName -> HC.SpanName -> | Implementation of service ( in RIO monad ) ServerT api (RIO env) -> RIO env Application traceServerRIO proxy service spanName app = traceServer proxy service spanName app runService traceServerRIOWithContext :: ( HC.HasHoney env, HC.HasSpanContext env, HasServer api ctx, #if MIN_VERSION_servant_server(0,18,0) HasContextEntry (ctx .++ DefaultErrorFormatters) ErrorFormatters, #endif HasRequestInfo api ) => Context ctx -> Proxy api -> HC.ServiceName -> HC.SpanName -> | Implementation of service ( in RIO monad ) ServerT api (RIO env) -> RIO env Application traceServerRIOWithContext context proxy service spanName app = traceServerWithContext context proxy service spanName app runService genericTraceServerRIO :: forall (routes :: Type -> Type) (env :: Type) (api :: Type). ( HC.HasHoney env, HC.HasSpanContext env, HasRequestInfo api, GenericServant routes (AsServerT (RIO env)), GenericServant routes AsApi, HasServer (ToServantApi routes) '[], ServerT (ToServantApi routes) (RIO env) ~ ToServant routes (AsServerT (RIO env)) ) => Proxy api -> HC.ServiceName -> HC.SpanName -> routes (AsServerT (RIO env)) -> RIO env Application genericTraceServerRIO api service spanName routes = do env <- ask runApplicationT . traceApplicationT api service spanName . liftApplication $ genericServeT (runService env) routes genericTraceServerWithContextRIO :: forall (routes :: Type -> Type) (ctx :: [Type]) (env :: Type) (api :: Type). ( HC.HasHoney env, HC.HasSpanContext env, HasRequestInfo api, GenericServant routes (AsServerT (RIO env)), GenericServant routes AsApi, HasServer (ToServantApi routes) ctx, #if MIN_VERSION_servant_server(0,18,0) HasContextEntry (ctx .++ DefaultErrorFormatters) ErrorFormatters, #endif ServerT (ToServantApi routes) (RIO env) ~ ToServant routes (AsServerT (RIO env)) ) => Context ctx -> Proxy api -> HC.ServiceName -> HC.SpanName -> routes (AsServerT (RIO env)) -> RIO env Application genericTraceServerWithContextRIO context api service spanName routes = do env <- ask runApplicationT . traceApplicationT api service spanName . liftApplication $ genericServeTWithContext (runService env) routes context runService :: env -> RIO env a -> Handler a runService env inner = Handler . ExceptT . try $ runRIO env inner
473e9ff06419b0fd31ff35822a35e6293250d9c8086c7a8e26b59297786518e5
brownplt/cs173-python
python-desugar.rkt
#lang plai-typed (require "python-syntax.rkt" "python-core-syntax.rkt") (define (desugar expr) (type-case PyExpr expr [PySeq (es) (foldl (lambda (e1 e2) (CSeq e2 (desugar e1))) (desugar (first es)) (rest es))] [PyNum (n) (CNum n)] [PyApp (f args) (CApp (desugar f) (map desugar args))] [PyId (x) (CId x)]))
null
https://raw.githubusercontent.com/brownplt/cs173-python/d8ae026172f269282e54366f16ec42e037117cb4/python-desugar.rkt
racket
#lang plai-typed (require "python-syntax.rkt" "python-core-syntax.rkt") (define (desugar expr) (type-case PyExpr expr [PySeq (es) (foldl (lambda (e1 e2) (CSeq e2 (desugar e1))) (desugar (first es)) (rest es))] [PyNum (n) (CNum n)] [PyApp (f args) (CApp (desugar f) (map desugar args))] [PyId (x) (CId x)]))
b6f4a6a71daa4957453f9ad31df721002f33d1081aea88255ef8cbf4d88c6ea3
GaloisInc/jvm-verifier
Debugger.hs
# LANGUAGE LambdaCase # | Module : Verifier . Java . Debugger Description : Debugger implementation for JSS License : BSD3 Stability : provisional Point - of - contact : acfoltzer Debugger for the JVM Symbolic Simulator . This module provides implementations of the ' SEH ' event handlers . Module : Verifier.Java.Debugger Description : Debugger implementation for JSS License : BSD3 Stability : provisional Point-of-contact : acfoltzer Debugger for the JVM Symbolic Simulator. This module provides implementations of the 'SEH' event handlers. -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # # LANGUAGE CPP # # LANGUAGE FlexibleContexts # module Verifier.Java.Debugger ( breakOnMain , breakpointLogger , debuggerREPL , runAtBreakpoints ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Trans import Control.Lens import Data.Char import Data.List ( intercalate, isPrefixOf, stripPrefix ) import Data.List.Split import qualified Data.Map as M import qualified Data.Set as S import Data.Word (Word16) import System.Console.Haskeline import System.Console.Haskeline.History import System.Exit import Text.PrettyPrint import Data.JVM.Symbolic.AST import Verifier.Java.Common hiding (isFinished) import Verifier.Java.Simulator hiding (getCurrentClassName, getCurrentMethod, isFinished) import Prelude hiding ((<>)) #if __GLASGOW_HASKELL__ < 706 import qualified Text.ParserCombinators.ReadP as P import qualified Text.Read as R readEither :: Read a => String -> Either String a readEither s = case [ x | (x,"") <- R.readPrec_to_S read' R.minPrec s ] of [x] -> Right x [] -> Left "Prelude.read: no parse" _ -> Left "Prelude.read: ambiguous parse" where read' = do x <- R.readPrec R.lift P.skipSpaces return x -- | Parse a string using the 'Read' instance. Succeeds if there is exactly one valid result . readMaybe :: Read a => String -> Maybe a readMaybe s = case readEither s of Left _ -> Nothing Right a -> Just a #else import Text.Read (readMaybe) #endif uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (a, b, c) = f a b c -- | Add a breakpoint to the @main@ method of the given class breakOnMain :: ClassName -> Simulator sbe m () breakOnMain clName = addBreakpoint clName mainKey BreakEntry -- | Given a step handler, return a new step handler that runs it when -- breakpoints are encountered runAtBreakpoints :: (Functor m, Monad m) => (Maybe PC -> SymInsn -> Simulator sbe m ()) -> Maybe PC -> SymInsn -> Simulator sbe m () runAtBreakpoints sh (Just pc) insn = do atTransient <- handleTransientBreakpoints pc insn if atTransient then sh (Just pc) insn else do mp <- getPathMaybe case currentCallFrame =<< mp of Nothing -> return () Just cf -> do let clName = cf^.cfClass method = cf^.cfMethod mbps <- M.lookup (clName, method) <$> use breakpoints case S.member pc <$> mbps of Nothing -> return () Just False -> return () Just True -> sh (Just pc) insn runAtBreakpoints _ _ _ = return () -- | Check whether we're at a transient breakpoint, and if so, -- deactivate it and return 'True' handleTransientBreakpoints :: PC -> SymInsn -> Simulator sbe m Bool handleTransientBreakpoints pc insn = do method <- getCurrentMethod mLineNum <- getCurrentLineNumber pc let rember bp = do tbps <- use trBreakpoints if S.member bp tbps then do trBreakpoints %= S.delete bp return True else return False handleStep = rember BreakNextInsn handleRet = case insn of ReturnVal -> rember (BreakReturnFrom method) ReturnVoid -> rember (BreakReturnFrom method) _ -> return False handleLineChange = do tbps <- use trBreakpoints or <$> forM (S.elems tbps) (\bp -> case bp of BreakLineChange mLineNum' | mLineNum /= mLineNum' -> do rember (BreakLineChange mLineNum') _ -> return False) or <$> sequence [handleStep, handleRet, handleLineChange] breakpointLogger :: (Functor m, Monad m) => Maybe PC -> SymInsn -> Simulator sbe m () breakpointLogger = runAtBreakpoints (printLoc "hit breakpoint:") printLoc :: (Functor m, Monad m) => String -> Maybe PC -> SymInsn -> Simulator sbe m () printLoc msg mpc insn = do clName <- getCurrentClassName method <- getCurrentMethod let lineNum = maybe "unknown" (integer . fromIntegral) $ sourceLineNumberOrPrev method =<< mpc pc = maybe "unknown" (integer . fromIntegral) mpc dbugM . render $ text msg <+> text (unClassName clName) <> "." <> ppMethod method <> colon <> lineNum <> "%" <> pc <> colon <> ppSymInsn insn debuggerREPL :: (MonadSim sbe m) => Maybe PC -> SymInsn -> Simulator sbe m () debuggerREPL mpc insn = do printLoc "at" mpc insn let settings = setComplete completer $ defaultSettings { historyFile = Just ".jssdb" } runInputT settings loop where loop = do mline <- getInputLine "jss% " case mline of Nothing -> return () Just "" -> do -- repeat last command if nothing entered hist <- getHistory case historyLines hist of (l:_) -> doCmd (words l) _ -> loop Just input -> doCmd (words input) doCmd (cmd:args) = do case M.lookup cmd commandMap of Just cmd' -> do let go = cmdAction cmd' mpc insn args handleErr epe@(ErrorPathExc _ _) = throwSM epe handleErr (UnknownExc (Just (FailRsn rsn))) = do dbugM $ "error: " ++ rsn return False handleErr _ = do dbugM "unknown error"; return False continue <- lift $ catchSM go handleErr unless continue loop Nothing -> do outputStrLn $ "unknown command '" ++ cmd ++ "'" outputStrLn $ "type 'help' for more info" loop doCmd [] = error "unreachable" data Command m = Cmd { cmdNames :: [String] , cmdArgs :: [String] , cmdDesc :: String , cmdCompletion :: CompletionFunc m , cmdAction :: Maybe PC -> SymInsn -> [String] -> m Bool } commandMap :: MonadSim sbe m => M.Map String (Command (Simulator sbe m)) commandMap = M.fromList . concatMap expandNames $ cmds where expandNames cmd = do name <- cmdNames cmd return (name, cmd) cmds :: MonadSim sbe m => [Command (Simulator sbe m)] cmds = [ helpCmd , whereCmd , localsCmd , dumpCmd , contCmd , killCmd , satpathCmd , exitCmd , clearCmd , stopinCmd , clearinCmd , stopatCmd , clearatCmd , stoppcCmd , clearpcCmd , stepCmd , stepupCmd , stepiCmd ] killCmd :: (MonadSim sbe m) => Command (Simulator sbe m) killCmd = Cmd { cmdNames = ["kill"] , cmdArgs = ["[<msg>]"] , cmdDesc = "throw an exception on the current execution path" , cmdCompletion = noCompletion , cmdAction = \_ _ args -> do let rte = "java/lang/RuntimeException" when (null args) $ createAndThrow rte refFromString (unwords args) >>= \case msgStr@(Ref _ ty) -> do let params = Just [(ty, RValue msgStr)] exc <- createInstance rte params throw exc error "unreachable" _ -> failHelp } satpathCmd :: (MonadSim sbe m) => Command (Simulator sbe m) satpathCmd = Cmd { cmdNames = ["satpath"] , cmdArgs = [] , cmdDesc = "check whether the current path's assertions are satisfiable, killing this path if they are not" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do p <- getPath "debugger" sbe <- use backend sat <- liftIO $ satTerm sbe (p^.pathAssertions) if sat then do dbugM "path assertions satisfiable" return False else do dbugM "path assertions unsatisfiable; killed" errorPath $ FailRsn "path assertions unsatisfiable: killed by debugger" } whereCmd :: (Functor m, Monad m) => Command (Simulator sbe m) whereCmd = Cmd { cmdNames = ["where", "w"] , cmdArgs = [] , cmdDesc = "print call stack" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do mp <- getPathMaybe case mp of Nothing -> dbugM "no active execution path" Just p -> dbugM . render . ppStackTrace $ p^.pathStack return False } localsCmd :: MonadSim sbe m => Command (Simulator sbe m) localsCmd = Cmd { cmdNames = ["locals"] , cmdArgs = [] , cmdDesc = "print local variables in current stack frame" , cmdCompletion = noCompletion , cmdAction = \mpc _ _ -> do locals <- modifyCallFrameM "debugger" $ \cf -> return (cf^.cfLocals, cf) sbe <- use backend case mpc of Nothing -> dbugM . render $ ppLocals sbe locals Just pc -> do method <- getCurrentMethod dbugM . render =<< ppNamedLocals method pc locals return False } contCmd :: Monad m => Command m contCmd = Cmd { cmdNames = ["cont", "c"] , cmdArgs = [] , cmdDesc = "continue execution" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> return True } stopinCmd :: MonadSim sbe m => Command (Simulator sbe m) stopinCmd = Cmd { cmdNames = ["stopin"] , cmdArgs = ["<class id>.<method>[<type_descriptor>]"] , cmdDesc = "set a breakpoint in a method; type descriptor is optional" , cmdCompletion = methodCompletion , cmdAction = \_ _ args -> case args of [arg] -> do bps <- entriesForArg arg forM_ bps $ uncurry3 addBreakpoint return False _ -> failHelp } clearinCmd :: MonadSim sbe m => Command (Simulator sbe m) clearinCmd = Cmd { cmdNames = ["clearin"] , cmdArgs = ["<class id>.<method>[<type_descriptor>]"] , cmdDesc = "clear a breakpoint in a method; type descriptor is optional" , cmdCompletion = methodCompletion , cmdAction = \_ _ args -> case args of [arg] -> do bps <- entriesForArg arg forM_ bps $ uncurry3 removeBreakpoint return False _ -> failHelp } entriesForArg :: String -> Simulator sbe m [(ClassName, MethodKey, Breakpoint)] entriesForArg arg = do (clName, keys) <- keysForArg arg return . map (clName, , BreakEntry) $ keys -- | Given a string expected to be a method signature of the form @com . Foo.bar@ or @com . Foo.bar(I)V@ , return the class name and a -- list of method keys that correspond to that method keysForArg :: String -> Simulator sbe m (ClassName, [MethodKey]) keysForArg arg = do let (sig, desc) = break (== '(') arg ids = reverse (splitOn "." sig) clName <- case ids of (_methStr:rest) -> return . mkClassName . intercalate "/" . reverse $ rest _ -> fail $ "invalid method signature " ++ arg methName <- case ids of (methStr:_) -> return methStr _ -> fail $ "invalid method signature " ++ arg cl <- lookupClass clName let keys | not (null desc) = [makeMethodKey methName desc] | otherwise = concatMap (makeKeys . methodKey) (classMethods cl) makeKeys key = if thisName == methName then [key] else [] where thisName = methodKeyName key return (clName, keys) stopatCmd :: MonadSim sbe m => Command (Simulator sbe m) stopatCmd = Cmd { cmdNames = ["stopat"] , cmdArgs = ["<class id>:<line>"] , cmdDesc = "set a breakpoint at a line" , cmdCompletion = classCompletion , cmdAction = \_ _ args -> case args of [arg] -> do uncurry3 removeBreakpoint =<< lineNumForArg arg return False _ -> failHelp } clearatCmd :: MonadSim sbe m => Command (Simulator sbe m) clearatCmd = Cmd { cmdNames = ["clearat"] , cmdArgs = ["<class id>:<line>"] , cmdDesc = "clear a breakpoint at a line" , cmdCompletion = classCompletion , cmdAction = \_ _ args -> case args of [arg] -> do uncurry3 removeBreakpoint =<< lineNumForArg arg return False _ -> failHelp } stoppcCmd :: MonadSim sbe m => Command (Simulator sbe m) stoppcCmd = Cmd { cmdNames = ["stoppc"] , cmdArgs = ["<class id>.<method>[<type_descriptor>]%pc"] , cmdDesc = "set a breakpoint at a program counter" , cmdCompletion = methodCompletion , cmdAction = \_ _ args -> case args of [arg] -> do bps <- pcsForArg arg forM_ bps $ uncurry3 addBreakpoint return False _ -> failHelp } clearpcCmd :: MonadSim sbe m => Command (Simulator sbe m) clearpcCmd = Cmd { cmdNames = ["clearpc"] , cmdArgs = ["<class id>.<method>[<type_descriptor>]%pc"] , cmdDesc = "clear a breakpoint at a program counter" , cmdCompletion = methodCompletion , cmdAction = \_ _ args -> case args of [arg] -> do bps <- pcsForArg arg forM_ bps $ uncurry3 removeBreakpoint return False _ -> failHelp } -- | Complete a class name as the current word classCompletion :: MonadSim sbe m => CompletionFunc (Simulator sbe m) classCompletion = completeWordWithPrev Nothing " " fn where fn _revleft word = do cb <- use codebase classes <- liftIO $ getClasses cb return . map (notFinished . simpleCompletion) . filter (word `isPrefixOf`) . map (slashesToDots . unClassName . className) $ classes -- | Complete a method signature as the current word methodCompletion :: MonadSim sbe m => CompletionFunc (Simulator sbe m) methodCompletion = completeWordWithPrev Nothing " " fn where fn _revleft word = do cb <- use codebase classes <- liftIO $ getClasses cb let classNames = map (slashesToDots . unClassName . className) classes strictPrefixOf pfx xs = pfx `isPrefixOf` xs && pfx /= xs matches = filter (word `strictPrefixOf`) classNames case matches of -- still working on a class name _:_ -> return . map (notFinished . simpleCompletion) $ matches -- otherwise on a method, so figure out which classes we completed [] -> do let matches' = filter (`isPrefixOf` word) classNames concat <$> forM matches' (\clName -> do cl <- lookupClass (mkClassName clName) -- expect methods in their pretty-printed form let methodNames = map (render . ppMethod) . classMethods $ cl cleanup = notFinished . simpleCompletion . ((clName ++ ".") ++) case stripPrefix clName word of Just prefix -> do let prefix' = case prefix of '.':rest -> rest _ -> prefix return . map cleanup . filter (prefix' `isPrefixOf`) $ methodNames Nothing -> return . map cleanup $ methodNames) notFinished :: Completion -> Completion notFinished c = c { isFinished = False } clearCmd :: Command (Simulator sbe m) clearCmd = Cmd { cmdNames = ["clear"] , cmdArgs = [] , cmdDesc = "list breakpoints" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> dumpBPs >> return False } dumpBPs :: Simulator sbe m () dumpBPs = do bps <- use breakpoints if all S.null (M.elems bps) then dbugM "no breakpoints set" else dbugM . render . ppBreakpoints $ bps pcsForArg :: String -> Simulator sbe m [(ClassName, MethodKey, Breakpoint)] pcsForArg arg = do let (method, pcStr) = break (== '%') arg pc <- case readMaybe (drop 1 pcStr) of Just (n :: Word16) -> return n Nothing -> fail $ "invalid program counter " ++ pcStr (clName, keys) <- keysForArg method return . map (clName, , BreakPC pc) $ keys lineNumForArg :: String -> Simulator sbe m (ClassName, MethodKey, Breakpoint) lineNumForArg arg = do let (clStr, lnStr) = break (== ':') arg let clName = mkClassName clStr lineNum <- case readMaybe (drop 1 lnStr) of Just (n :: Word16) -> return n Nothing -> fail $ "invalid line number " ++ lnStr cl <- lookupClass clName case lookupLineMethodStartPC cl lineNum of Just (method, _pc) -> return (clName, (methodKey method), (BreakLineNum lineNum)) Nothing -> fail . render $ "line number" <+> integer (fromIntegral lineNum) <+> "not found in" <+> text clStr $$ "were class files compiled with debugging symbols?" dumpCmd :: MonadSim sbe m => Command (Simulator sbe m) dumpCmd = let args = ["ctrlstk", "memory", "method", "path"] in Cmd { cmdNames = ["dump", "d"] , cmdArgs = args , cmdDesc = "dump an object in the simulator" , cmdCompletion = completeWordWithPrev Nothing " " $ \revleft word -> do case length . words $ revleft of only dump one thing at a time 1 -> return . map simpleCompletion . filter (word `isPrefixOf`) $ args _ -> return [] , cmdAction = \_ _ args' -> do case args' of ["ctrlstk"] -> dumpCtrlStk ["memory"] -> dumpMemory "debugger" ["method"] -> dumpCurrentMethod ["path"] -> dumpCurrentPath _ -> dbugM $ "dump: unsupported object " ++ unwords args' return False } stepCmd :: (Functor m, Monad m) => Command (Simulator sbe m) stepCmd = Cmd { cmdNames = ["step", "s"] , cmdArgs = [] , cmdDesc = "execute current line" , cmdCompletion = noCompletion , cmdAction = \mpc _ _ -> do case mpc of Just pc -> breakLineChange pc >> return True Nothing -> dbugM "unknown current line (try 'stepi')" >> return False } stepupCmd :: (Functor m, Monad m) => Command (Simulator sbe m) stepupCmd = Cmd { cmdNames = ["stepup"] , cmdArgs = [] , cmdDesc = "execute until current method returns to its caller" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do breakCurrentMethodReturn return True } stepiCmd :: (Functor m, Monad m) => Command (Simulator sbe m) stepiCmd = Cmd { cmdNames = ["stepi"] , cmdArgs = [] , cmdDesc = "execute current symbolic instruction" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do breakNextInsn return True } exitCmd :: MonadIO m => Command m exitCmd = Cmd { cmdNames = ["exit", "quit"] , cmdArgs = [] , cmdDesc = "exit JSS" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> liftIO $ exitWith ExitSuccess } helpCmd :: forall sbe m . MonadSim sbe m => Command (Simulator sbe m) helpCmd = Cmd { cmdNames = ["help", "?"] , cmdArgs = [] , cmdDesc = "show this help" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do dbugM $ helpString (cmds :: [Command (Simulator sbe m)]) return False } failHelp :: MonadThrow m => m a failHelp = throwM $ SimulatorException "invalid arguments; type 'help' for details" helpString :: [Command m] -> String helpString cmds' = render . vcat $ [ invs <> colon $$ nest 2 (text $ cmdDesc cmd) | cmd <- cmds' , let invs = hsep . map text $ (cmdNames cmd ++ cmdArgs cmd) ] breakNextInsn :: Simulator sbe m () breakNextInsn = trBreakpoints %= S.insert BreakNextInsn breakCurrentMethodReturn :: Simulator sbe m () breakCurrentMethodReturn = do method <- getCurrentMethod trBreakpoints %= S.insert (BreakReturnFrom method) breakLineChange :: PC -> Simulator sbe m () breakLineChange pc = do mline <- getCurrentLineNumber pc trBreakpoints %= S.insert (BreakLineChange mline) completer :: forall sbe m . MonadSim sbe m => CompletionFunc (Simulator sbe m) completer (revleft, right) = do let (revword, revleft') = break isSpace revleft word = reverse revword cmdComps = map simpleCompletion . filter (word `isPrefixOf`) . M.keys $ m case all isSpace revleft' of True -> return (revleft', cmdComps) False -> do -- partial pattern ok: -- not (all isSpace revleft') => not (null (words revleft)) let (cmd:_args) = words (reverse revleft) case M.lookup cmd m of Nothing -> return (revleft, []) Just c -> cmdCompletion c (revleft, right) where m :: M.Map String (Command (Simulator sbe m)) m = commandMap
null
https://raw.githubusercontent.com/GaloisInc/jvm-verifier/3905dda18d0bdd5c595eef49804780f4a48c22f5/src/Verifier/Java/Debugger.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE OverloadedStrings # | Parse a string using the 'Read' instance. | Add a breakpoint to the @main@ method of the given class | Given a step handler, return a new step handler that runs it when breakpoints are encountered | Check whether we're at a transient breakpoint, and if so, deactivate it and return 'True' repeat last command if nothing entered | Given a string expected to be a method signature of the form list of method keys that correspond to that method | Complete a class name as the current word | Complete a method signature as the current word still working on a class name otherwise on a method, so figure out which classes we completed expect methods in their pretty-printed form partial pattern ok: not (all isSpace revleft') => not (null (words revleft))
# LANGUAGE LambdaCase # | Module : Verifier . Java . Debugger Description : Debugger implementation for JSS License : BSD3 Stability : provisional Point - of - contact : acfoltzer Debugger for the JVM Symbolic Simulator . This module provides implementations of the ' SEH ' event handlers . Module : Verifier.Java.Debugger Description : Debugger implementation for JSS License : BSD3 Stability : provisional Point-of-contact : acfoltzer Debugger for the JVM Symbolic Simulator. This module provides implementations of the 'SEH' event handlers. -} # LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # # LANGUAGE CPP # # LANGUAGE FlexibleContexts # module Verifier.Java.Debugger ( breakOnMain , breakpointLogger , debuggerREPL , runAtBreakpoints ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Trans import Control.Lens import Data.Char import Data.List ( intercalate, isPrefixOf, stripPrefix ) import Data.List.Split import qualified Data.Map as M import qualified Data.Set as S import Data.Word (Word16) import System.Console.Haskeline import System.Console.Haskeline.History import System.Exit import Text.PrettyPrint import Data.JVM.Symbolic.AST import Verifier.Java.Common hiding (isFinished) import Verifier.Java.Simulator hiding (getCurrentClassName, getCurrentMethod, isFinished) import Prelude hiding ((<>)) #if __GLASGOW_HASKELL__ < 706 import qualified Text.ParserCombinators.ReadP as P import qualified Text.Read as R readEither :: Read a => String -> Either String a readEither s = case [ x | (x,"") <- R.readPrec_to_S read' R.minPrec s ] of [x] -> Right x [] -> Left "Prelude.read: no parse" _ -> Left "Prelude.read: ambiguous parse" where read' = do x <- R.readPrec R.lift P.skipSpaces return x Succeeds if there is exactly one valid result . readMaybe :: Read a => String -> Maybe a readMaybe s = case readEither s of Left _ -> Nothing Right a -> Just a #else import Text.Read (readMaybe) #endif uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (a, b, c) = f a b c breakOnMain :: ClassName -> Simulator sbe m () breakOnMain clName = addBreakpoint clName mainKey BreakEntry runAtBreakpoints :: (Functor m, Monad m) => (Maybe PC -> SymInsn -> Simulator sbe m ()) -> Maybe PC -> SymInsn -> Simulator sbe m () runAtBreakpoints sh (Just pc) insn = do atTransient <- handleTransientBreakpoints pc insn if atTransient then sh (Just pc) insn else do mp <- getPathMaybe case currentCallFrame =<< mp of Nothing -> return () Just cf -> do let clName = cf^.cfClass method = cf^.cfMethod mbps <- M.lookup (clName, method) <$> use breakpoints case S.member pc <$> mbps of Nothing -> return () Just False -> return () Just True -> sh (Just pc) insn runAtBreakpoints _ _ _ = return () handleTransientBreakpoints :: PC -> SymInsn -> Simulator sbe m Bool handleTransientBreakpoints pc insn = do method <- getCurrentMethod mLineNum <- getCurrentLineNumber pc let rember bp = do tbps <- use trBreakpoints if S.member bp tbps then do trBreakpoints %= S.delete bp return True else return False handleStep = rember BreakNextInsn handleRet = case insn of ReturnVal -> rember (BreakReturnFrom method) ReturnVoid -> rember (BreakReturnFrom method) _ -> return False handleLineChange = do tbps <- use trBreakpoints or <$> forM (S.elems tbps) (\bp -> case bp of BreakLineChange mLineNum' | mLineNum /= mLineNum' -> do rember (BreakLineChange mLineNum') _ -> return False) or <$> sequence [handleStep, handleRet, handleLineChange] breakpointLogger :: (Functor m, Monad m) => Maybe PC -> SymInsn -> Simulator sbe m () breakpointLogger = runAtBreakpoints (printLoc "hit breakpoint:") printLoc :: (Functor m, Monad m) => String -> Maybe PC -> SymInsn -> Simulator sbe m () printLoc msg mpc insn = do clName <- getCurrentClassName method <- getCurrentMethod let lineNum = maybe "unknown" (integer . fromIntegral) $ sourceLineNumberOrPrev method =<< mpc pc = maybe "unknown" (integer . fromIntegral) mpc dbugM . render $ text msg <+> text (unClassName clName) <> "." <> ppMethod method <> colon <> lineNum <> "%" <> pc <> colon <> ppSymInsn insn debuggerREPL :: (MonadSim sbe m) => Maybe PC -> SymInsn -> Simulator sbe m () debuggerREPL mpc insn = do printLoc "at" mpc insn let settings = setComplete completer $ defaultSettings { historyFile = Just ".jssdb" } runInputT settings loop where loop = do mline <- getInputLine "jss% " case mline of Nothing -> return () Just "" -> do hist <- getHistory case historyLines hist of (l:_) -> doCmd (words l) _ -> loop Just input -> doCmd (words input) doCmd (cmd:args) = do case M.lookup cmd commandMap of Just cmd' -> do let go = cmdAction cmd' mpc insn args handleErr epe@(ErrorPathExc _ _) = throwSM epe handleErr (UnknownExc (Just (FailRsn rsn))) = do dbugM $ "error: " ++ rsn return False handleErr _ = do dbugM "unknown error"; return False continue <- lift $ catchSM go handleErr unless continue loop Nothing -> do outputStrLn $ "unknown command '" ++ cmd ++ "'" outputStrLn $ "type 'help' for more info" loop doCmd [] = error "unreachable" data Command m = Cmd { cmdNames :: [String] , cmdArgs :: [String] , cmdDesc :: String , cmdCompletion :: CompletionFunc m , cmdAction :: Maybe PC -> SymInsn -> [String] -> m Bool } commandMap :: MonadSim sbe m => M.Map String (Command (Simulator sbe m)) commandMap = M.fromList . concatMap expandNames $ cmds where expandNames cmd = do name <- cmdNames cmd return (name, cmd) cmds :: MonadSim sbe m => [Command (Simulator sbe m)] cmds = [ helpCmd , whereCmd , localsCmd , dumpCmd , contCmd , killCmd , satpathCmd , exitCmd , clearCmd , stopinCmd , clearinCmd , stopatCmd , clearatCmd , stoppcCmd , clearpcCmd , stepCmd , stepupCmd , stepiCmd ] killCmd :: (MonadSim sbe m) => Command (Simulator sbe m) killCmd = Cmd { cmdNames = ["kill"] , cmdArgs = ["[<msg>]"] , cmdDesc = "throw an exception on the current execution path" , cmdCompletion = noCompletion , cmdAction = \_ _ args -> do let rte = "java/lang/RuntimeException" when (null args) $ createAndThrow rte refFromString (unwords args) >>= \case msgStr@(Ref _ ty) -> do let params = Just [(ty, RValue msgStr)] exc <- createInstance rte params throw exc error "unreachable" _ -> failHelp } satpathCmd :: (MonadSim sbe m) => Command (Simulator sbe m) satpathCmd = Cmd { cmdNames = ["satpath"] , cmdArgs = [] , cmdDesc = "check whether the current path's assertions are satisfiable, killing this path if they are not" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do p <- getPath "debugger" sbe <- use backend sat <- liftIO $ satTerm sbe (p^.pathAssertions) if sat then do dbugM "path assertions satisfiable" return False else do dbugM "path assertions unsatisfiable; killed" errorPath $ FailRsn "path assertions unsatisfiable: killed by debugger" } whereCmd :: (Functor m, Monad m) => Command (Simulator sbe m) whereCmd = Cmd { cmdNames = ["where", "w"] , cmdArgs = [] , cmdDesc = "print call stack" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do mp <- getPathMaybe case mp of Nothing -> dbugM "no active execution path" Just p -> dbugM . render . ppStackTrace $ p^.pathStack return False } localsCmd :: MonadSim sbe m => Command (Simulator sbe m) localsCmd = Cmd { cmdNames = ["locals"] , cmdArgs = [] , cmdDesc = "print local variables in current stack frame" , cmdCompletion = noCompletion , cmdAction = \mpc _ _ -> do locals <- modifyCallFrameM "debugger" $ \cf -> return (cf^.cfLocals, cf) sbe <- use backend case mpc of Nothing -> dbugM . render $ ppLocals sbe locals Just pc -> do method <- getCurrentMethod dbugM . render =<< ppNamedLocals method pc locals return False } contCmd :: Monad m => Command m contCmd = Cmd { cmdNames = ["cont", "c"] , cmdArgs = [] , cmdDesc = "continue execution" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> return True } stopinCmd :: MonadSim sbe m => Command (Simulator sbe m) stopinCmd = Cmd { cmdNames = ["stopin"] , cmdArgs = ["<class id>.<method>[<type_descriptor>]"] , cmdDesc = "set a breakpoint in a method; type descriptor is optional" , cmdCompletion = methodCompletion , cmdAction = \_ _ args -> case args of [arg] -> do bps <- entriesForArg arg forM_ bps $ uncurry3 addBreakpoint return False _ -> failHelp } clearinCmd :: MonadSim sbe m => Command (Simulator sbe m) clearinCmd = Cmd { cmdNames = ["clearin"] , cmdArgs = ["<class id>.<method>[<type_descriptor>]"] , cmdDesc = "clear a breakpoint in a method; type descriptor is optional" , cmdCompletion = methodCompletion , cmdAction = \_ _ args -> case args of [arg] -> do bps <- entriesForArg arg forM_ bps $ uncurry3 removeBreakpoint return False _ -> failHelp } entriesForArg :: String -> Simulator sbe m [(ClassName, MethodKey, Breakpoint)] entriesForArg arg = do (clName, keys) <- keysForArg arg return . map (clName, , BreakEntry) $ keys @com . Foo.bar@ or @com . Foo.bar(I)V@ , return the class name and a keysForArg :: String -> Simulator sbe m (ClassName, [MethodKey]) keysForArg arg = do let (sig, desc) = break (== '(') arg ids = reverse (splitOn "." sig) clName <- case ids of (_methStr:rest) -> return . mkClassName . intercalate "/" . reverse $ rest _ -> fail $ "invalid method signature " ++ arg methName <- case ids of (methStr:_) -> return methStr _ -> fail $ "invalid method signature " ++ arg cl <- lookupClass clName let keys | not (null desc) = [makeMethodKey methName desc] | otherwise = concatMap (makeKeys . methodKey) (classMethods cl) makeKeys key = if thisName == methName then [key] else [] where thisName = methodKeyName key return (clName, keys) stopatCmd :: MonadSim sbe m => Command (Simulator sbe m) stopatCmd = Cmd { cmdNames = ["stopat"] , cmdArgs = ["<class id>:<line>"] , cmdDesc = "set a breakpoint at a line" , cmdCompletion = classCompletion , cmdAction = \_ _ args -> case args of [arg] -> do uncurry3 removeBreakpoint =<< lineNumForArg arg return False _ -> failHelp } clearatCmd :: MonadSim sbe m => Command (Simulator sbe m) clearatCmd = Cmd { cmdNames = ["clearat"] , cmdArgs = ["<class id>:<line>"] , cmdDesc = "clear a breakpoint at a line" , cmdCompletion = classCompletion , cmdAction = \_ _ args -> case args of [arg] -> do uncurry3 removeBreakpoint =<< lineNumForArg arg return False _ -> failHelp } stoppcCmd :: MonadSim sbe m => Command (Simulator sbe m) stoppcCmd = Cmd { cmdNames = ["stoppc"] , cmdArgs = ["<class id>.<method>[<type_descriptor>]%pc"] , cmdDesc = "set a breakpoint at a program counter" , cmdCompletion = methodCompletion , cmdAction = \_ _ args -> case args of [arg] -> do bps <- pcsForArg arg forM_ bps $ uncurry3 addBreakpoint return False _ -> failHelp } clearpcCmd :: MonadSim sbe m => Command (Simulator sbe m) clearpcCmd = Cmd { cmdNames = ["clearpc"] , cmdArgs = ["<class id>.<method>[<type_descriptor>]%pc"] , cmdDesc = "clear a breakpoint at a program counter" , cmdCompletion = methodCompletion , cmdAction = \_ _ args -> case args of [arg] -> do bps <- pcsForArg arg forM_ bps $ uncurry3 removeBreakpoint return False _ -> failHelp } classCompletion :: MonadSim sbe m => CompletionFunc (Simulator sbe m) classCompletion = completeWordWithPrev Nothing " " fn where fn _revleft word = do cb <- use codebase classes <- liftIO $ getClasses cb return . map (notFinished . simpleCompletion) . filter (word `isPrefixOf`) . map (slashesToDots . unClassName . className) $ classes methodCompletion :: MonadSim sbe m => CompletionFunc (Simulator sbe m) methodCompletion = completeWordWithPrev Nothing " " fn where fn _revleft word = do cb <- use codebase classes <- liftIO $ getClasses cb let classNames = map (slashesToDots . unClassName . className) classes strictPrefixOf pfx xs = pfx `isPrefixOf` xs && pfx /= xs matches = filter (word `strictPrefixOf`) classNames case matches of _:_ -> return . map (notFinished . simpleCompletion) $ matches [] -> do let matches' = filter (`isPrefixOf` word) classNames concat <$> forM matches' (\clName -> do cl <- lookupClass (mkClassName clName) let methodNames = map (render . ppMethod) . classMethods $ cl cleanup = notFinished . simpleCompletion . ((clName ++ ".") ++) case stripPrefix clName word of Just prefix -> do let prefix' = case prefix of '.':rest -> rest _ -> prefix return . map cleanup . filter (prefix' `isPrefixOf`) $ methodNames Nothing -> return . map cleanup $ methodNames) notFinished :: Completion -> Completion notFinished c = c { isFinished = False } clearCmd :: Command (Simulator sbe m) clearCmd = Cmd { cmdNames = ["clear"] , cmdArgs = [] , cmdDesc = "list breakpoints" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> dumpBPs >> return False } dumpBPs :: Simulator sbe m () dumpBPs = do bps <- use breakpoints if all S.null (M.elems bps) then dbugM "no breakpoints set" else dbugM . render . ppBreakpoints $ bps pcsForArg :: String -> Simulator sbe m [(ClassName, MethodKey, Breakpoint)] pcsForArg arg = do let (method, pcStr) = break (== '%') arg pc <- case readMaybe (drop 1 pcStr) of Just (n :: Word16) -> return n Nothing -> fail $ "invalid program counter " ++ pcStr (clName, keys) <- keysForArg method return . map (clName, , BreakPC pc) $ keys lineNumForArg :: String -> Simulator sbe m (ClassName, MethodKey, Breakpoint) lineNumForArg arg = do let (clStr, lnStr) = break (== ':') arg let clName = mkClassName clStr lineNum <- case readMaybe (drop 1 lnStr) of Just (n :: Word16) -> return n Nothing -> fail $ "invalid line number " ++ lnStr cl <- lookupClass clName case lookupLineMethodStartPC cl lineNum of Just (method, _pc) -> return (clName, (methodKey method), (BreakLineNum lineNum)) Nothing -> fail . render $ "line number" <+> integer (fromIntegral lineNum) <+> "not found in" <+> text clStr $$ "were class files compiled with debugging symbols?" dumpCmd :: MonadSim sbe m => Command (Simulator sbe m) dumpCmd = let args = ["ctrlstk", "memory", "method", "path"] in Cmd { cmdNames = ["dump", "d"] , cmdArgs = args , cmdDesc = "dump an object in the simulator" , cmdCompletion = completeWordWithPrev Nothing " " $ \revleft word -> do case length . words $ revleft of only dump one thing at a time 1 -> return . map simpleCompletion . filter (word `isPrefixOf`) $ args _ -> return [] , cmdAction = \_ _ args' -> do case args' of ["ctrlstk"] -> dumpCtrlStk ["memory"] -> dumpMemory "debugger" ["method"] -> dumpCurrentMethod ["path"] -> dumpCurrentPath _ -> dbugM $ "dump: unsupported object " ++ unwords args' return False } stepCmd :: (Functor m, Monad m) => Command (Simulator sbe m) stepCmd = Cmd { cmdNames = ["step", "s"] , cmdArgs = [] , cmdDesc = "execute current line" , cmdCompletion = noCompletion , cmdAction = \mpc _ _ -> do case mpc of Just pc -> breakLineChange pc >> return True Nothing -> dbugM "unknown current line (try 'stepi')" >> return False } stepupCmd :: (Functor m, Monad m) => Command (Simulator sbe m) stepupCmd = Cmd { cmdNames = ["stepup"] , cmdArgs = [] , cmdDesc = "execute until current method returns to its caller" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do breakCurrentMethodReturn return True } stepiCmd :: (Functor m, Monad m) => Command (Simulator sbe m) stepiCmd = Cmd { cmdNames = ["stepi"] , cmdArgs = [] , cmdDesc = "execute current symbolic instruction" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do breakNextInsn return True } exitCmd :: MonadIO m => Command m exitCmd = Cmd { cmdNames = ["exit", "quit"] , cmdArgs = [] , cmdDesc = "exit JSS" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> liftIO $ exitWith ExitSuccess } helpCmd :: forall sbe m . MonadSim sbe m => Command (Simulator sbe m) helpCmd = Cmd { cmdNames = ["help", "?"] , cmdArgs = [] , cmdDesc = "show this help" , cmdCompletion = noCompletion , cmdAction = \_ _ _ -> do dbugM $ helpString (cmds :: [Command (Simulator sbe m)]) return False } failHelp :: MonadThrow m => m a failHelp = throwM $ SimulatorException "invalid arguments; type 'help' for details" helpString :: [Command m] -> String helpString cmds' = render . vcat $ [ invs <> colon $$ nest 2 (text $ cmdDesc cmd) | cmd <- cmds' , let invs = hsep . map text $ (cmdNames cmd ++ cmdArgs cmd) ] breakNextInsn :: Simulator sbe m () breakNextInsn = trBreakpoints %= S.insert BreakNextInsn breakCurrentMethodReturn :: Simulator sbe m () breakCurrentMethodReturn = do method <- getCurrentMethod trBreakpoints %= S.insert (BreakReturnFrom method) breakLineChange :: PC -> Simulator sbe m () breakLineChange pc = do mline <- getCurrentLineNumber pc trBreakpoints %= S.insert (BreakLineChange mline) completer :: forall sbe m . MonadSim sbe m => CompletionFunc (Simulator sbe m) completer (revleft, right) = do let (revword, revleft') = break isSpace revleft word = reverse revword cmdComps = map simpleCompletion . filter (word `isPrefixOf`) . M.keys $ m case all isSpace revleft' of True -> return (revleft', cmdComps) False -> do let (cmd:_args) = words (reverse revleft) case M.lookup cmd m of Nothing -> return (revleft, []) Just c -> cmdCompletion c (revleft, right) where m :: M.Map String (Command (Simulator sbe m)) m = commandMap
e3d871ed90b5e4a493925a6312969ad045d7067b3e32b697ed3f73d7d06d0b21
zachsully/dl
CodeGen.hs
module DL.DMach.CodeGen (cCompile) where import DL.Backend import DL.Flat.Syntax import DL.DMach.Syntax import DL.DMach.Translation (trans) import DL.Utils.Pretty data CLike instance Pretty CLike where pp = undefined cCompile :: Backend FlatTerm cCompile = Backend (codeGen . trans) codeGen :: DMach -> CLike codeGen = undefined
null
https://raw.githubusercontent.com/zachsully/dl/383bcc9d34c5e1f9787dede440a84503e5a2fd28/haskell/DL/DMach/CodeGen.hs
haskell
module DL.DMach.CodeGen (cCompile) where import DL.Backend import DL.Flat.Syntax import DL.DMach.Syntax import DL.DMach.Translation (trans) import DL.Utils.Pretty data CLike instance Pretty CLike where pp = undefined cCompile :: Backend FlatTerm cCompile = Backend (codeGen . trans) codeGen :: DMach -> CLike codeGen = undefined
7c4007e90d69158b7127d5d491aa6a165554145e9ff4d508b9b3f43d9d143d10
rescript-association/reanalyze
ExnLib.ml
let raisesLibTable = let table = Hashtbl.create 15 in let open Exn in let array = [ ("get", [invalidArgument]); ("set", [invalidArgument]); ("make", [invalidArgument]); ("init", [invalidArgument]); ("make_matrix", [invalidArgument]); ("fill", [invalidArgument]); ("blit", [invalidArgument]); ("iter2", [invalidArgument]); ("map2", [invalidArgument]); ] in let beltArray = [("getExn", [assertFailure]); ("setExn", [assertFailure])] in let beltList = [("getExn", [notFound]); ("headExn", [notFound]); ("tailExn", [notFound])] in let beltMap = [("getExn", [notFound])] in let beltMutableMap = beltMap in let beltMutableQueue = [("peekExn", [notFound]); ("popExn", [notFound])] in let beltMutableSet = [("getExn", [notFound])] in let beltOption = [("getExn", [notFound])] in let beltResult = [("getExn", [notFound])] in let beltSet = [("getExn", [notFound])] in let bsJson = (* bs-json *) [ ("bool", [decodeError]); ("float", [decodeError]); ("int", [decodeError]); ("string", [decodeError]); ("char", [decodeError]); ("date", [decodeError]); ("nullable", [decodeError]); ("nullAs", [decodeError]); ("array", [decodeError]); ("list", [decodeError]); ("pair", [decodeError]); ("tuple2", [decodeError]); ("tuple3", [decodeError]); ("tuple4", [decodeError]); ("dict", [decodeError]); ("field", [decodeError]); ("at", [decodeError; invalidArgument]); ("oneOf", [decodeError]); ("either", [decodeError]); ] in let buffer = [ ("sub", [invalidArgument]); ("blit", [invalidArgument]); ("nth", [invalidArgument]); ("add_substitute", [notFound]); ("add_channel", [endOfFile]); ("truncate", [invalidArgument]); ] in let bytes = [ ("get", [invalidArgument]); ("set", [invalidArgument]); ("create", [invalidArgument]); ("make", [invalidArgument]); ("init", [invalidArgument]); ("sub", [invalidArgument]); ("sub_string", [invalidArgument]); ("extend", [invalidArgument]); ("fill", [invalidArgument]); ("blit", [invalidArgument]); ("blit_string", [invalidArgument]); ( " concat " , [ invalidArgument ] ) , if longer than { ! } ( " cat " , [ invalidArgument ] ) , if longer than { ! } ( " escaped " , [ invalidArgument ] ) , if longer than { ! } ("cat", [invalidArgument]), if longer than {!Sys.max_string_length} ("escaped", [invalidArgument]), if longer than {!Sys.max_string_length} *) ("index", [notFound]); ("rindex", [notFound]); ("index_from", [invalidArgument; notFound]); ("index_from_opt", [invalidArgument]); ("rindex_from", [invalidArgument; notFound]); ("rindex_from_opt", [invalidArgument]); ("contains_from", [invalidArgument]); ("rcontains_from", [invalidArgument]); ] in let filename = [ ("chop_extension", [invalidArgument]); ("temp_file", [sysError]); ("open_temp_file", [sysError]); ] in let hashtbl = [("find", [notFound])] in let list = [ ("hd", [failure]); ("tl", [failure]); ("nth", [failure; invalidArgument]); ("nth_opt", [invalidArgument]); ("init", [invalidArgument]); ("iter2", [invalidArgument]); ("map2", [invalidArgument]); ("fold_left2", [invalidArgument]); ("fold_right2", [invalidArgument]); ("for_all2", [invalidArgument]); ("exists2", [invalidArgument]); ("find", [notFound]); ("assoc", [notFound]); ("combine", [invalidArgument]); ] in let string = [ ("get", [invalidArgument]); ("set", [invalidArgument]); ("create", [invalidArgument]); ("make", [invalidArgument]); ("init", [invalidArgument]); ("sub", [invalidArgument]); ("fill", [invalidArgument]); ( " concat " , [ invalidArgument ] ) , if longer than { ! } ( " escaped " , [ invalidArgument ] ) , if longer than { ! } ("escaped", [invalidArgument]), if longer than {!Sys.max_string_length} *) ("index", [notFound]); ("rindex", [notFound]); ("index_from", [invalidArgument; notFound]); ("index_from_opt", [invalidArgument]); ("rindex_from", [invalidArgument; notFound]); ("rindex_from_opt", [invalidArgument]); ("contains_from", [invalidArgument]); ("rcontains_from", [invalidArgument]); ] in let stdlib = [ ("invalid_arg", [invalidArgument]); ("failwith", [failure]); ("/", [divisionByZero]); ("mod", [divisionByZero]); ("char_of_int", [invalidArgument]); ("bool_of_string", [invalidArgument]); ("int_of_string", [failure]); ("float_of_string", [failure]); ("read_int", [failure]); ("output", [invalidArgument]); ("close_out", [sysError]); ("input_char", [endOfFile]); ("input_line", [endOfFile]); ("input", [invalidArgument]); ("really_input", [endOfFile; invalidArgument]); ("really_input_string", [endOfFile]); ("input_byte", [endOfFile]); ("input_binary_int", [endOfFile]); ("close_in", [sysError]); ("exit", [exit]); ] in let str = [ ("search_forward", [notFound]); ("search_backward", [notFound]); ("matched_group", [notFound]); ("group_beginning", [notFound; invalidArgument]); ("group_end", [notFound; invalidArgument]); ] in let yojsonBasic = [("from_string", [yojsonJsonError])] in let yojsonBasicUtil = [ ("member", [yojsonTypeError]); ("to_assoc", [yojsonTypeError]); ("to_bool", [yojsonTypeError]); ("to_bool_option", [yojsonTypeError]); ("to_float", [yojsonTypeError]); ("to_float_option", [yojsonTypeError]); ("to_int", [yojsonTypeError]); ("to_list", [yojsonTypeError]); ("to_number", [yojsonTypeError]); ("to_number_option", [yojsonTypeError]); ("to_string", [yojsonTypeError]); ("to_string_option", [yojsonTypeError]); ] in [ ("Array", array); ("Belt.Array", beltArray); ("Belt_Array", beltArray); ("Belt.List", beltList); ("Belt_List", beltList); ("Belt.Map", beltMap); ("Belt.Map.Int", beltMap); ("Belt.Map.String", beltMap); ("Belt_Map", beltMap); ("Belt_Map.Int", beltMap); ("Belt_Map.String", beltMap); ("Belt_MapInt", beltMap); ("Belt_MapString", beltMap); ("Belt.MutableMap", beltMutableMap); ("Belt.MutableMap.Int", beltMutableMap); ("Belt.MutableMap.String", beltMutableMap); ("Belt_MutableMap", beltMutableMap); ("Belt_MutableMap.Int", beltMutableMap); ("Belt_MutableMap.String", beltMutableMap); ("Belt_MutableMapInt", beltMutableMap); ("Belt_MutableMapString", beltMutableMap); ("Belt.MutableQueue", beltMutableQueue); ("Belt_MutableQueue", beltMutableQueue); ("Belt.Option", beltOption); ("Belt_Option", beltOption); ("Belt.Result", beltResult); ("Belt_Result", beltResult); ("Belt.Set", beltSet); ("Belt.Set.Int", beltSet); ("Belt.Set.String", beltSet); ("Belt_Set", beltSet); ("Belt_Set.Int", beltSet); ("Belt_Set.String", beltSet); ("Belt_SetInt", beltSet); ("Belt_SetString", beltSet); ("Belt.MutableSet", beltMutableSet); ("Belt.MutableSet.Int", beltMutableSet); ("Belt.MutableSet.String", beltMutableSet); ("MutableSet", beltMutableSet); ("MutableSet.Int", beltMutableSet); ("MutableSet.String", beltMutableSet); ("Belt_MutableSetInt", beltMutableSet); ("Belt_MutableSetString", beltMutableSet); ("Buffer", buffer); ("Bytes", bytes); ("Char", [("chr", [invalidArgument])]); ("Filename", filename); ("Hashtbl", hashtbl); ("Js.Json", [("parseExn", [jsExnError])]); ("Json_decode", bsJson); ("Json.Decode", bsJson); ("List", list); ("Pervasives", stdlib); ("Stdlib", stdlib); ("Stdlib.Array", array); ("Stdlib.Buffer", buffer); ("Stdlib.Bytes", bytes); ("Stdlib.Filename", filename); ("Stdlib.Hashtbl", hashtbl); ("Stdlib.List", list); ("Stdlib.Str", str); ("Stdlib.String", string); ("Str", str); ("String", string); ("Yojson.Basic", yojsonBasic); ("Yojson.Basic.Util", yojsonBasicUtil); ] |> List.iter (fun (name, group) -> group |> List.iter (fun (s, e) -> Hashtbl.add table (name ^ "." ^ s) (e |> Exceptions.fromList))); table let find (path : Common.Path.t) = Hashtbl.find_opt raisesLibTable (path |> Common.Path.toString)
null
https://raw.githubusercontent.com/rescript-association/reanalyze/6335ce4399ecb305e653561d2d01912fd6c8f917/src/ExnLib.ml
ocaml
bs-json
let raisesLibTable = let table = Hashtbl.create 15 in let open Exn in let array = [ ("get", [invalidArgument]); ("set", [invalidArgument]); ("make", [invalidArgument]); ("init", [invalidArgument]); ("make_matrix", [invalidArgument]); ("fill", [invalidArgument]); ("blit", [invalidArgument]); ("iter2", [invalidArgument]); ("map2", [invalidArgument]); ] in let beltArray = [("getExn", [assertFailure]); ("setExn", [assertFailure])] in let beltList = [("getExn", [notFound]); ("headExn", [notFound]); ("tailExn", [notFound])] in let beltMap = [("getExn", [notFound])] in let beltMutableMap = beltMap in let beltMutableQueue = [("peekExn", [notFound]); ("popExn", [notFound])] in let beltMutableSet = [("getExn", [notFound])] in let beltOption = [("getExn", [notFound])] in let beltResult = [("getExn", [notFound])] in let beltSet = [("getExn", [notFound])] in let bsJson = [ ("bool", [decodeError]); ("float", [decodeError]); ("int", [decodeError]); ("string", [decodeError]); ("char", [decodeError]); ("date", [decodeError]); ("nullable", [decodeError]); ("nullAs", [decodeError]); ("array", [decodeError]); ("list", [decodeError]); ("pair", [decodeError]); ("tuple2", [decodeError]); ("tuple3", [decodeError]); ("tuple4", [decodeError]); ("dict", [decodeError]); ("field", [decodeError]); ("at", [decodeError; invalidArgument]); ("oneOf", [decodeError]); ("either", [decodeError]); ] in let buffer = [ ("sub", [invalidArgument]); ("blit", [invalidArgument]); ("nth", [invalidArgument]); ("add_substitute", [notFound]); ("add_channel", [endOfFile]); ("truncate", [invalidArgument]); ] in let bytes = [ ("get", [invalidArgument]); ("set", [invalidArgument]); ("create", [invalidArgument]); ("make", [invalidArgument]); ("init", [invalidArgument]); ("sub", [invalidArgument]); ("sub_string", [invalidArgument]); ("extend", [invalidArgument]); ("fill", [invalidArgument]); ("blit", [invalidArgument]); ("blit_string", [invalidArgument]); ( " concat " , [ invalidArgument ] ) , if longer than { ! } ( " cat " , [ invalidArgument ] ) , if longer than { ! } ( " escaped " , [ invalidArgument ] ) , if longer than { ! } ("cat", [invalidArgument]), if longer than {!Sys.max_string_length} ("escaped", [invalidArgument]), if longer than {!Sys.max_string_length} *) ("index", [notFound]); ("rindex", [notFound]); ("index_from", [invalidArgument; notFound]); ("index_from_opt", [invalidArgument]); ("rindex_from", [invalidArgument; notFound]); ("rindex_from_opt", [invalidArgument]); ("contains_from", [invalidArgument]); ("rcontains_from", [invalidArgument]); ] in let filename = [ ("chop_extension", [invalidArgument]); ("temp_file", [sysError]); ("open_temp_file", [sysError]); ] in let hashtbl = [("find", [notFound])] in let list = [ ("hd", [failure]); ("tl", [failure]); ("nth", [failure; invalidArgument]); ("nth_opt", [invalidArgument]); ("init", [invalidArgument]); ("iter2", [invalidArgument]); ("map2", [invalidArgument]); ("fold_left2", [invalidArgument]); ("fold_right2", [invalidArgument]); ("for_all2", [invalidArgument]); ("exists2", [invalidArgument]); ("find", [notFound]); ("assoc", [notFound]); ("combine", [invalidArgument]); ] in let string = [ ("get", [invalidArgument]); ("set", [invalidArgument]); ("create", [invalidArgument]); ("make", [invalidArgument]); ("init", [invalidArgument]); ("sub", [invalidArgument]); ("fill", [invalidArgument]); ( " concat " , [ invalidArgument ] ) , if longer than { ! } ( " escaped " , [ invalidArgument ] ) , if longer than { ! } ("escaped", [invalidArgument]), if longer than {!Sys.max_string_length} *) ("index", [notFound]); ("rindex", [notFound]); ("index_from", [invalidArgument; notFound]); ("index_from_opt", [invalidArgument]); ("rindex_from", [invalidArgument; notFound]); ("rindex_from_opt", [invalidArgument]); ("contains_from", [invalidArgument]); ("rcontains_from", [invalidArgument]); ] in let stdlib = [ ("invalid_arg", [invalidArgument]); ("failwith", [failure]); ("/", [divisionByZero]); ("mod", [divisionByZero]); ("char_of_int", [invalidArgument]); ("bool_of_string", [invalidArgument]); ("int_of_string", [failure]); ("float_of_string", [failure]); ("read_int", [failure]); ("output", [invalidArgument]); ("close_out", [sysError]); ("input_char", [endOfFile]); ("input_line", [endOfFile]); ("input", [invalidArgument]); ("really_input", [endOfFile; invalidArgument]); ("really_input_string", [endOfFile]); ("input_byte", [endOfFile]); ("input_binary_int", [endOfFile]); ("close_in", [sysError]); ("exit", [exit]); ] in let str = [ ("search_forward", [notFound]); ("search_backward", [notFound]); ("matched_group", [notFound]); ("group_beginning", [notFound; invalidArgument]); ("group_end", [notFound; invalidArgument]); ] in let yojsonBasic = [("from_string", [yojsonJsonError])] in let yojsonBasicUtil = [ ("member", [yojsonTypeError]); ("to_assoc", [yojsonTypeError]); ("to_bool", [yojsonTypeError]); ("to_bool_option", [yojsonTypeError]); ("to_float", [yojsonTypeError]); ("to_float_option", [yojsonTypeError]); ("to_int", [yojsonTypeError]); ("to_list", [yojsonTypeError]); ("to_number", [yojsonTypeError]); ("to_number_option", [yojsonTypeError]); ("to_string", [yojsonTypeError]); ("to_string_option", [yojsonTypeError]); ] in [ ("Array", array); ("Belt.Array", beltArray); ("Belt_Array", beltArray); ("Belt.List", beltList); ("Belt_List", beltList); ("Belt.Map", beltMap); ("Belt.Map.Int", beltMap); ("Belt.Map.String", beltMap); ("Belt_Map", beltMap); ("Belt_Map.Int", beltMap); ("Belt_Map.String", beltMap); ("Belt_MapInt", beltMap); ("Belt_MapString", beltMap); ("Belt.MutableMap", beltMutableMap); ("Belt.MutableMap.Int", beltMutableMap); ("Belt.MutableMap.String", beltMutableMap); ("Belt_MutableMap", beltMutableMap); ("Belt_MutableMap.Int", beltMutableMap); ("Belt_MutableMap.String", beltMutableMap); ("Belt_MutableMapInt", beltMutableMap); ("Belt_MutableMapString", beltMutableMap); ("Belt.MutableQueue", beltMutableQueue); ("Belt_MutableQueue", beltMutableQueue); ("Belt.Option", beltOption); ("Belt_Option", beltOption); ("Belt.Result", beltResult); ("Belt_Result", beltResult); ("Belt.Set", beltSet); ("Belt.Set.Int", beltSet); ("Belt.Set.String", beltSet); ("Belt_Set", beltSet); ("Belt_Set.Int", beltSet); ("Belt_Set.String", beltSet); ("Belt_SetInt", beltSet); ("Belt_SetString", beltSet); ("Belt.MutableSet", beltMutableSet); ("Belt.MutableSet.Int", beltMutableSet); ("Belt.MutableSet.String", beltMutableSet); ("MutableSet", beltMutableSet); ("MutableSet.Int", beltMutableSet); ("MutableSet.String", beltMutableSet); ("Belt_MutableSetInt", beltMutableSet); ("Belt_MutableSetString", beltMutableSet); ("Buffer", buffer); ("Bytes", bytes); ("Char", [("chr", [invalidArgument])]); ("Filename", filename); ("Hashtbl", hashtbl); ("Js.Json", [("parseExn", [jsExnError])]); ("Json_decode", bsJson); ("Json.Decode", bsJson); ("List", list); ("Pervasives", stdlib); ("Stdlib", stdlib); ("Stdlib.Array", array); ("Stdlib.Buffer", buffer); ("Stdlib.Bytes", bytes); ("Stdlib.Filename", filename); ("Stdlib.Hashtbl", hashtbl); ("Stdlib.List", list); ("Stdlib.Str", str); ("Stdlib.String", string); ("Str", str); ("String", string); ("Yojson.Basic", yojsonBasic); ("Yojson.Basic.Util", yojsonBasicUtil); ] |> List.iter (fun (name, group) -> group |> List.iter (fun (s, e) -> Hashtbl.add table (name ^ "." ^ s) (e |> Exceptions.fromList))); table let find (path : Common.Path.t) = Hashtbl.find_opt raisesLibTable (path |> Common.Path.toString)
48246e200a1abe20bd3e0a939e0872859a5ff6bb98d4bd85335664b9bf8cabd8
Rober-t/apxr_run
agent_mgr_sup.erl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright ( C ) 2018 ApproximateReality %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%---------------------------------------------------------------------------- @doc AgentMgr top level supervisor . %%% @end %%%---------------------------------------------------------------------------- -module(agent_mgr_sup). -behaviour(supervisor). Start / Stop -export([ start_link/0 ]). %% Supervisor callbacks -export([ init/1 ]). Xref -ignore_xref([ start_link/0 ]). %%%============================================================================ %%% Types %%%============================================================================ -type sup_flags() :: #{ intensity => non_neg_integer(), period => pos_integer(), strategy => one_for_all | one_for_one | rest_for_one | simple_one_for_one }. -type child_spec() :: [#{ id := _, start := {atom(), atom(), undefined | [any()]}, modules => dynamic | [atom()], restart => permanent | temporary | transient, shutdown => brutal_kill | infinity | non_neg_integer(), type => supervisor | worker }]. -export_type([ sup_flags/0, child_spec/0 ]). %%%============================================================================ %%% API %%%============================================================================ %%----------------------------------------------------------------------------- %% @doc Starts the supervisor. %% @end %%----------------------------------------------------------------------------- -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). %%%============================================================================ %%% Supervisor callbacks %%%============================================================================ %%----------------------------------------------------------------------------- @private @doc Whenever a supervisor is started using supervisor : start_link , %% this function is called by the new process to find out about restart %% strategy, maximum restart frequency and child specifications. We also %% make the supervisor the owner of an ETS table to improve fault %% tolerance. %% @end %%----------------------------------------------------------------------------- -spec init([]) -> {ok, {sup_flags(), child_spec()}}. init([]) -> ets:new(agent_ids_pids, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), SupFlags = #{ strategy => rest_for_one, intensity => 4, period => 20 }, PrivateScapeSup = #{ id => private_scape_sup, start => {private_scape_sup, start_link, []}, restart => permanent, shutdown => infinity, type => supervisor, modules => [private_scape_sup] }, AgentSup = #{ id => agent_sup, start => {agent_sup, start_link, []}, restart => permanent, shutdown => infinity, type => supervisor, modules => [agent_sup] }, AgentMgr = #{ id => agent_mgr, start => {agent_mgr, start_link, []}, restart => permanent, shutdown => 5000, type => worker, modules => [agent_mgr] }, ChildSpecs = [PrivateScapeSup, AgentSup, AgentMgr], {ok, {SupFlags, ChildSpecs}}. %%%============================================================================ Internal functions %%%============================================================================
null
https://raw.githubusercontent.com/Rober-t/apxr_run/9c62ab028af7ff3768ffe3f27b8eef1799540f05/src/agent_mgr/agent_mgr_sup.erl
erlang
---------------------------------------------------------------------------- @end ---------------------------------------------------------------------------- Supervisor callbacks ============================================================================ Types ============================================================================ ============================================================================ API ============================================================================ ----------------------------------------------------------------------------- @doc Starts the supervisor. @end ----------------------------------------------------------------------------- ============================================================================ Supervisor callbacks ============================================================================ ----------------------------------------------------------------------------- this function is called by the new process to find out about restart strategy, maximum restart frequency and child specifications. We also make the supervisor the owner of an ETS table to improve fault tolerance. @end ----------------------------------------------------------------------------- ============================================================================ ============================================================================
Copyright ( C ) 2018 ApproximateReality @doc AgentMgr top level supervisor . -module(agent_mgr_sup). -behaviour(supervisor). Start / Stop -export([ start_link/0 ]). -export([ init/1 ]). Xref -ignore_xref([ start_link/0 ]). -type sup_flags() :: #{ intensity => non_neg_integer(), period => pos_integer(), strategy => one_for_all | one_for_one | rest_for_one | simple_one_for_one }. -type child_spec() :: [#{ id := _, start := {atom(), atom(), undefined | [any()]}, modules => dynamic | [atom()], restart => permanent | temporary | transient, shutdown => brutal_kill | infinity | non_neg_integer(), type => supervisor | worker }]. -export_type([ sup_flags/0, child_spec/0 ]). -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). @private @doc Whenever a supervisor is started using supervisor : start_link , -spec init([]) -> {ok, {sup_flags(), child_spec()}}. init([]) -> ets:new(agent_ids_pids, [set, public, named_table, {write_concurrency, true}, {read_concurrency, true}]), SupFlags = #{ strategy => rest_for_one, intensity => 4, period => 20 }, PrivateScapeSup = #{ id => private_scape_sup, start => {private_scape_sup, start_link, []}, restart => permanent, shutdown => infinity, type => supervisor, modules => [private_scape_sup] }, AgentSup = #{ id => agent_sup, start => {agent_sup, start_link, []}, restart => permanent, shutdown => infinity, type => supervisor, modules => [agent_sup] }, AgentMgr = #{ id => agent_mgr, start => {agent_mgr, start_link, []}, restart => permanent, shutdown => 5000, type => worker, modules => [agent_mgr] }, ChildSpecs = [PrivateScapeSup, AgentSup, AgentMgr], {ok, {SupFlags, ChildSpecs}}. Internal functions
8c2b89caaf14a286aed9428808b9443e14e340b9ded020aa5b2ae37b8c451653
TyOverby/mono
int_intf.ml
(** An interface to use for int-like types, e.g., {{!Base.Int}[Int]} and {{!Base.Int64}[Int64]}. *) open! Import module type Round = sig type t * [ round ] rounds an int to a multiple of a given [ to_multiple_of ] argument , according to a direction [ dir ] , with default [ dir ] being [ ` Nearest ] . [ round ] will raise if [ to_multiple_of < = 0 ] . If the result overflows ( too far positive or too far negative ) , [ round ] returns an incorrect result . { v | ` Down | rounds toward Int.neg_infinity | | ` Up | rounds toward Int.infinity | | ` Nearest | rounds to the nearest multiple , or ` Up in case of a tie | | ` Zero | rounds toward zero | v } Here are some examples for [ round ~to_multiple_of:10 ] for each direction : { v | ` Down | { 10 .. 19 } -- > 10 | { 0 ... 9 } -- > 0 | { -10 ... -1 } -- > -10 | | ` Up | { 1 .. 10 } -- > 10 | { -9 ... 0 } -- > 0 | { -19 .. -10 } -- > -10 | | ` Zero | { 10 .. 19 } -- > 10 | { -9 ... 9 } -- > 0 | { -19 .. -10 } -- > -10 | | ` Nearest | { 5 .. 14 } -- > 10 | { -5 ... 4 } -- > 0 | { -15 ... -6 } -- > -10 | v } For convenience and performance , there are variants of [ round ] with [ dir ] hard - coded . If you are writing performance - critical code you should use these . to a direction [dir], with default [dir] being [`Nearest]. [round] will raise if [to_multiple_of <= 0]. If the result overflows (too far positive or too far negative), [round] returns an incorrect result. {v | `Down | rounds toward Int.neg_infinity | | `Up | rounds toward Int.infinity | | `Nearest | rounds to the nearest multiple, or `Up in case of a tie | | `Zero | rounds toward zero | v} Here are some examples for [round ~to_multiple_of:10] for each direction: {v | `Down | {10 .. 19} --> 10 | { 0 ... 9} --> 0 | {-10 ... -1} --> -10 | | `Up | { 1 .. 10} --> 10 | {-9 ... 0} --> 0 | {-19 .. -10} --> -10 | | `Zero | {10 .. 19} --> 10 | {-9 ... 9} --> 0 | {-19 .. -10} --> -10 | | `Nearest | { 5 .. 14} --> 10 | {-5 ... 4} --> 0 | {-15 ... -6} --> -10 | v} For convenience and performance, there are variants of [round] with [dir] hard-coded. If you are writing performance-critical code you should use these. *) val round : ?dir:[ `Zero | `Nearest | `Up | `Down ] -> t -> to_multiple_of:t -> t val round_towards_zero : t -> to_multiple_of:t -> t val round_down : t -> to_multiple_of:t -> t val round_up : t -> to_multiple_of:t -> t val round_nearest : t -> to_multiple_of:t -> t end module type Hexable = sig type t module Hex : sig type nonrec t = t [@@deriving_inline sexp, sexp_grammar, compare, hash] include Sexplib0.Sexpable.S with type t := t val t_sexp_grammar : t Sexplib0.Sexp_grammar.t include Ppx_compare_lib.Comparable.S with type t := t include Ppx_hash_lib.Hashable.S with type t := t [@@@end] include Stringable.S with type t := t val to_string_hum : ?delimiter:char -> t -> string end end module type S_common = sig type t [@@deriving_inline sexp, sexp_grammar] include Sexplib0.Sexpable.S with type t := t val t_sexp_grammar : t Sexplib0.Sexp_grammar.t [@@@end] include Floatable.S with type t := t include Intable.S with type t := t include Identifiable.S with type t := t include Comparable.With_zero with type t := t include Invariant.S with type t := t include Hexable with type t := t (** [delimiter] is an underscore by default. *) val to_string_hum : ?delimiter:char -> t -> string * { 2 Infix operators and constants } val zero : t val one : t val minus_one : t val ( + ) : t -> t -> t val ( - ) : t -> t -> t val ( * ) : t -> t -> t (** Integer exponentiation *) val ( ** ) : t -> t -> t (** Negation *) val neg : t -> t val ( ~- ) : t -> t * There are two pairs of integer division and remainder functions , [ /% ] and [ % ] , and [ / ] and [ rem ] . They both satisfy the same equation relating the quotient and the remainder : { [ x = ( x /% y ) * y + ( x % y ) ; x = ( x / y ) * y + ( rem x y ) ; ] } The functions return the same values if [ x ] and [ y ] are positive . They all raise if [ y = 0 ] . The functions differ if [ x < 0 ] or [ y < 0 ] . If [ y < 0 ] , then [ % ] and [ /% ] raise , whereas [ / ] and [ rem ] do not . [ x % y ] always returns a value between 0 and [ y - 1 ] , even when [ x < 0 ] . On the other hand , [ rem x y ] returns a negative value if and only if [ x < 0 ] ; that value satisfies [ abs ( rem x y ) < = abs y - 1 ] . [/] and [rem]. They both satisfy the same equation relating the quotient and the remainder: {[ x = (x /% y) * y + (x % y); x = (x / y) * y + (rem x y); ]} The functions return the same values if [x] and [y] are positive. They all raise if [y = 0]. The functions differ if [x < 0] or [y < 0]. If [y < 0], then [%] and [/%] raise, whereas [/] and [rem] do not. [x % y] always returns a value between 0 and [y - 1], even when [x < 0]. On the other hand, [rem x y] returns a negative value if and only if [x < 0]; that value satisfies [abs (rem x y) <= abs y - 1]. *) val ( /% ) : t -> t -> t val ( % ) : t -> t -> t val ( / ) : t -> t -> t val rem : t -> t -> t (** Float division of integers. *) val ( // ) : t -> t -> float (** Same as [bit_and]. *) val ( land ) : t -> t -> t (** Same as [bit_or]. *) val ( lor ) : t -> t -> t (** Same as [bit_xor]. *) val ( lxor ) : t -> t -> t (** Same as [bit_not]. *) val lnot : t -> t (** Same as [shift_left]. *) val ( lsl ) : t -> int -> t (** Same as [shift_right]. *) val ( asr ) : t -> int -> t * { 2 Other common functions } include Round with type t := t * Returns the absolute value of the argument . May be negative if the input is [ min_value ] . [min_value]. *) val abs : t -> t * { 2 Successor and predecessor functions } val succ : t -> t val pred : t -> t (** {2 Exponentiation} *) (** [pow base exponent] returns [base] raised to the power of [exponent]. It is OK if [base <= 0]. [pow] raises if [exponent < 0], or an integer overflow would occur. *) val pow : t -> t -> t * { 2 Bit - wise logical operations } (** These are identical to [land], [lor], etc. except they're not infix and have different names. *) val bit_and : t -> t -> t val bit_or : t -> t -> t val bit_xor : t -> t -> t val bit_not : t -> t * Returns the number of 1 bits in the binary representation of the input . val popcount : t -> int * { 2 Bit - shifting operations } The results are unspecified for negative shifts and shifts [ > = num_bits ] . The results are unspecified for negative shifts and shifts [>= num_bits]. *) (** Shifts left, filling in with zeroes. *) val shift_left : t -> int -> t (** Shifts right, preserving the sign of the input. *) val shift_right : t -> int -> t * { 2 Increment and decrement functions for integer references } val decr : t ref -> unit val incr : t ref -> unit * { 2 Conversion functions to related integer types } val of_int32_exn : int32 -> t val to_int32_exn : t -> int32 val of_int64_exn : int64 -> t val to_int64 : t -> int64 val of_nativeint_exn : nativeint -> t val to_nativeint_exn : t -> nativeint * [ of_float_unchecked ] truncates the given floating point number to an integer , rounding towards zero . The result is unspecified if the argument is or falls outside the range of representable integers . rounding towards zero. The result is unspecified if the argument is nan or falls outside the range of representable integers. *) val of_float_unchecked : float -> t end module type Operators_unbounded = sig type t val ( + ) : t -> t -> t val ( - ) : t -> t -> t val ( * ) : t -> t -> t val ( / ) : t -> t -> t val ( ~- ) : t -> t val ( ** ) : t -> t -> t include Comparisons.Infix with type t := t val abs : t -> t val neg : t -> t val zero : t val ( % ) : t -> t -> t val ( /% ) : t -> t -> t val ( // ) : t -> t -> float val ( land ) : t -> t -> t val ( lor ) : t -> t -> t val ( lxor ) : t -> t -> t val lnot : t -> t val ( lsl ) : t -> int -> t val ( asr ) : t -> int -> t end module type Operators = sig include Operators_unbounded val ( lsr ) : t -> int -> t end * [ S_unbounded ] is a generic interface for unbounded integers , e.g. [ . Bigint ] . [ S_unbounded ] is a restriction of [ S ] ( below ) that omits values that depend on fixed - size integers . [S_unbounded] is a restriction of [S] (below) that omits values that depend on fixed-size integers. *) module type S_unbounded = sig * @inline (** A sub-module designed to be opened to make working with ints more convenient. *) module O : Operators_unbounded with type t := t end (** [S] is a generic interface for fixed-size integers. *) module type S = sig * @inline (** The number of bits available in this integer type. Note that the integer representations are signed. *) val num_bits : int (** The largest representable integer. *) val max_value : t (** The smallest representable integer. *) val min_value : t (** Same as [shift_right_logical]. *) val ( lsr ) : t -> int -> t (** Shifts right, filling in with zeroes, which will not preserve the sign of the input. *) val shift_right_logical : t -> int -> t * [ ceil_pow2 x ] returns the smallest power of 2 that is greater than or equal to [ x ] . The implementation may only be called for [ x > 0 ] . Example : [ ceil_pow2 17 = 32 ] The implementation may only be called for [x > 0]. Example: [ceil_pow2 17 = 32] *) val ceil_pow2 : t -> t * [ floor_pow2 x ] returns the largest power of 2 that is less than or equal to [ x ] . The implementation may only be called for [ x > 0 ] . Example : [ floor_pow2 17 = 16 ] implementation may only be called for [x > 0]. Example: [floor_pow2 17 = 16] *) val floor_pow2 : t -> t (** [ceil_log2 x] returns the ceiling of log-base-2 of [x], and raises if [x <= 0]. *) val ceil_log2 : t -> int (** [floor_log2 x] returns the floor of log-base-2 of [x], and raises if [x <= 0]. *) val floor_log2 : t -> int * [ is_pow2 x ] returns true iff [ x ] is a power of 2 . [ is_pow2 ] raises if [ x < = 0 ] . val is_pow2 : t -> bool * Returns the number of leading zeros in the binary representation of the input , as an integer between 0 and one less than [ num_bits ] . The results are unspecified for [ t = 0 ] . integer between 0 and one less than [num_bits]. The results are unspecified for [t = 0]. *) val clz : t -> int * Returns the number of trailing zeros in the binary representation of the input , as an integer between 0 and one less than [ num_bits ] . The results are unspecified for [ t = 0 ] . an integer between 0 and one less than [num_bits]. The results are unspecified for [t = 0]. *) val ctz : t -> int (** A sub-module designed to be opened to make working with ints more convenient. *) module O : Operators with type t := t end module type Int_without_module_types = sig * OCaml 's native integer type . The number of bits in an integer is platform dependent , being 31 - bits on a 32 - bit platform , and 63 - bits on a 64 - bit platform . [ int ] is a signed integer type . [ int]s are also subject to overflow , meaning that [ Int.max_value + 1 = Int.min_value ] . [ int]s always fit in a machine word . The number of bits in an integer is platform dependent, being 31-bits on a 32-bit platform, and 63-bits on a 64-bit platform. [int] is a signed integer type. [int]s are also subject to overflow, meaning that [Int.max_value + 1 = Int.min_value]. [int]s always fit in a machine word. *) * @inline module O : sig (*_ Declared as externals so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. *) external ( + ) : t -> t -> t = "%addint" external ( - ) : t -> t -> t = "%subint" external ( * ) : t -> t -> t = "%mulint" external ( / ) : t -> t -> t = "%divint" external ( ~- ) : t -> t = "%negint" val ( ** ) : t -> t -> t external ( = ) : t -> t -> bool = "%equal" external ( <> ) : t -> t -> bool = "%notequal" external ( < ) : t -> t -> bool = "%lessthan" external ( > ) : t -> t -> bool = "%greaterthan" external ( <= ) : t -> t -> bool = "%lessequal" external ( >= ) : t -> t -> bool = "%greaterequal" external ( land ) : t -> t -> t = "%andint" external ( lor ) : t -> t -> t = "%orint" external ( lxor ) : t -> t -> t = "%xorint" val lnot : t -> t val abs : t -> t external neg : t -> t = "%negint" val zero : t val ( % ) : t -> t -> t val ( /% ) : t -> t -> t val ( // ) : t -> t -> float external ( lsl ) : t -> int -> t = "%lslint" external ( asr ) : t -> int -> t = "%asrint" external ( lsr ) : t -> int -> t = "%lsrint" end include module type of O * [ max_value_30_bits = 2 ^ 30 - 1 ] . It is useful for writing tests that work on both 64 - bit and 32 - bit platforms . 64-bit and 32-bit platforms. *) val max_value_30_bits : t * { 2 Conversion functions } val of_int : int -> t val to_int : t -> int val of_int32 : int32 -> t option val to_int32 : t -> int32 option val of_int64 : int64 -> t option val of_nativeint : nativeint -> t option val to_nativeint : t -> nativeint * { 3 Truncating conversions } These functions return the least - significant bits of the input . In cases where optional conversions return [ Some x ] , truncating conversions return [ x ] . These functions return the least-significant bits of the input. In cases where optional conversions return [Some x], truncating conversions return [x]. *) (*_ Declared as externals so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. *) external to_int32_trunc : t -> int32 = "%int32_of_int" external of_int32_trunc : int32 -> t = "%int32_to_int" external of_int64_trunc : int64 -> t = "%int64_to_int" external of_nativeint_trunc : nativeint -> t = "%nativeint_to_int" * { 2 Byte swap operations } Byte swap operations reverse the order of bytes in an integer . For example , { ! Int32.bswap32 } reorders the bottom 32 bits ( or 4 bytes ) , turning [ 0x1122_3344 ] to [ 0x4433_2211 ] . Byte swap functions exposed by Base use OCaml primitives to generate assembly instructions to perform the relevant byte swaps . For a more extensive list of functions , see { ! Int32 } and { ! Int64 } . Byte swap operations reverse the order of bytes in an integer. For example, {!Int32.bswap32} reorders the bottom 32 bits (or 4 bytes), turning [0x1122_3344] to [0x4433_2211]. Byte swap functions exposed by Base use OCaml primitives to generate assembly instructions to perform the relevant byte swaps. For a more extensive list of byteswap functions, see {!Int32} and {!Int64}. *) * Byte swaps bottom 16 bits ( 2 bytes ) . The values of the remaining bytes are undefined . are undefined. *) external bswap16 : int -> int = "%bswap16" (*_ Declared as an external so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. *) (**/**) (*_ See the Jane Street Style Guide for an explanation of [Private] submodules: /#private-submodules *) module Private : sig (*_ For ../bench/bench_int.ml *) module O_F : sig val ( % ) : int -> int -> int val ( /% ) : int -> int -> int val ( // ) : int -> int -> float end end end module type Int = sig * @inline * { 2 Module types specifying integer operations . } module type Hexable = Hexable module type Int_without_module_types = Int_without_module_types module type Operators = Operators module type Operators_unbounded = Operators_unbounded module type Round = Round module type S = S module type S_common = S_common module type S_unbounded = S_unbounded end
null
https://raw.githubusercontent.com/TyOverby/mono/7666c0328d194bf9a569fb65babc0486f2aaa40d/vendor/janestreet-base/src/int_intf.ml
ocaml
* An interface to use for int-like types, e.g., {{!Base.Int}[Int]} and {{!Base.Int64}[Int64]}. * [delimiter] is an underscore by default. * Integer exponentiation * Negation * Float division of integers. * Same as [bit_and]. * Same as [bit_or]. * Same as [bit_xor]. * Same as [bit_not]. * Same as [shift_left]. * Same as [shift_right]. * {2 Exponentiation} * [pow base exponent] returns [base] raised to the power of [exponent]. It is OK if [base <= 0]. [pow] raises if [exponent < 0], or an integer overflow would occur. * These are identical to [land], [lor], etc. except they're not infix and have different names. * Shifts left, filling in with zeroes. * Shifts right, preserving the sign of the input. * A sub-module designed to be opened to make working with ints more convenient. * [S] is a generic interface for fixed-size integers. * The number of bits available in this integer type. Note that the integer representations are signed. * The largest representable integer. * The smallest representable integer. * Same as [shift_right_logical]. * Shifts right, filling in with zeroes, which will not preserve the sign of the input. * [ceil_log2 x] returns the ceiling of log-base-2 of [x], and raises if [x <= 0]. * [floor_log2 x] returns the floor of log-base-2 of [x], and raises if [x <= 0]. * A sub-module designed to be opened to make working with ints more convenient. _ Declared as externals so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. _ Declared as externals so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. _ Declared as an external so that the compiler skips the caml_apply_X wrapping even when compiling without cross library inlining. */* _ See the Jane Street Style Guide for an explanation of [Private] submodules: /#private-submodules _ For ../bench/bench_int.ml
open! Import module type Round = sig type t * [ round ] rounds an int to a multiple of a given [ to_multiple_of ] argument , according to a direction [ dir ] , with default [ dir ] being [ ` Nearest ] . [ round ] will raise if [ to_multiple_of < = 0 ] . If the result overflows ( too far positive or too far negative ) , [ round ] returns an incorrect result . { v | ` Down | rounds toward Int.neg_infinity | | ` Up | rounds toward Int.infinity | | ` Nearest | rounds to the nearest multiple , or ` Up in case of a tie | | ` Zero | rounds toward zero | v } Here are some examples for [ round ~to_multiple_of:10 ] for each direction : { v | ` Down | { 10 .. 19 } -- > 10 | { 0 ... 9 } -- > 0 | { -10 ... -1 } -- > -10 | | ` Up | { 1 .. 10 } -- > 10 | { -9 ... 0 } -- > 0 | { -19 .. -10 } -- > -10 | | ` Zero | { 10 .. 19 } -- > 10 | { -9 ... 9 } -- > 0 | { -19 .. -10 } -- > -10 | | ` Nearest | { 5 .. 14 } -- > 10 | { -5 ... 4 } -- > 0 | { -15 ... -6 } -- > -10 | v } For convenience and performance , there are variants of [ round ] with [ dir ] hard - coded . If you are writing performance - critical code you should use these . to a direction [dir], with default [dir] being [`Nearest]. [round] will raise if [to_multiple_of <= 0]. If the result overflows (too far positive or too far negative), [round] returns an incorrect result. {v | `Down | rounds toward Int.neg_infinity | | `Up | rounds toward Int.infinity | | `Nearest | rounds to the nearest multiple, or `Up in case of a tie | | `Zero | rounds toward zero | v} Here are some examples for [round ~to_multiple_of:10] for each direction: {v | `Down | {10 .. 19} --> 10 | { 0 ... 9} --> 0 | {-10 ... -1} --> -10 | | `Up | { 1 .. 10} --> 10 | {-9 ... 0} --> 0 | {-19 .. -10} --> -10 | | `Zero | {10 .. 19} --> 10 | {-9 ... 9} --> 0 | {-19 .. -10} --> -10 | | `Nearest | { 5 .. 14} --> 10 | {-5 ... 4} --> 0 | {-15 ... -6} --> -10 | v} For convenience and performance, there are variants of [round] with [dir] hard-coded. If you are writing performance-critical code you should use these. *) val round : ?dir:[ `Zero | `Nearest | `Up | `Down ] -> t -> to_multiple_of:t -> t val round_towards_zero : t -> to_multiple_of:t -> t val round_down : t -> to_multiple_of:t -> t val round_up : t -> to_multiple_of:t -> t val round_nearest : t -> to_multiple_of:t -> t end module type Hexable = sig type t module Hex : sig type nonrec t = t [@@deriving_inline sexp, sexp_grammar, compare, hash] include Sexplib0.Sexpable.S with type t := t val t_sexp_grammar : t Sexplib0.Sexp_grammar.t include Ppx_compare_lib.Comparable.S with type t := t include Ppx_hash_lib.Hashable.S with type t := t [@@@end] include Stringable.S with type t := t val to_string_hum : ?delimiter:char -> t -> string end end module type S_common = sig type t [@@deriving_inline sexp, sexp_grammar] include Sexplib0.Sexpable.S with type t := t val t_sexp_grammar : t Sexplib0.Sexp_grammar.t [@@@end] include Floatable.S with type t := t include Intable.S with type t := t include Identifiable.S with type t := t include Comparable.With_zero with type t := t include Invariant.S with type t := t include Hexable with type t := t val to_string_hum : ?delimiter:char -> t -> string * { 2 Infix operators and constants } val zero : t val one : t val minus_one : t val ( + ) : t -> t -> t val ( - ) : t -> t -> t val ( * ) : t -> t -> t val ( ** ) : t -> t -> t val neg : t -> t val ( ~- ) : t -> t * There are two pairs of integer division and remainder functions , [ /% ] and [ % ] , and [ / ] and [ rem ] . They both satisfy the same equation relating the quotient and the remainder : { [ x = ( x /% y ) * y + ( x % y ) ; x = ( x / y ) * y + ( rem x y ) ; ] } The functions return the same values if [ x ] and [ y ] are positive . They all raise if [ y = 0 ] . The functions differ if [ x < 0 ] or [ y < 0 ] . If [ y < 0 ] , then [ % ] and [ /% ] raise , whereas [ / ] and [ rem ] do not . [ x % y ] always returns a value between 0 and [ y - 1 ] , even when [ x < 0 ] . On the other hand , [ rem x y ] returns a negative value if and only if [ x < 0 ] ; that value satisfies [ abs ( rem x y ) < = abs y - 1 ] . [/] and [rem]. They both satisfy the same equation relating the quotient and the remainder: {[ x = (x /% y) * y + (x % y); x = (x / y) * y + (rem x y); ]} The functions return the same values if [x] and [y] are positive. They all raise if [y = 0]. The functions differ if [x < 0] or [y < 0]. If [y < 0], then [%] and [/%] raise, whereas [/] and [rem] do not. [x % y] always returns a value between 0 and [y - 1], even when [x < 0]. On the other hand, [rem x y] returns a negative value if and only if [x < 0]; that value satisfies [abs (rem x y) <= abs y - 1]. *) val ( /% ) : t -> t -> t val ( % ) : t -> t -> t val ( / ) : t -> t -> t val rem : t -> t -> t val ( // ) : t -> t -> float val ( land ) : t -> t -> t val ( lor ) : t -> t -> t val ( lxor ) : t -> t -> t val lnot : t -> t val ( lsl ) : t -> int -> t val ( asr ) : t -> int -> t * { 2 Other common functions } include Round with type t := t * Returns the absolute value of the argument . May be negative if the input is [ min_value ] . [min_value]. *) val abs : t -> t * { 2 Successor and predecessor functions } val succ : t -> t val pred : t -> t val pow : t -> t -> t * { 2 Bit - wise logical operations } val bit_and : t -> t -> t val bit_or : t -> t -> t val bit_xor : t -> t -> t val bit_not : t -> t * Returns the number of 1 bits in the binary representation of the input . val popcount : t -> int * { 2 Bit - shifting operations } The results are unspecified for negative shifts and shifts [ > = num_bits ] . The results are unspecified for negative shifts and shifts [>= num_bits]. *) val shift_left : t -> int -> t val shift_right : t -> int -> t * { 2 Increment and decrement functions for integer references } val decr : t ref -> unit val incr : t ref -> unit * { 2 Conversion functions to related integer types } val of_int32_exn : int32 -> t val to_int32_exn : t -> int32 val of_int64_exn : int64 -> t val to_int64 : t -> int64 val of_nativeint_exn : nativeint -> t val to_nativeint_exn : t -> nativeint * [ of_float_unchecked ] truncates the given floating point number to an integer , rounding towards zero . The result is unspecified if the argument is or falls outside the range of representable integers . rounding towards zero. The result is unspecified if the argument is nan or falls outside the range of representable integers. *) val of_float_unchecked : float -> t end module type Operators_unbounded = sig type t val ( + ) : t -> t -> t val ( - ) : t -> t -> t val ( * ) : t -> t -> t val ( / ) : t -> t -> t val ( ~- ) : t -> t val ( ** ) : t -> t -> t include Comparisons.Infix with type t := t val abs : t -> t val neg : t -> t val zero : t val ( % ) : t -> t -> t val ( /% ) : t -> t -> t val ( // ) : t -> t -> float val ( land ) : t -> t -> t val ( lor ) : t -> t -> t val ( lxor ) : t -> t -> t val lnot : t -> t val ( lsl ) : t -> int -> t val ( asr ) : t -> int -> t end module type Operators = sig include Operators_unbounded val ( lsr ) : t -> int -> t end * [ S_unbounded ] is a generic interface for unbounded integers , e.g. [ . Bigint ] . [ S_unbounded ] is a restriction of [ S ] ( below ) that omits values that depend on fixed - size integers . [S_unbounded] is a restriction of [S] (below) that omits values that depend on fixed-size integers. *) module type S_unbounded = sig * @inline module O : Operators_unbounded with type t := t end module type S = sig * @inline val num_bits : int val max_value : t val min_value : t val ( lsr ) : t -> int -> t val shift_right_logical : t -> int -> t * [ ceil_pow2 x ] returns the smallest power of 2 that is greater than or equal to [ x ] . The implementation may only be called for [ x > 0 ] . Example : [ ceil_pow2 17 = 32 ] The implementation may only be called for [x > 0]. Example: [ceil_pow2 17 = 32] *) val ceil_pow2 : t -> t * [ floor_pow2 x ] returns the largest power of 2 that is less than or equal to [ x ] . The implementation may only be called for [ x > 0 ] . Example : [ floor_pow2 17 = 16 ] implementation may only be called for [x > 0]. Example: [floor_pow2 17 = 16] *) val floor_pow2 : t -> t val ceil_log2 : t -> int val floor_log2 : t -> int * [ is_pow2 x ] returns true iff [ x ] is a power of 2 . [ is_pow2 ] raises if [ x < = 0 ] . val is_pow2 : t -> bool * Returns the number of leading zeros in the binary representation of the input , as an integer between 0 and one less than [ num_bits ] . The results are unspecified for [ t = 0 ] . integer between 0 and one less than [num_bits]. The results are unspecified for [t = 0]. *) val clz : t -> int * Returns the number of trailing zeros in the binary representation of the input , as an integer between 0 and one less than [ num_bits ] . The results are unspecified for [ t = 0 ] . an integer between 0 and one less than [num_bits]. The results are unspecified for [t = 0]. *) val ctz : t -> int module O : Operators with type t := t end module type Int_without_module_types = sig * OCaml 's native integer type . The number of bits in an integer is platform dependent , being 31 - bits on a 32 - bit platform , and 63 - bits on a 64 - bit platform . [ int ] is a signed integer type . [ int]s are also subject to overflow , meaning that [ Int.max_value + 1 = Int.min_value ] . [ int]s always fit in a machine word . The number of bits in an integer is platform dependent, being 31-bits on a 32-bit platform, and 63-bits on a 64-bit platform. [int] is a signed integer type. [int]s are also subject to overflow, meaning that [Int.max_value + 1 = Int.min_value]. [int]s always fit in a machine word. *) * @inline module O : sig external ( + ) : t -> t -> t = "%addint" external ( - ) : t -> t -> t = "%subint" external ( * ) : t -> t -> t = "%mulint" external ( / ) : t -> t -> t = "%divint" external ( ~- ) : t -> t = "%negint" val ( ** ) : t -> t -> t external ( = ) : t -> t -> bool = "%equal" external ( <> ) : t -> t -> bool = "%notequal" external ( < ) : t -> t -> bool = "%lessthan" external ( > ) : t -> t -> bool = "%greaterthan" external ( <= ) : t -> t -> bool = "%lessequal" external ( >= ) : t -> t -> bool = "%greaterequal" external ( land ) : t -> t -> t = "%andint" external ( lor ) : t -> t -> t = "%orint" external ( lxor ) : t -> t -> t = "%xorint" val lnot : t -> t val abs : t -> t external neg : t -> t = "%negint" val zero : t val ( % ) : t -> t -> t val ( /% ) : t -> t -> t val ( // ) : t -> t -> float external ( lsl ) : t -> int -> t = "%lslint" external ( asr ) : t -> int -> t = "%asrint" external ( lsr ) : t -> int -> t = "%lsrint" end include module type of O * [ max_value_30_bits = 2 ^ 30 - 1 ] . It is useful for writing tests that work on both 64 - bit and 32 - bit platforms . 64-bit and 32-bit platforms. *) val max_value_30_bits : t * { 2 Conversion functions } val of_int : int -> t val to_int : t -> int val of_int32 : int32 -> t option val to_int32 : t -> int32 option val of_int64 : int64 -> t option val of_nativeint : nativeint -> t option val to_nativeint : t -> nativeint * { 3 Truncating conversions } These functions return the least - significant bits of the input . In cases where optional conversions return [ Some x ] , truncating conversions return [ x ] . These functions return the least-significant bits of the input. In cases where optional conversions return [Some x], truncating conversions return [x]. *) external to_int32_trunc : t -> int32 = "%int32_of_int" external of_int32_trunc : int32 -> t = "%int32_to_int" external of_int64_trunc : int64 -> t = "%int64_to_int" external of_nativeint_trunc : nativeint -> t = "%nativeint_to_int" * { 2 Byte swap operations } Byte swap operations reverse the order of bytes in an integer . For example , { ! Int32.bswap32 } reorders the bottom 32 bits ( or 4 bytes ) , turning [ 0x1122_3344 ] to [ 0x4433_2211 ] . Byte swap functions exposed by Base use OCaml primitives to generate assembly instructions to perform the relevant byte swaps . For a more extensive list of functions , see { ! Int32 } and { ! Int64 } . Byte swap operations reverse the order of bytes in an integer. For example, {!Int32.bswap32} reorders the bottom 32 bits (or 4 bytes), turning [0x1122_3344] to [0x4433_2211]. Byte swap functions exposed by Base use OCaml primitives to generate assembly instructions to perform the relevant byte swaps. For a more extensive list of byteswap functions, see {!Int32} and {!Int64}. *) * Byte swaps bottom 16 bits ( 2 bytes ) . The values of the remaining bytes are undefined . are undefined. *) external bswap16 : int -> int = "%bswap16" module Private : sig module O_F : sig val ( % ) : int -> int -> int val ( /% ) : int -> int -> int val ( // ) : int -> int -> float end end end module type Int = sig * @inline * { 2 Module types specifying integer operations . } module type Hexable = Hexable module type Int_without_module_types = Int_without_module_types module type Operators = Operators module type Operators_unbounded = Operators_unbounded module type Round = Round module type S = S module type S_common = S_common module type S_unbounded = S_unbounded end
7baf97ea1c7601949d4db052350c5428d4426ee0181f9eebf1a591f83699a0fc
footprintanalytics/footprint-web
users.clj
(ns metabase.test.data.users "Code related to creating / managing fake `Users` for testing purposes." (:require [clojure.test :as t] [medley.core :as m] [metabase.db.connection :as mdb.connection] [metabase.http-client :as client] [metabase.models.permissions-group :refer [PermissionsGroup]] [metabase.models.permissions-group-membership :refer [PermissionsGroupMembership]] [metabase.models.user :refer [User]] [metabase.server.middleware.session :as mw.session] [metabase.test.initialize :as initialize] [metabase.util :as u] [metabase.util.password :as u.password] [schema.core :as s] [toucan.db :as db] [toucan.util.test :as tt]) (:import clojure.lang.ExceptionInfo metabase.models.user.UserInstance)) ;;; ------------------------------------------------ User Definitions ------------------------------------------------ # # Test Users ;; ;; These users have permissions for the Test. They are lazily created as needed. Three test users are defined : ;; * rasta ;; * crowberto - superuser ;; * lucky * trashbird - inactive (def ^:private user->info {:rasta {:email "" :first "Rasta" :last "Toucan" :password "blueberries"} :crowberto {:email "" :first "Crowberto" :last "Corv" :password "blackjet" :superuser true} :lucky {:email "" :first "Lucky" :last "Pigeon" :password "almonds"} :trashbird {:email "" :first "Trash" :last "Bird" :password "birdseed" :active false}}) (def usernames (set (keys user->info))) (def ^:private TestUserName (apply s/enum usernames)) ;;; ------------------------------------------------- Test User Fns -------------------------------------------------- (def ^:private create-user-lock (Object.)) (defn- fetch-or-create-user! "Create User if they don't already exist and return User." [& {:keys [email first last password superuser active] :or {superuser false active true}}] {:pre [(string? email) (string? first) (string? last) (string? password) (m/boolean? superuser) (m/boolean? active)]} (initialize/initialize-if-needed! :db) (or (db/select-one User :email email) (locking create-user-lock (or (db/select-one User :email email) (db/insert! User :email email :first_name first :last_name last :password password :is_superuser superuser :is_qbnewb true :is_active active))))) (s/defn fetch-user :- UserInstance "Fetch the User object associated with `username`. Creates user if needed. (fetch-user :rasta) -> {:id 100 :first_name \"Rasta\" ...}" [username :- TestUserName] (m/mapply fetch-or-create-user! (user->info username))) (def ^{:arglists '([] [user-name])} user->id "Creates user if needed. With zero args, returns map of user name to ID. With 1 arg, returns ID of that User. Creates User(s) if needed. Memoized. - > { : rasta 4 , ... } (user->id :rasta) ; -> 4" (mdb.connection/memoize-for-application-db (fn ([] (zipmap usernames (map user->id usernames))) ([user-name] {:pre [(contains? usernames user-name)]} (u/the-id (fetch-user user-name)))))) (defn user-descriptor "Returns \"admin\" or \"non-admin\" for a given user. User could be a keyword like `:rasta` or a user object." [user] (cond (keyword user) (user-descriptor (fetch-user user)) (:is_superuser user) "admin" :else "non-admin")) (s/defn user->credentials :- {:username (s/pred u/email?), :password s/Str} "Return a map with `:username` and `:password` for User with `username`. (user->credentials :rasta) -> {:username \"\", :password \"blueberries\"}" [username :- TestUserName] {:pre [(contains? usernames username)]} (let [{:keys [email password]} (user->info username)] {:username email :password password})) (def ^{:arglists '([id])} id->user "Reverse of `user->id`. (id->user 4) -> :rasta" (let [m (delay (zipmap (map user->id usernames) usernames))] (fn [id] (@m id)))) (defonce ^:private tokens (atom {})) (s/defn username->token :- u/uuid-regex "Return cached session token for a test User, logging in first if needed." [username :- TestUserName] (or (@tokens username) (locking tokens (or (@tokens username) (u/prog1 (client/authenticate (user->credentials username)) (swap! tokens assoc username <>)))) (throw (Exception. (format "Authentication failed for %s with credentials %s" username (user->credentials username)))))) (defn clear-cached-session-tokens! "Clear any cached session tokens, which may have expired or been removed. You should do this in the even you get a `401` unauthenticated response, and then retry the request." [] (locking tokens (reset! tokens {}))) (def ^:private ^:dynamic *retrying-authentication* false) (defn- client-fn [username & args] (try (apply client/client (username->token username) args) (catch ExceptionInfo e (let [{:keys [status-code]} (ex-data e)] (when-not (= status-code 401) (throw e)) If we got a 401 unauthenticated clear the tokens cache + recur ;; ;; If we're already recursively retrying throw an Exception so we don't recurse forever. (when *retrying-authentication* (throw (ex-info (format "Failed to authenticate %s after two tries: %s" username (ex-message e)) {:user username} e))) (clear-cached-session-tokens!) (binding [*retrying-authentication* true] (apply client-fn username args)))))) (defn user-http-request "A version of our test HTTP client that issues the request with credentials for a given User. User may be either a redefined test User name, e.g. `:rasta`, or any User or User ID. (Because we don't have the User's original password, this function temporarily overrides the password for that User.)" {:arglists '([test-user-name-or-user-or-id method expected-status-code? endpoint request-options? http-body-map? & {:as query-params}])} [user & args] (if (keyword? user) (do (fetch-user user) (apply client-fn user args)) (let [user-id (u/the-id user) user-email (db/select-one-field :email User :id user-id) [old-password-info] (db/simple-select User {:select [:password :password_salt] :where [:= :id user-id]})] (when-not user-email (throw (ex-info "User does not exist" {:user user}))) (try (db/execute! {:update User :set {:password (u.password/hash-bcrypt user-email) :password_salt ""} :where [:= :id user-id]}) (apply client/client {:username user-email, :password user-email} args) (finally (db/execute! {:update User :set old-password-info :where [:= :id user-id]})))))) (defn do-with-test-user [user-kwd thunk] (t/testing (format "with test user %s\n" user-kwd) (mw.session/with-current-user (some-> user-kwd user->id) (thunk)))) (defmacro with-test-user "Call `body` with various `metabase.api.common` dynamic vars like `*current-user*` bound to the predefined test User named by `user-kwd`. If you want to bind a non-predefined-test User, use `mt/with-current-user` instead." {:style/indent 1} [user-kwd & body] `(do-with-test-user ~user-kwd (fn [] ~@body))) (defn test-user? "Does this User or User ID belong to one of the predefined test birds?" [user-or-id] (contains? (set (vals (user->id))) (u/the-id user-or-id))) (defn test-user-name-or-user-id->user-id [test-user-name-or-user-id] (if (keyword? test-user-name-or-user-id) (user->id test-user-name-or-user-id) (u/the-id test-user-name-or-user-id))) (defn do-with-group-for-user [group test-user-name-or-user-id f] (tt/with-temp* [PermissionsGroup [group group] PermissionsGroupMembership [_ {:group_id (u/the-id group) :user_id (test-user-name-or-user-id->user-id test-user-name-or-user-id)}]] (f group))) (defmacro with-group add test user ] to the group, then execute `body`." [[group-binding group] & body] `(do-with-group-for-user ~group :rasta (fn [~group-binding] ~@body))) (defmacro with-group-for-user "Like [[with-group]], but for any test user (by passing in a test username keyword e.g. `:rasta`) or User ID." [[group-binding test-user-name-or-user-id group] & body] `(do-with-group-for-user ~group ~test-user-name-or-user-id (fn [~group-binding] ~@body)))
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/test/data/users.clj
clojure
------------------------------------------------ User Definitions ------------------------------------------------ These users have permissions for the Test. They are lazily created as needed. * rasta * crowberto - superuser * lucky ------------------------------------------------- Test User Fns -------------------------------------------------- -> 4" If we're already recursively retrying throw an Exception so we don't recurse forever.
(ns metabase.test.data.users "Code related to creating / managing fake `Users` for testing purposes." (:require [clojure.test :as t] [medley.core :as m] [metabase.db.connection :as mdb.connection] [metabase.http-client :as client] [metabase.models.permissions-group :refer [PermissionsGroup]] [metabase.models.permissions-group-membership :refer [PermissionsGroupMembership]] [metabase.models.user :refer [User]] [metabase.server.middleware.session :as mw.session] [metabase.test.initialize :as initialize] [metabase.util :as u] [metabase.util.password :as u.password] [schema.core :as s] [toucan.db :as db] [toucan.util.test :as tt]) (:import clojure.lang.ExceptionInfo metabase.models.user.UserInstance)) # # Test Users Three test users are defined : * trashbird - inactive (def ^:private user->info {:rasta {:email "" :first "Rasta" :last "Toucan" :password "blueberries"} :crowberto {:email "" :first "Crowberto" :last "Corv" :password "blackjet" :superuser true} :lucky {:email "" :first "Lucky" :last "Pigeon" :password "almonds"} :trashbird {:email "" :first "Trash" :last "Bird" :password "birdseed" :active false}}) (def usernames (set (keys user->info))) (def ^:private TestUserName (apply s/enum usernames)) (def ^:private create-user-lock (Object.)) (defn- fetch-or-create-user! "Create User if they don't already exist and return User." [& {:keys [email first last password superuser active] :or {superuser false active true}}] {:pre [(string? email) (string? first) (string? last) (string? password) (m/boolean? superuser) (m/boolean? active)]} (initialize/initialize-if-needed! :db) (or (db/select-one User :email email) (locking create-user-lock (or (db/select-one User :email email) (db/insert! User :email email :first_name first :last_name last :password password :is_superuser superuser :is_qbnewb true :is_active active))))) (s/defn fetch-user :- UserInstance "Fetch the User object associated with `username`. Creates user if needed. (fetch-user :rasta) -> {:id 100 :first_name \"Rasta\" ...}" [username :- TestUserName] (m/mapply fetch-or-create-user! (user->info username))) (def ^{:arglists '([] [user-name])} user->id "Creates user if needed. With zero args, returns map of user name to ID. With 1 arg, returns ID of that User. Creates User(s) if needed. Memoized. - > { : rasta 4 , ... } (mdb.connection/memoize-for-application-db (fn ([] (zipmap usernames (map user->id usernames))) ([user-name] {:pre [(contains? usernames user-name)]} (u/the-id (fetch-user user-name)))))) (defn user-descriptor "Returns \"admin\" or \"non-admin\" for a given user. User could be a keyword like `:rasta` or a user object." [user] (cond (keyword user) (user-descriptor (fetch-user user)) (:is_superuser user) "admin" :else "non-admin")) (s/defn user->credentials :- {:username (s/pred u/email?), :password s/Str} "Return a map with `:username` and `:password` for User with `username`. (user->credentials :rasta) -> {:username \"\", :password \"blueberries\"}" [username :- TestUserName] {:pre [(contains? usernames username)]} (let [{:keys [email password]} (user->info username)] {:username email :password password})) (def ^{:arglists '([id])} id->user "Reverse of `user->id`. (id->user 4) -> :rasta" (let [m (delay (zipmap (map user->id usernames) usernames))] (fn [id] (@m id)))) (defonce ^:private tokens (atom {})) (s/defn username->token :- u/uuid-regex "Return cached session token for a test User, logging in first if needed." [username :- TestUserName] (or (@tokens username) (locking tokens (or (@tokens username) (u/prog1 (client/authenticate (user->credentials username)) (swap! tokens assoc username <>)))) (throw (Exception. (format "Authentication failed for %s with credentials %s" username (user->credentials username)))))) (defn clear-cached-session-tokens! "Clear any cached session tokens, which may have expired or been removed. You should do this in the even you get a `401` unauthenticated response, and then retry the request." [] (locking tokens (reset! tokens {}))) (def ^:private ^:dynamic *retrying-authentication* false) (defn- client-fn [username & args] (try (apply client/client (username->token username) args) (catch ExceptionInfo e (let [{:keys [status-code]} (ex-data e)] (when-not (= status-code 401) (throw e)) If we got a 401 unauthenticated clear the tokens cache + recur (when *retrying-authentication* (throw (ex-info (format "Failed to authenticate %s after two tries: %s" username (ex-message e)) {:user username} e))) (clear-cached-session-tokens!) (binding [*retrying-authentication* true] (apply client-fn username args)))))) (defn user-http-request "A version of our test HTTP client that issues the request with credentials for a given User. User may be either a redefined test User name, e.g. `:rasta`, or any User or User ID. (Because we don't have the User's original password, this function temporarily overrides the password for that User.)" {:arglists '([test-user-name-or-user-or-id method expected-status-code? endpoint request-options? http-body-map? & {:as query-params}])} [user & args] (if (keyword? user) (do (fetch-user user) (apply client-fn user args)) (let [user-id (u/the-id user) user-email (db/select-one-field :email User :id user-id) [old-password-info] (db/simple-select User {:select [:password :password_salt] :where [:= :id user-id]})] (when-not user-email (throw (ex-info "User does not exist" {:user user}))) (try (db/execute! {:update User :set {:password (u.password/hash-bcrypt user-email) :password_salt ""} :where [:= :id user-id]}) (apply client/client {:username user-email, :password user-email} args) (finally (db/execute! {:update User :set old-password-info :where [:= :id user-id]})))))) (defn do-with-test-user [user-kwd thunk] (t/testing (format "with test user %s\n" user-kwd) (mw.session/with-current-user (some-> user-kwd user->id) (thunk)))) (defmacro with-test-user "Call `body` with various `metabase.api.common` dynamic vars like `*current-user*` bound to the predefined test User named by `user-kwd`. If you want to bind a non-predefined-test User, use `mt/with-current-user` instead." {:style/indent 1} [user-kwd & body] `(do-with-test-user ~user-kwd (fn [] ~@body))) (defn test-user? "Does this User or User ID belong to one of the predefined test birds?" [user-or-id] (contains? (set (vals (user->id))) (u/the-id user-or-id))) (defn test-user-name-or-user-id->user-id [test-user-name-or-user-id] (if (keyword? test-user-name-or-user-id) (user->id test-user-name-or-user-id) (u/the-id test-user-name-or-user-id))) (defn do-with-group-for-user [group test-user-name-or-user-id f] (tt/with-temp* [PermissionsGroup [group group] PermissionsGroupMembership [_ {:group_id (u/the-id group) :user_id (test-user-name-or-user-id->user-id test-user-name-or-user-id)}]] (f group))) (defmacro with-group add test user ] to the group, then execute `body`." [[group-binding group] & body] `(do-with-group-for-user ~group :rasta (fn [~group-binding] ~@body))) (defmacro with-group-for-user "Like [[with-group]], but for any test user (by passing in a test username keyword e.g. `:rasta`) or User ID." [[group-binding test-user-name-or-user-id group] & body] `(do-with-group-for-user ~group ~test-user-name-or-user-id (fn [~group-binding] ~@body)))
45d3795b49c090faf9b6cf58fc3c97a0c57d5d28cefe57a16a0afcf8a6245850
cognitect-labs/vase
datomic.clj
(ns com.cognitect.vase.datomic (:require [datomic.api :as d] [io.rkn.conformity :as c] [io.pedestal.interceptor :as i])) (defn new-db-uri [] (str "datomic:mem://" (d/squuid))) (defn connect "Given a Datomic URI, attempt to create the database and connect to it, returning the connection." [uri] (d/create-database uri) (d/connect uri)) (defn normalize-norm-keys [norms] (reduce (fn [acc [k-title v-map]] (assoc acc k-title (reduce (fn [norm-acc [nk nv]] (assoc norm-acc (keyword (name nk)) nv)) {} v-map))) {} norms)) (defn ensure-schema [conn norms] (c/ensure-conforms conn (normalize-norm-keys norms))) (defn insert-datomic "Provide a Datomic conn and db in all incoming requests" [conn] (i/interceptor {:name ::insert-datomic :enter (fn [context] (-> context (assoc-in [:request :conn] conn) (assoc-in [:request :db] (d/db conn))))}))
null
https://raw.githubusercontent.com/cognitect-labs/vase/d882bc8f28e8af2077b55c80e069aa2238f646b7/src/com/cognitect/vase/datomic.clj
clojure
(ns com.cognitect.vase.datomic (:require [datomic.api :as d] [io.rkn.conformity :as c] [io.pedestal.interceptor :as i])) (defn new-db-uri [] (str "datomic:mem://" (d/squuid))) (defn connect "Given a Datomic URI, attempt to create the database and connect to it, returning the connection." [uri] (d/create-database uri) (d/connect uri)) (defn normalize-norm-keys [norms] (reduce (fn [acc [k-title v-map]] (assoc acc k-title (reduce (fn [norm-acc [nk nv]] (assoc norm-acc (keyword (name nk)) nv)) {} v-map))) {} norms)) (defn ensure-schema [conn norms] (c/ensure-conforms conn (normalize-norm-keys norms))) (defn insert-datomic "Provide a Datomic conn and db in all incoming requests" [conn] (i/interceptor {:name ::insert-datomic :enter (fn [context] (-> context (assoc-in [:request :conn] conn) (assoc-in [:request :db] (d/db conn))))}))
a7572762bb4a1293dcf2138a8dbff809046f6e80edcfd829587653e96cb20244
leksah/leksah-server
Server.hs
# LANGUAGE FlexibleInstances , ScopedTypeVariables # ----------------------------------------------------------------------------- -- -- Module : IDE.Utils.Server Copyright : 2007 - 2011 , -- License : GPL -- -- Maintainer : -- Stability : provisional -- Portability : -- -- | -- ------------------------------------------------------------------------------ module IDE.Utils.Server ( ipAddress , Server (..) , serveOne , serveMany , ServerRoutine , UserAndGroup (..) , WaitFor (waitFor)) where import Prelude () import Prelude.Compat import Network.Socket import System.IO import Control.Concurrent import Control.Exception as E import Data.Word import System.Log.Logger (infoM) import Data.Text (Text) import Control.Monad (void) data UserAndGroup = UserAndGroup Text Text | UserWithDefaultGroup Text -- | Set the user and group for the process. If the group is Nothing, then use the users default group. -- This is especially useful when you are root and want to become a user. setUserAndGroup :: UserAndGroup -> IO () setUserAndGroup _ = return () -- | make an IP Address: (127,0,0,1) is the localhost ipAddress :: (Word8, Word8, Word8, Word8) -> HostAddress ipAddress (a, b, c, d) = fromIntegral a + 0x100 * fromIntegral b + 0x10000 * fromIntegral c + 0x1000000 * fromIntegral d -- | the functionality of a server type ServerRoutine = (Handle, SockAddr) -> MVar () -> IO () serverSocket' :: Server -> IO Socket serverSocket' (Server addrInfo _) = socket (addrFamily addrInfo) (addrSocketType addrInfo) (addrProtocol addrInfo) serverSocket :: Server -> IO (Socket, Server) serverSocket server = do sock <- serverSocket' server setSocketOption sock ReuseAddr 1 bind sock (addrAddress $ serverAddr server) infoM "leksah-server" $ "Bind " ++ show (serverAddr server) listen sock maxListenQueue return (sock, server) -- |the specification of a serving process data Server = Server { serverAddr :: AddrInfo, serverRoutine :: ServerRoutine} startAccepting :: (Socket, Server) -> IO (ThreadId, MVar ()) startAccepting (sock, server) = do mvar <- newEmptyMVar threadId <- forkIO (acceptance sock mvar (serverRoutine server) `finally` putMVar mvar ()) return (threadId, mvar) serveMany :: Maybe UserAndGroup -> [Server] -> IO [(ThreadId, MVar ())] serveMany (Just userAndGroup) l = do ready <- mapM serverSocket l setUserAndGroup userAndGroup mapM startAccepting ready serveMany Nothing l = mapM serverSocket l >>= mapM startAccepting serveOne :: Maybe UserAndGroup -> Server -> IO (ThreadId, MVar ()) serveOne ug s = do l <- serveMany ug [s] return (head l) class WaitFor a where waitFor :: a -> IO () instance WaitFor (MVar a) where waitFor mvar = void (readMVar mvar) instance WaitFor a => WaitFor [a] where waitFor = mapM_ waitFor instance WaitFor (ThreadId, MVar ()) where waitFor (_, mvar) = waitFor mvar acceptance :: Socket -> MVar () -> ServerRoutine -> IO () acceptance sock mvar action = E.catch (do (s, a) <- accept sock h <- socketToHandle s ReadWriteMode void . forkIO $ action (h, a) mvar) (\(e :: SomeException) -> print e) >> acceptance sock mvar action
null
https://raw.githubusercontent.com/leksah/leksah-server/d4b735c17a36123dc97f79fabf1e9310d74984a6/src/IDE/Utils/Server.hs
haskell
--------------------------------------------------------------------------- Module : IDE.Utils.Server License : GPL Maintainer : Stability : provisional Portability : | ---------------------------------------------------------------------------- | Set the user and group for the process. If the group is Nothing, then use the users default group. This is especially useful when you are root and want to become a user. | make an IP Address: (127,0,0,1) is the localhost | the functionality of a server |the specification of a serving process
# LANGUAGE FlexibleInstances , ScopedTypeVariables # Copyright : 2007 - 2011 , module IDE.Utils.Server ( ipAddress , Server (..) , serveOne , serveMany , ServerRoutine , UserAndGroup (..) , WaitFor (waitFor)) where import Prelude () import Prelude.Compat import Network.Socket import System.IO import Control.Concurrent import Control.Exception as E import Data.Word import System.Log.Logger (infoM) import Data.Text (Text) import Control.Monad (void) data UserAndGroup = UserAndGroup Text Text | UserWithDefaultGroup Text setUserAndGroup :: UserAndGroup -> IO () setUserAndGroup _ = return () ipAddress :: (Word8, Word8, Word8, Word8) -> HostAddress ipAddress (a, b, c, d) = fromIntegral a + 0x100 * fromIntegral b + 0x10000 * fromIntegral c + 0x1000000 * fromIntegral d type ServerRoutine = (Handle, SockAddr) -> MVar () -> IO () serverSocket' :: Server -> IO Socket serverSocket' (Server addrInfo _) = socket (addrFamily addrInfo) (addrSocketType addrInfo) (addrProtocol addrInfo) serverSocket :: Server -> IO (Socket, Server) serverSocket server = do sock <- serverSocket' server setSocketOption sock ReuseAddr 1 bind sock (addrAddress $ serverAddr server) infoM "leksah-server" $ "Bind " ++ show (serverAddr server) listen sock maxListenQueue return (sock, server) data Server = Server { serverAddr :: AddrInfo, serverRoutine :: ServerRoutine} startAccepting :: (Socket, Server) -> IO (ThreadId, MVar ()) startAccepting (sock, server) = do mvar <- newEmptyMVar threadId <- forkIO (acceptance sock mvar (serverRoutine server) `finally` putMVar mvar ()) return (threadId, mvar) serveMany :: Maybe UserAndGroup -> [Server] -> IO [(ThreadId, MVar ())] serveMany (Just userAndGroup) l = do ready <- mapM serverSocket l setUserAndGroup userAndGroup mapM startAccepting ready serveMany Nothing l = mapM serverSocket l >>= mapM startAccepting serveOne :: Maybe UserAndGroup -> Server -> IO (ThreadId, MVar ()) serveOne ug s = do l <- serveMany ug [s] return (head l) class WaitFor a where waitFor :: a -> IO () instance WaitFor (MVar a) where waitFor mvar = void (readMVar mvar) instance WaitFor a => WaitFor [a] where waitFor = mapM_ waitFor instance WaitFor (ThreadId, MVar ()) where waitFor (_, mvar) = waitFor mvar acceptance :: Socket -> MVar () -> ServerRoutine -> IO () acceptance sock mvar action = E.catch (do (s, a) <- accept sock h <- socketToHandle s ReadWriteMode void . forkIO $ action (h, a) mvar) (\(e :: SomeException) -> print e) >> acceptance sock mvar action
c428d7daee302f7ea8597bf7fa6f6cf8e5ecb033e978e9a400087f8dc3465dd6
reborg/clojure-essential-reference
7.clj
< 1 > (defn ^:dynamic y [] 9) < 2 > (future (binding [x #(rand)] (* (x) (y)))) (future (binding [y #(rand)] (* (x) (y))))) [(x) (y)] ; <3> [ 5 9 ]
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/VarsandNamespaces/alter-var-rootandwith-redefs/7.clj
clojure
<3>
< 1 > (defn ^:dynamic y [] 9) < 2 > (future (binding [x #(rand)] (* (x) (y)))) (future (binding [y #(rand)] (* (x) (y))))) [ 5 9 ]
97a87be28e00bec72e760c03a6a8e15ba08c89937fa49abcdb569d42bed59b65
ultralisp/ultralisp
file-server.lisp
(defpackage #:ultralisp/file-server (:use #:cl) (:import-from #:reblocks-file-server) (:export #:make-route)) (in-package #:ultralisp/file-server) (defun make-route (root uri) (uiop:ensure-all-directories-exist (list root)) (reblocks-file-server:make-route :uri uri :root root))
null
https://raw.githubusercontent.com/ultralisp/ultralisp/37bd5d92b2cf751cd03ced69bac785bf4bcb6c15/src/file-server.lisp
lisp
(defpackage #:ultralisp/file-server (:use #:cl) (:import-from #:reblocks-file-server) (:export #:make-route)) (in-package #:ultralisp/file-server) (defun make-route (root uri) (uiop:ensure-all-directories-exist (list root)) (reblocks-file-server:make-route :uri uri :root root))
3a5439deb3a68b2c36cae4a07bbf1db7d30af0ed691b6f2fd7b44c4f5ad22f5a
ghc/packages-Cabal
Version.hs
----------------------------------------------------------------------------- -- | -- Module : Distribution.Version Copyright : , 2003 - 2004 2008 -- License : BSD3 -- -- Maintainer : -- Portability : portable -- -- Exports the 'Version' type along with a parser and pretty printer. A version is something like @\"1.3.3\"@. It also defines the ' VersionRange ' data types . Version ranges are like @\">= 1.2 & & < 2\"@. module Distribution.Version ( -- * Package versions Version, version0, mkVersion, mkVersion', versionNumbers, nullVersion, alterVersion, -- * Version ranges VersionRange, -- ** Constructing anyVersion, noVersion, thisVersion, notThisVersion, laterVersion, earlierVersion, orLaterVersion, orEarlierVersion, unionVersionRanges, intersectVersionRanges, differenceVersionRanges, invertVersionRange, withinVersion, majorBoundVersion, -- ** Inspection withinRange, isAnyVersion, isNoVersion, isSpecificVersion, simplifyVersionRange, foldVersionRange, normaliseVersionRange, stripParensVersionRange, hasUpperBound, hasLowerBound, * * Cata & ana VersionRangeF (..), cataVersionRange, anaVersionRange, hyloVersionRange, projectVersionRange, embedVersionRange, -- ** Utilities wildcardUpperBound, majorUpperBound, -- ** Modification removeUpperBound, removeLowerBound, -- * Version intervals view asVersionIntervals, VersionInterval, LowerBound(..), UpperBound(..), Bound(..), * * ' VersionIntervals ' abstract type | The ' VersionIntervals ' type and the accompanying functions are exposed -- primarily for completeness and testing purposes. In practice -- 'asVersionIntervals' is the main function to use to view a ' VersionRange ' as a bunch of ' VersionInterval 's . -- VersionIntervals, toVersionIntervals, fromVersionIntervals, withinIntervals, versionIntervals, mkVersionIntervals, unionVersionIntervals, intersectVersionIntervals, invertVersionIntervals ) where import Distribution.Types.Version import Distribution.Types.VersionRange import Distribution.Types.VersionInterval ------------------------------------------------------------------------------- Utilities on VersionRange requiring VersionInterval ------------------------------------------------------------------------------- -- | This is the converse of 'isAnyVersion'. It check if the version range is -- empty, if there is no possible version that satisfies the version range. -- For example this is ( for all @v@ ): -- -- > isNoVersion (EarlierVersion v `IntersectVersionRanges` LaterVersion v) -- isNoVersion :: VersionRange -> Bool isNoVersion vr = case asVersionIntervals vr of [] -> True _ -> False -- | Is this version range in fact just a specific version? -- For example the version range @\">= 3 & & < = 3\"@ contains only the version -- @3@. -- isSpecificVersion :: VersionRange -> Maybe Version isSpecificVersion vr = case asVersionIntervals vr of [(LowerBound v InclusiveBound ,UpperBound v' InclusiveBound)] | v == v' -> Just v _ -> Nothing | Simplify a ' VersionRange ' expression . For non - empty version ranges -- this produces a canonical form. Empty or inconsistent version ranges -- are left as-is because that provides more information. -- -- If you need a canonical form use -- @fromVersionIntervals . toVersionIntervals@ -- -- It satisfies the following properties: -- > withinRange v ( simplifyVersionRange r ) v r -- > withinRange v r = withinRange v r ' -- > ==> simplifyVersionRange r = simplifyVersionRange r' -- > || isNoVersion r -- > || isNoVersion r' -- simplifyVersionRange :: VersionRange -> VersionRange simplifyVersionRange vr -- If the version range is inconsistent then we just return the original since that has more information than " > 1 & & < 1 " , which -- is the canonical inconsistent version range. | null (versionIntervals vi) = vr | otherwise = fromVersionIntervals vi where vi = toVersionIntervals vr | The difference of two version ranges -- > withinRange v ' ( differenceVersionRanges vr1 vr2 ) > = withinRange v ' vr1 & & not ( withinRange v ' vr2 ) -- @since 1.24.1.0 differenceVersionRanges :: VersionRange -> VersionRange -> VersionRange differenceVersionRanges vr1 vr2 = intersectVersionRanges vr1 (invertVersionRange vr2) -- | The inverse of a version range -- > withinRange v ' ( invertVersionRange vr ) > = not ( withinRange v ' vr ) -- invertVersionRange :: VersionRange -> VersionRange invertVersionRange = fromVersionIntervals . invertVersionIntervals . toVersionIntervals | Given a version range , remove the highest upper bound . Example : @(>= 1 & & < 3 ) || ( > = 4 & & < 5)@ is converted to @(>= 1 & & < 3 ) || ( > = 4)@. removeUpperBound :: VersionRange -> VersionRange removeUpperBound = fromVersionIntervals . relaxLastInterval . toVersionIntervals -- | Given a version range, remove the lowest lower bound. Example : @(>= 1 & & < 3 ) || ( > = 4 & & < 5)@ is converted to @(>= 0 & & < 3 ) || ( > = 4 & & < 5)@. removeLowerBound :: VersionRange -> VersionRange removeLowerBound = fromVersionIntervals . relaxHeadInterval . toVersionIntervals
null
https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/Cabal/Distribution/Version.hs
haskell
--------------------------------------------------------------------------- | Module : Distribution.Version License : BSD3 Maintainer : Portability : portable Exports the 'Version' type along with a parser and pretty printer. A version * Package versions * Version ranges ** Constructing ** Inspection ** Utilities ** Modification * Version intervals view primarily for completeness and testing purposes. In practice 'asVersionIntervals' is the main function to use to ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- | This is the converse of 'isAnyVersion'. It check if the version range is empty, if there is no possible version that satisfies the version range. > isNoVersion (EarlierVersion v `IntersectVersionRanges` LaterVersion v) | Is this version range in fact just a specific version? @3@. this produces a canonical form. Empty or inconsistent version ranges are left as-is because that provides more information. If you need a canonical form use @fromVersionIntervals . toVersionIntervals@ It satisfies the following properties: > ==> simplifyVersionRange r = simplifyVersionRange r' > || isNoVersion r > || isNoVersion r' If the version range is inconsistent then we just return the is the canonical inconsistent version range. | The inverse of a version range | Given a version range, remove the lowest lower bound.
Copyright : , 2003 - 2004 2008 is something like @\"1.3.3\"@. It also defines the ' VersionRange ' data types . Version ranges are like @\">= 1.2 & & < 2\"@. module Distribution.Version ( Version, version0, mkVersion, mkVersion', versionNumbers, nullVersion, alterVersion, VersionRange, anyVersion, noVersion, thisVersion, notThisVersion, laterVersion, earlierVersion, orLaterVersion, orEarlierVersion, unionVersionRanges, intersectVersionRanges, differenceVersionRanges, invertVersionRange, withinVersion, majorBoundVersion, withinRange, isAnyVersion, isNoVersion, isSpecificVersion, simplifyVersionRange, foldVersionRange, normaliseVersionRange, stripParensVersionRange, hasUpperBound, hasLowerBound, * * Cata & ana VersionRangeF (..), cataVersionRange, anaVersionRange, hyloVersionRange, projectVersionRange, embedVersionRange, wildcardUpperBound, majorUpperBound, removeUpperBound, removeLowerBound, asVersionIntervals, VersionInterval, LowerBound(..), UpperBound(..), Bound(..), * * ' VersionIntervals ' abstract type | The ' VersionIntervals ' type and the accompanying functions are exposed view a ' VersionRange ' as a bunch of ' VersionInterval 's . VersionIntervals, toVersionIntervals, fromVersionIntervals, withinIntervals, versionIntervals, mkVersionIntervals, unionVersionIntervals, intersectVersionIntervals, invertVersionIntervals ) where import Distribution.Types.Version import Distribution.Types.VersionRange import Distribution.Types.VersionInterval Utilities on VersionRange requiring VersionInterval For example this is ( for all @v@ ): isNoVersion :: VersionRange -> Bool isNoVersion vr = case asVersionIntervals vr of [] -> True _ -> False For example the version range @\">= 3 & & < = 3\"@ contains only the version isSpecificVersion :: VersionRange -> Maybe Version isSpecificVersion vr = case asVersionIntervals vr of [(LowerBound v InclusiveBound ,UpperBound v' InclusiveBound)] | v == v' -> Just v _ -> Nothing | Simplify a ' VersionRange ' expression . For non - empty version ranges > withinRange v ( simplifyVersionRange r ) v r > withinRange v r = withinRange v r ' simplifyVersionRange :: VersionRange -> VersionRange simplifyVersionRange vr original since that has more information than " > 1 & & < 1 " , which | null (versionIntervals vi) = vr | otherwise = fromVersionIntervals vi where vi = toVersionIntervals vr | The difference of two version ranges > withinRange v ' ( differenceVersionRanges vr1 vr2 ) > = withinRange v ' vr1 & & not ( withinRange v ' vr2 ) @since 1.24.1.0 differenceVersionRanges :: VersionRange -> VersionRange -> VersionRange differenceVersionRanges vr1 vr2 = intersectVersionRanges vr1 (invertVersionRange vr2) > withinRange v ' ( invertVersionRange vr ) > = not ( withinRange v ' vr ) invertVersionRange :: VersionRange -> VersionRange invertVersionRange = fromVersionIntervals . invertVersionIntervals . toVersionIntervals | Given a version range , remove the highest upper bound . Example : @(>= 1 & & < 3 ) || ( > = 4 & & < 5)@ is converted to @(>= 1 & & < 3 ) || ( > = 4)@. removeUpperBound :: VersionRange -> VersionRange removeUpperBound = fromVersionIntervals . relaxLastInterval . toVersionIntervals Example : @(>= 1 & & < 3 ) || ( > = 4 & & < 5)@ is converted to @(>= 0 & & < 3 ) || ( > = 4 & & < 5)@. removeLowerBound :: VersionRange -> VersionRange removeLowerBound = fromVersionIntervals . relaxHeadInterval . toVersionIntervals
b15f5425fe1c4381d8d4a83d52a414ffcb3d95fa369ab51254e9caece1a8c4c3
nikita-volkov/rerebase
Strict.hs
module Control.Monad.ST.Strict ( module Rebase.Control.Monad.ST.Strict ) where import Rebase.Control.Monad.ST.Strict
null
https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Control/Monad/ST/Strict.hs
haskell
module Control.Monad.ST.Strict ( module Rebase.Control.Monad.ST.Strict ) where import Rebase.Control.Monad.ST.Strict
986537a832b68bdc4ae9914aa4e9b2688a51aa4ed2f66c5b876b2131d71f33e4
alanz/ghc-exactprint
LayoutWhere.hs
foo x = r where a = 3 b = 4 r = a + a + b
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc710/LayoutWhere.hs
haskell
foo x = r where a = 3 b = 4 r = a + a + b
6d37cdf9837a3d8b822811e8fea12b25c903703ccbad4de32fac3a8343e0f313
Perry961002/SICP
exe4.39.scm
(define (multiple-dwelling) (let ((baker (amb 1 2 3 4 5)) (cooper (amb 1 2 3 4 5)) (fletcher (amb 1 2 3 4 5)) (miller (amb 1 2 3 4 5)) (smith (amb 1 2 3 4 5))) (require (distinct? (list baker cooper fletcher miller smith))) (require (not (= (abs (- smith fletcher)) 1))) (require (not (= (abs (- fletcher cooper)) 1))) (require (> miller cooper)) (require (not (= baker 5))) (require (not (= cooper 1))) (require (not (fletcher 5))) (require (not (fletcher 1))) (list (list 'baker baker) (list 'cooper cooper) (list 'fletcher fletcher) (list 'miller miller) (list 'smith smith))))
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap4/exercise/exe4.39.scm
scheme
(define (multiple-dwelling) (let ((baker (amb 1 2 3 4 5)) (cooper (amb 1 2 3 4 5)) (fletcher (amb 1 2 3 4 5)) (miller (amb 1 2 3 4 5)) (smith (amb 1 2 3 4 5))) (require (distinct? (list baker cooper fletcher miller smith))) (require (not (= (abs (- smith fletcher)) 1))) (require (not (= (abs (- fletcher cooper)) 1))) (require (> miller cooper)) (require (not (= baker 5))) (require (not (= cooper 1))) (require (not (fletcher 5))) (require (not (fletcher 1))) (list (list 'baker baker) (list 'cooper cooper) (list 'fletcher fletcher) (list 'miller miller) (list 'smith smith))))
94ab19621a531d04fe7d5754e81a64818c5b96846d8219023a04496ef2016b8d
onedata/op-worker
archive_traverses_common.erl
%%%------------------------------------------------------------------- @author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%------------------------------------------------------------------- %%% @doc %%% Helper module containing common functions used across archivisation %%% traverse modules. %%% @end %%%------------------------------------------------------------------- -module(archive_traverses_common). -author("Michal Stanisz"). -include("tree_traverse.hrl"). -include("modules/dataset/archive.hrl"). -include("modules/datastore/datastore_models.hrl"). -include("modules/datastore/datastore_runner.hrl"). -include_lib("ctool/include/errors.hrl"). %% API -export([do_master_job/4]). -export([update_children_count/4, take_children_count/3]). -export([execute_unsafe_job/5]). -export([is_cancelling/1]). -type error_handler(T) :: fun((tree_traverse:job(), Error :: any(), Stacktrace :: list()) -> T). %%%=================================================================== %%% API functions %%%=================================================================== -spec do_master_job(module(), tree_traverse:master_job(), traverse:master_job_extended_args(), error_handler({ok, traverse:master_job_map()})) -> {ok, traverse:master_job_map()}. do_master_job( TraverseModule, Job = #tree_traverse{file_ctx = FileCtx}, MasterJobArgs, ErrorHandler ) -> {IsDir, FileCtx2} = file_ctx:is_dir(FileCtx), {Module, Function} = case IsDir of true -> {TraverseModule, do_dir_master_job_unsafe}; false -> {tree_traverse, do_master_job} end, UpdatedJob = Job#tree_traverse{file_ctx = FileCtx2}, archive_traverses_common:execute_unsafe_job( Module, Function, [MasterJobArgs], UpdatedJob, ErrorHandler). -spec execute_unsafe_job(module(), atom(), [term()], tree_traverse:job(), error_handler(T)) -> T. execute_unsafe_job(Module, JobFunctionName, Options, Job, ErrorHandler) -> try erlang:apply(Module, JobFunctionName, [Job | Options]) catch _Class:{badmatch, {error, Reason}}:Stacktrace -> ErrorHandler(Job, ?ERROR_POSIX(Reason), Stacktrace); _Class:Reason:Stacktrace -> ErrorHandler(Job, Reason, Stacktrace) end. -spec is_cancelling(archivisation_traverse_ctx:ctx() | archive:doc() | archive:id()) -> boolean() | {error, term()}. is_cancelling(ArchiveId) when is_binary(ArchiveId) -> case archive:get(ArchiveId) of {ok, #document{value = #archive{state = ?ARCHIVE_CANCELLING(_)}}} -> true; {ok, #document{}} -> false; {error, _} = Error -> Error end; is_cancelling(#document{key = ArchiveId}) -> is_cancelling(ArchiveId); is_cancelling(ArchiveCtx) -> case archivisation_traverse_ctx:get_archive_doc(ArchiveCtx) of undefined -> false; ArchiveDoc -> is_cancelling(ArchiveDoc) end. -spec update_children_count(tree_traverse:pool(), tree_traverse:id(), file_meta:uuid(), non_neg_integer()) -> ok. update_children_count(PoolName, TaskId, DirUuid, ChildrenCount) -> ?extract_ok(traverse_task:update_additional_data(traverse_task:get_ctx(), PoolName, TaskId, fun(AD) -> PrevCountMap = get_count_map(AD), UpdatedMap = case PrevCountMap of #{DirUuid := PrevCountBin} -> PrevCountMap#{ DirUuid => integer_to_binary(binary_to_integer(PrevCountBin) + ChildrenCount) }; _ -> PrevCountMap#{ DirUuid => integer_to_binary(ChildrenCount) } end, {ok, set_count_map(AD, UpdatedMap)} end )). -spec take_children_count(tree_traverse:pool(), tree_traverse:id(), file_meta:uuid()) -> non_neg_integer(). take_children_count(PoolName, TaskId, DirUuid) -> {ok, AdditionalData} = traverse_task:get_additional_data(PoolName, TaskId), ChildrenCount = maps:get(DirUuid, get_count_map(AdditionalData)), ok = ?extract_ok(traverse_task:update_additional_data(traverse_task:get_ctx(), PoolName, TaskId, fun(AD) -> {ok, set_count_map(AD, maps:remove(DirUuid, get_count_map(AD)))} end )), binary_to_integer(ChildrenCount). %%%=================================================================== Internal functions %%%=================================================================== -spec get_count_map(traverse:additional_data()) -> map(). get_count_map(AD) -> CountMapBin = maps:get(<<"children_count_map">>, AD, term_to_binary(#{})), binary_to_term(CountMapBin). -spec set_count_map(traverse:additional_data(), map()) -> traverse:additional_data(). set_count_map(AD, CountMap) -> AD#{<<"children_count_map">> => term_to_binary(CountMap)}.
null
https://raw.githubusercontent.com/onedata/op-worker/be74364154d030cba51abae90645447a1b740429/src/modules/archive/traverse/archive_traverses_common.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- @doc Helper module containing common functions used across archivisation traverse modules. @end ------------------------------------------------------------------- API =================================================================== API functions =================================================================== =================================================================== ===================================================================
@author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . -module(archive_traverses_common). -author("Michal Stanisz"). -include("tree_traverse.hrl"). -include("modules/dataset/archive.hrl"). -include("modules/datastore/datastore_models.hrl"). -include("modules/datastore/datastore_runner.hrl"). -include_lib("ctool/include/errors.hrl"). -export([do_master_job/4]). -export([update_children_count/4, take_children_count/3]). -export([execute_unsafe_job/5]). -export([is_cancelling/1]). -type error_handler(T) :: fun((tree_traverse:job(), Error :: any(), Stacktrace :: list()) -> T). -spec do_master_job(module(), tree_traverse:master_job(), traverse:master_job_extended_args(), error_handler({ok, traverse:master_job_map()})) -> {ok, traverse:master_job_map()}. do_master_job( TraverseModule, Job = #tree_traverse{file_ctx = FileCtx}, MasterJobArgs, ErrorHandler ) -> {IsDir, FileCtx2} = file_ctx:is_dir(FileCtx), {Module, Function} = case IsDir of true -> {TraverseModule, do_dir_master_job_unsafe}; false -> {tree_traverse, do_master_job} end, UpdatedJob = Job#tree_traverse{file_ctx = FileCtx2}, archive_traverses_common:execute_unsafe_job( Module, Function, [MasterJobArgs], UpdatedJob, ErrorHandler). -spec execute_unsafe_job(module(), atom(), [term()], tree_traverse:job(), error_handler(T)) -> T. execute_unsafe_job(Module, JobFunctionName, Options, Job, ErrorHandler) -> try erlang:apply(Module, JobFunctionName, [Job | Options]) catch _Class:{badmatch, {error, Reason}}:Stacktrace -> ErrorHandler(Job, ?ERROR_POSIX(Reason), Stacktrace); _Class:Reason:Stacktrace -> ErrorHandler(Job, Reason, Stacktrace) end. -spec is_cancelling(archivisation_traverse_ctx:ctx() | archive:doc() | archive:id()) -> boolean() | {error, term()}. is_cancelling(ArchiveId) when is_binary(ArchiveId) -> case archive:get(ArchiveId) of {ok, #document{value = #archive{state = ?ARCHIVE_CANCELLING(_)}}} -> true; {ok, #document{}} -> false; {error, _} = Error -> Error end; is_cancelling(#document{key = ArchiveId}) -> is_cancelling(ArchiveId); is_cancelling(ArchiveCtx) -> case archivisation_traverse_ctx:get_archive_doc(ArchiveCtx) of undefined -> false; ArchiveDoc -> is_cancelling(ArchiveDoc) end. -spec update_children_count(tree_traverse:pool(), tree_traverse:id(), file_meta:uuid(), non_neg_integer()) -> ok. update_children_count(PoolName, TaskId, DirUuid, ChildrenCount) -> ?extract_ok(traverse_task:update_additional_data(traverse_task:get_ctx(), PoolName, TaskId, fun(AD) -> PrevCountMap = get_count_map(AD), UpdatedMap = case PrevCountMap of #{DirUuid := PrevCountBin} -> PrevCountMap#{ DirUuid => integer_to_binary(binary_to_integer(PrevCountBin) + ChildrenCount) }; _ -> PrevCountMap#{ DirUuid => integer_to_binary(ChildrenCount) } end, {ok, set_count_map(AD, UpdatedMap)} end )). -spec take_children_count(tree_traverse:pool(), tree_traverse:id(), file_meta:uuid()) -> non_neg_integer(). take_children_count(PoolName, TaskId, DirUuid) -> {ok, AdditionalData} = traverse_task:get_additional_data(PoolName, TaskId), ChildrenCount = maps:get(DirUuid, get_count_map(AdditionalData)), ok = ?extract_ok(traverse_task:update_additional_data(traverse_task:get_ctx(), PoolName, TaskId, fun(AD) -> {ok, set_count_map(AD, maps:remove(DirUuid, get_count_map(AD)))} end )), binary_to_integer(ChildrenCount). Internal functions -spec get_count_map(traverse:additional_data()) -> map(). get_count_map(AD) -> CountMapBin = maps:get(<<"children_count_map">>, AD, term_to_binary(#{})), binary_to_term(CountMapBin). -spec set_count_map(traverse:additional_data(), map()) -> traverse:additional_data(). set_count_map(AD, CountMap) -> AD#{<<"children_count_map">> => term_to_binary(CountMap)}.
86e72574d1211489e33fb8f8c611dec788bc485a8146ee2aa9032e6cdf32667d
kupl/LearnML
patch.ml
let rec ifequal n (l : 'a list) : bool = match l with [] -> false | hd :: tl -> hd = n || ifequal n tl let rec __s3 __s4 (__s5 : 'b list) : bool = match __s5 with | [] -> true | __s11 :: __s12 -> if __s4 = __s11 then false else __s3 __s4 __s12 let rec uniq (lst : 'c list) : 'd list = let rec l (lst : 'c list) (result : 'c list) : 'c list = match lst with | [] -> result | hd :: tl -> if __s3 hd result then l tl (result @ [ hd ]) else l tl result in l lst [] let (_ : int list) = uniq [ 5; 6; 5; 4 ]
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/uniq/sub10/patch.ml
ocaml
let rec ifequal n (l : 'a list) : bool = match l with [] -> false | hd :: tl -> hd = n || ifequal n tl let rec __s3 __s4 (__s5 : 'b list) : bool = match __s5 with | [] -> true | __s11 :: __s12 -> if __s4 = __s11 then false else __s3 __s4 __s12 let rec uniq (lst : 'c list) : 'd list = let rec l (lst : 'c list) (result : 'c list) : 'c list = match lst with | [] -> result | hd :: tl -> if __s3 hd result then l tl (result @ [ hd ]) else l tl result in l lst [] let (_ : int list) = uniq [ 5; 6; 5; 4 ]
b6aff231b63283892f747a297aa00a6dd73d9c851ac3fef513e7b624443ad693
zcaudate-me/lein-repack
source.clj
(ns leiningen.repack.manifest.source (:require [clojure.java.io :as io] [leiningen.repack.manifest.common :as manifest] [leiningen.repack.data.util :as util] [clojure.string :as string])) (defn child-dirs [path] (let [children (seq (.list path))] (->> children (filter (fn [chd] (.isDirectory (io/file path chd))))))) (defn split-path [path] (let [idx (.lastIndexOf path ".")] (util/relative-path-vector (.substring path 0 idx)))) (defn group-by-package [opts files] (let [lvl (or (:levels opts) 1)] (reduce (fn [i f] (let [rpath (util/relative-path (:root opts) f) v (split-path rpath) pkg (take lvl v) pkg (if (get (:standalone opts) (first pkg)) (first pkg) (string/join "." pkg))] (update-in i [pkg] (fnil #(conj % rpath) #{rpath} )))) {} files))) (defmethod manifest/build-filemap :clojure [project-dir cfg] (let [src-path (:path cfg) src-dir (io/file project-dir src-path) root-path (or (:root cfg) (let [ds (child-dirs src-dir)] (if (= (count ds) 1) (first ds) (throw (Exception. (str "More than one possible root: " ds)))))) root-dir (io/file src-dir root-path) distro (->> root-dir (file-seq) (filter (fn [f] (not (.isDirectory f)))) (group-by-package (assoc cfg :root root-dir)))] (manifest/create-filemap distro {:root project-dir :folder (str src-path "/" root-path) :pnil "default"})))
null
https://raw.githubusercontent.com/zcaudate-me/lein-repack/1eb542d66a77f55c4b5625783027c31fd2dddfe5/src/leiningen/repack/manifest/source.clj
clojure
(ns leiningen.repack.manifest.source (:require [clojure.java.io :as io] [leiningen.repack.manifest.common :as manifest] [leiningen.repack.data.util :as util] [clojure.string :as string])) (defn child-dirs [path] (let [children (seq (.list path))] (->> children (filter (fn [chd] (.isDirectory (io/file path chd))))))) (defn split-path [path] (let [idx (.lastIndexOf path ".")] (util/relative-path-vector (.substring path 0 idx)))) (defn group-by-package [opts files] (let [lvl (or (:levels opts) 1)] (reduce (fn [i f] (let [rpath (util/relative-path (:root opts) f) v (split-path rpath) pkg (take lvl v) pkg (if (get (:standalone opts) (first pkg)) (first pkg) (string/join "." pkg))] (update-in i [pkg] (fnil #(conj % rpath) #{rpath} )))) {} files))) (defmethod manifest/build-filemap :clojure [project-dir cfg] (let [src-path (:path cfg) src-dir (io/file project-dir src-path) root-path (or (:root cfg) (let [ds (child-dirs src-dir)] (if (= (count ds) 1) (first ds) (throw (Exception. (str "More than one possible root: " ds)))))) root-dir (io/file src-dir root-path) distro (->> root-dir (file-seq) (filter (fn [f] (not (.isDirectory f)))) (group-by-package (assoc cfg :root root-dir)))] (manifest/create-filemap distro {:root project-dir :folder (str src-path "/" root-path) :pnil "default"})))
031fff1b99d854ed61be837d7f207d808461816e7c5d56e2660836aa0f2c0914
noinia/hgeometry
StarShapedSpec.hs
{-# LANGUAGE OverloadedStrings #-} module Geometry.Polygon.StarShapedSpec where import Control.Lens import Control.Monad.Random.Strict(evalRand) import Data.Ext import Geometry import Ipe import Ipe.Color (named) import Data.Maybe import System.Random (mkStdGen) import Test.Hspec import Paths_hgeometry_test -------------------------------------------------------------------------------- spec :: Spec spec = do testCases "src/Geometry/Polygon/star_shaped.ipe" testCases :: FilePath -> Spec testCases fp = runIO (readInputFromFile =<< getDataFileName fp) >>= \case Left e -> it "reading star-shaped file" $ expectationFailure $ "Failed to read ipe file " ++ show e Right tcs -> specify "isStarShaped test" $ mapM_ toSpec tcs data TestCase r = TestCase { _polygon :: SimplePolygon () r , _isStar :: Bool } deriving (Show) toSpec :: TestCase Rational -> Expectation toSpec (TestCase poly b) = do -- correct result isJust mq `shouldBe` b -- it "returned point in polygon" $ (maybe True (`intersects` poly) mq) `shouldBe` True where mq = flip evalRand (mkStdGen 15) (isStarShaped poly) readInputFromFile :: FilePath -> IO (Either ConversionError [TestCase Rational]) readInputFromFile fp = fmap f <$> readSinglePageFile fp where -- star shaped polygons are blue f page = [ TestCase poly (isBlue att) | (poly :+ att) <- polies ] where polies = page^..content.traverse._withAttrs _IpePath _asSimplePolygon isBlue = maybe False (== named "blue") . lookupAttr SStroke testPoly : : testPoly = . . . map ext $ [ origin , Point2 10 10 , Point2 20 5 , Point2 30 2 , Point2 3 1 , Point2 31 0 ] testPoly2 : : testPoly2 = . . . map ext -- $ [ Point2 208 752 , Point2 304 688 , Point2 224 592 , Point2 48 736 -- ] -- -- main = readInputFromFile "tests/Geometry/pointInPolygon.ipe"
null
https://raw.githubusercontent.com/noinia/hgeometry/89cd3d3109ec68f877bf8e34dc34b6df337a4ec1/hgeometry-test/src/Geometry/Polygon/StarShapedSpec.hs
haskell
# LANGUAGE OverloadedStrings # ------------------------------------------------------------------------------ correct result it "returned point in polygon" $ star shaped polygons are blue $ [ Point2 208 752 ] -- main = readInputFromFile "tests/Geometry/pointInPolygon.ipe"
module Geometry.Polygon.StarShapedSpec where import Control.Lens import Control.Monad.Random.Strict(evalRand) import Data.Ext import Geometry import Ipe import Ipe.Color (named) import Data.Maybe import System.Random (mkStdGen) import Test.Hspec import Paths_hgeometry_test spec :: Spec spec = do testCases "src/Geometry/Polygon/star_shaped.ipe" testCases :: FilePath -> Spec testCases fp = runIO (readInputFromFile =<< getDataFileName fp) >>= \case Left e -> it "reading star-shaped file" $ expectationFailure $ "Failed to read ipe file " ++ show e Right tcs -> specify "isStarShaped test" $ mapM_ toSpec tcs data TestCase r = TestCase { _polygon :: SimplePolygon () r , _isStar :: Bool } deriving (Show) toSpec :: TestCase Rational -> Expectation toSpec (TestCase poly b) = do isJust mq `shouldBe` b (maybe True (`intersects` poly) mq) `shouldBe` True where mq = flip evalRand (mkStdGen 15) (isStarShaped poly) readInputFromFile :: FilePath -> IO (Either ConversionError [TestCase Rational]) readInputFromFile fp = fmap f <$> readSinglePageFile fp where f page = [ TestCase poly (isBlue att) | (poly :+ att) <- polies ] where polies = page^..content.traverse._withAttrs _IpePath _asSimplePolygon isBlue = maybe False (== named "blue") . lookupAttr SStroke testPoly : : testPoly = . . . map ext $ [ origin , Point2 10 10 , Point2 20 5 , Point2 30 2 , Point2 3 1 , Point2 31 0 ] testPoly2 : : testPoly2 = . . . map ext , Point2 304 688 , Point2 224 592 , Point2 48 736
3c2444dc083b216e3ac9fc366bf1924be40ead35e3aedc89c19184ab7f1b4e26
metaocaml/ber-metaocaml
stackoverflow.ml
TEST flags = " -w a " * setup - ocamlc.byte - build - env * * ocamlc.byte * * * run * * * * check - program - output * * * setup - ocamlopt.byte - build - env * * * ocamlopt.byte * * * * run * * * * * check - program - output * libunix * * script script = " sh $ { test_source_directory}/has - stackoverflow - detection.sh " * * * setup - ocamlopt.byte - build - env * * * * ocamlopt.byte * * * * * run * * * * * * check - program - output flags = "-w a" * setup-ocamlc.byte-build-env ** ocamlc.byte *** run **** check-program-output * libwin32unix ** setup-ocamlopt.byte-build-env *** ocamlopt.byte **** run ***** check-program-output * libunix ** script script = "sh ${test_source_directory}/has-stackoverflow-detection.sh" *** setup-ocamlopt.byte-build-env **** ocamlopt.byte ***** run ****** check-program-output *) let rec f x = if not (x = 0 || x = 10000 || x = 20000) then 1 + f (x + 1) else try 1 + f (x + 1) with Stack_overflow -> print_string "x = "; print_int x; print_newline(); raise Stack_overflow let _ = begin try ignore(f 0) with Stack_overflow -> print_string "Stack overflow caught"; print_newline() end ; (* GPR#1289 *) Printexc.record_backtrace true; begin try ignore(f 0) with Stack_overflow -> print_string "second Stack overflow caught"; print_newline() end
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/runtime-errors/stackoverflow.ml
ocaml
GPR#1289
TEST flags = " -w a " * setup - ocamlc.byte - build - env * * ocamlc.byte * * * run * * * * check - program - output * * * setup - ocamlopt.byte - build - env * * * ocamlopt.byte * * * * run * * * * * check - program - output * libunix * * script script = " sh $ { test_source_directory}/has - stackoverflow - detection.sh " * * * setup - ocamlopt.byte - build - env * * * * ocamlopt.byte * * * * * run * * * * * * check - program - output flags = "-w a" * setup-ocamlc.byte-build-env ** ocamlc.byte *** run **** check-program-output * libwin32unix ** setup-ocamlopt.byte-build-env *** ocamlopt.byte **** run ***** check-program-output * libunix ** script script = "sh ${test_source_directory}/has-stackoverflow-detection.sh" *** setup-ocamlopt.byte-build-env **** ocamlopt.byte ***** run ****** check-program-output *) let rec f x = if not (x = 0 || x = 10000 || x = 20000) then 1 + f (x + 1) else try 1 + f (x + 1) with Stack_overflow -> print_string "x = "; print_int x; print_newline(); raise Stack_overflow let _ = begin try ignore(f 0) with Stack_overflow -> print_string "Stack overflow caught"; print_newline() end ; Printexc.record_backtrace true; begin try ignore(f 0) with Stack_overflow -> print_string "second Stack overflow caught"; print_newline() end
792dc1c41e9d1dfdae4cf17c8704971705f6bbda17e177f85903f3200d5d86d9
Soyn/sicp
Ex2.83.rkt
#lang racket ;; Ex2.83 Created by Soyn . 26/7/15 ;; @Brief:Suppose you are designing a generic arithmetic system for dealing with the tower of types shown in figure 2.25 : integer , rational , real , complex . For each type ( except complex ) , design a procedure that raises objects of that type one level in the tower . Show how to install a generic raise operation that ;; will work for each type (except complex). ( define ( integer->rational integer) ( make-rational integer 1)) ( define ( rational->real rational) ( define ( integer->floating-point integer) ( * integer 1.0)) ( make-real ( / ( integer->floating-point ( number rational)) ( denom rational)))) ( define ( real->complex real) ( make-complex-from-real-img real 0)) ;; put them in coersion table ( put-coersion 'integer 'rational integer->rational) ( put-coersion 'rational 'real ration->real) ( put-coersion 'real 'complex real->complex) ( define ( raise number) ( define tower '( integer rational real complex)) ;define a types tower ( define ( try tower) ;go through the types-tower ( if ( < ( length tower) 2) ( error "Couldn't raise type" number) ( let ( ( current-type ( car tower)) ( next-types ( cdr tower)) ( next-type ( car next-types))) ( if ( eq? ( type-tag number) current-type) ( ( get-coersion current-type next-type) number) ( try next-types))))) ( try tower))
null
https://raw.githubusercontent.com/Soyn/sicp/d2aa6e3b053f6d4c8150ab1b033a18f61fca7e1b/CH2/CH2.5/Ex2.83.rkt
racket
Ex2.83 @Brief:Suppose you are designing a generic arithmetic system for dealing with the tower of types will work for each type (except complex). put them in coersion table define a types tower go through the types-tower
#lang racket Created by Soyn . 26/7/15 shown in figure 2.25 : integer , rational , real , complex . For each type ( except complex ) , design a procedure that raises objects of that type one level in the tower . Show how to install a generic raise operation that ( define ( integer->rational integer) ( make-rational integer 1)) ( define ( rational->real rational) ( define ( integer->floating-point integer) ( * integer 1.0)) ( make-real ( / ( integer->floating-point ( number rational)) ( denom rational)))) ( define ( real->complex real) ( make-complex-from-real-img real 0)) ( put-coersion 'integer 'rational integer->rational) ( put-coersion 'rational 'real ration->real) ( put-coersion 'real 'complex real->complex) ( define ( raise number) ( if ( < ( length tower) 2) ( error "Couldn't raise type" number) ( let ( ( current-type ( car tower)) ( next-types ( cdr tower)) ( next-type ( car next-types))) ( if ( eq? ( type-tag number) current-type) ( ( get-coersion current-type next-type) number) ( try next-types))))) ( try tower))
33f84a42d76ce77b1025505a7ebd68579063e805558534a7f03b6300efa7db8c
gonzojive/hunchentoot
session.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : HUNCHENTOOT ; Base : 10 -*- $ Header : /usr / local / cvsrep / hunchentoot / session.lisp , v 1.12 2008/02/13 16:02:18 edi Exp $ Copyright ( c ) 2004 - 2010 , Dr. . All rights reserved . ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :hunchentoot) (defgeneric session-db-lock (acceptor &key whole-db-p) (:documentation "A function which returns a lock that will be used to prevent concurrent access to sessions. The first argument will be the acceptor that handles the current request, the second argument is true if the whole \(current) session database is modified. If it is NIL, only one existing session in the database is modified. This function can return NIL which means that sessions or session databases will be modified without a lock held \(for example for single-threaded environments). The default is to always return a global lock \(ignoring the ACCEPTOR argument) for Lisps that support threads and NIL otherwise.")) (defmethod session-db-lock ((acceptor t) &key (whole-db-p t)) (declare (ignore whole-db-p)) *global-session-db-lock*) (defmacro with-session-lock-held ((lock) &body body) "This is like WITH-LOCK-HELD except that it will accept NIL as a \"lock\" and just execute BODY in this case." (with-unique-names (thunk) (with-rebinding (lock) `(flet ((,thunk () ,@body)) (cond (,lock (with-lock-held (,lock) (,thunk))) (t (,thunk))))))) (defgeneric session-db (acceptor) (:documentation "Returns the current session database which is an alist where each car is a session's ID and the cdr is the corresponding SESSION object itself. The default is to use a global list for all acceptors.")) (defmethod session-db ((acceptor t)) *session-db*) (defgeneric (setf session-db) (new-value acceptor) (:documentation "Modifies the current session database. See SESSION-DB.")) (defmethod (setf session-db) (new-value (acceptor t)) (setq *session-db* new-value)) (defgeneric next-session-id (acceptor) (:documentation "Returns the next sequential session ID, an integer, which should be unique per session. The default method uses a simple global counter and isn't guarded by a lock. For a high-performance production environment you might consider using a more robust implementation.")) (let ((session-id-counter 0)) (defmethod next-session-id ((acceptor t)) (incf session-id-counter))) (defclass session () ((session-id :initform (next-session-id (request-acceptor *request*)) :reader session-id :type integer :documentation "The unique ID \(an INTEGER) of the session.") (session-string :reader session-string :documentation "The session string encodes enough data to safely retrieve this session. It is sent to the browser as a cookie value or as a GET parameter.") (user-agent :initform (user-agent *request*) :reader session-user-agent :documentation "The incoming 'User-Agent' header that was sent when this session was created.") (remote-addr :initform (real-remote-addr *request*) :reader session-remote-addr :documentation "The remote IP address of the client when this session was started as returned by REAL-REMOTE-ADDR.") (session-start :initform (get-universal-time) :reader session-start :documentation "The time this session was started.") (last-click :initform (get-universal-time) :reader session-last-click :documentation "The last time this session was used.") (session-data :initarg :session-data :initform nil :reader session-data :documentation "Data associated with this session - see SESSION-VALUE.") (max-time :initarg :max-time :initform *session-max-time* :accessor session-max-time :type fixnum :documentation "The time \(in seconds) after which this session expires if it's not used.")) (:documentation "SESSION objects are automatically maintained by Hunchentoot. They should not be created explicitly with MAKE-INSTANCE but implicitly with START-SESSION and they should be treated as opaque objects. You can ignore Hunchentoot's SESSION objects altogether and implement your own sessions if you provide corresponding methods for SESSION-COOKIE-VALUE and SESSION-VERIFY.")) (defun encode-session-string (id user-agent remote-addr start) "Creates a uniquely encoded session string based on the values ID, USER-AGENT, REMOTE-ADDR, and START" (unless (boundp '*session-secret*) (hunchentoot-warn "Session secret is unbound. Using Lisp's RANDOM function to initialize it.") (reset-session-secret)) ;; *SESSION-SECRET* is used twice due to known theoretical vulnerabilities of MD5 encoding (md5-hex (concatenate 'string *session-secret* (md5-hex (format nil "~A~A~@[~A~]~@[~A~]~A" *session-secret* id (and *use-user-agent-for-sessions* user-agent) (and *use-remote-addr-for-sessions* remote-addr) start))))) (defun stringify-session (session) "Creates a string representing the SESSION object SESSION. See ENCODE-SESSION-STRING." (encode-session-string (session-id session) (session-user-agent session) (session-remote-addr session) (session-start session))) (defmethod initialize-instance :after ((session session) &rest init-args) "Set SESSION-STRING slot after the session has been initialized." (declare (ignore init-args)) (setf (slot-value session 'session-string) (stringify-session session))) (defun session-gc () "Removes sessions from the current session database which are too old - see SESSION-TOO-OLD-P." (with-session-lock-held ((session-db-lock *acceptor*)) (setf (session-db *acceptor*) (loop for id-session-pair in (session-db *acceptor*) for (nil . session) = id-session-pair when (session-too-old-p session) do (funcall *session-removal-hook* session) else collect id-session-pair))) (values)) (defun session-value (symbol &optional (session *session*)) "Returns the value associated with SYMBOL from the session object SESSION \(the default is the current session) if it exists." (when session (let ((found (assoc symbol (session-data session) :test #'eq))) (values (cdr found) found)))) (defsetf session-value (symbol &optional session) (new-value) "Sets the value associated with SYMBOL from the session object SESSION. If there is already a value associated with SYMBOL it will be replaced. Will automatically start a session if none was supplied and there's no session for the current request." (with-rebinding (symbol) (with-unique-names (place %session) `(let ((,%session (or ,session (start-session)))) (with-session-lock-held ((session-db-lock *acceptor* :whole-db-p nil)) (let* ((,place (assoc ,symbol (session-data ,%session) :test #'eq))) (cond (,place (setf (cdr ,place) ,new-value)) (t (push (cons ,symbol ,new-value) (slot-value ,%session 'session-data)) ,new-value)))))))) (defun delete-session-value (symbol &optional (session *session*)) "Removes the value associated with SYMBOL from SESSION if there is one." (when session (setf (slot-value session 'session-data) (delete symbol (session-data session) :key #'car :test #'eq))) (values)) (defgeneric session-cookie-value (session) (:documentation "Returns a string which can be used to safely restore the session SESSION if as session has already been established. This is used as the value stored in the session cookie or in the corresponding GET parameter and verified by SESSION-VERIFY. A default method is provided and there's no reason to change it unless you want to use your own session objects.")) (defmethod session-cookie-value ((session session)) (and session (format nil "~A:~A" (session-id session) (session-string session)))) (defgeneric session-cookie-name (acceptor) (:documentation "Returns the name \(a string) of the cookie \(or the GET parameter) which is used to store a session on the client side. The default is to use the string \"hunchentoot-session\", but you can specialize this function if you want another name.")) (defmethod session-cookie-name ((acceptor t)) "hunchentoot-session") (defgeneric session-created (acceptor new-session) (:documentation "This function is called whenever a new session has been created. There's a default method which might trigger a session GC based on the value of *SESSION-GC-FREQUENCY*. The return value is ignored.")) (let ((global-session-usage-counter 0)) (defmethod session-created ((acceptor t) (session t)) "Counts session usage globally and triggers session GC if necessary." (when (and *session-gc-frequency* (zerop (mod (incf global-session-usage-counter) *session-gc-frequency*))) (session-gc)))) (defun start-session () "Returns the current SESSION object. If there is no current session, creates one and updates the corresponding data structures. In this case the function will also send a session cookie to the browser." (let ((session (session *request*))) (when session (return-from start-session session)) (setf session (make-instance 'session) (session *request*) session) (with-session-lock-held ((session-db-lock *acceptor*)) (setf (session-db *acceptor*) (acons (session-id session) session (session-db *acceptor*)))) (set-cookie (session-cookie-name *acceptor*) :value (session-cookie-value session) :path "/") (session-created *acceptor* session) (setq *session* session))) (defun remove-session (session) "Completely removes the SESSION object SESSION from Hunchentoot's internal session database." (with-session-lock-held ((session-db-lock *acceptor*)) (funcall *session-removal-hook* session) (setf (session-db *acceptor*) (delete (session-id session) (session-db *acceptor*) :key #'car :test #'=))) (values)) (defun session-too-old-p (session) "Returns true if the SESSION object SESSION has not been active in the last \(SESSION-MAX-TIME SESSION) seconds." (< (+ (session-last-click session) (session-max-time session)) (get-universal-time))) (defun get-stored-session (id) "Returns the SESSION object corresponding to the number ID if the session has not expired. Will remove the session if it has expired but will not create a new one." (let ((session (cdr (assoc id (session-db *acceptor*) :test #'=)))) (when (and session (session-too-old-p session)) (when *reply* (log-message :info "Session with ID ~A too old" id)) (remove-session session) (setq session nil)) session)) (defgeneric session-verify (request) (:documentation "Tries to get a session identifier from the cookies \(or alternatively from the GET parameters) sent by the client (see SESSION-COOKIE-NAME and SESSION-COOKIE-VALUE). This identifier is then checked for validity against the REQUEST object REQUEST. On success the corresponding session object \(if not too old) is returned \(and updated). Otherwise NIL is returned. A default method is provided and you only need to write your own one if you want to maintain your own sessions.")) (defmethod session-verify ((request request)) (let ((session-identifier (or (cookie-in (session-cookie-name *acceptor*) request) (get-parameter (session-cookie-name *acceptor*) request)))) (unless (and session-identifier (stringp session-identifier) (plusp (length session-identifier))) (return-from session-verify nil)) (destructuring-bind (id-string session-string) (split ":" session-identifier :limit 2) (let* ((id (parse-integer id-string)) (session (get-stored-session id)) (user-agent (user-agent request)) (remote-addr (remote-addr request))) (cond ((and session (string= session-string (session-string session)) (string= session-string (encode-session-string id user-agent (real-remote-addr request) (session-start session)))) ;; the session key presented by the client is valid (setf (slot-value session 'last-click) (get-universal-time)) session) (session ;; the session ID pointed to an existing session, but the ;; session string did not match the expected session string (log-message :warning "Fake session identifier '~A' (User-Agent: '~A', IP: '~A')" session-identifier user-agent remote-addr) ;; remove the session to make sure that it can't be used ;; again; the original legitimate user will be required to ;; log in again (remove-session session) nil) (t ;; no session was found under the ID given, presumably ;; because it has expired. (log-message :info "No session for session identifier '~A' (User-Agent: '~A', IP: '~A')" session-identifier user-agent remote-addr) nil)))))) (defun reset-session-secret () "Sets *SESSION-SECRET* to a new random value. All old sessions will cease to be valid." (setq *session-secret* (create-random-string 10 36))) (defun reset-sessions (&optional (acceptor *acceptor*)) "Removes ALL stored sessions of ACCEPTOR." (with-session-lock-held ((session-db-lock acceptor)) (loop for (nil . session) in (session-db acceptor) do (funcall *session-removal-hook* session)) (setq *session-db* nil)) (values))
null
https://raw.githubusercontent.com/gonzojive/hunchentoot/36e3a81655be0eeb8084efd853dd3ac3e5afc91b/session.lisp
lisp
Syntax : COMMON - LISP ; Package : HUNCHENTOOT ; Base : 10 -*- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *SESSION-SECRET* is used twice due to known theoretical the session key presented by the client is valid the session ID pointed to an existing session, but the session string did not match the expected session string remove the session to make sure that it can't be used again; the original legitimate user will be required to log in again no session was found under the ID given, presumably because it has expired.
$ Header : /usr / local / cvsrep / hunchentoot / session.lisp , v 1.12 2008/02/13 16:02:18 edi Exp $ Copyright ( c ) 2004 - 2010 , Dr. . All rights reserved . DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , (in-package :hunchentoot) (defgeneric session-db-lock (acceptor &key whole-db-p) (:documentation "A function which returns a lock that will be used to prevent concurrent access to sessions. The first argument will be the acceptor that handles the current request, the second argument is true if the whole \(current) session database is modified. If it is NIL, only one existing session in the database is modified. This function can return NIL which means that sessions or session databases will be modified without a lock held \(for example for single-threaded environments). The default is to always return a global lock \(ignoring the ACCEPTOR argument) for Lisps that support threads and NIL otherwise.")) (defmethod session-db-lock ((acceptor t) &key (whole-db-p t)) (declare (ignore whole-db-p)) *global-session-db-lock*) (defmacro with-session-lock-held ((lock) &body body) "This is like WITH-LOCK-HELD except that it will accept NIL as a \"lock\" and just execute BODY in this case." (with-unique-names (thunk) (with-rebinding (lock) `(flet ((,thunk () ,@body)) (cond (,lock (with-lock-held (,lock) (,thunk))) (t (,thunk))))))) (defgeneric session-db (acceptor) (:documentation "Returns the current session database which is an alist where each car is a session's ID and the cdr is the corresponding SESSION object itself. The default is to use a global list for all acceptors.")) (defmethod session-db ((acceptor t)) *session-db*) (defgeneric (setf session-db) (new-value acceptor) (:documentation "Modifies the current session database. See SESSION-DB.")) (defmethod (setf session-db) (new-value (acceptor t)) (setq *session-db* new-value)) (defgeneric next-session-id (acceptor) (:documentation "Returns the next sequential session ID, an integer, which should be unique per session. The default method uses a simple global counter and isn't guarded by a lock. For a high-performance production environment you might consider using a more robust implementation.")) (let ((session-id-counter 0)) (defmethod next-session-id ((acceptor t)) (incf session-id-counter))) (defclass session () ((session-id :initform (next-session-id (request-acceptor *request*)) :reader session-id :type integer :documentation "The unique ID \(an INTEGER) of the session.") (session-string :reader session-string :documentation "The session string encodes enough data to safely retrieve this session. It is sent to the browser as a cookie value or as a GET parameter.") (user-agent :initform (user-agent *request*) :reader session-user-agent :documentation "The incoming 'User-Agent' header that was sent when this session was created.") (remote-addr :initform (real-remote-addr *request*) :reader session-remote-addr :documentation "The remote IP address of the client when this session was started as returned by REAL-REMOTE-ADDR.") (session-start :initform (get-universal-time) :reader session-start :documentation "The time this session was started.") (last-click :initform (get-universal-time) :reader session-last-click :documentation "The last time this session was used.") (session-data :initarg :session-data :initform nil :reader session-data :documentation "Data associated with this session - see SESSION-VALUE.") (max-time :initarg :max-time :initform *session-max-time* :accessor session-max-time :type fixnum :documentation "The time \(in seconds) after which this session expires if it's not used.")) (:documentation "SESSION objects are automatically maintained by Hunchentoot. They should not be created explicitly with MAKE-INSTANCE but implicitly with START-SESSION and they should be treated as opaque objects. You can ignore Hunchentoot's SESSION objects altogether and implement your own sessions if you provide corresponding methods for SESSION-COOKIE-VALUE and SESSION-VERIFY.")) (defun encode-session-string (id user-agent remote-addr start) "Creates a uniquely encoded session string based on the values ID, USER-AGENT, REMOTE-ADDR, and START" (unless (boundp '*session-secret*) (hunchentoot-warn "Session secret is unbound. Using Lisp's RANDOM function to initialize it.") (reset-session-secret)) vulnerabilities of MD5 encoding (md5-hex (concatenate 'string *session-secret* (md5-hex (format nil "~A~A~@[~A~]~@[~A~]~A" *session-secret* id (and *use-user-agent-for-sessions* user-agent) (and *use-remote-addr-for-sessions* remote-addr) start))))) (defun stringify-session (session) "Creates a string representing the SESSION object SESSION. See ENCODE-SESSION-STRING." (encode-session-string (session-id session) (session-user-agent session) (session-remote-addr session) (session-start session))) (defmethod initialize-instance :after ((session session) &rest init-args) "Set SESSION-STRING slot after the session has been initialized." (declare (ignore init-args)) (setf (slot-value session 'session-string) (stringify-session session))) (defun session-gc () "Removes sessions from the current session database which are too old - see SESSION-TOO-OLD-P." (with-session-lock-held ((session-db-lock *acceptor*)) (setf (session-db *acceptor*) (loop for id-session-pair in (session-db *acceptor*) for (nil . session) = id-session-pair when (session-too-old-p session) do (funcall *session-removal-hook* session) else collect id-session-pair))) (values)) (defun session-value (symbol &optional (session *session*)) "Returns the value associated with SYMBOL from the session object SESSION \(the default is the current session) if it exists." (when session (let ((found (assoc symbol (session-data session) :test #'eq))) (values (cdr found) found)))) (defsetf session-value (symbol &optional session) (new-value) "Sets the value associated with SYMBOL from the session object SESSION. If there is already a value associated with SYMBOL it will be replaced. Will automatically start a session if none was supplied and there's no session for the current request." (with-rebinding (symbol) (with-unique-names (place %session) `(let ((,%session (or ,session (start-session)))) (with-session-lock-held ((session-db-lock *acceptor* :whole-db-p nil)) (let* ((,place (assoc ,symbol (session-data ,%session) :test #'eq))) (cond (,place (setf (cdr ,place) ,new-value)) (t (push (cons ,symbol ,new-value) (slot-value ,%session 'session-data)) ,new-value)))))))) (defun delete-session-value (symbol &optional (session *session*)) "Removes the value associated with SYMBOL from SESSION if there is one." (when session (setf (slot-value session 'session-data) (delete symbol (session-data session) :key #'car :test #'eq))) (values)) (defgeneric session-cookie-value (session) (:documentation "Returns a string which can be used to safely restore the session SESSION if as session has already been established. This is used as the value stored in the session cookie or in the corresponding GET parameter and verified by SESSION-VERIFY. A default method is provided and there's no reason to change it unless you want to use your own session objects.")) (defmethod session-cookie-value ((session session)) (and session (format nil "~A:~A" (session-id session) (session-string session)))) (defgeneric session-cookie-name (acceptor) (:documentation "Returns the name \(a string) of the cookie \(or the GET parameter) which is used to store a session on the client side. The default is to use the string \"hunchentoot-session\", but you can specialize this function if you want another name.")) (defmethod session-cookie-name ((acceptor t)) "hunchentoot-session") (defgeneric session-created (acceptor new-session) (:documentation "This function is called whenever a new session has been created. There's a default method which might trigger a session GC based on the value of *SESSION-GC-FREQUENCY*. The return value is ignored.")) (let ((global-session-usage-counter 0)) (defmethod session-created ((acceptor t) (session t)) "Counts session usage globally and triggers session GC if necessary." (when (and *session-gc-frequency* (zerop (mod (incf global-session-usage-counter) *session-gc-frequency*))) (session-gc)))) (defun start-session () "Returns the current SESSION object. If there is no current session, creates one and updates the corresponding data structures. In this case the function will also send a session cookie to the browser." (let ((session (session *request*))) (when session (return-from start-session session)) (setf session (make-instance 'session) (session *request*) session) (with-session-lock-held ((session-db-lock *acceptor*)) (setf (session-db *acceptor*) (acons (session-id session) session (session-db *acceptor*)))) (set-cookie (session-cookie-name *acceptor*) :value (session-cookie-value session) :path "/") (session-created *acceptor* session) (setq *session* session))) (defun remove-session (session) "Completely removes the SESSION object SESSION from Hunchentoot's internal session database." (with-session-lock-held ((session-db-lock *acceptor*)) (funcall *session-removal-hook* session) (setf (session-db *acceptor*) (delete (session-id session) (session-db *acceptor*) :key #'car :test #'=))) (values)) (defun session-too-old-p (session) "Returns true if the SESSION object SESSION has not been active in the last \(SESSION-MAX-TIME SESSION) seconds." (< (+ (session-last-click session) (session-max-time session)) (get-universal-time))) (defun get-stored-session (id) "Returns the SESSION object corresponding to the number ID if the session has not expired. Will remove the session if it has expired but will not create a new one." (let ((session (cdr (assoc id (session-db *acceptor*) :test #'=)))) (when (and session (session-too-old-p session)) (when *reply* (log-message :info "Session with ID ~A too old" id)) (remove-session session) (setq session nil)) session)) (defgeneric session-verify (request) (:documentation "Tries to get a session identifier from the cookies \(or alternatively from the GET parameters) sent by the client (see SESSION-COOKIE-NAME and SESSION-COOKIE-VALUE). This identifier is then checked for validity against the REQUEST object REQUEST. On success the corresponding session object \(if not too old) is returned \(and updated). Otherwise NIL is returned. A default method is provided and you only need to write your own one if you want to maintain your own sessions.")) (defmethod session-verify ((request request)) (let ((session-identifier (or (cookie-in (session-cookie-name *acceptor*) request) (get-parameter (session-cookie-name *acceptor*) request)))) (unless (and session-identifier (stringp session-identifier) (plusp (length session-identifier))) (return-from session-verify nil)) (destructuring-bind (id-string session-string) (split ":" session-identifier :limit 2) (let* ((id (parse-integer id-string)) (session (get-stored-session id)) (user-agent (user-agent request)) (remote-addr (remote-addr request))) (cond ((and session (string= session-string (session-string session)) (string= session-string (encode-session-string id user-agent (real-remote-addr request) (session-start session)))) (setf (slot-value session 'last-click) (get-universal-time)) session) (session (log-message :warning "Fake session identifier '~A' (User-Agent: '~A', IP: '~A')" session-identifier user-agent remote-addr) (remove-session session) nil) (t (log-message :info "No session for session identifier '~A' (User-Agent: '~A', IP: '~A')" session-identifier user-agent remote-addr) nil)))))) (defun reset-session-secret () "Sets *SESSION-SECRET* to a new random value. All old sessions will cease to be valid." (setq *session-secret* (create-random-string 10 36))) (defun reset-sessions (&optional (acceptor *acceptor*)) "Removes ALL stored sessions of ACCEPTOR." (with-session-lock-held ((session-db-lock acceptor)) (loop for (nil . session) in (session-db acceptor) do (funcall *session-removal-hook* session)) (setq *session-db* nil)) (values))
6d90fe2448953946a8b957cd3526a9d187dde2f6116ad8052d3e4b477f9cf963
lemmaandrew/CodingBatHaskell
frontPiece.hs
From Given an int array of any length , return a new array of its first 2 elements . If the array is smaller than length 2 , use whatever elements are present . Given an int array of any length, return a new array of its first 2 elements. If the array is smaller than length 2, use whatever elements are present. -} import Test.Hspec ( hspec, describe, it, shouldBe ) frontPiece :: [Int] -> [Int] frontPiece nums = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "[1,2]" $ frontPiece [1,2,3] `shouldBe` [1,2] it "[1,2]" $ frontPiece [1,2] `shouldBe` [1,2] it "[1]" $ frontPiece [1] `shouldBe` [1] it "[]" $ frontPiece [] `shouldBe` [] it "[6,5]" $ frontPiece [6,5,0] `shouldBe` [6,5] it "[6,5]" $ frontPiece [6,5] `shouldBe` [6,5] it "[3,1]" $ frontPiece [3,1,4,1,5] `shouldBe` [3,1] it "[6]" $ frontPiece [6] `shouldBe` [6]
null
https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/Array-1/frontPiece.hs
haskell
From Given an int array of any length , return a new array of its first 2 elements . If the array is smaller than length 2 , use whatever elements are present . Given an int array of any length, return a new array of its first 2 elements. If the array is smaller than length 2, use whatever elements are present. -} import Test.Hspec ( hspec, describe, it, shouldBe ) frontPiece :: [Int] -> [Int] frontPiece nums = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "[1,2]" $ frontPiece [1,2,3] `shouldBe` [1,2] it "[1,2]" $ frontPiece [1,2] `shouldBe` [1,2] it "[1]" $ frontPiece [1] `shouldBe` [1] it "[]" $ frontPiece [] `shouldBe` [] it "[6,5]" $ frontPiece [6,5,0] `shouldBe` [6,5] it "[6,5]" $ frontPiece [6,5] `shouldBe` [6,5] it "[3,1]" $ frontPiece [3,1,4,1,5] `shouldBe` [3,1] it "[6]" $ frontPiece [6] `shouldBe` [6]
e9212ff3dc8163222db27b04aa79e5ada01a962cba8a11a24fd74fa43789cc4f
yogthos/yuggoth
setup.clj
(ns yuggoth.routes.setup (:require [compojure.core :refer [defroutes GET POST]] [clojure.set :refer [rename-keys]] [noir.util.crypt :as crypt] [noir.response :refer [redirect]] [yuggoth.config :refer [configured? text]] [yuggoth.layout :as layout] [yuggoth.db.core :refer [get-admin set-admin!]] [yuggoth.db.schema :as schema] [yuggoth.config :refer [db save!]])) (defn error [id] (throw (Exception. (text id)))) (defn check-admin [{:keys [admin title admin-pass admin-pass-repeat]}] (cond (not= admin-pass admin-pass-repeat) (error :pass-mismatch) (empty? admin) (error :admin-required) (empty? title) (error :blog-title-required) :else true)) (defn create-admin [admin] (-> admin (dissoc :admin-pass-repeat) (rename-keys {:admin :handle :admin-pass :pass}) (update-in [:pass] crypt/encrypt) (set-admin!))) (defn init-blog! [config] (try (check-admin config) (save! (-> config (dissoc :admin :admin-pass :admin-pass-repeat) (assoc :initialized true) (update-in [:locale] keyword) (update-in [:port] #(Integer/parseInt %)) (update-in [:ssl] #(Boolean/parseBoolean %)) (update-in [:ssl-port] #(Integer/parseInt %)))) (schema/reset-blog @db) (create-admin (select-keys config [:admin :title :admin-pass :admin-pass-repeat])) (reset! configured? true) (redirect "/") (catch Exception ex (.printStackTrace ex) (layout/render "app.html" {:config config :error (.getMessage (if (instance? java.sql.BatchUpdateException ex) (.getNextException ex) ex))})))) (defroutes setup-routes (POST "/blog-setup" {:keys [params]} (if @configured? (redirect "/") (init-blog! params))))
null
https://raw.githubusercontent.com/yogthos/yuggoth/901541c5809fb1e77c249f26a3aa5df894c88242/src/yuggoth/routes/setup.clj
clojure
(ns yuggoth.routes.setup (:require [compojure.core :refer [defroutes GET POST]] [clojure.set :refer [rename-keys]] [noir.util.crypt :as crypt] [noir.response :refer [redirect]] [yuggoth.config :refer [configured? text]] [yuggoth.layout :as layout] [yuggoth.db.core :refer [get-admin set-admin!]] [yuggoth.db.schema :as schema] [yuggoth.config :refer [db save!]])) (defn error [id] (throw (Exception. (text id)))) (defn check-admin [{:keys [admin title admin-pass admin-pass-repeat]}] (cond (not= admin-pass admin-pass-repeat) (error :pass-mismatch) (empty? admin) (error :admin-required) (empty? title) (error :blog-title-required) :else true)) (defn create-admin [admin] (-> admin (dissoc :admin-pass-repeat) (rename-keys {:admin :handle :admin-pass :pass}) (update-in [:pass] crypt/encrypt) (set-admin!))) (defn init-blog! [config] (try (check-admin config) (save! (-> config (dissoc :admin :admin-pass :admin-pass-repeat) (assoc :initialized true) (update-in [:locale] keyword) (update-in [:port] #(Integer/parseInt %)) (update-in [:ssl] #(Boolean/parseBoolean %)) (update-in [:ssl-port] #(Integer/parseInt %)))) (schema/reset-blog @db) (create-admin (select-keys config [:admin :title :admin-pass :admin-pass-repeat])) (reset! configured? true) (redirect "/") (catch Exception ex (.printStackTrace ex) (layout/render "app.html" {:config config :error (.getMessage (if (instance? java.sql.BatchUpdateException ex) (.getNextException ex) ex))})))) (defroutes setup-routes (POST "/blog-setup" {:keys [params]} (if @configured? (redirect "/") (init-blog! params))))
efef3397fa35228ac35654be999d339b605397e546c40e6abfe664bb48a3a0e7
zhuangxm/clj-rpc
wire_format.clj
;; Different wire formats support. (ns clj-rpc.wire-format (:require [cheshire.core :as json] [clojure.edn :as edn])) (defmulti serialization "Returns a pair of encoder, decoder function." (partial keyword "clj-rpc.wire-format")) (defmethod serialization ::clj [_] [pr-str edn/read-string]) (defmethod serialization ::json [_] [json/generate-string json/parse-string])
null
https://raw.githubusercontent.com/zhuangxm/clj-rpc/73a2f66b5ed0cce865d102acb49ba229203343ad/src/clj_rpc/wire_format.clj
clojure
Different wire formats support.
(ns clj-rpc.wire-format (:require [cheshire.core :as json] [clojure.edn :as edn])) (defmulti serialization "Returns a pair of encoder, decoder function." (partial keyword "clj-rpc.wire-format")) (defmethod serialization ::clj [_] [pr-str edn/read-string]) (defmethod serialization ::json [_] [json/generate-string json/parse-string])
bab65354c3bc40a71af1f85566f7e0c6474d6748dbeb31e91daff5ca453c8650
scalaris-team/scalaris
db_bitcask_merge_extension.erl
2013 - 2016 Zuse Institute Berlin , Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @author < > @doc Triggers periodically a merge operation for a Bitcask DB . %% @end %% @version $Id$ -module(db_bitcask_merge_extension). -author(''). -include("scalaris.hrl"). -define(TRACE(X), ?TRACE(X, [])). %-define(TRACE(X,Y), io:format(X,Y)). -define(TRACE(X,Y), ok). -define(MERGE_INTERVAL, config:read(bitcask_merge_interval)). -define(MERGE_OFFSET, config:read(bitcask_merge_offset)). -export([check_config/0]). -export([init/1, init/2]). -export([on/2]). %% This component uses a trigger mechanism to become active from time %% to time. It is a dht_node_extension and therefore embedded in the %% dht_node process. -spec init(_Options::any()) -> ok. init(_Options) -> ignore dht_node_extension init since this module needs a bitcask DB reference . calls init/2 upon opening % a bitcask store. ok. %% @doc Sends a periodic trigger to itself -spec init(BitcaskHandle::reference(), Dir::string()) -> ok. init(BitcaskHandle, Dir) -> ?TRACE("bitcask_merge: init for DB directory ~p~n", [Dir]), send_trigger(merge_offset, BitcaskHandle, Dir, ?MERGE_OFFSET), ok. -spec on(comm:message(), State::dht_node_state:state()) -> dht_node_state:state(). on({merge_offset, BitcaskHandle, Dir}, State) -> %% calculate initial offset to prevent that all nodes are merging at the %% same time. mgmt_server:node_list(), Nodes = receive ?SCALARIS_RECV( {get_list_response, List}, lists:usort([Pid || {_, _, Pid} <- List]) ) after 2000 -> [self()] end, Slot = get_idx(self(), Nodes), SlotLength = ?MERGE_INTERVAL / length(Nodes), Offset = trunc(SlotLength * Slot), ?TRACE("PIDs: ~p~n~nSlot choosen: ~p~n", [Nodes, Slot]), send_trigger(merge_trigger, BitcaskHandle, Dir, Offset), State; on({merge_trigger, BitcaskHandle, Dir}, State) -> %% merges if necessary _ = case erlang:get(BitcaskHandle) of undefined -> %% handle was closed, no more merge operations %% possible. ?TRACE("bitcask_merge: Bitcask handle closed for ~p~n", [Dir]), ok; _ -> bitcask : needs_merge/1 cleans up open file descriptors left %% over from the last successful merge. Deleted files stay %% open until then... _ = case bitcask:needs_merge(BitcaskHandle) of {true, Files} -> ?TRACE("bitcask_merge: starting merge in dir ~p~n", [Dir]), bitcask_merge_worker:merge(Dir, [], Files); false -> ok end, send_trigger(merge_trigger, BitcaskHandle, Dir, ?MERGE_INTERVAL) end, State. %% @doc Sends a trigger message to itself -spec send_trigger(Message::atom(), BitcaskHandle::reference(), Dir::string(), Delay::integer()) -> ok. send_trigger(Message, BitcaskHandle, Dir, Delay) -> msg_delay:send_trigger(Delay, dht_node_extensions:wrap(?MODULE, {Message, BitcaskHandle, Dir})), ok. %% @doc Helper to find the index of an element in a list. %% Returns length(List)+1 if List does not contain E. -spec get_idx(E::any(), List::any()) -> integer(). get_idx(E, List) -> get_idx(E, List, 1). -spec get_idx(E::any(), List::any(), Idx::integer()) -> integer(). get_idx(_, [], Idx) -> Idx; get_idx(E, [E | _], Idx) -> Idx; get_idx(E, [_ | T], Idx) -> get_idx(E, T, Idx+1). %% @doc Checks whether config parameters exist and are valid. -spec check_config() -> boolean(). check_config() -> config:cfg_is_integer(bitcask_merge_interval) and config:cfg_is_integer(bitcask_merge_offset).
null
https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/src/db_bitcask_merge_extension.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @end @version $Id$ -define(TRACE(X,Y), io:format(X,Y)). This component uses a trigger mechanism to become active from time to time. It is a dht_node_extension and therefore embedded in the dht_node process. a bitcask store. @doc Sends a periodic trigger to itself calculate initial offset to prevent that all nodes are merging at the same time. merges if necessary handle was closed, no more merge operations possible. over from the last successful merge. Deleted files stay open until then... @doc Sends a trigger message to itself @doc Helper to find the index of an element in a list. Returns length(List)+1 if List does not contain E. @doc Checks whether config parameters exist and are valid.
2013 - 2016 Zuse Institute Berlin , Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > @doc Triggers periodically a merge operation for a Bitcask DB . -module(db_bitcask_merge_extension). -author(''). -include("scalaris.hrl"). -define(TRACE(X), ?TRACE(X, [])). -define(TRACE(X,Y), ok). -define(MERGE_INTERVAL, config:read(bitcask_merge_interval)). -define(MERGE_OFFSET, config:read(bitcask_merge_offset)). -export([check_config/0]). -export([init/1, init/2]). -export([on/2]). -spec init(_Options::any()) -> ok. init(_Options) -> ignore dht_node_extension init since this module needs a bitcask DB reference . calls init/2 upon opening ok. -spec init(BitcaskHandle::reference(), Dir::string()) -> ok. init(BitcaskHandle, Dir) -> ?TRACE("bitcask_merge: init for DB directory ~p~n", [Dir]), send_trigger(merge_offset, BitcaskHandle, Dir, ?MERGE_OFFSET), ok. -spec on(comm:message(), State::dht_node_state:state()) -> dht_node_state:state(). on({merge_offset, BitcaskHandle, Dir}, State) -> mgmt_server:node_list(), Nodes = receive ?SCALARIS_RECV( {get_list_response, List}, lists:usort([Pid || {_, _, Pid} <- List]) ) after 2000 -> [self()] end, Slot = get_idx(self(), Nodes), SlotLength = ?MERGE_INTERVAL / length(Nodes), Offset = trunc(SlotLength * Slot), ?TRACE("PIDs: ~p~n~nSlot choosen: ~p~n", [Nodes, Slot]), send_trigger(merge_trigger, BitcaskHandle, Dir, Offset), State; on({merge_trigger, BitcaskHandle, Dir}, State) -> _ = case erlang:get(BitcaskHandle) of undefined -> ?TRACE("bitcask_merge: Bitcask handle closed for ~p~n", [Dir]), ok; _ -> bitcask : needs_merge/1 cleans up open file descriptors left _ = case bitcask:needs_merge(BitcaskHandle) of {true, Files} -> ?TRACE("bitcask_merge: starting merge in dir ~p~n", [Dir]), bitcask_merge_worker:merge(Dir, [], Files); false -> ok end, send_trigger(merge_trigger, BitcaskHandle, Dir, ?MERGE_INTERVAL) end, State. -spec send_trigger(Message::atom(), BitcaskHandle::reference(), Dir::string(), Delay::integer()) -> ok. send_trigger(Message, BitcaskHandle, Dir, Delay) -> msg_delay:send_trigger(Delay, dht_node_extensions:wrap(?MODULE, {Message, BitcaskHandle, Dir})), ok. -spec get_idx(E::any(), List::any()) -> integer(). get_idx(E, List) -> get_idx(E, List, 1). -spec get_idx(E::any(), List::any(), Idx::integer()) -> integer(). get_idx(_, [], Idx) -> Idx; get_idx(E, [E | _], Idx) -> Idx; get_idx(E, [_ | T], Idx) -> get_idx(E, T, Idx+1). -spec check_config() -> boolean(). check_config() -> config:cfg_is_integer(bitcask_merge_interval) and config:cfg_is_integer(bitcask_merge_offset).
2e4c1b4b5d4142fd96ff2d7bdc46bd8d95162087c94ca67b8552433664069e68
valderman/haste-compiler
UTC.hs
{-# OPTIONS -fno-warn-unused-imports #-} # LANGUAGE Trustworthy # #include "HsConfigure.h" -- #hide module Data.Time.Clock.UTC ( -- * UTC -- | UTC is time as measured by a clock, corrected to keep pace with the earth by adding or removing -- occasional seconds, known as \"leap seconds\". These corrections are not predictable and are announced with six month 's notice . -- No table of these corrections is provided, as any program compiled with it would become out of date in six months . -- If you do n't care about leap seconds , use UTCTime and NominalDiffTime for your clock calculations , -- and you'll be fine. UTCTime(..),NominalDiffTime ) where import Control.DeepSeq import Data.Time.Calendar.Days import Data.Time.Clock.Scale import Data.Fixed import Data.Typeable #if LANGUAGE_Rank2Types import Data.Data #endif -- | This is the simplest representation of UTC. It consists of the day number , and a time offset from midnight . Note that if a day has a leap second added to it , it will have 86401 seconds . data UTCTime = UTCTime { -- | the day utctDay :: Day, | the time from midnight , 0 < = t < ( because of leap - seconds ) utctDayTime :: DiffTime } #if LANGUAGE_DeriveDataTypeable #if LANGUAGE_Rank2Types #if HAS_DataPico deriving (Data, Typeable) #endif #endif #endif instance NFData UTCTime where rnf (UTCTime d t) = d `deepseq` t `deepseq` () instance Eq UTCTime where (UTCTime da ta) == (UTCTime db tb) = (da == db) && (ta == tb) instance Ord UTCTime where compare (UTCTime da ta) (UTCTime db tb) = case (compare da db) of EQ -> compare ta tb cmp -> cmp -- | This is a length of time, as measured by UTC. -- Conversion functions will treat it as seconds. It has a precision of 10 ^ -12 s. -- It ignores leap-seconds, so it's not necessarily a fixed amount of clock time. For instance , 23:00 UTC + 2 hours of NominalDiffTime = 01:00 UTC ( + 1 day ) , -- regardless of whether a leap-second intervened. newtype NominalDiffTime = MkNominalDiffTime Pico deriving (Eq,Ord #if LANGUAGE_DeriveDataTypeable #if LANGUAGE_Rank2Types #if HAS_DataPico ,Data, Typeable #endif #endif #endif ) -- necessary because H98 doesn't have "cunning newtype" derivation instance NFData NominalDiffTime where -- FIXME: Data.Fixed had no NFData instances yet at time of writing rnf ndt = seq ndt () instance Enum NominalDiffTime where succ (MkNominalDiffTime a) = MkNominalDiffTime (succ a) pred (MkNominalDiffTime a) = MkNominalDiffTime (pred a) toEnum = MkNominalDiffTime . toEnum fromEnum (MkNominalDiffTime a) = fromEnum a enumFrom (MkNominalDiffTime a) = fmap MkNominalDiffTime (enumFrom a) enumFromThen (MkNominalDiffTime a) (MkNominalDiffTime b) = fmap MkNominalDiffTime (enumFromThen a b) enumFromTo (MkNominalDiffTime a) (MkNominalDiffTime b) = fmap MkNominalDiffTime (enumFromTo a b) enumFromThenTo (MkNominalDiffTime a) (MkNominalDiffTime b) (MkNominalDiffTime c) = fmap MkNominalDiffTime (enumFromThenTo a b c) instance Show NominalDiffTime where show (MkNominalDiffTime t) = (showFixed True t) ++ "s" -- necessary because H98 doesn't have "cunning newtype" derivation instance Num NominalDiffTime where (MkNominalDiffTime a) + (MkNominalDiffTime b) = MkNominalDiffTime (a + b) (MkNominalDiffTime a) - (MkNominalDiffTime b) = MkNominalDiffTime (a - b) (MkNominalDiffTime a) * (MkNominalDiffTime b) = MkNominalDiffTime (a * b) negate (MkNominalDiffTime a) = MkNominalDiffTime (negate a) abs (MkNominalDiffTime a) = MkNominalDiffTime (abs a) signum (MkNominalDiffTime a) = MkNominalDiffTime (signum a) fromInteger i = MkNominalDiffTime (fromInteger i) -- necessary because H98 doesn't have "cunning newtype" derivation instance Real NominalDiffTime where toRational (MkNominalDiffTime a) = toRational a -- necessary because H98 doesn't have "cunning newtype" derivation instance Fractional NominalDiffTime where (MkNominalDiffTime a) / (MkNominalDiffTime b) = MkNominalDiffTime (a / b) recip (MkNominalDiffTime a) = MkNominalDiffTime (recip a) fromRational r = MkNominalDiffTime (fromRational r) -- necessary because H98 doesn't have "cunning newtype" derivation instance RealFrac NominalDiffTime where properFraction (MkNominalDiffTime a) = (i,MkNominalDiffTime f) where (i,f) = properFraction a truncate (MkNominalDiffTime a) = truncate a round (MkNominalDiffTime a) = round a ceiling (MkNominalDiffTime a) = ceiling a floor (MkNominalDiffTime a) = floor a # RULES " realToFrac / DiffTime->NominalDiffTime " realToFrac = \ dt - > MkNominalDiffTime ( realToFrac dt ) " realToFrac / NominalDiffTime->DiffTime " realToFrac = \ ( MkNominalDiffTime ps ) - > realToFrac realToFrac / NominalDiffTime->Pico " realToFrac = \ ( MkNominalDiffTime ps ) - > ps " realToFrac / Pico->NominalDiffTime " realToFrac = MkNominalDiffTime # "realToFrac/DiffTime->NominalDiffTime" realToFrac = \ dt -> MkNominalDiffTime (realToFrac dt) "realToFrac/NominalDiffTime->DiffTime" realToFrac = \ (MkNominalDiffTime ps) -> realToFrac ps "realToFrac/NominalDiffTime->Pico" realToFrac = \ (MkNominalDiffTime ps) -> ps "realToFrac/Pico->NominalDiffTime" realToFrac = MkNominalDiffTime #-}
null
https://raw.githubusercontent.com/valderman/haste-compiler/47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8/libraries/time/lib/Data/Time/Clock/UTC.hs
haskell
# OPTIONS -fno-warn-unused-imports # #hide * UTC | UTC is time as measured by a clock, corrected to keep pace with the earth by adding or removing occasional seconds, known as \"leap seconds\". No table of these corrections is provided, as any program compiled with it would become and you'll be fine. | This is the simplest representation of UTC. | the day | This is a length of time, as measured by UTC. Conversion functions will treat it as seconds. It ignores leap-seconds, so it's not necessarily a fixed amount of clock time. regardless of whether a leap-second intervened. necessary because H98 doesn't have "cunning newtype" derivation FIXME: Data.Fixed had no NFData instances yet at time of writing necessary because H98 doesn't have "cunning newtype" derivation necessary because H98 doesn't have "cunning newtype" derivation necessary because H98 doesn't have "cunning newtype" derivation necessary because H98 doesn't have "cunning newtype" derivation
# LANGUAGE Trustworthy # #include "HsConfigure.h" module Data.Time.Clock.UTC ( These corrections are not predictable and are announced with six month 's notice . out of date in six months . If you do n't care about leap seconds , use UTCTime and NominalDiffTime for your clock calculations , UTCTime(..),NominalDiffTime ) where import Control.DeepSeq import Data.Time.Calendar.Days import Data.Time.Clock.Scale import Data.Fixed import Data.Typeable #if LANGUAGE_Rank2Types import Data.Data #endif It consists of the day number , and a time offset from midnight . Note that if a day has a leap second added to it , it will have 86401 seconds . data UTCTime = UTCTime { utctDay :: Day, | the time from midnight , 0 < = t < ( because of leap - seconds ) utctDayTime :: DiffTime } #if LANGUAGE_DeriveDataTypeable #if LANGUAGE_Rank2Types #if HAS_DataPico deriving (Data, Typeable) #endif #endif #endif instance NFData UTCTime where rnf (UTCTime d t) = d `deepseq` t `deepseq` () instance Eq UTCTime where (UTCTime da ta) == (UTCTime db tb) = (da == db) && (ta == tb) instance Ord UTCTime where compare (UTCTime da ta) (UTCTime db tb) = case (compare da db) of EQ -> compare ta tb cmp -> cmp It has a precision of 10 ^ -12 s. For instance , 23:00 UTC + 2 hours of NominalDiffTime = 01:00 UTC ( + 1 day ) , newtype NominalDiffTime = MkNominalDiffTime Pico deriving (Eq,Ord #if LANGUAGE_DeriveDataTypeable #if LANGUAGE_Rank2Types #if HAS_DataPico ,Data, Typeable #endif #endif #endif ) rnf ndt = seq ndt () instance Enum NominalDiffTime where succ (MkNominalDiffTime a) = MkNominalDiffTime (succ a) pred (MkNominalDiffTime a) = MkNominalDiffTime (pred a) toEnum = MkNominalDiffTime . toEnum fromEnum (MkNominalDiffTime a) = fromEnum a enumFrom (MkNominalDiffTime a) = fmap MkNominalDiffTime (enumFrom a) enumFromThen (MkNominalDiffTime a) (MkNominalDiffTime b) = fmap MkNominalDiffTime (enumFromThen a b) enumFromTo (MkNominalDiffTime a) (MkNominalDiffTime b) = fmap MkNominalDiffTime (enumFromTo a b) enumFromThenTo (MkNominalDiffTime a) (MkNominalDiffTime b) (MkNominalDiffTime c) = fmap MkNominalDiffTime (enumFromThenTo a b c) instance Show NominalDiffTime where show (MkNominalDiffTime t) = (showFixed True t) ++ "s" instance Num NominalDiffTime where (MkNominalDiffTime a) + (MkNominalDiffTime b) = MkNominalDiffTime (a + b) (MkNominalDiffTime a) - (MkNominalDiffTime b) = MkNominalDiffTime (a - b) (MkNominalDiffTime a) * (MkNominalDiffTime b) = MkNominalDiffTime (a * b) negate (MkNominalDiffTime a) = MkNominalDiffTime (negate a) abs (MkNominalDiffTime a) = MkNominalDiffTime (abs a) signum (MkNominalDiffTime a) = MkNominalDiffTime (signum a) fromInteger i = MkNominalDiffTime (fromInteger i) instance Real NominalDiffTime where toRational (MkNominalDiffTime a) = toRational a instance Fractional NominalDiffTime where (MkNominalDiffTime a) / (MkNominalDiffTime b) = MkNominalDiffTime (a / b) recip (MkNominalDiffTime a) = MkNominalDiffTime (recip a) fromRational r = MkNominalDiffTime (fromRational r) instance RealFrac NominalDiffTime where properFraction (MkNominalDiffTime a) = (i,MkNominalDiffTime f) where (i,f) = properFraction a truncate (MkNominalDiffTime a) = truncate a round (MkNominalDiffTime a) = round a ceiling (MkNominalDiffTime a) = ceiling a floor (MkNominalDiffTime a) = floor a # RULES " realToFrac / DiffTime->NominalDiffTime " realToFrac = \ dt - > MkNominalDiffTime ( realToFrac dt ) " realToFrac / NominalDiffTime->DiffTime " realToFrac = \ ( MkNominalDiffTime ps ) - > realToFrac realToFrac / NominalDiffTime->Pico " realToFrac = \ ( MkNominalDiffTime ps ) - > ps " realToFrac / Pico->NominalDiffTime " realToFrac = MkNominalDiffTime # "realToFrac/DiffTime->NominalDiffTime" realToFrac = \ dt -> MkNominalDiffTime (realToFrac dt) "realToFrac/NominalDiffTime->DiffTime" realToFrac = \ (MkNominalDiffTime ps) -> realToFrac ps "realToFrac/NominalDiffTime->Pico" realToFrac = \ (MkNominalDiffTime ps) -> ps "realToFrac/Pico->NominalDiffTime" realToFrac = MkNominalDiffTime #-}
e578ce444ba5bedcaa70d0d1147f2e0fcf37beed6e14dbffb8eca0190f2cef94
hbr/fmlib
indent.ml
type expectation = | Indent of int | Align of int | Align_between of int * int type violation = expectation let group (lst: ('a * expectation option) list) : (expectation option * 'a list) list = let rec grp lst = match lst with | [] -> [] | (a, ea) :: lst -> match grp lst with | [] -> [ea, [a]] | (e, elst) :: lst -> if ea = e then begin (e, a :: elst) :: lst end else begin (ea, [a]) :: (e, elst) :: lst end in grp lst Indentation set of a construct : It consists of a lower bound , an optional upper bound and an alignment flag . The upper bound is valid only if the alignment flag is set . The indentation of a construct is defined as the start position its first token . Tokens can appear anywhere starting from the lower bound as long as the alignment flag is not set . If the alignment flag is set , then a token has to appear between the lower bound and the optional upper bound . A token appearing within the allowed indentation set when the alignment flag is set , restricts the allowed indentation set to exactly the position of the start of the token and clears the alignment flag . I.e. all subsequent token belonging to the same parent can appear anywhere starting from the lower bound of the indentation set . It consists of a lower bound, an optional upper bound and an alignment flag. The upper bound is valid only if the alignment flag is set. The indentation of a construct is defined as the start position its first token. Tokens can appear anywhere starting from the lower bound as long as the alignment flag is not set. If the alignment flag is set, then a token has to appear between the lower bound and the optional upper bound. A token appearing within the allowed indentation set when the alignment flag is set, restricts the allowed indentation set to exactly the position of the start of the token and clears the alignment flag. I.e. all subsequent token belonging to the same parent can appear anywhere starting from the lower bound of the indentation set. *) type t = { lb: int; (* lower bound of the indentation set *) ub: int option; (* upper bound of the indentation set *) alignment flag ; if set , then we are waiting for the first token which has to be in the indentation set . first token which has to be in the indentation set. *) } let expectation (ind: t): expectation option = let expect () = if ind.lb = 0 then None else Some (Indent ind.lb) in match ind.ub with | None -> expect () | Some ub -> if not ind.abs then expect () else if ind.lb = ub then Some (Align ub) else Some (Align_between (ind.lb, ub)) let initial: t = { lb = 0; ub = None; abs = false } let check_position (pos: int) (ind: t): expectation option = let check_indent () = if ind.lb <= pos then None else Some (Indent ind.lb) in match ind.ub with | None -> check_indent () | Some ub -> if not ind.abs then check_indent () else if ind.lb <= pos && pos <= ub then None else if ind.lb = ub then Some (Align ind.lb) else Some (Align_between (ind.lb, ub)) let token (pos: int) (ind: t): t = assert (check_position pos ind = None); if not ind.abs then (* Normal case. Token are all wrapped with '>=' i.e. they can appear to the right of the indentation set of the parent. However, if the token appears within the indentation set of the parent, then it restricts the upper bound of the indentation set of the parent. A parent can by definition never be indented more than all its tokens. *) match ind.ub with | Some ub when ub <= pos -> ind | _ -> {ind with ub = Some pos} else First token of an aligned parent . Indentation set consists of exactly the token position . the token position. *) { lb = pos; ub = Some pos; abs = false } let align (ind: t): t = { ind with abs = true } let left_align (ind: t): t = { ind with ub = Some ind.lb; abs = true; } let end_align (ind0: t) (ind: t): t = if not ind.abs then (* flag is cleared, the aligned sequence is not empty. *) ind else (* the aligned sequence is empty and therefore must not have any effect *) {ind with abs = ind0.abs} let start_indent (i: int) (ind: t): t = assert (0 <= i); if ind.abs then No effect on aligned structures which have not yet received a first token . token. *) ind else { lb = ind.lb + i; ub = None; abs = false; } let end_indent (i: int) (ind0: t) (ind: t): t = if ind0.abs then ind else match ind.ub, ind0.ub with | None, _ -> (* Not yet received any token. *) ind0 | Some ub, None -> (* Received some token, but parent not yet. *) assert (ind0.lb + i <= ub); {ind0 with ub = ind.ub} | Some ub, Some ub0 -> assert (ind0.lb + i <= ub); {ind0 with ub = Some (min ub0 (ub - i))}
null
https://raw.githubusercontent.com/hbr/fmlib/45ee4d2c76a19ef44557c554de30ec57d94bb9e5/src/parse/indent.ml
ocaml
lower bound of the indentation set upper bound of the indentation set Normal case. Token are all wrapped with '>=' i.e. they can appear to the right of the indentation set of the parent. However, if the token appears within the indentation set of the parent, then it restricts the upper bound of the indentation set of the parent. A parent can by definition never be indented more than all its tokens. flag is cleared, the aligned sequence is not empty. the aligned sequence is empty and therefore must not have any effect Not yet received any token. Received some token, but parent not yet.
type expectation = | Indent of int | Align of int | Align_between of int * int type violation = expectation let group (lst: ('a * expectation option) list) : (expectation option * 'a list) list = let rec grp lst = match lst with | [] -> [] | (a, ea) :: lst -> match grp lst with | [] -> [ea, [a]] | (e, elst) :: lst -> if ea = e then begin (e, a :: elst) :: lst end else begin (ea, [a]) :: (e, elst) :: lst end in grp lst Indentation set of a construct : It consists of a lower bound , an optional upper bound and an alignment flag . The upper bound is valid only if the alignment flag is set . The indentation of a construct is defined as the start position its first token . Tokens can appear anywhere starting from the lower bound as long as the alignment flag is not set . If the alignment flag is set , then a token has to appear between the lower bound and the optional upper bound . A token appearing within the allowed indentation set when the alignment flag is set , restricts the allowed indentation set to exactly the position of the start of the token and clears the alignment flag . I.e. all subsequent token belonging to the same parent can appear anywhere starting from the lower bound of the indentation set . It consists of a lower bound, an optional upper bound and an alignment flag. The upper bound is valid only if the alignment flag is set. The indentation of a construct is defined as the start position its first token. Tokens can appear anywhere starting from the lower bound as long as the alignment flag is not set. If the alignment flag is set, then a token has to appear between the lower bound and the optional upper bound. A token appearing within the allowed indentation set when the alignment flag is set, restricts the allowed indentation set to exactly the position of the start of the token and clears the alignment flag. I.e. all subsequent token belonging to the same parent can appear anywhere starting from the lower bound of the indentation set. *) type t = { alignment flag ; if set , then we are waiting for the first token which has to be in the indentation set . first token which has to be in the indentation set. *) } let expectation (ind: t): expectation option = let expect () = if ind.lb = 0 then None else Some (Indent ind.lb) in match ind.ub with | None -> expect () | Some ub -> if not ind.abs then expect () else if ind.lb = ub then Some (Align ub) else Some (Align_between (ind.lb, ub)) let initial: t = { lb = 0; ub = None; abs = false } let check_position (pos: int) (ind: t): expectation option = let check_indent () = if ind.lb <= pos then None else Some (Indent ind.lb) in match ind.ub with | None -> check_indent () | Some ub -> if not ind.abs then check_indent () else if ind.lb <= pos && pos <= ub then None else if ind.lb = ub then Some (Align ind.lb) else Some (Align_between (ind.lb, ub)) let token (pos: int) (ind: t): t = assert (check_position pos ind = None); if not ind.abs then match ind.ub with | Some ub when ub <= pos -> ind | _ -> {ind with ub = Some pos} else First token of an aligned parent . Indentation set consists of exactly the token position . the token position. *) { lb = pos; ub = Some pos; abs = false } let align (ind: t): t = { ind with abs = true } let left_align (ind: t): t = { ind with ub = Some ind.lb; abs = true; } let end_align (ind0: t) (ind: t): t = if not ind.abs then ind else {ind with abs = ind0.abs} let start_indent (i: int) (ind: t): t = assert (0 <= i); if ind.abs then No effect on aligned structures which have not yet received a first token . token. *) ind else { lb = ind.lb + i; ub = None; abs = false; } let end_indent (i: int) (ind0: t) (ind: t): t = if ind0.abs then ind else match ind.ub, ind0.ub with | None, _ -> ind0 | Some ub, None -> assert (ind0.lb + i <= ub); {ind0 with ub = ind.ub} | Some ub, Some ub0 -> assert (ind0.lb + i <= ub); {ind0 with ub = Some (min ub0 (ub - i))}
a31d904ab29481f2095251da8f21514d9659c468649356e216664fa41348e718
CodyReichert/qi
packages.lisp
(in-package :cl-user) (defpackage qi.packages (:use :cl :qi.paths) (:import-from :qi.manifest :manifest-get-by-name :manifest-package :manifest-package-name :manifest-package-url) (:import-from :qi.util :download-strategy :is-tar-url? :is-git-url? :is-hg-url? :is-gh-url? :run-git-command :update-repository) (:export :*qi-dependencies* :*yaml-packages* :dependency :dependency-name :dependency-url :dependency-version :extract-dependency :get-sys-path :install-dependency :installed? :make-dependency :make-manifest-dependency :make-http-dependency :make-local-dependency :make-git-dependency :make-hg-dependency :location :local :http :git :hg)) (in-package :qi.packages) ;; code: ;; This package provides data types and generic functions for working with qi ' dependencies ' . Dependencies are specified by a user in their qi.yaml file . Three types of dependencies are supported : ;; - Local ;; + Only takes a path to a directory on the local machine ;; - HTTP ;; + An http link to a tarball ;; - Git ;; + Git URL's are cloned, and can take a couple of extra parameters: - Location ( http link to repo on github ) ;; - Version (version of the repo to check out) ;; - Mercurial ;; + Mercurial URL's are cloned (defvar *qi-dependencies* nil "A list of `dependencies' as required by the qi.yaml.") (defvar *yaml-packages* nil "A list of `dependencies' from the `+project-names+' qi.yaml") ;; `dependency' data type and methods (defstruct dependency "The base data structure for a dependency." name ;; Don't use "master" as default; instead let upstream dictate (branch nil) (download-strategy nil) (url nil) (version nil)) (defstruct (manifest-dependency (:include dependency)) "Manifest dependency data structure.") (defstruct (local-dependency (:include dependency)) "Local dependency data structure.") (defstruct (http-dependency (:include dependency)) "Tarball dependency data structure.") (defstruct (git-dependency (:include dependency)) "Github dependency data structure.") (defstruct (hg-dependency (:include dependency)) "Mercurial dependency data structure.") ;; Generic functions on a ` dependency ' ;; (defgeneric install-dependency (dependency) (:documentation "Install a dependency to share/qi/packages")) (defmethod install-dependency :before ((dependency dependency)) (setf *qi-dependencies* (cons dependency *qi-dependencies*))) (defmethod install-dependency ((dep git-dependency)) (clone-git-repo (dependency-url dep) dep) (make-dependency-available dep) (install-transitive-dependencies dep)) (defmethod install-dependency ((dep hg-dependency)) (clone-hg-repo (dependency-url dep) dep) (make-dependency-available dep) (install-transitive-dependencies dep)) (defmethod install-dependency ((dep http-dependency)) (remove-old-versions dep) (download-tarball (dependency-url dep) dep) (make-dependency-available dep) (install-transitive-dependencies dep)) (defmethod install-dependency ((dep manifest-dependency)) (let ((strat (dependency-download-strategy dep)) (url (dependency-url dep))) (cond ((eq :tarball strat) (remove-old-versions dep) (download-tarball url dep) ;; The dependency must be made available before it is ;; installed so ASDF can determine its dependencies in turn (make-dependency-available dep) (install-transitive-dependencies dep)) ((eq :git strat) (clone-git-repo url dep) (make-dependency-available dep) (install-transitive-dependencies dep)) (t ; unsupported strategy (error (format t "~%---X Download strategy \"~S\" is not yet supported" strat)))))) (defun extract-dependency (p) "Generate a dependency from package P." (cond ((eql nil (gethash "url" p)) (let* ((name (gethash "name" p)) (man (manifest-get-by-name name))) (unless man (error "---X Package \"~S\" is not in the manifest; please provide a URL" name)) (make-manifest-dependency :name name :branch (gethash "branch" p) :download-strategy (download-strategy (manifest-package-url man)) :url (manifest-package-url man) :version (or (gethash "tag" p) (gethash "revision" p) (gethash "version" p))))) ;; Dependency has a tarball URL ((is-tar-url? (gethash "url" p)) (make-http-dependency :name (gethash "name" p) :download-strategy :tarball :version (gethash "version" p) :url (gethash "url" p))) ;; Dependency has a git URL ((or (is-git-url? (gethash "url" p)) (is-gh-url? (gethash "url" p))) (make-git-dependency :name (gethash "name" p) :branch (gethash "branch" p) :download-strategy :git :version (or (gethash "tag" p) (gethash "revision" p) (gethash "version" p)) :url (gethash "url" p))) Dependency has a Mercurial URL ((is-hg-url? (gethash "url" p)) (make-hg-dependency :name (gethash "name" p) :download-strategy :hg :version (gethash "version" p) :url (car (cl-ppcre:split ".hg" (gethash "url" p))))) ;; Dependency is local path ((not (null (gethash "path" p))) (make-local-dependency :name (gethash "name" p) :download-strategy :local :version (gethash "version" p) :url (or (gethash "url" p) nil))) (t (error (format t "~%---X Cannot resolve dependency type"))))) (defun remove-old-versions (dep) "Walk the dependencies directory and remove versions of DEP that aren't current." (let* ((dependency-prefix (concatenate 'string (dependency-name dep) "-")) (old-versions (remove-if ;; don't delete the latest version, or tarballs for other dependencies (lambda (x) (or (and (pathname-match-p (get-sys-path dep) x) ;; if the version is unset, delete it ;; since that means we weren't able to ;; determine the real version; otherwise ;; keep it (not (dependency-version dep))) ;; keep it if it doesn't start with `dependency-prefix' (not (eql (length dependency-prefix) (string> (first (last (pathname-directory x))) dependency-prefix))))) (uiop/filesystem:subdirectories (qi.paths:package-dir))))) (loop for dir in old-versions do (progn (format t "~%.... Deleting outdated ~A" dir) (uiop:run-program (concatenate 'string "rm -r " (namestring dir)) :wait t :output :lines))))) (defun download-tarball (url dep) "Downloads and unpacks tarball from URL for DEP." (let ((out-path (tarball-path dep))) (format t "~%---> Downloading tarball from ~A" url) (with-open-file (f (ensure-directories-exist out-path) :direction :output :if-does-not-exist :create :if-exists :supersede :element-type '(unsigned-byte 8)) (let ((tar (drakma:http-request url :want-stream t))) (arnesi:awhile (read-byte tar nil nil) (write-byte arnesi:it f)) (close tar))) (unpack-tar dep))) (defun clone-git-repo (url dep) "Clones Git repository from URL." (let ((clone-path (get-sys-path dep))) (format t "~%---> Cloning ~A" url) (if (probe-file clone-path) (progn (update-repository :name (dependency-name dep) :branch (dependency-branch dep) :directory (namestring clone-path) :revision (dependency-version dep) :upstream url)) (progn (format t "~%.... to ~A~%" (namestring clone-path)) (run-git-command (concatenate 'string "clone " url " " (namestring clone-path))))))) (defun clone-hg-repo (url dep) "Clones Mercurial repository from URL." (let ((clone-path (get-sys-path dep))) (format t "~%---> Cloning ~A" url) (format t "~%---> to ~A" (namestring clone-path)) (run-hg-command (concatenate 'string "clone " url " " (namestring clone-path))) (if (probe-file (fad:merge-pathnames-as-file clone-path (concatenate 'string (dependency-name dep) ".asd"))) (error (format t "~%~%---X Failed to clone repository for ~A~%" url))))) (defun tarball-path (dep) (let ((out-file (concatenate 'string (dependency-name dep) "-" (dependency-version dep) ".tar.gz"))) (fad:merge-pathnames-as-file (qi.paths:+dep-cache+) (pathname out-file)))) (defun unpack-tar (dep) "Unarchive the downloaded DEP into its sys-path." (let* ((tar-path (tarball-path dep)) (unzipped-actual (extract-tarball* tar-path (qi.paths:+dep-cache+))) (unzipped-expected (get-sys-path dep))) (if (probe-file unzipped-expected) ;; Make sure it always returns non-nil on success, for testing unzipped-expected (rename-file unzipped-actual unzipped-expected)))) (defun extract-tarball* (tarball &optional (destination *default-pathname-defaults*)) (let ((*default-pathname-defaults* (or destination (qi.paths:package-dir)))) (gzip-stream:with-open-gzip-file (gzip tarball) (let ((archive (archive:open-archive 'archive:tar-archive gzip))) (prog1 (merge-pathnames (archive:name (archive:read-entry-from-archive archive)) *default-pathname-defaults*) (archive::extract-files-from-archive archive)))))) (defun get-sys-path (dependency) "Construct the sys-path for a DEPENDENCY." (fad:merge-pathnames-as-directory (qi.paths:package-dir) (concatenate 'string (dependency-name dependency) ;; If it's a (versioned) tarball, add the version to the sys - path . If it 's a VCS source , then instead ;; of the version use the download strategy as a ;; suffix (since we'll want to update the existing ;; repository when the version is changed, rather than ;; fetching the entire repo to a new directory) (if (eql (dependency-download-strategy dependency) :tarball) (concatenate 'string "-" (or (dependency-version dependency) "latest")) (concatenate 'string "--" (string-downcase (symbol-name (dependency-download-strategy dependency))))) ;; Trailing slash to keep fad from thinking the last ;; part is a filename and stripping it "/"))) (defun make-dependency-available (dep) (setf asdf:*central-registry* add this path to the ASDF registry . (list* (get-sys-path dep) asdf:*central-registry*))) (defun install-transitive-dependencies (dep) (when (system-is-available? (dependency-name dep)) ;; Skip transitive dependencies that are already installed, as well as those explicitly specified in qi.yaml (let ((uninstalled (remove-if (lambda (x) (or (installed? x) (member x *yaml-packages* :test #'(lambda (y z) (string= y (dependency-name z)))))) (asdf:system-depends-on (asdf:find-system (dependency-name dep)))))) (loop for d in uninstalled do (let* ((from-manifest (manifest-get-by-name d)) (tdep (or (car (member-if (lambda (x) (string= d (dependency-name x))) *yaml-packages*)) If it 's not defined in qi.yaml , check the manifest (and from-manifest (make-manifest-dependency :name d :url (manifest-package-url from-manifest) :download-strategy (download-strategy (manifest-package-url from-manifest))))))) (unless (or tdep (system-is-available? d)) (error (format t "~%~%---X Without ~A, we cannot install ~A~%" d (dependency-name dep)))) (when (and tdep (not (installed? d))) (install-dependency tdep))))))) (defun system-is-available? (sys) (handler-case (asdf:find-system sys) (error () () nil))) (defun installed? (name) "Checks if NAME is in the `*qi-dependencies*'." (member name *qi-dependencies* :test #'(lambda (y z) (string= y (dependency-name z)))))
null
https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/src/packages.lisp
lisp
code: This package provides data types and generic functions for working with - Local + Only takes a path to a directory on the local machine - HTTP + An http link to a tarball - Git + Git URL's are cloned, and can take a couple of extra parameters: - Version (version of the repo to check out) - Mercurial + Mercurial URL's are cloned `dependency' data type and methods Don't use "master" as default; instead let upstream dictate The dependency must be made available before it is installed so ASDF can determine its dependencies in turn unsupported strategy Dependency has a tarball URL Dependency has a git URL Dependency is local path don't delete the latest version, or tarballs for other dependencies if the version is unset, delete it since that means we weren't able to determine the real version; otherwise keep it keep it if it doesn't start with `dependency-prefix' Make sure it always returns non-nil on success, for testing If it's a (versioned) tarball, add the version to of the version use the download strategy as a suffix (since we'll want to update the existing repository when the version is changed, rather than fetching the entire repo to a new directory) Trailing slash to keep fad from thinking the last part is a filename and stripping it Skip transitive dependencies that are already installed, as
(in-package :cl-user) (defpackage qi.packages (:use :cl :qi.paths) (:import-from :qi.manifest :manifest-get-by-name :manifest-package :manifest-package-name :manifest-package-url) (:import-from :qi.util :download-strategy :is-tar-url? :is-git-url? :is-hg-url? :is-gh-url? :run-git-command :update-repository) (:export :*qi-dependencies* :*yaml-packages* :dependency :dependency-name :dependency-url :dependency-version :extract-dependency :get-sys-path :install-dependency :installed? :make-dependency :make-manifest-dependency :make-http-dependency :make-local-dependency :make-git-dependency :make-hg-dependency :location :local :http :git :hg)) (in-package :qi.packages) qi ' dependencies ' . Dependencies are specified by a user in their qi.yaml file . Three types of dependencies are supported : - Location ( http link to repo on github ) (defvar *qi-dependencies* nil "A list of `dependencies' as required by the qi.yaml.") (defvar *yaml-packages* nil "A list of `dependencies' from the `+project-names+' qi.yaml") (defstruct dependency "The base data structure for a dependency." name (branch nil) (download-strategy nil) (url nil) (version nil)) (defstruct (manifest-dependency (:include dependency)) "Manifest dependency data structure.") (defstruct (local-dependency (:include dependency)) "Local dependency data structure.") (defstruct (http-dependency (:include dependency)) "Tarball dependency data structure.") (defstruct (git-dependency (:include dependency)) "Github dependency data structure.") (defstruct (hg-dependency (:include dependency)) "Mercurial dependency data structure.") Generic functions on a ` dependency ' (defgeneric install-dependency (dependency) (:documentation "Install a dependency to share/qi/packages")) (defmethod install-dependency :before ((dependency dependency)) (setf *qi-dependencies* (cons dependency *qi-dependencies*))) (defmethod install-dependency ((dep git-dependency)) (clone-git-repo (dependency-url dep) dep) (make-dependency-available dep) (install-transitive-dependencies dep)) (defmethod install-dependency ((dep hg-dependency)) (clone-hg-repo (dependency-url dep) dep) (make-dependency-available dep) (install-transitive-dependencies dep)) (defmethod install-dependency ((dep http-dependency)) (remove-old-versions dep) (download-tarball (dependency-url dep) dep) (make-dependency-available dep) (install-transitive-dependencies dep)) (defmethod install-dependency ((dep manifest-dependency)) (let ((strat (dependency-download-strategy dep)) (url (dependency-url dep))) (cond ((eq :tarball strat) (remove-old-versions dep) (download-tarball url dep) (make-dependency-available dep) (install-transitive-dependencies dep)) ((eq :git strat) (clone-git-repo url dep) (make-dependency-available dep) (install-transitive-dependencies dep)) (error (format t "~%---X Download strategy \"~S\" is not yet supported" strat)))))) (defun extract-dependency (p) "Generate a dependency from package P." (cond ((eql nil (gethash "url" p)) (let* ((name (gethash "name" p)) (man (manifest-get-by-name name))) (unless man (error "---X Package \"~S\" is not in the manifest; please provide a URL" name)) (make-manifest-dependency :name name :branch (gethash "branch" p) :download-strategy (download-strategy (manifest-package-url man)) :url (manifest-package-url man) :version (or (gethash "tag" p) (gethash "revision" p) (gethash "version" p))))) ((is-tar-url? (gethash "url" p)) (make-http-dependency :name (gethash "name" p) :download-strategy :tarball :version (gethash "version" p) :url (gethash "url" p))) ((or (is-git-url? (gethash "url" p)) (is-gh-url? (gethash "url" p))) (make-git-dependency :name (gethash "name" p) :branch (gethash "branch" p) :download-strategy :git :version (or (gethash "tag" p) (gethash "revision" p) (gethash "version" p)) :url (gethash "url" p))) Dependency has a Mercurial URL ((is-hg-url? (gethash "url" p)) (make-hg-dependency :name (gethash "name" p) :download-strategy :hg :version (gethash "version" p) :url (car (cl-ppcre:split ".hg" (gethash "url" p))))) ((not (null (gethash "path" p))) (make-local-dependency :name (gethash "name" p) :download-strategy :local :version (gethash "version" p) :url (or (gethash "url" p) nil))) (t (error (format t "~%---X Cannot resolve dependency type"))))) (defun remove-old-versions (dep) "Walk the dependencies directory and remove versions of DEP that aren't current." (let* ((dependency-prefix (concatenate 'string (dependency-name dep) "-")) (old-versions (remove-if (lambda (x) (or (and (pathname-match-p (get-sys-path dep) x) (not (dependency-version dep))) (not (eql (length dependency-prefix) (string> (first (last (pathname-directory x))) dependency-prefix))))) (uiop/filesystem:subdirectories (qi.paths:package-dir))))) (loop for dir in old-versions do (progn (format t "~%.... Deleting outdated ~A" dir) (uiop:run-program (concatenate 'string "rm -r " (namestring dir)) :wait t :output :lines))))) (defun download-tarball (url dep) "Downloads and unpacks tarball from URL for DEP." (let ((out-path (tarball-path dep))) (format t "~%---> Downloading tarball from ~A" url) (with-open-file (f (ensure-directories-exist out-path) :direction :output :if-does-not-exist :create :if-exists :supersede :element-type '(unsigned-byte 8)) (let ((tar (drakma:http-request url :want-stream t))) (arnesi:awhile (read-byte tar nil nil) (write-byte arnesi:it f)) (close tar))) (unpack-tar dep))) (defun clone-git-repo (url dep) "Clones Git repository from URL." (let ((clone-path (get-sys-path dep))) (format t "~%---> Cloning ~A" url) (if (probe-file clone-path) (progn (update-repository :name (dependency-name dep) :branch (dependency-branch dep) :directory (namestring clone-path) :revision (dependency-version dep) :upstream url)) (progn (format t "~%.... to ~A~%" (namestring clone-path)) (run-git-command (concatenate 'string "clone " url " " (namestring clone-path))))))) (defun clone-hg-repo (url dep) "Clones Mercurial repository from URL." (let ((clone-path (get-sys-path dep))) (format t "~%---> Cloning ~A" url) (format t "~%---> to ~A" (namestring clone-path)) (run-hg-command (concatenate 'string "clone " url " " (namestring clone-path))) (if (probe-file (fad:merge-pathnames-as-file clone-path (concatenate 'string (dependency-name dep) ".asd"))) (error (format t "~%~%---X Failed to clone repository for ~A~%" url))))) (defun tarball-path (dep) (let ((out-file (concatenate 'string (dependency-name dep) "-" (dependency-version dep) ".tar.gz"))) (fad:merge-pathnames-as-file (qi.paths:+dep-cache+) (pathname out-file)))) (defun unpack-tar (dep) "Unarchive the downloaded DEP into its sys-path." (let* ((tar-path (tarball-path dep)) (unzipped-actual (extract-tarball* tar-path (qi.paths:+dep-cache+))) (unzipped-expected (get-sys-path dep))) (if (probe-file unzipped-expected) unzipped-expected (rename-file unzipped-actual unzipped-expected)))) (defun extract-tarball* (tarball &optional (destination *default-pathname-defaults*)) (let ((*default-pathname-defaults* (or destination (qi.paths:package-dir)))) (gzip-stream:with-open-gzip-file (gzip tarball) (let ((archive (archive:open-archive 'archive:tar-archive gzip))) (prog1 (merge-pathnames (archive:name (archive:read-entry-from-archive archive)) *default-pathname-defaults*) (archive::extract-files-from-archive archive)))))) (defun get-sys-path (dependency) "Construct the sys-path for a DEPENDENCY." (fad:merge-pathnames-as-directory (qi.paths:package-dir) (concatenate 'string (dependency-name dependency) the sys - path . If it 's a VCS source , then instead (if (eql (dependency-download-strategy dependency) :tarball) (concatenate 'string "-" (or (dependency-version dependency) "latest")) (concatenate 'string "--" (string-downcase (symbol-name (dependency-download-strategy dependency))))) "/"))) (defun make-dependency-available (dep) (setf asdf:*central-registry* add this path to the ASDF registry . (list* (get-sys-path dep) asdf:*central-registry*))) (defun install-transitive-dependencies (dep) (when (system-is-available? (dependency-name dep)) well as those explicitly specified in qi.yaml (let ((uninstalled (remove-if (lambda (x) (or (installed? x) (member x *yaml-packages* :test #'(lambda (y z) (string= y (dependency-name z)))))) (asdf:system-depends-on (asdf:find-system (dependency-name dep)))))) (loop for d in uninstalled do (let* ((from-manifest (manifest-get-by-name d)) (tdep (or (car (member-if (lambda (x) (string= d (dependency-name x))) *yaml-packages*)) If it 's not defined in qi.yaml , check the manifest (and from-manifest (make-manifest-dependency :name d :url (manifest-package-url from-manifest) :download-strategy (download-strategy (manifest-package-url from-manifest))))))) (unless (or tdep (system-is-available? d)) (error (format t "~%~%---X Without ~A, we cannot install ~A~%" d (dependency-name dep)))) (when (and tdep (not (installed? d))) (install-dependency tdep))))))) (defun system-is-available? (sys) (handler-case (asdf:find-system sys) (error () () nil))) (defun installed? (name) "Checks if NAME is in the `*qi-dependencies*'." (member name *qi-dependencies* :test #'(lambda (y z) (string= y (dependency-name z)))))
90aa598176fbcbd00dd7c384ca7fd6fe2bc80731143dc6e7c91b804f141c90b3
elastic/runbld
facts.clj
(ns runbld.facts (:require [runbld.io :as io] [schema.core :as s] [slingshot.slingshot :refer [throw+]])) (defprotocol Facter (arch [_]) (cpu-type [_]) (cpus [_]) (cpus-physical [_]) (facter-provider [_]) (facter-version [_]) (hostname [_]) (ip4 [_]) (ip6 [_]) (kernel-name [_]) (kernel-release [_]) (kernel-version [_]) (model [_]) (os [_]) (os-version [_]) (os-family [_]) (ram-mb [_]) (ram-gb [_]) (ram-bytes [_]) (timezone [_]) (uptime-days [_]) (uptime-secs [_]) (uptime [_]) (raw [_])) (s/defn ram-mb-from-slash-proc :- s/Num [facts :- {s/Keyword s/Any}] (let [meminfo "/proc/meminfo"] (if (.exists (io/file meminfo)) (let [memtotal-raw (:out (io/run "fgrep" "MemTotal" meminfo)) [_ kb] (or (re-find #"^MemTotal: +(\d+) kB" memtotal-raw) (throw+ {:type ::error :msg (format "can't get memtotal from meminfo:\n%s" (with-out-str (println memtotal-raw) (clojure.pprint/pprint facts)))}))] (float (/ (Integer/parseInt kb) 1024))) (throw+ {:type ::error :msg (format "can't get memory info from:\n%s" (with-out-str (clojure.pprint/pprint facts)))}))))
null
https://raw.githubusercontent.com/elastic/runbld/7afcb1d95a464dc068f95abf3ad8a7566202ce28/src/clj/runbld/facts.clj
clojure
(ns runbld.facts (:require [runbld.io :as io] [schema.core :as s] [slingshot.slingshot :refer [throw+]])) (defprotocol Facter (arch [_]) (cpu-type [_]) (cpus [_]) (cpus-physical [_]) (facter-provider [_]) (facter-version [_]) (hostname [_]) (ip4 [_]) (ip6 [_]) (kernel-name [_]) (kernel-release [_]) (kernel-version [_]) (model [_]) (os [_]) (os-version [_]) (os-family [_]) (ram-mb [_]) (ram-gb [_]) (ram-bytes [_]) (timezone [_]) (uptime-days [_]) (uptime-secs [_]) (uptime [_]) (raw [_])) (s/defn ram-mb-from-slash-proc :- s/Num [facts :- {s/Keyword s/Any}] (let [meminfo "/proc/meminfo"] (if (.exists (io/file meminfo)) (let [memtotal-raw (:out (io/run "fgrep" "MemTotal" meminfo)) [_ kb] (or (re-find #"^MemTotal: +(\d+) kB" memtotal-raw) (throw+ {:type ::error :msg (format "can't get memtotal from meminfo:\n%s" (with-out-str (println memtotal-raw) (clojure.pprint/pprint facts)))}))] (float (/ (Integer/parseInt kb) 1024))) (throw+ {:type ::error :msg (format "can't get memory info from:\n%s" (with-out-str (clojure.pprint/pprint facts)))}))))
baa4ab5da748256e4548362930a593b31734f053be165f690b975f71b151f848
abailly/xxi-century-typed
NetSpec.hs
module Minilang.REPL.NetSpec where --import Control.Concurrent (threadDelay) import Control.Concurrent.Async import Control.Concurrent.STM.TVar import Control.Exception (bracket) import Control.Monad (forM) import Data.Aeson (eitherDecode, encode) import Minilang.Env import Minilang.Eval (Value (EU), emptyContext) import Minilang.Log import Minilang.Parser import Minilang.REPL.Net import Minilang.REPL.Types import Minilang.Server.Types import Network.HTTP.Types (status400) import Network.Wai (responseLBS) import Network.Wai.Handler.Warp as Warp import Network.WebSockets as WS import System.Directory import System.FilePath ((</>)) import System.IO (hClose) import System.Posix.Temp (mkstemp) import Test.Hspec import Prelude hiding (lines, readFile, writeFile) startServer :: IO Server startServer = do (port, socket) <- openFreePort envs <- newTVarIO mempty logger <- newLog "test" let app = runNetREPL logger envs (\_ resp -> resp $ responseLBS status400 [] "Not a WebSocket request") settings = setGracefulShutdownTimeout (Just 0) defaultSettings thread <- async $ Warp.runSettingsSocket settings socket app pure $ Server (Just thread) port stopServer :: Server -> IO () stopServer (Server (Just th) _) = cancel th stopServer _ = pure () withServer :: (Server -> IO c) -> IO c withServer = bracket startServer stopServer runTestClient :: Int -> String -> [In] -> IO [Either String Out] runTestClient port envId inputs = runClient "127.0.0.1" port ("/repl/" <> envId) client where client cnx = do outs <- forM inputs $ \inp -> do WS.sendBinaryData cnx (encode inp) eitherDecode <$> WS.receiveData cnx WS.sendBinaryData cnx (encode EOF) WS.sendClose cnx (encode ("" :: String)) pure outs temporaryFile :: (FilePath -> IO c) -> IO c temporaryFile = bracket newTempFile removeFile where newTempFile = do dir <- getTemporaryDirectory (f, h) <- mkstemp (dir </> "repl.test") hClose h pure f spec :: Spec spec = around withServer $ describe "MiniLang Network REPL" $ do it "evaluates definition and returns defined symbol" $ \Server{serverPort} -> do let inp = [In "Unit : U = Sum(tt)"] expectedOutput = [Right $ Defined (B "Unit") (U 0)] res <- runTestClient serverPort ".newenv1" inp res `shouldBe` expectedOutput it "allows retrieving empty initial env" $ \Server{serverPort} -> do let inp = [Com DumpEnv] expectedOutput = [Right $ CurrentEnv EmptyEnv emptyContext] res <- runTestClient serverPort ".newenv2" inp res `shouldBe` expectedOutput it "can reconnect to existing environment" $ \Server{serverPort} -> do let inp = [In "Unit : U = Sum(tt)"] _ <- runTestClient serverPort ".newenv3" inp res <- runTestClient serverPort ".newenv3" [In "Unit"] res `shouldSatisfy` isEvaluated isEvaluated :: [Either a Out] -> Bool isEvaluated [Right (Evaluated _ EU{})] = True isEvaluated _ = False
null
https://raw.githubusercontent.com/abailly/xxi-century-typed/89df5eab3747ddb0ea37030ddb1947fb8c14265b/minilang/test/Minilang/REPL/NetSpec.hs
haskell
import Control.Concurrent (threadDelay)
module Minilang.REPL.NetSpec where import Control.Concurrent.Async import Control.Concurrent.STM.TVar import Control.Exception (bracket) import Control.Monad (forM) import Data.Aeson (eitherDecode, encode) import Minilang.Env import Minilang.Eval (Value (EU), emptyContext) import Minilang.Log import Minilang.Parser import Minilang.REPL.Net import Minilang.REPL.Types import Minilang.Server.Types import Network.HTTP.Types (status400) import Network.Wai (responseLBS) import Network.Wai.Handler.Warp as Warp import Network.WebSockets as WS import System.Directory import System.FilePath ((</>)) import System.IO (hClose) import System.Posix.Temp (mkstemp) import Test.Hspec import Prelude hiding (lines, readFile, writeFile) startServer :: IO Server startServer = do (port, socket) <- openFreePort envs <- newTVarIO mempty logger <- newLog "test" let app = runNetREPL logger envs (\_ resp -> resp $ responseLBS status400 [] "Not a WebSocket request") settings = setGracefulShutdownTimeout (Just 0) defaultSettings thread <- async $ Warp.runSettingsSocket settings socket app pure $ Server (Just thread) port stopServer :: Server -> IO () stopServer (Server (Just th) _) = cancel th stopServer _ = pure () withServer :: (Server -> IO c) -> IO c withServer = bracket startServer stopServer runTestClient :: Int -> String -> [In] -> IO [Either String Out] runTestClient port envId inputs = runClient "127.0.0.1" port ("/repl/" <> envId) client where client cnx = do outs <- forM inputs $ \inp -> do WS.sendBinaryData cnx (encode inp) eitherDecode <$> WS.receiveData cnx WS.sendBinaryData cnx (encode EOF) WS.sendClose cnx (encode ("" :: String)) pure outs temporaryFile :: (FilePath -> IO c) -> IO c temporaryFile = bracket newTempFile removeFile where newTempFile = do dir <- getTemporaryDirectory (f, h) <- mkstemp (dir </> "repl.test") hClose h pure f spec :: Spec spec = around withServer $ describe "MiniLang Network REPL" $ do it "evaluates definition and returns defined symbol" $ \Server{serverPort} -> do let inp = [In "Unit : U = Sum(tt)"] expectedOutput = [Right $ Defined (B "Unit") (U 0)] res <- runTestClient serverPort ".newenv1" inp res `shouldBe` expectedOutput it "allows retrieving empty initial env" $ \Server{serverPort} -> do let inp = [Com DumpEnv] expectedOutput = [Right $ CurrentEnv EmptyEnv emptyContext] res <- runTestClient serverPort ".newenv2" inp res `shouldBe` expectedOutput it "can reconnect to existing environment" $ \Server{serverPort} -> do let inp = [In "Unit : U = Sum(tt)"] _ <- runTestClient serverPort ".newenv3" inp res <- runTestClient serverPort ".newenv3" [In "Unit"] res `shouldSatisfy` isEvaluated isEvaluated :: [Either a Out] -> Bool isEvaluated [Right (Evaluated _ EU{})] = True isEvaluated _ = False
1e794950a580d9f1176d3243aa7241d2e23a0a671c948e140201175a08d46409
CatalaLang/catala
from_scopelang.ml
This file is part of the Catala compiler , a specification language for tax and social benefits computation rules . Copyright ( C ) 2020 , contributor : < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . and social benefits computation rules. Copyright (C) 2020 Inria, contributor: Denis Merigoux <> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) open Catala_utils open Shared_ast type scope_var_ctx = { scope_var_name : ScopeVar.t; scope_var_typ : naked_typ; scope_var_io : Desugared.Ast.io; } type scope_input_var_ctx = { scope_input_name : StructField.t; scope_input_io : Desugared.Ast.io_input Marked.pos; scope_input_typ : naked_typ; } type 'm scope_sig_ctx = { scope_sig_local_vars : scope_var_ctx list; (** List of scope variables *) * Var representing the scope scope_sig_input_var : 'm Ast.expr Var.t; * Var representing the scope input inside the scope func scope_sig_input_struct : StructName.t; (** Scope input *) scope_sig_output_struct : StructName.t; (** Scope output *) scope_sig_in_fields : scope_input_var_ctx ScopeVar.Map.t; (** Mapping between the input scope variables and the input struct fields. *) scope_sig_out_fields : StructField.t ScopeVar.Map.t; (** Mapping between the output scope variables and the output struct fields. TODO: could likely be removed now that we have it in the program ctx *) } type 'm scope_sigs_ctx = 'm scope_sig_ctx ScopeName.Map.t type 'm ctx = { structs : struct_ctx; enums : enum_ctx; scope_name : ScopeName.t option; scopes_parameters : 'm scope_sigs_ctx; toplevel_vars : ('m Ast.expr Var.t * naked_typ) TopdefName.Map.t; scope_vars : ('m Ast.expr Var.t * naked_typ * Desugared.Ast.io) ScopeVar.Map.t; subscope_vars : ('m Ast.expr Var.t * naked_typ * Desugared.Ast.io) ScopeVar.Map.t SubScopeName.Map.t; local_vars : ('m Scopelang.Ast.expr, 'm Ast.expr Var.t) Var.Map.t; } let mark_tany m pos = Expr.with_ty m (Marked.mark pos TAny) ~pos (* Expression argument is used as a type witness, its type and positions aren't used *) let pos_mark_mk (type a m) (e : (a, m mark) gexpr) : (Pos.t -> m mark) * ((_, Pos.t) Marked.t -> m mark) = let pos_mark pos = Expr.map_mark (fun _ -> pos) (fun _ -> TAny, pos) (Marked.get_mark e) in let pos_mark_as e = pos_mark (Marked.get_mark e) in pos_mark, pos_mark_as let merge_defaults ~(is_func : bool) (caller : (dcalc, 'm mark) boxed_gexpr) (callee : (dcalc, 'm mark) boxed_gexpr) : (dcalc, 'm mark) boxed_gexpr = the merging of the two defaults , from the reentrant caller and the callee , is straightfoward in the general case and a little subtler when the variable being defined is a function . is straightfoward in the general case and a little subtler when the variable being defined is a function. *) if is_func then let m_callee = Marked.get_mark callee in let unboxed_callee = Expr.unbox callee in match Marked.unmark unboxed_callee with | EAbs { binder; tys } -> let vars, body = Bindlib.unmbind binder in let m_body = Marked.get_mark body in let caller = let m = Marked.get_mark caller in let pos = Expr.mark_pos m in Expr.make_app caller (List.map2 (fun (var : (dcalc, 'm mark) naked_gexpr Bindlib.var) ty -> Expr.evar var (* we have to correctly propagate types when doing this rewriting *) (Expr.with_ty m_body ~pos:(Expr.mark_pos m_body) ty)) (Array.to_list vars) tys) pos in let ltrue = Expr.elit (LBool true) (Expr.with_ty m_callee (Marked.mark (Expr.mark_pos m_callee) (TLit TBool))) in let d = Expr.edefault [caller] ltrue (Expr.rebox body) m_body in Expr.make_abs vars (Expr.eerroronempty d m_body) tys (Expr.mark_pos m_callee) | _ -> assert false (* should not happen because there should always be a lambda at the beginning of a default with a function type *) else let caller = let m = Marked.get_mark caller in let pos = Expr.mark_pos m in Expr.make_app caller [Expr.elit LUnit (Expr.with_ty m (Marked.mark pos (TLit TUnit)))] pos in let body = let m = Marked.get_mark callee in let ltrue = Expr.elit (LBool true) (Expr.with_ty m (Marked.mark (Expr.mark_pos m) (TLit TBool))) in Expr.eerroronempty (Expr.edefault [caller] ltrue callee m) m in body let tag_with_log_entry (e : 'm Ast.expr boxed) (l : log_entry) (markings : Uid.MarkedString.info list) : 'm Ast.expr boxed = let m = mark_tany (Marked.get_mark e) (Expr.pos e) in Expr.eapp (Expr.eop (Log (l, markings)) [TAny, Expr.pos e] m) [e] m (* In a list of exceptions, it is normally an error if more than a single one apply at the same time. This relaxes this constraint slightly, allowing a conflict if all the triggered conflicting exception yield syntactically equal results (and as long as none of these exceptions have exceptions themselves) NOTE: the choice of the exception that will be triggered and show in the trace is arbitrary (but deterministic). *) let collapse_similar_outcomes (type m) (excepts : m Scopelang.Ast.expr list) : m Scopelang.Ast.expr list = let module ExprMap = Map.Make (struct type t = m Scopelang.Ast.expr let compare = Expr.compare end) in let cons_map = List.fold_left (fun map -> function | (EDefault { excepts = []; cons; _ }, _) as e -> ExprMap.update cons (fun prev -> Some (e :: Option.value ~default:[] prev)) map | _ -> map) ExprMap.empty excepts in let _, excepts = List.fold_right (fun e (cons_map, excepts) -> match e with | EDefault { excepts = []; cons; _ }, _ -> let collapsed_exc = List.fold_left (fun acc -> function | EDefault { excepts = []; just; cons }, pos -> [EDefault { excepts = acc; just; cons }, pos] | _ -> assert false) [] (ExprMap.find cons cons_map) in ExprMap.add cons [] cons_map, collapsed_exc @ excepts | e -> cons_map, e :: excepts) excepts (cons_map, []) in excepts let thunk_scope_arg ~is_func io_in e = (* For "context" (or reentrant) variables, we thunk them as [(fun () -> e)] so that we can put them in default terms at the initialisation of the function body, allowing an empty error to recover the default value. *) let silent_var = Var.make "_" in let pos = Marked.get_mark io_in in match Marked.unmark io_in with | Desugared.Ast.NoInput -> invalid_arg "thunk_scope_arg" | Desugared.Ast.OnlyInput -> Expr.eerroronempty e (Marked.get_mark e) | Desugared.Ast.Reentrant -> (* we don't need to thunk expressions that are already functions *) if is_func then e else Expr.make_abs [| silent_var |] e [TLit TUnit, pos] pos let rec translate_expr (ctx : 'm ctx) (e : 'm Scopelang.Ast.expr) : 'm Ast.expr boxed = let m = Marked.get_mark e in match Marked.unmark e with | EVar v -> Expr.evar (Var.Map.find v ctx.local_vars) m | ELit (( LBool _ | LEmptyError | LInt _ | LRat _ | LMoney _ | LUnit | LDate _ | LDuration _ ) as l) -> Expr.elit l m | EStruct { name; fields } -> let fields = StructField.Map.map (translate_expr ctx) fields in Expr.estruct name fields m | EStructAccess { e; field; name } -> Expr.estructaccess (translate_expr ctx e) field name m | ETuple es -> Expr.etuple (List.map (translate_expr ctx) es) m | ETupleAccess { e; index; size } -> Expr.etupleaccess (translate_expr ctx e) index size m | EInj { e; cons; name } -> let e' = translate_expr ctx e in Expr.einj e' cons name m | EMatch { e = e1; name; cases = e_cases } -> let enum_sig = EnumName.Map.find name ctx.enums in let d_cases, remaining_e_cases = (* FIXME: these checks should probably be moved to a better place *) EnumConstructor.Map.fold (fun constructor _ (d_cases, e_cases) -> let case_e = try EnumConstructor.Map.find constructor e_cases with Not_found -> Errors.raise_spanned_error (Expr.pos e) "The constructor %a of enum %a is missing from this pattern \ matching" EnumConstructor.format_t constructor EnumName.format_t name in let case_d = translate_expr ctx case_e in ( EnumConstructor.Map.add constructor case_d d_cases, EnumConstructor.Map.remove constructor e_cases )) enum_sig (EnumConstructor.Map.empty, e_cases) in if not (EnumConstructor.Map.is_empty remaining_e_cases) then Errors.raise_spanned_error (Expr.pos e) "Pattern matching is incomplete for enum %a: missing cases %a" EnumName.format_t name (Format.pp_print_list ~pp_sep:(fun fmt () -> Format.fprintf fmt ", ") (fun fmt (case_name, _) -> EnumConstructor.format_t fmt case_name)) (EnumConstructor.Map.bindings remaining_e_cases); let e1 = translate_expr ctx e1 in Expr.ematch e1 name d_cases m | EScopeCall { scope; args } -> let pos = Expr.mark_pos m in let sc_sig = ScopeName.Map.find scope ctx.scopes_parameters in let in_var_map = ScopeVar.Map.merge (fun var_name (str_field : scope_input_var_ctx option) expr -> let expr = match str_field, expr with | Some { scope_input_io = Desugared.Ast.Reentrant, _; _ }, None -> Some (Expr.unbox (Expr.elit LEmptyError (mark_tany m pos))) | _ -> expr in match str_field, expr with | None, None -> None | Some var_ctx, Some e -> Some ( var_ctx.scope_input_name, thunk_scope_arg ~is_func: (match var_ctx.scope_input_typ with | TArrow _ -> true | _ -> false) var_ctx.scope_input_io (translate_expr ctx e) ) | Some var_ctx, None -> Errors.raise_multispanned_error [ None, pos; ( Some "Declaration of the missing input variable", Marked.get_mark (StructField.get_info var_ctx.scope_input_name) ); ] "Definition of input variable '%a' missing in this scope call" ScopeVar.format_t var_name | None, Some _ -> Errors.raise_multispanned_error [ None, pos; ( Some "Declaration of scope '%a'", Marked.get_mark (ScopeName.get_info scope) ); ] "Unknown input variable '%a' in scope call of '%a'" ScopeVar.format_t var_name ScopeName.format_t scope) sc_sig.scope_sig_in_fields args in let field_map = ScopeVar.Map.fold (fun _ (fld, e) acc -> StructField.Map.add fld e acc) in_var_map StructField.Map.empty in let arg_struct = Expr.estruct sc_sig.scope_sig_input_struct field_map (mark_tany m pos) in let called_func = tag_with_log_entry (Expr.evar sc_sig.scope_sig_scope_var (mark_tany m pos)) BeginCall [ScopeName.get_info scope; Marked.mark (Expr.pos e) "direct"] in let single_arg = tag_with_log_entry arg_struct (VarDef (TStruct sc_sig.scope_sig_input_struct)) [ ScopeName.get_info scope; Marked.mark (Expr.pos e) "direct"; Marked.mark (Expr.pos e) "input"; ] in let direct_output_info = [ ScopeName.get_info scope; Marked.mark (Expr.pos e) "direct"; Marked.mark (Expr.pos e) "output"; ] in (* calling_expr = scope_function scope_input_struct *) let calling_expr = Expr.eapp called_func [single_arg] m in For the purposes of log parsing explained in Runtime . EventParser , we need to wrap this function call in a flurry of log tags . Specifically , we are mascarading this scope call as a function call . In a normal function call , the log parser expects the output of the function to be defined as a default , hence the production of the output should yield a PosRecordIfTrueBool ( which is not the case here ) . To remedy this absence we fabricate a fake attached to a silent let binding to " true " before returning the output value . But this is not sufficient . Indeed for the tricky case of [ tests / test_scope / scope_call3.catala_en ] , when a scope returns a function , because we insert loggins calls at the call site of the function and not during its definition , then we 're missing the call log instructions of the function returned . To avoid this trap , we need to rebind the resulting scope output struct by eta - expanding the functions to insert logging instructions to wrap this function call in a flurry of log tags. Specifically, we are mascarading this scope call as a function call. In a normal function call, the log parser expects the output of the function to be defined as a default, hence the production of the output should yield a PosRecordIfTrueBool (which is not the case here). To remedy this absence we fabricate a fake PosRecordIfTrueBool attached to a silent let binding to "true" before returning the output value. But this is not sufficient. Indeed for the tricky case of [tests/test_scope/scope_call3.catala_en], when a scope returns a function, because we insert loggins calls at the call site of the function and not during its definition, then we're missing the call log instructions of the function returned. To avoid this trap, we need to rebind the resulting scope output struct by eta-expanding the functions to insert logging instructions*) let result_var = Var.make "result" in let result_eta_expanded_var = Var.make "result" in (* result_eta_expanded = { struct_output_function_field = lambda x -> log (struct_output.struct_output_function_field x) ... } *) let result_eta_expanded = Expr.estruct sc_sig.scope_sig_output_struct (StructField.Map.mapi (fun field typ -> let original_field_expr = Expr.estructaccess (Expr.make_var result_var (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e))) field sc_sig.scope_sig_output_struct (Expr.with_ty m typ) in match Marked.unmark typ with | TArrow (ts_in, t_out) -> (* Here the output scope struct field is a function so we eta-expand it and insert logging instructions. Invariant: works because there is no partial evaluation. *) let params_vars = ListLabels.mapi ts_in ~f:(fun i _ -> Var.make ("param" ^ string_of_int i)) in let f_markings = [ScopeName.get_info scope; StructField.get_info field] in Expr.make_abs (Array.of_list params_vars) (tag_with_log_entry (tag_with_log_entry (Expr.eapp (tag_with_log_entry original_field_expr BeginCall f_markings) (ListLabels.mapi (List.combine params_vars ts_in) ~f:(fun i (param_var, t_in) -> tag_with_log_entry (Expr.make_var param_var (Expr.with_ty m t_in)) (VarDef (Marked.unmark t_in)) (f_markings @ [ Marked.mark (Expr.pos e) ("input" ^ string_of_int i); ]))) (Expr.with_ty m t_out)) (VarDef (Marked.unmark t_out)) (f_markings @ [Marked.mark (Expr.pos e) "output"])) EndCall f_markings) ts_in (Expr.pos e) | _ -> original_field_expr) (StructName.Map.find sc_sig.scope_sig_output_struct ctx.structs)) (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e)) in (* Here we have to go through an if statement that records a decision being taken with a log. We can't just do a let-in with the true boolean value enclosed in the log because it might get optimized by a compiler later down the chain. *) (* if_then_else_returned = if log true then result_eta_expanded else emptyError *) let if_then_else_returned = Expr.eifthenelse (tag_with_log_entry (Expr.box (Marked.mark (Expr.with_ty m (TLit TBool, Expr.pos e)) (ELit (LBool true)))) PosRecordIfTrueBool direct_output_info) (Expr.make_var result_eta_expanded_var (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e))) (Expr.box (Marked.mark (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e)) (ELit LEmptyError))) (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e)) in (* let result_var = calling_expr in let result_eta_expanded_var = result_eta_expaneded in log (if_then_else_returned ) *) Expr.make_let_in result_var (TStruct sc_sig.scope_sig_output_struct, Expr.pos e) calling_expr (Expr.make_let_in result_eta_expanded_var (TStruct sc_sig.scope_sig_output_struct, Expr.pos e) result_eta_expanded (tag_with_log_entry (tag_with_log_entry if_then_else_returned (VarDef (TStruct sc_sig.scope_sig_output_struct)) direct_output_info) EndCall [ScopeName.get_info scope; Marked.mark (Expr.pos e) "direct"]) (Expr.pos e)) (Expr.pos e) | EApp { f; args } -> (* We insert various log calls to record arguments and outputs of user-defined functions belonging to scopes *) let e1_func = translate_expr ctx f in let markings = match ctx.scope_name, Marked.unmark f with | Some sname, ELocation loc -> ( match loc with | ScopelangScopeVar (v, _) -> [ScopeName.get_info sname; ScopeVar.get_info v] | SubScopeVar (s, _, (v, _)) -> [ScopeName.get_info s; ScopeVar.get_info v] | ToplevelVar _ -> []) | _ -> [] in let e1_func = match markings with | [] -> e1_func | m -> tag_with_log_entry e1_func BeginCall m in let new_args = List.map (translate_expr ctx) args in let input_typs, output_typ = (* NOTE: this is a temporary solution, it works because it's assume that all function calls are from scope variable. However, this will change -- for more information see #discussion_r898851693. *) let retrieve_in_and_out_typ_or_any var vars = let _, typ, _ = ScopeVar.Map.find (Marked.unmark var) vars in match typ with | TArrow (marked_input_typ, marked_output_typ) -> ( List.map Marked.unmark marked_input_typ, Marked.unmark marked_output_typ ) | _ -> ListLabels.map new_args ~f:(fun _ -> TAny), TAny in match Marked.unmark f with | ELocation (ScopelangScopeVar var) -> retrieve_in_and_out_typ_or_any var ctx.scope_vars | ELocation (SubScopeVar (_, sname, var)) -> ctx.subscope_vars |> SubScopeName.Map.find (Marked.unmark sname) |> retrieve_in_and_out_typ_or_any var | ELocation (ToplevelVar tvar) -> ( let _, typ = TopdefName.Map.find (Marked.unmark tvar) ctx.toplevel_vars in match typ with | TArrow (tin, (tout, _)) -> List.map Marked.unmark tin, tout | _ -> Errors.raise_spanned_error (Expr.pos e) "Application of non-function toplevel variable") | _ -> ListLabels.map new_args ~f:(fun _ -> TAny), TAny in Cli.debug_format " new_args % d , input_typs : % d , input_typs % a " ( List.length ) ( List.length input_typs ) ( Format.pp_print_list Print.typ_debug ) ( List.map ( Marked.mark Pos.no_pos ) input_typs ) ; (List.length new_args) (List.length input_typs) (Format.pp_print_list Print.typ_debug) (List.map (Marked.mark Pos.no_pos) input_typs); *) let new_args = ListLabels.mapi (List.combine new_args input_typs) ~f:(fun i (new_arg, input_typ) -> match markings with | _ :: _ as m -> tag_with_log_entry new_arg (VarDef input_typ) (m @ [Marked.mark (Expr.pos e) ("input" ^ string_of_int i)]) | _ -> new_arg) in let new_e = Expr.eapp e1_func new_args m in let new_e = match markings with | [] -> new_e | m -> tag_with_log_entry (tag_with_log_entry new_e (VarDef output_typ) (m @ [Marked.mark (Expr.pos e) "output"])) EndCall m in new_e | EAbs { binder; tys } -> let xs, body = Bindlib.unmbind binder in let new_xs = Array.map (fun x -> Var.make (Bindlib.name_of x)) xs in let both_xs = Array.map2 (fun x new_x -> x, new_x) xs new_xs in let body = translate_expr { ctx with local_vars = Array.fold_left (fun local_vars (x, new_x) -> Var.Map.add x new_x local_vars) ctx.local_vars both_xs; } body in let binder = Expr.bind new_xs body in Expr.eabs binder tys m | EDefault { excepts; just; cons } -> let excepts = collapse_similar_outcomes excepts in Expr.edefault (List.map (translate_expr ctx) excepts) (translate_expr ctx just) (translate_expr ctx cons) m | ELocation (ScopelangScopeVar a) -> let v, _, _ = ScopeVar.Map.find (Marked.unmark a) ctx.scope_vars in Expr.evar v m | ELocation (SubScopeVar (_, s, a)) -> ( try let v, _, _ = ScopeVar.Map.find (Marked.unmark a) (SubScopeName.Map.find (Marked.unmark s) ctx.subscope_vars) in Expr.evar v m with Not_found -> Errors.raise_multispanned_error [ Some "Incriminated variable usage:", Expr.pos e; ( Some "Incriminated subscope variable declaration:", Marked.get_mark (ScopeVar.get_info (Marked.unmark a)) ); ( Some "Incriminated subscope declaration:", Marked.get_mark (SubScopeName.get_info (Marked.unmark s)) ); ] "The variable %a.%a cannot be used here, as it is not part of subscope \ %a's results. Maybe you forgot to qualify it as an output?" SubScopeName.format_t (Marked.unmark s) ScopeVar.format_t (Marked.unmark a) SubScopeName.format_t (Marked.unmark s)) | ELocation (ToplevelVar v) -> let v, _ = TopdefName.Map.find (Marked.unmark v) ctx.toplevel_vars in Expr.evar v m | EIfThenElse { cond; etrue; efalse } -> Expr.eifthenelse (translate_expr ctx cond) (translate_expr ctx etrue) (translate_expr ctx efalse) m | EOp { op; tys } -> Expr.eop (Operator.translate op) tys m | EErrorOnEmpty e' -> Expr.eerroronempty (translate_expr ctx e') m | EArray es -> Expr.earray (List.map (translate_expr ctx) es) m (** The result of a rule translation is a list of assignment, with variables and expressions. We also return the new translation context available after the assignment to use in later rule translations. The list is actually a continuation yielding a [Dcalc.scope_body_expr] by giving it what should come later in the chain of let-bindings. *) let translate_rule (ctx : 'm ctx) (rule : 'm Scopelang.Ast.rule) ((sigma_name, pos_sigma) : Uid.MarkedString.info) : ('m Ast.expr scope_body_expr Bindlib.box -> 'm Ast.expr scope_body_expr Bindlib.box) * 'm ctx = match rule with | Definition ((ScopelangScopeVar a, var_def_pos), tau, a_io, e) -> let pos_mark, pos_mark_as = pos_mark_mk e in let a_name = ScopeVar.get_info (Marked.unmark a) in let a_var = Var.make (Marked.unmark a_name) in let new_e = translate_expr ctx e in let a_expr = Expr.make_var a_var (pos_mark var_def_pos) in let merged_expr = match Marked.unmark a_io.io_input with | OnlyInput -> failwith "should not happen" (* scopelang should not contain any definitions of input only variables *) | Reentrant -> merge_defaults ~is_func: (match Marked.unmark tau with TArrow _ -> true | _ -> false) a_expr new_e | NoInput -> Expr.eerroronempty new_e (pos_mark_as a_name) in let merged_expr = tag_with_log_entry merged_expr (VarDef (Marked.unmark tau)) [sigma_name, pos_sigma; a_name] in ( (fun next -> Bindlib.box_apply2 (fun next merged_expr -> ScopeLet { scope_let_next = next; scope_let_typ = tau; scope_let_expr = merged_expr; scope_let_kind = ScopeVarDefinition; scope_let_pos = Marked.get_mark a; }) (Bindlib.bind_var a_var next) (Expr.Box.lift merged_expr)), { ctx with scope_vars = ScopeVar.Map.add (Marked.unmark a) (a_var, Marked.unmark tau, a_io) ctx.scope_vars; } ) | Definition ( (SubScopeVar (_subs_name, subs_index, subs_var), var_def_pos), tau, a_io, e ) -> let a_name = Marked.map_under_mark (fun str -> str ^ "." ^ Marked.unmark (ScopeVar.get_info (Marked.unmark subs_var))) (SubScopeName.get_info (Marked.unmark subs_index)) in let a_var = Var.make (Marked.unmark a_name) in let new_e = tag_with_log_entry (translate_expr ctx e) (VarDef (Marked.unmark tau)) [sigma_name, pos_sigma; a_name] in let is_func = match Marked.unmark tau with TArrow _ -> true | _ -> false in let thunked_or_nonempty_new_e = thunk_scope_arg ~is_func a_io.Desugared.Ast.io_input new_e in ( (fun next -> Bindlib.box_apply2 (fun next thunked_or_nonempty_new_e -> ScopeLet { scope_let_next = next; scope_let_pos = Marked.get_mark a_name; scope_let_typ = (match Marked.unmark a_io.io_input with | NoInput -> failwith "should not happen" | OnlyInput -> tau | Reentrant -> if is_func then tau else TArrow ([TLit TUnit, var_def_pos], tau), var_def_pos); scope_let_expr = thunked_or_nonempty_new_e; scope_let_kind = SubScopeVarDefinition; }) (Bindlib.bind_var a_var next) (Expr.Box.lift thunked_or_nonempty_new_e)), { ctx with subscope_vars = SubScopeName.Map.update (Marked.unmark subs_index) (fun map -> match map with | Some map -> Some (ScopeVar.Map.add (Marked.unmark subs_var) (a_var, Marked.unmark tau, a_io) map) | None -> Some (ScopeVar.Map.singleton (Marked.unmark subs_var) (a_var, Marked.unmark tau, a_io))) ctx.subscope_vars; } ) | Definition ((ToplevelVar _, _), _, _, _) -> assert false (* A global variable can't be defined locally. The [Definition] constructor could be made more specific to avoid this case, but the added complexity didn't seem worth it *) | Call (subname, subindex, m) -> let subscope_sig = ScopeName.Map.find subname ctx.scopes_parameters in let all_subscope_vars = subscope_sig.scope_sig_local_vars in let all_subscope_input_vars = List.filter (fun var_ctx -> match Marked.unmark var_ctx.scope_var_io.Desugared.Ast.io_input with | NoInput -> false | _ -> true) all_subscope_vars in let all_subscope_output_vars = List.filter (fun var_ctx -> Marked.unmark var_ctx.scope_var_io.Desugared.Ast.io_output) all_subscope_vars in let scope_dcalc_var = subscope_sig.scope_sig_scope_var in let called_scope_input_struct = subscope_sig.scope_sig_input_struct in let called_scope_return_struct = subscope_sig.scope_sig_output_struct in let subscope_vars_defined = try SubScopeName.Map.find subindex ctx.subscope_vars with Not_found -> ScopeVar.Map.empty in let subscope_var_not_yet_defined subvar = not (ScopeVar.Map.mem subvar subscope_vars_defined) in let pos_call = Marked.get_mark (SubScopeName.get_info subindex) in let subscope_args = List.fold_left (fun acc (subvar : scope_var_ctx) -> let e = if subscope_var_not_yet_defined subvar.scope_var_name then (* This is a redundant check. Normally, all subscope variables should have been defined (even an empty definition, if they're not defined by any rule in the source code) by the translation from desugared to the scope language. *) Expr.empty_thunked_term m else let a_var, _, _ = ScopeVar.Map.find subvar.scope_var_name subscope_vars_defined in Expr.make_var a_var (mark_tany m pos_call) in let field = (ScopeVar.Map.find subvar.scope_var_name subscope_sig.scope_sig_in_fields) .scope_input_name in StructField.Map.add field e acc) StructField.Map.empty all_subscope_input_vars in let subscope_struct_arg = Expr.estruct called_scope_input_struct subscope_args (mark_tany m pos_call) in let all_subscope_output_vars_dcalc = List.map (fun (subvar : scope_var_ctx) -> let sub_dcalc_var = Var.make (Marked.unmark (SubScopeName.get_info subindex) ^ "." ^ Marked.unmark (ScopeVar.get_info subvar.scope_var_name)) in subvar, sub_dcalc_var) all_subscope_output_vars in let subscope_func = tag_with_log_entry (Expr.make_var scope_dcalc_var (mark_tany m pos_call)) BeginCall [ sigma_name, pos_sigma; SubScopeName.get_info subindex; ScopeName.get_info subname; ] in let call_expr = tag_with_log_entry (Expr.eapp subscope_func [subscope_struct_arg] (mark_tany m pos_call)) EndCall [ sigma_name, pos_sigma; SubScopeName.get_info subindex; ScopeName.get_info subname; ] in let result_tuple_var = Var.make "result" in let result_tuple_typ = TStruct called_scope_return_struct, pos_sigma in let call_scope_let next = Bindlib.box_apply2 (fun next call_expr -> ScopeLet { scope_let_next = next; scope_let_pos = pos_sigma; scope_let_kind = CallingSubScope; scope_let_typ = result_tuple_typ; scope_let_expr = call_expr; }) (Bindlib.bind_var result_tuple_var next) (Expr.Box.lift call_expr) in let result_bindings_lets next = List.fold_right (fun (var_ctx, v) next -> let field = ScopeVar.Map.find var_ctx.scope_var_name subscope_sig.scope_sig_out_fields in Bindlib.box_apply2 (fun next r -> ScopeLet { scope_let_next = next; scope_let_pos = pos_sigma; scope_let_typ = var_ctx.scope_var_typ, pos_sigma; scope_let_kind = DestructuringSubScopeResults; scope_let_expr = ( EStructAccess { name = called_scope_return_struct; e = r; field }, mark_tany m pos_sigma ); }) (Bindlib.bind_var v next) (Expr.Box.lift (Expr.make_var result_tuple_var (mark_tany m pos_sigma)))) all_subscope_output_vars_dcalc next in ( (fun next -> call_scope_let (result_bindings_lets next)), { ctx with subscope_vars = SubScopeName.Map.add subindex (List.fold_left (fun acc (var_ctx, dvar) -> ScopeVar.Map.add var_ctx.scope_var_name (dvar, var_ctx.scope_var_typ, var_ctx.scope_var_io) acc) ScopeVar.Map.empty all_subscope_output_vars_dcalc) ctx.subscope_vars; } ) | Assertion e -> let new_e = translate_expr ctx e in let scope_let_pos = Expr.pos e in let scope_let_typ = TLit TUnit, scope_let_pos in ( (fun next -> Bindlib.box_apply2 (fun next new_e -> ScopeLet { scope_let_next = next; scope_let_pos; scope_let_typ; scope_let_expr = To ensure that we throw an error if the value is not defined , we add an check " ErrorOnEmpty " here . defined, we add an check "ErrorOnEmpty" here. *) Marked.mark (Expr.map_ty (fun _ -> scope_let_typ) (Marked.get_mark e)) (EAssert (Marked.same_mark_as (EErrorOnEmpty new_e) e)); scope_let_kind = Assertion; }) (Bindlib.bind_var (Var.make "_") next) (Expr.Box.lift new_e)), ctx ) let translate_rules (ctx : 'm ctx) (rules : 'm Scopelang.Ast.rule list) ((sigma_name, pos_sigma) : Uid.MarkedString.info) (mark : 'm mark) (scope_sig : 'm scope_sig_ctx) : 'm Ast.expr scope_body_expr Bindlib.box * 'm ctx = let scope_lets, new_ctx = List.fold_left (fun (scope_lets, ctx) rule -> let new_scope_lets, new_ctx = translate_rule ctx rule (sigma_name, pos_sigma) in (fun next -> scope_lets (new_scope_lets next)), new_ctx) ((fun next -> next), ctx) rules in let return_exp = Expr.estruct scope_sig.scope_sig_output_struct (ScopeVar.Map.fold (fun var (dcalc_var, _, io) acc -> if Marked.unmark io.Desugared.Ast.io_output then let field = ScopeVar.Map.find var scope_sig.scope_sig_out_fields in StructField.Map.add field (Expr.make_var dcalc_var (mark_tany mark pos_sigma)) acc else acc) new_ctx.scope_vars StructField.Map.empty) (mark_tany mark pos_sigma) in ( scope_lets (Bindlib.box_apply (fun return_exp -> Result return_exp) (Expr.Box.lift return_exp)), new_ctx ) let translate_scope_decl (ctx : 'm ctx) (scope_name : ScopeName.t) (sigma : 'm Scopelang.Ast.scope_decl) : 'm Ast.expr scope_body Bindlib.box * struct_ctx = let sigma_info = ScopeName.get_info sigma.scope_decl_name in let scope_sig = ScopeName.Map.find sigma.scope_decl_name ctx.scopes_parameters in let scope_variables = scope_sig.scope_sig_local_vars in let ctx = { ctx with scope_name = Some scope_name } in let ctx = (* the context must be initialized for fresh variables for all only-input scope variables *) List.fold_left (fun ctx scope_var -> match Marked.unmark scope_var.scope_var_io.io_input with | OnlyInput -> let scope_var_name = ScopeVar.get_info scope_var.scope_var_name in let scope_var_dcalc = Var.make (Marked.unmark scope_var_name) in { ctx with scope_vars = ScopeVar.Map.add scope_var.scope_var_name ( scope_var_dcalc, scope_var.scope_var_typ, scope_var.scope_var_io ) ctx.scope_vars; } | _ -> ctx) ctx scope_variables in let scope_input_var = scope_sig.scope_sig_input_var in let scope_input_struct_name = scope_sig.scope_sig_input_struct in let scope_return_struct_name = scope_sig.scope_sig_output_struct in let pos_sigma = Marked.get_mark sigma_info in let rules_with_return_expr, ctx = translate_rules ctx sigma.scope_decl_rules sigma_info sigma.scope_mark scope_sig in let scope_variables = List.map (fun var_ctx -> let dcalc_x, _, _ = ScopeVar.Map.find var_ctx.scope_var_name ctx.scope_vars in var_ctx, dcalc_x) scope_variables in (* first we create variables from the fields of the input struct *) let scope_input_variables = List.filter (fun (var_ctx, _) -> match Marked.unmark var_ctx.scope_var_io.io_input with | NoInput -> false | _ -> true) scope_variables in let input_var_typ (var_ctx : scope_var_ctx) = match Marked.unmark var_ctx.scope_var_io.io_input with | OnlyInput -> var_ctx.scope_var_typ, pos_sigma | Reentrant -> ( match var_ctx.scope_var_typ with | TArrow _ -> var_ctx.scope_var_typ, pos_sigma | _ -> ( TArrow ([TLit TUnit, pos_sigma], (var_ctx.scope_var_typ, pos_sigma)), pos_sigma )) | NoInput -> failwith "should not happen" in let input_destructurings next = List.fold_right (fun (var_ctx, v) next -> let field = (ScopeVar.Map.find var_ctx.scope_var_name scope_sig.scope_sig_in_fields) .scope_input_name in Bindlib.box_apply2 (fun next r -> ScopeLet { scope_let_kind = DestructuringInputStruct; scope_let_next = next; scope_let_pos = pos_sigma; scope_let_typ = input_var_typ var_ctx; scope_let_expr = ( EStructAccess { name = scope_input_struct_name; e = r; field }, mark_tany sigma.scope_mark pos_sigma ); }) (Bindlib.bind_var v next) (Expr.Box.lift (Expr.make_var scope_input_var (mark_tany sigma.scope_mark pos_sigma)))) scope_input_variables next in let field_map = List.fold_left (fun acc (var_ctx, _) -> let var = var_ctx.scope_var_name in let field = (ScopeVar.Map.find var scope_sig.scope_sig_in_fields).scope_input_name in StructField.Map.add field (input_var_typ var_ctx) acc) StructField.Map.empty scope_input_variables in let new_struct_ctx = StructName.Map.singleton scope_input_struct_name field_map in ( Bindlib.box_apply (fun scope_body_expr -> { scope_body_expr; scope_body_input_struct = scope_input_struct_name; scope_body_output_struct = scope_return_struct_name; }) (Bindlib.bind_var scope_input_var (input_destructurings rules_with_return_expr)), new_struct_ctx ) let translate_program (prgm : 'm Scopelang.Ast.program) : 'm Ast.program = let defs_dependencies = Scopelang.Dependency.build_program_dep_graph prgm in Scopelang.Dependency.check_for_cycle_in_defs defs_dependencies; let defs_ordering = Scopelang.Dependency.get_defs_ordering defs_dependencies in let decl_ctx = prgm.program_ctx in let sctx : 'm scope_sigs_ctx = ScopeName.Map.mapi (fun scope_name scope -> let scope_dvar = Var.make (Marked.unmark (ScopeName.get_info scope.Scopelang.Ast.scope_decl_name)) in let scope_return = ScopeName.Map.find scope_name decl_ctx.ctx_scopes in let scope_input_var = Var.make (Marked.unmark (ScopeName.get_info scope_name) ^ "_in") in let scope_input_struct_name = StructName.fresh (Marked.map_under_mark (fun s -> s ^ "_in") (ScopeName.get_info scope_name)) in let scope_sig_in_fields = ScopeVar.Map.filter_map (fun dvar (typ, vis) -> match Marked.unmark vis.Desugared.Ast.io_input with | NoInput -> None | OnlyInput | Reentrant -> let info = ScopeVar.get_info dvar in let s = Marked.unmark info ^ "_in" in Some { scope_input_name = StructField.fresh (s, Marked.get_mark info); scope_input_io = vis.Desugared.Ast.io_input; scope_input_typ = Marked.unmark typ; }) scope.scope_sig in { scope_sig_local_vars = List.map (fun (scope_var, (tau, vis)) -> { scope_var_name = scope_var; scope_var_typ = Marked.unmark tau; scope_var_io = vis; }) (ScopeVar.Map.bindings scope.scope_sig); scope_sig_scope_var = scope_dvar; scope_sig_input_var = scope_input_var; scope_sig_input_struct = scope_input_struct_name; scope_sig_output_struct = scope_return.out_struct_name; scope_sig_in_fields; scope_sig_out_fields = scope_return.out_struct_fields; }) prgm.Scopelang.Ast.program_scopes in let top_ctx = let toplevel_vars = TopdefName.Map.mapi (fun name (_, ty) -> Var.make (Marked.unmark (TopdefName.get_info name)), Marked.unmark ty) prgm.Scopelang.Ast.program_topdefs in { structs = decl_ctx.ctx_structs; enums = decl_ctx.ctx_enums; scope_name = None; scopes_parameters = sctx; scope_vars = ScopeVar.Map.empty; subscope_vars = SubScopeName.Map.empty; local_vars = Var.Map.empty; toplevel_vars; } in (* the resulting expression is the list of definitions of all the scopes, ending with the top-level scope. The decl_ctx is filled in left-to-right order, then the chained scopes aggregated from the right. *) let rec translate_defs ctx = function | [] -> Bindlib.box Nil, ctx | def :: next -> let ctx, dvar, def = match def with | Scopelang.Dependency.Topdef gname -> let expr, ty = TopdefName.Map.find gname prgm.program_topdefs in let expr = translate_expr ctx expr in ( ctx, fst (TopdefName.Map.find gname ctx.toplevel_vars), Bindlib.box_apply (fun e -> Topdef (gname, ty, e)) (Expr.Box.lift expr) ) | Scopelang.Dependency.Scope scope_name -> let scope = ScopeName.Map.find scope_name prgm.program_scopes in let scope_body, scope_in_struct = translate_scope_decl ctx scope_name scope in ( { ctx with structs = StructName.Map.union (fun _ _ -> assert false) ctx.structs scope_in_struct; }, (ScopeName.Map.find scope_name sctx).scope_sig_scope_var, Bindlib.box_apply (fun body -> ScopeDef (scope_name, body)) scope_body ) in let scope_next, ctx = translate_defs ctx next in let next_bind = Bindlib.bind_var dvar scope_next in ( Bindlib.box_apply2 (fun item next_bind -> Cons (item, next_bind)) def next_bind, ctx ) in let items, ctx = translate_defs top_ctx defs_ordering in { code_items = Bindlib.unbox items; decl_ctx = { decl_ctx with ctx_structs = ctx.structs }; }
null
https://raw.githubusercontent.com/CatalaLang/catala/5bd140ae5fb2a997a578b9cd67a932c4a8733526/compiler/dcalc/from_scopelang.ml
ocaml
* List of scope variables * Scope input * Scope output * Mapping between the input scope variables and the input struct fields. * Mapping between the output scope variables and the output struct fields. TODO: could likely be removed now that we have it in the program ctx Expression argument is used as a type witness, its type and positions aren't used we have to correctly propagate types when doing this rewriting should not happen because there should always be a lambda at the beginning of a default with a function type In a list of exceptions, it is normally an error if more than a single one apply at the same time. This relaxes this constraint slightly, allowing a conflict if all the triggered conflicting exception yield syntactically equal results (and as long as none of these exceptions have exceptions themselves) NOTE: the choice of the exception that will be triggered and show in the trace is arbitrary (but deterministic). For "context" (or reentrant) variables, we thunk them as [(fun () -> e)] so that we can put them in default terms at the initialisation of the function body, allowing an empty error to recover the default value. we don't need to thunk expressions that are already functions FIXME: these checks should probably be moved to a better place calling_expr = scope_function scope_input_struct result_eta_expanded = { struct_output_function_field = lambda x -> log (struct_output.struct_output_function_field x) ... } Here the output scope struct field is a function so we eta-expand it and insert logging instructions. Invariant: works because there is no partial evaluation. Here we have to go through an if statement that records a decision being taken with a log. We can't just do a let-in with the true boolean value enclosed in the log because it might get optimized by a compiler later down the chain. if_then_else_returned = if log true then result_eta_expanded else emptyError let result_var = calling_expr in let result_eta_expanded_var = result_eta_expaneded in log (if_then_else_returned ) We insert various log calls to record arguments and outputs of user-defined functions belonging to scopes NOTE: this is a temporary solution, it works because it's assume that all function calls are from scope variable. However, this will change -- for more information see #discussion_r898851693. * The result of a rule translation is a list of assignment, with variables and expressions. We also return the new translation context available after the assignment to use in later rule translations. The list is actually a continuation yielding a [Dcalc.scope_body_expr] by giving it what should come later in the chain of let-bindings. scopelang should not contain any definitions of input only variables A global variable can't be defined locally. The [Definition] constructor could be made more specific to avoid this case, but the added complexity didn't seem worth it This is a redundant check. Normally, all subscope variables should have been defined (even an empty definition, if they're not defined by any rule in the source code) by the translation from desugared to the scope language. the context must be initialized for fresh variables for all only-input scope variables first we create variables from the fields of the input struct the resulting expression is the list of definitions of all the scopes, ending with the top-level scope. The decl_ctx is filled in left-to-right order, then the chained scopes aggregated from the right.
This file is part of the Catala compiler , a specification language for tax and social benefits computation rules . Copyright ( C ) 2020 , contributor : < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . and social benefits computation rules. Copyright (C) 2020 Inria, contributor: Denis Merigoux <> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) open Catala_utils open Shared_ast type scope_var_ctx = { scope_var_name : ScopeVar.t; scope_var_typ : naked_typ; scope_var_io : Desugared.Ast.io; } type scope_input_var_ctx = { scope_input_name : StructField.t; scope_input_io : Desugared.Ast.io_input Marked.pos; scope_input_typ : naked_typ; } type 'm scope_sig_ctx = { * Var representing the scope scope_sig_input_var : 'm Ast.expr Var.t; * Var representing the scope input inside the scope func scope_sig_in_fields : scope_input_var_ctx ScopeVar.Map.t; scope_sig_out_fields : StructField.t ScopeVar.Map.t; } type 'm scope_sigs_ctx = 'm scope_sig_ctx ScopeName.Map.t type 'm ctx = { structs : struct_ctx; enums : enum_ctx; scope_name : ScopeName.t option; scopes_parameters : 'm scope_sigs_ctx; toplevel_vars : ('m Ast.expr Var.t * naked_typ) TopdefName.Map.t; scope_vars : ('m Ast.expr Var.t * naked_typ * Desugared.Ast.io) ScopeVar.Map.t; subscope_vars : ('m Ast.expr Var.t * naked_typ * Desugared.Ast.io) ScopeVar.Map.t SubScopeName.Map.t; local_vars : ('m Scopelang.Ast.expr, 'm Ast.expr Var.t) Var.Map.t; } let mark_tany m pos = Expr.with_ty m (Marked.mark pos TAny) ~pos let pos_mark_mk (type a m) (e : (a, m mark) gexpr) : (Pos.t -> m mark) * ((_, Pos.t) Marked.t -> m mark) = let pos_mark pos = Expr.map_mark (fun _ -> pos) (fun _ -> TAny, pos) (Marked.get_mark e) in let pos_mark_as e = pos_mark (Marked.get_mark e) in pos_mark, pos_mark_as let merge_defaults ~(is_func : bool) (caller : (dcalc, 'm mark) boxed_gexpr) (callee : (dcalc, 'm mark) boxed_gexpr) : (dcalc, 'm mark) boxed_gexpr = the merging of the two defaults , from the reentrant caller and the callee , is straightfoward in the general case and a little subtler when the variable being defined is a function . is straightfoward in the general case and a little subtler when the variable being defined is a function. *) if is_func then let m_callee = Marked.get_mark callee in let unboxed_callee = Expr.unbox callee in match Marked.unmark unboxed_callee with | EAbs { binder; tys } -> let vars, body = Bindlib.unmbind binder in let m_body = Marked.get_mark body in let caller = let m = Marked.get_mark caller in let pos = Expr.mark_pos m in Expr.make_app caller (List.map2 (fun (var : (dcalc, 'm mark) naked_gexpr Bindlib.var) ty -> Expr.evar var (Expr.with_ty m_body ~pos:(Expr.mark_pos m_body) ty)) (Array.to_list vars) tys) pos in let ltrue = Expr.elit (LBool true) (Expr.with_ty m_callee (Marked.mark (Expr.mark_pos m_callee) (TLit TBool))) in let d = Expr.edefault [caller] ltrue (Expr.rebox body) m_body in Expr.make_abs vars (Expr.eerroronempty d m_body) tys (Expr.mark_pos m_callee) | _ -> assert false else let caller = let m = Marked.get_mark caller in let pos = Expr.mark_pos m in Expr.make_app caller [Expr.elit LUnit (Expr.with_ty m (Marked.mark pos (TLit TUnit)))] pos in let body = let m = Marked.get_mark callee in let ltrue = Expr.elit (LBool true) (Expr.with_ty m (Marked.mark (Expr.mark_pos m) (TLit TBool))) in Expr.eerroronempty (Expr.edefault [caller] ltrue callee m) m in body let tag_with_log_entry (e : 'm Ast.expr boxed) (l : log_entry) (markings : Uid.MarkedString.info list) : 'm Ast.expr boxed = let m = mark_tany (Marked.get_mark e) (Expr.pos e) in Expr.eapp (Expr.eop (Log (l, markings)) [TAny, Expr.pos e] m) [e] m let collapse_similar_outcomes (type m) (excepts : m Scopelang.Ast.expr list) : m Scopelang.Ast.expr list = let module ExprMap = Map.Make (struct type t = m Scopelang.Ast.expr let compare = Expr.compare end) in let cons_map = List.fold_left (fun map -> function | (EDefault { excepts = []; cons; _ }, _) as e -> ExprMap.update cons (fun prev -> Some (e :: Option.value ~default:[] prev)) map | _ -> map) ExprMap.empty excepts in let _, excepts = List.fold_right (fun e (cons_map, excepts) -> match e with | EDefault { excepts = []; cons; _ }, _ -> let collapsed_exc = List.fold_left (fun acc -> function | EDefault { excepts = []; just; cons }, pos -> [EDefault { excepts = acc; just; cons }, pos] | _ -> assert false) [] (ExprMap.find cons cons_map) in ExprMap.add cons [] cons_map, collapsed_exc @ excepts | e -> cons_map, e :: excepts) excepts (cons_map, []) in excepts let thunk_scope_arg ~is_func io_in e = let silent_var = Var.make "_" in let pos = Marked.get_mark io_in in match Marked.unmark io_in with | Desugared.Ast.NoInput -> invalid_arg "thunk_scope_arg" | Desugared.Ast.OnlyInput -> Expr.eerroronempty e (Marked.get_mark e) | Desugared.Ast.Reentrant -> if is_func then e else Expr.make_abs [| silent_var |] e [TLit TUnit, pos] pos let rec translate_expr (ctx : 'm ctx) (e : 'm Scopelang.Ast.expr) : 'm Ast.expr boxed = let m = Marked.get_mark e in match Marked.unmark e with | EVar v -> Expr.evar (Var.Map.find v ctx.local_vars) m | ELit (( LBool _ | LEmptyError | LInt _ | LRat _ | LMoney _ | LUnit | LDate _ | LDuration _ ) as l) -> Expr.elit l m | EStruct { name; fields } -> let fields = StructField.Map.map (translate_expr ctx) fields in Expr.estruct name fields m | EStructAccess { e; field; name } -> Expr.estructaccess (translate_expr ctx e) field name m | ETuple es -> Expr.etuple (List.map (translate_expr ctx) es) m | ETupleAccess { e; index; size } -> Expr.etupleaccess (translate_expr ctx e) index size m | EInj { e; cons; name } -> let e' = translate_expr ctx e in Expr.einj e' cons name m | EMatch { e = e1; name; cases = e_cases } -> let enum_sig = EnumName.Map.find name ctx.enums in let d_cases, remaining_e_cases = EnumConstructor.Map.fold (fun constructor _ (d_cases, e_cases) -> let case_e = try EnumConstructor.Map.find constructor e_cases with Not_found -> Errors.raise_spanned_error (Expr.pos e) "The constructor %a of enum %a is missing from this pattern \ matching" EnumConstructor.format_t constructor EnumName.format_t name in let case_d = translate_expr ctx case_e in ( EnumConstructor.Map.add constructor case_d d_cases, EnumConstructor.Map.remove constructor e_cases )) enum_sig (EnumConstructor.Map.empty, e_cases) in if not (EnumConstructor.Map.is_empty remaining_e_cases) then Errors.raise_spanned_error (Expr.pos e) "Pattern matching is incomplete for enum %a: missing cases %a" EnumName.format_t name (Format.pp_print_list ~pp_sep:(fun fmt () -> Format.fprintf fmt ", ") (fun fmt (case_name, _) -> EnumConstructor.format_t fmt case_name)) (EnumConstructor.Map.bindings remaining_e_cases); let e1 = translate_expr ctx e1 in Expr.ematch e1 name d_cases m | EScopeCall { scope; args } -> let pos = Expr.mark_pos m in let sc_sig = ScopeName.Map.find scope ctx.scopes_parameters in let in_var_map = ScopeVar.Map.merge (fun var_name (str_field : scope_input_var_ctx option) expr -> let expr = match str_field, expr with | Some { scope_input_io = Desugared.Ast.Reentrant, _; _ }, None -> Some (Expr.unbox (Expr.elit LEmptyError (mark_tany m pos))) | _ -> expr in match str_field, expr with | None, None -> None | Some var_ctx, Some e -> Some ( var_ctx.scope_input_name, thunk_scope_arg ~is_func: (match var_ctx.scope_input_typ with | TArrow _ -> true | _ -> false) var_ctx.scope_input_io (translate_expr ctx e) ) | Some var_ctx, None -> Errors.raise_multispanned_error [ None, pos; ( Some "Declaration of the missing input variable", Marked.get_mark (StructField.get_info var_ctx.scope_input_name) ); ] "Definition of input variable '%a' missing in this scope call" ScopeVar.format_t var_name | None, Some _ -> Errors.raise_multispanned_error [ None, pos; ( Some "Declaration of scope '%a'", Marked.get_mark (ScopeName.get_info scope) ); ] "Unknown input variable '%a' in scope call of '%a'" ScopeVar.format_t var_name ScopeName.format_t scope) sc_sig.scope_sig_in_fields args in let field_map = ScopeVar.Map.fold (fun _ (fld, e) acc -> StructField.Map.add fld e acc) in_var_map StructField.Map.empty in let arg_struct = Expr.estruct sc_sig.scope_sig_input_struct field_map (mark_tany m pos) in let called_func = tag_with_log_entry (Expr.evar sc_sig.scope_sig_scope_var (mark_tany m pos)) BeginCall [ScopeName.get_info scope; Marked.mark (Expr.pos e) "direct"] in let single_arg = tag_with_log_entry arg_struct (VarDef (TStruct sc_sig.scope_sig_input_struct)) [ ScopeName.get_info scope; Marked.mark (Expr.pos e) "direct"; Marked.mark (Expr.pos e) "input"; ] in let direct_output_info = [ ScopeName.get_info scope; Marked.mark (Expr.pos e) "direct"; Marked.mark (Expr.pos e) "output"; ] in let calling_expr = Expr.eapp called_func [single_arg] m in For the purposes of log parsing explained in Runtime . EventParser , we need to wrap this function call in a flurry of log tags . Specifically , we are mascarading this scope call as a function call . In a normal function call , the log parser expects the output of the function to be defined as a default , hence the production of the output should yield a PosRecordIfTrueBool ( which is not the case here ) . To remedy this absence we fabricate a fake attached to a silent let binding to " true " before returning the output value . But this is not sufficient . Indeed for the tricky case of [ tests / test_scope / scope_call3.catala_en ] , when a scope returns a function , because we insert loggins calls at the call site of the function and not during its definition , then we 're missing the call log instructions of the function returned . To avoid this trap , we need to rebind the resulting scope output struct by eta - expanding the functions to insert logging instructions to wrap this function call in a flurry of log tags. Specifically, we are mascarading this scope call as a function call. In a normal function call, the log parser expects the output of the function to be defined as a default, hence the production of the output should yield a PosRecordIfTrueBool (which is not the case here). To remedy this absence we fabricate a fake PosRecordIfTrueBool attached to a silent let binding to "true" before returning the output value. But this is not sufficient. Indeed for the tricky case of [tests/test_scope/scope_call3.catala_en], when a scope returns a function, because we insert loggins calls at the call site of the function and not during its definition, then we're missing the call log instructions of the function returned. To avoid this trap, we need to rebind the resulting scope output struct by eta-expanding the functions to insert logging instructions*) let result_var = Var.make "result" in let result_eta_expanded_var = Var.make "result" in let result_eta_expanded = Expr.estruct sc_sig.scope_sig_output_struct (StructField.Map.mapi (fun field typ -> let original_field_expr = Expr.estructaccess (Expr.make_var result_var (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e))) field sc_sig.scope_sig_output_struct (Expr.with_ty m typ) in match Marked.unmark typ with | TArrow (ts_in, t_out) -> let params_vars = ListLabels.mapi ts_in ~f:(fun i _ -> Var.make ("param" ^ string_of_int i)) in let f_markings = [ScopeName.get_info scope; StructField.get_info field] in Expr.make_abs (Array.of_list params_vars) (tag_with_log_entry (tag_with_log_entry (Expr.eapp (tag_with_log_entry original_field_expr BeginCall f_markings) (ListLabels.mapi (List.combine params_vars ts_in) ~f:(fun i (param_var, t_in) -> tag_with_log_entry (Expr.make_var param_var (Expr.with_ty m t_in)) (VarDef (Marked.unmark t_in)) (f_markings @ [ Marked.mark (Expr.pos e) ("input" ^ string_of_int i); ]))) (Expr.with_ty m t_out)) (VarDef (Marked.unmark t_out)) (f_markings @ [Marked.mark (Expr.pos e) "output"])) EndCall f_markings) ts_in (Expr.pos e) | _ -> original_field_expr) (StructName.Map.find sc_sig.scope_sig_output_struct ctx.structs)) (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e)) in let if_then_else_returned = Expr.eifthenelse (tag_with_log_entry (Expr.box (Marked.mark (Expr.with_ty m (TLit TBool, Expr.pos e)) (ELit (LBool true)))) PosRecordIfTrueBool direct_output_info) (Expr.make_var result_eta_expanded_var (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e))) (Expr.box (Marked.mark (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e)) (ELit LEmptyError))) (Expr.with_ty m (TStruct sc_sig.scope_sig_output_struct, Expr.pos e)) in Expr.make_let_in result_var (TStruct sc_sig.scope_sig_output_struct, Expr.pos e) calling_expr (Expr.make_let_in result_eta_expanded_var (TStruct sc_sig.scope_sig_output_struct, Expr.pos e) result_eta_expanded (tag_with_log_entry (tag_with_log_entry if_then_else_returned (VarDef (TStruct sc_sig.scope_sig_output_struct)) direct_output_info) EndCall [ScopeName.get_info scope; Marked.mark (Expr.pos e) "direct"]) (Expr.pos e)) (Expr.pos e) | EApp { f; args } -> let e1_func = translate_expr ctx f in let markings = match ctx.scope_name, Marked.unmark f with | Some sname, ELocation loc -> ( match loc with | ScopelangScopeVar (v, _) -> [ScopeName.get_info sname; ScopeVar.get_info v] | SubScopeVar (s, _, (v, _)) -> [ScopeName.get_info s; ScopeVar.get_info v] | ToplevelVar _ -> []) | _ -> [] in let e1_func = match markings with | [] -> e1_func | m -> tag_with_log_entry e1_func BeginCall m in let new_args = List.map (translate_expr ctx) args in let input_typs, output_typ = let retrieve_in_and_out_typ_or_any var vars = let _, typ, _ = ScopeVar.Map.find (Marked.unmark var) vars in match typ with | TArrow (marked_input_typ, marked_output_typ) -> ( List.map Marked.unmark marked_input_typ, Marked.unmark marked_output_typ ) | _ -> ListLabels.map new_args ~f:(fun _ -> TAny), TAny in match Marked.unmark f with | ELocation (ScopelangScopeVar var) -> retrieve_in_and_out_typ_or_any var ctx.scope_vars | ELocation (SubScopeVar (_, sname, var)) -> ctx.subscope_vars |> SubScopeName.Map.find (Marked.unmark sname) |> retrieve_in_and_out_typ_or_any var | ELocation (ToplevelVar tvar) -> ( let _, typ = TopdefName.Map.find (Marked.unmark tvar) ctx.toplevel_vars in match typ with | TArrow (tin, (tout, _)) -> List.map Marked.unmark tin, tout | _ -> Errors.raise_spanned_error (Expr.pos e) "Application of non-function toplevel variable") | _ -> ListLabels.map new_args ~f:(fun _ -> TAny), TAny in Cli.debug_format " new_args % d , input_typs : % d , input_typs % a " ( List.length ) ( List.length input_typs ) ( Format.pp_print_list Print.typ_debug ) ( List.map ( Marked.mark Pos.no_pos ) input_typs ) ; (List.length new_args) (List.length input_typs) (Format.pp_print_list Print.typ_debug) (List.map (Marked.mark Pos.no_pos) input_typs); *) let new_args = ListLabels.mapi (List.combine new_args input_typs) ~f:(fun i (new_arg, input_typ) -> match markings with | _ :: _ as m -> tag_with_log_entry new_arg (VarDef input_typ) (m @ [Marked.mark (Expr.pos e) ("input" ^ string_of_int i)]) | _ -> new_arg) in let new_e = Expr.eapp e1_func new_args m in let new_e = match markings with | [] -> new_e | m -> tag_with_log_entry (tag_with_log_entry new_e (VarDef output_typ) (m @ [Marked.mark (Expr.pos e) "output"])) EndCall m in new_e | EAbs { binder; tys } -> let xs, body = Bindlib.unmbind binder in let new_xs = Array.map (fun x -> Var.make (Bindlib.name_of x)) xs in let both_xs = Array.map2 (fun x new_x -> x, new_x) xs new_xs in let body = translate_expr { ctx with local_vars = Array.fold_left (fun local_vars (x, new_x) -> Var.Map.add x new_x local_vars) ctx.local_vars both_xs; } body in let binder = Expr.bind new_xs body in Expr.eabs binder tys m | EDefault { excepts; just; cons } -> let excepts = collapse_similar_outcomes excepts in Expr.edefault (List.map (translate_expr ctx) excepts) (translate_expr ctx just) (translate_expr ctx cons) m | ELocation (ScopelangScopeVar a) -> let v, _, _ = ScopeVar.Map.find (Marked.unmark a) ctx.scope_vars in Expr.evar v m | ELocation (SubScopeVar (_, s, a)) -> ( try let v, _, _ = ScopeVar.Map.find (Marked.unmark a) (SubScopeName.Map.find (Marked.unmark s) ctx.subscope_vars) in Expr.evar v m with Not_found -> Errors.raise_multispanned_error [ Some "Incriminated variable usage:", Expr.pos e; ( Some "Incriminated subscope variable declaration:", Marked.get_mark (ScopeVar.get_info (Marked.unmark a)) ); ( Some "Incriminated subscope declaration:", Marked.get_mark (SubScopeName.get_info (Marked.unmark s)) ); ] "The variable %a.%a cannot be used here, as it is not part of subscope \ %a's results. Maybe you forgot to qualify it as an output?" SubScopeName.format_t (Marked.unmark s) ScopeVar.format_t (Marked.unmark a) SubScopeName.format_t (Marked.unmark s)) | ELocation (ToplevelVar v) -> let v, _ = TopdefName.Map.find (Marked.unmark v) ctx.toplevel_vars in Expr.evar v m | EIfThenElse { cond; etrue; efalse } -> Expr.eifthenelse (translate_expr ctx cond) (translate_expr ctx etrue) (translate_expr ctx efalse) m | EOp { op; tys } -> Expr.eop (Operator.translate op) tys m | EErrorOnEmpty e' -> Expr.eerroronempty (translate_expr ctx e') m | EArray es -> Expr.earray (List.map (translate_expr ctx) es) m let translate_rule (ctx : 'm ctx) (rule : 'm Scopelang.Ast.rule) ((sigma_name, pos_sigma) : Uid.MarkedString.info) : ('m Ast.expr scope_body_expr Bindlib.box -> 'm Ast.expr scope_body_expr Bindlib.box) * 'm ctx = match rule with | Definition ((ScopelangScopeVar a, var_def_pos), tau, a_io, e) -> let pos_mark, pos_mark_as = pos_mark_mk e in let a_name = ScopeVar.get_info (Marked.unmark a) in let a_var = Var.make (Marked.unmark a_name) in let new_e = translate_expr ctx e in let a_expr = Expr.make_var a_var (pos_mark var_def_pos) in let merged_expr = match Marked.unmark a_io.io_input with | OnlyInput -> failwith "should not happen" | Reentrant -> merge_defaults ~is_func: (match Marked.unmark tau with TArrow _ -> true | _ -> false) a_expr new_e | NoInput -> Expr.eerroronempty new_e (pos_mark_as a_name) in let merged_expr = tag_with_log_entry merged_expr (VarDef (Marked.unmark tau)) [sigma_name, pos_sigma; a_name] in ( (fun next -> Bindlib.box_apply2 (fun next merged_expr -> ScopeLet { scope_let_next = next; scope_let_typ = tau; scope_let_expr = merged_expr; scope_let_kind = ScopeVarDefinition; scope_let_pos = Marked.get_mark a; }) (Bindlib.bind_var a_var next) (Expr.Box.lift merged_expr)), { ctx with scope_vars = ScopeVar.Map.add (Marked.unmark a) (a_var, Marked.unmark tau, a_io) ctx.scope_vars; } ) | Definition ( (SubScopeVar (_subs_name, subs_index, subs_var), var_def_pos), tau, a_io, e ) -> let a_name = Marked.map_under_mark (fun str -> str ^ "." ^ Marked.unmark (ScopeVar.get_info (Marked.unmark subs_var))) (SubScopeName.get_info (Marked.unmark subs_index)) in let a_var = Var.make (Marked.unmark a_name) in let new_e = tag_with_log_entry (translate_expr ctx e) (VarDef (Marked.unmark tau)) [sigma_name, pos_sigma; a_name] in let is_func = match Marked.unmark tau with TArrow _ -> true | _ -> false in let thunked_or_nonempty_new_e = thunk_scope_arg ~is_func a_io.Desugared.Ast.io_input new_e in ( (fun next -> Bindlib.box_apply2 (fun next thunked_or_nonempty_new_e -> ScopeLet { scope_let_next = next; scope_let_pos = Marked.get_mark a_name; scope_let_typ = (match Marked.unmark a_io.io_input with | NoInput -> failwith "should not happen" | OnlyInput -> tau | Reentrant -> if is_func then tau else TArrow ([TLit TUnit, var_def_pos], tau), var_def_pos); scope_let_expr = thunked_or_nonempty_new_e; scope_let_kind = SubScopeVarDefinition; }) (Bindlib.bind_var a_var next) (Expr.Box.lift thunked_or_nonempty_new_e)), { ctx with subscope_vars = SubScopeName.Map.update (Marked.unmark subs_index) (fun map -> match map with | Some map -> Some (ScopeVar.Map.add (Marked.unmark subs_var) (a_var, Marked.unmark tau, a_io) map) | None -> Some (ScopeVar.Map.singleton (Marked.unmark subs_var) (a_var, Marked.unmark tau, a_io))) ctx.subscope_vars; } ) | Definition ((ToplevelVar _, _), _, _, _) -> assert false | Call (subname, subindex, m) -> let subscope_sig = ScopeName.Map.find subname ctx.scopes_parameters in let all_subscope_vars = subscope_sig.scope_sig_local_vars in let all_subscope_input_vars = List.filter (fun var_ctx -> match Marked.unmark var_ctx.scope_var_io.Desugared.Ast.io_input with | NoInput -> false | _ -> true) all_subscope_vars in let all_subscope_output_vars = List.filter (fun var_ctx -> Marked.unmark var_ctx.scope_var_io.Desugared.Ast.io_output) all_subscope_vars in let scope_dcalc_var = subscope_sig.scope_sig_scope_var in let called_scope_input_struct = subscope_sig.scope_sig_input_struct in let called_scope_return_struct = subscope_sig.scope_sig_output_struct in let subscope_vars_defined = try SubScopeName.Map.find subindex ctx.subscope_vars with Not_found -> ScopeVar.Map.empty in let subscope_var_not_yet_defined subvar = not (ScopeVar.Map.mem subvar subscope_vars_defined) in let pos_call = Marked.get_mark (SubScopeName.get_info subindex) in let subscope_args = List.fold_left (fun acc (subvar : scope_var_ctx) -> let e = if subscope_var_not_yet_defined subvar.scope_var_name then Expr.empty_thunked_term m else let a_var, _, _ = ScopeVar.Map.find subvar.scope_var_name subscope_vars_defined in Expr.make_var a_var (mark_tany m pos_call) in let field = (ScopeVar.Map.find subvar.scope_var_name subscope_sig.scope_sig_in_fields) .scope_input_name in StructField.Map.add field e acc) StructField.Map.empty all_subscope_input_vars in let subscope_struct_arg = Expr.estruct called_scope_input_struct subscope_args (mark_tany m pos_call) in let all_subscope_output_vars_dcalc = List.map (fun (subvar : scope_var_ctx) -> let sub_dcalc_var = Var.make (Marked.unmark (SubScopeName.get_info subindex) ^ "." ^ Marked.unmark (ScopeVar.get_info subvar.scope_var_name)) in subvar, sub_dcalc_var) all_subscope_output_vars in let subscope_func = tag_with_log_entry (Expr.make_var scope_dcalc_var (mark_tany m pos_call)) BeginCall [ sigma_name, pos_sigma; SubScopeName.get_info subindex; ScopeName.get_info subname; ] in let call_expr = tag_with_log_entry (Expr.eapp subscope_func [subscope_struct_arg] (mark_tany m pos_call)) EndCall [ sigma_name, pos_sigma; SubScopeName.get_info subindex; ScopeName.get_info subname; ] in let result_tuple_var = Var.make "result" in let result_tuple_typ = TStruct called_scope_return_struct, pos_sigma in let call_scope_let next = Bindlib.box_apply2 (fun next call_expr -> ScopeLet { scope_let_next = next; scope_let_pos = pos_sigma; scope_let_kind = CallingSubScope; scope_let_typ = result_tuple_typ; scope_let_expr = call_expr; }) (Bindlib.bind_var result_tuple_var next) (Expr.Box.lift call_expr) in let result_bindings_lets next = List.fold_right (fun (var_ctx, v) next -> let field = ScopeVar.Map.find var_ctx.scope_var_name subscope_sig.scope_sig_out_fields in Bindlib.box_apply2 (fun next r -> ScopeLet { scope_let_next = next; scope_let_pos = pos_sigma; scope_let_typ = var_ctx.scope_var_typ, pos_sigma; scope_let_kind = DestructuringSubScopeResults; scope_let_expr = ( EStructAccess { name = called_scope_return_struct; e = r; field }, mark_tany m pos_sigma ); }) (Bindlib.bind_var v next) (Expr.Box.lift (Expr.make_var result_tuple_var (mark_tany m pos_sigma)))) all_subscope_output_vars_dcalc next in ( (fun next -> call_scope_let (result_bindings_lets next)), { ctx with subscope_vars = SubScopeName.Map.add subindex (List.fold_left (fun acc (var_ctx, dvar) -> ScopeVar.Map.add var_ctx.scope_var_name (dvar, var_ctx.scope_var_typ, var_ctx.scope_var_io) acc) ScopeVar.Map.empty all_subscope_output_vars_dcalc) ctx.subscope_vars; } ) | Assertion e -> let new_e = translate_expr ctx e in let scope_let_pos = Expr.pos e in let scope_let_typ = TLit TUnit, scope_let_pos in ( (fun next -> Bindlib.box_apply2 (fun next new_e -> ScopeLet { scope_let_next = next; scope_let_pos; scope_let_typ; scope_let_expr = To ensure that we throw an error if the value is not defined , we add an check " ErrorOnEmpty " here . defined, we add an check "ErrorOnEmpty" here. *) Marked.mark (Expr.map_ty (fun _ -> scope_let_typ) (Marked.get_mark e)) (EAssert (Marked.same_mark_as (EErrorOnEmpty new_e) e)); scope_let_kind = Assertion; }) (Bindlib.bind_var (Var.make "_") next) (Expr.Box.lift new_e)), ctx ) let translate_rules (ctx : 'm ctx) (rules : 'm Scopelang.Ast.rule list) ((sigma_name, pos_sigma) : Uid.MarkedString.info) (mark : 'm mark) (scope_sig : 'm scope_sig_ctx) : 'm Ast.expr scope_body_expr Bindlib.box * 'm ctx = let scope_lets, new_ctx = List.fold_left (fun (scope_lets, ctx) rule -> let new_scope_lets, new_ctx = translate_rule ctx rule (sigma_name, pos_sigma) in (fun next -> scope_lets (new_scope_lets next)), new_ctx) ((fun next -> next), ctx) rules in let return_exp = Expr.estruct scope_sig.scope_sig_output_struct (ScopeVar.Map.fold (fun var (dcalc_var, _, io) acc -> if Marked.unmark io.Desugared.Ast.io_output then let field = ScopeVar.Map.find var scope_sig.scope_sig_out_fields in StructField.Map.add field (Expr.make_var dcalc_var (mark_tany mark pos_sigma)) acc else acc) new_ctx.scope_vars StructField.Map.empty) (mark_tany mark pos_sigma) in ( scope_lets (Bindlib.box_apply (fun return_exp -> Result return_exp) (Expr.Box.lift return_exp)), new_ctx ) let translate_scope_decl (ctx : 'm ctx) (scope_name : ScopeName.t) (sigma : 'm Scopelang.Ast.scope_decl) : 'm Ast.expr scope_body Bindlib.box * struct_ctx = let sigma_info = ScopeName.get_info sigma.scope_decl_name in let scope_sig = ScopeName.Map.find sigma.scope_decl_name ctx.scopes_parameters in let scope_variables = scope_sig.scope_sig_local_vars in let ctx = { ctx with scope_name = Some scope_name } in let ctx = List.fold_left (fun ctx scope_var -> match Marked.unmark scope_var.scope_var_io.io_input with | OnlyInput -> let scope_var_name = ScopeVar.get_info scope_var.scope_var_name in let scope_var_dcalc = Var.make (Marked.unmark scope_var_name) in { ctx with scope_vars = ScopeVar.Map.add scope_var.scope_var_name ( scope_var_dcalc, scope_var.scope_var_typ, scope_var.scope_var_io ) ctx.scope_vars; } | _ -> ctx) ctx scope_variables in let scope_input_var = scope_sig.scope_sig_input_var in let scope_input_struct_name = scope_sig.scope_sig_input_struct in let scope_return_struct_name = scope_sig.scope_sig_output_struct in let pos_sigma = Marked.get_mark sigma_info in let rules_with_return_expr, ctx = translate_rules ctx sigma.scope_decl_rules sigma_info sigma.scope_mark scope_sig in let scope_variables = List.map (fun var_ctx -> let dcalc_x, _, _ = ScopeVar.Map.find var_ctx.scope_var_name ctx.scope_vars in var_ctx, dcalc_x) scope_variables in let scope_input_variables = List.filter (fun (var_ctx, _) -> match Marked.unmark var_ctx.scope_var_io.io_input with | NoInput -> false | _ -> true) scope_variables in let input_var_typ (var_ctx : scope_var_ctx) = match Marked.unmark var_ctx.scope_var_io.io_input with | OnlyInput -> var_ctx.scope_var_typ, pos_sigma | Reentrant -> ( match var_ctx.scope_var_typ with | TArrow _ -> var_ctx.scope_var_typ, pos_sigma | _ -> ( TArrow ([TLit TUnit, pos_sigma], (var_ctx.scope_var_typ, pos_sigma)), pos_sigma )) | NoInput -> failwith "should not happen" in let input_destructurings next = List.fold_right (fun (var_ctx, v) next -> let field = (ScopeVar.Map.find var_ctx.scope_var_name scope_sig.scope_sig_in_fields) .scope_input_name in Bindlib.box_apply2 (fun next r -> ScopeLet { scope_let_kind = DestructuringInputStruct; scope_let_next = next; scope_let_pos = pos_sigma; scope_let_typ = input_var_typ var_ctx; scope_let_expr = ( EStructAccess { name = scope_input_struct_name; e = r; field }, mark_tany sigma.scope_mark pos_sigma ); }) (Bindlib.bind_var v next) (Expr.Box.lift (Expr.make_var scope_input_var (mark_tany sigma.scope_mark pos_sigma)))) scope_input_variables next in let field_map = List.fold_left (fun acc (var_ctx, _) -> let var = var_ctx.scope_var_name in let field = (ScopeVar.Map.find var scope_sig.scope_sig_in_fields).scope_input_name in StructField.Map.add field (input_var_typ var_ctx) acc) StructField.Map.empty scope_input_variables in let new_struct_ctx = StructName.Map.singleton scope_input_struct_name field_map in ( Bindlib.box_apply (fun scope_body_expr -> { scope_body_expr; scope_body_input_struct = scope_input_struct_name; scope_body_output_struct = scope_return_struct_name; }) (Bindlib.bind_var scope_input_var (input_destructurings rules_with_return_expr)), new_struct_ctx ) let translate_program (prgm : 'm Scopelang.Ast.program) : 'm Ast.program = let defs_dependencies = Scopelang.Dependency.build_program_dep_graph prgm in Scopelang.Dependency.check_for_cycle_in_defs defs_dependencies; let defs_ordering = Scopelang.Dependency.get_defs_ordering defs_dependencies in let decl_ctx = prgm.program_ctx in let sctx : 'm scope_sigs_ctx = ScopeName.Map.mapi (fun scope_name scope -> let scope_dvar = Var.make (Marked.unmark (ScopeName.get_info scope.Scopelang.Ast.scope_decl_name)) in let scope_return = ScopeName.Map.find scope_name decl_ctx.ctx_scopes in let scope_input_var = Var.make (Marked.unmark (ScopeName.get_info scope_name) ^ "_in") in let scope_input_struct_name = StructName.fresh (Marked.map_under_mark (fun s -> s ^ "_in") (ScopeName.get_info scope_name)) in let scope_sig_in_fields = ScopeVar.Map.filter_map (fun dvar (typ, vis) -> match Marked.unmark vis.Desugared.Ast.io_input with | NoInput -> None | OnlyInput | Reentrant -> let info = ScopeVar.get_info dvar in let s = Marked.unmark info ^ "_in" in Some { scope_input_name = StructField.fresh (s, Marked.get_mark info); scope_input_io = vis.Desugared.Ast.io_input; scope_input_typ = Marked.unmark typ; }) scope.scope_sig in { scope_sig_local_vars = List.map (fun (scope_var, (tau, vis)) -> { scope_var_name = scope_var; scope_var_typ = Marked.unmark tau; scope_var_io = vis; }) (ScopeVar.Map.bindings scope.scope_sig); scope_sig_scope_var = scope_dvar; scope_sig_input_var = scope_input_var; scope_sig_input_struct = scope_input_struct_name; scope_sig_output_struct = scope_return.out_struct_name; scope_sig_in_fields; scope_sig_out_fields = scope_return.out_struct_fields; }) prgm.Scopelang.Ast.program_scopes in let top_ctx = let toplevel_vars = TopdefName.Map.mapi (fun name (_, ty) -> Var.make (Marked.unmark (TopdefName.get_info name)), Marked.unmark ty) prgm.Scopelang.Ast.program_topdefs in { structs = decl_ctx.ctx_structs; enums = decl_ctx.ctx_enums; scope_name = None; scopes_parameters = sctx; scope_vars = ScopeVar.Map.empty; subscope_vars = SubScopeName.Map.empty; local_vars = Var.Map.empty; toplevel_vars; } in let rec translate_defs ctx = function | [] -> Bindlib.box Nil, ctx | def :: next -> let ctx, dvar, def = match def with | Scopelang.Dependency.Topdef gname -> let expr, ty = TopdefName.Map.find gname prgm.program_topdefs in let expr = translate_expr ctx expr in ( ctx, fst (TopdefName.Map.find gname ctx.toplevel_vars), Bindlib.box_apply (fun e -> Topdef (gname, ty, e)) (Expr.Box.lift expr) ) | Scopelang.Dependency.Scope scope_name -> let scope = ScopeName.Map.find scope_name prgm.program_scopes in let scope_body, scope_in_struct = translate_scope_decl ctx scope_name scope in ( { ctx with structs = StructName.Map.union (fun _ _ -> assert false) ctx.structs scope_in_struct; }, (ScopeName.Map.find scope_name sctx).scope_sig_scope_var, Bindlib.box_apply (fun body -> ScopeDef (scope_name, body)) scope_body ) in let scope_next, ctx = translate_defs ctx next in let next_bind = Bindlib.bind_var dvar scope_next in ( Bindlib.box_apply2 (fun item next_bind -> Cons (item, next_bind)) def next_bind, ctx ) in let items, ctx = translate_defs top_ctx defs_ordering in { code_items = Bindlib.unbox items; decl_ctx = { decl_ctx with ctx_structs = ctx.structs }; }
1a7d272701b7b0d21892c0f569b87590706b7915860742ba6e0f4c5d5fdaf50c
albertoruiz/easyVision
horizon.hs
import Vision.GUI import Image import Image.Processing import Util.Options(optionFromFile,getRawOption) import Data.Traversable(traverse) import Numeric.LinearAlgebra hiding (gjoin) import Vision(estimateHomography,scaling) import Util.Geometry as G import Util.Debug(debug) import Contours(bounding , poly2roi ) main = do mbimg <- getRawOption "--image" >>= traverse loadRGB runIt $ do p <- clickPoints "click rectangle" "--points" () (sh mbimg.fst) w <- browser "horizon" [] (const id) connectWith (g mbimg) p w sh mbimg pts = Draw [ Draw mbimg , color lightgreen . drawPointsLabeled $ pts] g mbimg (k,_) (ps,_) = (k, [Draw [Draw smbimg, color red [ Draw sls, pointSz 5 sps ]] ]) where [p1,p2,p3,p4] = take 4 ps l1 = gjoin p1 p2 l2 = gjoin p3 p4 l3 = gjoin p1 p4 l4 = gjoin p2 p3 l_inf' = (meet l1 l2) `gjoin` (meet l3 l4) ls | length ps >=4 = [l_inf',l1,l2,l3,l4] | otherwise = [] h = unsafeFromMatrix $ scaling (1/3) :: Homography sls = h <| ls sps = h <| ps smbimg = warp (Word24 50 0 0) (maybe (Size 400 400) size mbimg) (toMatrix h) `fmap` mbimg
null
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/vision/geom/horizon.hs
haskell
import Vision.GUI import Image import Image.Processing import Util.Options(optionFromFile,getRawOption) import Data.Traversable(traverse) import Numeric.LinearAlgebra hiding (gjoin) import Vision(estimateHomography,scaling) import Util.Geometry as G import Util.Debug(debug) import Contours(bounding , poly2roi ) main = do mbimg <- getRawOption "--image" >>= traverse loadRGB runIt $ do p <- clickPoints "click rectangle" "--points" () (sh mbimg.fst) w <- browser "horizon" [] (const id) connectWith (g mbimg) p w sh mbimg pts = Draw [ Draw mbimg , color lightgreen . drawPointsLabeled $ pts] g mbimg (k,_) (ps,_) = (k, [Draw [Draw smbimg, color red [ Draw sls, pointSz 5 sps ]] ]) where [p1,p2,p3,p4] = take 4 ps l1 = gjoin p1 p2 l2 = gjoin p3 p4 l3 = gjoin p1 p4 l4 = gjoin p2 p3 l_inf' = (meet l1 l2) `gjoin` (meet l3 l4) ls | length ps >=4 = [l_inf',l1,l2,l3,l4] | otherwise = [] h = unsafeFromMatrix $ scaling (1/3) :: Homography sls = h <| ls sps = h <| ps smbimg = warp (Word24 50 0 0) (maybe (Size 400 400) size mbimg) (toMatrix h) `fmap` mbimg
ca5669bdbc61a81ea8afba6e0cfa8ab18ae7488a708efc0a95114b2f087ee909
degree9/enterprise
profiler.cljs
(ns degree9.profiler (:require [taoensso.tufte :as tufte :refer-macros (defnp p profiled profile)])) (tufte/add-basic-println-handler! {}) (defn run-once [app] (profile {} (dotimes [_ 1] (p :app app))))
null
https://raw.githubusercontent.com/degree9/enterprise/36e4f242c18b1dde54d5a15c668b17dc800c01ff/src/degree9/profiler.cljs
clojure
(ns degree9.profiler (:require [taoensso.tufte :as tufte :refer-macros (defnp p profiled profile)])) (tufte/add-basic-println-handler! {}) (defn run-once [app] (profile {} (dotimes [_ 1] (p :app app))))
5e7a2387a30e86c625dcc8750b8a9153858d004ec2fb774e8e89bb369d97db33
jordanthayer/ocaml-search
recording_clamped.ml
(** A* search variant for recording search data online *) type 'a node = { Data Payload f : float; (* Total cost of a node*) mutable est_f : float; g : float; (* Cost of reaching a node *) h : float; d : float; depth : int; (* Depth of node in tree. Root @ 0 *) mutable q_pos : int; (* Position info for dpq *) } let wrap f = (** takes a function to be applied to the data payload such as the goal-test or the domain heuristic and wraps it so that it can be applied to the entire node *) (fun n -> f n.data) let unwrap_sol s = (** Unwraps a solution which is in the form of a search node and presents it in the format the domain expects it, which is domain data followed by cost *) match s with Limit.Nothing -> None | Limit.Incumbent (q,n) -> Some (n.data, n.g) let est_f_then_d_then_g a b = (** sorts nodes in order of estimated f, breaking ties in favor of low d values, and then in favor of high g *) (a.est_f < b.est_f) || (* sort by fhat *) ((a.est_f = b.est_f) && a.d < b.d) || (a.est_f = b.est_f && a.d = b.d && ((a.g >= b.g))) let f_then_g a b = * expansion ordering predicate , and also works for ordering duplicates assuming that h is the same for both ( hence f will be lower when g is lower ) . assuming that h is the same for both (hence f will be lower when g is lower). *) (a.f < b.f) || ((a.f = b.f) && (a.g >= b.g)) let just_f a b = (** Sorts nodes solely on total cost information *) a.f <= b.f let setpos n i = * Sets the location of a node , used by dpq 's n.q_pos <- i let getpos n = (** Returns the position of the node in its dpq. Useful for swapping nodes around on the open list *) n.q_pos let make_expand expand hd timer calc_h_data f_calc node_record = (** [expand] is the domain expand [hd] is a cost and distance estimator [timer] returns true every so often, to tell the openlist to resort [calc_h_data] takes the parent, the best child, and all children in order to make a better h estimator [f_calc] uses the estimated h values to calculate the bounded f estimates *) (fun n -> let best_f = ref infinity and best_child = ref n and reorder = timer() in let children = (List.map (fun (s, g) -> let h, d = hd s in let f = g +. h in let c = { est_f = f; f = f; h = h; d = d; g = g; depth = n.depth + 1; q_pos = Dpq.no_position; data = s;} in if f < !best_f then (best_child := c; best_f := f) else if f = !best_f then (if d < !best_child.d then (best_child := c; best_f := f)); c) (expand n.data n.g)) in node_record n n children; if not ((List.length children) = 0) then (calc_h_data n !best_child children; List.iter (fun c -> c.est_f <- f_calc c) children); reorder, children) let make_updater f_calc = (** Updates the estimated f values of all nodes in a given dpq *) (fun dpq -> Dpq.iter (fun n -> n.est_f <- f_calc n) dpq) (************************* Searches Base ************************************) let make_interface sface h_calc f_calc timer node_record = let init = Search_interface.make ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:(sface.Search_interface.halt_on) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain { est_f = neg_infinity; f = neg_infinity; h = neg_infinity; d = neg_infinity; g = 0.; depth = 0; q_pos = Dpq.no_position; data = sface.Search_interface.initial;} just_f (Limit.make_default_logger (fun n -> n.g +. n.h) (wrap sface.Search_interface.get_sol_length)) in Search_interface.alter ~resort_expand:(Some (make_expand sface.Search_interface.domain_expand sface.Search_interface.hd timer h_calc f_calc (node_record init.Search_interface.info))) init let no_dups sface bound timer h_calc f_calc node_record queue_record = (** Performs an A* search from the initial state to a goal, for domains with no duplicates. *) let search_interface = make_interface sface h_calc f_calc timer node_record in Limit.unwrap_sol5 unwrap_sol (Reorderable_best_first.search ~record:queue_record search_interface est_f_then_d_then_g just_f (make_updater f_calc)) let dups sface bound timer h_calc f_calc node_record queue_record = (** Performs an A* search from the initial state to a goal, for domains where duplicates are frequently encountered. *) (** Performs a search in domains where there are duplicates. [sface] is the domain's search interface [bound] is the desired quality bound [timer] is a timer from Timers.ml [h_calc] takes the parent, best child, and all children, returns unit [f_calc] takes a node and returns a float *) let search_interface = make_interface sface h_calc f_calc timer node_record in Limit.unwrap_sol6 unwrap_sol (Reorderable_best_first.search_dups ~record:queue_record search_interface est_f_then_d_then_g just_f setpos getpos (make_updater f_calc)) (* TODO: We aren't using bound, why is it in the footprint? *) let drop sface bound timer h_calc f_calc node_record queue_record = (** Performs an A* search from the initial state to a goal, for domains where duplicates are frequently encountered. *) (** Performs a search in domains where there are duplicates. [sface] is the domain's search interface [bound] is the desired quality bound [timer] is a timer from Timers.ml [h_calc] takes the parent, best child, and all children, returns unit [f_calc] takes a node and returns a float *) let search_interface = make_interface sface h_calc f_calc timer node_record in Limit.unwrap_sol6 unwrap_sol (Reorderable_best_first.search_drop_dups ~record:queue_record search_interface est_f_then_d_then_g just_f setpos getpos (make_updater f_calc)) (****************************************************************************) (*** Recorders ***) let exp_rec key_printer key = Recorders.expansion_recorder key_printer (wrap key) (fun n -> n.g) (fun n -> n.depth) (fun n -> n.est_f) let queue_rec key_printer key = Recorders.dpq_recorder key_printer (wrap key) let truth_rec key_printer key = (* note that for simplicities sake, forward heuristics still point forward*) Recorders.truth_recorder key_printer (wrap key) (fun n -> n.g) (fun n -> n.depth) (fun n -> n.h) (fun n -> n.d) (****************************************************************************) let expand_recorder_nodups sface bound timer hcalc fcalc = no_dups sface bound timer hcalc fcalc (exp_rec sface.Search_interface.key_printer sface.Search_interface.key) Recorders.none and expand_recorder_dups sface bound timer hcalc fcalc = dups sface bound timer hcalc fcalc (exp_rec sface.Search_interface.key_printer sface.Search_interface.key) Recorders.none and expand_recorder_dd sface bound timer hcalc fcalc = drop sface bound timer hcalc fcalc (exp_rec sface.Search_interface.key_printer sface.Search_interface.key) Recorders.none and queue_recorder_nodups sface bound timer hcalc fcalc = no_dups sface bound timer hcalc fcalc Recorders.no_node_record (queue_rec sface.Search_interface.key_printer sface.Search_interface.key) and queue_recorder_dups sface bound timer hcalc fcalc = dups sface bound timer hcalc fcalc Recorders.no_node_record (queue_rec sface.Search_interface.key_printer sface.Search_interface.key) and queue_recorder_dd sface bound timer hcalc fcalc = drop sface bound timer hcalc fcalc Recorders.no_node_record (queue_rec sface.Search_interface.key_printer sface.Search_interface.key) (*****************************************************************************) let h_ss_reckless_dups_exp sface args = (** perform a search based on this estimated f function on a domain with many duplicates. Never update f estimates or resort queues *) let bound = Search_args.get_float "Recording_clamped.h_ss_reckless_dups_exp" args 0 in let h_calc,f_calc = Global_h_ss.make_clamped_correction (fun n -> n.g) (fun n -> n.h) (fun n -> n.d) bound in expand_recorder_dups sface bound Timers.reckless h_calc f_calc let h_ss_reckless_dups_queue sface args = (** perform a search based on this estimated f function on a domain with many duplicates. Never update f estimates or resort queues *) let bound = Search_args.get_float "Recording_clamped.h_ss_reckless_dups_queue" args 0 in let h_calc,f_calc = Global_h_ss.make_clamped_correction (fun n -> n.g) (fun n -> n.h) (fun n -> n.d) bound in queue_recorder_dups sface bound Timers.reckless h_calc f_calc let h_ss_reckless_dd_exp sface args = (** perform a search based on this estimated f function on a domain with many duplicates. Never update f estimates or resort queues *) let bound = Search_args.get_float "Recording_clamped.h_ss_reckless_dd_exp" args 0 in let h_calc,f_calc = Global_h_ss.make_clamped_correction (fun n -> n.g) (fun n -> n.h) (fun n -> n.d) bound in expand_recorder_dd sface bound Timers.reckless h_calc f_calc let h_ss_reckless_dd_queue sface args = (** perform a search based on this estimated f function on a domain with many duplicates. Never update f estimates or resort queues *) let bound = Search_args.get_float "Recording_clamped.h_ss_reckless_dd_queue" args 0 in let h_calc,f_calc = Global_h_ss.make_clamped_correction (fun n -> n.g) (fun n -> n.h) (fun n -> n.d) bound in queue_recorder_dd sface bound Timers.reckless h_calc f_calc EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/recording/recording_clamped.ml
ocaml
* A* search variant for recording search data online Total cost of a node Cost of reaching a node Depth of node in tree. Root @ 0 Position info for dpq * takes a function to be applied to the data payload such as the goal-test or the domain heuristic and wraps it so that it can be applied to the entire node * Unwraps a solution which is in the form of a search node and presents it in the format the domain expects it, which is domain data followed by cost * sorts nodes in order of estimated f, breaking ties in favor of low d values, and then in favor of high g sort by fhat * Sorts nodes solely on total cost information * Returns the position of the node in its dpq. Useful for swapping nodes around on the open list * [expand] is the domain expand [hd] is a cost and distance estimator [timer] returns true every so often, to tell the openlist to resort [calc_h_data] takes the parent, the best child, and all children in order to make a better h estimator [f_calc] uses the estimated h values to calculate the bounded f estimates * Updates the estimated f values of all nodes in a given dpq ************************ Searches Base *********************************** * Performs an A* search from the initial state to a goal, for domains with no duplicates. * Performs an A* search from the initial state to a goal, for domains where duplicates are frequently encountered. * Performs a search in domains where there are duplicates. [sface] is the domain's search interface [bound] is the desired quality bound [timer] is a timer from Timers.ml [h_calc] takes the parent, best child, and all children, returns unit [f_calc] takes a node and returns a float TODO: We aren't using bound, why is it in the footprint? * Performs an A* search from the initial state to a goal, for domains where duplicates are frequently encountered. * Performs a search in domains where there are duplicates. [sface] is the domain's search interface [bound] is the desired quality bound [timer] is a timer from Timers.ml [h_calc] takes the parent, best child, and all children, returns unit [f_calc] takes a node and returns a float ************************************************************************** ** Recorders ** note that for simplicities sake, forward heuristics still point forward ************************************************************************** *************************************************************************** * perform a search based on this estimated f function on a domain with many duplicates. Never update f estimates or resort queues * perform a search based on this estimated f function on a domain with many duplicates. Never update f estimates or resort queues * perform a search based on this estimated f function on a domain with many duplicates. Never update f estimates or resort queues * perform a search based on this estimated f function on a domain with many duplicates. Never update f estimates or resort queues
type 'a node = { Data Payload mutable est_f : float; h : float; d : float; } let wrap f = (fun n -> f n.data) let unwrap_sol s = match s with Limit.Nothing -> None | Limit.Incumbent (q,n) -> Some (n.data, n.g) let est_f_then_d_then_g a b = ((a.est_f = b.est_f) && a.d < b.d) || (a.est_f = b.est_f && a.d = b.d && ((a.g >= b.g))) let f_then_g a b = * expansion ordering predicate , and also works for ordering duplicates assuming that h is the same for both ( hence f will be lower when g is lower ) . assuming that h is the same for both (hence f will be lower when g is lower). *) (a.f < b.f) || ((a.f = b.f) && (a.g >= b.g)) let just_f a b = a.f <= b.f let setpos n i = * Sets the location of a node , used by dpq 's n.q_pos <- i let getpos n = n.q_pos let make_expand expand hd timer calc_h_data f_calc node_record = (fun n -> let best_f = ref infinity and best_child = ref n and reorder = timer() in let children = (List.map (fun (s, g) -> let h, d = hd s in let f = g +. h in let c = { est_f = f; f = f; h = h; d = d; g = g; depth = n.depth + 1; q_pos = Dpq.no_position; data = s;} in if f < !best_f then (best_child := c; best_f := f) else if f = !best_f then (if d < !best_child.d then (best_child := c; best_f := f)); c) (expand n.data n.g)) in node_record n n children; if not ((List.length children) = 0) then (calc_h_data n !best_child children; List.iter (fun c -> c.est_f <- f_calc c) children); reorder, children) let make_updater f_calc = (fun dpq -> Dpq.iter (fun n -> n.est_f <- f_calc n) dpq) let make_interface sface h_calc f_calc timer node_record = let init = Search_interface.make ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:(sface.Search_interface.halt_on) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain { est_f = neg_infinity; f = neg_infinity; h = neg_infinity; d = neg_infinity; g = 0.; depth = 0; q_pos = Dpq.no_position; data = sface.Search_interface.initial;} just_f (Limit.make_default_logger (fun n -> n.g +. n.h) (wrap sface.Search_interface.get_sol_length)) in Search_interface.alter ~resort_expand:(Some (make_expand sface.Search_interface.domain_expand sface.Search_interface.hd timer h_calc f_calc (node_record init.Search_interface.info))) init let no_dups sface bound timer h_calc f_calc node_record queue_record = let search_interface = make_interface sface h_calc f_calc timer node_record in Limit.unwrap_sol5 unwrap_sol (Reorderable_best_first.search ~record:queue_record search_interface est_f_then_d_then_g just_f (make_updater f_calc)) let dups sface bound timer h_calc f_calc node_record queue_record = let search_interface = make_interface sface h_calc f_calc timer node_record in Limit.unwrap_sol6 unwrap_sol (Reorderable_best_first.search_dups ~record:queue_record search_interface est_f_then_d_then_g just_f setpos getpos (make_updater f_calc)) let drop sface bound timer h_calc f_calc node_record queue_record = let search_interface = make_interface sface h_calc f_calc timer node_record in Limit.unwrap_sol6 unwrap_sol (Reorderable_best_first.search_drop_dups ~record:queue_record search_interface est_f_then_d_then_g just_f setpos getpos (make_updater f_calc)) let exp_rec key_printer key = Recorders.expansion_recorder key_printer (wrap key) (fun n -> n.g) (fun n -> n.depth) (fun n -> n.est_f) let queue_rec key_printer key = Recorders.dpq_recorder key_printer (wrap key) let truth_rec key_printer key = Recorders.truth_recorder key_printer (wrap key) (fun n -> n.g) (fun n -> n.depth) (fun n -> n.h) (fun n -> n.d) let expand_recorder_nodups sface bound timer hcalc fcalc = no_dups sface bound timer hcalc fcalc (exp_rec sface.Search_interface.key_printer sface.Search_interface.key) Recorders.none and expand_recorder_dups sface bound timer hcalc fcalc = dups sface bound timer hcalc fcalc (exp_rec sface.Search_interface.key_printer sface.Search_interface.key) Recorders.none and expand_recorder_dd sface bound timer hcalc fcalc = drop sface bound timer hcalc fcalc (exp_rec sface.Search_interface.key_printer sface.Search_interface.key) Recorders.none and queue_recorder_nodups sface bound timer hcalc fcalc = no_dups sface bound timer hcalc fcalc Recorders.no_node_record (queue_rec sface.Search_interface.key_printer sface.Search_interface.key) and queue_recorder_dups sface bound timer hcalc fcalc = dups sface bound timer hcalc fcalc Recorders.no_node_record (queue_rec sface.Search_interface.key_printer sface.Search_interface.key) and queue_recorder_dd sface bound timer hcalc fcalc = drop sface bound timer hcalc fcalc Recorders.no_node_record (queue_rec sface.Search_interface.key_printer sface.Search_interface.key) let h_ss_reckless_dups_exp sface args = let bound = Search_args.get_float "Recording_clamped.h_ss_reckless_dups_exp" args 0 in let h_calc,f_calc = Global_h_ss.make_clamped_correction (fun n -> n.g) (fun n -> n.h) (fun n -> n.d) bound in expand_recorder_dups sface bound Timers.reckless h_calc f_calc let h_ss_reckless_dups_queue sface args = let bound = Search_args.get_float "Recording_clamped.h_ss_reckless_dups_queue" args 0 in let h_calc,f_calc = Global_h_ss.make_clamped_correction (fun n -> n.g) (fun n -> n.h) (fun n -> n.d) bound in queue_recorder_dups sface bound Timers.reckless h_calc f_calc let h_ss_reckless_dd_exp sface args = let bound = Search_args.get_float "Recording_clamped.h_ss_reckless_dd_exp" args 0 in let h_calc,f_calc = Global_h_ss.make_clamped_correction (fun n -> n.g) (fun n -> n.h) (fun n -> n.d) bound in expand_recorder_dd sface bound Timers.reckless h_calc f_calc let h_ss_reckless_dd_queue sface args = let bound = Search_args.get_float "Recording_clamped.h_ss_reckless_dd_queue" args 0 in let h_calc,f_calc = Global_h_ss.make_clamped_correction (fun n -> n.g) (fun n -> n.h) (fun n -> n.d) bound in queue_recorder_dd sface bound Timers.reckless h_calc f_calc EOF
9161ef935016d4f9d1a9facf8e9a6b5ec7dddae793b798d6be7b0ad03b73a26a
Liutos/Project-Euler
pro3.lisp
(defun largest-prime-factor (n) (labels ((rec (num acc) (cond ((= 1 num) acc) ((<= num 2) num) (t (let ((fac (do ((i 2 (1+ i))) ((or (>= i num) (zerop (mod num i))) i)))) (rec (/ num fac) fac)))))) (rec n 1)))
null
https://raw.githubusercontent.com/Liutos/Project-Euler/dd59940099ae37f971df1d74c4b7c78131fd5470/pro3.lisp
lisp
(defun largest-prime-factor (n) (labels ((rec (num acc) (cond ((= 1 num) acc) ((<= num 2) num) (t (let ((fac (do ((i 2 (1+ i))) ((or (>= i num) (zerop (mod num i))) i)))) (rec (/ num fac) fac)))))) (rec n 1)))
da4ae1004e17a88930d549177e0e63d8dcfcfc4627805f2b0375db9ebccf15d6
techascent/tech.resource
stack.clj
(ns tech.v3.resource.stack "Implementation of stack based resource system. Simple, predictable, deterministic, and applicable to most problems. Resource contexts are sequences of resources that need to be, at some point, released." (:require [clojure.tools.logging :as log]) (:import [java.lang Runnable] [java.io Closeable] [java.lang AutoCloseable] [clojure.lang IFn])) (defonce ^:dynamic *resource-context* (atom (list))) (defonce ^:dynamic *bound-resource-context?* false) (def ^:dynamic *resource-debug-double-free* nil) (defn do-release [item] (when item (try (cond (instance? Runnable item) (.run ^Runnable item) (instance? Closeable item) (.close ^Closeable item) (instance? AutoCloseable item) (.close ^AutoCloseable item) (instance? IFn item) (item) :else (throw (Exception. (format "Item is not runnable, closeable, or an IFn: %s" (type item))))) (catch Throwable e (log/errorf e "Failed to release %s" item))))) (defn track "Begin tracking this resource. Resource be released when current resource context ends. If the item satisfies the PResource protocol, then it can be tracked itself. Else the dispose function is tracked." ([item dispose-fn] (when (and *resource-debug-double-free* (some #(identical? item %) @*resource-context*)) (throw (ex-info "Duplicate track detected; this will result in a double free" {:item item}))) (when-not *bound-resource-context?* (log/warn "Stack resource tracking used but no resource context bound. This is probably a memory leak.")) (swap! *resource-context* conj [item dispose-fn]) item) ([item] (track item item))) (defn ignore-resources "Ignore these resources for which pred returns true and do not track them. They will not be released unless added again with track" [pred] (loop [resources @*resource-context*] (let [retval (filter (comp pred first) resources) leftover (->> (remove (comp pred first) resources) doall)] (if-not (compare-and-set! *resource-context* resources leftover) (recur @*resource-context*) retval)))) (defn ignore "Ignore specifically this resource." [item] (ignore-resources #(= item %)) item) (defn release "Release this resource and remove it from tracking. Exceptions propagate to callers." [item] (when item (let [release-list (first (ignore-resources #(= item %)))] (when release-list (do-release (ffirst release-list)))))) (defn release-resource-seq "Release a resource context returned from return-resource-context." [res-ctx & {:keys [pred] :or {pred identity}}] (->> res-ctx (filter (comp pred first)) ;;Avoid holding onto head. (map (fn [[_ dispose-fn]] (try (do-release dispose-fn) nil (catch Throwable e e)))) doall)) (defn release-current-resources "Release all resources matching either a predicate or all resources currently tracked. Returns any exceptions that happened during release but continues to attempt to release anything else in the resource list." ([pred] (let [leftover (ignore-resources pred)] (release-resource-seq leftover))) ([] (release-current-resources (constantly true)))) (defmacro with-resource-context "Begin a new resource context. Any resources added while this context is open will be released when the context ends." [& body] `(with-bindings {#'*resource-context* (atom (list)) #'*bound-resource-context?* true} (try ~@body (finally (release-current-resources))))) (defmacro with-bound-resource-seq "Run code and return both the return value and the (updated,appended) resources created. Returns: {:return-value retval :resource-seq resources}" [resource-seq & body] ;;It is important the resources sequences is a list. `(with-bindings {#'*resource-context* (atom (seq ~resource-seq)) #'*bound-resource-context?* true} (try (let [retval# (do ~@body)] {:return-value retval# :resource-seq @*resource-context*}) (catch Throwable e# (release-current-resources) (throw e#))))) (defmacro return-resource-seq "Run code and return both the return value and the resources the code created. Returns: {:return-value retval :resource-seq resources}" [& body] `(with-bound-resource-seq (list) ~@body))
null
https://raw.githubusercontent.com/techascent/tech.resource/d27e56d14f60504a343fc221d520797231fd11ba/src/tech/v3/resource/stack.clj
clojure
Avoid holding onto head. It is important the resources sequences is a list.
(ns tech.v3.resource.stack "Implementation of stack based resource system. Simple, predictable, deterministic, and applicable to most problems. Resource contexts are sequences of resources that need to be, at some point, released." (:require [clojure.tools.logging :as log]) (:import [java.lang Runnable] [java.io Closeable] [java.lang AutoCloseable] [clojure.lang IFn])) (defonce ^:dynamic *resource-context* (atom (list))) (defonce ^:dynamic *bound-resource-context?* false) (def ^:dynamic *resource-debug-double-free* nil) (defn do-release [item] (when item (try (cond (instance? Runnable item) (.run ^Runnable item) (instance? Closeable item) (.close ^Closeable item) (instance? AutoCloseable item) (.close ^AutoCloseable item) (instance? IFn item) (item) :else (throw (Exception. (format "Item is not runnable, closeable, or an IFn: %s" (type item))))) (catch Throwable e (log/errorf e "Failed to release %s" item))))) (defn track "Begin tracking this resource. Resource be released when current resource context ends. If the item satisfies the PResource protocol, then it can be tracked itself. Else the dispose function is tracked." ([item dispose-fn] (when (and *resource-debug-double-free* (some #(identical? item %) @*resource-context*)) (throw (ex-info "Duplicate track detected; this will result in a double free" {:item item}))) (when-not *bound-resource-context?* (log/warn "Stack resource tracking used but no resource context bound. This is probably a memory leak.")) (swap! *resource-context* conj [item dispose-fn]) item) ([item] (track item item))) (defn ignore-resources "Ignore these resources for which pred returns true and do not track them. They will not be released unless added again with track" [pred] (loop [resources @*resource-context*] (let [retval (filter (comp pred first) resources) leftover (->> (remove (comp pred first) resources) doall)] (if-not (compare-and-set! *resource-context* resources leftover) (recur @*resource-context*) retval)))) (defn ignore "Ignore specifically this resource." [item] (ignore-resources #(= item %)) item) (defn release "Release this resource and remove it from tracking. Exceptions propagate to callers." [item] (when item (let [release-list (first (ignore-resources #(= item %)))] (when release-list (do-release (ffirst release-list)))))) (defn release-resource-seq "Release a resource context returned from return-resource-context." [res-ctx & {:keys [pred] :or {pred identity}}] (->> res-ctx (filter (comp pred first)) (map (fn [[_ dispose-fn]] (try (do-release dispose-fn) nil (catch Throwable e e)))) doall)) (defn release-current-resources "Release all resources matching either a predicate or all resources currently tracked. Returns any exceptions that happened during release but continues to attempt to release anything else in the resource list." ([pred] (let [leftover (ignore-resources pred)] (release-resource-seq leftover))) ([] (release-current-resources (constantly true)))) (defmacro with-resource-context "Begin a new resource context. Any resources added while this context is open will be released when the context ends." [& body] `(with-bindings {#'*resource-context* (atom (list)) #'*bound-resource-context?* true} (try ~@body (finally (release-current-resources))))) (defmacro with-bound-resource-seq "Run code and return both the return value and the (updated,appended) resources created. Returns: {:return-value retval :resource-seq resources}" [resource-seq & body] `(with-bindings {#'*resource-context* (atom (seq ~resource-seq)) #'*bound-resource-context?* true} (try (let [retval# (do ~@body)] {:return-value retval# :resource-seq @*resource-context*}) (catch Throwable e# (release-current-resources) (throw e#))))) (defmacro return-resource-seq "Run code and return both the return value and the resources the code created. Returns: {:return-value retval :resource-seq resources}" [& body] `(with-bound-resource-seq (list) ~@body))
82fbcacb272a75d919259bc99290b504011421e87852709469c446f9eddab105
alanz/ghc-exactprint
T10052-input.hs
main = let (x :: String) = "hello" in putStrLn x
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/T10052-input.hs
haskell
main = let (x :: String) = "hello" in putStrLn x
8e5ee71b1cefe54b503ed423a041ca73dec139135de06c0885f8fb170194b5cb
daigotanaka/mern-cljs
project.clj
(defproject mern-cljs-example-common "0.1.1-SNAPSHOT" :description "MERN-cljs Example" :url "-cljs" :license {:name "MIT License" :url ""} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/clojurescript "1.7.48"] [org.clojure/core.async "0.1.346.0-17112a-alpha"] Added by Daigo [com.andrewmcveigh/cljs-time "0.4.0"] [com.cognitect/transit-cljs "0.8.220"] [com.cemerick/piggieback "0.2.1"] [com.cemerick/url "0.1.1"] [cljs-ajax "0.5.3"] [net.polyc0l0r/hasch "0.2.3"] ] :plugins [[lein-cljsbuild "1.1.0"] [lein-npm "0.6.1"]] :min-lein-version "2.1.2" :hooks [leiningen.cljsbuild] :source-paths ["src"] :clean-targets ^{:protect false} [[:cljsbuild :builds :compiler :output-to] "node_modules" :target-path :compile-path] :cljsbuild {:builds [ {:source-paths ["src"] :compiler {:target :nodejs :output-to "main.js" :output-dir "target" :optimizations :none :pretty-print true} }]})
null
https://raw.githubusercontent.com/daigotanaka/mern-cljs/a9dedbb3b622f96dd0b06832733b4fd961e6437d/example/common/project.clj
clojure
(defproject mern-cljs-example-common "0.1.1-SNAPSHOT" :description "MERN-cljs Example" :url "-cljs" :license {:name "MIT License" :url ""} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/clojurescript "1.7.48"] [org.clojure/core.async "0.1.346.0-17112a-alpha"] Added by Daigo [com.andrewmcveigh/cljs-time "0.4.0"] [com.cognitect/transit-cljs "0.8.220"] [com.cemerick/piggieback "0.2.1"] [com.cemerick/url "0.1.1"] [cljs-ajax "0.5.3"] [net.polyc0l0r/hasch "0.2.3"] ] :plugins [[lein-cljsbuild "1.1.0"] [lein-npm "0.6.1"]] :min-lein-version "2.1.2" :hooks [leiningen.cljsbuild] :source-paths ["src"] :clean-targets ^{:protect false} [[:cljsbuild :builds :compiler :output-to] "node_modules" :target-path :compile-path] :cljsbuild {:builds [ {:source-paths ["src"] :compiler {:target :nodejs :output-to "main.js" :output-dir "target" :optimizations :none :pretty-print true} }]})
a068a34e2d5bb3e554194c00697d3fb7603ec69416260a776f175426bc86725e
ocaml-multicore/tezos
test_reveal.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2020 Nomadic Labs . < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) * Testing ------- Component : Protocol ( revelation ) Invocation : dune exec \ / proto_alpha / lib_protocol / test / integration / operations / main.exe \ -- test " ^revelation$ " Subject : On the reveal operation . ------- Component: Protocol (revelation) Invocation: dune exec \ src/proto_alpha/lib_protocol/test/integration/operations/main.exe \ -- test "^revelation$" Subject: On the reveal operation. *) (** Test for the [Reveal] operation. *) open Protocol open Alpha_context open Test_tez let ten_tez = of_int 10 let test_simple_reveal () = Context.init ~consensus_threshold:0 1 >>=? fun (blk, contracts) -> let c = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let new_c = Account.new_account () in let new_contract = Alpha_context.Contract.implicit_contract new_c.pkh in (* Create the contract *) Op.transaction (B blk) c new_contract Tez.one >>=? fun operation -> Block.bake blk ~operation >>=? fun blk -> (Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | true -> Stdlib.failwith "Unexpected revelation" | false -> ()) >>=? fun () -> (* Reveal the contract *) Op.revelation (B blk) new_c.pk >>=? fun operation -> Block.bake blk ~operation >>=? fun blk -> Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | true -> () | false -> Stdlib.failwith "New contract revelation failed." let test_empty_account_on_reveal () = Context.init ~consensus_threshold:0 1 >>=? fun (blk, contracts) -> let c = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let new_c = Account.new_account () in let new_contract = Alpha_context.Contract.implicit_contract new_c.pkh in let amount = Tez.one_mutez in (* Create the contract *) Op.transaction (B blk) c new_contract amount >>=? fun operation -> Block.bake blk ~operation >>=? fun blk -> (Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | true -> Stdlib.failwith "Unexpected revelation" | false -> ()) >>=? fun () -> (* Reveal the contract *) Op.revelation ~fee:amount (B blk) new_c.pk >>=? fun operation -> Incremental.begin_construction blk >>=? fun inc -> Incremental.add_operation inc operation >>=? fun _ -> Block.bake blk ~operation >>=? fun blk -> Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | false -> () | true -> Stdlib.failwith "Empty account still exists and is revealed." let test_not_enough_found_for_reveal () = Context.init 1 >>=? fun (blk, contracts) -> let c = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let new_c = Account.new_account () in let new_contract = Alpha_context.Contract.implicit_contract new_c.pkh in (* Create the contract *) Op.transaction (B blk) c new_contract Tez.one_mutez >>=? fun operation -> Block.bake blk ~operation >>=? fun blk -> (Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | true -> Stdlib.failwith "Unexpected revelation" | false -> ()) >>=? fun () -> (* Reveal the contract *) Op.revelation ~fee:Tez.fifty_cents (B blk) new_c.pk >>=? fun operation -> Block.bake blk ~operation >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Contract_storage.Balance_too_low _ -> true | _ -> false) let tests = [ Tztest.tztest "simple reveal" `Quick test_simple_reveal; Tztest.tztest "empty account on reveal" `Quick test_empty_account_on_reveal; Tztest.tztest "not enough found for reveal" `Quick test_not_enough_found_for_reveal; ]
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_protocol/test/integration/operations/test_reveal.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Test for the [Reveal] operation. Create the contract Reveal the contract Create the contract Reveal the contract Create the contract Reveal the contract
Copyright ( c ) 2020 Nomadic Labs . < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING * Testing ------- Component : Protocol ( revelation ) Invocation : dune exec \ / proto_alpha / lib_protocol / test / integration / operations / main.exe \ -- test " ^revelation$ " Subject : On the reveal operation . ------- Component: Protocol (revelation) Invocation: dune exec \ src/proto_alpha/lib_protocol/test/integration/operations/main.exe \ -- test "^revelation$" Subject: On the reveal operation. *) open Protocol open Alpha_context open Test_tez let ten_tez = of_int 10 let test_simple_reveal () = Context.init ~consensus_threshold:0 1 >>=? fun (blk, contracts) -> let c = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let new_c = Account.new_account () in let new_contract = Alpha_context.Contract.implicit_contract new_c.pkh in Op.transaction (B blk) c new_contract Tez.one >>=? fun operation -> Block.bake blk ~operation >>=? fun blk -> (Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | true -> Stdlib.failwith "Unexpected revelation" | false -> ()) >>=? fun () -> Op.revelation (B blk) new_c.pk >>=? fun operation -> Block.bake blk ~operation >>=? fun blk -> Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | true -> () | false -> Stdlib.failwith "New contract revelation failed." let test_empty_account_on_reveal () = Context.init ~consensus_threshold:0 1 >>=? fun (blk, contracts) -> let c = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let new_c = Account.new_account () in let new_contract = Alpha_context.Contract.implicit_contract new_c.pkh in let amount = Tez.one_mutez in Op.transaction (B blk) c new_contract amount >>=? fun operation -> Block.bake blk ~operation >>=? fun blk -> (Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | true -> Stdlib.failwith "Unexpected revelation" | false -> ()) >>=? fun () -> Op.revelation ~fee:amount (B blk) new_c.pk >>=? fun operation -> Incremental.begin_construction blk >>=? fun inc -> Incremental.add_operation inc operation >>=? fun _ -> Block.bake blk ~operation >>=? fun blk -> Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | false -> () | true -> Stdlib.failwith "Empty account still exists and is revealed." let test_not_enough_found_for_reveal () = Context.init 1 >>=? fun (blk, contracts) -> let c = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let new_c = Account.new_account () in let new_contract = Alpha_context.Contract.implicit_contract new_c.pkh in Op.transaction (B blk) c new_contract Tez.one_mutez >>=? fun operation -> Block.bake blk ~operation >>=? fun blk -> (Context.Contract.is_manager_key_revealed (B blk) new_contract >|=? function | true -> Stdlib.failwith "Unexpected revelation" | false -> ()) >>=? fun () -> Op.revelation ~fee:Tez.fifty_cents (B blk) new_c.pk >>=? fun operation -> Block.bake blk ~operation >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Contract_storage.Balance_too_low _ -> true | _ -> false) let tests = [ Tztest.tztest "simple reveal" `Quick test_simple_reveal; Tztest.tztest "empty account on reveal" `Quick test_empty_account_on_reveal; Tztest.tztest "not enough found for reveal" `Quick test_not_enough_found_for_reveal; ]
108370ecd9ed4915b3c876c16f126b1b0eac931391dbe5ecb944def11e038bad
rowangithub/DOrder
qpVector.ml
type 'a vector = { mutable a : 'a array; mutable u : int; d : 'a; } let obj_count = ref 0 let make size value = let res = {a = Array.make (if size < 16 then 16 else size) value; u = size; d = value} in obj_count : = ! ; Gc.finalise ( fun _ - > obj_count : = ! ) res ; Gc.finalise (fun _ -> obj_count := !obj_count - 1) res; *) res let print_stats _ = Printf.printf "unfinalized vectors: %d" !obj_count; print_newline () let set v i vl = v.a.(i) <- vl let get v i = v.a.(i) let length v = v.u let resize v n = v.u <- n; let len = Array.length v.a in if n > len then let newlen = if n > 2 * len then n else 2 * len in let old = v.a in v.a <- (Array.make newlen v.d); Array.blit old 0 v.a 0 len let push v vl = let i = v.u in resize v (i + 1); set v i vl let pop v = v.u <- v.u - 1 let back v = v.a.(v.u - 1)
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/external/qp/qpVector.ml
ocaml
type 'a vector = { mutable a : 'a array; mutable u : int; d : 'a; } let obj_count = ref 0 let make size value = let res = {a = Array.make (if size < 16 then 16 else size) value; u = size; d = value} in obj_count : = ! ; Gc.finalise ( fun _ - > obj_count : = ! ) res ; Gc.finalise (fun _ -> obj_count := !obj_count - 1) res; *) res let print_stats _ = Printf.printf "unfinalized vectors: %d" !obj_count; print_newline () let set v i vl = v.a.(i) <- vl let get v i = v.a.(i) let length v = v.u let resize v n = v.u <- n; let len = Array.length v.a in if n > len then let newlen = if n > 2 * len then n else 2 * len in let old = v.a in v.a <- (Array.make newlen v.d); Array.blit old 0 v.a 0 len let push v vl = let i = v.u in resize v (i + 1); set v i vl let pop v = v.u <- v.u - 1 let back v = v.a.(v.u - 1)
5a323e426eab65183ba431acc5d6b62b93e4679dbe5c043ac82321c805d7e357
heechul/crest-z3
libmaincil.ml
* * Copyright ( c ) 2001 - 2002 , * < > * < > * < > * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions are * met : * * 1 . Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * 3 . The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission . * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS * IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED * TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER * OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , * EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR * PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING * NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . * * * Copyright (c) 2001-2002, * George C. Necula <> * Scott McPeak <> * Wes Weimer <> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *) (* libmaincil *) this is a replacement for maincil.ml , for the case when we 're * creating a C - callable library ( libcil.o ) ; all it does is register * a couple of functions and initialize CIL * creating a C-callable library (libcil.o); all it does is register * a couple of functions and initialize CIL *) module E = Errormsg open Cil print a ' file ' to stdout let unparseToStdout (cil : file) : unit = begin dumpFile defaultCilPrinter stdout cil end;; (* a visitor to unroll all types - may need to do some magic to keep attributes *) class unrollVisitorClass = object (self) inherit nopCilVisitor (* variable declaration *) method vvdec (vi : varinfo) : varinfo visitAction = begin vi.vtype <- unrollTypeDeep vi.vtype; ignore ( E.log " varinfo for % s in file ' % s ' line % d byte % d\n " vi.vname vi.vdecl.file vi.vdecl.line vi.vdecl.byte ) ; SkipChildren end (* global: need to unroll fields of compinfo *) method vglob (g : global) : global list visitAction = begin match g with GCompTag(ci, loc) as g -> let doFieldinfo (fi : fieldinfo) : unit = fi.ftype <- unrollTypeDeep fi.ftype in begin ignore(List.map doFieldinfo ci.cfields); (*ChangeTo [g]*) SkipChildren end | _ -> DoChildren end end;; let unrollVisitor = new unrollVisitorClass;; open and parse a C file into a ' file ' , unroll all typedefs let parseOneFile (fname: string) : file = let ast : file = Frontc.parse fname () in begin visitCilFile unrollVisitor ast; ast end ;; let getDummyTypes () : typ * typ = ( TPtr(TVoid [], []), TInt(IInt, []) ) ;; (* register some functions - these may be called from C code *) Callback.register "cil_parse" parseOneFile; Callback.register "cil_unparse" unparseToStdout; Callback.register " unroll_type_deep " unrollTypeDeep ; Callback.register "get_dummy_types" getDummyTypes; initalize CIL initCIL ();
null
https://raw.githubusercontent.com/heechul/crest-z3/cfcebadddb5e9d69e9956644fc37b46f6c2a21a0/cil/src/libmaincil.ml
ocaml
libmaincil a visitor to unroll all types - may need to do some magic to keep attributes variable declaration global: need to unroll fields of compinfo ChangeTo [g] register some functions - these may be called from C code
* * Copyright ( c ) 2001 - 2002 , * < > * < > * < > * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions are * met : * * 1 . Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * 3 . The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission . * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS * IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED * TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER * OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , * EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR * PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING * NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . * * * Copyright (c) 2001-2002, * George C. Necula <> * Scott McPeak <> * Wes Weimer <> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of the contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *) this is a replacement for maincil.ml , for the case when we 're * creating a C - callable library ( libcil.o ) ; all it does is register * a couple of functions and initialize CIL * creating a C-callable library (libcil.o); all it does is register * a couple of functions and initialize CIL *) module E = Errormsg open Cil print a ' file ' to stdout let unparseToStdout (cil : file) : unit = begin dumpFile defaultCilPrinter stdout cil end;; class unrollVisitorClass = object (self) inherit nopCilVisitor method vvdec (vi : varinfo) : varinfo visitAction = begin vi.vtype <- unrollTypeDeep vi.vtype; ignore ( E.log " varinfo for % s in file ' % s ' line % d byte % d\n " vi.vname vi.vdecl.file vi.vdecl.line vi.vdecl.byte ) ; SkipChildren end method vglob (g : global) : global list visitAction = begin match g with GCompTag(ci, loc) as g -> let doFieldinfo (fi : fieldinfo) : unit = fi.ftype <- unrollTypeDeep fi.ftype in begin ignore(List.map doFieldinfo ci.cfields); SkipChildren end | _ -> DoChildren end end;; let unrollVisitor = new unrollVisitorClass;; open and parse a C file into a ' file ' , unroll all typedefs let parseOneFile (fname: string) : file = let ast : file = Frontc.parse fname () in begin visitCilFile unrollVisitor ast; ast end ;; let getDummyTypes () : typ * typ = ( TPtr(TVoid [], []), TInt(IInt, []) ) ;; Callback.register "cil_parse" parseOneFile; Callback.register "cil_unparse" unparseToStdout; Callback.register " unroll_type_deep " unrollTypeDeep ; Callback.register "get_dummy_types" getDummyTypes; initalize CIL initCIL ();
e3766166c60b9e98d4c39cf52256530ea41598414887f80b105b9441ea86e7c7
binsec/haunted
sse.ml
(**************************************************************************) This file is part of BINSEC . (* *) Copyright ( C ) 2016 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Sse_types open Sse_options (* Enumerate jumps targets *) let get_entry_point () = match Kernel_functions.get_ep () with | Some v -> v | None -> Kernel_functions.get_img () |> Loader.Img.entry |> Virtual_address.create module type SSE_RUNNER = sig val start: unit -> unit end module Env_make(G: GLOBAL_ENV): SSE_RUNNER = struct module Stats = struct type t = { visited : int; (* Does not count the number uniquely visited paths but * should ... *) choices : int; } let empty = { visited = 0; choices = 0; } let add_visited s = { s with visited = s.visited + 1 } let add_choice s = { s with choices = s.choices + 1 } let pp ppf s = Format.fprintf ppf "@[<v 0>\ @[<h>selections %d@]@,\ @[<h>choice %d@]\ @]" s.visited s.choices ;; module R = struct let value = ref empty let add_visited () = value := add_visited !value let add_choice () = value := add_choice !value let pp ppf () = pp ppf !value end include R end module Env = struct type t = { global : G.t; local : Path_state.t; cfg : C.t; entrypoint : Virtual_address.t ; } let create ~global ~local = { global; local; cfg = Path_state.cfg local; entrypoint = Path_state.entrypoint local; } let local e = e.local let global e = e.global let of_global g = let global, local = G.Path.choose g in create ~global ~local let current_address e = Path_state.virtual_address @@ local e let goals_here e = G.Directives.at (current_address e) (global e) let choice_goals_here e = match goals_here e with | None -> [] | Some q -> Queue.fold (fun l d -> if Directive.is_choice d then d :: l else l) [] q let check_sat e = let sat_status, _ = Sse_smt.Solver.check_satistifiability e.local in sat_status let rec pick_path e = Stats.add_visited (); let e = of_global (global e) in check_sat_or_choose_another e and check_sat_or_choose_another e = let freq = Solver_call_frequency.get () in let n = Path_state.solver_calls e.local in if n = freq then match check_sat e with | Formula.SAT -> (* After a call, let's get back to the initial state *) let local = Path_state.reset_solver_calls e.local in { e with local } | _ -> pick_path e else let local = Path_state.incr_solver_calls e.local in { e with local } let is_good = function | None -> None | Some p -> if Path_state.may_lead_to_goal p then Some p else None let pick_alternative ~consequent ~alternative e = Stats.add_choice (); let do_pick ~first ~second = let global = G.(Path.add first e.global |> Path.add second) in pick_path { e with global } in match consequent, alternative with | None, None -> pick_path e | Some consequent, None -> {e with local = consequent} | None, Some alternative -> {e with local = alternative} | Some consequent, Some alternative -> let open Directive in match choice_goals_here e with | d :: ds -> if ds <> [] then Logger.warning "@[<h>%@ Ignoring %d choice directives@]" (List.length ds); begin match directive d with | Choice c -> let first, second = if Choice.is_alternative c then alternative, consequent else consequent, alternative in Choice.do_alternate c; do_pick ~first ~second | _ -> assert false end | [] -> let first, second = if Sse_options.Randomize.get () && Random.bool () then alternative, consequent else consequent, alternative in do_pick ~first ~second let add_if_good e path_state = match is_good (Some path_state) with | None -> Logger.info "Goal unreachable from@ %a" Path_state.pp_loc path_state; e | Some path_state -> { e with global = G.Path.add path_state e.global } end let halt e = Logger.info "@[<v 0>\ @[<v 2>SMT queries@,%a@]@,\ @[<v 2>Exploration@,%a@]@,\ @]" Sse_smt.Query_stats.pp () Stats.pp (); if Sse_options.Dot_filename_out.is_set () then let filename = Sse_options.Dot_filename_out.get () in Logger.info "Outputting CFG in %s" filename; let oc = open_out_bin filename in let cfg = e.Env.cfg in begin match C.mem_vertex_a cfg e.Env.entrypoint with | None -> () | Some entry -> C.output_graph oc e.Env.cfg [] ~entry end; close_out oc module Eval = struct let static_jump ~jump_target le = match jump_target with | Dba.JInner idx -> Some (Path_state.set_block_index idx le) | Dba.JOuter addr -> let vaddr = Dba_types.Caddress.to_virtual_address addr in Logger.debug ~level:5 "Jumping to new address %a" Virtual_address.pp vaddr; let open Sse_types.Path_state in match Path_state.counter vaddr le with | Some c -> begin match Address_counter.check_and_decr c with | Some c -> let p = Path_state.set_counter vaddr c le |> goto_vaddr vaddr in Some p | None -> Logger.debug "Cutting path at address %a : we reached the limit ..." Virtual_address.pp vaddr; None (* Could not decrement counter: should stop *) end | None -> Some (goto_vaddr vaddr le) (* lvalue <- e *) let assignment ~lvalue ~rvalue e = (* generate the logical constraint, add it to the path predicate, * update symbolic_state. *) let open Sse_smt in Env.{ e with local = Translate.assignment lvalue rvalue e.local } let nondet ~lvalue ~region e = let _ = region in (* generate the logical constraint, add it to the path predicate, * update symbolic_state. *) let open Sse_smt in Env.{ e with local = Translate.nondet lvalue e.local } let ite ~condition ~jump_target ~local_target e = (* expand path with assert condition and go to jump_target *) (* push path with assert not condition and go to local_target *) let state = Env.local e in let condition = let open Formula in let syst = Path_state.symbolic_state state in mk_bv_equal (Sse_smt.Translate.expr syst condition) mk_bv_one in let alternate_condition = Formula.mk_bl_not condition in let consequent = Path_state.add_assertion condition state |> static_jump ~jump_target in let alternate_state = Path_state.branch state in let alternative = Some ( Path_state.add_assertion alternate_condition alternate_state |> Sse_types.Path_state.set_block_index local_target) in Env.pick_alternative ~consequent ~alternative e let dynamic_jump ~jump_expr e = let img = Kernel_functions.get_img () in let path_state = Env.local e in let target = let symb_st = Path_state.symbolic_state path_state in Sse_smt.Translate.expr symb_st jump_expr in let n = Sse_options.JumpEnumDepth.get () in let concretes, path_state = Sse_smt.Solver.enumerate_values n target path_state in let with_bv env bv = let condition = Formula.(mk_bv_equal (mk_bv_cst bv) target) and addr = Virtual_address.of_bitvector bv and invalid bv = Logger.warning "@[<hov>Dynamic jump@ %a@ could have led to invalid address %a;@ \ skipping@]" Path_state.pp_loc path_state Bitvector.pp_hex bv; env in Logger.debug ~level:4 "@[<hov>Dynamic jump@ %a@ could lead to@ %a@]" Path_state.pp_loc path_state Bitvector.pp_hex bv; let address = Virtual_address.to_int addr in let section = Loader_utils.find_section_by_address ~address img in match section with | Some s when Loader.Section.has_flag Loader_types.Read s && Loader.Section.has_flag Loader_types.Exec s -> let ps = Path_state.add_assertion condition path_state in let ps = Sse_types.Path_state.goto_vaddr addr ps in Env.add_if_good env ps | Some _ | None -> invalid bv in let env = List.fold_left with_bv e concretes in Env.pick_path env let skip instruction idx e = Logger.info ~level:3 "Skipping %a" Dba_printer.Ascii.pp_instruction instruction; Env.{ e with local = Path_state.set_block_index idx e.local} (* If comment is activated, this will add, for every formula entry, a comment about where it comes from. This can be usefule to debug the path predicate translation. *) let maybe_add_comment ps = if Sse_options.Comment.get () then let syst = Path_state.symbolic_state ps in let comment = Print_utils.string_from_pp (Formula_pp.pp_as_comment Path_state.pp_loc) ps in let symbolic_state = Sse_symbolic.State.comment comment syst in Path_state.set_symbolic_state symbolic_state ps else ps let go e = let path_state = maybe_add_comment @@ Env.local e in Logger.debug ~level:5 "@[Evaluating@ %a@]" Path_state.pp_loc path_state; match Path_state.dba_instruction path_state with | Dba.Instr.Assign (lvalue, rvalue, idx) -> let e = assignment ~lvalue ~rvalue e in Env.{ e with local = Path_state.set_block_index idx e.local } | Dba.Instr.Nondet(lvalue,region,idx) -> let e = nondet ~lvalue ~region e in Env.{ e with local = Path_state.set_block_index idx e.local } | Dba.Instr.SJump (jump_target, _) -> begin match static_jump ~jump_target e.Env.local with | None -> (* This jump has been forbidden *) Env.pick_path e | Some local -> {e with Env.local} end | Dba.Instr.If (condition, jump_target, local_target) -> ite ~condition ~jump_target ~local_target e | Dba.Instr.DJump (je, _) -> dynamic_jump ~jump_expr:je e | Dba.Instr.Undef(_, idx) as instruction -> skip instruction idx e | Dba.Instr.Stop _ -> Discard current path , choose a new one Env.pick_path e | Dba.Instr.Assert _ | Dba.Instr.Assume _ | Dba.Instr.NondetAssume _ | Dba.Instr.Malloc _ | Dba.Instr.Free _ | Dba.Instr.Print _ | Dba.Instr.Serialize _ as dba_instruction -> let msg = Format.asprintf "%a" Dba_printer.Ascii.pp_instruction dba_instruction in Errors.not_yet_implemented msg end let sat_status p = fst @@ Sse_smt.Solver.check_satistifiability p type path_directive = | Continue | Discard let loop_until ~halt g = let get_vaddr e = Path_state.virtual_address @@ Env.local e in let e = Env.of_global g in let last_vaddr = ref (get_vaddr e) in let rec loop_aux e = let vaddr = get_vaddr e in if vaddr <> !last_vaddr then begin Logger.debug ~level:2 "%@%a %a" Virtual_address.pp vaddr Mnemonic.pp (Env.local e |> Path_state.inst |> Instruction.mnemonic) ; last_vaddr := vaddr; do_directives vaddr e end When the last virtual addresse has not changed , when are still in the same DBA block , hence no user action can have been performed . So , we just continue . same DBA block, hence no user action can have been performed. So, we just continue. *) else reloop e Continue and reloop e directive = if not @@ G.Directives.has (Env.global e) then halt e else let e_action = match directive with | Continue -> Eval.go | Discard -> Env.pick_path in match e_action e with | e -> loop_aux e | exception G.Path.Empty_worklist -> halt e and do_directives vaddr e = let glob = Env.global e in match G.Directives.at vaddr g with | None -> reloop e Continue | Some q -> let open Directive in (* q' is the new queue that will replace the old one. Uses side effects. *) let q' = Queue.create () in let rec handle_directives e path_directive = if Queue.is_empty q then begin if Queue.is_empty q' then G.Directives.remove vaddr glob else G.Directives.update vaddr q' glob; reloop e path_directive end else let g = Queue.take q in let p = Env.local e in match directive g with | Choice _ -> Branch choice is handled later on the DBA instruction itself Queue.add g q'; handle_directives e path_directive | Cut -> Queue.add g q'; Queue.clear q; Logger.result "@[<h>Directive :: cut %@ %a@]" Virtual_address.pp vaddr; handle_directives e Discard | Reach c -> Logger.debug "Reach"; begin match sat_status p with | Formula.SAT -> begin let c' = Count.decr c in Logger.result "@[<h>Directive :: reached address %a (%a to go)@]" Virtual_address.pp vaddr Count.pp c'; (match Sse_smt.Solver.get_model p with | Some m -> Logger.result "@[<v 0>Model %@ %a@ %a@]" Virtual_address.pp vaddr Smt_model.pp m; | None -> Logger.result "@[<h>No model %@ %a@]" Virtual_address.pp vaddr); (match c' with (* Do not add it to q', this is done*) | Count.Count 0 -> () | Count.Count n -> let loc = Loader_utils.Binary_loc.address vaddr in Queue.add (Directive.reach ~n loc) q' | Count.Unlimited -> Queue.add g q') ; handle_directives e path_directive end | status -> begin Logger.warning "@[<h>Directive :: reach \ reached address %a with %a \ (still %a to go)@]" Virtual_address.pp vaddr Formula_pp.pp_status status Count.pp c ; Queue.add g q'; (* It's not SAT - not counted as a reach *) handle_directives e Discard end end | Enumerate (k, ex) -> let e_fml = Sse_smt.Translate.expr (Path_state.symbolic_state p) ex in let enumerate_at_most k = let bv_vs, _p = Sse_smt.Solver.enumerate_values k e_fml p in G.Directives.Enumeration.record vaddr ex bv_vs glob; let n = G.Directives.Enumeration.count vaddr ex glob in let vs = G.Directives.Enumeration.get vaddr ex glob in Logger.result "@[<hov 0>Directive :: enumerate@ \ possible values (%d) for %a %@ %a:@ @[<hov 0>%a@]@]" n Dba_printer.EICAscii.pp_bl_term ex Virtual_address.pp vaddr (Print_utils.pp_list ~sep:",@ " Bitvector.pp) vs; n in (match k with | Count.Count k -> let m = k - enumerate_at_most k in if m > 0 then let loc = Loader_utils.Binary_loc.address vaddr in Queue.add (Directive.enumerate ~n:m ex loc) q' | Count.Unlimited -> Queue.add g q'; ignore @@ enumerate_at_most max_int ); handle_directives e path_directive | Assume expr -> let p = (* add comment *) let comment = Format.asprintf "@[<h>user constraint : assume %a @]" Dba_printer.EICAscii.pp_bl_term expr in Logger.debug "Assume %@ %a" Virtual_address.pp vaddr; let symb_state = Path_state.symbolic_state p |> Sse_symbolic.State.comment comment in Path_state.set_symbolic_state symb_state p in (* Adding the formula itself *) let local = Sse_smt.Translate.assume expr p in let e = Env.create ~global:glob ~local in Queue.add g q'; handle_directives e path_directive in handle_directives e Continue in let e = Env.of_global g in loop_aux e let interval_or_set_to_cond expr is = let open Parse_helpers.Initialization in match is with | Singleton _ -> assert false | Signed_interval (e1, e2) -> Dba.Expr.logand (Dba.Expr.sle e1 expr) (Dba.Expr.sle expr e2) | Unsigned_interval (e1, e2) -> Dba.Expr.logand (Dba.Expr.ule e1 expr) (Dba.Expr.ule expr e2) | Set l -> match l with | [] -> assert false | a :: b -> let f = Dba.Expr.equal expr in List.fold_left (fun acc e -> Dba.Expr.logor acc @@ f e) (f a) b let initialize_state ~filename ps = let ps = let cli_counters = Visit_address_counter.get () in match cli_counters with | [] -> ps | cs -> Logger.info "Found some address counters ... great"; let m = let open! Virtual_address in List.fold_left (fun m c -> Map.add c.Address_counter.address c m) Map.empty cs in Path_state.set_address_counters m ps in if not (Sys.file_exists filename) then begin Logger.warning "Cannot find sse configuration file %s" filename; ps end else let initials = Logger.debug "Reading initialization from %s" filename; let parser = Parser.initialization and lexer = Lexer.token in Parse_utils.read_file ~parser ~lexer ~filename in let f ps init = let open Parse_helpers.Initialization in match init.operation with | Mem_load (addr, size) -> Path_state.with_init_mem_at ps ~addr ~size | Universal lval -> begin match Dba_types.LValue.name_of lval with | Some name -> let symb = Path_state.symbolic_state ps in let size = Dba.LValue.size_of lval in let sort = Formula.BvSort size in let symb = Sse_symbolic.State.declare ~wild:true name sort symb in Path_state.set_symbolic_state symb ps | None -> ps end | Assignment (lval, rval, naming_hint) -> let wild = not init.controlled in match rval with | Singleton rv -> Sse_smt.Translate.assignment ~wild lval rv ps | x -> let state = Sse_smt.Translate.nondet ~wild ?naming_hint lval ps in let e = Dba.LValue.to_expr lval in let cond = interval_or_set_to_cond e x in Sse_smt.Translate.assume cond state in List.fold_left f ps initials let do_sse ~filename = let level = 3 in Logger.debug ~level "Running SSE on %s" filename; let entrypoint = get_entry_point () in Logger.debug ~level "Starting from %a" Virtual_address.pp entrypoint; let initialize_fun = initialize_state ~filename:(Sse_options.MemoryFile.get ()) in Logger.debug ~level "Initialization done ..."; Logger.debug ~level "Driver set ..."; loop_until ~halt (G.from_address ~initialize_fun ~entrypoint) let start () = let filename = Kernel_options.ExecFile.get () in do_sse ~filename end let run () = if Sse_options.is_enabled () && Kernel_options.ExecFile.is_set () then let (module H) = match Search_heuristics.get () with | Dfs -> (module Dfs_global:GLOBAL_ENV) | Bfs -> (module Bfs_global:GLOBAL_ENV) | Nurs -> let seed = match Seed.get_opt () with | Some s -> s | None -> let v = Utils.random_max_int () in Logger.info "Random search seed is %d" v; Seed.set v; v in Random.init seed; (module Nurs_global:GLOBAL_ENV) in let module S = Env_make(H) in S.start () let _ = Cli.Boot.enlist ~name:"SSE" ~f:run
null
https://raw.githubusercontent.com/binsec/haunted/f670f9a02fabc64e08c9f7b091b4a71d205d89a9/src/sse/sse.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ Enumerate jumps targets Does not count the number uniquely visited paths but * should ... After a call, let's get back to the initial state Could not decrement counter: should stop lvalue <- e generate the logical constraint, add it to the path predicate, * update symbolic_state. generate the logical constraint, add it to the path predicate, * update symbolic_state. expand path with assert condition and go to jump_target push path with assert not condition and go to local_target If comment is activated, this will add, for every formula entry, a comment about where it comes from. This can be usefule to debug the path predicate translation. This jump has been forbidden q' is the new queue that will replace the old one. Uses side effects. Do not add it to q', this is done It's not SAT - not counted as a reach add comment Adding the formula itself
This file is part of BINSEC . Copyright ( C ) 2016 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Sse_types open Sse_options let get_entry_point () = match Kernel_functions.get_ep () with | Some v -> v | None -> Kernel_functions.get_img () |> Loader.Img.entry |> Virtual_address.create module type SSE_RUNNER = sig val start: unit -> unit end module Env_make(G: GLOBAL_ENV): SSE_RUNNER = struct module Stats = struct type t = { choices : int; } let empty = { visited = 0; choices = 0; } let add_visited s = { s with visited = s.visited + 1 } let add_choice s = { s with choices = s.choices + 1 } let pp ppf s = Format.fprintf ppf "@[<v 0>\ @[<h>selections %d@]@,\ @[<h>choice %d@]\ @]" s.visited s.choices ;; module R = struct let value = ref empty let add_visited () = value := add_visited !value let add_choice () = value := add_choice !value let pp ppf () = pp ppf !value end include R end module Env = struct type t = { global : G.t; local : Path_state.t; cfg : C.t; entrypoint : Virtual_address.t ; } let create ~global ~local = { global; local; cfg = Path_state.cfg local; entrypoint = Path_state.entrypoint local; } let local e = e.local let global e = e.global let of_global g = let global, local = G.Path.choose g in create ~global ~local let current_address e = Path_state.virtual_address @@ local e let goals_here e = G.Directives.at (current_address e) (global e) let choice_goals_here e = match goals_here e with | None -> [] | Some q -> Queue.fold (fun l d -> if Directive.is_choice d then d :: l else l) [] q let check_sat e = let sat_status, _ = Sse_smt.Solver.check_satistifiability e.local in sat_status let rec pick_path e = Stats.add_visited (); let e = of_global (global e) in check_sat_or_choose_another e and check_sat_or_choose_another e = let freq = Solver_call_frequency.get () in let n = Path_state.solver_calls e.local in if n = freq then match check_sat e with | Formula.SAT -> let local = Path_state.reset_solver_calls e.local in { e with local } | _ -> pick_path e else let local = Path_state.incr_solver_calls e.local in { e with local } let is_good = function | None -> None | Some p -> if Path_state.may_lead_to_goal p then Some p else None let pick_alternative ~consequent ~alternative e = Stats.add_choice (); let do_pick ~first ~second = let global = G.(Path.add first e.global |> Path.add second) in pick_path { e with global } in match consequent, alternative with | None, None -> pick_path e | Some consequent, None -> {e with local = consequent} | None, Some alternative -> {e with local = alternative} | Some consequent, Some alternative -> let open Directive in match choice_goals_here e with | d :: ds -> if ds <> [] then Logger.warning "@[<h>%@ Ignoring %d choice directives@]" (List.length ds); begin match directive d with | Choice c -> let first, second = if Choice.is_alternative c then alternative, consequent else consequent, alternative in Choice.do_alternate c; do_pick ~first ~second | _ -> assert false end | [] -> let first, second = if Sse_options.Randomize.get () && Random.bool () then alternative, consequent else consequent, alternative in do_pick ~first ~second let add_if_good e path_state = match is_good (Some path_state) with | None -> Logger.info "Goal unreachable from@ %a" Path_state.pp_loc path_state; e | Some path_state -> { e with global = G.Path.add path_state e.global } end let halt e = Logger.info "@[<v 0>\ @[<v 2>SMT queries@,%a@]@,\ @[<v 2>Exploration@,%a@]@,\ @]" Sse_smt.Query_stats.pp () Stats.pp (); if Sse_options.Dot_filename_out.is_set () then let filename = Sse_options.Dot_filename_out.get () in Logger.info "Outputting CFG in %s" filename; let oc = open_out_bin filename in let cfg = e.Env.cfg in begin match C.mem_vertex_a cfg e.Env.entrypoint with | None -> () | Some entry -> C.output_graph oc e.Env.cfg [] ~entry end; close_out oc module Eval = struct let static_jump ~jump_target le = match jump_target with | Dba.JInner idx -> Some (Path_state.set_block_index idx le) | Dba.JOuter addr -> let vaddr = Dba_types.Caddress.to_virtual_address addr in Logger.debug ~level:5 "Jumping to new address %a" Virtual_address.pp vaddr; let open Sse_types.Path_state in match Path_state.counter vaddr le with | Some c -> begin match Address_counter.check_and_decr c with | Some c -> let p = Path_state.set_counter vaddr c le |> goto_vaddr vaddr in Some p | None -> Logger.debug "Cutting path at address %a : we reached the limit ..." Virtual_address.pp vaddr; None end | None -> Some (goto_vaddr vaddr le) let assignment ~lvalue ~rvalue e = let open Sse_smt in Env.{ e with local = Translate.assignment lvalue rvalue e.local } let nondet ~lvalue ~region e = let _ = region in let open Sse_smt in Env.{ e with local = Translate.nondet lvalue e.local } let ite ~condition ~jump_target ~local_target e = let state = Env.local e in let condition = let open Formula in let syst = Path_state.symbolic_state state in mk_bv_equal (Sse_smt.Translate.expr syst condition) mk_bv_one in let alternate_condition = Formula.mk_bl_not condition in let consequent = Path_state.add_assertion condition state |> static_jump ~jump_target in let alternate_state = Path_state.branch state in let alternative = Some ( Path_state.add_assertion alternate_condition alternate_state |> Sse_types.Path_state.set_block_index local_target) in Env.pick_alternative ~consequent ~alternative e let dynamic_jump ~jump_expr e = let img = Kernel_functions.get_img () in let path_state = Env.local e in let target = let symb_st = Path_state.symbolic_state path_state in Sse_smt.Translate.expr symb_st jump_expr in let n = Sse_options.JumpEnumDepth.get () in let concretes, path_state = Sse_smt.Solver.enumerate_values n target path_state in let with_bv env bv = let condition = Formula.(mk_bv_equal (mk_bv_cst bv) target) and addr = Virtual_address.of_bitvector bv and invalid bv = Logger.warning "@[<hov>Dynamic jump@ %a@ could have led to invalid address %a;@ \ skipping@]" Path_state.pp_loc path_state Bitvector.pp_hex bv; env in Logger.debug ~level:4 "@[<hov>Dynamic jump@ %a@ could lead to@ %a@]" Path_state.pp_loc path_state Bitvector.pp_hex bv; let address = Virtual_address.to_int addr in let section = Loader_utils.find_section_by_address ~address img in match section with | Some s when Loader.Section.has_flag Loader_types.Read s && Loader.Section.has_flag Loader_types.Exec s -> let ps = Path_state.add_assertion condition path_state in let ps = Sse_types.Path_state.goto_vaddr addr ps in Env.add_if_good env ps | Some _ | None -> invalid bv in let env = List.fold_left with_bv e concretes in Env.pick_path env let skip instruction idx e = Logger.info ~level:3 "Skipping %a" Dba_printer.Ascii.pp_instruction instruction; Env.{ e with local = Path_state.set_block_index idx e.local} let maybe_add_comment ps = if Sse_options.Comment.get () then let syst = Path_state.symbolic_state ps in let comment = Print_utils.string_from_pp (Formula_pp.pp_as_comment Path_state.pp_loc) ps in let symbolic_state = Sse_symbolic.State.comment comment syst in Path_state.set_symbolic_state symbolic_state ps else ps let go e = let path_state = maybe_add_comment @@ Env.local e in Logger.debug ~level:5 "@[Evaluating@ %a@]" Path_state.pp_loc path_state; match Path_state.dba_instruction path_state with | Dba.Instr.Assign (lvalue, rvalue, idx) -> let e = assignment ~lvalue ~rvalue e in Env.{ e with local = Path_state.set_block_index idx e.local } | Dba.Instr.Nondet(lvalue,region,idx) -> let e = nondet ~lvalue ~region e in Env.{ e with local = Path_state.set_block_index idx e.local } | Dba.Instr.SJump (jump_target, _) -> begin match static_jump ~jump_target e.Env.local with Env.pick_path e | Some local -> {e with Env.local} end | Dba.Instr.If (condition, jump_target, local_target) -> ite ~condition ~jump_target ~local_target e | Dba.Instr.DJump (je, _) -> dynamic_jump ~jump_expr:je e | Dba.Instr.Undef(_, idx) as instruction -> skip instruction idx e | Dba.Instr.Stop _ -> Discard current path , choose a new one Env.pick_path e | Dba.Instr.Assert _ | Dba.Instr.Assume _ | Dba.Instr.NondetAssume _ | Dba.Instr.Malloc _ | Dba.Instr.Free _ | Dba.Instr.Print _ | Dba.Instr.Serialize _ as dba_instruction -> let msg = Format.asprintf "%a" Dba_printer.Ascii.pp_instruction dba_instruction in Errors.not_yet_implemented msg end let sat_status p = fst @@ Sse_smt.Solver.check_satistifiability p type path_directive = | Continue | Discard let loop_until ~halt g = let get_vaddr e = Path_state.virtual_address @@ Env.local e in let e = Env.of_global g in let last_vaddr = ref (get_vaddr e) in let rec loop_aux e = let vaddr = get_vaddr e in if vaddr <> !last_vaddr then begin Logger.debug ~level:2 "%@%a %a" Virtual_address.pp vaddr Mnemonic.pp (Env.local e |> Path_state.inst |> Instruction.mnemonic) ; last_vaddr := vaddr; do_directives vaddr e end When the last virtual addresse has not changed , when are still in the same DBA block , hence no user action can have been performed . So , we just continue . same DBA block, hence no user action can have been performed. So, we just continue. *) else reloop e Continue and reloop e directive = if not @@ G.Directives.has (Env.global e) then halt e else let e_action = match directive with | Continue -> Eval.go | Discard -> Env.pick_path in match e_action e with | e -> loop_aux e | exception G.Path.Empty_worklist -> halt e and do_directives vaddr e = let glob = Env.global e in match G.Directives.at vaddr g with | None -> reloop e Continue | Some q -> let open Directive in let q' = Queue.create () in let rec handle_directives e path_directive = if Queue.is_empty q then begin if Queue.is_empty q' then G.Directives.remove vaddr glob else G.Directives.update vaddr q' glob; reloop e path_directive end else let g = Queue.take q in let p = Env.local e in match directive g with | Choice _ -> Branch choice is handled later on the DBA instruction itself Queue.add g q'; handle_directives e path_directive | Cut -> Queue.add g q'; Queue.clear q; Logger.result "@[<h>Directive :: cut %@ %a@]" Virtual_address.pp vaddr; handle_directives e Discard | Reach c -> Logger.debug "Reach"; begin match sat_status p with | Formula.SAT -> begin let c' = Count.decr c in Logger.result "@[<h>Directive :: reached address %a (%a to go)@]" Virtual_address.pp vaddr Count.pp c'; (match Sse_smt.Solver.get_model p with | Some m -> Logger.result "@[<v 0>Model %@ %a@ %a@]" Virtual_address.pp vaddr Smt_model.pp m; | None -> Logger.result "@[<h>No model %@ %a@]" Virtual_address.pp vaddr); (match c' with | Count.Count 0 -> () | Count.Count n -> let loc = Loader_utils.Binary_loc.address vaddr in Queue.add (Directive.reach ~n loc) q' | Count.Unlimited -> Queue.add g q') ; handle_directives e path_directive end | status -> begin Logger.warning "@[<h>Directive :: reach \ reached address %a with %a \ (still %a to go)@]" Virtual_address.pp vaddr Formula_pp.pp_status status Count.pp c ; Queue.add g q'; handle_directives e Discard end end | Enumerate (k, ex) -> let e_fml = Sse_smt.Translate.expr (Path_state.symbolic_state p) ex in let enumerate_at_most k = let bv_vs, _p = Sse_smt.Solver.enumerate_values k e_fml p in G.Directives.Enumeration.record vaddr ex bv_vs glob; let n = G.Directives.Enumeration.count vaddr ex glob in let vs = G.Directives.Enumeration.get vaddr ex glob in Logger.result "@[<hov 0>Directive :: enumerate@ \ possible values (%d) for %a %@ %a:@ @[<hov 0>%a@]@]" n Dba_printer.EICAscii.pp_bl_term ex Virtual_address.pp vaddr (Print_utils.pp_list ~sep:",@ " Bitvector.pp) vs; n in (match k with | Count.Count k -> let m = k - enumerate_at_most k in if m > 0 then let loc = Loader_utils.Binary_loc.address vaddr in Queue.add (Directive.enumerate ~n:m ex loc) q' | Count.Unlimited -> Queue.add g q'; ignore @@ enumerate_at_most max_int ); handle_directives e path_directive | Assume expr -> let p = let comment = Format.asprintf "@[<h>user constraint : assume %a @]" Dba_printer.EICAscii.pp_bl_term expr in Logger.debug "Assume %@ %a" Virtual_address.pp vaddr; let symb_state = Path_state.symbolic_state p |> Sse_symbolic.State.comment comment in Path_state.set_symbolic_state symb_state p in let local = Sse_smt.Translate.assume expr p in let e = Env.create ~global:glob ~local in Queue.add g q'; handle_directives e path_directive in handle_directives e Continue in let e = Env.of_global g in loop_aux e let interval_or_set_to_cond expr is = let open Parse_helpers.Initialization in match is with | Singleton _ -> assert false | Signed_interval (e1, e2) -> Dba.Expr.logand (Dba.Expr.sle e1 expr) (Dba.Expr.sle expr e2) | Unsigned_interval (e1, e2) -> Dba.Expr.logand (Dba.Expr.ule e1 expr) (Dba.Expr.ule expr e2) | Set l -> match l with | [] -> assert false | a :: b -> let f = Dba.Expr.equal expr in List.fold_left (fun acc e -> Dba.Expr.logor acc @@ f e) (f a) b let initialize_state ~filename ps = let ps = let cli_counters = Visit_address_counter.get () in match cli_counters with | [] -> ps | cs -> Logger.info "Found some address counters ... great"; let m = let open! Virtual_address in List.fold_left (fun m c -> Map.add c.Address_counter.address c m) Map.empty cs in Path_state.set_address_counters m ps in if not (Sys.file_exists filename) then begin Logger.warning "Cannot find sse configuration file %s" filename; ps end else let initials = Logger.debug "Reading initialization from %s" filename; let parser = Parser.initialization and lexer = Lexer.token in Parse_utils.read_file ~parser ~lexer ~filename in let f ps init = let open Parse_helpers.Initialization in match init.operation with | Mem_load (addr, size) -> Path_state.with_init_mem_at ps ~addr ~size | Universal lval -> begin match Dba_types.LValue.name_of lval with | Some name -> let symb = Path_state.symbolic_state ps in let size = Dba.LValue.size_of lval in let sort = Formula.BvSort size in let symb = Sse_symbolic.State.declare ~wild:true name sort symb in Path_state.set_symbolic_state symb ps | None -> ps end | Assignment (lval, rval, naming_hint) -> let wild = not init.controlled in match rval with | Singleton rv -> Sse_smt.Translate.assignment ~wild lval rv ps | x -> let state = Sse_smt.Translate.nondet ~wild ?naming_hint lval ps in let e = Dba.LValue.to_expr lval in let cond = interval_or_set_to_cond e x in Sse_smt.Translate.assume cond state in List.fold_left f ps initials let do_sse ~filename = let level = 3 in Logger.debug ~level "Running SSE on %s" filename; let entrypoint = get_entry_point () in Logger.debug ~level "Starting from %a" Virtual_address.pp entrypoint; let initialize_fun = initialize_state ~filename:(Sse_options.MemoryFile.get ()) in Logger.debug ~level "Initialization done ..."; Logger.debug ~level "Driver set ..."; loop_until ~halt (G.from_address ~initialize_fun ~entrypoint) let start () = let filename = Kernel_options.ExecFile.get () in do_sse ~filename end let run () = if Sse_options.is_enabled () && Kernel_options.ExecFile.is_set () then let (module H) = match Search_heuristics.get () with | Dfs -> (module Dfs_global:GLOBAL_ENV) | Bfs -> (module Bfs_global:GLOBAL_ENV) | Nurs -> let seed = match Seed.get_opt () with | Some s -> s | None -> let v = Utils.random_max_int () in Logger.info "Random search seed is %d" v; Seed.set v; v in Random.init seed; (module Nurs_global:GLOBAL_ENV) in let module S = Env_make(H) in S.start () let _ = Cli.Boot.enlist ~name:"SSE" ~f:run
f46be52a305e2d7d57fd65342432f15973d3287e7bdd8ad31ef710ac9ac9092a
psilord/option-9
game.lisp
Copyright 2010 ( ) ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; you ;; may not use this file except in compliance with the License. You may ;; obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express ;; or implied. See the License for the specific language governing ;; permissions and limitations under the License. (in-package #:option-9) #+option-9-debug (declaim (optimize (safety 3) (space 0) (speed 0) (debug 3))) (defun make-game (&key (window-width +game-width+) (window-height +game-height+) (game-width +game-width+) (game-height +game-height+)) (let ((game (make-instance 'game :scene-man (make-instance 'scene-manager) :window-width window-width :window-height window-height :game-width game-width :game-height game-height))) ;; and we insert our game context into the universe drawable... (setf (game-context (root (scene-man game))) game) game)) (defun window-aspect-ratio (game) (coerce (/ (window-width game) (window-height game)) 'double-float)) (defun game-aspect-ratio (game) (coerce (/ (game-width game) (game-height game)) 'double-float)) (defmethod per-window-width ((game game) percentage) (coerce (* (window-width game) percentage) 'double-float)) (defmethod per-window-width ((drawable drawable) percentage) (coerce (per-window-width (game-context drawable) percentage) 'double-float)) (defmethod per-window-height ((game game) percentage) (coerce (* (window-height game) percentage) 'double-float)) (defmethod per-window-height ((drawable drawable) percentage) (coerce (per-window-height (game-context drawable) percentage) 'double-float)) (defmethod per-game-width ((game game) percentage) (coerce (* (game-width game) (/ percentage 100d0)) 'double-float)) (defmethod per-game-width ((drawable drawable) percentage) (coerce (per-game-width (game-context drawable) percentage) 'double-float)) (defmethod per-game-height ((game game) percentage) (coerce (* (game-height game) (/ percentage 100d0)) 'double-float)) (defmethod per-game-height ((drawable drawable) percentage) (coerce (per-game-height (game-context drawable) percentage) 'double-float)) (defun add-spawnable (spawnable game) (push spawnable (spawnables game))) (defun clear-spawnables (game) (setf (spawnables game) nil)) (defun toggle-paused (g) (if (paused g) (setf (paused g) nil) (setf (paused g) t))) (defmacro with-game-init ((filename &key (window-width +game-width+) (window-height +game-height+) (game-width +game-width+) (game-height +game-height+)) &body body) ;; The let* is important to bind *id* before MAKE-GAME is called. `(let* ((*assets* (load-dat-file ,filename)) (*id* 0) (*game* (make-game :window-width ,window-width :window-height ,window-height :game-width ,game-width :game-height ,game-height))) ,@body)) (defun move-player-keyboard (game state dir) XXX this is for player one and it only assumes one player ! (let ((p (car (entities-with-role (scene-man game) :player)))) (when p (ecase state (:begin (ecase dir (:up (setf (dfvy p) (per-hz (forward-speed p)))) (:down (setf (dfvy p) (per-hz (* 0.75 (backward-speed p))))) (:left (setf (dfvx p) (per-hz (strafe-left-speed p)))) (:right (setf (dfvx p) (per-hz (strafe-right-speed p)))))) (:end (ecase dir (:up (when (> (dfvy p) (? :v-zero)) (setf (dfvy p) (? :v-zero)))) (:down (when (< (dfvy p) (? :v-zero)) (setf (dfvy p) (? :v-zero)))) (:left (when (< (dfvx p) (? :v-zero)) (setf (dfvx p) (? :v-zero)))) (:right (when (> (dfvx p) (? :v-zero)) (setf (dfvx p) (? :v-zero)))))))))) (defun move-player-joystick (game axis amount) (let ((p (car (entities-with-role (scene-man game) :player)))) (when p (cond ((= axis 1);; y axis (setf (dfvy p) (* -1d0 1.5d0 amount))) ((= axis 0) ;; x axis (setf (dfvx p) (* 1.5d0 amount))))))) TODO : this into a higher order function loop with flet and lambdas . ;; Get rid of the INTEGER->LIST call and just do it raw. (defun realize-score-boards (game) (when (modified-score-p game) ;; don't redraw unless required. (let ((db #(:digit-0 :digit-1 :digit-2 :digit-3 :digit-4 :digit-5 :digit-6 :digit-7 :digit-8 :digit-9))) (flet ((update-score (xstart ystart the-score role) First , remove from the scene the current score . (dolist (digit (entities-with-role (scene-man game) role)) (remove-from-scene (scene-man game) digit)) ;; Then add the new score into the scene. (let ((xstart xstart) (xstep -2) (ci 0)) (cond ((zerop the-score) (spawn 'sp-alphanum :digit-0 (pvec (coerce (+ xstart (* xstep ci)) 'double-float) ystart 0d0) game :roles `(,role))) (t Strip off the ones place each iteration and ;; write the number from right to left. (loop with num = the-score until (zerop num) do (multiple-value-bind (q r) (floor num 10) (spawn 'sp-alphanum (aref db r) (pvec (coerce (+ xstart (* xstep ci)) 'double-float) ystart 0d0) game :roles `(,role)) (incf ci) (setf num q) r))))))) ;; realize the score board (update-score (per-game-width game 85.0) (per-game-height game 98.0) (score game) :score-board) ;; realize the high score board (update-score (per-game-width game 15.0) (per-game-height game 98.0) (highscore game) :high-score-board) (setf (modified-score-p game) nil))))) (defun reset-score-to-zero (game) (setf (score game) 0 (modified-score-p game) t)) (defun modify-score (game points) (incf (score game) points) (setf (modified-score-p game) t) (when (< (score game) 0) (setf (score game) 0)) (when (> (score game) (highscore game)) (incf (highscore game) (- (score game) (highscore game))))) (defun display (game jutter-interpolant) (gl:clear :color-buffer-bit :depth-buffer-bit) (walk-frame-hierarchy (root (scene-man game)) (lambda (entity) (render entity jutter-interpolant)))) (defun step-game (game) (unless (paused game) (let ((scene (scene-man game))) 1 . If there is no player , spawn one . (unless (entities-with-role scene :player) (reset-score-to-zero game) (spawn 'sp-player :player-1 NIL game)) 2 . If enough time as passed , spawn an enemy ;;#+ignore (progn (decf (enemy-spawn-timer game)) (when (zerop (enemy-spawn-timer game)) (setf (enemy-spawn-timer game) (1+ (random 90))) ;; Just pick a random enemy from the various enemy instances (spawn 'sp-enemy :insts/enemies NIL game)) ) 3 . Show the score boards (realize-score-boards game) 4 . If possible , make concrete all currently pending spawns into ;; the scene tree. This makes them actually show up in the game ;; world. (realize-spawns game) 5 . After the spawns , THEN compute where everyone is to take into consideration one time translation vectors , flight , ;; rotation. (walk-frame-hierarchy (root scene) #'(lambda (frame) (active-step-once frame) (resolve-world-basis frame))) 5 . Note : This can not be folded into the above walk . Passive ;; effects require a fully computed world-basis for all objects ;; since the passive effects (generally fields and such things) ;; compute intersections with other objects in the world and all ;; physical locations must be resolved before those intersections ;; can happen. (walk-frame-hierarchy (root scene) #'passive-step-once) 7 . Each brain - entity can now think about what it wants to do ;; since the only left in the world are things that have survived ;; colliding, clipping, and time to live. It may shoot, change its ;; direction vector, insert other objects into the scene, or do ;; something else. (walk-frame-hierarchy (root scene) #'think) 8 . Perform collision detection between all of the collision ;; sets (dolist (plan (collision-plan *assets*)) (destructuring-bind (role-fists role-faces) plan (let ((fist-entities (apply #'all-entities-in-roles scene role-fists)) (face-entities (apply #'all-entities-in-roles scene role-faces))) ;; Only loop at all if there are things to collide! (when (and fist-entities face-entities) (dolist (fist fist-entities) (dolist (face face-entities) (collide fist face))))))) 8 . removal of not alive objects out of the world . (flet ((remove-y/n (e) (not (alivep e))) ;; make this a method like UPON-DEATH or something. XXX ;; Or maybe DIE is the right place for modify-score to be ;; called since that is not called on stale things. Hrm, ;; need to think about it. (assign-points-y/n (e) (when (deadp e) (modify-score game (points e))))) ;; XXX Check for hash-table removal violation problems, if any. (let ((all-views (views scene))) (loop for role being the hash-keys of all-views do ;; Figure out what needs to be removed for this role. (let ((removable-entities (remove-if-not #'remove-y/n (gethash role all-views)))) (dolist (ent removable-entities) ;; assign points if needed (assign-points-y/n ent) ;; Then actually remove it from the scene tree and ;; all views. (remove-from-scene scene ent)))))) )))
null
https://raw.githubusercontent.com/psilord/option-9/b5f35a482a9ea637c06dfa389b3df3acc0d8ca55/game.lisp
lisp
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. and we insert our game context into the universe drawable... The let* is important to bind *id* before MAKE-GAME is called. y axis x axis Get rid of the INTEGER->LIST call and just do it raw. don't redraw unless required. Then add the new score into the scene. write the number from right to left. realize the score board realize the high score board #+ignore Just pick a random enemy from the various enemy instances the scene tree. This makes them actually show up in the game world. rotation. effects require a fully computed world-basis for all objects since the passive effects (generally fields and such things) compute intersections with other objects in the world and all physical locations must be resolved before those intersections can happen. since the only left in the world are things that have survived colliding, clipping, and time to live. It may shoot, change its direction vector, insert other objects into the scene, or do something else. sets Only loop at all if there are things to collide! make this a method like UPON-DEATH or something. XXX Or maybe DIE is the right place for modify-score to be called since that is not called on stale things. Hrm, need to think about it. XXX Check for hash-table removal violation problems, if any. Figure out what needs to be removed for this role. assign points if needed Then actually remove it from the scene tree and all views.
Copyright 2010 ( ) distributed under the License is distributed on an " AS IS " BASIS , (in-package #:option-9) #+option-9-debug (declaim (optimize (safety 3) (space 0) (speed 0) (debug 3))) (defun make-game (&key (window-width +game-width+) (window-height +game-height+) (game-width +game-width+) (game-height +game-height+)) (let ((game (make-instance 'game :scene-man (make-instance 'scene-manager) :window-width window-width :window-height window-height :game-width game-width :game-height game-height))) (setf (game-context (root (scene-man game))) game) game)) (defun window-aspect-ratio (game) (coerce (/ (window-width game) (window-height game)) 'double-float)) (defun game-aspect-ratio (game) (coerce (/ (game-width game) (game-height game)) 'double-float)) (defmethod per-window-width ((game game) percentage) (coerce (* (window-width game) percentage) 'double-float)) (defmethod per-window-width ((drawable drawable) percentage) (coerce (per-window-width (game-context drawable) percentage) 'double-float)) (defmethod per-window-height ((game game) percentage) (coerce (* (window-height game) percentage) 'double-float)) (defmethod per-window-height ((drawable drawable) percentage) (coerce (per-window-height (game-context drawable) percentage) 'double-float)) (defmethod per-game-width ((game game) percentage) (coerce (* (game-width game) (/ percentage 100d0)) 'double-float)) (defmethod per-game-width ((drawable drawable) percentage) (coerce (per-game-width (game-context drawable) percentage) 'double-float)) (defmethod per-game-height ((game game) percentage) (coerce (* (game-height game) (/ percentage 100d0)) 'double-float)) (defmethod per-game-height ((drawable drawable) percentage) (coerce (per-game-height (game-context drawable) percentage) 'double-float)) (defun add-spawnable (spawnable game) (push spawnable (spawnables game))) (defun clear-spawnables (game) (setf (spawnables game) nil)) (defun toggle-paused (g) (if (paused g) (setf (paused g) nil) (setf (paused g) t))) (defmacro with-game-init ((filename &key (window-width +game-width+) (window-height +game-height+) (game-width +game-width+) (game-height +game-height+)) &body body) `(let* ((*assets* (load-dat-file ,filename)) (*id* 0) (*game* (make-game :window-width ,window-width :window-height ,window-height :game-width ,game-width :game-height ,game-height))) ,@body)) (defun move-player-keyboard (game state dir) XXX this is for player one and it only assumes one player ! (let ((p (car (entities-with-role (scene-man game) :player)))) (when p (ecase state (:begin (ecase dir (:up (setf (dfvy p) (per-hz (forward-speed p)))) (:down (setf (dfvy p) (per-hz (* 0.75 (backward-speed p))))) (:left (setf (dfvx p) (per-hz (strafe-left-speed p)))) (:right (setf (dfvx p) (per-hz (strafe-right-speed p)))))) (:end (ecase dir (:up (when (> (dfvy p) (? :v-zero)) (setf (dfvy p) (? :v-zero)))) (:down (when (< (dfvy p) (? :v-zero)) (setf (dfvy p) (? :v-zero)))) (:left (when (< (dfvx p) (? :v-zero)) (setf (dfvx p) (? :v-zero)))) (:right (when (> (dfvx p) (? :v-zero)) (setf (dfvx p) (? :v-zero)))))))))) (defun move-player-joystick (game axis amount) (let ((p (car (entities-with-role (scene-man game) :player)))) (when p (cond (setf (dfvy p) (* -1d0 1.5d0 amount))) (setf (dfvx p) (* 1.5d0 amount))))))) TODO : this into a higher order function loop with flet and lambdas . (defun realize-score-boards (game) (let ((db #(:digit-0 :digit-1 :digit-2 :digit-3 :digit-4 :digit-5 :digit-6 :digit-7 :digit-8 :digit-9))) (flet ((update-score (xstart ystart the-score role) First , remove from the scene the current score . (dolist (digit (entities-with-role (scene-man game) role)) (remove-from-scene (scene-man game) digit)) (let ((xstart xstart) (xstep -2) (ci 0)) (cond ((zerop the-score) (spawn 'sp-alphanum :digit-0 (pvec (coerce (+ xstart (* xstep ci)) 'double-float) ystart 0d0) game :roles `(,role))) (t Strip off the ones place each iteration and (loop with num = the-score until (zerop num) do (multiple-value-bind (q r) (floor num 10) (spawn 'sp-alphanum (aref db r) (pvec (coerce (+ xstart (* xstep ci)) 'double-float) ystart 0d0) game :roles `(,role)) (incf ci) (setf num q) r))))))) (update-score (per-game-width game 85.0) (per-game-height game 98.0) (score game) :score-board) (update-score (per-game-width game 15.0) (per-game-height game 98.0) (highscore game) :high-score-board) (setf (modified-score-p game) nil))))) (defun reset-score-to-zero (game) (setf (score game) 0 (modified-score-p game) t)) (defun modify-score (game points) (incf (score game) points) (setf (modified-score-p game) t) (when (< (score game) 0) (setf (score game) 0)) (when (> (score game) (highscore game)) (incf (highscore game) (- (score game) (highscore game))))) (defun display (game jutter-interpolant) (gl:clear :color-buffer-bit :depth-buffer-bit) (walk-frame-hierarchy (root (scene-man game)) (lambda (entity) (render entity jutter-interpolant)))) (defun step-game (game) (unless (paused game) (let ((scene (scene-man game))) 1 . If there is no player , spawn one . (unless (entities-with-role scene :player) (reset-score-to-zero game) (spawn 'sp-player :player-1 NIL game)) 2 . If enough time as passed , spawn an enemy (progn (decf (enemy-spawn-timer game)) (when (zerop (enemy-spawn-timer game)) (setf (enemy-spawn-timer game) (1+ (random 90))) (spawn 'sp-enemy :insts/enemies NIL game)) ) 3 . Show the score boards (realize-score-boards game) 4 . If possible , make concrete all currently pending spawns into (realize-spawns game) 5 . After the spawns , THEN compute where everyone is to take into consideration one time translation vectors , flight , (walk-frame-hierarchy (root scene) #'(lambda (frame) (active-step-once frame) (resolve-world-basis frame))) 5 . Note : This can not be folded into the above walk . Passive (walk-frame-hierarchy (root scene) #'passive-step-once) 7 . Each brain - entity can now think about what it wants to do (walk-frame-hierarchy (root scene) #'think) 8 . Perform collision detection between all of the collision (dolist (plan (collision-plan *assets*)) (destructuring-bind (role-fists role-faces) plan (let ((fist-entities (apply #'all-entities-in-roles scene role-fists)) (face-entities (apply #'all-entities-in-roles scene role-faces))) (when (and fist-entities face-entities) (dolist (fist fist-entities) (dolist (face face-entities) (collide fist face))))))) 8 . removal of not alive objects out of the world . (flet ((remove-y/n (e) (not (alivep e))) (assign-points-y/n (e) (when (deadp e) (modify-score game (points e))))) (let ((all-views (views scene))) (loop for role being the hash-keys of all-views do (let ((removable-entities (remove-if-not #'remove-y/n (gethash role all-views)))) (dolist (ent removable-entities) (assign-points-y/n ent) (remove-from-scene scene ent)))))) )))
7d2c287ea84be88681b35da0f33524451005243cd8ca6b012202938d805abf36
stedolan/mlsub
location.ml
open Lexing type source = { name : string; contents : string; (* (start, end) positions of lines, including newline *) lines : (int * int) list } type t = Loc of source * int * int module type Locator = sig val pos : Lexing.position * Lexing.position -> t end Split a string by a delimiter . are included in the result , so concatenating the output gives the original string so concatenating the output gives the original string *) let rec split_term r s = let open Str in let item ss = ss |> List.rev |> String.concat "" in let rec join res acc = function | [] -> List.rev (match acc with | [] -> res | _ -> item acc :: res) | Text s :: rest -> join res (s :: acc) rest | Delim s :: rest -> join (item (s :: acc) :: res) [] rest in join [] [] (full_split r s) let source name contents = let rec lines p = function | [] -> [] | s :: ss -> let p' = p + String.length s in (p, p') :: lines p' ss in { name; contents; lines = lines 0 (split_term (Str.regexp "\n") contents) } let slurp chan = let rec read_all chunks = let buf = Bytes.init 4096 (fun _ -> '\x00') in match (input chan buf 0 (Bytes.length buf)) with | 0 -> Bytes.concat (Bytes.of_string "") (List.rev chunks) | n -> read_all (Bytes.sub buf 0 n :: chunks) in read_all [] let of_file fname = source fname (slurp (open_in fname)) let of_string str = source "<input>" str type linepart = { txt : string; lineno : int; startpos : int; endpos : int } type source_loc = | Line of linepart | Multiline of linepart * linepart let get_source_loc (Loc (src, p, q)) = (* As a special case, report the location of end-of-file as the last character *) let (p, q) = match (p, q) with | (p, q) when p = q && p = String.length src.contents -> (p-1, q) | _ -> p, q in let line i s e = { txt = String.sub src.contents s (e - s); lineno = i; startpos = max 0 (p - s); endpos = min (e - s) (q - s) } in src.lines |> List.mapi (fun i (s, e) -> (i, s, e)) |> List.filter (fun (i, s, e) -> p < e && s < q) |> function | [] -> failwith "internal error: bad location" | [(i, s, e)] -> Line (line i s e) | (i, s, e) :: rest -> let (i', s', e') = List.(hd (rev rest)) in Multiline (line i s e, line i' s' e') let loc_srcname (Loc (src, _, _)) = src.name let ptext ppf (Loc (src, p, q)) = Format.fprintf ppf "%s" (String.sub src.contents p (q - p)) let psrc_loc loc ppf = function | Line { lineno } -> Format.fprintf ppf "%s:%d" (loc_srcname loc) (lineno + 1) | Multiline ({ lineno }, { lineno = lineno' }) -> Format.fprintf ppf "%s:%d-%d" (loc_srcname loc) (lineno + 1) (lineno' + 1) let ploc ppf loc = psrc_loc loc ppf (get_source_loc loc) let psource ppf loc = let srcloc = get_source_loc loc in let p loctxt { txt; lineno; startpos; endpos } = let txt = Str.replace_first (Str.regexp "\n") "" txt in Format.fprintf ppf "%s: %s\n%s %s%s\n" loctxt txt (String.make (String.length loctxt) ' ') (String.make startpos ' ') (String.make (endpos - startpos) '^') in let loctxt = Format.asprintf "%a" (psrc_loc loc) srcloc in match srcloc with | Line l -> p loctxt l | Multiline (({lineno} as l), ({lineno = lineno'} as l')) when lineno + 1 = lineno -> p loctxt l; p loctxt l' | Multiline (l, l') -> p loctxt l; Format.fprintf ppf "%s: ...\n" loctxt; p loctxt l' (* contains a b -> a contains or is equal to b *) let contains (Loc (s1, p, q)) (Loc (s2, p', q')) = s1 = s2 && p <= p' && q' <= q let internal = let loc = { name = "<internal>"; contents = "?"; lines = [(0,1)] } in Loc (loc, 0, 1) type location = t module LocSet = Set.Make (struct type t = location let compare = compare end) type set = LocSet.t let one = LocSet.singleton let join = LocSet.union let extract s = List.hd (LocSet.elements s) let empty = LocSet.empty
null
https://raw.githubusercontent.com/stedolan/mlsub/b425c8da91f45ea59780756950871b80a18ddfc2/location.ml
ocaml
(start, end) positions of lines, including newline As a special case, report the location of end-of-file as the last character contains a b -> a contains or is equal to b
open Lexing type source = { name : string; contents : string; lines : (int * int) list } type t = Loc of source * int * int module type Locator = sig val pos : Lexing.position * Lexing.position -> t end Split a string by a delimiter . are included in the result , so concatenating the output gives the original string so concatenating the output gives the original string *) let rec split_term r s = let open Str in let item ss = ss |> List.rev |> String.concat "" in let rec join res acc = function | [] -> List.rev (match acc with | [] -> res | _ -> item acc :: res) | Text s :: rest -> join res (s :: acc) rest | Delim s :: rest -> join (item (s :: acc) :: res) [] rest in join [] [] (full_split r s) let source name contents = let rec lines p = function | [] -> [] | s :: ss -> let p' = p + String.length s in (p, p') :: lines p' ss in { name; contents; lines = lines 0 (split_term (Str.regexp "\n") contents) } let slurp chan = let rec read_all chunks = let buf = Bytes.init 4096 (fun _ -> '\x00') in match (input chan buf 0 (Bytes.length buf)) with | 0 -> Bytes.concat (Bytes.of_string "") (List.rev chunks) | n -> read_all (Bytes.sub buf 0 n :: chunks) in read_all [] let of_file fname = source fname (slurp (open_in fname)) let of_string str = source "<input>" str type linepart = { txt : string; lineno : int; startpos : int; endpos : int } type source_loc = | Line of linepart | Multiline of linepart * linepart let get_source_loc (Loc (src, p, q)) = let (p, q) = match (p, q) with | (p, q) when p = q && p = String.length src.contents -> (p-1, q) | _ -> p, q in let line i s e = { txt = String.sub src.contents s (e - s); lineno = i; startpos = max 0 (p - s); endpos = min (e - s) (q - s) } in src.lines |> List.mapi (fun i (s, e) -> (i, s, e)) |> List.filter (fun (i, s, e) -> p < e && s < q) |> function | [] -> failwith "internal error: bad location" | [(i, s, e)] -> Line (line i s e) | (i, s, e) :: rest -> let (i', s', e') = List.(hd (rev rest)) in Multiline (line i s e, line i' s' e') let loc_srcname (Loc (src, _, _)) = src.name let ptext ppf (Loc (src, p, q)) = Format.fprintf ppf "%s" (String.sub src.contents p (q - p)) let psrc_loc loc ppf = function | Line { lineno } -> Format.fprintf ppf "%s:%d" (loc_srcname loc) (lineno + 1) | Multiline ({ lineno }, { lineno = lineno' }) -> Format.fprintf ppf "%s:%d-%d" (loc_srcname loc) (lineno + 1) (lineno' + 1) let ploc ppf loc = psrc_loc loc ppf (get_source_loc loc) let psource ppf loc = let srcloc = get_source_loc loc in let p loctxt { txt; lineno; startpos; endpos } = let txt = Str.replace_first (Str.regexp "\n") "" txt in Format.fprintf ppf "%s: %s\n%s %s%s\n" loctxt txt (String.make (String.length loctxt) ' ') (String.make startpos ' ') (String.make (endpos - startpos) '^') in let loctxt = Format.asprintf "%a" (psrc_loc loc) srcloc in match srcloc with | Line l -> p loctxt l | Multiline (({lineno} as l), ({lineno = lineno'} as l')) when lineno + 1 = lineno -> p loctxt l; p loctxt l' | Multiline (l, l') -> p loctxt l; Format.fprintf ppf "%s: ...\n" loctxt; p loctxt l' let contains (Loc (s1, p, q)) (Loc (s2, p', q')) = s1 = s2 && p <= p' && q' <= q let internal = let loc = { name = "<internal>"; contents = "?"; lines = [(0,1)] } in Loc (loc, 0, 1) type location = t module LocSet = Set.Make (struct type t = location let compare = compare end) type set = LocSet.t let one = LocSet.singleton let join = LocSet.union let extract s = List.hd (LocSet.elements s) let empty = LocSet.empty
b24a9ea183e291abdbb1d61e20e04bf63fc79e960a90f21a1d341d973d15da61
richmit/mjrcalc
tst-probe.lisp
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; @file tst-probe.lisp @author < > ;; @brief Unit Tests.@EOL ;; @std Common Lisp ;; @see use-probe.lisp @parblock Copyright ( c ) 1995,2013,2015 , < > All rights reserved . ;; ;; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: ;; 1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer . ;; 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; 3 . Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT ;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;; @endparblock ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage :MJR_PROBE-TESTS (:USE :COMMON-LISP :LISP-UNIT :MJR_PROBE :MJR_PRNG :MJR_EPS)) (in-package :MJR_PROBE-TESTS) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_probe_epdf-int*-naive (epdf pos-int) "Compute product of the EPDF and POS-INT" (cond ((not (integerp pos-int)) (error "mjr_probe_epdf-int*: pos-int must be an integer")) ((>= 0 pos-int) (error "mjr_probe_epdf-int*: pos-int must be positive"))) (let ((epdf (if (vectorp epdf) epdf (concatenate 'vector epdf))) (newpdf (copy-seq epdf))) (dotimes (i (1- pos-int) newpdf) (setf newpdf (mjr_probe_epdf-+ newpdf epdf))))) (defvar ecdf1 #(1)) (defvar ecdf2 #(1/10 3/10 1/10 1/5 1/5 1/10)) (defvar ecdf3 #(1/45 2/45 1/15 4/45 1/9 2/15 7/45 8/45 1/5)) (defvar ecdf4 #(1/52 3/208 5/208 7/208 9/208 1/208 5/208 7/208 3/208 7/208 3/104 1/26 3/208 9/208 1/104 1/208 1/26 0 0 1/52 1/208 3/208 3/208 0 5/208 1/104 0 3/104 1/208 0 1/52 9/208 1/104 9/208 3/208 5/208 7/208 7/208 3/104 1/26 5/208 0 1/208 1/26 1/52 1/104 1/208 1/52 1/104 1/26)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ewt2ecwt (assert-equalp #(1/11 3/11 6/11 11/11) (mjr_probe_ewt2ecwt #(1/11 2/11 3/11 5/11))) ;; PDF ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ewt2epdf (assert-equalp #(1/11 2/11 3/11 5/11) (mjr_probe_ewt2epdf #(1/11 2/11 3/11 5/11))) ;; PDF ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ewt2efreq (assert-equalp #(1 2 3 5) (mjr_probe_ewt2efreq #(1/2 2/2 3/2 5/2))) ;; WT ( not minimal ) (assert-equalp #(1 2 3 5) (mjr_probe_ewt2efreq #(1/11 2/11 3/11 5/11))) ;; PDF ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ecwt2ecfreq (assert-equalp #(1 3 6 11) (mjr_probe_ecwt2ecfreq #(1 3 6 11))) ;; CFREQ (assert-equalp #(1 3 6 11) (mjr_probe_ecwt2ecfreq #(1/2 3/2 6/2 11/2))) ;; CWT (assert-equalp #(1 3 6 11) (mjr_probe_ecwt2ecfreq #(2 6 12 22))) ;; CFREQ (not minimal) CDF ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ecwt2ecdf (assert-equalp #(1/11 3/11 6/11 11/11) (mjr_probe_ecwt2ecdf #(1 3 6 11))) ;; CFREQ CDF ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ecwt2ewt (assert-equalp #(1 2 3 5) (mjr_probe_ecwt2ewt #(1 3 6 11))) ;; CFREQ CDF ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_data2efreq (assert-equalp #(1 2 3 5) (mjr_probe_data2efreq #(0 1 1 2 2 2 3 3 3 3 3))) ;; DATA (assert-equalp #(1 2 3 5) (mjr_probe_data2efreq #(0 1 1 2 2 2 3 3 3 3 3 0 1 1 2 2 2 3 3 3 3 3))) ;; DATA (assert-equalp #(1 2 3 5) (mjr_probe_data2efreq #(0 1 2 2 3 3 1 2 2 3 3 3 0 1 1 2 3 3 3 2 3 3))) ;; DATA ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ewt2data ( not minimal ) (assert-equalp #(0 1 1 2 2 2 3 3 3 3 3) (mjr_probe_ewt2data #(1/2 2/2 3/2 5/2))) ;; WT (assert-equalp #(0 1 1 2 2 2 3 3 3 3 3) (mjr_probe_ewt2data #(1/11 2/11 3/11 5/11))) ;; PDF ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_epdf-+ 1 4 - sided die 2 4 - sided die 3 4 - sided die 4 4 - sided die 5 4 - sided die ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_epdf-e 1 4 - sided die 1 6 - sided die ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_epdf-v 1 4 - sided die 1 6 - sided die ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_epdf-moment 1 4 - sided die 1 6 - sided die 1 4 - sided die 1 6 - sided die ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ewt2pdf ( not minimal ) #(1/2 2/2 3/2 5/2) ;; WT #(1/11 2/11 3/11 5/11)) ;; PDF for epdf = (mjr_probe_ewt2epdf ewt) for f = (mjr_probe_ewt2pdf ewt) do (loop for p1 across epdf for i from 0 do (assert-equalp p1 (funcall f i)))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ewt2cdf (loop for ewt in '(#(1 3 6 11) ;; CFREQ #(1/2 3/2 6/2 11/2) ;; CWT #(2 6 12 22) ;; CFREQ (not minimal) CDF for ecdf = (mjr_probe_ecwt2ecdf ewt) for f = (mjr_probe_ecwt2cdf ewt) do (loop for p1 across ecdf for i from 0 do (assert-equalp p1 (funcall f i)))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_data2prng (loop for data = (mjr_prng_vector 10 #'mjr_prng_int-cc 0 5) for maxd = (reduce #'max data) for mind = (reduce #'min data) for prng = (mjr_probe_data2prng data) for i from 1 upto 100 do (loop for j from 1 upto 100 for r = (funcall prng) do (assert-true (<= r maxd)) do (assert-true (>= r mind)))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ecwt2prng ;; ;; This is how we check this function, but every now and then we get unlucky. :) It is a PRNG afterall... ;; (dotimes (k 10) ;; (let* ((freq (mjr_prng_vector 5 #'mjr_prng_int-cc 0 10)) ;; (prng (mjr_probe_ewt2prng freq)) ( data ( loop for i from 0 upto 1000000 collect ( ) ) ) ( pdf ( mjr_probe_ewt2epdf ( mjr_probe_data2efreq data ) ) ) ) ;; (assert-equality (mjr_eps_make-fixed= .1) pdf (mjr_probe_ewt2epdf freq)))) 1 ) ;; (let* ((freq #(1 1 0 0 0 2 1 1 3 1 0 0)) ( ( mjr_probe_ewt2prng freq ) ) ( data ( loop for i from 0 upto 100000 collect ( ) ) ) ( pdf1 ( mjr_probe_ewt2epdf ( mjr_probe_data2efreq data ) ) ) ;; (pdf2 (mjr_probe_ewt2epdf freq))) ( mjr_vec_print pdf1 " ~10,3f " ) ( mjr_vec_print pdf2 " ~10,3f " ) ( mjr_vec_print ( mjr_vec_- pdf1 pdf2 ) " ~10,3f " ) ;; nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ecwt2prng (loop for i from 1 upto 10 for epdf = (mjr_probe_ewt2epdf (mjr_prng_vector (mjr_prng_int-cc 1 15) #'mjr_prng_int-cc 1 10)) do (loop for j from 1 upto 10 for n = (mjr_prng_int-cc 1 15) for p1 = (apply #'mjr_probe_epdf-+ (loop for k from 1 upto n collect epdf)) for p2 = (mjr_probe_epdf-int* epdf n) do (assert-equalp p1 p2))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_epdf-int* (loop for i from 1 upto 10 do (assert-equalp (MJR_PROBE_EPDF-INT*-naive ecdf1 i) (MJR_PROBE_EPDF-INT* ecdf1 i))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_pdf2epdf 1 6 - sided die ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_cdf2ecdf 1 6 - sided die ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_ewt2prng ;; The test cases for mjr_probe_ecwt2prng make heavy use of this function, so we don't need many tests here. 1 ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_probe_help ;; Note: This function dosen't need test cases.. 1 ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (run-tests )
null
https://raw.githubusercontent.com/richmit/mjrcalc/96f66d030034754e7d3421688ff201f4f1db4833/tst-probe.lisp
lisp
-*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*- @file tst-probe.lisp @brief Unit Tests.@EOL @std Common Lisp @see use-probe.lisp Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: and/or other materials provided with the distribution. without specific prior written permission. LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @endparblock PDF PDF WT PDF CFREQ CWT CFREQ (not minimal) CFREQ CFREQ DATA DATA DATA WT PDF WT PDF CFREQ CWT CFREQ (not minimal) ;; This is how we check this function, but every now and then we get unlucky. :) It is a PRNG afterall... (dotimes (k 10) (let* ((freq (mjr_prng_vector 5 #'mjr_prng_int-cc 0 10)) (prng (mjr_probe_ewt2prng freq)) (assert-equality (mjr_eps_make-fixed= .1) pdf (mjr_probe_ewt2epdf freq)))) (let* ((freq #(1 1 0 0 0 2 1 1 3 1 0 0)) (pdf2 (mjr_probe_ewt2epdf freq))) nil) The test cases for mjr_probe_ecwt2prng make heavy use of this function, so we don't need many tests here. Note: This function dosen't need test cases..
@author < > @parblock Copyright ( c ) 1995,2013,2015 , < > All rights reserved . 1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation 3 . Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS (defpackage :MJR_PROBE-TESTS (:USE :COMMON-LISP :LISP-UNIT :MJR_PROBE :MJR_PRNG :MJR_EPS)) (in-package :MJR_PROBE-TESTS) (defun mjr_probe_epdf-int*-naive (epdf pos-int) "Compute product of the EPDF and POS-INT" (cond ((not (integerp pos-int)) (error "mjr_probe_epdf-int*: pos-int must be an integer")) ((>= 0 pos-int) (error "mjr_probe_epdf-int*: pos-int must be positive"))) (let ((epdf (if (vectorp epdf) epdf (concatenate 'vector epdf))) (newpdf (copy-seq epdf))) (dotimes (i (1- pos-int) newpdf) (setf newpdf (mjr_probe_epdf-+ newpdf epdf))))) (defvar ecdf1 #(1)) (defvar ecdf2 #(1/10 3/10 1/10 1/5 1/5 1/10)) (defvar ecdf3 #(1/45 2/45 1/15 4/45 1/9 2/15 7/45 8/45 1/5)) (defvar ecdf4 #(1/52 3/208 5/208 7/208 9/208 1/208 5/208 7/208 3/208 7/208 3/104 1/26 3/208 9/208 1/104 1/208 1/26 0 0 1/52 1/208 3/208 3/208 0 5/208 1/104 0 3/104 1/208 0 1/52 9/208 1/104 9/208 3/208 5/208 7/208 7/208 3/104 1/26 5/208 0 1/208 1/26 1/52 1/104 1/208 1/52 1/104 1/26)) (define-test mjr_probe_ewt2ecwt ) (define-test mjr_probe_ewt2epdf ) (define-test mjr_probe_ewt2efreq ( not minimal ) ) (define-test mjr_probe_ecwt2ecfreq CDF ) (define-test mjr_probe_ecwt2ecdf CDF ) (define-test mjr_probe_ecwt2ewt CDF ) (define-test mjr_probe_data2efreq ) (define-test mjr_probe_ewt2data ( not minimal ) ) (define-test mjr_probe_epdf-+ 1 4 - sided die 2 4 - sided die 3 4 - sided die 4 4 - sided die 5 4 - sided die ) (define-test mjr_probe_epdf-e 1 4 - sided die 1 6 - sided die ) (define-test mjr_probe_epdf-v 1 4 - sided die 1 6 - sided die ) (define-test mjr_probe_epdf-moment 1 4 - sided die 1 6 - sided die 1 4 - sided die 1 6 - sided die ) (define-test mjr_probe_ewt2pdf ( not minimal ) for epdf = (mjr_probe_ewt2epdf ewt) for f = (mjr_probe_ewt2pdf ewt) do (loop for p1 across epdf for i from 0 do (assert-equalp p1 (funcall f i)))) ) (define-test mjr_probe_ewt2cdf CDF for ecdf = (mjr_probe_ecwt2ecdf ewt) for f = (mjr_probe_ecwt2cdf ewt) do (loop for p1 across ecdf for i from 0 do (assert-equalp p1 (funcall f i)))) ) (define-test mjr_probe_data2prng (loop for data = (mjr_prng_vector 10 #'mjr_prng_int-cc 0 5) for maxd = (reduce #'max data) for mind = (reduce #'min data) for prng = (mjr_probe_data2prng data) for i from 1 upto 100 do (loop for j from 1 upto 100 for r = (funcall prng) do (assert-true (<= r maxd)) do (assert-true (>= r mind)))) ) (define-test mjr_probe_ecwt2prng ( data ( loop for i from 0 upto 1000000 collect ( ) ) ) ( pdf ( mjr_probe_ewt2epdf ( mjr_probe_data2efreq data ) ) ) ) 1 ) ( ( mjr_probe_ewt2prng freq ) ) ( data ( loop for i from 0 upto 100000 collect ( ) ) ) ( pdf1 ( mjr_probe_ewt2epdf ( mjr_probe_data2efreq data ) ) ) ( mjr_vec_print pdf1 " ~10,3f " ) ( mjr_vec_print pdf2 " ~10,3f " ) ( mjr_vec_print ( mjr_vec_- pdf1 pdf2 ) " ~10,3f " ) (define-test mjr_probe_ecwt2prng (loop for i from 1 upto 10 for epdf = (mjr_probe_ewt2epdf (mjr_prng_vector (mjr_prng_int-cc 1 15) #'mjr_prng_int-cc 1 10)) do (loop for j from 1 upto 10 for n = (mjr_prng_int-cc 1 15) for p1 = (apply #'mjr_probe_epdf-+ (loop for k from 1 upto n collect epdf)) for p2 = (mjr_probe_epdf-int* epdf n) do (assert-equalp p1 p2))) ) (define-test mjr_probe_epdf-int* (loop for i from 1 upto 10 do (assert-equalp (MJR_PROBE_EPDF-INT*-naive ecdf1 i) (MJR_PROBE_EPDF-INT* ecdf1 i))) ) (define-test mjr_probe_pdf2epdf 1 6 - sided die ) (define-test mjr_probe_cdf2ecdf 1 6 - sided die ) (define-test mjr_probe_ewt2prng 1 ) (define-test mjr_probe_help 1 ) (run-tests )
af26aac8d86244292a47ba498a73dac3fbdcc573faced6bf486453f60b68e986
privet-kitty/cl-competitive
dopairs.lisp
(defpackage :cp/dopairs (:use :cl) (:export #:dopairs)) (in-package :cp/dopairs) ;; NOTE: not enclosed with (BLOCK NIL) (defmacro dopairs ((var1 var2 list &optional result) &body body) "Iterates BODY for each subset of LIST containing two elements." (let ((suffix (gensym)) (_list (gensym))) `(let ((,_list ,list)) (loop for ,suffix on ,_list for ,var1 = (car ,suffix) do (dolist (,var2 (cdr ,suffix)) ,@body)) ,result)))
null
https://raw.githubusercontent.com/privet-kitty/cl-competitive/4d1c601ff42b10773a5d0c5989b1234da5bb98b6/module/dopairs.lisp
lisp
NOTE: not enclosed with (BLOCK NIL)
(defpackage :cp/dopairs (:use :cl) (:export #:dopairs)) (in-package :cp/dopairs) (defmacro dopairs ((var1 var2 list &optional result) &body body) "Iterates BODY for each subset of LIST containing two elements." (let ((suffix (gensym)) (_list (gensym))) `(let ((,_list ,list)) (loop for ,suffix on ,_list for ,var1 = (car ,suffix) do (dolist (,var2 (cdr ,suffix)) ,@body)) ,result)))
a10dd9725bd07b69f24058f417676907390362462b0ce79f5d9889057dfd7435
nuttycom/aftok
AftokM.hs
# LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # module AftokD.AftokM where import Aftok.Billing ( Billable', ContactChannel (..), Subscription', contactChannel, customer, paymentRequestEmailTemplate, project, ) import qualified Aftok.Billing as B import qualified Aftok.Config as AC import Aftok.Currency.Bitcoin (Satoshi, _Satoshi) import qualified Aftok.Currency.Bitcoin.Payments as Bitcoin import qualified Aftok.Database as DB import Aftok.Database.PostgreSQL (QDBM (..)) import qualified Aftok.Payments as P import qualified Aftok.Payments.Bitcoin as Bitcoin import qualified Aftok.Payments.Types as P import Aftok.Project ( Project, projectName, ) import Aftok.Types ( ProjectId (..), User, UserId, _Email, ) import qualified AftokD as D import Control.Error.Util (exceptT, maybeT) import Control.Lens ( Iso', from, iso, makeClassyPrisms, makeLenses, over, set, to, traverseOf, (.~), (^.), ) import Control.Monad.Except ( MonadError, throwError, ) import Control.Monad.Trans.Except (withExceptT) import Control.Monad.Trans.Reader (mapReaderT) import Crypto.Random.Types (MonadRandom (..)) import qualified Data.Text as T import Data.Thyme.Clock as C import Database.PostgreSQL.Simple ( Connection, connect, ) import Filesystem.Path.CurrentOS (encodeString) import qualified Network.Mail.Mime as Mime import qualified Network.Mail.SMTP as SMTP import Network.URI (URI) import Text.StringTemplate ( directoryGroup, getStringTemplate, newSTMP, render, setManyAttrib, ) data AftokDErr = ConfigError Text | DBErr DB.DBError | PaymentErr P.PaymentError | MailGenError makeClassyPrisms ''AftokDErr -- instance P.AsPaymentError AftokDErr where _ PaymentError = _ PaymentErr . P._PaymentError _ Overdue = _ PaymentErr . P._Overdue _ SigningError = _ PaymentErr . P._SigningError data AftokMEnv = AftokMEnv { _dcfg :: !D.Config, _conn :: !Connection, _pcfg :: !(P.PaymentsConfig AftokM) } instance P.HasPaymentsConfig AftokMEnv where -- networkMode = pcfg . P.networkMode -- signingKey = pcfg . P.signingKey pkiData = pcfg . P.pkiData -- paymentsConfig = pcfg newtype AftokM a = AftokM {runAftokM :: ReaderT AftokMEnv (ExceptT AftokDErr IO) a} deriving (Functor, Applicative, Monad, MonadIO, MonadError AftokDErr, MonadReader AftokMEnv) makeLenses ''AftokMEnv instance MonadRandom AftokM where getRandomBytes = liftIO . getRandomBytes instance DB.MonadDB AftokM where liftdb = liftQDBM . DB.liftdb liftQDBM :: QDBM a -> AftokM a liftQDBM (QDBM r) = do let f a = (a ^. dcfg . D.billingConfig . AC.bitcoinConfig . AC.networkMode, a ^. conn) AftokM . mapReaderT (withExceptT DBErr) . withReaderT f $ r createAllPaymentRequests :: D.Config -> IO () createAllPaymentRequests cfg = do conn' <- connect $ cfg ^. D.dbConfig pcfg' <- AC.toPaymentsConfig $ cfg ^. D.billingConfig let env = AftokMEnv cfg conn' pcfg' void . runExceptT $ (runReaderT . runAftokM) createProjectsPaymentRequests $ env createProjectsPaymentRequests :: AftokM () createProjectsPaymentRequests = do projects <- liftQDBM $ DB.listProjects traverse_ createProjectSubscriptionPaymentRequests projects createProjectSubscriptionPaymentRequests :: ProjectId -> AftokM () createProjectSubscriptionPaymentRequests pid = do now <- liftIO C.getCurrentTime pcfg' <- asks _pcfg subscribers <- liftQDBM $ DB.findSubscribers pid subscriptions <- join <$> traverse (DB.findSubscriptions pid) subscribers requests <- fmap join . exceptT (throwError . PaymentErr) pure $ traverse (\s -> fmap (snd s,) <$> P.createSubscriptionPaymentRequests pcfg' now s) subscriptions traverse_ sendPaymentRequestEmail requests _Compose :: Iso' (f (g a)) (Compose f g a) _Compose = iso Compose getCompose | TODO : Currently will only send email for bip70 requests sendPaymentRequestEmail :: (B.Subscription, (P.PaymentRequestId, P.SomePaymentRequestDetail)) -> AftokM () sendPaymentRequestEmail (sub, (_, P.SomePaymentRequest req)) = do cfg <- ask pcfg' <- liftIO $ AC.toPaymentsConfig @AftokM (cfg ^. dcfg . D.billingConfig) let AC.SmtpConfig {..} = cfg ^. (dcfg . D.smtpConfig) preqCfg = cfg ^. (dcfg . D.paymentRequestConfig) req' = over P.billable (\b -> Compose $ sub & B.billable .~ b) req req'' <- enrichWithUser req' req''' <- enrichWithProject req'' case req''' ^. P.nativeRequest of P.Bip70Request nreq -> do let bip70URIGen = Bitcoin.uriGen (pcfg' ^. P.bitcoinBillingOps) bip70URL <- bip70URIGen (nreq ^. Bitcoin.paymentRequestKey) mail <- traverse (buildBip70PaymentRequestEmail preqCfg req''') bip70URL let mailer = maybe (SMTP.sendMailWithLogin _smtpHost) (SMTP.sendMailWithLogin' _smtpHost) _smtpPort case mail of Just email -> liftIO $ mailer _smtpUser _smtpPass email Nothing -> throwError MailGenError P.Zip321Request _ -> pure () enrichWithUser :: P.PaymentRequest' (Compose (Subscription' UserId) (Billable' p u)) a -> AftokM (P.PaymentRequest' (Compose (Subscription' User) (Billable' p u)) a) enrichWithUser req = do let sub = req ^. P.billable . from _Compose sub' <- maybeT (throwError $ DBErr DB.SubjectNotFound) pure $ traverseOf customer DB.findUser sub pure (set P.billable (Compose sub') req) enrichWithProject :: P.PaymentRequest' (Compose (Subscription' u) (Billable' ProjectId u')) a -> AftokM (P.PaymentRequest' (Compose (Subscription' u) (Billable' Project u')) a) enrichWithProject req = do let sub = req ^. P.billable . from _Compose sub' <- maybeT (throwError $ DBErr DB.SubjectNotFound) pure $ traverseOf (B.billable . project) DB.findProject sub pure (set P.billable (Compose sub') req) buildBip70PaymentRequestEmail :: (MonadIO m, MonadError AftokDErr m) => D.PaymentRequestConfig -> P.PaymentRequest' (Compose (Subscription' User) (Billable' Project UserId)) Satoshi -> URI -> m Mime.Mail buildBip70PaymentRequestEmail cfg req paymentUrl = do templates <- liftIO . directoryGroup $ encodeString (cfg ^. D.templatePath) let billTemplate = (newSTMP . T.unpack) <$> (req ^. P.billable . to getCompose . B.billable . paymentRequestEmailTemplate) defaultTemplate = getStringTemplate "payment_request" templates case billTemplate <|> defaultTemplate of Nothing -> throwError $ ConfigError "Could not find template for invitation email" Just template -> do toEmail <- case req ^. (P.billable . to getCompose . contactChannel) of EmailChannel email -> pure email -- TODO: other channels let fromEmail = cfg ^. D.billingFromEmail pname = req ^. P.billable . to getCompose . B.billable . B.project . projectName total = req ^. P.billable . to getCompose . B.billable . B.amount setAttrs = setManyAttrib [ ("from_email", fromEmail ^. _Email), ("project_name", pname), ("to_email", toEmail ^. _Email), ("amount_due", show $ total ^. _Satoshi), ("payment_url", show paymentUrl) ] fromAddr = Mime.Address Nothing ("") toAddr = Mime.Address Nothing (toEmail ^. _Email) subject = "Payment is due for your " <> pname <> " subscription!" body = Mime.plainPart . render $ setAttrs template pure $ SMTP.simpleMail fromAddr [toAddr] [] [] subject [body]
null
https://raw.githubusercontent.com/nuttycom/aftok/58feefe675cea908cf10619cc88ca4770152e82e/daemon/AftokD/AftokM.hs
haskell
instance P.AsPaymentError AftokDErr where networkMode = pcfg . P.networkMode signingKey = pcfg . P.signingKey paymentsConfig = pcfg TODO: other channels
# LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # module AftokD.AftokM where import Aftok.Billing ( Billable', ContactChannel (..), Subscription', contactChannel, customer, paymentRequestEmailTemplate, project, ) import qualified Aftok.Billing as B import qualified Aftok.Config as AC import Aftok.Currency.Bitcoin (Satoshi, _Satoshi) import qualified Aftok.Currency.Bitcoin.Payments as Bitcoin import qualified Aftok.Database as DB import Aftok.Database.PostgreSQL (QDBM (..)) import qualified Aftok.Payments as P import qualified Aftok.Payments.Bitcoin as Bitcoin import qualified Aftok.Payments.Types as P import Aftok.Project ( Project, projectName, ) import Aftok.Types ( ProjectId (..), User, UserId, _Email, ) import qualified AftokD as D import Control.Error.Util (exceptT, maybeT) import Control.Lens ( Iso', from, iso, makeClassyPrisms, makeLenses, over, set, to, traverseOf, (.~), (^.), ) import Control.Monad.Except ( MonadError, throwError, ) import Control.Monad.Trans.Except (withExceptT) import Control.Monad.Trans.Reader (mapReaderT) import Crypto.Random.Types (MonadRandom (..)) import qualified Data.Text as T import Data.Thyme.Clock as C import Database.PostgreSQL.Simple ( Connection, connect, ) import Filesystem.Path.CurrentOS (encodeString) import qualified Network.Mail.Mime as Mime import qualified Network.Mail.SMTP as SMTP import Network.URI (URI) import Text.StringTemplate ( directoryGroup, getStringTemplate, newSTMP, render, setManyAttrib, ) data AftokDErr = ConfigError Text | DBErr DB.DBError | PaymentErr P.PaymentError | MailGenError makeClassyPrisms ''AftokDErr _ PaymentError = _ PaymentErr . P._PaymentError _ Overdue = _ PaymentErr . P._Overdue _ SigningError = _ PaymentErr . P._SigningError data AftokMEnv = AftokMEnv { _dcfg :: !D.Config, _conn :: !Connection, _pcfg :: !(P.PaymentsConfig AftokM) } instance P.HasPaymentsConfig AftokMEnv where pkiData = pcfg . P.pkiData newtype AftokM a = AftokM {runAftokM :: ReaderT AftokMEnv (ExceptT AftokDErr IO) a} deriving (Functor, Applicative, Monad, MonadIO, MonadError AftokDErr, MonadReader AftokMEnv) makeLenses ''AftokMEnv instance MonadRandom AftokM where getRandomBytes = liftIO . getRandomBytes instance DB.MonadDB AftokM where liftdb = liftQDBM . DB.liftdb liftQDBM :: QDBM a -> AftokM a liftQDBM (QDBM r) = do let f a = (a ^. dcfg . D.billingConfig . AC.bitcoinConfig . AC.networkMode, a ^. conn) AftokM . mapReaderT (withExceptT DBErr) . withReaderT f $ r createAllPaymentRequests :: D.Config -> IO () createAllPaymentRequests cfg = do conn' <- connect $ cfg ^. D.dbConfig pcfg' <- AC.toPaymentsConfig $ cfg ^. D.billingConfig let env = AftokMEnv cfg conn' pcfg' void . runExceptT $ (runReaderT . runAftokM) createProjectsPaymentRequests $ env createProjectsPaymentRequests :: AftokM () createProjectsPaymentRequests = do projects <- liftQDBM $ DB.listProjects traverse_ createProjectSubscriptionPaymentRequests projects createProjectSubscriptionPaymentRequests :: ProjectId -> AftokM () createProjectSubscriptionPaymentRequests pid = do now <- liftIO C.getCurrentTime pcfg' <- asks _pcfg subscribers <- liftQDBM $ DB.findSubscribers pid subscriptions <- join <$> traverse (DB.findSubscriptions pid) subscribers requests <- fmap join . exceptT (throwError . PaymentErr) pure $ traverse (\s -> fmap (snd s,) <$> P.createSubscriptionPaymentRequests pcfg' now s) subscriptions traverse_ sendPaymentRequestEmail requests _Compose :: Iso' (f (g a)) (Compose f g a) _Compose = iso Compose getCompose | TODO : Currently will only send email for bip70 requests sendPaymentRequestEmail :: (B.Subscription, (P.PaymentRequestId, P.SomePaymentRequestDetail)) -> AftokM () sendPaymentRequestEmail (sub, (_, P.SomePaymentRequest req)) = do cfg <- ask pcfg' <- liftIO $ AC.toPaymentsConfig @AftokM (cfg ^. dcfg . D.billingConfig) let AC.SmtpConfig {..} = cfg ^. (dcfg . D.smtpConfig) preqCfg = cfg ^. (dcfg . D.paymentRequestConfig) req' = over P.billable (\b -> Compose $ sub & B.billable .~ b) req req'' <- enrichWithUser req' req''' <- enrichWithProject req'' case req''' ^. P.nativeRequest of P.Bip70Request nreq -> do let bip70URIGen = Bitcoin.uriGen (pcfg' ^. P.bitcoinBillingOps) bip70URL <- bip70URIGen (nreq ^. Bitcoin.paymentRequestKey) mail <- traverse (buildBip70PaymentRequestEmail preqCfg req''') bip70URL let mailer = maybe (SMTP.sendMailWithLogin _smtpHost) (SMTP.sendMailWithLogin' _smtpHost) _smtpPort case mail of Just email -> liftIO $ mailer _smtpUser _smtpPass email Nothing -> throwError MailGenError P.Zip321Request _ -> pure () enrichWithUser :: P.PaymentRequest' (Compose (Subscription' UserId) (Billable' p u)) a -> AftokM (P.PaymentRequest' (Compose (Subscription' User) (Billable' p u)) a) enrichWithUser req = do let sub = req ^. P.billable . from _Compose sub' <- maybeT (throwError $ DBErr DB.SubjectNotFound) pure $ traverseOf customer DB.findUser sub pure (set P.billable (Compose sub') req) enrichWithProject :: P.PaymentRequest' (Compose (Subscription' u) (Billable' ProjectId u')) a -> AftokM (P.PaymentRequest' (Compose (Subscription' u) (Billable' Project u')) a) enrichWithProject req = do let sub = req ^. P.billable . from _Compose sub' <- maybeT (throwError $ DBErr DB.SubjectNotFound) pure $ traverseOf (B.billable . project) DB.findProject sub pure (set P.billable (Compose sub') req) buildBip70PaymentRequestEmail :: (MonadIO m, MonadError AftokDErr m) => D.PaymentRequestConfig -> P.PaymentRequest' (Compose (Subscription' User) (Billable' Project UserId)) Satoshi -> URI -> m Mime.Mail buildBip70PaymentRequestEmail cfg req paymentUrl = do templates <- liftIO . directoryGroup $ encodeString (cfg ^. D.templatePath) let billTemplate = (newSTMP . T.unpack) <$> (req ^. P.billable . to getCompose . B.billable . paymentRequestEmailTemplate) defaultTemplate = getStringTemplate "payment_request" templates case billTemplate <|> defaultTemplate of Nothing -> throwError $ ConfigError "Could not find template for invitation email" Just template -> do toEmail <- case req ^. (P.billable . to getCompose . contactChannel) of EmailChannel email -> pure email let fromEmail = cfg ^. D.billingFromEmail pname = req ^. P.billable . to getCompose . B.billable . B.project . projectName total = req ^. P.billable . to getCompose . B.billable . B.amount setAttrs = setManyAttrib [ ("from_email", fromEmail ^. _Email), ("project_name", pname), ("to_email", toEmail ^. _Email), ("amount_due", show $ total ^. _Satoshi), ("payment_url", show paymentUrl) ] fromAddr = Mime.Address Nothing ("") toAddr = Mime.Address Nothing (toEmail ^. _Email) subject = "Payment is due for your " <> pname <> " subscription!" body = Mime.plainPart . render $ setAttrs template pure $ SMTP.simpleMail fromAddr [toAddr] [] [] subject [body]
383437961932e335a78458a93d7685340b9ef665c009c8e1279bbd980f407322
haskell/hackage-server
HtPasswdDb.hs
-- | Parsing @.htpasswd@ files -- module Distribution.Client.HtPasswdDb ( HtPasswdDb, HtPasswdHash(..), parse, ) where import Distribution.Server.Users.Types (UserName(..)) type HtPasswdDb = [(UserName, Maybe HtPasswdHash)] newtype HtPasswdHash = HtPasswdHash String deriving (Eq, Show) parse :: String -> Either String HtPasswdDb parse = accum 0 [] . map parseLine . lines where accum _ pairs [] = Right (reverse pairs) accum n pairs (Just pair:rest) = accum (n+1) (pair:pairs) rest accum n _ (Nothing :_ ) = Left errmsg where errmsg = "parse error in htpasswd file on line " ++ show (n :: Int) parseLine :: String -> Maybe (UserName, Maybe HtPasswdHash) parseLine line = case break (==':') line of -- entries like "myName:$apr1$r31.....$HqJZimcKQFAMYayBlzkrA/" this is a special Apache md5 - based format that we do not handle (user@(_:_), ':' :'$':_) -> Just (UserName user, Nothing) -- entries like "myName:rqXexS6ZhobKA" (user@(_:_), ':' : hash) -> Just (UserName user, Just (HtPasswdHash hash)) _ -> Nothing
null
https://raw.githubusercontent.com/haskell/hackage-server/6c8689a779b688b3e6b927614c90318936d5bb3f/src/Distribution/Client/HtPasswdDb.hs
haskell
| Parsing @.htpasswd@ files entries like "myName:$apr1$r31.....$HqJZimcKQFAMYayBlzkrA/" entries like "myName:rqXexS6ZhobKA"
module Distribution.Client.HtPasswdDb ( HtPasswdDb, HtPasswdHash(..), parse, ) where import Distribution.Server.Users.Types (UserName(..)) type HtPasswdDb = [(UserName, Maybe HtPasswdHash)] newtype HtPasswdHash = HtPasswdHash String deriving (Eq, Show) parse :: String -> Either String HtPasswdDb parse = accum 0 [] . map parseLine . lines where accum _ pairs [] = Right (reverse pairs) accum n pairs (Just pair:rest) = accum (n+1) (pair:pairs) rest accum n _ (Nothing :_ ) = Left errmsg where errmsg = "parse error in htpasswd file on line " ++ show (n :: Int) parseLine :: String -> Maybe (UserName, Maybe HtPasswdHash) parseLine line = case break (==':') line of this is a special Apache md5 - based format that we do not handle (user@(_:_), ':' :'$':_) -> Just (UserName user, Nothing) (user@(_:_), ':' : hash) -> Just (UserName user, Just (HtPasswdHash hash)) _ -> Nothing
1a2d7863776e83cf9c95046594f91c473c056707dffbde92ce3d3b36a1211662
chaw/r7rs-libs
priority-search-test.sps
;; Original Test Suite from converted to use SRFI 64 tests by (import (scheme base) (pfds priority-search-queue) (only (scheme list) fold filter) (srfi 64) (scheme sort)) (define (alist->psq alist key<? priority<?) (fold (lambda (kv psq) (psq-set psq (car kv) (cdr kv))) (make-psq key<? priority<?) alist)) (define (add1 n) (+ 1 n)) (test-begin "pfds-priority-search-queue") (test-assert (psq? (make-psq string<? <))) (test-assert (psq-empty? (make-psq string<? <))) (test-assert (zero? (psq-size (make-psq string<? <)))) ;; psq-set (let* ((empty (make-psq char<? <)) (psq1 (psq-set empty #\a 10)) (psq2 (psq-set psq1 #\b 33)) (psq3 (psq-set psq2 #\c 3)) (psq4 (psq-set psq3 #\a 12))) (test-equal 10 (psq-ref psq1 #\a)) (test-error (psq-ref psq1 #\b)) (test-equal 1 (psq-size psq1)) (test-equal 10 (psq-ref psq2 #\a)) (test-equal 33 (psq-ref psq2 #\b)) (test-assert (not (psq-contains? psq2 #\c))) (test-equal 2 (psq-size psq2)) (test-equal 10 (psq-ref psq3 #\a)) (test-equal 33 (psq-ref psq3 #\b)) (test-equal 3 (psq-ref psq3 #\c)) (test-equal 3 (psq-size psq3)) (test-equal 12 (psq-ref psq4 #\a)) (test-equal 33 (psq-ref psq4 #\b)) (test-equal 3 (psq-ref psq4 #\c)) (test-equal 3 (psq-size psq4))) ;; psq-delete (let* ((psq1 (alist->psq '((#\a . 10) (#\b . 33) (#\c . 3)) char<? <)) (psq2 (psq-delete psq1 #\c)) (psq3 (psq-delete psq2 #\b)) (psq4 (psq-delete psq3 #\a)) (psq5 (psq-delete psq1 #\d))) (test-equal #t (psq-contains? psq1 #\c)) (test-assert (not (psq-contains? psq2 #\c))) (test-equal #t (psq-contains? psq2 #\b)) (test-assert (not (psq-contains? psq3 #\b))) (test-equal #t (psq-contains? psq3 #\a)) (test-assert (psq-empty? psq4)) (test-equal (psq-size psq1) (psq-size psq5))) ;; psq-update (let* ((empty (make-psq char<? <)) (psq1 (psq-update empty #\a add1 10)) (psq2 (psq-update psq1 #\b add1 33)) (psq3 (psq-update psq2 #\c add1 3)) (psq4 (psq-update psq3 #\a add1 0)) (psq5 (psq-update psq3 #\c add1 0))) (test-equal 11 (psq-ref psq3 #\a)) (test-equal 34 (psq-ref psq3 #\b)) (test-equal 4 (psq-ref psq3 #\c)) (test-equal 12 (psq-ref psq4 #\a)) (test-equal 34 (psq-ref psq4 #\b)) (test-equal 4 (psq-ref psq4 #\c)) (test-equal 3 (psq-size psq4)) (test-equal 11 (psq-ref psq5 #\a)) (test-equal 34 (psq-ref psq5 #\b)) (test-equal 5 (psq-ref psq5 #\c)) (test-equal 3 (psq-size psq5))) ;; priority-queue-functions (let* ((psq1 (alist->psq '((#\a . 10) (#\b . 33) (#\c . 3) (#\d . 23) (#\e . 7)) char<? <)) (psq2 (psq-delete-min psq1)) (psq3 (psq-delete-min (psq-set psq2 #\b 9))) (psq4 (make-psq < <))) (test-equal #\c (psq-min psq1)) (test-equal #\e (psq-min psq2)) (test-error (psq-delete-min psq4)) (test-equal #\a (psq-min (psq-set psq1 #\a 0))) (call-with-values (lambda () (psq-pop psq3)) (lambda (min rest) (test-equal #\b min) (test-equal #\a (psq-min rest))))) ;; ranged-functions (let* ((alist '((#\f . 24) (#\u . 42) (#\p . 16) (#\s . 34) (#\e . 17) (#\x . 45) (#\l . 14) (#\z . 5) (#\t . 45) (#\r . 41) (#\k . 32) (#\w . 14) (#\d . 12) (#\c . 16) (#\m . 20) (#\j . 25))) (alist-sorted (list-sort (lambda (x y) (char<? (car x) (car y))) alist)) (psq (alist->psq alist char<? <))) (test-equal alist-sorted (psq-at-most psq +inf.0)) (test-equal '() (psq-at-most psq 0)) (test-equal '((#\c . 16) (#\d . 12) (#\e . 17) (#\l . 14) (#\m . 20) (#\p . 16) (#\w . 14) (#\z . 5)) (psq-at-most psq 20)) (test-equal alist-sorted (psq-at-most-range psq +inf.0 #\x00 #\xFF)) ;; with bounds outwith range in psq, is the same as psq-at-most (test-equal '() (psq-at-most-range psq 0 #\x00 #\xFF)) (test-equal '((#\c . 16) (#\d . 12) (#\e . 17) (#\l . 14) (#\m . 20) (#\p . 16) (#\w . 14) (#\z . 5)) (psq-at-most-range psq 20 #\x00 #\xFF)) (test-equal '((#\c . 16) (#\d . 12) (#\e . 17) (#\l . 14) (#\m . 20) (#\p . 16) (#\w . 14) (#\z . 5)) (psq-at-most psq 20)) (test-equal (filter (lambda (x) (char<=? #\e (car x) #\u)) alist-sorted) (psq-at-most-range psq +inf.0 #\e #\u)) (test-equal '() (psq-at-most-range psq 0 #\e #\u)) (test-equal '((#\e . 17) (#\l . 14) (#\m . 20) (#\p . 16)) (psq-at-most-range psq 20 #\e #\u)) ;; inclusiveness check (test-equal '((#\t . 45)) (psq-at-most-range psq 80 #\t #\t)) ;; if lower bound is higher than upper, then nothing (test-equal '() (psq-at-most-range psq 80 #\t #\r))) (test-end)
null
https://raw.githubusercontent.com/chaw/r7rs-libs/b8b625c36b040ff3d4b723e4346629a8a0e8d6c2/pfds-tests/priority-search-test.sps
scheme
Original Test Suite from psq-set psq-delete psq-update priority-queue-functions ranged-functions with bounds outwith range in psq, is the same as psq-at-most inclusiveness check if lower bound is higher than upper, then nothing
converted to use SRFI 64 tests by (import (scheme base) (pfds priority-search-queue) (only (scheme list) fold filter) (srfi 64) (scheme sort)) (define (alist->psq alist key<? priority<?) (fold (lambda (kv psq) (psq-set psq (car kv) (cdr kv))) (make-psq key<? priority<?) alist)) (define (add1 n) (+ 1 n)) (test-begin "pfds-priority-search-queue") (test-assert (psq? (make-psq string<? <))) (test-assert (psq-empty? (make-psq string<? <))) (test-assert (zero? (psq-size (make-psq string<? <)))) (let* ((empty (make-psq char<? <)) (psq1 (psq-set empty #\a 10)) (psq2 (psq-set psq1 #\b 33)) (psq3 (psq-set psq2 #\c 3)) (psq4 (psq-set psq3 #\a 12))) (test-equal 10 (psq-ref psq1 #\a)) (test-error (psq-ref psq1 #\b)) (test-equal 1 (psq-size psq1)) (test-equal 10 (psq-ref psq2 #\a)) (test-equal 33 (psq-ref psq2 #\b)) (test-assert (not (psq-contains? psq2 #\c))) (test-equal 2 (psq-size psq2)) (test-equal 10 (psq-ref psq3 #\a)) (test-equal 33 (psq-ref psq3 #\b)) (test-equal 3 (psq-ref psq3 #\c)) (test-equal 3 (psq-size psq3)) (test-equal 12 (psq-ref psq4 #\a)) (test-equal 33 (psq-ref psq4 #\b)) (test-equal 3 (psq-ref psq4 #\c)) (test-equal 3 (psq-size psq4))) (let* ((psq1 (alist->psq '((#\a . 10) (#\b . 33) (#\c . 3)) char<? <)) (psq2 (psq-delete psq1 #\c)) (psq3 (psq-delete psq2 #\b)) (psq4 (psq-delete psq3 #\a)) (psq5 (psq-delete psq1 #\d))) (test-equal #t (psq-contains? psq1 #\c)) (test-assert (not (psq-contains? psq2 #\c))) (test-equal #t (psq-contains? psq2 #\b)) (test-assert (not (psq-contains? psq3 #\b))) (test-equal #t (psq-contains? psq3 #\a)) (test-assert (psq-empty? psq4)) (test-equal (psq-size psq1) (psq-size psq5))) (let* ((empty (make-psq char<? <)) (psq1 (psq-update empty #\a add1 10)) (psq2 (psq-update psq1 #\b add1 33)) (psq3 (psq-update psq2 #\c add1 3)) (psq4 (psq-update psq3 #\a add1 0)) (psq5 (psq-update psq3 #\c add1 0))) (test-equal 11 (psq-ref psq3 #\a)) (test-equal 34 (psq-ref psq3 #\b)) (test-equal 4 (psq-ref psq3 #\c)) (test-equal 12 (psq-ref psq4 #\a)) (test-equal 34 (psq-ref psq4 #\b)) (test-equal 4 (psq-ref psq4 #\c)) (test-equal 3 (psq-size psq4)) (test-equal 11 (psq-ref psq5 #\a)) (test-equal 34 (psq-ref psq5 #\b)) (test-equal 5 (psq-ref psq5 #\c)) (test-equal 3 (psq-size psq5))) (let* ((psq1 (alist->psq '((#\a . 10) (#\b . 33) (#\c . 3) (#\d . 23) (#\e . 7)) char<? <)) (psq2 (psq-delete-min psq1)) (psq3 (psq-delete-min (psq-set psq2 #\b 9))) (psq4 (make-psq < <))) (test-equal #\c (psq-min psq1)) (test-equal #\e (psq-min psq2)) (test-error (psq-delete-min psq4)) (test-equal #\a (psq-min (psq-set psq1 #\a 0))) (call-with-values (lambda () (psq-pop psq3)) (lambda (min rest) (test-equal #\b min) (test-equal #\a (psq-min rest))))) (let* ((alist '((#\f . 24) (#\u . 42) (#\p . 16) (#\s . 34) (#\e . 17) (#\x . 45) (#\l . 14) (#\z . 5) (#\t . 45) (#\r . 41) (#\k . 32) (#\w . 14) (#\d . 12) (#\c . 16) (#\m . 20) (#\j . 25))) (alist-sorted (list-sort (lambda (x y) (char<? (car x) (car y))) alist)) (psq (alist->psq alist char<? <))) (test-equal alist-sorted (psq-at-most psq +inf.0)) (test-equal '() (psq-at-most psq 0)) (test-equal '((#\c . 16) (#\d . 12) (#\e . 17) (#\l . 14) (#\m . 20) (#\p . 16) (#\w . 14) (#\z . 5)) (psq-at-most psq 20)) (test-equal alist-sorted (psq-at-most-range psq +inf.0 #\x00 #\xFF)) (test-equal '() (psq-at-most-range psq 0 #\x00 #\xFF)) (test-equal '((#\c . 16) (#\d . 12) (#\e . 17) (#\l . 14) (#\m . 20) (#\p . 16) (#\w . 14) (#\z . 5)) (psq-at-most-range psq 20 #\x00 #\xFF)) (test-equal '((#\c . 16) (#\d . 12) (#\e . 17) (#\l . 14) (#\m . 20) (#\p . 16) (#\w . 14) (#\z . 5)) (psq-at-most psq 20)) (test-equal (filter (lambda (x) (char<=? #\e (car x) #\u)) alist-sorted) (psq-at-most-range psq +inf.0 #\e #\u)) (test-equal '() (psq-at-most-range psq 0 #\e #\u)) (test-equal '((#\e . 17) (#\l . 14) (#\m . 20) (#\p . 16)) (psq-at-most-range psq 20 #\e #\u)) (test-equal '((#\t . 45)) (psq-at-most-range psq 80 #\t #\t)) (test-equal '() (psq-at-most-range psq 80 #\t #\r))) (test-end)
39e9bba98f24101158ae7fe8cae6f7b6914598bd655b858180af9f089c326de7
rems-project/lem
batUTF8.ml
(** UTF-8 encoded Unicode strings. The type is normal string. *) Copyright ( C ) 2002 , 2003 . (* This library is free software; you can redistribute it and/or *) (* modify it under the terms of the GNU Lesser General Public License *) as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . As a special exception to the GNU Library General Public License , you (* may link, statically or dynamically, a "work that uses this library" *) (* with a publicly distributed version of this library to produce an *) (* executable file containing portions of this library, and distribute *) (* that executable file under terms of your choice, without any of the *) additional requirements listed in clause 6 of the GNU Library General (* Public License. By "a publicly distributed version of this library", *) we mean either the unmodified Library as distributed by the authors , (* or a modified version of this library that is distributed under the *) conditions defined in clause 3 of the GNU Library General Public (* License. This exception does not however invalidate any other reasons *) why the executable file might be covered by the GNU Library General (* Public License . *) (* This library is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *) (* Lesser General Public License for more details. *) You should have received a copy of the GNU Lesser General Public (* License along with this library; if not, write to the Free Software *) Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA (* You can contact the authour by sending email to *) (* *) type t = string let empty = "" type index = int let length0 n = if n < 0x80 then 1 else if n < 0xe0 then 2 else if n < 0xf0 then 3 else 4 let look s i = let n' = let n = Char.code (String.unsafe_get s i) in if n < 0x80 then n else if n <= 0xdf then (n - 0xc0) lsl 6 lor (0x7f land (Char.code (String.unsafe_get s (i + 1)))) else if n <= 0xef then let n' = n - 0xe0 in let m = Char.code (String.unsafe_get s (i + 1)) in let n' = n' lsl 6 lor (0x7f land m) in let m = Char.code (String.unsafe_get s (i + 2)) in n' lsl 6 lor (0x7f land m) else let n' = n - 0xf0 in let m = Char.code (String.unsafe_get s (i + 1)) in let n' = n' lsl 6 lor (0x7f land m) in let m = Char.code (String.unsafe_get s (i + 2)) in let n' = n' lsl 6 lor (0x7f land m) in let m = Char.code (String.unsafe_get s (i + 3)) in n' lsl 6 lor (0x7f land m) in BatUChar.unsafe_chr n' let next s i = let n = Char.code s.[i] in if n < 0x80 then i + 1 else if n <= 0xdf then i + 2 else if n <= 0xef then i + 3 else i + 4 let rec search_head_backward s i = if i < 0 then -1 else let n = Char.code s.[i] in if n < 0x80 || n >= 0xc2 then i else search_head_backward s (i - 1) let prev s i = search_head_backward s (i - 1) let move s i n = if n >= 0 then let rec loop i n = if n <= 0 then i else loop (next s i) (n - 1) in loop i n else let rec loop i n = if n >= 0 then i else loop (prev s i) (n + 1) in loop i n let rec nth_aux s i n = if n = 0 then i else nth_aux s (next s i) (n - 1) let nth s n = nth_aux s 0 n let first _ = 0 let last s = search_head_backward s (String.length s - 1) let out_of_range s i = i < 0 || i >= String.length s let compare_index _ i j = i - j let get s n = look s (nth s n) let add_uchar buf u = let masq = 0b111111 in let k = BatUChar.code u in if k <= 0x7f then Buffer.add_char buf (Char.unsafe_chr k) else if k <= 0x7ff then begin Buffer.add_char buf (Char.unsafe_chr (0xc0 lor (k lsr 6))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor (k land masq))) end else if k <= 0xffff then begin Buffer.add_char buf (Char.unsafe_chr (0xe0 lor (k lsr 12))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor ((k lsr 6) land masq))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor (k land masq))); end else begin Buffer.add_char buf (Char.unsafe_chr (0xf0 + (k lsr 18))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor ((k lsr 12) land masq))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor ((k lsr 6) land masq))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor (k land masq))); end let init len f = let buf = Buffer.create len in for c = 0 to len - 1 do add_uchar buf (f c) done; Buffer.contents buf let make len u = init len (fun _ -> u) let of_char u = make 1 u let of_string_unsafe s = s let to_string_unsafe s = s let rec length_aux s c i = if i >= String.length s then c else let n = Char.code (String.unsafe_get s i) in let k = if n < 0x80 then 1 else if n < 0xe0 then 2 else if n < 0xf0 then 3 else 4 in length_aux s (c + 1) (i + k) let length s = length_aux s 0 0 let rec iter_aux proc s i = if i >= String.length s then () else let u = look s i in proc u; iter_aux proc s (next s i) let iter proc s = iter_aux proc s 0 let rec iteri_aux f s i count = if i >= String.length s then () else let u = look s i in f u count; iteri_aux f s (next s i) (count + 1) let iteri f s = iteri_aux f s 0 0 let compare s1 s2 = String.compare s1 s2 let sub s n len = let ipos = move s (first s) n in let jpos = move s ipos len in String.sub s ipos (jpos-ipos) exception Malformed_code let validate s = let rec trail c i a = if c = 0 then a else if i >= String.length s then raise Malformed_code else let n = Char.code (String.unsafe_get s i) in if n < 0x80 || n >= 0xc0 then raise Malformed_code else trail (c - 1) (i + 1) (a lsl 6 lor (0x7f land n)) in let rec main i = if i >= String.length s then () else let n = Char.code (String.unsafe_get s i) in if n < 0x80 then main (i + 1) else if n < 0xc2 then raise Malformed_code else if n <= 0xdf then if trail 1 (i + 1) (n - 0xc0) < 0x80 then raise Malformed_code else main (i + 2) else if n <= 0xef then let n' = trail 2 (i + 1) (n - 0xe0) in if n' < 0x800 then raise Malformed_code else if n' >= 0xd800 && n' <= 0xdfff then raise Malformed_code else main (i + 3) else if n <= 0xf4 then let n = trail 3 (i + 1) (n - 0xf0) in if n < 0x10000 || n > 0x10FFFF then raise Malformed_code else main (i + 4) else raise Malformed_code in main 0 let of_ascii s = for i = 0 to String.length s - 1 do if Char.code s.[i] >= 0x80 then raise Malformed_code; done; s let of_latin1 s = init (String.length s) (fun i -> BatUChar.of_char s.[i]) module Buf = struct include Buffer type buf = t let add_char = add_uchar end let map f us = let b = Buf.create (length us) in iter (fun c -> Buf.add_char b (f c)) us; Buf.contents b let filter_map f us = let b = Buf.create (length us) in iter (fun c -> match f c with None -> () | Some c -> Buf.add_char b c) us; Buf.contents b let filter p us = let b = Buf.create (length us) in iter (fun c -> if p c then Buf.add_char b c) us; Buf.contents b let fold f a s = let rec loop a i = if out_of_range s i then a else let a' = f a (look s i) in loop a' (next s i) in loop a 0 let escaped = String.escaped module ByteIndex : sig type t = string type b_idx(* = private int*) type char_idx = int val of_int_unsafe : int -> b_idx val to_int : b_idx -> int val next : t -> b_idx -> b_idx val prev : t -> b_idx -> b_idx val of_char_idx : t -> char_idx -> b_idx val at_end : t -> b_idx -> bool val out_of_range : t -> b_idx -> bool val first : b_idx val last : t -> b_idx val move : t -> b_idx -> int -> b_idx val look : t -> b_idx -> BatUChar.t end = struct type t = string type b_idx = int type char_idx = int external of_int_unsafe : int -> b_idx = "%identity" external to_int : b_idx -> int = "%identity" let look = look let next = next let prev = prev let first = 0 let last us = prev us (String.length us) let at_end us bi = bi = String.length us let out_of_range us bi = bi < 0 || bi >= String.length us let move us bi n = (* faster moving positive than negative n *) let bi = ref bi in let step = if n > 0 then next else prev in for _j = 1 to abs n do bi := step us !bi done; !bi let of_char_idx us ci = move us first ci end (* Could be improved. *) let rindex us ch = let rec aux ci bi = if ByteIndex.out_of_range us bi then raise Not_found; if ByteIndex.look us bi = ch then ci else aux (ci-1) (ByteIndex.prev us bi) in aux 0 (ByteIndex.last us) let rec contains_aux step bi us ch = if ByteIndex.out_of_range us bi then false else if ByteIndex.look us bi = ch then true else contains_aux step (step us bi) us ch let contains us ch = contains_aux ByteIndex.next ByteIndex.first us ch
null
https://raw.githubusercontent.com/rems-project/lem/5243fa8f6752dd247fce9deff97008b814f4bd7c/src/ulib/batUTF8.ml
ocaml
* UTF-8 encoded Unicode strings. The type is normal string. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License may link, statically or dynamically, a "work that uses this library" with a publicly distributed version of this library to produce an executable file containing portions of this library, and distribute that executable file under terms of your choice, without any of the Public License. By "a publicly distributed version of this library", or a modified version of this library that is distributed under the License. This exception does not however invalidate any other reasons Public License . This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with this library; if not, write to the Free Software You can contact the authour by sending email to = private int faster moving positive than negative n Could be improved.
Copyright ( C ) 2002 , 2003 . as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . As a special exception to the GNU Library General Public License , you additional requirements listed in clause 6 of the GNU Library General we mean either the unmodified Library as distributed by the authors , conditions defined in clause 3 of the GNU Library General Public why the executable file might be covered by the GNU Library General You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA type t = string let empty = "" type index = int let length0 n = if n < 0x80 then 1 else if n < 0xe0 then 2 else if n < 0xf0 then 3 else 4 let look s i = let n' = let n = Char.code (String.unsafe_get s i) in if n < 0x80 then n else if n <= 0xdf then (n - 0xc0) lsl 6 lor (0x7f land (Char.code (String.unsafe_get s (i + 1)))) else if n <= 0xef then let n' = n - 0xe0 in let m = Char.code (String.unsafe_get s (i + 1)) in let n' = n' lsl 6 lor (0x7f land m) in let m = Char.code (String.unsafe_get s (i + 2)) in n' lsl 6 lor (0x7f land m) else let n' = n - 0xf0 in let m = Char.code (String.unsafe_get s (i + 1)) in let n' = n' lsl 6 lor (0x7f land m) in let m = Char.code (String.unsafe_get s (i + 2)) in let n' = n' lsl 6 lor (0x7f land m) in let m = Char.code (String.unsafe_get s (i + 3)) in n' lsl 6 lor (0x7f land m) in BatUChar.unsafe_chr n' let next s i = let n = Char.code s.[i] in if n < 0x80 then i + 1 else if n <= 0xdf then i + 2 else if n <= 0xef then i + 3 else i + 4 let rec search_head_backward s i = if i < 0 then -1 else let n = Char.code s.[i] in if n < 0x80 || n >= 0xc2 then i else search_head_backward s (i - 1) let prev s i = search_head_backward s (i - 1) let move s i n = if n >= 0 then let rec loop i n = if n <= 0 then i else loop (next s i) (n - 1) in loop i n else let rec loop i n = if n >= 0 then i else loop (prev s i) (n + 1) in loop i n let rec nth_aux s i n = if n = 0 then i else nth_aux s (next s i) (n - 1) let nth s n = nth_aux s 0 n let first _ = 0 let last s = search_head_backward s (String.length s - 1) let out_of_range s i = i < 0 || i >= String.length s let compare_index _ i j = i - j let get s n = look s (nth s n) let add_uchar buf u = let masq = 0b111111 in let k = BatUChar.code u in if k <= 0x7f then Buffer.add_char buf (Char.unsafe_chr k) else if k <= 0x7ff then begin Buffer.add_char buf (Char.unsafe_chr (0xc0 lor (k lsr 6))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor (k land masq))) end else if k <= 0xffff then begin Buffer.add_char buf (Char.unsafe_chr (0xe0 lor (k lsr 12))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor ((k lsr 6) land masq))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor (k land masq))); end else begin Buffer.add_char buf (Char.unsafe_chr (0xf0 + (k lsr 18))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor ((k lsr 12) land masq))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor ((k lsr 6) land masq))); Buffer.add_char buf (Char.unsafe_chr (0x80 lor (k land masq))); end let init len f = let buf = Buffer.create len in for c = 0 to len - 1 do add_uchar buf (f c) done; Buffer.contents buf let make len u = init len (fun _ -> u) let of_char u = make 1 u let of_string_unsafe s = s let to_string_unsafe s = s let rec length_aux s c i = if i >= String.length s then c else let n = Char.code (String.unsafe_get s i) in let k = if n < 0x80 then 1 else if n < 0xe0 then 2 else if n < 0xf0 then 3 else 4 in length_aux s (c + 1) (i + k) let length s = length_aux s 0 0 let rec iter_aux proc s i = if i >= String.length s then () else let u = look s i in proc u; iter_aux proc s (next s i) let iter proc s = iter_aux proc s 0 let rec iteri_aux f s i count = if i >= String.length s then () else let u = look s i in f u count; iteri_aux f s (next s i) (count + 1) let iteri f s = iteri_aux f s 0 0 let compare s1 s2 = String.compare s1 s2 let sub s n len = let ipos = move s (first s) n in let jpos = move s ipos len in String.sub s ipos (jpos-ipos) exception Malformed_code let validate s = let rec trail c i a = if c = 0 then a else if i >= String.length s then raise Malformed_code else let n = Char.code (String.unsafe_get s i) in if n < 0x80 || n >= 0xc0 then raise Malformed_code else trail (c - 1) (i + 1) (a lsl 6 lor (0x7f land n)) in let rec main i = if i >= String.length s then () else let n = Char.code (String.unsafe_get s i) in if n < 0x80 then main (i + 1) else if n < 0xc2 then raise Malformed_code else if n <= 0xdf then if trail 1 (i + 1) (n - 0xc0) < 0x80 then raise Malformed_code else main (i + 2) else if n <= 0xef then let n' = trail 2 (i + 1) (n - 0xe0) in if n' < 0x800 then raise Malformed_code else if n' >= 0xd800 && n' <= 0xdfff then raise Malformed_code else main (i + 3) else if n <= 0xf4 then let n = trail 3 (i + 1) (n - 0xf0) in if n < 0x10000 || n > 0x10FFFF then raise Malformed_code else main (i + 4) else raise Malformed_code in main 0 let of_ascii s = for i = 0 to String.length s - 1 do if Char.code s.[i] >= 0x80 then raise Malformed_code; done; s let of_latin1 s = init (String.length s) (fun i -> BatUChar.of_char s.[i]) module Buf = struct include Buffer type buf = t let add_char = add_uchar end let map f us = let b = Buf.create (length us) in iter (fun c -> Buf.add_char b (f c)) us; Buf.contents b let filter_map f us = let b = Buf.create (length us) in iter (fun c -> match f c with None -> () | Some c -> Buf.add_char b c) us; Buf.contents b let filter p us = let b = Buf.create (length us) in iter (fun c -> if p c then Buf.add_char b c) us; Buf.contents b let fold f a s = let rec loop a i = if out_of_range s i then a else let a' = f a (look s i) in loop a' (next s i) in loop a 0 let escaped = String.escaped module ByteIndex : sig type t = string type char_idx = int val of_int_unsafe : int -> b_idx val to_int : b_idx -> int val next : t -> b_idx -> b_idx val prev : t -> b_idx -> b_idx val of_char_idx : t -> char_idx -> b_idx val at_end : t -> b_idx -> bool val out_of_range : t -> b_idx -> bool val first : b_idx val last : t -> b_idx val move : t -> b_idx -> int -> b_idx val look : t -> b_idx -> BatUChar.t end = struct type t = string type b_idx = int type char_idx = int external of_int_unsafe : int -> b_idx = "%identity" external to_int : b_idx -> int = "%identity" let look = look let next = next let prev = prev let first = 0 let last us = prev us (String.length us) let at_end us bi = bi = String.length us let out_of_range us bi = bi < 0 || bi >= String.length us let bi = ref bi in let step = if n > 0 then next else prev in for _j = 1 to abs n do bi := step us !bi done; !bi let of_char_idx us ci = move us first ci end let rindex us ch = let rec aux ci bi = if ByteIndex.out_of_range us bi then raise Not_found; if ByteIndex.look us bi = ch then ci else aux (ci-1) (ByteIndex.prev us bi) in aux 0 (ByteIndex.last us) let rec contains_aux step bi us ch = if ByteIndex.out_of_range us bi then false else if ByteIndex.look us bi = ch then true else contains_aux step (step us bi) us ch let contains us ch = contains_aux ByteIndex.next ByteIndex.first us ch
a237963c2a037448e55aeaeea3b7d80df3c8d2c51a4b9447ed55f564223b6a32
Helium4Haskell/helium
TypeBug7.hs
module TypeBug7 where main (x,y,z) = f(concat(g(special z))) where f (a:as) = a : "|" : f as g [a] = [head a : "\n" : g (tail a)] special :: [[String]] -> [[String]] special = undefined
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeerrors/Examples/TypeBug7.hs
haskell
module TypeBug7 where main (x,y,z) = f(concat(g(special z))) where f (a:as) = a : "|" : f as g [a] = [head a : "\n" : g (tail a)] special :: [[String]] -> [[String]] special = undefined
1deddebb4f4f8897105ae9704a0660c5c836a3acaff02a9d445989e9b24b7742
avsm/eeww
pprintast.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , OCamlPro (* Fabrice Le Fessant, INRIA Saclay *) , University of Pennsylvania (* *) Copyright 2007 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) Original Code from Ber - metaocaml , modified for 3.12.0 and fixed (* Printing code expressions *) Authors : , Extensive Rewrite : : University of Pennsylvania TODO more fine - grained precedence pretty - printing open Asttypes open Format open Location open Longident open Parsetree open Ast_helper let prefix_symbols = [ '!'; '?'; '~' ] let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/'; '$'; '%'; '#' ] (* type fixity = Infix| Prefix *) let special_infix_strings = ["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!="; "::" ] let letop s = String.length s > 3 && s.[0] = 'l' && s.[1] = 'e' && s.[2] = 't' && List.mem s.[3] infix_symbols let andop s = String.length s > 3 && s.[0] = 'a' && s.[1] = 'n' && s.[2] = 'd' && List.mem s.[3] infix_symbols determines if the string is an infix string . checks backwards , first allowing a renaming postfix ( " _ 102 " ) which may have resulted from - > Texp - > translation , then checking if all the characters in the beginning of the string are valid infix characters . checks backwards, first allowing a renaming postfix ("_102") which may have resulted from Pexp -> Texp -> Pexp translation, then checking if all the characters in the beginning of the string are valid infix characters. *) let fixity_of_string = function | "" -> `Normal | s when List.mem s special_infix_strings -> `Infix s | s when List.mem s.[0] infix_symbols -> `Infix s | s when List.mem s.[0] prefix_symbols -> `Prefix s | s when s.[0] = '.' -> `Mixfix s | s when letop s -> `Letop s | s when andop s -> `Andop s | _ -> `Normal let view_fixity_of_exp = function | {pexp_desc = Pexp_ident {txt=Lident l;_}; pexp_attributes = []} -> fixity_of_string l | _ -> `Normal let is_infix = function `Infix _ -> true | _ -> false let is_mixfix = function `Mixfix _ -> true | _ -> false let is_kwdop = function `Letop _ | `Andop _ -> true | _ -> false let first_is c str = str <> "" && str.[0] = c let last_is c str = str <> "" && str.[String.length str - 1] = c let first_is_in cs str = str <> "" && List.mem str.[0] cs (* which identifiers are in fact operators needing parentheses *) let needs_parens txt = let fix = fixity_of_string txt in is_infix fix || is_mixfix fix || is_kwdop fix || first_is_in prefix_symbols txt (* some infixes need spaces around parens to avoid clashes with comment syntax *) let needs_spaces txt = first_is '*' txt || last_is '*' txt let string_loc ppf x = fprintf ppf "%s" x.txt (* add parentheses to binders when they are in fact infix or prefix operators *) let protect_ident ppf txt = let format : (_, _, _) format = if not (needs_parens txt) then "%s" else if needs_spaces txt then "(@;%s@;)" else "(%s)" in fprintf ppf format txt let protect_longident ppf print_longident longprefix txt = let format : (_, _, _) format = if not (needs_parens txt) then "%a.%s" else if needs_spaces txt then "%a.(@;%s@;)" else "%a.(%s)" in fprintf ppf format print_longident longprefix txt type space_formatter = (unit, Format.formatter, unit) format let override = function | Override -> "!" | Fresh -> "" (* variance encoding: need to sync up with the [parser.mly] *) let type_variance = function | NoVariance -> "" | Covariant -> "+" | Contravariant -> "-" let type_injectivity = function | NoInjectivity -> "" | Injective -> "!" type construct = [ `cons of expression list | `list of expression list | `nil | `normal | `simple of Longident.t | `tuple ] let view_expr x = match x.pexp_desc with | Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple | Pexp_construct ( {txt= Lident "[]";_},_) -> `nil | Pexp_construct ( {txt= Lident"::";_},Some _) -> let rec loop exp acc = match exp with | {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_); pexp_attributes = []} -> (List.rev acc,true) | {pexp_desc= Pexp_construct ({txt=Lident "::";_}, Some ({pexp_desc= Pexp_tuple([e1;e2]); pexp_attributes = []})); pexp_attributes = []} -> loop e2 (e1::acc) | e -> (List.rev (e::acc),false) in let (ls,b) = loop x [] in if b then `list ls else `cons ls | Pexp_construct (x,None) -> `simple (x.txt) | _ -> `normal let is_simple_construct :construct -> bool = function | `nil | `tuple | `list _ | `simple _ -> true | `cons _ | `normal -> false let pp = fprintf type ctxt = { pipe : bool; semi : bool; ifthenelse : bool; } let reset_ctxt = { pipe=false; semi=false; ifthenelse=false } let under_pipe ctxt = { ctxt with pipe=true } let under_semi ctxt = { ctxt with semi=true } let under_ifthenelse ctxt = { ctxt with ifthenelse=true } let reset_semi = with semi = false } let reset_ifthenelse = with ifthenelse = false } let = with pipe = false } let reset_semi ctxt = { ctxt with semi=false } let reset_ifthenelse ctxt = { ctxt with ifthenelse=false } let reset_pipe ctxt = { ctxt with pipe=false } *) let list : 'a . ?sep:space_formatter -> ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a list -> unit = fun ?sep ?first ?last fu f xs -> let first = match first with Some x -> x |None -> ("": _ format6) and last = match last with Some x -> x |None -> ("": _ format6) and sep = match sep with Some x -> x |None -> ("@ ": _ format6) in let aux f = function | [] -> () | [x] -> fu f x | xs -> let rec loop f = function | [x] -> fu f x | x::xs -> fu f x; pp f sep; loop f xs; | _ -> assert false in begin pp f first; loop f xs; pp f last; end in aux f xs let option : 'a. ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit = fun ?first ?last fu f a -> let first = match first with Some x -> x | None -> ("": _ format6) and last = match last with Some x -> x | None -> ("": _ format6) in match a with | None -> () | Some x -> pp f first; fu f x; pp f last let paren: 'a . ?first:space_formatter -> ?last:space_formatter -> bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit = fun ?(first=("": _ format6)) ?(last=("": _ format6)) b fu f x -> if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")") else fu f x let rec longident f = function | Lident s -> protect_ident f s | Ldot(y,s) -> protect_longident f longident y s | Lapply (y,s) -> pp f "%a(%a)" longident y longident s let longident_loc f x = pp f "%a" longident x.txt let constant f = function | Pconst_char i -> pp f "%C" i | Pconst_string (i, _, None) -> pp f "%S" i | Pconst_string (i, _, Some delim) -> pp f "{%s|%s|%s}" delim i delim | Pconst_integer (i, None) -> paren (first_is '-' i) (fun f -> pp f "%s") f i | Pconst_integer (i, Some m) -> paren (first_is '-' i) (fun f (i, m) -> pp f "%s%c" i m) f (i,m) | Pconst_float (i, None) -> paren (first_is '-' i) (fun f -> pp f "%s") f i | Pconst_float (i, Some m) -> paren (first_is '-' i) (fun f (i,m) -> pp f "%s%c" i m) f (i,m) (* trailing space*) let mutable_flag f = function | Immutable -> () | Mutable -> pp f "mutable@;" let virtual_flag f = function | Concrete -> () | Virtual -> pp f "virtual@;" (* trailing space added *) let rec_flag f rf = match rf with | Nonrecursive -> () | Recursive -> pp f "rec " let nonrec_flag f rf = match rf with | Nonrecursive -> pp f "nonrec " | Recursive -> () let direction_flag f = function | Upto -> pp f "to@ " | Downto -> pp f "downto@ " let private_flag f = function | Public -> () | Private -> pp f "private@ " let iter_loc f ctxt {txt; loc = _} = f ctxt txt let constant_string f s = pp f "%S" s let tyvar ppf s = if String.length s >= 2 && s.[1] = '\'' then (* without the space, this would be parsed as a character literal *) Format.fprintf ppf "' %s" s else Format.fprintf ppf "'%s" s let tyvar_loc f str = tyvar f str.txt let string_quot f x = pp f "`%s" x (* c ['a,'b] *) let rec class_params_def ctxt f = function | [] -> () | l -> pp f "[%a] " (* space *) (list (type_param ctxt) ~sep:",") l and type_with_label ctxt f (label, c) = match label with | Nolabel -> core_type1 ctxt f c (* otherwise parenthesize *) | Labelled s -> pp f "%s:%a" s (core_type1 ctxt) c | Optional s -> pp f "?%s:%a" s (core_type1 ctxt) c and core_type ctxt f x = if x.ptyp_attributes <> [] then begin pp f "((%a)%a)" (core_type ctxt) {x with ptyp_attributes=[]} (attributes ctxt) x.ptyp_attributes end else match x.ptyp_desc with | Ptyp_arrow (l, ct1, ct2) -> FIXME remove parens later (type_with_label ctxt) (l,ct1) (core_type ctxt) ct2 | Ptyp_alias (ct, s) -> pp f "@[<2>%a@;as@;%a@]" (core_type1 ctxt) ct tyvar s | Ptyp_poly ([], ct) -> core_type ctxt f ct | Ptyp_poly (sl, ct) -> pp f "@[<2>%a%a@]" (fun f l -> match l with | [] -> () | _ -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") l) sl (core_type ctxt) ct | _ -> pp f "@[<2>%a@]" (core_type1 ctxt) x and core_type1 ctxt f x = if x.ptyp_attributes <> [] then core_type ctxt f x else match x.ptyp_desc with | Ptyp_any -> pp f "_"; | Ptyp_var s -> tyvar f s; | Ptyp_tuple l -> pp f "(%a)" (list (core_type1 ctxt) ~sep:"@;*@;") l | Ptyp_constr (li, l) -> pp f (* "%a%a@;" *) "%a%a" (fun f l -> match l with |[] -> () |[x]-> pp f "%a@;" (core_type1 ctxt) x | _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l) l longident_loc li | Ptyp_variant (l, closed, low) -> let first_is_inherit = match l with | {Parsetree.prf_desc = Rinherit _}::_ -> true | _ -> false in let type_variant_helper f x = match x.prf_desc with | Rtag (l, _, ctl) -> pp f "@[<2>%a%a@;%a@]" (iter_loc string_quot) l (fun f l -> match l with |[] -> () | _ -> pp f "@;of@;%a" (list (core_type ctxt) ~sep:"&") ctl) ctl (attributes ctxt) x.prf_attributes | Rinherit ct -> core_type ctxt f ct in pp f "@[<2>[%a%a]@]" (fun f l -> match l, closed with | [], Closed -> () | [], Open -> pp f ">" (* Cf #7200: print [>] correctly *) | _ -> pp f "%s@;%a" (match (closed,low) with | (Closed,None) -> if first_is_inherit then " |" else "" | (Closed,Some _) -> "<" (* FIXME desugar the syntax sugar*) | (Open,_) -> ">") (list type_variant_helper ~sep:"@;<1 -2>| ") l) l (fun f low -> match low with |Some [] |None -> () |Some xs -> pp f ">@ %a" (list string_quot) xs) low | Ptyp_object (l, o) -> let core_field_type f x = match x.pof_desc with | Otag (l, ct) -> Cf # 7200 pp f "@[<hov2>%s: %a@ %a@ @]" l.txt (core_type ctxt) ct (attributes ctxt) x.pof_attributes | Oinherit ct -> pp f "@[<hov2>%a@ @]" (core_type ctxt) ct in let field_var f = function | Asttypes.Closed -> () | Asttypes.Open -> match l with | [] -> pp f ".." | _ -> pp f " ;.." in pp f "@[<hov2><@ %a%a@ > @]" (list core_field_type ~sep:";") l Cf # 7200 FIXME pp f "@[<hov2>%a#%a@]" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") l longident_loc li | Ptyp_package (lid, cstrs) -> let aux f (s, ct) = pp f "type %a@ =@ %a" longident_loc s (core_type ctxt) ct in (match cstrs with |[] -> pp f "@[<hov2>(module@ %a)@]" longident_loc lid |_ -> pp f "@[<hov2>(module@ %a@ with@ %a)@]" longident_loc lid (list aux ~sep:"@ and@ ") cstrs) | Ptyp_extension e -> extension ctxt f e | _ -> paren true (core_type ctxt) f x (********************pattern********************) be cautious when use [ pattern ] , [ ] is preferred and pattern ctxt f x = if x.ppat_attributes <> [] then begin pp f "((%a)%a)" (pattern ctxt) {x with ppat_attributes=[]} (attributes ctxt) x.ppat_attributes end else match x.ppat_desc with | Ppat_alias (p, s) -> pp f "@[<2>%a@;as@;%a@]" (pattern ctxt) p protect_ident s.txt | _ -> pattern_or ctxt f x and pattern_or ctxt f x = let rec left_associative x acc = match x with | {ppat_desc=Ppat_or (p1,p2); ppat_attributes = []} -> left_associative p1 (p2 :: acc) | x -> x :: acc in match left_associative x [] with | [] -> assert false | [x] -> pattern1 ctxt f x | orpats -> pp f "@[<hov0>%a@]" (list ~sep:"@ | " (pattern1 ctxt)) orpats and pattern1 ctxt (f:Format.formatter) (x:pattern) : unit = let rec pattern_list_helper f = function | {ppat_desc = Ppat_construct ({ txt = Lident("::") ;_}, Some ([], {ppat_desc = Ppat_tuple([pat1; pat2]);_})); ppat_attributes = []} -> pp f "%a::%a" (simple_pattern ctxt) pat1 pattern_list_helper pat2 (*RA*) | p -> pattern1 ctxt f p in if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_variant (l, Some p) -> pp f "@[<2>`%s@;%a@]" l (simple_pattern ctxt) p | Ppat_construct (({txt=Lident("()"|"[]");_}), _) -> simple_pattern ctxt f x | Ppat_construct (({txt;_} as li), po) -> FIXME The third field always false if txt = Lident "::" then pp f "%a" pattern_list_helper x else (match po with | Some ([], x) -> pp f "%a@;%a" longident_loc li (simple_pattern ctxt) x | Some (vl, x) -> pp f "%a@ (type %a)@;%a" longident_loc li (list ~sep:"@ " string_loc) vl (simple_pattern ctxt) x | None -> pp f "%a" longident_loc li) | _ -> simple_pattern ctxt f x and simple_pattern ctxt (f:Format.formatter) (x:pattern) : unit = if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_construct (({txt=Lident ("()"|"[]" as x);_}), None) -> pp f "%s" x | Ppat_any -> pp f "_"; | Ppat_var ({txt = txt;_}) -> protect_ident f txt | Ppat_array l -> pp f "@[<2>[|%a|]@]" (list (pattern1 ctxt) ~sep:";") l | Ppat_unpack { txt = None } -> pp f "(module@ _)@ " | Ppat_unpack { txt = Some s } -> pp f "(module@ %s)@ " s | Ppat_type li -> pp f "#%a" longident_loc li | Ppat_record (l, closed) -> let longident_x_pattern f (li, p) = match (li,p) with | ({txt=Lident s;_ }, {ppat_desc=Ppat_var {txt;_}; ppat_attributes=[]; _}) when s = txt -> pp f "@[<2>%a@]" longident_loc li | _ -> pp f "@[<2>%a@;=@;%a@]" longident_loc li (pattern1 ctxt) p in begin match closed with | Closed -> pp f "@[<2>{@;%a@;}@]" (list longident_x_pattern ~sep:";@;") l | _ -> pp f "@[<2>{@;%a;_}@]" (list longident_x_pattern ~sep:";@;") l end | Ppat_tuple l -> | Ppat_constant (c) -> pp f "%a" constant c | Ppat_interval (c1, c2) -> pp f "%a..%a" constant c1 constant c2 | Ppat_variant (l,None) -> pp f "`%s" l | Ppat_constraint (p, ct) -> pp f "@[<2>(%a@;:@;%a)@]" (pattern1 ctxt) p (core_type ctxt) ct | Ppat_lazy p -> pp f "@[<2>(lazy@;%a)@]" (simple_pattern ctxt) p | Ppat_exception p -> pp f "@[<2>exception@;%a@]" (pattern1 ctxt) p | Ppat_extension e -> extension ctxt f e | Ppat_open (lid, p) -> let with_paren = match p.ppat_desc with | Ppat_array _ | Ppat_record _ | Ppat_construct (({txt=Lident ("()"|"[]");_}), None) -> false | _ -> true in pp f "@[<2>%a.%a @]" longident_loc lid (paren with_paren @@ pattern1 ctxt) p | _ -> paren true (pattern ctxt) f x and label_exp ctxt f (l,opt,p) = match l with | Nolabel -> (* single case pattern parens needed here *) pp f "%a@ " (simple_pattern ctxt) p | Optional rest -> begin match p with | {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []} when txt = rest -> (match opt with | Some o -> pp f "?(%s=@;%a)@;" rest (expression ctxt) o | None -> pp f "?%s@ " rest) | _ -> (match opt with | Some o -> pp f "?%s:(%a=@;%a)@;" rest (pattern1 ctxt) p (expression ctxt) o | None -> pp f "?%s:%a@;" rest (simple_pattern ctxt) p) end | Labelled l -> match p with | {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []} when txt = l -> pp f "~%s@;" l | _ -> pp f "~%s:%a@;" l (simple_pattern ctxt) p and sugar_expr ctxt f e = if e.pexp_attributes <> [] then false else match e.pexp_desc with | Pexp_apply ({ pexp_desc = Pexp_ident {txt = id; _}; pexp_attributes=[]; _}, args) when List.for_all (fun (lab, _) -> lab = Nolabel) args -> begin let print_indexop a path_prefix assign left sep right print_index indices rem_args = let print_path ppf = function | None -> () | Some m -> pp ppf ".%a" longident m in match assign, rem_args with | false, [] -> pp f "@[%a%a%s%a%s@]" (simple_expr ctxt) a print_path path_prefix left (list ~sep print_index) indices right; true | true, [v] -> pp f "@[%a%a%s%a%s@ <-@;<1 2>%a@]" (simple_expr ctxt) a print_path path_prefix left (list ~sep print_index) indices right (simple_expr ctxt) v; true | _ -> false in match id, List.map snd args with | Lident "!", [e] -> pp f "@[<hov>!%a@]" (simple_expr ctxt) e; true | Ldot (path, ("get"|"set" as func)), a :: other_args -> begin let assign = func = "set" in let print = print_indexop a None assign in match path, other_args with | Lident "Array", i :: rest -> print ".(" "" ")" (expression ctxt) [i] rest | Lident "String", i :: rest -> print ".[" "" "]" (expression ctxt) [i] rest | Ldot (Lident "Bigarray", "Array1"), i1 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1] rest | Ldot (Lident "Bigarray", "Array2"), i1 :: i2 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1; i2] rest | Ldot (Lident "Bigarray", "Array3"), i1 :: i2 :: i3 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1; i2; i3] rest | Ldot (Lident "Bigarray", "Genarray"), {pexp_desc = Pexp_array indexes; pexp_attributes = []} :: rest -> print ".{" "," "}" (simple_expr ctxt) indexes rest | _ -> false end | (Lident s | Ldot(_,s)) , a :: i :: rest when first_is '.' s -> (* extract operator: assignment operators end with [right_bracket ^ "<-"], access operators end with [right_bracket] directly *) let multi_indices = String.contains s ';' in let i = match i.pexp_desc with | Pexp_array l when multi_indices -> l | _ -> [ i ] in let assign = last_is '-' s in let kind = (* extract the right end bracket *) let n = String.length s in if assign then s.[n - 3] else s.[n - 1] in let left, right = match kind with | ')' -> '(', ")" | ']' -> '[', "]" | '}' -> '{', "}" | _ -> assert false in let path_prefix = match id with | Ldot(m,_) -> Some m | _ -> None in let left = String.sub s 0 (1+String.index s left) in print_indexop a path_prefix assign left ";" right (if multi_indices then expression ctxt else simple_expr ctxt) i rest | _ -> false end | _ -> false and expression ctxt f x = if x.pexp_attributes <> [] then pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]} (attributes ctxt) x.pexp_attributes else match x.pexp_desc with | Pexp_function _ | Pexp_fun _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _ | Pexp_newtype _ when ctxt.pipe || ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_ifthenelse _ | Pexp_sequence _ when ctxt.ifthenelse -> paren true (expression reset_ctxt) f x | Pexp_let _ | Pexp_letmodule _ | Pexp_open _ | Pexp_letexception _ | Pexp_letop _ when ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_fun (l, e0, p, e) -> pp f "@[<2>fun@;%a->@;%a@]" (label_exp ctxt) (l, e0, p) (expression ctxt) e | Pexp_newtype (lid, e) -> pp f "@[<2>fun@;(type@;%s)@;->@;%a@]" lid.txt (expression ctxt) e | Pexp_function l -> pp f "@[<hv>function%a@]" (case_list ctxt) l | Pexp_match (e, l) -> pp f "@[<hv0>@[<hv0>@[<2>match %a@]@ with@]%a@]" (expression reset_ctxt) e (case_list ctxt) l | Pexp_try (e, l) -> pp f "@[<0>@[<hv2>try@ %a@]@ @[<0>with%a@]@]" (* "try@;@[<2>%a@]@\nwith@\n%a"*) (expression reset_ctxt) e (case_list ctxt) l | Pexp_let (rf, l, e) -> (* pp f "@[<2>let %a%a in@;<1 -2>%a@]" (*no indentation here, a new line*) *) rec_flag rf pp f "@[<2>%a in@;<1 -2>%a@]" (bindings reset_ctxt) (rf,l) (expression ctxt) e | Pexp_apply (e, l) -> begin if not (sugar_expr ctxt f x) then match view_fixity_of_exp e with | `Infix s -> begin match l with | [ (Nolabel, _) as arg1; (Nolabel, _) as arg2 ] -> FIXME associativity label_x_expression_param pp f "@[<2>%a@;%s@;%a@]" (label_x_expression_param reset_ctxt) arg1 s (label_x_expression_param ctxt) arg2 | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | `Prefix s -> let s = if List.mem s ["~+";"~-";"~+.";"~-."] && (match l with (* See #7200: avoid turning (~- 1) into (- 1) which is parsed as an int literal *) |[(_,{pexp_desc=Pexp_constant _})] -> false | _ -> true) then String.sub s 1 (String.length s -1) else s in begin match l with | [(Nolabel, x)] -> pp f "@[<2>%s@;%a@]" s (simple_expr ctxt) x | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | _ -> pp f "@[<hov2>%a@]" begin fun f (e,l) -> pp f "%a@ %a" (expression2 ctxt) e (list (label_x_expression_param reset_ctxt)) l (* reset here only because [function,match,try,sequence] are lower priority *) end (e,l) end | Pexp_construct (li, Some eo) when not (is_simple_construct (view_expr x))-> (* Not efficient FIXME*) (match view_expr x with | `cons ls -> list (simple_expr ctxt) f ls ~sep:"@;::@;" | `normal -> pp f "@[<2>%a@;%a@]" longident_loc li (simple_expr ctxt) eo | _ -> assert false) | Pexp_setfield (e1, li, e2) -> pp f "@[<2>%a.%a@ <-@ %a@]" (simple_expr ctxt) e1 longident_loc li (simple_expr ctxt) e2 | Pexp_ifthenelse (e1, e2, eo) -> (* @;@[<2>else@ %a@]@] *) let fmt:(_,_,_)format ="@[<hv0>@[<2>if@ %a@]@;@[<2>then@ %a@]%a@]" in let expression_under_ifthenelse = expression (under_ifthenelse ctxt) in pp f fmt expression_under_ifthenelse e1 expression_under_ifthenelse e2 (fun f eo -> match eo with | Some x -> pp f "@;@[<2>else@;%a@]" (expression (under_semi ctxt)) x | None -> () (* pp f "()" *)) eo | Pexp_sequence _ -> let rec sequence_helper acc = function | {pexp_desc=Pexp_sequence(e1,e2); pexp_attributes = []} -> sequence_helper (e1::acc) e2 | v -> List.rev (v::acc) in let lst = sequence_helper [] x in pp f "@[<hv>%a@]" (list (expression (under_semi ctxt)) ~sep:";@;") lst | Pexp_new (li) -> pp f "@[<hov2>new@ %a@]" longident_loc li; | Pexp_setinstvar (s, e) -> pp f "@[<hov2>%s@ <-@ %a@]" s.txt (expression ctxt) e FIXME let string_x_expression f (s, e) = pp f "@[<hov2>%s@ =@ %a@]" s.txt (expression ctxt) e in pp f "@[<hov2>{<%a>}@]" (list string_x_expression ~sep:";" ) l; | Pexp_letmodule (s, me, e) -> pp f "@[<hov2>let@ module@ %s@ =@ %a@ in@ %a@]" (Option.value s.txt ~default:"_") (module_expr reset_ctxt) me (expression ctxt) e | Pexp_letexception (cd, e) -> pp f "@[<hov2>let@ exception@ %a@ in@ %a@]" (extension_constructor ctxt) cd (expression ctxt) e | Pexp_assert e -> pp f "@[<hov2>assert@ %a@]" (simple_expr ctxt) e | Pexp_lazy (e) -> pp f "@[<hov2>lazy@ %a@]" (simple_expr ctxt) e (* Pexp_poly: impossible but we should print it anyway, rather than assert false *) | Pexp_poly (e, None) -> pp f "@[<hov2>!poly!@ %a@]" (simple_expr ctxt) e | Pexp_poly (e, Some ct) -> pp f "@[<hov2>(!poly!@ %a@ : %a)@]" (simple_expr ctxt) e (core_type ctxt) ct | Pexp_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) (module_expr ctxt) o.popen_expr (expression ctxt) e | Pexp_variant (l,Some eo) -> pp f "@[<2>`%s@;%a@]" l (simple_expr ctxt) eo | Pexp_letop {let_; ands; body} -> pp f "@[<2>@[<v>%a@,%a@] in@;<1 -2>%a@]" (binding_op ctxt) let_ (list ~sep:"@," (binding_op ctxt)) ands (expression ctxt) body | Pexp_extension e -> extension ctxt f e | Pexp_unreachable -> pp f "." | _ -> expression1 ctxt f x and expression1 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_object cs -> pp f "%a" (class_structure ctxt) cs | _ -> expression2 ctxt f x (* used in [Pexp_apply] *) and expression2 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_field (e, li) -> pp f "@[<hov2>%a.%a@]" (simple_expr ctxt) e longident_loc li | Pexp_send (e, s) -> pp f "@[<hov2>%a#%s@]" (simple_expr ctxt) e s.txt | _ -> simple_expr ctxt f x and simple_expr ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_construct _ when is_simple_construct (view_expr x) -> (match view_expr x with | `nil -> pp f "[]" | `tuple -> pp f "()" | `list xs -> pp f "@[<hv0>[%a]@]" (list (expression (under_semi ctxt)) ~sep:";@;") xs | `simple x -> longident f x | _ -> assert false) | Pexp_ident li -> longident_loc f li (* (match view_fixity_of_exp x with *) (* |`Normal -> longident_loc f li *) (* | `Prefix _ | `Infix _ -> pp f "( %a )" longident_loc li) *) | Pexp_constant c -> constant f c; | Pexp_pack me -> pp f "(module@;%a)" (module_expr ctxt) me | Pexp_tuple l -> pp f "@[<hov2>(%a)@]" (list (simple_expr ctxt) ~sep:",@;") l | Pexp_constraint (e, ct) -> pp f "(%a : %a)" (expression ctxt) e (core_type ctxt) ct | Pexp_coerce (e, cto1, ct) -> pp f "(%a%a :> %a)" (expression ctxt) e (option (core_type ctxt) ~first:" : " ~last:" ") cto1 (* no sep hint*) (core_type ctxt) ct | Pexp_variant (l, None) -> pp f "`%s" l | Pexp_record (l, eo) -> let longident_x_expression f ( li, e) = match e with | {pexp_desc=Pexp_ident {txt;_}; pexp_attributes=[]; _} when li.txt = txt -> pp f "@[<hov2>%a@]" longident_loc li | _ -> pp f "@[<hov2>%a@;=@;%a@]" longident_loc li (simple_expr ctxt) e in pp f "@[<hv0>@[<hv2>{@;%a%a@]@;}@]"(* "@[<hov2>{%a%a}@]" *) (option ~last:" with@;" (simple_expr ctxt)) eo (list longident_x_expression ~sep:";@;") l | Pexp_array (l) -> pp f "@[<0>@[<2>[|%a|]@]@]" (list (simple_expr (under_semi ctxt)) ~sep:";") l | Pexp_while (e1, e2) -> let fmt : (_,_,_) format = "@[<2>while@;%a@;do@;%a@;done@]" in pp f fmt (expression ctxt) e1 (expression ctxt) e2 | Pexp_for (s, e1, e2, df, e3) -> let fmt:(_,_,_)format = "@[<hv0>@[<hv2>@[<2>for %a =@;%a@;%a%a@;do@]@;%a@]@;done@]" in let expression = expression ctxt in pp f fmt (pattern ctxt) s expression e1 direction_flag df expression e2 expression e3 | _ -> paren true (expression ctxt) f x and attributes ctxt f l = List.iter (attribute ctxt f) l and item_attributes ctxt f l = List.iter (item_attribute ctxt f) l and attribute ctxt f a = pp f "@[<2>[@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and item_attribute ctxt f a = pp f "@[<2>[@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and floating_attribute ctxt f a = pp f "@[<2>[@@@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and value_description ctxt f x = (* note: value_description has an attribute field, but they're already printed by the callers this method *) pp f "@[<hov2>%a%a@]" (core_type ctxt) x.pval_type (fun f x -> if x.pval_prim <> [] then pp f "@ =@ %a" (list constant_string) x.pval_prim ) x and extension ctxt f (s, e) = pp f "@[<2>[%%%s@ %a]@]" s.txt (payload ctxt) e and item_extension ctxt f (s, e) = pp f "@[<2>[%%%%%s@ %a]@]" s.txt (payload ctxt) e and exception_declaration ctxt f x = pp f "@[<hov2>exception@ %a@]%a" (extension_constructor ctxt) x.ptyexn_constructor (item_attributes ctxt) x.ptyexn_attributes and class_type_field ctxt f x = match x.pctf_desc with | Pctf_inherit (ct) -> pp f "@[<2>inherit@ %a@]%a" (class_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_val (s, mf, vf, ct) -> pp f "@[<2>val @ %a%a%s@ :@ %a@]%a" mutable_flag mf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_method (s, pf, vf, ct) -> pp f "@[<2>method %a %a%s :@;%a@]%a" private_flag pf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_constraint (ct1, ct2) -> pp f "@[<2>constraint@ %a@ =@ %a@]%a" (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pctf_attributes | Pctf_attribute a -> floating_attribute ctxt f a | Pctf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pctf_attributes and class_signature ctxt f { pcsig_self = ct; pcsig_fields = l ;_} = pp f "@[<hv0>@[<hv2>object@[<1>%a@]@ %a@]@ end@]" (fun f -> function {ptyp_desc=Ptyp_any; ptyp_attributes=[]; _} -> () | ct -> pp f " (%a)" (core_type ctxt) ct) ct (list (class_type_field ctxt) ~sep:"@;") l (* call [class_signature] called by [class_signature] *) and class_type ctxt f x = match x.pcty_desc with | Pcty_signature cs -> class_signature ctxt f cs; attributes ctxt f x.pcty_attributes | Pcty_constr (li, l) -> pp f "%a%a%a" (fun f l -> match l with | [] -> () | _ -> pp f "[%a]@ " (list (core_type ctxt) ~sep:"," ) l) l longident_loc li (attributes ctxt) x.pcty_attributes | Pcty_arrow (l, co, cl) -> FIXME remove parens later (type_with_label ctxt) (l,co) (class_type ctxt) cl | Pcty_extension e -> extension ctxt f e; attributes ctxt f x.pcty_attributes | Pcty_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) longident_loc o.popen_expr (class_type ctxt) e (* [class type a = object end] *) and class_type_declaration_list ctxt f l = let class_type_declaration kwd f x = let { pci_params=ls; pci_name={ txt; _ }; _ } = x in pp f "@[<2>%s %a%a%s@ =@ %a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in match l with | [] -> () | [x] -> class_type_declaration "class type" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_type_declaration "class type") x (list ~sep:"@," (class_type_declaration "and")) xs and class_field ctxt f x = match x.pcf_desc with | Pcf_inherit (ovf, ce, so) -> pp f "@[<2>inherit@ %s@ %a%a@]%a" (override ovf) (class_expr ctxt) ce (fun f so -> match so with | None -> (); | Some (s) -> pp f "@ as %s" s.txt ) so (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_concrete (ovf, e)) -> pp f "@[<2>val%s %a%s =@;%a@]%a" (override ovf) mutable_flag mf s.txt (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_virtual ct) -> pp f "@[<2>method virtual %a %s :@;%a@]%a" private_flag pf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_virtual ct) -> pp f "@[<2>val virtual %a%s :@ %a@]%a" mutable_flag mf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_concrete (ovf, e)) -> let bind e = binding ctxt f {pvb_pat= {ppat_desc=Ppat_var s; ppat_loc=Location.none; ppat_loc_stack=[]; ppat_attributes=[]}; pvb_expr=e; pvb_attributes=[]; pvb_loc=Location.none; } in pp f "@[<2>method%s %a%a@]%a" (override ovf) private_flag pf (fun f -> function | {pexp_desc=Pexp_poly (e, Some ct); pexp_attributes=[]; _} -> pp f "%s :@;%a=@;%a" s.txt (core_type ctxt) ct (expression ctxt) e | {pexp_desc=Pexp_poly (e, None); pexp_attributes=[]; _} -> bind e | _ -> bind e) e (item_attributes ctxt) x.pcf_attributes | Pcf_constraint (ct1, ct2) -> pp f "@[<2>constraint %a =@;%a@]%a" (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pcf_attributes | Pcf_initializer (e) -> pp f "@[<2>initializer@ %a@]%a" (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_attribute a -> floating_attribute ctxt f a | Pcf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pcf_attributes and class_structure ctxt f { pcstr_self = p; pcstr_fields = l } = pp f "@[<hv0>@[<hv2>object%a@;%a@]@;end@]" (fun f p -> match p.ppat_desc with | Ppat_any -> () | Ppat_constraint _ -> pp f " %a" (pattern ctxt) p | _ -> pp f " (%a)" (pattern ctxt) p) p (list (class_field ctxt)) l and class_expr ctxt f x = if x.pcl_attributes <> [] then begin pp f "((%a)%a)" (class_expr ctxt) {x with pcl_attributes=[]} (attributes ctxt) x.pcl_attributes end else match x.pcl_desc with | Pcl_structure (cs) -> class_structure ctxt f cs | Pcl_fun (l, eo, p, e) -> pp f "fun@ %a@ ->@ %a" (label_exp ctxt) (l,eo,p) (class_expr ctxt) e | Pcl_let (rf, l, ce) -> pp f "%a@ in@ %a" (bindings ctxt) (rf,l) (class_expr ctxt) ce | Pcl_apply (ce, l) -> Cf : # 7200 (class_expr ctxt) ce (list (label_x_expression_param ctxt)) l | Pcl_constr (li, l) -> pp f "%a%a" (fun f l-> if l <>[] then pp f "[%a]@ " (list (core_type ctxt) ~sep:",") l) l longident_loc li | Pcl_constraint (ce, ct) -> pp f "(%a@ :@ %a)" (class_expr ctxt) ce (class_type ctxt) ct | Pcl_extension e -> extension ctxt f e | Pcl_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) longident_loc o.popen_expr (class_expr ctxt) e and module_type ctxt f x = if x.pmty_attributes <> [] then begin pp f "((%a)%a)" (module_type ctxt) {x with pmty_attributes=[]} (attributes ctxt) x.pmty_attributes end else match x.pmty_desc with | Pmty_functor (Unit, mt2) -> pp f "@[<hov2>() ->@ %a@]" (module_type ctxt) mt2 | Pmty_functor (Named (s, mt1), mt2) -> begin match s.txt with | None -> pp f "@[<hov2>%a@ ->@ %a@]" (module_type1 ctxt) mt1 (module_type ctxt) mt2 | Some name -> pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" name (module_type ctxt) mt1 (module_type ctxt) mt2 end | Pmty_with (mt, []) -> module_type ctxt f mt | Pmty_with (mt, l) -> pp f "@[<hov2>%a@ with@ %a@]" (module_type1 ctxt) mt (list (with_constraint ctxt) ~sep:"@ and@ ") l | _ -> module_type1 ctxt f x and with_constraint ctxt f = function | Pwith_type (li, ({ptype_params= ls ;_} as td)) -> pp f "type@ %a %a =@ %a" (type_params ctxt) ls longident_loc li (type_declaration ctxt) td | Pwith_module (li, li2) -> pp f "module %a =@ %a" longident_loc li longident_loc li2; | Pwith_modtype (li, mty) -> pp f "module type %a =@ %a" longident_loc li (module_type ctxt) mty; | Pwith_typesubst (li, ({ptype_params=ls;_} as td)) -> pp f "type@ %a %a :=@ %a" (type_params ctxt) ls longident_loc li (type_declaration ctxt) td | Pwith_modsubst (li, li2) -> pp f "module %a :=@ %a" longident_loc li longident_loc li2 | Pwith_modtypesubst (li, mty) -> pp f "module type %a :=@ %a" longident_loc li (module_type ctxt) mty; and module_type1 ctxt f x = if x.pmty_attributes <> [] then module_type ctxt f x else match x.pmty_desc with | Pmty_ident li -> pp f "%a" longident_loc li; | Pmty_alias li -> pp f "(module %a)" longident_loc li; | Pmty_signature (s) -> pp f "@[<hv0>@[<hv2>sig@ %a@]@ end@]" (* "@[<hov>sig@ %a@ end@]" *) (list (signature_item ctxt)) s (* FIXME wrong indentation*) | Pmty_typeof me -> pp f "@[<hov2>module@ type@ of@ %a@]" (module_expr ctxt) me | Pmty_extension e -> extension ctxt f e | _ -> paren true (module_type ctxt) f x and signature ctxt f x = list ~sep:"@\n" (signature_item ctxt) f x and signature_item ctxt f x : unit = match x.psig_desc with | Psig_type (rf, l) -> type_def_list ctxt f (rf, true, l) | Psig_typesubst l -> (* Psig_typesubst is never recursive, but we specify [Recursive] here to avoid printing a [nonrec] flag, which would be rejected by the parser. *) type_def_list ctxt f (Recursive, false, l) | Psig_value vd -> let intro = if vd.pval_prim = [] then "val" else "external" in pp f "@[<2>%s@ %a@ :@ %a@]%a" intro protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Psig_typext te -> type_extension ctxt f te | Psig_exception ed -> exception_declaration ctxt f ed | Psig_class l -> let class_description kwd f ({pci_params=ls;pci_name={txt;_};_} as x) = pp f "@[<2>%s %a%a%s@;:@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_description "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_description "class") x (list ~sep:"@," (class_description "and")) xs end | Psig_module ({pmd_type={pmty_desc=Pmty_alias alias; pmty_attributes=[]; _};_} as pmd) -> pp f "@[<hov>module@ %s@ =@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") longident_loc alias (item_attributes ctxt) pmd.pmd_attributes | Psig_module pmd -> pp f "@[<hov>module@ %s@ :@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes | Psig_modsubst pms -> pp f "@[<hov>module@ %s@ :=@ %a@]%a" pms.pms_name.txt longident_loc pms.pms_manifest (item_attributes ctxt) pms.pms_attributes | Psig_open od -> pp f "@[<hov2>open%s@ %a@]%a" (override od.popen_override) longident_loc od.popen_expr (item_attributes ctxt) od.popen_attributes | Psig_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_type ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes | Psig_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>module@ type@ %s%a@]%a" s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Psig_modtypesubst {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> let md = match md with | None -> assert false (* ast invariant *) | Some mt -> mt in pp f "@[<hov2>module@ type@ %s@ :=@ %a@]%a" s.txt (module_type ctxt) md (item_attributes ctxt) attrs | Psig_class_type (l) -> class_type_declaration_list ctxt f l | Psig_recmodule decls -> let rec string_x_module_type_list f ?(first=true) l = match l with | [] -> () ; | pmd :: tl -> if not first then pp f "@ @[<hov2>and@ %s:@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes else pp f "@[<hov2>module@ rec@ %s:@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes; string_x_module_type_list f ~first:false tl in string_x_module_type_list f decls | Psig_attribute a -> floating_attribute ctxt f a | Psig_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and module_expr ctxt f x = if x.pmod_attributes <> [] then pp f "((%a)%a)" (module_expr ctxt) {x with pmod_attributes=[]} (attributes ctxt) x.pmod_attributes else match x.pmod_desc with | Pmod_structure (s) -> pp f "@[<hv2>struct@;@[<0>%a@]@;<1 -2>end@]" (list (structure_item ctxt) ~sep:"@\n") s; | Pmod_constraint (me, mt) -> pp f "@[<hov2>(%a@ :@ %a)@]" (module_expr ctxt) me (module_type ctxt) mt | Pmod_ident (li) -> pp f "%a" longident_loc li; | Pmod_functor (Unit, me) -> pp f "functor ()@;->@;%a" (module_expr ctxt) me | Pmod_functor (Named (s, mt), me) -> pp f "functor@ (%s@ :@ %a)@;->@;%a" (Option.value s.txt ~default:"_") (module_type ctxt) mt (module_expr ctxt) me | Pmod_apply (me1, me2) -> pp f "(%a)(%a)" (module_expr ctxt) me1 (module_expr ctxt) me2 Cf : # 7200 | Pmod_unpack e -> pp f "(val@ %a)" (expression ctxt) e | Pmod_extension e -> extension ctxt f e and structure ctxt f x = list ~sep:"@\n" (structure_item ctxt) f x and payload ctxt f = function | PStr [{pstr_desc = Pstr_eval (e, attrs)}] -> pp f "@[<2>%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | PStr x -> structure ctxt f x | PTyp x -> pp f ":@ "; core_type ctxt f x | PSig x -> pp f ":@ "; signature ctxt f x | PPat (x, None) -> pp f "?@ "; pattern ctxt f x | PPat (x, Some e) -> pp f "?@ "; pattern ctxt f x; pp f " when "; expression ctxt f e (* transform [f = fun g h -> ..] to [f g h = ... ] could be improved *) and binding ctxt f {pvb_pat=p; pvb_expr=x; _} = (* .pvb_attributes have already been printed by the caller, #bindings *) let rec pp_print_pexp_function f x = if x.pexp_attributes <> [] then pp f "=@;%a" (expression ctxt) x else match x.pexp_desc with | Pexp_fun (label, eo, p, e) -> if label=Nolabel then pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function e else pp f "%a@ %a" (label_exp ctxt) (label,eo,p) pp_print_pexp_function e | Pexp_newtype (str,e) -> pp f "(type@ %s)@ %a" str.txt pp_print_pexp_function e | _ -> pp f "=@;%a" (expression ctxt) x in let tyvars_str tyvars = List.map (fun v -> v.txt) tyvars in let is_desugared_gadt p e = let gadt_pattern = match p with | {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _} as pat, {ptyp_desc=Ptyp_poly (args_tyvars, rt)}); ppat_attributes=[]}-> Some (pat, args_tyvars, rt) | _ -> None in let rec gadt_exp tyvars e = match e with | {pexp_desc=Pexp_newtype (tyvar, e); pexp_attributes=[]} -> gadt_exp (tyvar :: tyvars) e | {pexp_desc=Pexp_constraint (e, ct); pexp_attributes=[]} -> Some (List.rev tyvars, e, ct) | _ -> None in let gadt_exp = gadt_exp [] e in match gadt_pattern, gadt_exp with | Some (p, pt_tyvars, pt_ct), Some (e_tyvars, e, e_ct) when tyvars_str pt_tyvars = tyvars_str e_tyvars -> let ety = Typ.varify_constructors e_tyvars e_ct in if ety = pt_ct then Some (p, pt_tyvars, e_ct, e) else None | _ -> None in if x.pexp_attributes <> [] then match p with | {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _; _} as pat, ({ptyp_desc=Ptyp_poly _; _} as typ)); ppat_attributes=[]; _} -> pp f "%a@;: %a@;=@;%a" (simple_pattern ctxt) pat (core_type ctxt) typ (expression ctxt) x | _ -> pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x else match is_desugared_gadt p x with | Some (p, [], ct, e) -> pp f "%a@;: %a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ct (expression ctxt) e | Some (p, tyvars, ct, e) -> begin pp f "%a@;: type@;%a.@;%a@;=@;%a" (simple_pattern ctxt) p (list pp_print_string ~sep:"@;") (tyvars_str tyvars) (core_type ctxt) ct (expression ctxt) e end | None -> begin match p with | {ppat_desc=Ppat_constraint(p ,ty); special case for the first begin match ty with | {ptyp_desc=Ptyp_poly _; ptyp_attributes=[]} -> pp f "%a@;:@;%a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x | _ -> pp f "(%a@;:@;%a)@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x end | {ppat_desc=Ppat_var _; ppat_attributes=[]} -> pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function x | _ -> pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x end (* [in] is not printed *) and bindings ctxt f (rf,l) = let binding kwd rf f x = pp f "@[<2>%s %a%a@]%a" kwd rec_flag rf (binding ctxt) x (item_attributes ctxt) x.pvb_attributes in match l with | [] -> () | [x] -> binding "let" rf f x | x::xs -> pp f "@[<v>%a@,%a@]" (binding "let" rf) x (list ~sep:"@," (binding "and" Nonrecursive)) xs and binding_op ctxt f x = match x.pbop_pat, x.pbop_exp with | {ppat_desc = Ppat_var { txt=pvar; _ }; ppat_attributes = []; _}, {pexp_desc = Pexp_ident { txt=Lident evar; _}; pexp_attributes = []; _} when pvar = evar -> pp f "@[<2>%s %s@]" x.pbop_op.txt evar | pat, exp -> pp f "@[<2>%s %a@;=@;%a@]" x.pbop_op.txt (pattern ctxt) pat (expression ctxt) exp and structure_item ctxt f x = match x.pstr_desc with | Pstr_eval (e, attrs) -> pp f "@[<hov2>;;%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | Pstr_type (_, []) -> assert false | Pstr_type (rf, l) -> type_def_list ctxt f (rf, true, l) | Pstr_value (rf, l) -> pp f " @[<hov2 > let % a%a@ ] " rec_flag rf bindings l pp f "@[<2>%a@]" (bindings ctxt) (rf,l) | Pstr_typext te -> type_extension ctxt f te | Pstr_exception ed -> exception_declaration ctxt f ed | Pstr_module x -> let rec module_helper = function | {pmod_desc=Pmod_functor(arg_opt,me'); pmod_attributes = []} -> begin match arg_opt with | Unit -> pp f "()" | Named (s, mt) -> pp f "(%s:%a)" (Option.value s.txt ~default:"_") (module_type ctxt) mt end; module_helper me' | me -> me in pp f "@[<hov2>module %s%a@]%a" (Option.value x.pmb_name.txt ~default:"_") (fun f me -> let me = module_helper me in match me with | {pmod_desc= Pmod_constraint (me', ({pmty_desc=(Pmty_ident (_) | Pmty_signature (_));_} as mt)); pmod_attributes = []} -> pp f " :@;%a@;=@;%a@;" (module_type ctxt) mt (module_expr ctxt) me' | _ -> pp f " =@ %a" (module_expr ctxt) me ) x.pmb_expr (item_attributes ctxt) x.pmb_attributes | Pstr_open od -> pp f "@[<2>open%s@;%a@]%a" (override od.popen_override) (module_expr ctxt) od.popen_expr (item_attributes ctxt) od.popen_attributes | Pstr_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>module@ type@ %s%a@]%a" s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Pstr_class l -> let extract_class_args cl = let rec loop acc = function | {pcl_desc=Pcl_fun (l, eo, p, cl'); pcl_attributes = []} -> loop ((l,eo,p) :: acc) cl' | cl -> List.rev acc, cl in let args, cl = loop [] cl in let constr, cl = match cl with | {pcl_desc=Pcl_constraint (cl', ct); pcl_attributes = []} -> Some ct, cl' | _ -> None, cl in args, constr, cl in let class_constraint f ct = pp f ": @[%a@] " (class_type ctxt) ct in let class_declaration kwd f ({pci_params=ls; pci_name={txt;_}; _} as x) = let args, constr, cl = extract_class_args x.pci_expr in pp f "@[<2>%s %a%a%s %a%a=@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (list (label_exp ctxt)) args (option class_constraint) constr (class_expr ctxt) cl (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_declaration "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_declaration "class") x (list ~sep:"@," (class_declaration "and")) xs end | Pstr_class_type l -> class_type_declaration_list ctxt f l | Pstr_primitive vd -> pp f "@[<hov2>external@ %a@ :@ %a@]%a" protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Pstr_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_expr ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes 3.07 let aux f = function | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) -> pp f "@[<hov2>@ and@ %s:%a@ =@ %a@]%a" (Option.value pmb.pmb_name.txt ~default:"_") (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes | pmb -> pp f "@[<hov2>@ and@ %s@ =@ %a@]%a" (Option.value pmb.pmb_name.txt ~default:"_") (module_expr ctxt) pmb.pmb_expr (item_attributes ctxt) pmb.pmb_attributes in begin match decls with | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) :: l2 -> pp f "@[<hv>@[<hov2>module@ rec@ %s:%a@ =@ %a@]%a@ %a@]" (Option.value pmb.pmb_name.txt ~default:"_") (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | pmb :: l2 -> pp f "@[<hv>@[<hov2>module@ rec@ %s@ =@ %a@]%a@ %a@]" (Option.value pmb.pmb_name.txt ~default:"_") (module_expr ctxt) pmb.pmb_expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | _ -> assert false end | Pstr_attribute a -> floating_attribute ctxt f a | Pstr_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and type_param ctxt f (ct, (a,b)) = pp f "%s%s%a" (type_variance a) (type_injectivity b) (core_type ctxt) ct and type_params ctxt f = function | [] -> () | l -> pp f "%a " (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",@;") l and type_def_list ctxt f (rf, exported, l) = let type_decl kwd rf f x = let eq = if (x.ptype_kind = Ptype_abstract) && (x.ptype_manifest = None) then "" else if exported then " =" else " :=" in pp f "@[<2>%s %a%a%s%s%a@]%a" kwd nonrec_flag rf (type_params ctxt) x.ptype_params x.ptype_name.txt eq (type_declaration ctxt) x (item_attributes ctxt) x.ptype_attributes in match l with | [] -> assert false | [x] -> type_decl "type" rf f x | x :: xs -> pp f "@[<v>%a@,%a@]" (type_decl "type" rf) x (list ~sep:"@," (type_decl "and" Recursive)) xs and record_declaration ctxt f lbls = let type_record_field f pld = pp f "@[<2>%a%s:@;%a@;%a@]" mutable_flag pld.pld_mutable pld.pld_name.txt (core_type ctxt) pld.pld_type (attributes ctxt) pld.pld_attributes in pp f "{@\n%a}" (list type_record_field ~sep:";@\n" ) lbls and type_declaration ctxt f x = (* type_declaration has an attribute field, but it's been printed by the caller of this method *) let priv f = match x.ptype_private with | Public -> () | Private -> pp f "@;private" in let manifest f = match x.ptype_manifest with | None -> () | Some y -> if x.ptype_kind = Ptype_abstract then pp f "%t@;%a" priv (core_type ctxt) y else pp f "@;%a" (core_type ctxt) y in let constructor_declaration f pcd = pp f "|@;"; constructor_declaration ctxt f (pcd.pcd_name.txt, pcd.pcd_vars, pcd.pcd_args, pcd.pcd_res, pcd.pcd_attributes) in let repr f = let intro f = if x.ptype_manifest = None then () else pp f "@;=" in match x.ptype_kind with | Ptype_variant xs -> let variants fmt xs = if xs = [] then pp fmt " |" else pp fmt "@\n%a" (list ~sep:"@\n" constructor_declaration) xs in pp f "%t%t%a" intro priv variants xs | Ptype_abstract -> () | Ptype_record l -> pp f "%t%t@;%a" intro priv (record_declaration ctxt) l | Ptype_open -> pp f "%t%t@;.." intro priv in let constraints f = List.iter (fun (ct1,ct2,_) -> pp f "@[<hov2>@ constraint@ %a@ =@ %a@]" (core_type ctxt) ct1 (core_type ctxt) ct2) x.ptype_cstrs in pp f "%t%t%t" manifest repr constraints and type_extension ctxt f x = let extension_constructor f x = pp f "@\n|@;%a" (extension_constructor ctxt) x in pp f "@[<2>type %a%a += %a@ %a@]%a" (fun f -> function | [] -> () | l -> pp f "%a@;" (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l) x.ptyext_params longident_loc x.ptyext_path Cf : # 7200 (list ~sep:"" extension_constructor) x.ptyext_constructors (item_attributes ctxt) x.ptyext_attributes and constructor_declaration ctxt f (name, vars, args, res, attrs) = let name = match name with | "::" -> "(::)" | s -> s in let pp_vars f vs = match vs with | [] -> () | vs -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") vs in match res with | None -> pp f "%s%a@;%a" name (fun f -> function | Pcstr_tuple [] -> () | Pcstr_tuple l -> pp f "@;of@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l | Pcstr_record l -> pp f "@;of@;%a" (record_declaration ctxt) l ) args (attributes ctxt) attrs | Some r -> pp f "%s:@;%a%a@;%a" name pp_vars vars (fun f -> function | Pcstr_tuple [] -> core_type1 ctxt f r | Pcstr_tuple l -> pp f "%a@;->@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l (core_type1 ctxt) r | Pcstr_record l -> pp f "%a@;->@;%a" (record_declaration ctxt) l (core_type1 ctxt) r ) args (attributes ctxt) attrs and extension_constructor ctxt f x = Cf : # 7200 match x.pext_kind with | Pext_decl(v, l, r) -> constructor_declaration ctxt f (x.pext_name.txt, v, l, r, x.pext_attributes) | Pext_rebind li -> pp f "%s@;=@;%a%a" x.pext_name.txt longident_loc li (attributes ctxt) x.pext_attributes and case_list ctxt f l : unit = let aux f {pc_lhs; pc_guard; pc_rhs} = pp f "@;| @[<2>%a%a@;->@;%a@]" (pattern ctxt) pc_lhs (option (expression ctxt) ~first:"@;when@;") pc_guard (expression (under_pipe ctxt)) pc_rhs in list aux f l ~sep:"" and label_x_expression_param ctxt f (l,e) = let simple_name = match e with | {pexp_desc=Pexp_ident {txt=Lident l;_}; pexp_attributes=[]} -> Some l | _ -> None in match l with level 2 | Optional str -> if Some str = simple_name then pp f "?%s" str else pp f "?%s:%a" str (simple_expr ctxt) e | Labelled lbl -> if Some lbl = simple_name then pp f "~%s" lbl else pp f "~%s:%a" lbl (simple_expr ctxt) e and directive_argument f x = match x.pdira_desc with | Pdir_string (s) -> pp f "@ %S" s | Pdir_int (n, None) -> pp f "@ %s" n | Pdir_int (n, Some m) -> pp f "@ %s%c" n m | Pdir_ident (li) -> pp f "@ %a" longident li | Pdir_bool (b) -> pp f "@ %s" (string_of_bool b) let toplevel_phrase f x = match x with | Ptop_def (s) ->pp f "@[<hov0>%a@]" (list (structure_item reset_ctxt)) s (* pp_open_hvbox f 0; *) (* pp_print_list structure_item f s ; *) pp_close_box f ( ) ; | Ptop_dir {pdir_name; pdir_arg = None; _} -> pp f "@[<hov2>#%s@]" pdir_name.txt | Ptop_dir {pdir_name; pdir_arg = Some pdir_arg; _} -> pp f "@[<hov2>#%s@ %a@]" pdir_name.txt directive_argument pdir_arg let expression f x = pp f "@[%a@]" (expression reset_ctxt) x let string_of_expression x = ignore (flush_str_formatter ()) ; let f = str_formatter in expression f x; flush_str_formatter () let string_of_structure x = ignore (flush_str_formatter ()); let f = str_formatter in structure reset_ctxt f x; flush_str_formatter () let top_phrase f x = pp_print_newline f (); toplevel_phrase f x; pp f ";;"; pp_print_newline f () let core_type = core_type reset_ctxt let pattern = pattern reset_ctxt let signature = signature reset_ctxt let structure = structure reset_ctxt let module_expr = module_expr reset_ctxt let module_type = module_type reset_ctxt let class_field = class_field reset_ctxt let class_type_field = class_type_field reset_ctxt let class_expr = class_expr reset_ctxt let class_type = class_type reset_ctxt let structure_item = structure_item reset_ctxt let signature_item = signature_item reset_ctxt let binding = binding reset_ctxt let payload = payload reset_ctxt
null
https://raw.githubusercontent.com/avsm/eeww/4834abb9a40a9f35d0d7041a61e53e3426d8886f/boot/ocaml/parsing/pprintast.ml
ocaml
************************************************************************ OCaml Fabrice Le Fessant, INRIA Saclay en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Printing code expressions type fixity = Infix| Prefix which identifiers are in fact operators needing parentheses some infixes need spaces around parens to avoid clashes with comment syntax add parentheses to binders when they are in fact infix or prefix operators variance encoding: need to sync up with the [parser.mly] trailing space trailing space added without the space, this would be parsed as a character literal c ['a,'b] space otherwise parenthesize "%a%a@;" Cf #7200: print [>] correctly FIXME desugar the syntax sugar *******************pattern******************* RA single case pattern parens needed here extract operator: assignment operators end with [right_bracket ^ "<-"], access operators end with [right_bracket] directly extract the right end bracket "try@;@[<2>%a@]@\nwith@\n%a" pp f "@[<2>let %a%a in@;<1 -2>%a@]" (*no indentation here, a new line See #7200: avoid turning (~- 1) into (- 1) which is parsed as an int literal reset here only because [function,match,try,sequence] are lower priority Not efficient FIXME @;@[<2>else@ %a@]@] pp f "()" Pexp_poly: impossible but we should print it anyway, rather than assert false used in [Pexp_apply] (match view_fixity_of_exp x with |`Normal -> longident_loc f li | `Prefix _ | `Infix _ -> pp f "( %a )" longident_loc li) no sep hint "@[<hov2>{%a%a}@]" note: value_description has an attribute field, but they're already printed by the callers this method call [class_signature] called by [class_signature] [class type a = object end] "@[<hov>sig@ %a@ end@]" FIXME wrong indentation Psig_typesubst is never recursive, but we specify [Recursive] here to avoid printing a [nonrec] flag, which would be rejected by the parser. ast invariant transform [f = fun g h -> ..] to [f g h = ... ] could be improved .pvb_attributes have already been printed by the caller, #bindings [in] is not printed type_declaration has an attribute field, but it's been printed by the caller of this method pp_open_hvbox f 0; pp_print_list structure_item f s ;
, OCamlPro , University of Pennsylvania Copyright 2007 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the Original Code from Ber - metaocaml , modified for 3.12.0 and fixed Authors : , Extensive Rewrite : : University of Pennsylvania TODO more fine - grained precedence pretty - printing open Asttypes open Format open Location open Longident open Parsetree open Ast_helper let prefix_symbols = [ '!'; '?'; '~' ] let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/'; '$'; '%'; '#' ] let special_infix_strings = ["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!="; "::" ] let letop s = String.length s > 3 && s.[0] = 'l' && s.[1] = 'e' && s.[2] = 't' && List.mem s.[3] infix_symbols let andop s = String.length s > 3 && s.[0] = 'a' && s.[1] = 'n' && s.[2] = 'd' && List.mem s.[3] infix_symbols determines if the string is an infix string . checks backwards , first allowing a renaming postfix ( " _ 102 " ) which may have resulted from - > Texp - > translation , then checking if all the characters in the beginning of the string are valid infix characters . checks backwards, first allowing a renaming postfix ("_102") which may have resulted from Pexp -> Texp -> Pexp translation, then checking if all the characters in the beginning of the string are valid infix characters. *) let fixity_of_string = function | "" -> `Normal | s when List.mem s special_infix_strings -> `Infix s | s when List.mem s.[0] infix_symbols -> `Infix s | s when List.mem s.[0] prefix_symbols -> `Prefix s | s when s.[0] = '.' -> `Mixfix s | s when letop s -> `Letop s | s when andop s -> `Andop s | _ -> `Normal let view_fixity_of_exp = function | {pexp_desc = Pexp_ident {txt=Lident l;_}; pexp_attributes = []} -> fixity_of_string l | _ -> `Normal let is_infix = function `Infix _ -> true | _ -> false let is_mixfix = function `Mixfix _ -> true | _ -> false let is_kwdop = function `Letop _ | `Andop _ -> true | _ -> false let first_is c str = str <> "" && str.[0] = c let last_is c str = str <> "" && str.[String.length str - 1] = c let first_is_in cs str = str <> "" && List.mem str.[0] cs let needs_parens txt = let fix = fixity_of_string txt in is_infix fix || is_mixfix fix || is_kwdop fix || first_is_in prefix_symbols txt let needs_spaces txt = first_is '*' txt || last_is '*' txt let string_loc ppf x = fprintf ppf "%s" x.txt let protect_ident ppf txt = let format : (_, _, _) format = if not (needs_parens txt) then "%s" else if needs_spaces txt then "(@;%s@;)" else "(%s)" in fprintf ppf format txt let protect_longident ppf print_longident longprefix txt = let format : (_, _, _) format = if not (needs_parens txt) then "%a.%s" else if needs_spaces txt then "%a.(@;%s@;)" else "%a.(%s)" in fprintf ppf format print_longident longprefix txt type space_formatter = (unit, Format.formatter, unit) format let override = function | Override -> "!" | Fresh -> "" let type_variance = function | NoVariance -> "" | Covariant -> "+" | Contravariant -> "-" let type_injectivity = function | NoInjectivity -> "" | Injective -> "!" type construct = [ `cons of expression list | `list of expression list | `nil | `normal | `simple of Longident.t | `tuple ] let view_expr x = match x.pexp_desc with | Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple | Pexp_construct ( {txt= Lident "[]";_},_) -> `nil | Pexp_construct ( {txt= Lident"::";_},Some _) -> let rec loop exp acc = match exp with | {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_); pexp_attributes = []} -> (List.rev acc,true) | {pexp_desc= Pexp_construct ({txt=Lident "::";_}, Some ({pexp_desc= Pexp_tuple([e1;e2]); pexp_attributes = []})); pexp_attributes = []} -> loop e2 (e1::acc) | e -> (List.rev (e::acc),false) in let (ls,b) = loop x [] in if b then `list ls else `cons ls | Pexp_construct (x,None) -> `simple (x.txt) | _ -> `normal let is_simple_construct :construct -> bool = function | `nil | `tuple | `list _ | `simple _ -> true | `cons _ | `normal -> false let pp = fprintf type ctxt = { pipe : bool; semi : bool; ifthenelse : bool; } let reset_ctxt = { pipe=false; semi=false; ifthenelse=false } let under_pipe ctxt = { ctxt with pipe=true } let under_semi ctxt = { ctxt with semi=true } let under_ifthenelse ctxt = { ctxt with ifthenelse=true } let reset_semi = with semi = false } let reset_ifthenelse = with ifthenelse = false } let = with pipe = false } let reset_semi ctxt = { ctxt with semi=false } let reset_ifthenelse ctxt = { ctxt with ifthenelse=false } let reset_pipe ctxt = { ctxt with pipe=false } *) let list : 'a . ?sep:space_formatter -> ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a list -> unit = fun ?sep ?first ?last fu f xs -> let first = match first with Some x -> x |None -> ("": _ format6) and last = match last with Some x -> x |None -> ("": _ format6) and sep = match sep with Some x -> x |None -> ("@ ": _ format6) in let aux f = function | [] -> () | [x] -> fu f x | xs -> let rec loop f = function | [x] -> fu f x | x::xs -> fu f x; pp f sep; loop f xs; | _ -> assert false in begin pp f first; loop f xs; pp f last; end in aux f xs let option : 'a. ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit = fun ?first ?last fu f a -> let first = match first with Some x -> x | None -> ("": _ format6) and last = match last with Some x -> x | None -> ("": _ format6) in match a with | None -> () | Some x -> pp f first; fu f x; pp f last let paren: 'a . ?first:space_formatter -> ?last:space_formatter -> bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit = fun ?(first=("": _ format6)) ?(last=("": _ format6)) b fu f x -> if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")") else fu f x let rec longident f = function | Lident s -> protect_ident f s | Ldot(y,s) -> protect_longident f longident y s | Lapply (y,s) -> pp f "%a(%a)" longident y longident s let longident_loc f x = pp f "%a" longident x.txt let constant f = function | Pconst_char i -> pp f "%C" i | Pconst_string (i, _, None) -> pp f "%S" i | Pconst_string (i, _, Some delim) -> pp f "{%s|%s|%s}" delim i delim | Pconst_integer (i, None) -> paren (first_is '-' i) (fun f -> pp f "%s") f i | Pconst_integer (i, Some m) -> paren (first_is '-' i) (fun f (i, m) -> pp f "%s%c" i m) f (i,m) | Pconst_float (i, None) -> paren (first_is '-' i) (fun f -> pp f "%s") f i | Pconst_float (i, Some m) -> paren (first_is '-' i) (fun f (i,m) -> pp f "%s%c" i m) f (i,m) let mutable_flag f = function | Immutable -> () | Mutable -> pp f "mutable@;" let virtual_flag f = function | Concrete -> () | Virtual -> pp f "virtual@;" let rec_flag f rf = match rf with | Nonrecursive -> () | Recursive -> pp f "rec " let nonrec_flag f rf = match rf with | Nonrecursive -> pp f "nonrec " | Recursive -> () let direction_flag f = function | Upto -> pp f "to@ " | Downto -> pp f "downto@ " let private_flag f = function | Public -> () | Private -> pp f "private@ " let iter_loc f ctxt {txt; loc = _} = f ctxt txt let constant_string f s = pp f "%S" s let tyvar ppf s = if String.length s >= 2 && s.[1] = '\'' then Format.fprintf ppf "' %s" s else Format.fprintf ppf "'%s" s let tyvar_loc f str = tyvar f str.txt let string_quot f x = pp f "`%s" x let rec class_params_def ctxt f = function | [] -> () | l -> (list (type_param ctxt) ~sep:",") l and type_with_label ctxt f (label, c) = match label with | Labelled s -> pp f "%s:%a" s (core_type1 ctxt) c | Optional s -> pp f "?%s:%a" s (core_type1 ctxt) c and core_type ctxt f x = if x.ptyp_attributes <> [] then begin pp f "((%a)%a)" (core_type ctxt) {x with ptyp_attributes=[]} (attributes ctxt) x.ptyp_attributes end else match x.ptyp_desc with | Ptyp_arrow (l, ct1, ct2) -> FIXME remove parens later (type_with_label ctxt) (l,ct1) (core_type ctxt) ct2 | Ptyp_alias (ct, s) -> pp f "@[<2>%a@;as@;%a@]" (core_type1 ctxt) ct tyvar s | Ptyp_poly ([], ct) -> core_type ctxt f ct | Ptyp_poly (sl, ct) -> pp f "@[<2>%a%a@]" (fun f l -> match l with | [] -> () | _ -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") l) sl (core_type ctxt) ct | _ -> pp f "@[<2>%a@]" (core_type1 ctxt) x and core_type1 ctxt f x = if x.ptyp_attributes <> [] then core_type ctxt f x else match x.ptyp_desc with | Ptyp_any -> pp f "_"; | Ptyp_var s -> tyvar f s; | Ptyp_tuple l -> pp f "(%a)" (list (core_type1 ctxt) ~sep:"@;*@;") l | Ptyp_constr (li, l) -> (fun f l -> match l with |[] -> () |[x]-> pp f "%a@;" (core_type1 ctxt) x | _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l) l longident_loc li | Ptyp_variant (l, closed, low) -> let first_is_inherit = match l with | {Parsetree.prf_desc = Rinherit _}::_ -> true | _ -> false in let type_variant_helper f x = match x.prf_desc with | Rtag (l, _, ctl) -> pp f "@[<2>%a%a@;%a@]" (iter_loc string_quot) l (fun f l -> match l with |[] -> () | _ -> pp f "@;of@;%a" (list (core_type ctxt) ~sep:"&") ctl) ctl (attributes ctxt) x.prf_attributes | Rinherit ct -> core_type ctxt f ct in pp f "@[<2>[%a%a]@]" (fun f l -> match l, closed with | [], Closed -> () | _ -> pp f "%s@;%a" (match (closed,low) with | (Closed,None) -> if first_is_inherit then " |" else "" | (Open,_) -> ">") (list type_variant_helper ~sep:"@;<1 -2>| ") l) l (fun f low -> match low with |Some [] |None -> () |Some xs -> pp f ">@ %a" (list string_quot) xs) low | Ptyp_object (l, o) -> let core_field_type f x = match x.pof_desc with | Otag (l, ct) -> Cf # 7200 pp f "@[<hov2>%s: %a@ %a@ @]" l.txt (core_type ctxt) ct (attributes ctxt) x.pof_attributes | Oinherit ct -> pp f "@[<hov2>%a@ @]" (core_type ctxt) ct in let field_var f = function | Asttypes.Closed -> () | Asttypes.Open -> match l with | [] -> pp f ".." | _ -> pp f " ;.." in pp f "@[<hov2><@ %a%a@ > @]" (list core_field_type ~sep:";") l Cf # 7200 FIXME pp f "@[<hov2>%a#%a@]" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") l longident_loc li | Ptyp_package (lid, cstrs) -> let aux f (s, ct) = pp f "type %a@ =@ %a" longident_loc s (core_type ctxt) ct in (match cstrs with |[] -> pp f "@[<hov2>(module@ %a)@]" longident_loc lid |_ -> pp f "@[<hov2>(module@ %a@ with@ %a)@]" longident_loc lid (list aux ~sep:"@ and@ ") cstrs) | Ptyp_extension e -> extension ctxt f e | _ -> paren true (core_type ctxt) f x be cautious when use [ pattern ] , [ ] is preferred and pattern ctxt f x = if x.ppat_attributes <> [] then begin pp f "((%a)%a)" (pattern ctxt) {x with ppat_attributes=[]} (attributes ctxt) x.ppat_attributes end else match x.ppat_desc with | Ppat_alias (p, s) -> pp f "@[<2>%a@;as@;%a@]" (pattern ctxt) p protect_ident s.txt | _ -> pattern_or ctxt f x and pattern_or ctxt f x = let rec left_associative x acc = match x with | {ppat_desc=Ppat_or (p1,p2); ppat_attributes = []} -> left_associative p1 (p2 :: acc) | x -> x :: acc in match left_associative x [] with | [] -> assert false | [x] -> pattern1 ctxt f x | orpats -> pp f "@[<hov0>%a@]" (list ~sep:"@ | " (pattern1 ctxt)) orpats and pattern1 ctxt (f:Format.formatter) (x:pattern) : unit = let rec pattern_list_helper f = function | {ppat_desc = Ppat_construct ({ txt = Lident("::") ;_}, Some ([], {ppat_desc = Ppat_tuple([pat1; pat2]);_})); ppat_attributes = []} -> | p -> pattern1 ctxt f p in if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_variant (l, Some p) -> pp f "@[<2>`%s@;%a@]" l (simple_pattern ctxt) p | Ppat_construct (({txt=Lident("()"|"[]");_}), _) -> simple_pattern ctxt f x | Ppat_construct (({txt;_} as li), po) -> FIXME The third field always false if txt = Lident "::" then pp f "%a" pattern_list_helper x else (match po with | Some ([], x) -> pp f "%a@;%a" longident_loc li (simple_pattern ctxt) x | Some (vl, x) -> pp f "%a@ (type %a)@;%a" longident_loc li (list ~sep:"@ " string_loc) vl (simple_pattern ctxt) x | None -> pp f "%a" longident_loc li) | _ -> simple_pattern ctxt f x and simple_pattern ctxt (f:Format.formatter) (x:pattern) : unit = if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_construct (({txt=Lident ("()"|"[]" as x);_}), None) -> pp f "%s" x | Ppat_any -> pp f "_"; | Ppat_var ({txt = txt;_}) -> protect_ident f txt | Ppat_array l -> pp f "@[<2>[|%a|]@]" (list (pattern1 ctxt) ~sep:";") l | Ppat_unpack { txt = None } -> pp f "(module@ _)@ " | Ppat_unpack { txt = Some s } -> pp f "(module@ %s)@ " s | Ppat_type li -> pp f "#%a" longident_loc li | Ppat_record (l, closed) -> let longident_x_pattern f (li, p) = match (li,p) with | ({txt=Lident s;_ }, {ppat_desc=Ppat_var {txt;_}; ppat_attributes=[]; _}) when s = txt -> pp f "@[<2>%a@]" longident_loc li | _ -> pp f "@[<2>%a@;=@;%a@]" longident_loc li (pattern1 ctxt) p in begin match closed with | Closed -> pp f "@[<2>{@;%a@;}@]" (list longident_x_pattern ~sep:";@;") l | _ -> pp f "@[<2>{@;%a;_}@]" (list longident_x_pattern ~sep:";@;") l end | Ppat_tuple l -> | Ppat_constant (c) -> pp f "%a" constant c | Ppat_interval (c1, c2) -> pp f "%a..%a" constant c1 constant c2 | Ppat_variant (l,None) -> pp f "`%s" l | Ppat_constraint (p, ct) -> pp f "@[<2>(%a@;:@;%a)@]" (pattern1 ctxt) p (core_type ctxt) ct | Ppat_lazy p -> pp f "@[<2>(lazy@;%a)@]" (simple_pattern ctxt) p | Ppat_exception p -> pp f "@[<2>exception@;%a@]" (pattern1 ctxt) p | Ppat_extension e -> extension ctxt f e | Ppat_open (lid, p) -> let with_paren = match p.ppat_desc with | Ppat_array _ | Ppat_record _ | Ppat_construct (({txt=Lident ("()"|"[]");_}), None) -> false | _ -> true in pp f "@[<2>%a.%a @]" longident_loc lid (paren with_paren @@ pattern1 ctxt) p | _ -> paren true (pattern ctxt) f x and label_exp ctxt f (l,opt,p) = match l with | Nolabel -> pp f "%a@ " (simple_pattern ctxt) p | Optional rest -> begin match p with | {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []} when txt = rest -> (match opt with | Some o -> pp f "?(%s=@;%a)@;" rest (expression ctxt) o | None -> pp f "?%s@ " rest) | _ -> (match opt with | Some o -> pp f "?%s:(%a=@;%a)@;" rest (pattern1 ctxt) p (expression ctxt) o | None -> pp f "?%s:%a@;" rest (simple_pattern ctxt) p) end | Labelled l -> match p with | {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []} when txt = l -> pp f "~%s@;" l | _ -> pp f "~%s:%a@;" l (simple_pattern ctxt) p and sugar_expr ctxt f e = if e.pexp_attributes <> [] then false else match e.pexp_desc with | Pexp_apply ({ pexp_desc = Pexp_ident {txt = id; _}; pexp_attributes=[]; _}, args) when List.for_all (fun (lab, _) -> lab = Nolabel) args -> begin let print_indexop a path_prefix assign left sep right print_index indices rem_args = let print_path ppf = function | None -> () | Some m -> pp ppf ".%a" longident m in match assign, rem_args with | false, [] -> pp f "@[%a%a%s%a%s@]" (simple_expr ctxt) a print_path path_prefix left (list ~sep print_index) indices right; true | true, [v] -> pp f "@[%a%a%s%a%s@ <-@;<1 2>%a@]" (simple_expr ctxt) a print_path path_prefix left (list ~sep print_index) indices right (simple_expr ctxt) v; true | _ -> false in match id, List.map snd args with | Lident "!", [e] -> pp f "@[<hov>!%a@]" (simple_expr ctxt) e; true | Ldot (path, ("get"|"set" as func)), a :: other_args -> begin let assign = func = "set" in let print = print_indexop a None assign in match path, other_args with | Lident "Array", i :: rest -> print ".(" "" ")" (expression ctxt) [i] rest | Lident "String", i :: rest -> print ".[" "" "]" (expression ctxt) [i] rest | Ldot (Lident "Bigarray", "Array1"), i1 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1] rest | Ldot (Lident "Bigarray", "Array2"), i1 :: i2 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1; i2] rest | Ldot (Lident "Bigarray", "Array3"), i1 :: i2 :: i3 :: rest -> print ".{" "," "}" (simple_expr ctxt) [i1; i2; i3] rest | Ldot (Lident "Bigarray", "Genarray"), {pexp_desc = Pexp_array indexes; pexp_attributes = []} :: rest -> print ".{" "," "}" (simple_expr ctxt) indexes rest | _ -> false end | (Lident s | Ldot(_,s)) , a :: i :: rest when first_is '.' s -> let multi_indices = String.contains s ';' in let i = match i.pexp_desc with | Pexp_array l when multi_indices -> l | _ -> [ i ] in let assign = last_is '-' s in let kind = let n = String.length s in if assign then s.[n - 3] else s.[n - 1] in let left, right = match kind with | ')' -> '(', ")" | ']' -> '[', "]" | '}' -> '{', "}" | _ -> assert false in let path_prefix = match id with | Ldot(m,_) -> Some m | _ -> None in let left = String.sub s 0 (1+String.index s left) in print_indexop a path_prefix assign left ";" right (if multi_indices then expression ctxt else simple_expr ctxt) i rest | _ -> false end | _ -> false and expression ctxt f x = if x.pexp_attributes <> [] then pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]} (attributes ctxt) x.pexp_attributes else match x.pexp_desc with | Pexp_function _ | Pexp_fun _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _ | Pexp_newtype _ when ctxt.pipe || ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_ifthenelse _ | Pexp_sequence _ when ctxt.ifthenelse -> paren true (expression reset_ctxt) f x | Pexp_let _ | Pexp_letmodule _ | Pexp_open _ | Pexp_letexception _ | Pexp_letop _ when ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_fun (l, e0, p, e) -> pp f "@[<2>fun@;%a->@;%a@]" (label_exp ctxt) (l, e0, p) (expression ctxt) e | Pexp_newtype (lid, e) -> pp f "@[<2>fun@;(type@;%s)@;->@;%a@]" lid.txt (expression ctxt) e | Pexp_function l -> pp f "@[<hv>function%a@]" (case_list ctxt) l | Pexp_match (e, l) -> pp f "@[<hv0>@[<hv0>@[<2>match %a@]@ with@]%a@]" (expression reset_ctxt) e (case_list ctxt) l | Pexp_try (e, l) -> pp f "@[<0>@[<hv2>try@ %a@]@ @[<0>with%a@]@]" (expression reset_ctxt) e (case_list ctxt) l | Pexp_let (rf, l, e) -> rec_flag rf pp f "@[<2>%a in@;<1 -2>%a@]" (bindings reset_ctxt) (rf,l) (expression ctxt) e | Pexp_apply (e, l) -> begin if not (sugar_expr ctxt f x) then match view_fixity_of_exp e with | `Infix s -> begin match l with | [ (Nolabel, _) as arg1; (Nolabel, _) as arg2 ] -> FIXME associativity label_x_expression_param pp f "@[<2>%a@;%s@;%a@]" (label_x_expression_param reset_ctxt) arg1 s (label_x_expression_param ctxt) arg2 | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | `Prefix s -> let s = if List.mem s ["~+";"~-";"~+.";"~-."] && (match l with |[(_,{pexp_desc=Pexp_constant _})] -> false | _ -> true) then String.sub s 1 (String.length s -1) else s in begin match l with | [(Nolabel, x)] -> pp f "@[<2>%s@;%a@]" s (simple_expr ctxt) x | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | _ -> pp f "@[<hov2>%a@]" begin fun f (e,l) -> pp f "%a@ %a" (expression2 ctxt) e (list (label_x_expression_param reset_ctxt)) l end (e,l) end | Pexp_construct (li, Some eo) (match view_expr x with | `cons ls -> list (simple_expr ctxt) f ls ~sep:"@;::@;" | `normal -> pp f "@[<2>%a@;%a@]" longident_loc li (simple_expr ctxt) eo | _ -> assert false) | Pexp_setfield (e1, li, e2) -> pp f "@[<2>%a.%a@ <-@ %a@]" (simple_expr ctxt) e1 longident_loc li (simple_expr ctxt) e2 | Pexp_ifthenelse (e1, e2, eo) -> let fmt:(_,_,_)format ="@[<hv0>@[<2>if@ %a@]@;@[<2>then@ %a@]%a@]" in let expression_under_ifthenelse = expression (under_ifthenelse ctxt) in pp f fmt expression_under_ifthenelse e1 expression_under_ifthenelse e2 (fun f eo -> match eo with | Some x -> pp f "@;@[<2>else@;%a@]" (expression (under_semi ctxt)) x | Pexp_sequence _ -> let rec sequence_helper acc = function | {pexp_desc=Pexp_sequence(e1,e2); pexp_attributes = []} -> sequence_helper (e1::acc) e2 | v -> List.rev (v::acc) in let lst = sequence_helper [] x in pp f "@[<hv>%a@]" (list (expression (under_semi ctxt)) ~sep:";@;") lst | Pexp_new (li) -> pp f "@[<hov2>new@ %a@]" longident_loc li; | Pexp_setinstvar (s, e) -> pp f "@[<hov2>%s@ <-@ %a@]" s.txt (expression ctxt) e FIXME let string_x_expression f (s, e) = pp f "@[<hov2>%s@ =@ %a@]" s.txt (expression ctxt) e in pp f "@[<hov2>{<%a>}@]" (list string_x_expression ~sep:";" ) l; | Pexp_letmodule (s, me, e) -> pp f "@[<hov2>let@ module@ %s@ =@ %a@ in@ %a@]" (Option.value s.txt ~default:"_") (module_expr reset_ctxt) me (expression ctxt) e | Pexp_letexception (cd, e) -> pp f "@[<hov2>let@ exception@ %a@ in@ %a@]" (extension_constructor ctxt) cd (expression ctxt) e | Pexp_assert e -> pp f "@[<hov2>assert@ %a@]" (simple_expr ctxt) e | Pexp_lazy (e) -> pp f "@[<hov2>lazy@ %a@]" (simple_expr ctxt) e | Pexp_poly (e, None) -> pp f "@[<hov2>!poly!@ %a@]" (simple_expr ctxt) e | Pexp_poly (e, Some ct) -> pp f "@[<hov2>(!poly!@ %a@ : %a)@]" (simple_expr ctxt) e (core_type ctxt) ct | Pexp_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) (module_expr ctxt) o.popen_expr (expression ctxt) e | Pexp_variant (l,Some eo) -> pp f "@[<2>`%s@;%a@]" l (simple_expr ctxt) eo | Pexp_letop {let_; ands; body} -> pp f "@[<2>@[<v>%a@,%a@] in@;<1 -2>%a@]" (binding_op ctxt) let_ (list ~sep:"@," (binding_op ctxt)) ands (expression ctxt) body | Pexp_extension e -> extension ctxt f e | Pexp_unreachable -> pp f "." | _ -> expression1 ctxt f x and expression1 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_object cs -> pp f "%a" (class_structure ctxt) cs | _ -> expression2 ctxt f x and expression2 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_field (e, li) -> pp f "@[<hov2>%a.%a@]" (simple_expr ctxt) e longident_loc li | Pexp_send (e, s) -> pp f "@[<hov2>%a#%s@]" (simple_expr ctxt) e s.txt | _ -> simple_expr ctxt f x and simple_expr ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_construct _ when is_simple_construct (view_expr x) -> (match view_expr x with | `nil -> pp f "[]" | `tuple -> pp f "()" | `list xs -> pp f "@[<hv0>[%a]@]" (list (expression (under_semi ctxt)) ~sep:";@;") xs | `simple x -> longident f x | _ -> assert false) | Pexp_ident li -> longident_loc f li | Pexp_constant c -> constant f c; | Pexp_pack me -> pp f "(module@;%a)" (module_expr ctxt) me | Pexp_tuple l -> pp f "@[<hov2>(%a)@]" (list (simple_expr ctxt) ~sep:",@;") l | Pexp_constraint (e, ct) -> pp f "(%a : %a)" (expression ctxt) e (core_type ctxt) ct | Pexp_coerce (e, cto1, ct) -> pp f "(%a%a :> %a)" (expression ctxt) e (core_type ctxt) ct | Pexp_variant (l, None) -> pp f "`%s" l | Pexp_record (l, eo) -> let longident_x_expression f ( li, e) = match e with | {pexp_desc=Pexp_ident {txt;_}; pexp_attributes=[]; _} when li.txt = txt -> pp f "@[<hov2>%a@]" longident_loc li | _ -> pp f "@[<hov2>%a@;=@;%a@]" longident_loc li (simple_expr ctxt) e in (option ~last:" with@;" (simple_expr ctxt)) eo (list longident_x_expression ~sep:";@;") l | Pexp_array (l) -> pp f "@[<0>@[<2>[|%a|]@]@]" (list (simple_expr (under_semi ctxt)) ~sep:";") l | Pexp_while (e1, e2) -> let fmt : (_,_,_) format = "@[<2>while@;%a@;do@;%a@;done@]" in pp f fmt (expression ctxt) e1 (expression ctxt) e2 | Pexp_for (s, e1, e2, df, e3) -> let fmt:(_,_,_)format = "@[<hv0>@[<hv2>@[<2>for %a =@;%a@;%a%a@;do@]@;%a@]@;done@]" in let expression = expression ctxt in pp f fmt (pattern ctxt) s expression e1 direction_flag df expression e2 expression e3 | _ -> paren true (expression ctxt) f x and attributes ctxt f l = List.iter (attribute ctxt f) l and item_attributes ctxt f l = List.iter (item_attribute ctxt f) l and attribute ctxt f a = pp f "@[<2>[@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and item_attribute ctxt f a = pp f "@[<2>[@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and floating_attribute ctxt f a = pp f "@[<2>[@@@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload and value_description ctxt f x = pp f "@[<hov2>%a%a@]" (core_type ctxt) x.pval_type (fun f x -> if x.pval_prim <> [] then pp f "@ =@ %a" (list constant_string) x.pval_prim ) x and extension ctxt f (s, e) = pp f "@[<2>[%%%s@ %a]@]" s.txt (payload ctxt) e and item_extension ctxt f (s, e) = pp f "@[<2>[%%%%%s@ %a]@]" s.txt (payload ctxt) e and exception_declaration ctxt f x = pp f "@[<hov2>exception@ %a@]%a" (extension_constructor ctxt) x.ptyexn_constructor (item_attributes ctxt) x.ptyexn_attributes and class_type_field ctxt f x = match x.pctf_desc with | Pctf_inherit (ct) -> pp f "@[<2>inherit@ %a@]%a" (class_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_val (s, mf, vf, ct) -> pp f "@[<2>val @ %a%a%s@ :@ %a@]%a" mutable_flag mf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_method (s, pf, vf, ct) -> pp f "@[<2>method %a %a%s :@;%a@]%a" private_flag pf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_constraint (ct1, ct2) -> pp f "@[<2>constraint@ %a@ =@ %a@]%a" (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pctf_attributes | Pctf_attribute a -> floating_attribute ctxt f a | Pctf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pctf_attributes and class_signature ctxt f { pcsig_self = ct; pcsig_fields = l ;_} = pp f "@[<hv0>@[<hv2>object@[<1>%a@]@ %a@]@ end@]" (fun f -> function {ptyp_desc=Ptyp_any; ptyp_attributes=[]; _} -> () | ct -> pp f " (%a)" (core_type ctxt) ct) ct (list (class_type_field ctxt) ~sep:"@;") l and class_type ctxt f x = match x.pcty_desc with | Pcty_signature cs -> class_signature ctxt f cs; attributes ctxt f x.pcty_attributes | Pcty_constr (li, l) -> pp f "%a%a%a" (fun f l -> match l with | [] -> () | _ -> pp f "[%a]@ " (list (core_type ctxt) ~sep:"," ) l) l longident_loc li (attributes ctxt) x.pcty_attributes | Pcty_arrow (l, co, cl) -> FIXME remove parens later (type_with_label ctxt) (l,co) (class_type ctxt) cl | Pcty_extension e -> extension ctxt f e; attributes ctxt f x.pcty_attributes | Pcty_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) longident_loc o.popen_expr (class_type ctxt) e and class_type_declaration_list ctxt f l = let class_type_declaration kwd f x = let { pci_params=ls; pci_name={ txt; _ }; _ } = x in pp f "@[<2>%s %a%a%s@ =@ %a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in match l with | [] -> () | [x] -> class_type_declaration "class type" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_type_declaration "class type") x (list ~sep:"@," (class_type_declaration "and")) xs and class_field ctxt f x = match x.pcf_desc with | Pcf_inherit (ovf, ce, so) -> pp f "@[<2>inherit@ %s@ %a%a@]%a" (override ovf) (class_expr ctxt) ce (fun f so -> match so with | None -> (); | Some (s) -> pp f "@ as %s" s.txt ) so (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_concrete (ovf, e)) -> pp f "@[<2>val%s %a%s =@;%a@]%a" (override ovf) mutable_flag mf s.txt (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_virtual ct) -> pp f "@[<2>method virtual %a %s :@;%a@]%a" private_flag pf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_virtual ct) -> pp f "@[<2>val virtual %a%s :@ %a@]%a" mutable_flag mf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_concrete (ovf, e)) -> let bind e = binding ctxt f {pvb_pat= {ppat_desc=Ppat_var s; ppat_loc=Location.none; ppat_loc_stack=[]; ppat_attributes=[]}; pvb_expr=e; pvb_attributes=[]; pvb_loc=Location.none; } in pp f "@[<2>method%s %a%a@]%a" (override ovf) private_flag pf (fun f -> function | {pexp_desc=Pexp_poly (e, Some ct); pexp_attributes=[]; _} -> pp f "%s :@;%a=@;%a" s.txt (core_type ctxt) ct (expression ctxt) e | {pexp_desc=Pexp_poly (e, None); pexp_attributes=[]; _} -> bind e | _ -> bind e) e (item_attributes ctxt) x.pcf_attributes | Pcf_constraint (ct1, ct2) -> pp f "@[<2>constraint %a =@;%a@]%a" (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pcf_attributes | Pcf_initializer (e) -> pp f "@[<2>initializer@ %a@]%a" (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_attribute a -> floating_attribute ctxt f a | Pcf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pcf_attributes and class_structure ctxt f { pcstr_self = p; pcstr_fields = l } = pp f "@[<hv0>@[<hv2>object%a@;%a@]@;end@]" (fun f p -> match p.ppat_desc with | Ppat_any -> () | Ppat_constraint _ -> pp f " %a" (pattern ctxt) p | _ -> pp f " (%a)" (pattern ctxt) p) p (list (class_field ctxt)) l and class_expr ctxt f x = if x.pcl_attributes <> [] then begin pp f "((%a)%a)" (class_expr ctxt) {x with pcl_attributes=[]} (attributes ctxt) x.pcl_attributes end else match x.pcl_desc with | Pcl_structure (cs) -> class_structure ctxt f cs | Pcl_fun (l, eo, p, e) -> pp f "fun@ %a@ ->@ %a" (label_exp ctxt) (l,eo,p) (class_expr ctxt) e | Pcl_let (rf, l, ce) -> pp f "%a@ in@ %a" (bindings ctxt) (rf,l) (class_expr ctxt) ce | Pcl_apply (ce, l) -> Cf : # 7200 (class_expr ctxt) ce (list (label_x_expression_param ctxt)) l | Pcl_constr (li, l) -> pp f "%a%a" (fun f l-> if l <>[] then pp f "[%a]@ " (list (core_type ctxt) ~sep:",") l) l longident_loc li | Pcl_constraint (ce, ct) -> pp f "(%a@ :@ %a)" (class_expr ctxt) ce (class_type ctxt) ct | Pcl_extension e -> extension ctxt f e | Pcl_open (o, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override o.popen_override) longident_loc o.popen_expr (class_expr ctxt) e and module_type ctxt f x = if x.pmty_attributes <> [] then begin pp f "((%a)%a)" (module_type ctxt) {x with pmty_attributes=[]} (attributes ctxt) x.pmty_attributes end else match x.pmty_desc with | Pmty_functor (Unit, mt2) -> pp f "@[<hov2>() ->@ %a@]" (module_type ctxt) mt2 | Pmty_functor (Named (s, mt1), mt2) -> begin match s.txt with | None -> pp f "@[<hov2>%a@ ->@ %a@]" (module_type1 ctxt) mt1 (module_type ctxt) mt2 | Some name -> pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" name (module_type ctxt) mt1 (module_type ctxt) mt2 end | Pmty_with (mt, []) -> module_type ctxt f mt | Pmty_with (mt, l) -> pp f "@[<hov2>%a@ with@ %a@]" (module_type1 ctxt) mt (list (with_constraint ctxt) ~sep:"@ and@ ") l | _ -> module_type1 ctxt f x and with_constraint ctxt f = function | Pwith_type (li, ({ptype_params= ls ;_} as td)) -> pp f "type@ %a %a =@ %a" (type_params ctxt) ls longident_loc li (type_declaration ctxt) td | Pwith_module (li, li2) -> pp f "module %a =@ %a" longident_loc li longident_loc li2; | Pwith_modtype (li, mty) -> pp f "module type %a =@ %a" longident_loc li (module_type ctxt) mty; | Pwith_typesubst (li, ({ptype_params=ls;_} as td)) -> pp f "type@ %a %a :=@ %a" (type_params ctxt) ls longident_loc li (type_declaration ctxt) td | Pwith_modsubst (li, li2) -> pp f "module %a :=@ %a" longident_loc li longident_loc li2 | Pwith_modtypesubst (li, mty) -> pp f "module type %a :=@ %a" longident_loc li (module_type ctxt) mty; and module_type1 ctxt f x = if x.pmty_attributes <> [] then module_type ctxt f x else match x.pmty_desc with | Pmty_ident li -> pp f "%a" longident_loc li; | Pmty_alias li -> pp f "(module %a)" longident_loc li; | Pmty_signature (s) -> | Pmty_typeof me -> pp f "@[<hov2>module@ type@ of@ %a@]" (module_expr ctxt) me | Pmty_extension e -> extension ctxt f e | _ -> paren true (module_type ctxt) f x and signature ctxt f x = list ~sep:"@\n" (signature_item ctxt) f x and signature_item ctxt f x : unit = match x.psig_desc with | Psig_type (rf, l) -> type_def_list ctxt f (rf, true, l) | Psig_typesubst l -> type_def_list ctxt f (Recursive, false, l) | Psig_value vd -> let intro = if vd.pval_prim = [] then "val" else "external" in pp f "@[<2>%s@ %a@ :@ %a@]%a" intro protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Psig_typext te -> type_extension ctxt f te | Psig_exception ed -> exception_declaration ctxt f ed | Psig_class l -> let class_description kwd f ({pci_params=ls;pci_name={txt;_};_} as x) = pp f "@[<2>%s %a%a%s@;:@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_description "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_description "class") x (list ~sep:"@," (class_description "and")) xs end | Psig_module ({pmd_type={pmty_desc=Pmty_alias alias; pmty_attributes=[]; _};_} as pmd) -> pp f "@[<hov>module@ %s@ =@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") longident_loc alias (item_attributes ctxt) pmd.pmd_attributes | Psig_module pmd -> pp f "@[<hov>module@ %s@ :@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes | Psig_modsubst pms -> pp f "@[<hov>module@ %s@ :=@ %a@]%a" pms.pms_name.txt longident_loc pms.pms_manifest (item_attributes ctxt) pms.pms_attributes | Psig_open od -> pp f "@[<hov2>open%s@ %a@]%a" (override od.popen_override) longident_loc od.popen_expr (item_attributes ctxt) od.popen_attributes | Psig_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_type ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes | Psig_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>module@ type@ %s%a@]%a" s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Psig_modtypesubst {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> let md = match md with | Some mt -> mt in pp f "@[<hov2>module@ type@ %s@ :=@ %a@]%a" s.txt (module_type ctxt) md (item_attributes ctxt) attrs | Psig_class_type (l) -> class_type_declaration_list ctxt f l | Psig_recmodule decls -> let rec string_x_module_type_list f ?(first=true) l = match l with | [] -> () ; | pmd :: tl -> if not first then pp f "@ @[<hov2>and@ %s:@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes else pp f "@[<hov2>module@ rec@ %s:@ %a@]%a" (Option.value pmd.pmd_name.txt ~default:"_") (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes; string_x_module_type_list f ~first:false tl in string_x_module_type_list f decls | Psig_attribute a -> floating_attribute ctxt f a | Psig_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and module_expr ctxt f x = if x.pmod_attributes <> [] then pp f "((%a)%a)" (module_expr ctxt) {x with pmod_attributes=[]} (attributes ctxt) x.pmod_attributes else match x.pmod_desc with | Pmod_structure (s) -> pp f "@[<hv2>struct@;@[<0>%a@]@;<1 -2>end@]" (list (structure_item ctxt) ~sep:"@\n") s; | Pmod_constraint (me, mt) -> pp f "@[<hov2>(%a@ :@ %a)@]" (module_expr ctxt) me (module_type ctxt) mt | Pmod_ident (li) -> pp f "%a" longident_loc li; | Pmod_functor (Unit, me) -> pp f "functor ()@;->@;%a" (module_expr ctxt) me | Pmod_functor (Named (s, mt), me) -> pp f "functor@ (%s@ :@ %a)@;->@;%a" (Option.value s.txt ~default:"_") (module_type ctxt) mt (module_expr ctxt) me | Pmod_apply (me1, me2) -> pp f "(%a)(%a)" (module_expr ctxt) me1 (module_expr ctxt) me2 Cf : # 7200 | Pmod_unpack e -> pp f "(val@ %a)" (expression ctxt) e | Pmod_extension e -> extension ctxt f e and structure ctxt f x = list ~sep:"@\n" (structure_item ctxt) f x and payload ctxt f = function | PStr [{pstr_desc = Pstr_eval (e, attrs)}] -> pp f "@[<2>%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | PStr x -> structure ctxt f x | PTyp x -> pp f ":@ "; core_type ctxt f x | PSig x -> pp f ":@ "; signature ctxt f x | PPat (x, None) -> pp f "?@ "; pattern ctxt f x | PPat (x, Some e) -> pp f "?@ "; pattern ctxt f x; pp f " when "; expression ctxt f e and binding ctxt f {pvb_pat=p; pvb_expr=x; _} = let rec pp_print_pexp_function f x = if x.pexp_attributes <> [] then pp f "=@;%a" (expression ctxt) x else match x.pexp_desc with | Pexp_fun (label, eo, p, e) -> if label=Nolabel then pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function e else pp f "%a@ %a" (label_exp ctxt) (label,eo,p) pp_print_pexp_function e | Pexp_newtype (str,e) -> pp f "(type@ %s)@ %a" str.txt pp_print_pexp_function e | _ -> pp f "=@;%a" (expression ctxt) x in let tyvars_str tyvars = List.map (fun v -> v.txt) tyvars in let is_desugared_gadt p e = let gadt_pattern = match p with | {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _} as pat, {ptyp_desc=Ptyp_poly (args_tyvars, rt)}); ppat_attributes=[]}-> Some (pat, args_tyvars, rt) | _ -> None in let rec gadt_exp tyvars e = match e with | {pexp_desc=Pexp_newtype (tyvar, e); pexp_attributes=[]} -> gadt_exp (tyvar :: tyvars) e | {pexp_desc=Pexp_constraint (e, ct); pexp_attributes=[]} -> Some (List.rev tyvars, e, ct) | _ -> None in let gadt_exp = gadt_exp [] e in match gadt_pattern, gadt_exp with | Some (p, pt_tyvars, pt_ct), Some (e_tyvars, e, e_ct) when tyvars_str pt_tyvars = tyvars_str e_tyvars -> let ety = Typ.varify_constructors e_tyvars e_ct in if ety = pt_ct then Some (p, pt_tyvars, e_ct, e) else None | _ -> None in if x.pexp_attributes <> [] then match p with | {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _; _} as pat, ({ptyp_desc=Ptyp_poly _; _} as typ)); ppat_attributes=[]; _} -> pp f "%a@;: %a@;=@;%a" (simple_pattern ctxt) pat (core_type ctxt) typ (expression ctxt) x | _ -> pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x else match is_desugared_gadt p x with | Some (p, [], ct, e) -> pp f "%a@;: %a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ct (expression ctxt) e | Some (p, tyvars, ct, e) -> begin pp f "%a@;: type@;%a.@;%a@;=@;%a" (simple_pattern ctxt) p (list pp_print_string ~sep:"@;") (tyvars_str tyvars) (core_type ctxt) ct (expression ctxt) e end | None -> begin match p with | {ppat_desc=Ppat_constraint(p ,ty); special case for the first begin match ty with | {ptyp_desc=Ptyp_poly _; ptyp_attributes=[]} -> pp f "%a@;:@;%a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x | _ -> pp f "(%a@;:@;%a)@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x end | {ppat_desc=Ppat_var _; ppat_attributes=[]} -> pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function x | _ -> pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x end and bindings ctxt f (rf,l) = let binding kwd rf f x = pp f "@[<2>%s %a%a@]%a" kwd rec_flag rf (binding ctxt) x (item_attributes ctxt) x.pvb_attributes in match l with | [] -> () | [x] -> binding "let" rf f x | x::xs -> pp f "@[<v>%a@,%a@]" (binding "let" rf) x (list ~sep:"@," (binding "and" Nonrecursive)) xs and binding_op ctxt f x = match x.pbop_pat, x.pbop_exp with | {ppat_desc = Ppat_var { txt=pvar; _ }; ppat_attributes = []; _}, {pexp_desc = Pexp_ident { txt=Lident evar; _}; pexp_attributes = []; _} when pvar = evar -> pp f "@[<2>%s %s@]" x.pbop_op.txt evar | pat, exp -> pp f "@[<2>%s %a@;=@;%a@]" x.pbop_op.txt (pattern ctxt) pat (expression ctxt) exp and structure_item ctxt f x = match x.pstr_desc with | Pstr_eval (e, attrs) -> pp f "@[<hov2>;;%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | Pstr_type (_, []) -> assert false | Pstr_type (rf, l) -> type_def_list ctxt f (rf, true, l) | Pstr_value (rf, l) -> pp f " @[<hov2 > let % a%a@ ] " rec_flag rf bindings l pp f "@[<2>%a@]" (bindings ctxt) (rf,l) | Pstr_typext te -> type_extension ctxt f te | Pstr_exception ed -> exception_declaration ctxt f ed | Pstr_module x -> let rec module_helper = function | {pmod_desc=Pmod_functor(arg_opt,me'); pmod_attributes = []} -> begin match arg_opt with | Unit -> pp f "()" | Named (s, mt) -> pp f "(%s:%a)" (Option.value s.txt ~default:"_") (module_type ctxt) mt end; module_helper me' | me -> me in pp f "@[<hov2>module %s%a@]%a" (Option.value x.pmb_name.txt ~default:"_") (fun f me -> let me = module_helper me in match me with | {pmod_desc= Pmod_constraint (me', ({pmty_desc=(Pmty_ident (_) | Pmty_signature (_));_} as mt)); pmod_attributes = []} -> pp f " :@;%a@;=@;%a@;" (module_type ctxt) mt (module_expr ctxt) me' | _ -> pp f " =@ %a" (module_expr ctxt) me ) x.pmb_expr (item_attributes ctxt) x.pmb_attributes | Pstr_open od -> pp f "@[<2>open%s@;%a@]%a" (override od.popen_override) (module_expr ctxt) od.popen_expr (item_attributes ctxt) od.popen_attributes | Pstr_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>module@ type@ %s%a@]%a" s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Pstr_class l -> let extract_class_args cl = let rec loop acc = function | {pcl_desc=Pcl_fun (l, eo, p, cl'); pcl_attributes = []} -> loop ((l,eo,p) :: acc) cl' | cl -> List.rev acc, cl in let args, cl = loop [] cl in let constr, cl = match cl with | {pcl_desc=Pcl_constraint (cl', ct); pcl_attributes = []} -> Some ct, cl' | _ -> None, cl in args, constr, cl in let class_constraint f ct = pp f ": @[%a@] " (class_type ctxt) ct in let class_declaration kwd f ({pci_params=ls; pci_name={txt;_}; _} as x) = let args, constr, cl = extract_class_args x.pci_expr in pp f "@[<2>%s %a%a%s %a%a=@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (list (label_exp ctxt)) args (option class_constraint) constr (class_expr ctxt) cl (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_declaration "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_declaration "class") x (list ~sep:"@," (class_declaration "and")) xs end | Pstr_class_type l -> class_type_declaration_list ctxt f l | Pstr_primitive vd -> pp f "@[<hov2>external@ %a@ :@ %a@]%a" protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Pstr_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_expr ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes 3.07 let aux f = function | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) -> pp f "@[<hov2>@ and@ %s:%a@ =@ %a@]%a" (Option.value pmb.pmb_name.txt ~default:"_") (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes | pmb -> pp f "@[<hov2>@ and@ %s@ =@ %a@]%a" (Option.value pmb.pmb_name.txt ~default:"_") (module_expr ctxt) pmb.pmb_expr (item_attributes ctxt) pmb.pmb_attributes in begin match decls with | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) :: l2 -> pp f "@[<hv>@[<hov2>module@ rec@ %s:%a@ =@ %a@]%a@ %a@]" (Option.value pmb.pmb_name.txt ~default:"_") (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | pmb :: l2 -> pp f "@[<hv>@[<hov2>module@ rec@ %s@ =@ %a@]%a@ %a@]" (Option.value pmb.pmb_name.txt ~default:"_") (module_expr ctxt) pmb.pmb_expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | _ -> assert false end | Pstr_attribute a -> floating_attribute ctxt f a | Pstr_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and type_param ctxt f (ct, (a,b)) = pp f "%s%s%a" (type_variance a) (type_injectivity b) (core_type ctxt) ct and type_params ctxt f = function | [] -> () | l -> pp f "%a " (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",@;") l and type_def_list ctxt f (rf, exported, l) = let type_decl kwd rf f x = let eq = if (x.ptype_kind = Ptype_abstract) && (x.ptype_manifest = None) then "" else if exported then " =" else " :=" in pp f "@[<2>%s %a%a%s%s%a@]%a" kwd nonrec_flag rf (type_params ctxt) x.ptype_params x.ptype_name.txt eq (type_declaration ctxt) x (item_attributes ctxt) x.ptype_attributes in match l with | [] -> assert false | [x] -> type_decl "type" rf f x | x :: xs -> pp f "@[<v>%a@,%a@]" (type_decl "type" rf) x (list ~sep:"@," (type_decl "and" Recursive)) xs and record_declaration ctxt f lbls = let type_record_field f pld = pp f "@[<2>%a%s:@;%a@;%a@]" mutable_flag pld.pld_mutable pld.pld_name.txt (core_type ctxt) pld.pld_type (attributes ctxt) pld.pld_attributes in pp f "{@\n%a}" (list type_record_field ~sep:";@\n" ) lbls and type_declaration ctxt f x = let priv f = match x.ptype_private with | Public -> () | Private -> pp f "@;private" in let manifest f = match x.ptype_manifest with | None -> () | Some y -> if x.ptype_kind = Ptype_abstract then pp f "%t@;%a" priv (core_type ctxt) y else pp f "@;%a" (core_type ctxt) y in let constructor_declaration f pcd = pp f "|@;"; constructor_declaration ctxt f (pcd.pcd_name.txt, pcd.pcd_vars, pcd.pcd_args, pcd.pcd_res, pcd.pcd_attributes) in let repr f = let intro f = if x.ptype_manifest = None then () else pp f "@;=" in match x.ptype_kind with | Ptype_variant xs -> let variants fmt xs = if xs = [] then pp fmt " |" else pp fmt "@\n%a" (list ~sep:"@\n" constructor_declaration) xs in pp f "%t%t%a" intro priv variants xs | Ptype_abstract -> () | Ptype_record l -> pp f "%t%t@;%a" intro priv (record_declaration ctxt) l | Ptype_open -> pp f "%t%t@;.." intro priv in let constraints f = List.iter (fun (ct1,ct2,_) -> pp f "@[<hov2>@ constraint@ %a@ =@ %a@]" (core_type ctxt) ct1 (core_type ctxt) ct2) x.ptype_cstrs in pp f "%t%t%t" manifest repr constraints and type_extension ctxt f x = let extension_constructor f x = pp f "@\n|@;%a" (extension_constructor ctxt) x in pp f "@[<2>type %a%a += %a@ %a@]%a" (fun f -> function | [] -> () | l -> pp f "%a@;" (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l) x.ptyext_params longident_loc x.ptyext_path Cf : # 7200 (list ~sep:"" extension_constructor) x.ptyext_constructors (item_attributes ctxt) x.ptyext_attributes and constructor_declaration ctxt f (name, vars, args, res, attrs) = let name = match name with | "::" -> "(::)" | s -> s in let pp_vars f vs = match vs with | [] -> () | vs -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") vs in match res with | None -> pp f "%s%a@;%a" name (fun f -> function | Pcstr_tuple [] -> () | Pcstr_tuple l -> pp f "@;of@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l | Pcstr_record l -> pp f "@;of@;%a" (record_declaration ctxt) l ) args (attributes ctxt) attrs | Some r -> pp f "%s:@;%a%a@;%a" name pp_vars vars (fun f -> function | Pcstr_tuple [] -> core_type1 ctxt f r | Pcstr_tuple l -> pp f "%a@;->@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l (core_type1 ctxt) r | Pcstr_record l -> pp f "%a@;->@;%a" (record_declaration ctxt) l (core_type1 ctxt) r ) args (attributes ctxt) attrs and extension_constructor ctxt f x = Cf : # 7200 match x.pext_kind with | Pext_decl(v, l, r) -> constructor_declaration ctxt f (x.pext_name.txt, v, l, r, x.pext_attributes) | Pext_rebind li -> pp f "%s@;=@;%a%a" x.pext_name.txt longident_loc li (attributes ctxt) x.pext_attributes and case_list ctxt f l : unit = let aux f {pc_lhs; pc_guard; pc_rhs} = pp f "@;| @[<2>%a%a@;->@;%a@]" (pattern ctxt) pc_lhs (option (expression ctxt) ~first:"@;when@;") pc_guard (expression (under_pipe ctxt)) pc_rhs in list aux f l ~sep:"" and label_x_expression_param ctxt f (l,e) = let simple_name = match e with | {pexp_desc=Pexp_ident {txt=Lident l;_}; pexp_attributes=[]} -> Some l | _ -> None in match l with level 2 | Optional str -> if Some str = simple_name then pp f "?%s" str else pp f "?%s:%a" str (simple_expr ctxt) e | Labelled lbl -> if Some lbl = simple_name then pp f "~%s" lbl else pp f "~%s:%a" lbl (simple_expr ctxt) e and directive_argument f x = match x.pdira_desc with | Pdir_string (s) -> pp f "@ %S" s | Pdir_int (n, None) -> pp f "@ %s" n | Pdir_int (n, Some m) -> pp f "@ %s%c" n m | Pdir_ident (li) -> pp f "@ %a" longident li | Pdir_bool (b) -> pp f "@ %s" (string_of_bool b) let toplevel_phrase f x = match x with | Ptop_def (s) ->pp f "@[<hov0>%a@]" (list (structure_item reset_ctxt)) s pp_close_box f ( ) ; | Ptop_dir {pdir_name; pdir_arg = None; _} -> pp f "@[<hov2>#%s@]" pdir_name.txt | Ptop_dir {pdir_name; pdir_arg = Some pdir_arg; _} -> pp f "@[<hov2>#%s@ %a@]" pdir_name.txt directive_argument pdir_arg let expression f x = pp f "@[%a@]" (expression reset_ctxt) x let string_of_expression x = ignore (flush_str_formatter ()) ; let f = str_formatter in expression f x; flush_str_formatter () let string_of_structure x = ignore (flush_str_formatter ()); let f = str_formatter in structure reset_ctxt f x; flush_str_formatter () let top_phrase f x = pp_print_newline f (); toplevel_phrase f x; pp f ";;"; pp_print_newline f () let core_type = core_type reset_ctxt let pattern = pattern reset_ctxt let signature = signature reset_ctxt let structure = structure reset_ctxt let module_expr = module_expr reset_ctxt let module_type = module_type reset_ctxt let class_field = class_field reset_ctxt let class_type_field = class_type_field reset_ctxt let class_expr = class_expr reset_ctxt let class_type = class_type reset_ctxt let structure_item = structure_item reset_ctxt let signature_item = signature_item reset_ctxt let binding = binding reset_ctxt let payload = payload reset_ctxt
fd08f03d5a6d8a09eb4a80df0a72f8fb6332a424583ac48bd52d5c359e9b955a
Leonidas-from-XIV/orewa
resp.ml
open Core open Async type redis_error = string [@@deriving show, eq] let crlf = "\r\n" type t = | String of string | Error of redis_error | Integer of int | Bulk of string | Array of t list | Null [@@deriving show, eq] let terminator = function | true -> crlf | false -> "" let rec encode = function | String s -> Printf.sprintf "+%s%s" s crlf | Error e -> Printf.sprintf "-%s%s" e crlf | Integer n -> Printf.sprintf ":%d%s" n crlf | Bulk s -> let len = String.length s in Printf.sprintf "$%d%s%s%s" len crlf s crlf | Array xs -> let payload = xs |> List.map ~f:encode |> String.concat in let len = List.length xs in Printf.sprintf "*%d%s%s%s" len crlf payload crlf | Null -> Printf.sprintf "$-1%s" crlf
null
https://raw.githubusercontent.com/Leonidas-from-XIV/orewa/d0ed6de3581ae11d02b91cdc238216c633859960/src/resp.ml
ocaml
open Core open Async type redis_error = string [@@deriving show, eq] let crlf = "\r\n" type t = | String of string | Error of redis_error | Integer of int | Bulk of string | Array of t list | Null [@@deriving show, eq] let terminator = function | true -> crlf | false -> "" let rec encode = function | String s -> Printf.sprintf "+%s%s" s crlf | Error e -> Printf.sprintf "-%s%s" e crlf | Integer n -> Printf.sprintf ":%d%s" n crlf | Bulk s -> let len = String.length s in Printf.sprintf "$%d%s%s%s" len crlf s crlf | Array xs -> let payload = xs |> List.map ~f:encode |> String.concat in let len = List.length xs in Printf.sprintf "*%d%s%s%s" len crlf payload crlf | Null -> Printf.sprintf "$-1%s" crlf
c2196dfac7a66d99bd1ed3dd1a4d8880d047ca6bd03629c54ba78890d2461737
lasp-lang/partisan
partisan_acceptor_pool.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2016 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(partisan_acceptor_pool). -author("Christopher Meiklejohn <>"). -behaviour(acceptor_pool). -export([start_link/0, accept_socket/2]). -export([init/1]). %% public api start_link() -> acceptor_pool:start_link({local, ?MODULE}, ?MODULE, []). accept_socket(Socket, Acceptors) -> acceptor_pool:accept_socket(?MODULE, Socket, Acceptors). %% acceptor_pool api init([]) -> Conn = #{id => partisan_peer_service_server, start => {partisan_peer_service_server, [], []}, Give connections 5000ms to close before shutdown {ok, {#{}, [Conn]}}.
null
https://raw.githubusercontent.com/lasp-lang/partisan/fd048fc1b34309d9fa41450434a7e7b3b2fa1fb8/src/partisan_acceptor_pool.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. ------------------------------------------------------------------- public api acceptor_pool api
Copyright ( c ) 2016 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(partisan_acceptor_pool). -author("Christopher Meiklejohn <>"). -behaviour(acceptor_pool). -export([start_link/0, accept_socket/2]). -export([init/1]). start_link() -> acceptor_pool:start_link({local, ?MODULE}, ?MODULE, []). accept_socket(Socket, Acceptors) -> acceptor_pool:accept_socket(?MODULE, Socket, Acceptors). init([]) -> Conn = #{id => partisan_peer_service_server, start => {partisan_peer_service_server, [], []}, Give connections 5000ms to close before shutdown {ok, {#{}, [Conn]}}.
15af790d3b51c25524013c1523976048f1d52aa0050c4dc9cb229af5a1b1e89e
flyspeck/flyspeck
pair.ml
(* ========================================================================= *) (* Syntax sugaring; theory of pairing, with a bit of support. *) (* *) , University of Cambridge Computer Laboratory (* *) ( c ) Copyright , University of Cambridge 1998 ( c ) Copyright , 1998 - 2007 (* ========================================================================= *) open Parser include Impconv (* ------------------------------------------------------------------------- *) (* Constants implementing (or at least tagging) syntactic sugar. *) (* ------------------------------------------------------------------------- *) let LET_DEF = new_definition `LET (f:A->B) x = f x`;; let LET_END_DEF = new_definition `LET_END (t:A) = t`;; let GABS_DEF = new_definition `GABS (P:A->bool) = (@) P`;; let GEQ_DEF = new_definition `GEQ a b = (a:A = b)`;; let _SEQPATTERN = new_definition `_SEQPATTERN = \r s x. if ?y. r x y then r x else s x`;; let _UNGUARDED_PATTERN = new_definition `_UNGUARDED_PATTERN = \p r. p /\ r`;; let _GUARDED_PATTERN = new_definition `_GUARDED_PATTERN = \p g r. p /\ g /\ r`;; let _MATCH = new_definition `_MATCH = \e r. if (?!) (r e) then (@) (r e) else @z. F`;; let _FUNCTION = new_definition `_FUNCTION = \r x. if (?!) (r x) then (@) (r x) else @z. F`;; (* ------------------------------------------------------------------------- *) (* Pair type. *) (* ------------------------------------------------------------------------- *) let mk_pair_def = new_definition `mk_pair (x:A) (y:B) = \a b. (a = x) /\ (b = y)`;; let PAIR_EXISTS_THM = prove (`?x. ?(a:A) (b:B). x = mk_pair a b`, MESON_TAC[]);; let prod_tybij = new_type_definition "prod" ("ABS_prod","REP_prod") PAIR_EXISTS_THM;; let REP_ABS_PAIR = prove (`!(x:A) (y:B). REP_prod (ABS_prod (mk_pair x y)) = mk_pair x y`, MESON_TAC[prod_tybij]);; parse_as_infix (",",(14,"right"));; let COMMA_DEF = new_definition `(x:A),(y:B) = ABS_prod(mk_pair x y)`;; let FST_DEF = new_definition `FST (p:A#B) = @x. ?y. p = x,y`;; let SND_DEF = new_definition `SND (p:A#B) = @y. ?x. p = x,y`;; let PAIR_EQ = prove (`!(x:A) (y:B) a b. (x,y = a,b) <=> (x = a) /\ (y = b)`, REPEAT GEN_TAC THEN EQ_TAC THENL [REWRITE_TAC[COMMA_DEF] THEN DISCH_THEN(MP_TAC o AP_TERM `REP_prod:A#B->A->B->bool`) THEN REWRITE_TAC[REP_ABS_PAIR] THEN REWRITE_TAC[mk_pair_def; FUN_EQ_THM]; ALL_TAC] THEN MESON_TAC[]);; let PAIR_SURJECTIVE = prove (`!p:A#B. ?x y. p = x,y`, GEN_TAC THEN REWRITE_TAC[COMMA_DEF] THEN MP_TAC(SPEC `REP_prod p :A->B->bool` (CONJUNCT2 prod_tybij)) THEN REWRITE_TAC[CONJUNCT1 prod_tybij] THEN DISCH_THEN(X_CHOOSE_THEN `a:A` (X_CHOOSE_THEN `b:B` MP_TAC)) THEN DISCH_THEN(MP_TAC o AP_TERM `ABS_prod:(A->B->bool)->A#B`) THEN REWRITE_TAC[CONJUNCT1 prod_tybij] THEN DISCH_THEN SUBST1_TAC THEN MAP_EVERY EXISTS_TAC [`a:A`; `b:B`] THEN REFL_TAC);; let FST = prove (`!(x:A) (y:B). FST(x,y) = x`, REPEAT GEN_TAC THEN REWRITE_TAC[FST_DEF] THEN MATCH_MP_TAC SELECT_UNIQUE THEN GEN_TAC THEN BETA_TAC THEN REWRITE_TAC[PAIR_EQ] THEN EQ_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[] THEN EXISTS_TAC `y:B` THEN ASM_REWRITE_TAC[]);; let SND = prove (`!(x:A) (y:B). SND(x,y) = y`, REPEAT GEN_TAC THEN REWRITE_TAC[SND_DEF] THEN MATCH_MP_TAC SELECT_UNIQUE THEN GEN_TAC THEN BETA_TAC THEN REWRITE_TAC[PAIR_EQ] THEN EQ_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[] THEN EXISTS_TAC `x:A` THEN ASM_REWRITE_TAC[]);; let PAIR = prove (`!x:A#B. FST x,SND x = x`, GEN_TAC THEN (X_CHOOSE_THEN `a:A` (X_CHOOSE_THEN `b:B` SUBST1_TAC) (SPEC `x:A#B` PAIR_SURJECTIVE)) THEN REWRITE_TAC[FST; SND]);; let pair_INDUCT = prove (`!P. (!x y. P (x,y)) ==> !p. P p`, REPEAT STRIP_TAC THEN GEN_REWRITE_TAC RAND_CONV [GSYM PAIR] THEN FIRST_ASSUM MATCH_ACCEPT_TAC);; let pair_RECURSION = prove (`!PAIR'. ?fn:A#B->C. !a0 a1. fn (a0,a1) = PAIR' a0 a1`, GEN_TAC THEN EXISTS_TAC `\p. (PAIR':A->B->C) (FST p) (SND p)` THEN REWRITE_TAC[FST; SND]);; (* ------------------------------------------------------------------------- *) (* Syntax operations. *) (* ------------------------------------------------------------------------- *) let is_pair = is_binary ",";; let dest_pair = dest_binary ",";; let mk_pair = let ptm = mk_const(",",[]) in fun (l,r) -> mk_comb(mk_comb(inst [type_of l,aty; type_of r,bty] ptm,l),r);; (* ------------------------------------------------------------------------- *) (* Extend basic rewrites; extend new_definition to allow paired varstructs. *) (* ------------------------------------------------------------------------- *) extend_basic_rewrites [FST; SND; PAIR];; (* ------------------------------------------------------------------------- *) (* Extend definitions to paired varstructs with benignity checking. *) (* ------------------------------------------------------------------------- *) let the_definitions = ref [SND_DEF; FST_DEF; COMMA_DEF; mk_pair_def; GEQ_DEF; GABS_DEF; LET_END_DEF; LET_DEF; one_DEF; I_DEF; o_DEF; COND_DEF; _FALSITY_; EXISTS_UNIQUE_DEF; NOT_DEF; F_DEF; OR_DEF; EXISTS_DEF; FORALL_DEF; IMP_DEF; AND_DEF; T_DEF];; let new_definition = let depair = let rec depair gv arg = try let l,r = dest_pair arg in (depair (list_mk_icomb "FST" [gv]) l) @ (depair (list_mk_icomb "SND" [gv]) r) with Failure _ -> [gv,arg] in fun arg -> let gv = genvar(type_of arg) in gv,depair gv arg in fun tm -> let avs,def = strip_forall tm in try let th,th' = tryfind (fun th -> th,PART_MATCH I th def) (!the_definitions) in ignore(PART_MATCH I th' (snd(strip_forall(concl th)))); warn true "Benign redefinition"; GEN_ALL (GENL avs th') with Failure _ -> let l,r = dest_eq def in let fn,args = strip_comb l in let gargs,reps = (I F_F unions) (unzip(map depair args)) in let l' = list_mk_comb(fn,gargs) and r' = subst reps r in let th1 = new_definition (mk_eq(l',r')) in let slist = zip args gargs in let th2 = INST slist (SPEC_ALL th1) in let xreps = map (subst slist o fst) reps in let threps = map (SYM o PURE_REWRITE_CONV[FST; SND]) xreps in let th3 = TRANS th2 (SYM(SUBS_CONV threps r)) in let th4 = GEN_ALL (GENL avs th3) in the_definitions := th4::(!the_definitions); th4;; (* ------------------------------------------------------------------------- *) (* A few more useful definitions. *) (* ------------------------------------------------------------------------- *) let CURRY_DEF = new_definition `CURRY(f:A#B->C) x y = f(x,y)`;; let UNCURRY_DEF = new_definition `!f x y. UNCURRY(f:A->B->C)(x,y) = f x y`;; let PASSOC_DEF = new_definition `!f x y z. PASSOC (f:(A#B)#C->D) (x,y,z) = f ((x,y),z)`;; (* ------------------------------------------------------------------------- *) Analog of ABS_CONV for generalized abstraction . (* ------------------------------------------------------------------------- *) let GABS_CONV conv tm = if is_abs tm then ABS_CONV conv tm else let gabs,bod = dest_comb tm in let f,qtm = dest_abs bod in let xs,bod = strip_forall qtm in AP_TERM gabs (ABS f (itlist MK_FORALL xs (RAND_CONV conv bod)));; (* ------------------------------------------------------------------------- *) (* General beta-conversion over linear pattern of nested constructors. *) (* ------------------------------------------------------------------------- *) let GEN_BETA_CONV = let projection_cache = ref [] in let create_projections conname = try assoc conname (!projection_cache) with Failure _ -> let genty = get_const_type conname in let conty = fst(dest_type(repeat (snd o dest_fun_ty) genty)) in let _,_,rth = assoc conty (!inductive_type_store) in let sth = SPEC_ALL rth in let evs,bod = strip_exists(concl sth) in let cjs = conjuncts bod in let ourcj = find ((=)conname o fst o dest_const o fst o strip_comb o rand o lhand o snd o strip_forall) cjs in let n = index ourcj cjs in let avs,eqn = strip_forall ourcj in let con',args = strip_comb(rand eqn) in let aargs,zargs = chop_list (length avs) args in let gargs = map (genvar o type_of) zargs in let gcon = genvar(itlist (mk_fun_ty o type_of) avs (type_of(rand eqn))) in let bth = INST [list_mk_abs(aargs @ gargs,list_mk_comb(gcon,avs)),con'] sth in let cth = el n (CONJUNCTS(ASSUME(snd(strip_exists(concl bth))))) in let dth = CONV_RULE (funpow (length avs) BINDER_CONV (RAND_CONV(BETAS_CONV))) cth in let eth = SIMPLE_EXISTS (rator(lhand(snd(strip_forall(concl dth))))) dth in let fth = PROVE_HYP bth (itlist SIMPLE_CHOOSE evs eth) in let zty = type_of (rand(snd(strip_forall(concl dth)))) in let mk_projector a = let ity = type_of a in let th = BETA_RULE(PINST [ity,zty] [list_mk_abs(avs,a),gcon] fth) in SYM(SPEC_ALL(SELECT_RULE th)) in let ths = map mk_projector avs in (projection_cache := (conname,ths)::(!projection_cache); ths) in let GEQ_CONV = REWR_CONV(GSYM GEQ_DEF) and DEGEQ_RULE = CONV_RULE(REWR_CONV GEQ_DEF) in let GABS_RULE = let pth = prove (`(?) P ==> P (GABS P)`, SIMP_TAC[GABS_DEF; SELECT_AX; ETA_AX]) in MATCH_MP pth in let rec create_iterated_projections tm = if frees tm = [] then [] else if is_var tm then [REFL tm] else let con,args = strip_comb tm in let prjths = create_projections (fst(dest_const con)) in let atm = rand(rand(concl(hd prjths))) in let instn = term_match [] atm tm in let arths = map (INSTANTIATE instn) prjths in let ths = map (fun arth -> let sths = create_iterated_projections (lhand(concl arth)) in map (CONV_RULE(RAND_CONV(SUBS_CONV[arth]))) sths) arths in unions' equals_thm ths in let GEN_BETA_CONV tm = try BETA_CONV tm with Failure _ -> let l,r = dest_comb tm in let vstr,bod = dest_gabs l in let instn = term_match [] vstr r in let prjs = create_iterated_projections vstr in let th1 = SUBS_CONV prjs bod in let bod' = rand(concl th1) in let gv = genvar(type_of vstr) in let pat = mk_abs(gv,subst[gv,vstr] bod') in let th2 = TRANS (BETA_CONV (mk_comb(pat,vstr))) (SYM th1) in let avs = fst(strip_forall(body(rand l))) in let th3 = GENL (fst(strip_forall(body(rand l)))) th2 in let efn = genvar(type_of pat) in let th4 = EXISTS(mk_exists(efn,subst[efn,pat] (concl th3)),pat) th3 in let th5 = CONV_RULE(funpow (length avs + 1) BINDER_CONV GEQ_CONV) th4 in let th6 = CONV_RULE BETA_CONV (GABS_RULE th5) in INSTANTIATE instn (DEGEQ_RULE (SPEC_ALL th6)) in GEN_BETA_CONV;; (* ------------------------------------------------------------------------- *) (* Add this to the basic "rewrites" and pairs to the inductive type store. *) (* ------------------------------------------------------------------------- *) extend_basic_convs("GEN_BETA_CONV",(`GABS (\a. b) c`,GEN_BETA_CONV));; inductive_type_store := ("prod",(1,pair_INDUCT,pair_RECURSION))::(!inductive_type_store);; (* ------------------------------------------------------------------------- *) (* Convenient rules to eliminate binders over pairs. *) (* ------------------------------------------------------------------------- *) let FORALL_PAIR_THM = prove (`!P. (!p. P p) <=> (!p1 p2. P(p1,p2))`, MESON_TAC[PAIR]);; let EXISTS_PAIR_THM = prove (`!P. (?p. P p) <=> ?p1 p2. P(p1,p2)`, MESON_TAC[PAIR]);; let LAMBDA_PAIR_THM = prove (`!t. (\p. t p) = (\(x,y). t(x,y))`, REWRITE_TAC[FORALL_PAIR_THM; FUN_EQ_THM]);; let PAIRED_ETA_THM = prove (`(!f. (\(x,y). f (x,y)) = f) /\ (!f. (\(x,y,z). f (x,y,z)) = f) /\ (!f. (\(w,x,y,z). f (w,x,y,z)) = f)`, REPEAT STRIP_TAC THEN REWRITE_TAC[FUN_EQ_THM; FORALL_PAIR_THM]);; let FORALL_UNCURRY = prove (`!P. (!f:A->B->C. P f) <=> (!f. P (\a b. f(a,b)))`, GEN_TAC THEN EQ_TAC THEN SIMP_TAC[] THEN DISCH_TAC THEN X_GEN_TAC `f:A->B->C` THEN FIRST_ASSUM(MP_TAC o SPEC `\(a,b). (f:A->B->C) a b`) THEN SIMP_TAC[ETA_AX]);; let EXISTS_UNCURRY = prove (`!P. (?f:A->B->C. P f) <=> (?f. P (\a b. f(a,b)))`, ONCE_REWRITE_TAC[MESON[] `(?x. P x) <=> ~(!x. ~P x)`] THEN REWRITE_TAC[FORALL_UNCURRY]);; let EXISTS_CURRY = prove (`!P. (?f. P f) <=> (?f. P (\(a,b). f a b))`, REWRITE_TAC[EXISTS_UNCURRY; PAIRED_ETA_THM]);; let FORALL_CURRY = prove (`!P. (!f. P f) <=> (!f. P (\(a,b). f a b))`, REWRITE_TAC[FORALL_UNCURRY; PAIRED_ETA_THM]);; let FORALL_UNPAIR_THM = prove (`!P. (!x y. P x y) <=> !z. P (FST z) (SND z)`, REWRITE_TAC[FORALL_PAIR_THM; FST; SND] THEN MESON_TAC[]);; let EXISTS_UNPAIR_THM = prove (`!P. (?x y. P x y) <=> ?z. P (FST z) (SND z)`, REWRITE_TAC[EXISTS_PAIR_THM; FST; SND] THEN MESON_TAC[]);; (* ------------------------------------------------------------------------- *) (* Related theorems for explicitly paired quantifiers. *) (* ------------------------------------------------------------------------- *) let FORALL_PAIRED_THM = prove (`!P. (!(x,y). P x y) <=> (!x y. P x y)`, GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o RATOR_CONV) [FORALL_DEF] THEN REWRITE_TAC[FUN_EQ_THM; FORALL_PAIR_THM]);; let EXISTS_PAIRED_THM = prove (`!P. (?(x,y). P x y) <=> (?x y. P x y)`, GEN_TAC THEN MATCH_MP_TAC(TAUT `(~p <=> ~q) ==> (p <=> q)`) THEN REWRITE_TAC[REWRITE_RULE[ETA_AX] NOT_EXISTS_THM; FORALL_PAIR_THM]);; (* ------------------------------------------------------------------------- *) (* Likewise for tripled quantifiers (could continue with the same proof). *) (* ------------------------------------------------------------------------- *) let FORALL_TRIPLED_THM = prove (`!P. (!(x,y,z). P x y z) <=> (!x y z. P x y z)`, GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o RATOR_CONV) [FORALL_DEF] THEN REWRITE_TAC[FUN_EQ_THM; FORALL_PAIR_THM]);; let EXISTS_TRIPLED_THM = prove (`!P. (?(x,y,z). P x y z) <=> (?x y z. P x y z)`, GEN_TAC THEN MATCH_MP_TAC(TAUT `(~p <=> ~q) ==> (p <=> q)`) THEN REWRITE_TAC[REWRITE_RULE[ETA_AX] NOT_EXISTS_THM; FORALL_PAIR_THM]);; (* ------------------------------------------------------------------------- *) (* Expansion of a let-term. *) (* ------------------------------------------------------------------------- *) let let_CONV = let let1_CONV = REWR_CONV LET_DEF THENC GEN_BETA_CONV and lete_CONV = REWR_CONV LET_END_DEF in let rec EXPAND_BETAS_CONV tm = let tm' = rator tm in try let1_CONV tm with Failure _ -> let th1 = AP_THM (EXPAND_BETAS_CONV tm') (rand tm) in let th2 = GEN_BETA_CONV (rand(concl th1)) in TRANS th1 th2 in fun tm -> let ltm,pargs = strip_comb tm in if fst(dest_const ltm) <> "LET" or pargs = [] then failwith "let_CONV" else let abstm = hd pargs in let vs,bod = strip_gabs abstm in let es = tl pargs in let n = length es in if length vs <> n then failwith "let_CONV" else (EXPAND_BETAS_CONV THENC lete_CONV) tm;; let (LET_TAC:tactic) = let is_trivlet tm = try let assigs,bod = dest_let tm in forall (uncurry (=)) assigs with Failure _ -> false and PROVE_DEPAIRING_EXISTS = let pth = prove (`((x,y) = a) <=> (x = FST a) /\ (y = SND a)`, MESON_TAC[PAIR; PAIR_EQ]) in let rewr1_CONV = GEN_REWRITE_CONV TOP_DEPTH_CONV [pth] and rewr2_RULE = GEN_REWRITE_RULE (LAND_CONV o DEPTH_CONV) [TAUT `(x = x) <=> T`; TAUT `a /\ T <=> a`] in fun tm -> let th1 = rewr1_CONV tm in let tm1 = rand(concl th1) in let cjs = conjuncts tm1 in let vars = map lhand cjs in let th2 = EQ_MP (SYM th1) (ASSUME tm1) in let th3 = DISCH_ALL (itlist SIMPLE_EXISTS vars th2) in let th4 = INST (map (fun t -> rand t,lhand t) cjs) th3 in MP (rewr2_RULE th4) TRUTH in fun (asl,w as gl) -> let path = try find_path is_trivlet w with Failure _ -> find_path is_let w in let tm = follow_path path w in let assigs,bod = dest_let tm in let abbrevs = mapfilter (fun (x,y) -> if x = y then fail() else mk_eq(x,y)) assigs in let lvars = itlist (union o frees o lhs) abbrevs [] and avoids = itlist (union o thm_frees o snd) asl (frees w) in let rename = vsubst (zip (variants avoids lvars) lvars) in let abbrevs' = map (fun eq -> let l,r = dest_eq eq in mk_eq(rename l,r)) abbrevs in let deprths = map PROVE_DEPAIRING_EXISTS abbrevs' in (MAP_EVERY (REPEAT_TCL CHOOSE_THEN (fun th -> let th' = SYM th in SUBST_ALL_TAC th' THEN ASSUME_TAC th')) deprths THEN W(fun (asl',w') -> let tm' = follow_path path w' in CONV_TAC(PATH_CONV path (K(let_CONV tm'))))) gl;; print_endline "pair.ml loaded"
null
https://raw.githubusercontent.com/flyspeck/flyspeck/05bd66666b4b641f49e5131a37830f4881f39db9/azure/hol-light-nat/pair.ml
ocaml
========================================================================= Syntax sugaring; theory of pairing, with a bit of support. ========================================================================= ------------------------------------------------------------------------- Constants implementing (or at least tagging) syntactic sugar. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Pair type. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Syntax operations. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Extend basic rewrites; extend new_definition to allow paired varstructs. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Extend definitions to paired varstructs with benignity checking. ------------------------------------------------------------------------- ------------------------------------------------------------------------- A few more useful definitions. ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- General beta-conversion over linear pattern of nested constructors. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Add this to the basic "rewrites" and pairs to the inductive type store. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Convenient rules to eliminate binders over pairs. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Related theorems for explicitly paired quantifiers. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Likewise for tripled quantifiers (could continue with the same proof). ------------------------------------------------------------------------- ------------------------------------------------------------------------- Expansion of a let-term. -------------------------------------------------------------------------
, University of Cambridge Computer Laboratory ( c ) Copyright , University of Cambridge 1998 ( c ) Copyright , 1998 - 2007 open Parser include Impconv let LET_DEF = new_definition `LET (f:A->B) x = f x`;; let LET_END_DEF = new_definition `LET_END (t:A) = t`;; let GABS_DEF = new_definition `GABS (P:A->bool) = (@) P`;; let GEQ_DEF = new_definition `GEQ a b = (a:A = b)`;; let _SEQPATTERN = new_definition `_SEQPATTERN = \r s x. if ?y. r x y then r x else s x`;; let _UNGUARDED_PATTERN = new_definition `_UNGUARDED_PATTERN = \p r. p /\ r`;; let _GUARDED_PATTERN = new_definition `_GUARDED_PATTERN = \p g r. p /\ g /\ r`;; let _MATCH = new_definition `_MATCH = \e r. if (?!) (r e) then (@) (r e) else @z. F`;; let _FUNCTION = new_definition `_FUNCTION = \r x. if (?!) (r x) then (@) (r x) else @z. F`;; let mk_pair_def = new_definition `mk_pair (x:A) (y:B) = \a b. (a = x) /\ (b = y)`;; let PAIR_EXISTS_THM = prove (`?x. ?(a:A) (b:B). x = mk_pair a b`, MESON_TAC[]);; let prod_tybij = new_type_definition "prod" ("ABS_prod","REP_prod") PAIR_EXISTS_THM;; let REP_ABS_PAIR = prove (`!(x:A) (y:B). REP_prod (ABS_prod (mk_pair x y)) = mk_pair x y`, MESON_TAC[prod_tybij]);; parse_as_infix (",",(14,"right"));; let COMMA_DEF = new_definition `(x:A),(y:B) = ABS_prod(mk_pair x y)`;; let FST_DEF = new_definition `FST (p:A#B) = @x. ?y. p = x,y`;; let SND_DEF = new_definition `SND (p:A#B) = @y. ?x. p = x,y`;; let PAIR_EQ = prove (`!(x:A) (y:B) a b. (x,y = a,b) <=> (x = a) /\ (y = b)`, REPEAT GEN_TAC THEN EQ_TAC THENL [REWRITE_TAC[COMMA_DEF] THEN DISCH_THEN(MP_TAC o AP_TERM `REP_prod:A#B->A->B->bool`) THEN REWRITE_TAC[REP_ABS_PAIR] THEN REWRITE_TAC[mk_pair_def; FUN_EQ_THM]; ALL_TAC] THEN MESON_TAC[]);; let PAIR_SURJECTIVE = prove (`!p:A#B. ?x y. p = x,y`, GEN_TAC THEN REWRITE_TAC[COMMA_DEF] THEN MP_TAC(SPEC `REP_prod p :A->B->bool` (CONJUNCT2 prod_tybij)) THEN REWRITE_TAC[CONJUNCT1 prod_tybij] THEN DISCH_THEN(X_CHOOSE_THEN `a:A` (X_CHOOSE_THEN `b:B` MP_TAC)) THEN DISCH_THEN(MP_TAC o AP_TERM `ABS_prod:(A->B->bool)->A#B`) THEN REWRITE_TAC[CONJUNCT1 prod_tybij] THEN DISCH_THEN SUBST1_TAC THEN MAP_EVERY EXISTS_TAC [`a:A`; `b:B`] THEN REFL_TAC);; let FST = prove (`!(x:A) (y:B). FST(x,y) = x`, REPEAT GEN_TAC THEN REWRITE_TAC[FST_DEF] THEN MATCH_MP_TAC SELECT_UNIQUE THEN GEN_TAC THEN BETA_TAC THEN REWRITE_TAC[PAIR_EQ] THEN EQ_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[] THEN EXISTS_TAC `y:B` THEN ASM_REWRITE_TAC[]);; let SND = prove (`!(x:A) (y:B). SND(x,y) = y`, REPEAT GEN_TAC THEN REWRITE_TAC[SND_DEF] THEN MATCH_MP_TAC SELECT_UNIQUE THEN GEN_TAC THEN BETA_TAC THEN REWRITE_TAC[PAIR_EQ] THEN EQ_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[] THEN EXISTS_TAC `x:A` THEN ASM_REWRITE_TAC[]);; let PAIR = prove (`!x:A#B. FST x,SND x = x`, GEN_TAC THEN (X_CHOOSE_THEN `a:A` (X_CHOOSE_THEN `b:B` SUBST1_TAC) (SPEC `x:A#B` PAIR_SURJECTIVE)) THEN REWRITE_TAC[FST; SND]);; let pair_INDUCT = prove (`!P. (!x y. P (x,y)) ==> !p. P p`, REPEAT STRIP_TAC THEN GEN_REWRITE_TAC RAND_CONV [GSYM PAIR] THEN FIRST_ASSUM MATCH_ACCEPT_TAC);; let pair_RECURSION = prove (`!PAIR'. ?fn:A#B->C. !a0 a1. fn (a0,a1) = PAIR' a0 a1`, GEN_TAC THEN EXISTS_TAC `\p. (PAIR':A->B->C) (FST p) (SND p)` THEN REWRITE_TAC[FST; SND]);; let is_pair = is_binary ",";; let dest_pair = dest_binary ",";; let mk_pair = let ptm = mk_const(",",[]) in fun (l,r) -> mk_comb(mk_comb(inst [type_of l,aty; type_of r,bty] ptm,l),r);; extend_basic_rewrites [FST; SND; PAIR];; let the_definitions = ref [SND_DEF; FST_DEF; COMMA_DEF; mk_pair_def; GEQ_DEF; GABS_DEF; LET_END_DEF; LET_DEF; one_DEF; I_DEF; o_DEF; COND_DEF; _FALSITY_; EXISTS_UNIQUE_DEF; NOT_DEF; F_DEF; OR_DEF; EXISTS_DEF; FORALL_DEF; IMP_DEF; AND_DEF; T_DEF];; let new_definition = let depair = let rec depair gv arg = try let l,r = dest_pair arg in (depair (list_mk_icomb "FST" [gv]) l) @ (depair (list_mk_icomb "SND" [gv]) r) with Failure _ -> [gv,arg] in fun arg -> let gv = genvar(type_of arg) in gv,depair gv arg in fun tm -> let avs,def = strip_forall tm in try let th,th' = tryfind (fun th -> th,PART_MATCH I th def) (!the_definitions) in ignore(PART_MATCH I th' (snd(strip_forall(concl th)))); warn true "Benign redefinition"; GEN_ALL (GENL avs th') with Failure _ -> let l,r = dest_eq def in let fn,args = strip_comb l in let gargs,reps = (I F_F unions) (unzip(map depair args)) in let l' = list_mk_comb(fn,gargs) and r' = subst reps r in let th1 = new_definition (mk_eq(l',r')) in let slist = zip args gargs in let th2 = INST slist (SPEC_ALL th1) in let xreps = map (subst slist o fst) reps in let threps = map (SYM o PURE_REWRITE_CONV[FST; SND]) xreps in let th3 = TRANS th2 (SYM(SUBS_CONV threps r)) in let th4 = GEN_ALL (GENL avs th3) in the_definitions := th4::(!the_definitions); th4;; let CURRY_DEF = new_definition `CURRY(f:A#B->C) x y = f(x,y)`;; let UNCURRY_DEF = new_definition `!f x y. UNCURRY(f:A->B->C)(x,y) = f x y`;; let PASSOC_DEF = new_definition `!f x y z. PASSOC (f:(A#B)#C->D) (x,y,z) = f ((x,y),z)`;; Analog of ABS_CONV for generalized abstraction . let GABS_CONV conv tm = if is_abs tm then ABS_CONV conv tm else let gabs,bod = dest_comb tm in let f,qtm = dest_abs bod in let xs,bod = strip_forall qtm in AP_TERM gabs (ABS f (itlist MK_FORALL xs (RAND_CONV conv bod)));; let GEN_BETA_CONV = let projection_cache = ref [] in let create_projections conname = try assoc conname (!projection_cache) with Failure _ -> let genty = get_const_type conname in let conty = fst(dest_type(repeat (snd o dest_fun_ty) genty)) in let _,_,rth = assoc conty (!inductive_type_store) in let sth = SPEC_ALL rth in let evs,bod = strip_exists(concl sth) in let cjs = conjuncts bod in let ourcj = find ((=)conname o fst o dest_const o fst o strip_comb o rand o lhand o snd o strip_forall) cjs in let n = index ourcj cjs in let avs,eqn = strip_forall ourcj in let con',args = strip_comb(rand eqn) in let aargs,zargs = chop_list (length avs) args in let gargs = map (genvar o type_of) zargs in let gcon = genvar(itlist (mk_fun_ty o type_of) avs (type_of(rand eqn))) in let bth = INST [list_mk_abs(aargs @ gargs,list_mk_comb(gcon,avs)),con'] sth in let cth = el n (CONJUNCTS(ASSUME(snd(strip_exists(concl bth))))) in let dth = CONV_RULE (funpow (length avs) BINDER_CONV (RAND_CONV(BETAS_CONV))) cth in let eth = SIMPLE_EXISTS (rator(lhand(snd(strip_forall(concl dth))))) dth in let fth = PROVE_HYP bth (itlist SIMPLE_CHOOSE evs eth) in let zty = type_of (rand(snd(strip_forall(concl dth)))) in let mk_projector a = let ity = type_of a in let th = BETA_RULE(PINST [ity,zty] [list_mk_abs(avs,a),gcon] fth) in SYM(SPEC_ALL(SELECT_RULE th)) in let ths = map mk_projector avs in (projection_cache := (conname,ths)::(!projection_cache); ths) in let GEQ_CONV = REWR_CONV(GSYM GEQ_DEF) and DEGEQ_RULE = CONV_RULE(REWR_CONV GEQ_DEF) in let GABS_RULE = let pth = prove (`(?) P ==> P (GABS P)`, SIMP_TAC[GABS_DEF; SELECT_AX; ETA_AX]) in MATCH_MP pth in let rec create_iterated_projections tm = if frees tm = [] then [] else if is_var tm then [REFL tm] else let con,args = strip_comb tm in let prjths = create_projections (fst(dest_const con)) in let atm = rand(rand(concl(hd prjths))) in let instn = term_match [] atm tm in let arths = map (INSTANTIATE instn) prjths in let ths = map (fun arth -> let sths = create_iterated_projections (lhand(concl arth)) in map (CONV_RULE(RAND_CONV(SUBS_CONV[arth]))) sths) arths in unions' equals_thm ths in let GEN_BETA_CONV tm = try BETA_CONV tm with Failure _ -> let l,r = dest_comb tm in let vstr,bod = dest_gabs l in let instn = term_match [] vstr r in let prjs = create_iterated_projections vstr in let th1 = SUBS_CONV prjs bod in let bod' = rand(concl th1) in let gv = genvar(type_of vstr) in let pat = mk_abs(gv,subst[gv,vstr] bod') in let th2 = TRANS (BETA_CONV (mk_comb(pat,vstr))) (SYM th1) in let avs = fst(strip_forall(body(rand l))) in let th3 = GENL (fst(strip_forall(body(rand l)))) th2 in let efn = genvar(type_of pat) in let th4 = EXISTS(mk_exists(efn,subst[efn,pat] (concl th3)),pat) th3 in let th5 = CONV_RULE(funpow (length avs + 1) BINDER_CONV GEQ_CONV) th4 in let th6 = CONV_RULE BETA_CONV (GABS_RULE th5) in INSTANTIATE instn (DEGEQ_RULE (SPEC_ALL th6)) in GEN_BETA_CONV;; extend_basic_convs("GEN_BETA_CONV",(`GABS (\a. b) c`,GEN_BETA_CONV));; inductive_type_store := ("prod",(1,pair_INDUCT,pair_RECURSION))::(!inductive_type_store);; let FORALL_PAIR_THM = prove (`!P. (!p. P p) <=> (!p1 p2. P(p1,p2))`, MESON_TAC[PAIR]);; let EXISTS_PAIR_THM = prove (`!P. (?p. P p) <=> ?p1 p2. P(p1,p2)`, MESON_TAC[PAIR]);; let LAMBDA_PAIR_THM = prove (`!t. (\p. t p) = (\(x,y). t(x,y))`, REWRITE_TAC[FORALL_PAIR_THM; FUN_EQ_THM]);; let PAIRED_ETA_THM = prove (`(!f. (\(x,y). f (x,y)) = f) /\ (!f. (\(x,y,z). f (x,y,z)) = f) /\ (!f. (\(w,x,y,z). f (w,x,y,z)) = f)`, REPEAT STRIP_TAC THEN REWRITE_TAC[FUN_EQ_THM; FORALL_PAIR_THM]);; let FORALL_UNCURRY = prove (`!P. (!f:A->B->C. P f) <=> (!f. P (\a b. f(a,b)))`, GEN_TAC THEN EQ_TAC THEN SIMP_TAC[] THEN DISCH_TAC THEN X_GEN_TAC `f:A->B->C` THEN FIRST_ASSUM(MP_TAC o SPEC `\(a,b). (f:A->B->C) a b`) THEN SIMP_TAC[ETA_AX]);; let EXISTS_UNCURRY = prove (`!P. (?f:A->B->C. P f) <=> (?f. P (\a b. f(a,b)))`, ONCE_REWRITE_TAC[MESON[] `(?x. P x) <=> ~(!x. ~P x)`] THEN REWRITE_TAC[FORALL_UNCURRY]);; let EXISTS_CURRY = prove (`!P. (?f. P f) <=> (?f. P (\(a,b). f a b))`, REWRITE_TAC[EXISTS_UNCURRY; PAIRED_ETA_THM]);; let FORALL_CURRY = prove (`!P. (!f. P f) <=> (!f. P (\(a,b). f a b))`, REWRITE_TAC[FORALL_UNCURRY; PAIRED_ETA_THM]);; let FORALL_UNPAIR_THM = prove (`!P. (!x y. P x y) <=> !z. P (FST z) (SND z)`, REWRITE_TAC[FORALL_PAIR_THM; FST; SND] THEN MESON_TAC[]);; let EXISTS_UNPAIR_THM = prove (`!P. (?x y. P x y) <=> ?z. P (FST z) (SND z)`, REWRITE_TAC[EXISTS_PAIR_THM; FST; SND] THEN MESON_TAC[]);; let FORALL_PAIRED_THM = prove (`!P. (!(x,y). P x y) <=> (!x y. P x y)`, GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o RATOR_CONV) [FORALL_DEF] THEN REWRITE_TAC[FUN_EQ_THM; FORALL_PAIR_THM]);; let EXISTS_PAIRED_THM = prove (`!P. (?(x,y). P x y) <=> (?x y. P x y)`, GEN_TAC THEN MATCH_MP_TAC(TAUT `(~p <=> ~q) ==> (p <=> q)`) THEN REWRITE_TAC[REWRITE_RULE[ETA_AX] NOT_EXISTS_THM; FORALL_PAIR_THM]);; let FORALL_TRIPLED_THM = prove (`!P. (!(x,y,z). P x y z) <=> (!x y z. P x y z)`, GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o RATOR_CONV) [FORALL_DEF] THEN REWRITE_TAC[FUN_EQ_THM; FORALL_PAIR_THM]);; let EXISTS_TRIPLED_THM = prove (`!P. (?(x,y,z). P x y z) <=> (?x y z. P x y z)`, GEN_TAC THEN MATCH_MP_TAC(TAUT `(~p <=> ~q) ==> (p <=> q)`) THEN REWRITE_TAC[REWRITE_RULE[ETA_AX] NOT_EXISTS_THM; FORALL_PAIR_THM]);; let let_CONV = let let1_CONV = REWR_CONV LET_DEF THENC GEN_BETA_CONV and lete_CONV = REWR_CONV LET_END_DEF in let rec EXPAND_BETAS_CONV tm = let tm' = rator tm in try let1_CONV tm with Failure _ -> let th1 = AP_THM (EXPAND_BETAS_CONV tm') (rand tm) in let th2 = GEN_BETA_CONV (rand(concl th1)) in TRANS th1 th2 in fun tm -> let ltm,pargs = strip_comb tm in if fst(dest_const ltm) <> "LET" or pargs = [] then failwith "let_CONV" else let abstm = hd pargs in let vs,bod = strip_gabs abstm in let es = tl pargs in let n = length es in if length vs <> n then failwith "let_CONV" else (EXPAND_BETAS_CONV THENC lete_CONV) tm;; let (LET_TAC:tactic) = let is_trivlet tm = try let assigs,bod = dest_let tm in forall (uncurry (=)) assigs with Failure _ -> false and PROVE_DEPAIRING_EXISTS = let pth = prove (`((x,y) = a) <=> (x = FST a) /\ (y = SND a)`, MESON_TAC[PAIR; PAIR_EQ]) in let rewr1_CONV = GEN_REWRITE_CONV TOP_DEPTH_CONV [pth] and rewr2_RULE = GEN_REWRITE_RULE (LAND_CONV o DEPTH_CONV) [TAUT `(x = x) <=> T`; TAUT `a /\ T <=> a`] in fun tm -> let th1 = rewr1_CONV tm in let tm1 = rand(concl th1) in let cjs = conjuncts tm1 in let vars = map lhand cjs in let th2 = EQ_MP (SYM th1) (ASSUME tm1) in let th3 = DISCH_ALL (itlist SIMPLE_EXISTS vars th2) in let th4 = INST (map (fun t -> rand t,lhand t) cjs) th3 in MP (rewr2_RULE th4) TRUTH in fun (asl,w as gl) -> let path = try find_path is_trivlet w with Failure _ -> find_path is_let w in let tm = follow_path path w in let assigs,bod = dest_let tm in let abbrevs = mapfilter (fun (x,y) -> if x = y then fail() else mk_eq(x,y)) assigs in let lvars = itlist (union o frees o lhs) abbrevs [] and avoids = itlist (union o thm_frees o snd) asl (frees w) in let rename = vsubst (zip (variants avoids lvars) lvars) in let abbrevs' = map (fun eq -> let l,r = dest_eq eq in mk_eq(rename l,r)) abbrevs in let deprths = map PROVE_DEPAIRING_EXISTS abbrevs' in (MAP_EVERY (REPEAT_TCL CHOOSE_THEN (fun th -> let th' = SYM th in SUBST_ALL_TAC th' THEN ASSUME_TAC th')) deprths THEN W(fun (asl',w') -> let tm' = follow_path path w' in CONV_TAC(PATH_CONV path (K(let_CONV tm'))))) gl;; print_endline "pair.ml loaded"
00acd8a5a6690289170bc5fe31c0bdf2f4ad901c07cae95081cfead8d4819ad6
nobsun/hs-bcopl
Semantics.hs
{-# LANGUAGE GADTs #-} # LANGUAGE TypeFamilies # # LANGUAGE DataKinds # # LANGUAGE KindSignatures # # LANGUAGE TypeOperators # # LANGUAGE FlexibleInstances # # LANGUAGE EmptyCase # module Language.BCoPL.TypeLevel.MetaTheory.Semantics where import Language.BCoPL.TypeLevel.Peano import Language.BCoPL.TypeLevel.Exp import Language.BCoPL.TypeLevel.EvalNatExp import Language.BCoPL.TypeLevel.ReduceNatExp import Language . BCoPL.TypeLevel . MetaTheory . import Language . BCoPL.TypeLevel . . | 定理 2.27 evalReduce :: Exp' e -> Nat' n -> EvalTo e n -> e :-*-> ENat n evalReduce e n ev = case ev of EConst _ -> MRZero e EPlus e1 e2 n1 n2 _n ev1 ev2 p -> case evalReduce e1 n1 ev1 of rd1 -> case evalReduce e2 n2 ev2 of rd2 -> case plusSubRedL e1 (ENat' n1) e2 rd1 of rd -> case plusSubRedR (ENat' n1) e2 (ENat' n2) rd2 of rd' -> MRMulti (e1 :+: e2) (ENat' n1 :+: ENat' n2) (ENat' n) (MRMulti (e1 :+: e2) (ENat' n1 :+: e2) (ENat' n1 :+: ENat' n2) rd rd') (MROne (ENat' n1 :+: ENat' n2) (ENat' n) (RPlus n1 n2 n p)) ETimes e1 e2 n1 n2 _n ev1 ev2 p -> case evalReduce e1 n1 ev1 of rd1 -> case evalReduce e2 n2 ev2 of rd2 -> case timesSubRedL e1 (ENat' n1) e2 rd1 of rd -> case timesSubRedR (ENat' n1) e2 (ENat' n2) rd2 of rd' -> MRMulti (e1 :×: e2) (ENat' n1 :×: ENat' n2) (ENat' n) (MRMulti (e1 :×: e2) (ENat' n1 :×: e2) (ENat' n1 :×: ENat' n2) rd rd') (MROne (ENat' n1 :×: ENat' n2) (ENat' n) (RTimes n1 n2 n p)) plusSubRedL :: Exp' e1 -> Exp' e1' -> Exp' e2 -> e1 :-*-> e1' -> (e1 :+ e2) :-*-> (e1' :+ e2) plusSubRedL e1 e1' e2 mr1 = case mr1 of MRZero _ -> MRZero (e1 :+: e2) MROne _ _ r1 -> MROne (e1 :+: e2) (e1' :+: e2) (RPlusL e1 e1' e2 r1) MRMulti _ e1'' _ mr1'' mr1' -> MRMulti (e1 :+: e2) (e1'' :+: e2) (e1' :+: e2) (plusSubRedL e1 e1'' e2 mr1'') (plusSubRedL e1'' e1' e2 mr1') plusSubRedR :: Exp' e1 -> Exp' e2 -> Exp' e2' -> e2 :-*-> e2' -> (e1 :+ e2) :-*-> (e1 :+ e2') plusSubRedR e1 e2 e2' mr2 = case mr2 of MRZero _ -> MRZero (e1 :+: e2) MROne _ _ r2 -> MROne (e1 :+: e2) (e1 :+: e2') (RPlusR e1 e2 e2' r2) MRMulti _ e2'' _ mr2'' mr2' -> MRMulti (e1 :+: e2) (e1 :+: e2'') (e1 :+: e2') (plusSubRedR e1 e2 e2'' mr2'') (plusSubRedR e1 e2'' e2' mr2') timesSubRedL :: Exp' e1 -> Exp' e1' -> Exp' e2 -> e1 :-*-> e1' -> (e1 :× e2) :-*-> (e1' :× e2) timesSubRedL e1 e1' e2 mr1 = case mr1 of MRZero _ -> MRZero (e1 :×: e2) MROne _ _ r1 -> MROne (e1 :×: e2) (e1' :×: e2) (RTimesL e1 e1' e2 r1) MRMulti _ e1'' _ mr1'' mr1' -> MRMulti (e1 :×: e2) (e1'' :×: e2) (e1' :×: e2) (timesSubRedL e1 e1'' e2 mr1'') (timesSubRedL e1'' e1' e2 mr1') timesSubRedR :: Exp' e1 -> Exp' e2 -> Exp' e2' -> e2 :-*-> e2' -> (e1 :× e2) :-*-> (e1 :× e2') timesSubRedR e1 e2 e2' mr2 = case mr2 of MRZero _ -> MRZero (e1 :×: e2) MROne _ _ r2 -> MROne (e1 :×: e2) (e1 :×: e2') (RTimesR e1 e2 e2' r2) MRMulti _ e2'' _ mr2'' mr2' -> MRMulti (e1 :×: e2) (e1 :×: e2'') (e1 :×: e2') (timesSubRedR e1 e2 e2'' mr2'') (timesSubRedR e1 e2'' e2' mr2') | 定理 2.28 reduceEval :: Exp' e -> Nat' n -> e :-*-> ENat n -> EvalTo e n reduceEval e n rd = case normalizeMRM rd of MRZero _ -> EConst n MROne e' _ r -> case r of RPlus n1 n2 _ p -> EPlus (ENat' n1) (ENat' n2) n1 n2 n (EConst n1) (EConst n2) p RTimes n1 n2 _ t -> ETimes (ENat' n1) (ENat' n2) n1 n2 n (EConst n1) (EConst n2) t pat -> case pat of {} MRMulti _ dex _ mr mr' -> case (e,dex) of (e1 :+: e2, ENat' n1 :+: ENat' n2) -> case separateRPathPlus e1 e2 (ENat' n1) (ENat' n2) mr of (rd1,rd2) -> case mr' of MROne _ _ r -> case r of RPlus _ _ _ p -> EPlus e1 e2 n1 n2 n (reduceEval e1 n1 rd1) (reduceEval e2 n2 rd2) p pat -> case pat of {} pat -> case pat of {} (e1 :×: e2, ENat' n1 :×: ENat' n2) -> case separateRPathTimes e1 e2 (ENat' n1) (ENat' n2) mr of (rd1,rd2) -> case mr' of MROne _ _ r -> case r of RTimes _ _ _ t -> ETimes e1 e2 n1 n2 n (reduceEval e1 n1 rd1) (reduceEval e2 n2 rd2) t pat -> case pat of {} pat -> case pat of {} pat -> case pat of {} separateRPathPlus :: Exp' e1 -> Exp' e2 -> Exp' e1' -> Exp' e2' -> (e1 :+ e2) :-*-> (e1' :+ e2') -> (e1 :-*-> e1', e2 :-*-> e2') separateRPathPlus e1 e2 e1' e2' mr = case normalizeMRM mr of MRZero _ -> (MRZero e1,MRZero e2) MROne _ _ r -> case r of RPlusL _ _ _ r' -> (MROne e1 e1' r', MRZero e2) RPlusR _ _ _ r' -> (MRZero e1, MROne e2 e2' r') pat -> case pat of {} MRMulti _ (e1'' :+: e2'') _ mr1 mr2 -> case mr2 of MROne _ _ r -> case r of RPlusL _ _ _ r' -> case separateRPathPlus e1 e2 e1'' e2'' mr1 of (mr1',mr2') -> (MRMulti e1 e1'' e1' mr1' (MROne e1'' e1' r'), mr2') RPlusR _ _ _ r' -> case separateRPathPlus e1 e2 e1'' e2'' mr1 of (mr1',mr2') -> (mr1',MRMulti e2 e2'' e2' mr2' (MROne e2'' e2' r')) pat -> case pat of {} pat -> case pat of {} separateRPathTimes :: Exp' e1 -> Exp' e2 -> Exp' e1' -> Exp' e2' -> (e1 :× e2) :-*-> (e1' :× e2') -> (e1 :-*-> e1', e2 :-*-> e2') separateRPathTimes e1 e2 e1' e2' mr = case normalizeMRM mr of MRZero _ -> (MRZero e1,MRZero e2) MROne _ _ r -> case r of RTimesL _ _ _ r' -> (MROne e1 e1' r', MRZero e2) RTimesR _ _ _ r' -> (MRZero e1, MROne e2 e2' r') pat -> case pat of {} MRMulti _ (e1'' :×: e2'') _ mr1 mr2 -> case mr2 of MROne _ _ r -> case r of RTimesL _ _ _ r' -> case separateRPathTimes e1 e2 e1'' e2'' mr1 of (mr1',mr2') -> (MRMulti e1 e1'' e1' mr1' (MROne e1'' e1' r'), mr2') RTimesR _ _ _ r' -> case separateRPathTimes e1 e2 e1'' e2'' mr1 of (mr1',mr2') -> (mr1',MRMulti e2 e2'' e2' mr2' (MROne e2'' e2' r')) pat -> case pat of {} pat -> case pat of {}
null
https://raw.githubusercontent.com/nobsun/hs-bcopl/d8ede46ad0f458312efffff9065bd58eb8a3e9e4/src/Language/BCoPL/TypeLevel/MetaTheory/Semantics.hs
haskell
# LANGUAGE GADTs #
# LANGUAGE TypeFamilies # # LANGUAGE DataKinds # # LANGUAGE KindSignatures # # LANGUAGE TypeOperators # # LANGUAGE FlexibleInstances # # LANGUAGE EmptyCase # module Language.BCoPL.TypeLevel.MetaTheory.Semantics where import Language.BCoPL.TypeLevel.Peano import Language.BCoPL.TypeLevel.Exp import Language.BCoPL.TypeLevel.EvalNatExp import Language.BCoPL.TypeLevel.ReduceNatExp import Language . BCoPL.TypeLevel . MetaTheory . import Language . BCoPL.TypeLevel . . | 定理 2.27 evalReduce :: Exp' e -> Nat' n -> EvalTo e n -> e :-*-> ENat n evalReduce e n ev = case ev of EConst _ -> MRZero e EPlus e1 e2 n1 n2 _n ev1 ev2 p -> case evalReduce e1 n1 ev1 of rd1 -> case evalReduce e2 n2 ev2 of rd2 -> case plusSubRedL e1 (ENat' n1) e2 rd1 of rd -> case plusSubRedR (ENat' n1) e2 (ENat' n2) rd2 of rd' -> MRMulti (e1 :+: e2) (ENat' n1 :+: ENat' n2) (ENat' n) (MRMulti (e1 :+: e2) (ENat' n1 :+: e2) (ENat' n1 :+: ENat' n2) rd rd') (MROne (ENat' n1 :+: ENat' n2) (ENat' n) (RPlus n1 n2 n p)) ETimes e1 e2 n1 n2 _n ev1 ev2 p -> case evalReduce e1 n1 ev1 of rd1 -> case evalReduce e2 n2 ev2 of rd2 -> case timesSubRedL e1 (ENat' n1) e2 rd1 of rd -> case timesSubRedR (ENat' n1) e2 (ENat' n2) rd2 of rd' -> MRMulti (e1 :×: e2) (ENat' n1 :×: ENat' n2) (ENat' n) (MRMulti (e1 :×: e2) (ENat' n1 :×: e2) (ENat' n1 :×: ENat' n2) rd rd') (MROne (ENat' n1 :×: ENat' n2) (ENat' n) (RTimes n1 n2 n p)) plusSubRedL :: Exp' e1 -> Exp' e1' -> Exp' e2 -> e1 :-*-> e1' -> (e1 :+ e2) :-*-> (e1' :+ e2) plusSubRedL e1 e1' e2 mr1 = case mr1 of MRZero _ -> MRZero (e1 :+: e2) MROne _ _ r1 -> MROne (e1 :+: e2) (e1' :+: e2) (RPlusL e1 e1' e2 r1) MRMulti _ e1'' _ mr1'' mr1' -> MRMulti (e1 :+: e2) (e1'' :+: e2) (e1' :+: e2) (plusSubRedL e1 e1'' e2 mr1'') (plusSubRedL e1'' e1' e2 mr1') plusSubRedR :: Exp' e1 -> Exp' e2 -> Exp' e2' -> e2 :-*-> e2' -> (e1 :+ e2) :-*-> (e1 :+ e2') plusSubRedR e1 e2 e2' mr2 = case mr2 of MRZero _ -> MRZero (e1 :+: e2) MROne _ _ r2 -> MROne (e1 :+: e2) (e1 :+: e2') (RPlusR e1 e2 e2' r2) MRMulti _ e2'' _ mr2'' mr2' -> MRMulti (e1 :+: e2) (e1 :+: e2'') (e1 :+: e2') (plusSubRedR e1 e2 e2'' mr2'') (plusSubRedR e1 e2'' e2' mr2') timesSubRedL :: Exp' e1 -> Exp' e1' -> Exp' e2 -> e1 :-*-> e1' -> (e1 :× e2) :-*-> (e1' :× e2) timesSubRedL e1 e1' e2 mr1 = case mr1 of MRZero _ -> MRZero (e1 :×: e2) MROne _ _ r1 -> MROne (e1 :×: e2) (e1' :×: e2) (RTimesL e1 e1' e2 r1) MRMulti _ e1'' _ mr1'' mr1' -> MRMulti (e1 :×: e2) (e1'' :×: e2) (e1' :×: e2) (timesSubRedL e1 e1'' e2 mr1'') (timesSubRedL e1'' e1' e2 mr1') timesSubRedR :: Exp' e1 -> Exp' e2 -> Exp' e2' -> e2 :-*-> e2' -> (e1 :× e2) :-*-> (e1 :× e2') timesSubRedR e1 e2 e2' mr2 = case mr2 of MRZero _ -> MRZero (e1 :×: e2) MROne _ _ r2 -> MROne (e1 :×: e2) (e1 :×: e2') (RTimesR e1 e2 e2' r2) MRMulti _ e2'' _ mr2'' mr2' -> MRMulti (e1 :×: e2) (e1 :×: e2'') (e1 :×: e2') (timesSubRedR e1 e2 e2'' mr2'') (timesSubRedR e1 e2'' e2' mr2') | 定理 2.28 reduceEval :: Exp' e -> Nat' n -> e :-*-> ENat n -> EvalTo e n reduceEval e n rd = case normalizeMRM rd of MRZero _ -> EConst n MROne e' _ r -> case r of RPlus n1 n2 _ p -> EPlus (ENat' n1) (ENat' n2) n1 n2 n (EConst n1) (EConst n2) p RTimes n1 n2 _ t -> ETimes (ENat' n1) (ENat' n2) n1 n2 n (EConst n1) (EConst n2) t pat -> case pat of {} MRMulti _ dex _ mr mr' -> case (e,dex) of (e1 :+: e2, ENat' n1 :+: ENat' n2) -> case separateRPathPlus e1 e2 (ENat' n1) (ENat' n2) mr of (rd1,rd2) -> case mr' of MROne _ _ r -> case r of RPlus _ _ _ p -> EPlus e1 e2 n1 n2 n (reduceEval e1 n1 rd1) (reduceEval e2 n2 rd2) p pat -> case pat of {} pat -> case pat of {} (e1 :×: e2, ENat' n1 :×: ENat' n2) -> case separateRPathTimes e1 e2 (ENat' n1) (ENat' n2) mr of (rd1,rd2) -> case mr' of MROne _ _ r -> case r of RTimes _ _ _ t -> ETimes e1 e2 n1 n2 n (reduceEval e1 n1 rd1) (reduceEval e2 n2 rd2) t pat -> case pat of {} pat -> case pat of {} pat -> case pat of {} separateRPathPlus :: Exp' e1 -> Exp' e2 -> Exp' e1' -> Exp' e2' -> (e1 :+ e2) :-*-> (e1' :+ e2') -> (e1 :-*-> e1', e2 :-*-> e2') separateRPathPlus e1 e2 e1' e2' mr = case normalizeMRM mr of MRZero _ -> (MRZero e1,MRZero e2) MROne _ _ r -> case r of RPlusL _ _ _ r' -> (MROne e1 e1' r', MRZero e2) RPlusR _ _ _ r' -> (MRZero e1, MROne e2 e2' r') pat -> case pat of {} MRMulti _ (e1'' :+: e2'') _ mr1 mr2 -> case mr2 of MROne _ _ r -> case r of RPlusL _ _ _ r' -> case separateRPathPlus e1 e2 e1'' e2'' mr1 of (mr1',mr2') -> (MRMulti e1 e1'' e1' mr1' (MROne e1'' e1' r'), mr2') RPlusR _ _ _ r' -> case separateRPathPlus e1 e2 e1'' e2'' mr1 of (mr1',mr2') -> (mr1',MRMulti e2 e2'' e2' mr2' (MROne e2'' e2' r')) pat -> case pat of {} pat -> case pat of {} separateRPathTimes :: Exp' e1 -> Exp' e2 -> Exp' e1' -> Exp' e2' -> (e1 :× e2) :-*-> (e1' :× e2') -> (e1 :-*-> e1', e2 :-*-> e2') separateRPathTimes e1 e2 e1' e2' mr = case normalizeMRM mr of MRZero _ -> (MRZero e1,MRZero e2) MROne _ _ r -> case r of RTimesL _ _ _ r' -> (MROne e1 e1' r', MRZero e2) RTimesR _ _ _ r' -> (MRZero e1, MROne e2 e2' r') pat -> case pat of {} MRMulti _ (e1'' :×: e2'') _ mr1 mr2 -> case mr2 of MROne _ _ r -> case r of RTimesL _ _ _ r' -> case separateRPathTimes e1 e2 e1'' e2'' mr1 of (mr1',mr2') -> (MRMulti e1 e1'' e1' mr1' (MROne e1'' e1' r'), mr2') RTimesR _ _ _ r' -> case separateRPathTimes e1 e2 e1'' e2'' mr1 of (mr1',mr2') -> (mr1',MRMulti e2 e2'' e2' mr2' (MROne e2'' e2' r')) pat -> case pat of {} pat -> case pat of {}
0038346d2574a80baa86636515849b160ce41ee94b9b927ab105861a75d359d1
rtoy/cmucl
vop.lisp
;;; -*- Package: C; Log: C.Log -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . ;;; (ext:file-comment "$Header: src/compiler/vop.lisp $") ;;; ;;; ********************************************************************** ;;; Structures for the second ( virtual machine ) intermediate representation ;;; in the compiler, IR2. ;;; Written by ;;; (in-package "C") (intl:textdomain "cmucl") (export '(tn-ref tn-ref-p make-tn-ref tn-ref-tn tn-ref-write-p tn-ref-next tn-ref-vop tn-ref-next-ref tn-ref-across tn-ref-target tn-ref-load-tn sb sb-p sb-name sc sc-p sc-name sc-number sc-sb tn tn-p make-random-tn tn-sc tn-offset Call.lisp and core.lisp need to get at these slots . ir2-component-constants ir2-environment-number-stack-p needs these . ir2-component-dyncount-info ir2-block-block vop-block)) (eval-when (compile load eval) ;;; ;;; The largest number of TNs whose liveness changes that we can have in any ;;; block. (defconstant local-tn-limit 64) (deftype local-tn-number () `(integer 0 (,local-tn-limit))) (deftype local-tn-count () `(integer 0 ,local-tn-limit)) (deftype local-tn-vector () `(simple-vector ,local-tn-limit)) (deftype local-tn-bit-vector () `(simple-bit-vector ,local-tn-limit)) Type of an SC number . (deftype sc-number () `(integer 0 (,sc-number-limit))) Types for vectors indexed by SC numbers . (deftype sc-vector () `(simple-vector ,sc-number-limit)) (deftype sc-bit-vector () `(simple-bit-vector ,sc-number-limit)) ;;; The different policies we can use to determine the coding strategy. ;;; (deftype policies () '(member :safe :small :fast :fast-safe)) ); Eval-When (Compile Load Eval) ;;;; Primitive types: ;;; ;;; The primitive type is used to represent the aspects of type interesting to the VM . Selection of IR2 translation templates is done on the basis of ;;; the primitive types of the operands, and the primitive type of a value ;;; is used to constrain the possible representations of that value. ;;; (eval-when (compile load eval) ;;; (defstruct (primitive-type (:print-function %print-primitive-type)) ;; ;; The name of this primitive-type. (name nil :type symbol) ;; A list the SC numbers for all the SCs that a TN of this type can be ;; allocated in. (scs nil :type list) ;; ;; The Lisp type equivalent to this type. If this type could never be returned by Primitive - Type , then this is the NIL ( or empty ) type . (type (required-argument) :type ctype) ;; ;; The template used to check that an object is of this type. This is a template of one argument and one result , both of primitive - type T. If ;; the argument is of the correct type, then it is delivered into the result. ;; If the type is incorrect, then an error is signalled. (check nil :type (or template null))) (defprinter primitive-type name (type :test (and type (not (eq (type-specifier type) (primitive-type-name structure)))) :prin1 (type-specifier type))) ); eval-when (compile load eval) ;;;; IR1 annotations used for IR2 conversion: ;;; ;;; Block-Info Holds the IR2 - Block structure . If there are overflow blocks , then this points to the first IR2 - Block . The Block - Info of the dummy component ;;; head and tail are dummy IR2 blocks that begin and end the emission order ;;; thread. ;;; ;;; Component-Info Holds the IR2 - Component structure . ;;; Continuation - Info Holds the IR2 - Continuation structure . Continuations whose values are n't ;;; used won't have any. ;;; Cleanup - Info If non - null , then a TN in which the affected dynamic environment pointer ;;; should be saved after the binding is instantiated. ;;; ;;; Environment-Info Holds the IR2 - Environment structure . ;;; Tail - Set - Info Holds the Return - Info structure . ;;; NLX - Info - Info Holds the IR2 - NLX - Info structure . ;;; Leaf - Info If a non - set lexical variable , the TN that holds the value in the home environment . If a constant , then the corresponding constant TN . ;;; If an XEP lambda, then the corresponding Entry-Info structure. ;;; Basic - Combination - Info The template chosen by LTN , or ;;; :FULL if this is definitely a full call. ;;; :FUNNY if this is a random thing with IR2-convert. ;;; :LOCAL if this is a local call. ;;; ;;; Node-Tail-P After LTN analysis , this is true only in combination nodes that are ;;; truly tail recursive. ;;; ;;; The IR2-Block structure holds information about a block that is used during ;;; and after IR2 conversion. It is stored in the Block-Info slot for the ;;; associated block. ;;; (defstruct (ir2-block (:include block-annotation) (:constructor really-make-ir2-block (block)) (:print-function %print-ir2-block)) ;; The IR2 - Block 's number , which differs from Block 's Block - Number if any ;; blocks are split. This is assigned by lifetime analysis. (number nil :type (or index null)) ;; ;; Information about unknown-values continuations that is used by stack ;; analysis to do stack simulation. A unknown-values continuation is Pushed ;; if it's Dest is in another block. Similarly, a continuation is Popped if its Dest is in this block but has its uses elsewhere . The continuations ;; are in the order that are pushed/popped in the block. Note that the args to a single MV - Combination appear reversed in Popped , since we must effectively pop the last argument first . All pops must come before all pushes ( although internal MV uses may be interleaved . ) Popped is computed by LTN , and Pushed is computed by stack analysis . (pushed () :type list) (popped () :type list) ;; ;; The result of stack analysis: lists of all the unknown-values ;; continuations on the stack at the block start and end, topmost continuation first . (start-stack () :type list) (end-stack () :type list) ;; The first and last VOP in this block . If there are none , both slots are ;; null. (start-vop nil :type (or vop null)) (last-vop nil :type (or vop null)) ;; ;; Number of local TNs actually allocated. (local-tn-count 0 :type local-tn-count) ;; A vector that maps local TN numbers to TNs . Some entries may be NIL , ;; indicating that that number is unused. (This allows us to delete local conflict information without compressing the LTN numbers . ) ;; If an entry is : More , then this block contains only a single VOP . This VOP has so many more arguments and/or results that they can not all be ;; assigned distinct LTN numbers. In this case, we assign all the more args one LTN number , and all the more results another LTN number . We can do ;; this, since more operands are referenced simultaneously as far as conflict ;; analysis is concerned. Note that all these :More TNs will be global TNs. (local-tns (make-array local-tn-limit) :type local-tn-vector) ;; ;; Bit-vectors used during lifetime analysis to keep track of references to local TNs . When indexed by the LTN number , the index for a TN is non - zero ;; in Written if it is ever written in the block, and in Live-Out if the first reference is a read . (written (make-array local-tn-limit :element-type 'bit :initial-element 0) :type local-tn-bit-vector) (live-out (make-array local-tn-limit :element-type 'bit) :type local-tn-bit-vector) ;; Similar to the above , but is updated by lifetime flow analysis to have a 1 for LTN numbers of TNs live at the end of the block . This takes into ;; account all TNs that aren't :Live. (live-in (make-array local-tn-limit :element-type 'bit :initial-element 0) :type local-tn-bit-vector) ;; ;; A thread running through the global-conflicts structures for this block, sorted by TN number . (global-tns nil :type (or global-conflicts null)) ;; ;; The assembler label that points to the beginning of the code for this ;; block. Null when we haven't assigned a label yet. (%label nil) ;; ;; List of Location-Info structures describing all the interesting (to the ;; debugger) locations in this block. (locations nil :type list)) (defprinter ir2-block (pushed :test pushed) (popped :test popped) (start-vop :test start-vop) (last-vop :test last-vop) (local-tn-count :test (not (zerop local-tn-count))) (%label :test %label)) The IR2 - Continuation structure is used to annotate continuations that are used as a function result continuation or that receive MVs . ;;; (defstruct (ir2-continuation (:constructor make-ir2-continuation (primitive-type)) (:print-function %print-ir2-continuation)) ;; ;; If this is :Delayed, then this is a single value continuation for which ;; the evaluation of the use is to be postponed until the evaluation of ;; destination. This can be done for ref nodes or predicates whose ;; destination is an IF. ;; ;; If this is :Fixed, then this continuation has a fixed number of values, with the TNs in . ;; ;; If this is :Unknown, then this is an unknown-values continuation, using the passing locations in Locs . ;; ;; If this is :Unused, then this continuation should never actually be used ;; as the destination of a value: it is only used tail-recursively. (kind :fixed :type (member :delayed :fixed :unknown :unused)) ;; The primitive - type of the first value of this continuation . This is primarily for internal use during LTN , but it also records the type ;; restriction on delayed references. In multiple-value contexts, this is ;; null to indicate that it is meaningless. This is always (primitive-type ;; (continuation-type cont)), which may be more restrictive than the tn - primitive - type of the value TN . This is becase the value TN must hold ;; any possible type that could be computed (before type checking.) (primitive-type nil :type (or primitive-type null)) ;; ;; Locations used to hold the values of the continuation. If the number of values if fixed , then there is one TN per value . If the number of values is unknown , then this is a two - list of TNs holding the start of the ;; values glob and the number of values. Note that since type checking is ;; the responsibility of the values receiver, these TNs primitive type is ;; only based on the proven type information. (locs nil :type list)) (defprinter ir2-continuation kind primitive-type locs) The IR2 - Component serves mostly to accumulate non - code information about ;;; the component being compiled. ;;;; (defstruct ir2-component ;; The counter used to allocate global TN numbers . (global-tn-counter 0 :type index) ;; ;; Normal-TNs is the head of the list of all the normal TNs that need to be packed , linked through the Next slot . We place TNs on this list when we ;; allocate them so that Pack can find them. ;; Restricted - TNs are TNs that must be packed within a finite SC . We pack these TNs first to ensure that the restrictions will be satisfied ( if ;; possible). ;; Wired - TNs are TNs that must be packed at a specific location . The SC and Offset are already filled in . ;; Constant - TNs are non - packed TNs that represent constants . : ;; may eventually be converted to :Cached-Constant normal TNs. (normal-tns nil :type (or tn null)) (restricted-tns nil :type (or tn null)) (wired-tns nil :type (or tn null)) (constant-tns nil :type (or tn null)) ;; ;; A list of all the :COMPONENT TNs (live throughout the component.) These ;; TNs will also appear in the {NORMAL,RESTRICTED,WIRED} TNs as appropriate ;; to their location. (component-tns () :type list) ;; ;; If this component has a NFP, then this is it. (nfp nil :type (or tn null)) ;; ;; A list of the explicitly specified save TNs (kind :SPECIFIED-SAVE). These ;; TNs will also appear in the {NORMAL,RESTRICTED,WIRED} TNs as appropriate ;; to their location. (specified-save-tns () :type list) ;; Values - Receivers is a list of all the blocks whose ir2 - block has a non - null value for Popped . This slot is initialized by LTN - Analyze as an input to Stack - Analyze . (values-receivers nil :type list) ;; ;; An adjustable vector that records all the constants in the constant pool. A non - immediate : with offset 0 refers to the constant in ;; element 0, etc. Normal constants are represented by the placing the ;; Constant leaf in this vector. A load-time constant is distinguished by ;; being a cons (Kind . What). Kind is a keyword indicating how the constant ;; is computed, and What is some context. ;; ;; These load-time constants are recognized: ;; ;; (:entry . <function>) ;; Is replaced by the code pointer for the specified function. This is how compiled code ( including DEFUN ) gets its hands on a function . < function > is the XEP lambda for the called function ; it 's Leaf - Info ;; should be an Entry-Info structure. ;; ;; (:label . <label>) ;; Is replaced with the byte offset of that label from the start of the ;; code vector (including the header length.) ;; ;; A null entry in this vector is a placeholder for implementation overhead ;; that is eventually stuffed in somehow. ;; (constants (make-array 10 :fill-pointer 0 :adjustable t) :type vector) ;; ;; Some kind of info about the component's run-time representation. This is filled in by the VM supplied Select - Component - Format function . format ;; A list of the Entry - Info structures describing all of the entries into ;; this component. Filled in by entry analysis. (entries nil :type list) ;; Head of the list of : ALIAS TNs in this component , threaded by TN - NEXT . (alias-tns nil :type (or tn null)) ;; ;; Spilled-VOPs is a hashtable translating from "interesting" VOPs to a list of the TNs spilled at that VOP . This is used when computing debug info so that we do n't consider the TN 's value to be valid when it is in fact somewhere else . Spilled - TNs has T for every " interesting " TN that is ever ;; spilled, providing a representation that is more convenient some places. (spilled-vops (make-hash-table :test #'eq) :type hash-table) (spilled-tns (make-hash-table :test #'eq) :type hash-table) ;; Dynamic vop count info . This is needed by both ir2 - convert and ;; setup-dynamic-count-info. (But only if we are generating code to ;; collect dynamic statistics.) (dyncount-info nil :type (or null dyncount-info))) The Entry - Info structure condenses all the information that the dumper needs to create each XEP 's function entry data structure . The Entry - Info structures are somtimes created before they are initialized , since ir2 ;;; conversion may need to compile a forward reference. In this case ;;; the slots aren't actually initialized until entry analysis runs. ;;; (defstruct entry-info ;; ;; True if this function has a non-null closure environment. (closure-p nil :type boolean) ;; ;; A label pointing to the entry vector for this function. Null until ;; ENTRY-ANALYZE runs. (offset nil :type (or label null)) ;; If this function was defined using DEFUN , then this is the name of the function , a symbol or ( SETF < symbol > ) . Otherwise , this is some string ;; that is intended to be informative. (name "<not computed>" :type (or simple-string list symbol)) ;; ;; A string representing the argument list that the function was defined ;; with. (arguments nil :type (or simple-string null)) ;; ;; A function type specifier representing the arguments and results of this ;; function. (type 'function :type (or list (member function)))) The IR2 - Environment is used to annotate non - let lambdas with their passing locations . It is stored in the Environment - Info . ;;; (defstruct (ir2-environment (:print-function %print-ir2-environment)) ;; ;; The TNs that hold the passed environment within the function. This is an alist translating from the NLX - Info or lambda - var to the TN that holds ;; the corresponding value within this function. This list is in the same ;; order as the ENVIRONMENT-CLOSURE. (environment nil :type list) ;; ;; The TNs that hold the Old-Fp and Return-PC within the function. We ;; always save these so that the debugger can do a backtrace, even if the ;; function has no return (and thus never uses them). Null only temporarily. (old-fp nil :type (or tn null)) (return-pc nil :type (or tn null)) ;; ;; The passing location for the Return-PC. The return PC is treated ;; differently from the other arguments, since in some implementations we may ;; use a call instruction that requires the return PC to be passed in a ;; particular place. (return-pc-pass (required-argument) :type tn) ;; ;; True if this function has a frame on the number stack. This is set by ;; representation selection whenever it is possible that some function in ;; our tail set will make use of the number stack. (number-stack-p nil :type boolean) ;; ;; A list of all the :Environment TNs live in this environment. (live-tns nil :type list) ;; ;; A list of all the :Debug-Environment TNs live in this environment. (debug-live-tns nil :type list) ;; ;; A label that marks the start of elsewhere code for this function. Null until this label is assigned by codegen . Used for maintaining the debug ;; source map. (elsewhere-start nil :type (or label null)) ;; A label that marks the first location in this function at which the ;; environment is properly initialized, i.e. arguments moved from their ;; passing locations, etc. This is the start of the function as far as the ;; debugger is concerned. (environment-start nil :type (or label null))) (defprinter ir2-environment environment old-fp return-pc return-pc-pass) The Return - Info structure is used by to represent the return strategy ;;; and locations for all the functions in a given Tail-Set. It is stored in the Tail - Set - Info . ;;; (defstruct (return-info (:print-function %print-return-info)) ;; ;; The return convention used: ;; -- If :Unknown, we use the standard return convention. ;; -- If :Fixed, we use the known-values convention. (kind (required-argument) :type (member :fixed :unknown)) ;; ;; The number of values returned, or :Unknown if we don't know. Count may be ;; known when Kind is :Unknown, since we may choose the standard return ;; convention for other reasons. (count (required-argument) :type (or index (member :unknown))) ;; ;; If count isn't :Unknown, then this is a list of the primitive-types of ;; each value. (types () :type list) ;; ;; If kind is :Fixed, then this is the list of the TNs that we return the ;; values in. (locations () :type list)) (defprinter return-info kind count types locations) (defstruct (ir2-nlx-info (:print-function %print-ir2-nlx-info)) ;; ;; If the kind is :Entry (a lexical exit), then in the home environment, this ;; holds a Value-Cell object containing the unwind block pointer. In the ;; other cases nobody directly references the unwind-block, so we leave this ;; slot null. (home nil :type (or tn null)) ;; ;; The saved control stack pointer. (save-sp (required-argument) :type tn) ;; The list of dynamic state save TNs . (dynamic-state (list* (make-stack-pointer-tn) (make-dynamic-state-tns)) :type list) ;; The target label for NLX entry . (target (gen-label) :type label)) (defprinter ir2-nlx-info home save-sp dynamic-state) ;;; The Loop structure holds information about a loop. ;;; (defstruct (cloop (:print-function %print-loop) (:conc-name loop-) (:predicate loop-p) (:constructor make-loop) (:copier copy-loop)) ;; ;; The kind of loop that this is. These values are legal: ;; ;; :Outer ;; This is the outermost loop structure, and represents all the ;; code in a component. ;; ;; :Natural A normal loop with only one entry . ;; ;; :Strange ;; A segment of a "strange loop" in a non-reducible flow graph. ;; (kind (required-argument) :type (member :outer :natural :strange)) ;; The first and last blocks in the loop . There may be more than one tail , ;; since there may be multiple back branches to the same head. (head nil :type (or cblock null)) (tail nil :type list) ;; ;; A list of all the blocks in this loop or its inferiors that have a ;; successor outside of the loop. (exits nil :type list) ;; ;; The loop that this loop is nested within. This is null in the outermost ;; loop structure. (superior nil :type (or cloop null)) ;; ;; A list of the loops nested directly within this one. (inferiors nil :type list) (depth 0 :type fixnum) ;; ;; The head of the list of blocks directly within this loop. We must recurse ;; on Inferiors to find all the blocks. (blocks nil :type (or null cblock))) (defprinter loop kind head tail exits) ;;;; VOPs and Templates: A VOP is a Virtual Operation . It represents an operation and the operands ;;; to the operation. ;;; (defstruct (vop (:print-function %print-vop) (:constructor really-make-vop (block node info args results))) ;; VOP - Info structure containing static info about the operation . (info nil :type (or vop-info null)) ;; The IR2 - Block this VOP is in . (block (required-argument) :type ir2-block) ;; ;; VOPs evaluated after and before this one. Null at the beginning/end of ;; the block, and temporarily during IR2 translation. (next nil :type (or vop null)) (prev nil :type (or vop null)) ;; ;; Heads of the TN-Ref lists for operand TNs, linked using the Across slot. (args nil :type (or tn-ref null)) (results nil :type (or tn-ref null)) ;; ;; Head of the list of write refs for each explicitly allocated temporary, ;; linked together using the Across slot. (temps nil :type (or tn-ref null)) ;; Head of the list of all TN - refs for references in this VOP , linked by the Next - Ref slot . There will be one entry for each operand and two ( a read ;; and a write) for each temporary. (refs nil :type (or tn-ref null)) ;; Stuff that is passed uninterpreted from IR2 conversion to codegen . The meaning of this slot is totally dependent on the VOP . codegen-info ;; Node that generated this VOP , for keeping track of debug info . (node nil :type (or node null)) ;; ;; Local-TN bit vector representing the set of TNs live after args are read ;; and before results are written. This is only filled in when VOP - INFO - SAVE - P is non - null . (save-set nil :type (or local-tn-bit-vector null))) (defprinter vop (info :prin1 (vop-info-name info)) args results (codegen-info :test codegen-info)) ;;; The TN-Ref structure contains information about a particular reference to a TN . The information in the TN - Refs largely determines how TNs are packed . ;;; (defstruct (tn-ref (:print-function %print-tn-ref) (:constructor really-make-tn-ref (tn write-p))) ;; The TN referenced . (tn (required-argument) :type tn) ;; ;; True if this is a write reference, false if a read. (write-p nil :type boolean) ;; Thread running through all TN - Refs for this TN of the same kind ( read or ;; write). (next nil :type (or tn-ref null)) ;; The VOP where the reference happens . The this is null only temporarily . (vop nil :type (or vop null)) ;; Thread running through all TN - Refs in VOP , in reverse order of reference . (next-ref nil :type (or tn-ref null)) ;; Thread the TN - Refs in VOP of the same kind ( argument , result , temp ) . (across nil :type (or tn-ref null)) ;; If true , this is a TN - Ref also in VOP whose TN we would like packed in the same location as our TN . Read and write refs are always paired : Target in ;; the read points to the write, and vice-versa. (target nil :type (or null tn-ref)) ;; ;; Load TN allocated for this operand, if any. (load-tn nil :type (or tn null))) (defprinter tn-ref tn write-p (vop :test vop :prin1 (vop-info-name (vop-info vop)))) The Template represents a particular IR2 coding strategy for a known ;;; function. ;;; (defstruct (template (:print-function %print-template) (:pure t)) ;; The symbol name of this VOP . This is used when printing the VOP and is ;; also used to provide a handle for definition and translation. (name nil :type symbol) ;; ;; A Function-Type describing the arg/result type restrictions. We compute ;; this from the Primitive-Type restrictions to make life easier for IR1 phases that need to anticipate LTN 's template selection . (type (required-argument) :type function-type) ;; ;; Lists of restrictions on the argument and result types. A restriction may ;; take several forms: ;; -- The restriction * is no restriction at all. ;; -- A restriction (:OR <primitive-type>*) means that the operand must have one of the specified primitive types . ;; -- A restriction (:CONSTANT <predicate> <type-spec>) means that the ;; argument (not a result) must be a compile-time constant that satisfies ;; the specified predicate function. In this case, the constant value ;; will be passed as an info argument rather than as a normal argument. ;; <type-spec> is a Lisp type specifier for the type tested by the ;; predicate, used when we want to represent the type constraint as a Lisp ;; function type. ;; ;; If Result-Types is :Conditional, then this is an IF-xxx style conditional that yeilds its result as a control transfer . The emit function takes two ;; info arguments: the target label and a boolean flag indicating whether to ;; negate the sense of the test. (arg-types nil :type list) (result-types nil :type (or list (member :conditional))) ;; ;; The primitive type restriction applied to each extra argument or result following the fixed operands . If NIL , no extra args / results are allowed . ;; Otherwise, either * or a (:OR ...) list as described for the ;; {ARG,RESULT}-TYPES. (more-args-type nil :type (or (member nil *) cons)) (more-results-type nil :type (or (member nil *) cons)) ;; ;; If true, this is a function that is called with no arguments to see if ;; this template can be emitted. This is used to conditionally compile for different target hardware configuarations ( e.g. FP hardware . ) (guard nil :type (or function null)) ;; ;; The policy under which this template is the best translation. Note that LTN might use this template under other policies if it ca n't figure our ;; anything better to do. (policy (required-argument) :type policies) ;; ;; The base cost for this template, given optimistic assumptions such as no ;; operand loading, etc. (cost (required-argument) :type index) ;; If true , then a short noun - like phrase describing what this VOP " does " , ;; i.e. the implementation strategy. This is for use in efficiency notes. (note nil :type (or string null)) ;; The number of trailing arguments to VOP or % Primitive that we bundle into ;; a list and pass into the emit function. This provides a way to pass ;; uninterpreted stuff directly to the code generator. (info-arg-count 0 :type index) ;; ;; A function that emits the VOPs for this template. Arguments: 1 ] Node for source context . 2 ] IR2 - Block that we place the VOP in . 3 ] This structure . 4 ] Head of argument TN - Ref list . 5 ] Head of result TN - Ref list . 6 ] If Info - Arg - Count is non - zero , then a list of the magic arguments . ;; Two values are returned : the first and last VOP emitted . This vop sequence must be linked into the VOP Next / Prev chain for the block . At least one VOP is always emitted . (emit-function (required-argument) :type function) ;; ;; The text domain for the note. (note-domain intl::*default-domain* :type (or string null))) (defprinter template name arg-types result-types (more-args-type :test more-args-type :prin1 more-args-type) (more-results-type :test more-results-type :prin1 more-results-type) policy cost (note :test note) (info-arg-count :test (not (zerop info-arg-count)))) ;;; The VOP-Info structure holds the constant information for a given virtual operation . We include Template so functions with a direct VOP equivalent ;;; can be translated easily. ;;; (defstruct (vop-info (:include template) (:print-function %print-template) (:make-load-form-fun :ignore-it)) ;; Side - effects of this VOP and side - effects that affect the value of this VOP . (effects (required-argument) :type attributes) (affected (required-argument) :type attributes) ;; If true , causes special casing of TNs live after this VOP that are n't ;; results: -- If T , all such TNs that are allocated in a SC with a defined save - sc will be saved in a TN in the save SC before the VOP and restored after the VOP . This is used by call VOPs . A bit vector representing the live TNs is stored in the VOP - SAVE - SET . ;; -- If :Force-To-Stack, all such TNs will made into :Environment TNs and ;; forced to be allocated in SCs without any save-sc. This is used by NLX ;; entry vops. ;; -- If :Compute-Only, just compute the save set, don't do any saving. This ;; is used to get the live variables for debug info. ;; (save-p nil :type (member t nil :force-to-stack :compute-only)) ;; ;; Info for automatic emission of move-arg VOPs by representation selection. If NIL , then do nothing special . If non - null , then there must be a more ;; arg. Each more arg is moved to its passing location using the appropriate representation - specific move - argument VOP . The first ( fixed ) argument ;; must be the control-stack frame pointer for the frame to move into. The ;; first info arg is the list of passing locations. ;; ;; Additional constraints depend on the value: ;; ;; :FULL-CALL ;; None. ;; ;; :LOCAL-CALL The second ( fixed ) arg is the NFP for the called function ( from ;; ALLOCATE-FRAME.) ;; ;; :KNOWN-RETURN If needed , the old NFP is computed using COMPUTE - OLD - NFP . ;; (move-args nil :type (member nil :full-call :local-call :known-return)) ;; ;; A list of sc-vectors representing the loading costs of each fixed argument ;; and result. (arg-costs nil :type list) (result-costs nil :type list) ;; ;; If true, sc-vectors representing the loading costs for any more args and ;; results. (more-arg-costs nil :type (or sc-vector null)) (more-result-costs nil :type (or sc-vector null)) ;; Lists of sc - vectors mapping each SC to the SCs that we can load into . If a SC is directly acceptable to the VOP , then the entry is T. Otherwise , it is a list of the SC numbers of all the SCs that we can load into . This list will be empty if there is no load function which loads from that SC to an SC allowed by the operand SC restriction . (arg-load-scs nil :type list) (result-load-scs nil :type list) ;; If true , a function that is called with the VOP to do operand targeting . This is done by modifiying the TN - Ref - Target slots in the TN - Refs so that they point to other TN - Refs in the same VOP . (target-function nil :type (or null function)) ;; A function that emits assembly code for a use of this VOP when it is called with the VOP structure . Null if this VOP has no specified ;; generator (i.e. it exists only to be inherited by other VOPs.) (generator-function nil :type (or function null)) ;; ;; A list of things that are used to parameterize an inherited generator. ;; This allows the same generator function to be used for a group of VOPs ;; with similar implementations. (variant nil :type list) ;; ;; The number of arguments and results. Each regular arg/result counts as one , and all the more args / results together count as 1 . (num-args 0 :type index) (num-results 0 :type index) ;; Vector of the temporaries the vop needs . See emit - generic - vop in vmdef ;; for information on how the temps are encoded. (temps nil :type (or null (simple-array (unsigned-byte 16) (*)))) ;; ;; The order all the refs for this vop should be put in. Each operand is ;; assigned a number in the following ordering: ;; args, more-args, results, more-results, temps ;; This vector represents the order the operands should be put into in the ;; next-ref link. (ref-ordering nil :type (or null (simple-array (unsigned-byte 8) (*)))) ;; ;; Array of the various targets that should be done. Each element encodes ;; the source ref (shifted 8) and the dest ref index. (targets nil :type (or null (simple-array (unsigned-byte 16) (*))))) ;;;; SBs and SCs: (eval-when (compile load eval) The SB structure represents the global information associated with a ;;; storage base. ;;; (defstruct (sb (:print-function %print-sb) (:make-load-form-fun :just-dump-it-normally)) ;; ;; Name, for printing and reference. (name nil :type symbol) ;; ;; The kind of storage base (which determines the packing algorithm). (kind :non-packed :type (member :finite :unbounded :non-packed)) ;; The number of elements in the SB . If finite , this is the total size . If unbounded , this is the size that the SB is initially allocated at . (size 0 :type index)) (defprinter sb name) ;;; The Finite-SB structure holds information needed by the packing algorithm ;;; for finite SBs. ;;; (defstruct (finite-sb (:include sb) (:print-function %print-sb)) ;; ;; ;; The number of locations currently allocated in this SB. (current-size 0 :type index) ;; ;; The last location packed in, used by pack to scatter TNs to prevent a few ;; locations from getting all the TNs, and thus getting overcrowded, reducing ;; the possiblilities for targeting. (last-offset 0 :type index) ;; A vector containing , for each location in this SB , a vector indexed by IR2 block numbers , holding local conflict bit vectors . A TN must not be packed in a given location within a particular block if the LTN number for that TN in that block corresponds to a set bit in the bit - vector . (conflicts '#() :type simple-vector) ;; A vector containing , for each location in this SB , a bit - vector indexed by ;; IR2 block numbers. If the bit corresponding to a block is set, then the ;; location is in use somewhere in the block, and thus has a conflict for ;; always-live TNs. (always-live '#() :type simple-vector) ;; A vector containing the TN currently live in each location in the SB , or NIL if the location is unused . This is used during load - tn pack . (live-tns '#() :type simple-vector) ;; The number of blocks for which the ALWAYS - LIVE and CONFLICTS might not be ;; virgin, and thus must be reinitialized when PACK starts. Less then the ;; length of those vectors when not all of the length was used on the ;; previously packed component. (last-block-count 0 :type index)) the SC structure holds the storage base that storage is allocated in and information used to select locations within the SB . ;;; (defstruct (sc (:print-function %print-sc)) ;; ;; Name, for printing and reference. (name nil :type symbol) ;; The number used to index SC cost vectors . (number 0 :type sc-number) ;; The storage base that this SC allocates storage from . (sb nil :type (or sb null)) ;; The size of elements in this SC , in units of locations in the SB . (element-size 0 :type index) ;; If our SB is finite , a list of the locations in this SC . (locations nil :type list) ;; A list of the alternate ( save ) SCs for this SC . (alternate-scs nil :type list) ;; A list of the constant SCs that can me moved into this SC . (constant-scs nil :type list) ;; True if this values in this SC needs to be saved across calls . (save-p nil :type boolean) ;; Vectors mapping from SC numbers to information about how to load from the index SC to this one . Move - Functions holds the names of the functions ;; used to do loading, and Load-Costs holds the cost of the corresponding Move - Functions . If loading is impossible , then the entries are NIL . Load - Costs is initialized to have a 0 for this SC . (move-functions (make-array sc-number-limit :initial-element nil) :type sc-vector) (load-costs (make-array sc-number-limit :initial-element nil) :type sc-vector) ;; Vector mapping from SC numbers to possibly representation - specific move and coerce VOPs . Each entry is a list of VOP - INFOs for VOPs that move / coerce an object in the index SC 's representation into this SC 's ;; representation. This vector is filled out with entries for all SCs that can somehow be coerced into this SC , not just those VOPs defined to directly move into this SC ( i.e. it allows for operand loading on the move VOP 's operands . ) ;; ;; When there are multiple applicable VOPs, the template arg and result type ;; restrictions are used to determine which one to use. The list is sorted by increasing cost , so the first applicable VOP should be used . ;; ;; Move (or move-arg) VOPs with descriptor results shouldn't have TNs wired ;; in the standard argument registers, since there may already be live TNs ;; wired in those locations holding the values that we are setting up for ;; unknown-values return. (move-vops (make-array sc-number-limit :initial-element nil) :type sc-vector) ;; The costs corresponding to the MOVE - VOPS . Separate because this info is ;; needed at meta-compile time, while the MOVE-VOPs don't exist till load time . If no move is defined , then the entry is NIL . (move-costs (make-array sc-number-limit :initial-element nil) :type sc-vector) ;; Similar to Move - VOPs , except that we only ever use the entries for this SC ;; and its alternates, since we never combine complex representation ;; conversion with argument passing. (move-arg-vops (make-array sc-number-limit :initial-element nil) :type sc-vector) ;; True if this SC or one of its alternates in in the NUMBER - STACK SB . (number-stack-p nil :type boolean) ;; ;; Alignment restriction. The offset must be an even multiple of this. (alignment 1 :type (and index (integer 1))) ;; ;; A list of locations that we avoid packing in during normal register ;; allocation to ensure that these locations will be free for operand ;; loading. This prevents load-TN packing from thrashing by spilling a lot. (reserve-locations nil :type list)) (defprinter sc name) ); eval-when (compile load eval) ;;;; TNs: (defstruct (tn (:include sset-element) (:constructor make-random-tn) (:constructor really-make-tn (number kind primitive-type sc)) (:print-function %print-tn)) ;; The kind of TN this is : ;; ;; :Normal A normal , non - constant TN , representing a variable or temporary . ;; Lifetime information is computed so that packing can be done. ;; ;; :Environment A TN that has hidden references ( debugger or NLX ) , and thus must be ;; allocated for the duration of the environment it is referenced in. ;; ;; :DEBUG-ENVIRONMENT ;; Like :ENVIRONMENT, but is used for TNs that we want to be able to ;; target to/from and that don't absolutely have to be live ;; everywhere. These TNs are live in all blocks in the environment that do n't reference this TN . ;; ;; :Component A TN that implicitly conflicts with all other TNs . No conflict ;; info is computed. ;; ;; :Save ;; :Save-Once A TN used for saving a : Normal TN across function calls . The lifetime information slots are unitialized : get the original TN our of the SAVE - TN slot and use it for conflicts . Save - Once is like ;; :Save, except that it is only save once at the single writer of the original TN . ;; ;; :SPECIFIED-SAVE A TN that was explicitly specified as the save TN for another TN . ;; When we actually get around to doing the saving, this will be changed to : SAVE or : SAVE - ONCE . ;; ;; :Load ;; A load-TN used to compute an argument or result that is restricted to some finite SB . Load TNs do n't have any conflict information . ;; Load TN pack uses a special local conflict determination method. ;; ;; :Constant Represents a constant , with TN - Leaf a Constant leaf . Lifetime ;; information isn't computed, since the value isn't allocated by ;; pack, but is instead generated as a load at each use. Since lifetime analysis is n't done on : , they do n't have ;; Local-Numbers and similar stuff. ;; ;; :ALIAS A special kind of TN used to represent initialization of local call ;; arguments in the caller. It provides another name for the argument ;; TN so that lifetime analysis doesn't get confused by self-recursive calls . Lifetime analysis treats this the same as : NORMAL , but then at the end merges the conflict info into the original TN and replaces all uses of the alias with the original TN . SAVE - TN holds the aliased TN . ;; (kind (required-argument) :type (member :normal :environment :debug-environment :save :save-once :specified-save :load :constant :component :alias)) ;; The primitive - type for this TN 's value . Null in restricted or wired TNs . (primitive-type nil :type (or primitive-type null)) ;; If this TN represents a variable or constant , then this is the corresponding Leaf . (leaf nil :type (or leaf null)) ;; ;; Thread that links TNs together so that we can find them. (next nil :type (or tn null)) ;; Head of TN - Ref lists for reads and writes of this TN . (reads nil :type (or tn-ref null)) (writes nil :type (or tn-ref null)) ;; A link we use when building various temporary TN lists . (next* nil :type (or tn null)) ;; Some block that contains a reference to this TN , or Nil if we have n't seen any reference yet . If the TN is local , then this is the block it is local ;; to. (local nil :type (or ir2-block null)) ;; If a local TN , the block relative number for this TN . Global TNs whose ;; liveness changes within a block are also assigned a local number during the conflicts analysis of that block . If the TN has no local number within the block , then this is . (local-number nil :type (or local-tn-number null)) ;; If a local TN , a bit - vector with 1 for the local - number of every TN that ;; we conflict with. (local-conflicts (make-array local-tn-limit :element-type 'bit :initial-element 0) :type local-tn-bit-vector) ;; Head of the list of Global - Conflicts structures for a global TN . This list is sorted by block number ( i.e. reverse DFO ) , allowing the intersection between the lifetimes for two global TNs to be easily found . If null , then this TN is a local TN . (global-conflicts nil :type (or global-conflicts null)) ;; ;; During lifetime analysis, this is used as a pointer into the conflicts chain , for scanning through blocks in reverse DFO . (current-conflict nil) ;; In a : Save TN , this is the TN saved . In a : Normal or : Environment TN , this is the associated save TN . In TNs with no save TN , this is null . (save-tn nil :type (or tn null)) ;; After pack , the SC we packed into . Beforehand , the SC we want to pack ;; into, or null if we don't know. (sc nil :type (or sc null)) ;; The offset within the SB that this TN is packed into . This is what indicates that the TN is packed . (offset nil :type (or index null)) ;; Some kind of info about how important this TN is . (cost 0 :type fixnum) ;; ;; If a :ENVIRONMENT or :DEBUG-ENVIRONMENT TN, this is the environment that the TN is live throughout . (environment nil :type (or environment null)) The depth of the deepest loop that this TN is used in . (loop-depth 0 :type fixnum)) (defun %print-tn (s stream d) (declare (ignore d)) (write-string "#<TN " stream) (print-tn s stream) (write-char #\> stream)) The Global - Conflicts structure represents the conflicts for global TNs . Each global TN has a list of these structures , one for each block that it ;;; is live in. In addition to representing the result of lifetime analysis, the ;;; global conflicts structure is used during lifetime analysis to represent the set of TNs live at the start of the IR2 block . ;;; (defstruct (global-conflicts (:constructor really-make-global-conflicts (kind tn block number)) (:print-function %print-global-conflicts)) ;; The IR2 - Block that this structure represents the conflicts for . (block (required-argument) :type ir2-block) ;; Thread running through all the Global - Conflict for Block . This thread is sorted by TN number . (next nil :type (or global-conflicts null)) ;; The way that TN is used by Block : ;; ;; :Read The TN is read before it is written . It starts the block live , but ;; is written within the block. ;; ;; :Write The TN is written before any read . It starts the block dead , and ;; need not have a read within the block. ;; ;; :Read-Only The TN is read , but never written . It starts the block live , and is not killed by the block . Lifetime analysis will promote ;; :Read-Only TNs to :Live if they are live at the block end. ;; ;; :Live The TN is not referenced . It is live everywhere in the block . ;; (kind :read-only :type (member :read :write :read-only :live)) ;; A local conflicts vector representing conflicts with TNs live in Block . The index for the local TN number of each TN we conflict with in this block is 1 . To find the full conflict set , the : Live TNs for Block must ;; also be included. This slot is not meaningful when Kind is :Live. (conflicts (make-array local-tn-limit :element-type 'bit :initial-element 0) :type local-tn-bit-vector) ;; The TN we are recording conflicts for . (tn (required-argument) :type tn) ;; Thread through all the Global - Conflicts for TN . (tn-next nil :type (or global-conflicts null)) ;; TN 's local TN number in Block . : Live TNs do n't have local numbers . (number nil :type (or local-tn-number null))) (defprinter global-conflicts tn block kind (number :test number))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/vop.lisp
lisp
-*- Package: C; Log: C.Log -*- ********************************************************************** ********************************************************************** in the compiler, IR2. The largest number of TNs whose liveness changes that we can have in any block. The different policies we can use to determine the coding strategy. Eval-When (Compile Load Eval) Primitive types: The primitive type is used to represent the aspects of type interesting the primitive types of the operands, and the primitive type of a value is used to constrain the possible representations of that value. The name of this primitive-type. allocated in. The Lisp type equivalent to this type. If this type could never be The template used to check that an object is of this type. This is the argument is of the correct type, then it is delivered into the result. If the type is incorrect, then an error is signalled. eval-when (compile load eval) IR1 annotations used for IR2 conversion: Block-Info head and tail are dummy IR2 blocks that begin and end the emission order thread. Component-Info used won't have any. should be saved after the binding is instantiated. Environment-Info If an XEP lambda, then the corresponding Entry-Info structure. :FULL if this is definitely a full call. :FUNNY if this is a random thing with IR2-convert. :LOCAL if this is a local call. Node-Tail-P truly tail recursive. The IR2-Block structure holds information about a block that is used during and after IR2 conversion. It is stored in the Block-Info slot for the associated block. blocks are split. This is assigned by lifetime analysis. Information about unknown-values continuations that is used by stack analysis to do stack simulation. A unknown-values continuation is Pushed if it's Dest is in another block. Similarly, a continuation is Popped if are in the order that are pushed/popped in the block. Note that the args The result of stack analysis: lists of all the unknown-values continuations on the stack at the block start and end, topmost null. Number of local TNs actually allocated. indicating that that number is unused. (This allows us to delete local assigned distinct LTN numbers. In this case, we assign all the more args this, since more operands are referenced simultaneously as far as conflict analysis is concerned. Note that all these :More TNs will be global TNs. Bit-vectors used during lifetime analysis to keep track of references to in Written if it is ever written in the block, and in Live-Out if account all TNs that aren't :Live. A thread running through the global-conflicts structures for this block, The assembler label that points to the beginning of the code for this block. Null when we haven't assigned a label yet. List of Location-Info structures describing all the interesting (to the debugger) locations in this block. If this is :Delayed, then this is a single value continuation for which the evaluation of the use is to be postponed until the evaluation of destination. This can be done for ref nodes or predicates whose destination is an IF. If this is :Fixed, then this continuation has a fixed number of values, If this is :Unknown, then this is an unknown-values continuation, using If this is :Unused, then this continuation should never actually be used as the destination of a value: it is only used tail-recursively. restriction on delayed references. In multiple-value contexts, this is null to indicate that it is meaningless. This is always (primitive-type (continuation-type cont)), which may be more restrictive than the any possible type that could be computed (before type checking.) Locations used to hold the values of the continuation. If the number values glob and the number of values. Note that since type checking is the responsibility of the values receiver, these TNs primitive type is only based on the proven type information. the component being compiled. Normal-TNs is the head of the list of all the normal TNs that need to be allocate them so that Pack can find them. possible). may eventually be converted to :Cached-Constant normal TNs. A list of all the :COMPONENT TNs (live throughout the component.) These TNs will also appear in the {NORMAL,RESTRICTED,WIRED} TNs as appropriate to their location. If this component has a NFP, then this is it. A list of the explicitly specified save TNs (kind :SPECIFIED-SAVE). These TNs will also appear in the {NORMAL,RESTRICTED,WIRED} TNs as appropriate to their location. An adjustable vector that records all the constants in the constant pool. element 0, etc. Normal constants are represented by the placing the Constant leaf in this vector. A load-time constant is distinguished by being a cons (Kind . What). Kind is a keyword indicating how the constant is computed, and What is some context. These load-time constants are recognized: (:entry . <function>) Is replaced by the code pointer for the specified function. This is it 's Leaf - Info should be an Entry-Info structure. (:label . <label>) Is replaced with the byte offset of that label from the start of the code vector (including the header length.) A null entry in this vector is a placeholder for implementation overhead that is eventually stuffed in somehow. Some kind of info about the component's run-time representation. This is this component. Filled in by entry analysis. Spilled-VOPs is a hashtable translating from "interesting" VOPs to a list spilled, providing a representation that is more convenient some places. setup-dynamic-count-info. (But only if we are generating code to collect dynamic statistics.) conversion may need to compile a forward reference. In this case the slots aren't actually initialized until entry analysis runs. True if this function has a non-null closure environment. A label pointing to the entry vector for this function. Null until ENTRY-ANALYZE runs. that is intended to be informative. A string representing the argument list that the function was defined with. A function type specifier representing the arguments and results of this function. The TNs that hold the passed environment within the function. This is an the corresponding value within this function. This list is in the same order as the ENVIRONMENT-CLOSURE. The TNs that hold the Old-Fp and Return-PC within the function. We always save these so that the debugger can do a backtrace, even if the function has no return (and thus never uses them). Null only temporarily. The passing location for the Return-PC. The return PC is treated differently from the other arguments, since in some implementations we may use a call instruction that requires the return PC to be passed in a particular place. True if this function has a frame on the number stack. This is set by representation selection whenever it is possible that some function in our tail set will make use of the number stack. A list of all the :Environment TNs live in this environment. A list of all the :Debug-Environment TNs live in this environment. A label that marks the start of elsewhere code for this function. Null source map. environment is properly initialized, i.e. arguments moved from their passing locations, etc. This is the start of the function as far as the debugger is concerned. and locations for all the functions in a given Tail-Set. It is stored in The return convention used: -- If :Unknown, we use the standard return convention. -- If :Fixed, we use the known-values convention. The number of values returned, or :Unknown if we don't know. Count may be known when Kind is :Unknown, since we may choose the standard return convention for other reasons. If count isn't :Unknown, then this is a list of the primitive-types of each value. If kind is :Fixed, then this is the list of the TNs that we return the values in. If the kind is :Entry (a lexical exit), then in the home environment, this holds a Value-Cell object containing the unwind block pointer. In the other cases nobody directly references the unwind-block, so we leave this slot null. The saved control stack pointer. The Loop structure holds information about a loop. The kind of loop that this is. These values are legal: :Outer This is the outermost loop structure, and represents all the code in a component. :Natural :Strange A segment of a "strange loop" in a non-reducible flow graph. since there may be multiple back branches to the same head. A list of all the blocks in this loop or its inferiors that have a successor outside of the loop. The loop that this loop is nested within. This is null in the outermost loop structure. A list of the loops nested directly within this one. The head of the list of blocks directly within this loop. We must recurse on Inferiors to find all the blocks. VOPs and Templates: to the operation. VOPs evaluated after and before this one. Null at the beginning/end of the block, and temporarily during IR2 translation. Heads of the TN-Ref lists for operand TNs, linked using the Across slot. Head of the list of write refs for each explicitly allocated temporary, linked together using the Across slot. and a write) for each temporary. Local-TN bit vector representing the set of TNs live after args are read and before results are written. This is only filled in when The TN-Ref structure contains information about a particular reference to a True if this is a write reference, false if a read. write). the read points to the write, and vice-versa. Load TN allocated for this operand, if any. function. also used to provide a handle for definition and translation. A Function-Type describing the arg/result type restrictions. We compute this from the Primitive-Type restrictions to make life easier for IR1 Lists of restrictions on the argument and result types. A restriction may take several forms: -- The restriction * is no restriction at all. -- A restriction (:OR <primitive-type>*) means that the operand must have -- A restriction (:CONSTANT <predicate> <type-spec>) means that the argument (not a result) must be a compile-time constant that satisfies the specified predicate function. In this case, the constant value will be passed as an info argument rather than as a normal argument. <type-spec> is a Lisp type specifier for the type tested by the predicate, used when we want to represent the type constraint as a Lisp function type. If Result-Types is :Conditional, then this is an IF-xxx style conditional info arguments: the target label and a boolean flag indicating whether to negate the sense of the test. The primitive type restriction applied to each extra argument or result Otherwise, either * or a (:OR ...) list as described for the {ARG,RESULT}-TYPES. If true, this is a function that is called with no arguments to see if this template can be emitted. This is used to conditionally compile for The policy under which this template is the best translation. Note that anything better to do. The base cost for this template, given optimistic assumptions such as no operand loading, etc. i.e. the implementation strategy. This is for use in efficiency notes. a list and pass into the emit function. This provides a way to pass uninterpreted stuff directly to the code generator. A function that emits the VOPs for this template. Arguments: The text domain for the note. The VOP-Info structure holds the constant information for a given virtual can be translated easily. results: -- If :Force-To-Stack, all such TNs will made into :Environment TNs and forced to be allocated in SCs without any save-sc. This is used by NLX entry vops. -- If :Compute-Only, just compute the save set, don't do any saving. This is used to get the live variables for debug info. Info for automatic emission of move-arg VOPs by representation selection. arg. Each more arg is moved to its passing location using the appropriate must be the control-stack frame pointer for the frame to move into. The first info arg is the list of passing locations. Additional constraints depend on the value: :FULL-CALL None. :LOCAL-CALL ALLOCATE-FRAME.) :KNOWN-RETURN A list of sc-vectors representing the loading costs of each fixed argument and result. If true, sc-vectors representing the loading costs for any more args and results. generator (i.e. it exists only to be inherited by other VOPs.) A list of things that are used to parameterize an inherited generator. This allows the same generator function to be used for a group of VOPs with similar implementations. The number of arguments and results. Each regular arg/result counts as for information on how the temps are encoded. The order all the refs for this vop should be put in. Each operand is assigned a number in the following ordering: args, more-args, results, more-results, temps This vector represents the order the operands should be put into in the next-ref link. Array of the various targets that should be done. Each element encodes the source ref (shifted 8) and the dest ref index. SBs and SCs: storage base. Name, for printing and reference. The kind of storage base (which determines the packing algorithm). The Finite-SB structure holds information needed by the packing algorithm for finite SBs. The number of locations currently allocated in this SB. The last location packed in, used by pack to scatter TNs to prevent a few locations from getting all the TNs, and thus getting overcrowded, reducing the possiblilities for targeting. IR2 block numbers. If the bit corresponding to a block is set, then the location is in use somewhere in the block, and thus has a conflict for always-live TNs. virgin, and thus must be reinitialized when PACK starts. Less then the length of those vectors when not all of the length was used on the previously packed component. Name, for printing and reference. used to do loading, and Load-Costs holds the cost of the corresponding representation. This vector is filled out with entries for all SCs that When there are multiple applicable VOPs, the template arg and result type restrictions are used to determine which one to use. The list is sorted Move (or move-arg) VOPs with descriptor results shouldn't have TNs wired in the standard argument registers, since there may already be live TNs wired in those locations holding the values that we are setting up for unknown-values return. needed at meta-compile time, while the MOVE-VOPs don't exist till load and its alternates, since we never combine complex representation conversion with argument passing. Alignment restriction. The offset must be an even multiple of this. A list of locations that we avoid packing in during normal register allocation to ensure that these locations will be free for operand loading. This prevents load-TN packing from thrashing by spilling a lot. eval-when (compile load eval) TNs: :Normal Lifetime information is computed so that packing can be done. :Environment allocated for the duration of the environment it is referenced in. :DEBUG-ENVIRONMENT Like :ENVIRONMENT, but is used for TNs that we want to be able to target to/from and that don't absolutely have to be live everywhere. These TNs are live in all blocks in the environment :Component info is computed. :Save :Save-Once :Save, except that it is only save once at the single writer of the :SPECIFIED-SAVE When we actually get around to doing the saving, this will be :Load A load-TN used to compute an argument or result that is restricted Load TN pack uses a special local conflict determination method. :Constant information isn't computed, since the value isn't allocated by pack, but is instead generated as a load at each use. Since Local-Numbers and similar stuff. :ALIAS arguments in the caller. It provides another name for the argument TN so that lifetime analysis doesn't get confused by self-recursive Thread that links TNs together so that we can find them. to. liveness changes within a block are also assigned a local number during we conflict with. During lifetime analysis, this is used as a pointer into the conflicts into, or null if we don't know. If a :ENVIRONMENT or :DEBUG-ENVIRONMENT TN, this is the environment that is live in. In addition to representing the result of lifetime analysis, the global conflicts structure is used during lifetime analysis to represent :Read is written within the block. :Write need not have a read within the block. :Read-Only :Read-Only TNs to :Live if they are live at the block end. :Live also be included. This slot is not meaningful when Kind is :Live.
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . (ext:file-comment "$Header: src/compiler/vop.lisp $") Structures for the second ( virtual machine ) intermediate representation Written by (in-package "C") (intl:textdomain "cmucl") (export '(tn-ref tn-ref-p make-tn-ref tn-ref-tn tn-ref-write-p tn-ref-next tn-ref-vop tn-ref-next-ref tn-ref-across tn-ref-target tn-ref-load-tn sb sb-p sb-name sc sc-p sc-name sc-number sc-sb tn tn-p make-random-tn tn-sc tn-offset Call.lisp and core.lisp need to get at these slots . ir2-component-constants ir2-environment-number-stack-p needs these . ir2-component-dyncount-info ir2-block-block vop-block)) (eval-when (compile load eval) (defconstant local-tn-limit 64) (deftype local-tn-number () `(integer 0 (,local-tn-limit))) (deftype local-tn-count () `(integer 0 ,local-tn-limit)) (deftype local-tn-vector () `(simple-vector ,local-tn-limit)) (deftype local-tn-bit-vector () `(simple-bit-vector ,local-tn-limit)) Type of an SC number . (deftype sc-number () `(integer 0 (,sc-number-limit))) Types for vectors indexed by SC numbers . (deftype sc-vector () `(simple-vector ,sc-number-limit)) (deftype sc-bit-vector () `(simple-bit-vector ,sc-number-limit)) (deftype policies () '(member :safe :small :fast :fast-safe)) to the VM . Selection of IR2 translation templates is done on the basis of (eval-when (compile load eval) (defstruct (primitive-type (:print-function %print-primitive-type)) (name nil :type symbol) A list the SC numbers for all the SCs that a TN of this type can be (scs nil :type list) returned by Primitive - Type , then this is the NIL ( or empty ) type . (type (required-argument) :type ctype) a template of one argument and one result , both of primitive - type T. If (check nil :type (or template null))) (defprinter primitive-type name (type :test (and type (not (eq (type-specifier type) (primitive-type-name structure)))) :prin1 (type-specifier type))) Holds the IR2 - Block structure . If there are overflow blocks , then this points to the first IR2 - Block . The Block - Info of the dummy component Holds the IR2 - Component structure . Continuation - Info Holds the IR2 - Continuation structure . Continuations whose values are n't Cleanup - Info If non - null , then a TN in which the affected dynamic environment pointer Holds the IR2 - Environment structure . Tail - Set - Info Holds the Return - Info structure . NLX - Info - Info Holds the IR2 - NLX - Info structure . Leaf - Info If a non - set lexical variable , the TN that holds the value in the home environment . If a constant , then the corresponding constant TN . Basic - Combination - Info The template chosen by LTN , or After LTN analysis , this is true only in combination nodes that are (defstruct (ir2-block (:include block-annotation) (:constructor really-make-ir2-block (block)) (:print-function %print-ir2-block)) The IR2 - Block 's number , which differs from Block 's Block - Number if any (number nil :type (or index null)) its Dest is in this block but has its uses elsewhere . The continuations to a single MV - Combination appear reversed in Popped , since we must effectively pop the last argument first . All pops must come before all pushes ( although internal MV uses may be interleaved . ) Popped is computed by LTN , and Pushed is computed by stack analysis . (pushed () :type list) (popped () :type list) continuation first . (start-stack () :type list) (end-stack () :type list) The first and last VOP in this block . If there are none , both slots are (start-vop nil :type (or vop null)) (last-vop nil :type (or vop null)) (local-tn-count 0 :type local-tn-count) A vector that maps local TN numbers to TNs . Some entries may be NIL , conflict information without compressing the LTN numbers . ) If an entry is : More , then this block contains only a single VOP . This VOP has so many more arguments and/or results that they can not all be one LTN number , and all the more results another LTN number . We can do (local-tns (make-array local-tn-limit) :type local-tn-vector) local TNs . When indexed by the LTN number , the index for a TN is non - zero the first reference is a read . (written (make-array local-tn-limit :element-type 'bit :initial-element 0) :type local-tn-bit-vector) (live-out (make-array local-tn-limit :element-type 'bit) :type local-tn-bit-vector) Similar to the above , but is updated by lifetime flow analysis to have a 1 for LTN numbers of TNs live at the end of the block . This takes into (live-in (make-array local-tn-limit :element-type 'bit :initial-element 0) :type local-tn-bit-vector) sorted by TN number . (global-tns nil :type (or global-conflicts null)) (%label nil) (locations nil :type list)) (defprinter ir2-block (pushed :test pushed) (popped :test popped) (start-vop :test start-vop) (last-vop :test last-vop) (local-tn-count :test (not (zerop local-tn-count))) (%label :test %label)) The IR2 - Continuation structure is used to annotate continuations that are used as a function result continuation or that receive MVs . (defstruct (ir2-continuation (:constructor make-ir2-continuation (primitive-type)) (:print-function %print-ir2-continuation)) with the TNs in . the passing locations in Locs . (kind :fixed :type (member :delayed :fixed :unknown :unused)) The primitive - type of the first value of this continuation . This is primarily for internal use during LTN , but it also records the type tn - primitive - type of the value TN . This is becase the value TN must hold (primitive-type nil :type (or primitive-type null)) of values if fixed , then there is one TN per value . If the number of values is unknown , then this is a two - list of TNs holding the start of the (locs nil :type list)) (defprinter ir2-continuation kind primitive-type locs) The IR2 - Component serves mostly to accumulate non - code information about (defstruct ir2-component The counter used to allocate global TN numbers . (global-tn-counter 0 :type index) packed , linked through the Next slot . We place TNs on this list when we Restricted - TNs are TNs that must be packed within a finite SC . We pack these TNs first to ensure that the restrictions will be satisfied ( if Wired - TNs are TNs that must be packed at a specific location . The SC and Offset are already filled in . Constant - TNs are non - packed TNs that represent constants . : (normal-tns nil :type (or tn null)) (restricted-tns nil :type (or tn null)) (wired-tns nil :type (or tn null)) (constant-tns nil :type (or tn null)) (component-tns () :type list) (nfp nil :type (or tn null)) (specified-save-tns () :type list) Values - Receivers is a list of all the blocks whose ir2 - block has a non - null value for Popped . This slot is initialized by LTN - Analyze as an input to Stack - Analyze . (values-receivers nil :type list) A non - immediate : with offset 0 refers to the constant in how compiled code ( including DEFUN ) gets its hands on a function . (constants (make-array 10 :fill-pointer 0 :adjustable t) :type vector) filled in by the VM supplied Select - Component - Format function . format A list of the Entry - Info structures describing all of the entries into (entries nil :type list) Head of the list of : ALIAS TNs in this component , threaded by TN - NEXT . (alias-tns nil :type (or tn null)) of the TNs spilled at that VOP . This is used when computing debug info so that we do n't consider the TN 's value to be valid when it is in fact somewhere else . Spilled - TNs has T for every " interesting " TN that is ever (spilled-vops (make-hash-table :test #'eq) :type hash-table) (spilled-tns (make-hash-table :test #'eq) :type hash-table) Dynamic vop count info . This is needed by both ir2 - convert and (dyncount-info nil :type (or null dyncount-info))) The Entry - Info structure condenses all the information that the dumper needs to create each XEP 's function entry data structure . The Entry - Info structures are somtimes created before they are initialized , since ir2 (defstruct entry-info (closure-p nil :type boolean) (offset nil :type (or label null)) If this function was defined using DEFUN , then this is the name of the function , a symbol or ( SETF < symbol > ) . Otherwise , this is some string (name "<not computed>" :type (or simple-string list symbol)) (arguments nil :type (or simple-string null)) (type 'function :type (or list (member function)))) The IR2 - Environment is used to annotate non - let lambdas with their passing locations . It is stored in the Environment - Info . (defstruct (ir2-environment (:print-function %print-ir2-environment)) alist translating from the NLX - Info or lambda - var to the TN that holds (environment nil :type list) (old-fp nil :type (or tn null)) (return-pc nil :type (or tn null)) (return-pc-pass (required-argument) :type tn) (number-stack-p nil :type boolean) (live-tns nil :type list) (debug-live-tns nil :type list) until this label is assigned by codegen . Used for maintaining the debug (elsewhere-start nil :type (or label null)) A label that marks the first location in this function at which the (environment-start nil :type (or label null))) (defprinter ir2-environment environment old-fp return-pc return-pc-pass) The Return - Info structure is used by to represent the return strategy the Tail - Set - Info . (defstruct (return-info (:print-function %print-return-info)) (kind (required-argument) :type (member :fixed :unknown)) (count (required-argument) :type (or index (member :unknown))) (types () :type list) (locations () :type list)) (defprinter return-info kind count types locations) (defstruct (ir2-nlx-info (:print-function %print-ir2-nlx-info)) (home nil :type (or tn null)) (save-sp (required-argument) :type tn) The list of dynamic state save TNs . (dynamic-state (list* (make-stack-pointer-tn) (make-dynamic-state-tns)) :type list) The target label for NLX entry . (target (gen-label) :type label)) (defprinter ir2-nlx-info home save-sp dynamic-state) (defstruct (cloop (:print-function %print-loop) (:conc-name loop-) (:predicate loop-p) (:constructor make-loop) (:copier copy-loop)) A normal loop with only one entry . (kind (required-argument) :type (member :outer :natural :strange)) The first and last blocks in the loop . There may be more than one tail , (head nil :type (or cblock null)) (tail nil :type list) (exits nil :type list) (superior nil :type (or cloop null)) (inferiors nil :type list) (depth 0 :type fixnum) (blocks nil :type (or null cblock))) (defprinter loop kind head tail exits) A VOP is a Virtual Operation . It represents an operation and the operands (defstruct (vop (:print-function %print-vop) (:constructor really-make-vop (block node info args results))) VOP - Info structure containing static info about the operation . (info nil :type (or vop-info null)) The IR2 - Block this VOP is in . (block (required-argument) :type ir2-block) (next nil :type (or vop null)) (prev nil :type (or vop null)) (args nil :type (or tn-ref null)) (results nil :type (or tn-ref null)) (temps nil :type (or tn-ref null)) Head of the list of all TN - refs for references in this VOP , linked by the Next - Ref slot . There will be one entry for each operand and two ( a read (refs nil :type (or tn-ref null)) Stuff that is passed uninterpreted from IR2 conversion to codegen . The meaning of this slot is totally dependent on the VOP . codegen-info Node that generated this VOP , for keeping track of debug info . (node nil :type (or node null)) VOP - INFO - SAVE - P is non - null . (save-set nil :type (or local-tn-bit-vector null))) (defprinter vop (info :prin1 (vop-info-name info)) args results (codegen-info :test codegen-info)) TN . The information in the TN - Refs largely determines how TNs are packed . (defstruct (tn-ref (:print-function %print-tn-ref) (:constructor really-make-tn-ref (tn write-p))) The TN referenced . (tn (required-argument) :type tn) (write-p nil :type boolean) Thread running through all TN - Refs for this TN of the same kind ( read or (next nil :type (or tn-ref null)) The VOP where the reference happens . The this is null only temporarily . (vop nil :type (or vop null)) Thread running through all TN - Refs in VOP , in reverse order of reference . (next-ref nil :type (or tn-ref null)) Thread the TN - Refs in VOP of the same kind ( argument , result , temp ) . (across nil :type (or tn-ref null)) If true , this is a TN - Ref also in VOP whose TN we would like packed in the same location as our TN . Read and write refs are always paired : Target in (target nil :type (or null tn-ref)) (load-tn nil :type (or tn null))) (defprinter tn-ref tn write-p (vop :test vop :prin1 (vop-info-name (vop-info vop)))) The Template represents a particular IR2 coding strategy for a known (defstruct (template (:print-function %print-template) (:pure t)) The symbol name of this VOP . This is used when printing the VOP and is (name nil :type symbol) phases that need to anticipate LTN 's template selection . (type (required-argument) :type function-type) one of the specified primitive types . that yeilds its result as a control transfer . The emit function takes two (arg-types nil :type list) (result-types nil :type (or list (member :conditional))) following the fixed operands . If NIL , no extra args / results are allowed . (more-args-type nil :type (or (member nil *) cons)) (more-results-type nil :type (or (member nil *) cons)) different target hardware configuarations ( e.g. FP hardware . ) (guard nil :type (or function null)) LTN might use this template under other policies if it ca n't figure our (policy (required-argument) :type policies) (cost (required-argument) :type index) If true , then a short noun - like phrase describing what this VOP " does " , (note nil :type (or string null)) The number of trailing arguments to VOP or % Primitive that we bundle into (info-arg-count 0 :type index) 1 ] Node for source context . 2 ] IR2 - Block that we place the VOP in . 3 ] This structure . 4 ] Head of argument TN - Ref list . 5 ] Head of result TN - Ref list . 6 ] If Info - Arg - Count is non - zero , then a list of the magic arguments . Two values are returned : the first and last VOP emitted . This vop sequence must be linked into the VOP Next / Prev chain for the block . At least one VOP is always emitted . (emit-function (required-argument) :type function) (note-domain intl::*default-domain* :type (or string null))) (defprinter template name arg-types result-types (more-args-type :test more-args-type :prin1 more-args-type) (more-results-type :test more-results-type :prin1 more-results-type) policy cost (note :test note) (info-arg-count :test (not (zerop info-arg-count)))) operation . We include Template so functions with a direct VOP equivalent (defstruct (vop-info (:include template) (:print-function %print-template) (:make-load-form-fun :ignore-it)) Side - effects of this VOP and side - effects that affect the value of this VOP . (effects (required-argument) :type attributes) (affected (required-argument) :type attributes) If true , causes special casing of TNs live after this VOP that are n't -- If T , all such TNs that are allocated in a SC with a defined save - sc will be saved in a TN in the save SC before the VOP and restored after the VOP . This is used by call VOPs . A bit vector representing the live TNs is stored in the VOP - SAVE - SET . (save-p nil :type (member t nil :force-to-stack :compute-only)) If NIL , then do nothing special . If non - null , then there must be a more representation - specific move - argument VOP . The first ( fixed ) argument The second ( fixed ) arg is the NFP for the called function ( from If needed , the old NFP is computed using COMPUTE - OLD - NFP . (move-args nil :type (member nil :full-call :local-call :known-return)) (arg-costs nil :type list) (result-costs nil :type list) (more-arg-costs nil :type (or sc-vector null)) (more-result-costs nil :type (or sc-vector null)) Lists of sc - vectors mapping each SC to the SCs that we can load into . If a SC is directly acceptable to the VOP , then the entry is T. Otherwise , it is a list of the SC numbers of all the SCs that we can load into . This list will be empty if there is no load function which loads from that SC to an SC allowed by the operand SC restriction . (arg-load-scs nil :type list) (result-load-scs nil :type list) If true , a function that is called with the VOP to do operand targeting . This is done by modifiying the TN - Ref - Target slots in the TN - Refs so that they point to other TN - Refs in the same VOP . (target-function nil :type (or null function)) A function that emits assembly code for a use of this VOP when it is called with the VOP structure . Null if this VOP has no specified (generator-function nil :type (or function null)) (variant nil :type list) one , and all the more args / results together count as 1 . (num-args 0 :type index) (num-results 0 :type index) Vector of the temporaries the vop needs . See emit - generic - vop in vmdef (temps nil :type (or null (simple-array (unsigned-byte 16) (*)))) (ref-ordering nil :type (or null (simple-array (unsigned-byte 8) (*)))) (targets nil :type (or null (simple-array (unsigned-byte 16) (*))))) (eval-when (compile load eval) The SB structure represents the global information associated with a (defstruct (sb (:print-function %print-sb) (:make-load-form-fun :just-dump-it-normally)) (name nil :type symbol) (kind :non-packed :type (member :finite :unbounded :non-packed)) The number of elements in the SB . If finite , this is the total size . If unbounded , this is the size that the SB is initially allocated at . (size 0 :type index)) (defprinter sb name) (defstruct (finite-sb (:include sb) (:print-function %print-sb)) (current-size 0 :type index) (last-offset 0 :type index) A vector containing , for each location in this SB , a vector indexed by IR2 block numbers , holding local conflict bit vectors . A TN must not be packed in a given location within a particular block if the LTN number for that TN in that block corresponds to a set bit in the bit - vector . (conflicts '#() :type simple-vector) A vector containing , for each location in this SB , a bit - vector indexed by (always-live '#() :type simple-vector) A vector containing the TN currently live in each location in the SB , or NIL if the location is unused . This is used during load - tn pack . (live-tns '#() :type simple-vector) The number of blocks for which the ALWAYS - LIVE and CONFLICTS might not be (last-block-count 0 :type index)) the SC structure holds the storage base that storage is allocated in and information used to select locations within the SB . (defstruct (sc (:print-function %print-sc)) (name nil :type symbol) The number used to index SC cost vectors . (number 0 :type sc-number) The storage base that this SC allocates storage from . (sb nil :type (or sb null)) The size of elements in this SC , in units of locations in the SB . (element-size 0 :type index) If our SB is finite , a list of the locations in this SC . (locations nil :type list) A list of the alternate ( save ) SCs for this SC . (alternate-scs nil :type list) A list of the constant SCs that can me moved into this SC . (constant-scs nil :type list) True if this values in this SC needs to be saved across calls . (save-p nil :type boolean) Vectors mapping from SC numbers to information about how to load from the index SC to this one . Move - Functions holds the names of the functions Move - Functions . If loading is impossible , then the entries are NIL . Load - Costs is initialized to have a 0 for this SC . (move-functions (make-array sc-number-limit :initial-element nil) :type sc-vector) (load-costs (make-array sc-number-limit :initial-element nil) :type sc-vector) Vector mapping from SC numbers to possibly representation - specific move and coerce VOPs . Each entry is a list of VOP - INFOs for VOPs that move / coerce an object in the index SC 's representation into this SC 's can somehow be coerced into this SC , not just those VOPs defined to directly move into this SC ( i.e. it allows for operand loading on the move VOP 's operands . ) by increasing cost , so the first applicable VOP should be used . (move-vops (make-array sc-number-limit :initial-element nil) :type sc-vector) The costs corresponding to the MOVE - VOPS . Separate because this info is time . If no move is defined , then the entry is NIL . (move-costs (make-array sc-number-limit :initial-element nil) :type sc-vector) Similar to Move - VOPs , except that we only ever use the entries for this SC (move-arg-vops (make-array sc-number-limit :initial-element nil) :type sc-vector) True if this SC or one of its alternates in in the NUMBER - STACK SB . (number-stack-p nil :type boolean) (alignment 1 :type (and index (integer 1))) (reserve-locations nil :type list)) (defprinter sc name) (defstruct (tn (:include sset-element) (:constructor make-random-tn) (:constructor really-make-tn (number kind primitive-type sc)) (:print-function %print-tn)) The kind of TN this is : A normal , non - constant TN , representing a variable or temporary . A TN that has hidden references ( debugger or NLX ) , and thus must be that do n't reference this TN . A TN that implicitly conflicts with all other TNs . No conflict A TN used for saving a : Normal TN across function calls . The lifetime information slots are unitialized : get the original TN our of the SAVE - TN slot and use it for conflicts . Save - Once is like original TN . A TN that was explicitly specified as the save TN for another TN . changed to : SAVE or : SAVE - ONCE . to some finite SB . Load TNs do n't have any conflict information . Represents a constant , with TN - Leaf a Constant leaf . Lifetime lifetime analysis is n't done on : , they do n't have A special kind of TN used to represent initialization of local call calls . Lifetime analysis treats this the same as : NORMAL , but then at the end merges the conflict info into the original TN and replaces all uses of the alias with the original TN . SAVE - TN holds the aliased TN . (kind (required-argument) :type (member :normal :environment :debug-environment :save :save-once :specified-save :load :constant :component :alias)) The primitive - type for this TN 's value . Null in restricted or wired TNs . (primitive-type nil :type (or primitive-type null)) If this TN represents a variable or constant , then this is the corresponding Leaf . (leaf nil :type (or leaf null)) (next nil :type (or tn null)) Head of TN - Ref lists for reads and writes of this TN . (reads nil :type (or tn-ref null)) (writes nil :type (or tn-ref null)) A link we use when building various temporary TN lists . (next* nil :type (or tn null)) Some block that contains a reference to this TN , or Nil if we have n't seen any reference yet . If the TN is local , then this is the block it is local (local nil :type (or ir2-block null)) If a local TN , the block relative number for this TN . Global TNs whose the conflicts analysis of that block . If the TN has no local number within the block , then this is . (local-number nil :type (or local-tn-number null)) If a local TN , a bit - vector with 1 for the local - number of every TN that (local-conflicts (make-array local-tn-limit :element-type 'bit :initial-element 0) :type local-tn-bit-vector) Head of the list of Global - Conflicts structures for a global TN . This list is sorted by block number ( i.e. reverse DFO ) , allowing the intersection between the lifetimes for two global TNs to be easily found . If null , then this TN is a local TN . (global-conflicts nil :type (or global-conflicts null)) chain , for scanning through blocks in reverse DFO . (current-conflict nil) In a : Save TN , this is the TN saved . In a : Normal or : Environment TN , this is the associated save TN . In TNs with no save TN , this is null . (save-tn nil :type (or tn null)) After pack , the SC we packed into . Beforehand , the SC we want to pack (sc nil :type (or sc null)) The offset within the SB that this TN is packed into . This is what indicates that the TN is packed . (offset nil :type (or index null)) Some kind of info about how important this TN is . (cost 0 :type fixnum) the TN is live throughout . (environment nil :type (or environment null)) The depth of the deepest loop that this TN is used in . (loop-depth 0 :type fixnum)) (defun %print-tn (s stream d) (declare (ignore d)) (write-string "#<TN " stream) (print-tn s stream) (write-char #\> stream)) The Global - Conflicts structure represents the conflicts for global TNs . Each global TN has a list of these structures , one for each block that it the set of TNs live at the start of the IR2 block . (defstruct (global-conflicts (:constructor really-make-global-conflicts (kind tn block number)) (:print-function %print-global-conflicts)) The IR2 - Block that this structure represents the conflicts for . (block (required-argument) :type ir2-block) Thread running through all the Global - Conflict for Block . This thread is sorted by TN number . (next nil :type (or global-conflicts null)) The way that TN is used by Block : The TN is read before it is written . It starts the block live , but The TN is written before any read . It starts the block dead , and The TN is read , but never written . It starts the block live , and is not killed by the block . Lifetime analysis will promote The TN is not referenced . It is live everywhere in the block . (kind :read-only :type (member :read :write :read-only :live)) A local conflicts vector representing conflicts with TNs live in Block . The index for the local TN number of each TN we conflict with in this block is 1 . To find the full conflict set , the : Live TNs for Block must (conflicts (make-array local-tn-limit :element-type 'bit :initial-element 0) :type local-tn-bit-vector) The TN we are recording conflicts for . (tn (required-argument) :type tn) Thread through all the Global - Conflicts for TN . (tn-next nil :type (or global-conflicts null)) TN 's local TN number in Block . : Live TNs do n't have local numbers . (number nil :type (or local-tn-number null))) (defprinter global-conflicts tn block kind (number :test number))
b800558a740f6c9943f43e7293164b6065cc399716a668e12a0f68691e47dbe4
dylex/haskell-nfs
String.hs
# LANGUAGE GeneralizedNewtypeDeriving # module Network.NFS.V4.String ( StrCS(..) , StrCIS(..) , StrMixed(..) ) where import qualified Data.ByteString.Char8 as BSC import qualified Data.CaseInsensitive as CI import Data.Monoid ((<>)) import Data.String (IsString(..)) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Network.ONCRPC.XDR.Opaque (Opaqued(..)) -- |For 'NFS.Utf8str_cs'. newtype StrCS = StrCS{ strCSText :: T.Text } deriving (Eq, Ord, IsString) -- |For 'NFS.Utf8str_cis'. newtype StrCIS = StrCIS{ strCISText :: CI.CI T.Text } deriving (Eq, Ord, IsString) |For ' NFS.Utf8str_mixed ' , components are separated with \"\@\ " . data StrMixed = StrMixed { strMixedPrefix :: StrCS , strMixedDomain :: Maybe StrCIS } deriving (Eq, Ord) instance IsString StrMixed where fromString s = case break ('@' ==) s of (p, []) -> StrMixed (fromString p) Nothing (p, ~('@':d)) -> StrMixed (fromString p) (Just $ fromString d) instance Opaqued StrCS where opacify = TE.encodeUtf8 . strCSText unopacify = either (fail . show) (return . StrCS) . TE.decodeUtf8' instance Opaqued StrCIS where opacify = TE.encodeUtf8 . CI.original . strCISText unopacify = either (fail . show) (return . StrCIS . CI.mk) . TE.decodeUtf8' instance Opaqued StrMixed where opacify (StrMixed p d) = opacify p <> foldMap (BSC.cons '@' . opacify) d unopacify s = maybe ((`StrMixed` Nothing) <$> unopacify s) (\i -> StrMixed <$> unopacify (BSC.take i s) <*> (Just <$> unopacify (BSC.drop (succ i) s))) $ BSC.elemIndexEnd '@' s
null
https://raw.githubusercontent.com/dylex/haskell-nfs/07d213e09f7bf9e6fe3200aca3de494c3dcd54f7/nfs/Network/NFS/V4/String.hs
haskell
|For 'NFS.Utf8str_cs'. |For 'NFS.Utf8str_cis'.
# LANGUAGE GeneralizedNewtypeDeriving # module Network.NFS.V4.String ( StrCS(..) , StrCIS(..) , StrMixed(..) ) where import qualified Data.ByteString.Char8 as BSC import qualified Data.CaseInsensitive as CI import Data.Monoid ((<>)) import Data.String (IsString(..)) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Network.ONCRPC.XDR.Opaque (Opaqued(..)) newtype StrCS = StrCS{ strCSText :: T.Text } deriving (Eq, Ord, IsString) newtype StrCIS = StrCIS{ strCISText :: CI.CI T.Text } deriving (Eq, Ord, IsString) |For ' NFS.Utf8str_mixed ' , components are separated with \"\@\ " . data StrMixed = StrMixed { strMixedPrefix :: StrCS , strMixedDomain :: Maybe StrCIS } deriving (Eq, Ord) instance IsString StrMixed where fromString s = case break ('@' ==) s of (p, []) -> StrMixed (fromString p) Nothing (p, ~('@':d)) -> StrMixed (fromString p) (Just $ fromString d) instance Opaqued StrCS where opacify = TE.encodeUtf8 . strCSText unopacify = either (fail . show) (return . StrCS) . TE.decodeUtf8' instance Opaqued StrCIS where opacify = TE.encodeUtf8 . CI.original . strCISText unopacify = either (fail . show) (return . StrCIS . CI.mk) . TE.decodeUtf8' instance Opaqued StrMixed where opacify (StrMixed p d) = opacify p <> foldMap (BSC.cons '@' . opacify) d unopacify s = maybe ((`StrMixed` Nothing) <$> unopacify s) (\i -> StrMixed <$> unopacify (BSC.take i s) <*> (Just <$> unopacify (BSC.drop (succ i) s))) $ BSC.elemIndexEnd '@' s
0111f5cb2c505bdfbedf87486ced3b6456380bb21c00c79251aab9747f6ef3e8
karamellpelle/grid
GL3D.hs
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGLHelper.OpenGL3D -- -- helper functions for 3D -- -------------------------------------------------------------------------------- module OpenGL.Helpers.GL3D ( lookAt9, vertex3, normal3, translate3, rotate3D, scale3, ) where import OpenGL as GL import Control.Monad.Trans -- | look at point p from point e, with upward direction u lookAt9 :: MonadIO m => Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> m () lookAt9 ex ey ez px py pz ux uy uz = liftIO $ gluLookAt (realToFrac ex) (realToFrac ey) (realToFrac ez) (realToFrac px) (realToFrac py) (realToFrac pz) (realToFrac ux) (realToFrac uy) (realToFrac uz) -- todo: we should use OpenGLRaw to push/pop matrix, so that we are able to run MonadIO inside: -- as3DView :: MonadIO m => Double -> Double -> Double -> Double -> Double -> m a -> m a -- as3DView w h fovy near far = ... -- | vertex at (x, y, z) vertex3 :: MonadIO m => Double -> Double -> Double -> m () vertex3 x y z = liftIO $ glVertex3f (realToFrac x) (realToFrac y) (realToFrac z) -- | normal in direction (x, y, z) note : normals shall typically have length 1 . arguments to this functions are scaled -- by modelview, if this is a problem, set GL.rescaleNormal $= Enabled normal3 :: MonadIO m => Double -> Double -> Double -> m () normal3 x y z = liftIO $ glNormal3f (realToFrac x) (realToFrac y) (realToFrac z) -- | translate (x, y, z) translate3 :: MonadIO m => Double -> Double -> Double -> m () translate3 x y z = do liftIO $ glTranslatef (realToFrac x) (realToFrac y) (realToFrac z) -- | rotating radians around direction rotate3D :: MonadIO m => Double -> Double -> Double -> Double -> m () rotate3D rad x y z = do liftIO $ glRotatef (realToFrac $ rad * 57.295780) (realToFrac x) (realToFrac y) (realToFrac z) -- | scaling (x, y, z) scale3 :: MonadIO m => Double -> Double -> Double -> m () scale3 x y z = do liftIO $ glScalef (realToFrac x) (realToFrac y) (realToFrac z)
null
https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/designer/source/OpenGL/Helpers/GL3D.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.Rendering.OpenGLHelper.OpenGL3D helper functions for 3D ------------------------------------------------------------------------------ | look at point p from point e, with upward direction u todo: we should use OpenGLRaw to push/pop matrix, so that we are able to run MonadIO inside: as3DView :: MonadIO m => Double -> Double -> Double -> Double -> Double -> m a -> m a as3DView w h fovy near far = ... | vertex at (x, y, z) | normal in direction (x, y, z) by modelview, if this is a problem, set GL.rescaleNormal $= Enabled | translate (x, y, z) | rotating radians around direction | scaling (x, y, z)
module OpenGL.Helpers.GL3D ( lookAt9, vertex3, normal3, translate3, rotate3D, scale3, ) where import OpenGL as GL import Control.Monad.Trans lookAt9 :: MonadIO m => Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> m () lookAt9 ex ey ez px py pz ux uy uz = liftIO $ gluLookAt (realToFrac ex) (realToFrac ey) (realToFrac ez) (realToFrac px) (realToFrac py) (realToFrac pz) (realToFrac ux) (realToFrac uy) (realToFrac uz) vertex3 :: MonadIO m => Double -> Double -> Double -> m () vertex3 x y z = liftIO $ glVertex3f (realToFrac x) (realToFrac y) (realToFrac z) note : normals shall typically have length 1 . arguments to this functions are scaled normal3 :: MonadIO m => Double -> Double -> Double -> m () normal3 x y z = liftIO $ glNormal3f (realToFrac x) (realToFrac y) (realToFrac z) translate3 :: MonadIO m => Double -> Double -> Double -> m () translate3 x y z = do liftIO $ glTranslatef (realToFrac x) (realToFrac y) (realToFrac z) rotate3D :: MonadIO m => Double -> Double -> Double -> Double -> m () rotate3D rad x y z = do liftIO $ glRotatef (realToFrac $ rad * 57.295780) (realToFrac x) (realToFrac y) (realToFrac z) scale3 :: MonadIO m => Double -> Double -> Double -> m () scale3 x y z = do liftIO $ glScalef (realToFrac x) (realToFrac y) (realToFrac z)
597ba2ed8f2d91eb493bb392ad7889d001c3d0ea34465ef2a21d92acdf4d9e57
ujihisa/cloft
cloft.clj
(ns cloft.cloft (:require [clojure.string :as s]) (:require [clojure.set]) (:require [cloft.material :as m]) (:import [org.bukkit.util Vector]) (:import [org.bukkit Bukkit Material Location]) (:import [org.bukkit.entity Animals Arrow Blaze Boat CaveSpider Chicken ComplexEntityPart ComplexLivingEntity Cow Creature Creeper Egg EnderCrystal EnderDragon EnderDragonPart Enderman EnderPearl EnderSignal ExperienceOrb Explosive FallingSand Fireball Fish Flying Ghast Giant HumanEntity Item LightningStrike LivingEntity MagmaCube Minecart Monster MushroomCow NPC Painting Pig PigZombie Player PoweredMinecart Projectile Sheep Silverfish Skeleton Slime SmallFireball Snowball Snowman Spider Squid StorageMinecart ThrownPotion TNTPrimed Vehicle Villager WaterMob Weather Wolf Zombie]) (:import [org.bukkit.event.entity CreatureSpawnEvent CreeperPowerEvent EntityChangeBlockEvent EntityCombustByBlockEvent EntityCombustByEntityEvent EntityCombustEvent EntityCreatePortalEvent EntityDamageByBlockEvent EntityDamageByEntityEvent EntityDamageEvent EntityDeathEvent EntityEvent EntityExplodeEvent EntityDamageEvent$DamageCause EntityInteractEvent EntityPortalEnterEvent EntityRegainHealthEvent EntityShootBowEvent EntityTameEvent EntityTargetEvent ExplosionPrimeEvent FoodLevelChangeEvent ItemDespawnEvent ItemSpawnEvent PigZapEvent PlayerDeathEvent PotionSplashEvent ProjectileHitEvent SheepDyeWoolEvent SheepRegrowWoolEvent SlimeSplitEvent]) (:import [org.bukkit.potion PotionType])) (defonce plugin* nil) (defmacro later [& exps] `(.scheduleSyncDelayedTask (Bukkit/getScheduler) plugin* (fn [] ~@exps) 0)) (defn init-plugin [plugin] (when-not plugin* (def plugin* plugin))) (defn world [] (Bukkit/getWorld "world")) (defn broadcast [& strs] (.broadcastMessage (Bukkit/getServer) (apply str strs))) (defn location-in-lisp [location] (list `Location. (.getName (.getWorld location)) (.getX location) (.getY location) (.getZ location) (.getPitch location) (.getYaw location))) (defn swap-entity [target klass] (let [location (.getLocation target) world (.getWorld target)] (.remove target) (.spawn (world) location klass))) (defn consume-item [player] (let [itemstack (.getItemInHand player) amount (.getAmount itemstack)] (if (= 1 amount) (.remove (.getInventory player) itemstack) (.setAmount itemstack (dec amount))))) (defn get-player [name] (first (filter #(= name (.getDisplayName %)) (Bukkit/getOnlinePlayers)))) (defn ujm [] (get-player "ujm")) (defn jumping? [moveevt] (< (.getY (.getFrom moveevt)) (.getY (.getTo moveevt)))) (defn consume-itemstack [inventory mtype] (let [idx (.first inventory mtype) itemstack (.getItem inventory idx) amount (.getAmount itemstack)] (if (= 1 amount) (.remove inventory itemstack) (.setAmount itemstack (dec amount))))) (defn location-bound? [loc min max] (.isInAABB (.toVector loc) (.toVector min) (.toVector max))) (defn add-velocity [entity x y z] (.setVelocity entity (.add (.getVelocity entity) (Vector. (double x) (double y) (double z))))) (defn entities-nearby-from [location radius] "location -> set of entities" (let [players (filter #(> radius (.distance (.getLocation %) location)) (Bukkit/getOnlinePlayers))] (apply clojure.set/union (map #(set (cons % (.getNearbyEntities % radius radius radius))) players)))) (defn removable-block? [block] (and (nil? (#{Material/AIR Material/CHEST Material/FURNACE Material/BURNING_FURNACE Material/BEDROCK} (.getType block))) (not (.isLiquid block)))) (defn entity2name [entity] (cond (instance? Blaze entity) "Blaze" (instance? CaveSpider entity) "CaveSpider" (instance? Chicken entity) "Chicken" ;(instance? ComplexLivingEntity entity) "ComplexLivingEntity" (instance? Cow entity) "Cow" ;(instance? Creature entity) "Creature" (instance? Creeper entity) "Creeper" (instance? EnderDragon entity) "EnderDragon" (instance? Enderman entity) "Enderman" ;(instance? Flying entity) "Flying" (instance? Ghast entity) "Ghast" (instance? Giant entity) "Giant" ;(instance? HumanEntity entity) "HumanEntity" (instance? MagmaCube entity) "MagmaCube" ;(instance? Monster entity) "Monster" (instance? MushroomCow entity) "MushroomCow" ( instance ? NPC entity ) " NPC " (instance? Pig entity) "Pig" (instance? PigZombie entity) "PigZombie" (instance? Player entity) (.getDisplayName entity) (instance? Sheep entity) "Sheep" (instance? Silverfish entity) "Silverfish" (instance? Skeleton entity) "Skeleton" (instance? Slime entity) "Slime" (instance? Snowman entity) "Snowman" (instance? Spider entity) "Spider" (instance? Squid entity) "Squid" (instance? Villager entity) "Villager" ( instance ? WaterMob entity ) " WaterMob " (instance? Wolf entity) "Wolf" (instance? Zombie entity) "Zombie" (instance? TNTPrimed entity) "TNT" (instance? Fireball entity) "Fireball" :else (last (clojure.string/split (str (class entity)) #"\.")))) (defn move-entity [entity x y z] (let [loc (.getLocation entity)] (.add loc x y z) (.teleport entity loc))) (defn teleport-without-angle [entity location] (.setYaw location (.getYaw (.getLocation entity))) (.setPitch location (.getPitch (.getLocation entity))) (.teleport entity location) #_(when-let [vehicle (.getVehicle entity)] (.teleport vehicle location))) (defn freeze [target sec] (when-not (.isDead target) (let [loc (.getLocation (.getBlock (.getLocation target)))] (doseq [y [0 1] [x z] [[-1 0] [1 0] [0 -1] [0 1]] :let [block (.getBlock (.add (.clone loc) x y z))] :when (#{m/air m/snow} (.getType block))] (.setType block m/glass)) (doseq [y [-1 2] :let [block (.getBlock (.add (.clone loc) 0 y 0))] :when (#{m/air m/snow} (.getType block))] (.setType block m/glass)) (future (Thread/sleep 1000) (when-not (.isDead target) (later (.teleport target (.add (.clone loc) 0.5 0.0 0.5))))) (future (Thread/sleep (* sec 1000)) (doseq [y [0 1] [x z] [[-1 0] [1 0] [0 -1] [0 1]] :let [block (.getBlock (.add (.clone loc) x y z))] :when (= (.getType block) m/glass)] (later (.setType block m/air))) (doseq [y [-1 2] :let [block (.getBlock (.add (.clone loc) 0 y 0))] :when (= (.getType block) m/glass)] (later (.setType block m/air))))))) (defn freeze-for-20-sec [target] (freeze target 20)) (def potion-types [PotionType/FIRE_RESISTANCE PotionType/INSTANT_DAMAGE PotionType/INSTANT_HEAL PotionType/POISON PotionType/REGEN PotionType/SLOWNESS PotionType/SPEED PotionType/STRENGTH PotionType/WATER PotionType/WEAKNESS])
null
https://raw.githubusercontent.com/ujihisa/cloft/98284fa763d16280d4685478b2be2ab0efbb00b0/src/cloft/cloft.clj
clojure
(instance? ComplexLivingEntity entity) "ComplexLivingEntity" (instance? Creature entity) "Creature" (instance? Flying entity) "Flying" (instance? HumanEntity entity) "HumanEntity" (instance? Monster entity) "Monster"
(ns cloft.cloft (:require [clojure.string :as s]) (:require [clojure.set]) (:require [cloft.material :as m]) (:import [org.bukkit.util Vector]) (:import [org.bukkit Bukkit Material Location]) (:import [org.bukkit.entity Animals Arrow Blaze Boat CaveSpider Chicken ComplexEntityPart ComplexLivingEntity Cow Creature Creeper Egg EnderCrystal EnderDragon EnderDragonPart Enderman EnderPearl EnderSignal ExperienceOrb Explosive FallingSand Fireball Fish Flying Ghast Giant HumanEntity Item LightningStrike LivingEntity MagmaCube Minecart Monster MushroomCow NPC Painting Pig PigZombie Player PoweredMinecart Projectile Sheep Silverfish Skeleton Slime SmallFireball Snowball Snowman Spider Squid StorageMinecart ThrownPotion TNTPrimed Vehicle Villager WaterMob Weather Wolf Zombie]) (:import [org.bukkit.event.entity CreatureSpawnEvent CreeperPowerEvent EntityChangeBlockEvent EntityCombustByBlockEvent EntityCombustByEntityEvent EntityCombustEvent EntityCreatePortalEvent EntityDamageByBlockEvent EntityDamageByEntityEvent EntityDamageEvent EntityDeathEvent EntityEvent EntityExplodeEvent EntityDamageEvent$DamageCause EntityInteractEvent EntityPortalEnterEvent EntityRegainHealthEvent EntityShootBowEvent EntityTameEvent EntityTargetEvent ExplosionPrimeEvent FoodLevelChangeEvent ItemDespawnEvent ItemSpawnEvent PigZapEvent PlayerDeathEvent PotionSplashEvent ProjectileHitEvent SheepDyeWoolEvent SheepRegrowWoolEvent SlimeSplitEvent]) (:import [org.bukkit.potion PotionType])) (defonce plugin* nil) (defmacro later [& exps] `(.scheduleSyncDelayedTask (Bukkit/getScheduler) plugin* (fn [] ~@exps) 0)) (defn init-plugin [plugin] (when-not plugin* (def plugin* plugin))) (defn world [] (Bukkit/getWorld "world")) (defn broadcast [& strs] (.broadcastMessage (Bukkit/getServer) (apply str strs))) (defn location-in-lisp [location] (list `Location. (.getName (.getWorld location)) (.getX location) (.getY location) (.getZ location) (.getPitch location) (.getYaw location))) (defn swap-entity [target klass] (let [location (.getLocation target) world (.getWorld target)] (.remove target) (.spawn (world) location klass))) (defn consume-item [player] (let [itemstack (.getItemInHand player) amount (.getAmount itemstack)] (if (= 1 amount) (.remove (.getInventory player) itemstack) (.setAmount itemstack (dec amount))))) (defn get-player [name] (first (filter #(= name (.getDisplayName %)) (Bukkit/getOnlinePlayers)))) (defn ujm [] (get-player "ujm")) (defn jumping? [moveevt] (< (.getY (.getFrom moveevt)) (.getY (.getTo moveevt)))) (defn consume-itemstack [inventory mtype] (let [idx (.first inventory mtype) itemstack (.getItem inventory idx) amount (.getAmount itemstack)] (if (= 1 amount) (.remove inventory itemstack) (.setAmount itemstack (dec amount))))) (defn location-bound? [loc min max] (.isInAABB (.toVector loc) (.toVector min) (.toVector max))) (defn add-velocity [entity x y z] (.setVelocity entity (.add (.getVelocity entity) (Vector. (double x) (double y) (double z))))) (defn entities-nearby-from [location radius] "location -> set of entities" (let [players (filter #(> radius (.distance (.getLocation %) location)) (Bukkit/getOnlinePlayers))] (apply clojure.set/union (map #(set (cons % (.getNearbyEntities % radius radius radius))) players)))) (defn removable-block? [block] (and (nil? (#{Material/AIR Material/CHEST Material/FURNACE Material/BURNING_FURNACE Material/BEDROCK} (.getType block))) (not (.isLiquid block)))) (defn entity2name [entity] (cond (instance? Blaze entity) "Blaze" (instance? CaveSpider entity) "CaveSpider" (instance? Chicken entity) "Chicken" (instance? Cow entity) "Cow" (instance? Creeper entity) "Creeper" (instance? EnderDragon entity) "EnderDragon" (instance? Enderman entity) "Enderman" (instance? Ghast entity) "Ghast" (instance? Giant entity) "Giant" (instance? MagmaCube entity) "MagmaCube" (instance? MushroomCow entity) "MushroomCow" ( instance ? NPC entity ) " NPC " (instance? Pig entity) "Pig" (instance? PigZombie entity) "PigZombie" (instance? Player entity) (.getDisplayName entity) (instance? Sheep entity) "Sheep" (instance? Silverfish entity) "Silverfish" (instance? Skeleton entity) "Skeleton" (instance? Slime entity) "Slime" (instance? Snowman entity) "Snowman" (instance? Spider entity) "Spider" (instance? Squid entity) "Squid" (instance? Villager entity) "Villager" ( instance ? WaterMob entity ) " WaterMob " (instance? Wolf entity) "Wolf" (instance? Zombie entity) "Zombie" (instance? TNTPrimed entity) "TNT" (instance? Fireball entity) "Fireball" :else (last (clojure.string/split (str (class entity)) #"\.")))) (defn move-entity [entity x y z] (let [loc (.getLocation entity)] (.add loc x y z) (.teleport entity loc))) (defn teleport-without-angle [entity location] (.setYaw location (.getYaw (.getLocation entity))) (.setPitch location (.getPitch (.getLocation entity))) (.teleport entity location) #_(when-let [vehicle (.getVehicle entity)] (.teleport vehicle location))) (defn freeze [target sec] (when-not (.isDead target) (let [loc (.getLocation (.getBlock (.getLocation target)))] (doseq [y [0 1] [x z] [[-1 0] [1 0] [0 -1] [0 1]] :let [block (.getBlock (.add (.clone loc) x y z))] :when (#{m/air m/snow} (.getType block))] (.setType block m/glass)) (doseq [y [-1 2] :let [block (.getBlock (.add (.clone loc) 0 y 0))] :when (#{m/air m/snow} (.getType block))] (.setType block m/glass)) (future (Thread/sleep 1000) (when-not (.isDead target) (later (.teleport target (.add (.clone loc) 0.5 0.0 0.5))))) (future (Thread/sleep (* sec 1000)) (doseq [y [0 1] [x z] [[-1 0] [1 0] [0 -1] [0 1]] :let [block (.getBlock (.add (.clone loc) x y z))] :when (= (.getType block) m/glass)] (later (.setType block m/air))) (doseq [y [-1 2] :let [block (.getBlock (.add (.clone loc) 0 y 0))] :when (= (.getType block) m/glass)] (later (.setType block m/air))))))) (defn freeze-for-20-sec [target] (freeze target 20)) (def potion-types [PotionType/FIRE_RESISTANCE PotionType/INSTANT_DAMAGE PotionType/INSTANT_HEAL PotionType/POISON PotionType/REGEN PotionType/SLOWNESS PotionType/SPEED PotionType/STRENGTH PotionType/WATER PotionType/WEAKNESS])
e22510109cc434eac5ccfd7685150fa93a09379800f6cfd15750bc40aaf879b6
cedlemo/OCaml-GI-ctypes-bindings-generator
HSVPrivate.ml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "HSVPrivate"
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/HSVPrivate.ml
ocaml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "HSVPrivate"
1805aa8b9302bc5b43c2bd0606365391d465080f6178ccfdba2d9209295a66a8
hedgehogqa/haskell-hedgehog
Hedgehog.hs
-- | -- This module includes almost everything you need to get started writing property tests with Hedgehog . -- -- It is designed to be used alongside "Hedgehog.Gen" and "Hedgehog.Range", which should be imported qualified . You also need to enable Template Haskell so the Hedgehog test runner can find your properties . -- -- > {-# LANGUAGE TemplateHaskell #-} -- > -- > import Hedgehog -- > import qualified Hedgehog.Gen as Gen > import qualified Hedgehog . Range as Range -- -- Once you have your imports set up, you can write a simple property: -- -- > prop_reverse :: Property -- > prop_reverse = -- > property $ do -- > xs <- forAll $ Gen.list (Range.linear 0 100) Gen.alpha -- > reverse (reverse xs) === xs -- -- And add the Template Haskell splice which will discover your properties: -- -- > tests :: IO Bool -- > tests = -- > checkParallel $$(discover) -- -- If you prefer to avoid macros, you can specify the group of properties to -- run manually instead: -- -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > tests :: IO Bool -- > tests = > checkParallel $ Group " Test . Example " [ -- > ("prop_reverse", prop_reverse) -- > ] -- -- You can then load the module in GHCi, and run it: -- -- > λ tests > . Example > ✓ prop_reverse passed 100 tests . -- module Hedgehog ( -- * Properties Property , PropertyT , Group(..) , PropertyName , GroupName , property , test , forAll , forAllWith , discard , check , recheck , recheckAt , discover , discoverPrefix , checkParallel , checkSequential , Confidence , verifiedTermination , withConfidence , withTests , TestLimit , withDiscards , DiscardLimit , withShrinks , ShrinkLimit , withRetries , ShrinkRetries , withSkip , Skip -- * Generating Test Data , Gen , GenT , MonadGen(..) , Range , Size(..) , Seed(..) -- * Tests , Test , TestT , MonadTest(..) , annotate , annotateShow , footnote , footnoteShow , success , failure , assert , diff , (===) , (/==) , tripping , eval , evalNF , evalM , evalIO , evalEither , evalEitherM , evalExceptT , evalMaybe , evalMaybeM -- * Coverage , LabelName , classify , cover , label , collect -- * State Machine Tests , Command(..) , Callback(..) , Action , Sequential(..) , Parallel(..) , executeSequential , executeParallel , Var(..) , concrete , opaque , Symbolic , Concrete(..) , Opaque(..) -- * Transformers , distributeT -- * Functors -- $functors , FunctorB(..) , TraversableB(..) , Rec(..) , Eq1 , eq1 , Ord1 , compare1 , Show1 , showsPrec1 -- * Deprecated , HTraversable(..) ) where import Data.Functor.Classes (Eq1, eq1, Ord1, compare1, Show1, showsPrec1) import Hedgehog.Internal.Barbie (FunctorB(..), TraversableB(..), Rec(..)) import Hedgehog.Internal.Distributive (distributeT) import Hedgehog.Internal.Gen (Gen, GenT, MonadGen(..)) import Hedgehog.Internal.HTraversable (HTraversable(..)) import Hedgehog.Internal.Opaque (Opaque(..)) import Hedgehog.Internal.Property (annotate, annotateShow) import Hedgehog.Internal.Property (assert, diff, (===), (/==)) import Hedgehog.Internal.Property (classify, cover) import Hedgehog.Internal.Property (discard, failure, success) import Hedgehog.Internal.Property (DiscardLimit, withDiscards) import Hedgehog.Internal.Property (eval, evalNF, evalM, evalIO) import Hedgehog.Internal.Property (evalEither, evalEitherM, evalExceptT, evalMaybe, evalMaybeM) import Hedgehog.Internal.Property (footnote, footnoteShow) import Hedgehog.Internal.Property (forAll, forAllWith) import Hedgehog.Internal.Property (LabelName, MonadTest(..)) import Hedgehog.Internal.Property (Property, PropertyT, PropertyName) import Hedgehog.Internal.Property (Group(..), GroupName) import Hedgehog.Internal.Property (Confidence, verifiedTermination, withConfidence) import Hedgehog.Internal.Property (ShrinkLimit, withShrinks) import Hedgehog.Internal.Property (ShrinkRetries, withRetries) import Hedgehog.Internal.Property (Skip, withSkip) import Hedgehog.Internal.Property (Test, TestT, property, test) import Hedgehog.Internal.Property (TestLimit, withTests) import Hedgehog.Internal.Property (collect, label) import Hedgehog.Internal.Range (Range, Size(..)) import Hedgehog.Internal.Runner (check, recheck, recheckAt, checkSequential, checkParallel) import Hedgehog.Internal.Seed (Seed(..)) import Hedgehog.Internal.State (Command(..), Callback(..)) import Hedgehog.Internal.State (Action, Sequential(..), Parallel(..)) import Hedgehog.Internal.State (executeSequential, executeParallel) import Hedgehog.Internal.State (Var(..), Symbolic, Concrete(..), concrete, opaque) import Hedgehog.Internal.TH (discover, discoverPrefix) import Hedgehog.Internal.Tripping (tripping) -- $functors -- -- 'FunctorB' and 'TraversableB' must be implemented for all 'Command' @input@ types. -- This is most easily achieved using ` DeriveGeneric ` : -- -- @ data Register v = Register Name ( ) deriving ( Eq , Show , Generic ) -- -- instance FunctorB Register -- instance TraversableB Register -- newtype ( v : : * - > * ) = -- Unregister Name deriving ( Eq , Show , Generic ) -- -- instance FunctorB Unregister instance TraversableB -- @ -- ` DeriveAnyClass ` and ` DerivingStrategies ` allow a more compact syntax : -- -- @ data Register v = Register Name ( ) deriving ( Eq , Show , Generic , FunctorB , TraversableB ) -- newtype ( v : : * - > * ) = -- Unregister Name deriving ( Eq , Show , Generic ) -- deriving anyclass (FunctorB, TraversableB) -- @ --
null
https://raw.githubusercontent.com/hedgehogqa/haskell-hedgehog/f670bdf146368bb5574c256889aa25779cc0a9f8/hedgehog/src/Hedgehog.hs
haskell
| This module includes almost everything you need to get started writing It is designed to be used alongside "Hedgehog.Gen" and "Hedgehog.Range", > {-# LANGUAGE TemplateHaskell #-} > > import Hedgehog > import qualified Hedgehog.Gen as Gen Once you have your imports set up, you can write a simple property: > prop_reverse :: Property > prop_reverse = > property $ do > xs <- forAll $ Gen.list (Range.linear 0 100) Gen.alpha > reverse (reverse xs) === xs And add the Template Haskell splice which will discover your properties: > tests :: IO Bool > tests = > checkParallel $$(discover) If you prefer to avoid macros, you can specify the group of properties to run manually instead: > {-# LANGUAGE OverloadedStrings #-} > > tests :: IO Bool > tests = > ("prop_reverse", prop_reverse) > ] You can then load the module in GHCi, and run it: > λ tests * Properties * Generating Test Data * Tests * Coverage * State Machine Tests * Transformers * Functors $functors * Deprecated $functors 'FunctorB' and 'TraversableB' must be implemented for all 'Command' @input@ types. @ instance FunctorB Register instance TraversableB Register Unregister Name instance FunctorB Unregister @ @ Unregister Name deriving anyclass (FunctorB, TraversableB) @
property tests with Hedgehog . which should be imported qualified . You also need to enable Template Haskell so the Hedgehog test runner can find your properties . > import qualified Hedgehog . Range as Range > checkParallel $ Group " Test . Example " [ > . Example > ✓ prop_reverse passed 100 tests . module Hedgehog ( Property , PropertyT , Group(..) , PropertyName , GroupName , property , test , forAll , forAllWith , discard , check , recheck , recheckAt , discover , discoverPrefix , checkParallel , checkSequential , Confidence , verifiedTermination , withConfidence , withTests , TestLimit , withDiscards , DiscardLimit , withShrinks , ShrinkLimit , withRetries , ShrinkRetries , withSkip , Skip , Gen , GenT , MonadGen(..) , Range , Size(..) , Seed(..) , Test , TestT , MonadTest(..) , annotate , annotateShow , footnote , footnoteShow , success , failure , assert , diff , (===) , (/==) , tripping , eval , evalNF , evalM , evalIO , evalEither , evalEitherM , evalExceptT , evalMaybe , evalMaybeM , LabelName , classify , cover , label , collect , Command(..) , Callback(..) , Action , Sequential(..) , Parallel(..) , executeSequential , executeParallel , Var(..) , concrete , opaque , Symbolic , Concrete(..) , Opaque(..) , distributeT , FunctorB(..) , TraversableB(..) , Rec(..) , Eq1 , eq1 , Ord1 , compare1 , Show1 , showsPrec1 , HTraversable(..) ) where import Data.Functor.Classes (Eq1, eq1, Ord1, compare1, Show1, showsPrec1) import Hedgehog.Internal.Barbie (FunctorB(..), TraversableB(..), Rec(..)) import Hedgehog.Internal.Distributive (distributeT) import Hedgehog.Internal.Gen (Gen, GenT, MonadGen(..)) import Hedgehog.Internal.HTraversable (HTraversable(..)) import Hedgehog.Internal.Opaque (Opaque(..)) import Hedgehog.Internal.Property (annotate, annotateShow) import Hedgehog.Internal.Property (assert, diff, (===), (/==)) import Hedgehog.Internal.Property (classify, cover) import Hedgehog.Internal.Property (discard, failure, success) import Hedgehog.Internal.Property (DiscardLimit, withDiscards) import Hedgehog.Internal.Property (eval, evalNF, evalM, evalIO) import Hedgehog.Internal.Property (evalEither, evalEitherM, evalExceptT, evalMaybe, evalMaybeM) import Hedgehog.Internal.Property (footnote, footnoteShow) import Hedgehog.Internal.Property (forAll, forAllWith) import Hedgehog.Internal.Property (LabelName, MonadTest(..)) import Hedgehog.Internal.Property (Property, PropertyT, PropertyName) import Hedgehog.Internal.Property (Group(..), GroupName) import Hedgehog.Internal.Property (Confidence, verifiedTermination, withConfidence) import Hedgehog.Internal.Property (ShrinkLimit, withShrinks) import Hedgehog.Internal.Property (ShrinkRetries, withRetries) import Hedgehog.Internal.Property (Skip, withSkip) import Hedgehog.Internal.Property (Test, TestT, property, test) import Hedgehog.Internal.Property (TestLimit, withTests) import Hedgehog.Internal.Property (collect, label) import Hedgehog.Internal.Range (Range, Size(..)) import Hedgehog.Internal.Runner (check, recheck, recheckAt, checkSequential, checkParallel) import Hedgehog.Internal.Seed (Seed(..)) import Hedgehog.Internal.State (Command(..), Callback(..)) import Hedgehog.Internal.State (Action, Sequential(..), Parallel(..)) import Hedgehog.Internal.State (executeSequential, executeParallel) import Hedgehog.Internal.State (Var(..), Symbolic, Concrete(..), concrete, opaque) import Hedgehog.Internal.TH (discover, discoverPrefix) import Hedgehog.Internal.Tripping (tripping) This is most easily achieved using ` DeriveGeneric ` : data Register v = Register Name ( ) deriving ( Eq , Show , Generic ) newtype ( v : : * - > * ) = deriving ( Eq , Show , Generic ) instance TraversableB ` DeriveAnyClass ` and ` DerivingStrategies ` allow a more compact syntax : data Register v = Register Name ( ) deriving ( Eq , Show , Generic , FunctorB , TraversableB ) newtype ( v : : * - > * ) = deriving ( Eq , Show , Generic )