_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
a6ac3eaf2d77c05b9d5ae0e3475a0178fe2566c6675fedced08f28a12f7b3784
Raynes/clojail
testers.clj
(ns clojail.testers "A set of predefined testers that you can use in your own sandboxes. I'm not promising that any of these are really totally secure. I cannot possibly test these for everything." (:require [bultitude.core :as nses] [serializable.fn :as sfn])) (deftype ClojailWrapper [object]) (defmethod print-method ClojailWrapper [p out] (.write out (str "#clojail.testers.ClojailWrapper[" (binding [*print-dup* true] (pr-str (.object p))) "]"))) (defn wrap-object "Wraps an object in the ClojailWrapper type to be passed into the tester." [object] (if (instance? ClojailWrapper object) object (->ClojailWrapper object))) (defn blacklist-nses "Blacklist Clojure namespaces. nses should be a collection of namespaces." [nses] (let [nses (map wrap-object nses)] (sfn/fn [s] (when-let [result (first (filter #(let [n (.object %)] (or (= s n) (when (symbol? s) (.startsWith (name s) (str n))))) nses))] (.object result))))) (defn blacklist-symbols "Blacklist symbols. Second argument should be a set of symbols." [symbols] (sfn/fn [s] (when (symbol? s) (first (filter #(or (= s %) (.endsWith (name s) (munge (str "$" %)))) symbols))))) (defn blacklist-packages "Blacklist packages. Packages should be a list of strings corresponding to packages." [packages] (let [packages (map wrap-object packages)] (sfn/fn [obj] (let [obj (if (= Class (type obj)) (.getPackage obj) obj)] (when obj (first (filter #(let [pack (.object %)] (or (= obj (Package/getPackage pack)) (= obj (symbol pack)))) packages))))))) (defn blacklist-objects "Blacklist some objects. objs should be a collection of things." [objs] (let [objs (map wrap-object objs)] (sfn/fn [s] (when-let [result (first (filter #(= s (.object %)) objs))] (.object result))))) (defn blanket "Takes a tester and some namespace prefixes as strings. Looks up the prefixes with bultitude, getting a list of all namespaces on the classpath matching those prefixes." [& prefixes] (blacklist-nses (mapcat (partial nses/namespaces-on-classpath :prefix) prefixes))) (def ^{:doc "A tester that attempts to be secure, and allows def."} secure-tester-without-def [(blacklist-objects [clojure.lang.Compiler clojure.lang.Ref clojure.lang.Reflector clojure.lang.Namespace clojure.lang.Var clojure.lang.RT java.io.ObjectInputStream]) (blacklist-packages ["java.lang.reflect" "java.security" "java.util.concurrent" "java.awt"]) (blacklist-symbols '#{alter-var-root intern eval catch load-string load-reader addMethod ns-resolve resolve find-var *read-eval* ns-publics ns-unmap set! ns-map ns-interns the-ns push-thread-bindings pop-thread-bindings future-call agent send send-off pmap pcalls pvals in-ns System/out System/in System/err with-redefs-fn Class/forName}) (blacklist-nses '[clojure.main]) (blanket "clojail")]) (def ^{:doc "A somewhat secure tester. No promises."} secure-tester (conj secure-tester-without-def (blacklist-symbols '#{def})))
null
https://raw.githubusercontent.com/Raynes/clojail/1b648f225429613d1a9b0792f58521a80aaeb0f8/src/clojail/testers.clj
clojure
(ns clojail.testers "A set of predefined testers that you can use in your own sandboxes. I'm not promising that any of these are really totally secure. I cannot possibly test these for everything." (:require [bultitude.core :as nses] [serializable.fn :as sfn])) (deftype ClojailWrapper [object]) (defmethod print-method ClojailWrapper [p out] (.write out (str "#clojail.testers.ClojailWrapper[" (binding [*print-dup* true] (pr-str (.object p))) "]"))) (defn wrap-object "Wraps an object in the ClojailWrapper type to be passed into the tester." [object] (if (instance? ClojailWrapper object) object (->ClojailWrapper object))) (defn blacklist-nses "Blacklist Clojure namespaces. nses should be a collection of namespaces." [nses] (let [nses (map wrap-object nses)] (sfn/fn [s] (when-let [result (first (filter #(let [n (.object %)] (or (= s n) (when (symbol? s) (.startsWith (name s) (str n))))) nses))] (.object result))))) (defn blacklist-symbols "Blacklist symbols. Second argument should be a set of symbols." [symbols] (sfn/fn [s] (when (symbol? s) (first (filter #(or (= s %) (.endsWith (name s) (munge (str "$" %)))) symbols))))) (defn blacklist-packages "Blacklist packages. Packages should be a list of strings corresponding to packages." [packages] (let [packages (map wrap-object packages)] (sfn/fn [obj] (let [obj (if (= Class (type obj)) (.getPackage obj) obj)] (when obj (first (filter #(let [pack (.object %)] (or (= obj (Package/getPackage pack)) (= obj (symbol pack)))) packages))))))) (defn blacklist-objects "Blacklist some objects. objs should be a collection of things." [objs] (let [objs (map wrap-object objs)] (sfn/fn [s] (when-let [result (first (filter #(= s (.object %)) objs))] (.object result))))) (defn blanket "Takes a tester and some namespace prefixes as strings. Looks up the prefixes with bultitude, getting a list of all namespaces on the classpath matching those prefixes." [& prefixes] (blacklist-nses (mapcat (partial nses/namespaces-on-classpath :prefix) prefixes))) (def ^{:doc "A tester that attempts to be secure, and allows def."} secure-tester-without-def [(blacklist-objects [clojure.lang.Compiler clojure.lang.Ref clojure.lang.Reflector clojure.lang.Namespace clojure.lang.Var clojure.lang.RT java.io.ObjectInputStream]) (blacklist-packages ["java.lang.reflect" "java.security" "java.util.concurrent" "java.awt"]) (blacklist-symbols '#{alter-var-root intern eval catch load-string load-reader addMethod ns-resolve resolve find-var *read-eval* ns-publics ns-unmap set! ns-map ns-interns the-ns push-thread-bindings pop-thread-bindings future-call agent send send-off pmap pcalls pvals in-ns System/out System/in System/err with-redefs-fn Class/forName}) (blacklist-nses '[clojure.main]) (blanket "clojail")]) (def ^{:doc "A somewhat secure tester. No promises."} secure-tester (conj secure-tester-without-def (blacklist-symbols '#{def})))
68c1a187c71452a5465ad90ef97aa88d9aae463c1631e86a145f7b8ed8e4e51b
8c6794b6/guile-tjit
srfi-64.scm
srfi-64.scm -- SRFI 64 - A Scheme API for test suites . Copyright ( C ) 2014 Free Software Foundation , Inc. ;; ;; This library is free software; you can redistribute it and/or ;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . ;; ;; This library is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Lesser General Public License for more details. ;; You should have received a copy of the GNU Lesser General Public ;; License along with this library; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA (define-module (srfi srfi-64) #:export (test-begin test-end test-assert test-eqv test-eq test-equal test-approximate test-assert test-error test-apply test-with-runner test-match-nth test-match-all test-match-any test-match-name test-skip test-expect-fail test-read-eval-string test-runner-group-path test-group test-group-with-cleanup test-result-ref test-result-set! test-result-clear test-result-remove test-result-kind test-passed? test-log-to-file test-runner? test-runner-reset test-runner-null test-runner-simple test-runner-current test-runner-factory test-runner-get test-runner-create test-runner-test-name test-runner-pass-count test-runner-pass-count! test-runner-fail-count test-runner-fail-count! test-runner-xpass-count test-runner-xpass-count! test-runner-xfail-count test-runner-xfail-count! test-runner-skip-count test-runner-skip-count! test-runner-group-stack test-runner-group-stack! test-runner-on-test-begin test-runner-on-test-begin! test-runner-on-test-end test-runner-on-test-end! test-runner-on-group-begin test-runner-on-group-begin! test-runner-on-group-end test-runner-on-group-end! test-runner-on-final test-runner-on-final! test-runner-on-bad-count test-runner-on-bad-count! test-runner-on-bad-end-name test-runner-on-bad-end-name! test-result-alist test-result-alist! test-runner-aux-value test-runner-aux-value! test-on-group-begin-simple test-on-group-end-simple test-on-bad-count-simple test-on-bad-end-name-simple test-on-final-simple test-on-test-end-simple test-on-final-simple)) (cond-expand-provide (current-module) '(srfi-64)) (include-from-path "srfi/srfi-64/testing.scm")
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/srfi/srfi-64.scm
scheme
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public either This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with this library; if not, write to the Free Software
srfi-64.scm -- SRFI 64 - A Scheme API for test suites . Copyright ( C ) 2014 Free Software Foundation , Inc. version 3 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA (define-module (srfi srfi-64) #:export (test-begin test-end test-assert test-eqv test-eq test-equal test-approximate test-assert test-error test-apply test-with-runner test-match-nth test-match-all test-match-any test-match-name test-skip test-expect-fail test-read-eval-string test-runner-group-path test-group test-group-with-cleanup test-result-ref test-result-set! test-result-clear test-result-remove test-result-kind test-passed? test-log-to-file test-runner? test-runner-reset test-runner-null test-runner-simple test-runner-current test-runner-factory test-runner-get test-runner-create test-runner-test-name test-runner-pass-count test-runner-pass-count! test-runner-fail-count test-runner-fail-count! test-runner-xpass-count test-runner-xpass-count! test-runner-xfail-count test-runner-xfail-count! test-runner-skip-count test-runner-skip-count! test-runner-group-stack test-runner-group-stack! test-runner-on-test-begin test-runner-on-test-begin! test-runner-on-test-end test-runner-on-test-end! test-runner-on-group-begin test-runner-on-group-begin! test-runner-on-group-end test-runner-on-group-end! test-runner-on-final test-runner-on-final! test-runner-on-bad-count test-runner-on-bad-count! test-runner-on-bad-end-name test-runner-on-bad-end-name! test-result-alist test-result-alist! test-runner-aux-value test-runner-aux-value! test-on-group-begin-simple test-on-group-end-simple test-on-bad-count-simple test-on-bad-end-name-simple test-on-final-simple test-on-test-end-simple test-on-final-simple)) (cond-expand-provide (current-module) '(srfi-64)) (include-from-path "srfi/srfi-64/testing.scm")
672e170ab3b3fe15eb6583434b3d43c9a5776c91e3e6c0d0a1da2fd434b8daf9
umd-cmsc330/cmsc330spring22
public.ml
open OUnit2 open TestUtils open P2b.Data open P2b.Funs open P2b.Higher let public_contains_elem _ = let a = [] in let b = ["a";"b";"c";"d"] in let c = [91;2;96;42;100] in assert_equal ~printer:string_of_bool false @@ contains_elem a "hello"; assert_equal ~printer:string_of_bool true @@ contains_elem b "b"; assert_equal ~printer:string_of_bool false @@ contains_elem b "z"; assert_equal ~printer:string_of_bool true @@ contains_elem c 42; assert_equal ~printer:string_of_bool false @@ contains_elem c 90 let public_is_present _ = let a = [] in let b = ["w";"x";"y";"z"] in let c = [14;20;42;1;81] in assert_equal ~printer:string_of_int_list [] @@ is_present a 123; assert_equal ~printer:string_of_int_list [0;0;1;0] @@ is_present b "y"; assert_equal ~printer:string_of_int_list [0;0;0;0] @@ is_present b "v"; assert_equal ~printer:string_of_int_list [0;0;1;0;0] @@ is_present c 42; assert_equal ~printer:string_of_int_list [1;0;0;0;0] @@ is_present c 14 let public_count_occ _ = let y = ["a";"a";"b";"a"] in let z = [1;7;7;1;5;2;7;7] in let a = [true;false;false;true;false;false;false] in let b = [] in assert_equal ~printer:string_of_int_pair (3,1) @@ (count_occ y "a", count_occ y "b"); assert_equal ~printer:string_of_int_quad (2,4,1,1) @@ (count_occ z 1, count_occ z 7, count_occ z 5, count_occ z 2); assert_equal ~printer:string_of_int_pair (2,5) @@ (count_occ a true, count_occ a false); assert_equal ~printer:string_of_int_pair (0,0) @@ (count_occ b "a", count_occ b 1) let public_uniq _ = let y = ["a";"a";"b";"a"] in let z = [1;7;7;1;5;2;7;7] in let a = [true;false;false;true;false;false;false] in let b = [] in let cmp x y = if x < y then (-1) else if x = y then 0 else 1 in assert_equal ~printer:string_of_string_list ["a";"b"] @@ List.sort cmp (uniq y); assert_equal ~printer:string_of_int_list [1;2;5;7] @@ List.sort cmp (uniq z); assert_equal ~printer:string_of_bool_list [false;true] @@ List.sort cmp (uniq a); assert_equal ~printer:string_of_int_list [] @@ uniq b let public_assoc_list _ = let y = ["a";"a";"b";"a"] in let z = [1;7;7;1;5;2;7;7] in let a = [true;false;false;true;false;false;false] in let b = [] in let cmp x y = if x < y then (-1) else if x = y then 0 else 1 in assert_equal ~printer:string_of_string_int_pair_list [("a",3);("b",1)] @@ List.sort cmp (assoc_list y); assert_equal ~printer:string_of_int_pair_list [(1,2);(2,1);(5,1);(7,4)] @@ List.sort cmp (assoc_list z); assert_equal ~printer:string_of_bool_int_pair_list [(false,5);(true,2)] @@ List.sort cmp (assoc_list a); assert_equal ~printer:string_of_int_pair_list [] @@ assoc_list b let public_ap _ = let x = [5;6;7;3] in let y = [5;6;7] in let z = [7;5] in let a = [3;5;8;10;9] in let b = [3] in let c = [] in let fs1 = [((+) 2) ; (( * ) 7)] in let fs2 = [pred] in assert_equal ~printer:string_of_int_list [7;8;9;5;35;42;49;21] @@ ap fs1 x; assert_equal ~printer:string_of_int_list [7;8;9;35;42;49] @@ ap fs1 y; assert_equal ~printer:string_of_int_list [9;7;49;35] @@ ap fs1 z; assert_equal ~printer:string_of_int_list [5;7;10;12;11;21;35;56;70;63] @@ ap fs1 a; assert_equal ~printer:string_of_int_list [5;21] @@ ap fs1 b; assert_equal ~printer:string_of_int_list [] @@ ap fs1 c; assert_equal ~printer:string_of_int_list (map pred x) @@ ap fs2 x; assert_equal ~printer:string_of_int_list (map pred y) @@ ap fs2 y; assert_equal ~printer:string_of_int_list (map pred z) @@ ap fs2 z; assert_equal ~printer:string_of_int_list (map pred a) @@ ap fs2 a; assert_equal ~printer:string_of_int_list (map pred b) @@ ap fs2 b; assert_equal ~printer:string_of_int_list (map pred c) @@ ap fs2 c let public_int_tree_insert_and_mem _ = let root = int_insert 20 (int_insert 10 empty_int_tree) in let left = int_insert 9 (int_insert 5 root) in let middle = int_insert 15 (int_insert 13 left) in let right = int_insert 29 (int_insert 21 middle) in assert_equal ~printer:string_of_bool true (int_mem 10 right); assert_equal ~printer:string_of_bool true (int_mem 15 right); assert_equal ~printer:string_of_bool true (int_mem 20 right); assert_equal ~printer:string_of_bool true (int_mem 5 right) let public_int_tree_insert_and_size _ = let root = int_insert 20 (int_insert 10 empty_int_tree) in let left = int_insert 9 (int_insert 5 root) in let middle = int_insert 15 (int_insert 13 left) in let right = int_insert 29 (int_insert 21 middle) in assert_equal ~printer:string_of_int 8 (int_size right); assert_equal ~printer:string_of_int 6 (int_size middle); assert_equal ~printer:string_of_int 4 (int_size left); assert_equal ~printer:string_of_int 2 (int_size root) let public_int_tree_insert_and_max _ = let root = int_insert 20 (int_insert 10 empty_int_tree) in let left = int_insert 9 (int_insert 5 root) in let middle = int_insert 15 (int_insert 13 left) in let right = int_insert 29 (int_insert 21 middle) in assert_equal ~printer:string_of_int 29 (int_max right); assert_equal ~printer:string_of_int 20 (int_max middle) let public_tree_map_put_and_get _ = let t0 = empty_tree_map in let t1 = map_put 5 "a" t0 in let t2 = map_put 3 "b" t1 in let t3 = map_put 1 "c" t2 in let t4 = map_put 13 "d" t3 in assert_equal ~printer:string_of_string "a" (map_get 5 t1); assert_equal ~printer:string_of_string "b" (map_get 3 t2); assert_equal ~printer:string_of_string "c" (map_get 1 t4) let public_var _ = let t = push_scope empty_table in let t = add_var "x" 3 t in let t = add_var "y" 4 t in let t = add_var "asdf" 14 t in assert_equal 3 (lookup "x" t) ~msg:"public_var (1)"; assert_equal 4 (lookup "y" t) ~msg:"public_var (2)"; assert_equal 14 (lookup "asdf" t) ~msg:"public_var (3)"; assert_raises (Failure ("Variable not found!")) (fun () -> lookup "z" t) ~msg:"public_var (2)" let public_scopes _ = let a = push_scope empty_table in let a = add_var "a" 10 a in let a = add_var "b" 40 a in let b = push_scope a in let b = add_var "a" 20 b in let b = add_var "c" 30 b in let c = pop_scope b in assert_equal 10 (lookup "a" c) ~msg:"public_scopes (1)"; assert_equal 40 (lookup "b" c) ~msg:"public_scopes (2)"; assert_equal 20 (lookup "a" b) ~msg:"public_scopes (3)"; assert_equal 30 (lookup "c" b) ~msg:"public_scopes (4)"; assert_raises (Failure ("Variable not found!")) (fun () -> lookup "c" c) ~msg:"public_scopes (5)" let suite = "public" >::: [ "is_elem" >:: public_contains_elem; "is_present" >:: public_is_present; "count_occ" >:: public_count_occ; "uniq" >:: public_uniq; "assoc_list" >:: public_assoc_list; "ap" >:: public_ap; "insert_and_max" >:: public_int_tree_insert_and_max; "int_tree_insert_and_mem" >:: public_int_tree_insert_and_mem; "int_tree_insert_and_size" >:: public_int_tree_insert_and_size; "tree_map_put_and_get" >:: public_tree_map_put_and_get; "var" >:: public_var; "scopes" >:: public_scopes ] let _ = run_test_tt_main suite
null
https://raw.githubusercontent.com/umd-cmsc330/cmsc330spring22/e499004813cebd2e6aeffc79088ff7279560cbf0/project2b/test/public/public.ml
ocaml
open OUnit2 open TestUtils open P2b.Data open P2b.Funs open P2b.Higher let public_contains_elem _ = let a = [] in let b = ["a";"b";"c";"d"] in let c = [91;2;96;42;100] in assert_equal ~printer:string_of_bool false @@ contains_elem a "hello"; assert_equal ~printer:string_of_bool true @@ contains_elem b "b"; assert_equal ~printer:string_of_bool false @@ contains_elem b "z"; assert_equal ~printer:string_of_bool true @@ contains_elem c 42; assert_equal ~printer:string_of_bool false @@ contains_elem c 90 let public_is_present _ = let a = [] in let b = ["w";"x";"y";"z"] in let c = [14;20;42;1;81] in assert_equal ~printer:string_of_int_list [] @@ is_present a 123; assert_equal ~printer:string_of_int_list [0;0;1;0] @@ is_present b "y"; assert_equal ~printer:string_of_int_list [0;0;0;0] @@ is_present b "v"; assert_equal ~printer:string_of_int_list [0;0;1;0;0] @@ is_present c 42; assert_equal ~printer:string_of_int_list [1;0;0;0;0] @@ is_present c 14 let public_count_occ _ = let y = ["a";"a";"b";"a"] in let z = [1;7;7;1;5;2;7;7] in let a = [true;false;false;true;false;false;false] in let b = [] in assert_equal ~printer:string_of_int_pair (3,1) @@ (count_occ y "a", count_occ y "b"); assert_equal ~printer:string_of_int_quad (2,4,1,1) @@ (count_occ z 1, count_occ z 7, count_occ z 5, count_occ z 2); assert_equal ~printer:string_of_int_pair (2,5) @@ (count_occ a true, count_occ a false); assert_equal ~printer:string_of_int_pair (0,0) @@ (count_occ b "a", count_occ b 1) let public_uniq _ = let y = ["a";"a";"b";"a"] in let z = [1;7;7;1;5;2;7;7] in let a = [true;false;false;true;false;false;false] in let b = [] in let cmp x y = if x < y then (-1) else if x = y then 0 else 1 in assert_equal ~printer:string_of_string_list ["a";"b"] @@ List.sort cmp (uniq y); assert_equal ~printer:string_of_int_list [1;2;5;7] @@ List.sort cmp (uniq z); assert_equal ~printer:string_of_bool_list [false;true] @@ List.sort cmp (uniq a); assert_equal ~printer:string_of_int_list [] @@ uniq b let public_assoc_list _ = let y = ["a";"a";"b";"a"] in let z = [1;7;7;1;5;2;7;7] in let a = [true;false;false;true;false;false;false] in let b = [] in let cmp x y = if x < y then (-1) else if x = y then 0 else 1 in assert_equal ~printer:string_of_string_int_pair_list [("a",3);("b",1)] @@ List.sort cmp (assoc_list y); assert_equal ~printer:string_of_int_pair_list [(1,2);(2,1);(5,1);(7,4)] @@ List.sort cmp (assoc_list z); assert_equal ~printer:string_of_bool_int_pair_list [(false,5);(true,2)] @@ List.sort cmp (assoc_list a); assert_equal ~printer:string_of_int_pair_list [] @@ assoc_list b let public_ap _ = let x = [5;6;7;3] in let y = [5;6;7] in let z = [7;5] in let a = [3;5;8;10;9] in let b = [3] in let c = [] in let fs1 = [((+) 2) ; (( * ) 7)] in let fs2 = [pred] in assert_equal ~printer:string_of_int_list [7;8;9;5;35;42;49;21] @@ ap fs1 x; assert_equal ~printer:string_of_int_list [7;8;9;35;42;49] @@ ap fs1 y; assert_equal ~printer:string_of_int_list [9;7;49;35] @@ ap fs1 z; assert_equal ~printer:string_of_int_list [5;7;10;12;11;21;35;56;70;63] @@ ap fs1 a; assert_equal ~printer:string_of_int_list [5;21] @@ ap fs1 b; assert_equal ~printer:string_of_int_list [] @@ ap fs1 c; assert_equal ~printer:string_of_int_list (map pred x) @@ ap fs2 x; assert_equal ~printer:string_of_int_list (map pred y) @@ ap fs2 y; assert_equal ~printer:string_of_int_list (map pred z) @@ ap fs2 z; assert_equal ~printer:string_of_int_list (map pred a) @@ ap fs2 a; assert_equal ~printer:string_of_int_list (map pred b) @@ ap fs2 b; assert_equal ~printer:string_of_int_list (map pred c) @@ ap fs2 c let public_int_tree_insert_and_mem _ = let root = int_insert 20 (int_insert 10 empty_int_tree) in let left = int_insert 9 (int_insert 5 root) in let middle = int_insert 15 (int_insert 13 left) in let right = int_insert 29 (int_insert 21 middle) in assert_equal ~printer:string_of_bool true (int_mem 10 right); assert_equal ~printer:string_of_bool true (int_mem 15 right); assert_equal ~printer:string_of_bool true (int_mem 20 right); assert_equal ~printer:string_of_bool true (int_mem 5 right) let public_int_tree_insert_and_size _ = let root = int_insert 20 (int_insert 10 empty_int_tree) in let left = int_insert 9 (int_insert 5 root) in let middle = int_insert 15 (int_insert 13 left) in let right = int_insert 29 (int_insert 21 middle) in assert_equal ~printer:string_of_int 8 (int_size right); assert_equal ~printer:string_of_int 6 (int_size middle); assert_equal ~printer:string_of_int 4 (int_size left); assert_equal ~printer:string_of_int 2 (int_size root) let public_int_tree_insert_and_max _ = let root = int_insert 20 (int_insert 10 empty_int_tree) in let left = int_insert 9 (int_insert 5 root) in let middle = int_insert 15 (int_insert 13 left) in let right = int_insert 29 (int_insert 21 middle) in assert_equal ~printer:string_of_int 29 (int_max right); assert_equal ~printer:string_of_int 20 (int_max middle) let public_tree_map_put_and_get _ = let t0 = empty_tree_map in let t1 = map_put 5 "a" t0 in let t2 = map_put 3 "b" t1 in let t3 = map_put 1 "c" t2 in let t4 = map_put 13 "d" t3 in assert_equal ~printer:string_of_string "a" (map_get 5 t1); assert_equal ~printer:string_of_string "b" (map_get 3 t2); assert_equal ~printer:string_of_string "c" (map_get 1 t4) let public_var _ = let t = push_scope empty_table in let t = add_var "x" 3 t in let t = add_var "y" 4 t in let t = add_var "asdf" 14 t in assert_equal 3 (lookup "x" t) ~msg:"public_var (1)"; assert_equal 4 (lookup "y" t) ~msg:"public_var (2)"; assert_equal 14 (lookup "asdf" t) ~msg:"public_var (3)"; assert_raises (Failure ("Variable not found!")) (fun () -> lookup "z" t) ~msg:"public_var (2)" let public_scopes _ = let a = push_scope empty_table in let a = add_var "a" 10 a in let a = add_var "b" 40 a in let b = push_scope a in let b = add_var "a" 20 b in let b = add_var "c" 30 b in let c = pop_scope b in assert_equal 10 (lookup "a" c) ~msg:"public_scopes (1)"; assert_equal 40 (lookup "b" c) ~msg:"public_scopes (2)"; assert_equal 20 (lookup "a" b) ~msg:"public_scopes (3)"; assert_equal 30 (lookup "c" b) ~msg:"public_scopes (4)"; assert_raises (Failure ("Variable not found!")) (fun () -> lookup "c" c) ~msg:"public_scopes (5)" let suite = "public" >::: [ "is_elem" >:: public_contains_elem; "is_present" >:: public_is_present; "count_occ" >:: public_count_occ; "uniq" >:: public_uniq; "assoc_list" >:: public_assoc_list; "ap" >:: public_ap; "insert_and_max" >:: public_int_tree_insert_and_max; "int_tree_insert_and_mem" >:: public_int_tree_insert_and_mem; "int_tree_insert_and_size" >:: public_int_tree_insert_and_size; "tree_map_put_and_get" >:: public_tree_map_put_and_get; "var" >:: public_var; "scopes" >:: public_scopes ] let _ = run_test_tt_main suite
4de3989271037f23a94c7ee0c404325f286ce7dc32caca4350d04c41d1a6459c
expipiplus1/vulkan
VK_KHR_dynamic_rendering.hs
{-# language CPP #-} -- | = Name -- -- VK_KHR_dynamic_rendering - device extension -- -- == VK_KHR_dynamic_rendering -- -- [__Name String__] -- @VK_KHR_dynamic_rendering@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] 45 -- -- [__Revision__] 1 -- -- [__Extension and Version Dependencies__] -- - Requires support for Vulkan 1.0 -- -- - Requires @VK_KHR_depth_stencil_resolve@ to be enabled for any -- device-level functionality -- -- - Requires @VK_KHR_get_physical_device_properties2@ to be enabled -- for any device-level functionality -- -- [__Deprecation state__] -- -- - /Promoted/ to -- <-extensions/html/vkspec.html#versions-1.3-promotions Vulkan 1.3> -- -- [__Contact__] -- - -- <-Docs/issues/new?body=[VK_KHR_dynamic_rendering] @tobski%0A*Here describe the issue or question you have about the VK_KHR_dynamic_rendering extension* > -- -- [__Extension Proposal__] -- <-Docs/tree/main/proposals/VK_KHR_dynamic_rendering.adoc VK_KHR_dynamic_rendering> -- -- == Other Extension Metadata -- -- [__Last Modified Date__] 2021 - 10 - 06 -- -- [__Interactions and External Dependencies__] -- - Promoted to Vulkan 1.3 Core -- -- [__Contributors__] -- - , AMD -- - , Roblox -- - , Gameloft -- - , AMD -- - , Google -- - , Google -- - , Qualcomm -- - Jan - , Arm -- - , Nvidia -- - , Imagination -- - , Mobica -- - , Google -- - , Valve -- -- == Description -- -- This extension allows applications to create single-pass render pass -- instances without needing to create render pass objects or framebuffers. -- Dynamic render passes can also span across multiple primary command -- buffers, rather than relying on secondary command buffers. -- -- This extension also incorporates 'ATTACHMENT_STORE_OP_NONE_KHR' from -- @VK_QCOM_render_pass_store_ops@, enabling applications to avoid -- unnecessary synchronization when an attachment is not written during a -- render pass. -- -- == New Commands -- -- - 'cmdBeginRenderingKHR' -- - ' cmdEndRenderingKHR ' -- -- == New Structures -- -- - 'RenderingAttachmentInfoKHR' -- -- - 'RenderingInfoKHR' -- -- - Extending ' Vulkan . Core10.CommandBuffer . ' : -- -- - 'CommandBufferInheritanceRenderingInfoKHR' -- - Extending ' Vulkan . Core10.Pipeline . ' : -- -- - 'PipelineRenderingCreateInfoKHR' -- -- - Extending ' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 ' , ' Vulkan . Core10.Device . DeviceCreateInfo ' : -- -- - 'PhysicalDeviceDynamicRenderingFeaturesKHR' -- -- If -- <-extensions/html/vkspec.html#VK_AMD_mixed_attachment_samples VK_AMD_mixed_attachment_samples> -- is supported: -- -- - Extending ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo ' , ' Vulkan . Core10.Pipeline . ' : -- - ' AttachmentSampleCountInfoAMD ' -- -- If < -extensions/html/vkspec.html#VK_EXT_fragment_density_map > -- is supported: -- -- - Extending ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' : -- -- - 'RenderingFragmentDensityMapAttachmentInfoEXT' -- -- If < -extensions/html/vkspec.html#VK_KHR_fragment_shading_rate VK_KHR_fragment_shading_rate > -- is supported: -- -- - Extending ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' : -- -- - 'RenderingFragmentShadingRateAttachmentInfoKHR' -- -- If -- <-extensions/html/vkspec.html#VK_NV_framebuffer_mixed_samples VK_NV_framebuffer_mixed_samples> -- is supported: -- -- - Extending ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo ' , ' Vulkan . Core10.Pipeline . ' : -- - ' AttachmentSampleCountInfoNV ' -- -- If < -extensions/html/vkspec.html#VK_NVX_multiview_per_view_attributes VK_NVX_multiview_per_view_attributes > -- is supported: -- -- - Extending ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo ' , ' Vulkan . Core10.Pipeline . ' , ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' : -- - ' MultiviewPerViewAttributesInfoNVX ' -- -- == New Enums -- -- - 'RenderingFlagBitsKHR' -- -- == New Bitmasks -- -- - 'RenderingFlagsKHR' -- -- == New Enum Constants -- - ' KHR_DYNAMIC_RENDERING_EXTENSION_NAME ' -- -- - 'KHR_DYNAMIC_RENDERING_SPEC_VERSION' -- - Extending ' Vulkan . Core10.Enums . AttachmentStoreOp . AttachmentStoreOp ' : -- -- - 'ATTACHMENT_STORE_OP_NONE_KHR' -- - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : -- -- - 'STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR' -- - ' STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR ' -- - ' STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR ' -- - ' ' -- -- - 'STRUCTURE_TYPE_RENDERING_INFO_KHR' -- -- If -- <-extensions/html/vkspec.html#VK_AMD_mixed_attachment_samples VK_AMD_mixed_attachment_samples> -- is supported: -- - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : -- - ' Vulkan . Core10.Enums . StructureType . ' -- -- If < -extensions/html/vkspec.html#VK_EXT_fragment_density_map > -- is supported: -- -- - Extending ' Vulkan . Core10.Enums . PipelineCreateFlagBits . ' : -- - ' Vulkan . Core10.Enums . . PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT ' -- -- - 'PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT' -- - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : -- - ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT ' -- -- If < -extensions/html/vkspec.html#VK_KHR_fragment_shading_rate VK_KHR_fragment_shading_rate > -- is supported: -- -- - Extending ' Vulkan . Core10.Enums . PipelineCreateFlagBits . ' : -- - ' Vulkan . Core10.Enums . . PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR ' -- -- - 'PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR' -- - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : -- - ' Vulkan . Core10.Enums . StructureType . ' -- -- If -- <-extensions/html/vkspec.html#VK_NV_framebuffer_mixed_samples VK_NV_framebuffer_mixed_samples> -- is supported: -- - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : -- -- - 'STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV' -- -- If < -extensions/html/vkspec.html#VK_NVX_multiview_per_view_attributes VK_NVX_multiview_per_view_attributes > -- is supported: -- - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : -- - ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX ' -- = = Promotion to Vulkan 1.3 -- Functionality in this extension is included in core Vulkan 1.3 , with the suffix omitted . The original type , enum and command names are still -- available as aliases of the core functionality. -- -- == Version History -- - Revision 1 , 2021 - 10 - 06 ( ) -- -- - Initial revision -- -- == See Also -- -- 'CommandBufferInheritanceRenderingInfoKHR', -- 'PhysicalDeviceDynamicRenderingFeaturesKHR', -- 'PipelineRenderingCreateInfoKHR', 'RenderingAttachmentInfoKHR', -- 'RenderingFlagBitsKHR', 'RenderingFlagsKHR', 'RenderingInfoKHR', -- 'cmdBeginRenderingKHR', 'cmdEndRenderingKHR' -- -- == Document Notes -- -- For more information, see the -- <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_KHR_dynamic_rendering ( pattern STRUCTURE_TYPE_RENDERING_INFO_KHR , pattern STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR , pattern STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR , pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR , pattern STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR , pattern ATTACHMENT_STORE_OP_NONE_KHR , pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR , pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT , pattern STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV , cmdBeginRenderingKHR , cmdEndRenderingKHR , RenderingFragmentShadingRateAttachmentInfoKHR(..) , RenderingFragmentDensityMapAttachmentInfoEXT(..) , AttachmentSampleCountInfoAMD(..) , MultiviewPerViewAttributesInfoNVX(..) , RenderingFlagsKHR , RenderingFlagBitsKHR , PipelineRenderingCreateInfoKHR , RenderingInfoKHR , RenderingAttachmentInfoKHR , PhysicalDeviceDynamicRenderingFeaturesKHR , CommandBufferInheritanceRenderingInfoKHR , AttachmentSampleCountInfoNV , KHR_DYNAMIC_RENDERING_SPEC_VERSION , pattern KHR_DYNAMIC_RENDERING_SPEC_VERSION , KHR_DYNAMIC_RENDERING_EXTENSION_NAME , pattern KHR_DYNAMIC_RENDERING_EXTENSION_NAME ) where import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import qualified Data.Vector (imapM_) import qualified Data.Vector (length) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (cmdBeginRendering) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (cmdEndRendering) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (CommandBufferInheritanceRenderingInfo) import Vulkan.Core10.FundamentalTypes (Extent2D) import Vulkan.Core10.Enums.ImageLayout (ImageLayout) import Vulkan.Core10.Handles (ImageView) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (PhysicalDeviceDynamicRenderingFeatures) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (PipelineRenderingCreateInfo) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (RenderingAttachmentInfo) import Vulkan.Core13.Enums.RenderingFlagBits (RenderingFlagBits) import Vulkan.Core13.Enums.RenderingFlagBits (RenderingFlags) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (RenderingInfo) import Vulkan.Core10.Enums.SampleCountFlagBits (SampleCountFlagBits) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.AttachmentStoreOp (AttachmentStoreOp(ATTACHMENT_STORE_OP_NONE)) import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlags) import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlagBits(PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT)) import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlags) import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlagBits(PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_INFO)) No documentation found for TopLevel " VK_STRUCTURE_TYPE_RENDERING_INFO_KHR " pattern STRUCTURE_TYPE_RENDERING_INFO_KHR = STRUCTURE_TYPE_RENDERING_INFO No documentation found for TopLevel " VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR " pattern STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR = STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO No documentation found for TopLevel " VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR " pattern STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR = STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO No documentation found for TopLevel " VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR " pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES No documentation found for TopLevel " VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR " pattern STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR = STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO No documentation found for TopLevel " VK_ATTACHMENT_STORE_OP_NONE_KHR " pattern ATTACHMENT_STORE_OP_NONE_KHR = ATTACHMENT_STORE_OP_NONE No documentation found for TopLevel " VK_PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR " pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR = PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR No documentation found for TopLevel " VK_PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT " pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT = PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT No documentation found for TopLevel " VK_STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV " pattern STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV = STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD No documentation found for TopLevel " vkCmdBeginRenderingKHR " cmdBeginRenderingKHR = cmdBeginRendering No documentation found for TopLevel " vkCmdEndRenderingKHR " cmdEndRenderingKHR = cmdEndRendering -- | VkRenderingFragmentShadingRateAttachmentInfoKHR - Structure specifying -- fragment shading rate attachment information -- -- = Description -- -- This structure can be included in the @pNext@ chain of ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' to -- define a -- <-extensions/html/vkspec.html#primsrast-fragment-shading-rate-attachment fragment shading rate attachment>. If is ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , or if this -- structure is not specified, the implementation behaves as if a valid -- shading rate attachment was specified with all texels specifying a -- single pixel per fragment. -- -- == Valid Usage -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06147# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , -- @layout@ /must/ be ' Vulkan . Core10.Enums . ImageLayout . IMAGE_LAYOUT_GENERAL ' or ' Vulkan . Core10.Enums . ImageLayout . IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR ' -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06148# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , it -- /must/ have been created with ' Vulkan . Core10.Enums . ImageUsageFlagBits . IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR ' -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06149# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.width@ /must/ be a power of two -- value -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06150# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.width@ /must/ be less than or equal -- to < -extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSize maxFragmentShadingRateAttachmentTexelSize.width > -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06151# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.width@ /must/ be greater than or -- equal to < -extensions/html/vkspec.html#limits-minFragmentShadingRateAttachmentTexelSize minFragmentShadingRateAttachmentTexelSize.width > -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06152# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.height@ /must/ be a power of two -- value -- - # VUID - VkRenderingFragmentShadingRateAttachmentInfoKHR - imageView-06153 # If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.height@ /must/ be less than or equal -- to < -extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSize > -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06154# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.height@ /must/ be greater than or -- equal to -- <-extensions/html/vkspec.html#limits-minFragmentShadingRateAttachmentTexelSize minFragmentShadingRateAttachmentTexelSize.height> -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06155# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , the quotient of @shadingRateAttachmentTexelSize.width@ and @shadingRateAttachmentTexelSize.height@ /must/ be less than or equal -- to -- <-extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSizeAspectRatio maxFragmentShadingRateAttachmentTexelSizeAspectRatio> -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06156# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , the quotient of @shadingRateAttachmentTexelSize.height@ and @shadingRateAttachmentTexelSize.width@ /must/ be less than or equal -- to -- <-extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSizeAspectRatio maxFragmentShadingRateAttachmentTexelSizeAspectRatio> -- -- == Valid Usage (Implicit) -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-sType-sType# -- @sType@ /must/ be ' Vulkan . Core10.Enums . StructureType . ' -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-parameter# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @imageView@ /must/ be a valid ' Vulkan . Core10.Handles . ImageView ' -- handle -- -- - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageLayout-parameter# -- @imageLayout@ /must/ be a valid ' Vulkan . Core10.Enums . ImageLayout . ImageLayout ' value -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>, < -extensions/html/vkspec.html#VK_KHR_fragment_shading_rate VK_KHR_fragment_shading_rate > , ' Vulkan . Core10.FundamentalTypes . Extent2D ' , ' Vulkan . Core10.Enums . ImageLayout . ImageLayout ' , ' Vulkan . Core10.Handles . ImageView ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data RenderingFragmentShadingRateAttachmentInfoKHR = RenderingFragmentShadingRateAttachmentInfoKHR { -- | @imageView@ is the image view that will be used as a fragment shading -- rate attachment. imageView :: ImageView | @imageLayout@ is the layout that will be in during -- rendering. imageLayout :: ImageLayout , -- | @shadingRateAttachmentTexelSize@ specifies the number of pixels -- corresponding to each texel in @imageView@. shadingRateAttachmentTexelSize :: Extent2D } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (RenderingFragmentShadingRateAttachmentInfoKHR) #endif deriving instance Show RenderingFragmentShadingRateAttachmentInfoKHR instance ToCStruct RenderingFragmentShadingRateAttachmentInfoKHR where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p RenderingFragmentShadingRateAttachmentInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageView)) (imageView) poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (imageLayout) poke ((p `plusPtr` 28 :: Ptr Extent2D)) (shadingRateAttachmentTexelSize) f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (zero) poke ((p `plusPtr` 28 :: Ptr Extent2D)) (zero) f instance FromCStruct RenderingFragmentShadingRateAttachmentInfoKHR where peekCStruct p = do imageView <- peek @ImageView ((p `plusPtr` 16 :: Ptr ImageView)) imageLayout <- peek @ImageLayout ((p `plusPtr` 24 :: Ptr ImageLayout)) shadingRateAttachmentTexelSize <- peekCStruct @Extent2D ((p `plusPtr` 28 :: Ptr Extent2D)) pure $ RenderingFragmentShadingRateAttachmentInfoKHR imageView imageLayout shadingRateAttachmentTexelSize instance Storable RenderingFragmentShadingRateAttachmentInfoKHR where sizeOf ~_ = 40 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero RenderingFragmentShadingRateAttachmentInfoKHR where zero = RenderingFragmentShadingRateAttachmentInfoKHR zero zero zero -- | VkRenderingFragmentDensityMapAttachmentInfoEXT - Structure specifying -- fragment shading rate attachment information -- -- = Description -- -- This structure can be included in the @pNext@ chain of ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' to -- define a fragment density map. If this structure is not included in the @pNext@ chain , is treated as ' Vulkan . Core10.APIConstants . NULL_HANDLE ' . -- -- == Valid Usage -- -- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-06157# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , -- @layout@ /must/ be ' Vulkan . Core10.Enums . ImageLayout . IMAGE_LAYOUT_GENERAL ' or ' Vulkan . Core10.Enums . ImageLayout . IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT ' -- -- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-06158# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , it -- /must/ have been created with ' Vulkan . Core10.Enums . ImageUsageFlagBits . IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT ' -- -- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-06159# If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , it -- /must/ not have been created with ' Vulkan . Core10.Enums . ImageCreateFlagBits . IMAGE_CREATE_SUBSAMPLED_BIT_EXT ' -- -- == Valid Usage (Implicit) -- -- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-sType-sType# -- @sType@ /must/ be ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT ' -- -- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-parameter# @imageView@ /must/ be a valid ' Vulkan . Core10.Handles . ImageView ' -- handle -- -- - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageLayout-parameter# -- @imageLayout@ /must/ be a valid ' Vulkan . Core10.Enums . ImageLayout . ImageLayout ' value -- -- = See Also -- < -extensions/html/vkspec.html#VK_EXT_fragment_density_map > , -- <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>, ' Vulkan . Core10.Enums . ImageLayout . ImageLayout ' , ' Vulkan . Core10.Handles . ImageView ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data RenderingFragmentDensityMapAttachmentInfoEXT = RenderingFragmentDensityMapAttachmentInfoEXT { -- | @imageView@ is the image view that will be used as a fragment density -- map attachment. imageView :: ImageView | @imageLayout@ is the layout that will be in during -- rendering. imageLayout :: ImageLayout } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (RenderingFragmentDensityMapAttachmentInfoEXT) #endif deriving instance Show RenderingFragmentDensityMapAttachmentInfoEXT instance ToCStruct RenderingFragmentDensityMapAttachmentInfoEXT where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p RenderingFragmentDensityMapAttachmentInfoEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageView)) (imageView) poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (imageLayout) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageView)) (zero) poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (zero) f instance FromCStruct RenderingFragmentDensityMapAttachmentInfoEXT where peekCStruct p = do imageView <- peek @ImageView ((p `plusPtr` 16 :: Ptr ImageView)) imageLayout <- peek @ImageLayout ((p `plusPtr` 24 :: Ptr ImageLayout)) pure $ RenderingFragmentDensityMapAttachmentInfoEXT imageView imageLayout instance Storable RenderingFragmentDensityMapAttachmentInfoEXT where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero RenderingFragmentDensityMapAttachmentInfoEXT where zero = RenderingFragmentDensityMapAttachmentInfoEXT zero zero -- | VkAttachmentSampleCountInfoAMD - Structure specifying command buffer -- inheritance info for dynamic render pass instances -- -- = Description -- -- If ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo'::@renderPass@ is ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , ' Vulkan . Core10.Enums . CommandBufferUsageFlagBits . COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT ' -- is specified in ' Vulkan . Core10.CommandBuffer . , and the -- @pNext@ chain of ' Vulkan . Core10.CommandBuffer . ' includes ' AttachmentSampleCountInfoAMD ' , then this structure defines the sample -- counts of each attachment within the render pass instance. If ' AttachmentSampleCountInfoAMD ' is not included , the value of ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . CommandBufferInheritanceRenderingInfo'::@rasterizationSamples@ -- is used as the sample count for each attachment. If ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo'::@renderPass@ is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , or ' Vulkan . Core10.Enums . CommandBufferUsageFlagBits . COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT ' -- is not specified in ' Vulkan . Core10.CommandBuffer . , -- parameters of this structure are ignored. -- ' AttachmentSampleCountInfoAMD ' also be included in the @pNext@ chain of ' Vulkan . Core10.Pipeline . ' . When a -- graphics pipeline is created without a ' Vulkan . Core10.Handles . RenderPass ' , if this structure is present in the @pNext@ chain of ' Vulkan . Core10.Pipeline . ' , it -- specifies the sample count of attachments used for rendering. If this -- structure is not specified, and the pipeline does not include a ' Vulkan . Core10.Handles . RenderPass ' , the value of ' Vulkan . Core10.Pipeline . PipelineMultisampleStateCreateInfo'::@rasterizationSamples@ -- is used as the sample count for each attachment. If a graphics pipeline is created with a valid ' Vulkan . Core10.Handles . RenderPass ' , parameters -- of this structure are ignored. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_AMD_mixed_attachment_samples VK_AMD_mixed_attachment_samples>, -- <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>, -- <-extensions/html/vkspec.html#VK_NV_framebuffer_mixed_samples VK_NV_framebuffer_mixed_samples>, ' Vulkan . Core10.Enums . SampleCountFlagBits . SampleCountFlagBits ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data AttachmentSampleCountInfoAMD = AttachmentSampleCountInfoAMD | @pColorAttachmentSamples@ is a pointer to an array of ' Vulkan . Core10.Enums . SampleCountFlagBits . SampleCountFlagBits ' values -- defining the sample count of color attachments. colorAttachmentSamples :: Vector SampleCountFlagBits , -- | @depthStencilAttachmentSamples@ is a ' Vulkan . Core10.Enums . SampleCountFlagBits . SampleCountFlagBits ' value defining the sample count of a depth\/stencil attachment . depthStencilAttachmentSamples :: SampleCountFlagBits } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (AttachmentSampleCountInfoAMD) #endif deriving instance Show AttachmentSampleCountInfoAMD instance ToCStruct AttachmentSampleCountInfoAMD where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p AttachmentSampleCountInfoAMD{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (colorAttachmentSamples)) :: Word32)) pPColorAttachmentSamples' <- ContT $ allocaBytes @SampleCountFlagBits ((Data.Vector.length (colorAttachmentSamples)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPColorAttachmentSamples' `plusPtr` (4 * (i)) :: Ptr SampleCountFlagBits) (e)) (colorAttachmentSamples) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr SampleCountFlagBits))) (pPColorAttachmentSamples') lift $ poke ((p `plusPtr` 32 :: Ptr SampleCountFlagBits)) (depthStencilAttachmentSamples) lift $ f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) f instance FromCStruct AttachmentSampleCountInfoAMD where peekCStruct p = do colorAttachmentCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pColorAttachmentSamples <- peek @(Ptr SampleCountFlagBits) ((p `plusPtr` 24 :: Ptr (Ptr SampleCountFlagBits))) pColorAttachmentSamples' <- generateM (fromIntegral colorAttachmentCount) (\i -> peek @SampleCountFlagBits ((pColorAttachmentSamples `advancePtrBytes` (4 * (i)) :: Ptr SampleCountFlagBits))) depthStencilAttachmentSamples <- peek @SampleCountFlagBits ((p `plusPtr` 32 :: Ptr SampleCountFlagBits)) pure $ AttachmentSampleCountInfoAMD pColorAttachmentSamples' depthStencilAttachmentSamples instance Zero AttachmentSampleCountInfoAMD where zero = AttachmentSampleCountInfoAMD mempty zero -- | VkMultiviewPerViewAttributesInfoNVX - Structure specifying the multiview -- per-attribute properties -- -- = Description -- -- When dynamic render pass instances are being used, instead of specifying ' Vulkan . Core10.Enums . SubpassDescriptionFlagBits . SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX ' -- or ' Vulkan . Core10.Enums . SubpassDescriptionFlagBits . SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX ' in the subpass description flags , the per - attribute properties of the -- render pass instance /must/ be specified by the ' MultiviewPerViewAttributesInfoNVX ' structure Include the ' MultiviewPerViewAttributesInfoNVX ' structure in the @pNext@ chain of ' Vulkan . Core10.Pipeline . ' when creating a -- graphics pipeline for dynamic rendering, ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' -- when starting a dynamic render pass instance, and ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo ' when -- specifying the dynamic render pass instance parameters for secondary -- command buffers. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>, < -extensions/html/vkspec.html#VK_NVX_multiview_per_view_attributes VK_NVX_multiview_per_view_attributes > , ' Vulkan . Core10.FundamentalTypes . Bool32 ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data MultiviewPerViewAttributesInfoNVX = MultiviewPerViewAttributesInfoNVX { -- | @perViewAttributes@ specifies that shaders compiled for this pipeline -- write the attributes for all views in a single invocation of each vertex -- processing stage. All pipelines executed within a render pass instance -- that includes this bit /must/ write per-view attributes to the -- @*PerViewNV[]@ shader outputs, in addition to the non-per-view (e.g. -- @Position@) outputs. perViewAttributes :: Bool , -- | @perViewAttributesPositionXOnly@ specifies that shaders compiled for -- this pipeline use per-view positions which only differ in value in the x component . Per - view viewport mask also be used . perViewAttributesPositionXOnly :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (MultiviewPerViewAttributesInfoNVX) #endif deriving instance Show MultiviewPerViewAttributesInfoNVX instance ToCStruct MultiviewPerViewAttributesInfoNVX where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p MultiviewPerViewAttributesInfoNVX{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (perViewAttributes)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (perViewAttributesPositionXOnly)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct MultiviewPerViewAttributesInfoNVX where peekCStruct p = do perViewAttributes <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) perViewAttributesPositionXOnly <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32)) pure $ MultiviewPerViewAttributesInfoNVX (bool32ToBool perViewAttributes) (bool32ToBool perViewAttributesPositionXOnly) instance Storable MultiviewPerViewAttributesInfoNVX where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero MultiviewPerViewAttributesInfoNVX where zero = MultiviewPerViewAttributesInfoNVX zero zero No documentation found for TopLevel " " type RenderingFlagsKHR = RenderingFlags No documentation found for TopLevel " VkRenderingFlagBitsKHR " type RenderingFlagBitsKHR = RenderingFlagBits No documentation found for TopLevel " VkPipelineRenderingCreateInfoKHR " type PipelineRenderingCreateInfoKHR = PipelineRenderingCreateInfo No documentation found for TopLevel " VkRenderingInfoKHR " type RenderingInfoKHR = RenderingInfo No documentation found for TopLevel " VkRenderingAttachmentInfoKHR " type RenderingAttachmentInfoKHR = RenderingAttachmentInfo No documentation found for TopLevel " VkPhysicalDeviceDynamicRenderingFeaturesKHR " type PhysicalDeviceDynamicRenderingFeaturesKHR = PhysicalDeviceDynamicRenderingFeatures No documentation found for TopLevel " VkCommandBufferInheritanceRenderingInfoKHR " type CommandBufferInheritanceRenderingInfoKHR = CommandBufferInheritanceRenderingInfo No documentation found for TopLevel " VkAttachmentSampleCountInfoNV " type AttachmentSampleCountInfoNV = AttachmentSampleCountInfoAMD type KHR_DYNAMIC_RENDERING_SPEC_VERSION = 1 No documentation found for TopLevel " VK_KHR_DYNAMIC_RENDERING_SPEC_VERSION " pattern KHR_DYNAMIC_RENDERING_SPEC_VERSION :: forall a . Integral a => a pattern KHR_DYNAMIC_RENDERING_SPEC_VERSION = 1 type KHR_DYNAMIC_RENDERING_EXTENSION_NAME = "VK_KHR_dynamic_rendering" No documentation found for TopLevel " VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME " pattern KHR_DYNAMIC_RENDERING_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_DYNAMIC_RENDERING_EXTENSION_NAME = "VK_KHR_dynamic_rendering"
null
https://raw.githubusercontent.com/expipiplus1/vulkan/d765efafb2ea2965ceba268e9e4e54cbd415aa33/src/Vulkan/Extensions/VK_KHR_dynamic_rendering.hs
haskell
# language CPP # | = Name VK_KHR_dynamic_rendering - device extension == VK_KHR_dynamic_rendering [__Name String__] @VK_KHR_dynamic_rendering@ [__Extension Type__] Device extension [__Registered Extension Number__] [__Revision__] [__Extension and Version Dependencies__] - Requires @VK_KHR_depth_stencil_resolve@ to be enabled for any device-level functionality - Requires @VK_KHR_get_physical_device_properties2@ to be enabled for any device-level functionality [__Deprecation state__] - /Promoted/ to <-extensions/html/vkspec.html#versions-1.3-promotions Vulkan 1.3> [__Contact__] <-Docs/issues/new?body=[VK_KHR_dynamic_rendering] @tobski%0A*Here describe the issue or question you have about the VK_KHR_dynamic_rendering extension* > [__Extension Proposal__] <-Docs/tree/main/proposals/VK_KHR_dynamic_rendering.adoc VK_KHR_dynamic_rendering> == Other Extension Metadata [__Last Modified Date__] [__Interactions and External Dependencies__] [__Contributors__] == Description This extension allows applications to create single-pass render pass instances without needing to create render pass objects or framebuffers. Dynamic render passes can also span across multiple primary command buffers, rather than relying on secondary command buffers. This extension also incorporates 'ATTACHMENT_STORE_OP_NONE_KHR' from @VK_QCOM_render_pass_store_ops@, enabling applications to avoid unnecessary synchronization when an attachment is not written during a render pass. == New Commands - 'cmdBeginRenderingKHR' == New Structures - 'RenderingAttachmentInfoKHR' - 'RenderingInfoKHR' - Extending - 'CommandBufferInheritanceRenderingInfoKHR' - 'PipelineRenderingCreateInfoKHR' - Extending - 'PhysicalDeviceDynamicRenderingFeaturesKHR' If <-extensions/html/vkspec.html#VK_AMD_mixed_attachment_samples VK_AMD_mixed_attachment_samples> is supported: - Extending If is supported: - Extending - 'RenderingFragmentDensityMapAttachmentInfoEXT' If is supported: - Extending - 'RenderingFragmentShadingRateAttachmentInfoKHR' If <-extensions/html/vkspec.html#VK_NV_framebuffer_mixed_samples VK_NV_framebuffer_mixed_samples> is supported: - Extending If is supported: - Extending == New Enums - 'RenderingFlagBitsKHR' == New Bitmasks - 'RenderingFlagsKHR' == New Enum Constants - 'KHR_DYNAMIC_RENDERING_SPEC_VERSION' - 'ATTACHMENT_STORE_OP_NONE_KHR' - 'STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR' - 'STRUCTURE_TYPE_RENDERING_INFO_KHR' If <-extensions/html/vkspec.html#VK_AMD_mixed_attachment_samples VK_AMD_mixed_attachment_samples> is supported: If is supported: - Extending - 'PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT' If is supported: - Extending - 'PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR' If <-extensions/html/vkspec.html#VK_NV_framebuffer_mixed_samples VK_NV_framebuffer_mixed_samples> is supported: - 'STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV' If is supported: available as aliases of the core functionality. == Version History - Initial revision == See Also 'CommandBufferInheritanceRenderingInfoKHR', 'PhysicalDeviceDynamicRenderingFeaturesKHR', 'PipelineRenderingCreateInfoKHR', 'RenderingAttachmentInfoKHR', 'RenderingFlagBitsKHR', 'RenderingFlagsKHR', 'RenderingInfoKHR', 'cmdBeginRenderingKHR', 'cmdEndRenderingKHR' == Document Notes For more information, see the <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering Vulkan Specification> This page is a generated document. Fixes and changes should be made to the generator scripts, not directly. | VkRenderingFragmentShadingRateAttachmentInfoKHR - Structure specifying fragment shading rate attachment information = Description This structure can be included in the @pNext@ chain of define a <-extensions/html/vkspec.html#primsrast-fragment-shading-rate-attachment fragment shading rate attachment>. structure is not specified, the implementation behaves as if a valid shading rate attachment was specified with all texels specifying a single pixel per fragment. == Valid Usage - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06147# @layout@ /must/ be - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06148# /must/ have been created with - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06149# value - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06150# to - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06151# equal to - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06152# value to - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06154# equal to <-extensions/html/vkspec.html#limits-minFragmentShadingRateAttachmentTexelSize minFragmentShadingRateAttachmentTexelSize.height> - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06155# to <-extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSizeAspectRatio maxFragmentShadingRateAttachmentTexelSizeAspectRatio> - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-06156# to <-extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSizeAspectRatio maxFragmentShadingRateAttachmentTexelSizeAspectRatio> == Valid Usage (Implicit) - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-sType-sType# @sType@ /must/ be - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageView-parameter# handle - #VUID-VkRenderingFragmentShadingRateAttachmentInfoKHR-imageLayout-parameter# @imageLayout@ /must/ be a valid = See Also <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>, | @imageView@ is the image view that will be used as a fragment shading rate attachment. rendering. | @shadingRateAttachmentTexelSize@ specifies the number of pixels corresponding to each texel in @imageView@. | VkRenderingFragmentDensityMapAttachmentInfoEXT - Structure specifying fragment shading rate attachment information = Description This structure can be included in the @pNext@ chain of define a fragment density map. If this structure is not included in the == Valid Usage - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-06157# @layout@ /must/ be - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-06158# /must/ have been created with - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-06159# /must/ not have been created with == Valid Usage (Implicit) - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-sType-sType# @sType@ /must/ be - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageView-parameter# handle - #VUID-VkRenderingFragmentDensityMapAttachmentInfoEXT-imageLayout-parameter# @imageLayout@ /must/ be a valid = See Also <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>, | @imageView@ is the image view that will be used as a fragment density map attachment. rendering. | VkAttachmentSampleCountInfoAMD - Structure specifying command buffer inheritance info for dynamic render pass instances = Description If is specified in @pNext@ chain of counts of each attachment within the render pass instance. If is used as the sample count for each attachment. If is not specified in parameters of this structure are ignored. graphics pipeline is created without a specifies the sample count of attachments used for rendering. If this structure is not specified, and the pipeline does not include a is used as the sample count for each attachment. If a graphics pipeline of this structure are ignored. == Valid Usage (Implicit) = See Also <-extensions/html/vkspec.html#VK_AMD_mixed_attachment_samples VK_AMD_mixed_attachment_samples>, <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>, <-extensions/html/vkspec.html#VK_NV_framebuffer_mixed_samples VK_NV_framebuffer_mixed_samples>, defining the sample count of color attachments. | @depthStencilAttachmentSamples@ is a | VkMultiviewPerViewAttributesInfoNVX - Structure specifying the multiview per-attribute properties = Description When dynamic render pass instances are being used, instead of specifying or render pass instance /must/ be specified by the graphics pipeline for dynamic rendering, when starting a dynamic render pass instance, and specifying the dynamic render pass instance parameters for secondary command buffers. == Valid Usage (Implicit) = See Also <-extensions/html/vkspec.html#VK_KHR_dynamic_rendering VK_KHR_dynamic_rendering>, | @perViewAttributes@ specifies that shaders compiled for this pipeline write the attributes for all views in a single invocation of each vertex processing stage. All pipelines executed within a render pass instance that includes this bit /must/ write per-view attributes to the @*PerViewNV[]@ shader outputs, in addition to the non-per-view (e.g. @Position@) outputs. | @perViewAttributesPositionXOnly@ specifies that shaders compiled for this pipeline use per-view positions which only differ in value in the x
45 1 - Requires support for Vulkan 1.0 - 2021 - 10 - 06 - Promoted to Vulkan 1.3 Core - , AMD - , Roblox - , Gameloft - , AMD - , Google - , Google - , Qualcomm - Jan - , Arm - , Nvidia - , Imagination - , Mobica - , Google - , Valve - ' cmdEndRenderingKHR ' ' Vulkan . Core10.CommandBuffer . ' : - Extending ' Vulkan . Core10.Pipeline . ' : ' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 ' , ' Vulkan . Core10.Device . DeviceCreateInfo ' : ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo ' , ' Vulkan . Core10.Pipeline . ' : - ' AttachmentSampleCountInfoAMD ' < -extensions/html/vkspec.html#VK_EXT_fragment_density_map > ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' : < -extensions/html/vkspec.html#VK_KHR_fragment_shading_rate VK_KHR_fragment_shading_rate > ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' : ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo ' , ' Vulkan . Core10.Pipeline . ' : - ' AttachmentSampleCountInfoNV ' < -extensions/html/vkspec.html#VK_NVX_multiview_per_view_attributes VK_NVX_multiview_per_view_attributes > ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo ' , ' Vulkan . Core10.Pipeline . ' , ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' : - ' MultiviewPerViewAttributesInfoNVX ' - ' KHR_DYNAMIC_RENDERING_EXTENSION_NAME ' - Extending ' Vulkan . Core10.Enums . AttachmentStoreOp . AttachmentStoreOp ' : - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : - ' STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR ' - ' STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR ' - ' ' - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : - ' Vulkan . Core10.Enums . StructureType . ' < -extensions/html/vkspec.html#VK_EXT_fragment_density_map > ' Vulkan . Core10.Enums . PipelineCreateFlagBits . ' : - ' Vulkan . Core10.Enums . . PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT ' - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : - ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT ' < -extensions/html/vkspec.html#VK_KHR_fragment_shading_rate VK_KHR_fragment_shading_rate > ' Vulkan . Core10.Enums . PipelineCreateFlagBits . ' : - ' Vulkan . Core10.Enums . . PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR ' - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : - ' Vulkan . Core10.Enums . StructureType . ' - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : < -extensions/html/vkspec.html#VK_NVX_multiview_per_view_attributes VK_NVX_multiview_per_view_attributes > - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : - ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX ' = = Promotion to Vulkan 1.3 Functionality in this extension is included in core Vulkan 1.3 , with the suffix omitted . The original type , enum and command names are still - Revision 1 , 2021 - 10 - 06 ( ) module Vulkan.Extensions.VK_KHR_dynamic_rendering ( pattern STRUCTURE_TYPE_RENDERING_INFO_KHR , pattern STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR , pattern STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR , pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR , pattern STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR , pattern ATTACHMENT_STORE_OP_NONE_KHR , pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR , pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT , pattern STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV , cmdBeginRenderingKHR , cmdEndRenderingKHR , RenderingFragmentShadingRateAttachmentInfoKHR(..) , RenderingFragmentDensityMapAttachmentInfoEXT(..) , AttachmentSampleCountInfoAMD(..) , MultiviewPerViewAttributesInfoNVX(..) , RenderingFlagsKHR , RenderingFlagBitsKHR , PipelineRenderingCreateInfoKHR , RenderingInfoKHR , RenderingAttachmentInfoKHR , PhysicalDeviceDynamicRenderingFeaturesKHR , CommandBufferInheritanceRenderingInfoKHR , AttachmentSampleCountInfoNV , KHR_DYNAMIC_RENDERING_SPEC_VERSION , pattern KHR_DYNAMIC_RENDERING_SPEC_VERSION , KHR_DYNAMIC_RENDERING_EXTENSION_NAME , pattern KHR_DYNAMIC_RENDERING_EXTENSION_NAME ) where import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import qualified Data.Vector (imapM_) import qualified Data.Vector (length) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (cmdBeginRendering) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (cmdEndRendering) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (CommandBufferInheritanceRenderingInfo) import Vulkan.Core10.FundamentalTypes (Extent2D) import Vulkan.Core10.Enums.ImageLayout (ImageLayout) import Vulkan.Core10.Handles (ImageView) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (PhysicalDeviceDynamicRenderingFeatures) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (PipelineRenderingCreateInfo) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (RenderingAttachmentInfo) import Vulkan.Core13.Enums.RenderingFlagBits (RenderingFlagBits) import Vulkan.Core13.Enums.RenderingFlagBits (RenderingFlags) import Vulkan.Core13.Promoted_From_VK_KHR_dynamic_rendering (RenderingInfo) import Vulkan.Core10.Enums.SampleCountFlagBits (SampleCountFlagBits) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.AttachmentStoreOp (AttachmentStoreOp(ATTACHMENT_STORE_OP_NONE)) import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlags) import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlagBits(PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT)) import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlags) import Vulkan.Core10.Enums.PipelineCreateFlagBits (PipelineCreateFlagBits(PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_RENDERING_INFO)) No documentation found for TopLevel " VK_STRUCTURE_TYPE_RENDERING_INFO_KHR " pattern STRUCTURE_TYPE_RENDERING_INFO_KHR = STRUCTURE_TYPE_RENDERING_INFO No documentation found for TopLevel " VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR " pattern STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR = STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO No documentation found for TopLevel " VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR " pattern STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR = STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO No documentation found for TopLevel " VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR " pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES No documentation found for TopLevel " VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR " pattern STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO_KHR = STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_RENDERING_INFO No documentation found for TopLevel " VK_ATTACHMENT_STORE_OP_NONE_KHR " pattern ATTACHMENT_STORE_OP_NONE_KHR = ATTACHMENT_STORE_OP_NONE No documentation found for TopLevel " VK_PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR " pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR = PIPELINE_CREATE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR No documentation found for TopLevel " VK_PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT " pattern PIPELINE_RASTERIZATION_STATE_CREATE_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT = PIPELINE_CREATE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_BIT_EXT No documentation found for TopLevel " VK_STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV " pattern STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV = STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD No documentation found for TopLevel " vkCmdBeginRenderingKHR " cmdBeginRenderingKHR = cmdBeginRendering No documentation found for TopLevel " vkCmdEndRenderingKHR " cmdEndRenderingKHR = cmdEndRendering ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' to If is ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , or if this If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , ' Vulkan . Core10.Enums . ImageLayout . IMAGE_LAYOUT_GENERAL ' or ' Vulkan . Core10.Enums . ImageLayout . IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR ' If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , it ' Vulkan . Core10.Enums . ImageUsageFlagBits . IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR ' If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.width@ /must/ be a power of two If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.width@ /must/ be less than or equal < -extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSize maxFragmentShadingRateAttachmentTexelSize.width > If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.width@ /must/ be greater than or < -extensions/html/vkspec.html#limits-minFragmentShadingRateAttachmentTexelSize minFragmentShadingRateAttachmentTexelSize.width > If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.height@ /must/ be a power of two - # VUID - VkRenderingFragmentShadingRateAttachmentInfoKHR - imageView-06153 # If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.height@ /must/ be less than or equal < -extensions/html/vkspec.html#limits-maxFragmentShadingRateAttachmentTexelSize > If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @shadingRateAttachmentTexelSize.height@ /must/ be greater than or If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , the quotient of @shadingRateAttachmentTexelSize.width@ and @shadingRateAttachmentTexelSize.height@ /must/ be less than or equal If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , the quotient of @shadingRateAttachmentTexelSize.height@ and @shadingRateAttachmentTexelSize.width@ /must/ be less than or equal ' Vulkan . Core10.Enums . StructureType . ' If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , @imageView@ /must/ be a valid ' Vulkan . Core10.Handles . ImageView ' ' Vulkan . Core10.Enums . ImageLayout . ImageLayout ' value < -extensions/html/vkspec.html#VK_KHR_fragment_shading_rate VK_KHR_fragment_shading_rate > , ' Vulkan . Core10.FundamentalTypes . Extent2D ' , ' Vulkan . Core10.Enums . ImageLayout . ImageLayout ' , ' Vulkan . Core10.Handles . ImageView ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data RenderingFragmentShadingRateAttachmentInfoKHR = RenderingFragmentShadingRateAttachmentInfoKHR imageView :: ImageView | @imageLayout@ is the layout that will be in during imageLayout :: ImageLayout shadingRateAttachmentTexelSize :: Extent2D } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (RenderingFragmentShadingRateAttachmentInfoKHR) #endif deriving instance Show RenderingFragmentShadingRateAttachmentInfoKHR instance ToCStruct RenderingFragmentShadingRateAttachmentInfoKHR where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p RenderingFragmentShadingRateAttachmentInfoKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageView)) (imageView) poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (imageLayout) poke ((p `plusPtr` 28 :: Ptr Extent2D)) (shadingRateAttachmentTexelSize) f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (zero) poke ((p `plusPtr` 28 :: Ptr Extent2D)) (zero) f instance FromCStruct RenderingFragmentShadingRateAttachmentInfoKHR where peekCStruct p = do imageView <- peek @ImageView ((p `plusPtr` 16 :: Ptr ImageView)) imageLayout <- peek @ImageLayout ((p `plusPtr` 24 :: Ptr ImageLayout)) shadingRateAttachmentTexelSize <- peekCStruct @Extent2D ((p `plusPtr` 28 :: Ptr Extent2D)) pure $ RenderingFragmentShadingRateAttachmentInfoKHR imageView imageLayout shadingRateAttachmentTexelSize instance Storable RenderingFragmentShadingRateAttachmentInfoKHR where sizeOf ~_ = 40 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero RenderingFragmentShadingRateAttachmentInfoKHR where zero = RenderingFragmentShadingRateAttachmentInfoKHR zero zero zero ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' to @pNext@ chain , is treated as ' Vulkan . Core10.APIConstants . NULL_HANDLE ' . If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , ' Vulkan . Core10.Enums . ImageLayout . IMAGE_LAYOUT_GENERAL ' or ' Vulkan . Core10.Enums . ImageLayout . IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT ' If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , it ' Vulkan . Core10.Enums . ImageUsageFlagBits . IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT ' If is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , it ' Vulkan . Core10.Enums . ImageCreateFlagBits . IMAGE_CREATE_SUBSAMPLED_BIT_EXT ' ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT ' @imageView@ /must/ be a valid ' Vulkan . Core10.Handles . ImageView ' ' Vulkan . Core10.Enums . ImageLayout . ImageLayout ' value < -extensions/html/vkspec.html#VK_EXT_fragment_density_map > , ' Vulkan . Core10.Enums . ImageLayout . ImageLayout ' , ' Vulkan . Core10.Handles . ImageView ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data RenderingFragmentDensityMapAttachmentInfoEXT = RenderingFragmentDensityMapAttachmentInfoEXT imageView :: ImageView | @imageLayout@ is the layout that will be in during imageLayout :: ImageLayout } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (RenderingFragmentDensityMapAttachmentInfoEXT) #endif deriving instance Show RenderingFragmentDensityMapAttachmentInfoEXT instance ToCStruct RenderingFragmentDensityMapAttachmentInfoEXT where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p RenderingFragmentDensityMapAttachmentInfoEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageView)) (imageView) poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (imageLayout) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_RENDERING_FRAGMENT_DENSITY_MAP_ATTACHMENT_INFO_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr ImageView)) (zero) poke ((p `plusPtr` 24 :: Ptr ImageLayout)) (zero) f instance FromCStruct RenderingFragmentDensityMapAttachmentInfoEXT where peekCStruct p = do imageView <- peek @ImageView ((p `plusPtr` 16 :: Ptr ImageView)) imageLayout <- peek @ImageLayout ((p `plusPtr` 24 :: Ptr ImageLayout)) pure $ RenderingFragmentDensityMapAttachmentInfoEXT imageView imageLayout instance Storable RenderingFragmentDensityMapAttachmentInfoEXT where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero RenderingFragmentDensityMapAttachmentInfoEXT where zero = RenderingFragmentDensityMapAttachmentInfoEXT zero zero ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo'::@renderPass@ is ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , ' Vulkan . Core10.Enums . CommandBufferUsageFlagBits . COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT ' ' Vulkan . Core10.CommandBuffer . , and the ' Vulkan . Core10.CommandBuffer . ' includes ' AttachmentSampleCountInfoAMD ' , then this structure defines the sample ' AttachmentSampleCountInfoAMD ' is not included , the value of ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . CommandBufferInheritanceRenderingInfo'::@rasterizationSamples@ ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo'::@renderPass@ is not ' Vulkan . Core10.APIConstants . NULL_HANDLE ' , or ' Vulkan . Core10.Enums . CommandBufferUsageFlagBits . COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT ' ' Vulkan . Core10.CommandBuffer . , ' AttachmentSampleCountInfoAMD ' also be included in the @pNext@ chain of ' Vulkan . Core10.Pipeline . ' . When a ' Vulkan . Core10.Handles . RenderPass ' , if this structure is present in the @pNext@ chain of ' Vulkan . Core10.Pipeline . ' , it ' Vulkan . Core10.Handles . RenderPass ' , the value of ' Vulkan . Core10.Pipeline . PipelineMultisampleStateCreateInfo'::@rasterizationSamples@ is created with a valid ' Vulkan . Core10.Handles . RenderPass ' , parameters ' Vulkan . Core10.Enums . SampleCountFlagBits . SampleCountFlagBits ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data AttachmentSampleCountInfoAMD = AttachmentSampleCountInfoAMD | @pColorAttachmentSamples@ is a pointer to an array of ' Vulkan . Core10.Enums . SampleCountFlagBits . SampleCountFlagBits ' values colorAttachmentSamples :: Vector SampleCountFlagBits ' Vulkan . Core10.Enums . SampleCountFlagBits . SampleCountFlagBits ' value defining the sample count of a depth\/stencil attachment . depthStencilAttachmentSamples :: SampleCountFlagBits } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (AttachmentSampleCountInfoAMD) #endif deriving instance Show AttachmentSampleCountInfoAMD instance ToCStruct AttachmentSampleCountInfoAMD where withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p) pokeCStruct p AttachmentSampleCountInfoAMD{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (colorAttachmentSamples)) :: Word32)) pPColorAttachmentSamples' <- ContT $ allocaBytes @SampleCountFlagBits ((Data.Vector.length (colorAttachmentSamples)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPColorAttachmentSamples' `plusPtr` (4 * (i)) :: Ptr SampleCountFlagBits) (e)) (colorAttachmentSamples) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr SampleCountFlagBits))) (pPColorAttachmentSamples') lift $ poke ((p `plusPtr` 32 :: Ptr SampleCountFlagBits)) (depthStencilAttachmentSamples) lift $ f cStructSize = 40 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_AMD) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) f instance FromCStruct AttachmentSampleCountInfoAMD where peekCStruct p = do colorAttachmentCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pColorAttachmentSamples <- peek @(Ptr SampleCountFlagBits) ((p `plusPtr` 24 :: Ptr (Ptr SampleCountFlagBits))) pColorAttachmentSamples' <- generateM (fromIntegral colorAttachmentCount) (\i -> peek @SampleCountFlagBits ((pColorAttachmentSamples `advancePtrBytes` (4 * (i)) :: Ptr SampleCountFlagBits))) depthStencilAttachmentSamples <- peek @SampleCountFlagBits ((p `plusPtr` 32 :: Ptr SampleCountFlagBits)) pure $ AttachmentSampleCountInfoAMD pColorAttachmentSamples' depthStencilAttachmentSamples instance Zero AttachmentSampleCountInfoAMD where zero = AttachmentSampleCountInfoAMD mempty zero ' Vulkan . Core10.Enums . SubpassDescriptionFlagBits . SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX ' ' Vulkan . Core10.Enums . SubpassDescriptionFlagBits . SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX ' in the subpass description flags , the per - attribute properties of the ' MultiviewPerViewAttributesInfoNVX ' structure Include the ' MultiviewPerViewAttributesInfoNVX ' structure in the @pNext@ chain of ' Vulkan . Core10.Pipeline . ' when creating a ' Vulkan . Core13.Promoted_From_VK_KHR_dynamic_rendering . RenderingInfo ' ' Vulkan . Core10.CommandBuffer . CommandBufferInheritanceInfo ' when < -extensions/html/vkspec.html#VK_NVX_multiview_per_view_attributes VK_NVX_multiview_per_view_attributes > , ' Vulkan . Core10.FundamentalTypes . Bool32 ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data MultiviewPerViewAttributesInfoNVX = MultiviewPerViewAttributesInfoNVX perViewAttributes :: Bool component . Per - view viewport mask also be used . perViewAttributesPositionXOnly :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (MultiviewPerViewAttributesInfoNVX) #endif deriving instance Show MultiviewPerViewAttributesInfoNVX instance ToCStruct MultiviewPerViewAttributesInfoNVX where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p MultiviewPerViewAttributesInfoNVX{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (perViewAttributes)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (perViewAttributesPositionXOnly)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_MULTIVIEW_PER_VIEW_ATTRIBUTES_INFO_NVX) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct MultiviewPerViewAttributesInfoNVX where peekCStruct p = do perViewAttributes <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) perViewAttributesPositionXOnly <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32)) pure $ MultiviewPerViewAttributesInfoNVX (bool32ToBool perViewAttributes) (bool32ToBool perViewAttributesPositionXOnly) instance Storable MultiviewPerViewAttributesInfoNVX where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero MultiviewPerViewAttributesInfoNVX where zero = MultiviewPerViewAttributesInfoNVX zero zero No documentation found for TopLevel " " type RenderingFlagsKHR = RenderingFlags No documentation found for TopLevel " VkRenderingFlagBitsKHR " type RenderingFlagBitsKHR = RenderingFlagBits No documentation found for TopLevel " VkPipelineRenderingCreateInfoKHR " type PipelineRenderingCreateInfoKHR = PipelineRenderingCreateInfo No documentation found for TopLevel " VkRenderingInfoKHR " type RenderingInfoKHR = RenderingInfo No documentation found for TopLevel " VkRenderingAttachmentInfoKHR " type RenderingAttachmentInfoKHR = RenderingAttachmentInfo No documentation found for TopLevel " VkPhysicalDeviceDynamicRenderingFeaturesKHR " type PhysicalDeviceDynamicRenderingFeaturesKHR = PhysicalDeviceDynamicRenderingFeatures No documentation found for TopLevel " VkCommandBufferInheritanceRenderingInfoKHR " type CommandBufferInheritanceRenderingInfoKHR = CommandBufferInheritanceRenderingInfo No documentation found for TopLevel " VkAttachmentSampleCountInfoNV " type AttachmentSampleCountInfoNV = AttachmentSampleCountInfoAMD type KHR_DYNAMIC_RENDERING_SPEC_VERSION = 1 No documentation found for TopLevel " VK_KHR_DYNAMIC_RENDERING_SPEC_VERSION " pattern KHR_DYNAMIC_RENDERING_SPEC_VERSION :: forall a . Integral a => a pattern KHR_DYNAMIC_RENDERING_SPEC_VERSION = 1 type KHR_DYNAMIC_RENDERING_EXTENSION_NAME = "VK_KHR_dynamic_rendering" No documentation found for TopLevel " VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME " pattern KHR_DYNAMIC_RENDERING_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_DYNAMIC_RENDERING_EXTENSION_NAME = "VK_KHR_dynamic_rendering"
4914cf815fdbc10b543f514b44e40363cced541b90dff571afaaf242ea2da01c
ml4tp/tcoq
cctac.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) This file is the interface between the c - c algorithm and Coq open Evd open Names open Inductiveops open Declarations open Term open Vars open Tacmach open Tactics open Typing open Ccalgo open Ccproof open Pp open CErrors open Util open Proofview.Notations open Context.Rel.Declaration let reference dir s = lazy (Coqlib.gen_reference "CC" dir s) let _f_equal = reference ["Init";"Logic"] "f_equal" let _eq_rect = reference ["Init";"Logic"] "eq_rect" let _refl_equal = reference ["Init";"Logic"] "eq_refl" let _sym_eq = reference ["Init";"Logic"] "eq_sym" let _trans_eq = reference ["Init";"Logic"] "eq_trans" let _eq = reference ["Init";"Logic"] "eq" let _False = reference ["Init";"Logic"] "False" let _True = reference ["Init";"Logic"] "True" let _I = reference ["Init";"Logic"] "I" let whd env= let infos=CClosure.create_clos_infos CClosure.betaiotazeta env in (fun t -> CClosure.whd_val infos (CClosure.inject t)) let whd_delta env= let infos=CClosure.create_clos_infos CClosure.all env in (fun t -> CClosure.whd_val infos (CClosure.inject t)) (* decompose member of equality in an applicative format *) (** FIXME: evar leak *) let sf_of env sigma c = e_sort_of env (ref sigma) c let rec decompose_term env sigma t= match kind_of_term (whd env t) with App (f,args)-> let tf=decompose_term env sigma f in let targs=Array.map (decompose_term env sigma) args in Array.fold_left (fun s t->Appli (s,t)) tf targs | Prod (_,a,_b) when not (Termops.dependent (mkRel 1) _b) -> let b = Termops.pop _b in let sort_b = sf_of env sigma b in let sort_a = sf_of env sigma a in Appli(Appli(Product (sort_a,sort_b) , decompose_term env sigma a), decompose_term env sigma b) | Construct c -> let (((mind,i_ind),i_con),u)= c in let canon_mind = mind_of_kn (canonical_mind mind) in let canon_ind = canon_mind,i_ind in let (oib,_)=Global.lookup_inductive (canon_ind) in let nargs=constructor_nallargs_env env (canon_ind,i_con) in Constructor {ci_constr= ((canon_ind,i_con),u); ci_arity=nargs; ci_nhyps=nargs-oib.mind_nparams} | Ind c -> let (mind,i_ind),u = c in let canon_mind = mind_of_kn (canonical_mind mind) in let canon_ind = canon_mind,i_ind in (Symb (mkIndU (canon_ind,u))) | Const (c,u) -> let canon_const = constant_of_kn (canonical_con c) in (Symb (mkConstU (canon_const,u))) | Proj (p, c) -> let canon_const kn = constant_of_kn (canonical_con kn) in let p' = Projection.map canon_const p in (Appli (Symb (mkConst (Projection.constant p')), decompose_term env sigma c)) | _ -> let t = strip_outer_cast t in if closed0 t then Symb t else raise Not_found (* decompose equality in members and type *) open Globnames let atom_of_constr env sigma term = let wh = (whd_delta env term) in let kot = kind_of_term wh in match kot with App (f,args)-> if is_global (Lazy.force _eq) f && Int.equal (Array.length args) 3 then `Eq (args.(0), decompose_term env sigma args.(1), decompose_term env sigma args.(2)) else `Other (decompose_term env sigma term) | _ -> `Other (decompose_term env sigma term) let rec pattern_of_constr env sigma c = match kind_of_term (whd env c) with App (f,args)-> let pf = decompose_term env sigma f in let pargs,lrels = List.split (Array.map_to_list (pattern_of_constr env sigma) args) in PApp (pf,List.rev pargs), List.fold_left Int.Set.union Int.Set.empty lrels | Prod (_,a,_b) when not (Termops.dependent (mkRel 1) _b) -> let b = Termops.pop _b in let pa,sa = pattern_of_constr env sigma a in let pb,sb = pattern_of_constr env sigma b in let sort_b = sf_of env sigma b in let sort_a = sf_of env sigma a in PApp(Product (sort_a,sort_b), [pa;pb]),(Int.Set.union sa sb) | Rel i -> PVar i,Int.Set.singleton i | _ -> let pf = decompose_term env sigma c in PApp (pf,[]),Int.Set.empty let non_trivial = function PVar _ -> false | _ -> true let patterns_of_constr env sigma nrels term= let f,args= try destApp (whd_delta env term) with DestKO -> raise Not_found in if is_global (Lazy.force _eq) f && Int.equal (Array.length args) 3 then let patt1,rels1 = pattern_of_constr env sigma args.(1) and patt2,rels2 = pattern_of_constr env sigma args.(2) in let valid1 = if not (Int.equal (Int.Set.cardinal rels1) nrels) then Creates_variables else if non_trivial patt1 then Normal else Trivial args.(0) and valid2 = if not (Int.equal (Int.Set.cardinal rels2) nrels) then Creates_variables else if non_trivial patt2 then Normal else Trivial args.(0) in if valid1 != Creates_variables || valid2 != Creates_variables then nrels,valid1,patt1,valid2,patt2 else raise Not_found else raise Not_found let rec quantified_atom_of_constr env sigma nrels term = match kind_of_term (whd_delta env term) with Prod (id,atom,ff) -> if is_global (Lazy.force _False) ff then let patts=patterns_of_constr env sigma nrels atom in `Nrule patts else quantified_atom_of_constr (Environ.push_rel (LocalAssum (id,atom)) env) sigma (succ nrels) ff | _ -> let patts=patterns_of_constr env sigma nrels term in `Rule patts let litteral_of_constr env sigma term= match kind_of_term (whd_delta env term) with | Prod (id,atom,ff) -> if is_global (Lazy.force _False) ff then match (atom_of_constr env sigma atom) with `Eq(t,a,b) -> `Neq(t,a,b) | `Other(p) -> `Nother(p) else begin try quantified_atom_of_constr (Environ.push_rel (LocalAssum (id,atom)) env) sigma 1 ff with Not_found -> `Other (decompose_term env sigma term) end | _ -> atom_of_constr env sigma term (* store all equalities from the context *) let make_prb gls depth additionnal_terms = let env=pf_env gls in let sigma=sig_sig gls in let state = empty depth gls in let pos_hyps = ref [] in let neg_hyps =ref [] in List.iter (fun c -> let t = decompose_term env sigma c in ignore (add_term state t)) additionnal_terms; List.iter (fun decl -> let (id,_,e) = Context.Named.Declaration.to_tuple decl in begin let cid=mkVar id in match litteral_of_constr env sigma e with `Eq (t,a,b) -> add_equality state cid a b | `Neq (t,a,b) -> add_disequality state (Hyp cid) a b | `Other ph -> List.iter (fun (cidn,nh) -> add_disequality state (HeqnH (cid,cidn)) ph nh) !neg_hyps; pos_hyps:=(cid,ph):: !pos_hyps | `Nother nh -> List.iter (fun (cidp,ph) -> add_disequality state (HeqnH (cidp,cid)) ph nh) !pos_hyps; neg_hyps:=(cid,nh):: !neg_hyps | `Rule patts -> add_quant state id true patts | `Nrule patts -> add_quant state id false patts end) (Environ.named_context_of_val (Goal.V82.nf_hyps gls.sigma gls.it)); begin match atom_of_constr env sigma (Evarutil.nf_evar sigma (pf_concl gls)) with `Eq (t,a,b) -> add_disequality state Goal a b | `Other g -> List.iter (fun (idp,ph) -> add_disequality state (HeqG idp) ph g) !pos_hyps end; state indhyps builds the array of arrays of constructor hyps for ( ) let build_projection intype (cstr:pconstructor) special default gls= let ci= (snd(fst cstr)) in let body=Equality.build_selector (pf_env gls) (project gls) ci (mkRel 1) intype special default in let id=pf_get_new_id (Id.of_string "t") gls in mkLambda(Name id,intype,body) (* generate an adhoc tactic following the proof tree *) let _M =mkMeta let app_global f args k = Tacticals.pf_constr_of_global (Lazy.force f) (fun fc -> k (mkApp (fc, args))) let new_app_global f args k = Tacticals.New.pf_constr_of_global (Lazy.force f) (fun fc -> k (mkApp (fc, args))) let new_refine c = Proofview.V82.tactic (refine c) let assert_before n c = Proofview.Goal.enter { enter = begin fun gl -> let evm, _ = Tacmach.New.pf_apply type_of gl c in Tacticals.New.tclTHEN (Proofview.V82.tactic (Refiner.tclEVARS evm)) (assert_before n c) end } let refresh_type env evm ty = Evarsolve.refresh_universes ~status:Evd.univ_flexible ~refreshset:true (Some false) env evm ty let refresh_universes ty k = Proofview.Goal.enter { enter = begin fun gl -> let env = Proofview.Goal.env gl in let evm = Tacmach.New.project gl in let evm, ty = refresh_type env evm ty in Tacticals.New.tclTHEN (Proofview.V82.tactic (Refiner.tclEVARS evm)) (k ty) end } let rec proof_tac p : unit Proofview.tactic = Proofview.Goal.nf_enter { enter = begin fun gl -> let type_of t = Tacmach.New.pf_unsafe_type_of gl t in try (* type_of can raise exceptions *) match p.p_rule with Ax c -> exact_check c | SymAx c -> let l=constr_of_term p.p_lhs and r=constr_of_term p.p_rhs in refresh_universes (type_of l) (fun typ -> new_app_global _sym_eq [|typ;r;l;c|] exact_check) | Refl t -> let lr = constr_of_term t in refresh_universes (type_of lr) (fun typ -> new_app_global _refl_equal [|typ;constr_of_term t|] exact_check) | Trans (p1,p2)-> let t1 = constr_of_term p1.p_lhs and t2 = constr_of_term p1.p_rhs and t3 = constr_of_term p2.p_rhs in refresh_universes (type_of t2) (fun typ -> let prf = new_app_global _trans_eq [|typ;t1;t2;t3;_M 1;_M 2|] in Tacticals.New.tclTHENS (prf new_refine) [(proof_tac p1);(proof_tac p2)]) | Congr (p1,p2)-> let tf1=constr_of_term p1.p_lhs and tx1=constr_of_term p2.p_lhs and tf2=constr_of_term p1.p_rhs and tx2=constr_of_term p2.p_rhs in refresh_universes (type_of tf1) (fun typf -> refresh_universes (type_of tx1) (fun typx -> refresh_universes (type_of (mkApp (tf1,[|tx1|]))) (fun typfx -> let id = Tacmach.New.of_old (fun gls -> pf_get_new_id (Id.of_string "f") gls) gl in let appx1 = mkLambda(Name id,typf,mkApp(mkRel 1,[|tx1|])) in let lemma1 = app_global _f_equal [|typf;typfx;appx1;tf1;tf2;_M 1|] in let lemma2 = app_global _f_equal [|typx;typfx;tf2;tx1;tx2;_M 1|] in let prf = app_global _trans_eq [|typfx; mkApp(tf1,[|tx1|]); mkApp(tf2,[|tx1|]); mkApp(tf2,[|tx2|]);_M 2;_M 3|] in Tacticals.New.tclTHENS (Proofview.V82.tactic (prf refine)) [Tacticals.New.tclTHEN (Proofview.V82.tactic (lemma1 refine)) (proof_tac p1); Tacticals.New.tclFIRST [Tacticals.New.tclTHEN (Proofview.V82.tactic (lemma2 refine)) (proof_tac p2); reflexivity; Tacticals.New.tclZEROMSG (Pp.str "I don't know how to handle dependent equality")]]))) | Inject (prf,cstr,nargs,argind) -> let ti=constr_of_term prf.p_lhs in let tj=constr_of_term prf.p_rhs in let default=constr_of_term p.p_lhs in let special=mkRel (1+nargs-argind) in refresh_universes (type_of ti) (fun intype -> refresh_universes (type_of default) (fun outtype -> let proj = Tacmach.New.of_old (build_projection intype cstr special default) gl in let injt= app_global _f_equal [|intype;outtype;proj;ti;tj;_M 1|] in Tacticals.New.tclTHEN (Proofview.V82.tactic (injt refine)) (proof_tac prf))) with e when Proofview.V82.catchable_exception e -> Proofview.tclZERO e end } let refute_tac c t1 t2 p = Proofview.Goal.nf_enter { enter = begin fun gl -> let tt1=constr_of_term t1 and tt2=constr_of_term t2 in let hid = Tacmach.New.of_old (pf_get_new_id (Id.of_string "Heq")) gl in let false_t=mkApp (c,[|mkVar hid|]) in let k intype = let neweq= new_app_global _eq [|intype;tt1;tt2|] in Tacticals.New.tclTHENS (neweq (assert_before (Name hid))) [proof_tac p; simplest_elim false_t] in refresh_universes (Tacmach.New.pf_unsafe_type_of gl tt1) k end } let refine_exact_check c gl = let evm, _ = pf_apply type_of gl c in Tacticals.tclTHEN (Refiner.tclEVARS evm) (Proofview.V82.of_tactic (exact_check c)) gl let convert_to_goal_tac c t1 t2 p = Proofview.Goal.nf_enter { enter = begin fun gl -> let tt1=constr_of_term t1 and tt2=constr_of_term t2 in let k sort = let neweq= new_app_global _eq [|sort;tt1;tt2|] in let e = Tacmach.New.of_old (pf_get_new_id (Id.of_string "e")) gl in let x = Tacmach.New.of_old (pf_get_new_id (Id.of_string "X")) gl in let identity=mkLambda (Name x,sort,mkRel 1) in let endt=app_global _eq_rect [|sort;tt1;identity;c;tt2;mkVar e|] in Tacticals.New.tclTHENS (neweq (assert_before (Name e))) [proof_tac p; Proofview.V82.tactic (endt refine_exact_check)] in refresh_universes (Tacmach.New.pf_unsafe_type_of gl tt2) k end } let convert_to_hyp_tac c1 t1 c2 t2 p = Proofview.Goal.nf_enter { enter = begin fun gl -> let tt2=constr_of_term t2 in let h = Tacmach.New.of_old (pf_get_new_id (Id.of_string "H")) gl in let false_t=mkApp (c2,[|mkVar h|]) in Tacticals.New.tclTHENS (assert_before (Name h) tt2) [convert_to_goal_tac c1 t1 t2 p; simplest_elim false_t] end } let discriminate_tac (cstr,u as cstru) p = Proofview.Goal.nf_enter { enter = begin fun gl -> let t1=constr_of_term p.p_lhs and t2=constr_of_term p.p_rhs in let env = Proofview.Goal.env gl in let concl = Proofview.Goal.concl gl in let xid = Tacmach.New.of_old (pf_get_new_id (Id.of_string "X")) gl in let identity = Universes.constr_of_global (Lazy.force _I) in let trivial = Universes.constr_of_global (Lazy.force _True) in let evm = Tacmach.New.project gl in let evm, intype = refresh_type env evm (Tacmach.New.pf_unsafe_type_of gl t1) in let evm, outtype = Evd.new_sort_variable Evd.univ_flexible evm in let outtype = mkSort outtype in let pred = mkLambda(Name xid,outtype,mkRel 1) in let hid = Tacmach.New.of_old (pf_get_new_id (Id.of_string "Heq")) gl in let proj = Tacmach.New.of_old (build_projection intype cstru trivial concl) gl in let injt=app_global _f_equal [|intype;outtype;proj;t1;t2;mkVar hid|] in let endt k = injt (fun injt -> app_global _eq_rect [|outtype;trivial;pred;identity;concl;injt|] k) in let neweq=new_app_global _eq [|intype;t1;t2|] in Tacticals.New.tclTHEN (Proofview.Unsafe.tclEVARS evm) (Tacticals.New.tclTHENS (neweq (assert_before (Name hid))) [proof_tac p; Proofview.V82.tactic (endt refine_exact_check)]) end } (* wrap everything *) let build_term_to_complete uf meta pac = let cinfo = get_constructor_info uf pac.cnode in let real_args = List.map (fun i -> constr_of_term (term uf i)) pac.args in let dummy_args = List.rev (List.init pac.arity meta) in let all_args = List.rev_append real_args dummy_args in applistc (mkConstructU cinfo.ci_constr) all_args let cc_tactic depth additionnal_terms = Proofview.Goal.nf_enter { enter = begin fun gl -> Coqlib.check_required_library Coqlib.logic_module_name; let _ = debug (fun () -> Pp.str "Reading subgoal ...") in let state = Tacmach.New.of_old (fun gls -> make_prb gls depth additionnal_terms) gl in let _ = debug (fun () -> Pp.str "Problem built, solving ...") in let sol = execute true state in let _ = debug (fun () -> Pp.str "Computation completed.") in let uf=forest state in match sol with None -> Tacticals.New.tclFAIL 0 (str "congruence failed") | Some reason -> debug (fun () -> Pp.str "Goal solved, generating proof ..."); match reason with Discrimination (i,ipac,j,jpac) -> let p=build_proof uf (`Discr (i,ipac,j,jpac)) in let cstr=(get_constructor_info uf ipac.cnode).ci_constr in discriminate_tac cstr p | Incomplete -> let env = Proofview.Goal.env gl in let metacnt = ref 0 in let newmeta _ = incr metacnt; _M !metacnt in let terms_to_complete = List.map (build_term_to_complete uf newmeta) (epsilons uf) in Feedback.msg_info (Pp.str "Goal is solvable by congruence but \ some arguments are missing."); Feedback.msg_info (Pp.str " Try " ++ hov 8 begin str "\"congruence with (" ++ prlist_with_sep (fun () -> str ")" ++ spc () ++ str "(") (Termops.print_constr_env env) terms_to_complete ++ str ")\"," end ++ Pp.str " replacing metavariables by arbitrary terms."); Tacticals.New.tclFAIL 0 (str "Incomplete") | Contradiction dis -> let p=build_proof uf (`Prove (dis.lhs,dis.rhs)) in let ta=term uf dis.lhs and tb=term uf dis.rhs in match dis.rule with Goal -> proof_tac p | Hyp id -> refute_tac id ta tb p | HeqG id -> convert_to_goal_tac id ta tb p | HeqnH (ida,idb) -> convert_to_hyp_tac ida ta idb tb p end } let cc_fail gls = errorlabstrm "Congruence" (Pp.str "congruence failed.") let congruence_tac depth l = Tacticals.New.tclORELSE (Tacticals.New.tclTHEN (Tacticals.New.tclREPEAT introf) (cc_tactic depth l)) (Proofview.V82.tactic cc_fail) Beware : reflexivity = constructor 1 = apply refl_equal might be slow now , let 's rather do something equivalent to a " simple apply refl_equal " might be slow now, let's rather do something equivalent to a "simple apply refl_equal" *) (* The [f_equal] tactic. It mimics the use of lemmas [f_equal], [f_equal2], etc. This isn't particularly related with congruence, apart from the fact that congruence is called internally. *) let mk_eq f c1 c2 k = Tacticals.New.pf_constr_of_global (Lazy.force f) (fun fc -> Proofview.Goal.enter { enter = begin fun gl -> let open Tacmach.New in let evm, ty = pf_apply type_of gl c1 in let evm, ty = Evarsolve.refresh_universes (Some false) (pf_env gl) evm ty in let term = mkApp (fc, [| ty; c1; c2 |]) in let evm, _ = type_of (pf_env gl) evm term in Tacticals.New.tclTHEN (Proofview.V82.tactic (Refiner.tclEVARS evm)) (k term) end }) let f_equal = Proofview.Goal.nf_enter { enter = begin fun gl -> let concl = Proofview.Goal.concl gl in let cut_eq c1 c2 = try (* type_of can raise an exception *) Tacticals.New.tclTHENS (mk_eq _eq c1 c2 Tactics.cut) [Proofview.tclUNIT ();Tacticals.New.tclTRY ((new_app_global _refl_equal [||]) apply)] with e when Proofview.V82.catchable_exception e -> Proofview.tclZERO e in Proofview.tclORELSE begin match kind_of_term concl with | App (r,[|_;t;t'|]) when Globnames.is_global (Lazy.force _eq) r -> begin match kind_of_term t, kind_of_term t' with | App (f,v), App (f',v') when Int.equal (Array.length v) (Array.length v') -> let rec cuts i = if i < 0 then Tacticals.New.tclTRY (congruence_tac 1000 []) else Tacticals.New.tclTHENFIRST (cut_eq v.(i) v'.(i)) (cuts (i-1)) in cuts (Array.length v - 1) | _ -> Proofview.tclUNIT () end | _ -> Proofview.tclUNIT () end begin function (e, info) -> match e with | Type_errors.TypeError _ -> Proofview.tclUNIT () | e -> Proofview.tclZERO ~info e end end }
null
https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/plugins/cc/cctac.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** decompose member of equality in an applicative format * FIXME: evar leak decompose equality in members and type store all equalities from the context generate an adhoc tactic following the proof tree type_of can raise exceptions wrap everything The [f_equal] tactic. It mimics the use of lemmas [f_equal], [f_equal2], etc. This isn't particularly related with congruence, apart from the fact that congruence is called internally. type_of can raise an exception
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is the interface between the c - c algorithm and Coq open Evd open Names open Inductiveops open Declarations open Term open Vars open Tacmach open Tactics open Typing open Ccalgo open Ccproof open Pp open CErrors open Util open Proofview.Notations open Context.Rel.Declaration let reference dir s = lazy (Coqlib.gen_reference "CC" dir s) let _f_equal = reference ["Init";"Logic"] "f_equal" let _eq_rect = reference ["Init";"Logic"] "eq_rect" let _refl_equal = reference ["Init";"Logic"] "eq_refl" let _sym_eq = reference ["Init";"Logic"] "eq_sym" let _trans_eq = reference ["Init";"Logic"] "eq_trans" let _eq = reference ["Init";"Logic"] "eq" let _False = reference ["Init";"Logic"] "False" let _True = reference ["Init";"Logic"] "True" let _I = reference ["Init";"Logic"] "I" let whd env= let infos=CClosure.create_clos_infos CClosure.betaiotazeta env in (fun t -> CClosure.whd_val infos (CClosure.inject t)) let whd_delta env= let infos=CClosure.create_clos_infos CClosure.all env in (fun t -> CClosure.whd_val infos (CClosure.inject t)) let sf_of env sigma c = e_sort_of env (ref sigma) c let rec decompose_term env sigma t= match kind_of_term (whd env t) with App (f,args)-> let tf=decompose_term env sigma f in let targs=Array.map (decompose_term env sigma) args in Array.fold_left (fun s t->Appli (s,t)) tf targs | Prod (_,a,_b) when not (Termops.dependent (mkRel 1) _b) -> let b = Termops.pop _b in let sort_b = sf_of env sigma b in let sort_a = sf_of env sigma a in Appli(Appli(Product (sort_a,sort_b) , decompose_term env sigma a), decompose_term env sigma b) | Construct c -> let (((mind,i_ind),i_con),u)= c in let canon_mind = mind_of_kn (canonical_mind mind) in let canon_ind = canon_mind,i_ind in let (oib,_)=Global.lookup_inductive (canon_ind) in let nargs=constructor_nallargs_env env (canon_ind,i_con) in Constructor {ci_constr= ((canon_ind,i_con),u); ci_arity=nargs; ci_nhyps=nargs-oib.mind_nparams} | Ind c -> let (mind,i_ind),u = c in let canon_mind = mind_of_kn (canonical_mind mind) in let canon_ind = canon_mind,i_ind in (Symb (mkIndU (canon_ind,u))) | Const (c,u) -> let canon_const = constant_of_kn (canonical_con c) in (Symb (mkConstU (canon_const,u))) | Proj (p, c) -> let canon_const kn = constant_of_kn (canonical_con kn) in let p' = Projection.map canon_const p in (Appli (Symb (mkConst (Projection.constant p')), decompose_term env sigma c)) | _ -> let t = strip_outer_cast t in if closed0 t then Symb t else raise Not_found open Globnames let atom_of_constr env sigma term = let wh = (whd_delta env term) in let kot = kind_of_term wh in match kot with App (f,args)-> if is_global (Lazy.force _eq) f && Int.equal (Array.length args) 3 then `Eq (args.(0), decompose_term env sigma args.(1), decompose_term env sigma args.(2)) else `Other (decompose_term env sigma term) | _ -> `Other (decompose_term env sigma term) let rec pattern_of_constr env sigma c = match kind_of_term (whd env c) with App (f,args)-> let pf = decompose_term env sigma f in let pargs,lrels = List.split (Array.map_to_list (pattern_of_constr env sigma) args) in PApp (pf,List.rev pargs), List.fold_left Int.Set.union Int.Set.empty lrels | Prod (_,a,_b) when not (Termops.dependent (mkRel 1) _b) -> let b = Termops.pop _b in let pa,sa = pattern_of_constr env sigma a in let pb,sb = pattern_of_constr env sigma b in let sort_b = sf_of env sigma b in let sort_a = sf_of env sigma a in PApp(Product (sort_a,sort_b), [pa;pb]),(Int.Set.union sa sb) | Rel i -> PVar i,Int.Set.singleton i | _ -> let pf = decompose_term env sigma c in PApp (pf,[]),Int.Set.empty let non_trivial = function PVar _ -> false | _ -> true let patterns_of_constr env sigma nrels term= let f,args= try destApp (whd_delta env term) with DestKO -> raise Not_found in if is_global (Lazy.force _eq) f && Int.equal (Array.length args) 3 then let patt1,rels1 = pattern_of_constr env sigma args.(1) and patt2,rels2 = pattern_of_constr env sigma args.(2) in let valid1 = if not (Int.equal (Int.Set.cardinal rels1) nrels) then Creates_variables else if non_trivial patt1 then Normal else Trivial args.(0) and valid2 = if not (Int.equal (Int.Set.cardinal rels2) nrels) then Creates_variables else if non_trivial patt2 then Normal else Trivial args.(0) in if valid1 != Creates_variables || valid2 != Creates_variables then nrels,valid1,patt1,valid2,patt2 else raise Not_found else raise Not_found let rec quantified_atom_of_constr env sigma nrels term = match kind_of_term (whd_delta env term) with Prod (id,atom,ff) -> if is_global (Lazy.force _False) ff then let patts=patterns_of_constr env sigma nrels atom in `Nrule patts else quantified_atom_of_constr (Environ.push_rel (LocalAssum (id,atom)) env) sigma (succ nrels) ff | _ -> let patts=patterns_of_constr env sigma nrels term in `Rule patts let litteral_of_constr env sigma term= match kind_of_term (whd_delta env term) with | Prod (id,atom,ff) -> if is_global (Lazy.force _False) ff then match (atom_of_constr env sigma atom) with `Eq(t,a,b) -> `Neq(t,a,b) | `Other(p) -> `Nother(p) else begin try quantified_atom_of_constr (Environ.push_rel (LocalAssum (id,atom)) env) sigma 1 ff with Not_found -> `Other (decompose_term env sigma term) end | _ -> atom_of_constr env sigma term let make_prb gls depth additionnal_terms = let env=pf_env gls in let sigma=sig_sig gls in let state = empty depth gls in let pos_hyps = ref [] in let neg_hyps =ref [] in List.iter (fun c -> let t = decompose_term env sigma c in ignore (add_term state t)) additionnal_terms; List.iter (fun decl -> let (id,_,e) = Context.Named.Declaration.to_tuple decl in begin let cid=mkVar id in match litteral_of_constr env sigma e with `Eq (t,a,b) -> add_equality state cid a b | `Neq (t,a,b) -> add_disequality state (Hyp cid) a b | `Other ph -> List.iter (fun (cidn,nh) -> add_disequality state (HeqnH (cid,cidn)) ph nh) !neg_hyps; pos_hyps:=(cid,ph):: !pos_hyps | `Nother nh -> List.iter (fun (cidp,ph) -> add_disequality state (HeqnH (cidp,cid)) ph nh) !pos_hyps; neg_hyps:=(cid,nh):: !neg_hyps | `Rule patts -> add_quant state id true patts | `Nrule patts -> add_quant state id false patts end) (Environ.named_context_of_val (Goal.V82.nf_hyps gls.sigma gls.it)); begin match atom_of_constr env sigma (Evarutil.nf_evar sigma (pf_concl gls)) with `Eq (t,a,b) -> add_disequality state Goal a b | `Other g -> List.iter (fun (idp,ph) -> add_disequality state (HeqG idp) ph g) !pos_hyps end; state indhyps builds the array of arrays of constructor hyps for ( ) let build_projection intype (cstr:pconstructor) special default gls= let ci= (snd(fst cstr)) in let body=Equality.build_selector (pf_env gls) (project gls) ci (mkRel 1) intype special default in let id=pf_get_new_id (Id.of_string "t") gls in mkLambda(Name id,intype,body) let _M =mkMeta let app_global f args k = Tacticals.pf_constr_of_global (Lazy.force f) (fun fc -> k (mkApp (fc, args))) let new_app_global f args k = Tacticals.New.pf_constr_of_global (Lazy.force f) (fun fc -> k (mkApp (fc, args))) let new_refine c = Proofview.V82.tactic (refine c) let assert_before n c = Proofview.Goal.enter { enter = begin fun gl -> let evm, _ = Tacmach.New.pf_apply type_of gl c in Tacticals.New.tclTHEN (Proofview.V82.tactic (Refiner.tclEVARS evm)) (assert_before n c) end } let refresh_type env evm ty = Evarsolve.refresh_universes ~status:Evd.univ_flexible ~refreshset:true (Some false) env evm ty let refresh_universes ty k = Proofview.Goal.enter { enter = begin fun gl -> let env = Proofview.Goal.env gl in let evm = Tacmach.New.project gl in let evm, ty = refresh_type env evm ty in Tacticals.New.tclTHEN (Proofview.V82.tactic (Refiner.tclEVARS evm)) (k ty) end } let rec proof_tac p : unit Proofview.tactic = Proofview.Goal.nf_enter { enter = begin fun gl -> let type_of t = Tacmach.New.pf_unsafe_type_of gl t in match p.p_rule with Ax c -> exact_check c | SymAx c -> let l=constr_of_term p.p_lhs and r=constr_of_term p.p_rhs in refresh_universes (type_of l) (fun typ -> new_app_global _sym_eq [|typ;r;l;c|] exact_check) | Refl t -> let lr = constr_of_term t in refresh_universes (type_of lr) (fun typ -> new_app_global _refl_equal [|typ;constr_of_term t|] exact_check) | Trans (p1,p2)-> let t1 = constr_of_term p1.p_lhs and t2 = constr_of_term p1.p_rhs and t3 = constr_of_term p2.p_rhs in refresh_universes (type_of t2) (fun typ -> let prf = new_app_global _trans_eq [|typ;t1;t2;t3;_M 1;_M 2|] in Tacticals.New.tclTHENS (prf new_refine) [(proof_tac p1);(proof_tac p2)]) | Congr (p1,p2)-> let tf1=constr_of_term p1.p_lhs and tx1=constr_of_term p2.p_lhs and tf2=constr_of_term p1.p_rhs and tx2=constr_of_term p2.p_rhs in refresh_universes (type_of tf1) (fun typf -> refresh_universes (type_of tx1) (fun typx -> refresh_universes (type_of (mkApp (tf1,[|tx1|]))) (fun typfx -> let id = Tacmach.New.of_old (fun gls -> pf_get_new_id (Id.of_string "f") gls) gl in let appx1 = mkLambda(Name id,typf,mkApp(mkRel 1,[|tx1|])) in let lemma1 = app_global _f_equal [|typf;typfx;appx1;tf1;tf2;_M 1|] in let lemma2 = app_global _f_equal [|typx;typfx;tf2;tx1;tx2;_M 1|] in let prf = app_global _trans_eq [|typfx; mkApp(tf1,[|tx1|]); mkApp(tf2,[|tx1|]); mkApp(tf2,[|tx2|]);_M 2;_M 3|] in Tacticals.New.tclTHENS (Proofview.V82.tactic (prf refine)) [Tacticals.New.tclTHEN (Proofview.V82.tactic (lemma1 refine)) (proof_tac p1); Tacticals.New.tclFIRST [Tacticals.New.tclTHEN (Proofview.V82.tactic (lemma2 refine)) (proof_tac p2); reflexivity; Tacticals.New.tclZEROMSG (Pp.str "I don't know how to handle dependent equality")]]))) | Inject (prf,cstr,nargs,argind) -> let ti=constr_of_term prf.p_lhs in let tj=constr_of_term prf.p_rhs in let default=constr_of_term p.p_lhs in let special=mkRel (1+nargs-argind) in refresh_universes (type_of ti) (fun intype -> refresh_universes (type_of default) (fun outtype -> let proj = Tacmach.New.of_old (build_projection intype cstr special default) gl in let injt= app_global _f_equal [|intype;outtype;proj;ti;tj;_M 1|] in Tacticals.New.tclTHEN (Proofview.V82.tactic (injt refine)) (proof_tac prf))) with e when Proofview.V82.catchable_exception e -> Proofview.tclZERO e end } let refute_tac c t1 t2 p = Proofview.Goal.nf_enter { enter = begin fun gl -> let tt1=constr_of_term t1 and tt2=constr_of_term t2 in let hid = Tacmach.New.of_old (pf_get_new_id (Id.of_string "Heq")) gl in let false_t=mkApp (c,[|mkVar hid|]) in let k intype = let neweq= new_app_global _eq [|intype;tt1;tt2|] in Tacticals.New.tclTHENS (neweq (assert_before (Name hid))) [proof_tac p; simplest_elim false_t] in refresh_universes (Tacmach.New.pf_unsafe_type_of gl tt1) k end } let refine_exact_check c gl = let evm, _ = pf_apply type_of gl c in Tacticals.tclTHEN (Refiner.tclEVARS evm) (Proofview.V82.of_tactic (exact_check c)) gl let convert_to_goal_tac c t1 t2 p = Proofview.Goal.nf_enter { enter = begin fun gl -> let tt1=constr_of_term t1 and tt2=constr_of_term t2 in let k sort = let neweq= new_app_global _eq [|sort;tt1;tt2|] in let e = Tacmach.New.of_old (pf_get_new_id (Id.of_string "e")) gl in let x = Tacmach.New.of_old (pf_get_new_id (Id.of_string "X")) gl in let identity=mkLambda (Name x,sort,mkRel 1) in let endt=app_global _eq_rect [|sort;tt1;identity;c;tt2;mkVar e|] in Tacticals.New.tclTHENS (neweq (assert_before (Name e))) [proof_tac p; Proofview.V82.tactic (endt refine_exact_check)] in refresh_universes (Tacmach.New.pf_unsafe_type_of gl tt2) k end } let convert_to_hyp_tac c1 t1 c2 t2 p = Proofview.Goal.nf_enter { enter = begin fun gl -> let tt2=constr_of_term t2 in let h = Tacmach.New.of_old (pf_get_new_id (Id.of_string "H")) gl in let false_t=mkApp (c2,[|mkVar h|]) in Tacticals.New.tclTHENS (assert_before (Name h) tt2) [convert_to_goal_tac c1 t1 t2 p; simplest_elim false_t] end } let discriminate_tac (cstr,u as cstru) p = Proofview.Goal.nf_enter { enter = begin fun gl -> let t1=constr_of_term p.p_lhs and t2=constr_of_term p.p_rhs in let env = Proofview.Goal.env gl in let concl = Proofview.Goal.concl gl in let xid = Tacmach.New.of_old (pf_get_new_id (Id.of_string "X")) gl in let identity = Universes.constr_of_global (Lazy.force _I) in let trivial = Universes.constr_of_global (Lazy.force _True) in let evm = Tacmach.New.project gl in let evm, intype = refresh_type env evm (Tacmach.New.pf_unsafe_type_of gl t1) in let evm, outtype = Evd.new_sort_variable Evd.univ_flexible evm in let outtype = mkSort outtype in let pred = mkLambda(Name xid,outtype,mkRel 1) in let hid = Tacmach.New.of_old (pf_get_new_id (Id.of_string "Heq")) gl in let proj = Tacmach.New.of_old (build_projection intype cstru trivial concl) gl in let injt=app_global _f_equal [|intype;outtype;proj;t1;t2;mkVar hid|] in let endt k = injt (fun injt -> app_global _eq_rect [|outtype;trivial;pred;identity;concl;injt|] k) in let neweq=new_app_global _eq [|intype;t1;t2|] in Tacticals.New.tclTHEN (Proofview.Unsafe.tclEVARS evm) (Tacticals.New.tclTHENS (neweq (assert_before (Name hid))) [proof_tac p; Proofview.V82.tactic (endt refine_exact_check)]) end } let build_term_to_complete uf meta pac = let cinfo = get_constructor_info uf pac.cnode in let real_args = List.map (fun i -> constr_of_term (term uf i)) pac.args in let dummy_args = List.rev (List.init pac.arity meta) in let all_args = List.rev_append real_args dummy_args in applistc (mkConstructU cinfo.ci_constr) all_args let cc_tactic depth additionnal_terms = Proofview.Goal.nf_enter { enter = begin fun gl -> Coqlib.check_required_library Coqlib.logic_module_name; let _ = debug (fun () -> Pp.str "Reading subgoal ...") in let state = Tacmach.New.of_old (fun gls -> make_prb gls depth additionnal_terms) gl in let _ = debug (fun () -> Pp.str "Problem built, solving ...") in let sol = execute true state in let _ = debug (fun () -> Pp.str "Computation completed.") in let uf=forest state in match sol with None -> Tacticals.New.tclFAIL 0 (str "congruence failed") | Some reason -> debug (fun () -> Pp.str "Goal solved, generating proof ..."); match reason with Discrimination (i,ipac,j,jpac) -> let p=build_proof uf (`Discr (i,ipac,j,jpac)) in let cstr=(get_constructor_info uf ipac.cnode).ci_constr in discriminate_tac cstr p | Incomplete -> let env = Proofview.Goal.env gl in let metacnt = ref 0 in let newmeta _ = incr metacnt; _M !metacnt in let terms_to_complete = List.map (build_term_to_complete uf newmeta) (epsilons uf) in Feedback.msg_info (Pp.str "Goal is solvable by congruence but \ some arguments are missing."); Feedback.msg_info (Pp.str " Try " ++ hov 8 begin str "\"congruence with (" ++ prlist_with_sep (fun () -> str ")" ++ spc () ++ str "(") (Termops.print_constr_env env) terms_to_complete ++ str ")\"," end ++ Pp.str " replacing metavariables by arbitrary terms."); Tacticals.New.tclFAIL 0 (str "Incomplete") | Contradiction dis -> let p=build_proof uf (`Prove (dis.lhs,dis.rhs)) in let ta=term uf dis.lhs and tb=term uf dis.rhs in match dis.rule with Goal -> proof_tac p | Hyp id -> refute_tac id ta tb p | HeqG id -> convert_to_goal_tac id ta tb p | HeqnH (ida,idb) -> convert_to_hyp_tac ida ta idb tb p end } let cc_fail gls = errorlabstrm "Congruence" (Pp.str "congruence failed.") let congruence_tac depth l = Tacticals.New.tclORELSE (Tacticals.New.tclTHEN (Tacticals.New.tclREPEAT introf) (cc_tactic depth l)) (Proofview.V82.tactic cc_fail) Beware : reflexivity = constructor 1 = apply refl_equal might be slow now , let 's rather do something equivalent to a " simple apply refl_equal " might be slow now, let's rather do something equivalent to a "simple apply refl_equal" *) let mk_eq f c1 c2 k = Tacticals.New.pf_constr_of_global (Lazy.force f) (fun fc -> Proofview.Goal.enter { enter = begin fun gl -> let open Tacmach.New in let evm, ty = pf_apply type_of gl c1 in let evm, ty = Evarsolve.refresh_universes (Some false) (pf_env gl) evm ty in let term = mkApp (fc, [| ty; c1; c2 |]) in let evm, _ = type_of (pf_env gl) evm term in Tacticals.New.tclTHEN (Proofview.V82.tactic (Refiner.tclEVARS evm)) (k term) end }) let f_equal = Proofview.Goal.nf_enter { enter = begin fun gl -> let concl = Proofview.Goal.concl gl in let cut_eq c1 c2 = Tacticals.New.tclTHENS (mk_eq _eq c1 c2 Tactics.cut) [Proofview.tclUNIT ();Tacticals.New.tclTRY ((new_app_global _refl_equal [||]) apply)] with e when Proofview.V82.catchable_exception e -> Proofview.tclZERO e in Proofview.tclORELSE begin match kind_of_term concl with | App (r,[|_;t;t'|]) when Globnames.is_global (Lazy.force _eq) r -> begin match kind_of_term t, kind_of_term t' with | App (f,v), App (f',v') when Int.equal (Array.length v) (Array.length v') -> let rec cuts i = if i < 0 then Tacticals.New.tclTRY (congruence_tac 1000 []) else Tacticals.New.tclTHENFIRST (cut_eq v.(i) v'.(i)) (cuts (i-1)) in cuts (Array.length v - 1) | _ -> Proofview.tclUNIT () end | _ -> Proofview.tclUNIT () end begin function (e, info) -> match e with | Type_errors.TypeError _ -> Proofview.tclUNIT () | e -> Proofview.tclZERO ~info e end end }
0d6e399e1bbfcef0c221ba02af12c8c8dbc206ed14231437f4f83ad1a14aa6de
finnishtransportagency/harja
transit.cljc
(ns harja.transit "Harjan transit laajennokset" (:require [cognitect.transit :as t] [harja.pvm :as pvm] [harja.domain.roolit :as roolit] #?(:clj [harja.geo :as geo] :cljs [harja.pvm :as pvm]) [clojure.string :as str] [harja.fmt :as fmt] [harja.tyokalut.big :as big]) (:import #?@(:clj [(java.text SimpleDateFormat) (java.time LocalTime)] :cljs [(goog.date DateTime UtcDateTime)]))) #?(:clj (def +fi-date-time-format+ "dd.MM.yyyy HH:mm:ss") :cljs (deftype DateTimeHandler [] Object (tag [_ v] "dt") (rep [_ v] (pvm/pvm-aika-sek v)))) #?(:cljs (do (deftype AikaHandler [] Object (tag [_ v] "aika") (rep [_ v] (fmt/aika v))) (defn luo-aika [aika] (let [[t m h] (map js/parseInt (str/split aika #":"))] (pvm/->Aika t m h))))) #?(:cljs (do (deftype BigDecHandler [] Object (tag [_ v] "big") (rep [_ v] (.toString (:b v)))))) #?(:clj (def write-optiot {:handlers {java.util.Date (t/write-handler (constantly "dt") #(.format (SimpleDateFormat. +fi-date-time-format+) %)) java.math.BigDecimal (t/write-handler (constantly "bd") double) harja.tyokalut.big.BigDec (t/write-handler (constantly "big") (comp str :b)) org.postgresql.geometric.PGpoint (t/write-handler (constantly "pp") geo/pg->clj) org.postgis.PGgeometry (t/write-handler "pg" geo/pg->clj) harja.domain.roolit.EiOikeutta (t/write-handler (constantly "eo") #(:syy %)) java.time.LocalTime (t/write-handler "aika" str)}}) :cljs (def write-optiot {:handlers {DateTime (DateTimeHandler.) UtcDateTime (DateTimeHandler.) pvm/Aika (AikaHandler.) big/BigDec (BigDecHandler.) }})) #?(:clj (def read-optiot {:handlers {"dt" (t/read-handler #(.parse (SimpleDateFormat. +fi-date-time-format+) %)) "aika" (t/read-handler #(LocalTime/parse %)) "big" (t/read-handler big/parse)}}) :cljs (def read-optiot {:handlers {"dt" #(pvm/->pvm-aika-sek %) java.math . BigDecimal typen ;; muunnettuna, joten tässä kelpaa identity "bd" identity PGpoint ja PGgeometry muunnettuina kelpaa meille sellaisenaan "pp" js->clj "pg" js->clj EiOikeutta tulee serveriltä " eo " syy stringiä "eo" #(roolit/->EiOikeutta %) "aika" luo-aika "big" big/parse}})) (defn clj->transit "Muuntaa Clojure tietorakenteen Transit+JSON merkkijonoksi." ([data] (clj->transit data nil)) ([data wo] (let [write-optiot (or wo write-optiot)] #?(:clj (with-open [out (java.io.ByteArrayOutputStream.)] (t/write (t/writer out :json write-optiot) data) (str out)) :cljs (t/write (t/writer :json write-optiot) data))))) (defn lue-transit "Lukee Transit+JSON muotoisen tiedon annetusta inputista." ([in] (lue-transit in nil)) ([in ro] (let [read-optiot (or ro read-optiot)] #?(:clj (t/read (t/reader in :json read-optiot)) :cljs (t/read (t/reader :json read-optiot) in))))) #?(:clj (defn lue-transit-string ([in] (lue-transit-string in nil)) ([in ro] (lue-transit (java.io.ByteArrayInputStream. (.getBytes in)) ro))))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/488b1e096f0611e175221d74ba4f2ffed6bea8f1/src/cljc/harja/transit.cljc
clojure
muunnettuna, joten tässä kelpaa identity
(ns harja.transit "Harjan transit laajennokset" (:require [cognitect.transit :as t] [harja.pvm :as pvm] [harja.domain.roolit :as roolit] #?(:clj [harja.geo :as geo] :cljs [harja.pvm :as pvm]) [clojure.string :as str] [harja.fmt :as fmt] [harja.tyokalut.big :as big]) (:import #?@(:clj [(java.text SimpleDateFormat) (java.time LocalTime)] :cljs [(goog.date DateTime UtcDateTime)]))) #?(:clj (def +fi-date-time-format+ "dd.MM.yyyy HH:mm:ss") :cljs (deftype DateTimeHandler [] Object (tag [_ v] "dt") (rep [_ v] (pvm/pvm-aika-sek v)))) #?(:cljs (do (deftype AikaHandler [] Object (tag [_ v] "aika") (rep [_ v] (fmt/aika v))) (defn luo-aika [aika] (let [[t m h] (map js/parseInt (str/split aika #":"))] (pvm/->Aika t m h))))) #?(:cljs (do (deftype BigDecHandler [] Object (tag [_ v] "big") (rep [_ v] (.toString (:b v)))))) #?(:clj (def write-optiot {:handlers {java.util.Date (t/write-handler (constantly "dt") #(.format (SimpleDateFormat. +fi-date-time-format+) %)) java.math.BigDecimal (t/write-handler (constantly "bd") double) harja.tyokalut.big.BigDec (t/write-handler (constantly "big") (comp str :b)) org.postgresql.geometric.PGpoint (t/write-handler (constantly "pp") geo/pg->clj) org.postgis.PGgeometry (t/write-handler "pg" geo/pg->clj) harja.domain.roolit.EiOikeutta (t/write-handler (constantly "eo") #(:syy %)) java.time.LocalTime (t/write-handler "aika" str)}}) :cljs (def write-optiot {:handlers {DateTime (DateTimeHandler.) UtcDateTime (DateTimeHandler.) pvm/Aika (AikaHandler.) big/BigDec (BigDecHandler.) }})) #?(:clj (def read-optiot {:handlers {"dt" (t/read-handler #(.parse (SimpleDateFormat. +fi-date-time-format+) %)) "aika" (t/read-handler #(LocalTime/parse %)) "big" (t/read-handler big/parse)}}) :cljs (def read-optiot {:handlers {"dt" #(pvm/->pvm-aika-sek %) java.math . BigDecimal typen "bd" identity PGpoint ja PGgeometry muunnettuina kelpaa meille sellaisenaan "pp" js->clj "pg" js->clj EiOikeutta tulee serveriltä " eo " syy stringiä "eo" #(roolit/->EiOikeutta %) "aika" luo-aika "big" big/parse}})) (defn clj->transit "Muuntaa Clojure tietorakenteen Transit+JSON merkkijonoksi." ([data] (clj->transit data nil)) ([data wo] (let [write-optiot (or wo write-optiot)] #?(:clj (with-open [out (java.io.ByteArrayOutputStream.)] (t/write (t/writer out :json write-optiot) data) (str out)) :cljs (t/write (t/writer :json write-optiot) data))))) (defn lue-transit "Lukee Transit+JSON muotoisen tiedon annetusta inputista." ([in] (lue-transit in nil)) ([in ro] (let [read-optiot (or ro read-optiot)] #?(:clj (t/read (t/reader in :json read-optiot)) :cljs (t/read (t/reader :json read-optiot) in))))) #?(:clj (defn lue-transit-string ([in] (lue-transit-string in nil)) ([in ro] (lue-transit (java.io.ByteArrayInputStream. (.getBytes in)) ro))))
170d6e844e0e1c12987435c9b98cb0ef9b6fee54979af3502c245a5db83e0627
ivanjovanovic/sicp
e-3.42.scm
Exercise 3.42 . suggests that it 's a waste of time to create a ; new serialized procedure in response to every withdraw and deposit message. ; He says that make-account could be changed so that the calls to protected are ; done outside the dispatch procedure. That is, an account would return the ; same serialized procedure (which was created at the same time as the account) ; each time it is asked for a withdrawal procedure. (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((protected (make-serializer))) (let ((protected-withdraw (protected withdraw)) (protected-deposit (protected deposit))) (define (dispatch m) (cond ((eq? m 'withdraw) protected-withdraw) ((eq? m 'deposit) protected-deposit) ((eq? m 'balance) balance) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch))) ; Is this a safe change to make? In particular, is there any difference in what concurrency is allowed by these two versions of make - account ? ; ------------------------------------------------------------ ; Difference is that in the previous case we had for every call ( ( account ' withdraw ) 50 ) new protected procedure to execute ; ; In the case of this example we have always the same procedure execution. ; Both of these are local to this account object and they are safe to be ; this way since they will anyway share same synchronization primitive I guess.
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/3.4/e-3.42.scm
scheme
new serialized procedure in response to every withdraw and deposit message. He says that make-account could be changed so that the calls to protected are done outside the dispatch procedure. That is, an account would return the same serialized procedure (which was created at the same time as the account) each time it is asked for a withdrawal procedure. Is this a safe change to make? In particular, is there any difference in what ------------------------------------------------------------ Difference is that in the previous case we had for every call In the case of this example we have always the same procedure execution. Both of these are local to this account object and they are safe to be this way since they will anyway share same synchronization primitive I guess.
Exercise 3.42 . suggests that it 's a waste of time to create a (define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((protected (make-serializer))) (let ((protected-withdraw (protected withdraw)) (protected-deposit (protected deposit))) (define (dispatch m) (cond ((eq? m 'withdraw) protected-withdraw) ((eq? m 'deposit) protected-deposit) ((eq? m 'balance) balance) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch))) concurrency is allowed by these two versions of make - account ? ( ( account ' withdraw ) 50 ) new protected procedure to execute
f5ee8c5efcbbb524c344fe8b1a450bfe57d9aa79f8cb0162535f57fbbd2f3dcb
jumarko/clojure-experiments
simple_closures.clj
(ns four-clojure.simple-closures) ;;; ;;; Lexical scope and first - class functions are two of the most basic building blocks of functional language like Clojure ;;; With Lexical Closures you can get a great control overal lifetime of you local bindings ;;; ;;; Let's build a simple closure: ;;; Given a positive integer n, return a function (f x) which computes x^n. ;;; Observe that the effect of this is to preserve the value of n for use outside the scope in which it is defined. (defn lexical-closure [n] (fn [x] (int ( Math/pow x n)))) (= 256 ((lexical-closure 2) 16) ((lexical-closure 8) 2)) (= [1 8 27 64] (map (lexical-closure 3) [1 2 3 4])) (= [1 2 4 8 16] (map #((lexical-closure %) 2) [0 1 2 3 4]))
null
https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/four_clojure/simple_closures.clj
clojure
With Lexical Closures you can get a great control overal lifetime of you local bindings Let's build a simple closure: Given a positive integer n, return a function (f x) which computes x^n. Observe that the effect of this is to preserve the value of n for use outside the scope in which it is defined.
(ns four-clojure.simple-closures) Lexical scope and first - class functions are two of the most basic building blocks of functional language like Clojure (defn lexical-closure [n] (fn [x] (int ( Math/pow x n)))) (= 256 ((lexical-closure 2) 16) ((lexical-closure 8) 2)) (= [1 8 27 64] (map (lexical-closure 3) [1 2 3 4])) (= [1 2 4 8 16] (map #((lexical-closure %) 2) [0 1 2 3 4]))
91aa3b5049520f1472164cea745e42e6e46321b33596c8eb5701e930c04d088f
chetmurthy/poly-protobuf
test01_ml.ml
module T = Test01_types module Pb = Test01_pb module Pp = Test01_pp let decode_ref_data () = T.({ p1 = { first_name = "John"; last_name = "Doe"; date_of_birth = 19820429l; tel_number = None; employment = Employed_by "Google"; marital_status = None; gender = Some Male; }; p2 = { first_name = "Marie"; last_name = "Dupont"; date_of_birth = 19820306l; tel_number = Some {area_code = 917l; number = 1111111l}; employment = Employed_by "INRIA"; marital_status = None; gender = Some Female; }; contact_numbers = { area_code = 917l; number = 123450l; } :: { area_code = 917l; number = 123451l; } :: []; number_of_children = Some (0l); }) let () = Printf.printf "Show is working: %s\n" @@ T.show_couple (decode_ref_data ()) let () = let mode = Test_util.parse_args () in match mode with | Test_util.Decode -> Test_util.decode "test01.c2ml.data" Pb.decode_couple Pp.pp_couple (decode_ref_data ()) | Test_util.Encode -> Test_util.encode "test01.ml2c.data" Pb.encode_couple (decode_ref_data ()) let () = let expected_default_person = T.({ first_name = "Max"; last_name = "Ransan"; date_of_birth = 19820429l; tel_number = None; employment = Self_employed 0l; marital_status = None; gender = None; }) in assert (expected_default_person = T.default_person ())
null
https://raw.githubusercontent.com/chetmurthy/poly-protobuf/1f80774af6472fa30ee2fb10d0ef91905a13a144/tests/testdata/integration-tests/test01_ml.ml
ocaml
module T = Test01_types module Pb = Test01_pb module Pp = Test01_pp let decode_ref_data () = T.({ p1 = { first_name = "John"; last_name = "Doe"; date_of_birth = 19820429l; tel_number = None; employment = Employed_by "Google"; marital_status = None; gender = Some Male; }; p2 = { first_name = "Marie"; last_name = "Dupont"; date_of_birth = 19820306l; tel_number = Some {area_code = 917l; number = 1111111l}; employment = Employed_by "INRIA"; marital_status = None; gender = Some Female; }; contact_numbers = { area_code = 917l; number = 123450l; } :: { area_code = 917l; number = 123451l; } :: []; number_of_children = Some (0l); }) let () = Printf.printf "Show is working: %s\n" @@ T.show_couple (decode_ref_data ()) let () = let mode = Test_util.parse_args () in match mode with | Test_util.Decode -> Test_util.decode "test01.c2ml.data" Pb.decode_couple Pp.pp_couple (decode_ref_data ()) | Test_util.Encode -> Test_util.encode "test01.ml2c.data" Pb.encode_couple (decode_ref_data ()) let () = let expected_default_person = T.({ first_name = "Max"; last_name = "Ransan"; date_of_birth = 19820429l; tel_number = None; employment = Self_employed 0l; marital_status = None; gender = None; }) in assert (expected_default_person = T.default_person ())
a9d5f17ee0ae872ad1e25761a59e7b79b942492d698aa6ea084445a5849bc31c
grin-compiler/ghc-whole-program-compiler-project
gen-obj.hs
# LANGUAGE RecordWildCards # module Main where import Control.Monad import Control.Monad.IO.Class import System.Environment import Stg.IO import Stg.GHC.ToStg import Stg.GHC.Backend import Stg.DeadFunctionElimination.StripModule import qualified GHC.Driver.Types as GHC import GHC import GHC.Paths ( libdir ) = StgModule { stgUnitId : : UnitId , stgModuleName : : ModuleName , stgModuleTyCons : : [ TyCon ] , stgTopBindings : : [ StgTopBinding ] , stgForeignStubs : : , stgForeignFiles : : [ ( ForeignSrcLang , FilePath ) ] } = StgModule { stgUnitId :: UnitId , stgModuleName :: ModuleName , stgModuleTyCons :: [TyCon] , stgTopBindings :: [StgTopBinding] , stgForeignStubs :: ForeignStubs , stgForeignFiles :: [(ForeignSrcLang, FilePath)] } -} main :: IO () main = runGhc (Just libdir) $ do let cg = NCG modpaks <- liftIO getArgs forM_ modpaks $ \modpakName -> do extStgModule <- liftIO $ do putStrLn $ modpakName readModpakL modpakName modpakStgbinPath decodeStgbin strippedExtModule <- liftIO $ tryStripDeadParts {-modpakName-}"." extStgModule -- TODO: fix liveness input name let StgModule{..} = toStg strippedExtModule oName = modpakName ++ ".o" liftIO $ putStrLn $ " compiling " + + oName putStrLn $ unlines $ map show stgIdUniqueMap -- HINT: the stubs are compiled at link time compileToObjectM cg stgUnitId stgModuleName GHC.NoStubs stgModuleTyCons stgTopBindings oName TODO : simplify API to : compileToObject cg stgModule oName
null
https://raw.githubusercontent.com/grin-compiler/ghc-whole-program-compiler-project/3fe5fb0aaebfe8005d44d29357dc53156c8b6537/external-stg-compiler/app/gen-obj.hs
haskell
modpakName TODO: fix liveness input name HINT: the stubs are compiled at link time
# LANGUAGE RecordWildCards # module Main where import Control.Monad import Control.Monad.IO.Class import System.Environment import Stg.IO import Stg.GHC.ToStg import Stg.GHC.Backend import Stg.DeadFunctionElimination.StripModule import qualified GHC.Driver.Types as GHC import GHC import GHC.Paths ( libdir ) = StgModule { stgUnitId : : UnitId , stgModuleName : : ModuleName , stgModuleTyCons : : [ TyCon ] , stgTopBindings : : [ StgTopBinding ] , stgForeignStubs : : , stgForeignFiles : : [ ( ForeignSrcLang , FilePath ) ] } = StgModule { stgUnitId :: UnitId , stgModuleName :: ModuleName , stgModuleTyCons :: [TyCon] , stgTopBindings :: [StgTopBinding] , stgForeignStubs :: ForeignStubs , stgForeignFiles :: [(ForeignSrcLang, FilePath)] } -} main :: IO () main = runGhc (Just libdir) $ do let cg = NCG modpaks <- liftIO getArgs forM_ modpaks $ \modpakName -> do extStgModule <- liftIO $ do putStrLn $ modpakName readModpakL modpakName modpakStgbinPath decodeStgbin let StgModule{..} = toStg strippedExtModule oName = modpakName ++ ".o" liftIO $ putStrLn $ " compiling " + + oName putStrLn $ unlines $ map show stgIdUniqueMap compileToObjectM cg stgUnitId stgModuleName GHC.NoStubs stgModuleTyCons stgTopBindings oName TODO : simplify API to : compileToObject cg stgModule oName
a5df24c1ee8562cf2129dfae6cdbd2f494982125bd40c8ddf9d0d4b4ab187ae9
freizl/dive-into-haskell
mysql.hs
-- file: mysql.hs import Control.Monad import Database.HDBC import Database.HDBC.MySQL main = do conn <- connectMySQL defaultMySQLConnectInfo { mysqlUser = "root", mysqlPassword = "navichina", mysqlDatabase = "swingshowcase" } rows <- quickQuery' conn "SELECT * from customer" [] forM_ rows $ \row -> putStrLn $ show row conn < - connectMySQL defaultMySQLConnectInfo { mysqlHost = " localhost " , mysqlUser = " root " , = " " , mysqlDatabase="swingshowcase " }
null
https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/codes/hdbc/mysql.hs
haskell
file: mysql.hs
import Control.Monad import Database.HDBC import Database.HDBC.MySQL main = do conn <- connectMySQL defaultMySQLConnectInfo { mysqlUser = "root", mysqlPassword = "navichina", mysqlDatabase = "swingshowcase" } rows <- quickQuery' conn "SELECT * from customer" [] forM_ rows $ \row -> putStrLn $ show row conn < - connectMySQL defaultMySQLConnectInfo { mysqlHost = " localhost " , mysqlUser = " root " , = " " , mysqlDatabase="swingshowcase " }
46a562992bafcb32ff10c84a464ab22ae121c1dff8e51c971ea5a7967d7bd7b7
Simre1/haskell-game
DoctestSpec.hs
# LANGUAGE CPP # module DoctestSpec where import Test.Hspec import Test.DocTest spec :: Spec spec = parallel $ describe "Error messages" $ it "should pass the doctest" $ doctest [ "-isrc/" , "--fast" , "-XDataKinds" , "-XDeriveFunctor" , "-XFlexibleContexts" , "-XGADTs" , "-XLambdaCase" , "-XPolyKinds" , "-XRankNTypes" , "-XScopedTypeVariables" , "-XStandaloneDeriving" , "-XTypeApplications" , "-XTypeFamilies" , "-XTypeOperators" , "-XUnicodeSyntax" , "-package type-errors" #if __GLASGOW_HASKELL__ < 806 , "-XMonadFailDesugaring" , "-XTypeInType" #endif , "test/TypeErrors.hs" -- Modules that are explicitly imported for this test must be listed here , "src/Polysemy.hs" , "src/Polysemy/Error.hs" , "src/Polysemy/Output.hs" , "src/Polysemy/Reader.hs" , "src/Polysemy/Resource.hs" , "src/Polysemy/State.hs" , "src/Polysemy/Trace.hs" ]
null
https://raw.githubusercontent.com/Simre1/haskell-game/272a0674157aedc7b0e0ee00da8d3a464903dc67/polysemy/test/DoctestSpec.hs
haskell
Modules that are explicitly imported for this test must be listed here
# LANGUAGE CPP # module DoctestSpec where import Test.Hspec import Test.DocTest spec :: Spec spec = parallel $ describe "Error messages" $ it "should pass the doctest" $ doctest [ "-isrc/" , "--fast" , "-XDataKinds" , "-XDeriveFunctor" , "-XFlexibleContexts" , "-XGADTs" , "-XLambdaCase" , "-XPolyKinds" , "-XRankNTypes" , "-XScopedTypeVariables" , "-XStandaloneDeriving" , "-XTypeApplications" , "-XTypeFamilies" , "-XTypeOperators" , "-XUnicodeSyntax" , "-package type-errors" #if __GLASGOW_HASKELL__ < 806 , "-XMonadFailDesugaring" , "-XTypeInType" #endif , "test/TypeErrors.hs" , "src/Polysemy.hs" , "src/Polysemy/Error.hs" , "src/Polysemy/Output.hs" , "src/Polysemy/Reader.hs" , "src/Polysemy/Resource.hs" , "src/Polysemy/State.hs" , "src/Polysemy/Trace.hs" ]
72e7c0ef09bb9fd1f5a2e656ad3464634933ca816345b46ac49cd01cc9ddc9e5
public-law/nevada-revised-statutes-parser
TreeParser.hs
module TreeParser ( parseTree ) where import BasicPrelude ( Maybe(Just, Nothing) , Either(..) , error , head , ($) ) import qualified Data.HashMap.Lazy as HM import Text.InterpolatedString.Perl6 ( qq ) import ChapterFile ( ChapterMap , parseChapter ) import HtmlUtil ( Html ) import IndexFile ( parseTitlesAndChapters ) import Config import Models.Chapter import Models.Tree parseTree :: Html -> ChapterMap -> Tree parseTree indexFile chapterMap = Tree { chapter0 = parseChapterZero chapterMap , titles = parseTitlesAndChapters indexFile (allButChapterZero chapterMap) } parseChapterZero :: ChapterMap -> Chapter parseChapterZero chapterMap = let path = chapterZeroPathname in case HM.lookup path chapterMap of Just html -> case parseChapter html of Left message -> error [qq| Can't parse chap. zero: $message |] Right aChapter -> aChapter Nothing -> error [qq| Chap. Zero $path not found in {head $ HM.keys chapterMap} |] allButChapterZero :: ChapterMap -> ChapterMap allButChapterZero = HM.delete chapterZeroPathname
null
https://raw.githubusercontent.com/public-law/nevada-revised-statutes-parser/88a886debdab6ce5bd6cf5819c846cec1ffb9220/src/TreeParser.hs
haskell
module TreeParser ( parseTree ) where import BasicPrelude ( Maybe(Just, Nothing) , Either(..) , error , head , ($) ) import qualified Data.HashMap.Lazy as HM import Text.InterpolatedString.Perl6 ( qq ) import ChapterFile ( ChapterMap , parseChapter ) import HtmlUtil ( Html ) import IndexFile ( parseTitlesAndChapters ) import Config import Models.Chapter import Models.Tree parseTree :: Html -> ChapterMap -> Tree parseTree indexFile chapterMap = Tree { chapter0 = parseChapterZero chapterMap , titles = parseTitlesAndChapters indexFile (allButChapterZero chapterMap) } parseChapterZero :: ChapterMap -> Chapter parseChapterZero chapterMap = let path = chapterZeroPathname in case HM.lookup path chapterMap of Just html -> case parseChapter html of Left message -> error [qq| Can't parse chap. zero: $message |] Right aChapter -> aChapter Nothing -> error [qq| Chap. Zero $path not found in {head $ HM.keys chapterMap} |] allButChapterZero :: ChapterMap -> ChapterMap allButChapterZero = HM.delete chapterZeroPathname
cb90469bb652f1ee20efc6c1286e873d44ab532c4f240180c8b921535c369c3d
stepcut/plugins
Plugin.hs
module Plugin ( resource ) where import API resource = plugin { field = "hello out there" }
null
https://raw.githubusercontent.com/stepcut/plugins/52c660b5bc71182627d14c1d333d0234050cac01/testsuite/make/o/Plugin.hs
haskell
module Plugin ( resource ) where import API resource = plugin { field = "hello out there" }
54ff7acb8a9047a723f07c2f132d010681c180f89a9be20b65754afa2788badd
zotonic/zotonic
action_wires_growl.erl
@author < > 2009 Copyright 2009 %% 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(action_wires_growl). -include_lib("zotonic_core/include/zotonic.hrl"). -export([render_action/4]). render_action(_TriggerId, _TargetId, Args, Context) -> Text = proplists:get_value(text, Args, ""), Stay = proplists:get_value(stay, Args, 0), Type = proplists:get_value(type, Args, "notice"), TextJS = z_utils:js_escape(Text, Context), StayJS = case z_convert:to_bool(Stay) of true -> $1; false -> $0 end, TypeJS = z_utils:js_escape(Type, Context), Script = [<<"z_growl_add(\"">>,TextJS,<<"\", ">>, StayJS,<<",\"">>, TypeJS, $", $), $;], {Script, Context}.
null
https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_mod_wires/src/actions/action_wires_growl.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.
@author < > 2009 Copyright 2009 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(action_wires_growl). -include_lib("zotonic_core/include/zotonic.hrl"). -export([render_action/4]). render_action(_TriggerId, _TargetId, Args, Context) -> Text = proplists:get_value(text, Args, ""), Stay = proplists:get_value(stay, Args, 0), Type = proplists:get_value(type, Args, "notice"), TextJS = z_utils:js_escape(Text, Context), StayJS = case z_convert:to_bool(Stay) of true -> $1; false -> $0 end, TypeJS = z_utils:js_escape(Type, Context), Script = [<<"z_growl_add(\"">>,TextJS,<<"\", ">>, StayJS,<<",\"">>, TypeJS, $", $), $;], {Script, Context}.
dd953602f7a04758afbcefb8526aae97f10a063b35fb29af60d7bcaf7e480272
DHSProgram/DHS-Indicators-SPSS
NT_tables_PR.sps
* Encoding: windows-1252. ***************************************************************************************************** Program: NT_tables_PR.sps Purpose: produce tables for indicators Author: Ivana Bjelic Date last modified: May 18 2020 by Ivana Bjelic *This do file will produce the following tables in excel: 1. Tables_nut_ch: Contains the tables for nutritional status indicators for children 2. Tables_anemia_ch: Contains the tables for anemia indicators for children *****************************************************************************************************/ * the total will show on the last row of each table. * comment out the tables or indicator section you do not want. **************************************************** * When implementing a crosstabs command instead of ctables command please change: ctables to *ctables. *crosstabs to crosstabs *frequencies to frequencies. * the total will show on the last row of each table. * comment out the tables or indicator section you do not want. **************************************************** * indicators from PR file. compute wt=hv005/1000000. weight by wt. ************************************************************************************************** * background variables *Age in months. recode hc1 (0 thru 5=1) (6 thru 8=2) (9 thru 11=3) (12 thru 17=4) (18 thru 23=5) (24 thru 35=6) (36 thru 47=7) (48 thru 59=8) into agemonths. variable labels agemonths "Age in months". value labels agemonths 1 " <6" 2 " 6-8" 3 " 9-11" 4 " 12-17" 5 " 18-23" 6 " 24-35" 7 " 36-47" 8 " 48-59". * Note: other variables such as size at birth (from KR file) and mother's BMI (from IR) are found in other files and need to be merged with PR file * These tables are only for variables available in the PR file ************************************************************************************************** * Anthropometric indicators for children under age 5 ************************************************************************************************** *Severely stunted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_sev_stunt [c] [rowpct.validn '' f5.1] + nt_ch_sev_stunt [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Severely stunted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_sev_stunt /format = avalue tables /cells = row /count asis. **************************************************** *Stunted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_stunt [c] [rowpct.validn '' f5.1] + nt_ch_stunt [s][validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Stunted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_stunt /format = avalue tables /cells = row /count asis. **************************************************** *Mean haz. descriptives variables = nt_ch_mean_haz /statistics = mean. * this is a scalar and only produced for the total. **************************************************** *Severely wasted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_sev_wast [c] [rowpct.validn '' f5.1] + nt_ch_sev_wast [s][validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Severely wasted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_sev_wast /format = avalue tables /cells = row /count asis. **************************************************** *Wasted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_wast [c] [rowpct.validn '' f5.1] + nt_ch_wast [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Wasted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_wast /format = avalue tables /cells = row /count asis. **************************************************** *Overweight for height. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_ovwt_ht [c] [rowpct.validn '' f5.1] + nt_ch_ovwt_ht [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Overweight for height". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_ovwt_ht /format = avalue tables /cells = row /count asis. **************************************************** *Mean whz. descriptives variables = nt_ch_mean_whz /statistics = mean. * this is a scalar and only produced for the total. **************************************************** *Severely underweight. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_sev_underwt [c] [rowpct.validn '' f5.1] + nt_ch_sev_underwt [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Severely underweight". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_sev_underwt /format = avalue tables /cells = row /count asis. **************************************************** *Wasted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_underwt [c] [rowpct.validn '' f5.1] + nt_ch_underwt [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Wasted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_underwt /format = avalue tables /cells = row /count asis. **************************************************** *Overweight for height. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_ovwt_age [c] [rowpct.validn '' f5.1] + nt_ch_ovwt_age [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Overweight for height". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_ovwt_age /format = avalue tables /cells = row /count asis. **************************************************** *Mean whz. descriptives variables = nt_ch_mean_waz /statistics = mean. * this is a scalar and only produced for the total. **************************************************** * Export Output. output export /contents export=visible layers=printsetting modelviews=printsetting /xlsx documentfile="Tables_nut_ch.xlsx" operation=createfile. output close * . ************************************************************************************************** * Anemia in children 6-59 months ************************************************************************************************** . compute filter=hc1>5. filter by filter. *Any anemia. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_any_anem [c] [rowpct.validn '' f5.1] + nt_ch_any_anem [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Any anemia". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_any_anem /format = avalue tables /cells = row /count asis. **************************************************** *Mild anemia. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_mild_anem [c] [rowpct.validn '' f5.1] + nt_ch_mild_anem [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Mild anemia". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_mild_anem /format = avalue tables /cells = row /count asis. **************************************************** *Moderate anemia. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_mod_anem [c] [rowpct.validn '' f5.1] + nt_ch_mod_anem [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Moderate anemia". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_mod_anem /format = avalue tables /cells = row /count asis. **************************************************** *Severe anemia. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_sev_anem [c] [rowpct.validn '' f5.1] + nt_ch_sev_anem [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Severe anemia". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_sev_anem /format = avalue tables /cells = row /count asis. **************************************************** * Export Output. output export /contents export=visible layers=printsetting modelviews=printsetting /xlsx documentfile="Tables_anemia_ch.xlsx" operation=createfile. output close * . **************************************************** new file.
null
https://raw.githubusercontent.com/DHSProgram/DHS-Indicators-SPSS/578e6d40eff9edebda7cf0db0d9a0a52a537d98c/Chap11_NT/NT_tables_PR.sps
scheme
* Encoding: windows-1252. ***************************************************************************************************** Program: NT_tables_PR.sps Purpose: produce tables for indicators Author: Ivana Bjelic Date last modified: May 18 2020 by Ivana Bjelic *This do file will produce the following tables in excel: 1. Tables_nut_ch: Contains the tables for nutritional status indicators for children 2. Tables_anemia_ch: Contains the tables for anemia indicators for children *****************************************************************************************************/ * the total will show on the last row of each table. * comment out the tables or indicator section you do not want. **************************************************** * When implementing a crosstabs command instead of ctables command please change: ctables to *ctables. *crosstabs to crosstabs *frequencies to frequencies. * the total will show on the last row of each table. * comment out the tables or indicator section you do not want. **************************************************** * indicators from PR file. compute wt=hv005/1000000. weight by wt. ************************************************************************************************** * background variables *Age in months. recode hc1 (0 thru 5=1) (6 thru 8=2) (9 thru 11=3) (12 thru 17=4) (18 thru 23=5) (24 thru 35=6) (36 thru 47=7) (48 thru 59=8) into agemonths. variable labels agemonths "Age in months". value labels agemonths 1 " <6" 2 " 6-8" 3 " 9-11" 4 " 12-17" 5 " 18-23" 6 " 24-35" 7 " 36-47" 8 " 48-59". * Note: other variables such as size at birth (from KR file) and mother's BMI (from IR) are found in other files and need to be merged with PR file * These tables are only for variables available in the PR file ************************************************************************************************** * Anthropometric indicators for children under age 5 ************************************************************************************************** *Severely stunted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_sev_stunt [c] [rowpct.validn '' f5.1] + nt_ch_sev_stunt [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Severely stunted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_sev_stunt /format = avalue tables /cells = row /count asis. **************************************************** *Stunted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_stunt [c] [rowpct.validn '' f5.1] + nt_ch_stunt [s][validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Stunted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_stunt /format = avalue tables /cells = row /count asis. **************************************************** *Mean haz. descriptives variables = nt_ch_mean_haz /statistics = mean. * this is a scalar and only produced for the total. **************************************************** *Severely wasted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_sev_wast [c] [rowpct.validn '' f5.1] + nt_ch_sev_wast [s][validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Severely wasted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_sev_wast /format = avalue tables /cells = row /count asis. **************************************************** *Wasted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_wast [c] [rowpct.validn '' f5.1] + nt_ch_wast [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Wasted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_wast /format = avalue tables /cells = row /count asis. **************************************************** *Overweight for height. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_ovwt_ht [c] [rowpct.validn '' f5.1] + nt_ch_ovwt_ht [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Overweight for height". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_ovwt_ht /format = avalue tables /cells = row /count asis. **************************************************** *Mean whz. descriptives variables = nt_ch_mean_whz /statistics = mean. * this is a scalar and only produced for the total. **************************************************** *Severely underweight. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_sev_underwt [c] [rowpct.validn '' f5.1] + nt_ch_sev_underwt [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Severely underweight". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_sev_underwt /format = avalue tables /cells = row /count asis. **************************************************** *Wasted. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_underwt [c] [rowpct.validn '' f5.1] + nt_ch_underwt [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Wasted". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_underwt /format = avalue tables /cells = row /count asis. **************************************************** *Overweight for height. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_ovwt_age [c] [rowpct.validn '' f5.1] + nt_ch_ovwt_age [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Overweight for height". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_ovwt_age /format = avalue tables /cells = row /count asis. **************************************************** *Mean whz. descriptives variables = nt_ch_mean_waz /statistics = mean. * this is a scalar and only produced for the total. **************************************************** * Export Output. output export /contents export=visible layers=printsetting modelviews=printsetting /xlsx documentfile="Tables_nut_ch.xlsx" operation=createfile. output close * . ************************************************************************************************** * Anemia in children 6-59 months ************************************************************************************************** . compute filter=hc1>5. filter by filter. *Any anemia. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_any_anem [c] [rowpct.validn '' f5.1] + nt_ch_any_anem [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Any anemia". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_any_anem /format = avalue tables /cells = row /count asis. **************************************************** *Mild anemia. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_mild_anem [c] [rowpct.validn '' f5.1] + nt_ch_mild_anem [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Mild anemia". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_mild_anem /format = avalue tables /cells = row /count asis. **************************************************** *Moderate anemia. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_mod_anem [c] [rowpct.validn '' f5.1] + nt_ch_mod_anem [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Moderate anemia". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_mod_anem /format = avalue tables /cells = row /count asis. **************************************************** *Severe anemia. ctables /table agemonths [c] + hc27 [c] + hv025 [c] + hv024 [c] + hv270 [c] by nt_ch_sev_anem [c] [rowpct.validn '' f5.1] + nt_ch_sev_anem [s] [validn ,'', f5.0] /categories variables=all empty=exclude missing=exclude /categories variables=all total=yes position=after label="Total" /slabels visible=no /titles title= "Severe anemia". *crosstabs /tables = agemonths hc27 hv025 hv024 hv270 by nt_ch_sev_anem /format = avalue tables /cells = row /count asis. **************************************************** * Export Output. output export /contents export=visible layers=printsetting modelviews=printsetting /xlsx documentfile="Tables_anemia_ch.xlsx" operation=createfile. output close * . **************************************************** new file.
a0eb4490711038f657f0e6b40f0b9bf04ed49161302a7cd8dce1605a95230fa1
clj-kafka/franzy
configuration_tests.clj
(ns franzy.embedded.configuration-tests (:require [midje.sweet :refer :all] [franzy.embedded.defaults :as defaults] [franzy.embedded.configuration :as config]) (:import (clojure.lang IPersistentMap) (kafka.server KafkaConfig))) (facts "Kafka configs can be created a few ways" (fact "You can create and view the broker defaults." (instance? IPersistentMap (defaults/default-config)) => true) (fact "You can make a concrete Kafka configuration object." (instance? KafkaConfig (config/make-kafka-config)) => true) (fact "You can pass a config map and it will be created as a Kafka config." (instance? KafkaConfig (config/make-kafka-config {:host.name "127.0.0.1" :port 9092 :broker.id 0 :zookeeper.connect "127.0.0.1:2181"})) => true) (fact "You cannot pass values in your config map that are not valid Kafka configs." (config/make-kafka-config {:creepy-cereal-mascots ["Lucky Charms Guy" "Toucan Sam" "Raisin Bran Sun"]}) => (throws Exception)))
null
https://raw.githubusercontent.com/clj-kafka/franzy/6c2e2e65ad137d2bcbc04ff6e671f97ea8c0e380/embedded/test/franzy/embedded/configuration_tests.clj
clojure
(ns franzy.embedded.configuration-tests (:require [midje.sweet :refer :all] [franzy.embedded.defaults :as defaults] [franzy.embedded.configuration :as config]) (:import (clojure.lang IPersistentMap) (kafka.server KafkaConfig))) (facts "Kafka configs can be created a few ways" (fact "You can create and view the broker defaults." (instance? IPersistentMap (defaults/default-config)) => true) (fact "You can make a concrete Kafka configuration object." (instance? KafkaConfig (config/make-kafka-config)) => true) (fact "You can pass a config map and it will be created as a Kafka config." (instance? KafkaConfig (config/make-kafka-config {:host.name "127.0.0.1" :port 9092 :broker.id 0 :zookeeper.connect "127.0.0.1:2181"})) => true) (fact "You cannot pass values in your config map that are not valid Kafka configs." (config/make-kafka-config {:creepy-cereal-mascots ["Lucky Charms Guy" "Toucan Sam" "Raisin Bran Sun"]}) => (throws Exception)))
f951e7dd63bb0e449c7c8e408e5ef2161caf192b3626c34bfb95d16bb991c9d6
mwotton/roboservant
BuildFrom.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DerivingVia # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Roboservant.Types.BuildFrom where import Data.List(nub) import qualified Data.Dependent.Map as DM import Data.Hashable import qualified Data.IntSet as IntSet import Data.Kind import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NEL import Data.Typeable (Typeable) import GHC.Generics import Roboservant.Types.Internal import qualified Type.Reflection as R import Servant(NoContent) import Roboservant.Types.Orphans() buildFrom :: forall x. (Hashable x, BuildFrom x, Typeable x) => Stash -> Maybe (StashValue x) buildFrom = buildStash . buildFrom' where buildStash :: [([Provenance], x)] -> Maybe (StashValue x) buildStash = fmap (foldr1 addStash . fmap promoteToStash) . NEL.nonEmpty promoteToStash :: ([Provenance], x) -> StashValue x promoteToStash (p, x) = StashValue (pure (p, x)) (IntSet.singleton (hash x)) addStash :: StashValue x -> StashValue x -> StashValue x addStash old (StashValue newVal _) = let insertableVals = NEL.filter ((`IntSet.notMember` stashHash old) . hash) newVal in StashValue (addListToNE (getStashValue old) insertableVals) (IntSet.union (IntSet.fromList . map hash . fmap snd . NEL.toList $ newVal) (stashHash old)) addListToNE :: NonEmpty a -> [a] -> NonEmpty a addListToNE ne l = NEL.fromList (NEL.toList ne <> l) buildFrom' :: forall x. (Hashable x, BuildFrom x, Typeable x) => Stash -> [([Provenance], x)] buildFrom' stash = maybe [] (NEL.toList . getStashValue) (DM.lookup R.typeRep (getStash stash)) <> extras stash class (Hashable x, Typeable x) => BuildFrom (x :: Type) where extras :: Stash -> [([Provenance], x)] instance (Hashable x, Typeable x) => BuildFrom (Atom x) where extras _ = [] deriving via (Atom Bool) instance BuildFrom Bool deriving via (Compound (Maybe x)) instance (Typeable x, Hashable x, BuildFrom x) => BuildFrom (Maybe x) -- this isn't wonderful, but we need a hand-rolled instance for recursive datatypes right now. -- with an arbitrary-ish interface, we could use a size parameter, rng access etc. instance (Eq x, BuildFrom x) => BuildFrom [x] where extras stash = nub $ map (\xs -> (concatMap fst xs, map snd xs)) $ notpowerset $ buildFrom' @x stash where -- powerset creates way too much stuff. something better here eventually. notpowerset xs = []:xs:map pure xs instance (Hashable x, Typeable x, Generic x, GBuildFrom (Rep x)) => BuildFrom (Compound (x :: Type)) where extras stash = fmap (Compound . to) <$> gExtras stash deriving via (Atom Int) instance BuildFrom Int deriving via (Atom Char) instance BuildFrom Char class GBuildFrom (f :: k -> Type) where gExtras :: Stash -> [([Provenance], f a)] instance GBuildFrom b => GBuildFrom (M1 D a b) where gExtras = fmap (fmap M1) . gExtras -- not recursion safe! instance (GBuildFrom a, GBuildFrom b) => GBuildFrom (a :+: b) where gExtras stash = (fmap L1 <$> gExtras stash) <> (fmap R1 <$> gExtras stash) instance (GBuildFrom a, GBuildFrom b) => GBuildFrom (a :*: b) where gExtras stash = [(pa <> pb, a' :*: b') | (pa, a') <- gExtras stash, (pb, b') <- gExtras stash] instance GBuildFrom b => GBuildFrom (M1 C a b) where gExtras = fmap (fmap M1) . gExtras instance GBuildFrom b => GBuildFrom (M1 S a b) where gExtras = fmap (fmap M1) . gExtras instance BuildFrom a => GBuildFrom (K1 i a) where gExtras = fmap (fmap K1) . buildFrom' instance GBuildFrom U1 where gExtras _ = [([], U1)] deriving via (Atom NoContent) instance BuildFrom NoContent
null
https://raw.githubusercontent.com/mwotton/roboservant/c89e1693fc146ea653ea48d411124082e01dec2d/src/Roboservant/Types/BuildFrom.hs
haskell
this isn't wonderful, but we need a hand-rolled instance for recursive datatypes right now. with an arbitrary-ish interface, we could use a size parameter, rng access etc. powerset creates way too much stuff. something better here eventually. not recursion safe!
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DerivingVia # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Roboservant.Types.BuildFrom where import Data.List(nub) import qualified Data.Dependent.Map as DM import Data.Hashable import qualified Data.IntSet as IntSet import Data.Kind import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NEL import Data.Typeable (Typeable) import GHC.Generics import Roboservant.Types.Internal import qualified Type.Reflection as R import Servant(NoContent) import Roboservant.Types.Orphans() buildFrom :: forall x. (Hashable x, BuildFrom x, Typeable x) => Stash -> Maybe (StashValue x) buildFrom = buildStash . buildFrom' where buildStash :: [([Provenance], x)] -> Maybe (StashValue x) buildStash = fmap (foldr1 addStash . fmap promoteToStash) . NEL.nonEmpty promoteToStash :: ([Provenance], x) -> StashValue x promoteToStash (p, x) = StashValue (pure (p, x)) (IntSet.singleton (hash x)) addStash :: StashValue x -> StashValue x -> StashValue x addStash old (StashValue newVal _) = let insertableVals = NEL.filter ((`IntSet.notMember` stashHash old) . hash) newVal in StashValue (addListToNE (getStashValue old) insertableVals) (IntSet.union (IntSet.fromList . map hash . fmap snd . NEL.toList $ newVal) (stashHash old)) addListToNE :: NonEmpty a -> [a] -> NonEmpty a addListToNE ne l = NEL.fromList (NEL.toList ne <> l) buildFrom' :: forall x. (Hashable x, BuildFrom x, Typeable x) => Stash -> [([Provenance], x)] buildFrom' stash = maybe [] (NEL.toList . getStashValue) (DM.lookup R.typeRep (getStash stash)) <> extras stash class (Hashable x, Typeable x) => BuildFrom (x :: Type) where extras :: Stash -> [([Provenance], x)] instance (Hashable x, Typeable x) => BuildFrom (Atom x) where extras _ = [] deriving via (Atom Bool) instance BuildFrom Bool deriving via (Compound (Maybe x)) instance (Typeable x, Hashable x, BuildFrom x) => BuildFrom (Maybe x) instance (Eq x, BuildFrom x) => BuildFrom [x] where extras stash = nub $ map (\xs -> (concatMap fst xs, map snd xs)) $ notpowerset $ buildFrom' @x stash where notpowerset xs = []:xs:map pure xs instance (Hashable x, Typeable x, Generic x, GBuildFrom (Rep x)) => BuildFrom (Compound (x :: Type)) where extras stash = fmap (Compound . to) <$> gExtras stash deriving via (Atom Int) instance BuildFrom Int deriving via (Atom Char) instance BuildFrom Char class GBuildFrom (f :: k -> Type) where gExtras :: Stash -> [([Provenance], f a)] instance GBuildFrom b => GBuildFrom (M1 D a b) where gExtras = fmap (fmap M1) . gExtras instance (GBuildFrom a, GBuildFrom b) => GBuildFrom (a :+: b) where gExtras stash = (fmap L1 <$> gExtras stash) <> (fmap R1 <$> gExtras stash) instance (GBuildFrom a, GBuildFrom b) => GBuildFrom (a :*: b) where gExtras stash = [(pa <> pb, a' :*: b') | (pa, a') <- gExtras stash, (pb, b') <- gExtras stash] instance GBuildFrom b => GBuildFrom (M1 C a b) where gExtras = fmap (fmap M1) . gExtras instance GBuildFrom b => GBuildFrom (M1 S a b) where gExtras = fmap (fmap M1) . gExtras instance BuildFrom a => GBuildFrom (K1 i a) where gExtras = fmap (fmap K1) . buildFrom' instance GBuildFrom U1 where gExtras _ = [([], U1)] deriving via (Atom NoContent) instance BuildFrom NoContent
fe17c749c7bc3f5c1ffb1bf55f396b509598d567b175f800a5f2d9d5f0c6a31a
tonyg/kali-scheme
jar-assem.scm
; -*- Mode: Scheme; Syntax: Scheme; Package: Scheme; -*- Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . ; This is file assem.scm. Assembler Courtesy . LAP syntax is much like that of the output of the disassembler except ; that global and set-global! take a symbol as an argument, ; statements may be labeled, and jump, jump-if-false, and make-cont ; may make a forward reference to a label to give an offset. ; Example : a translation of ( define ( dog ) ( if x 0 1 ) ) . ; (define dog ; (lap dog ; (check-nargs= 0) ; (global x) ; (jump-if-false 8) ; (literal '0) ; 8 (jump out) ; (literal '1) ; out (return))) (define-compilator '(lap syntax) (let ((op/closure (enum op closure))) (lambda (node cenv depth cont) (let ((exp (node-form node))) (deliver-value (instruction-with-template op/closure (compile-lap (cddr exp) cenv) (cadr exp)) cont))))) Assembler label environments are simply a - lists . (define assembler-empty-env '()) (define (assembler-extend sym val env) (cons (cons sym val) env)) (define (assembler-lookup sym env) (let ((val (assv sym env))) (if (pair? val) (cdr val) #f))) (define (compile-lap instruction-list cenv) (assemble instruction-list assembler-empty-env cenv)) ; ASSEMBLE returns a segment. (define (assemble instruction-list lenv cenv) (if (null? instruction-list) (sequentially) (let ((instr (car instruction-list)) (instruction-list (cdr instruction-list))) (cond ((pair? instr) ; Instruction (sequentially (assemble-instruction instr lenv cenv) (assemble instruction-list lenv cenv))) ((or (symbol? instr) ; Label (number? instr)) (let ((label (make-label))) (attach-label label (assemble instruction-list (assembler-extend instr label lenv) cenv)))) (else (error "invalid instruction" instr)))))) ; ASSEMBLE-INSTRUCTION returns a segment. (define (assemble-instruction instr lenv cenv) (let* ((opcode (name->enumerand (car instr) op)) (arg-specs (vector-ref opcode-arg-specs opcode))) (cond ((or (not (pair? arg-specs)) (not (pair? (cdr instr)))) (instruction opcode)) ((eq? (car arg-specs) 'index) (assemble-instruction-with-index opcode arg-specs (cdr instr) cenv)) ((eq? (car arg-specs) 'offset) (let ((operand (cadr instr))) (apply instruction-using-label opcode (let ((probe (assembler-lookup operand lenv))) (if probe probe (begin (syntax-error "can't find forward label reference" operand) empty-segment))) (assemble-operands (cddr instr) arg-specs)))) (else (apply instruction opcode (assemble-operands (cdr instr) arg-specs)))))) ; <index> ::= (quote <datum>) | (lap <name> <instr>) | <name> (define (assemble-instruction-with-index opcode arg-specs operands cenv) (let ((operand (car operands))) (if (pair? operand) (case (car operand) ((quote) (instruction-with-literal opcode (cadr operand))) ((lap) (instruction-with-template opcode (compile-lap (cddr operand)) (cadr operand))) (else (syntax-error "invalid index operand" operand) empty-segment)) ;; Top-level variable reference (instruction-with-location opcode (get-location (lookup cenv operand) cenv operand value-type))))) (define (assemble-operands operands arg-specs) (map (lambda (operand arg-spec) (case arg-spec ((stob) (or (name->enumerand operand stob) (error "unknown stored object type" operand))) ((byte nargs) operand) (else (error "unknown operand type" operand arg-spec)))) operands arg-specs))
null
https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/env/jar-assem.scm
scheme
-*- Mode: Scheme; Syntax: Scheme; Package: Scheme; -*- This is file assem.scm. that global and set-global! take a symbol as an argument, statements may be labeled, and jump, jump-if-false, and make-cont may make a forward reference to a label to give an offset. (define dog (lap dog (check-nargs= 0) (global x) (jump-if-false 8) (literal '0) 8 (jump out) (literal '1) out (return))) ASSEMBLE returns a segment. Instruction Label ASSEMBLE-INSTRUCTION returns a segment. <index> ::= (quote <datum>) | (lap <name> <instr>) | <name> Top-level variable reference
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . Assembler Courtesy . LAP syntax is much like that of the output of the disassembler except Example : a translation of ( define ( dog ) ( if x 0 1 ) ) . (define-compilator '(lap syntax) (let ((op/closure (enum op closure))) (lambda (node cenv depth cont) (let ((exp (node-form node))) (deliver-value (instruction-with-template op/closure (compile-lap (cddr exp) cenv) (cadr exp)) cont))))) Assembler label environments are simply a - lists . (define assembler-empty-env '()) (define (assembler-extend sym val env) (cons (cons sym val) env)) (define (assembler-lookup sym env) (let ((val (assv sym env))) (if (pair? val) (cdr val) #f))) (define (compile-lap instruction-list cenv) (assemble instruction-list assembler-empty-env cenv)) (define (assemble instruction-list lenv cenv) (if (null? instruction-list) (sequentially) (let ((instr (car instruction-list)) (instruction-list (cdr instruction-list))) (sequentially (assemble-instruction instr lenv cenv) (assemble instruction-list lenv cenv))) (number? instr)) (let ((label (make-label))) (attach-label label (assemble instruction-list (assembler-extend instr label lenv) cenv)))) (else (error "invalid instruction" instr)))))) (define (assemble-instruction instr lenv cenv) (let* ((opcode (name->enumerand (car instr) op)) (arg-specs (vector-ref opcode-arg-specs opcode))) (cond ((or (not (pair? arg-specs)) (not (pair? (cdr instr)))) (instruction opcode)) ((eq? (car arg-specs) 'index) (assemble-instruction-with-index opcode arg-specs (cdr instr) cenv)) ((eq? (car arg-specs) 'offset) (let ((operand (cadr instr))) (apply instruction-using-label opcode (let ((probe (assembler-lookup operand lenv))) (if probe probe (begin (syntax-error "can't find forward label reference" operand) empty-segment))) (assemble-operands (cddr instr) arg-specs)))) (else (apply instruction opcode (assemble-operands (cdr instr) arg-specs)))))) (define (assemble-instruction-with-index opcode arg-specs operands cenv) (let ((operand (car operands))) (if (pair? operand) (case (car operand) ((quote) (instruction-with-literal opcode (cadr operand))) ((lap) (instruction-with-template opcode (compile-lap (cddr operand)) (cadr operand))) (else (syntax-error "invalid index operand" operand) empty-segment)) (instruction-with-location opcode (get-location (lookup cenv operand) cenv operand value-type))))) (define (assemble-operands operands arg-specs) (map (lambda (operand arg-spec) (case arg-spec ((stob) (or (name->enumerand operand stob) (error "unknown stored object type" operand))) ((byte nargs) operand) (else (error "unknown operand type" operand arg-spec)))) operands arg-specs))
fe1938cbc91b66ca090fa7e02f46180a1c8a527e35cbdbb9fbf61e976493d814
OdonataResearchLLC/linear-algebra
linear-algebra-test.lisp
Unit Tests for Linear Algebra in Common Lisp (in-package :cl-user) (defpackage :linear-algebra-test (:use :common-lisp :lisp-unit)) (in-package :linear-algebra-test) ;;; Convenience functions (defun random-interior-index (size) "Return an interior index that is guaranteed not to be an end point." (check-type size fixnum) (cond ((= 3 size) 1) ((< 3 size) (let ((end (1- size))) (do ((index (random end) (random end))) ((< 0 index end) index)))) (t (error "Invalid size : ~D." size)))) (defun zero-matrix (rows columns &key (matrix-type 'linear-algebra:dense-matrix)) "Return a ROWSxCOLUMNS zero matrix." (linear-algebra:make-matrix rows columns :matrix-type matrix-type :initial-element 0)) (defun unit-matrix (rows columns &key (matrix-type 'linear-algebra:dense-matrix)) "Return a ROWSxCOLUMNS unit matrix." (linear-algebra:make-matrix rows columns :matrix-type matrix-type :initial-element 1)) (defun identity-array (size) (let ((the-array (make-array (list size size) :initial-element 0.0))) (dotimes (i0 size the-array) (setf (aref the-array i0 i0) 1.0)))) (defun coordinate-array (&optional (row 0) (column 0) (row-end 10) (column-end 10)) "Return an array with the elements denoting the coordinate." (cond ((not (<= 0 row row-end 10)) (error "Invalid range of rows (~D:~D)." row row-end)) ((not (<= 0 column column-end 10)) (error "Invalid range of columns (~D:~D)." column column-end)) (t (let* ((rows (- row-end row)) (columns (- column-end column)) (the-array (make-array (list rows columns)))) (dotimes (i0 rows the-array) (dotimes (i1 columns) (setf (aref the-array i0 i1) (+ row i0 (/ (+ column i1) 10.0))))))))) (defun symmetric-array (&optional (start 0) (end 10)) "Return a symmetric array with the element denoting the coordinate." (if (<= 0 start end 10) (let* ((size (- end start)) (the-array (make-array (list size size))) (val nil)) (dotimes (i0 size the-array) (setf (aref the-array i0 i0) (+ start i0 (/ (+ start i0) 10.0))) (dotimes (i1 i0) (setf val (+ start i0 (/ (+ start i1) 10.0)) (aref the-array i0 i1) val (aref the-array i1 i0) val)))) (error "Invalid range (~D:~D)." start end))) (defun hermitian-array (&optional (start 0) (end 10)) "Return a Hermitian array with the element denoting the coordinate." (if (<= 0 start end 10) (let* ((size (- end start)) (the-array (make-array (list size size)))) (dotimes (i0 size the-array) (setf (aref the-array i0 i0) (complex (+ 1 start i0) 0)) (dotimes (i1 i0) (setf (aref the-array i0 i1) (complex (+ 1 start i0) (- -1 start i1))) (setf (aref the-array i1 i0) (complex (+ 1 start i0) (+ 1 start i1)))))) (error "Invalid range (~D:~D)." start end))) (defun upper-triangular-array (&optional (start 0) (end 10)) "Return a 10x10 list with the element denoting the coordinate." (if (<= 0 start end 10) (let* ((size (- end start)) (the-array (make-array (list size size) :element-type 'single-float :initial-element 0.0))) (dotimes (i1 size the-array) (setf (aref the-array i1 i1) 1.0) (dotimes (i0 i1) (setf (aref the-array i0 i1) 1.0)))) (error "Invalid range (~D:~D)." start end))) (defun lower-triangular-array (&optional (start 0) (end 10)) "Return a 10x10 list with the element denoting the coordinate." (if (<= 0 start end 10) (let* ((size (- end start)) (the-array (make-array (list size size) :element-type 'single-float :initial-element 0.0))) (dotimes (i0 size the-array) (setf (aref the-array i0 i0) 1.0) (dotimes (i1 i0) (setf (aref the-array i0 i1) 1.0)))) (error "Invalid range (~D:~D)." start end))) (defun random-permutation-vector (size &optional (counter -1)) "Return a random permutation vector of SIZE." (let ((permutation (map-into (make-array size) (lambda () (incf counter))))) (do ((index 0 (1+ index)) (swap (random size) (random size))) ((>= index size) permutation) (rotatef (svref permutation index) (svref permutation swap))))) (defun random-permutation-array (size) "Return a random permutation matrix of SIZE." (let ((permutation (random-permutation-vector size)) (the-array (make-array (list size size) :initial-element 0))) (dotimes (row size the-array) (setf (aref the-array row (svref permutation row)) 1)))) (defun permutations (list) "Return permutations of the list. [Erik Naggum]" (if (cdr list) (loop with rotation = list do (setq rotation (nconc (last rotation) (nbutlast rotation))) nconc (loop for list in (permutations (rest rotation)) collect (cons (first rotation) (copy-list list))) until (eq rotation list)) (list list))) (defun cartesian-product (list1 list2) "Return a list of the Cartesian product of two lists." (mapcan (lambda (x) (mapcar (lambda (y) (list x y)) list2)) list1)) (defun nary-product (list1 list2 &rest more-lists) "Return a list of the n-ary Cartesian product of the lists." (if (null more-lists) (cartesian-product list1 list2) (mapcan (lambda (x) (mapcar (lambda (y) (push x y)) (apply #'nary-product list2 (car more-lists) (rest more-lists)))) list1))) ;;; Data vector equality (defmethod rational-equal ((result1 sequence) (result2 linear-algebra:data-vector)) (rational-equal result1 (linear-algebra::contents result2))) (defmethod float-equal ((result1 sequence) (result2 linear-algebra:data-vector) &optional (epsilon lisp-unit:*epsilon*)) (float-equal result1 (linear-algebra::contents result2) epsilon)) (defmethod rational-equal ((result1 linear-algebra:data-vector) (result2 linear-algebra:data-vector)) (rational-equal (linear-algebra::contents result1) (linear-algebra::contents result2))) (defmethod float-equal ((result1 linear-algebra:data-vector) (result2 linear-algebra:data-vector) &optional (epsilon lisp-unit:*epsilon*)) (float-equal (linear-algebra::contents result1) (linear-algebra::contents result2) epsilon)) ;;; Dense matrix equality (defmethod rational-equal ((result1 list) (result2 linear-algebra:dense-matrix)) (let* ((contents (linear-algebra::contents result2)) (rows (array-dimension contents 0)) (columns (array-dimension contents 1)) (data-row nil)) (when (= rows (length result1)) (dotimes (i0 rows t) (if (= columns (length (setf data-row (nth i0 result1)))) (dotimes (i1 columns) (unless (rational-equal (elt data-row i1) (aref contents i0 i1)) (return-from rational-equal))) (return-from rational-equal)))))) (defmethod float-equal ((result1 list) (result2 linear-algebra:dense-matrix) &optional (epsilon lisp-unit:*epsilon*)) (let* ((contents (linear-algebra::contents result2)) (rows (array-dimension contents 0)) (columns (array-dimension contents 1)) (data-row nil)) (when (= rows (length result1)) (dotimes (i0 rows t) (if (= columns (length (setf data-row (nth i0 result1)))) (dotimes (i1 columns) (unless (float-equal (elt data-row i1) (aref contents i0 i1) epsilon) (return-from float-equal))) (return-from float-equal)))))) (defmethod rational-equal ((result1 vector) (result2 linear-algebra:dense-matrix)) (let* ((contents (linear-algebra::contents result2)) (rows (array-dimension contents 0)) (columns (array-dimension contents 1)) (data-row nil)) (when (= rows (length result1)) (dotimes (i0 rows t) (if (= columns (length (setf data-row (svref result1 i0)))) (dotimes (i1 columns) (unless (rational-equal (elt data-row i1) (aref contents i0 i1)) (return-from rational-equal))) (return-from rational-equal)))))) (defmethod float-equal ((result1 vector) (result2 linear-algebra:dense-matrix) &optional (epsilon lisp-unit:*epsilon*)) (let* ((contents (linear-algebra::contents result2)) (rows (array-dimension contents 0)) (columns (array-dimension contents 1)) (data-row nil)) (when (= rows (length result1)) (dotimes (i0 rows t) (if (= columns (length (setf data-row (svref result1 i0)))) (dotimes (i1 columns) (unless (float-equal (elt data-row i1) (aref contents i0 i1) epsilon) (return-from float-equal))) (return-from float-equal)))))) (defmethod rational-equal ((result1 array) (result2 linear-algebra:dense-matrix)) (rational-equal result1 (linear-algebra::contents result2))) (defmethod float-equal ((result1 array) (result2 linear-algebra:dense-matrix) &optional (epsilon lisp-unit:*epsilon*)) (float-equal result1 (linear-algebra::contents result2) epsilon)) (defmethod rational-equal ((result1 linear-algebra:dense-matrix) (result2 linear-algebra:dense-matrix)) (rational-equal (linear-algebra::contents result1) (linear-algebra::contents result2))) (defmethod float-equal ((result1 linear-algebra:dense-matrix) (result2 linear-algebra:dense-matrix) &optional (epsilon lisp-unit:*epsilon*)) (float-equal (linear-algebra::contents result1) (linear-algebra::contents result2) epsilon))
null
https://raw.githubusercontent.com/OdonataResearchLLC/linear-algebra/188bf6c3b7a78383c2707154c0bd19b2a4d88a07/test/linear-algebra-test.lisp
lisp
Convenience functions Data vector equality Dense matrix equality
Unit Tests for Linear Algebra in Common Lisp (in-package :cl-user) (defpackage :linear-algebra-test (:use :common-lisp :lisp-unit)) (in-package :linear-algebra-test) (defun random-interior-index (size) "Return an interior index that is guaranteed not to be an end point." (check-type size fixnum) (cond ((= 3 size) 1) ((< 3 size) (let ((end (1- size))) (do ((index (random end) (random end))) ((< 0 index end) index)))) (t (error "Invalid size : ~D." size)))) (defun zero-matrix (rows columns &key (matrix-type 'linear-algebra:dense-matrix)) "Return a ROWSxCOLUMNS zero matrix." (linear-algebra:make-matrix rows columns :matrix-type matrix-type :initial-element 0)) (defun unit-matrix (rows columns &key (matrix-type 'linear-algebra:dense-matrix)) "Return a ROWSxCOLUMNS unit matrix." (linear-algebra:make-matrix rows columns :matrix-type matrix-type :initial-element 1)) (defun identity-array (size) (let ((the-array (make-array (list size size) :initial-element 0.0))) (dotimes (i0 size the-array) (setf (aref the-array i0 i0) 1.0)))) (defun coordinate-array (&optional (row 0) (column 0) (row-end 10) (column-end 10)) "Return an array with the elements denoting the coordinate." (cond ((not (<= 0 row row-end 10)) (error "Invalid range of rows (~D:~D)." row row-end)) ((not (<= 0 column column-end 10)) (error "Invalid range of columns (~D:~D)." column column-end)) (t (let* ((rows (- row-end row)) (columns (- column-end column)) (the-array (make-array (list rows columns)))) (dotimes (i0 rows the-array) (dotimes (i1 columns) (setf (aref the-array i0 i1) (+ row i0 (/ (+ column i1) 10.0))))))))) (defun symmetric-array (&optional (start 0) (end 10)) "Return a symmetric array with the element denoting the coordinate." (if (<= 0 start end 10) (let* ((size (- end start)) (the-array (make-array (list size size))) (val nil)) (dotimes (i0 size the-array) (setf (aref the-array i0 i0) (+ start i0 (/ (+ start i0) 10.0))) (dotimes (i1 i0) (setf val (+ start i0 (/ (+ start i1) 10.0)) (aref the-array i0 i1) val (aref the-array i1 i0) val)))) (error "Invalid range (~D:~D)." start end))) (defun hermitian-array (&optional (start 0) (end 10)) "Return a Hermitian array with the element denoting the coordinate." (if (<= 0 start end 10) (let* ((size (- end start)) (the-array (make-array (list size size)))) (dotimes (i0 size the-array) (setf (aref the-array i0 i0) (complex (+ 1 start i0) 0)) (dotimes (i1 i0) (setf (aref the-array i0 i1) (complex (+ 1 start i0) (- -1 start i1))) (setf (aref the-array i1 i0) (complex (+ 1 start i0) (+ 1 start i1)))))) (error "Invalid range (~D:~D)." start end))) (defun upper-triangular-array (&optional (start 0) (end 10)) "Return a 10x10 list with the element denoting the coordinate." (if (<= 0 start end 10) (let* ((size (- end start)) (the-array (make-array (list size size) :element-type 'single-float :initial-element 0.0))) (dotimes (i1 size the-array) (setf (aref the-array i1 i1) 1.0) (dotimes (i0 i1) (setf (aref the-array i0 i1) 1.0)))) (error "Invalid range (~D:~D)." start end))) (defun lower-triangular-array (&optional (start 0) (end 10)) "Return a 10x10 list with the element denoting the coordinate." (if (<= 0 start end 10) (let* ((size (- end start)) (the-array (make-array (list size size) :element-type 'single-float :initial-element 0.0))) (dotimes (i0 size the-array) (setf (aref the-array i0 i0) 1.0) (dotimes (i1 i0) (setf (aref the-array i0 i1) 1.0)))) (error "Invalid range (~D:~D)." start end))) (defun random-permutation-vector (size &optional (counter -1)) "Return a random permutation vector of SIZE." (let ((permutation (map-into (make-array size) (lambda () (incf counter))))) (do ((index 0 (1+ index)) (swap (random size) (random size))) ((>= index size) permutation) (rotatef (svref permutation index) (svref permutation swap))))) (defun random-permutation-array (size) "Return a random permutation matrix of SIZE." (let ((permutation (random-permutation-vector size)) (the-array (make-array (list size size) :initial-element 0))) (dotimes (row size the-array) (setf (aref the-array row (svref permutation row)) 1)))) (defun permutations (list) "Return permutations of the list. [Erik Naggum]" (if (cdr list) (loop with rotation = list do (setq rotation (nconc (last rotation) (nbutlast rotation))) nconc (loop for list in (permutations (rest rotation)) collect (cons (first rotation) (copy-list list))) until (eq rotation list)) (list list))) (defun cartesian-product (list1 list2) "Return a list of the Cartesian product of two lists." (mapcan (lambda (x) (mapcar (lambda (y) (list x y)) list2)) list1)) (defun nary-product (list1 list2 &rest more-lists) "Return a list of the n-ary Cartesian product of the lists." (if (null more-lists) (cartesian-product list1 list2) (mapcan (lambda (x) (mapcar (lambda (y) (push x y)) (apply #'nary-product list2 (car more-lists) (rest more-lists)))) list1))) (defmethod rational-equal ((result1 sequence) (result2 linear-algebra:data-vector)) (rational-equal result1 (linear-algebra::contents result2))) (defmethod float-equal ((result1 sequence) (result2 linear-algebra:data-vector) &optional (epsilon lisp-unit:*epsilon*)) (float-equal result1 (linear-algebra::contents result2) epsilon)) (defmethod rational-equal ((result1 linear-algebra:data-vector) (result2 linear-algebra:data-vector)) (rational-equal (linear-algebra::contents result1) (linear-algebra::contents result2))) (defmethod float-equal ((result1 linear-algebra:data-vector) (result2 linear-algebra:data-vector) &optional (epsilon lisp-unit:*epsilon*)) (float-equal (linear-algebra::contents result1) (linear-algebra::contents result2) epsilon)) (defmethod rational-equal ((result1 list) (result2 linear-algebra:dense-matrix)) (let* ((contents (linear-algebra::contents result2)) (rows (array-dimension contents 0)) (columns (array-dimension contents 1)) (data-row nil)) (when (= rows (length result1)) (dotimes (i0 rows t) (if (= columns (length (setf data-row (nth i0 result1)))) (dotimes (i1 columns) (unless (rational-equal (elt data-row i1) (aref contents i0 i1)) (return-from rational-equal))) (return-from rational-equal)))))) (defmethod float-equal ((result1 list) (result2 linear-algebra:dense-matrix) &optional (epsilon lisp-unit:*epsilon*)) (let* ((contents (linear-algebra::contents result2)) (rows (array-dimension contents 0)) (columns (array-dimension contents 1)) (data-row nil)) (when (= rows (length result1)) (dotimes (i0 rows t) (if (= columns (length (setf data-row (nth i0 result1)))) (dotimes (i1 columns) (unless (float-equal (elt data-row i1) (aref contents i0 i1) epsilon) (return-from float-equal))) (return-from float-equal)))))) (defmethod rational-equal ((result1 vector) (result2 linear-algebra:dense-matrix)) (let* ((contents (linear-algebra::contents result2)) (rows (array-dimension contents 0)) (columns (array-dimension contents 1)) (data-row nil)) (when (= rows (length result1)) (dotimes (i0 rows t) (if (= columns (length (setf data-row (svref result1 i0)))) (dotimes (i1 columns) (unless (rational-equal (elt data-row i1) (aref contents i0 i1)) (return-from rational-equal))) (return-from rational-equal)))))) (defmethod float-equal ((result1 vector) (result2 linear-algebra:dense-matrix) &optional (epsilon lisp-unit:*epsilon*)) (let* ((contents (linear-algebra::contents result2)) (rows (array-dimension contents 0)) (columns (array-dimension contents 1)) (data-row nil)) (when (= rows (length result1)) (dotimes (i0 rows t) (if (= columns (length (setf data-row (svref result1 i0)))) (dotimes (i1 columns) (unless (float-equal (elt data-row i1) (aref contents i0 i1) epsilon) (return-from float-equal))) (return-from float-equal)))))) (defmethod rational-equal ((result1 array) (result2 linear-algebra:dense-matrix)) (rational-equal result1 (linear-algebra::contents result2))) (defmethod float-equal ((result1 array) (result2 linear-algebra:dense-matrix) &optional (epsilon lisp-unit:*epsilon*)) (float-equal result1 (linear-algebra::contents result2) epsilon)) (defmethod rational-equal ((result1 linear-algebra:dense-matrix) (result2 linear-algebra:dense-matrix)) (rational-equal (linear-algebra::contents result1) (linear-algebra::contents result2))) (defmethod float-equal ((result1 linear-algebra:dense-matrix) (result2 linear-algebra:dense-matrix) &optional (epsilon lisp-unit:*epsilon*)) (float-equal (linear-algebra::contents result1) (linear-algebra::contents result2) epsilon))
9b8c2b38c586a7911aa1e6a8456a5f0437327d6c32ffdeb92b7c52b387f9c53b
may-liu/qtalk
win32_dns.erl
%%%---------------------------------------------------------------------- %%% File : win32_dns.erl Author : nt Purpose : Get name servers in a Windows machine Created : 5 Mar 2009 by nt %%% %%% ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . %%% %%%---------------------------------------------------------------------- -module(win32_dns). -export([get_nameservers/0]). -include("ejabberd.hrl"). -include("logger.hrl"). -define(IF_KEY, "\\hklm\\system\\CurrentControlSet\\Services\\TcpIp\\Parameters\\Interfaces"). -define(TOP_KEY, "\\hklm\\system\\CurrentControlSet\\Services\\TcpIp\\Parameters"). get_nameservers() -> {_, Config} = pick_config(), IPTs = get_value(["NameServer"], Config), lists:filter(fun(IPTuple) -> is_good_ns(IPTuple) end, IPTs). is_good_ns(Addr) -> element(1, inet_res:nnslookup("a.root-servers.net", in, any, [{Addr,53}], timer:seconds(5) ) ) =:= ok. reg() -> {ok, R} = win32reg:open([read]), R. interfaces(R) -> ok = win32reg:change_key(R, ?IF_KEY), {ok, I} = win32reg:sub_keys(R), I. config_keys(R, Key) -> ok = win32reg:change_key(R, Key), [ {K, case win32reg:value(R, K) of {ok, V} -> try_translate(K, V); _ -> undefined end } || K <- ["Domain", "DhcpDomain", "NameServer", "DhcpNameServer", "SearchList"]]. try_translate(K, V) -> try translate(K, V) of Res -> Res catch A:B -> ?ERROR_MSG("Error '~p' translating Win32 registry~n" "K: ~p~nV: ~p~nError: ~p", [A, K, V, B]), undefined end. translate(NS, V) when NS =:= "NameServer"; NS =:= "DhcpNameServer" -> %% The IPs may be separated by commas ',' or by spaces " " %% The parts of an IP are separated by dots '.' IPsStrings = [string:tokens(IP, ".") || IP <- string:tokens(V, " ,")], [ list_to_tuple([list_to_integer(String) || String <- IpStrings]) || IpStrings <- IPsStrings]; translate(_, V) -> V. interface_configs(R) -> [{If, config_keys(R, ?IF_KEY ++ "\\" ++ If)} || If <- interfaces(R)]. sort_configs(Configs) -> lists:sort(fun ({_, A}, {_, B}) -> ANS = proplists:get_value("NameServer", A), BNS = proplists:get_value("NameServer", B), if ANS =/= undefined, BNS =:= undefined -> false; true -> count_undef(A) < count_undef(B) end end, Configs). count_undef(L) when is_list(L) -> lists:foldl(fun ({_K, undefined}, Acc) -> Acc +1; ({_K, []}, Acc) -> Acc +1; (_, Acc) -> Acc end, 0, L). all_configs() -> R = reg(), TopConfig = config_keys(R, ?TOP_KEY), Configs = [{top, TopConfig} | interface_configs(R)], win32reg:close(R), {TopConfig, Configs}. pick_config() -> {TopConfig, Configs} = all_configs(), NSConfigs = [{If, C} || {If, C} <- Configs, get_value(["DhcpNameServer","NameServer"], C) =/= undefined], case get_value(["DhcpNameServer","NameServer"], TopConfig) of %% No top level nameserver to pick interface with undefined -> hd(sort_configs(NSConfigs)); %% Top level has a nameserver - use this to select an interface. NS -> Cs = [ {If, C} || {If, C} <- Configs, lists:member(NS, [get_value(["NameServer"], C), get_value(["DhcpNameServer"], C)])], hd(sort_configs(Cs)) end. get_value([], _Config) -> undefined; get_value([K|Keys], Config) -> case proplists:get_value(K, Config) of undefined -> get_value(Keys, Config); V -> V end.
null
https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/win32_dns.erl
erlang
---------------------------------------------------------------------- File : win32_dns.erl This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ---------------------------------------------------------------------- The IPs may be separated by commas ',' or by spaces " " The parts of an IP are separated by dots '.' No top level nameserver to pick interface with Top level has a nameserver - use this to select an interface.
Author : nt Purpose : Get name servers in a Windows machine Created : 5 Mar 2009 by nt ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . -module(win32_dns). -export([get_nameservers/0]). -include("ejabberd.hrl"). -include("logger.hrl"). -define(IF_KEY, "\\hklm\\system\\CurrentControlSet\\Services\\TcpIp\\Parameters\\Interfaces"). -define(TOP_KEY, "\\hklm\\system\\CurrentControlSet\\Services\\TcpIp\\Parameters"). get_nameservers() -> {_, Config} = pick_config(), IPTs = get_value(["NameServer"], Config), lists:filter(fun(IPTuple) -> is_good_ns(IPTuple) end, IPTs). is_good_ns(Addr) -> element(1, inet_res:nnslookup("a.root-servers.net", in, any, [{Addr,53}], timer:seconds(5) ) ) =:= ok. reg() -> {ok, R} = win32reg:open([read]), R. interfaces(R) -> ok = win32reg:change_key(R, ?IF_KEY), {ok, I} = win32reg:sub_keys(R), I. config_keys(R, Key) -> ok = win32reg:change_key(R, Key), [ {K, case win32reg:value(R, K) of {ok, V} -> try_translate(K, V); _ -> undefined end } || K <- ["Domain", "DhcpDomain", "NameServer", "DhcpNameServer", "SearchList"]]. try_translate(K, V) -> try translate(K, V) of Res -> Res catch A:B -> ?ERROR_MSG("Error '~p' translating Win32 registry~n" "K: ~p~nV: ~p~nError: ~p", [A, K, V, B]), undefined end. translate(NS, V) when NS =:= "NameServer"; NS =:= "DhcpNameServer" -> IPsStrings = [string:tokens(IP, ".") || IP <- string:tokens(V, " ,")], [ list_to_tuple([list_to_integer(String) || String <- IpStrings]) || IpStrings <- IPsStrings]; translate(_, V) -> V. interface_configs(R) -> [{If, config_keys(R, ?IF_KEY ++ "\\" ++ If)} || If <- interfaces(R)]. sort_configs(Configs) -> lists:sort(fun ({_, A}, {_, B}) -> ANS = proplists:get_value("NameServer", A), BNS = proplists:get_value("NameServer", B), if ANS =/= undefined, BNS =:= undefined -> false; true -> count_undef(A) < count_undef(B) end end, Configs). count_undef(L) when is_list(L) -> lists:foldl(fun ({_K, undefined}, Acc) -> Acc +1; ({_K, []}, Acc) -> Acc +1; (_, Acc) -> Acc end, 0, L). all_configs() -> R = reg(), TopConfig = config_keys(R, ?TOP_KEY), Configs = [{top, TopConfig} | interface_configs(R)], win32reg:close(R), {TopConfig, Configs}. pick_config() -> {TopConfig, Configs} = all_configs(), NSConfigs = [{If, C} || {If, C} <- Configs, get_value(["DhcpNameServer","NameServer"], C) =/= undefined], case get_value(["DhcpNameServer","NameServer"], TopConfig) of undefined -> hd(sort_configs(NSConfigs)); NS -> Cs = [ {If, C} || {If, C} <- Configs, lists:member(NS, [get_value(["NameServer"], C), get_value(["DhcpNameServer"], C)])], hd(sort_configs(Cs)) end. get_value([], _Config) -> undefined; get_value([K|Keys], Config) -> case proplists:get_value(K, Config) of undefined -> get_value(Keys, Config); V -> V end.
b794775afe7f1da9689f1732b3a23180f67cda0907f08a5c9eb6584359580ea8
grin-compiler/grin
TrivialCaseEliminationSpec.hs
# LANGUAGE OverloadedStrings , QuasiQuotes , ViewPatterns # module Transformations.Optimising.TrivialCaseEliminationSpec where import Transformations.Optimising.TrivialCaseElimination import Test.Hspec import Grin.TH import Test.Test hiding (newVar) import Test.Assertions runTests :: IO () runTests = hspec spec spec :: Spec spec = do testExprContextE $ \ctx -> do it "Figure 4.24" $ do let before = [expr| case v of (Ffun a1 a2 a3) -> fun a1 a2 a3 |] let after = [expr| do (Ffun a1 a2 a3) <- pure v fun a1 a2 a3 |] trivialCaseElimination (ctx before) `sameAs` (ctx after) it "bypass" $ do let before = [expr| case v of (Ffun1 a1 a2 a3) -> fun1 a1 a2 a3 #default -> pure 2 |] let after = [expr| case v of (Ffun1 a1 a2 a3) -> fun1 a1 a2 a3 #default -> pure 2 |] trivialCaseElimination (ctx before) `sameAs` (ctx after) it "default alternative" $ do let before = [expr| case v of #default -> pure 2 |] let after = [expr| do pure 2 |] trivialCaseElimination (ctx before) `sameAs` (ctx after)
null
https://raw.githubusercontent.com/grin-compiler/grin/44ac2958810ecee969c8028d2d2a082d47fba51b/grin/test/Transformations/Optimising/TrivialCaseEliminationSpec.hs
haskell
# LANGUAGE OverloadedStrings , QuasiQuotes , ViewPatterns # module Transformations.Optimising.TrivialCaseEliminationSpec where import Transformations.Optimising.TrivialCaseElimination import Test.Hspec import Grin.TH import Test.Test hiding (newVar) import Test.Assertions runTests :: IO () runTests = hspec spec spec :: Spec spec = do testExprContextE $ \ctx -> do it "Figure 4.24" $ do let before = [expr| case v of (Ffun a1 a2 a3) -> fun a1 a2 a3 |] let after = [expr| do (Ffun a1 a2 a3) <- pure v fun a1 a2 a3 |] trivialCaseElimination (ctx before) `sameAs` (ctx after) it "bypass" $ do let before = [expr| case v of (Ffun1 a1 a2 a3) -> fun1 a1 a2 a3 #default -> pure 2 |] let after = [expr| case v of (Ffun1 a1 a2 a3) -> fun1 a1 a2 a3 #default -> pure 2 |] trivialCaseElimination (ctx before) `sameAs` (ctx after) it "default alternative" $ do let before = [expr| case v of #default -> pure 2 |] let after = [expr| do pure 2 |] trivialCaseElimination (ctx before) `sameAs` (ctx after)
660b68517643ffd7a8ee202ef32e004fa6d38dbb87c2934f845661c64bd640df
shayan-najd/QFeldspar
CDSL.hs
module Examples.IPGray.CDSL where import Prelude hiding (Int,pi,div,foldl,map) import QFeldspar.CDSL redCoefficient :: Dp Word32 redCoefficient = 30 greenCoefficient :: Dp Word32 greenCoefficient = 59 blueCoefficient :: Dp Word32 blueCoefficient = 11 rgbToGray :: Dp Word32 -> Dp Word32 -> Dp Word32 -> Dp Word32 rgbToGray = \ r -> \ g -> \ b -> divE ((r * redCoefficient) + (g * greenCoefficient) + (b * blueCoefficient)) 100 ipgrayVec :: Vec (Dp Word32) -> Vec (Dp Word32) ipgrayVec = \ (Vec l f) -> Vec (divE l 3) (\ i -> share (i * 3) (\ j -> rgbToGray (f j) (f (j + 1)) (f (j + 2)))) ipgray :: Dp (Ary Word32) -> Dp (Ary Word32) ipgray = toExpF ipgrayVec
null
https://raw.githubusercontent.com/shayan-najd/QFeldspar/ed60ce02794a548833317388f6e82e2ab1eabc1c/Examples/IPGray/CDSL.hs
haskell
module Examples.IPGray.CDSL where import Prelude hiding (Int,pi,div,foldl,map) import QFeldspar.CDSL redCoefficient :: Dp Word32 redCoefficient = 30 greenCoefficient :: Dp Word32 greenCoefficient = 59 blueCoefficient :: Dp Word32 blueCoefficient = 11 rgbToGray :: Dp Word32 -> Dp Word32 -> Dp Word32 -> Dp Word32 rgbToGray = \ r -> \ g -> \ b -> divE ((r * redCoefficient) + (g * greenCoefficient) + (b * blueCoefficient)) 100 ipgrayVec :: Vec (Dp Word32) -> Vec (Dp Word32) ipgrayVec = \ (Vec l f) -> Vec (divE l 3) (\ i -> share (i * 3) (\ j -> rgbToGray (f j) (f (j + 1)) (f (j + 2)))) ipgray :: Dp (Ary Word32) -> Dp (Ary Word32) ipgray = toExpF ipgrayVec
e89adbee534c7fd202c1b59fd99e0304f83e8bb0d2ade2e3fd109be01a9f321d
AdRoll/rebar3_hank
unnecessary_function_arguments_SUITE.erl
-module(unnecessary_function_arguments_SUITE). -export([all/0, init_per_testcase/2, end_per_testcase/2]). -export([with_warnings/1, without_warnings/1, macros/1, ignore/1, ignore_config/1, ct_suite/1]). all() -> [with_warnings, without_warnings, macros, ignore, ct_suite]. init_per_testcase(_, Config) -> hank_test_utils:init_per_testcase(Config, "unnecessary_function_arguments"). end_per_testcase(_, Config) -> hank_test_utils:end_per_testcase(Config). @doc finds unused function parameters with_warnings(_Config) -> ct:comment("Should detect and display warnings for unused function parameters"), FileA = "warnings_A.erl", FileB = "warnings_B.erl", FileC = "a_behaviour.erl", FileD = "a_behaviour_imp.erl", FileE = "gen_server_imp.erl", [#{file := FileC, text := <<"a_function_from_the_behaviour/1 doesn't need its #1 argument">>}, #{file := FileD, text := <<"non_exported_function_with/2 doesn't need its #1 argument">>}, #{file := FileE, text := <<"my_function/1 doesn't need its #1 argument">>}, #{file := FileE, text := <<"my_other_function/2 doesn't need its #2 argument">>}, #{file := FileA, text := <<"single_fun/2 doesn't need its #2 argument">>}, #{file := FileA, text := <<"multi_fun/3 doesn't need its #3 argument">>}, #{file := FileA, text := <<"unicode_αβåö/1 doesn't need its #1 argument"/utf8>>}, #{file := FileA, text := <<"with_nif_stub/2 doesn't need its #1 argument">>}, #{file := FileB, text := <<"underscore/3 doesn't need its #1 argument">>}] = analyze([FileA, FileB, FileC, FileD, FileE, "macro_behaviour_imp.erl"]), ok. @doc finds nothing ! without_warnings(_Config) -> ct:comment("Should not detect anything since the files are clean from warnings"), [] = analyze(["weird.erl", "clean.erl", "nifs.erl", "macro_behaviour_imp.erl", "parse_transf.erl"]), ok. @doc Macros as function names should work macros(_Config) -> ct:comment("Macros as function names should not crash hank"), [#{file := "macros.erl", text := <<"?MODULE/1 doesn't need its #1 argument">>}] = analyze(["macros.erl"]), ok. @doc should correctly ignore warnings ignore(_Config) -> ct:comment("Should correctly ignore warnings"), [#{file := "ignore.erl", text := <<"ignore_arg2/2 doesn't need its #2 argument">>}] = analyze(["ignore.erl"]), ok. %% @doc No warnings since rebar.config specifically states that all of them %% should be ignored. ignore_config(_) -> File = "ignore_config.erl", Files = [File], IgnoreSpecs = [{File, unnecessary_function_arguments, [{ignore_arg2, 3, 2}, {ignore_arg2, 2, 1}, {ignore_arg2, 2, 2}, {ignore_whole_func3, 3}, ignore_whole_func]}], #{results := [], unused_ignores := []} = hank_test_utils:analyze_and_sort(Files, IgnoreSpecs, [unnecessary_function_arguments]). %% @doc Common Test suites should be ignored ct_suite(_Config) -> ct:comment("CT suites should not generate warnings"), Files = case code:which(ct_suite) of OTP < 23.2 ["old_ct_SUITE.erl"]; _ -> ["ct_SUITE.erl"] end, [] = analyze(Files). analyze(Files) -> #{results := Results, unused_ignores := []} = hank_test_utils:analyze_and_sort(Files, [unnecessary_function_arguments]), Results.
null
https://raw.githubusercontent.com/AdRoll/rebar3_hank/6035f08e74c694ae56c4c9382e74303e7b3e9018/test/unnecessary_function_arguments_SUITE.erl
erlang
@doc No warnings since rebar.config specifically states that all of them should be ignored. @doc Common Test suites should be ignored
-module(unnecessary_function_arguments_SUITE). -export([all/0, init_per_testcase/2, end_per_testcase/2]). -export([with_warnings/1, without_warnings/1, macros/1, ignore/1, ignore_config/1, ct_suite/1]). all() -> [with_warnings, without_warnings, macros, ignore, ct_suite]. init_per_testcase(_, Config) -> hank_test_utils:init_per_testcase(Config, "unnecessary_function_arguments"). end_per_testcase(_, Config) -> hank_test_utils:end_per_testcase(Config). @doc finds unused function parameters with_warnings(_Config) -> ct:comment("Should detect and display warnings for unused function parameters"), FileA = "warnings_A.erl", FileB = "warnings_B.erl", FileC = "a_behaviour.erl", FileD = "a_behaviour_imp.erl", FileE = "gen_server_imp.erl", [#{file := FileC, text := <<"a_function_from_the_behaviour/1 doesn't need its #1 argument">>}, #{file := FileD, text := <<"non_exported_function_with/2 doesn't need its #1 argument">>}, #{file := FileE, text := <<"my_function/1 doesn't need its #1 argument">>}, #{file := FileE, text := <<"my_other_function/2 doesn't need its #2 argument">>}, #{file := FileA, text := <<"single_fun/2 doesn't need its #2 argument">>}, #{file := FileA, text := <<"multi_fun/3 doesn't need its #3 argument">>}, #{file := FileA, text := <<"unicode_αβåö/1 doesn't need its #1 argument"/utf8>>}, #{file := FileA, text := <<"with_nif_stub/2 doesn't need its #1 argument">>}, #{file := FileB, text := <<"underscore/3 doesn't need its #1 argument">>}] = analyze([FileA, FileB, FileC, FileD, FileE, "macro_behaviour_imp.erl"]), ok. @doc finds nothing ! without_warnings(_Config) -> ct:comment("Should not detect anything since the files are clean from warnings"), [] = analyze(["weird.erl", "clean.erl", "nifs.erl", "macro_behaviour_imp.erl", "parse_transf.erl"]), ok. @doc Macros as function names should work macros(_Config) -> ct:comment("Macros as function names should not crash hank"), [#{file := "macros.erl", text := <<"?MODULE/1 doesn't need its #1 argument">>}] = analyze(["macros.erl"]), ok. @doc should correctly ignore warnings ignore(_Config) -> ct:comment("Should correctly ignore warnings"), [#{file := "ignore.erl", text := <<"ignore_arg2/2 doesn't need its #2 argument">>}] = analyze(["ignore.erl"]), ok. ignore_config(_) -> File = "ignore_config.erl", Files = [File], IgnoreSpecs = [{File, unnecessary_function_arguments, [{ignore_arg2, 3, 2}, {ignore_arg2, 2, 1}, {ignore_arg2, 2, 2}, {ignore_whole_func3, 3}, ignore_whole_func]}], #{results := [], unused_ignores := []} = hank_test_utils:analyze_and_sort(Files, IgnoreSpecs, [unnecessary_function_arguments]). ct_suite(_Config) -> ct:comment("CT suites should not generate warnings"), Files = case code:which(ct_suite) of OTP < 23.2 ["old_ct_SUITE.erl"]; _ -> ["ct_SUITE.erl"] end, [] = analyze(Files). analyze(Files) -> #{results := Results, unused_ignores := []} = hank_test_utils:analyze_and_sort(Files, [unnecessary_function_arguments]), Results.
19c23ef7059af2f59fe199939fed3efb4a1b84a14dca34d6d9731cc7c1baa2d4
gheber/kenzo
suspensions-test.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 - * (in-package :kenzo-test-7) (in-suite :kenzo-7) (test suspension-cmpr (cat-7:cat-init) (let* ((cc (cat-7:deltab)) (cmpr (cat-7:suspension-cmpr (cat-7:cmpr cc)))) (is (equal :equal (funcall cmpr :s-bsgn :s-bsgn))) (is (equal :greater (funcall cmpr 6 5))))) (test suspension-basis (cat-7:cat-init) (let* ((cc (cat-7:sphere 2)) (basis (cat-7:suspension-basis (cat-7:basis cc)))) (dotimes (i 6) (print (funcall basis i))) (cat-7:suspension-basis :locally-effective))) (test suspension-intr-dffr (cat-7:cat-init) (let* ((cc (cat-7:deltab)) (intr (cat-7:suspension-intr-dffr (cat-7:dffr cc)))) (funcall intr (cat-7:cmbn 0 3 :s-bsgn)) (funcall intr (cat-7:cmbn 3 66 7)))) (test suspension (cat-7:cat-init) (let* ((cc (cat-7:deltab)) (scc (cat-7:suspension cc))) (cat-7:cmpr scc 7 11) (signals simple-error (cat-7:basis scc 3)) (cat-7:bsgn scc) (cat-7:? scc 3 11) (setf scc (cat-7:suspension cc 2)) (cat-7:? scc 4 11))) (test suspension-intr-cprd (cat-7:suspension-intr-cprd (cat-7:cmbn 0)) (cat-7:suspension-intr-cprd (cat-7:cmbn 0 5 :s-bsgn)) (cat-7:suspension-intr-cprd (cat-7:cmbn 3 4 7 5 11))) (test coal (cat-7:cat-init) (let* ((coal (cat-7:deltab)) (scoal (cat-7:suspension coal))) (setf scoal (cat-7:suspension coal)) (cat-7:? scoal 3 7) (cat-7:cprd scoal 3 7))) (test suspension-face (cat-7:cat-init) (let* ((ss (cat-7:deltab)) (face (cat-7:suspension-face (cat-7:face ss))) (m (cat-7:moore 2 3))) (funcall face 4 4 15) (funcall face 0 4 15) #+(or ecl sbcl) (signals type-error (cat-7:check-faces #'cat-7:f-cmpr face 4 15)) #+(or ecl sbcl) (signals type-error (cat-7:check-faces #'cat-7:f-cmpr face 3 7)) #+(or ecl sbcl) (signals type-error (cat-7:check-faces #'cat-7:f-cmpr face 2 3)) #-(or ecl sbcl) (cat-7:check-faces #'cat-7:f-cmpr face 4 15) #-(or ecl sbcl) (cat-7:check-faces #'cat-7:f-cmpr face 3 7) #-(or ecl sbcl) (cat-7:check-faces #'cat-7:f-cmpr face 2 3) (setf face (cat-7:suspension-face (cat-7:face m))) (dotimes (i 5) (print (funcall face i 4 'm3))) (dotimes (i 6) (print (funcall face i 5 'mm4))) (cat-7:check-faces #'cat-7:s-cmpr face 4 'm3) (cat-7:check-faces #'cat-7:s-cmpr face 5 'mm4) )) (test suspension1 (cat-7:cat-init) (let* ((d (cat-7:deltab)) (sd (cat-7:suspension d)) (m (cat-7:moore 2 1)) (sm (cat-7:suspension m))) (setf sd (cat-7:suspension d)) (cat-7:? sd 3 7) (cat-7:cprd sd 3 7) (cat-7:face sd 3 3 7) (cat-7:face sd 2 3 7) (cat-7:homology sm 0 5) (setf ssm (cat-7:suspension sm)) (cat-7:homology ssm 0 6))) (test suspension-intr (cat-7:cat-init) (let* ((f (cat-7:idnt-mrph (cat-7:deltab))) (sf (cat-7:suspension-intr f)) (d (cat-7:dffr (cat-7:deltab))) (sd (cat-7:suspension-intr d))) (funcall sf (cat-7:cmbn 0 3 :s-bsgn)) (funcall sf (cat-7:cmbn 2 4 3)) (funcall sd (cat-7:cmbn 0 3 :s-bsgn)) (funcall sd (cat-7:cmbn 2 4 3)) (funcall sd (cat-7:cmbn 3 4 7)))) (test suspension2 (cat-7:cat-init) (let* ((f (cat-7:idnt-mrph (cat-7:deltab))) (sf (cat-7:suspension f)) (d (cat-7:dffr (cat-7:deltab))) (sd (cat-7:suspension d))) (cat-7:? sf (cat-7:cmbn 0 3 :s-bsgn)) (cat-7:? sf (cat-7:cmbn 2 4 3)) (cat-7:? sd (cat-7:cmbn 0 3 :s-bsgn)) (cat-7:? sd (cat-7:cmbn 2 4 3)) (cat-7:? sd (cat-7:cmbn 3 4 7)))) (test suspension3 (cat-7:cat-init) (let* ((rdct (cat-7:ez (cat-7:deltab) (cat-7:deltab))) (srdct (cat-7:suspension rdct))) (cat-7:pre-check-rdct srdct) (setf cat-7:*tc* (cat-7:cmbn 4 1 (cat-7:crpr 0 15 0 15))) (setf cat-7:*bc* (cat-7:cmbn 4 1 (cat-7:tnpr 0 1 3 15) 5 (cat-7:tnpr 1 3 2 7) 10 (cat-7:tnpr 2 7 1 3) 100 (cat-7:tnpr 3 15 0 1))) (check-rdct))) (test suspension4 (cat-7:cat-init) (let ((sk (cat-7:suspension (cat-7:k-z 2)))) (cat-7:homology sk 0 10)))
null
https://raw.githubusercontent.com/gheber/kenzo/48e2ea398b80f39d3b5954157a7df57e07a362d7/test/kenzo-7/suspensions-test.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 - *
(in-package :kenzo-test-7) (in-suite :kenzo-7) (test suspension-cmpr (cat-7:cat-init) (let* ((cc (cat-7:deltab)) (cmpr (cat-7:suspension-cmpr (cat-7:cmpr cc)))) (is (equal :equal (funcall cmpr :s-bsgn :s-bsgn))) (is (equal :greater (funcall cmpr 6 5))))) (test suspension-basis (cat-7:cat-init) (let* ((cc (cat-7:sphere 2)) (basis (cat-7:suspension-basis (cat-7:basis cc)))) (dotimes (i 6) (print (funcall basis i))) (cat-7:suspension-basis :locally-effective))) (test suspension-intr-dffr (cat-7:cat-init) (let* ((cc (cat-7:deltab)) (intr (cat-7:suspension-intr-dffr (cat-7:dffr cc)))) (funcall intr (cat-7:cmbn 0 3 :s-bsgn)) (funcall intr (cat-7:cmbn 3 66 7)))) (test suspension (cat-7:cat-init) (let* ((cc (cat-7:deltab)) (scc (cat-7:suspension cc))) (cat-7:cmpr scc 7 11) (signals simple-error (cat-7:basis scc 3)) (cat-7:bsgn scc) (cat-7:? scc 3 11) (setf scc (cat-7:suspension cc 2)) (cat-7:? scc 4 11))) (test suspension-intr-cprd (cat-7:suspension-intr-cprd (cat-7:cmbn 0)) (cat-7:suspension-intr-cprd (cat-7:cmbn 0 5 :s-bsgn)) (cat-7:suspension-intr-cprd (cat-7:cmbn 3 4 7 5 11))) (test coal (cat-7:cat-init) (let* ((coal (cat-7:deltab)) (scoal (cat-7:suspension coal))) (setf scoal (cat-7:suspension coal)) (cat-7:? scoal 3 7) (cat-7:cprd scoal 3 7))) (test suspension-face (cat-7:cat-init) (let* ((ss (cat-7:deltab)) (face (cat-7:suspension-face (cat-7:face ss))) (m (cat-7:moore 2 3))) (funcall face 4 4 15) (funcall face 0 4 15) #+(or ecl sbcl) (signals type-error (cat-7:check-faces #'cat-7:f-cmpr face 4 15)) #+(or ecl sbcl) (signals type-error (cat-7:check-faces #'cat-7:f-cmpr face 3 7)) #+(or ecl sbcl) (signals type-error (cat-7:check-faces #'cat-7:f-cmpr face 2 3)) #-(or ecl sbcl) (cat-7:check-faces #'cat-7:f-cmpr face 4 15) #-(or ecl sbcl) (cat-7:check-faces #'cat-7:f-cmpr face 3 7) #-(or ecl sbcl) (cat-7:check-faces #'cat-7:f-cmpr face 2 3) (setf face (cat-7:suspension-face (cat-7:face m))) (dotimes (i 5) (print (funcall face i 4 'm3))) (dotimes (i 6) (print (funcall face i 5 'mm4))) (cat-7:check-faces #'cat-7:s-cmpr face 4 'm3) (cat-7:check-faces #'cat-7:s-cmpr face 5 'mm4) )) (test suspension1 (cat-7:cat-init) (let* ((d (cat-7:deltab)) (sd (cat-7:suspension d)) (m (cat-7:moore 2 1)) (sm (cat-7:suspension m))) (setf sd (cat-7:suspension d)) (cat-7:? sd 3 7) (cat-7:cprd sd 3 7) (cat-7:face sd 3 3 7) (cat-7:face sd 2 3 7) (cat-7:homology sm 0 5) (setf ssm (cat-7:suspension sm)) (cat-7:homology ssm 0 6))) (test suspension-intr (cat-7:cat-init) (let* ((f (cat-7:idnt-mrph (cat-7:deltab))) (sf (cat-7:suspension-intr f)) (d (cat-7:dffr (cat-7:deltab))) (sd (cat-7:suspension-intr d))) (funcall sf (cat-7:cmbn 0 3 :s-bsgn)) (funcall sf (cat-7:cmbn 2 4 3)) (funcall sd (cat-7:cmbn 0 3 :s-bsgn)) (funcall sd (cat-7:cmbn 2 4 3)) (funcall sd (cat-7:cmbn 3 4 7)))) (test suspension2 (cat-7:cat-init) (let* ((f (cat-7:idnt-mrph (cat-7:deltab))) (sf (cat-7:suspension f)) (d (cat-7:dffr (cat-7:deltab))) (sd (cat-7:suspension d))) (cat-7:? sf (cat-7:cmbn 0 3 :s-bsgn)) (cat-7:? sf (cat-7:cmbn 2 4 3)) (cat-7:? sd (cat-7:cmbn 0 3 :s-bsgn)) (cat-7:? sd (cat-7:cmbn 2 4 3)) (cat-7:? sd (cat-7:cmbn 3 4 7)))) (test suspension3 (cat-7:cat-init) (let* ((rdct (cat-7:ez (cat-7:deltab) (cat-7:deltab))) (srdct (cat-7:suspension rdct))) (cat-7:pre-check-rdct srdct) (setf cat-7:*tc* (cat-7:cmbn 4 1 (cat-7:crpr 0 15 0 15))) (setf cat-7:*bc* (cat-7:cmbn 4 1 (cat-7:tnpr 0 1 3 15) 5 (cat-7:tnpr 1 3 2 7) 10 (cat-7:tnpr 2 7 1 3) 100 (cat-7:tnpr 3 15 0 1))) (check-rdct))) (test suspension4 (cat-7:cat-init) (let ((sk (cat-7:suspension (cat-7:k-z 2)))) (cat-7:homology sk 0 10)))
fe50e9d9574adc3aeb2338ec798cb96bf9d1a37f71f4e7ad6a944b35e86b2fbd
clarle/ai-class
trees.clj
(ns unit02.test.trees (:use [unit02.trees]) (:use [clojure.test])) (def tree-1 (node :a [(node :b [(node :d []) (node :e [])]) (node :c [(node :f []) (node :g [])])])) (def tree-2 (node :a [(node :b [(node :d []) (node :e [])]) (node :q []) (node :c [(node :f [(node :x []) (node :y [(node :z [])])]) (node :g [])])])) (deftest test-bf-binary-paths (is (= (:path (search-breadth tree-1 :a)) [:a]) "Breadth-first search didn't find the path to the root node") (is (= (:path (search-breadth tree-1 :b)) [:a :b]) "Breadth-first search didn't find the path to a child node") (is (= (:path (search-breadth tree-1 :c)) [:a :c]) "Breadth-first search didn't find the path to a child node") (is (= (:path (search-breadth tree-1 :d)) [:a :b :d]) "Breadth-first search didn't find the path to a leaf node") (is (= (:path (search-breadth tree-1 :g)) [:a :c :g]) "Breadth-first search didn't find the path to a leaf node")) (deftest test-df-binary-paths (is (= (:path (search-depth tree-1 :a)) [:a]) "Depth-first search didn't find the path to the root node") (is (= (:path (search-depth tree-1 :b)) [:a :b]) "Depth-first search didn't find the path to a child node") (is (= (:path (search-depth tree-1 :c)) [:a :c]) "Depth-first search didn't find the path to a child node") (is (= (:path (search-depth tree-1 :d)) [:a :b :d]) "Depth-first search didn't find the path to a leaf node") (is (= (:path (search-depth tree-1 :g)) [:a :c :g]) "Depth-first search didn't find the path to a leaf node")) (deftest test-bf-nonbinary-paths (is (= (:path (search-breadth tree-2 :a)) [:a]) "Breadth-first search didn't find the path to the root node") (is (= (:path (search-breadth tree-2 :q)) [:a :q]) "Breadth-first search didn't find the path to a leaf node") (is (= (:path (search-breadth tree-2 :c)) [:a :c]) "Breadth-first search didn't find the path to a child node") (is (= (:path (search-breadth tree-2 :y)) [:a :c :f :y]) "Breadth-first search didn't find the path to a child node") (is (= (:path (search-breadth tree-2 :z)) [:a :c :f :y :z]) "Breadth-first search didn't find the path to a leaf node")) (deftest test-df-nonbinary-paths (is (= (:path (search-depth tree-2 :a)) [:a]) "Depth-first search didn't find the path to the root node") (is (= (:path (search-depth tree-2 :q)) [:a :q]) "Depth-first search didn't find the path to a child node") (is (= (:path (search-depth tree-2 :c)) [:a :c]) "Depth-first search didn't find the path to a child node") (is (= (:path (search-depth tree-2 :y)) [:a :c :f :y]) "Depth-first search didn't find the path to a leaf node") (is (= (:path (search-depth tree-2 :z)) [:a :c :f :y :z]) "Depth-first search didn't find the path to a leaf node")) (deftest test-bf-binary-costs (is (= (:examined (search-breadth tree-1 :a)) 1) "Breadth-first search didn't examine the correct number of nodes to find the root node") (is (= (:examined (search-breadth tree-1 :b)) 2) "Breadth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-breadth tree-1 :c)) 3) "Breadth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-breadth tree-1 :d)) 4) "Breadth-first search didn't examine the correct number of nodes to find a leaf node") (is (= (:examined (search-breadth tree-1 :g)) 7) "Breadth-first search didn't examine the correct number of nodes to find a leaf node")) (deftest test-df-binary-costs (is (= (:examined (search-depth tree-1 :a)) 1) "Depth-first search didn't examine the correct number of nodes to find the root node") (is (= (:examined (search-depth tree-1 :b)) 2) "Depth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-depth tree-1 :c)) 5) "Depth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-depth tree-1 :d)) 3) "Depth-first search didn't examine the correct number of nodes to find a leaf node") (is (= (:examined (search-depth tree-1 :g)) 7) "Depth-first search didn't examine the correct number of nodes to find a leaf node")) (deftest test-bf-nonbinary-costs (is (= (:examined (search-breadth tree-2 :a)) 1) "Breadth-first search didn't examine the correct number of nodes to find the root node") (is (= (:examined (search-breadth tree-2 :q)) 3) "Breadth-first search didn't examine the correct number of nodes to find a leaf node") (is (= (:examined (search-breadth tree-2 :c)) 4) "Breadth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-breadth tree-2 :y)) 10) "Breadth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-breadth tree-2 :z)) 11) "Breadth-first search didn't examine the correct number of nodes to find a leaf node")) (deftest test-df-nonbinary-costs (is (= (:examined (search-depth tree-2 :a)) 1) "Depth-first search didn't examine the correct number of nodes to find the root node") (is (= (:examined (search-depth tree-2 :q)) 5) "Depth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-depth tree-2 :c)) 6) "Depth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-depth tree-2 :y)) 9) "Depth-first search didn't examine the correct number of nodes to find a leaf node") (is (= (:examined (search-depth tree-2 :z)) 10) "Depth-first search didn't examine the correct number of nodes to find a leaf node"))
null
https://raw.githubusercontent.com/clarle/ai-class/44ca6d34380942600fb3a61a09e6a2dc4a4841c1/unit02/clojure/unit02/test/unit02/test/trees.clj
clojure
(ns unit02.test.trees (:use [unit02.trees]) (:use [clojure.test])) (def tree-1 (node :a [(node :b [(node :d []) (node :e [])]) (node :c [(node :f []) (node :g [])])])) (def tree-2 (node :a [(node :b [(node :d []) (node :e [])]) (node :q []) (node :c [(node :f [(node :x []) (node :y [(node :z [])])]) (node :g [])])])) (deftest test-bf-binary-paths (is (= (:path (search-breadth tree-1 :a)) [:a]) "Breadth-first search didn't find the path to the root node") (is (= (:path (search-breadth tree-1 :b)) [:a :b]) "Breadth-first search didn't find the path to a child node") (is (= (:path (search-breadth tree-1 :c)) [:a :c]) "Breadth-first search didn't find the path to a child node") (is (= (:path (search-breadth tree-1 :d)) [:a :b :d]) "Breadth-first search didn't find the path to a leaf node") (is (= (:path (search-breadth tree-1 :g)) [:a :c :g]) "Breadth-first search didn't find the path to a leaf node")) (deftest test-df-binary-paths (is (= (:path (search-depth tree-1 :a)) [:a]) "Depth-first search didn't find the path to the root node") (is (= (:path (search-depth tree-1 :b)) [:a :b]) "Depth-first search didn't find the path to a child node") (is (= (:path (search-depth tree-1 :c)) [:a :c]) "Depth-first search didn't find the path to a child node") (is (= (:path (search-depth tree-1 :d)) [:a :b :d]) "Depth-first search didn't find the path to a leaf node") (is (= (:path (search-depth tree-1 :g)) [:a :c :g]) "Depth-first search didn't find the path to a leaf node")) (deftest test-bf-nonbinary-paths (is (= (:path (search-breadth tree-2 :a)) [:a]) "Breadth-first search didn't find the path to the root node") (is (= (:path (search-breadth tree-2 :q)) [:a :q]) "Breadth-first search didn't find the path to a leaf node") (is (= (:path (search-breadth tree-2 :c)) [:a :c]) "Breadth-first search didn't find the path to a child node") (is (= (:path (search-breadth tree-2 :y)) [:a :c :f :y]) "Breadth-first search didn't find the path to a child node") (is (= (:path (search-breadth tree-2 :z)) [:a :c :f :y :z]) "Breadth-first search didn't find the path to a leaf node")) (deftest test-df-nonbinary-paths (is (= (:path (search-depth tree-2 :a)) [:a]) "Depth-first search didn't find the path to the root node") (is (= (:path (search-depth tree-2 :q)) [:a :q]) "Depth-first search didn't find the path to a child node") (is (= (:path (search-depth tree-2 :c)) [:a :c]) "Depth-first search didn't find the path to a child node") (is (= (:path (search-depth tree-2 :y)) [:a :c :f :y]) "Depth-first search didn't find the path to a leaf node") (is (= (:path (search-depth tree-2 :z)) [:a :c :f :y :z]) "Depth-first search didn't find the path to a leaf node")) (deftest test-bf-binary-costs (is (= (:examined (search-breadth tree-1 :a)) 1) "Breadth-first search didn't examine the correct number of nodes to find the root node") (is (= (:examined (search-breadth tree-1 :b)) 2) "Breadth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-breadth tree-1 :c)) 3) "Breadth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-breadth tree-1 :d)) 4) "Breadth-first search didn't examine the correct number of nodes to find a leaf node") (is (= (:examined (search-breadth tree-1 :g)) 7) "Breadth-first search didn't examine the correct number of nodes to find a leaf node")) (deftest test-df-binary-costs (is (= (:examined (search-depth tree-1 :a)) 1) "Depth-first search didn't examine the correct number of nodes to find the root node") (is (= (:examined (search-depth tree-1 :b)) 2) "Depth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-depth tree-1 :c)) 5) "Depth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-depth tree-1 :d)) 3) "Depth-first search didn't examine the correct number of nodes to find a leaf node") (is (= (:examined (search-depth tree-1 :g)) 7) "Depth-first search didn't examine the correct number of nodes to find a leaf node")) (deftest test-bf-nonbinary-costs (is (= (:examined (search-breadth tree-2 :a)) 1) "Breadth-first search didn't examine the correct number of nodes to find the root node") (is (= (:examined (search-breadth tree-2 :q)) 3) "Breadth-first search didn't examine the correct number of nodes to find a leaf node") (is (= (:examined (search-breadth tree-2 :c)) 4) "Breadth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-breadth tree-2 :y)) 10) "Breadth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-breadth tree-2 :z)) 11) "Breadth-first search didn't examine the correct number of nodes to find a leaf node")) (deftest test-df-nonbinary-costs (is (= (:examined (search-depth tree-2 :a)) 1) "Depth-first search didn't examine the correct number of nodes to find the root node") (is (= (:examined (search-depth tree-2 :q)) 5) "Depth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-depth tree-2 :c)) 6) "Depth-first search didn't examine the correct number of nodes to find a child node") (is (= (:examined (search-depth tree-2 :y)) 9) "Depth-first search didn't examine the correct number of nodes to find a leaf node") (is (= (:examined (search-depth tree-2 :z)) 10) "Depth-first search didn't examine the correct number of nodes to find a leaf node"))
5754b43e6166943468a3f9e5d061decf57f9019f77a6163acefa9f28756b57b9
lsevero/clj-xlsxio
read_test.clj
(ns clj-xlsxio.read-test (:require [clj-xlsxio.read :as sut] [clojure.test :refer [deftest is testing]] [clojure.java.io :as io] [clojure.string :as st])) (deftest read-xlsx (testing "basic reading from string filename" (let [res (sut/read-xlsx "examples/test.xlsx")] (is (= (first res) ["column1" "column2" "column3"])) (is (= (last res) ["43766" "" "←"])))) (testing "basic reading convert to enumerated maps by column number." (is (= (-> "examples/test.xlsx" sut/read-xlsx sut/xlsx->enumerated-maps) (list {0 "column1", 1 "column2", 2 "column3"} {0 "34262", 1 "", 2 "3"} {0 "", 1 "b", 2 "c"} {0 "", 1 "", 2 ""} {0 "z", 1 "x", 2 "c"} {0 "", 1 "", 2 ""} {0 "43766", 1 "", 2 "←"})))) (testing "convert to enumerated maps using excel column name as keys" (is (= (-> "examples/test.xlsx" sut/read-xlsx sut/xlsx->excel-enumerated-maps) (list {:A "column1", :B "column2", :C "column3"} {:A "34262", :B "", :C "3"} {:A "", :B "b", :C "c"} {:A "", :B "", :C ""} {:A "z", :B "x", :C "c"} {:A "", :B "", :C ""} {:A "43766", :B "", :C "←"})))) (testing "convert to maps using the content of first rows as keys" (is (= (-> "examples/test.xlsx" sut/read-xlsx sut/xlsx->column-title-maps) (list {:column1 "34262", :column2 "", :column3 "3"} {:column1 "", :column2 "b", :column3 "c"} {:column1 "", :column2 "", :column3 ""} {:column1 "z", :column2 "x", :column3 "c"} {:column1 "", :column2 "", :column3 ""} {:column1 "43766", :column2 "", :column3 "←"})))) (testing "pass a function to modify the formating of the column names" (is (= (-> "examples/test.xlsx" sut/read-xlsx (sut/xlsx->column-title-maps :column-fn st/upper-case)) (list {:COLUMN1 "34262", :COLUMN2 "", :COLUMN3 "3"} {:COLUMN1 "", :COLUMN2 "b", :COLUMN3 "c"} {:COLUMN1 "", :COLUMN2 "", :COLUMN3 ""} {:COLUMN1 "z", :COLUMN2 "x", :COLUMN3 "c"} {:COLUMN1 "", :COLUMN2 "", :COLUMN3 ""} {:COLUMN1 "43766", :COLUMN2 "", :COLUMN3 "←"})))) (testing "enable the keys of the maps to be strings." (is (= (-> "examples/test.xlsx" sut/read-xlsx (sut/xlsx->column-title-maps :str-keys true)) (list {"column1" "34262", "column2" "", "column3" "3"} {"column1" "", "column2" "b", "column3" "c"} {"column1" "", "column2" "", "column3" ""} {"column1" "z", "column2" "x", "column3" "c"} {"column1" "", "column2" "", "column3" ""} {"column1" "43766", "column2" "", "column3" "←"})))) (testing "also possible to compose both previous two options and modify the string keys in the maps" (is (= (-> "examples/test.xlsx" sut/read-xlsx (sut/xlsx->column-title-maps :str-keys true :column-fn st/upper-case)) (list {"COLUMN1" "34262", "COLUMN2" "", "COLUMN3" "3"} {"COLUMN1" "", "COLUMN2" "b", "COLUMN3" "c"} {"COLUMN1" "", "COLUMN2" "", "COLUMN3" ""} {"COLUMN1" "z", "COLUMN2" "x", "COLUMN3" "c"} {"COLUMN1" "", "COLUMN2" "", "COLUMN3" ""} {"COLUMN1" "43766", "COLUMN2" "", "COLUMN3" "←"})))) (testing "basic reading from java.io.File" (let [res (sut/read-xlsx (io/file "examples/test.xlsx"))] (is (= res (list ["column1" "column2" "column3"] ["34262" "" "3"] ["" "b" "c"] ["" "" ""] ["z" "x" "c"] ["" "" ""] ["43766" "" "←"]))))) (testing "basic reading from java.io.BufferedInputStream" (let [res (sut/read-xlsx (io/input-stream "examples/test.xlsx"))] (is (= res (list ["column1" "column2" "column3"] ["34262" "" "3"] ["" "b" "c"] ["" "" ""] ["z" "x" "c"] ["" "" ""] ["43766" "" "←"])))))) (deftest read-xlsx-coerce (testing "coerce values by passing generic functions to be executed in each cell." (let [res (-> "examples/coerce_test.xlsx" sut/read-xlsx (sut/coerce [(comp inc #(Long/parseLong %)) st/upper-case sut/excel-date->java-date])) test-collumn-pred (fn [col pred] (apply (every-pred pred) (map #(nth % col) res)))] (is (test-collumn-pred 0 #(instance? Long %))) (is (test-collumn-pred 1 #(every? (fn [^Character x] (Character/isUpperCase x)) %))) (is (test-collumn-pred 2 #(instance? java.util.Date %)))))) (deftest list-sheets (testing "list sheets inside the xlsx" (is (= (sut/list-sheets "examples/test.xlsx") ["Sheet1"]))) (testing "list sheets reading from java.io.File" (is (= (sut/list-sheets (io/file "examples/test.xlsx")) ["Sheet1"]))) (testing "list sheets reading from java.io.BufferedInputStream" (is (= (sut/list-sheets (io/input-stream "examples/test.xlsx")) ["Sheet1"]))))
null
https://raw.githubusercontent.com/lsevero/clj-xlsxio/5609b04258db74ea5ef673fb9fdca64400fc3495/test/clj_xlsxio/read_test.clj
clojure
(ns clj-xlsxio.read-test (:require [clj-xlsxio.read :as sut] [clojure.test :refer [deftest is testing]] [clojure.java.io :as io] [clojure.string :as st])) (deftest read-xlsx (testing "basic reading from string filename" (let [res (sut/read-xlsx "examples/test.xlsx")] (is (= (first res) ["column1" "column2" "column3"])) (is (= (last res) ["43766" "" "←"])))) (testing "basic reading convert to enumerated maps by column number." (is (= (-> "examples/test.xlsx" sut/read-xlsx sut/xlsx->enumerated-maps) (list {0 "column1", 1 "column2", 2 "column3"} {0 "34262", 1 "", 2 "3"} {0 "", 1 "b", 2 "c"} {0 "", 1 "", 2 ""} {0 "z", 1 "x", 2 "c"} {0 "", 1 "", 2 ""} {0 "43766", 1 "", 2 "←"})))) (testing "convert to enumerated maps using excel column name as keys" (is (= (-> "examples/test.xlsx" sut/read-xlsx sut/xlsx->excel-enumerated-maps) (list {:A "column1", :B "column2", :C "column3"} {:A "34262", :B "", :C "3"} {:A "", :B "b", :C "c"} {:A "", :B "", :C ""} {:A "z", :B "x", :C "c"} {:A "", :B "", :C ""} {:A "43766", :B "", :C "←"})))) (testing "convert to maps using the content of first rows as keys" (is (= (-> "examples/test.xlsx" sut/read-xlsx sut/xlsx->column-title-maps) (list {:column1 "34262", :column2 "", :column3 "3"} {:column1 "", :column2 "b", :column3 "c"} {:column1 "", :column2 "", :column3 ""} {:column1 "z", :column2 "x", :column3 "c"} {:column1 "", :column2 "", :column3 ""} {:column1 "43766", :column2 "", :column3 "←"})))) (testing "pass a function to modify the formating of the column names" (is (= (-> "examples/test.xlsx" sut/read-xlsx (sut/xlsx->column-title-maps :column-fn st/upper-case)) (list {:COLUMN1 "34262", :COLUMN2 "", :COLUMN3 "3"} {:COLUMN1 "", :COLUMN2 "b", :COLUMN3 "c"} {:COLUMN1 "", :COLUMN2 "", :COLUMN3 ""} {:COLUMN1 "z", :COLUMN2 "x", :COLUMN3 "c"} {:COLUMN1 "", :COLUMN2 "", :COLUMN3 ""} {:COLUMN1 "43766", :COLUMN2 "", :COLUMN3 "←"})))) (testing "enable the keys of the maps to be strings." (is (= (-> "examples/test.xlsx" sut/read-xlsx (sut/xlsx->column-title-maps :str-keys true)) (list {"column1" "34262", "column2" "", "column3" "3"} {"column1" "", "column2" "b", "column3" "c"} {"column1" "", "column2" "", "column3" ""} {"column1" "z", "column2" "x", "column3" "c"} {"column1" "", "column2" "", "column3" ""} {"column1" "43766", "column2" "", "column3" "←"})))) (testing "also possible to compose both previous two options and modify the string keys in the maps" (is (= (-> "examples/test.xlsx" sut/read-xlsx (sut/xlsx->column-title-maps :str-keys true :column-fn st/upper-case)) (list {"COLUMN1" "34262", "COLUMN2" "", "COLUMN3" "3"} {"COLUMN1" "", "COLUMN2" "b", "COLUMN3" "c"} {"COLUMN1" "", "COLUMN2" "", "COLUMN3" ""} {"COLUMN1" "z", "COLUMN2" "x", "COLUMN3" "c"} {"COLUMN1" "", "COLUMN2" "", "COLUMN3" ""} {"COLUMN1" "43766", "COLUMN2" "", "COLUMN3" "←"})))) (testing "basic reading from java.io.File" (let [res (sut/read-xlsx (io/file "examples/test.xlsx"))] (is (= res (list ["column1" "column2" "column3"] ["34262" "" "3"] ["" "b" "c"] ["" "" ""] ["z" "x" "c"] ["" "" ""] ["43766" "" "←"]))))) (testing "basic reading from java.io.BufferedInputStream" (let [res (sut/read-xlsx (io/input-stream "examples/test.xlsx"))] (is (= res (list ["column1" "column2" "column3"] ["34262" "" "3"] ["" "b" "c"] ["" "" ""] ["z" "x" "c"] ["" "" ""] ["43766" "" "←"])))))) (deftest read-xlsx-coerce (testing "coerce values by passing generic functions to be executed in each cell." (let [res (-> "examples/coerce_test.xlsx" sut/read-xlsx (sut/coerce [(comp inc #(Long/parseLong %)) st/upper-case sut/excel-date->java-date])) test-collumn-pred (fn [col pred] (apply (every-pred pred) (map #(nth % col) res)))] (is (test-collumn-pred 0 #(instance? Long %))) (is (test-collumn-pred 1 #(every? (fn [^Character x] (Character/isUpperCase x)) %))) (is (test-collumn-pred 2 #(instance? java.util.Date %)))))) (deftest list-sheets (testing "list sheets inside the xlsx" (is (= (sut/list-sheets "examples/test.xlsx") ["Sheet1"]))) (testing "list sheets reading from java.io.File" (is (= (sut/list-sheets (io/file "examples/test.xlsx")) ["Sheet1"]))) (testing "list sheets reading from java.io.BufferedInputStream" (is (= (sut/list-sheets (io/input-stream "examples/test.xlsx")) ["Sheet1"]))))
7ee9f4b1296892a766530b1a21960e4997a3102eccbdcaff5c06ffc631508e3f
spechub/Hets
Conversion.hs
| Module : ./atermlib / src / ATerm / Conversion.hs Description : the class ShATermConvertible and basic instances Copyright : ( c ) , , Uni Bremen 2002 - 2006 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : non - portable(imports ATerm . AbstractSyntax ) the class ' ShATermConvertible ' depending on the class ' ' for converting datatypes to and from ' ShATerm 's in ' ATermTable 's , plus a couple of basic instances and utilities Module : ./atermlib/src/ATerm/Conversion.hs Description : the class ShATermConvertible and basic instances Copyright : (c) Klaus Luettich, C. Maeder, Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : non-portable(imports ATerm.AbstractSyntax) the class 'ShATermConvertible' depending on the class 'Typeable' for converting datatypes to and from 'ShATerm's in 'ATermTable's, plus a couple of basic instances and utilities -} module ATerm.Conversion where import ATerm.AbstractSyntax import qualified Data.Map as Map import qualified Data.IntMap as IntMap import qualified Data.Set as Set import Data.Typeable import Data.List (mapAccumL) import Data.Ratio import Data.Word import Control.Monad class Typeable t => ShATermConvertible t where -- functions for conversion to an ATermTable toShATermAux :: ATermTable -> t -> IO (ATermTable, Int) toShATermList' :: ATermTable -> [t] -> IO (ATermTable, Int) fromShATermAux :: Int -> ATermTable -> (ATermTable, t) fromShATermList' :: Int -> ATermTable -> (ATermTable, [t]) default functions ignore the Annotation part toShATermList' att ts = do (att2, inds) <- foldM (\ (att0, l) t -> do (att1, i) <- toShATerm' att0 t return (att1, i : l)) (att, []) ts return $ addATerm (ShAList (reverse inds) []) att2 fromShATermList' ix att0 = case getShATerm ix att0 of ShAList ats _ -> mapAccumL (flip fromShATerm') att0 ats u -> fromShATermError "[]" u toShATerm' :: ShATermConvertible t => ATermTable -> t -> IO (ATermTable, Int) toShATerm' att t = do k <- mkKey t m <- getKey k att case m of Nothing -> do (att1, i) <- toShATermAux att t setKey k i att1 Just i -> return (att, i) fromShATerm' :: ShATermConvertible t => Int -> ATermTable -> (ATermTable, t) fromShATerm' i att = case getATerm' i att of Just d -> (att, d) _ -> case fromShATermAux i att of (attN, t) -> (setATerm' i t attN, t) fromShATermError :: String -> ShATerm -> a fromShATermError t u = error $ "Cannot convert ShATerm to " ++ t ++ ": !" ++ show u -- some instances ----------------------------------------------- instance ShATermConvertible Bool where toShATermAux att b = return $ addATerm (ShAAppl (if b then "T" else "F") [] []) att fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "T" [] _ -> (att0, True) ShAAppl "F" [] _ -> (att0, False) u -> fromShATermError "Prelude.Bool" u instance ShATermConvertible Integer where toShATermAux att x = return $ addATerm (ShAInt x []) att fromShATermAux ix att0 = case getShATerm ix att0 of ShAInt x _ -> (att0, x) u -> fromShATermError "Prelude.Integer" u instance ShATermConvertible Int where toShATermAux att = toShATermAux att . toInteger fromShATermAux ix att0 = case getShATerm ix att0 of ShAInt x _ -> (att0, integer2Int x) u -> fromShATermError "Prelude.Int" u instance ShATermConvertible Word8 where toShATermAux att = toShATermAux att . toInteger fromShATermAux ix att0 = case getShATerm ix att0 of ShAInt x _ | x <= toInteger (maxBound :: Word8) && x >= toInteger (minBound :: Word8) -> (att0, fromIntegral x) u -> fromShATermError "Data.Word8" u instance (ShATermConvertible a, Integral a) => ShATermConvertible (Ratio a) where toShATermAux att0 i = do (att1, i1') <- toShATerm' att0 $ numerator i (att2, i2') <- toShATerm' att1 $ denominator i return $ addATerm (ShAAppl "Ratio" [i1', i2'] []) att2 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Ratio" [a, b] _ -> case fromShATerm' a att0 of { (att1, a') -> case fromShATerm' b att1 of { (att2, b') -> (att2, a' % b') }} u -> fromShATermError "Prelude.Integral" u instance ShATermConvertible Float where toShATermAux att = toShATermAux att . toRational fromShATermAux ix att0 = case fromShATermAux ix att0 of (att, r) -> (att, fromRational r) instance ShATermConvertible Char where toShATermAux att c = return $ addATerm (ShAAppl (show [c]) [] []) att fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl s [] _ -> (att0, str2Char s) u -> fromShATermError "Prelude.Char" u toShATermList' att s = return $ addATerm (ShAAppl (show s) [] []) att fromShATermList' ix att0 = case getShATerm ix att0 of ShAAppl s [] _ -> (att0, read s) u -> fromShATermError "Prelude.String" u instance ShATermConvertible () where toShATermAux att _ = return $ addATerm (ShAAppl "U" [] []) att fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "U" [] _ -> (att0, ()) u -> fromShATermError "()" u instance (ShATermConvertible a) => ShATermConvertible (Maybe a) where toShATermAux att mb = case mb of Nothing -> return $ addATerm (ShAAppl "N" [] []) att Just x -> do (att1, x') <- toShATerm' att x return $ addATerm (ShAAppl "J" [x'] []) att1 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "N" [] _ -> (att0, Nothing) ShAAppl "J" [a] _ -> case fromShATerm' a att0 of { (att1, a') -> (att1, Just a') } u -> fromShATermError "Prelude.Maybe" u instance (ShATermConvertible a, ShATermConvertible b) => ShATermConvertible (Either a b) where toShATermAux att0 (Left aa) = do (att1, aa') <- toShATerm' att0 aa return $ addATerm (ShAAppl "Left" [ aa' ] []) att1 toShATermAux att0 (Right aa) = do (att1, aa') <- toShATerm' att0 aa return $ addATerm (ShAAppl "Right" [ aa' ] []) att1 fromShATermAux ix att = case getShATerm ix att of ShAAppl "Left" [ aa ] _ -> case fromShATerm' aa att of { (att2, aa') -> (att2, Left aa') } ShAAppl "Right" [ aa ] _ -> case fromShATerm' aa att of { (att2, aa') -> (att2, Right aa') } u -> fromShATermError "Either" u instance ShATermConvertible a => ShATermConvertible [a] where toShATermAux = toShATermList' fromShATermAux = fromShATermList' instance (ShATermConvertible a, ShATermConvertible b) => ShATermConvertible (a, b) where toShATermAux att0 (x, y) = do (att1, x') <- toShATerm' att0 x (att2, y') <- toShATerm' att1 y return $ addATerm (ShAAppl "" [x', y'] []) att2 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "" [a, b] _ -> case fromShATerm' a att0 of { (att1, a') -> case fromShATerm' b att1 of { (att2, b') -> (att2, (a', b'))}} u -> fromShATermError "(,)" u instance (ShATermConvertible a, ShATermConvertible b, ShATermConvertible c) => ShATermConvertible (a, b, c) where toShATermAux att0 (x, y, z) = do (att1, x') <- toShATerm' att0 x (att2, y') <- toShATerm' att1 y (att3, z') <- toShATerm' att2 z return $ addATerm (ShAAppl "" [x', y', z'] []) att3 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "" [a, b, c] _ -> case fromShATerm' a att0 of { (att1, a') -> case fromShATerm' b att1 of { (att2, b') -> case fromShATerm' c att2 of { (att3, c') -> (att3, (a', b', c'))}}} u -> fromShATermError "(,,)" u instance (ShATermConvertible a, ShATermConvertible b, ShATermConvertible c, ShATermConvertible d) => ShATermConvertible (a, b, c, d) where toShATermAux att0 (x, y, z, w) = do (att1, x') <- toShATerm' att0 x (att2, y') <- toShATerm' att1 y (att3, z') <- toShATerm' att2 z (att4, w') <- toShATerm' att3 w return $ addATerm (ShAAppl "" [x', y', z', w'] []) att4 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "" [a, b, c, d] _ -> case fromShATerm' a att0 of { (att1, a') -> case fromShATerm' b att1 of { (att2, b') -> case fromShATerm' c att2 of { (att3, c') -> case fromShATerm' d att3 of { (att4, d') -> (att4, (a', b', c', d'))}}}} u -> fromShATermError "(,,,)" u instance (ShATermConvertible a, ShATermConvertible b) => ShATermConvertible (Map.Map a b) where toShATermAux att fm = do (att1, i) <- toShATerm' att $ Map.toList fm return $ addATerm (ShAAppl "Map" [i] []) att1 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Map" [a] _ -> case fromShATerm' a att0 of { (att1, a') -> (att1, Map.fromDistinctAscList a') } u -> fromShATermError "Map.Map" u instance ShATermConvertible a => ShATermConvertible (IntMap.IntMap a) where toShATermAux att fm = do (att1, i) <- toShATerm' att $ IntMap.toList fm return $ addATerm (ShAAppl "IntMap" [i] []) att1 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "IntMap" [a] _ -> case fromShATerm' a att0 of { (att1, a') -> (att1, IntMap.fromDistinctAscList a') } u -> fromShATermError "IntMap.IntMap" u instance ShATermConvertible a => ShATermConvertible (Set.Set a) where toShATermAux att set = do (att1, i) <- toShATerm' att $ Set.toList set return $ addATerm (ShAAppl "Set" [i] []) att1 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Set" [a] _ -> case fromShATerm' a att0 of { (att1, a') -> (att1, Set.fromDistinctAscList a') } u -> fromShATermError "Set.Set" u
null
https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/atermlib/src/ATerm/Conversion.hs
haskell
functions for conversion to an ATermTable some instances -----------------------------------------------
| Module : ./atermlib / src / ATerm / Conversion.hs Description : the class ShATermConvertible and basic instances Copyright : ( c ) , , Uni Bremen 2002 - 2006 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : non - portable(imports ATerm . AbstractSyntax ) the class ' ShATermConvertible ' depending on the class ' ' for converting datatypes to and from ' ShATerm 's in ' ATermTable 's , plus a couple of basic instances and utilities Module : ./atermlib/src/ATerm/Conversion.hs Description : the class ShATermConvertible and basic instances Copyright : (c) Klaus Luettich, C. Maeder, Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : non-portable(imports ATerm.AbstractSyntax) the class 'ShATermConvertible' depending on the class 'Typeable' for converting datatypes to and from 'ShATerm's in 'ATermTable's, plus a couple of basic instances and utilities -} module ATerm.Conversion where import ATerm.AbstractSyntax import qualified Data.Map as Map import qualified Data.IntMap as IntMap import qualified Data.Set as Set import Data.Typeable import Data.List (mapAccumL) import Data.Ratio import Data.Word import Control.Monad class Typeable t => ShATermConvertible t where toShATermAux :: ATermTable -> t -> IO (ATermTable, Int) toShATermList' :: ATermTable -> [t] -> IO (ATermTable, Int) fromShATermAux :: Int -> ATermTable -> (ATermTable, t) fromShATermList' :: Int -> ATermTable -> (ATermTable, [t]) default functions ignore the Annotation part toShATermList' att ts = do (att2, inds) <- foldM (\ (att0, l) t -> do (att1, i) <- toShATerm' att0 t return (att1, i : l)) (att, []) ts return $ addATerm (ShAList (reverse inds) []) att2 fromShATermList' ix att0 = case getShATerm ix att0 of ShAList ats _ -> mapAccumL (flip fromShATerm') att0 ats u -> fromShATermError "[]" u toShATerm' :: ShATermConvertible t => ATermTable -> t -> IO (ATermTable, Int) toShATerm' att t = do k <- mkKey t m <- getKey k att case m of Nothing -> do (att1, i) <- toShATermAux att t setKey k i att1 Just i -> return (att, i) fromShATerm' :: ShATermConvertible t => Int -> ATermTable -> (ATermTable, t) fromShATerm' i att = case getATerm' i att of Just d -> (att, d) _ -> case fromShATermAux i att of (attN, t) -> (setATerm' i t attN, t) fromShATermError :: String -> ShATerm -> a fromShATermError t u = error $ "Cannot convert ShATerm to " ++ t ++ ": !" ++ show u instance ShATermConvertible Bool where toShATermAux att b = return $ addATerm (ShAAppl (if b then "T" else "F") [] []) att fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "T" [] _ -> (att0, True) ShAAppl "F" [] _ -> (att0, False) u -> fromShATermError "Prelude.Bool" u instance ShATermConvertible Integer where toShATermAux att x = return $ addATerm (ShAInt x []) att fromShATermAux ix att0 = case getShATerm ix att0 of ShAInt x _ -> (att0, x) u -> fromShATermError "Prelude.Integer" u instance ShATermConvertible Int where toShATermAux att = toShATermAux att . toInteger fromShATermAux ix att0 = case getShATerm ix att0 of ShAInt x _ -> (att0, integer2Int x) u -> fromShATermError "Prelude.Int" u instance ShATermConvertible Word8 where toShATermAux att = toShATermAux att . toInteger fromShATermAux ix att0 = case getShATerm ix att0 of ShAInt x _ | x <= toInteger (maxBound :: Word8) && x >= toInteger (minBound :: Word8) -> (att0, fromIntegral x) u -> fromShATermError "Data.Word8" u instance (ShATermConvertible a, Integral a) => ShATermConvertible (Ratio a) where toShATermAux att0 i = do (att1, i1') <- toShATerm' att0 $ numerator i (att2, i2') <- toShATerm' att1 $ denominator i return $ addATerm (ShAAppl "Ratio" [i1', i2'] []) att2 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Ratio" [a, b] _ -> case fromShATerm' a att0 of { (att1, a') -> case fromShATerm' b att1 of { (att2, b') -> (att2, a' % b') }} u -> fromShATermError "Prelude.Integral" u instance ShATermConvertible Float where toShATermAux att = toShATermAux att . toRational fromShATermAux ix att0 = case fromShATermAux ix att0 of (att, r) -> (att, fromRational r) instance ShATermConvertible Char where toShATermAux att c = return $ addATerm (ShAAppl (show [c]) [] []) att fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl s [] _ -> (att0, str2Char s) u -> fromShATermError "Prelude.Char" u toShATermList' att s = return $ addATerm (ShAAppl (show s) [] []) att fromShATermList' ix att0 = case getShATerm ix att0 of ShAAppl s [] _ -> (att0, read s) u -> fromShATermError "Prelude.String" u instance ShATermConvertible () where toShATermAux att _ = return $ addATerm (ShAAppl "U" [] []) att fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "U" [] _ -> (att0, ()) u -> fromShATermError "()" u instance (ShATermConvertible a) => ShATermConvertible (Maybe a) where toShATermAux att mb = case mb of Nothing -> return $ addATerm (ShAAppl "N" [] []) att Just x -> do (att1, x') <- toShATerm' att x return $ addATerm (ShAAppl "J" [x'] []) att1 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "N" [] _ -> (att0, Nothing) ShAAppl "J" [a] _ -> case fromShATerm' a att0 of { (att1, a') -> (att1, Just a') } u -> fromShATermError "Prelude.Maybe" u instance (ShATermConvertible a, ShATermConvertible b) => ShATermConvertible (Either a b) where toShATermAux att0 (Left aa) = do (att1, aa') <- toShATerm' att0 aa return $ addATerm (ShAAppl "Left" [ aa' ] []) att1 toShATermAux att0 (Right aa) = do (att1, aa') <- toShATerm' att0 aa return $ addATerm (ShAAppl "Right" [ aa' ] []) att1 fromShATermAux ix att = case getShATerm ix att of ShAAppl "Left" [ aa ] _ -> case fromShATerm' aa att of { (att2, aa') -> (att2, Left aa') } ShAAppl "Right" [ aa ] _ -> case fromShATerm' aa att of { (att2, aa') -> (att2, Right aa') } u -> fromShATermError "Either" u instance ShATermConvertible a => ShATermConvertible [a] where toShATermAux = toShATermList' fromShATermAux = fromShATermList' instance (ShATermConvertible a, ShATermConvertible b) => ShATermConvertible (a, b) where toShATermAux att0 (x, y) = do (att1, x') <- toShATerm' att0 x (att2, y') <- toShATerm' att1 y return $ addATerm (ShAAppl "" [x', y'] []) att2 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "" [a, b] _ -> case fromShATerm' a att0 of { (att1, a') -> case fromShATerm' b att1 of { (att2, b') -> (att2, (a', b'))}} u -> fromShATermError "(,)" u instance (ShATermConvertible a, ShATermConvertible b, ShATermConvertible c) => ShATermConvertible (a, b, c) where toShATermAux att0 (x, y, z) = do (att1, x') <- toShATerm' att0 x (att2, y') <- toShATerm' att1 y (att3, z') <- toShATerm' att2 z return $ addATerm (ShAAppl "" [x', y', z'] []) att3 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "" [a, b, c] _ -> case fromShATerm' a att0 of { (att1, a') -> case fromShATerm' b att1 of { (att2, b') -> case fromShATerm' c att2 of { (att3, c') -> (att3, (a', b', c'))}}} u -> fromShATermError "(,,)" u instance (ShATermConvertible a, ShATermConvertible b, ShATermConvertible c, ShATermConvertible d) => ShATermConvertible (a, b, c, d) where toShATermAux att0 (x, y, z, w) = do (att1, x') <- toShATerm' att0 x (att2, y') <- toShATerm' att1 y (att3, z') <- toShATerm' att2 z (att4, w') <- toShATerm' att3 w return $ addATerm (ShAAppl "" [x', y', z', w'] []) att4 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "" [a, b, c, d] _ -> case fromShATerm' a att0 of { (att1, a') -> case fromShATerm' b att1 of { (att2, b') -> case fromShATerm' c att2 of { (att3, c') -> case fromShATerm' d att3 of { (att4, d') -> (att4, (a', b', c', d'))}}}} u -> fromShATermError "(,,,)" u instance (ShATermConvertible a, ShATermConvertible b) => ShATermConvertible (Map.Map a b) where toShATermAux att fm = do (att1, i) <- toShATerm' att $ Map.toList fm return $ addATerm (ShAAppl "Map" [i] []) att1 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Map" [a] _ -> case fromShATerm' a att0 of { (att1, a') -> (att1, Map.fromDistinctAscList a') } u -> fromShATermError "Map.Map" u instance ShATermConvertible a => ShATermConvertible (IntMap.IntMap a) where toShATermAux att fm = do (att1, i) <- toShATerm' att $ IntMap.toList fm return $ addATerm (ShAAppl "IntMap" [i] []) att1 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "IntMap" [a] _ -> case fromShATerm' a att0 of { (att1, a') -> (att1, IntMap.fromDistinctAscList a') } u -> fromShATermError "IntMap.IntMap" u instance ShATermConvertible a => ShATermConvertible (Set.Set a) where toShATermAux att set = do (att1, i) <- toShATerm' att $ Set.toList set return $ addATerm (ShAAppl "Set" [i] []) att1 fromShATermAux ix att0 = case getShATerm ix att0 of ShAAppl "Set" [a] _ -> case fromShATerm' a att0 of { (att1, a') -> (att1, Set.fromDistinctAscList a') } u -> fromShATermError "Set.Set" u
a62774c350c1e0ce702df1a92538f6694c52c19c5d7e6c1dbaba6517a0652371
padsproj/pads-haskell
DFAC.hs
# LANGUAGE TypeFamilies , ScopedTypeVariables , DeriveDataTypeable , MultiParamTypeClasses , TypeSynonymInstances , TemplateHaskell , QuasiQuotes , FlexibleInstances , FlexibleContexts , RecordWildCards , NamedFieldPuns , OverloadedStrings # , ScopedTypeVariables , DeriveDataTypeable , MultiParamTypeClasses , TypeSynonymInstances , TemplateHaskell , QuasiQuotes , FlexibleInstances , FlexibleContexts , RecordWildCards , NamedFieldPuns , OverloadedStrings #-} module DFAC where import Language.Pads.Padsc import Language.Pads.Testing import Data.Word [pads| constrained dfa -- accepts all caaats with each character followed by a consistent number: c1a1t1 or c5a5a5a5t5 but not c1a2t2 START -- _ -- > S1 -- S1 -- c --> S2 -- S2 -- a --> S3 -- S3 -- a --> S3 -- S3 -- t --> ACCEPT data AA = AA {'a','a','a'} data START = START {start::S1} -- s1 -- c --> s2 data S1 = S1 { 'c', c1 :: Char, s2 :: S2 c1 } -- s2 -- a --> s3 data S2 (n::Char) = S2 { 'a', constrain c2 :: Char where <| n == c2 |>, s3 :: S3 c2 } -- s3 -- a --> s3 -- s3 -- t --> s4 data S3 (n::Char) = S3A { 'a', constrain c3a :: Char where <| n == c3a |>, s3a :: S3 c3a } | S3T { 't', constrain c3t :: Char where <| n == c3t |>, ss4 :: S4 c3t} data S4 (n::Char) = S4 {s4::ACCEPT} data ACCEPT = ACCEPT () |] testdfa parser str = let ((x, (y, z)), s) = parser str bad = numErrors y + length s in case bad of 0 -> "DFA accepts " ++ str ++ "" n -> "DFA rejects " ++ str ++ " with " ++ (show n) ++ " errors." sTART_parseS " c1a1t1 " sTART_parseS " c1a1t2 " sTART_parseS " c1a1a1a1a1a1a1a1t2 " sTART_parseS " c1a1a1a1a1a1a1a1t1 "
null
https://raw.githubusercontent.com/padsproj/pads-haskell/8dce6b2b28bf7d98028e67f6faa2be753a6ad691/examples/DFAC.hs
haskell
accepts all caaats with each character followed by a consistent number: _ -- > S1 S1 -- c --> S2 S2 -- a --> S3 S3 -- a --> S3 S3 -- t --> ACCEPT s1 -- c --> s2 s2 -- a --> s3 s3 -- a --> s3 s3 -- t --> s4
# LANGUAGE TypeFamilies , ScopedTypeVariables , DeriveDataTypeable , MultiParamTypeClasses , TypeSynonymInstances , TemplateHaskell , QuasiQuotes , FlexibleInstances , FlexibleContexts , RecordWildCards , NamedFieldPuns , OverloadedStrings # , ScopedTypeVariables , DeriveDataTypeable , MultiParamTypeClasses , TypeSynonymInstances , TemplateHaskell , QuasiQuotes , FlexibleInstances , FlexibleContexts , RecordWildCards , NamedFieldPuns , OverloadedStrings #-} module DFAC where import Language.Pads.Padsc import Language.Pads.Testing import Data.Word [pads| constrained dfa c1a1t1 or c5a5a5a5t5 but not c1a2t2 data AA = AA {'a','a','a'} data START = START {start::S1} data S1 = S1 { 'c', c1 :: Char, s2 :: S2 c1 } data S2 (n::Char) = S2 { 'a', constrain c2 :: Char where <| n == c2 |>, s3 :: S3 c2 } data S3 (n::Char) = S3A { 'a', constrain c3a :: Char where <| n == c3a |>, s3a :: S3 c3a } | S3T { 't', constrain c3t :: Char where <| n == c3t |>, ss4 :: S4 c3t} data S4 (n::Char) = S4 {s4::ACCEPT} data ACCEPT = ACCEPT () |] testdfa parser str = let ((x, (y, z)), s) = parser str bad = numErrors y + length s in case bad of 0 -> "DFA accepts " ++ str ++ "" n -> "DFA rejects " ++ str ++ " with " ++ (show n) ++ " errors." sTART_parseS " c1a1t1 " sTART_parseS " c1a1t2 " sTART_parseS " c1a1a1a1a1a1a1a1t2 " sTART_parseS " c1a1a1a1a1a1a1a1t1 "
ac254c82e9ff31fbd3aef9d50a5e98044948d61ce943756885cdeb9d7cd0a317
hyperfiddle/electric
subs2.cljc
(ns dustin.rosie.subs2 (:require [clojure.spec.alpha :as s] [datascript.core :as d] [hyperfiddle.api :as hf :refer [hfql]] [hfdl.lang :as p] [hyperfiddle.photon-dom :as dom] [hyperfiddle.rcf :as rcf :refer [tests tap %]] [missionary.core :as m] )) (p/defn suber-name [e] ) (p/defn sub-tags [e] #?(:clj (->> (:sub/tags (d/entity hf/*$* e)) (remove #(re-find filter-out-tags-regexp (or (namespace %) ""))) vec))) (p/defn sub-locations [e] #?(:clj (->> (:sub/tags (d/entity hf/*$* e)) (filter #(= (namespace %) "location")) vec))) (s/fdef all-tags :args (s/cat :needle string?)) (p/defn all-tags [needle] #?(:clj (->> (d/q '[:find [?tag ...] :in $ ?needle :where [_ :sub/tags ?tag] [(swinged.rosie.subs/ns-different "geocode" ?tag)] [(swinged.rosie.subs/ns-different "location" ?tag)] [(rosie.rosie-common-util/needle-match ?tag ?needle)]] hf/*$* (str/trim (or needle ""))) (sort-by (juxt namespace name)) (vec)))) (s/fdef all-locations :args (s/cat :sub any? :needle string?)) (p/defn all-locations [needle] #?(:clj (into [] (comp (take hf/browser-query-limit) (map #(nth % 2))) (rosie.rosie-sub/list-locations2 needle)))) (p/defn sub-display [e] e) (s/fdef sub-display :args (s/cat ::sub (s/and some? ref?)) :ret (s/keys)) (s/fdef school-picklist :args (s/cat :_ any? :needle string?)) (p/defn school-picklist [needle] #?(:clj (into [] (take hf/browser-query-limit) (d/q '[:in $ ?needle :find [(pull ?e [:school/name :school/id]) ...] :where [?e :school/id] [?e :school/name ?name] [(rosie.rosie-common-util/needle-match ?name ?needle)]] hf/*$* needle)))) (s/fdef event-reason-codes-picklist :args (s/cat :needle string?)) (p/defn event-reason-codes-picklist [needle] #?(:clj (doall (take hf/browser-query-limit (event-codes needle))))) (p/defn unlink-mode-options [] [:force-cancel :leave-commitments]) (s/fdef school-requested-block :args (s/cat :sub (s/and some? ref?) ::school (s/and some? ref?) ::block-reason (s/and some? ref?) ::block-mode (s/and some? keyword?) ::penalize? boolean?)) (p/defn school-requested-block [sub school block-reason mode penalize] nil) (p/defn render-school-requested-block [sub school block-reason mode penalize] (dom/fragment (dom/h1 "Block sub from school") (dom/p "School has requested that the given sub be blocked from their school. This will always unlink the sub."))) (def sub-display (hf/router {(sub-display {?sub [suber-name]}) [(suber-name ?sub) :sub/id :db/id '(sub-requests ?sub) ('(school-requested-block {?sub [:sub/id]} {(?school ::hf/render picklist ::hf/options (school-picklist ?needle) ::hf/option-label :school/name) [:school/id :school/name]} {(?block-reason ::hf/render picklist ::hf/options (event-reason-codes-picklist ?needle) ::hf/option-label (comp name :db/ident)) [:db/ident]} (?block-mode ::hf/render checkbox-picker ::hf/default (or ?block-mode :force-cancel) ::hf/options (unlink-mode-options) ::hf/option-label (let [wide {:style {:display "inline-block" :width "12em"}}] {:force-cancel (dom/span (dom/span wide ":force-cancel") "Cancel all the sub's existing commitment at this school") :leave-commitments (dom/span (dom/span wide ":leave-commitments") "Don’t cancel sub's existing commitments")})) (?penalize ::hf/default (if (some? ?penalize) ?penalize false))) ::hf/prompt render-school-requested-block ::hf/tx [(suber2.web.cmd/school-requested-block' ?school ?sub ?block-mode ?block-reason ?penalize)]) ((sub-tags ?sub) ::hf/options (all-tags (?needle ::hf/default (or ?needle "")))) ((sub-locations ?sub) ::hf/options (all-locations (?needle ::hf/default (or ?needle "")))) {(:school/_subs ::hf/render ... ::hf/options (sub-schools-picker-options ?needle)) [:school/id :school/name]}]}))
null
https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2022/hfql/subs2.cljc
clojure
(ns dustin.rosie.subs2 (:require [clojure.spec.alpha :as s] [datascript.core :as d] [hyperfiddle.api :as hf :refer [hfql]] [hfdl.lang :as p] [hyperfiddle.photon-dom :as dom] [hyperfiddle.rcf :as rcf :refer [tests tap %]] [missionary.core :as m] )) (p/defn suber-name [e] ) (p/defn sub-tags [e] #?(:clj (->> (:sub/tags (d/entity hf/*$* e)) (remove #(re-find filter-out-tags-regexp (or (namespace %) ""))) vec))) (p/defn sub-locations [e] #?(:clj (->> (:sub/tags (d/entity hf/*$* e)) (filter #(= (namespace %) "location")) vec))) (s/fdef all-tags :args (s/cat :needle string?)) (p/defn all-tags [needle] #?(:clj (->> (d/q '[:find [?tag ...] :in $ ?needle :where [_ :sub/tags ?tag] [(swinged.rosie.subs/ns-different "geocode" ?tag)] [(swinged.rosie.subs/ns-different "location" ?tag)] [(rosie.rosie-common-util/needle-match ?tag ?needle)]] hf/*$* (str/trim (or needle ""))) (sort-by (juxt namespace name)) (vec)))) (s/fdef all-locations :args (s/cat :sub any? :needle string?)) (p/defn all-locations [needle] #?(:clj (into [] (comp (take hf/browser-query-limit) (map #(nth % 2))) (rosie.rosie-sub/list-locations2 needle)))) (p/defn sub-display [e] e) (s/fdef sub-display :args (s/cat ::sub (s/and some? ref?)) :ret (s/keys)) (s/fdef school-picklist :args (s/cat :_ any? :needle string?)) (p/defn school-picklist [needle] #?(:clj (into [] (take hf/browser-query-limit) (d/q '[:in $ ?needle :find [(pull ?e [:school/name :school/id]) ...] :where [?e :school/id] [?e :school/name ?name] [(rosie.rosie-common-util/needle-match ?name ?needle)]] hf/*$* needle)))) (s/fdef event-reason-codes-picklist :args (s/cat :needle string?)) (p/defn event-reason-codes-picklist [needle] #?(:clj (doall (take hf/browser-query-limit (event-codes needle))))) (p/defn unlink-mode-options [] [:force-cancel :leave-commitments]) (s/fdef school-requested-block :args (s/cat :sub (s/and some? ref?) ::school (s/and some? ref?) ::block-reason (s/and some? ref?) ::block-mode (s/and some? keyword?) ::penalize? boolean?)) (p/defn school-requested-block [sub school block-reason mode penalize] nil) (p/defn render-school-requested-block [sub school block-reason mode penalize] (dom/fragment (dom/h1 "Block sub from school") (dom/p "School has requested that the given sub be blocked from their school. This will always unlink the sub."))) (def sub-display (hf/router {(sub-display {?sub [suber-name]}) [(suber-name ?sub) :sub/id :db/id '(sub-requests ?sub) ('(school-requested-block {?sub [:sub/id]} {(?school ::hf/render picklist ::hf/options (school-picklist ?needle) ::hf/option-label :school/name) [:school/id :school/name]} {(?block-reason ::hf/render picklist ::hf/options (event-reason-codes-picklist ?needle) ::hf/option-label (comp name :db/ident)) [:db/ident]} (?block-mode ::hf/render checkbox-picker ::hf/default (or ?block-mode :force-cancel) ::hf/options (unlink-mode-options) ::hf/option-label (let [wide {:style {:display "inline-block" :width "12em"}}] {:force-cancel (dom/span (dom/span wide ":force-cancel") "Cancel all the sub's existing commitment at this school") :leave-commitments (dom/span (dom/span wide ":leave-commitments") "Don’t cancel sub's existing commitments")})) (?penalize ::hf/default (if (some? ?penalize) ?penalize false))) ::hf/prompt render-school-requested-block ::hf/tx [(suber2.web.cmd/school-requested-block' ?school ?sub ?block-mode ?block-reason ?penalize)]) ((sub-tags ?sub) ::hf/options (all-tags (?needle ::hf/default (or ?needle "")))) ((sub-locations ?sub) ::hf/options (all-locations (?needle ::hf/default (or ?needle "")))) {(:school/_subs ::hf/render ... ::hf/options (sub-schools-picker-options ?needle)) [:school/id :school/name]}]}))
afc9b4cea6a5aca6e35d7804b6be98aa9c0d62b4bc814f57abf946e40f0781ca
janestreet/krb
cache_type.mli
open! Core * Types [ API ] and [ MSLSA ] are only supported on Windows . [ KEYRING ] is only supported on Linux Linux *) type t = | API | DIR | FILE | KEYRING | MEMORY | MSLSA [@@deriving compare, enumerate, sexp_of] include Stringable.S with type t := t module Stable : sig module V1 : Stable_without_comparator with type t = t end
null
https://raw.githubusercontent.com/janestreet/krb/1105ba1e8b836f80f09e663bc1b4233cf2607e7b/internal/cache_type.mli
ocaml
open! Core * Types [ API ] and [ MSLSA ] are only supported on Windows . [ KEYRING ] is only supported on Linux Linux *) type t = | API | DIR | FILE | KEYRING | MEMORY | MSLSA [@@deriving compare, enumerate, sexp_of] include Stringable.S with type t := t module Stable : sig module V1 : Stable_without_comparator with type t = t end
066e8a670ea114f166cb14bb6e9f97ef5bfea7c5d56071529bcef10b74d2c855
onyx-platform/onyx-starter
dev_system.clj
(ns onyx-starter.launcher.dev-system (:require [clojure.core.async :refer [chan <!!]] [clojure.java.io :refer [resource]] [com.stuartsierra.component :as component] [onyx.plugin.core-async] [onyx.api])) (defrecord OnyxDevEnv [n-peers] component/Lifecycle (start [component] (println "Starting Onyx development environment") (let [onyx-id (java.util.UUID/randomUUID) env-config (assoc (-> "env-config.edn" resource slurp read-string) :onyx/tenancy-id onyx-id) peer-config (assoc (-> "dev-peer-config.edn" resource slurp read-string) :onyx/tenancy-id onyx-id) env (onyx.api/start-env env-config) peer-group (onyx.api/start-peer-group peer-config) peers (onyx.api/start-peers n-peers peer-group)] (assoc component :env env :peer-group peer-group :peers peers :onyx-id onyx-id))) (stop [component] (println "Stopping Onyx development environment") (doseq [v-peer (:peers component)] (onyx.api/shutdown-peer v-peer)) (onyx.api/shutdown-peer-group (:peer-group component)) (onyx.api/shutdown-env (:env component)) (assoc component :env nil :peer-group nil :peers nil))) (defn onyx-dev-env [n-peers] (map->OnyxDevEnv {:n-peers n-peers}))
null
https://raw.githubusercontent.com/onyx-platform/onyx-starter/d9f0cf5095e7b4089c1e3b708b7691d8184cb36b/src/onyx_starter/launcher/dev_system.clj
clojure
(ns onyx-starter.launcher.dev-system (:require [clojure.core.async :refer [chan <!!]] [clojure.java.io :refer [resource]] [com.stuartsierra.component :as component] [onyx.plugin.core-async] [onyx.api])) (defrecord OnyxDevEnv [n-peers] component/Lifecycle (start [component] (println "Starting Onyx development environment") (let [onyx-id (java.util.UUID/randomUUID) env-config (assoc (-> "env-config.edn" resource slurp read-string) :onyx/tenancy-id onyx-id) peer-config (assoc (-> "dev-peer-config.edn" resource slurp read-string) :onyx/tenancy-id onyx-id) env (onyx.api/start-env env-config) peer-group (onyx.api/start-peer-group peer-config) peers (onyx.api/start-peers n-peers peer-group)] (assoc component :env env :peer-group peer-group :peers peers :onyx-id onyx-id))) (stop [component] (println "Stopping Onyx development environment") (doseq [v-peer (:peers component)] (onyx.api/shutdown-peer v-peer)) (onyx.api/shutdown-peer-group (:peer-group component)) (onyx.api/shutdown-env (:env component)) (assoc component :env nil :peer-group nil :peers nil))) (defn onyx-dev-env [n-peers] (map->OnyxDevEnv {:n-peers n-peers}))
a0893fd9eccc2756620eae5185bbcd1364a91e2455c12e43d2c1d109c3a8153c
2600hz-archive/whistle
gm_soak_test.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License at %% / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the %% License for the specific language governing rights and limitations %% under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is VMware , Inc. Copyright ( c ) 2007 - 2011 VMware , Inc. All rights reserved . %% -module(gm_soak_test). -export([test/0]). -export([joined/2, members_changed/3, handle_msg/3, terminate/2]). -behaviour(gm). -include("gm_specs.hrl"). %% --------------------------------------------------------------------------- %% Soak test %% --------------------------------------------------------------------------- get_state() -> get(state). with_state(Fun) -> put(state, Fun(get_state())). inc() -> case 1 + get(count) of 100000 -> Now = now(), Start = put(ts, Now), Diff = timer:now_diff(Now, Start), Rate = 100000 / (Diff / 1000000), io:format("~p seeing ~p msgs/sec~n", [self(), Rate]), put(count, 0); N -> put(count, N) end. joined([], Members) -> io:format("Joined ~p (~p members)~n", [self(), length(Members)]), put(state, dict:from_list([{Member, empty} || Member <- Members])), put(count, 0), put(ts, now()), ok. members_changed([], Births, Deaths) -> with_state( fun (State) -> State1 = lists:foldl( fun (Born, StateN) -> false = dict:is_key(Born, StateN), dict:store(Born, empty, StateN) end, State, Births), lists:foldl( fun (Died, StateN) -> true = dict:is_key(Died, StateN), dict:store(Died, died, StateN) end, State1, Deaths) end), ok. handle_msg([], From, {test_msg, Num}) -> inc(), with_state( fun (State) -> ok = case dict:find(From, State) of {ok, died} -> exit({{from, From}, {received_posthumous_delivery, Num}}); {ok, empty} -> ok; {ok, Num} -> ok; {ok, Num1} when Num < Num1 -> exit({{from, From}, {duplicate_delivery_of, Num1}, {expecting, Num}}); {ok, Num1} -> exit({{from, From}, {missing_delivery_of, Num}, {received_early, Num1}}); error -> exit({{from, From}, {received_premature_delivery, Num}}) end, dict:store(From, Num + 1, State) end), ok. terminate([], Reason) -> io:format("Left ~p (~p)~n", [self(), Reason]), ok. spawn_member() -> spawn_link( fun () -> {MegaSecs, Secs, MicroSecs} = now(), random:seed(MegaSecs, Secs, MicroSecs), start up delay of no more than 10 seconds timer:sleep(random:uniform(10000)), {ok, Pid} = gm:start_link(?MODULE, ?MODULE, []), Start = random:uniform(10000), send_loop(Pid, Start, Start + random:uniform(10000)), gm:leave(Pid), spawn_more() end). spawn_more() -> [spawn_member() || _ <- lists:seq(1, 4 - random:uniform(4))]. send_loop(_Pid, Target, Target) -> ok; send_loop(Pid, Count, Target) when Target > Count -> case random:uniform(3) of 3 -> gm:confirmed_broadcast(Pid, {test_msg, Count}); _ -> gm:broadcast(Pid, {test_msg, Count}) end, sleep up to 4 ms send_loop(Pid, Count + 1, Target). test() -> ok = gm:create_tables(), spawn_member(), spawn_member().
null
https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/lib/rabbitmq_server-2.4.1/src/gm_soak_test.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. --------------------------------------------------------------------------- Soak test ---------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is VMware , Inc. Copyright ( c ) 2007 - 2011 VMware , Inc. All rights reserved . -module(gm_soak_test). -export([test/0]). -export([joined/2, members_changed/3, handle_msg/3, terminate/2]). -behaviour(gm). -include("gm_specs.hrl"). get_state() -> get(state). with_state(Fun) -> put(state, Fun(get_state())). inc() -> case 1 + get(count) of 100000 -> Now = now(), Start = put(ts, Now), Diff = timer:now_diff(Now, Start), Rate = 100000 / (Diff / 1000000), io:format("~p seeing ~p msgs/sec~n", [self(), Rate]), put(count, 0); N -> put(count, N) end. joined([], Members) -> io:format("Joined ~p (~p members)~n", [self(), length(Members)]), put(state, dict:from_list([{Member, empty} || Member <- Members])), put(count, 0), put(ts, now()), ok. members_changed([], Births, Deaths) -> with_state( fun (State) -> State1 = lists:foldl( fun (Born, StateN) -> false = dict:is_key(Born, StateN), dict:store(Born, empty, StateN) end, State, Births), lists:foldl( fun (Died, StateN) -> true = dict:is_key(Died, StateN), dict:store(Died, died, StateN) end, State1, Deaths) end), ok. handle_msg([], From, {test_msg, Num}) -> inc(), with_state( fun (State) -> ok = case dict:find(From, State) of {ok, died} -> exit({{from, From}, {received_posthumous_delivery, Num}}); {ok, empty} -> ok; {ok, Num} -> ok; {ok, Num1} when Num < Num1 -> exit({{from, From}, {duplicate_delivery_of, Num1}, {expecting, Num}}); {ok, Num1} -> exit({{from, From}, {missing_delivery_of, Num}, {received_early, Num1}}); error -> exit({{from, From}, {received_premature_delivery, Num}}) end, dict:store(From, Num + 1, State) end), ok. terminate([], Reason) -> io:format("Left ~p (~p)~n", [self(), Reason]), ok. spawn_member() -> spawn_link( fun () -> {MegaSecs, Secs, MicroSecs} = now(), random:seed(MegaSecs, Secs, MicroSecs), start up delay of no more than 10 seconds timer:sleep(random:uniform(10000)), {ok, Pid} = gm:start_link(?MODULE, ?MODULE, []), Start = random:uniform(10000), send_loop(Pid, Start, Start + random:uniform(10000)), gm:leave(Pid), spawn_more() end). spawn_more() -> [spawn_member() || _ <- lists:seq(1, 4 - random:uniform(4))]. send_loop(_Pid, Target, Target) -> ok; send_loop(Pid, Count, Target) when Target > Count -> case random:uniform(3) of 3 -> gm:confirmed_broadcast(Pid, {test_msg, Count}); _ -> gm:broadcast(Pid, {test_msg, Count}) end, sleep up to 4 ms send_loop(Pid, Count + 1, Target). test() -> ok = gm:create_tables(), spawn_member(), spawn_member().
786574b6a579b71b03d1959b688b46f887452145a5305583483ecb1e66ce61c9
habit-lang/alb
Surface.hs
{-# LANGUAGE TypeSynonymInstances #-} -- For Printable Id instance module Printer.Surface (module Printer.Surface, Printable(..), quoted) where import Prelude hiding ((<$>)) import Data.Char import qualified Data.Map as Map import Data.Maybe (isJust) import Printer.Common hiding (printInfix) import Syntax.Surface as Surface -- this is probably wrong isOperator (Ident s@(c:_) 0 _) = s /= "()" && not (isAlphaNum c) && c /= '_' isOperator _ = False printInfix :: Printable t => (Id -> Printer Fixity) -> Id -> t -> t -> Doc printInfix fixity id@(Ident op 0 _) lhs rhs = do f <- fixity id case f of Fixity NoAssoc n -> atPrecedence n (withPrecedence (n + 1) (ppr lhs) <+> text op <+> withPrecedence (n + 1) (ppr rhs)) Fixity LeftAssoc n -> atPrecedence n (ppr lhs <+> text op <+> withPrecedence (n + 1) (ppr rhs)) Fixity RightAssoc n -> atPrecedence n (withPrecedence (n + 1) (ppr lhs) <+> text op <+> ppr rhs) printInfix _ id lhs rhs = pprApp (pprApp (ppr id) (ppr lhs)) (ppr rhs) where pprApp x y = atPrecedence 9 (x <+> withPrecedence 10 y) instance Printable Type where ppr (TyCon s) = ppr s ppr (TyVar s) = ppr s ppr TyWild = text "_" ppr (TyApp (At _ (TyApp (At _ (TyVar op)) lhs)) rhs) | isOperator op = printInfix typeFixity op lhs rhs ppr (TyApp (At _ (TyApp (At _ (TyVar op)) lhs)) rhs) | isOperator op = printInfix typeFixity op lhs rhs ppr (TyApp t t') = atPrecedence 9 (ppr t <+> withPrecedence 10 (ppr t')) ppr (TyNat i) = integer i ppr (TyTuple ts) = parens (cat (punctuate comma (map ppr ts))) ppr (TyTupleCon n) = parens (cat (replicate n comma)) ppr (TyKinded t k) = ppr t <+> text "::" <+> ppr k ppr (TyLabel s) = char '#' <> ppr s ppr (TySelect t (At _ l)) = withPrecedence 10 (ppr t) <> dot <> ppr l ppr (TyInfix first rest) = atPrecedence 8 (withPrecedence 9 (ppr first <+> hsep [ ppr op <+> ppr t | (op, t) <- rest ])) instance Printable Pred where ppr (Pred (At _ t) mt Holds) = ppr t <> maybe empty (\t -> space <> equals <+> ppr t) mt ppr (Pred (At _ t) mt Fails) = ppr t <> maybe empty (\t -> space <> equals <+> ppr t) mt <+> text "fails" instance Printable t => Printable (Qual t) where ppr ([] :=> t) = ppr t ppr (preds :=> t) = parens (cat (punctuate comma (map ppr preds))) <+> text "=>" <+> ppr t instance Printable Expr where ppr (ELet ds body) = text "let" <+> ppr ds </> text "in" <+> ppr body ppr (EIf cond cons alt) = text "if" <+> ppr cond </> text "then" <+> ppr cons </> text "else" <+> ppr alt ppr (ECase scrutinee alts) = nest 4 (text "case" <+> ppr scrutinee <+> text "of" <$> align (vcat (map ppr alts))) ppr (ELam patterns body) = nest 4 (backslash <> withPrecedence 10 (hsep (map ppr patterns)) <+> text "->" </> ppr body) ppr (EVar id) = ppr id ppr (ECon id) = ppr id ppr (ELit l) = ppr l ppr (ETuple es) = parens (cat (punctuate comma (map ppr es))) ppr (ETupleCon n) = parens (cat (replicate n comma)) ppr (EApp (At _ (EApp (At _ (EVar op)) lhs)) rhs) | isOperator op = printInfix valFixity op lhs rhs ppr (EApp (At _ (EApp (At _ (EVar op)) lhs)) rhs) | isOperator op = printInfix valFixity op lhs rhs ppr (EApp e e') = atPrecedence 9 (ppr e <+> withPrecedence 10 (ppr e')) ppr (EBind Nothing e rest) = ppr e <> semi </> ppr rest ppr (EBind (Just var) e rest) = ppr var <+> text "<-" <+> ppr e <> semi </> ppr rest ppr (ESelect e (At _ l)) = withPrecedence 10 (ppr e) <> dot <> ppr l ppr (EUpdate e fields) = ppr e <+> brackets (align (cat (punctuate (space <> bar <> space) [ ppr id <+> equals <+> ppr val | (id, val) <- fields ]))) ppr (ELeftSection e (At _ op)) = parens (ppr e <+> ppr op) ppr (ERightSection (At _ op) e) = parens (ppr op <+> ppr e) ppr (EStructInit name fields) = ppr name <+> brackets (align (cat (punctuate (space <> bar <> space) [ ppr id <+> equals <+> ppr val | (id, val) <- fields ]))) ppr (ETyped expr ty) = atPrecedence 0 (withPrecedence 1 (ppr expr)) <::> ppr ty ppr (EInfix first rest) = atPrecedence 8 (withPrecedence 9 (ppr first <+> hsep [ ppr op <+> ppr e | (op, e) <- rest ])) instance Printable Scrutinee where ppr (ScExpr e) = ppr e ppr (ScFrom Nothing e) = text "<-" <+> ppr e ppr (ScFrom (Just id) e) = ppr id <+> text "<-" <+> ppr e instance Printable Pattern where ppr (PVar id) = ppr id ppr (PLit l) = ppr l ppr PWild = char '_' ppr (PAs id p) = atPrecedence 0 (ppr id <+> char '@' <+> withPrecedence 1 (ppr p)) ppr (PTyped p t) = atPrecedence 0 (withPrecedence 1 (ppr p) <+> text "::" <+> ppr t) ppr (PCon id) = ppr id ppr (PTuple ps) = parens (cat (punctuate comma (map ppr ps))) ppr (PTupleCon n) = parens (cat (replicate n comma)) ppr (PApp (At _ (PApp (At _ (PCon op)) lhs)) rhs) | isOperator op = printInfix eitherFixity op lhs rhs ppr (PApp (At _ (PApp (At _ (PVar op)) lhs)) rhs) | isOperator op = printInfix eitherFixity op lhs rhs ppr (PApp p p') = atPrecedence 9 (ppr p <+> withPrecedence 10 (ppr p')) ppr (PLabeled name fields) = ppr name <+> brackets (align (cat (punctuate (space <> bar <> space) (map ppr fields)))) ppr (PInfix first rest) = atPrecedence 8 (withPrecedence 9 (ppr first <+> hsep [ ppr op <+> ppr e | (op, e) <- rest ])) instance Printable FieldPattern where ppr (FieldPattern id p) = ppr id <+> equals <+> ppr p printMaybeDecls :: Maybe Decls -> Doc printMaybeDecls Nothing = empty printMaybeDecls (Just ds) = line <> nest 6 (text "where" <+> ppr ds) printRhs :: String -> Rhs -> Doc printRhs separator (Unguarded body ds) = text separator <+> ppr body <> printMaybeDecls ds printRhs separator (Guarded ps ds) = align (vcat [ bar <+> ppr guard <+> text separator <+> ppr body | (guard, body) <- ps ]) <> printMaybeDecls ds instance Printable Alt where ppr (p :-> rhs) = ppr p <+> printRhs "->" rhs instance Printable Equation where ppr (lhs := rhs) = nest 4 (ppr lhs <+> printRhs "=" rhs) instance Printable Signature where ppr (Signature id (ps :=> t)) = ppr id <+> text "::" <> (if null ps then empty else space <> parens (cat (punctuate comma (map ppr ps))) <+> text "=>") <+> ppr t instance Printable Fixities where ppr f = vcat (map printTypeFixity (Map.assocs (typeFixities f)) ++ map printFixity (Map.assocs (valFixities f))) where printTypeFixity (id, At _ (Fixity assoc n)) = ppr assoc <+> text "type" <+> int n <+> if isOperator id then ppr id else char '`' <> ppr id <> char '`' printFixity (id, At _ (Fixity assoc n)) = ppr assoc <+> int n <+> if isOperator id then ppr id else char '`' <> ppr id <> char '`' instance Printable Assoc where ppr LeftAssoc = text "infixl" ppr RightAssoc = text "infixr" ppr NoAssoc = text "infix" instance Printable Decls where ppr ds = withFixities (Surface.fixities ds) (vsep (map ppr (signatures ds) ++ map ppr (equations ds)) <> pprFixities) where pprFixities | Map.null (typeFixities (Surface.fixities ds)) && Map.null (valFixities (Surface.fixities ds)) = empty | otherwise = line <> ppr (Surface.fixities ds) instance Printable Class where ppr (Class lhs determined constraints decls) = nest 4 (text "class" <+> ppr lhs <> pprDetermined <> pprCs <> printMaybeDecls decls) where pprDetermined = case determined of Nothing -> empty Just t -> space <> equals <+> ppr t pprCs | null constraints = empty | otherwise = space <> bar <+> cat (punctuate comma (map ppr constraints)) instance Printable ClassConstraint where ppr (Superclass p) = ppr p ppr (Fundep (xs :~> ys)) = vars xs <+> text "->" <+> vars ys where vars = cat . punctuate comma . map ppr ppr (Opaque v) = text "opaque" <+> ppr v instance Printable Instance where ppr (Instance ((hypotheses :=> conclusion, decls) : alternatives)) = text "instance" <+> pprInstanceBody conclusion hypotheses decls <> pprAlts where pprInstanceBody conclusion hypotheses decls = ppr conclusion <+> (if null hypotheses then empty else text "if" <+> cat (punctuate comma (map ppr hypotheses))) <> nest 4 (printMaybeDecls decls) pprAlts | null alternatives = empty | otherwise = vcat [ line <> text "else" <+> pprInstanceBody conclusion hypotheses decls | (hypotheses :=> conclusion, decls) <- alternatives ] instance Printable Requirement where ppr (Require ps qs) = "require" <+> cat (punctuate ", " (map ppr ps)) <+> "if" <+> cat (punctuate ", " (map ppr qs)) instance Printable Synonym where ppr (Synonym lhs rhs interface) = (if isJust interface then text "opaque" <> space else empty) <> text "type" <+> ppr lhs <+> equals <+> ppr rhs <> nest 4 (printMaybeDecls interface) instance Printable Datatype where ppr (Datatype lhs ctors drv interface) = nest 4 ((if isJust interface then text "opaque" <> space else empty) <> text "data" <+> ppr lhs <> pprCtors <> pprDrvs <> nest 4 (printMaybeDecls interface)) where pprCtor (Ctor name _ [] fields) = ppr name <+> pprFields fields pprCtor (Ctor name _ preds fields) = ppr name <+> pprFields fields <+> text "if" <+> cat (punctuate comma (map ppr preds)) pprFields fs | all unlabeled fs = sep (map (atPrecedence 10 . pprField) fs) | otherwise = brackets (cat (punctuate " | " (map pprField fs))) where unlabeled (At _ (DataField Nothing _)) = True unlabeled _ = False pprField (At _ (DataField (Just l) t)) = ppr l <+> "::" <+> ppr t pprField (At _ (DataField Nothing t)) = ppr t pprCtors = case ctors of [] -> empty (first : rest) -> equals <+> pprCtor first <> cat [ softline <> bar <+> pprCtor ctor | ctor <- rest ] pprDrvs | null drv = empty | otherwise = softline <> text "deriving" <+> parens (cat (punctuate comma (map ppr drv))) instance Printable Bitdatatype where ppr (Bitdatatype lhs size ctors drv) = nest 4 (text "bitdata" <+> ppr lhs <> (maybe empty (\t -> slash <> ppr t) size) <> pprCtors <> pprDrvs) where pprCtor (Ctor name _ [] fields) = ppr name <+> brackets (cat (punctuate (space <> bar <> space) (map ppr fields))) pprCtor (Ctor name _ preds fields) = ppr name <+> brackets (cat (punctuate (space <> bar <> space) (map ppr fields))) <+> text "if" <+> cat (punctuate comma (map ppr preds)) pprCtors = case ctors of [] -> empty (first : rest) -> equals <+> pprCtor first <> cat [ softline <> bar <+> pprCtor ctor | ctor <- rest ] pprDrvs | null drv = empty | otherwise = softline <> text "deriving" <+> parens (cat (punctuate comma (map ppr drv))) instance Printable BitdataField where ppr (LabeledField name ty init) = ppr name <> maybe empty (\init -> space <> equals <+> ppr init) init <::> ppr ty ppr (ConstantField e) = ppr e instance Printable Struct where ppr (Struct name size (Ctor _ _ preds regions) align drv) = nest 4 (ppr name <> maybe empty (\t -> slash <> ppr t) size <+> brackets (cat (punctuate (softline <> bar <> space) (map ppr regions))) <> (if null preds then empty else softline <> text "if" <+> cat (punctuate (comma <> softline) (map ppr preds))) <> (maybe empty ((" aligned" <+>) . ppr) align) <> pprDrvs) where pprDrvs | null drv = empty | otherwise = softline <> text "deriving" <+> parens (cat (punctuate comma (map ppr drv))) instance Printable StructRegion where ppr (StructRegion Nothing ty) = ppr ty ppr (StructRegion (Just (StructField id Nothing)) ty) = ppr id <+> text "::" <+> ppr ty ppr (StructRegion (Just (StructField id (Just init))) ty) = ppr id <+> text "<-" <+> ppr init <+> text "::" <+> ppr ty instance Printable Area where ppr (Area v ids ty align decls) = nest 4 ((if v then text "volatile " else empty) <> text "area" <+> cat (punctuate (comma <> softline) [ ppr name <> maybe empty (\init -> space <> text "<-" <+> ppr init) init | (name, init) <- ids ]) </> text "::" <+> ppr ty <> (maybe empty ((" aligned" <+>) . ppr) align) <> printMaybeDecls decls) instance Printable Primitive where ppr (PrimValue s name private) = text "primitive" <+> (if private then empty else "private" <> space) <> ppr s <+> parens (text name) ppr (PrimCon s name private) = text "primitive" <+> (if private then empty else "private" <> space) <> ppr s <+> parens (text name) ppr (PrimType t) = text "primitive" <+> ppr t ppr (PrimClass lhs rhs constraints decls) = text "primitive" <+> ppr (Class lhs rhs (map (fmap Fundep) constraints) decls) instance Printable Program where ppr p = vcat (punctuate line (map ppr (datatypes p) ++ map ppr (bitdatatypes p) ++ map ppr (structures p) ++ map ppr (synonyms p) ++ map ppr (classes p) ++ map ppr (instances p) ++ map ppr (areas p) ++ map ppr (primitives p) ++ [ppr (Surface.decls p)]))
null
https://raw.githubusercontent.com/habit-lang/alb/567d4c86194a884cc1ceeffca9663211de2d554c/src/Printer/Surface.hs
haskell
# LANGUAGE TypeSynonymInstances # For Printable Id instance this is probably wrong
module Printer.Surface (module Printer.Surface, Printable(..), quoted) where import Prelude hiding ((<$>)) import Data.Char import qualified Data.Map as Map import Data.Maybe (isJust) import Printer.Common hiding (printInfix) import Syntax.Surface as Surface isOperator (Ident s@(c:_) 0 _) = s /= "()" && not (isAlphaNum c) && c /= '_' isOperator _ = False printInfix :: Printable t => (Id -> Printer Fixity) -> Id -> t -> t -> Doc printInfix fixity id@(Ident op 0 _) lhs rhs = do f <- fixity id case f of Fixity NoAssoc n -> atPrecedence n (withPrecedence (n + 1) (ppr lhs) <+> text op <+> withPrecedence (n + 1) (ppr rhs)) Fixity LeftAssoc n -> atPrecedence n (ppr lhs <+> text op <+> withPrecedence (n + 1) (ppr rhs)) Fixity RightAssoc n -> atPrecedence n (withPrecedence (n + 1) (ppr lhs) <+> text op <+> ppr rhs) printInfix _ id lhs rhs = pprApp (pprApp (ppr id) (ppr lhs)) (ppr rhs) where pprApp x y = atPrecedence 9 (x <+> withPrecedence 10 y) instance Printable Type where ppr (TyCon s) = ppr s ppr (TyVar s) = ppr s ppr TyWild = text "_" ppr (TyApp (At _ (TyApp (At _ (TyVar op)) lhs)) rhs) | isOperator op = printInfix typeFixity op lhs rhs ppr (TyApp (At _ (TyApp (At _ (TyVar op)) lhs)) rhs) | isOperator op = printInfix typeFixity op lhs rhs ppr (TyApp t t') = atPrecedence 9 (ppr t <+> withPrecedence 10 (ppr t')) ppr (TyNat i) = integer i ppr (TyTuple ts) = parens (cat (punctuate comma (map ppr ts))) ppr (TyTupleCon n) = parens (cat (replicate n comma)) ppr (TyKinded t k) = ppr t <+> text "::" <+> ppr k ppr (TyLabel s) = char '#' <> ppr s ppr (TySelect t (At _ l)) = withPrecedence 10 (ppr t) <> dot <> ppr l ppr (TyInfix first rest) = atPrecedence 8 (withPrecedence 9 (ppr first <+> hsep [ ppr op <+> ppr t | (op, t) <- rest ])) instance Printable Pred where ppr (Pred (At _ t) mt Holds) = ppr t <> maybe empty (\t -> space <> equals <+> ppr t) mt ppr (Pred (At _ t) mt Fails) = ppr t <> maybe empty (\t -> space <> equals <+> ppr t) mt <+> text "fails" instance Printable t => Printable (Qual t) where ppr ([] :=> t) = ppr t ppr (preds :=> t) = parens (cat (punctuate comma (map ppr preds))) <+> text "=>" <+> ppr t instance Printable Expr where ppr (ELet ds body) = text "let" <+> ppr ds </> text "in" <+> ppr body ppr (EIf cond cons alt) = text "if" <+> ppr cond </> text "then" <+> ppr cons </> text "else" <+> ppr alt ppr (ECase scrutinee alts) = nest 4 (text "case" <+> ppr scrutinee <+> text "of" <$> align (vcat (map ppr alts))) ppr (ELam patterns body) = nest 4 (backslash <> withPrecedence 10 (hsep (map ppr patterns)) <+> text "->" </> ppr body) ppr (EVar id) = ppr id ppr (ECon id) = ppr id ppr (ELit l) = ppr l ppr (ETuple es) = parens (cat (punctuate comma (map ppr es))) ppr (ETupleCon n) = parens (cat (replicate n comma)) ppr (EApp (At _ (EApp (At _ (EVar op)) lhs)) rhs) | isOperator op = printInfix valFixity op lhs rhs ppr (EApp (At _ (EApp (At _ (EVar op)) lhs)) rhs) | isOperator op = printInfix valFixity op lhs rhs ppr (EApp e e') = atPrecedence 9 (ppr e <+> withPrecedence 10 (ppr e')) ppr (EBind Nothing e rest) = ppr e <> semi </> ppr rest ppr (EBind (Just var) e rest) = ppr var <+> text "<-" <+> ppr e <> semi </> ppr rest ppr (ESelect e (At _ l)) = withPrecedence 10 (ppr e) <> dot <> ppr l ppr (EUpdate e fields) = ppr e <+> brackets (align (cat (punctuate (space <> bar <> space) [ ppr id <+> equals <+> ppr val | (id, val) <- fields ]))) ppr (ELeftSection e (At _ op)) = parens (ppr e <+> ppr op) ppr (ERightSection (At _ op) e) = parens (ppr op <+> ppr e) ppr (EStructInit name fields) = ppr name <+> brackets (align (cat (punctuate (space <> bar <> space) [ ppr id <+> equals <+> ppr val | (id, val) <- fields ]))) ppr (ETyped expr ty) = atPrecedence 0 (withPrecedence 1 (ppr expr)) <::> ppr ty ppr (EInfix first rest) = atPrecedence 8 (withPrecedence 9 (ppr first <+> hsep [ ppr op <+> ppr e | (op, e) <- rest ])) instance Printable Scrutinee where ppr (ScExpr e) = ppr e ppr (ScFrom Nothing e) = text "<-" <+> ppr e ppr (ScFrom (Just id) e) = ppr id <+> text "<-" <+> ppr e instance Printable Pattern where ppr (PVar id) = ppr id ppr (PLit l) = ppr l ppr PWild = char '_' ppr (PAs id p) = atPrecedence 0 (ppr id <+> char '@' <+> withPrecedence 1 (ppr p)) ppr (PTyped p t) = atPrecedence 0 (withPrecedence 1 (ppr p) <+> text "::" <+> ppr t) ppr (PCon id) = ppr id ppr (PTuple ps) = parens (cat (punctuate comma (map ppr ps))) ppr (PTupleCon n) = parens (cat (replicate n comma)) ppr (PApp (At _ (PApp (At _ (PCon op)) lhs)) rhs) | isOperator op = printInfix eitherFixity op lhs rhs ppr (PApp (At _ (PApp (At _ (PVar op)) lhs)) rhs) | isOperator op = printInfix eitherFixity op lhs rhs ppr (PApp p p') = atPrecedence 9 (ppr p <+> withPrecedence 10 (ppr p')) ppr (PLabeled name fields) = ppr name <+> brackets (align (cat (punctuate (space <> bar <> space) (map ppr fields)))) ppr (PInfix first rest) = atPrecedence 8 (withPrecedence 9 (ppr first <+> hsep [ ppr op <+> ppr e | (op, e) <- rest ])) instance Printable FieldPattern where ppr (FieldPattern id p) = ppr id <+> equals <+> ppr p printMaybeDecls :: Maybe Decls -> Doc printMaybeDecls Nothing = empty printMaybeDecls (Just ds) = line <> nest 6 (text "where" <+> ppr ds) printRhs :: String -> Rhs -> Doc printRhs separator (Unguarded body ds) = text separator <+> ppr body <> printMaybeDecls ds printRhs separator (Guarded ps ds) = align (vcat [ bar <+> ppr guard <+> text separator <+> ppr body | (guard, body) <- ps ]) <> printMaybeDecls ds instance Printable Alt where ppr (p :-> rhs) = ppr p <+> printRhs "->" rhs instance Printable Equation where ppr (lhs := rhs) = nest 4 (ppr lhs <+> printRhs "=" rhs) instance Printable Signature where ppr (Signature id (ps :=> t)) = ppr id <+> text "::" <> (if null ps then empty else space <> parens (cat (punctuate comma (map ppr ps))) <+> text "=>") <+> ppr t instance Printable Fixities where ppr f = vcat (map printTypeFixity (Map.assocs (typeFixities f)) ++ map printFixity (Map.assocs (valFixities f))) where printTypeFixity (id, At _ (Fixity assoc n)) = ppr assoc <+> text "type" <+> int n <+> if isOperator id then ppr id else char '`' <> ppr id <> char '`' printFixity (id, At _ (Fixity assoc n)) = ppr assoc <+> int n <+> if isOperator id then ppr id else char '`' <> ppr id <> char '`' instance Printable Assoc where ppr LeftAssoc = text "infixl" ppr RightAssoc = text "infixr" ppr NoAssoc = text "infix" instance Printable Decls where ppr ds = withFixities (Surface.fixities ds) (vsep (map ppr (signatures ds) ++ map ppr (equations ds)) <> pprFixities) where pprFixities | Map.null (typeFixities (Surface.fixities ds)) && Map.null (valFixities (Surface.fixities ds)) = empty | otherwise = line <> ppr (Surface.fixities ds) instance Printable Class where ppr (Class lhs determined constraints decls) = nest 4 (text "class" <+> ppr lhs <> pprDetermined <> pprCs <> printMaybeDecls decls) where pprDetermined = case determined of Nothing -> empty Just t -> space <> equals <+> ppr t pprCs | null constraints = empty | otherwise = space <> bar <+> cat (punctuate comma (map ppr constraints)) instance Printable ClassConstraint where ppr (Superclass p) = ppr p ppr (Fundep (xs :~> ys)) = vars xs <+> text "->" <+> vars ys where vars = cat . punctuate comma . map ppr ppr (Opaque v) = text "opaque" <+> ppr v instance Printable Instance where ppr (Instance ((hypotheses :=> conclusion, decls) : alternatives)) = text "instance" <+> pprInstanceBody conclusion hypotheses decls <> pprAlts where pprInstanceBody conclusion hypotheses decls = ppr conclusion <+> (if null hypotheses then empty else text "if" <+> cat (punctuate comma (map ppr hypotheses))) <> nest 4 (printMaybeDecls decls) pprAlts | null alternatives = empty | otherwise = vcat [ line <> text "else" <+> pprInstanceBody conclusion hypotheses decls | (hypotheses :=> conclusion, decls) <- alternatives ] instance Printable Requirement where ppr (Require ps qs) = "require" <+> cat (punctuate ", " (map ppr ps)) <+> "if" <+> cat (punctuate ", " (map ppr qs)) instance Printable Synonym where ppr (Synonym lhs rhs interface) = (if isJust interface then text "opaque" <> space else empty) <> text "type" <+> ppr lhs <+> equals <+> ppr rhs <> nest 4 (printMaybeDecls interface) instance Printable Datatype where ppr (Datatype lhs ctors drv interface) = nest 4 ((if isJust interface then text "opaque" <> space else empty) <> text "data" <+> ppr lhs <> pprCtors <> pprDrvs <> nest 4 (printMaybeDecls interface)) where pprCtor (Ctor name _ [] fields) = ppr name <+> pprFields fields pprCtor (Ctor name _ preds fields) = ppr name <+> pprFields fields <+> text "if" <+> cat (punctuate comma (map ppr preds)) pprFields fs | all unlabeled fs = sep (map (atPrecedence 10 . pprField) fs) | otherwise = brackets (cat (punctuate " | " (map pprField fs))) where unlabeled (At _ (DataField Nothing _)) = True unlabeled _ = False pprField (At _ (DataField (Just l) t)) = ppr l <+> "::" <+> ppr t pprField (At _ (DataField Nothing t)) = ppr t pprCtors = case ctors of [] -> empty (first : rest) -> equals <+> pprCtor first <> cat [ softline <> bar <+> pprCtor ctor | ctor <- rest ] pprDrvs | null drv = empty | otherwise = softline <> text "deriving" <+> parens (cat (punctuate comma (map ppr drv))) instance Printable Bitdatatype where ppr (Bitdatatype lhs size ctors drv) = nest 4 (text "bitdata" <+> ppr lhs <> (maybe empty (\t -> slash <> ppr t) size) <> pprCtors <> pprDrvs) where pprCtor (Ctor name _ [] fields) = ppr name <+> brackets (cat (punctuate (space <> bar <> space) (map ppr fields))) pprCtor (Ctor name _ preds fields) = ppr name <+> brackets (cat (punctuate (space <> bar <> space) (map ppr fields))) <+> text "if" <+> cat (punctuate comma (map ppr preds)) pprCtors = case ctors of [] -> empty (first : rest) -> equals <+> pprCtor first <> cat [ softline <> bar <+> pprCtor ctor | ctor <- rest ] pprDrvs | null drv = empty | otherwise = softline <> text "deriving" <+> parens (cat (punctuate comma (map ppr drv))) instance Printable BitdataField where ppr (LabeledField name ty init) = ppr name <> maybe empty (\init -> space <> equals <+> ppr init) init <::> ppr ty ppr (ConstantField e) = ppr e instance Printable Struct where ppr (Struct name size (Ctor _ _ preds regions) align drv) = nest 4 (ppr name <> maybe empty (\t -> slash <> ppr t) size <+> brackets (cat (punctuate (softline <> bar <> space) (map ppr regions))) <> (if null preds then empty else softline <> text "if" <+> cat (punctuate (comma <> softline) (map ppr preds))) <> (maybe empty ((" aligned" <+>) . ppr) align) <> pprDrvs) where pprDrvs | null drv = empty | otherwise = softline <> text "deriving" <+> parens (cat (punctuate comma (map ppr drv))) instance Printable StructRegion where ppr (StructRegion Nothing ty) = ppr ty ppr (StructRegion (Just (StructField id Nothing)) ty) = ppr id <+> text "::" <+> ppr ty ppr (StructRegion (Just (StructField id (Just init))) ty) = ppr id <+> text "<-" <+> ppr init <+> text "::" <+> ppr ty instance Printable Area where ppr (Area v ids ty align decls) = nest 4 ((if v then text "volatile " else empty) <> text "area" <+> cat (punctuate (comma <> softline) [ ppr name <> maybe empty (\init -> space <> text "<-" <+> ppr init) init | (name, init) <- ids ]) </> text "::" <+> ppr ty <> (maybe empty ((" aligned" <+>) . ppr) align) <> printMaybeDecls decls) instance Printable Primitive where ppr (PrimValue s name private) = text "primitive" <+> (if private then empty else "private" <> space) <> ppr s <+> parens (text name) ppr (PrimCon s name private) = text "primitive" <+> (if private then empty else "private" <> space) <> ppr s <+> parens (text name) ppr (PrimType t) = text "primitive" <+> ppr t ppr (PrimClass lhs rhs constraints decls) = text "primitive" <+> ppr (Class lhs rhs (map (fmap Fundep) constraints) decls) instance Printable Program where ppr p = vcat (punctuate line (map ppr (datatypes p) ++ map ppr (bitdatatypes p) ++ map ppr (structures p) ++ map ppr (synonyms p) ++ map ppr (classes p) ++ map ppr (instances p) ++ map ppr (areas p) ++ map ppr (primitives p) ++ [ppr (Surface.decls p)]))
965d68eea4d10a672e8568837a7a48fc01e172e45795e9dc4ded7d3a9df04c97
exercism/babashka
run_length_encoding.clj
(ns run-length-encoding) (defn run-length-encode "encodes a string with run-length-encoding" [s] (apply str (for [x (partition-by identity s)] (str (when-not (= 1 (count x)) (count x)) (first x))))) (defn run-length-decode "decodes a run-length-encoded string" [s] (->> s (re-seq #"[0-9]+.|[a-zA-Z\s]") (map #(if (= (count %) 1) (str "1" %) %)) (map #(list (Integer. (reduce str "" (butlast %))) (str (last %)))) (map #(apply str (repeat (first %) (second %)))) (reduce str)))
null
https://raw.githubusercontent.com/exercism/babashka/707356c52e08490e66cb1b2e63e4f4439d91cf08/exercises/practice/run-length-encoding/src/run_length_encoding.clj
clojure
(ns run-length-encoding) (defn run-length-encode "encodes a string with run-length-encoding" [s] (apply str (for [x (partition-by identity s)] (str (when-not (= 1 (count x)) (count x)) (first x))))) (defn run-length-decode "decodes a run-length-encoded string" [s] (->> s (re-seq #"[0-9]+.|[a-zA-Z\s]") (map #(if (= (count %) 1) (str "1" %) %)) (map #(list (Integer. (reduce str "" (butlast %))) (str (last %)))) (map #(apply str (repeat (first %) (second %)))) (reduce str)))
a5d724f1c4527c3899df76953580435330fd67aaa25721118ec46409d5dd7403
hidaris/thinking-dumps
tests.rkt
#lang racket (provide test-list) ;;;;;;;;;;;;;;;; tests ;;;;;;;;;;;;;;;; (define test-list '( ;; simple arithmetic (positive-const "11" 11) (negative-const "-33" -33) (simple-arith-1 "(- 44 33)" 11) ;; nested arithmetic (nested-arith-left "(- (- 44 33) 22)" -11) (nested-arith-right "(- 55 (- 22 11))" 44) ;; simple variables (test-var-1 "x" 10) (test-var-2 "(- x 1)" 9) (test-var-3 "(- 1 x)" -9) ;; simple unbound variables (test-unbound-var-1 "foo" error) (test-unbound-var-2 "(- x foo)" error) ;; simple conditionals (if-true "(if (zero? 0) 3 4)" 3) (if-false "(if (zero? 1) 3 4)" 4) ;; test dynamic typechecking (no-bool-to-diff-1 "(- (zero? 0) 1)" error) (no-bool-to-diff-2 "(- 1 (zero? 0))" error) (no-int-to-if "(if 1 2 3)" error) ;; make sure that the test and both arms get evaluated ;; properly. (if-eval-test-true "(if (zero? (- 11 11)) 3 4)" 3) (if-eval-test-false "(if (zero? (- 11 12)) 3 4)" 4) ;; and make sure the other arm doesn't get evaluated. (if-eval-test-true-2 "(if (zero? (- 11 11)) 3 foo)" 3) (if-eval-test-false-2 "(if (zero? (- 11 12)) foo 4)" 4) ;; simple let (simple-let-1 "(let x 3 in x)" 3) make sure the body and rhs get evaluated (eval-let-body "(let x 3 in (- x 1))" 2) (eval-let-rhs "(let x (- 4 1) in (- x 1))" 2) ;; check nested let and shadowing (simple-nested-let "(let x 3 in (let y 4 in (- x y)))" -1) (check-shadowing-in-body "(let x 3 in (let x 4 in x))" 4) (check-shadowing-in-rhs "(let x 3 in (let x (- x 1) in x))" 2) (negative-exp "(- 33)" -33) (apply-exp "((proc (x) (- x 33)) 0)" -33) (apply-multi-exp "((proc (x y) (- x y)) 1 0)" 1) (curried-exp "(let f (proc (x) (proc (y) (- x y))) in ((f 4) 3))" 1) (test4-exp "(let makemult (proc (maker) (proc (x) (if (zero? x) 0 (- ((maker maker) (- x 1)) -4)))) in (let time4 (proc (x) ((makemult makemult) x)) in (time4 3)))" 12) (fact-exp "(let makefact (proc (maker) (proc (x) (if (zero? x) 1 (* ((maker maker) (- x 1)) x)))) in (let fact (proc (x) ((makefact makefact) x)) in (fact 3)))" 6) (times-exp "(let makemult (proc (maker) (proc (x) (proc (y) (if (zero? x) 0 (- (((maker maker) (- x 1)) y) (- y)))))) in (let times (proc (x) (proc (y) (((makemult makemult) x) y))) in ((times 3) 4)))" 12) (times-fact-exp "(let makemult (proc (maker) (proc (x) (proc (y) (if (zero? x) 0 (- (((maker maker) (- x 1)) y) (- y)))))) in (let times (proc (x) (proc (y) (((makemult makemult) x) y))) in (let makefact (proc (maker) (proc (x) (if (zero? x) 1 ((times ((maker maker) (- x 1))) x)))) in (let fact (proc (x) ((makefact makefact) x)) in (fact 3)))))" 6) (odd?-exp "(let makeodd? (proc (maker) (proc (x) (if (zero? x) (not (zero? x)) (not ((maker maker) (- x 1)))))) in (let odd? (proc (x) ((makeodd? makeodd?) x)) in (odd? 3)))" #t) (not-odd?-exp "(let makeodd? (proc (maker) (proc (x) (if (zero? x) (not (zero? x)) (not ((maker maker) (- x 1)))))) in (let odd? (proc (x) ((makeodd? makeodd?) x)) in (odd? 4)))" #f) (even?-exp "(let makeeven? (proc (maker) (proc (x) (if (zero? x) (zero? x) (not ((maker maker) (- x 1)))))) in (let even? (proc (x) ((makeeven? makeeven?) x)) in (even? 3)))" #f) (not-even?-exp "(let makeeven? (proc (maker) (proc (x) (if (zero? x) (zero? x) (not ((maker maker) (- x 1)))))) in (let even? (proc (x) ((makeeven? makeeven?) x)) in (even? 4)))" #t) ))
null
https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/eopl-solutions/chap3/3-24/tests.rkt
racket
tests ;;;;;;;;;;;;;;;; simple arithmetic nested arithmetic simple variables simple unbound variables simple conditionals test dynamic typechecking make sure that the test and both arms get evaluated properly. and make sure the other arm doesn't get evaluated. simple let check nested let and shadowing
#lang racket (provide test-list) (define test-list '( (positive-const "11" 11) (negative-const "-33" -33) (simple-arith-1 "(- 44 33)" 11) (nested-arith-left "(- (- 44 33) 22)" -11) (nested-arith-right "(- 55 (- 22 11))" 44) (test-var-1 "x" 10) (test-var-2 "(- x 1)" 9) (test-var-3 "(- 1 x)" -9) (test-unbound-var-1 "foo" error) (test-unbound-var-2 "(- x foo)" error) (if-true "(if (zero? 0) 3 4)" 3) (if-false "(if (zero? 1) 3 4)" 4) (no-bool-to-diff-1 "(- (zero? 0) 1)" error) (no-bool-to-diff-2 "(- 1 (zero? 0))" error) (no-int-to-if "(if 1 2 3)" error) (if-eval-test-true "(if (zero? (- 11 11)) 3 4)" 3) (if-eval-test-false "(if (zero? (- 11 12)) 3 4)" 4) (if-eval-test-true-2 "(if (zero? (- 11 11)) 3 foo)" 3) (if-eval-test-false-2 "(if (zero? (- 11 12)) foo 4)" 4) (simple-let-1 "(let x 3 in x)" 3) make sure the body and rhs get evaluated (eval-let-body "(let x 3 in (- x 1))" 2) (eval-let-rhs "(let x (- 4 1) in (- x 1))" 2) (simple-nested-let "(let x 3 in (let y 4 in (- x y)))" -1) (check-shadowing-in-body "(let x 3 in (let x 4 in x))" 4) (check-shadowing-in-rhs "(let x 3 in (let x (- x 1) in x))" 2) (negative-exp "(- 33)" -33) (apply-exp "((proc (x) (- x 33)) 0)" -33) (apply-multi-exp "((proc (x y) (- x y)) 1 0)" 1) (curried-exp "(let f (proc (x) (proc (y) (- x y))) in ((f 4) 3))" 1) (test4-exp "(let makemult (proc (maker) (proc (x) (if (zero? x) 0 (- ((maker maker) (- x 1)) -4)))) in (let time4 (proc (x) ((makemult makemult) x)) in (time4 3)))" 12) (fact-exp "(let makefact (proc (maker) (proc (x) (if (zero? x) 1 (* ((maker maker) (- x 1)) x)))) in (let fact (proc (x) ((makefact makefact) x)) in (fact 3)))" 6) (times-exp "(let makemult (proc (maker) (proc (x) (proc (y) (if (zero? x) 0 (- (((maker maker) (- x 1)) y) (- y)))))) in (let times (proc (x) (proc (y) (((makemult makemult) x) y))) in ((times 3) 4)))" 12) (times-fact-exp "(let makemult (proc (maker) (proc (x) (proc (y) (if (zero? x) 0 (- (((maker maker) (- x 1)) y) (- y)))))) in (let times (proc (x) (proc (y) (((makemult makemult) x) y))) in (let makefact (proc (maker) (proc (x) (if (zero? x) 1 ((times ((maker maker) (- x 1))) x)))) in (let fact (proc (x) ((makefact makefact) x)) in (fact 3)))))" 6) (odd?-exp "(let makeodd? (proc (maker) (proc (x) (if (zero? x) (not (zero? x)) (not ((maker maker) (- x 1)))))) in (let odd? (proc (x) ((makeodd? makeodd?) x)) in (odd? 3)))" #t) (not-odd?-exp "(let makeodd? (proc (maker) (proc (x) (if (zero? x) (not (zero? x)) (not ((maker maker) (- x 1)))))) in (let odd? (proc (x) ((makeodd? makeodd?) x)) in (odd? 4)))" #f) (even?-exp "(let makeeven? (proc (maker) (proc (x) (if (zero? x) (zero? x) (not ((maker maker) (- x 1)))))) in (let even? (proc (x) ((makeeven? makeeven?) x)) in (even? 3)))" #f) (not-even?-exp "(let makeeven? (proc (maker) (proc (x) (if (zero? x) (zero? x) (not ((maker maker) (- x 1)))))) in (let even? (proc (x) ((makeeven? makeeven?) x)) in (even? 4)))" #t) ))
f44287d9f538670837653619f14863ae32c46a03ab775bf21526d0871419c13f
ammarhakim/gkylcas
basisSer2x.lisp
;;; -*- Mode: LISP; package:maxima; syntax:common-lisp; -*- (in-package :maxima) (DSKSETQ |$varsC| '((MLIST SIMP) $X $Y)) (ADD2LNC '|$varsC| $VALUES) (DSKSETQ |$basisC| '((MLIST SIMP (9. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/basis-precalc/basis-pre-cdim-calc.mac" SRC |$writeBasisToFile| 7.)) ((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 2.) $X $Y)) ((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 2.) $X $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))))) ((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 2.) $X $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.)))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 7. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 3.))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 7. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $Y) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 3.))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 21. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 3.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 21. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X $Y) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 3.))))) ((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 2.) $X $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.)))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 7. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 3.))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 7. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $Y) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 3.))) ((MTIMES SIMP) ((RAT SIMP) 45. 8.) ((MPLUS SIMP) ((RAT SIMP) -1. 9.) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.)))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 21. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 3.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 21. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X $Y) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 3.)))) ((MTIMES SIMP) ((RAT SIMP) 105. 16.) ((MPLUS SIMP) ((RAT SIMP) -1. 5.) ((MTIMES SIMP) ((RAT SIMP) -6. 7.) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 4.))) ((MTIMES SIMP) ((RAT SIMP) 105. 16.) ((MPLUS SIMP) ((RAT SIMP) -1. 5.) ((MTIMES SIMP) ((RAT SIMP) -6. 7.) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 4.))) ((MTIMES SIMP) ((RAT SIMP) 35. 16.) ((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 5.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 4.) $Y) ((MTIMES SIMP) ((RAT SIMP) -6. 7.) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) $Y))))) ((MTIMES SIMP) ((RAT SIMP) 35. 16.) ((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 5.) $X) ((MTIMES SIMP) ((RAT SIMP) -6. 7.) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.)))) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 4.))))))) (ADD2LNC '|$basisC| $VALUES) (DSKSETQ |$basisConstant| '((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.))) (ADD2LNC '|$basisConstant| $VALUES)
null
https://raw.githubusercontent.com/ammarhakim/gkylcas/1f8adad4f344ce8e3663451e16fdf1c32107ceed/maxima/g2/basis-precalc/basisSer2x.lisp
lisp
-*- Mode: LISP; package:maxima; syntax:common-lisp; -*-
(in-package :maxima) (DSKSETQ |$varsC| '((MLIST SIMP) $X $Y)) (ADD2LNC '|$varsC| $VALUES) (DSKSETQ |$basisC| '((MLIST SIMP (9. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/basis-precalc/basis-pre-cdim-calc.mac" SRC |$writeBasisToFile| 7.)) ((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 2.) $X $Y)) ((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 2.) $X $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))))) ((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 2.) $X $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.)))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 7. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 3.))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 7. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $Y) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 3.))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 21. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 3.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 21. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X $Y) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 3.))))) ((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X) ((MTIMES SIMP) ((RAT SIMP) 1. 2.) ((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 2.) $X $Y) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 3. 4.) ((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.)))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 7. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 3.))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 7. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $Y) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 3.))) ((MTIMES SIMP) ((RAT SIMP) 45. 8.) ((MPLUS SIMP) ((RAT SIMP) -1. 9.) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.)))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 21. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 3.) $Y))) ((MTIMES SIMP) ((RAT SIMP) 5. 4.) ((MEXPT SIMP) 21. ((RAT SIMP) 1. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -3. 5.) $X $Y) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 3.)))) ((MTIMES SIMP) ((RAT SIMP) 105. 16.) ((MPLUS SIMP) ((RAT SIMP) -1. 5.) ((MTIMES SIMP) ((RAT SIMP) -6. 7.) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.))) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 4.))) ((MTIMES SIMP) ((RAT SIMP) 105. 16.) ((MPLUS SIMP) ((RAT SIMP) -1. 5.) ((MTIMES SIMP) ((RAT SIMP) -6. 7.) ((MPLUS SIMP) ((RAT SIMP) -1. 3.) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.))) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 4.))) ((MTIMES SIMP) ((RAT SIMP) 35. 16.) ((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 5.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 4.) $Y) ((MTIMES SIMP) ((RAT SIMP) -6. 7.) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $Y) ((MTIMES SIMP) ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $X 2.) $Y))))) ((MTIMES SIMP) ((RAT SIMP) 35. 16.) ((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 5.) $X) ((MTIMES SIMP) ((RAT SIMP) -6. 7.) ((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 2.)))) ((MTIMES SIMP) $X ((MEXPT SIMP (61. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$calcPowers| 61.)) $Y 4.))))))) (ADD2LNC '|$basisC| $VALUES) (DSKSETQ |$basisConstant| '((MLIST SIMP (31. "/Users/ahakim/research/gkyl-project/gkyl/cas-scripts/modal-basis.mac" SRC |$gsOrthoNorm| 29.)) ((RAT SIMP) 1. 2.))) (ADD2LNC '|$basisConstant| $VALUES)
6ae3bf033e065f508e96d129cbdc49af1ebb50b9b20f42d6b17322810569f628
quark-lang/quark
Environment.hs
module Core.Macro.Initializing.Environment where import Core.Macro.Definition import Core.Parser.AST import qualified Data.Map as M isID :: Expression -> Bool isID (Identifier _) = True isID _ = False identifiers :: [Expression] -> [String] identifiers e = map (\(Identifier s) -> s) e' where e' = filter isID e runMacroEnvironment :: Expression -> Macros runMacroEnvironment (Node (Identifier "defm") [Identifier name, List args, body]) = let macro = Macro name (identifiers args) body in M.singleton name macro runMacroEnvironment (Node (Identifier "defm") [Identifier name, value]) = let macro = Macro name [] value in M.singleton name macro runMacroEnvironment _ = M.empty runEnvironments :: [Expression] -> Macros runEnvironments = M.unions . map runMacroEnvironment
null
https://raw.githubusercontent.com/quark-lang/quark/40515ef28d46cd2d43227f6a54ab3e0a7228e4a2/app/Core/Macro/Initializing/Environment.hs
haskell
module Core.Macro.Initializing.Environment where import Core.Macro.Definition import Core.Parser.AST import qualified Data.Map as M isID :: Expression -> Bool isID (Identifier _) = True isID _ = False identifiers :: [Expression] -> [String] identifiers e = map (\(Identifier s) -> s) e' where e' = filter isID e runMacroEnvironment :: Expression -> Macros runMacroEnvironment (Node (Identifier "defm") [Identifier name, List args, body]) = let macro = Macro name (identifiers args) body in M.singleton name macro runMacroEnvironment (Node (Identifier "defm") [Identifier name, value]) = let macro = Macro name [] value in M.singleton name macro runMacroEnvironment _ = M.empty runEnvironments :: [Expression] -> Macros runEnvironments = M.unions . map runMacroEnvironment
f32357397f4c9b30537b47962a2b956d5de0193ef03bf3bb8416dede3ff60d57
robashton/cravendb
inflight_spec.clj
(ns cravendb.inflight-spec (:use [speclj.core] [cravendb.testing] [cravendb.core]) (:require [cravendb.vclock :as v] [cravendb.documents :as docs] [cravendb.storage :as s] [cravendb.inflight :as inflight] [me.raynes.fs :as fs] )) (describe "In-flight transactions" (with db (s/create-in-memory-storage)) (with te (inflight/create @db "root")) (after (.close @db) (fs/delete-dir "testdir")) (describe "Adding a single document via the in-flight system" (with txid (inflight/open @te)) (before (inflight/add-document @te @txid "doc-1" {:foo "bar"} {}) (inflight/complete! @te @txid)) (it "will write the document to storage" (should (docs/load-document @db "doc-1"))) (it "will clear the document from the in-flight system" (should-not (inflight/is-registered? @te "doc-1"))) (it "will clear the transaction from the in-flight system" (should-not (inflight/is-txid? @te @txid)))) (describe "Deleting a single document via the in-flight system" (with txid (inflight/open @te)) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {} {})) (inflight/delete-document @te @txid "doc-1" {}) (inflight/complete! @te @txid))) (it "will write the document to storage" (should-not (docs/load-document @db "doc-1"))) (it "will clear the document from the in-flight system" (should-not (inflight/is-registered? @te "doc-1"))) (it "will clear the transaction from the in-flight system" (should-not (inflight/is-txid? @te @txid)))) (describe "Two clients writing at the same time without specifying history" (with txid-1 (inflight/open @te)) (with txid-2 (inflight/open @te)) (before (inflight/add-document @te @txid-1 "doc-1" { :name "1"} {}) (inflight/add-document @te @txid-2 "doc-1" { :name "2"} {}) (inflight/complete! @te @txid-2) (inflight/complete! @te @txid-1)) (it "will write the first document" (should== {:name "1"} (docs/load-document @db "doc-1"))) (it "will generate a conflict document for the second write" (should== {:name "2"} (first (map :data (docs/conflicts @db)))))) (describe "Two clients writing at the same time, no history specified, second client deletes" (with txid-1 (inflight/open @te)) (with txid-2 (inflight/open @te)) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "original"} {}))) (inflight/add-document @te @txid-1 "doc-1" { :name "1"} {}) (inflight/delete-document @te @txid-2 "doc-1" {}) (inflight/complete! @te @txid-2) (inflight/complete! @te @txid-1)) (it "will write the first document" (should= { :name "1" } (docs/load-document @db "doc-1"))) (it "will generate a conflict document for the :delete" (should= :deleted (first (map :data (docs/conflicts @db)))))) (describe "A client writing with no history when a document already exists" (with txid (inflight/open @te)) (with old-history (v/next "boo" (v/new))) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "old-doc"} { :history @old-history})) (inflight/add-document @te @txid "doc-1" {:name "new-doc"} {}) (inflight/complete! @te @txid))) (it "will write the document to storage" (should== { :name "new-doc" } (docs/load-document @db "doc-1"))) (it "will clear the document from the in-flight system" (should-not (inflight/is-registered? @te "doc-1"))) (it "will be a descendent of the old document" (should (v/descends? (:history (docs/load-document-metadata @db "doc-1")) @old-history))) (it "will not generate a conflict" (should= 0 (count (docs/conflicts @db))))) (describe "Two clients both providing history trying to write a document" (with txid-1 (inflight/open @te)) (with txid-2 (inflight/open @te)) (with old-history (v/next "boo" (v/new))) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "old-doc"} { :history @old-history}))) (inflight/add-document @te @txid-1 "doc-1" { :name "1"} {}) (inflight/add-document @te @txid-2 "doc-1" { :name "2"} {}) (inflight/complete! @te @txid-2) (inflight/complete! @te @txid-1)) (it "will write the first document" (should== {:name "1"} (docs/load-document @db "doc-1"))) (it "will write the first document as a descendent of the orignal" (should (v/descends? (:history (docs/load-document-metadata @db "doc-1")) @old-history))) (it "will generate a conflict for the second document" (should== { :name "2"} (first (map :data (docs/conflicts @db))))) (it "will write the conflict as a descendent of the original" (should (v/descends? (first (map (comp :history :metadata) (docs/conflicts @db))) @old-history)))) (describe "A client providing an out of date history when writing" (with txid (inflight/open @te)) (with old-history (v/next "boo" (v/new))) (with supplied-history (v/next "fred" (v/new))) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "old-doc"} { :history @old-history}))) (inflight/add-document @te @txid "doc-1" { :name "1"} { :history @supplied-history }) (inflight/complete! @te @txid)) (it "will generate a conflict for that document" (should== { :name "1"} (first (map :data (docs/conflicts @db))))) (it "will write the conflict as a descendent of the specified history" (should (v/descends? (first (map (comp :history :metadata) (docs/conflicts @db))) @supplied-history)))) (describe "A client writing a valid document when a previous client has conflicted" (with tx1 (inflight/open @te)) (with tx2 (inflight/open @te)) (with old-history (v/next "boo" (v/new))) (with supplied-history (v/next "fred" (v/new))) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "old-doc"} { :history @old-history}))) (inflight/add-document @te @tx1 "doc-1" { :name "conflict"} { :history @supplied-history }) (inflight/add-document @te @tx2 "doc-1" { :name "fine"} {}) (inflight/complete! @te @tx1) (inflight/complete! @te @tx2)) (it "will still write the original conflicted document as conflicted" (should== { :name "conflict"} (first (map :data (docs/conflicts @db))))) (it "will write the second document to the underlying store" (should== {:name "fine"} (docs/load-document @db "doc-1")) )))
null
https://raw.githubusercontent.com/robashton/cravendb/461e80c7c028478adb4287922db6ee4d2593a880/spec/cravendb/inflight_spec.clj
clojure
(ns cravendb.inflight-spec (:use [speclj.core] [cravendb.testing] [cravendb.core]) (:require [cravendb.vclock :as v] [cravendb.documents :as docs] [cravendb.storage :as s] [cravendb.inflight :as inflight] [me.raynes.fs :as fs] )) (describe "In-flight transactions" (with db (s/create-in-memory-storage)) (with te (inflight/create @db "root")) (after (.close @db) (fs/delete-dir "testdir")) (describe "Adding a single document via the in-flight system" (with txid (inflight/open @te)) (before (inflight/add-document @te @txid "doc-1" {:foo "bar"} {}) (inflight/complete! @te @txid)) (it "will write the document to storage" (should (docs/load-document @db "doc-1"))) (it "will clear the document from the in-flight system" (should-not (inflight/is-registered? @te "doc-1"))) (it "will clear the transaction from the in-flight system" (should-not (inflight/is-txid? @te @txid)))) (describe "Deleting a single document via the in-flight system" (with txid (inflight/open @te)) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {} {})) (inflight/delete-document @te @txid "doc-1" {}) (inflight/complete! @te @txid))) (it "will write the document to storage" (should-not (docs/load-document @db "doc-1"))) (it "will clear the document from the in-flight system" (should-not (inflight/is-registered? @te "doc-1"))) (it "will clear the transaction from the in-flight system" (should-not (inflight/is-txid? @te @txid)))) (describe "Two clients writing at the same time without specifying history" (with txid-1 (inflight/open @te)) (with txid-2 (inflight/open @te)) (before (inflight/add-document @te @txid-1 "doc-1" { :name "1"} {}) (inflight/add-document @te @txid-2 "doc-1" { :name "2"} {}) (inflight/complete! @te @txid-2) (inflight/complete! @te @txid-1)) (it "will write the first document" (should== {:name "1"} (docs/load-document @db "doc-1"))) (it "will generate a conflict document for the second write" (should== {:name "2"} (first (map :data (docs/conflicts @db)))))) (describe "Two clients writing at the same time, no history specified, second client deletes" (with txid-1 (inflight/open @te)) (with txid-2 (inflight/open @te)) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "original"} {}))) (inflight/add-document @te @txid-1 "doc-1" { :name "1"} {}) (inflight/delete-document @te @txid-2 "doc-1" {}) (inflight/complete! @te @txid-2) (inflight/complete! @te @txid-1)) (it "will write the first document" (should= { :name "1" } (docs/load-document @db "doc-1"))) (it "will generate a conflict document for the :delete" (should= :deleted (first (map :data (docs/conflicts @db)))))) (describe "A client writing with no history when a document already exists" (with txid (inflight/open @te)) (with old-history (v/next "boo" (v/new))) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "old-doc"} { :history @old-history})) (inflight/add-document @te @txid "doc-1" {:name "new-doc"} {}) (inflight/complete! @te @txid))) (it "will write the document to storage" (should== { :name "new-doc" } (docs/load-document @db "doc-1"))) (it "will clear the document from the in-flight system" (should-not (inflight/is-registered? @te "doc-1"))) (it "will be a descendent of the old document" (should (v/descends? (:history (docs/load-document-metadata @db "doc-1")) @old-history))) (it "will not generate a conflict" (should= 0 (count (docs/conflicts @db))))) (describe "Two clients both providing history trying to write a document" (with txid-1 (inflight/open @te)) (with txid-2 (inflight/open @te)) (with old-history (v/next "boo" (v/new))) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "old-doc"} { :history @old-history}))) (inflight/add-document @te @txid-1 "doc-1" { :name "1"} {}) (inflight/add-document @te @txid-2 "doc-1" { :name "2"} {}) (inflight/complete! @te @txid-2) (inflight/complete! @te @txid-1)) (it "will write the first document" (should== {:name "1"} (docs/load-document @db "doc-1"))) (it "will write the first document as a descendent of the orignal" (should (v/descends? (:history (docs/load-document-metadata @db "doc-1")) @old-history))) (it "will generate a conflict for the second document" (should== { :name "2"} (first (map :data (docs/conflicts @db))))) (it "will write the conflict as a descendent of the original" (should (v/descends? (first (map (comp :history :metadata) (docs/conflicts @db))) @old-history)))) (describe "A client providing an out of date history when writing" (with txid (inflight/open @te)) (with old-history (v/next "boo" (v/new))) (with supplied-history (v/next "fred" (v/new))) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "old-doc"} { :history @old-history}))) (inflight/add-document @te @txid "doc-1" { :name "1"} { :history @supplied-history }) (inflight/complete! @te @txid)) (it "will generate a conflict for that document" (should== { :name "1"} (first (map :data (docs/conflicts @db))))) (it "will write the conflict as a descendent of the specified history" (should (v/descends? (first (map (comp :history :metadata) (docs/conflicts @db))) @supplied-history)))) (describe "A client writing a valid document when a previous client has conflicted" (with tx1 (inflight/open @te)) (with tx2 (inflight/open @te)) (with old-history (v/next "boo" (v/new))) (with supplied-history (v/next "fred" (v/new))) (before (with-open [tx (s/ensure-transaction @db)] (s/commit! (docs/store-document tx "doc-1" {:name "old-doc"} { :history @old-history}))) (inflight/add-document @te @tx1 "doc-1" { :name "conflict"} { :history @supplied-history }) (inflight/add-document @te @tx2 "doc-1" { :name "fine"} {}) (inflight/complete! @te @tx1) (inflight/complete! @te @tx2)) (it "will still write the original conflicted document as conflicted" (should== { :name "conflict"} (first (map :data (docs/conflicts @db))))) (it "will write the second document to the underlying store" (should== {:name "fine"} (docs/load-document @db "doc-1")) )))
78e32c40e0591a1ef5ddb36249455c578e52856fe03ea071f08250653edcccaf
esl/MongooseIM
ejabberd_auth_jwt.erl
%%%---------------------------------------------------------------------- %%% File : ejabberd_auth_jwt.erl Author : < > %%% Purpose : Authentification with JSON Web Tokens Created : 02 Aug 2016 by < > %%% %%% MongooseIM , Copyright ( C ) 2016 CostaDigital %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License %%% along with this program; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA %%% %%%---------------------------------------------------------------------- -module(ejabberd_auth_jwt). -author(''). %% External exports -behaviour(mongoose_gen_auth). -export([start/1, stop/1, config_spec/0, authorize/1, check_password/4, check_password/6, does_user_exist/3, supports_sasl_module/2, supported_features/0 ]). %% Config spec callbacks -export([process_jwt_secret/1]). -include("mongoose.hrl"). -include("mongoose_config_spec.hrl"). %%%---------------------------------------------------------------------- %%% API %%%---------------------------------------------------------------------- -spec start(HostType :: mongooseim:host_type()) -> ok. start(HostType) -> JWTSecret = get_jwt_secret(HostType), persistent_term:put({?MODULE, HostType, jwt_secret}, JWTSecret), ok. -spec stop(HostType :: mongooseim:host_type()) -> ok. stop(_HostType) -> persistent_term:erase(jwt_secret), ok. -spec config_spec() -> mongoose_config_spec:config_section(). config_spec() -> #section{ items = #{<<"secret">> => jwt_secret_config_spec(), <<"algorithm">> => #option{type = binary, validate = {enum, algorithms()}}, <<"username_key">> => #option{type = atom, validate = non_empty} }, required = all }. jwt_secret_config_spec() -> #section{ items = #{<<"file">> => #option{type = string, validate = filename}, <<"env">> => #option{type = string, validate = non_empty}, <<"value">> => #option{type = binary}}, format_items = list, process = fun ?MODULE:process_jwt_secret/1 }. process_jwt_secret([V]) -> V. -spec supports_sasl_module(binary(), cyrsasl:sasl_module()) -> boolean(). supports_sasl_module(_, Module) -> Module =:= cyrsasl_plain. -spec authorize(mongoose_credentials:t()) -> {ok, mongoose_credentials:t()} | {error, any()}. authorize(Creds) -> ejabberd_auth:authorize_with_check_password(?MODULE, Creds). -spec check_password(HostType :: mongooseim:host_type(), LUser :: jid:luser(), LServer :: jid:lserver(), Password :: binary()) -> boolean(). check_password(HostType, LUser, LServer, Password) -> Key = case persistent_term:get({?MODULE, HostType, jwt_secret}) of Key1 when is_binary(Key1) -> Key1; {env, Var} -> list_to_binary(os:getenv(Var)) end, BinAlg = mongoose_config:get_opt([{auth, HostType}, jwt, algorithm]), Alg = binary_to_atom(jid:str_tolower(BinAlg), utf8), case jwerl:verify(Password, Alg, Key) of {ok, TokenData} -> UserKey = mongoose_config:get_opt([{auth,HostType}, jwt, username_key]), case maps:find(UserKey, TokenData) of {ok, LUser} -> Login username matches $ token_user_key in TokenData ?LOG_INFO(#{what => jwt_success_auth, text => <<"Successfully authenticated with JWT">>, user => LUser, server => LServer, token => TokenData}), true; {ok, ExpectedUser} -> ?LOG_WARNING(#{what => wrong_jwt_user, text => <<"JWT contains wrond user">>, expected_user => ExpectedUser, user => LUser, server => LServer}), false; error -> ?LOG_WARNING(#{what => missing_jwt_key, text => <<"Missing key {user_key} in JWT data">>, user_key => UserKey, token => TokenData, user => LUser, server => LServer}), false end; {error, Reason} -> ?LOG_WARNING(#{what => jwt_verification_failed, text => <<"Cannot verify JWT for user">>, reason => Reason, user => LUser, server => LServer}), false end. -spec check_password(HostType :: mongooseim:host_type(), LUser :: jid:luser(), LServer :: jid:lserver(), Password :: binary(), Digest :: binary(), DigestGen :: fun()) -> boolean(). check_password(HostType, LUser, LServer, Password, _Digest, _DigestGen) -> check_password(HostType, LUser, LServer, Password). -spec does_user_exist(HostType :: mongooseim:host_type(), LUser :: jid:luser(), LServer :: jid:lserver()) -> boolean() | {error, atom()}. does_user_exist(_HostType, _LUser, _LServer) -> true. -spec supported_features() -> [atom()]. supported_features() -> [dynamic_domains]. %%%---------------------------------------------------------------------- Internal helpers %%%---------------------------------------------------------------------- % A direct path to a file is read only once during startup, % a path in environment variable is read on every auth request. -spec get_jwt_secret(mongooseim:host_type()) -> binary() | {env, string()}. get_jwt_secret(HostType) -> case mongoose_config:get_opt([{auth, HostType}, jwt, secret]) of {value, JWTSecret} -> JWTSecret; {env, Env} -> {env, Env}; {file, Path} -> {ok, JWTSecret} = file:read_file(Path), JWTSecret end. algorithms() -> [<<"HS256">>, <<"RS256">>, <<"ES256">>, <<"HS386">>, <<"RS386">>, <<"ES386">>, <<"HS512">>, <<"RS512">>, <<"ES512">>].
null
https://raw.githubusercontent.com/esl/MongooseIM/b47f7872d33523841057c77626b5b5776d8a9ffb/src/auth/ejabberd_auth_jwt.erl
erlang
---------------------------------------------------------------------- File : ejabberd_auth_jwt.erl Purpose : Authentification with JSON Web Tokens This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software ---------------------------------------------------------------------- External exports Config spec callbacks ---------------------------------------------------------------------- API ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- A direct path to a file is read only once during startup, a path in environment variable is read on every auth request.
Author : < > Created : 02 Aug 2016 by < > MongooseIM , Copyright ( C ) 2016 CostaDigital modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA -module(ejabberd_auth_jwt). -author(''). -behaviour(mongoose_gen_auth). -export([start/1, stop/1, config_spec/0, authorize/1, check_password/4, check_password/6, does_user_exist/3, supports_sasl_module/2, supported_features/0 ]). -export([process_jwt_secret/1]). -include("mongoose.hrl"). -include("mongoose_config_spec.hrl"). -spec start(HostType :: mongooseim:host_type()) -> ok. start(HostType) -> JWTSecret = get_jwt_secret(HostType), persistent_term:put({?MODULE, HostType, jwt_secret}, JWTSecret), ok. -spec stop(HostType :: mongooseim:host_type()) -> ok. stop(_HostType) -> persistent_term:erase(jwt_secret), ok. -spec config_spec() -> mongoose_config_spec:config_section(). config_spec() -> #section{ items = #{<<"secret">> => jwt_secret_config_spec(), <<"algorithm">> => #option{type = binary, validate = {enum, algorithms()}}, <<"username_key">> => #option{type = atom, validate = non_empty} }, required = all }. jwt_secret_config_spec() -> #section{ items = #{<<"file">> => #option{type = string, validate = filename}, <<"env">> => #option{type = string, validate = non_empty}, <<"value">> => #option{type = binary}}, format_items = list, process = fun ?MODULE:process_jwt_secret/1 }. process_jwt_secret([V]) -> V. -spec supports_sasl_module(binary(), cyrsasl:sasl_module()) -> boolean(). supports_sasl_module(_, Module) -> Module =:= cyrsasl_plain. -spec authorize(mongoose_credentials:t()) -> {ok, mongoose_credentials:t()} | {error, any()}. authorize(Creds) -> ejabberd_auth:authorize_with_check_password(?MODULE, Creds). -spec check_password(HostType :: mongooseim:host_type(), LUser :: jid:luser(), LServer :: jid:lserver(), Password :: binary()) -> boolean(). check_password(HostType, LUser, LServer, Password) -> Key = case persistent_term:get({?MODULE, HostType, jwt_secret}) of Key1 when is_binary(Key1) -> Key1; {env, Var} -> list_to_binary(os:getenv(Var)) end, BinAlg = mongoose_config:get_opt([{auth, HostType}, jwt, algorithm]), Alg = binary_to_atom(jid:str_tolower(BinAlg), utf8), case jwerl:verify(Password, Alg, Key) of {ok, TokenData} -> UserKey = mongoose_config:get_opt([{auth,HostType}, jwt, username_key]), case maps:find(UserKey, TokenData) of {ok, LUser} -> Login username matches $ token_user_key in TokenData ?LOG_INFO(#{what => jwt_success_auth, text => <<"Successfully authenticated with JWT">>, user => LUser, server => LServer, token => TokenData}), true; {ok, ExpectedUser} -> ?LOG_WARNING(#{what => wrong_jwt_user, text => <<"JWT contains wrond user">>, expected_user => ExpectedUser, user => LUser, server => LServer}), false; error -> ?LOG_WARNING(#{what => missing_jwt_key, text => <<"Missing key {user_key} in JWT data">>, user_key => UserKey, token => TokenData, user => LUser, server => LServer}), false end; {error, Reason} -> ?LOG_WARNING(#{what => jwt_verification_failed, text => <<"Cannot verify JWT for user">>, reason => Reason, user => LUser, server => LServer}), false end. -spec check_password(HostType :: mongooseim:host_type(), LUser :: jid:luser(), LServer :: jid:lserver(), Password :: binary(), Digest :: binary(), DigestGen :: fun()) -> boolean(). check_password(HostType, LUser, LServer, Password, _Digest, _DigestGen) -> check_password(HostType, LUser, LServer, Password). -spec does_user_exist(HostType :: mongooseim:host_type(), LUser :: jid:luser(), LServer :: jid:lserver()) -> boolean() | {error, atom()}. does_user_exist(_HostType, _LUser, _LServer) -> true. -spec supported_features() -> [atom()]. supported_features() -> [dynamic_domains]. Internal helpers -spec get_jwt_secret(mongooseim:host_type()) -> binary() | {env, string()}. get_jwt_secret(HostType) -> case mongoose_config:get_opt([{auth, HostType}, jwt, secret]) of {value, JWTSecret} -> JWTSecret; {env, Env} -> {env, Env}; {file, Path} -> {ok, JWTSecret} = file:read_file(Path), JWTSecret end. algorithms() -> [<<"HS256">>, <<"RS256">>, <<"ES256">>, <<"HS386">>, <<"RS386">>, <<"ES386">>, <<"HS512">>, <<"RS512">>, <<"ES512">>].
c7f988dda857bb9f5464b4cb164a2235ddd52c2607079ef7abfd03a610622d9a
chetmurthy/pa_ppx
tsort0.ml
type 'a edges_t = {mutable edges: 'a list} type 'a hash_adj_t = ('a, 'a edges_t) Hashtbl.t let nodes edgl = let s = Hashtbl.create 23 in let nodes = ref [] in let chkadd n = if not(Hashtbl.mem s n) then begin Hashtbl.add s n (); nodes := n :: !nodes end in List.iter (fun (a,b) -> chkadd a; chkadd b) edgl; !nodes type 'a visit_type = PRE of 'a | POST of 'a | EDGE of 'a * 'a let dfs stf visitf nodes dadj stk stopt = let visited = Hashtbl.create 23 in let rec dfsrec st n = if not(Hashtbl.mem visited n) then begin Hashtbl.add visited n (); let edges = (Hashtbl.find dadj n).edges in let st' = stf st n in visitf st (PRE n); List.iter (fun n' -> visitf st' (EDGE(n,n')); dfsrec st' n') edges; visitf st (POST n) end in match stopt with Some nl -> List.iter (dfsrec stk) nl | None -> List.iter (fun n -> if not(Hashtbl.mem visited n) then dfsrec stk n) nodes let mkadj edgl = let dadj = Hashtbl.create 23 in let nodelist = nodes edgl in List.iter (fun n -> Hashtbl.add dadj n {edges=[]}) nodelist; let _ = List.iter (fun (a,b) -> let edges = Hashtbl.find dadj a in edges.edges <- b::edges.edges) edgl in dadj let cycles nodes dadj = let uf = Uf.mk nodes in let cyfind n stk = let rec cyrec = function h::_ as l when (Uf.find uf h)=(Uf.find uf n) -> l | h::t -> cyrec t | [] -> [] in cyrec (List.rev stk) in let () = dfs (fun stk n -> n::stk) (fun stk -> function (EDGE(n,n')) -> List.iter (Uf.union uf n') (cyfind n' stk) | _ -> ()) nodes dadj [] None in let cynodes = ref [] in let cyh = Hashtbl.create 23 in let () = List.iter (fun n -> let rep = (Uf.find uf n) in if rep<>n then begin (if not(Hashtbl.mem cyh rep) then (cynodes := rep :: !cynodes)); Hashtbl.add cyh rep n end) nodes in (uf,List.map (fun n -> (n,n::(Hashtbl.find_all cyh n))) !cynodes) let cyclic nodes dadj = let (_, cl) = cycles nodes dadj in cl <> [] let tsort nodes dadj = let (uf,cyclel) = cycles nodes dadj in let packets = ref [] in let pushed = Hashtbl.create 23 in let () = dfs (fun stk n -> if not(List.exists (fun m -> (Uf.find uf m)=(Uf.find uf n)) stk) then n::stk else stk) (fun stk -> function POST n -> let rep = (Uf.find uf n) in (if not(Hashtbl.mem pushed rep) && not(List.exists (fun m -> (Uf.find uf n)=(Uf.find uf m)) stk) then (packets := rep :: !packets; Hashtbl.add pushed rep ())) | _ -> ()) nodes dadj [] None in let packl = List.rev !packets in let cyh = Hashtbl.create 23 in let _ = List.iter (fun (_,l) -> List.iter (fun n -> Hashtbl.add cyh n l) l) cyclel in List.map (fun n -> try List.assoc n cyclel with Not_found -> [n]) packl let tclos nodes dadj nl = let l = ref [] in let _ = dfs (fun stk n -> n::stk) (fun stk -> function PRE n -> l := n :: !l | _ -> ()) nodes dadj [] (Some nl) in !l
null
https://raw.githubusercontent.com/chetmurthy/pa_ppx/7c662fcf4897c978ae8a5ea230af0e8b2fa5858b/util-lib/tsort0.ml
ocaml
type 'a edges_t = {mutable edges: 'a list} type 'a hash_adj_t = ('a, 'a edges_t) Hashtbl.t let nodes edgl = let s = Hashtbl.create 23 in let nodes = ref [] in let chkadd n = if not(Hashtbl.mem s n) then begin Hashtbl.add s n (); nodes := n :: !nodes end in List.iter (fun (a,b) -> chkadd a; chkadd b) edgl; !nodes type 'a visit_type = PRE of 'a | POST of 'a | EDGE of 'a * 'a let dfs stf visitf nodes dadj stk stopt = let visited = Hashtbl.create 23 in let rec dfsrec st n = if not(Hashtbl.mem visited n) then begin Hashtbl.add visited n (); let edges = (Hashtbl.find dadj n).edges in let st' = stf st n in visitf st (PRE n); List.iter (fun n' -> visitf st' (EDGE(n,n')); dfsrec st' n') edges; visitf st (POST n) end in match stopt with Some nl -> List.iter (dfsrec stk) nl | None -> List.iter (fun n -> if not(Hashtbl.mem visited n) then dfsrec stk n) nodes let mkadj edgl = let dadj = Hashtbl.create 23 in let nodelist = nodes edgl in List.iter (fun n -> Hashtbl.add dadj n {edges=[]}) nodelist; let _ = List.iter (fun (a,b) -> let edges = Hashtbl.find dadj a in edges.edges <- b::edges.edges) edgl in dadj let cycles nodes dadj = let uf = Uf.mk nodes in let cyfind n stk = let rec cyrec = function h::_ as l when (Uf.find uf h)=(Uf.find uf n) -> l | h::t -> cyrec t | [] -> [] in cyrec (List.rev stk) in let () = dfs (fun stk n -> n::stk) (fun stk -> function (EDGE(n,n')) -> List.iter (Uf.union uf n') (cyfind n' stk) | _ -> ()) nodes dadj [] None in let cynodes = ref [] in let cyh = Hashtbl.create 23 in let () = List.iter (fun n -> let rep = (Uf.find uf n) in if rep<>n then begin (if not(Hashtbl.mem cyh rep) then (cynodes := rep :: !cynodes)); Hashtbl.add cyh rep n end) nodes in (uf,List.map (fun n -> (n,n::(Hashtbl.find_all cyh n))) !cynodes) let cyclic nodes dadj = let (_, cl) = cycles nodes dadj in cl <> [] let tsort nodes dadj = let (uf,cyclel) = cycles nodes dadj in let packets = ref [] in let pushed = Hashtbl.create 23 in let () = dfs (fun stk n -> if not(List.exists (fun m -> (Uf.find uf m)=(Uf.find uf n)) stk) then n::stk else stk) (fun stk -> function POST n -> let rep = (Uf.find uf n) in (if not(Hashtbl.mem pushed rep) && not(List.exists (fun m -> (Uf.find uf n)=(Uf.find uf m)) stk) then (packets := rep :: !packets; Hashtbl.add pushed rep ())) | _ -> ()) nodes dadj [] None in let packl = List.rev !packets in let cyh = Hashtbl.create 23 in let _ = List.iter (fun (_,l) -> List.iter (fun n -> Hashtbl.add cyh n l) l) cyclel in List.map (fun n -> try List.assoc n cyclel with Not_found -> [n]) packl let tclos nodes dadj nl = let l = ref [] in let _ = dfs (fun stk n -> n::stk) (fun stk -> function PRE n -> l := n :: !l | _ -> ()) nodes dadj [] (Some nl) in !l
c334ef81d186ad646cc43a3c2ee51939d6b8f388bc89098696db4d3902e9e212
JustusAdam/language-haskell
Ticks.hs
SYNTAX TEST " source.haskell " " Ticks in various positions " x = Tt_'_.T_'__t' T'D_'.C T_'ttt_'t_' T'x T_x T_'_ ^^^^^^ ^^^^^^ entity.name.namespace.haskell ^^^^^^^ ^ ^^^^ constant.other.haskell -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid x = a `Tt_'_.T_'__t'` b `T'D_'.C` c `T_'ttt_'t_'` d `T'x` e `T_x` f `T_'_` -- ^^^^^^ ^^^^^^ entity.name.namespace.haskell ^^^^^^^ ^ ^^^^^^^^^^^ ^^^ ^^^ ^^^^ constant.other.haskell -- ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ - entity.name.namespace.haskell constant.other.haskell ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid x = 'T' '_' string.quoted.single.haskell -- ^^^^^^^ - invalid type T = Tt'.T_'__t' 'TD'.C 'Tt'T.T.T' T_'ttt_'t_' 'T T'x T_x T_'_ ^^^^ ^^^^ ^^^^^^^ entity.name.namespace.haskell -- ^ ^ ^ keyword.operator.promotion.haskell ^^^^^^^ ^ ^^ ^ ^^^ ^^^ ^^^^ storage.type.haskell -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid type T = a `Tt'.T_'__t'` b '`TD'.C` c '`Tt'T.T.T'` d `T_'ttt_'t_'` e '`T` f `T'x` g `T_x` h `T_'_` -- ^^^^ ^^^^ ^^^^^^^ entity.name.namespace.haskell -- ^ ^ ^ keyword.operator.promotion.haskell ^^^^^^^ ^ ^^ ^ ^^^ ^^^ ^^^^ storage.type.infix.haskell -- ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ - entity.name.namespace.haskell constant.other.haskell -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid type T = '(F, (B,G.C,'[A,B,C])) ^ ^ ^ ^ ^ ^ storage.type.haskell -- ^^ entity.name.namespace.haskell -- ^ ^ keyword.operator.promotion.haskell type T = '() '[] -- ^ ^ keyword.operator.promotion.haskell -- ^^ support.constant.unit.haskell ^^ support.constant.empty-list.haskell type T = T.'C -- ^^ - entity.name.namespace.haskell -- ^ storage.type.operator.infix.haskell -- ^ keyword.operator.promotion.haskell ^ ^ storage.type.haskell type T = '(:+) '(AC.:+) 'AC.:++ 'AC.++ -- ^ ^ ^ keyword.operator.promotion.haskell -- ^^^ ^^^ entity.name.namespace.haskell ^^ ^^ storage.type.operator.haskell -- ^^^ ^^ storage.type.operator.infix.haskell -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid type T = _t'_a' ^^^^^^ variable.other.generic-type.haskell -- ^^^^^^ - invalid type T = " a ' b ' c 'de' f'g''' 'a'" -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ string.quoted.double.haskell -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid type T = '_'_t_a' -- ^^^ invalid type T = 'T'x -- ^^^ invalid type T = '_' -- ^^^ invalid type T = '_' -- ^^^ invalid
null
https://raw.githubusercontent.com/JustusAdam/language-haskell/c9ee1b3ee166c44db9ce350920ba502fcc868245/test/tests/Ticks.hs
haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid ^^^^^^ ^^^^^^ entity.name.namespace.haskell ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ - entity.name.namespace.haskell constant.other.haskell ^^^^^^^ - invalid ^ ^ ^ keyword.operator.promotion.haskell ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid ^^^^ ^^^^ ^^^^^^^ entity.name.namespace.haskell ^ ^ ^ keyword.operator.promotion.haskell ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ - entity.name.namespace.haskell constant.other.haskell ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid ^^ entity.name.namespace.haskell ^ ^ keyword.operator.promotion.haskell ^ ^ keyword.operator.promotion.haskell ^^ support.constant.unit.haskell ^^ - entity.name.namespace.haskell ^ storage.type.operator.infix.haskell ^ keyword.operator.promotion.haskell ^ ^ ^ keyword.operator.promotion.haskell ^^^ ^^^ entity.name.namespace.haskell ^^^ ^^ storage.type.operator.infix.haskell ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid ^^^^^^ - invalid ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ string.quoted.double.haskell ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid ^^^ invalid ^^^ invalid ^^^ invalid ^^^ invalid
SYNTAX TEST " source.haskell " " Ticks in various positions " x = Tt_'_.T_'__t' T'D_'.C T_'ttt_'t_' T'x T_x T_'_ ^^^^^^ ^^^^^^ entity.name.namespace.haskell ^^^^^^^ ^ ^^^^ constant.other.haskell x = a `Tt_'_.T_'__t'` b `T'D_'.C` c `T_'ttt_'t_'` d `T'x` e `T_x` f `T_'_` ^^^^^^^ ^ ^^^^^^^^^^^ ^^^ ^^^ ^^^^ constant.other.haskell ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - invalid x = 'T' '_' string.quoted.single.haskell type T = Tt'.T_'__t' 'TD'.C 'Tt'T.T.T' T_'ttt_'t_' 'T T'x T_x T_'_ ^^^^ ^^^^ ^^^^^^^ entity.name.namespace.haskell ^^^^^^^ ^ ^^ ^ ^^^ ^^^ ^^^^ storage.type.haskell type T = a `Tt'.T_'__t'` b '`TD'.C` c '`Tt'T.T.T'` d `T_'ttt_'t_'` e '`T` f `T'x` g `T_x` h `T_'_` ^^^^^^^ ^ ^^ ^ ^^^ ^^^ ^^^^ storage.type.infix.haskell type T = '(F, (B,G.C,'[A,B,C])) ^ ^ ^ ^ ^ ^ storage.type.haskell type T = '() '[] ^^ support.constant.empty-list.haskell type T = T.'C ^ ^ storage.type.haskell type T = '(:+) '(AC.:+) 'AC.:++ 'AC.++ ^^ ^^ storage.type.operator.haskell type T = _t'_a' ^^^^^^ variable.other.generic-type.haskell type T = " a ' b ' c 'de' f'g''' 'a'" type T = '_'_t_a' type T = 'T'x type T = '_' type T = '_'
8c047e22c568a11aacb2f97d176c711fb56f166da7d12c145687d2e13044c0c3
dterei/SafeHaskellExamples
ExpDicts_Sub.hs
# LANGUAGE RoleAnnotations # # LANGUAGE IncoherentInstances # module ExpDicts_Sub ( MEQ(..), normMEQ ) where -- Requires we explicitly use representational type role MEQ representational class MEQ a where { meq :: a -> a -> Bool } instance MEQ Char where { meq _ _ = True } normMEQ :: MEQ a => a -> a -> Bool normMEQ a b = a `meq` b
null
https://raw.githubusercontent.com/dterei/SafeHaskellExamples/0f7bbb53cf1cbb8419ce3a4aa4258b84be30ffcc/roles2/ExpDicts_Sub.hs
haskell
Requires we explicitly use representational
# LANGUAGE RoleAnnotations # # LANGUAGE IncoherentInstances # module ExpDicts_Sub ( MEQ(..), normMEQ ) where type role MEQ representational class MEQ a where { meq :: a -> a -> Bool } instance MEQ Char where { meq _ _ = True } normMEQ :: MEQ a => a -> a -> Bool normMEQ a b = a `meq` b
4fc30a07d06cd0c5da4d2c91ca5765cbadcee676ea85a4ec8abdacf00dae48c0
conscell/hugs-android
Compiler.hs
# OPTIONS_GHC -cpp # ----------------------------------------------------------------------------- -- | -- Module : Distribution.Compiler Copyright : 2003 - 2004 -- Maintainer : < > -- Stability : alpha -- Portability : portable -- Haskell implementations . 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 . * Neither the name of nor the names of other 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 OWNER OR 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 . 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. * Neither the name of Isaac Jones nor the names of other 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 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. -} module Distribution.Compiler ( * implementations CompilerFlavor(..), Compiler(..), showCompilerId, compilerBinaryName, -- * Support for language extensions Opt, extensionsToFlags, extensionsToGHCFlag, extensionsToHugsFlag, extensionsToNHCFlag, extensionsToJHCFlag, ) where import Distribution.Version (Version(..), showVersion) import Language.Haskell.Extension (Extension(..)) import Data.List (nub) -- ------------------------------------------------------------ -- * Command Line Types and Exports -- ------------------------------------------------------------ data CompilerFlavor = GHC | NHC | Hugs | HBC | Helium | JHC | OtherCompiler String deriving (Show, Read, Eq) data Compiler = Compiler {compilerFlavor:: CompilerFlavor, compilerVersion :: Version, compilerPath :: FilePath, compilerPkgTool :: FilePath} deriving (Show, Read, Eq) showCompilerId :: Compiler -> String showCompilerId (Compiler f (Version [] _) _ _) = compilerBinaryName f showCompilerId (Compiler f v _ _) = compilerBinaryName f ++ '-': showVersion v compilerBinaryName :: CompilerFlavor -> String compilerBinaryName GHC = "ghc" FIX : uses for now compilerBinaryName Hugs = "ffihugs" compilerBinaryName JHC = "jhc" compilerBinaryName cmp = error $ "Unsupported compiler: " ++ (show cmp) -- ------------------------------------------------------------ -- * Extensions -- ------------------------------------------------------------ -- |For the given compiler, return the unsupported extensions, and the -- flags for the supported extensions. extensionsToFlags :: CompilerFlavor -> [ Extension ] -> ([Extension], [Opt]) extensionsToFlags GHC exts = extensionsToGHCFlag exts extensionsToFlags Hugs exts = extensionsToHugsFlag exts extensionsToFlags NHC exts = extensionsToNHCFlag exts extensionsToFlags JHC exts = extensionsToJHCFlag exts extensionsToFlags _ exts = (exts, []) -- |GHC: Return the unsupported extensions, and the flags for the supported extensions extensionsToGHCFlag :: [ Extension ] -> ([Extension], [Opt]) extensionsToGHCFlag l = splitEither $ nub $ map extensionToGHCFlag l where extensionToGHCFlag :: Extension -> Either Extension String extensionToGHCFlag OverlappingInstances = Right "-fallow-overlapping-instances" extensionToGHCFlag TypeSynonymInstances = Right "-fglasgow-exts" extensionToGHCFlag TemplateHaskell = Right "-fth" extensionToGHCFlag ForeignFunctionInterface = Right "-fffi" extensionToGHCFlag NoMonomorphismRestriction = Right "-fno-monomorphism-restriction" extensionToGHCFlag UndecidableInstances = Right "-fallow-undecidable-instances" extensionToGHCFlag IncoherentInstances = Right "-fallow-incoherent-instances" extensionToGHCFlag InlinePhase = Right "-finline-phase" extensionToGHCFlag ContextStack = Right "-fcontext-stack" extensionToGHCFlag Arrows = Right "-farrows" extensionToGHCFlag Generics = Right "-fgenerics" extensionToGHCFlag NoImplicitPrelude = Right "-fno-implicit-prelude" extensionToGHCFlag ImplicitParams = Right "-fimplicit-params" extensionToGHCFlag CPP = Right "-cpp" extensionToGHCFlag BangPatterns = Right "-fbang-patterns" extensionToGHCFlag RecursiveDo = Right "-fglasgow-exts" extensionToGHCFlag ParallelListComp = Right "-fglasgow-exts" extensionToGHCFlag MultiParamTypeClasses = Right "-fglasgow-exts" extensionToGHCFlag FunctionalDependencies = Right "-fglasgow-exts" extensionToGHCFlag Rank2Types = Right "-fglasgow-exts" extensionToGHCFlag RankNTypes = Right "-fglasgow-exts" extensionToGHCFlag PolymorphicComponents = Right "-fglasgow-exts" extensionToGHCFlag ExistentialQuantification = Right "-fglasgow-exts" extensionToGHCFlag ScopedTypeVariables = Right "-fglasgow-exts" extensionToGHCFlag FlexibleContexts = Right "-fglasgow-exts" extensionToGHCFlag FlexibleInstances = Right "-fglasgow-exts" extensionToGHCFlag EmptyDataDecls = Right "-fglasgow-exts" extensionToGHCFlag PatternGuards = Right "-fglasgow-exts" extensionToGHCFlag GeneralizedNewtypeDeriving = Right "-fglasgow-exts" extensionToGHCFlag e@ExtensibleRecords = Left e extensionToGHCFlag e@RestrictedTypeSynonyms = Left e extensionToGHCFlag e@HereDocuments = Left e extensionToGHCFlag e@NamedFieldPuns = Left e -- |NHC: Return the unsupported extensions, and the flags for the supported extensions extensionsToNHCFlag :: [ Extension ] -> ([Extension], [Opt]) extensionsToNHCFlag l = splitEither $ nub $ map extensionToNHCFlag l where NHC does n't enforce the monomorphism restriction at all . extensionToNHCFlag NoMonomorphismRestriction = Right "" extensionToNHCFlag ForeignFunctionInterface = Right "" extensionToNHCFlag ExistentialQuantification = Right "" extensionToNHCFlag EmptyDataDecls = Right "" extensionToNHCFlag NamedFieldPuns = Right "-puns" extensionToNHCFlag CPP = Right "-cpp" extensionToNHCFlag e = Left e -- |JHC: Return the unsupported extensions, and the flags for the supported extensions extensionsToJHCFlag :: [ Extension ] -> ([Extension], [Opt]) extensionsToJHCFlag l = (es, filter (not . null) rs) where (es,rs) = splitEither $ nub $ map extensionToJHCFlag l extensionToJHCFlag TypeSynonymInstances = Right "" extensionToJHCFlag ForeignFunctionInterface = Right "" extensionToJHCFlag NoImplicitPrelude = Right "--noprelude" extensionToJHCFlag CPP = Right "-fcpp" extensionToJHCFlag e = Left e -- |Hugs: Return the unsupported extensions, and the flags for the supported extensions extensionsToHugsFlag :: [ Extension ] -> ([Extension], [Opt]) extensionsToHugsFlag l = splitEither $ nub $ map extensionToHugsFlag l where extensionToHugsFlag OverlappingInstances = Right "+o" extensionToHugsFlag IncoherentInstances = Right "+oO" extensionToHugsFlag HereDocuments = Right "+H" extensionToHugsFlag TypeSynonymInstances = Right "-98" extensionToHugsFlag RecursiveDo = Right "-98" extensionToHugsFlag ParallelListComp = Right "-98" extensionToHugsFlag MultiParamTypeClasses = Right "-98" extensionToHugsFlag FunctionalDependencies = Right "-98" extensionToHugsFlag Rank2Types = Right "-98" extensionToHugsFlag PolymorphicComponents = Right "-98" extensionToHugsFlag ExistentialQuantification = Right "-98" extensionToHugsFlag ScopedTypeVariables = Right "-98" extensionToHugsFlag ImplicitParams = Right "-98" extensionToHugsFlag ExtensibleRecords = Right "-98" extensionToHugsFlag RestrictedTypeSynonyms = Right "-98" extensionToHugsFlag FlexibleContexts = Right "-98" extensionToHugsFlag FlexibleInstances = Right "-98" extensionToHugsFlag ForeignFunctionInterface = Right "" extensionToHugsFlag EmptyDataDecls = Right "" extensionToHugsFlag CPP = Right "" extensionToHugsFlag e = Left e splitEither :: [Either a b] -> ([a], [b]) splitEither l = ([a | Left a <- l], [b | Right b <- l]) type Opt = String -- ------------------------------------------------------------ -- * Testing -- ------------------------------------------------------------
null
https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/packages/Cabal/Distribution/Compiler.hs
haskell
--------------------------------------------------------------------------- | Module : Distribution.Compiler Stability : alpha Portability : portable * Support for language extensions ------------------------------------------------------------ * Command Line Types and Exports ------------------------------------------------------------ ------------------------------------------------------------ * Extensions ------------------------------------------------------------ |For the given compiler, return the unsupported extensions, and the flags for the supported extensions. |GHC: Return the unsupported extensions, and the flags for the supported extensions |NHC: Return the unsupported extensions, and the flags for the supported extensions |JHC: Return the unsupported extensions, and the flags for the supported extensions |Hugs: Return the unsupported extensions, and the flags for the supported extensions ------------------------------------------------------------ * Testing ------------------------------------------------------------
# OPTIONS_GHC -cpp # Copyright : 2003 - 2004 Maintainer : < > Haskell implementations . 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 . * Neither the name of nor the names of other 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 OWNER OR 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 . 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. * Neither the name of Isaac Jones nor the names of other 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 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. -} module Distribution.Compiler ( * implementations CompilerFlavor(..), Compiler(..), showCompilerId, compilerBinaryName, Opt, extensionsToFlags, extensionsToGHCFlag, extensionsToHugsFlag, extensionsToNHCFlag, extensionsToJHCFlag, ) where import Distribution.Version (Version(..), showVersion) import Language.Haskell.Extension (Extension(..)) import Data.List (nub) data CompilerFlavor = GHC | NHC | Hugs | HBC | Helium | JHC | OtherCompiler String deriving (Show, Read, Eq) data Compiler = Compiler {compilerFlavor:: CompilerFlavor, compilerVersion :: Version, compilerPath :: FilePath, compilerPkgTool :: FilePath} deriving (Show, Read, Eq) showCompilerId :: Compiler -> String showCompilerId (Compiler f (Version [] _) _ _) = compilerBinaryName f showCompilerId (Compiler f v _ _) = compilerBinaryName f ++ '-': showVersion v compilerBinaryName :: CompilerFlavor -> String compilerBinaryName GHC = "ghc" FIX : uses for now compilerBinaryName Hugs = "ffihugs" compilerBinaryName JHC = "jhc" compilerBinaryName cmp = error $ "Unsupported compiler: " ++ (show cmp) extensionsToFlags :: CompilerFlavor -> [ Extension ] -> ([Extension], [Opt]) extensionsToFlags GHC exts = extensionsToGHCFlag exts extensionsToFlags Hugs exts = extensionsToHugsFlag exts extensionsToFlags NHC exts = extensionsToNHCFlag exts extensionsToFlags JHC exts = extensionsToJHCFlag exts extensionsToFlags _ exts = (exts, []) extensionsToGHCFlag :: [ Extension ] -> ([Extension], [Opt]) extensionsToGHCFlag l = splitEither $ nub $ map extensionToGHCFlag l where extensionToGHCFlag :: Extension -> Either Extension String extensionToGHCFlag OverlappingInstances = Right "-fallow-overlapping-instances" extensionToGHCFlag TypeSynonymInstances = Right "-fglasgow-exts" extensionToGHCFlag TemplateHaskell = Right "-fth" extensionToGHCFlag ForeignFunctionInterface = Right "-fffi" extensionToGHCFlag NoMonomorphismRestriction = Right "-fno-monomorphism-restriction" extensionToGHCFlag UndecidableInstances = Right "-fallow-undecidable-instances" extensionToGHCFlag IncoherentInstances = Right "-fallow-incoherent-instances" extensionToGHCFlag InlinePhase = Right "-finline-phase" extensionToGHCFlag ContextStack = Right "-fcontext-stack" extensionToGHCFlag Arrows = Right "-farrows" extensionToGHCFlag Generics = Right "-fgenerics" extensionToGHCFlag NoImplicitPrelude = Right "-fno-implicit-prelude" extensionToGHCFlag ImplicitParams = Right "-fimplicit-params" extensionToGHCFlag CPP = Right "-cpp" extensionToGHCFlag BangPatterns = Right "-fbang-patterns" extensionToGHCFlag RecursiveDo = Right "-fglasgow-exts" extensionToGHCFlag ParallelListComp = Right "-fglasgow-exts" extensionToGHCFlag MultiParamTypeClasses = Right "-fglasgow-exts" extensionToGHCFlag FunctionalDependencies = Right "-fglasgow-exts" extensionToGHCFlag Rank2Types = Right "-fglasgow-exts" extensionToGHCFlag RankNTypes = Right "-fglasgow-exts" extensionToGHCFlag PolymorphicComponents = Right "-fglasgow-exts" extensionToGHCFlag ExistentialQuantification = Right "-fglasgow-exts" extensionToGHCFlag ScopedTypeVariables = Right "-fglasgow-exts" extensionToGHCFlag FlexibleContexts = Right "-fglasgow-exts" extensionToGHCFlag FlexibleInstances = Right "-fglasgow-exts" extensionToGHCFlag EmptyDataDecls = Right "-fglasgow-exts" extensionToGHCFlag PatternGuards = Right "-fglasgow-exts" extensionToGHCFlag GeneralizedNewtypeDeriving = Right "-fglasgow-exts" extensionToGHCFlag e@ExtensibleRecords = Left e extensionToGHCFlag e@RestrictedTypeSynonyms = Left e extensionToGHCFlag e@HereDocuments = Left e extensionToGHCFlag e@NamedFieldPuns = Left e extensionsToNHCFlag :: [ Extension ] -> ([Extension], [Opt]) extensionsToNHCFlag l = splitEither $ nub $ map extensionToNHCFlag l where NHC does n't enforce the monomorphism restriction at all . extensionToNHCFlag NoMonomorphismRestriction = Right "" extensionToNHCFlag ForeignFunctionInterface = Right "" extensionToNHCFlag ExistentialQuantification = Right "" extensionToNHCFlag EmptyDataDecls = Right "" extensionToNHCFlag NamedFieldPuns = Right "-puns" extensionToNHCFlag CPP = Right "-cpp" extensionToNHCFlag e = Left e extensionsToJHCFlag :: [ Extension ] -> ([Extension], [Opt]) extensionsToJHCFlag l = (es, filter (not . null) rs) where (es,rs) = splitEither $ nub $ map extensionToJHCFlag l extensionToJHCFlag TypeSynonymInstances = Right "" extensionToJHCFlag ForeignFunctionInterface = Right "" extensionToJHCFlag NoImplicitPrelude = Right "--noprelude" extensionToJHCFlag CPP = Right "-fcpp" extensionToJHCFlag e = Left e extensionsToHugsFlag :: [ Extension ] -> ([Extension], [Opt]) extensionsToHugsFlag l = splitEither $ nub $ map extensionToHugsFlag l where extensionToHugsFlag OverlappingInstances = Right "+o" extensionToHugsFlag IncoherentInstances = Right "+oO" extensionToHugsFlag HereDocuments = Right "+H" extensionToHugsFlag TypeSynonymInstances = Right "-98" extensionToHugsFlag RecursiveDo = Right "-98" extensionToHugsFlag ParallelListComp = Right "-98" extensionToHugsFlag MultiParamTypeClasses = Right "-98" extensionToHugsFlag FunctionalDependencies = Right "-98" extensionToHugsFlag Rank2Types = Right "-98" extensionToHugsFlag PolymorphicComponents = Right "-98" extensionToHugsFlag ExistentialQuantification = Right "-98" extensionToHugsFlag ScopedTypeVariables = Right "-98" extensionToHugsFlag ImplicitParams = Right "-98" extensionToHugsFlag ExtensibleRecords = Right "-98" extensionToHugsFlag RestrictedTypeSynonyms = Right "-98" extensionToHugsFlag FlexibleContexts = Right "-98" extensionToHugsFlag FlexibleInstances = Right "-98" extensionToHugsFlag ForeignFunctionInterface = Right "" extensionToHugsFlag EmptyDataDecls = Right "" extensionToHugsFlag CPP = Right "" extensionToHugsFlag e = Left e splitEither :: [Either a b] -> ([a], [b]) splitEither l = ([a | Left a <- l], [b | Right b <- l]) type Opt = String
08f9125470e03b18a5800d44bae64901013147cd981c9a7ebb921bf15ab5aa5b
jackfirth/racket-mock
util-doc.rkt
#lang sweet-exp racket/base provide args-tech behavior-tech define-behavior-tech define-mock-tech define-opaque-tech define-persistent-mock-examples define-stub-tech mock-examples mock-tech opaque-tech parameter-tech stub-tech for-label all-from-out mock racket/base racket/contract racket/list racket/file racket/function racket/set require scribble/example scribble/manual syntax/parse/define for-label mock racket/base racket/contract racket/list racket/file racket/function racket/set (define mock-doc '(lib "mock/main.scrbl")) (define-simple-macro (define-techs [key:str use-id:id def-id:id] ...) (begin (begin (define (def-id . pre-flow) (apply deftech #:key key pre-flow)) (define (use-id . pre-flow) (apply tech #:key key #:doc mock-doc pre-flow))) ...)) (define-techs ["behavior" behavior-tech define-behavior-tech] ["mock" mock-tech define-mock-tech] ["opaque" opaque-tech define-opaque-tech] ["stub" stub-tech define-stub-tech]) (define (args-tech . pre-flow) (apply tech #:doc '(lib "arguments/main.scrbl") #:key "arguments-struct" pre-flow)) (define (parameter-tech . pre-flow) (apply tech #:doc '(lib "scribblings/guide/guide.scrbl") pre-flow)) (define mock-requires '(mock racket/format racket/function racket/file racket/list racket/set)) (define (make-mock-eval) (make-base-eval #:lang 'racket/base (cons 'require mock-requires))) (define-syntax-rule (mock-examples example ...) (examples #:eval (make-mock-eval) example ...)) (define-syntax-rule (define-persistent-mock-examples id) (begin (define shared-eval (make-mock-eval)) (define-syntax-rule (id example (... ...)) (examples #:eval shared-eval example (... ...)))))
null
https://raw.githubusercontent.com/jackfirth/racket-mock/5e8e2a1dd125e5e437510c87dabf903d0ec25749/mock/private/util-doc.rkt
racket
#lang sweet-exp racket/base provide args-tech behavior-tech define-behavior-tech define-mock-tech define-opaque-tech define-persistent-mock-examples define-stub-tech mock-examples mock-tech opaque-tech parameter-tech stub-tech for-label all-from-out mock racket/base racket/contract racket/list racket/file racket/function racket/set require scribble/example scribble/manual syntax/parse/define for-label mock racket/base racket/contract racket/list racket/file racket/function racket/set (define mock-doc '(lib "mock/main.scrbl")) (define-simple-macro (define-techs [key:str use-id:id def-id:id] ...) (begin (begin (define (def-id . pre-flow) (apply deftech #:key key pre-flow)) (define (use-id . pre-flow) (apply tech #:key key #:doc mock-doc pre-flow))) ...)) (define-techs ["behavior" behavior-tech define-behavior-tech] ["mock" mock-tech define-mock-tech] ["opaque" opaque-tech define-opaque-tech] ["stub" stub-tech define-stub-tech]) (define (args-tech . pre-flow) (apply tech #:doc '(lib "arguments/main.scrbl") #:key "arguments-struct" pre-flow)) (define (parameter-tech . pre-flow) (apply tech #:doc '(lib "scribblings/guide/guide.scrbl") pre-flow)) (define mock-requires '(mock racket/format racket/function racket/file racket/list racket/set)) (define (make-mock-eval) (make-base-eval #:lang 'racket/base (cons 'require mock-requires))) (define-syntax-rule (mock-examples example ...) (examples #:eval (make-mock-eval) example ...)) (define-syntax-rule (define-persistent-mock-examples id) (begin (define shared-eval (make-mock-eval)) (define-syntax-rule (id example (... ...)) (examples #:eval shared-eval example (... ...)))))
db3699c33437b6f21cbee754ac7b21953aeccafd555fb0bdc54ab1d8040d9c02
alaricsp/chicken-scheme
locative-stress-test.scm
locative-stress-test.scm - by (declare (usual-integrations)) ;(set-gc-report! #t) (require-extension srfi-1) #> long *ptrs[10]; if(!C_in_stackp((C_word)o##n ) & & ! C_in_fromspacep((C_word)o##n ) ) C_dbg_hook(0 ) ; #define check(n) long fill_10(long i, long *o0, long *o1, long *o2, long *o3, long *o4, long *o5, long *o6, long *o7, long *o8, long *o9) { check(0) check(1) check(2) check(3) check(4) check(5) check(6) check(7) check(8) check(9) *o0=*o1=*o2=*o3=*o4=*o5=*o6=*o7=*o8=*o9=i; return i; } <# (define fill-10! (foreign-lambda long "fill_10" long (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long))) (let* ((el 1) (expected (make-list 10 el))) (let loop ((i (string->number (optional (command-line-arguments) "100000")))) (unless (eq? i 0) (let-location ((o0 long) (o1 long) (o2 long) (o3 long) (o4 long) (o5 long) (o6 long) (o7 long) (o8 long) (o9 long)) (fill-10! el #$o0 #$o1 #$o2 #$o3 #$o4 #$o5 #$o6 #$o7 #$o8 #$o9) (let ((result (list o0 o1 o2 o3 o4 o5 o6 o7 o8 o9))) (if (not (equal? result expected)) (error "strange values: " result) (loop (fx- i 1))))))))
null
https://raw.githubusercontent.com/alaricsp/chicken-scheme/1eb14684c26b7c2250ca9b944c6b671cb62cafbc/tests/locative-stress-test.scm
scheme
(set-gc-report! #t)
locative-stress-test.scm - by (declare (usual-integrations)) (require-extension srfi-1) #> #define check(n) long fill_10(long i, long *o0, long *o1, long *o2, long *o3, long *o4, long *o5, long *o6, long *o7, long *o8, long *o9) { check(0) check(1) check(2) check(3) check(4) check(5) check(6) check(7) check(8) check(9) } <# (define fill-10! (foreign-lambda long "fill_10" long (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long) (c-pointer long))) (let* ((el 1) (expected (make-list 10 el))) (let loop ((i (string->number (optional (command-line-arguments) "100000")))) (unless (eq? i 0) (let-location ((o0 long) (o1 long) (o2 long) (o3 long) (o4 long) (o5 long) (o6 long) (o7 long) (o8 long) (o9 long)) (fill-10! el #$o0 #$o1 #$o2 #$o3 #$o4 #$o5 #$o6 #$o7 #$o8 #$o9) (let ((result (list o0 o1 o2 o3 o4 o5 o6 o7 o8 o9))) (if (not (equal? result expected)) (error "strange values: " result) (loop (fx- i 1))))))))
8b7330df5fa493244f10d2ad9ab5a7ca27f44a850fc8ab31ab2d13ddef9423d8
theHamsta/petalisp-cuda
petalisp.lisp
(defpackage petalisp-cuda.utils.petalisp (:use :cl :petalisp.ir :petalisp) (:export :pass-as-scalar-argument-p :scalar-buffer-p)) (in-package petalisp-cuda.utils.petalisp) (defun scalar-buffer-p (buffer) (= 0 (shape-rank (buffer-shape buffer)))) (defun pass-as-scalar-argument-p (buffer) (and (scalar-buffer-p buffer) (arrayp (buffer-storage buffer)) ; we pass the arguments with a pointer array right now and all are types are 8 bytes or smaller (= 8 (cffi:foreign-type-size :pointer))))
null
https://raw.githubusercontent.com/theHamsta/petalisp-cuda/12b9ee426e14edf492d862d5bd2dbec18ec427c6/src/utils/petalisp.lisp
lisp
we pass the arguments with a pointer array right now
(defpackage petalisp-cuda.utils.petalisp (:use :cl :petalisp.ir :petalisp) (:export :pass-as-scalar-argument-p :scalar-buffer-p)) (in-package petalisp-cuda.utils.petalisp) (defun scalar-buffer-p (buffer) (= 0 (shape-rank (buffer-shape buffer)))) (defun pass-as-scalar-argument-p (buffer) (and (scalar-buffer-p buffer) (arrayp (buffer-storage buffer)) and all are types are 8 bytes or smaller (= 8 (cffi:foreign-type-size :pointer))))
ffffd6d5a86f74a88bc2cfa38213eeec4cde9c2ecf3fde9a900dd51b490bdd5e
thierry-martinez/clangml
special_bindings.ml
[%%metapackage "metapp"] [%%metadir "config/.clangml_config.objs/byte"] [%%metaload "config/clangml_config.cmxs"] open Clang__bindings [%%meta Metapp.Stri.of_list ( if Clangml_config.version >= { major = 7; minor = 0; subminor = 0 } then [%str external get_token : cxtranslationunit -> cxsourcelocation -> cxtoken option = "clang_getToken_wrapper" (** Get the raw lexical token starting with the given location. *)] else [])] external tokenize : cxtranslationunit -> cxsourcerange -> cxtoken array = "clang_tokenize_wrapper" (** Tokenize the source code described by the given range into raw lexical tokens. *)
null
https://raw.githubusercontent.com/thierry-martinez/clangml/d9501e74ea48d066eeba147fdcf9aeb3408c778f/clangml/special_bindings.ml
ocaml
* Get the raw lexical token starting with the given location. * Tokenize the source code described by the given range into raw lexical tokens.
[%%metapackage "metapp"] [%%metadir "config/.clangml_config.objs/byte"] [%%metaload "config/clangml_config.cmxs"] open Clang__bindings [%%meta Metapp.Stri.of_list ( if Clangml_config.version >= { major = 7; minor = 0; subminor = 0 } then [%str external get_token : cxtranslationunit -> cxsourcelocation -> cxtoken option = "clang_getToken_wrapper" else [])] external tokenize : cxtranslationunit -> cxsourcerange -> cxtoken array = "clang_tokenize_wrapper"
8c1b9b954f6e87e7c31af96b5120b653b3bd2131c6aa82edba6da6e37225cb27
namin/clpsmt-miniKanren
full-interp-extended-tests.scm
(load "mk.scm") (load "z3-driver.scm") (load "test-check.scm") (load "full-interp-extended.scm") (test "evalo-simple-let-a" (run* (q) (evalo '(let ((foo (+ 1 2))) (* foo foo)) q)) '(9)) symbolic execution example from slide 7 of slides on symbolic execution ( contains contents from ;;; slides) ;;; ;;; -SymExec.pdf 1 . int a = α , b = β , c = γ 2 . // symbolic 3 . int x = 0 , y = 0 , z = 0 ; 4 . if ( a ) { 5 . x = -2 ; 6 . } 7 . if ( b < 5 ) { 8 . if ( ! a & & c ) { y = 1 ; } 9 . z = 2 ; 10 . } 11 . assert(x+y+z!=3 ) (test "evalo-symbolic-execution-a" (run 1 (q) (fresh (alpha beta gamma) (== (list alpha beta gamma) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good 'bad))))))) 'bad))) '((0 4 1))) (test "evalo-symbolic-execution-b" (run 8 (q) (fresh (alpha beta gamma) (== (list alpha beta gamma) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good 'bad))))))) 'bad))) '((0 4 1) (0 0 -1) (0 -1 -2) (0 -2 -3) (0 -3 -4) (0 -4 -5) (0 -5 -6) (0 -6 -7))) (test "evalo-symbolic-execution-c" (run 8 (q) (fresh (alpha beta gamma vals) (== (list alpha beta gamma vals) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))))) `(bad . ,vals)))) '((0 4 1 (0 1 2)) (0 0 -1 (0 1 2)) (0 -1 -2 (0 1 2)) (0 -2 -3 (0 1 2)) (0 -3 -4 (0 1 2)) (0 -4 -5 (0 1 2)) (0 -5 -6 (0 1 2)) (0 -6 -7 (0 1 2)))) (test "evalo-symbolic-execution-d" (run 1 (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,beta))) (== (list alpha beta gamma vals) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))))) `(bad . ,vals)))) '((0 1 1 (0 1 2)))) (test "evalo-symbolic-execution-e" (run 1 (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,alpha))) (== (list alpha beta gamma vals) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))))) `(bad . ,vals)))) '()) ;;; (test "evalo-symbolic-execution-f" (run 8 (q) (fresh (alpha beta gamma vals) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '((0 4 1 (0 1 2)) (0 0 -1 (0 1 2)) (0 -1 -2 (0 1 2)) (0 -2 -3 (0 1 2)) (0 -3 -4 (0 1 2)) (0 -4 -5 (0 1 2)) (0 -5 -6 (0 1 2)) (0 -6 -7 (0 1 2)))) (test "evalo-symbolic-execution-g" (run 8 (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,beta))) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '((0 1 1 (0 1 2)) (0 -1 -1 (0 1 2)) (0 -2 -2 (0 1 2)) (0 -3 -3 (0 1 2)) (0 -4 -4 (0 1 2)) (0 -5 -5 (0 1 2)) (0 -6 -6 (0 1 2)) (0 2 -7 (0 1 2)))) (test "evalo-symbolic-execution-h" (run* (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,alpha))) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '()) ;;; (test "evalo-symbolic-execution-i" (run 8 (q) (fresh (alpha beta gamma vals) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) ((lambda (x y z) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z))) ;; x (if (!= a 0) -2 0) ;; y (if (and (< b 5) (= a 0) (!= c 0)) 1 0) ;; z (if (< b 5) 2 0))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '((0 4 1 (0 1 2)) (0 0 -1 (0 1 2)) (0 -1 -2 (0 1 2)) (0 -2 -3 (0 1 2)) (0 -3 -4 (0 1 2)) (0 -4 -5 (0 1 2)) (0 -5 -6 (0 1 2)) (0 -6 -7 (0 1 2)))) (test "evalo-symbolic-execution-j" (run 8 (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,beta))) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) ((lambda (x y z) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z))) ;; x (if (!= a 0) -2 0) ;; y (if (and (< b 5) (= a 0) (!= c 0)) 1 0) ;; z (if (< b 5) 2 0))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '((0 1 1 (0 1 2)) (0 -1 -1 (0 1 2)) (0 -2 -2 (0 1 2)) (0 -3 -3 (0 1 2)) (0 -4 -4 (0 1 2)) (0 -5 -5 (0 1 2)) (0 -6 -6 (0 1 2)) (0 2 -7 (0 1 2)))) (test "evalo-symbolic-execution-k" (run* (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,alpha))) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) ((lambda (x y z) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z))) ;; x (if (!= a 0) -2 0) ;; y (if (and (< b 5) (= a 0) (!= c 0)) 1 0) ;; z (if (< b 5) 2 0))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '()) #!eof ;;; old tests: (test "evalo-1" (run* (q) (evalo '(+ 1 2) q)) '(3)) (test "evalo-backwards-1" (run* (q) (evalo `(+ 0 ',q) 3)) '(3)) (test "evalo-bop-1" (run* (q) (evalo `((lambda (n) (< n 0)) 0) q)) '(#f)) (test "evalo-2" (run* (q) (evalo `(((lambda (f) (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (f (- n 1))))))) (lambda (x) 1)) 2) q)) '(2)) (test "evalo-fac-6" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac 6)) q)) '(720)) ;; slowish (test "evalo-fac-9" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac 9)) q)) '(362880)) (test "evalo-backwards-fac-6" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac ,q)) 720)) '(6)) ;; remember the quote! (test "evalo-backwards-fac-quoted-6" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac ',q)) 720)) '(6)) ;; slowish (test "evalo-backwards-fac-9" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac ,q)) 362880)) '(9)) ;; remember the quote! (test "evalo-backwards-fac-quoted-9" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac ',q)) 362880)) '(9)) ;; slowish (test "evalo-fac-table" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) q)) '((1 1 2 6))) (test "evalo-fac-synthesis-hole-0" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) ',q (* n (fac (- n 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6))) '(1)) (test "evalo-fac-synthesis-hole-1" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (,q (- n 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6))) '(fac)) ;; takes a while (test "evalo-fac-synthesis-hole-1-reversed-examples" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (,q (- n 1)))))))) (list (fac 3) (fac 2) (fac 1) (fac 0))) '(6 2 1 1))) '(fac)) (test "evalo-fac-synthesis-hole-2" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- ,q 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6))) '(n)) (test "evalo-fac-synthesis-hole-3" (run 1 (q) (fresh (r s) (== (list r s) q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- ,r ,s)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6)))) '((n 1))) slow , even with the ' symbolo ' constraint on ' q ' (test "evalo-fac-synthesis-hole-4" (run 1 (q) (symbolo q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (,q n 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6))) '(-)) (test "evalo-division-using-multiplication-0" (run* (q) (evalo `(* 3 ',q) 6)) '(2)) (test "evalo-division-using-multiplication-1" (run* (q) (evalo `(* 4 ',q) 6)) '()) (test "evalo-division-using-multiplication-2" (run* (q) (evalo `(* 3 ',q) 18)) '(6)) (test "evalo-many-0" (run* (q) (fresh (x y) (evalo `(* ',x ',y) 6) (== q (list x y)))) '(((6 1) (2 3) (1 6) (-3 -2) (-2 -3) (-1 -6) (-6 -1) (3 2)))) (test "many-1" (run* (q) (fresh (x y) (evalo `(+ (* ',x ',y) (* ',x ',y)) 6) (== q (list x y)))) '((3 1) (1 3) (-1 -3) (-3 -1))) (test "many-2" (run* (q) (fresh (x y) (evalo `(* (* ',x ',y) 2) 6) (== q (list x y)))) '((3 1) (-1 -3) (-3 -1) (1 3))) ;;; time to get interesting!
null
https://raw.githubusercontent.com/namin/clpsmt-miniKanren/4fa74fb973c95b7913f0e0239852f18a23073ccc/full-interp-extended-tests.scm
scheme
slides) -SymExec.pdf } x y z x y z x y z old tests: slowish remember the quote! slowish remember the quote! slowish takes a while time to get interesting!
(load "mk.scm") (load "z3-driver.scm") (load "test-check.scm") (load "full-interp-extended.scm") (test "evalo-simple-let-a" (run* (q) (evalo '(let ((foo (+ 1 2))) (* foo foo)) q)) '(9)) symbolic execution example from slide 7 of slides on symbolic execution ( contains contents from 1 . int a = α , b = β , c = γ 2 . // symbolic 4 . if ( a ) { 6 . } 7 . if ( b < 5 ) { 10 . } 11 . assert(x+y+z!=3 ) (test "evalo-symbolic-execution-a" (run 1 (q) (fresh (alpha beta gamma) (== (list alpha beta gamma) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good 'bad))))))) 'bad))) '((0 4 1))) (test "evalo-symbolic-execution-b" (run 8 (q) (fresh (alpha beta gamma) (== (list alpha beta gamma) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good 'bad))))))) 'bad))) '((0 4 1) (0 0 -1) (0 -1 -2) (0 -2 -3) (0 -3 -4) (0 -4 -5) (0 -5 -6) (0 -6 -7))) (test "evalo-symbolic-execution-c" (run 8 (q) (fresh (alpha beta gamma vals) (== (list alpha beta gamma vals) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))))) `(bad . ,vals)))) '((0 4 1 (0 1 2)) (0 0 -1 (0 1 2)) (0 -1 -2 (0 1 2)) (0 -2 -3 (0 1 2)) (0 -3 -4 (0 1 2)) (0 -4 -5 (0 1 2)) (0 -5 -6 (0 1 2)) (0 -6 -7 (0 1 2)))) (test "evalo-symbolic-execution-d" (run 1 (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,beta))) (== (list alpha beta gamma vals) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))))) `(bad . ,vals)))) '((0 1 1 (0 1 2)))) (test "evalo-symbolic-execution-e" (run 1 (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,alpha))) (== (list alpha beta gamma vals) q) (evalo `(let ((a ',alpha)) (let ((b ',beta)) (let ((c ',gamma)) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))))) `(bad . ,vals)))) '()) (test "evalo-symbolic-execution-f" (run 8 (q) (fresh (alpha beta gamma vals) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '((0 4 1 (0 1 2)) (0 0 -1 (0 1 2)) (0 -1 -2 (0 1 2)) (0 -2 -3 (0 1 2)) (0 -3 -4 (0 1 2)) (0 -4 -5 (0 1 2)) (0 -5 -6 (0 1 2)) (0 -6 -7 (0 1 2)))) (test "evalo-symbolic-execution-g" (run 8 (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,beta))) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '((0 1 1 (0 1 2)) (0 -1 -1 (0 1 2)) (0 -2 -2 (0 1 2)) (0 -3 -3 (0 1 2)) (0 -4 -4 (0 1 2)) (0 -5 -5 (0 1 2)) (0 -6 -6 (0 1 2)) (0 2 -7 (0 1 2)))) (test "evalo-symbolic-execution-h" (run* (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,alpha))) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) (let ((x (if (!= a 0) -2 0))) (let ((y (if (and (< b 5) (= a 0) (!= c 0)) 1 0))) (let ((z (if (< b 5) 2 0))) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z)))))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '()) (test "evalo-symbolic-execution-i" (run 8 (q) (fresh (alpha beta gamma vals) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) ((lambda (x y z) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z))) (if (!= a 0) -2 0) (if (and (< b 5) (= a 0) (!= c 0)) 1 0) (if (< b 5) 2 0))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '((0 4 1 (0 1 2)) (0 0 -1 (0 1 2)) (0 -1 -2 (0 1 2)) (0 -2 -3 (0 1 2)) (0 -3 -4 (0 1 2)) (0 -4 -5 (0 1 2)) (0 -5 -6 (0 1 2)) (0 -6 -7 (0 1 2)))) (test "evalo-symbolic-execution-j" (run 8 (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,beta))) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) ((lambda (x y z) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z))) (if (!= a 0) -2 0) (if (and (< b 5) (= a 0) (!= c 0)) 1 0) (if (< b 5) 2 0))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '((0 1 1 (0 1 2)) (0 -1 -1 (0 1 2)) (0 -2 -2 (0 1 2)) (0 -3 -3 (0 1 2)) (0 -4 -4 (0 1 2)) (0 -5 -5 (0 1 2)) (0 -6 -6 (0 1 2)) (0 2 -7 (0 1 2)))) (test "evalo-symbolic-execution-k" (run* (q) (fresh (alpha beta gamma vals) (z/assert `(not (= 0 ,alpha))) (== (list alpha beta gamma vals) q) (evalo `((lambda (a b c) ((lambda (x y z) (if (!= (+ x (+ y z)) 3) 'good (list 'bad x y z))) (if (!= a 0) -2 0) (if (and (< b 5) (= a 0) (!= c 0)) 1 0) (if (< b 5) 2 0))) ',alpha ',beta ',gamma) `(bad . ,vals)))) '()) #!eof (test "evalo-1" (run* (q) (evalo '(+ 1 2) q)) '(3)) (test "evalo-backwards-1" (run* (q) (evalo `(+ 0 ',q) 3)) '(3)) (test "evalo-bop-1" (run* (q) (evalo `((lambda (n) (< n 0)) 0) q)) '(#f)) (test "evalo-2" (run* (q) (evalo `(((lambda (f) (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (f (- n 1))))))) (lambda (x) 1)) 2) q)) '(2)) (test "evalo-fac-6" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac 6)) q)) '(720)) (test "evalo-fac-9" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac 9)) q)) '(362880)) (test "evalo-backwards-fac-6" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac ,q)) 720)) '(6)) (test "evalo-backwards-fac-quoted-6" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac ',q)) 720)) '(6)) (test "evalo-backwards-fac-9" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac ,q)) 362880)) '(9)) (test "evalo-backwards-fac-quoted-9" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (fac ',q)) 362880)) '(9)) (test "evalo-fac-table" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- n 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) q)) '((1 1 2 6))) (test "evalo-fac-synthesis-hole-0" (run* (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) ',q (* n (fac (- n 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6))) '(1)) (test "evalo-fac-synthesis-hole-1" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (,q (- n 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6))) '(fac)) (test "evalo-fac-synthesis-hole-1-reversed-examples" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (,q (- n 1)))))))) (list (fac 3) (fac 2) (fac 1) (fac 0))) '(6 2 1 1))) '(fac)) (test "evalo-fac-synthesis-hole-2" (run 1 (q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- ,q 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6))) '(n)) (test "evalo-fac-synthesis-hole-3" (run 1 (q) (fresh (r s) (== (list r s) q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (- ,r ,s)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6)))) '((n 1))) slow , even with the ' symbolo ' constraint on ' q ' (test "evalo-fac-synthesis-hole-4" (run 1 (q) (symbolo q) (evalo `(letrec ((fac (lambda (n) (if (< n 0) #f (if (= n 0) 1 (* n (fac (,q n 1)))))))) (list (fac 0) (fac 1) (fac 2) (fac 3))) '(1 1 2 6))) '(-)) (test "evalo-division-using-multiplication-0" (run* (q) (evalo `(* 3 ',q) 6)) '(2)) (test "evalo-division-using-multiplication-1" (run* (q) (evalo `(* 4 ',q) 6)) '()) (test "evalo-division-using-multiplication-2" (run* (q) (evalo `(* 3 ',q) 18)) '(6)) (test "evalo-many-0" (run* (q) (fresh (x y) (evalo `(* ',x ',y) 6) (== q (list x y)))) '(((6 1) (2 3) (1 6) (-3 -2) (-2 -3) (-1 -6) (-6 -1) (3 2)))) (test "many-1" (run* (q) (fresh (x y) (evalo `(+ (* ',x ',y) (* ',x ',y)) 6) (== q (list x y)))) '((3 1) (1 3) (-1 -3) (-3 -1))) (test "many-2" (run* (q) (fresh (x y) (evalo `(* (* ',x ',y) 2) 6) (== q (list x y)))) '((3 1) (-1 -3) (-3 -1) (1 3)))
f50384317c02aae8cb23550c0f975d3a3f7884e822464940362d5e041e482773
reasonml/reason
utils.ml
let const c = fun _ -> c let group_assoc l = let cons k v acc = (k, List.rev v) :: acc in let rec aux k v vs acc = function | [] -> List.rev (cons k (v :: vs) acc) | (k', v') :: xs when compare k k' = 0 -> if compare v v' = 0 then aux k v vs acc xs else aux k v' (v :: vs) acc xs | (k', v') :: xs -> aux k' v' [] (cons k (v :: vs) acc) xs in match List.sort compare l with | [] -> [] | (k, v) :: xs -> aux k v [] [] xs let rec list_last = function | [x] -> x | _ :: xs -> list_last xs | [] -> invalid_arg "list_last" let pp_list f ppf = function | [] -> Format.fprintf ppf "[]" | x :: xs -> Format.fprintf ppf "[%a" f x; List.iter (Format.fprintf ppf "; %a" f) xs; Format.fprintf ppf "]" let rec list_filter_map f = function | [] -> [] | x :: xs -> match f x with | None -> list_filter_map f xs | Some x' -> x' :: list_filter_map f xs module Cost : sig type t = private int val zero : t val infinite : t val compare : t -> t -> int val add : t -> t -> t val of_int : int -> t val to_int : t -> int val is_infinite : t -> bool val arg_min : ('a -> t) -> 'a -> 'a -> 'a end = struct type t = int let zero = 0 let infinite = max_int let compare : t -> t -> int = compare let add t1 t2 = let result = t1 + t2 in if result < 0 then infinite else result let of_int x = if x < 0 then invalid_arg "Cost.of_int: cost must be positive" else x let to_int x = x let is_infinite x = x = infinite let arg_min f a b = if compare (f a) (f b) <= 0 then a else b end
null
https://raw.githubusercontent.com/reasonml/reason/daa11255cb4716ce1c370925251021bd6e3bd974/src/menhir-recover/utils.ml
ocaml
let const c = fun _ -> c let group_assoc l = let cons k v acc = (k, List.rev v) :: acc in let rec aux k v vs acc = function | [] -> List.rev (cons k (v :: vs) acc) | (k', v') :: xs when compare k k' = 0 -> if compare v v' = 0 then aux k v vs acc xs else aux k v' (v :: vs) acc xs | (k', v') :: xs -> aux k' v' [] (cons k (v :: vs) acc) xs in match List.sort compare l with | [] -> [] | (k, v) :: xs -> aux k v [] [] xs let rec list_last = function | [x] -> x | _ :: xs -> list_last xs | [] -> invalid_arg "list_last" let pp_list f ppf = function | [] -> Format.fprintf ppf "[]" | x :: xs -> Format.fprintf ppf "[%a" f x; List.iter (Format.fprintf ppf "; %a" f) xs; Format.fprintf ppf "]" let rec list_filter_map f = function | [] -> [] | x :: xs -> match f x with | None -> list_filter_map f xs | Some x' -> x' :: list_filter_map f xs module Cost : sig type t = private int val zero : t val infinite : t val compare : t -> t -> int val add : t -> t -> t val of_int : int -> t val to_int : t -> int val is_infinite : t -> bool val arg_min : ('a -> t) -> 'a -> 'a -> 'a end = struct type t = int let zero = 0 let infinite = max_int let compare : t -> t -> int = compare let add t1 t2 = let result = t1 + t2 in if result < 0 then infinite else result let of_int x = if x < 0 then invalid_arg "Cost.of_int: cost must be positive" else x let to_int x = x let is_infinite x = x = infinite let arg_min f a b = if compare (f a) (f b) <= 0 then a else b end
ece76d617a8bc4e3d4c63d3b0dd51635705f94bb26b2c1bc6d6a62e2218d8ff2
synrc/nitro
element_date.erl
-module(element_date). -author('Vladimir Galunshchikov'). -include_lib("nitro/include/nitro.hrl"). -include_lib("nitro/include/event.hrl"). -compile(export_all). render_element(Record) when Record#date.show_if==false -> [<<>>]; render_element(Record) -> Id = case Record#date.postback of [] -> Record#date.id; Postback -> ID = case Record#date.id of [] -> nitro:temp_id(); I -> I end, nitro:wire(#event{type=click, postback=Postback, target=ID, source=Record#date.source, delegate=Record#date.delegate }), ID end, List = [ %global {<<"accesskey">>, Record#date.accesskey}, {<<"class">>, Record#date.class}, {<<"contenteditable">>, case Record#date.contenteditable of true -> "true"; false -> "false"; _ -> [] end}, {<<"contextmenu">>, Record#date.contextmenu}, {<<"dir">>, case Record#date.dir of "ltr" -> "ltr"; "rtl" -> "rtl"; "auto" -> "auto"; _ -> [] end}, {<<"draggable">>, case Record#date.draggable of true -> "true"; false -> "false"; _ -> [] end}, {<<"dropzone">>, Record#date.dropzone}, {<<"hidden">>, case Record#date.hidden of "hidden" -> "hidden"; _ -> [] end}, {<<"id">>, Id}, {<<"lang">>, Record#date.lang}, {<<"spellcheck">>, case Record#date.spellcheck of true -> "true"; false -> "false"; _ -> [] end}, {<<"style">>, Record#date.style}, {<<"tabindex">>, Record#date.tabindex}, {<<"title">>, Record#date.title}, {<<"translate">>, case Record#date.contenteditable of "yes" -> "yes"; "no" -> "no"; _ -> [] end}, % spec {<<"autocomplete">>, case Record#date.autocomplete of true -> "on"; false -> "off"; _ -> [] end}, {<<"autofocus">>,if Record#date.autofocus == true -> "autofocus"; true -> [] end}, {<<"disabled">>, if Record#date.disabled == true -> "disabled"; true -> [] end}, {<<"form">>,Record#date.form}, {<<"list">>,Record#date.list}, {<<"max">>,Record#date.max}, {<<"min">>,Record#date.min}, {<<"name">>,Record#date.name}, {<<"readonly">>,if Record#date.readonly == true -> "readonly"; true -> [] end}, {<<"required">>,if Record#date.required == true -> "required"; true -> [] end}, {<<"step">>,Record#date.step}, {<<"type">>, <<"date">>}, {<<"value">>, Record#date.value} | Record#date.data_fields ], wf_tags:emit_tag(<<"input">>, nitro:render(Record#date.body), List).
null
https://raw.githubusercontent.com/synrc/nitro/753b543626add2c014584546ec50870808a2eb90/src/elements/input/element_date.erl
erlang
global spec
-module(element_date). -author('Vladimir Galunshchikov'). -include_lib("nitro/include/nitro.hrl"). -include_lib("nitro/include/event.hrl"). -compile(export_all). render_element(Record) when Record#date.show_if==false -> [<<>>]; render_element(Record) -> Id = case Record#date.postback of [] -> Record#date.id; Postback -> ID = case Record#date.id of [] -> nitro:temp_id(); I -> I end, nitro:wire(#event{type=click, postback=Postback, target=ID, source=Record#date.source, delegate=Record#date.delegate }), ID end, List = [ {<<"accesskey">>, Record#date.accesskey}, {<<"class">>, Record#date.class}, {<<"contenteditable">>, case Record#date.contenteditable of true -> "true"; false -> "false"; _ -> [] end}, {<<"contextmenu">>, Record#date.contextmenu}, {<<"dir">>, case Record#date.dir of "ltr" -> "ltr"; "rtl" -> "rtl"; "auto" -> "auto"; _ -> [] end}, {<<"draggable">>, case Record#date.draggable of true -> "true"; false -> "false"; _ -> [] end}, {<<"dropzone">>, Record#date.dropzone}, {<<"hidden">>, case Record#date.hidden of "hidden" -> "hidden"; _ -> [] end}, {<<"id">>, Id}, {<<"lang">>, Record#date.lang}, {<<"spellcheck">>, case Record#date.spellcheck of true -> "true"; false -> "false"; _ -> [] end}, {<<"style">>, Record#date.style}, {<<"tabindex">>, Record#date.tabindex}, {<<"title">>, Record#date.title}, {<<"translate">>, case Record#date.contenteditable of "yes" -> "yes"; "no" -> "no"; _ -> [] end}, {<<"autocomplete">>, case Record#date.autocomplete of true -> "on"; false -> "off"; _ -> [] end}, {<<"autofocus">>,if Record#date.autofocus == true -> "autofocus"; true -> [] end}, {<<"disabled">>, if Record#date.disabled == true -> "disabled"; true -> [] end}, {<<"form">>,Record#date.form}, {<<"list">>,Record#date.list}, {<<"max">>,Record#date.max}, {<<"min">>,Record#date.min}, {<<"name">>,Record#date.name}, {<<"readonly">>,if Record#date.readonly == true -> "readonly"; true -> [] end}, {<<"required">>,if Record#date.required == true -> "required"; true -> [] end}, {<<"step">>,Record#date.step}, {<<"type">>, <<"date">>}, {<<"value">>, Record#date.value} | Record#date.data_fields ], wf_tags:emit_tag(<<"input">>, nitro:render(Record#date.body), List).
93e6d1979cc9f5ecc4e3dbb75c8f97beab4071d5bcf4e6633cb710cf8db8d3b2
lisp-korea/sicp2014
ex-1-23.scm
#lang planet neil/sicp make ( next ) procedure returning 2 , 3 , 5 , 7 , ... change ( + test - divisor 1 ) to ( next test - divisor ) (define (square x) (* x x)) (define (smallest-divisor n) (find-divisor n 2)) (define (next n) (if (= n 2) 3 (+ n 2))) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (next test-divisor))))) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest-divisor n))) ;; -- (define (timed-prime-test n) (newline) (display n) (start-prime-test n (runtime))) (define (start-prime-test n start-time) (if (prime? n) (report-prime (- (runtime) start-time)))) (define (report-prime elapsed-time) (display " *** ") (display elapsed-time)) ;; -- (define (search-for-primes n) (find-prime-from n 3 (runtime))) (define (print-time elapsed-time) (display " *** ") (display elapsed-time)) (define (print-and-go n cnt start-time) (display n) (newline) (if (= cnt 0) (print-time (- (runtime) start-time)) (find-prime-from (+ n 1) cnt start-time))) (define (find-prime-from n cnt start-time) (if (prime? n) (print-and-go n (- cnt 1) start-time) (find-prime-from (+ n 1) cnt start-time))) ;; -- (search-for-primes 1000) 141 (search-for-primes 10000) 178 -- > 166 (search-for-primes 100000) 252 -- > 210 (search-for-primes 1000000) 404 -- > 308
null
https://raw.githubusercontent.com/lisp-korea/sicp2014/9e60f70cb84ad2ad5987a71aebe1069db288b680/vvalkyrie/1.2/ex-1-23.scm
scheme
-- -- --
#lang planet neil/sicp make ( next ) procedure returning 2 , 3 , 5 , 7 , ... change ( + test - divisor 1 ) to ( next test - divisor ) (define (square x) (* x x)) (define (smallest-divisor n) (find-divisor n 2)) (define (next n) (if (= n 2) 3 (+ n 2))) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (next test-divisor))))) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest-divisor n))) (define (timed-prime-test n) (newline) (display n) (start-prime-test n (runtime))) (define (start-prime-test n start-time) (if (prime? n) (report-prime (- (runtime) start-time)))) (define (report-prime elapsed-time) (display " *** ") (display elapsed-time)) (define (search-for-primes n) (find-prime-from n 3 (runtime))) (define (print-time elapsed-time) (display " *** ") (display elapsed-time)) (define (print-and-go n cnt start-time) (display n) (newline) (if (= cnt 0) (print-time (- (runtime) start-time)) (find-prime-from (+ n 1) cnt start-time))) (define (find-prime-from n cnt start-time) (if (prime? n) (print-and-go n (- cnt 1) start-time) (find-prime-from (+ n 1) cnt start-time))) (search-for-primes 1000) 141 (search-for-primes 10000) 178 -- > 166 (search-for-primes 100000) 252 -- > 210 (search-for-primes 1000000) 404 -- > 308
cfbf6e427c17d74f7921768847513c33402e33a38b19356bb10e19e216da3497
cerner/clara-rules
test_memory.cljc
#?(:clj (ns clara.test-memory (:require [clara.tools.testing-utils :refer [def-rules-test] :as tu] [clara.rules :refer [fire-rules insert insert-all insert! retract query]] [clara.rules.testfacts :refer [->Temperature ->Cold ->WindSpeed ->Hot ->ColdAndWindy ->First ->Second]] [clojure.test :refer [is deftest run-tests testing use-fixtures]] [clara.rules.accumulators :as acc] [schema.test :as st]) (:import [clara.rules.testfacts Temperature Hot Cold WindSpeed ColdAndWindy First Second])) :cljs (ns clara.test-memory (:require [clara.rules :refer [fire-rules insert insert! insert-all retract query]] [clara.rules.testfacts :refer [->Temperature Temperature ->Cold Cold ->Hot Hot ->WindSpeed WindSpeed ->ColdAndWindy ColdAndWindy ->First First ->Second Second]] [clara.rules.accumulators :as acc] [clara.tools.testing-utils :as tu] [cljs.test] [schema.test :as st]) (:require-macros [clara.tools.testing-utils :refer [def-rules-test]] [cljs.test :refer [is deftest run-tests testing use-fixtures]]))) (use-fixtures :once st/validate-schemas #?(:clj tu/opts-fixture)) ;; While the memory is tested through rules and queries, rather than direct unit tests on the memory, ;; the intent of these tests is to create patterns in the engine that cover edge cases and other paths ;; of concern in clara.rules.memory. ;; This test are here to verify -rules/issues/303 (def-rules-test test-negation-complex-join-with-numerous-non-matching-facts-inserted-after-descendant-negation {:rules [] :queries [query1 [[] [[Hot (= ?t temperature)] [:not [Cold (tu/join-filter-equals ?t temperature)]]]] query2 [[] [[Hot (= ?t temperature)] [:not [Cold (= ?t temperature)]]]]] :sessions [empty-session-jfe [query1] {} empty-session-equals [query2] {}]} (let [lots-of-hot (doall (for [_ (range 100)] (->Hot 20)))] (is (= (repeat 100 {:?t 20}) (-> empty-session-jfe (insert (->Cold 10)) fire-rules (insert-all lots-of-hot) fire-rules (query query1)))) (is (= (repeat 100 {:?t 20}) (-> empty-session-equals (insert (->Cold 10)) fire-rules (insert-all lots-of-hot) fire-rules (query query2)))))) (def-rules-test test-query-for-many-added-elements {:queries [temp-query [[] [[Temperature (= ?t temperature)]]]] :sessions [empty-session [temp-query] {}]} (let [n 6000 ;; Do not batch insert to expose any StackOverflowError potential ;; of stacking lazy evaluations in working memory. session (reduce insert empty-session (for [i (range n)] (->Temperature i "MCI"))) session (fire-rules session)] (is (= n (count (query session temp-query)))))) (def-rules-test test-query-for-many-added-tokens {:rules [cold-temp [[[Temperature (< temperature 30) (= ?t temperature)]] (insert! (->Cold ?t))]] :queries [cold-query [[] [[Cold (= ?t temperature)]]]] :sessions [empty-session [cold-temp cold-query] {}]} (let [n 6000 ;; Do not batch insert to expose any StackOverflowError potential ;; of stacking lazy evaluations in working memory. session (reduce insert empty-session (for [i (range n)] (->Temperature (- i) "MCI"))) session (fire-rules session)] (is (= n (count (query session cold-query)))))) (def-rules-test test-many-retract-accumulated-for-same-accumulate-with-join-filter-node {:rules [count-cold-temps [[[Cold (= ?cold-temp temperature)] [?temp-count <- (acc/count) :from [Temperature (some? temperature) (<= temperature ?cold-temp)]]] (insert! {:count ?temp-count :type :temp-counter})]] :queries [cold-temp-count-query [[] [[:temp-counter [{:keys [count]}] (= ?count count)]]]] :sessions [empty-session [count-cold-temps cold-temp-count-query] {:fact-type-fn (fn [f] (or (:type f) (type f)))}]} (let [n 6000 session (reduce insert empty-session ;; Insert all temperatures one at a time to ensure the ;; accumulate node will continuously re-accumulate via ;; `right-activate-reduced` to expose any StackOverflowError ;; potential of stacking lazy evaluations in working memory. (for [t (range n)] (->Temperature (- t) "MCI"))) session (-> session (insert (->Cold 30)) fire-rules)] ;; All temperatures are under the Cold temperature threshold. (is (= #{{:?count 6000}} (set (query session cold-temp-count-query)))))) (def-rules-test test-disjunctions-sharing-production-node ;; Ensures that when 'sibling' nodes are sharing a common child ;; production node, that activations are effectively retracted in some TMS control flows . ;; See -rules/pull/145 for more context. {:rules [r [[[:or [First] [Second]] [?ts <- (acc/all) :from [Temperature]]] (insert! (with-meta {:ts ?ts} {:type :holder}))]] :queries [q [[] [[?h <- :holder]]]] :sessions [s [r q] {}]} (let [;; Vary the insertion order to ensure that the outcomes are the same. ;; This insertion order will cause retractions to need to be propagated ;; to the RHS production node that is shared by the nested conditions ;; of the disjunction. qres1 (-> s (insert (->First)) (insert (->Temperature 1 "MCI")) (insert (->Second)) (insert (->Temperature 2 "MCI")) fire-rules (query q) set) qres2 (-> s (insert (->First)) (insert (->Temperature 1 "MCI")) (insert (->Temperature 2 "MCI")) (insert (->Second)) fire-rules (query q) set)] (is (= qres1 qres2)))) (def-rules-test test-force-multiple-transient-transitions-activation-memory ;; The objective of this test is to verify that activation memory works ;; properly after going through persistent/transient shifts, including shifts ;; that empty it (i.e. firing the rules.) {:rules [rule [[[ColdAndWindy]] (insert! (->Cold 10))]] :queries [cold-query [[] [[Cold (= ?t temperature)]]]] :sessions [empty-session [rule cold-query] {}]} (let [windy-fact (->ColdAndWindy 20 20)] (is (= (-> empty-session (insert windy-fact) (insert windy-fact) fire-rules (query cold-query)) [{:?t 10} {:?t 10}]) "Make two insert calls forcing the memory to go through a persistent/transient transition in between insert calls.") (is (= (-> empty-session (insert windy-fact) (insert windy-fact) fire-rules (insert windy-fact) (insert windy-fact) fire-rules (query cold-query)) (repeat 4 {:?t 10})) "Validate that we can still go through a persistent/transient transition in the memory after firing rules causes the activation memory to be emptied.")))
null
https://raw.githubusercontent.com/cerner/clara-rules/8107a5ab7fdb475e323c0bcb39084a83454deb1c/src/test/common/clara/test_memory.cljc
clojure
While the memory is tested through rules and queries, rather than direct unit tests on the memory, the intent of these tests is to create patterns in the engine that cover edge cases and other paths of concern in clara.rules.memory. This test are here to verify -rules/issues/303 Do not batch insert to expose any StackOverflowError potential of stacking lazy evaluations in working memory. Do not batch insert to expose any StackOverflowError potential of stacking lazy evaluations in working memory. Insert all temperatures one at a time to ensure the accumulate node will continuously re-accumulate via `right-activate-reduced` to expose any StackOverflowError potential of stacking lazy evaluations in working memory. All temperatures are under the Cold temperature threshold. Ensures that when 'sibling' nodes are sharing a common child production node, that activations are effectively retracted in some See -rules/pull/145 for more context. Vary the insertion order to ensure that the outcomes are the same. This insertion order will cause retractions to need to be propagated to the RHS production node that is shared by the nested conditions of the disjunction. The objective of this test is to verify that activation memory works properly after going through persistent/transient shifts, including shifts that empty it (i.e. firing the rules.)
#?(:clj (ns clara.test-memory (:require [clara.tools.testing-utils :refer [def-rules-test] :as tu] [clara.rules :refer [fire-rules insert insert-all insert! retract query]] [clara.rules.testfacts :refer [->Temperature ->Cold ->WindSpeed ->Hot ->ColdAndWindy ->First ->Second]] [clojure.test :refer [is deftest run-tests testing use-fixtures]] [clara.rules.accumulators :as acc] [schema.test :as st]) (:import [clara.rules.testfacts Temperature Hot Cold WindSpeed ColdAndWindy First Second])) :cljs (ns clara.test-memory (:require [clara.rules :refer [fire-rules insert insert! insert-all retract query]] [clara.rules.testfacts :refer [->Temperature Temperature ->Cold Cold ->Hot Hot ->WindSpeed WindSpeed ->ColdAndWindy ColdAndWindy ->First First ->Second Second]] [clara.rules.accumulators :as acc] [clara.tools.testing-utils :as tu] [cljs.test] [schema.test :as st]) (:require-macros [clara.tools.testing-utils :refer [def-rules-test]] [cljs.test :refer [is deftest run-tests testing use-fixtures]]))) (use-fixtures :once st/validate-schemas #?(:clj tu/opts-fixture)) (def-rules-test test-negation-complex-join-with-numerous-non-matching-facts-inserted-after-descendant-negation {:rules [] :queries [query1 [[] [[Hot (= ?t temperature)] [:not [Cold (tu/join-filter-equals ?t temperature)]]]] query2 [[] [[Hot (= ?t temperature)] [:not [Cold (= ?t temperature)]]]]] :sessions [empty-session-jfe [query1] {} empty-session-equals [query2] {}]} (let [lots-of-hot (doall (for [_ (range 100)] (->Hot 20)))] (is (= (repeat 100 {:?t 20}) (-> empty-session-jfe (insert (->Cold 10)) fire-rules (insert-all lots-of-hot) fire-rules (query query1)))) (is (= (repeat 100 {:?t 20}) (-> empty-session-equals (insert (->Cold 10)) fire-rules (insert-all lots-of-hot) fire-rules (query query2)))))) (def-rules-test test-query-for-many-added-elements {:queries [temp-query [[] [[Temperature (= ?t temperature)]]]] :sessions [empty-session [temp-query] {}]} (let [n 6000 session (reduce insert empty-session (for [i (range n)] (->Temperature i "MCI"))) session (fire-rules session)] (is (= n (count (query session temp-query)))))) (def-rules-test test-query-for-many-added-tokens {:rules [cold-temp [[[Temperature (< temperature 30) (= ?t temperature)]] (insert! (->Cold ?t))]] :queries [cold-query [[] [[Cold (= ?t temperature)]]]] :sessions [empty-session [cold-temp cold-query] {}]} (let [n 6000 session (reduce insert empty-session (for [i (range n)] (->Temperature (- i) "MCI"))) session (fire-rules session)] (is (= n (count (query session cold-query)))))) (def-rules-test test-many-retract-accumulated-for-same-accumulate-with-join-filter-node {:rules [count-cold-temps [[[Cold (= ?cold-temp temperature)] [?temp-count <- (acc/count) :from [Temperature (some? temperature) (<= temperature ?cold-temp)]]] (insert! {:count ?temp-count :type :temp-counter})]] :queries [cold-temp-count-query [[] [[:temp-counter [{:keys [count]}] (= ?count count)]]]] :sessions [empty-session [count-cold-temps cold-temp-count-query] {:fact-type-fn (fn [f] (or (:type f) (type f)))}]} (let [n 6000 session (reduce insert empty-session (for [t (range n)] (->Temperature (- t) "MCI"))) session (-> session (insert (->Cold 30)) fire-rules)] (is (= #{{:?count 6000}} (set (query session cold-temp-count-query)))))) (def-rules-test test-disjunctions-sharing-production-node TMS control flows . {:rules [r [[[:or [First] [Second]] [?ts <- (acc/all) :from [Temperature]]] (insert! (with-meta {:ts ?ts} {:type :holder}))]] :queries [q [[] [[?h <- :holder]]]] :sessions [s [r q] {}]} qres1 (-> s (insert (->First)) (insert (->Temperature 1 "MCI")) (insert (->Second)) (insert (->Temperature 2 "MCI")) fire-rules (query q) set) qres2 (-> s (insert (->First)) (insert (->Temperature 1 "MCI")) (insert (->Temperature 2 "MCI")) (insert (->Second)) fire-rules (query q) set)] (is (= qres1 qres2)))) (def-rules-test test-force-multiple-transient-transitions-activation-memory {:rules [rule [[[ColdAndWindy]] (insert! (->Cold 10))]] :queries [cold-query [[] [[Cold (= ?t temperature)]]]] :sessions [empty-session [rule cold-query] {}]} (let [windy-fact (->ColdAndWindy 20 20)] (is (= (-> empty-session (insert windy-fact) (insert windy-fact) fire-rules (query cold-query)) [{:?t 10} {:?t 10}]) "Make two insert calls forcing the memory to go through a persistent/transient transition in between insert calls.") (is (= (-> empty-session (insert windy-fact) (insert windy-fact) fire-rules (insert windy-fact) (insert windy-fact) fire-rules (query cold-query)) (repeat 4 {:?t 10})) "Validate that we can still go through a persistent/transient transition in the memory after firing rules causes the activation memory to be emptied.")))
c7e7daa3ba238ed49bd87d980de5cf3185243ca1532880305f9ee41e9203e986
freedesktop/bustle
Util.hs
# LANGUAGE ForeignFunctionInterface # Bustle . Util : miscellaneous utility functions Copyright © 2008–2012 Collabora Ltd. This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA Bustle.Util: miscellaneous utility functions Copyright © 2008–2012 Collabora Ltd. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} module Bustle.Util ( io , warn , getCacheDir -- You probably don't actually want to use this function. , traceM ) where import Control.Monad.Trans (MonadIO, liftIO) import Control.Monad import Debug.Trace (trace) import System.IO (hPutStrLn, stderr) import Foreign.C.String import System.Directory import System.FilePath ((</>)) import Bustle.Translation (__) -- Escape hatch to log a value from a non-IO monadic context. traceM :: (Show a, Monad m) => a -> m () traceM = void . return . trace . show -- Log a warning which isn't worth showing to the user, but which might -- interest someone debugging the application. warn :: String -> IO () warn = hPutStrLn stderr . (__ "Warning: " ++) -- Shorthand for liftIO. io :: MonadIO m => IO a -> m a io = liftIO foreign import ccall "g_get_user_cache_dir" g_get_user_cache_dir :: IO CString getCacheDir :: IO FilePath getCacheDir = do dotCache <- peekCString =<< g_get_user_cache_dir let dir = dotCache </> "bustle" createDirectoryIfMissing True dir return dir
null
https://raw.githubusercontent.com/freedesktop/bustle/e506b5ca71e14af3d2ebd0a63c1b8d3ea0fb1795/Bustle/Util.hs
haskell
You probably don't actually want to use this function. Escape hatch to log a value from a non-IO monadic context. Log a warning which isn't worth showing to the user, but which might interest someone debugging the application. Shorthand for liftIO.
# LANGUAGE ForeignFunctionInterface # Bustle . Util : miscellaneous utility functions Copyright © 2008–2012 Collabora Ltd. This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA Bustle.Util: miscellaneous utility functions Copyright © 2008–2012 Collabora Ltd. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} module Bustle.Util ( io , warn , getCacheDir , traceM ) where import Control.Monad.Trans (MonadIO, liftIO) import Control.Monad import Debug.Trace (trace) import System.IO (hPutStrLn, stderr) import Foreign.C.String import System.Directory import System.FilePath ((</>)) import Bustle.Translation (__) traceM :: (Show a, Monad m) => a -> m () traceM = void . return . trace . show warn :: String -> IO () warn = hPutStrLn stderr . (__ "Warning: " ++) io :: MonadIO m => IO a -> m a io = liftIO foreign import ccall "g_get_user_cache_dir" g_get_user_cache_dir :: IO CString getCacheDir :: IO FilePath getCacheDir = do dotCache <- peekCString =<< g_get_user_cache_dir let dir = dotCache </> "bustle" createDirectoryIfMissing True dir return dir
19f4065bec4ca43ad771cda23fc41dc3a016fe818253fc31f4265834db6e105a
gmartinezramirez/USACH-Paradigmas-Programacion
aplicacion-listas.rkt
#lang racket ( member ? ( list 1 2 3 ) 3 ) return : # t ( member ? ( list 1 2 3 ) 5 ) return : # f ; Recursion natural (define member? (lambda (lst x) (cond [(null? lst) #f] [(eq? (car lst) x) #t] [else (member? (cdr lst) x)]))) ; Sin recursion ( insert - tail - sin - duplicado ( list 1 2 3 ) 3 ) ( insert - tail - sin - duplicado ( list 1 2 3 ) 4 ) (define insert-tail-sin-duplicado (lambda (lst x) (cond [(member? lst x) lst] [else (reverse (cons x (reverse lst))) ]))) ; Recursion natural ; No especifica QUE debe ser con recursion natural ( insert - tail - rec ( list 1 2 3 ) 3 ) ( insert - tail - rec ( list 1 2 3 ) 4 ) (define insert-tail-rec (lambda (lst x) (cond [(member? lst x) lst] [else (insert-item lst x) ]))) ; Tipo de recursion: recursion natural Ejemplo : ( insert - item ( list 1 2 3 4 ) 50 ) ; '(1 2 3 4 50) (define insert-item (lambda (lst item) (cond [(null? lst) (cons item null)] [else (cons (car lst) (insert-item (cdr lst) item))]))) ( my - inverse - tail - rec ( list 1 2 3 4 ) null ) = ' ( 4 3 2 1 ) (define my-inverse-tail-rec (lambda (lst lst-so-far) (cond [(null? lst) lst-so-far] [else (my-inverse-tail-rec (cdr lst) (cons (car lst) lst-so-far))])))
null
https://raw.githubusercontent.com/gmartinezramirez/USACH-Paradigmas-Programacion/e1fdfe7501a156e2e17fcefb8e30068cee3fb44f/2021-02/01-FP/aplicacion-listas.rkt
racket
Recursion natural Sin recursion Recursion natural No especifica QUE debe ser con recursion natural Tipo de recursion: recursion natural '(1 2 3 4 50)
#lang racket ( member ? ( list 1 2 3 ) 3 ) return : # t ( member ? ( list 1 2 3 ) 5 ) return : # f (define member? (lambda (lst x) (cond [(null? lst) #f] [(eq? (car lst) x) #t] [else (member? (cdr lst) x)]))) ( insert - tail - sin - duplicado ( list 1 2 3 ) 3 ) ( insert - tail - sin - duplicado ( list 1 2 3 ) 4 ) (define insert-tail-sin-duplicado (lambda (lst x) (cond [(member? lst x) lst] [else (reverse (cons x (reverse lst))) ]))) ( insert - tail - rec ( list 1 2 3 ) 3 ) ( insert - tail - rec ( list 1 2 3 ) 4 ) (define insert-tail-rec (lambda (lst x) (cond [(member? lst x) lst] [else (insert-item lst x) ]))) Ejemplo : ( insert - item ( list 1 2 3 4 ) 50 ) (define insert-item (lambda (lst item) (cond [(null? lst) (cons item null)] [else (cons (car lst) (insert-item (cdr lst) item))]))) ( my - inverse - tail - rec ( list 1 2 3 4 ) null ) = ' ( 4 3 2 1 ) (define my-inverse-tail-rec (lambda (lst lst-so-far) (cond [(null? lst) lst-so-far] [else (my-inverse-tail-rec (cdr lst) (cons (car lst) lst-so-far))])))
a40a59417ddbe65a40aa9e7e37ed6da08e4a88f70c5fbe70c934458f267973bc
thma/PolysemyCleanArchitecture
StaticConfigProvider.hs
module ExternalInterfaces.StaticConfigProvider ( runStaticConfigProvider ) where import InterfaceAdapters.Config import ExternalInterfaces.ConfigProvider import Polysemy (Embed, Member, Sem, embed, interpret) -- | just provides a static config instance runStaticConfigProvider :: (Member (Embed IO) r) => Sem (ConfigProvider : r) a -> Sem r a runStaticConfigProvider = interpret $ \case GetConfig -> embed loadConfig -- | load application config. In real life, this would load a config file or read commandline args. loadConfig :: IO Config loadConfig = return Config {port = 8080, backend = SQLite, dbPath = "kvs.db", verbose = True}
null
https://raw.githubusercontent.com/thma/PolysemyCleanArchitecture/3bb375a30bcbf35c9df62802902e0faa03e3f03d/src/ExternalInterfaces/StaticConfigProvider.hs
haskell
| just provides a static config instance | load application config. In real life, this would load a config file or read commandline args.
module ExternalInterfaces.StaticConfigProvider ( runStaticConfigProvider ) where import InterfaceAdapters.Config import ExternalInterfaces.ConfigProvider import Polysemy (Embed, Member, Sem, embed, interpret) runStaticConfigProvider :: (Member (Embed IO) r) => Sem (ConfigProvider : r) a -> Sem r a runStaticConfigProvider = interpret $ \case GetConfig -> embed loadConfig loadConfig :: IO Config loadConfig = return Config {port = 8080, backend = SQLite, dbPath = "kvs.db", verbose = True}
f82a46991a9a60aef6b8ac5d78ffb18a2a7ac14fcea1d8bdaca172f28e759f8a
gedge-platform/gedge-platform
amqp_auth_mechanisms.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . %% @private -module(amqp_auth_mechanisms). -include("amqp_client.hrl"). -export([plain/3, amqplain/3, external/3, crdemo/3]). %%--------------------------------------------------------------------------- plain(none, _, init) -> {<<"PLAIN">>, []}; plain(none, #amqp_params_network{username = Username, password = Password}, _State) -> DecryptedPassword = credentials_obfuscation:decrypt(Password), {<<0, Username/binary, 0, DecryptedPassword/binary>>, _State}. amqplain(none, _, init) -> {<<"AMQPLAIN">>, []}; amqplain(none, #amqp_params_network{username = Username, password = Password}, _State) -> LoginTable = [{<<"LOGIN">>, longstr, Username}, {<<"PASSWORD">>, longstr, credentials_obfuscation:decrypt(Password)}], {rabbit_binary_generator:generate_table(LoginTable), _State}. external(none, _, init) -> {<<"EXTERNAL">>, []}; external(none, _, _State) -> {<<"">>, _State}. crdemo(none, _, init) -> {<<"RABBIT-CR-DEMO">>, 0}; crdemo(none, #amqp_params_network{username = Username}, 0) -> {Username, 1}; crdemo(<<"Please tell me your password">>, #amqp_params_network{password = Password}, 1) -> DecryptedPassword = credentials_obfuscation:decrypt(Password), {<<"My password is ", DecryptedPassword/binary>>, 2}.
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/amqp_client/src/amqp_auth_mechanisms.erl
erlang
---------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . @private -module(amqp_auth_mechanisms). -include("amqp_client.hrl"). -export([plain/3, amqplain/3, external/3, crdemo/3]). plain(none, _, init) -> {<<"PLAIN">>, []}; plain(none, #amqp_params_network{username = Username, password = Password}, _State) -> DecryptedPassword = credentials_obfuscation:decrypt(Password), {<<0, Username/binary, 0, DecryptedPassword/binary>>, _State}. amqplain(none, _, init) -> {<<"AMQPLAIN">>, []}; amqplain(none, #amqp_params_network{username = Username, password = Password}, _State) -> LoginTable = [{<<"LOGIN">>, longstr, Username}, {<<"PASSWORD">>, longstr, credentials_obfuscation:decrypt(Password)}], {rabbit_binary_generator:generate_table(LoginTable), _State}. external(none, _, init) -> {<<"EXTERNAL">>, []}; external(none, _, _State) -> {<<"">>, _State}. crdemo(none, _, init) -> {<<"RABBIT-CR-DEMO">>, 0}; crdemo(none, #amqp_params_network{username = Username}, 0) -> {Username, 1}; crdemo(<<"Please tell me your password">>, #amqp_params_network{password = Password}, 1) -> DecryptedPassword = credentials_obfuscation:decrypt(Password), {<<"My password is ", DecryptedPassword/binary>>, 2}.
b12c1e8592a8a16d2bdfd1de4105a15b0e9880d3c682542d2e5c17128bb581e0
datacrypt-project/hitchhiker-tree
core.cljc
(ns hitchhiker.tree.core (:refer-clojure :exclude [compare resolve subvec]) (:require [clojure.core.rrb-vector :refer [catvec subvec]] #?(:clj [clojure.pprint :as pp]) #?(:clj [clojure.core.async :refer [go chan put! <! <!! promise-chan] :as async] :cljs [cljs.core.async :refer [chan put! <! promise-chan] :as async]) #?(:cljs [goog.array]) #?(:clj [taoensso.nippy :as nippy])) #?(:clj (:import java.io.Writer [java.util Arrays Collections])) #?(:cljs (:require-macros [cljs.core.async.macros :refer [go]] [hitchhiker.tree.core :refer [go-try <? <?resolve]]))) cljs macro environment (defn- cljs-env? "Take the &env from a macro, and tell whether we are expanding into cljs." [env] (boolean (:ns env))) #?(:clj (defmacro if-cljs "Return then if we are generating cljs code and else for Clojure code. " [then else] (if (cljs-env? &env) then else))) ;; core.async helpers (defn throw-if-exception "Helper method that checks if x is Exception and if yes, wraps it in a new exception, passing though ex-data if any, and throws it. The wrapping is done to maintain a full stack trace when jumping between multiple contexts." [x] (if (instance? #?(:clj Exception :cljs js/Error) x) (throw (ex-info (or #?(:clj (.getMessage x)) (str x)) (or (ex-data x) {}) x)) x)) #?(:clj (defmacro go-try "Asynchronously executes the body in a go block. Returns a channel which will receive the result of the body when completed or the exception if an exception is thrown. You are responsible to take this exception and deal with it! This means you need to take the result from the channel at some point." {:style/indent 1} [ & body] `(if-cljs (cljs.core.async.macros/go (try ~@body (catch js/Error e# e#))) (go (try ~@body (catch Exception e# e#)))))) #?(:clj (defmacro <? "Same as core.async <! but throws an exception if the channel returns a throwable error." [ch] `(if-cljs (throw-if-exception (cljs.core.async/<! ~ch)) (throw-if-exception (<! ~ch))))) #?(:clj (defn <?? "Same as core.async <!! but throws an exception if the channel returns a throwable error." [ch] (throw-if-exception (<!! ch)))) (defn reduce< "Reduces over a sequence s with a go function go-f given the initial value init." [go-f init s] (go-try (loop [res init [f & r] s] (if f (recur (<? (go-f res f)) r) res)))) ;; core code (defrecord Config [index-b data-b op-buf-size]) (defprotocol IKeyCompare (compare [key1 key2])) (defprotocol IResolve "All nodes must implement this protocol. It's includes the minimal functionality necessary to avoid resolving nodes unless strictly necessary." (index? [_] "Returns true if this is an index node") (last-key [_] "Returns the rightmost key of the node") (dirty? [_] "Returns true if this should be flushed") TODO resolve should be instrumented (resolve [_] "Returns the INode version of this node in a go-block; could trigger IO")) (defn tree-node? [node] (satisfies? IResolve node)) (defprotocol INode (overflow? [node] "Returns true if this node has too many elements") (underflow? [node] "Returns true if this node has too few elements") (merge-node [node other] "Combines this node with the other to form a bigger node. We assume they're siblings") (split-node [node] "Returns a Split object with the 2 nodes that we turned this into") (lookup [node key] "Returns the child node which contains the given key")) (defrecord Split [left right median]) ;; TODO maybe this is a good protocol? ;; how to track dirty bits... ;; could model w/ monad (ground state dirty unless loaded from storage), ;; gets cleaned after each flush-flood flush - flood is the BFS for all dirty nodes ; individual nodes must be flushable ;; A storage backend must be able to take a node as arg, serialize, assign addr, ;; and call "clean" on the node to allow it to have a backing addr ;; Maybe disk backing should n't be done as a monad , since that double the total IOPS when 2 users of a snapshot need flush / clones ;; (N uses makes N useless copies). ;; ;; So perhaps each node can have a promise, it's address on storage. When someone wants to flush it , they first dump it to disk , then try to clean it . ;; If the clean succeeds, they're done. If the clean fails (i.e. deliver fails), ;; they roll back the write and read the address from the promise. ;; ;; Monads will be reserved for things we want persisted, rather than the ;; in-memory flushing system, which can afford extra communication ;; ;; We can totally rely on a caching layer to manage keeping nodes around for ;; when a single tree is passed to several different consumers. This layer will make it easier ta manage the overall JVM 's memory allocation , and it 's far simpler than trying to use weak pointers to track unresolved ;; so that we can supply the data to all of them when we fetch it. The cache will also have better GC properties , by not accidentally sticking random tree bits into jvm GC roots that could be held a long time . ;; ;; So flushing writes are shared, but loading from disk is cached instead. ;; Maybe write flushing could itself just be a smaller (or bigger) "write cache"... ;; no, that could be defeated by really big writes, which are already guaranteed ;; to be resident (since they were pending and thus linked to the tree's root). ;; We 'll make an IOPS measuring backend , which specifically makes " fake " ;; that keep pointers to the nodes they "stored". Importantly, it needs to record ;; each read and write operation into counters, so that we can run a test ;; and check the total IOPS we spent. ;; ;; The advanced work with this will allow us to define hard IOPS bounds ;; (based on proven data), and then send generated loads to check we stay within ;; our targets. (extend-protocol IKeyCompare ;; By default, we use the default comparator #?@(:clj [Object (compare [key1 key2] (clojure.core/compare key1 key2)) Double (compare [^Double key1 key2] (if (instance? Double key2) (.compareTo key1 key2) (clojure.core/compare key1 key2))) Long (compare [^Long key1 key2] (if (instance? Long key2) (.compareTo key1 key2)) (clojure.core/compare key1 key2))] :cljs [number (compare [key1 key2] (cljs.core/compare key1 key2)) object (compare [key1 key2] (cljs.core/compare key1 key2))])) ;; TODO enforce that there always (= (count children) (inc (count keys))) ;; ;; TODO we should be able to find all uncommited data by searching for ;; resolved & unresolved children (declare data-node dirty!) (defn index-node-keys "Calculates the separating keys given the children of an index node" [children] (mapv last-key (butlast children))) (declare ->IndexNode) (defrecord IndexNode [children storage-addr op-buf cfg] IResolve (index? [this] true) (dirty? [this] (not (async/poll! storage-addr))) (resolve [this] (go this)) (last-key [this] TODO should optimize by caching to reduce IOps ( can use monad ) (last-key (peek children))) INode (overflow? [this] (>= (count children) (* 2 (:index-b cfg)))) (underflow? [this] (< (count children) (:index-b cfg))) (split-node [this] (let [b (:index-b cfg) median (nth (index-node-keys children) (dec b)) [left-buf right-buf] (split-with #(not (pos? (compare (:key %) median))) TODO this should use msg / affects - key (sort-by :key op-buf))] (->Split (->IndexNode (subvec children 0 b) (promise-chan) (vec left-buf) cfg) (->IndexNode (subvec children b) (promise-chan) (vec right-buf) cfg) median))) (merge-node [this other] (->IndexNode (catvec children (:children other)) (promise-chan) (catvec op-buf (:op-buf other)) cfg)) (lookup [root key] ;;This is written like so because it's performance critical (let [l (dec (count children)) a (object-array l) _ (dotimes [i l] (aset a i (last-key (nth children i)))) x #?(:clj (Arrays/binarySearch a 0 l key compare) :cljs (goog.array/binarySearch a key compare))] (if (neg? x) (- (inc x)) x)))) #?(:clj (nippy/extend-freeze IndexNode :b-tree/index-node [{:keys [storage-addr cfg children op-buf]} data-output] (nippy/freeze-to-out! data-output cfg) (nippy/freeze-to-out! data-output children) ;;TODO apparently RRB-vectors don't freeze correctly; ;;we'll force it to a normal vector as a workaround (nippy/freeze-to-out! data-output (into [] op-buf)))) #?(:clj (nippy/extend-thaw :b-tree/index-node [data-input] (let [cfg (nippy/thaw-from-in! data-input) children (nippy/thaw-from-in! data-input) op-buf (nippy/thaw-from-in! data-input)] (->IndexNode children nil op-buf cfg)))) (defn index-node? [node] (instance? IndexNode node)) #?(:clj (defn print-index-node "Optionally include" [node ^Writer writer fully-qualified?] (.write writer (if fully-qualified? (pr-str IndexNode) "IndexNode")) (.write writer (str {:keys (index-node-keys (:children node)) :children (:children node)})))) #?(:clj (defmethod print-method IndexNode [node writer] (print-index-node node writer false))) #?(:clj (defmethod print-dup IndexNode [node writer] (print-index-node node writer true))) #?(:clj (defn node-status-bits [node] (str "[" (if (dirty? node) "D" " ") "]"))) #?(:clj (defmethod pp/simple-dispatch IndexNode [node] (let [out ^Writer *out*] (.write out "IndexNode") (.write out (node-status-bits node)) (pp/pprint-logical-block :prefix "{" :suffix "}" (pp/pprint-logical-block (.write out ":keys ") (pp/write-out (index-node-keys (:children node))) (pp/pprint-newline :linear)) (pp/pprint-logical-block (.write out ":op-buf ") (pp/write-out (:op-buf node)) (pp/pprint-newline :linear)) (pp/pprint-logical-block (.write out ":children ") (pp/pprint-newline :mandatory) (pp/write-out (:children node))))))) (defn nth-of-set "Like nth, but for sorted sets. O(n)" [set index] (first (drop index set))) (defrecord DataNode [children storage-addr cfg] IResolve (index? [this] false) (resolve [this] (go this)) (dirty? [this] (not (async/poll! storage-addr))) (last-key [this] (when (seq children) (-> children (rseq) (first) (key)))) INode ;; Should have between b & 2b-1 children (overflow? [this] (>= (count children) (* 2 (:data-b cfg)))) (underflow? [this] (< (count children) (:data-b cfg))) (split-node [this] (->Split (data-node cfg (into (sorted-map-by compare) (take (:data-b cfg)) children)) (data-node cfg (into (sorted-map-by compare) (drop (:data-b cfg)) children)) (nth-of-set children (dec (:data-b cfg))))) (merge-node [this other] (data-node cfg (into children (:children other)))) (lookup [root key] (let [x #?(:clj (Collections/binarySearch (vec (keys children)) key compare) :cljs (goog.array/binarySearch (into-array (keys children)) key compare))] (if (neg? x) (- (inc x)) x)))) (defn data-node "Creates a new data node" [cfg children] (->DataNode children (promise-chan) cfg)) (defn data-node? [node] (instance? DataNode node)) #?(:clj (defmacro <?resolve "HACK Attempt faster inlined resolve to avoid unnecessary channel ops." [e] `(if (or (data-node? ~e) (index-node? ~e)) ~e (<? (resolve ~e))))) #?(:clj (nippy/extend-freeze DataNode :b-tree/data-node [{:keys [cfg children]} data-output] (nippy/freeze-to-out! data-output cfg) (nippy/freeze-to-out! data-output children))) #?(:clj (nippy/extend-thaw :b-tree/data-node [data-input] (let [cfg (nippy/thaw-from-in! data-input) children (nippy/thaw-from-in! data-input)] (->DataNode children nil cfg)))) ;(println (b-tree :foo :bar :baz)) ( pp / pprint ( apply b - tree ( range 100 ) ) ) #?(:clj (defn print-data-node [node ^Writer writer fully-qualified?] (.write writer (if fully-qualified? (pr-str DataNode) "DataNode")) (.write writer (str {:children (:children node)})))) #?(:clj (defmethod print-method DataNode [node writer] (print-data-node node writer false))) #?(:clj (defmethod print-dup DataNode [node writer] (print-data-node node writer true))) #?(:clj (defmethod pp/simple-dispatch DataNode [node] (let [out ^Writer *out*] (.write out (str "DataNode" (node-status-bits node))) (.write out (str {:children (:children node)}))))) (defn backtrack-up-path-until "Given a path (starting with root and ending with an index), searches backwards, passing each pair of parent & index we just came from to the predicate function. When that function returns true, we return the path ending in the index for which it was true, or else we return the empty path" [path pred] (loop [path path] (when (seq path) (let [from-index (peek path) tmp (pop path) parent (peek tmp)] (if (pred parent from-index) path (recur (pop tmp))))))) (defn right-successor "Given a node on a path, find's that node's right successor node" [path] ;(clojure.pprint/pprint path) ;TODO this function would benefit from a prefetching hint to keep the next several sibs in mem (go-try (when-let [common-parent-path (backtrack-up-path-until path (fn [parent index] (< (inc index) (count (:children parent)))))] (let [next-index (-> common-parent-path peek inc) parent (-> common-parent-path pop peek) new-sibling (<?resolve (nth (:children parent) next-index)) ;; We must get back down to the data node ;; iterate cannot do blocking operations with core.async, so we use a loop sibling-lineage (loop [res [new-sibling] s new-sibling] (let [c (-> s :children first) c (if (tree-node? c) (<?resolve c) c)] (if (or (index-node? c) (data-node? c)) (recur (conj res c) c) res))) path-suffix (-> (interleave sibling-lineage (repeat 0)) (butlast)) ; butlast ensures we end w/ node ] (-> (pop common-parent-path) (conj next-index) (into path-suffix)))))) (defn forward-iterator "Takes the result of a search and puts the iterated elements onto iter-ch going forward over the tree as needed. Does lg(n) backtracking sometimes." [iter-ch path start-key] (go-try (loop [path path] (if path (let [start-node (peek path) _ (assert (data-node? start-node)) elements (-> start-node :children ; Get the indices of it (subseq >= start-key))] (<? (async/onto-chan iter-ch elements false)) (recur (<? (right-successor (pop path))))) (async/close! iter-ch))))) (defn lookup-path "Given a B-tree and a key, gets a path into the tree" [tree key] (go-try (loop [path [tree] ;alternating node/index/node/index/node... of the search taken cur tree ;current search node ] (if (seq (:children cur)) (if (data-node? cur) path (let [index (lookup cur key) child (if (data-node? cur) nil #_(nth-of-set (:children cur) index) (-> (:children cur) ;;TODO what are the semantics for exceeding on the right? currently it's trunc to the last element (nth index (peek (:children cur))) (<?resolve))) path' (conj path index child)] (recur path' child))) nil)))) (defn lookup-key "Given a B-tree and a key, gets an iterator into the tree" ([tree key] (lookup-key tree key nil)) ([tree key not-found] (go-try (-> (-> (<? (lookup-path tree key)) (peek) (<?resolve)) :children (get key not-found))))) ;; this is only for the REPL and testing #?(:clj (defn chan-seq [ch] (when-some [v (<?? ch)] (cons v (lazy-seq (chan-seq ch)))))) #?(:clj (defn lookup-fwd-iter "Compatibility helper to clojure sequences. Please prefer the channel interface of forward-iterator, as this function blocks your thread, which disturbs async contexts and might lead to poor performance. It is mainly here to facilitate testing." [tree key] (let [path (<?? (lookup-path tree key)) iter-ch (chan)] (forward-iterator iter-ch path key) (chan-seq iter-ch)))) (defn insert [{:keys [cfg] :as tree} key value] (go-try (let [path (<? (lookup-path tree key)) {:keys [children] :or {children (sorted-map-by compare)}} (peek path) updated-data-node (data-node cfg (assoc children key value))] (loop [node updated-data-node path (pop path)] (if (empty? path) (if (overflow? node) (let [{:keys [left right median]} (split-node node)] (->IndexNode [left right] (promise-chan) [] cfg)) node) (let [index (peek path) {:keys [children keys] :as parent} (peek (pop path))] (if (overflow? node) ; splice the split into the parent TODO refactor paths to be node / index pairs or 2 vectors or something (let [{:keys [left right median]} (split-node node) new-children (catvec (conj (subvec children 0 index) left right) (subvec children (inc index)))] (recur (-> parent (assoc :children new-children) (dirty!)) (pop (pop path)))) (recur (-> parent ;;TODO this assoc-in seems to be a bottleneck (assoc-in [:children index] node) (dirty!)) (pop (pop path)))))))))) ;;TODO: cool optimization: when merging children, push as many operations as you can into them to opportunistically minimize overall IO costs (defn delete [{:keys [cfg] :as tree} key] (go-try (let [path (<? (lookup-path tree key)) ; don't care about the found key or its index {:keys [children] :or {children (sorted-map-by compare)}} (peek path) updated-data-node (data-node cfg (dissoc children key))] (loop [node updated-data-node path (pop path)] (if (empty? path) ;; Check for special root underflow case (if (and (index-node? node) (= 1 (count (:children node)))) (first (:children node)) node) (let [index (peek path) {:keys [children keys op-buf] :as parent} (peek (pop path))] (if (underflow? node) ; splice the split into the parent ;;TODO this needs to use a polymorphic sibling-count to work on serialized nodes (let [bigger-sibling-idx (cond only have left sib only have right sib (> (count (:children (nth children (dec index)))) (count (:children (nth children (inc index))))) right sib bigger :else (inc index)) node-first? (> bigger-sibling-idx index) ; if true, `node` is left merged (if node-first? (merge-node node (<?resolve (nth children bigger-sibling-idx))) (merge-node (<?resolve (nth children bigger-sibling-idx)) node)) old-left-children (subvec children 0 (min index bigger-sibling-idx)) old-right-children (subvec children (inc (max index bigger-sibling-idx)))] (if (overflow? merged) (let [{:keys [left right median]} (split-node merged)] (recur (->IndexNode (catvec (conj old-left-children left right) old-right-children) (promise-chan) op-buf cfg) (pop (pop path)))) (recur (->IndexNode (catvec (conj old-left-children merged) old-right-children) (promise-chan) op-buf cfg) (pop (pop path))))) (recur (->IndexNode (assoc children index node) (promise-chan) op-buf cfg) (pop (pop path)))))))))) (defn b-tree [cfg & kvs] (go-try (loop [[[k v] & r] (partition 2 kvs) t (data-node cfg (sorted-map-by compare))] (if k (recur r (<? (insert t k v))) t))) #_(reduce (fn [t [k v]] (insert t k v)) (data-node cfg (sorted-map-by compare)) (partition 2 kvs))) (defrecord TestingAddr [last-key node] IResolve (dirty? [this] false) (last-key [_] last-key) (resolve [_] (go node))) #?(:clj (defn print-testing-addr [node ^Writer writer fully-qualified?] (.write writer (if fully-qualified? (pr-str TestingAddr) "TestingAddr")) (.write writer (str {})))) #?(:clj (defmethod print-method TestingAddr [node writer] (print-testing-addr node writer false))) #?(:clj (defmethod print-dup TestingAddr [node writer] (print-testing-addr node writer true))) #?(:clj (defmethod pp/simple-dispatch TestingAddr [node] (let [out ^Writer *out*] (.write out (str "TestingAddr" (node-status-bits node))) (.write out (str {}))))) (defn dirty! "Marks a node as being dirty if it was clean" [node] (assert (not (instance? TestingAddr node))) (assoc node :storage-addr (promise-chan))) TODO make this a loop / recur instead of mutual recursion (declare flush-tree) (defn flush-children [children backend session] (go-try (loop [[c & r] children res []] (if-not c res (recur r (conj res (<? (flush-tree c backend session)))))))) (defprotocol IBackend (new-session [backend] "Returns a session object that will collect stats") (write-node [backend node session] "Writes the given node to storage, returning a go-block with its assigned address") (anchor-root [backend node] "Tells the backend this is a temporary root") (delete-addr [backend addr session] "Deletes the given addr from storage")) (defrecord TestingBackend [] IBackend (new-session [_] (atom {:writes 0})) (anchor-root [_ root] root) (write-node [_ node session] (go-try (swap! session update-in [:writes] inc) (->TestingAddr (last-key node) node))) (delete-addr [_ addr session ])) (defn flush-tree "Given the tree, finds all dirty nodes, delivering addrs into them. Every dirty node also gets replaced with its TestingAddr. These form a GC cycle, have fun with the unmanaged memory port :)" ([tree backend] (go-try (let [session (new-session backend) flushed (<? (flush-tree tree backend session)) root (anchor-root backend flushed)] {:tree (<?resolve root) ; root should never be unresolved for API :stats session}))) ([tree backend stats] (go (if (dirty? tree) (let [cleaned-children (if (data-node? tree) (:children tree) TODO throw on nested errors (->> (flush-children (:children tree) backend stats) <? catvec)) cleaned-node (assoc tree :children cleaned-children) new-addr (<? (write-node backend cleaned-node stats))] (put! (:storage-addr tree) new-addr) (when (not= new-addr (<? (:storage-addr tree))) (delete-addr backend new-addr stats)) new-addr) tree)))) ;; The parts of the serialization system that seem like they're need hooks are: ;; - Must provide a function that takes a node, serializes it, and returns an addr ;; - Must be able to rollback writing an addr ;; - Whatever the addr it returns, it should cache its resolve in-mem somehow ;; - The serialize a node & rollback a node functions should accept a "stats" object as well ;; - The "stats" object must be convertible to a summary or whatever at the end
null
https://raw.githubusercontent.com/datacrypt-project/hitchhiker-tree/f7d0f926541d7cb31fac11c2d2245c5bac451b86/src/hitchhiker/tree/core.cljc
clojure
core.async helpers core code TODO maybe this is a good protocol? how to track dirty bits... could model w/ monad (ground state dirty unless loaded from storage), gets cleaned after each flush-flood individual nodes must be flushable A storage backend must be able to take a node as arg, serialize, assign addr, and call "clean" on the node to allow it to have a backing addr (N uses makes N useless copies). So perhaps each node can have a promise, it's address on storage. If the clean succeeds, they're done. If the clean fails (i.e. deliver fails), they roll back the write and read the address from the promise. Monads will be reserved for things we want persisted, rather than the in-memory flushing system, which can afford extra communication We can totally rely on a caching layer to manage keeping nodes around for when a single tree is passed to several different consumers. This layer so that we can supply the data to all of them when we fetch it. The cache So flushing writes are shared, but loading from disk is cached instead. Maybe write flushing could itself just be a smaller (or bigger) "write cache"... no, that could be defeated by really big writes, which are already guaranteed to be resident (since they were pending and thus linked to the tree's root). that keep pointers to the nodes they "stored". Importantly, it needs to record each read and write operation into counters, so that we can run a test and check the total IOPS we spent. The advanced work with this will allow us to define hard IOPS bounds (based on proven data), and then send generated loads to check we stay within our targets. By default, we use the default comparator TODO enforce that there always (= (count children) (inc (count keys))) TODO we should be able to find all uncommited data by searching for resolved & unresolved children This is written like so because it's performance critical TODO apparently RRB-vectors don't freeze correctly; we'll force it to a normal vector as a workaround Should have between b & 2b-1 children (println (b-tree :foo :bar :baz)) (clojure.pprint/pprint path) TODO this function would benefit from a prefetching hint We must get back down to the data node iterate cannot do blocking operations with core.async, so we use a loop butlast ensures we end w/ node Get the indices of it alternating node/index/node/index/node... of the search taken current search node TODO what are the semantics for exceeding on the right? currently it's trunc to the last element this is only for the REPL and testing splice the split into the parent TODO this assoc-in seems to be a bottleneck TODO: cool optimization: when merging children, push as many operations as you can don't care about the found key or its index Check for special root underflow case splice the split into the parent TODO this needs to use a polymorphic sibling-count to work on serialized nodes if true, `node` is left root should never be unresolved for API The parts of the serialization system that seem like they're need hooks are: - Must provide a function that takes a node, serializes it, and returns an addr - Must be able to rollback writing an addr - Whatever the addr it returns, it should cache its resolve in-mem somehow - The serialize a node & rollback a node functions should accept a "stats" object as well - The "stats" object must be convertible to a summary or whatever at the end
(ns hitchhiker.tree.core (:refer-clojure :exclude [compare resolve subvec]) (:require [clojure.core.rrb-vector :refer [catvec subvec]] #?(:clj [clojure.pprint :as pp]) #?(:clj [clojure.core.async :refer [go chan put! <! <!! promise-chan] :as async] :cljs [cljs.core.async :refer [chan put! <! promise-chan] :as async]) #?(:cljs [goog.array]) #?(:clj [taoensso.nippy :as nippy])) #?(:clj (:import java.io.Writer [java.util Arrays Collections])) #?(:cljs (:require-macros [cljs.core.async.macros :refer [go]] [hitchhiker.tree.core :refer [go-try <? <?resolve]]))) cljs macro environment (defn- cljs-env? "Take the &env from a macro, and tell whether we are expanding into cljs." [env] (boolean (:ns env))) #?(:clj (defmacro if-cljs "Return then if we are generating cljs code and else for Clojure code. " [then else] (if (cljs-env? &env) then else))) (defn throw-if-exception "Helper method that checks if x is Exception and if yes, wraps it in a new exception, passing though ex-data if any, and throws it. The wrapping is done to maintain a full stack trace when jumping between multiple contexts." [x] (if (instance? #?(:clj Exception :cljs js/Error) x) (throw (ex-info (or #?(:clj (.getMessage x)) (str x)) (or (ex-data x) {}) x)) x)) #?(:clj (defmacro go-try "Asynchronously executes the body in a go block. Returns a channel which will receive the result of the body when completed or the exception if an exception is thrown. You are responsible to take this exception and deal with it! This means you need to take the result from the channel at some point." {:style/indent 1} [ & body] `(if-cljs (cljs.core.async.macros/go (try ~@body (catch js/Error e# e#))) (go (try ~@body (catch Exception e# e#)))))) #?(:clj (defmacro <? "Same as core.async <! but throws an exception if the channel returns a throwable error." [ch] `(if-cljs (throw-if-exception (cljs.core.async/<! ~ch)) (throw-if-exception (<! ~ch))))) #?(:clj (defn <?? "Same as core.async <!! but throws an exception if the channel returns a throwable error." [ch] (throw-if-exception (<!! ch)))) (defn reduce< "Reduces over a sequence s with a go function go-f given the initial value init." [go-f init s] (go-try (loop [res init [f & r] s] (if f (recur (<? (go-f res f)) r) res)))) (defrecord Config [index-b data-b op-buf-size]) (defprotocol IKeyCompare (compare [key1 key2])) (defprotocol IResolve "All nodes must implement this protocol. It's includes the minimal functionality necessary to avoid resolving nodes unless strictly necessary." (index? [_] "Returns true if this is an index node") (last-key [_] "Returns the rightmost key of the node") (dirty? [_] "Returns true if this should be flushed") TODO resolve should be instrumented (resolve [_] "Returns the INode version of this node in a go-block; could trigger IO")) (defn tree-node? [node] (satisfies? IResolve node)) (defprotocol INode (overflow? [node] "Returns true if this node has too many elements") (underflow? [node] "Returns true if this node has too few elements") (merge-node [node other] "Combines this node with the other to form a bigger node. We assume they're siblings") (split-node [node] "Returns a Split object with the 2 nodes that we turned this into") (lookup [node key] "Returns the child node which contains the given key")) (defrecord Split [left right median]) Maybe disk backing should n't be done as a monad , since that double the total IOPS when 2 users of a snapshot need flush / clones When someone wants to flush it , they first dump it to disk , then try to clean it . will make it easier ta manage the overall JVM 's memory allocation , and it 's far simpler than trying to use weak pointers to track unresolved will also have better GC properties , by not accidentally sticking random tree bits into jvm GC roots that could be held a long time . We 'll make an IOPS measuring backend , which specifically makes " fake " (extend-protocol IKeyCompare #?@(:clj [Object (compare [key1 key2] (clojure.core/compare key1 key2)) Double (compare [^Double key1 key2] (if (instance? Double key2) (.compareTo key1 key2) (clojure.core/compare key1 key2))) Long (compare [^Long key1 key2] (if (instance? Long key2) (.compareTo key1 key2)) (clojure.core/compare key1 key2))] :cljs [number (compare [key1 key2] (cljs.core/compare key1 key2)) object (compare [key1 key2] (cljs.core/compare key1 key2))])) (declare data-node dirty!) (defn index-node-keys "Calculates the separating keys given the children of an index node" [children] (mapv last-key (butlast children))) (declare ->IndexNode) (defrecord IndexNode [children storage-addr op-buf cfg] IResolve (index? [this] true) (dirty? [this] (not (async/poll! storage-addr))) (resolve [this] (go this)) (last-key [this] TODO should optimize by caching to reduce IOps ( can use monad ) (last-key (peek children))) INode (overflow? [this] (>= (count children) (* 2 (:index-b cfg)))) (underflow? [this] (< (count children) (:index-b cfg))) (split-node [this] (let [b (:index-b cfg) median (nth (index-node-keys children) (dec b)) [left-buf right-buf] (split-with #(not (pos? (compare (:key %) median))) TODO this should use msg / affects - key (sort-by :key op-buf))] (->Split (->IndexNode (subvec children 0 b) (promise-chan) (vec left-buf) cfg) (->IndexNode (subvec children b) (promise-chan) (vec right-buf) cfg) median))) (merge-node [this other] (->IndexNode (catvec children (:children other)) (promise-chan) (catvec op-buf (:op-buf other)) cfg)) (lookup [root key] (let [l (dec (count children)) a (object-array l) _ (dotimes [i l] (aset a i (last-key (nth children i)))) x #?(:clj (Arrays/binarySearch a 0 l key compare) :cljs (goog.array/binarySearch a key compare))] (if (neg? x) (- (inc x)) x)))) #?(:clj (nippy/extend-freeze IndexNode :b-tree/index-node [{:keys [storage-addr cfg children op-buf]} data-output] (nippy/freeze-to-out! data-output cfg) (nippy/freeze-to-out! data-output children) (nippy/freeze-to-out! data-output (into [] op-buf)))) #?(:clj (nippy/extend-thaw :b-tree/index-node [data-input] (let [cfg (nippy/thaw-from-in! data-input) children (nippy/thaw-from-in! data-input) op-buf (nippy/thaw-from-in! data-input)] (->IndexNode children nil op-buf cfg)))) (defn index-node? [node] (instance? IndexNode node)) #?(:clj (defn print-index-node "Optionally include" [node ^Writer writer fully-qualified?] (.write writer (if fully-qualified? (pr-str IndexNode) "IndexNode")) (.write writer (str {:keys (index-node-keys (:children node)) :children (:children node)})))) #?(:clj (defmethod print-method IndexNode [node writer] (print-index-node node writer false))) #?(:clj (defmethod print-dup IndexNode [node writer] (print-index-node node writer true))) #?(:clj (defn node-status-bits [node] (str "[" (if (dirty? node) "D" " ") "]"))) #?(:clj (defmethod pp/simple-dispatch IndexNode [node] (let [out ^Writer *out*] (.write out "IndexNode") (.write out (node-status-bits node)) (pp/pprint-logical-block :prefix "{" :suffix "}" (pp/pprint-logical-block (.write out ":keys ") (pp/write-out (index-node-keys (:children node))) (pp/pprint-newline :linear)) (pp/pprint-logical-block (.write out ":op-buf ") (pp/write-out (:op-buf node)) (pp/pprint-newline :linear)) (pp/pprint-logical-block (.write out ":children ") (pp/pprint-newline :mandatory) (pp/write-out (:children node))))))) (defn nth-of-set "Like nth, but for sorted sets. O(n)" [set index] (first (drop index set))) (defrecord DataNode [children storage-addr cfg] IResolve (index? [this] false) (resolve [this] (go this)) (dirty? [this] (not (async/poll! storage-addr))) (last-key [this] (when (seq children) (-> children (rseq) (first) (key)))) INode (overflow? [this] (>= (count children) (* 2 (:data-b cfg)))) (underflow? [this] (< (count children) (:data-b cfg))) (split-node [this] (->Split (data-node cfg (into (sorted-map-by compare) (take (:data-b cfg)) children)) (data-node cfg (into (sorted-map-by compare) (drop (:data-b cfg)) children)) (nth-of-set children (dec (:data-b cfg))))) (merge-node [this other] (data-node cfg (into children (:children other)))) (lookup [root key] (let [x #?(:clj (Collections/binarySearch (vec (keys children)) key compare) :cljs (goog.array/binarySearch (into-array (keys children)) key compare))] (if (neg? x) (- (inc x)) x)))) (defn data-node "Creates a new data node" [cfg children] (->DataNode children (promise-chan) cfg)) (defn data-node? [node] (instance? DataNode node)) #?(:clj (defmacro <?resolve "HACK Attempt faster inlined resolve to avoid unnecessary channel ops." [e] `(if (or (data-node? ~e) (index-node? ~e)) ~e (<? (resolve ~e))))) #?(:clj (nippy/extend-freeze DataNode :b-tree/data-node [{:keys [cfg children]} data-output] (nippy/freeze-to-out! data-output cfg) (nippy/freeze-to-out! data-output children))) #?(:clj (nippy/extend-thaw :b-tree/data-node [data-input] (let [cfg (nippy/thaw-from-in! data-input) children (nippy/thaw-from-in! data-input)] (->DataNode children nil cfg)))) ( pp / pprint ( apply b - tree ( range 100 ) ) ) #?(:clj (defn print-data-node [node ^Writer writer fully-qualified?] (.write writer (if fully-qualified? (pr-str DataNode) "DataNode")) (.write writer (str {:children (:children node)})))) #?(:clj (defmethod print-method DataNode [node writer] (print-data-node node writer false))) #?(:clj (defmethod print-dup DataNode [node writer] (print-data-node node writer true))) #?(:clj (defmethod pp/simple-dispatch DataNode [node] (let [out ^Writer *out*] (.write out (str "DataNode" (node-status-bits node))) (.write out (str {:children (:children node)}))))) (defn backtrack-up-path-until "Given a path (starting with root and ending with an index), searches backwards, passing each pair of parent & index we just came from to the predicate function. When that function returns true, we return the path ending in the index for which it was true, or else we return the empty path" [path pred] (loop [path path] (when (seq path) (let [from-index (peek path) tmp (pop path) parent (peek tmp)] (if (pred parent from-index) path (recur (pop tmp))))))) (defn right-successor "Given a node on a path, find's that node's right successor node" [path] to keep the next several sibs in mem (go-try (when-let [common-parent-path (backtrack-up-path-until path (fn [parent index] (< (inc index) (count (:children parent)))))] (let [next-index (-> common-parent-path peek inc) parent (-> common-parent-path pop peek) new-sibling (<?resolve (nth (:children parent) next-index)) sibling-lineage (loop [res [new-sibling] s new-sibling] (let [c (-> s :children first) c (if (tree-node? c) (<?resolve c) c)] (if (or (index-node? c) (data-node? c)) (recur (conj res c) c) res))) path-suffix (-> (interleave sibling-lineage (repeat 0)) ] (-> (pop common-parent-path) (conj next-index) (into path-suffix)))))) (defn forward-iterator "Takes the result of a search and puts the iterated elements onto iter-ch going forward over the tree as needed. Does lg(n) backtracking sometimes." [iter-ch path start-key] (go-try (loop [path path] (if path (let [start-node (peek path) _ (assert (data-node? start-node)) elements (-> start-node (subseq >= start-key))] (<? (async/onto-chan iter-ch elements false)) (recur (<? (right-successor (pop path))))) (async/close! iter-ch))))) (defn lookup-path "Given a B-tree and a key, gets a path into the tree" [tree key] (go-try ] (if (seq (:children cur)) (if (data-node? cur) path (let [index (lookup cur key) child (if (data-node? cur) nil #_(nth-of-set (:children cur) index) (-> (:children cur) (nth index (peek (:children cur))) (<?resolve))) path' (conj path index child)] (recur path' child))) nil)))) (defn lookup-key "Given a B-tree and a key, gets an iterator into the tree" ([tree key] (lookup-key tree key nil)) ([tree key not-found] (go-try (-> (-> (<? (lookup-path tree key)) (peek) (<?resolve)) :children (get key not-found))))) #?(:clj (defn chan-seq [ch] (when-some [v (<?? ch)] (cons v (lazy-seq (chan-seq ch)))))) #?(:clj (defn lookup-fwd-iter "Compatibility helper to clojure sequences. Please prefer the channel interface of forward-iterator, as this function blocks your thread, which disturbs async contexts and might lead to poor performance. It is mainly here to facilitate testing." [tree key] (let [path (<?? (lookup-path tree key)) iter-ch (chan)] (forward-iterator iter-ch path key) (chan-seq iter-ch)))) (defn insert [{:keys [cfg] :as tree} key value] (go-try (let [path (<? (lookup-path tree key)) {:keys [children] :or {children (sorted-map-by compare)}} (peek path) updated-data-node (data-node cfg (assoc children key value))] (loop [node updated-data-node path (pop path)] (if (empty? path) (if (overflow? node) (let [{:keys [left right median]} (split-node node)] (->IndexNode [left right] (promise-chan) [] cfg)) node) (let [index (peek path) {:keys [children keys] :as parent} (peek (pop path))] TODO refactor paths to be node / index pairs or 2 vectors or something (let [{:keys [left right median]} (split-node node) new-children (catvec (conj (subvec children 0 index) left right) (subvec children (inc index)))] (recur (-> parent (assoc :children new-children) (dirty!)) (pop (pop path)))) (recur (-> parent (assoc-in [:children index] node) (dirty!)) (pop (pop path)))))))))) into them to opportunistically minimize overall IO costs (defn delete [{:keys [cfg] :as tree} key] (go-try {:keys [children] :or {children (sorted-map-by compare)}} (peek path) updated-data-node (data-node cfg (dissoc children key))] (loop [node updated-data-node path (pop path)] (if (empty? path) (if (and (index-node? node) (= 1 (count (:children node)))) (first (:children node)) node) (let [index (peek path) {:keys [children keys op-buf] :as parent} (peek (pop path))] (let [bigger-sibling-idx (cond only have left sib only have right sib (> (count (:children (nth children (dec index)))) (count (:children (nth children (inc index))))) right sib bigger :else (inc index)) merged (if node-first? (merge-node node (<?resolve (nth children bigger-sibling-idx))) (merge-node (<?resolve (nth children bigger-sibling-idx)) node)) old-left-children (subvec children 0 (min index bigger-sibling-idx)) old-right-children (subvec children (inc (max index bigger-sibling-idx)))] (if (overflow? merged) (let [{:keys [left right median]} (split-node merged)] (recur (->IndexNode (catvec (conj old-left-children left right) old-right-children) (promise-chan) op-buf cfg) (pop (pop path)))) (recur (->IndexNode (catvec (conj old-left-children merged) old-right-children) (promise-chan) op-buf cfg) (pop (pop path))))) (recur (->IndexNode (assoc children index node) (promise-chan) op-buf cfg) (pop (pop path)))))))))) (defn b-tree [cfg & kvs] (go-try (loop [[[k v] & r] (partition 2 kvs) t (data-node cfg (sorted-map-by compare))] (if k (recur r (<? (insert t k v))) t))) #_(reduce (fn [t [k v]] (insert t k v)) (data-node cfg (sorted-map-by compare)) (partition 2 kvs))) (defrecord TestingAddr [last-key node] IResolve (dirty? [this] false) (last-key [_] last-key) (resolve [_] (go node))) #?(:clj (defn print-testing-addr [node ^Writer writer fully-qualified?] (.write writer (if fully-qualified? (pr-str TestingAddr) "TestingAddr")) (.write writer (str {})))) #?(:clj (defmethod print-method TestingAddr [node writer] (print-testing-addr node writer false))) #?(:clj (defmethod print-dup TestingAddr [node writer] (print-testing-addr node writer true))) #?(:clj (defmethod pp/simple-dispatch TestingAddr [node] (let [out ^Writer *out*] (.write out (str "TestingAddr" (node-status-bits node))) (.write out (str {}))))) (defn dirty! "Marks a node as being dirty if it was clean" [node] (assert (not (instance? TestingAddr node))) (assoc node :storage-addr (promise-chan))) TODO make this a loop / recur instead of mutual recursion (declare flush-tree) (defn flush-children [children backend session] (go-try (loop [[c & r] children res []] (if-not c res (recur r (conj res (<? (flush-tree c backend session)))))))) (defprotocol IBackend (new-session [backend] "Returns a session object that will collect stats") (write-node [backend node session] "Writes the given node to storage, returning a go-block with its assigned address") (anchor-root [backend node] "Tells the backend this is a temporary root") (delete-addr [backend addr session] "Deletes the given addr from storage")) (defrecord TestingBackend [] IBackend (new-session [_] (atom {:writes 0})) (anchor-root [_ root] root) (write-node [_ node session] (go-try (swap! session update-in [:writes] inc) (->TestingAddr (last-key node) node))) (delete-addr [_ addr session ])) (defn flush-tree "Given the tree, finds all dirty nodes, delivering addrs into them. Every dirty node also gets replaced with its TestingAddr. These form a GC cycle, have fun with the unmanaged memory port :)" ([tree backend] (go-try (let [session (new-session backend) flushed (<? (flush-tree tree backend session)) root (anchor-root backend flushed)] :stats session}))) ([tree backend stats] (go (if (dirty? tree) (let [cleaned-children (if (data-node? tree) (:children tree) TODO throw on nested errors (->> (flush-children (:children tree) backend stats) <? catvec)) cleaned-node (assoc tree :children cleaned-children) new-addr (<? (write-node backend cleaned-node stats))] (put! (:storage-addr tree) new-addr) (when (not= new-addr (<? (:storage-addr tree))) (delete-addr backend new-addr stats)) new-addr) tree))))
2209e13eebe707773baaa2179508e48f31b8e06209b5c3d7c6874b5af83da71a
jaked/orpc
server_impl.ml
let rec lst_map f l = match l with | `Nil -> `Nil | `Cons (a,l) -> `Cons (f a, lst_map f l) module Sync = struct type 'a _r = 'a let add1 i = i + 1 let add1_list l = List.map (fun i -> i + 1) l let add1_pair (a, b) = (a + 1, b + 1) let add1_r { Types.fst = f; snd = s; trd = t } = { Types.fst = f + 1; snd = (match s with None -> None | Some s -> Some (s + 1)); trd = Array.map (fun e -> e + 1) t; } let add1_lst l = lst_map (fun i -> i + 1) l let addN ?(n = 1) i = i + n let maybe_raise flag = if flag then raise (Protocol.Bar 17) end module Lwt = struct type 'a _r = 'a Lwt.t open Lwt let add1 i = return (i + 1) let add1_list l = return (List.map (fun i -> i + 1) l) let add1_pair (a, b) = return (a + 1, b + 1) let add1_r { Types.fst = f; snd = s; trd = t } = return { Types.fst = f + 1; snd = (match s with None -> None | Some s -> Some (s + 1)); trd = Array.map (fun e -> e + 1) t; } let add1_lst l = return (lst_map (fun i -> i + 1) l) let addN ?(n=1) i = return (i + n) let maybe_raise flag = if flag then fail (Protocol.Bar 17) else return () end
null
https://raw.githubusercontent.com/jaked/orpc/ecb5df8ec928070cd89cf035167fcedf3623ee3c/examples/external/server_impl.ml
ocaml
let rec lst_map f l = match l with | `Nil -> `Nil | `Cons (a,l) -> `Cons (f a, lst_map f l) module Sync = struct type 'a _r = 'a let add1 i = i + 1 let add1_list l = List.map (fun i -> i + 1) l let add1_pair (a, b) = (a + 1, b + 1) let add1_r { Types.fst = f; snd = s; trd = t } = { Types.fst = f + 1; snd = (match s with None -> None | Some s -> Some (s + 1)); trd = Array.map (fun e -> e + 1) t; } let add1_lst l = lst_map (fun i -> i + 1) l let addN ?(n = 1) i = i + n let maybe_raise flag = if flag then raise (Protocol.Bar 17) end module Lwt = struct type 'a _r = 'a Lwt.t open Lwt let add1 i = return (i + 1) let add1_list l = return (List.map (fun i -> i + 1) l) let add1_pair (a, b) = return (a + 1, b + 1) let add1_r { Types.fst = f; snd = s; trd = t } = return { Types.fst = f + 1; snd = (match s with None -> None | Some s -> Some (s + 1)); trd = Array.map (fun e -> e + 1) t; } let add1_lst l = return (lst_map (fun i -> i + 1) l) let addN ?(n=1) i = return (i + n) let maybe_raise flag = if flag then fail (Protocol.Bar 17) else return () end
91ee1cad3166994c8f26b55f17f74697b2c5c51c0c82c677b7aa4e4b8be29031
evdubs/chart-simulator
descending-triangle.rkt
#lang racket/base (require racket/stream racket/vector "../structs.rkt" "../technical-indicators.rkt") (provide descending-triangle-execution) (struct descending-triangle-in (dohlc sma-20 sma-20-slope sma-50 sma-50-slope satr-50 dc-25-high dc-25-low dc-25-prev-high dc-25-prev-low) #:transparent) (define (descending-triangle t ; timeframe entry stop target p ; position h ; history i) ; market data inputs (if (or (stream-empty? (descending-triangle-in-dohlc i)) (stream-empty? (descending-triangle-in-sma-20 i)) (stream-empty? (descending-triangle-in-sma-20-slope i)) (stream-empty? (descending-triangle-in-sma-50 i)) (stream-empty? (descending-triangle-in-sma-50-slope i)) (stream-empty? (descending-triangle-in-satr-50 i)) (stream-empty? (descending-triangle-in-dc-25-high i)) (stream-empty? (descending-triangle-in-dc-25-low i)) (stream-empty? (descending-triangle-in-dc-25-prev-high i)) (stream-empty? (descending-triangle-in-dc-25-prev-low i))) h (let ([date (dohlc-date (stream-first (descending-triangle-in-dohlc i)))] [open (dohlc-open (stream-first (descending-triangle-in-dohlc i)))] [high (dohlc-high (stream-first (descending-triangle-in-dohlc i)))] [low (dohlc-low (stream-first (descending-triangle-in-dohlc i)))] [close (dohlc-close (stream-first (descending-triangle-in-dohlc i)))] [sma-20 (dv-value (stream-first (descending-triangle-in-sma-20 i)))] [sma-20-slope (dv-value (stream-first (descending-triangle-in-sma-20-slope i)))] [sma-50 (dv-value (stream-first (descending-triangle-in-sma-50 i)))] [sma-50-slope (dv-value (stream-first (descending-triangle-in-sma-50-slope i)))] [satr (dv-value (stream-first (descending-triangle-in-satr-50 i)))] [dc-25-high (dv-value (stream-first (descending-triangle-in-dc-25-high i)))] [dc-25-low (dv-value (stream-first (descending-triangle-in-dc-25-low i)))] [dc-25-prev-high (dv-value (stream-first (descending-triangle-in-dc-25-prev-high i)))] [dc-25-prev-low (dv-value (stream-first (descending-triangle-in-dc-25-prev-low i)))]) ( t ) ( ) ( h ) ( printf " ~a ~a ~a ~a ~a ~a ~a ~a ~a ~a\n " date open high low close sma-20 sma-50 satr dc - high dc - low ) (cond found satisfactory conditions for entry for the first time [(and (null? t) (null? p) (< satr (* close 4/100)) (< sma-20 sma-50) (> 0 sma-50-slope) (< close sma-20) (> 0 sma-20-slope) (< close (+ dc-25-low (* satr 4/2))) (< dc-25-low dc-25-prev-low) (< dc-25-prev-low (* dc-25-low 101/100)) (< (+ dc-25-high (* (- dc-25-high dc-25-low) 1/2)) dc-25-prev-high)) (let ([new-test (test 20 (- dc-25-low 5/100) (+ dc-25-low (* satr 2)) (- dc-25-low (* satr 4)))]) (descending-triangle new-test p (history (append (history-test h) (list (dv date new-test))) (history-trade h)) (descending-triangle-in-drop-1 i)))] ; satisfactory conditions no longer exist for entry [(and (not (null? t)) (null? p) (or (>= open (test-stop t)) (>= high (test-stop t)) (>= low (test-stop t)) (>= close (test-stop t)))) (descending-triangle null p h (descending-triangle-in-drop-1 i))] ; satisfactory conditions exist for entry and open price leads to execution [(and (not (null? t)) (null? p) (< open (test-entry t))) (descending-triangle t (position open -1) (history (history-test h) (append (history-trade h) (list (trade date open -1 t)))) (descending-triangle-in-drop-1 i))] ; satisfactory conditions exist for entry and price range leads to execution [(and (not (null? t)) (null? p) (>= open (test-entry t)) (>= high (test-entry t)) (<= low (test-entry t))) (descending-triangle t (position (test-entry t) -1) (history (history-test h) (append (history-trade h) (list (trade date (test-entry t) -1 t)))) (descending-triangle-in-drop-1 i))] ; have position and open above stop [(and (not (null? p)) (>= open (test-stop t))) (descending-triangle null null (history (history-test h) (append (history-trade h) (list (trade date open 1 t)))) (descending-triangle-in-drop-1 i))] ; have position and price range above stop [(and (not (null? p)) (< open (test-stop t)) (>= high (test-stop t)) (<= low (test-stop t))) (descending-triangle null null (history (history-test h) (append (history-trade h) (list (trade date (test-stop t) 1 t)))) (descending-triangle-in-drop-1 i))] ; have position and both parts of open/close below target and stop [(and (not (null? p)) (< open (test-target t)) (< close (test-target t)) (< open (test-stop t)) (< close (test-stop t))) (let ([new-test (test (test-timeframe t) (test-entry t) (max open close) (test-target t))]) (descending-triangle new-test p (history (append (history-test h) (list (dv date new-test))) (history-trade h)) (descending-triangle-in-drop-1 i)))] ; have position and timeframe has ended [(and (not (null? p)) (= 0 (test-timeframe t))) (descending-triangle null null (history (history-test h) (append (history-trade h) (list (trade date close 1 t)))) (descending-triangle-in-drop-1 i))] ; have position and should move stop closer to close [(and (not (null? p)) (< (* 3 satr) (- (test-stop t) high))) (let ([new-test (test (- (test-timeframe t) 1) (test-entry t) ( + close ( * 2 satr ) ) (test-target t))]) (descending-triangle new-test p (history (append (history-test h) (list (dv date new-test))) (history-trade h)) (descending-triangle-in-drop-1 i)))] ; have position and can do nothing [(not (null? p)) (descending-triangle (test-timeframe-minus-1 t) p h (descending-triangle-in-drop-1 i))] ; have no position and can do nothing [else (descending-triangle t p h (descending-triangle-in-drop-1 i))])))) (define (descending-triangle-in-drop-1 atid) (descending-triangle-in (stream-rest (descending-triangle-in-dohlc atid)) (stream-rest (descending-triangle-in-sma-20 atid)) (stream-rest (descending-triangle-in-sma-20-slope atid)) (stream-rest (descending-triangle-in-sma-50 atid)) (stream-rest (descending-triangle-in-sma-50-slope atid)) (stream-rest (descending-triangle-in-satr-50 atid)) (stream-rest (descending-triangle-in-dc-25-high atid)) (stream-rest (descending-triangle-in-dc-25-low atid)) (stream-rest (descending-triangle-in-dc-25-prev-high atid)) (stream-rest (descending-triangle-in-dc-25-prev-low atid)))) (define (descending-triangle-execution dohlc-list) (let*-values ([(dohlc-vector) (list->vector dohlc-list)] [(sma-20) (simple-moving-average dohlc-vector 20)] [(sma-20-slope) (delta sma-20 50)] [(sma-50) (simple-moving-average dohlc-vector 50)] [(sma-50-slope) (delta sma-50 50)] [(satr-50) (simple-average-true-range dohlc-vector 50)] [(dc-25-high dc-25-low) (donchian-channel dohlc-vector 25)] [(dc-25-prev-high dc-25-prev-low) (values (shift dc-25-high 25) (shift dc-25-low 25))] [(min-length) (min (vector-length dohlc-vector) (vector-length sma-20) (vector-length sma-20-slope) (vector-length sma-50) (vector-length sma-50-slope) (vector-length satr-50) (vector-length dc-25-high) (vector-length dc-25-low) (vector-length dc-25-prev-high) (vector-length dc-25-prev-low))]) (descending-triangle null null (history (list) (list)) (descending-triangle-in (sequence->stream (vector-take-right dohlc-vector min-length)) (sequence->stream (vector-take-right sma-20 min-length)) (sequence->stream (vector-take-right sma-20-slope min-length)) (sequence->stream (vector-take-right sma-50 min-length)) (sequence->stream (vector-take-right sma-50-slope min-length)) (sequence->stream (vector-take-right satr-50 min-length)) (sequence->stream (vector-take-right dc-25-high min-length)) (sequence->stream (vector-take-right dc-25-low min-length)) (sequence->stream (vector-take-right dc-25-prev-high min-length)) (sequence->stream (vector-take-right dc-25-prev-low min-length))))))
null
https://raw.githubusercontent.com/evdubs/chart-simulator/a615e2a5c05a73bd712fdf6d7070a83d354754a8/strategy/descending-triangle.rkt
racket
timeframe entry stop target position history market data inputs satisfactory conditions no longer exist for entry satisfactory conditions exist for entry and open price leads to execution satisfactory conditions exist for entry and price range leads to execution have position and open above stop have position and price range above stop have position and both parts of open/close below target and stop have position and timeframe has ended have position and should move stop closer to close have position and can do nothing have no position and can do nothing
#lang racket/base (require racket/stream racket/vector "../structs.rkt" "../technical-indicators.rkt") (provide descending-triangle-execution) (struct descending-triangle-in (dohlc sma-20 sma-20-slope sma-50 sma-50-slope satr-50 dc-25-high dc-25-low dc-25-prev-high dc-25-prev-low) #:transparent) (if (or (stream-empty? (descending-triangle-in-dohlc i)) (stream-empty? (descending-triangle-in-sma-20 i)) (stream-empty? (descending-triangle-in-sma-20-slope i)) (stream-empty? (descending-triangle-in-sma-50 i)) (stream-empty? (descending-triangle-in-sma-50-slope i)) (stream-empty? (descending-triangle-in-satr-50 i)) (stream-empty? (descending-triangle-in-dc-25-high i)) (stream-empty? (descending-triangle-in-dc-25-low i)) (stream-empty? (descending-triangle-in-dc-25-prev-high i)) (stream-empty? (descending-triangle-in-dc-25-prev-low i))) h (let ([date (dohlc-date (stream-first (descending-triangle-in-dohlc i)))] [open (dohlc-open (stream-first (descending-triangle-in-dohlc i)))] [high (dohlc-high (stream-first (descending-triangle-in-dohlc i)))] [low (dohlc-low (stream-first (descending-triangle-in-dohlc i)))] [close (dohlc-close (stream-first (descending-triangle-in-dohlc i)))] [sma-20 (dv-value (stream-first (descending-triangle-in-sma-20 i)))] [sma-20-slope (dv-value (stream-first (descending-triangle-in-sma-20-slope i)))] [sma-50 (dv-value (stream-first (descending-triangle-in-sma-50 i)))] [sma-50-slope (dv-value (stream-first (descending-triangle-in-sma-50-slope i)))] [satr (dv-value (stream-first (descending-triangle-in-satr-50 i)))] [dc-25-high (dv-value (stream-first (descending-triangle-in-dc-25-high i)))] [dc-25-low (dv-value (stream-first (descending-triangle-in-dc-25-low i)))] [dc-25-prev-high (dv-value (stream-first (descending-triangle-in-dc-25-prev-high i)))] [dc-25-prev-low (dv-value (stream-first (descending-triangle-in-dc-25-prev-low i)))]) ( t ) ( ) ( h ) ( printf " ~a ~a ~a ~a ~a ~a ~a ~a ~a ~a\n " date open high low close sma-20 sma-50 satr dc - high dc - low ) (cond found satisfactory conditions for entry for the first time [(and (null? t) (null? p) (< satr (* close 4/100)) (< sma-20 sma-50) (> 0 sma-50-slope) (< close sma-20) (> 0 sma-20-slope) (< close (+ dc-25-low (* satr 4/2))) (< dc-25-low dc-25-prev-low) (< dc-25-prev-low (* dc-25-low 101/100)) (< (+ dc-25-high (* (- dc-25-high dc-25-low) 1/2)) dc-25-prev-high)) (let ([new-test (test 20 (- dc-25-low 5/100) (+ dc-25-low (* satr 2)) (- dc-25-low (* satr 4)))]) (descending-triangle new-test p (history (append (history-test h) (list (dv date new-test))) (history-trade h)) (descending-triangle-in-drop-1 i)))] [(and (not (null? t)) (null? p) (or (>= open (test-stop t)) (>= high (test-stop t)) (>= low (test-stop t)) (>= close (test-stop t)))) (descending-triangle null p h (descending-triangle-in-drop-1 i))] [(and (not (null? t)) (null? p) (< open (test-entry t))) (descending-triangle t (position open -1) (history (history-test h) (append (history-trade h) (list (trade date open -1 t)))) (descending-triangle-in-drop-1 i))] [(and (not (null? t)) (null? p) (>= open (test-entry t)) (>= high (test-entry t)) (<= low (test-entry t))) (descending-triangle t (position (test-entry t) -1) (history (history-test h) (append (history-trade h) (list (trade date (test-entry t) -1 t)))) (descending-triangle-in-drop-1 i))] [(and (not (null? p)) (>= open (test-stop t))) (descending-triangle null null (history (history-test h) (append (history-trade h) (list (trade date open 1 t)))) (descending-triangle-in-drop-1 i))] [(and (not (null? p)) (< open (test-stop t)) (>= high (test-stop t)) (<= low (test-stop t))) (descending-triangle null null (history (history-test h) (append (history-trade h) (list (trade date (test-stop t) 1 t)))) (descending-triangle-in-drop-1 i))] [(and (not (null? p)) (< open (test-target t)) (< close (test-target t)) (< open (test-stop t)) (< close (test-stop t))) (let ([new-test (test (test-timeframe t) (test-entry t) (max open close) (test-target t))]) (descending-triangle new-test p (history (append (history-test h) (list (dv date new-test))) (history-trade h)) (descending-triangle-in-drop-1 i)))] [(and (not (null? p)) (= 0 (test-timeframe t))) (descending-triangle null null (history (history-test h) (append (history-trade h) (list (trade date close 1 t)))) (descending-triangle-in-drop-1 i))] [(and (not (null? p)) (< (* 3 satr) (- (test-stop t) high))) (let ([new-test (test (- (test-timeframe t) 1) (test-entry t) ( + close ( * 2 satr ) ) (test-target t))]) (descending-triangle new-test p (history (append (history-test h) (list (dv date new-test))) (history-trade h)) (descending-triangle-in-drop-1 i)))] [(not (null? p)) (descending-triangle (test-timeframe-minus-1 t) p h (descending-triangle-in-drop-1 i))] [else (descending-triangle t p h (descending-triangle-in-drop-1 i))])))) (define (descending-triangle-in-drop-1 atid) (descending-triangle-in (stream-rest (descending-triangle-in-dohlc atid)) (stream-rest (descending-triangle-in-sma-20 atid)) (stream-rest (descending-triangle-in-sma-20-slope atid)) (stream-rest (descending-triangle-in-sma-50 atid)) (stream-rest (descending-triangle-in-sma-50-slope atid)) (stream-rest (descending-triangle-in-satr-50 atid)) (stream-rest (descending-triangle-in-dc-25-high atid)) (stream-rest (descending-triangle-in-dc-25-low atid)) (stream-rest (descending-triangle-in-dc-25-prev-high atid)) (stream-rest (descending-triangle-in-dc-25-prev-low atid)))) (define (descending-triangle-execution dohlc-list) (let*-values ([(dohlc-vector) (list->vector dohlc-list)] [(sma-20) (simple-moving-average dohlc-vector 20)] [(sma-20-slope) (delta sma-20 50)] [(sma-50) (simple-moving-average dohlc-vector 50)] [(sma-50-slope) (delta sma-50 50)] [(satr-50) (simple-average-true-range dohlc-vector 50)] [(dc-25-high dc-25-low) (donchian-channel dohlc-vector 25)] [(dc-25-prev-high dc-25-prev-low) (values (shift dc-25-high 25) (shift dc-25-low 25))] [(min-length) (min (vector-length dohlc-vector) (vector-length sma-20) (vector-length sma-20-slope) (vector-length sma-50) (vector-length sma-50-slope) (vector-length satr-50) (vector-length dc-25-high) (vector-length dc-25-low) (vector-length dc-25-prev-high) (vector-length dc-25-prev-low))]) (descending-triangle null null (history (list) (list)) (descending-triangle-in (sequence->stream (vector-take-right dohlc-vector min-length)) (sequence->stream (vector-take-right sma-20 min-length)) (sequence->stream (vector-take-right sma-20-slope min-length)) (sequence->stream (vector-take-right sma-50 min-length)) (sequence->stream (vector-take-right sma-50-slope min-length)) (sequence->stream (vector-take-right satr-50 min-length)) (sequence->stream (vector-take-right dc-25-high min-length)) (sequence->stream (vector-take-right dc-25-low min-length)) (sequence->stream (vector-take-right dc-25-prev-high min-length)) (sequence->stream (vector-take-right dc-25-prev-low min-length))))))
513cb6b10796be511950a47b257f1d0ab532501640c9dad028fc95c05816d5e3
simplegeo/erlang
string_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2004 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %%%---------------------------------------------------------------- %%% Purpose: string test suite. %%%----------------------------------------------------------------- -module(string_SUITE). -include("test_server.hrl"). % Default timetrap timeout (set in init_per_testcase). -define(default_timeout, ?t:minutes(1)). % Test server specific exports -export([all/1]). -export([init_per_testcase/2, fin_per_testcase/2]). % Test cases must be exported. -export([len/1,equal/1,concat/1,chr_rchr/1,str_rstr/1]). -export([span_cspan/1,substr/1,tokens/1,chars/1]). -export([copies/1,words/1,strip/1,sub_word/1,left_right/1]). -export([sub_string/1,centre/1, join/1]). -export([to_integer/1,to_float/1]). -export([to_upper_to_lower/1]). %% %% all/1 %% all(doc) -> []; all(suite) -> [len,equal,concat,chr_rchr,str_rstr, span_cspan,substr,tokens,chars, copies,words,strip,sub_word,left_right, sub_string,centre, join, to_integer,to_float,to_upper_to_lower]. init_per_testcase(_Case, Config) -> ?line Dog=test_server:timetrap(?default_timeout), [{watchdog, Dog}|Config]. fin_per_testcase(_Case, Config) -> Dog=?config(watchdog, Config), test_server:timetrap_cancel(Dog), ok. % % Test cases starts here. % len(suite) -> []; len(doc) -> []; len(Config) when is_list(Config) -> ?line 0 = string:len(""), ?line L = tuple_size(list_to_tuple(atom_to_list(?MODULE))), ?line L = string:len(atom_to_list(?MODULE)), %% invalid arg type ?line {'EXIT',_} = (catch string:len({})), ok. equal(suite) -> []; equal(doc) -> []; equal(Config) when is_list(Config) -> ?line true = string:equal("", ""), ?line false = string:equal("", " "), ?line true = string:equal("laban", "laban"), ?line false = string:equal("skvimp", "skvump"), %% invalid arg type ?line true = string:equal(2, 2), % not good, should crash ok. concat(suite) -> []; concat(doc) -> []; concat(Config) when is_list(Config) -> ?line "erlang rules" = string:concat("erlang ", "rules"), ?line "" = string:concat("", ""), ?line "x" = string:concat("x", ""), ?line "y" = string:concat("", "y"), %% invalid arg type ?line {'EXIT',_} = (catch string:concat(hello, please)), ok. chr_rchr(suite) -> []; chr_rchr(doc) -> []; chr_rchr(Config) when is_list(Config) -> ?line {_,_,X} = now(), ?line 0 = string:chr("", (X rem (255-32)) + 32), ?line 0 = string:rchr("", (X rem (255-32)) + 32), ?line 1 = string:chr("x", $x), ?line 1 = string:rchr("x", $x), ?line 1 = string:chr("xx", $x), ?line 2 = string:rchr("xx", $x), ?line 3 = string:chr("xyzyx", $z), ?line 3 = string:rchr("xyzyx", $z), %% invalid arg type ?line {'EXIT',_} = (catch string:chr(hello, $h)), %% invalid arg type ?line {'EXIT',_} = (catch string:chr("hello", h)), %% invalid arg type ?line {'EXIT',_} = (catch string:rchr(hello, $h)), %% invalid arg type ?line {'EXIT',_} = (catch string:rchr("hello", h)), ok. str_rstr(suite) -> []; str_rstr(doc) -> []; str_rstr(Config) when is_list(Config) -> ?line {_,_,X} = now(), ?line 0 = string:str("", [(X rem (255-32)) + 32]), ?line 0 = string:rstr("", [(X rem (255-32)) + 32]), ?line 1 = string:str("x", "x"), ?line 1 = string:rstr("x", "x"), ?line 0 = string:str("hello", ""), ?line 0 = string:rstr("hello", ""), ?line 1 = string:str("xxxx", "xx"), ?line 3 = string:rstr("xxxx", "xx"), ?line 3 = string:str("xy z yx", " z"), ?line 3 = string:rstr("xy z yx", " z"), %% invalid arg type ?line {'EXIT',_} = (catch string:str(hello, "he")), %% invalid arg type ?line {'EXIT',_} = (catch string:str("hello", he)), %% invalid arg type ?line {'EXIT',_} = (catch string:rstr(hello, "he")), %% invalid arg type ?line {'EXIT',_} = (catch string:rstr("hello", he)), ok. span_cspan(suite) -> []; span_cspan(doc) -> []; span_cspan(Config) when is_list(Config) -> ?line 0 = string:span("", "1"), ?line 0 = string:span("1", ""), ?line 0 = string:cspan("", "1"), ?line 1 = string:cspan("1", ""), ?line 1 = string:span("1 ", "1"), ?line 5 = string:span(" 1 ", "12 "), ?line 6 = string:span("1231234", "123"), ?line 0 = string:cspan("1 ", "1"), ?line 1 = string:cspan("3 ", "12 "), ?line 6 = string:cspan("1231234", "4"), %% invalid arg type ?line {'EXIT',_} = (catch string:span(1234, "1")), %% invalid arg type ?line {'EXIT',_} = (catch string:span(1234, "1")), %% invalid arg type ?line {'EXIT',_} = (catch string:cspan("1234", 1)), %% invalid arg type ?line {'EXIT',_} = (catch string:cspan("1234", 4)), ok. substr(suite) -> []; substr(doc) -> []; substr(Config) when is_list(Config) -> ?line {'EXIT',_} = (catch string:substr("", 0)), ?line [] = string:substr("", 1), ?line {'EXIT',_} = (catch string:substr("", 2)), ?line [] = string:substr("1", 2), ?line {'EXIT',_} = (catch string:substr("", 0, 1)), ?line [] = string:substr("", 1, 1), ?line [] = string:substr("", 1, 2), ?line {'EXIT',_} = (catch string:substr("", 2, 2)), ?line "1234" = string:substr("1234", 1), ?line "1234" = string:substr("1234", 1, 4), ?line "1234" = string:substr("1234", 1, 5), ?line "23" = string:substr("1234", 2, 2), ?line "4" = string:substr("1234", 4), ?line "" = string:substr("1234", 4, 0), ?line "4" = string:substr("1234", 4, 1), %% invalid arg type ?line {'EXIT',_} = (catch string:substr(1234, 1)), %% invalid arg type ?line {'EXIT',_} = (catch string:substr("1234", "1")), ok. tokens(suite) -> []; tokens(doc) -> []; tokens(Config) when is_list(Config) -> ?line [] = string:tokens("",""), ?line [] = string:tokens("abc","abc"), ?line ["abc"] = string:tokens("abc", ""), ?line ["1","2 34","4","5"] = string:tokens("1,2 34,4;5", ";,"), %% invalid arg type ?line {'EXIT',_} = (catch string:tokens('x,y', ",")), %% invalid arg type ?line {'EXIT',_} = (catch string:tokens("x,y", ',')), ok. chars(suite) -> []; chars(doc) -> []; chars(Config) when is_list(Config) -> ?line [] = string:chars($., 0), ?line [] = string:chars($., 0, []), ?line 10 = length(string:chars(32, 10, [])), ?line "aaargh" = string:chars($a, 3, "rgh"), %% invalid arg type ?line {'EXIT',_} = (catch string:chars($x, [])), ok. copies(suite) -> []; copies(doc) -> []; copies(Config) when is_list(Config) -> ?line "" = string:copies("", 10), ?line "" = string:copies(".", 0), ?line "." = string:copies(".", 1), ?line 30 = length(string:copies("123", 10)), %% invalid arg type ?line {'EXIT',_} = (catch string:chars("hej", -1)), ok. words(suite) -> []; words(doc) -> []; words(Config) when is_list(Config) -> ?line 1 = string:words(""), ?line 1 = string:words("", $,), ?line 1 = string:words("hello"), ?line 1 = string:words("hello", $,), ?line 1 = string:words("...", $.), ?line 2 = string:words("2.35", $.), ?line 100 = string:words(string:copies(". ", 100)), %% invalid arg type ?line {'EXIT',_} = (catch string:chars(hej)), %% invalid arg type ?line {'EXIT',_} = (catch string:chars("hej", " ")), ok. strip(suite) -> []; strip(doc) -> []; strip(Config) when is_list(Config) -> ?line "" = string:strip(""), ?line "" = string:strip("", both), ?line "" = string:strip("", both, $.), ?line "hej" = string:strip(" hej "), ?line "hej " = string:strip(" hej ", left), ?line " hej" = string:strip(" hej ", right), ?line " hej " = string:strip(" hej ", right, $.), ?line "hej hopp" = string:strip(" hej hopp ", both), %% invalid arg type ?line {'EXIT',_} = (catch string:strip(hej)), %% invalid arg type ?line {'EXIT',_} = (catch string:strip(" hej", up)), %% invalid arg type ?line {'EXIT',_} = (catch string:strip(" hej", left, " ")), % not good ok. sub_word(suite) -> []; sub_word(doc) -> []; sub_word(Config) when is_list(Config) -> ?line "" = string:sub_word("", 1), ?line "" = string:sub_word("", 1, $,), ?line {'EXIT',_} = (catch string:sub_word("1 2 3", 0)), ?line "" = string:sub_word("1 2 3", 4), ?line "llo th" = string:sub_word("but hello there", 2, $e), %% invalid arg type ?line {'EXIT',_} = (catch string:sub_word('hello there', 1)), %% invalid arg type ?line {'EXIT',_} = (catch string:sub_word("hello there", 1, "e")), ok. left_right(suite) -> []; left_right(doc) -> []; left_right(Config) when is_list(Config) -> ?line "" = string:left("", 0), ?line "" = string:left("hej", 0), ?line "" = string:left("hej", 0, $.), ?line "" = string:right("", 0), ?line "" = string:right("hej", 0), ?line "" = string:right("hej", 0, $.), ?line "123 " = string:left("123 ", 5), ?line " 123" = string:right(" 123", 5), ?line "123!!" = string:left("123!", 5, $!), ?line "==123" = string:right("=123", 5, $=), ?line "1" = string:left("123", 1, $.), ?line "3" = string:right("123", 1, $.), %% invalid arg type ?line {'EXIT',_} = (catch string:left(hello, 5)), %% invalid arg type ?line {'EXIT',_} = (catch string:right(hello, 5)), %% invalid arg type ?line {'EXIT',_} = (catch string:left("hello", 5, ".")), %% invalid arg type ?line {'EXIT',_} = (catch string:right("hello", 5, ".")), ok. sub_string(suite) -> []; sub_string(doc) -> []; sub_string(Config) when is_list(Config) -> ?line {'EXIT',_} = (catch string:sub_string("", 0)), ?line [] = string:sub_string("", 1), ?line {'EXIT',_} = (catch string:sub_string("", 2)), ?line [] = string:sub_string("1", 2), ?line {'EXIT',_} = (catch string:sub_string("", 0, 1)), ?line [] = string:sub_string("", 1, 1), ?line [] = string:sub_string("", 1, 2), ?line {'EXIT',_} = (catch string:sub_string("", 2, 2)), ?line "1234" = string:sub_string("1234", 1), ?line "1234" = string:sub_string("1234", 1, 4), ?line "1234" = string:sub_string("1234", 1, 5), ?line "23" = string:sub_string("1234", 2, 3), ?line "4" = string:sub_string("1234", 4), ?line "4" = string:sub_string("1234", 4, 4), ?line "4" = string:sub_string("1234", 4, 5), %% invalid arg type ?line {'EXIT',_} = (catch string:sub_string(1234, 1)), %% invalid arg type ?line {'EXIT',_} = (catch string:sub_string("1234", "1")), ok. centre(suite) -> []; centre(doc) -> []; centre(Config) when is_list(Config) -> ?line "" = string:centre("", 0), ?line "" = string:centre("1", 0), ?line "" = string:centre("", 0, $-), ?line "" = string:centre("1", 0, $-), ?line "gd" = string:centre("agda", 2), ?line "agda " = string:centre("agda", 5), ?line " agda " = string:centre("agda", 6), ?line "agda." = string:centre("agda", 5, $.), ?line "--agda--" = string:centre("agda", 8, $-), ?line "agda" = string:centre("agda", 4), %% invalid arg type ?line {'EXIT',_} = (catch string:centre(hello, 10)), ok. to_integer(suite) -> []; to_integer(doc) -> []; to_integer(Config) when is_list(Config) -> ?line {1,""} = test_to_integer("1"), ?line {1,""} = test_to_integer("+1"), ?line {-1,""} = test_to_integer("-1"), ?line {1,"="} = test_to_integer("1="), ?line {7,"F"} = test_to_integer("7F"), ?line {709,""} = test_to_integer("709"), ?line {709,"*2"} = test_to_integer("709*2"), ?line {0,"xAB"} = test_to_integer("0xAB"), ?line {16,"#FF"} = test_to_integer("16#FF"), ?line {error,no_integer} = test_to_integer(""), ?line {error,no_integer} = test_to_integer("!1"), ?line {error,no_integer} = test_to_integer("F1"), ?line {error,not_a_list} = test_to_integer('23'), ?line {3,[[]]} = test_to_integer([$3,[]]), ?line {3,[hello]} = test_to_integer([$3,hello]), ok. test_to_integer(Str) -> io:format("Checking ~p~n", [Str]), case string:to_integer(Str) of {error,_Reason} = Bad -> ?line {'EXIT',_} = (catch list_to_integer(Str)), Bad; {F,_Rest} = Res -> ?line _ = integer_to_list(F), Res end. to_float(suite) -> []; to_float(doc) -> []; to_float(Config) when is_list(Config) -> ?line {1.2,""} = test_to_float("1.2"), ?line {1.2,""} = test_to_float("1,2"), ?line {120.0,""} = test_to_float("1.2e2"), ?line {120.0,""} = test_to_float("+1,2e2"), ?line {-120.0,""} = test_to_float("-1.2e2"), ?line {-120.0,""} = test_to_float("-1,2e+2"), ?line {-1.2e-2,""} = test_to_float("-1.2e-2"), ?line {1.2,"="} = test_to_float("1.2="), ?line {7.9,"e"} = test_to_float("7.9e"), ?line {7.9,"ee"} = test_to_float("7.9ee"), ?line {7.9,"e+"} = test_to_float("7.9e+"), ?line {7.9,"e-"} = test_to_float("7.9e-"), ?line {7.9,"e++"} = test_to_float("7.9e++"), ?line {7.9,"e--"} = test_to_float("7.9e--"), ?line {7.9,"e+e"} = test_to_float("7.9e+e"), ?line {7.9,"e-e"} = test_to_float("7.9e-e"), ?line {7.9,"e+."} = test_to_float("7.9e+."), ?line {7.9,"e-."} = test_to_float("7.9e-."), ?line {7.9,"e+,"} = test_to_float("7.9e+,"), ?line {7.9,"e-,"} = test_to_float("7.9e-,"), ?line {error,no_float} = test_to_float(""), ?line {error,no_float} = test_to_float("e1,0"), ?line {error,no_float} = test_to_float("1;0"), ?line {error,no_float} = test_to_float("1"), ?line {error,no_float} = test_to_float("1e"), ?line {error,no_float} = test_to_float("2."), ?line {error,not_a_list} = test_to_float('2.3'), ?line {2.3,[[]]} = test_to_float([$2,$.,$3,[]]), ?line {2.3,[hello]} = test_to_float([$2,$.,$3,hello]), ok. test_to_float(Str) -> io:format("Checking ~p~n", [Str]), case string:to_float(Str) of {error,_Reason} = Bad -> ?line {'EXIT',_} = (catch list_to_float(Str)), Bad; {F,_Rest} = Res -> ?line _ = float_to_list(F), Res end. to_upper_to_lower(suite) -> []; to_upper_to_lower(doc) -> []; to_upper_to_lower(Config) when is_list(Config) -> ?line "1234ABCDEFÅÄÖ=" = string:to_upper("1234abcdefåäö="), ?line "éèíúùòóåäöabc()" = string:to_lower("ÉÈÍÚÙÒÓÅÄÖabc()"), ?line All = lists:seq(0, 255), ?line UC = string:to_upper(All), ?line 256 = length(UC), ?line all_upper_latin1(UC, 0), ?line LC = string:to_lower(All), ?line all_lower_latin1(LC, 0), ?line LC = string:to_lower(string:to_upper(LC)), ?line LC = string:to_lower(string:to_upper(UC)), ?line UC = string:to_upper(string:to_lower(LC)), ?line UC = string:to_upper(string:to_lower(UC)), ok. all_upper_latin1([C|T], C) when 0 =< C, C < $a; $z < C, C < 16#E0; C =:= 16#F7; C =:= 16#FF -> all_upper_latin1(T, C+1); all_upper_latin1([H|T], C) when $a =< C, C =< $z; 16#E0 =< C, C =< 16#F6; 16#F8 =< C, C =< 16#FE -> H = C - 32, all_upper_latin1(T, C+1); all_upper_latin1([], 256) -> ok. all_lower_latin1([C|T], C) when 0 =< C, C < $A; $Z < C, C < 16#C0; C =:= 16#D7; 16#DF =< C, C =< 255 -> all_lower_latin1(T, C+1); all_lower_latin1([H|T], C) when $A =< C, C =< $Z; 16#C0 =< C, C =< 16#F6; 16#C8 =< C, C =< 16#DE -> io:format("~p\n", [{H,C}]), H = C + 32, all_lower_latin1(T, C+1); all_lower_latin1([], 256) -> ok. join(suite) -> []; join(doc) -> []; join(Config) when is_list(Config) -> ?line "erlang rules" = string:join(["erlang", "rules"], " "), ?line "a,-,b,-,c" = string:join(["a", "b", "c"], ",-,"), ?line "1234" = string:join(["1", "2", "3", "4"], ""), ?line [] = string:join([], ""), % OTP-7231 %% invalid arg type ?line {'EXIT',_} = (catch string:join([apa], "")), ok.
null
https://raw.githubusercontent.com/simplegeo/erlang/15eda8de27ba73d176c7eeb3a70a64167f50e2c4/lib/stdlib/test/string_SUITE.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% ---------------------------------------------------------------- Purpose: string test suite. ----------------------------------------------------------------- Default timetrap timeout (set in init_per_testcase). Test server specific exports Test cases must be exported. all/1 Test cases starts here. invalid arg type invalid arg type not good, should crash invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type not good invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type invalid arg type OTP-7231 invalid arg type
Copyright Ericsson AB 2004 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(string_SUITE). -include("test_server.hrl"). -define(default_timeout, ?t:minutes(1)). -export([all/1]). -export([init_per_testcase/2, fin_per_testcase/2]). -export([len/1,equal/1,concat/1,chr_rchr/1,str_rstr/1]). -export([span_cspan/1,substr/1,tokens/1,chars/1]). -export([copies/1,words/1,strip/1,sub_word/1,left_right/1]). -export([sub_string/1,centre/1, join/1]). -export([to_integer/1,to_float/1]). -export([to_upper_to_lower/1]). all(doc) -> []; all(suite) -> [len,equal,concat,chr_rchr,str_rstr, span_cspan,substr,tokens,chars, copies,words,strip,sub_word,left_right, sub_string,centre, join, to_integer,to_float,to_upper_to_lower]. init_per_testcase(_Case, Config) -> ?line Dog=test_server:timetrap(?default_timeout), [{watchdog, Dog}|Config]. fin_per_testcase(_Case, Config) -> Dog=?config(watchdog, Config), test_server:timetrap_cancel(Dog), ok. len(suite) -> []; len(doc) -> []; len(Config) when is_list(Config) -> ?line 0 = string:len(""), ?line L = tuple_size(list_to_tuple(atom_to_list(?MODULE))), ?line L = string:len(atom_to_list(?MODULE)), ?line {'EXIT',_} = (catch string:len({})), ok. equal(suite) -> []; equal(doc) -> []; equal(Config) when is_list(Config) -> ?line true = string:equal("", ""), ?line false = string:equal("", " "), ?line true = string:equal("laban", "laban"), ?line false = string:equal("skvimp", "skvump"), ok. concat(suite) -> []; concat(doc) -> []; concat(Config) when is_list(Config) -> ?line "erlang rules" = string:concat("erlang ", "rules"), ?line "" = string:concat("", ""), ?line "x" = string:concat("x", ""), ?line "y" = string:concat("", "y"), ?line {'EXIT',_} = (catch string:concat(hello, please)), ok. chr_rchr(suite) -> []; chr_rchr(doc) -> []; chr_rchr(Config) when is_list(Config) -> ?line {_,_,X} = now(), ?line 0 = string:chr("", (X rem (255-32)) + 32), ?line 0 = string:rchr("", (X rem (255-32)) + 32), ?line 1 = string:chr("x", $x), ?line 1 = string:rchr("x", $x), ?line 1 = string:chr("xx", $x), ?line 2 = string:rchr("xx", $x), ?line 3 = string:chr("xyzyx", $z), ?line 3 = string:rchr("xyzyx", $z), ?line {'EXIT',_} = (catch string:chr(hello, $h)), ?line {'EXIT',_} = (catch string:chr("hello", h)), ?line {'EXIT',_} = (catch string:rchr(hello, $h)), ?line {'EXIT',_} = (catch string:rchr("hello", h)), ok. str_rstr(suite) -> []; str_rstr(doc) -> []; str_rstr(Config) when is_list(Config) -> ?line {_,_,X} = now(), ?line 0 = string:str("", [(X rem (255-32)) + 32]), ?line 0 = string:rstr("", [(X rem (255-32)) + 32]), ?line 1 = string:str("x", "x"), ?line 1 = string:rstr("x", "x"), ?line 0 = string:str("hello", ""), ?line 0 = string:rstr("hello", ""), ?line 1 = string:str("xxxx", "xx"), ?line 3 = string:rstr("xxxx", "xx"), ?line 3 = string:str("xy z yx", " z"), ?line 3 = string:rstr("xy z yx", " z"), ?line {'EXIT',_} = (catch string:str(hello, "he")), ?line {'EXIT',_} = (catch string:str("hello", he)), ?line {'EXIT',_} = (catch string:rstr(hello, "he")), ?line {'EXIT',_} = (catch string:rstr("hello", he)), ok. span_cspan(suite) -> []; span_cspan(doc) -> []; span_cspan(Config) when is_list(Config) -> ?line 0 = string:span("", "1"), ?line 0 = string:span("1", ""), ?line 0 = string:cspan("", "1"), ?line 1 = string:cspan("1", ""), ?line 1 = string:span("1 ", "1"), ?line 5 = string:span(" 1 ", "12 "), ?line 6 = string:span("1231234", "123"), ?line 0 = string:cspan("1 ", "1"), ?line 1 = string:cspan("3 ", "12 "), ?line 6 = string:cspan("1231234", "4"), ?line {'EXIT',_} = (catch string:span(1234, "1")), ?line {'EXIT',_} = (catch string:span(1234, "1")), ?line {'EXIT',_} = (catch string:cspan("1234", 1)), ?line {'EXIT',_} = (catch string:cspan("1234", 4)), ok. substr(suite) -> []; substr(doc) -> []; substr(Config) when is_list(Config) -> ?line {'EXIT',_} = (catch string:substr("", 0)), ?line [] = string:substr("", 1), ?line {'EXIT',_} = (catch string:substr("", 2)), ?line [] = string:substr("1", 2), ?line {'EXIT',_} = (catch string:substr("", 0, 1)), ?line [] = string:substr("", 1, 1), ?line [] = string:substr("", 1, 2), ?line {'EXIT',_} = (catch string:substr("", 2, 2)), ?line "1234" = string:substr("1234", 1), ?line "1234" = string:substr("1234", 1, 4), ?line "1234" = string:substr("1234", 1, 5), ?line "23" = string:substr("1234", 2, 2), ?line "4" = string:substr("1234", 4), ?line "" = string:substr("1234", 4, 0), ?line "4" = string:substr("1234", 4, 1), ?line {'EXIT',_} = (catch string:substr(1234, 1)), ?line {'EXIT',_} = (catch string:substr("1234", "1")), ok. tokens(suite) -> []; tokens(doc) -> []; tokens(Config) when is_list(Config) -> ?line [] = string:tokens("",""), ?line [] = string:tokens("abc","abc"), ?line ["abc"] = string:tokens("abc", ""), ?line ["1","2 34","4","5"] = string:tokens("1,2 34,4;5", ";,"), ?line {'EXIT',_} = (catch string:tokens('x,y', ",")), ?line {'EXIT',_} = (catch string:tokens("x,y", ',')), ok. chars(suite) -> []; chars(doc) -> []; chars(Config) when is_list(Config) -> ?line [] = string:chars($., 0), ?line [] = string:chars($., 0, []), ?line 10 = length(string:chars(32, 10, [])), ?line "aaargh" = string:chars($a, 3, "rgh"), ?line {'EXIT',_} = (catch string:chars($x, [])), ok. copies(suite) -> []; copies(doc) -> []; copies(Config) when is_list(Config) -> ?line "" = string:copies("", 10), ?line "" = string:copies(".", 0), ?line "." = string:copies(".", 1), ?line 30 = length(string:copies("123", 10)), ?line {'EXIT',_} = (catch string:chars("hej", -1)), ok. words(suite) -> []; words(doc) -> []; words(Config) when is_list(Config) -> ?line 1 = string:words(""), ?line 1 = string:words("", $,), ?line 1 = string:words("hello"), ?line 1 = string:words("hello", $,), ?line 1 = string:words("...", $.), ?line 2 = string:words("2.35", $.), ?line 100 = string:words(string:copies(". ", 100)), ?line {'EXIT',_} = (catch string:chars(hej)), ?line {'EXIT',_} = (catch string:chars("hej", " ")), ok. strip(suite) -> []; strip(doc) -> []; strip(Config) when is_list(Config) -> ?line "" = string:strip(""), ?line "" = string:strip("", both), ?line "" = string:strip("", both, $.), ?line "hej" = string:strip(" hej "), ?line "hej " = string:strip(" hej ", left), ?line " hej" = string:strip(" hej ", right), ?line " hej " = string:strip(" hej ", right, $.), ?line "hej hopp" = string:strip(" hej hopp ", both), ?line {'EXIT',_} = (catch string:strip(hej)), ?line {'EXIT',_} = (catch string:strip(" hej", up)), ok. sub_word(suite) -> []; sub_word(doc) -> []; sub_word(Config) when is_list(Config) -> ?line "" = string:sub_word("", 1), ?line "" = string:sub_word("", 1, $,), ?line {'EXIT',_} = (catch string:sub_word("1 2 3", 0)), ?line "" = string:sub_word("1 2 3", 4), ?line "llo th" = string:sub_word("but hello there", 2, $e), ?line {'EXIT',_} = (catch string:sub_word('hello there', 1)), ?line {'EXIT',_} = (catch string:sub_word("hello there", 1, "e")), ok. left_right(suite) -> []; left_right(doc) -> []; left_right(Config) when is_list(Config) -> ?line "" = string:left("", 0), ?line "" = string:left("hej", 0), ?line "" = string:left("hej", 0, $.), ?line "" = string:right("", 0), ?line "" = string:right("hej", 0), ?line "" = string:right("hej", 0, $.), ?line "123 " = string:left("123 ", 5), ?line " 123" = string:right(" 123", 5), ?line "123!!" = string:left("123!", 5, $!), ?line "==123" = string:right("=123", 5, $=), ?line "1" = string:left("123", 1, $.), ?line "3" = string:right("123", 1, $.), ?line {'EXIT',_} = (catch string:left(hello, 5)), ?line {'EXIT',_} = (catch string:right(hello, 5)), ?line {'EXIT',_} = (catch string:left("hello", 5, ".")), ?line {'EXIT',_} = (catch string:right("hello", 5, ".")), ok. sub_string(suite) -> []; sub_string(doc) -> []; sub_string(Config) when is_list(Config) -> ?line {'EXIT',_} = (catch string:sub_string("", 0)), ?line [] = string:sub_string("", 1), ?line {'EXIT',_} = (catch string:sub_string("", 2)), ?line [] = string:sub_string("1", 2), ?line {'EXIT',_} = (catch string:sub_string("", 0, 1)), ?line [] = string:sub_string("", 1, 1), ?line [] = string:sub_string("", 1, 2), ?line {'EXIT',_} = (catch string:sub_string("", 2, 2)), ?line "1234" = string:sub_string("1234", 1), ?line "1234" = string:sub_string("1234", 1, 4), ?line "1234" = string:sub_string("1234", 1, 5), ?line "23" = string:sub_string("1234", 2, 3), ?line "4" = string:sub_string("1234", 4), ?line "4" = string:sub_string("1234", 4, 4), ?line "4" = string:sub_string("1234", 4, 5), ?line {'EXIT',_} = (catch string:sub_string(1234, 1)), ?line {'EXIT',_} = (catch string:sub_string("1234", "1")), ok. centre(suite) -> []; centre(doc) -> []; centre(Config) when is_list(Config) -> ?line "" = string:centre("", 0), ?line "" = string:centre("1", 0), ?line "" = string:centre("", 0, $-), ?line "" = string:centre("1", 0, $-), ?line "gd" = string:centre("agda", 2), ?line "agda " = string:centre("agda", 5), ?line " agda " = string:centre("agda", 6), ?line "agda." = string:centre("agda", 5, $.), ?line "--agda--" = string:centre("agda", 8, $-), ?line "agda" = string:centre("agda", 4), ?line {'EXIT',_} = (catch string:centre(hello, 10)), ok. to_integer(suite) -> []; to_integer(doc) -> []; to_integer(Config) when is_list(Config) -> ?line {1,""} = test_to_integer("1"), ?line {1,""} = test_to_integer("+1"), ?line {-1,""} = test_to_integer("-1"), ?line {1,"="} = test_to_integer("1="), ?line {7,"F"} = test_to_integer("7F"), ?line {709,""} = test_to_integer("709"), ?line {709,"*2"} = test_to_integer("709*2"), ?line {0,"xAB"} = test_to_integer("0xAB"), ?line {16,"#FF"} = test_to_integer("16#FF"), ?line {error,no_integer} = test_to_integer(""), ?line {error,no_integer} = test_to_integer("!1"), ?line {error,no_integer} = test_to_integer("F1"), ?line {error,not_a_list} = test_to_integer('23'), ?line {3,[[]]} = test_to_integer([$3,[]]), ?line {3,[hello]} = test_to_integer([$3,hello]), ok. test_to_integer(Str) -> io:format("Checking ~p~n", [Str]), case string:to_integer(Str) of {error,_Reason} = Bad -> ?line {'EXIT',_} = (catch list_to_integer(Str)), Bad; {F,_Rest} = Res -> ?line _ = integer_to_list(F), Res end. to_float(suite) -> []; to_float(doc) -> []; to_float(Config) when is_list(Config) -> ?line {1.2,""} = test_to_float("1.2"), ?line {1.2,""} = test_to_float("1,2"), ?line {120.0,""} = test_to_float("1.2e2"), ?line {120.0,""} = test_to_float("+1,2e2"), ?line {-120.0,""} = test_to_float("-1.2e2"), ?line {-120.0,""} = test_to_float("-1,2e+2"), ?line {-1.2e-2,""} = test_to_float("-1.2e-2"), ?line {1.2,"="} = test_to_float("1.2="), ?line {7.9,"e"} = test_to_float("7.9e"), ?line {7.9,"ee"} = test_to_float("7.9ee"), ?line {7.9,"e+"} = test_to_float("7.9e+"), ?line {7.9,"e-"} = test_to_float("7.9e-"), ?line {7.9,"e++"} = test_to_float("7.9e++"), ?line {7.9,"e--"} = test_to_float("7.9e--"), ?line {7.9,"e+e"} = test_to_float("7.9e+e"), ?line {7.9,"e-e"} = test_to_float("7.9e-e"), ?line {7.9,"e+."} = test_to_float("7.9e+."), ?line {7.9,"e-."} = test_to_float("7.9e-."), ?line {7.9,"e+,"} = test_to_float("7.9e+,"), ?line {7.9,"e-,"} = test_to_float("7.9e-,"), ?line {error,no_float} = test_to_float(""), ?line {error,no_float} = test_to_float("e1,0"), ?line {error,no_float} = test_to_float("1;0"), ?line {error,no_float} = test_to_float("1"), ?line {error,no_float} = test_to_float("1e"), ?line {error,no_float} = test_to_float("2."), ?line {error,not_a_list} = test_to_float('2.3'), ?line {2.3,[[]]} = test_to_float([$2,$.,$3,[]]), ?line {2.3,[hello]} = test_to_float([$2,$.,$3,hello]), ok. test_to_float(Str) -> io:format("Checking ~p~n", [Str]), case string:to_float(Str) of {error,_Reason} = Bad -> ?line {'EXIT',_} = (catch list_to_float(Str)), Bad; {F,_Rest} = Res -> ?line _ = float_to_list(F), Res end. to_upper_to_lower(suite) -> []; to_upper_to_lower(doc) -> []; to_upper_to_lower(Config) when is_list(Config) -> ?line "1234ABCDEFÅÄÖ=" = string:to_upper("1234abcdefåäö="), ?line "éèíúùòóåäöabc()" = string:to_lower("ÉÈÍÚÙÒÓÅÄÖabc()"), ?line All = lists:seq(0, 255), ?line UC = string:to_upper(All), ?line 256 = length(UC), ?line all_upper_latin1(UC, 0), ?line LC = string:to_lower(All), ?line all_lower_latin1(LC, 0), ?line LC = string:to_lower(string:to_upper(LC)), ?line LC = string:to_lower(string:to_upper(UC)), ?line UC = string:to_upper(string:to_lower(LC)), ?line UC = string:to_upper(string:to_lower(UC)), ok. all_upper_latin1([C|T], C) when 0 =< C, C < $a; $z < C, C < 16#E0; C =:= 16#F7; C =:= 16#FF -> all_upper_latin1(T, C+1); all_upper_latin1([H|T], C) when $a =< C, C =< $z; 16#E0 =< C, C =< 16#F6; 16#F8 =< C, C =< 16#FE -> H = C - 32, all_upper_latin1(T, C+1); all_upper_latin1([], 256) -> ok. all_lower_latin1([C|T], C) when 0 =< C, C < $A; $Z < C, C < 16#C0; C =:= 16#D7; 16#DF =< C, C =< 255 -> all_lower_latin1(T, C+1); all_lower_latin1([H|T], C) when $A =< C, C =< $Z; 16#C0 =< C, C =< 16#F6; 16#C8 =< C, C =< 16#DE -> io:format("~p\n", [{H,C}]), H = C + 32, all_lower_latin1(T, C+1); all_lower_latin1([], 256) -> ok. join(suite) -> []; join(doc) -> []; join(Config) when is_list(Config) -> ?line "erlang rules" = string:join(["erlang", "rules"], " "), ?line "a,-,b,-,c" = string:join(["a", "b", "c"], ",-,"), ?line "1234" = string:join(["1", "2", "3", "4"], ""), ?line {'EXIT',_} = (catch string:join([apa], "")), ok.
442a0a68af0c9ae7ebf33ed07e5a964198177478454372ee0286cf47283ab1e1
wujuihsuan2016/LL_prover
formula.ml
(*** Basic definitions of formulas, sequents and rules ***) (** Definition of formulas of propositional linear logic **) type atom = string type formula = | Pos of atom | Neg of atom | One | Zero | Top | Bottom | OfCourse of formula | Whynot of formula | Tensor of formula * formula | Plus of formula * formula | With of formula * formula | Par of formula * formula | Impl of formula * formula (** LLF **) type llf_rule = | One_intro | Top_intro | Bottom_intro | Par_intro | With_intro | Tensor_intro of formula list * formula list | Plus_intro_1 | Plus_intro_2 | OfCourse_intro | Whynot_intro | I1 | I2 | D1 of formula * formula list | D2 of formula | R_async | R_sync module Set_formula = Set.Make(struct type t = formula let compare = compare end) module Set_int = Set.Make(struct type t = int let compare = compare end) module Set_var = Set.Make(struct type t = string let compare = compare end) type sequent2 = formula list * formula list type llf_sequent = | Async of Set_formula.t * formula list * formula list | Sync of Set_formula.t * formula list * formula type llf_proof = | Node of llf_sequent * llf_rule * llf_proof list | Null (** ILLF **) type illf_sequent = | R_focal of Set_formula.t * formula list * formula | L_focal of Set_formula.t * formula list * formula * formula | Active of Set_formula.t * formula list * formula list * formula type illf_rule = | Tensor_L | Tensor_R of (formula list * formula list) | Impl_L of (formula list * formula list) | Impl_R | One_L | One_R | Zero_L | Init | Top_R | OfCourse_L | OfCourse_R | With_R | With_L_1 | With_L_2 | Plus_L | Plus_R_1 | Plus_R_2 | Lf | Copy of formula | Rf | Lb | Rb | Rb_ | Act type illf_proof = | INode of illf_sequent * illf_rule * illf_proof list | INull (** LL **) type ll_sequent = formula list type ll_rule = | LAx | LTensor | LPar | LOne | LBottom | LPlus_1 | LPlus_2 | LWith | LTop | Lder | Lwk | Lcont | LOfCourse type ll_proof = | LNode of ll_sequent * ll_rule * ll_proof list | LNull * ILL * type ill_sequent = formula list * formula type ill_rule = | ILAx | ILTensor_L | ILTensor_R | ILOne_L | ILOne_R | ILImpl_L | ILImpl_R | ILPlus_L | ILPlus_R_1 | ILPlus_R_2 | ILZero_L | ILWith_L_1 | ILWith_L_2 | ILWith_R | ILTop_R | ILwk_L | ILcont_L | ILder_L | ILOfCourse_R type ill_proof = | ILNode of ill_sequent * ill_rule * ill_proof list | ILNull
null
https://raw.githubusercontent.com/wujuihsuan2016/LL_prover/c55f59d27824d3685f41ed554c2e7d4f8e3e6e47/src/formula.ml
ocaml
** Basic definitions of formulas, sequents and rules ** * Definition of formulas of propositional linear logic * * LLF * * ILLF * * LL *
type atom = string type formula = | Pos of atom | Neg of atom | One | Zero | Top | Bottom | OfCourse of formula | Whynot of formula | Tensor of formula * formula | Plus of formula * formula | With of formula * formula | Par of formula * formula | Impl of formula * formula type llf_rule = | One_intro | Top_intro | Bottom_intro | Par_intro | With_intro | Tensor_intro of formula list * formula list | Plus_intro_1 | Plus_intro_2 | OfCourse_intro | Whynot_intro | I1 | I2 | D1 of formula * formula list | D2 of formula | R_async | R_sync module Set_formula = Set.Make(struct type t = formula let compare = compare end) module Set_int = Set.Make(struct type t = int let compare = compare end) module Set_var = Set.Make(struct type t = string let compare = compare end) type sequent2 = formula list * formula list type llf_sequent = | Async of Set_formula.t * formula list * formula list | Sync of Set_formula.t * formula list * formula type llf_proof = | Node of llf_sequent * llf_rule * llf_proof list | Null type illf_sequent = | R_focal of Set_formula.t * formula list * formula | L_focal of Set_formula.t * formula list * formula * formula | Active of Set_formula.t * formula list * formula list * formula type illf_rule = | Tensor_L | Tensor_R of (formula list * formula list) | Impl_L of (formula list * formula list) | Impl_R | One_L | One_R | Zero_L | Init | Top_R | OfCourse_L | OfCourse_R | With_R | With_L_1 | With_L_2 | Plus_L | Plus_R_1 | Plus_R_2 | Lf | Copy of formula | Rf | Lb | Rb | Rb_ | Act type illf_proof = | INode of illf_sequent * illf_rule * illf_proof list | INull type ll_sequent = formula list type ll_rule = | LAx | LTensor | LPar | LOne | LBottom | LPlus_1 | LPlus_2 | LWith | LTop | Lder | Lwk | Lcont | LOfCourse type ll_proof = | LNode of ll_sequent * ll_rule * ll_proof list | LNull * ILL * type ill_sequent = formula list * formula type ill_rule = | ILAx | ILTensor_L | ILTensor_R | ILOne_L | ILOne_R | ILImpl_L | ILImpl_R | ILPlus_L | ILPlus_R_1 | ILPlus_R_2 | ILZero_L | ILWith_L_1 | ILWith_L_2 | ILWith_R | ILTop_R | ILwk_L | ILcont_L | ILder_L | ILOfCourse_R type ill_proof = | ILNode of ill_sequent * ill_rule * ill_proof list | ILNull
fc1121ef9c564a458c599f29bbdba7fd034ce84c9093a2f298f5ea87f7d718a9
skogsbaer/HTF
TestTypes.hs
# LANGUAGE FlexibleInstances # -- Copyright ( c ) 2005 - 2022 - -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . -- -- 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 -- {-| This module defines types (and small auxiliary functions) for organizing tests, for configuring the execution of tests, and for representing and reporting their results. This functionality is mainly used internally in the code generated by the @hftpp@ pre-processor. -} module Test.Framework.TestTypes ( -- * Organizing tests TestID, Test(..), TestOptions(..), AssertionWithTestOptions(..), WithTestOptions(..), TestSuite(..), TestSort(..), TestPath(..), GenFlatTest(..), FlatTest, TestFilter, testPathToList, flatName, finalName, prefixName, defaultTestOptions, withOptions, historyKey, -- * Executing tests TR, TestState(..), initTestState, TestConfig(..), TestOutput(..), -- * Reporting results ReportAllTests, ReportGlobalStart, ReportTestStart, ReportTestResult, ReportGlobalResults, ReportGlobalResultsArg(..), TestReporter(..), emptyTestReporter, attachCallStack, CallStack, -- * Specifying results. TestResult(..), FlatTestResult, Milliseconds, RunResult(..) ) where import Test.Framework.Location import Test.Framework.Colors import Test.Framework.History import Test.Framework.TestInterface import Control.Monad.RWS import System.IO import Data.Maybe import qualified Data.List as List import qualified Data.Text as T -- | Type for naming tests. type TestID = String -- | Type for distinguishing different sorts of tests. data TestSort = UnitTest | QuickCheckTest | BlackBoxTest deriving (Eq,Show,Read) -- | General options for tests data TestOptions = TestOptions { to_parallel :: Bool } deriving (Eq,Show,Read) -- | The default 'TestOptions' defaultTestOptions :: TestOptions defaultTestOptions = TestOptions { to_parallel = True } -- | Something with 'TestOptions' data WithTestOptions a = WithTestOptions { wto_options :: TestOptions , wto_payload :: a } deriving (Eq,Show,Read) -- | Shortcut for constructing a 'WithTestOptions' value. withOptions :: (TestOptions -> TestOptions) -> a -> WithTestOptions a withOptions f x = WithTestOptions (f defaultTestOptions) x -- | A type class for an assertion with 'TestOptions'. class AssertionWithTestOptions a where testOptions :: a -> TestOptions assertion :: a -> Assertion instance AssertionWithTestOptions (IO a) where testOptions _ = defaultTestOptions assertion io = io >> return () instance AssertionWithTestOptions (WithTestOptions (IO a)) where testOptions (WithTestOptions opts _) = opts assertion (WithTestOptions _ io) = io >> return () -- | Abstract type for tests and their results. data Test = BaseTest TestSort TestID (Maybe Location) TestOptions Assertion | CompoundTest TestSuite -- | Abstract type for test suites and their results. data TestSuite = TestSuite TestID [Test] | AnonTestSuite [Test] -- | A type denoting the hierarchical name of a test. data TestPath = TestPathBase TestID | TestPathCompound (Maybe TestID) TestPath deriving (Show) -- | Splits a 'TestPath' into a list of test identifiers. testPathToList :: TestPath -> [Maybe TestID] testPathToList (TestPathBase i) = [Just i] testPathToList (TestPathCompound mi p) = mi : testPathToList p -- | Creates a string representation from a 'TestPath'. flatName :: TestPath -> String flatName p = flatNameFromList (testPathToList p) flatNameFromList :: [Maybe TestID] -> String flatNameFromList l = List.intercalate ":" (map (fromMaybe "") l) -- | Returns the final name of a 'TestPath' finalName :: TestPath -> String finalName (TestPathBase i) = i finalName (TestPathCompound _ p) = finalName p -- | Returns the name of the prefix of a test path. The prefix is everything except the -- last element. prefixName :: TestPath -> String prefixName path = let l = case reverse (testPathToList path) of [] -> [] (_:xs) -> reverse xs in flatNameFromList l -- | Generic type for flattened tests and their results. data GenFlatTest a = FlatTest { ft_sort :: TestSort -- ^ The sort of the test. , ft_path :: TestPath -- ^ Hierarchival path. , ft_location :: Maybe Location -- ^ Place of definition. , ft_payload :: a -- ^ A generic payload. } -- | Key of a flat test for the history database. historyKey :: GenFlatTest a -> T.Text historyKey ft = T.pack (flatName (ft_path ft)) -- | Flattened representation of tests. type FlatTest = GenFlatTest (WithTestOptions Assertion) -- | A filter is a predicate on 'FlatTest'. If the predicate is 'True', the flat test is run. type TestFilter = FlatTest -> Bool -- | A type for call-stacks type CallStack = [(Maybe String, Location)] -- | The result of a test run. data RunResult = RunResult { rr_result :: TestResult -- ^ The summary result of the test. , rr_stack :: HtfStack -- ^ The stack leading to the test failure , rr_message :: ColorString -- ^ A message describing the result. , rr_wallTimeMs :: Milliseconds -- ^ Execution time in milliseconds. , rr_timeout :: Bool -- ^ 'True' if the execution took too long } attachCallStack :: ColorString -> HtfStack -> ColorString attachCallStack msg stack = let fstack = formatHtfStack stack in if fstack == "" then msg else ensureNewlineColorString msg +++ noColor fstack -- | The result of running a 'FlatTest' type FlatTestResult = GenFlatTest RunResult -- | The state type for the 'TR' monad. data TestState = TestState { ts_results :: [FlatTestResult] -- ^ Results collected so far. , ts_index :: Int -- ^ Current index for splitted output. } -- | The initial test state. initTestState :: TestState initTestState = TestState [] 0 -- | The 'TR' (test runner) monad. type TR = RWST TestConfig () TestState IO | The destination of progress and result messages from HTF . data TestOutput = TestOutputHandle Handle Bool -- ^ Output goes to 'Handle', boolean flag indicates whether the handle should be closed at the end. ^ Output goes to files whose names are derived from ' FilePath ' by appending a number to it . Numbering starts at zero . deriving (Show, Eq) -- | Configuration of test execution. data TestConfig = TestConfig { tc_quiet :: Bool -- ^ If set, displays messages only for failed tests. ^ Use @Just i@ for parallel execution with @i@ threads , @Nothing@ for sequential execution . , tc_shuffle :: Bool -- ^ Shuffle tests before parallel execution , tc_output :: TestOutput -- ^ Output destination of progress and result messages. , tc_outputXml :: Maybe FilePath -- ^ Output destination of XML result summary , tc_filter :: TestFilter -- ^ Filter for the tests to run. , tc_reporters :: [TestReporter] -- ^ Test reporters to use. , tc_useColors :: Bool -- ^ Whether to use colored output , tc_historyFile :: FilePath -- ^ Path to history file , tc_history :: TestHistory -- ^ History of previous test runs , tc_sortByPrevTime :: Bool -- ^ Sort ascending by previous execution times ^ Stop test run as soon as one test fails , tc_timeoutIsSuccess :: Bool -- ^ Do not regard timeout as an error , tc_maxSingleTestTime :: Maybe Milliseconds -- ^ Maximum time in milliseconds a single test is allowed to run , tc_prevFactor :: Maybe Double -- ^ Maximum factor a single test is allowed to run slower than its previous execution , tc_repeat :: Int -- ^ Number of times to repeat tests selected on the command line before reporting them as a success. } instance Show TestConfig where showsPrec prec tc = showParen (prec > 0) $ showString "TestConfig { " . showString "tc_quiet=" . showsPrec 1 (tc_quiet tc) . showString ", tc_threads=" . showsPrec 1 (tc_threads tc) . showString ", tc_shuffle=" . showsPrec 1 (tc_shuffle tc) . showString ", tc_output=" . showsPrec 1 (tc_output tc) . showString ", tc_outputXml=" . showsPrec 1 (tc_outputXml tc) . showString ", tc_filter=<filter>" . showString ", tc_reporters=" . showsPrec 1 (tc_reporters tc) . showString ", tc_useColors=" . showsPrec 1 (tc_useColors tc) . showString ", tc_historyFile=" . showsPrec 1 (tc_historyFile tc) . showString ", tc_history=" . showsPrec 1 (tc_history tc) . showString ", tc_sortByPrevTime=" . showsPrec 1 (tc_sortByPrevTime tc) . showString ", tc_failFast=" . showsPrec 1 (tc_failFast tc) . showString ", tc_timeoutIsSuccess=" . showsPrec 1 (tc_timeoutIsSuccess tc) . showString ", tc_maxSingleTestTime=" . showsPrec 1 (tc_maxSingleTestTime tc) . showString ", tc_prevFactor=" . showsPrec 1 (tc_prevFactor tc) . showString ", tc_repeat=" . showsPrec 1 (tc_repeat tc) . showString " }" | A ' TestReporter ' provides hooks to customize the output of HTF . data TestReporter = TestReporter { tr_id :: String , tr_reportAllTests :: ReportAllTests -- ^ Called to report the IDs of all tests available. , tr_reportGlobalStart :: ReportGlobalStart -- ^ Called to report the start of test execution. , tr_reportTestStart :: ReportTestStart -- ^ Called to report the start of a single test. , tr_reportTestResult :: ReportTestResult -- ^ Called to report the result of a single test. , tr_reportGlobalResults :: ReportGlobalResults -- ^ Called to report the overall results of all tests. } emptyTestReporter :: String -> TestReporter emptyTestReporter id = TestReporter { tr_id = id , tr_reportAllTests = \_ -> return () , tr_reportGlobalStart = \_ -> return () , tr_reportTestStart = \_ -> return () , tr_reportTestResult = \_ -> return () , tr_reportGlobalResults = \_ -> return () } instance Show TestReporter where showsPrec _ x = showString (tr_id x) instance Eq TestReporter where x == y = (tr_id x) == (tr_id y) -- | Reports the IDs of all tests available. type ReportAllTests = [FlatTest] -> TR () -- | Signals that test execution is about to start. type ReportGlobalStart = [FlatTest] -> TR () -- | Reports the start of a single test. type ReportTestStart = FlatTest -> TR () -- | Reports the result of a single test. type ReportTestResult = FlatTestResult -> TR () data ReportGlobalResultsArg = ReportGlobalResultsArg { rgra_timeMs :: Milliseconds , rgra_passed :: [FlatTestResult] , rgra_pending :: [FlatTestResult] , rgra_failed :: [FlatTestResult] , rgra_errors :: [FlatTestResult] , rgra_timedOut :: [FlatTestResult] , rgra_filtered :: [FlatTest] } -- | Reports the overall results of all tests. type ReportGlobalResults = ReportGlobalResultsArg -> TR ()
null
https://raw.githubusercontent.com/skogsbaer/HTF/a42450c89b7a3a3a50e381f36de3ac28faab2a16/Test/Framework/TestTypes.hs
haskell
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public 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 | This module defines types (and small auxiliary functions) for organizing tests, for configuring the execution of tests, and for representing and reporting their results. This functionality is mainly used internally in the code generated by the @hftpp@ pre-processor. * Organizing tests * Executing tests * Reporting results * Specifying results. | Type for naming tests. | Type for distinguishing different sorts of tests. | General options for tests | The default 'TestOptions' | Something with 'TestOptions' | Shortcut for constructing a 'WithTestOptions' value. | A type class for an assertion with 'TestOptions'. | Abstract type for tests and their results. | Abstract type for test suites and their results. | A type denoting the hierarchical name of a test. | Splits a 'TestPath' into a list of test identifiers. | Creates a string representation from a 'TestPath'. | Returns the final name of a 'TestPath' | Returns the name of the prefix of a test path. The prefix is everything except the last element. | Generic type for flattened tests and their results. ^ The sort of the test. ^ Hierarchival path. ^ Place of definition. ^ A generic payload. | Key of a flat test for the history database. | Flattened representation of tests. | A filter is a predicate on 'FlatTest'. If the predicate is 'True', the flat test is run. | A type for call-stacks | The result of a test run. ^ The summary result of the test. ^ The stack leading to the test failure ^ A message describing the result. ^ Execution time in milliseconds. ^ 'True' if the execution took too long | The result of running a 'FlatTest' | The state type for the 'TR' monad. ^ Results collected so far. ^ Current index for splitted output. | The initial test state. | The 'TR' (test runner) monad. ^ Output goes to 'Handle', boolean flag indicates whether the handle should be closed at the end. | Configuration of test execution. ^ If set, displays messages only for failed tests. ^ Shuffle tests before parallel execution ^ Output destination of progress and result messages. ^ Output destination of XML result summary ^ Filter for the tests to run. ^ Test reporters to use. ^ Whether to use colored output ^ Path to history file ^ History of previous test runs ^ Sort ascending by previous execution times ^ Do not regard timeout as an error ^ Maximum time in milliseconds a single test is allowed to run ^ Maximum factor a single test is allowed to run slower than its previous execution ^ Number of times to repeat tests selected on the command line before reporting them as a success. ^ Called to report the IDs of all tests available. ^ Called to report the start of test execution. ^ Called to report the start of a single test. ^ Called to report the result of a single test. ^ Called to report the overall results of all tests. | Reports the IDs of all tests available. | Signals that test execution is about to start. | Reports the start of a single test. | Reports the result of a single test. | Reports the overall results of all tests.
# LANGUAGE FlexibleInstances # Copyright ( c ) 2005 - 2022 - License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 , USA module Test.Framework.TestTypes ( TestID, Test(..), TestOptions(..), AssertionWithTestOptions(..), WithTestOptions(..), TestSuite(..), TestSort(..), TestPath(..), GenFlatTest(..), FlatTest, TestFilter, testPathToList, flatName, finalName, prefixName, defaultTestOptions, withOptions, historyKey, TR, TestState(..), initTestState, TestConfig(..), TestOutput(..), ReportAllTests, ReportGlobalStart, ReportTestStart, ReportTestResult, ReportGlobalResults, ReportGlobalResultsArg(..), TestReporter(..), emptyTestReporter, attachCallStack, CallStack, TestResult(..), FlatTestResult, Milliseconds, RunResult(..) ) where import Test.Framework.Location import Test.Framework.Colors import Test.Framework.History import Test.Framework.TestInterface import Control.Monad.RWS import System.IO import Data.Maybe import qualified Data.List as List import qualified Data.Text as T type TestID = String data TestSort = UnitTest | QuickCheckTest | BlackBoxTest deriving (Eq,Show,Read) data TestOptions = TestOptions { to_parallel :: Bool } deriving (Eq,Show,Read) defaultTestOptions :: TestOptions defaultTestOptions = TestOptions { to_parallel = True } data WithTestOptions a = WithTestOptions { wto_options :: TestOptions , wto_payload :: a } deriving (Eq,Show,Read) withOptions :: (TestOptions -> TestOptions) -> a -> WithTestOptions a withOptions f x = WithTestOptions (f defaultTestOptions) x class AssertionWithTestOptions a where testOptions :: a -> TestOptions assertion :: a -> Assertion instance AssertionWithTestOptions (IO a) where testOptions _ = defaultTestOptions assertion io = io >> return () instance AssertionWithTestOptions (WithTestOptions (IO a)) where testOptions (WithTestOptions opts _) = opts assertion (WithTestOptions _ io) = io >> return () data Test = BaseTest TestSort TestID (Maybe Location) TestOptions Assertion | CompoundTest TestSuite data TestSuite = TestSuite TestID [Test] | AnonTestSuite [Test] data TestPath = TestPathBase TestID | TestPathCompound (Maybe TestID) TestPath deriving (Show) testPathToList :: TestPath -> [Maybe TestID] testPathToList (TestPathBase i) = [Just i] testPathToList (TestPathCompound mi p) = mi : testPathToList p flatName :: TestPath -> String flatName p = flatNameFromList (testPathToList p) flatNameFromList :: [Maybe TestID] -> String flatNameFromList l = List.intercalate ":" (map (fromMaybe "") l) finalName :: TestPath -> String finalName (TestPathBase i) = i finalName (TestPathCompound _ p) = finalName p prefixName :: TestPath -> String prefixName path = let l = case reverse (testPathToList path) of [] -> [] (_:xs) -> reverse xs in flatNameFromList l data GenFlatTest a = FlatTest } historyKey :: GenFlatTest a -> T.Text historyKey ft = T.pack (flatName (ft_path ft)) type FlatTest = GenFlatTest (WithTestOptions Assertion) type TestFilter = FlatTest -> Bool type CallStack = [(Maybe String, Location)] data RunResult = RunResult } attachCallStack :: ColorString -> HtfStack -> ColorString attachCallStack msg stack = let fstack = formatHtfStack stack in if fstack == "" then msg else ensureNewlineColorString msg +++ noColor fstack type FlatTestResult = GenFlatTest RunResult } initTestState :: TestState initTestState = TestState [] 0 type TR = RWST TestConfig () TestState IO | The destination of progress and result messages from HTF . ^ Output goes to files whose names are derived from ' FilePath ' by appending a number to it . Numbering starts at zero . deriving (Show, Eq) data TestConfig = TestConfig ^ Use @Just i@ for parallel execution with @i@ threads , @Nothing@ for sequential execution . ^ Stop test run as soon as one test fails } instance Show TestConfig where showsPrec prec tc = showParen (prec > 0) $ showString "TestConfig { " . showString "tc_quiet=" . showsPrec 1 (tc_quiet tc) . showString ", tc_threads=" . showsPrec 1 (tc_threads tc) . showString ", tc_shuffle=" . showsPrec 1 (tc_shuffle tc) . showString ", tc_output=" . showsPrec 1 (tc_output tc) . showString ", tc_outputXml=" . showsPrec 1 (tc_outputXml tc) . showString ", tc_filter=<filter>" . showString ", tc_reporters=" . showsPrec 1 (tc_reporters tc) . showString ", tc_useColors=" . showsPrec 1 (tc_useColors tc) . showString ", tc_historyFile=" . showsPrec 1 (tc_historyFile tc) . showString ", tc_history=" . showsPrec 1 (tc_history tc) . showString ", tc_sortByPrevTime=" . showsPrec 1 (tc_sortByPrevTime tc) . showString ", tc_failFast=" . showsPrec 1 (tc_failFast tc) . showString ", tc_timeoutIsSuccess=" . showsPrec 1 (tc_timeoutIsSuccess tc) . showString ", tc_maxSingleTestTime=" . showsPrec 1 (tc_maxSingleTestTime tc) . showString ", tc_prevFactor=" . showsPrec 1 (tc_prevFactor tc) . showString ", tc_repeat=" . showsPrec 1 (tc_repeat tc) . showString " }" | A ' TestReporter ' provides hooks to customize the output of HTF . data TestReporter = TestReporter { tr_id :: String } emptyTestReporter :: String -> TestReporter emptyTestReporter id = TestReporter { tr_id = id , tr_reportAllTests = \_ -> return () , tr_reportGlobalStart = \_ -> return () , tr_reportTestStart = \_ -> return () , tr_reportTestResult = \_ -> return () , tr_reportGlobalResults = \_ -> return () } instance Show TestReporter where showsPrec _ x = showString (tr_id x) instance Eq TestReporter where x == y = (tr_id x) == (tr_id y) type ReportAllTests = [FlatTest] -> TR () type ReportGlobalStart = [FlatTest] -> TR () type ReportTestStart = FlatTest -> TR () type ReportTestResult = FlatTestResult -> TR () data ReportGlobalResultsArg = ReportGlobalResultsArg { rgra_timeMs :: Milliseconds , rgra_passed :: [FlatTestResult] , rgra_pending :: [FlatTestResult] , rgra_failed :: [FlatTestResult] , rgra_errors :: [FlatTestResult] , rgra_timedOut :: [FlatTestResult] , rgra_filtered :: [FlatTest] } type ReportGlobalResults = ReportGlobalResultsArg -> TR ()
c5a3b063c69d513b83e4ca09da8940ce41bfd16db1c4fd9abb652c8a3edc3586
aryx/xix
dev_textual_window.ml
open Common open Device module W = Window module T = Terminal let dev_text = { Device.default with name = "text"; perm = Plan9.r; read_threaded = (fun offset count w -> let term = w.W.terminal in let str = String.create term.T.nrunes in for i = 0 to term.T.nrunes - 1 do str.[i] <- term.T.text.(i); done; Device.honor_offset_and_count offset count str ); }
null
https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/windows/dev_textual_window.ml
ocaml
open Common open Device module W = Window module T = Terminal let dev_text = { Device.default with name = "text"; perm = Plan9.r; read_threaded = (fun offset count w -> let term = w.W.terminal in let str = String.create term.T.nrunes in for i = 0 to term.T.nrunes - 1 do str.[i] <- term.T.text.(i); done; Device.honor_offset_and_count offset count str ); }
0f0f7144b643052662f5185f1e9fbb57d52c073c463f98783d77ea567aca78be
FrancoisMalan/DivideScannedImages
DivideScannedImages.scm
; DivideScannedImages.scm by Based on a script originally by ; ; Locates each separate element in an image and creates a new image from each. if option is selected , will call the deskew plugin by ( if it is installed ) on each item ; ; License: ; ; 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. ; The GNU Public License is available at ; (define (script_fu_DivideScannedImages img inLayer inSquareCrop inPadding inLimit inDeskew inAutoClose inThreshold inSize inDefBg inBgCol inCorner inX inY inSaveInSourceDir inDir inSaveType inJpgQual inFileName inFileNumber) (let* ( (inSaveFiles TRUE) (width (car (gimp-image-width img))) (height (car (gimp-image-height img))) (newpath 0) (strokes 0) (tempVector 0) (tempImage 0) (tempLayer 0) (bounds 0) (centroidx 0) (centroidy 0) (sizex 0) (sizey 0) (halfsidelength 0) (sidelength 0) (count 0) (numextracted 0) (saveString "") (newFileName "") (tempdisplay 0) (buffname "dsibuff") (pathchar (if (equal? (substring gimp-dir 0 1) "/") "/" "\\")) (imgpath "") ) ; it begins here (gimp-context-push) (set! imgpath (car (gimp-image-get-filename img))) (gimp-image-undo-disable img) ;logging ;(gimp-message-set-handler ERROR-CONSOLE) ;(gimp-message-set-handler CONSOLE) ;(gimp-message-set-handler MESSAGE-BOX) or start GIMP wwith " gimp --console - messages " to spawn a console box ;then use this: ( gimp - message " foobar " ) ;testing for functions defined ( if ( defined ? ' plug - in - shift ) ( gimp - message " It Exists " ) ( gimp - message " Does nt Exist " ) ) ;set up saving (if (= inSaveFiles TRUE) (set! saveString (cond (( equal? inSaveType 0 ) ".jpg" ) (( equal? inSaveType 1 ) ".png" ) ) )) ; The block below was included in the original "DivideScannedImages.scm", but seems to cause problems by adding a white border which is then subsequently sampled. ; Expand the image a bit to fix problem with images near the right edge. Probably could get away just expanding ; width but go ahead and expand height in case same issue is there... ( set ! width ( + width 30 ) ) ( set ! height ( + height 30 ) ) ( gimp - image - resize img width height 15 15 ) ;(gimp-layer-resize-to-image-size inLayer) If the background was n't manually defined , pick the colour from one of the four corners ( using radius 3 average ) (if (not (= inDefBg TRUE)) (begin (cond ; else ( (equal? inCorner 0) (set! inBgCol (car (gimp-image-pick-color img inLayer inX inY TRUE TRUE 5))) ) ( (equal? inCorner 1) (set! inBgCol (car (gimp-image-pick-color img inLayer (- width inX) inY TRUE TRUE 5))) ) ( (equal? inCorner 2) (set! inBgCol (car (gimp-image-pick-color img inLayer inX (- height inY) TRUE TRUE 5))) ) ( (equal? inCorner 3) (set! inBgCol (car (gimp-image-pick-color img inLayer (- width inX) (- height inY) TRUE TRUE 5))) )) )) (gimp-image-select-color img CHANNEL-OP-REPLACE inLayer inBgCol) (gimp-context-set-background inBgCol) ; convert inverted copy of the background selection to a path (gimp-selection-feather img (/ (min width height) 100)) (gimp-selection-sharpen img) (gimp-selection-invert img) (plug-in-sel2path RUN-NONINTERACTIVE img inLayer) ;break up the vectors and loop across each vector (boundary path of each object) (set! newpath (vector-ref (cadr (gimp-image-get-vectors img)) 0)) (set! strokes (gimp-vectors-get-strokes newpath)) (while (and (< count (car strokes)) (< numextracted inLimit)) (set! tempVector (gimp-vectors-new img "Temp")) (gimp-image-add-vectors img (car tempVector) -1) (gimp-vectors-stroke-new-from-points (car tempVector) (list-ref (gimp-vectors-stroke-get-points newpath (vector-ref (cadr strokes) count)) 0) (list-ref (gimp-vectors-stroke-get-points newpath (vector-ref (cadr strokes) count)) 1) (list-ref (gimp-vectors-stroke-get-points newpath (vector-ref (cadr strokes) count)) 2) (list-ref (gimp-vectors-stroke-get-points newpath (vector-ref (cadr strokes) count)) 3) ) (gimp-vectors-to-selection (car tempVector) CHANNEL-OP-REPLACE TRUE FALSE 0 0) ;check for minimum size (set! bounds (gimp-selection-bounds img)) (set! sizex (- (list-ref bounds 3) (list-ref bounds 1))) (set! sizey (- (list-ref bounds 4) (list-ref bounds 2))) (if (and (> sizex inSize) (> sizey inSize) ;min size slider (< sizex width) (< sizey height)) ;max size image (begin (if (and (= inDeskew TRUE) (defined? 'gimp-deskew-plugin)) (begin (gimp-progress-set-text "Deskewing...") (gimp-rect-select img (list-ref bounds 1) (list-ref bounds 2) sizex sizey CHANNEL-OP-REPLACE FALSE 0 ) (set! buffname (car (gimp-edit-named-copy inLayer buffname))) (set! tempImage (car (gimp-edit-named-paste-as-new buffname))) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) (gimp-image-undo-disable tempImage) ;(set! tempdisplay (car (gimp-display-new tempImage))) (gimp-layer-flatten tempLayer) (gimp-deskew-plugin 0 tempImage tempLayer 0 0 0 0 0) (gimp-image-resize-to-layers tempImage) (gimp-layer-flatten tempLayer) (gimp-fuzzy-select tempLayer 0 0 inThreshold CHANNEL-OP-REPLACE TRUE FALSE 0 TRUE) (gimp-selection-invert tempImage) (set! bounds (gimp-selection-bounds tempImage)) (set! sizex (- (list-ref bounds 3) (list-ref bounds 1))) (set! sizey (- (list-ref bounds 4) (list-ref bounds 2))) (gimp-selection-none tempImage) (gimp-image-crop tempImage sizex sizey (list-ref bounds 1) (list-ref bounds 2)) (if (= inSquareCrop TRUE) (begin (if (> sizex sizey) (begin (script-fu-addborder tempImage tempLayer 0 (/ (- sizex sizey) 2) inBgCol 0) (gimp-image-raise-item-to-top tempImage tempLayer) (gimp-image-merge-visible-layers tempImage EXPAND-AS-NECESSARY) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) )) (if (< sizex sizey) (begin (script-fu-addborder tempImage tempLayer (/ (- sizey sizex) 2) 0 inBgCol 0) (gimp-image-raise-item-to-top tempImage tempLayer) (gimp-image-merge-visible-layers tempImage EXPAND-AS-NECESSARY) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) )) ))) (begin (set! tempImage img) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) (gimp-image-undo-disable tempImage) (if (= inSquareCrop TRUE) (begin (set! centroidx (* 0.5 (+ (list-ref bounds 1) (list-ref bounds 3)))) (set! centroidy (* 0.5 (+ (list-ref bounds 2) (list-ref bounds 4)))) (set! halfsidelength (+ inPadding (* 0.5 (max sizex sizey)))) (gimp-rect-select tempImage (- centroidx halfsidelength) (- centroidy halfsidelength) (* halfsidelength 2) (* halfsidelength 2) CHANNEL-OP-REPLACE FALSE 0 ) ) (gimp-rect-select tempImage (list-ref bounds 1) (list-ref bounds 2) sizex sizey CHANNEL-OP-REPLACE FALSE 0) ) (set! buffname (car (gimp-edit-named-copy inLayer buffname))) (set! tempImage (car (gimp-edit-named-paste-as-new buffname))) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) ) ) (set! tempdisplay (car (gimp-display-new tempImage))) (if (> inPadding 0) (begin (script-fu-addborder tempImage tempLayer inPadding inPadding inBgCol 0) (gimp-image-merge-visible-layers tempImage EXPAND-AS-NECESSARY) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) )) (gimp-image-undo-enable tempImage) ;save file (if (= inSaveFiles TRUE) (begin (let* ((targetDir inDir)) (if (= inSaveInSourceDir TRUE) (set! targetDir (unbreakupstr (butlast (strbreakup imgpath pathchar)) pathchar)) ) (set! newFileName (string-append targetDir pathchar inFileName (substring "00000" (string-length (number->string (+ inFileNumber numextracted)))) (number->string (+ inFileNumber numextracted)) saveString)) (gimp-image-set-resolution tempImage 600 600) ; The DPI (if (equal? saveString ".jpg") (file-jpeg-save RUN-NONINTERACTIVE tempImage tempLayer newFileName newFileName inJpgQual 0.1 1 0 "Custom JPG compression by FrancoisM" 0 1 0 1) (gimp-file-save RUN-NONINTERACTIVE tempImage tempLayer newFileName newFileName) ) (if (= inAutoClose TRUE) (begin (gimp-display-delete tempdisplay) ) ) ) )) (set! numextracted (+ numextracted 1)) ) ) (gimp-image-remove-vectors img (car tempVector)) (set! count (+ count 1)) ) input drawable name should be set to 1919191919 if in batch (if (and (> numextracted 0) (equal? (car (gimp-drawable-get-name inLayer)) "1919191919")) (gimp-drawable-set-name inLayer (number->string (+ 1919191919 numextracted)))) ;delete temp path (gimp-image-remove-vectors img newpath) (gimp-selection-none img) ;done (gimp-image-undo-enable img) (gimp-progress-end) (gimp-displays-flush) (gimp-context-pop) ) ) (script-fu-register "script_fu_DivideScannedImages" "<Image>/Filters/Divide Scanned Images..." "Attempts to isolate images from a uniform background and saves a new square image for each" "Francois Malan" "Francois Malan" "Feb 2016" "RGB* GRAY*" SF-IMAGE "image" 0 SF-DRAWABLE "drawable" 0 SF-TOGGLE "Force square crop" FALSE SF-ADJUSTMENT "Square border padding (pixels)" (list 0 0 100 1 10 0 SF-SLIDER) SF-ADJUSTMENT "Max number of items" (list 10 1 100 1 10 0 SF-SLIDER) SF-TOGGLE "Run Deskew" TRUE SF-TOGGLE "Auto-close sub-images after saving" TRUE SF-ADJUSTMENT "Selection Threshold" (list 25 0 255 1 10 1 SF-SLIDER) SF-ADJUSTMENT "Size Threshold" (list 100 0 2000 10 100 1 SF-SLIDER) SF-TOGGLE "Manually define background colour" FALSE SF-COLOR "Manual background colour" '(255 255 255) SF-OPTION "Auto-background sample corner" (list "Top Left" "Top Right" "Bottom Left" "Bottom Right") SF-ADJUSTMENT "Auto-background sample x-offset" (list 25 5 100 1 10 1 SF-SLIDER) SF-ADJUSTMENT "Auto-background sample y-offset" (list 25 5 100 1 10 1 SF-SLIDER) SF-TOGGLE "Save output to source directory" TRUE SF-DIRNAME "Target directory (if not to source)" "" SF-OPTION "Save File Type" (list "jpg" "png") SF-ADJUSTMENT "JPG Quality" (list 0.8 0.1 1.0 1 10 1 SF-SLIDER) SF-STRING "Save File Base Name" "Crop" SF-ADJUSTMENT "Save File Start Number" (list 1 0 9000 1 100 0 SF-SPINNER) ) (define (script_fu_BatchDivideScannedImages inSourceDir inLoadType inSquareCrop inPadding inLimit inDeskew inAutoClose inThreshold inSize inDefBg inBgCol inCorner inX inY inSaveInSourceDir inDestDir inSaveType inJpgQual inFileName inFileNumber) (let* ( (varLoadStr "") (varFileList 0) (varCounter inFileNumber) (pathchar (if (equal? (substring gimp-dir 0 1) "/") "/" "\\")) ) (define split (lambda (ls) (letrec ((split-h (lambda (ls ls1 ls2) (cond ((or (null? ls) (null? (cdr ls))) (cons (reverse ls2) ls1)) (else (split-h (cddr ls) (cdr ls1) (cons (car ls1) ls2))))))) (split-h ls ls '())))) (define merge (lambda (pred ls1 ls2) (cond ((null? ls1) ls2) ((null? ls2) ls1) ((pred (car ls1) (car ls2)) (cons (car ls1) (merge pred (cdr ls1) ls2))) (else (cons (car ls2) (merge pred ls1 (cdr ls2))))))) ;pred is the comparison, i.e. <= for an ascending numeric list, or ;string<=? for a case sensitive alphabetical sort, ;string-ci<=? for a case insensitive alphabetical sort, (define merge-sort (lambda (pred ls) (cond ((null? ls) ls) ((null? (cdr ls)) ls) (else (let ((splits (split ls))) (merge pred (merge-sort pred (car splits)) (merge-sort pred (cdr splits)))))))) ;begin here (set! varLoadStr (cond (( equal? inLoadType 0 ) ".[jJ][pP][gG]" ) (( equal? inLoadType 1 ) ".[jJ][pP][eE][gG]" ) (( equal? inLoadType 2 ) ".[bB][mM][pP]" ) (( equal? inLoadType 3 ) ".[pP][nN][gG]" ) (( equal? inLoadType 4 ) ".[tT][iI][fF]" ) (( equal? inLoadType 5 ) ".[tT][iI][fF][fF]" ) )) (set! varFileList (merge-sort string<=? (cadr (file-glob (string-append inSourceDir pathchar "*" varLoadStr) 1)))) (while (not (null? varFileList)) (let* ((filename (car varFileList)) (image (car (gimp-file-load RUN-NONINTERACTIVE filename filename))) (drawable (car (gimp-image-get-active-layer image)))) ;flag for batch mode (gimp-drawable-set-name drawable "1919191919") (gimp-progress-set-text (string-append "Working on ->" filename)) (script_fu_DivideScannedImages image drawable inSquareCrop inPadding inLimit inDeskew inAutoClose inThreshold inSize inDefBg inBgCol inCorner inX inY inSaveInSourceDir inDestDir inSaveType inJpgQual inFileName varCounter) ;increment by number extracted. (set! varCounter (+ varCounter (- (string->number (car (gimp-drawable-get-name drawable))) 1919191919))) (gimp-image-delete image) ) (set! varFileList (cdr varFileList)) ) ) ) (script-fu-register "script_fu_BatchDivideScannedImages" "<Toolbox>/Xtns/Batch Tools/Batch Divide Scanned Images..." "Batch-divide a folder of full-page scans of images." "Francois Malan" "Francois Malan" "Feb 2016" "" SF-DIRNAME "Load from" "" SF-OPTION "Load File Type" (list "jpg" "jpeg" "bmp" "png" "tif" "tiff") SF-TOGGLE "Force square crop" FALSE SF-ADJUSTMENT "Square border padding (pixels)" (list 0 0 100 1 10 0 SF-SLIDER) SF-ADJUSTMENT "Max number of items" (list 10 1 100 1 10 0 SF-SLIDER) SF-TOGGLE "Run Deskew" TRUE SF-TOGGLE "Auto-close sub-images after saving" TRUE SF-ADJUSTMENT "Selection Threshold" (list 25 0 255 1 10 1 SF-SLIDER) SF-ADJUSTMENT "Size Threshold" (list 100 0 2000 10 100 1 SF-SLIDER) SF-TOGGLE "Manually define background colour" FALSE SF-COLOR "Manual background colour" '(255 255 255) SF-OPTION "Auto-background sample corner" (list "Top Left" "Top Right" "Bottom Left" "Bottom Right") SF-ADJUSTMENT "Auto-background sample x-offset" (list 25 5 100 1 10 1 SF-SLIDER) SF-ADJUSTMENT "Auto-background sample y-offset" (list 25 5 100 1 10 1 SF-SLIDER) SF-TOGGLE "Save output to source directory" TRUE SF-DIRNAME "Target directory (if not to source)" "" SF-OPTION "Save File Type" (list "jpg" "png") SF-ADJUSTMENT "JPG Quality" (list 0.8 0.1 1.0 1 10 1 SF-SLIDER) SF-STRING "Save File Base Name" "Crop" SF-ADJUSTMENT "Save File Start Number" (list 1 0 9000 1 100 0 SF-SPINNER) )
null
https://raw.githubusercontent.com/FrancoisMalan/DivideScannedImages/51e8f3983feeeeec4e2e3b3b00c5a06020e3e22b/DivideScannedImages.scm
scheme
DivideScannedImages.scm Locates each separate element in an image and creates a new image from each. License: This program is free software; you can redistribute it and/or modify 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. it begins here logging (gimp-message-set-handler ERROR-CONSOLE) (gimp-message-set-handler CONSOLE) (gimp-message-set-handler MESSAGE-BOX) then use this: testing for functions defined set up saving The block below was included in the original "DivideScannedImages.scm", but seems to cause problems by adding a white border which is then subsequently sampled. Expand the image a bit to fix problem with images near the right edge. Probably could get away just expanding width but go ahead and expand height in case same issue is there... (gimp-layer-resize-to-image-size inLayer) else convert inverted copy of the background selection to a path break up the vectors and loop across each vector (boundary path of each object) check for minimum size min size slider max size image (set! tempdisplay (car (gimp-display-new tempImage))) save file The DPI delete temp path done pred is the comparison, i.e. <= for an ascending numeric list, or string<=? for a case sensitive alphabetical sort, string-ci<=? for a case insensitive alphabetical sort, begin here flag for batch mode increment by number extracted.
by Based on a script originally by if option is selected , will call the deskew plugin by ( if it is installed ) on each item it under the terms of the GNU General Public License as published by The GNU Public License is available at (define (script_fu_DivideScannedImages img inLayer inSquareCrop inPadding inLimit inDeskew inAutoClose inThreshold inSize inDefBg inBgCol inCorner inX inY inSaveInSourceDir inDir inSaveType inJpgQual inFileName inFileNumber) (let* ( (inSaveFiles TRUE) (width (car (gimp-image-width img))) (height (car (gimp-image-height img))) (newpath 0) (strokes 0) (tempVector 0) (tempImage 0) (tempLayer 0) (bounds 0) (centroidx 0) (centroidy 0) (sizex 0) (sizey 0) (halfsidelength 0) (sidelength 0) (count 0) (numextracted 0) (saveString "") (newFileName "") (tempdisplay 0) (buffname "dsibuff") (pathchar (if (equal? (substring gimp-dir 0 1) "/") "/" "\\")) (imgpath "") ) (gimp-context-push) (set! imgpath (car (gimp-image-get-filename img))) (gimp-image-undo-disable img) or start GIMP wwith " gimp --console - messages " to spawn a console box ( gimp - message " foobar " ) ( if ( defined ? ' plug - in - shift ) ( gimp - message " It Exists " ) ( gimp - message " Does nt Exist " ) ) (if (= inSaveFiles TRUE) (set! saveString (cond (( equal? inSaveType 0 ) ".jpg" ) (( equal? inSaveType 1 ) ".png" ) ) )) ( set ! width ( + width 30 ) ) ( set ! height ( + height 30 ) ) ( gimp - image - resize img width height 15 15 ) If the background was n't manually defined , pick the colour from one of the four corners ( using radius 3 average ) (if (not (= inDefBg TRUE)) (begin ( (equal? inCorner 0) (set! inBgCol (car (gimp-image-pick-color img inLayer inX inY TRUE TRUE 5))) ) ( (equal? inCorner 1) (set! inBgCol (car (gimp-image-pick-color img inLayer (- width inX) inY TRUE TRUE 5))) ) ( (equal? inCorner 2) (set! inBgCol (car (gimp-image-pick-color img inLayer inX (- height inY) TRUE TRUE 5))) ) ( (equal? inCorner 3) (set! inBgCol (car (gimp-image-pick-color img inLayer (- width inX) (- height inY) TRUE TRUE 5))) )) )) (gimp-image-select-color img CHANNEL-OP-REPLACE inLayer inBgCol) (gimp-context-set-background inBgCol) (gimp-selection-feather img (/ (min width height) 100)) (gimp-selection-sharpen img) (gimp-selection-invert img) (plug-in-sel2path RUN-NONINTERACTIVE img inLayer) (set! newpath (vector-ref (cadr (gimp-image-get-vectors img)) 0)) (set! strokes (gimp-vectors-get-strokes newpath)) (while (and (< count (car strokes)) (< numextracted inLimit)) (set! tempVector (gimp-vectors-new img "Temp")) (gimp-image-add-vectors img (car tempVector) -1) (gimp-vectors-stroke-new-from-points (car tempVector) (list-ref (gimp-vectors-stroke-get-points newpath (vector-ref (cadr strokes) count)) 0) (list-ref (gimp-vectors-stroke-get-points newpath (vector-ref (cadr strokes) count)) 1) (list-ref (gimp-vectors-stroke-get-points newpath (vector-ref (cadr strokes) count)) 2) (list-ref (gimp-vectors-stroke-get-points newpath (vector-ref (cadr strokes) count)) 3) ) (gimp-vectors-to-selection (car tempVector) CHANNEL-OP-REPLACE TRUE FALSE 0 0) (set! bounds (gimp-selection-bounds img)) (set! sizex (- (list-ref bounds 3) (list-ref bounds 1))) (set! sizey (- (list-ref bounds 4) (list-ref bounds 2))) (begin (if (and (= inDeskew TRUE) (defined? 'gimp-deskew-plugin)) (begin (gimp-progress-set-text "Deskewing...") (gimp-rect-select img (list-ref bounds 1) (list-ref bounds 2) sizex sizey CHANNEL-OP-REPLACE FALSE 0 ) (set! buffname (car (gimp-edit-named-copy inLayer buffname))) (set! tempImage (car (gimp-edit-named-paste-as-new buffname))) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) (gimp-image-undo-disable tempImage) (gimp-layer-flatten tempLayer) (gimp-deskew-plugin 0 tempImage tempLayer 0 0 0 0 0) (gimp-image-resize-to-layers tempImage) (gimp-layer-flatten tempLayer) (gimp-fuzzy-select tempLayer 0 0 inThreshold CHANNEL-OP-REPLACE TRUE FALSE 0 TRUE) (gimp-selection-invert tempImage) (set! bounds (gimp-selection-bounds tempImage)) (set! sizex (- (list-ref bounds 3) (list-ref bounds 1))) (set! sizey (- (list-ref bounds 4) (list-ref bounds 2))) (gimp-selection-none tempImage) (gimp-image-crop tempImage sizex sizey (list-ref bounds 1) (list-ref bounds 2)) (if (= inSquareCrop TRUE) (begin (if (> sizex sizey) (begin (script-fu-addborder tempImage tempLayer 0 (/ (- sizex sizey) 2) inBgCol 0) (gimp-image-raise-item-to-top tempImage tempLayer) (gimp-image-merge-visible-layers tempImage EXPAND-AS-NECESSARY) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) )) (if (< sizex sizey) (begin (script-fu-addborder tempImage tempLayer (/ (- sizey sizex) 2) 0 inBgCol 0) (gimp-image-raise-item-to-top tempImage tempLayer) (gimp-image-merge-visible-layers tempImage EXPAND-AS-NECESSARY) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) )) ))) (begin (set! tempImage img) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) (gimp-image-undo-disable tempImage) (if (= inSquareCrop TRUE) (begin (set! centroidx (* 0.5 (+ (list-ref bounds 1) (list-ref bounds 3)))) (set! centroidy (* 0.5 (+ (list-ref bounds 2) (list-ref bounds 4)))) (set! halfsidelength (+ inPadding (* 0.5 (max sizex sizey)))) (gimp-rect-select tempImage (- centroidx halfsidelength) (- centroidy halfsidelength) (* halfsidelength 2) (* halfsidelength 2) CHANNEL-OP-REPLACE FALSE 0 ) ) (gimp-rect-select tempImage (list-ref bounds 1) (list-ref bounds 2) sizex sizey CHANNEL-OP-REPLACE FALSE 0) ) (set! buffname (car (gimp-edit-named-copy inLayer buffname))) (set! tempImage (car (gimp-edit-named-paste-as-new buffname))) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) ) ) (set! tempdisplay (car (gimp-display-new tempImage))) (if (> inPadding 0) (begin (script-fu-addborder tempImage tempLayer inPadding inPadding inBgCol 0) (gimp-image-merge-visible-layers tempImage EXPAND-AS-NECESSARY) (set! tempLayer (car (gimp-image-get-active-layer tempImage))) )) (gimp-image-undo-enable tempImage) (if (= inSaveFiles TRUE) (begin (let* ((targetDir inDir)) (if (= inSaveInSourceDir TRUE) (set! targetDir (unbreakupstr (butlast (strbreakup imgpath pathchar)) pathchar)) ) (set! newFileName (string-append targetDir pathchar inFileName (substring "00000" (string-length (number->string (+ inFileNumber numextracted)))) (number->string (+ inFileNumber numextracted)) saveString)) (if (equal? saveString ".jpg") (file-jpeg-save RUN-NONINTERACTIVE tempImage tempLayer newFileName newFileName inJpgQual 0.1 1 0 "Custom JPG compression by FrancoisM" 0 1 0 1) (gimp-file-save RUN-NONINTERACTIVE tempImage tempLayer newFileName newFileName) ) (if (= inAutoClose TRUE) (begin (gimp-display-delete tempdisplay) ) ) ) )) (set! numextracted (+ numextracted 1)) ) ) (gimp-image-remove-vectors img (car tempVector)) (set! count (+ count 1)) ) input drawable name should be set to 1919191919 if in batch (if (and (> numextracted 0) (equal? (car (gimp-drawable-get-name inLayer)) "1919191919")) (gimp-drawable-set-name inLayer (number->string (+ 1919191919 numextracted)))) (gimp-image-remove-vectors img newpath) (gimp-selection-none img) (gimp-image-undo-enable img) (gimp-progress-end) (gimp-displays-flush) (gimp-context-pop) ) ) (script-fu-register "script_fu_DivideScannedImages" "<Image>/Filters/Divide Scanned Images..." "Attempts to isolate images from a uniform background and saves a new square image for each" "Francois Malan" "Francois Malan" "Feb 2016" "RGB* GRAY*" SF-IMAGE "image" 0 SF-DRAWABLE "drawable" 0 SF-TOGGLE "Force square crop" FALSE SF-ADJUSTMENT "Square border padding (pixels)" (list 0 0 100 1 10 0 SF-SLIDER) SF-ADJUSTMENT "Max number of items" (list 10 1 100 1 10 0 SF-SLIDER) SF-TOGGLE "Run Deskew" TRUE SF-TOGGLE "Auto-close sub-images after saving" TRUE SF-ADJUSTMENT "Selection Threshold" (list 25 0 255 1 10 1 SF-SLIDER) SF-ADJUSTMENT "Size Threshold" (list 100 0 2000 10 100 1 SF-SLIDER) SF-TOGGLE "Manually define background colour" FALSE SF-COLOR "Manual background colour" '(255 255 255) SF-OPTION "Auto-background sample corner" (list "Top Left" "Top Right" "Bottom Left" "Bottom Right") SF-ADJUSTMENT "Auto-background sample x-offset" (list 25 5 100 1 10 1 SF-SLIDER) SF-ADJUSTMENT "Auto-background sample y-offset" (list 25 5 100 1 10 1 SF-SLIDER) SF-TOGGLE "Save output to source directory" TRUE SF-DIRNAME "Target directory (if not to source)" "" SF-OPTION "Save File Type" (list "jpg" "png") SF-ADJUSTMENT "JPG Quality" (list 0.8 0.1 1.0 1 10 1 SF-SLIDER) SF-STRING "Save File Base Name" "Crop" SF-ADJUSTMENT "Save File Start Number" (list 1 0 9000 1 100 0 SF-SPINNER) ) (define (script_fu_BatchDivideScannedImages inSourceDir inLoadType inSquareCrop inPadding inLimit inDeskew inAutoClose inThreshold inSize inDefBg inBgCol inCorner inX inY inSaveInSourceDir inDestDir inSaveType inJpgQual inFileName inFileNumber) (let* ( (varLoadStr "") (varFileList 0) (varCounter inFileNumber) (pathchar (if (equal? (substring gimp-dir 0 1) "/") "/" "\\")) ) (define split (lambda (ls) (letrec ((split-h (lambda (ls ls1 ls2) (cond ((or (null? ls) (null? (cdr ls))) (cons (reverse ls2) ls1)) (else (split-h (cddr ls) (cdr ls1) (cons (car ls1) ls2))))))) (split-h ls ls '())))) (define merge (lambda (pred ls1 ls2) (cond ((null? ls1) ls2) ((null? ls2) ls1) ((pred (car ls1) (car ls2)) (cons (car ls1) (merge pred (cdr ls1) ls2))) (else (cons (car ls2) (merge pred ls1 (cdr ls2))))))) (define merge-sort (lambda (pred ls) (cond ((null? ls) ls) ((null? (cdr ls)) ls) (else (let ((splits (split ls))) (merge pred (merge-sort pred (car splits)) (merge-sort pred (cdr splits)))))))) (set! varLoadStr (cond (( equal? inLoadType 0 ) ".[jJ][pP][gG]" ) (( equal? inLoadType 1 ) ".[jJ][pP][eE][gG]" ) (( equal? inLoadType 2 ) ".[bB][mM][pP]" ) (( equal? inLoadType 3 ) ".[pP][nN][gG]" ) (( equal? inLoadType 4 ) ".[tT][iI][fF]" ) (( equal? inLoadType 5 ) ".[tT][iI][fF][fF]" ) )) (set! varFileList (merge-sort string<=? (cadr (file-glob (string-append inSourceDir pathchar "*" varLoadStr) 1)))) (while (not (null? varFileList)) (let* ((filename (car varFileList)) (image (car (gimp-file-load RUN-NONINTERACTIVE filename filename))) (drawable (car (gimp-image-get-active-layer image)))) (gimp-drawable-set-name drawable "1919191919") (gimp-progress-set-text (string-append "Working on ->" filename)) (script_fu_DivideScannedImages image drawable inSquareCrop inPadding inLimit inDeskew inAutoClose inThreshold inSize inDefBg inBgCol inCorner inX inY inSaveInSourceDir inDestDir inSaveType inJpgQual inFileName varCounter) (set! varCounter (+ varCounter (- (string->number (car (gimp-drawable-get-name drawable))) 1919191919))) (gimp-image-delete image) ) (set! varFileList (cdr varFileList)) ) ) ) (script-fu-register "script_fu_BatchDivideScannedImages" "<Toolbox>/Xtns/Batch Tools/Batch Divide Scanned Images..." "Batch-divide a folder of full-page scans of images." "Francois Malan" "Francois Malan" "Feb 2016" "" SF-DIRNAME "Load from" "" SF-OPTION "Load File Type" (list "jpg" "jpeg" "bmp" "png" "tif" "tiff") SF-TOGGLE "Force square crop" FALSE SF-ADJUSTMENT "Square border padding (pixels)" (list 0 0 100 1 10 0 SF-SLIDER) SF-ADJUSTMENT "Max number of items" (list 10 1 100 1 10 0 SF-SLIDER) SF-TOGGLE "Run Deskew" TRUE SF-TOGGLE "Auto-close sub-images after saving" TRUE SF-ADJUSTMENT "Selection Threshold" (list 25 0 255 1 10 1 SF-SLIDER) SF-ADJUSTMENT "Size Threshold" (list 100 0 2000 10 100 1 SF-SLIDER) SF-TOGGLE "Manually define background colour" FALSE SF-COLOR "Manual background colour" '(255 255 255) SF-OPTION "Auto-background sample corner" (list "Top Left" "Top Right" "Bottom Left" "Bottom Right") SF-ADJUSTMENT "Auto-background sample x-offset" (list 25 5 100 1 10 1 SF-SLIDER) SF-ADJUSTMENT "Auto-background sample y-offset" (list 25 5 100 1 10 1 SF-SLIDER) SF-TOGGLE "Save output to source directory" TRUE SF-DIRNAME "Target directory (if not to source)" "" SF-OPTION "Save File Type" (list "jpg" "png") SF-ADJUSTMENT "JPG Quality" (list 0.8 0.1 1.0 1 10 1 SF-SLIDER) SF-STRING "Save File Base Name" "Crop" SF-ADJUSTMENT "Save File Start Number" (list 1 0 9000 1 100 0 SF-SPINNER) )
0883a8f2b53666dc3cbe83ed4e3ad2937a725538b857a3b8b110923477d50a69
TrustInSoft/tis-interpreter
one_hyp.ml
Modified by TrustInSoft open Cil_types let emitter = Emitter.create "Test" [ Emitter.Property_status ] ~correctness:[] ~tuning:[] let emitter2 = Emitter.create "Test2" [ Emitter.Property_status ] ~correctness:[] ~tuning:[] let set_status ?(emitter=emitter) p hyps s = Kernel.feedback "SETTING STATUS OF %a TO %a" Property.pretty p Property_status.Emitted_status.pretty s; Property_status.emit emitter p ~hyps s let print_status = Dynamic.get ~plugin:"Report" "print" (Datatype.func Datatype.unit Datatype.unit) let clear () = Kernel.feedback "CLEARING"; Project.clear ~selection:(State_selection.with_dependencies Property_status.self) () let main () = Ast.compute (); print_status (); let main, _, _, h, g = let l = Annotations.fold_all_code_annot (fun stmt _ ca acc -> let kf = Kernel_function.find_englobing_kf stmt in let ps = Property.ip_of_code_annot kf stmt ca in match ps with | [ p ] -> p :: acc | _ -> assert false) [] in match l with | [ p1; p2; p3; p4; p5 ] -> p1, p2, p3, p4, p5 | _ -> assert false in let ensures = let kf = Globals.Functions.find_by_name "f" in let spec = Annotations.funspec kf in Property.ip_post_cond_of_spec kf Kglobal ~active:[] spec in (* *********************************************************************** *) (* hyp = never_tried *) (* unknown *) set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = considered_valid *) clear (); (* unknown *) set_status h ensures Property_status.Dont_know; print_status (); (* true *) set_status h ensures Property_status.True; print_status (); clear (); (* false *) set_status h [] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = valid *) clear (); (* unknown *) set_status main [] Property_status.True; set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status main [] Property_status.True; set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = valid under hyp *) clear (); (* unknown *) set_status g [] Property_status.Dont_know; set_status main [ g ] Property_status.True; set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status g [] Property_status.Dont_know; set_status main [ g ] Property_status.True; set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = dont_know *) clear (); (* unknown *) set_status main [] Property_status.Dont_know; set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status main [] Property_status.Dont_know; set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = invalid *) clear (); (* unknown *) set_status main [] Property_status.False_and_reachable; set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status main [] Property_status.False_and_reachable; set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = invalid under hyp *) clear (); (* unknown *) set_status g [] Property_status.Dont_know; set_status main [ ] Property_status.False_and_reachable; set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status g [] Property_status.Dont_know; set_status main [ ] Property_status.False_and_reachable; set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = invalid but dead *) clear (); (* unknown *) set_status g [] Property_status.False_and_reachable; set_status main [ ] Property_status.False_and_reachable; set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status g [] Property_status.False_and_reachable; set_status main [ ] Property_status.False_and_reachable; set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = valid but dead *) clear (); (* unknown *) set_status g [] Property_status.False_and_reachable; set_status main [ g ] Property_status.True; set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status g [] Property_status.False_and_reachable; set_status main [ g ] Property_status.True; set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = unknown but dead *) clear (); (* unknown *) set_status g [] Property_status.False_and_reachable; set_status main [ g ] Property_status.Dont_know; set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status g [] Property_status.False_and_reachable; set_status main [ g ] Property_status.Dont_know; set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) (* hyp = inconsistent *) clear (); (* unknown *) set_status main [] Property_status.True; set_status ~emitter:emitter2 main [] Property_status.False_and_reachable; set_status h [ main ] Property_status.Dont_know; print_status (); (* true *) set_status h [ main ] Property_status.True; print_status (); clear (); (* false *) set_status main [] Property_status.True; set_status ~emitter:emitter2 main [] Property_status.False_and_reachable; set_status h [ ] Property_status.False_and_reachable; print_status (); (* *********************************************************************** *) () let () = Db.Main.extend main
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/report/tests/report/one_hyp.ml
ocaml
*********************************************************************** hyp = never_tried unknown true false *********************************************************************** hyp = considered_valid unknown true false *********************************************************************** hyp = valid unknown true false *********************************************************************** hyp = valid under hyp unknown true false *********************************************************************** hyp = dont_know unknown true false *********************************************************************** hyp = invalid unknown true false *********************************************************************** hyp = invalid under hyp unknown true false *********************************************************************** hyp = invalid but dead unknown true false *********************************************************************** hyp = valid but dead unknown true false *********************************************************************** hyp = unknown but dead unknown true false *********************************************************************** hyp = inconsistent unknown true false ***********************************************************************
Modified by TrustInSoft open Cil_types let emitter = Emitter.create "Test" [ Emitter.Property_status ] ~correctness:[] ~tuning:[] let emitter2 = Emitter.create "Test2" [ Emitter.Property_status ] ~correctness:[] ~tuning:[] let set_status ?(emitter=emitter) p hyps s = Kernel.feedback "SETTING STATUS OF %a TO %a" Property.pretty p Property_status.Emitted_status.pretty s; Property_status.emit emitter p ~hyps s let print_status = Dynamic.get ~plugin:"Report" "print" (Datatype.func Datatype.unit Datatype.unit) let clear () = Kernel.feedback "CLEARING"; Project.clear ~selection:(State_selection.with_dependencies Property_status.self) () let main () = Ast.compute (); print_status (); let main, _, _, h, g = let l = Annotations.fold_all_code_annot (fun stmt _ ca acc -> let kf = Kernel_function.find_englobing_kf stmt in let ps = Property.ip_of_code_annot kf stmt ca in match ps with | [ p ] -> p :: acc | _ -> assert false) [] in match l with | [ p1; p2; p3; p4; p5 ] -> p1, p2, p3, p4, p5 | _ -> assert false in let ensures = let kf = Globals.Functions.find_by_name "f" in let spec = Annotations.funspec kf in Property.ip_post_cond_of_spec kf Kglobal ~active:[] spec in set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status h [ ] Property_status.False_and_reachable; print_status (); clear (); set_status h ensures Property_status.Dont_know; print_status (); set_status h ensures Property_status.True; print_status (); clear (); set_status h [] Property_status.False_and_reachable; print_status (); clear (); set_status main [] Property_status.True; set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status main [] Property_status.True; set_status h [ ] Property_status.False_and_reachable; print_status (); clear (); set_status g [] Property_status.Dont_know; set_status main [ g ] Property_status.True; set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status g [] Property_status.Dont_know; set_status main [ g ] Property_status.True; set_status h [ ] Property_status.False_and_reachable; print_status (); clear (); set_status main [] Property_status.Dont_know; set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status main [] Property_status.Dont_know; set_status h [ ] Property_status.False_and_reachable; print_status (); clear (); set_status main [] Property_status.False_and_reachable; set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status main [] Property_status.False_and_reachable; set_status h [ ] Property_status.False_and_reachable; print_status (); clear (); set_status g [] Property_status.Dont_know; set_status main [ ] Property_status.False_and_reachable; set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status g [] Property_status.Dont_know; set_status main [ ] Property_status.False_and_reachable; set_status h [ ] Property_status.False_and_reachable; print_status (); clear (); set_status g [] Property_status.False_and_reachable; set_status main [ ] Property_status.False_and_reachable; set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status g [] Property_status.False_and_reachable; set_status main [ ] Property_status.False_and_reachable; set_status h [ ] Property_status.False_and_reachable; print_status (); clear (); set_status g [] Property_status.False_and_reachable; set_status main [ g ] Property_status.True; set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status g [] Property_status.False_and_reachable; set_status main [ g ] Property_status.True; set_status h [ ] Property_status.False_and_reachable; print_status (); clear (); set_status g [] Property_status.False_and_reachable; set_status main [ g ] Property_status.Dont_know; set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status g [] Property_status.False_and_reachable; set_status main [ g ] Property_status.Dont_know; set_status h [ ] Property_status.False_and_reachable; print_status (); clear (); set_status main [] Property_status.True; set_status ~emitter:emitter2 main [] Property_status.False_and_reachable; set_status h [ main ] Property_status.Dont_know; print_status (); set_status h [ main ] Property_status.True; print_status (); clear (); set_status main [] Property_status.True; set_status ~emitter:emitter2 main [] Property_status.False_and_reachable; set_status h [ ] Property_status.False_and_reachable; print_status (); () let () = Db.Main.extend main
e8a9403b043b40c93e1ac6445b0890778ac4aedaf1da6cfad111f8fbf83b25e7
chaw/r7rs-libs
64.body.scm
SRFI 67 : Compare Procedures ;;; $ Id$ ;;; Extensively modified for R6RS , with substantial cleanup for R7RS . Copyright ( c ) 2005 , 2006 Per Bothner ;; ;; 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. (define-record-type test-runner (%test-runner-alloc) test-runner? Cumulate count of all tests that have passed and were expected to . (pass-count test-runner-pass-count test-runner-pass-count!) (fail-count test-runner-fail-count test-runner-fail-count!) (xpass-count test-runner-xpass-count test-runner-xpass-count!) (xfail-count test-runner-xfail-count test-runner-xfail-count!) (skip-count test-runner-skip-count test-runner-skip-count!) (skip-list %test-runner-skip-list %test-runner-skip-list!) (fail-list %test-runner-fail-list %test-runner-fail-list!) ;; Normally #t, except when in a test-apply. (run-list %test-runner-run-list %test-runner-run-list!) (skip-save %test-runner-skip-save %test-runner-skip-save!) (fail-save %test-runner-fail-save %test-runner-fail-save!) (group-stack test-runner-group-stack test-runner-group-stack!) (on-test-begin test-runner-on-test-begin test-runner-on-test-begin!) (on-test-end test-runner-on-test-end test-runner-on-test-end!) ;; Call-back when entering a group. Takes (runner suite-name count). (on-group-begin test-runner-on-group-begin test-runner-on-group-begin!) ;; Call-back when leaving a group. (on-group-end test-runner-on-group-end test-runner-on-group-end!) ;; Call-back when leaving the outermost group. (on-final test-runner-on-final test-runner-on-final!) ;; Call-back when expected number of tests was wrong. (on-bad-count test-runner-on-bad-count test-runner-on-bad-count!) ;; Call-back when name in test=end doesn't match test-begin. (on-bad-end-name test-runner-on-bad-end-name test-runner-on-bad-end-name!) Cumulate count of all tests that have been done . (total-count %test-runner-total-count %test-runner-total-count!) Stack ( list ) of ( count - at - start . expected - count ): (count-list %test-runner-count-list %test-runner-count-list!) (result-alist test-result-alist test-result-alist!) Field can be used by test - runner for any purpose . ;; test-runner-simple uses it for a log file. (aux-value test-runner-aux-value test-runner-aux-value!)) (define (test-runner-reset runner) (test-result-alist! runner '()) (test-runner-pass-count! runner 0) (test-runner-fail-count! runner 0) (test-runner-xpass-count! runner 0) (test-runner-xfail-count! runner 0) (test-runner-skip-count! runner 0) (%test-runner-total-count! runner 0) (%test-runner-count-list! runner '()) (%test-runner-run-list! runner #t) (%test-runner-skip-list! runner '()) (%test-runner-fail-list! runner '()) (%test-runner-skip-save! runner '()) (%test-runner-fail-save! runner '()) (test-runner-group-stack! runner '())) (define (test-runner-group-path runner) (reverse (test-runner-group-stack runner))) (define (%test-null-callback runner) #f) (define (test-runner-null) (let ((runner (%test-runner-alloc))) (test-runner-reset runner) (test-runner-on-group-begin! runner (lambda (runner name count) #f)) (test-runner-on-group-end! runner %test-null-callback) (test-runner-on-final! runner %test-null-callback) (test-runner-on-test-begin! runner %test-null-callback) (test-runner-on-test-end! runner %test-null-callback) (test-runner-on-bad-count! runner (lambda (runner count expected) #f)) (test-runner-on-bad-end-name! runner (lambda (runner begin end) #f)) runner)) Not part of the specification . FIXME ;; Controls whether a log file is generated. (define test-log-to-file #t) (define (test-runner-simple) (let ((runner (%test-runner-alloc))) (test-runner-reset runner) (test-runner-on-group-begin! runner test-on-group-begin-simple) (test-runner-on-group-end! runner test-on-group-end-simple) (test-runner-on-final! runner test-on-final-simple) (test-runner-on-test-begin! runner test-on-test-begin-simple) (test-runner-on-test-end! runner test-on-test-end-simple) (test-runner-on-bad-count! runner test-on-bad-count-simple) (test-runner-on-bad-end-name! runner test-on-bad-end-name-simple) runner)) (cond-expand ((or srfi-39 r7rs) (define test-runner-current (make-parameter #f)) (define test-runner-factory (make-parameter test-runner-simple))) (else (define %test-runner-current #f) (define-syntax test-runner-current (syntax-rules () ((test-runner-current) %test-runner-current) ((test-runner-current runner) (set! %test-runner-current runner)))) (define %test-runner-factory test-runner-simple) (define-syntax test-runner-factory (syntax-rules () ((test-runner-factory) %test-runner-factory) ((test-runner-factory runner) (set! %test-runner-factory runner)))))) ;; A safer wrapper to test-runner-current. (define (test-runner-get) (let ((r (test-runner-current))) (if (not r) (error "test-runner not initialized - test-begin missing?")) r)) (define (%test-specifier-matches spec runner) (spec runner)) (define (test-runner-create) ((test-runner-factory))) (define (%test-any-specifier-matches list runner) (let ((result #f)) (let loop ((l list)) (cond ((null? l) result) (else (if (%test-specifier-matches (car l) runner) (set! result #t)) (loop (cdr l))))))) ;; Returns #f, #t, or 'xfail. (define (%test-should-execute runner) (let ((run (%test-runner-run-list runner))) (cond ((or (not (or (eqv? run #t) (%test-any-specifier-matches run runner))) (%test-any-specifier-matches (%test-runner-skip-list runner) runner)) (test-result-set! runner 'result-kind 'skip) #f) ((%test-any-specifier-matches (%test-runner-fail-list runner) runner) (test-result-set! runner 'result-kind 'xfail) 'xfail) (else #t)))) (define (%test-begin suite-name count) (if (not (test-runner-current)) (test-runner-current (test-runner-create))) (let ((runner (test-runner-current))) ((test-runner-on-group-begin runner) runner suite-name count) (%test-runner-skip-save! runner (cons (%test-runner-skip-list runner) (%test-runner-skip-save runner))) (%test-runner-fail-save! runner (cons (%test-runner-fail-list runner) (%test-runner-fail-save runner))) (%test-runner-count-list! runner (cons (cons (%test-runner-total-count runner) count) (%test-runner-count-list runner))) (test-runner-group-stack! runner (cons suite-name (test-runner-group-stack runner))))) (cond-expand (kawa Kawa has test - begin built in , implemented as : ;; (begin ( cond - expand ( srfi-64 # ! void ) ( else ( require ' srfi-64 ) ) ) ;; (%test-begin suite-name [count])) ;; This puts test-begin but only test-begin in the default environment., ;; which makes normal test suites loadable without non-portable commands. ) (else (define-syntax test-begin (syntax-rules () ((test-begin suite-name) (%test-begin suite-name #f)) ((test-begin suite-name count) (%test-begin suite-name count)))))) (define (test-on-group-begin-simple runner suite-name count) (if (null? (test-runner-group-stack runner)) (begin (display "%%%% Starting test ") (display suite-name) (if test-log-to-file (let* ((log-file-name (if (string? test-log-to-file) test-log-to-file (string-append suite-name ".log"))) (log-file (open-output-file log-file-name))) (display "%%%% Starting test " log-file) (display suite-name log-file) (newline log-file) (test-runner-aux-value! runner log-file) (display " (Writing full log to \"") (display log-file-name) (display "\")"))) (newline))) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (display "Group begin: " log) (display suite-name log) (newline log)))) #f) (define (test-on-group-end-simple runner) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (display "Group end: " log) (display (car (test-runner-group-stack runner)) log) (newline log)))) #f) (define (%test-on-bad-count-write runner count expected-count port) (display "*** Total number of tests was " port) (display count port) (display " but should be " port) (display expected-count port) (display ". ***" port) (newline port) (display "*** Discrepancy indicates testsuite error or exceptions. ***" port) (newline port)) (define (test-on-bad-count-simple runner count expected-count) (%test-on-bad-count-write runner count expected-count (current-output-port)) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (%test-on-bad-count-write runner count expected-count log)))) (define (test-on-bad-end-name-simple runner begin-name end-name) (let ((msg (string-append (%test-format-line runner) "test-end " begin-name " does not match test-begin " end-name))) (error msg))) (define (%test-final-report1 value label port) (if (> value 0) (begin (display label port) (display value port) (newline port)))) (define (%test-final-report-simple runner port) (%test-final-report1 (test-runner-pass-count runner) "# of expected passes " port) (%test-final-report1 (test-runner-xfail-count runner) "# of expected failures " port) (%test-final-report1 (test-runner-xpass-count runner) "# of unexpected successes " port) (%test-final-report1 (test-runner-fail-count runner) "# of unexpected failures " port) (%test-final-report1 (test-runner-skip-count runner) "# of skipped tests " port)) (define (test-on-final-simple runner) (%test-final-report-simple runner (current-output-port)) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (%test-final-report-simple runner log) (display "%%%% Closing log file\n") (close-output-port log))))) (define (%test-format-line runner) (let* ((line-info (test-result-alist runner)) (source-file (assq 'source-file line-info)) (source-line (assq 'source-line line-info)) (file (if source-file (cdr source-file) ""))) (if source-line (string-append file ":" (number->string (cdr source-line)) ": ") ""))) (define (%test-end suite-name line-info) (let* ((r (test-runner-get)) (groups (test-runner-group-stack r)) (line (%test-format-line r))) (test-result-alist! r line-info) (if (null? groups) (let ((msg (string-append line "test-end not in a group"))) (error msg))) (if (and suite-name (not (equal? suite-name (car groups)))) ((test-runner-on-bad-end-name r) r suite-name (car groups))) (let* ((count-list (%test-runner-count-list r)) (expected-count (cdar count-list)) (saved-count (caar count-list)) (group-count (- (%test-runner-total-count r) saved-count))) (if (and expected-count (not (= expected-count group-count))) ((test-runner-on-bad-count r) r group-count expected-count)) ((test-runner-on-group-end r) r) (test-runner-group-stack! r (cdr (test-runner-group-stack r))) (%test-runner-skip-list! r (car (%test-runner-skip-save r))) (%test-runner-skip-save! r (cdr (%test-runner-skip-save r))) (%test-runner-fail-list! r (car (%test-runner-fail-save r))) (%test-runner-fail-save! r (cdr (%test-runner-fail-save r))) (%test-runner-count-list! r (cdr count-list)) (if (null? (test-runner-group-stack r)) ((test-runner-on-final r) r))))) (define-syntax test-group (syntax-rules () ((test-group suite-name . body) (let ((r (test-runner-current))) ;; Ideally should also set line-number, if available. (test-result-alist! r (list (cons 'test-name suite-name))) (if (%test-should-execute r) (dynamic-wind (lambda () (test-begin suite-name)) (lambda () . body) (lambda () (test-end suite-name)))))))) (define-syntax test-group-with-cleanup (syntax-rules () ((test-group-with-cleanup suite-name form cleanup-form) (test-group suite-name (dynamic-wind (lambda () #f) (lambda () form) (lambda () cleanup-form)))) ((test-group-with-cleanup suite-name cleanup-form) (test-group-with-cleanup suite-name #f cleanup-form)) ((test-group-with-cleanup suite-name form1 form2 form3 . rest) (test-group-with-cleanup suite-name (begin form1 form2) form3 . rest)))) (define (test-on-test-begin-simple runner) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (let* ((results (test-result-alist runner)) (source-file (assq 'source-file results)) (source-line (assq 'source-line results)) (source-form (assq 'source-form results)) (test-name (assq 'test-name results))) (display "Test begin:" log) (newline log) (if test-name (%test-write-result1 test-name log)) (if source-file (%test-write-result1 source-file log)) (if source-line (%test-write-result1 source-line log)) (if source-file (%test-write-result1 source-form log)))))) (define-syntax test-result-ref (syntax-rules () ((test-result-ref runner pname) (test-result-ref runner pname #f)) ((test-result-ref runner pname default) (let ((p (assq pname (test-result-alist runner)))) (if p (cdr p) default))))) (define (test-on-test-end-simple runner) (let ((log (test-runner-aux-value runner)) (kind (test-result-ref runner 'result-kind))) (if (memq kind '(fail xpass)) (let* ((results (test-result-alist runner)) (source-file (assq 'source-file results)) (source-line (assq 'source-line results)) (test-name (assq 'test-name results))) (if (or source-file source-line) (begin (if source-file (display (cdr source-file))) (display ":") (if source-line (display (cdr source-line))) (display ": "))) (display (if (eq? kind 'xpass) "XPASS" "FAIL")) (if test-name (begin (display " ") (display (cdr test-name)))) (newline))) (if (output-port? log) (begin (display "Test end:" log) (newline log) (let loop ((list (test-result-alist runner))) (if (pair? list) (let ((pair (car list))) ;; Write out properties not written out by on-test-begin. (if (not (memq (car pair) '(test-name source-file source-line source-form))) (%test-write-result1 pair log)) (loop (cdr list))))))))) (define (%test-write-result1 pair port) (display " " port) (display (car pair) port) (display ": " port) (write (cdr pair) port) (newline port)) (define (test-result-set! runner pname value) (let* ((alist (test-result-alist runner)) (p (assq pname alist))) (if p (set-cdr! p value) (test-result-alist! runner (cons (cons pname value) alist))))) (define (test-result-clear runner) (test-result-alist! runner '())) (define (test-result-remove runner pname) (let* ((alist (test-result-alist runner)) (p (assq pname alist))) (if p (test-result-alist! runner (let loop ((r alist)) (if (eq? r p) (cdr r) (cons (car r) (loop (cdr r))))))))) (define (test-result-kind . rest) (let ((runner (if (pair? rest) (car rest) (test-runner-current)))) (test-result-ref runner 'result-kind))) (define (test-passed? . rest) (let ((runner (if (pair? rest) (car rest) (test-runner-get)))) (memq (test-result-ref runner 'result-kind) '(pass xpass)))) (define (%test-report-result) (let* ((r (test-runner-get)) (result-kind (test-result-kind r))) (case result-kind ((pass) (test-runner-pass-count! r (+ 1 (test-runner-pass-count r)))) ((fail) (test-runner-fail-count! r (+ 1 (test-runner-fail-count r)))) ((xpass) (test-runner-xpass-count! r (+ 1 (test-runner-xpass-count r)))) ((xfail) (test-runner-xfail-count! r (+ 1 (test-runner-xfail-count r)))) (else (test-runner-skip-count! r (+ 1 (test-runner-skip-count r))))) (%test-runner-total-count! r (+ 1 (%test-runner-total-count r))) ((test-runner-on-test-end r) r))) Hack for Larceny 's R5RS mode , in which guard catches exceptions ;;; raised by calling the raise procedure but does not catch exceptions ;;; raised by most standard procedures. ;;; FIXME : Larceny 's R6RS and R7RS runtimes can be and usually are compiled in R5RS execution mode , which is why the exact - closed feature appears below . Larceny 's implementation of SRFI 0 ;;; does not recognize exact-closed, so it will be recognized only if cond - expand is in effect , which is what we want here . (cond-expand ((or r6rs r7rs (not larceny) (and larceny exact-closed)) (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (guard (err (else #f)) test-expression))))) (larceny (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (call-without-errors (lambda () test-expression) #f)))))) (define (%test-on-test-begin r) (%test-should-execute r) ((test-runner-on-test-begin r) r) (not (eq? 'skip (test-result-ref r 'result-kind)))) (define (%test-on-test-end r result) (test-result-set! r 'result-kind (if (eq? (test-result-ref r 'result-kind) 'xfail) (if result 'xpass 'xfail) (if result 'pass 'fail)))) (define (test-runner-test-name runner) (test-result-ref runner 'test-name "")) (define-syntax %test-comp2body (syntax-rules () ((%test-comp2body r comp expected expr) (let () (if (%test-on-test-begin r) (let ((exp expected)) (test-result-set! r 'expected-value exp) (let ((res (%test-evaluate-with-catch expr))) (test-result-set! r 'actual-value res) (%test-on-test-end r (comp exp res))))) (%test-report-result))))) (define (%test-approximate= error) (lambda (value expected) (let ((rval (real-part value)) (ival (imag-part value)) (rexp (real-part expected)) (iexp (imag-part expected))) (and (>= rval (- rexp error)) (>= ival (- iexp error)) (<= rval (+ rexp error)) (<= ival (+ iexp error)))))) (define-syntax %test-comp1body (syntax-rules () ((%test-comp1body r expr) (let () (if (%test-on-test-begin r) (let () (let ((res (%test-evaluate-with-catch expr))) (test-result-set! r 'actual-value res) (%test-on-test-end r res)))) (%test-report-result))))) (define-syntax test-end (syntax-rules () ((test-end) (%test-end #f '())) ((test-end suite-name) (%test-end suite-name '())))) (define-syntax test-assert (syntax-rules () ((test-assert tname test-expression) (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r '((test-name . tname))) (%test-comp1body r test-expression))) ((test-assert test-expression) (let* ((r (test-runner-get))) (test-result-alist! r '()) (%test-comp1body r test-expression))))) (define-syntax %test-comp2 (syntax-rules () ((%test-comp2 comp tname expected expr) (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (list (cons 'test-name tname))) (%test-comp2body r comp expected expr))) ((%test-comp2 comp expected expr) (let* ((r (test-runner-get))) (test-result-alist! r '()) (%test-comp2body r comp expected expr))))) (define-syntax test-equal (syntax-rules () ((test-equal . rest) (%test-comp2 equal? . rest)))) (define-syntax test-eqv (syntax-rules () ((test-eqv . rest) (%test-comp2 eqv? . rest)))) (define-syntax test-eq (syntax-rules () ((test-eq . rest) (%test-comp2 eq? . rest)))) (define-syntax test-approximate (syntax-rules () ((test-approximate tname expected expr error) (%test-comp2 (%test-approximate= error) tname expected expr)) ((test-approximate expected expr error) (%test-comp2 (%test-approximate= error) expected expr)))) Hack for Larceny 's R5RS mode , in which guard catches exceptions ;;; raised by calling the raise procedure but does not catch exceptions ;;; raised by most standard procedures. ;;; ;;; FIXME: See earlier note concerning exact-closed. (cond-expand ((or r6rs r7rs (not larceny) (and larceny exact-closed)) (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (guard (ex (else #t)) expr #f)))))) (larceny (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (call-without-errors (lambda () expr #f) #t))))))) (define-syntax test-error (syntax-rules () ((test-error name etype expr) (let ((r (test-runner-get))) (test-result-alist! r `((test-name . ,name))) (%test-error r etype expr))) ((test-error etype expr) (let ((r (test-runner-get))) (test-result-alist! r '()) (%test-error r etype expr))) ((test-error expr) (let ((r (test-runner-get))) (test-result-alist! r '()) (%test-error r #t expr))))) In R5RS , macros must be defined before they 're used . (define-syntax test-with-runner (syntax-rules () ((test-with-runner runner form ...) (let ((saved-runner (test-runner-current))) (dynamic-wind (lambda () (test-runner-current runner)) (lambda () form ...) (lambda () (test-runner-current saved-runner))))))) (define (test-apply first . rest) (if (test-runner? first) (test-with-runner first (apply test-apply rest)) (let ((r (test-runner-current))) (if r (let ((run-list (%test-runner-run-list r))) (cond ((null? rest) (%test-runner-run-list! r (reverse run-list)) (first)) ;; actually apply procedure thunk (else (%test-runner-run-list! r (if (eq? run-list #t) (list first) (cons first run-list))) (apply test-apply rest) (%test-runner-run-list! r run-list)))) (let ((r (test-runner-create))) (test-with-runner r (apply test-apply first rest)) ((test-runner-on-final r) r)))))) ;;; Predicates (define (%test-match-nth n count) (let ((i 0)) (lambda (runner) (set! i (+ i 1)) (and (>= i n) (< i (+ n count)))))) (define-syntax test-match-nth (syntax-rules () ((test-match-nth n) (test-match-nth n 1)) ((test-match-nth n count) (%test-match-nth n count)))) (define (%test-match-all . pred-list) (lambda (runner) (let ((result #t)) (let loop ((l pred-list)) (if (null? l) result (begin (if (not ((car l) runner)) (set! result #f)) (loop (cdr l)))))))) (define-syntax test-match-all (syntax-rules () ((test-match-all pred ...) (%test-match-all (%test-as-specifier pred) ...)))) (define (%test-match-any . pred-list) (lambda (runner) (let ((result #f)) (let loop ((l pred-list)) (if (null? l) result (begin (if ((car l) runner) (set! result #t)) (loop (cdr l)))))))) (define-syntax test-match-any (syntax-rules () ((test-match-any pred ...) (%test-match-any (%test-as-specifier pred) ...)))) Coerce to a predicate function : (define (%test-as-specifier specifier) (cond ((procedure? specifier) specifier) ((integer? specifier) (test-match-nth 1 specifier)) ((string? specifier) (test-match-name specifier)) (else (error "not a valid test specifier")))) (define-syntax test-skip (syntax-rules () ((test-skip pred ...) (let ((runner (test-runner-get))) (%test-runner-skip-list! runner (cons (test-match-all (%test-as-specifier pred) ...) (%test-runner-skip-list runner))))))) (define-syntax test-expect-fail (syntax-rules () ((test-expect-fail pred ...) (let ((runner (test-runner-get))) (%test-runner-fail-list! runner (cons (test-match-all (%test-as-specifier pred) ...) (%test-runner-fail-list runner))))))) (define (test-match-name name) (lambda (runner) (equal? name (test-runner-test-name runner)))) (define (test-read-eval-string string) (let* ((port (open-input-string string)) (form (read port))) (if (eof-object? (read-char port)) (eval form (environment '(rnrs))) (error "(not at eof)"))))
null
https://raw.githubusercontent.com/chaw/r7rs-libs/b8b625c36b040ff3d4b723e4346629a8a0e8d6c2/srfis/gauche/srfi/64.body.scm
scheme
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Normally #t, except when in a test-apply. Call-back when entering a group. Takes (runner suite-name count). Call-back when leaving a group. Call-back when leaving the outermost group. Call-back when expected number of tests was wrong. Call-back when name in test=end doesn't match test-begin. test-runner-simple uses it for a log file. Controls whether a log file is generated. A safer wrapper to test-runner-current. Returns #f, #t, or 'xfail. (begin (%test-begin suite-name [count])) This puts test-begin but only test-begin in the default environment., which makes normal test suites loadable without non-portable commands. Ideally should also set line-number, if available. Write out properties not written out by on-test-begin. raised by calling the raise procedure but does not catch exceptions raised by most standard procedures. does not recognize exact-closed, so it will be recognized only raised by calling the raise procedure but does not catch exceptions raised by most standard procedures. FIXME: See earlier note concerning exact-closed. actually apply procedure thunk Predicates
SRFI 67 : Compare Procedures $ Id$ Extensively modified for R6RS , with substantial cleanup for R7RS . Copyright ( c ) 2005 , 2006 Per Bothner files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN (define-record-type test-runner (%test-runner-alloc) test-runner? Cumulate count of all tests that have passed and were expected to . (pass-count test-runner-pass-count test-runner-pass-count!) (fail-count test-runner-fail-count test-runner-fail-count!) (xpass-count test-runner-xpass-count test-runner-xpass-count!) (xfail-count test-runner-xfail-count test-runner-xfail-count!) (skip-count test-runner-skip-count test-runner-skip-count!) (skip-list %test-runner-skip-list %test-runner-skip-list!) (fail-list %test-runner-fail-list %test-runner-fail-list!) (run-list %test-runner-run-list %test-runner-run-list!) (skip-save %test-runner-skip-save %test-runner-skip-save!) (fail-save %test-runner-fail-save %test-runner-fail-save!) (group-stack test-runner-group-stack test-runner-group-stack!) (on-test-begin test-runner-on-test-begin test-runner-on-test-begin!) (on-test-end test-runner-on-test-end test-runner-on-test-end!) (on-group-begin test-runner-on-group-begin test-runner-on-group-begin!) (on-group-end test-runner-on-group-end test-runner-on-group-end!) (on-final test-runner-on-final test-runner-on-final!) (on-bad-count test-runner-on-bad-count test-runner-on-bad-count!) (on-bad-end-name test-runner-on-bad-end-name test-runner-on-bad-end-name!) Cumulate count of all tests that have been done . (total-count %test-runner-total-count %test-runner-total-count!) Stack ( list ) of ( count - at - start . expected - count ): (count-list %test-runner-count-list %test-runner-count-list!) (result-alist test-result-alist test-result-alist!) Field can be used by test - runner for any purpose . (aux-value test-runner-aux-value test-runner-aux-value!)) (define (test-runner-reset runner) (test-result-alist! runner '()) (test-runner-pass-count! runner 0) (test-runner-fail-count! runner 0) (test-runner-xpass-count! runner 0) (test-runner-xfail-count! runner 0) (test-runner-skip-count! runner 0) (%test-runner-total-count! runner 0) (%test-runner-count-list! runner '()) (%test-runner-run-list! runner #t) (%test-runner-skip-list! runner '()) (%test-runner-fail-list! runner '()) (%test-runner-skip-save! runner '()) (%test-runner-fail-save! runner '()) (test-runner-group-stack! runner '())) (define (test-runner-group-path runner) (reverse (test-runner-group-stack runner))) (define (%test-null-callback runner) #f) (define (test-runner-null) (let ((runner (%test-runner-alloc))) (test-runner-reset runner) (test-runner-on-group-begin! runner (lambda (runner name count) #f)) (test-runner-on-group-end! runner %test-null-callback) (test-runner-on-final! runner %test-null-callback) (test-runner-on-test-begin! runner %test-null-callback) (test-runner-on-test-end! runner %test-null-callback) (test-runner-on-bad-count! runner (lambda (runner count expected) #f)) (test-runner-on-bad-end-name! runner (lambda (runner begin end) #f)) runner)) Not part of the specification . FIXME (define test-log-to-file #t) (define (test-runner-simple) (let ((runner (%test-runner-alloc))) (test-runner-reset runner) (test-runner-on-group-begin! runner test-on-group-begin-simple) (test-runner-on-group-end! runner test-on-group-end-simple) (test-runner-on-final! runner test-on-final-simple) (test-runner-on-test-begin! runner test-on-test-begin-simple) (test-runner-on-test-end! runner test-on-test-end-simple) (test-runner-on-bad-count! runner test-on-bad-count-simple) (test-runner-on-bad-end-name! runner test-on-bad-end-name-simple) runner)) (cond-expand ((or srfi-39 r7rs) (define test-runner-current (make-parameter #f)) (define test-runner-factory (make-parameter test-runner-simple))) (else (define %test-runner-current #f) (define-syntax test-runner-current (syntax-rules () ((test-runner-current) %test-runner-current) ((test-runner-current runner) (set! %test-runner-current runner)))) (define %test-runner-factory test-runner-simple) (define-syntax test-runner-factory (syntax-rules () ((test-runner-factory) %test-runner-factory) ((test-runner-factory runner) (set! %test-runner-factory runner)))))) (define (test-runner-get) (let ((r (test-runner-current))) (if (not r) (error "test-runner not initialized - test-begin missing?")) r)) (define (%test-specifier-matches spec runner) (spec runner)) (define (test-runner-create) ((test-runner-factory))) (define (%test-any-specifier-matches list runner) (let ((result #f)) (let loop ((l list)) (cond ((null? l) result) (else (if (%test-specifier-matches (car l) runner) (set! result #t)) (loop (cdr l))))))) (define (%test-should-execute runner) (let ((run (%test-runner-run-list runner))) (cond ((or (not (or (eqv? run #t) (%test-any-specifier-matches run runner))) (%test-any-specifier-matches (%test-runner-skip-list runner) runner)) (test-result-set! runner 'result-kind 'skip) #f) ((%test-any-specifier-matches (%test-runner-fail-list runner) runner) (test-result-set! runner 'result-kind 'xfail) 'xfail) (else #t)))) (define (%test-begin suite-name count) (if (not (test-runner-current)) (test-runner-current (test-runner-create))) (let ((runner (test-runner-current))) ((test-runner-on-group-begin runner) runner suite-name count) (%test-runner-skip-save! runner (cons (%test-runner-skip-list runner) (%test-runner-skip-save runner))) (%test-runner-fail-save! runner (cons (%test-runner-fail-list runner) (%test-runner-fail-save runner))) (%test-runner-count-list! runner (cons (cons (%test-runner-total-count runner) count) (%test-runner-count-list runner))) (test-runner-group-stack! runner (cons suite-name (test-runner-group-stack runner))))) (cond-expand (kawa Kawa has test - begin built in , implemented as : ( cond - expand ( srfi-64 # ! void ) ( else ( require ' srfi-64 ) ) ) ) (else (define-syntax test-begin (syntax-rules () ((test-begin suite-name) (%test-begin suite-name #f)) ((test-begin suite-name count) (%test-begin suite-name count)))))) (define (test-on-group-begin-simple runner suite-name count) (if (null? (test-runner-group-stack runner)) (begin (display "%%%% Starting test ") (display suite-name) (if test-log-to-file (let* ((log-file-name (if (string? test-log-to-file) test-log-to-file (string-append suite-name ".log"))) (log-file (open-output-file log-file-name))) (display "%%%% Starting test " log-file) (display suite-name log-file) (newline log-file) (test-runner-aux-value! runner log-file) (display " (Writing full log to \"") (display log-file-name) (display "\")"))) (newline))) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (display "Group begin: " log) (display suite-name log) (newline log)))) #f) (define (test-on-group-end-simple runner) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (display "Group end: " log) (display (car (test-runner-group-stack runner)) log) (newline log)))) #f) (define (%test-on-bad-count-write runner count expected-count port) (display "*** Total number of tests was " port) (display count port) (display " but should be " port) (display expected-count port) (display ". ***" port) (newline port) (display "*** Discrepancy indicates testsuite error or exceptions. ***" port) (newline port)) (define (test-on-bad-count-simple runner count expected-count) (%test-on-bad-count-write runner count expected-count (current-output-port)) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (%test-on-bad-count-write runner count expected-count log)))) (define (test-on-bad-end-name-simple runner begin-name end-name) (let ((msg (string-append (%test-format-line runner) "test-end " begin-name " does not match test-begin " end-name))) (error msg))) (define (%test-final-report1 value label port) (if (> value 0) (begin (display label port) (display value port) (newline port)))) (define (%test-final-report-simple runner port) (%test-final-report1 (test-runner-pass-count runner) "# of expected passes " port) (%test-final-report1 (test-runner-xfail-count runner) "# of expected failures " port) (%test-final-report1 (test-runner-xpass-count runner) "# of unexpected successes " port) (%test-final-report1 (test-runner-fail-count runner) "# of unexpected failures " port) (%test-final-report1 (test-runner-skip-count runner) "# of skipped tests " port)) (define (test-on-final-simple runner) (%test-final-report-simple runner (current-output-port)) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (%test-final-report-simple runner log) (display "%%%% Closing log file\n") (close-output-port log))))) (define (%test-format-line runner) (let* ((line-info (test-result-alist runner)) (source-file (assq 'source-file line-info)) (source-line (assq 'source-line line-info)) (file (if source-file (cdr source-file) ""))) (if source-line (string-append file ":" (number->string (cdr source-line)) ": ") ""))) (define (%test-end suite-name line-info) (let* ((r (test-runner-get)) (groups (test-runner-group-stack r)) (line (%test-format-line r))) (test-result-alist! r line-info) (if (null? groups) (let ((msg (string-append line "test-end not in a group"))) (error msg))) (if (and suite-name (not (equal? suite-name (car groups)))) ((test-runner-on-bad-end-name r) r suite-name (car groups))) (let* ((count-list (%test-runner-count-list r)) (expected-count (cdar count-list)) (saved-count (caar count-list)) (group-count (- (%test-runner-total-count r) saved-count))) (if (and expected-count (not (= expected-count group-count))) ((test-runner-on-bad-count r) r group-count expected-count)) ((test-runner-on-group-end r) r) (test-runner-group-stack! r (cdr (test-runner-group-stack r))) (%test-runner-skip-list! r (car (%test-runner-skip-save r))) (%test-runner-skip-save! r (cdr (%test-runner-skip-save r))) (%test-runner-fail-list! r (car (%test-runner-fail-save r))) (%test-runner-fail-save! r (cdr (%test-runner-fail-save r))) (%test-runner-count-list! r (cdr count-list)) (if (null? (test-runner-group-stack r)) ((test-runner-on-final r) r))))) (define-syntax test-group (syntax-rules () ((test-group suite-name . body) (let ((r (test-runner-current))) (test-result-alist! r (list (cons 'test-name suite-name))) (if (%test-should-execute r) (dynamic-wind (lambda () (test-begin suite-name)) (lambda () . body) (lambda () (test-end suite-name)))))))) (define-syntax test-group-with-cleanup (syntax-rules () ((test-group-with-cleanup suite-name form cleanup-form) (test-group suite-name (dynamic-wind (lambda () #f) (lambda () form) (lambda () cleanup-form)))) ((test-group-with-cleanup suite-name cleanup-form) (test-group-with-cleanup suite-name #f cleanup-form)) ((test-group-with-cleanup suite-name form1 form2 form3 . rest) (test-group-with-cleanup suite-name (begin form1 form2) form3 . rest)))) (define (test-on-test-begin-simple runner) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (let* ((results (test-result-alist runner)) (source-file (assq 'source-file results)) (source-line (assq 'source-line results)) (source-form (assq 'source-form results)) (test-name (assq 'test-name results))) (display "Test begin:" log) (newline log) (if test-name (%test-write-result1 test-name log)) (if source-file (%test-write-result1 source-file log)) (if source-line (%test-write-result1 source-line log)) (if source-file (%test-write-result1 source-form log)))))) (define-syntax test-result-ref (syntax-rules () ((test-result-ref runner pname) (test-result-ref runner pname #f)) ((test-result-ref runner pname default) (let ((p (assq pname (test-result-alist runner)))) (if p (cdr p) default))))) (define (test-on-test-end-simple runner) (let ((log (test-runner-aux-value runner)) (kind (test-result-ref runner 'result-kind))) (if (memq kind '(fail xpass)) (let* ((results (test-result-alist runner)) (source-file (assq 'source-file results)) (source-line (assq 'source-line results)) (test-name (assq 'test-name results))) (if (or source-file source-line) (begin (if source-file (display (cdr source-file))) (display ":") (if source-line (display (cdr source-line))) (display ": "))) (display (if (eq? kind 'xpass) "XPASS" "FAIL")) (if test-name (begin (display " ") (display (cdr test-name)))) (newline))) (if (output-port? log) (begin (display "Test end:" log) (newline log) (let loop ((list (test-result-alist runner))) (if (pair? list) (let ((pair (car list))) (if (not (memq (car pair) '(test-name source-file source-line source-form))) (%test-write-result1 pair log)) (loop (cdr list))))))))) (define (%test-write-result1 pair port) (display " " port) (display (car pair) port) (display ": " port) (write (cdr pair) port) (newline port)) (define (test-result-set! runner pname value) (let* ((alist (test-result-alist runner)) (p (assq pname alist))) (if p (set-cdr! p value) (test-result-alist! runner (cons (cons pname value) alist))))) (define (test-result-clear runner) (test-result-alist! runner '())) (define (test-result-remove runner pname) (let* ((alist (test-result-alist runner)) (p (assq pname alist))) (if p (test-result-alist! runner (let loop ((r alist)) (if (eq? r p) (cdr r) (cons (car r) (loop (cdr r))))))))) (define (test-result-kind . rest) (let ((runner (if (pair? rest) (car rest) (test-runner-current)))) (test-result-ref runner 'result-kind))) (define (test-passed? . rest) (let ((runner (if (pair? rest) (car rest) (test-runner-get)))) (memq (test-result-ref runner 'result-kind) '(pass xpass)))) (define (%test-report-result) (let* ((r (test-runner-get)) (result-kind (test-result-kind r))) (case result-kind ((pass) (test-runner-pass-count! r (+ 1 (test-runner-pass-count r)))) ((fail) (test-runner-fail-count! r (+ 1 (test-runner-fail-count r)))) ((xpass) (test-runner-xpass-count! r (+ 1 (test-runner-xpass-count r)))) ((xfail) (test-runner-xfail-count! r (+ 1 (test-runner-xfail-count r)))) (else (test-runner-skip-count! r (+ 1 (test-runner-skip-count r))))) (%test-runner-total-count! r (+ 1 (%test-runner-total-count r))) ((test-runner-on-test-end r) r))) Hack for Larceny 's R5RS mode , in which guard catches exceptions FIXME : Larceny 's R6RS and R7RS runtimes can be and usually are compiled in R5RS execution mode , which is why the exact - closed feature appears below . Larceny 's implementation of SRFI 0 if cond - expand is in effect , which is what we want here . (cond-expand ((or r6rs r7rs (not larceny) (and larceny exact-closed)) (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (guard (err (else #f)) test-expression))))) (larceny (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (call-without-errors (lambda () test-expression) #f)))))) (define (%test-on-test-begin r) (%test-should-execute r) ((test-runner-on-test-begin r) r) (not (eq? 'skip (test-result-ref r 'result-kind)))) (define (%test-on-test-end r result) (test-result-set! r 'result-kind (if (eq? (test-result-ref r 'result-kind) 'xfail) (if result 'xpass 'xfail) (if result 'pass 'fail)))) (define (test-runner-test-name runner) (test-result-ref runner 'test-name "")) (define-syntax %test-comp2body (syntax-rules () ((%test-comp2body r comp expected expr) (let () (if (%test-on-test-begin r) (let ((exp expected)) (test-result-set! r 'expected-value exp) (let ((res (%test-evaluate-with-catch expr))) (test-result-set! r 'actual-value res) (%test-on-test-end r (comp exp res))))) (%test-report-result))))) (define (%test-approximate= error) (lambda (value expected) (let ((rval (real-part value)) (ival (imag-part value)) (rexp (real-part expected)) (iexp (imag-part expected))) (and (>= rval (- rexp error)) (>= ival (- iexp error)) (<= rval (+ rexp error)) (<= ival (+ iexp error)))))) (define-syntax %test-comp1body (syntax-rules () ((%test-comp1body r expr) (let () (if (%test-on-test-begin r) (let () (let ((res (%test-evaluate-with-catch expr))) (test-result-set! r 'actual-value res) (%test-on-test-end r res)))) (%test-report-result))))) (define-syntax test-end (syntax-rules () ((test-end) (%test-end #f '())) ((test-end suite-name) (%test-end suite-name '())))) (define-syntax test-assert (syntax-rules () ((test-assert tname test-expression) (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r '((test-name . tname))) (%test-comp1body r test-expression))) ((test-assert test-expression) (let* ((r (test-runner-get))) (test-result-alist! r '()) (%test-comp1body r test-expression))))) (define-syntax %test-comp2 (syntax-rules () ((%test-comp2 comp tname expected expr) (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (list (cons 'test-name tname))) (%test-comp2body r comp expected expr))) ((%test-comp2 comp expected expr) (let* ((r (test-runner-get))) (test-result-alist! r '()) (%test-comp2body r comp expected expr))))) (define-syntax test-equal (syntax-rules () ((test-equal . rest) (%test-comp2 equal? . rest)))) (define-syntax test-eqv (syntax-rules () ((test-eqv . rest) (%test-comp2 eqv? . rest)))) (define-syntax test-eq (syntax-rules () ((test-eq . rest) (%test-comp2 eq? . rest)))) (define-syntax test-approximate (syntax-rules () ((test-approximate tname expected expr error) (%test-comp2 (%test-approximate= error) tname expected expr)) ((test-approximate expected expr error) (%test-comp2 (%test-approximate= error) expected expr)))) Hack for Larceny 's R5RS mode , in which guard catches exceptions (cond-expand ((or r6rs r7rs (not larceny) (and larceny exact-closed)) (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (guard (ex (else #t)) expr #f)))))) (larceny (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (call-without-errors (lambda () expr #f) #t))))))) (define-syntax test-error (syntax-rules () ((test-error name etype expr) (let ((r (test-runner-get))) (test-result-alist! r `((test-name . ,name))) (%test-error r etype expr))) ((test-error etype expr) (let ((r (test-runner-get))) (test-result-alist! r '()) (%test-error r etype expr))) ((test-error expr) (let ((r (test-runner-get))) (test-result-alist! r '()) (%test-error r #t expr))))) In R5RS , macros must be defined before they 're used . (define-syntax test-with-runner (syntax-rules () ((test-with-runner runner form ...) (let ((saved-runner (test-runner-current))) (dynamic-wind (lambda () (test-runner-current runner)) (lambda () form ...) (lambda () (test-runner-current saved-runner))))))) (define (test-apply first . rest) (if (test-runner? first) (test-with-runner first (apply test-apply rest)) (let ((r (test-runner-current))) (if r (let ((run-list (%test-runner-run-list r))) (cond ((null? rest) (%test-runner-run-list! r (reverse run-list)) (else (%test-runner-run-list! r (if (eq? run-list #t) (list first) (cons first run-list))) (apply test-apply rest) (%test-runner-run-list! r run-list)))) (let ((r (test-runner-create))) (test-with-runner r (apply test-apply first rest)) ((test-runner-on-final r) r)))))) (define (%test-match-nth n count) (let ((i 0)) (lambda (runner) (set! i (+ i 1)) (and (>= i n) (< i (+ n count)))))) (define-syntax test-match-nth (syntax-rules () ((test-match-nth n) (test-match-nth n 1)) ((test-match-nth n count) (%test-match-nth n count)))) (define (%test-match-all . pred-list) (lambda (runner) (let ((result #t)) (let loop ((l pred-list)) (if (null? l) result (begin (if (not ((car l) runner)) (set! result #f)) (loop (cdr l)))))))) (define-syntax test-match-all (syntax-rules () ((test-match-all pred ...) (%test-match-all (%test-as-specifier pred) ...)))) (define (%test-match-any . pred-list) (lambda (runner) (let ((result #f)) (let loop ((l pred-list)) (if (null? l) result (begin (if ((car l) runner) (set! result #t)) (loop (cdr l)))))))) (define-syntax test-match-any (syntax-rules () ((test-match-any pred ...) (%test-match-any (%test-as-specifier pred) ...)))) Coerce to a predicate function : (define (%test-as-specifier specifier) (cond ((procedure? specifier) specifier) ((integer? specifier) (test-match-nth 1 specifier)) ((string? specifier) (test-match-name specifier)) (else (error "not a valid test specifier")))) (define-syntax test-skip (syntax-rules () ((test-skip pred ...) (let ((runner (test-runner-get))) (%test-runner-skip-list! runner (cons (test-match-all (%test-as-specifier pred) ...) (%test-runner-skip-list runner))))))) (define-syntax test-expect-fail (syntax-rules () ((test-expect-fail pred ...) (let ((runner (test-runner-get))) (%test-runner-fail-list! runner (cons (test-match-all (%test-as-specifier pred) ...) (%test-runner-fail-list runner))))))) (define (test-match-name name) (lambda (runner) (equal? name (test-runner-test-name runner)))) (define (test-read-eval-string string) (let* ((port (open-input-string string)) (form (read port))) (if (eof-object? (read-char port)) (eval form (environment '(rnrs))) (error "(not at eof)"))))
f6f0d222af2911c6a33b636e4a4b216794da931edcd050396ceaa464e4c76745
ghcjs/jsaddle-dom
HTMLDirectoryElement.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.HTMLDirectoryElement (setCompact, getCompact, HTMLDirectoryElement(..), gTypeHTMLDirectoryElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/HTMLDirectoryElement.compact Mozilla HTMLDirectoryElement.compact documentation > setCompact :: (MonadDOM m) => HTMLDirectoryElement -> Bool -> m () setCompact self val = liftDOM (self ^. jss "compact" (toJSVal val)) | < -US/docs/Web/API/HTMLDirectoryElement.compact Mozilla HTMLDirectoryElement.compact documentation > getCompact :: (MonadDOM m) => HTMLDirectoryElement -> m Bool getCompact self = liftDOM ((self ^. js "compact") >>= valToBool)
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/HTMLDirectoryElement.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.HTMLDirectoryElement (setCompact, getCompact, HTMLDirectoryElement(..), gTypeHTMLDirectoryElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/HTMLDirectoryElement.compact Mozilla HTMLDirectoryElement.compact documentation > setCompact :: (MonadDOM m) => HTMLDirectoryElement -> Bool -> m () setCompact self val = liftDOM (self ^. jss "compact" (toJSVal val)) | < -US/docs/Web/API/HTMLDirectoryElement.compact Mozilla HTMLDirectoryElement.compact documentation > getCompact :: (MonadDOM m) => HTMLDirectoryElement -> m Bool getCompact self = liftDOM ((self ^. js "compact") >>= valToBool)
2d34751cb7a19d9fa07c39595c05c2f0a2a87200ec562cf35a5de7ec40d13157
inhabitedtype/ocaml-aws
rejectTransitGatewayPeeringAttachment.ml
open Types open Aws type input = RejectTransitGatewayPeeringAttachmentRequest.t type output = RejectTransitGatewayPeeringAttachmentResult.t type error = Errors_internal.t let service = "ec2" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2016-11-15" ] ; "Action", [ "RejectTransitGatewayPeeringAttachment" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (RejectTransitGatewayPeeringAttachmentRequest.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Xml.member "RejectTransitGatewayPeeringAttachmentResponse" (snd xml) in try Util.or_error (Util.option_bind resp RejectTransitGatewayPeeringAttachmentResult.parse) (let open Error in BadResponse { body ; message = "Could not find well formed RejectTransitGatewayPeeringAttachmentResult." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing RejectTransitGatewayPeeringAttachmentResult - missing \ field in body or children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/ec2/lib/rejectTransitGatewayPeeringAttachment.ml
ocaml
open Types open Aws type input = RejectTransitGatewayPeeringAttachmentRequest.t type output = RejectTransitGatewayPeeringAttachmentResult.t type error = Errors_internal.t let service = "ec2" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2016-11-15" ] ; "Action", [ "RejectTransitGatewayPeeringAttachment" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (RejectTransitGatewayPeeringAttachmentRequest.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Xml.member "RejectTransitGatewayPeeringAttachmentResponse" (snd xml) in try Util.or_error (Util.option_bind resp RejectTransitGatewayPeeringAttachmentResult.parse) (let open Error in BadResponse { body ; message = "Could not find well formed RejectTransitGatewayPeeringAttachmentResult." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing RejectTransitGatewayPeeringAttachmentResult - missing \ field in body or children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
a552ab37147af5dd22520e2409c1771a599326dcfdd3a301212b9276de04a701
jsinglet/cam
Parser.hs
module Parser where import Lexer import Lang import Debug.Trace import Compile Abstract Syntax = = = = = = = = = = = = = = = --------------- --------------- c-- language --------------- e : : = | ident | e1 e2 -- application | e1 op e2 -- binop | [ e1 , e2 ] -- pair | if e1 then e2 else e3 | let { rec } p = e in e | fun p - > e if a > 3 then fun x - > x + 1 else fun x - > x - 1 7 p : : = | ( ) | ( p1 , p2 ) Abstract Syntax =============== Marie Simulator --------------- Baci Simulation --------------- c-- language Ocaml Simulator --------------- e ::= | ident | e1 e2 -- application | e1 op e2 -- binop | [e1, e2] -- pair | if e1 then e2 else e3 | let {rec} p = e in e | fun p -> e if a > 3 then fun x -> x + 1 else fun x -> x - 1 7 p ::= | () | (p1, p2) -} test1 = expression $ getTokens "1 + 1" test2 = expression $ getTokens "1 + let a = 3 in a" test3 = expression $ getTokens "if 1 == 1 then 2 else 3" test4 = expression $ getTokens "1 + if 1 == 2 then 2 else 3" test5 = expression $ getTokens "fun x -> x + 3 3" test1c = compile $ fst test1 test2c = compile $ fst test2 test3c = compile $ fst test3 test4c = compile $ fst test4 test1e = eval $ fst test1 test2e = eval $ fst test2 test3e = eval $ fst test3 test4e = eval $ fst test4 terms :: [Token] terms = [TokenAdd, TokenMinus, TokenEquals] factors :: [Token] factors = [TokenMultiply, TokenDivide, TokenGt, TokenLt] ops = factors ++ terms getOp :: Token -> M_BINOP getOp t = case t of (TokenAdd) -> M_ADD (TokenMinus) -> M_SUB (TokenMultiply) -> M_MULT (TokenEquals) -> M_EQ (TokenLt) -> M_LT (TokenGt) -> M_GT (TokenDivide) -> M_DIV _ -> error $ "Parser Error: Unknown Operator " ++ (show t) term :: [Token] -> (EXP,[Token]) term (TokenBooleanLiteral b:xs) = (EXP_BOOL b, xs) term (TokenIntegerLiteral i:xs) = (EXP_INT i, xs) term (TokenIdent s:xs) = (EXP_VAR s, xs) term (TokenOpenParen:xs) = let (e, rest) = expression xs in (e, skip rest TokenCloseParen) --term xs = expression xs term t = error $ "Unknown Term: " ++ show t expression :: [Token] -> (EXP, [Token]) -- pairs expression (TokenOpenPair:xs) = let (p1, rest) = expression xs in let rest1 = skip rest TokenComma in let (p2, rest2) = expression rest1 in let rest3 = skip rest2 TokenClosePair in (EXP_PAIR p1 p2, rest3) -- structures expression (TokenFst:xs) = let (e1, rest) = expression xs in (EXP_UNOP M_FST e1, rest) expression (TokenSnd:xs) = let (e1, rest) = expression xs in (EXP_UNOP M_SND e1, rest) expression (TokenIf:xs) = let (e1, rest) = expression xs in let (e2, rest1) = expression (skip rest TokenThen) in let (e3, rest2) = expression (skip rest1 TokenElse) in (EXP_IF e1 e2 e3, rest2) -- lambdas expression (TokenFun:xs) = case (xs) of (TokenIdent i:xs) -> let rest = (skip xs TokenArrow) in let (e1, rest1) = expression rest in (EXP_FUN i e1, rest1) _ -> error $ "Expected a functional parameter (ident) following lambda but found: " ++ (show (head xs)) -- application -- expression (TokenOpenParen:xs) = -- let (e1, rest) = expression xs in let rest1 = skip rest in -- let (e2, rest2) = expression rest1 in ( EXP_APP e1 e2 , rest2 ) expression (TokenLet:xs) = case (xs) of (TokenIdent i:xs) -> let rest = (skip xs TokenAssign) in let (e1, rest1) = expression rest in let rest2 = skip rest1 TokenIn in let (e2, rest3) = expression rest2 in (EXP_LET i e1 e2, rest3) _ -> error $ "Parse Error: Expected Ident following let but found: " ++ (show $ head xs) expression (TokenLetRec:xs) = case (xs) of (TokenIdent i:xs) -> let rest = (skip xs TokenAssign) in let (e1, rest1) = expression rest in let rest2 = skip rest1 TokenIn in let (e2, rest3) = expression rest2 in (EXP_LETREC i e1 e2, rest3) _ -> error $ "Expression Error: Expected Ident following letrec but found: " ++ (show $ head xs) expression xs = let (e1, rest) = term xs in if rest == [] then (e1, rest) else if (head rest) `elem` ops then -- binary expression let (op:rest1) = rest in let operator = getOp op in let (e2, rest2) = expression rest1 in (EXP_BINOP operator e1 e2, rest2) else -- if it's a special token, we are done parsing if (head rest) `elem` [TokenIn,TokenCloseParen, TokenClosePair, TokenThen, TokenElse, TokenComma] then (e1, rest) -- otherwise, we have another expression else let (e2, rest1) = expression rest in (EXP_APP e1 e2, rest1) maybeApply :: (EXP, [Token]) -> (EXP, [Token]) maybeApply (e, t@(x:xs)) = let (e',tokens) = expression t in (EXP_APP e e', tokens) maybeApply (e, []) = (e, []) skip :: [Token] -> Token -> [Token] skip (x:rest) t = if t ==x then rest else error $ "Parse Error: Expected " ++ (show t) ++ " but found " ++ (show x)
null
https://raw.githubusercontent.com/jsinglet/cam/bca0e53fe428baf7b5e489569df2355f77ea3484/src/Parser.hs
haskell
------------- ------------- language ------------- application binop pair ------------- ------------- language ------------- application binop pair term xs = expression xs pairs structures lambdas application expression (TokenOpenParen:xs) = let (e1, rest) = expression xs in let (e2, rest2) = expression rest1 in binary expression if it's a special token, we are done parsing otherwise, we have another expression
module Parser where import Lexer import Lang import Debug.Trace import Compile Abstract Syntax = = = = = = = = = = = = = = = e : : = | ident | if e1 then e2 else e3 | let { rec } p = e in e | fun p - > e if a > 3 then fun x - > x + 1 else fun x - > x - 1 7 p : : = | ( ) | ( p1 , p2 ) Abstract Syntax =============== Marie Simulator Baci Simulation Ocaml Simulator e ::= | ident | if e1 then e2 else e3 | let {rec} p = e in e | fun p -> e if a > 3 then fun x -> x + 1 else fun x -> x - 1 7 p ::= | () | (p1, p2) -} test1 = expression $ getTokens "1 + 1" test2 = expression $ getTokens "1 + let a = 3 in a" test3 = expression $ getTokens "if 1 == 1 then 2 else 3" test4 = expression $ getTokens "1 + if 1 == 2 then 2 else 3" test5 = expression $ getTokens "fun x -> x + 3 3" test1c = compile $ fst test1 test2c = compile $ fst test2 test3c = compile $ fst test3 test4c = compile $ fst test4 test1e = eval $ fst test1 test2e = eval $ fst test2 test3e = eval $ fst test3 test4e = eval $ fst test4 terms :: [Token] terms = [TokenAdd, TokenMinus, TokenEquals] factors :: [Token] factors = [TokenMultiply, TokenDivide, TokenGt, TokenLt] ops = factors ++ terms getOp :: Token -> M_BINOP getOp t = case t of (TokenAdd) -> M_ADD (TokenMinus) -> M_SUB (TokenMultiply) -> M_MULT (TokenEquals) -> M_EQ (TokenLt) -> M_LT (TokenGt) -> M_GT (TokenDivide) -> M_DIV _ -> error $ "Parser Error: Unknown Operator " ++ (show t) term :: [Token] -> (EXP,[Token]) term (TokenBooleanLiteral b:xs) = (EXP_BOOL b, xs) term (TokenIntegerLiteral i:xs) = (EXP_INT i, xs) term (TokenIdent s:xs) = (EXP_VAR s, xs) term (TokenOpenParen:xs) = let (e, rest) = expression xs in (e, skip rest TokenCloseParen) term t = error $ "Unknown Term: " ++ show t expression :: [Token] -> (EXP, [Token]) expression (TokenOpenPair:xs) = let (p1, rest) = expression xs in let rest1 = skip rest TokenComma in let (p2, rest2) = expression rest1 in let rest3 = skip rest2 TokenClosePair in (EXP_PAIR p1 p2, rest3) expression (TokenFst:xs) = let (e1, rest) = expression xs in (EXP_UNOP M_FST e1, rest) expression (TokenSnd:xs) = let (e1, rest) = expression xs in (EXP_UNOP M_SND e1, rest) expression (TokenIf:xs) = let (e1, rest) = expression xs in let (e2, rest1) = expression (skip rest TokenThen) in let (e3, rest2) = expression (skip rest1 TokenElse) in (EXP_IF e1 e2 e3, rest2) expression (TokenFun:xs) = case (xs) of (TokenIdent i:xs) -> let rest = (skip xs TokenArrow) in let (e1, rest1) = expression rest in (EXP_FUN i e1, rest1) _ -> error $ "Expected a functional parameter (ident) following lambda but found: " ++ (show (head xs)) let rest1 = skip rest in ( EXP_APP e1 e2 , rest2 ) expression (TokenLet:xs) = case (xs) of (TokenIdent i:xs) -> let rest = (skip xs TokenAssign) in let (e1, rest1) = expression rest in let rest2 = skip rest1 TokenIn in let (e2, rest3) = expression rest2 in (EXP_LET i e1 e2, rest3) _ -> error $ "Parse Error: Expected Ident following let but found: " ++ (show $ head xs) expression (TokenLetRec:xs) = case (xs) of (TokenIdent i:xs) -> let rest = (skip xs TokenAssign) in let (e1, rest1) = expression rest in let rest2 = skip rest1 TokenIn in let (e2, rest3) = expression rest2 in (EXP_LETREC i e1 e2, rest3) _ -> error $ "Expression Error: Expected Ident following letrec but found: " ++ (show $ head xs) expression xs = let (e1, rest) = term xs in if rest == [] then (e1, rest) else let (op:rest1) = rest in let operator = getOp op in let (e2, rest2) = expression rest1 in (EXP_BINOP operator e1 e2, rest2) else if (head rest) `elem` [TokenIn,TokenCloseParen, TokenClosePair, TokenThen, TokenElse, TokenComma] then (e1, rest) else let (e2, rest1) = expression rest in (EXP_APP e1 e2, rest1) maybeApply :: (EXP, [Token]) -> (EXP, [Token]) maybeApply (e, t@(x:xs)) = let (e',tokens) = expression t in (EXP_APP e e', tokens) maybeApply (e, []) = (e, []) skip :: [Token] -> Token -> [Token] skip (x:rest) t = if t ==x then rest else error $ "Parse Error: Expected " ++ (show t) ++ " but found " ++ (show x)
d74b48c6da37be671104130a2c69a414bc3ba97937fb2e31b1ff4bbb1e02ba14
input-output-hk/plutus-apps
Client.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE GADTs # # LANGUAGE NamedFieldPuns # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module Cardano.Protocol.Socket.Client where import Control.Concurrent import Control.Monad.Catch (Handler (..), SomeException (..)) import Data.Aeson (FromJSON, ToJSON) import Data.Text (Text, pack) import GHC.Generics (Generic) import Cardano.Api (BlockInMode (..), CardanoMode, ChainPoint (..), ChainTip (..), ConsensusModeParams (..), LocalChainSyncClient (..), LocalNodeClientProtocols (..), LocalNodeClientProtocolsInMode, LocalNodeConnectInfo (..), NetworkId, connectToLocalNode) import Cardano.BM.Data.Trace (Trace) import Cardano.BM.Data.Tracer (ToObject (..)) import Cardano.BM.Trace (logDebug, logWarning) import Cardano.Node.Emulator.TimeSlot (SlotConfig, currentSlot) import Control.Retry (fibonacciBackoff, recovering, skipAsyncExceptions) import Control.Tracer (nullTracer) import Ouroboros.Network.IOManager import Ouroboros.Network.Protocol.ChainSync.Client qualified as ChainSync import Cardano.Protocol.Socket.Type hiding (Tip) import Ledger (Slot (..)) import Plutus.ChainIndex.Compatibility (fromCardanoPoint, fromCardanoTip) import Plutus.ChainIndex.Types (Point, Tip) data ChainSyncHandle event = ChainSyncHandle { cshCurrentSlot :: IO Slot , cshHandler :: event -> Slot -> IO () } data ChainSyncEvent = Resume !ChainPoint | RollForward !(BlockInMode CardanoMode) !ChainTip | RollBackward !ChainPoint !ChainTip {- | The `Slot` parameter here represents the `current` slot as computed from the current time. There is also the slot where the block was published, which is available from the `ChainSyncEvent`. Currently we are using this current slot everywhere, which is why I leave it here, as a parameter. -} type ChainSyncCallback = ChainSyncEvent -> Slot -> IO () data ClientMsg = Disconnected Text | Resumed Point | RolledForward Tip | RolledBackward Point deriving stock (Eq, Show, Generic) deriving anyclass (FromJSON, ToJSON, ToObject) getCurrentSlot :: forall block. ChainSyncHandle block -> IO Slot getCurrentSlot = cshCurrentSlot -- | Run the chain sync protocol to get access to the current slot number. runChainSync' :: FilePath -> SlotConfig -> NetworkId -> [ChainPoint] -> IO (ChainSyncHandle ChainSyncEvent) runChainSync' socketPath slotConfig networkId resumePoints = runChainSync socketPath nullTracer slotConfig networkId resumePoints (\_ -> pure ()) runChainSync :: FilePath -> Trace IO ClientMsg -> SlotConfig -> NetworkId -> [ChainPoint] -> (ChainSyncEvent -> IO ()) -> IO (ChainSyncHandle ChainSyncEvent) runChainSync socketPath trace slotConfig networkId resumePoints onChainSyncEvent = do let handle = ChainSyncHandle { cshCurrentSlot = currentSlot slotConfig, cshHandler = chainSyncEventHandler } _ <- forkIO $ withIOManager $ \_ -> recovering (fibonacciBackoff 500) (skipAsyncExceptions ++ [(\_ -> Handler $ \(err :: SomeException) -> do logWarning trace (Disconnected $ pack $ show err) pure True )]) (\_ -> connectToLocalNode localNodeConnectInfo localNodeClientProtocols) pure handle where chainSyncEventHandler evt _ = onChainSyncEvent evt localNodeConnectInfo = LocalNodeConnectInfo { localConsensusModeParams = CardanoModeParams epochSlots, localNodeNetworkId = networkId, localNodeSocketPath = socketPath } localNodeClientProtocols :: LocalNodeClientProtocolsInMode CardanoMode localNodeClientProtocols = LocalNodeClientProtocols { localChainSyncClient = LocalChainSyncClient $ chainSyncClient trace slotConfig resumePoints chainSyncEventHandler, localTxSubmissionClient = Nothing, localStateQueryClient = Nothing, localTxMonitoringClient = Nothing } -- | The client updates the application state when the protocol state changes. chainSyncClient :: Trace IO ClientMsg -> SlotConfig -> [ChainPoint] -> ChainSyncCallback -> ChainSync.ChainSyncClient (BlockInMode CardanoMode) ChainPoint ChainTip IO () chainSyncClient trace slotConfig [] chainSyncEventHandler = chainSyncClient trace slotConfig [ChainPointAtGenesis] chainSyncEventHandler chainSyncClient trace slotConfig resumePoints chainSyncEventHandler = ChainSync.ChainSyncClient $ pure initialise where initialise :: ChainSync.ClientStIdle (BlockInMode CardanoMode) ChainPoint ChainTip IO () initialise = ChainSync.SendMsgFindIntersect resumePoints $ ChainSync.ClientStIntersect { ChainSync.recvMsgIntersectFound = \chainPoint _ -> ChainSync.ChainSyncClient $ do slot <- currentSlot slotConfig logDebug trace (Resumed $ fromCardanoPoint chainPoint) chainSyncEventHandler (Resume chainPoint) slot pure requestNext, ChainSync.recvMsgIntersectNotFound = \_ -> ChainSync.ChainSyncClient $ pure requestNext } requestNext :: ChainSync.ClientStIdle (BlockInMode CardanoMode) ChainPoint ChainTip IO () requestNext = ChainSync.SendMsgRequestNext handleNext (return handleNext) handleNext :: ChainSync.ClientStNext (BlockInMode CardanoMode) ChainPoint ChainTip IO () handleNext = ChainSync.ClientStNext { ChainSync.recvMsgRollForward = \block tip -> ChainSync.ChainSyncClient $ do slot <- currentSlot slotConfig logDebug trace (RolledForward $ fromCardanoTip tip) chainSyncEventHandler (RollForward block tip) slot pure requestNext , ChainSync.recvMsgRollBackward = \point tip -> ChainSync.ChainSyncClient $ do slot <- currentSlot slotConfig logDebug trace (RolledBackward $ fromCardanoPoint point) chainSyncEventHandler (RollBackward point tip) slot pure requestNext }
null
https://raw.githubusercontent.com/input-output-hk/plutus-apps/8706e6c7c525b4973a7b6d2ed7c9d0ef9cd4ef46/plutus-chain-index-core/src/Cardano/Protocol/Socket/Client.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveAnyClass # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # | The `Slot` parameter here represents the `current` slot as computed from the current time. There is also the slot where the block was published, which is available from the `ChainSyncEvent`. Currently we are using this current slot everywhere, which is why I leave it here, as a parameter. | Run the chain sync protocol to get access to the current slot number. | The client updates the application state when the protocol state changes.
# LANGUAGE GADTs # # LANGUAGE NamedFieldPuns # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module Cardano.Protocol.Socket.Client where import Control.Concurrent import Control.Monad.Catch (Handler (..), SomeException (..)) import Data.Aeson (FromJSON, ToJSON) import Data.Text (Text, pack) import GHC.Generics (Generic) import Cardano.Api (BlockInMode (..), CardanoMode, ChainPoint (..), ChainTip (..), ConsensusModeParams (..), LocalChainSyncClient (..), LocalNodeClientProtocols (..), LocalNodeClientProtocolsInMode, LocalNodeConnectInfo (..), NetworkId, connectToLocalNode) import Cardano.BM.Data.Trace (Trace) import Cardano.BM.Data.Tracer (ToObject (..)) import Cardano.BM.Trace (logDebug, logWarning) import Cardano.Node.Emulator.TimeSlot (SlotConfig, currentSlot) import Control.Retry (fibonacciBackoff, recovering, skipAsyncExceptions) import Control.Tracer (nullTracer) import Ouroboros.Network.IOManager import Ouroboros.Network.Protocol.ChainSync.Client qualified as ChainSync import Cardano.Protocol.Socket.Type hiding (Tip) import Ledger (Slot (..)) import Plutus.ChainIndex.Compatibility (fromCardanoPoint, fromCardanoTip) import Plutus.ChainIndex.Types (Point, Tip) data ChainSyncHandle event = ChainSyncHandle { cshCurrentSlot :: IO Slot , cshHandler :: event -> Slot -> IO () } data ChainSyncEvent = Resume !ChainPoint | RollForward !(BlockInMode CardanoMode) !ChainTip | RollBackward !ChainPoint !ChainTip type ChainSyncCallback = ChainSyncEvent -> Slot -> IO () data ClientMsg = Disconnected Text | Resumed Point | RolledForward Tip | RolledBackward Point deriving stock (Eq, Show, Generic) deriving anyclass (FromJSON, ToJSON, ToObject) getCurrentSlot :: forall block. ChainSyncHandle block -> IO Slot getCurrentSlot = cshCurrentSlot runChainSync' :: FilePath -> SlotConfig -> NetworkId -> [ChainPoint] -> IO (ChainSyncHandle ChainSyncEvent) runChainSync' socketPath slotConfig networkId resumePoints = runChainSync socketPath nullTracer slotConfig networkId resumePoints (\_ -> pure ()) runChainSync :: FilePath -> Trace IO ClientMsg -> SlotConfig -> NetworkId -> [ChainPoint] -> (ChainSyncEvent -> IO ()) -> IO (ChainSyncHandle ChainSyncEvent) runChainSync socketPath trace slotConfig networkId resumePoints onChainSyncEvent = do let handle = ChainSyncHandle { cshCurrentSlot = currentSlot slotConfig, cshHandler = chainSyncEventHandler } _ <- forkIO $ withIOManager $ \_ -> recovering (fibonacciBackoff 500) (skipAsyncExceptions ++ [(\_ -> Handler $ \(err :: SomeException) -> do logWarning trace (Disconnected $ pack $ show err) pure True )]) (\_ -> connectToLocalNode localNodeConnectInfo localNodeClientProtocols) pure handle where chainSyncEventHandler evt _ = onChainSyncEvent evt localNodeConnectInfo = LocalNodeConnectInfo { localConsensusModeParams = CardanoModeParams epochSlots, localNodeNetworkId = networkId, localNodeSocketPath = socketPath } localNodeClientProtocols :: LocalNodeClientProtocolsInMode CardanoMode localNodeClientProtocols = LocalNodeClientProtocols { localChainSyncClient = LocalChainSyncClient $ chainSyncClient trace slotConfig resumePoints chainSyncEventHandler, localTxSubmissionClient = Nothing, localStateQueryClient = Nothing, localTxMonitoringClient = Nothing } chainSyncClient :: Trace IO ClientMsg -> SlotConfig -> [ChainPoint] -> ChainSyncCallback -> ChainSync.ChainSyncClient (BlockInMode CardanoMode) ChainPoint ChainTip IO () chainSyncClient trace slotConfig [] chainSyncEventHandler = chainSyncClient trace slotConfig [ChainPointAtGenesis] chainSyncEventHandler chainSyncClient trace slotConfig resumePoints chainSyncEventHandler = ChainSync.ChainSyncClient $ pure initialise where initialise :: ChainSync.ClientStIdle (BlockInMode CardanoMode) ChainPoint ChainTip IO () initialise = ChainSync.SendMsgFindIntersect resumePoints $ ChainSync.ClientStIntersect { ChainSync.recvMsgIntersectFound = \chainPoint _ -> ChainSync.ChainSyncClient $ do slot <- currentSlot slotConfig logDebug trace (Resumed $ fromCardanoPoint chainPoint) chainSyncEventHandler (Resume chainPoint) slot pure requestNext, ChainSync.recvMsgIntersectNotFound = \_ -> ChainSync.ChainSyncClient $ pure requestNext } requestNext :: ChainSync.ClientStIdle (BlockInMode CardanoMode) ChainPoint ChainTip IO () requestNext = ChainSync.SendMsgRequestNext handleNext (return handleNext) handleNext :: ChainSync.ClientStNext (BlockInMode CardanoMode) ChainPoint ChainTip IO () handleNext = ChainSync.ClientStNext { ChainSync.recvMsgRollForward = \block tip -> ChainSync.ChainSyncClient $ do slot <- currentSlot slotConfig logDebug trace (RolledForward $ fromCardanoTip tip) chainSyncEventHandler (RollForward block tip) slot pure requestNext , ChainSync.recvMsgRollBackward = \point tip -> ChainSync.ChainSyncClient $ do slot <- currentSlot slotConfig logDebug trace (RolledBackward $ fromCardanoPoint point) chainSyncEventHandler (RollBackward point tip) slot pure requestNext }
5b95c03afa83c091982a808258c1a9aaaef7ce702d3f266c079b0d0733c90104
elaforge/karya
DDebug.hs
Copyright 2015 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt | Utilities to debug derivers . These are intended for temporary use via -- "Util.Debug". They're not in a test because I wind up putting them in -- call definitions, and non-test code can't link test modules. module Derive.DDebug where import qualified Util.Seq as Seq import qualified Derive.Call.SubT as SubT import qualified Derive.Derive as Derive import qualified Derive.Score as Score import qualified Derive.Stream as Stream import qualified Perform.Pitch as Pitch import Global apply_sub :: Functor f => (a -> f b) -> SubT.EventT a -> f (SubT.EventT b) apply_sub f (SubT.EventT s d n) = SubT.EventT s d <$> f n showr :: Maybe Derive.NoteDeriver -> Derive.Deriver Text showr = maybe (return "-") showd showd :: Derive.NoteDeriver -> Derive.Deriver Text showd d = do es <- Stream.events_of <$> d return $ maybe "?" Pitch.note_text $ Score.initial_note =<< Seq.head es
null
https://raw.githubusercontent.com/elaforge/karya/471a2131f5a68b3b10b1a138e6f9ed1282980a18/Derive/DDebug.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt "Util.Debug". They're not in a test because I wind up putting them in call definitions, and non-test code can't link test modules.
Copyright 2015 | Utilities to debug derivers . These are intended for temporary use via module Derive.DDebug where import qualified Util.Seq as Seq import qualified Derive.Call.SubT as SubT import qualified Derive.Derive as Derive import qualified Derive.Score as Score import qualified Derive.Stream as Stream import qualified Perform.Pitch as Pitch import Global apply_sub :: Functor f => (a -> f b) -> SubT.EventT a -> f (SubT.EventT b) apply_sub f (SubT.EventT s d n) = SubT.EventT s d <$> f n showr :: Maybe Derive.NoteDeriver -> Derive.Deriver Text showr = maybe (return "-") showd showd :: Derive.NoteDeriver -> Derive.Deriver Text showd d = do es <- Stream.events_of <$> d return $ maybe "?" Pitch.note_text $ Score.initial_note =<< Seq.head es
c4ff2c65177fcf520903f7395cc6aa2ca15e9a5be4694823f808df4c65bd896d
ocaml-gospel/cameleer
binary_search_tree.ml
module type OrderedType = sig type t val compare : t -> t -> int [@@logic] (*@ axiom is_pre_order: is_pre_order compare *) end module Make (Ord : OrderedType) = struct type elt = Ord.t type t = E | T of t * elt * t @ function occ ( x : elt ) ( t : t ) : integer = match t with | E - > 0 | T l v r - > occ x l + occ x r + ( if Ord.compare x v = 0 then 1 else 0 ) | E -> 0 | T l v r -> occ x l + occ x r + (if Ord.compare x v = 0 then 1 else 0) *) @ : forall x : elt , t : t > = 0 (*@ predicate mem (x: elt) (t: t) = occ x t > 0 *) @ predicate ( t : t ) = match t with | E - > true | T l v r - > ( forall lv . lv l - > Ord.compare lv v < 0 ) & & ( forall rv . Ord.compare rv v > 0 ) & & bst l & & bst r | E -> true | T l v r -> (forall lv. mem lv l -> Ord.compare lv v < 0) && (forall rv. mem rv r -> Ord.compare rv v > 0) && bst l && bst r *) let empty = E @ r = empty ensures forall x. occ x r = 0 ensures bst r ensures forall x. occ x r = 0 ensures bst r *) let rec insert x = function | E -> T (E, x, E) | T (l, y, r) -> if Ord.compare x y = 0 then T (l, y, r) else if Ord.compare x y < 0 then T (insert x l, y, r) else T (l, y, insert x r) @ t = insert x param requires bst param variant param ensures forall y. y < > x - > occ y t = occ y param ensures occ x t = occ x param t = 1 + occ x param ensures bst t requires bst param variant param ensures forall y. y <> x -> occ y t = occ y param ensures occ x t = occ x param || occ x t = 1 + occ x param ensures bst t *) let rec mem x = function | E -> false | T (l, v, r) -> let c = Ord.compare x v in c = 0 || mem x (if c < 0 then l else r) @ b = mem x param requires bst param variant param ensures b < - > mem x param requires bst param variant param ensures b <-> mem x param *) (*@ function min (t: t) : elt *) (*@ axiom is_min_empty: forall x r. min (T E x r) = x *) @ axiom is_min_left : forall l x r. l < > E - > min ( T l x r ) = min l let[@lemma] rec occ_min (t : t) = match t with | E -> assert false | T (E, _, _) -> () | T (l, _, r) -> occ_min l @ occ_min t requires t < > E requires bst t variant t ensures occ ( min t ) t = 1 requires t <> E requires bst t variant t ensures occ (min t) t = 1 *) let rec min_elt = function | E -> assert false | T (E, v, _) -> v | T (l, _, _) -> min_elt l (*@ r = min_elt t requires t <> E variant t ensures r = min t *) let rec remove_min = function | E -> E | T (E, _, r) -> r | T (l, v, r) -> T (remove_min l, v, r) @ r = remove_min t requires bst t variant t ensures bst r ensures forall x. x < > min t - > occ x t = occ x r ensures occ ( min t ) r = 0 requires bst t variant t ensures bst r ensures forall x. x <> min t -> occ x t = occ x r ensures occ (min t) r = 0 *) let rec remove x = function | E -> E | T (l, v, r) -> ( if Ord.compare x v < 0 then T (remove x l, v, r) else if Ord.compare x v > 0 then T (l, v, remove x r) else match r with | E -> l | r -> let min_value = min_elt r in let new_r = remove_min r in T (l, min_value, new_r)) @ r = remove x t requires bst t variant t ensures bst t ensures forall y. y < > x - > occ y r = occ y t ensures occ x r = 0 requires bst t variant t ensures bst t ensures forall y. y <> x -> occ y r = occ y t ensures occ x r = 0 *) end
null
https://raw.githubusercontent.com/ocaml-gospel/cameleer/11730187347b171bee4c12ff33b049a476af6b2d/examples/exercises/solutions/binary_search_tree.ml
ocaml
@ axiom is_pre_order: is_pre_order compare @ predicate mem (x: elt) (t: t) = occ x t > 0 @ function min (t: t) : elt @ axiom is_min_empty: forall x r. min (T E x r) = x @ r = min_elt t requires t <> E variant t ensures r = min t
module type OrderedType = sig type t val compare : t -> t -> int [@@logic] end module Make (Ord : OrderedType) = struct type elt = Ord.t type t = E | T of t * elt * t @ function occ ( x : elt ) ( t : t ) : integer = match t with | E - > 0 | T l v r - > occ x l + occ x r + ( if Ord.compare x v = 0 then 1 else 0 ) | E -> 0 | T l v r -> occ x l + occ x r + (if Ord.compare x v = 0 then 1 else 0) *) @ : forall x : elt , t : t > = 0 @ predicate ( t : t ) = match t with | E - > true | T l v r - > ( forall lv . lv l - > Ord.compare lv v < 0 ) & & ( forall rv . Ord.compare rv v > 0 ) & & bst l & & bst r | E -> true | T l v r -> (forall lv. mem lv l -> Ord.compare lv v < 0) && (forall rv. mem rv r -> Ord.compare rv v > 0) && bst l && bst r *) let empty = E @ r = empty ensures forall x. occ x r = 0 ensures bst r ensures forall x. occ x r = 0 ensures bst r *) let rec insert x = function | E -> T (E, x, E) | T (l, y, r) -> if Ord.compare x y = 0 then T (l, y, r) else if Ord.compare x y < 0 then T (insert x l, y, r) else T (l, y, insert x r) @ t = insert x param requires bst param variant param ensures forall y. y < > x - > occ y t = occ y param ensures occ x t = occ x param t = 1 + occ x param ensures bst t requires bst param variant param ensures forall y. y <> x -> occ y t = occ y param ensures occ x t = occ x param || occ x t = 1 + occ x param ensures bst t *) let rec mem x = function | E -> false | T (l, v, r) -> let c = Ord.compare x v in c = 0 || mem x (if c < 0 then l else r) @ b = mem x param requires bst param variant param ensures b < - > mem x param requires bst param variant param ensures b <-> mem x param *) @ axiom is_min_left : forall l x r. l < > E - > min ( T l x r ) = min l let[@lemma] rec occ_min (t : t) = match t with | E -> assert false | T (E, _, _) -> () | T (l, _, r) -> occ_min l @ occ_min t requires t < > E requires bst t variant t ensures occ ( min t ) t = 1 requires t <> E requires bst t variant t ensures occ (min t) t = 1 *) let rec min_elt = function | E -> assert false | T (E, v, _) -> v | T (l, _, _) -> min_elt l let rec remove_min = function | E -> E | T (E, _, r) -> r | T (l, v, r) -> T (remove_min l, v, r) @ r = remove_min t requires bst t variant t ensures bst r ensures forall x. x < > min t - > occ x t = occ x r ensures occ ( min t ) r = 0 requires bst t variant t ensures bst r ensures forall x. x <> min t -> occ x t = occ x r ensures occ (min t) r = 0 *) let rec remove x = function | E -> E | T (l, v, r) -> ( if Ord.compare x v < 0 then T (remove x l, v, r) else if Ord.compare x v > 0 then T (l, v, remove x r) else match r with | E -> l | r -> let min_value = min_elt r in let new_r = remove_min r in T (l, min_value, new_r)) @ r = remove x t requires bst t variant t ensures bst t ensures forall y. y < > x - > occ y r = occ y t ensures occ x r = 0 requires bst t variant t ensures bst t ensures forall y. y <> x -> occ y r = occ y t ensures occ x r = 0 *) end
fd6e69f75bab31f3e43ab68e7539941da13072e66e10766a9a6f517e552c5953
padsproj/oforest
oopsla.ml
Use Makefile in examples directory : ./desugar.sh oopsla / oopsla.ml Compile : make oopsla This example uses data from : -names-from-social-security-card-applications-national-level-data Use Makefile in examples directory Desugar: ./desugar.sh oopsla/oopsla.ml Compile: make oopsla This example uses data from: -names-from-social-security-card-applications-national-level-data *) open Pads open Forest open Printf open String module CostMon = CostUnitMon let lines = Str.split (Str.regexp "\n") let location = RE "[A-Z]+" let gender = RE "[MF]" let name = RE "[A-Za-z]+" let nL = REd ("\r?\n","\n") [%%pads {| ptype item = { location : $location$; ","; gender : $gender$; ","; year : Pint; ","; name : $name$; ","; freq : Pint } ptype items = item Plist($nL$,EOF) |} ] [%%forest {| d = directory { files is [ f :: pads items | f <- matches GL "*.TXT" ] } d_inc = directory { files is [ f :: <pads items> | f <- matches GL "*.TXT" ] } |} ] let search pred print list = try let x = List.find pred list in Printf.printf "%s\n%!" (print x) with Not_found -> Printf.printf "Not found\n%!" let string_contains s x = let rx = Str.regexp (Printf.sprintf ".*%s.*" x) in Str.string_match rx s 0 let search_strings name list = let pred = (fun s -> string_contains s name) in let print = (fun s -> s) in search pred print list let search_items name items = let pred = (fun i -> string_contains i.name name) in let print = (fun i -> item_to_string (i, item_default_md)) in search pred print items let read_lines (fn:string) : string list = let r = ref [] in let ch = open_in fn in try while true do r := input_line ch :: !r done; [] with End_of_file -> close_in ch; List.rev !r let find_classic dir name = let%bind cur = d_new dir in let%bind (r,md) = load cur in if md.num_errors = 0 then return (List.iter (search_items name) r.files) else return (List.iter (fun s -> Printf.printf "%s\n%!" s) md.error_msg) let find_incremental dir name = let%bind cur = d_inc_new dir in let%bind (r,md) = load cur in if md.num_errors = 0 then let (fr,fmd) = Forest.sort_comp_path (r.files,md.data.files_md) in let rec loop = function | [] -> return () | c::rest -> let%bind (items,md) = load c in search_items name items; loop rest in loop fr else return (List.iter (fun s -> Printf.printf "%s\n%!" s) md.error_msg) let find_manual (dir:string) (name:string) : unit = let files : string array = Sys.readdir dir in Array.iter (fun file -> let lines = read_lines (Printf.sprintf "%s/%s" dir file) in search_strings name lines) files let usage () = Printf.printf "usage: %s [options] <dir> <name>\n" Sys.argv.(0); Printf.printf " -manual : Manual OCaml\n"; Printf.printf " -classic : Classic Forest\n"; Printf.printf " -incremental : Incremental Forest\n"; exit 1 let _ = if Array.length Sys.argv < 4 then usage () else let cmd = Sys.argv.(1) in let dir = Sys.argv.(2) in let name = Sys.argv.(3) in match cmd with | "-classic" -> run @@ find_classic dir name | "-incremental" -> run @@ find_incremental dir name | "-manual" -> run @@ (find_manual dir name; return ()) | _ -> usage ()
null
https://raw.githubusercontent.com/padsproj/oforest/e10abf1c35f6d49d4bdf13d51cab44487629b3a3/examples/oopsla/oopsla.ml
ocaml
Use Makefile in examples directory : ./desugar.sh oopsla / oopsla.ml Compile : make oopsla This example uses data from : -names-from-social-security-card-applications-national-level-data Use Makefile in examples directory Desugar: ./desugar.sh oopsla/oopsla.ml Compile: make oopsla This example uses data from: -names-from-social-security-card-applications-national-level-data *) open Pads open Forest open Printf open String module CostMon = CostUnitMon let lines = Str.split (Str.regexp "\n") let location = RE "[A-Z]+" let gender = RE "[MF]" let name = RE "[A-Za-z]+" let nL = REd ("\r?\n","\n") [%%pads {| ptype item = { location : $location$; ","; gender : $gender$; ","; year : Pint; ","; name : $name$; ","; freq : Pint } ptype items = item Plist($nL$,EOF) |} ] [%%forest {| d = directory { files is [ f :: pads items | f <- matches GL "*.TXT" ] } d_inc = directory { files is [ f :: <pads items> | f <- matches GL "*.TXT" ] } |} ] let search pred print list = try let x = List.find pred list in Printf.printf "%s\n%!" (print x) with Not_found -> Printf.printf "Not found\n%!" let string_contains s x = let rx = Str.regexp (Printf.sprintf ".*%s.*" x) in Str.string_match rx s 0 let search_strings name list = let pred = (fun s -> string_contains s name) in let print = (fun s -> s) in search pred print list let search_items name items = let pred = (fun i -> string_contains i.name name) in let print = (fun i -> item_to_string (i, item_default_md)) in search pred print items let read_lines (fn:string) : string list = let r = ref [] in let ch = open_in fn in try while true do r := input_line ch :: !r done; [] with End_of_file -> close_in ch; List.rev !r let find_classic dir name = let%bind cur = d_new dir in let%bind (r,md) = load cur in if md.num_errors = 0 then return (List.iter (search_items name) r.files) else return (List.iter (fun s -> Printf.printf "%s\n%!" s) md.error_msg) let find_incremental dir name = let%bind cur = d_inc_new dir in let%bind (r,md) = load cur in if md.num_errors = 0 then let (fr,fmd) = Forest.sort_comp_path (r.files,md.data.files_md) in let rec loop = function | [] -> return () | c::rest -> let%bind (items,md) = load c in search_items name items; loop rest in loop fr else return (List.iter (fun s -> Printf.printf "%s\n%!" s) md.error_msg) let find_manual (dir:string) (name:string) : unit = let files : string array = Sys.readdir dir in Array.iter (fun file -> let lines = read_lines (Printf.sprintf "%s/%s" dir file) in search_strings name lines) files let usage () = Printf.printf "usage: %s [options] <dir> <name>\n" Sys.argv.(0); Printf.printf " -manual : Manual OCaml\n"; Printf.printf " -classic : Classic Forest\n"; Printf.printf " -incremental : Incremental Forest\n"; exit 1 let _ = if Array.length Sys.argv < 4 then usage () else let cmd = Sys.argv.(1) in let dir = Sys.argv.(2) in let name = Sys.argv.(3) in match cmd with | "-classic" -> run @@ find_classic dir name | "-incremental" -> run @@ find_incremental dir name | "-manual" -> run @@ (find_manual dir name; return ()) | _ -> usage ()
5ddc76777af6c20b1db1368e1dd82f76f25f49e01038bbb4945e4da30cb0d41c
linuxsoares/artigos-clojure
env.clj
(ns hello-web-app.env (:require [clojure.tools.logging :as log])) (def defaults {:init (fn [] (log/info "\n-=[hello-web-app started successfully]=-")) :stop (fn [] (log/info "\n-=[hello-web-app has shut down successfully]=-")) :middleware identity})
null
https://raw.githubusercontent.com/linuxsoares/artigos-clojure/6c4183e767e71168c778973dd5831e7c9edfaf4a/criando-web-application-clojure/hello-web-app/env/prod/clj/hello_web_app/env.clj
clojure
(ns hello-web-app.env (:require [clojure.tools.logging :as log])) (def defaults {:init (fn [] (log/info "\n-=[hello-web-app started successfully]=-")) :stop (fn [] (log/info "\n-=[hello-web-app has shut down successfully]=-")) :middleware identity})
ba4b9114d94e103de394520d8cc48d6209a41ce2576f5f52812265dee61fc611
Incanus3/ExiL
examples-clips.lisp
(in-package :exil-user) (format t "~%~%Running examples with clips-compatible syntax:~%") (complete-reset) (deftemplate goal (slot action (default move)) (slot object) (slot from) (slot to)) (deftemplate in (slot object) (slot location)) (deffacts world (in (object robot) (location A)) (in (object box) (location B)) (goal (object box) (from B) (to A))) (defrule move-robot (goal (action move) (object ?obj) (from ?from)) (in (object ?obj) (location ?from)) (- in (object robot) (location ?from)) ?robot <- (in (object robot) (location ?z)) => (modify ?robot (location ?from))) (defrule move-object (goal (action move) (object ?obj) (from ?from) (to ?to)) ?object <- (in (object ?obj) (location ?from)) ?robot <- (in (object robot) (location ?from)) => (modify ?robot (location ?to)) (modify ?object (location ?to))) (defrule stop ?goal <- (goal (action move) (object ?obj) (to ?to)) (in (object ?obj) (location ?to)) => (retract ?goal) (halt)) (unwatch all) (watch facts) ;(watch activations) (reset) (run) #| (step) |# (complete-reset)
null
https://raw.githubusercontent.com/Incanus3/ExiL/de0f7c37538cecb7032cc1f2aa070524b0bc048d/src/examples/examples-clips.lisp
lisp
(watch activations) (step)
(in-package :exil-user) (format t "~%~%Running examples with clips-compatible syntax:~%") (complete-reset) (deftemplate goal (slot action (default move)) (slot object) (slot from) (slot to)) (deftemplate in (slot object) (slot location)) (deffacts world (in (object robot) (location A)) (in (object box) (location B)) (goal (object box) (from B) (to A))) (defrule move-robot (goal (action move) (object ?obj) (from ?from)) (in (object ?obj) (location ?from)) (- in (object robot) (location ?from)) ?robot <- (in (object robot) (location ?z)) => (modify ?robot (location ?from))) (defrule move-object (goal (action move) (object ?obj) (from ?from) (to ?to)) ?object <- (in (object ?obj) (location ?from)) ?robot <- (in (object robot) (location ?from)) => (modify ?robot (location ?to)) (modify ?object (location ?to))) (defrule stop ?goal <- (goal (action move) (object ?obj) (to ?to)) (in (object ?obj) (location ?to)) => (retract ?goal) (halt)) (unwatch all) (watch facts) (reset) (run) (complete-reset)
95eb768dc9389ea847dca990e4f27cfbf9f8927cdccfae02c1631e0b2f2253f1
crategus/cl-cffi-gtk
application-open.lisp
;;;; Example Application Open - 2021-10-9 (in-package :gio-example) (defun application-open (&rest argv) (let ((app (make-instance 'g-application :application-id "com.crategus.application-open" :flags :handles-open)) (argv (if argv argv (uiop:command-line-arguments)))) ;; Print information about the application (format t "Start application~%") (format t " arg : ~a~%" argv) (format t " prgname : ~a~%" (g-prgname)) Signal handler " startup " (g-signal-connect app "startup" (lambda (application) (declare (ignore application)) (format t "The application is in STARTUP~%"))) Signal handler " activate " (g-signal-connect app "activate" (lambda (application) (declare (ignore application)) (format t "The application is in ACTIVATE~%") ;; Note: when doing a longer-lasting action here that ;; returns to the main loop, you should use ;; g-application-hold and g-application-release to ;; keep the application alive until the action is ;; completed. )) Signal handler " open " (g-signal-connect app "open" (lambda (application files n-files hint) (declare (ignore application)) (format t "The application is in OPEN~%") (format t " n-files : ~A~%" n-files) (format t " hint : ~A~%" hint) ;; The argument FILES is a C pointer to an array of GFile objects . We list the pathnames of the files . (dotimes (i n-files) (let ((file (mem-aref files '(g-object g-file) i))) (format t " ~a~%" (g-file-path file)))))) Signal handler " shutdown " (g-signal-connect app "shutdown" (lambda (application) (declare (ignore application)) (format t "The application is in SHUTDOWN~%"))) ;; Run the application (g-application-run app argv)))
null
https://raw.githubusercontent.com/crategus/cl-cffi-gtk/7f5a09f78d8004a71efa82794265f2587fff98ab/demo/gio-example/application-open.lisp
lisp
Example Application Open - 2021-10-9 Print information about the application Note: when doing a longer-lasting action here that returns to the main loop, you should use g-application-hold and g-application-release to keep the application alive until the action is completed. The argument FILES is a C pointer to an array of Run the application
(in-package :gio-example) (defun application-open (&rest argv) (let ((app (make-instance 'g-application :application-id "com.crategus.application-open" :flags :handles-open)) (argv (if argv argv (uiop:command-line-arguments)))) (format t "Start application~%") (format t " arg : ~a~%" argv) (format t " prgname : ~a~%" (g-prgname)) Signal handler " startup " (g-signal-connect app "startup" (lambda (application) (declare (ignore application)) (format t "The application is in STARTUP~%"))) Signal handler " activate " (g-signal-connect app "activate" (lambda (application) (declare (ignore application)) (format t "The application is in ACTIVATE~%") )) Signal handler " open " (g-signal-connect app "open" (lambda (application files n-files hint) (declare (ignore application)) (format t "The application is in OPEN~%") (format t " n-files : ~A~%" n-files) (format t " hint : ~A~%" hint) GFile objects . We list the pathnames of the files . (dotimes (i n-files) (let ((file (mem-aref files '(g-object g-file) i))) (format t " ~a~%" (g-file-path file)))))) Signal handler " shutdown " (g-signal-connect app "shutdown" (lambda (application) (declare (ignore application)) (format t "The application is in SHUTDOWN~%"))) (g-application-run app argv)))
5938ace865dea9a9183c416885a15c0503ee290405ad36db52a3d53a10f3c29b
aristidb/aws
Core.hs
module Aws.Ses.Core ( SesError(..) , SesMetadata(..) , SesConfiguration(..) , sesEuWest1 , sesUsEast , sesUsEast1 , sesUsWest2 , sesHttpsGet , sesHttpsPost , sesSignQuery , sesResponseConsumer , RawMessage(..) , Destination(..) , EmailAddress , Sender(..) , sesAsQuery ) where import Aws.Core import qualified Blaze.ByteString.Builder as Blaze import qualified Blaze.ByteString.Builder.Char8 as Blaze8 import qualified Control.Exception as C import Control.Monad (mplus) import Control.Monad.Trans.Resource (throwM) import qualified Data.ByteString as B import qualified Data.ByteString.Base64 as B64 import Data.ByteString.Char8 ({-IsString-}) import Data.IORef import Data.Maybe import Data.Monoid import qualified Data.Semigroup as Sem import Data.Text (Text) import qualified Data.Text.Encoding as TE import Data.Typeable import Prelude import qualified Network.HTTP.Conduit as HTTP import qualified Network.HTTP.Types as HTTP import Text.XML.Cursor (($/), ($//)) import qualified Text.XML.Cursor as Cu data SesError = SesError { sesStatusCode :: HTTP.Status , sesErrorCode :: Text , sesErrorMessage :: Text } deriving (Show, Typeable) instance C.Exception SesError data SesMetadata = SesMetadata { requestId :: Maybe Text } deriving (Show, Typeable) instance Loggable SesMetadata where toLogText (SesMetadata rid) = "SES: request ID=" `mappend` fromMaybe "<none>" rid instance Sem.Semigroup SesMetadata where SesMetadata r1 <> SesMetadata r2 = SesMetadata (r1 `mplus` r2) instance Monoid SesMetadata where mempty = SesMetadata Nothing mappend = (Sem.<>) data SesConfiguration qt = SesConfiguration { sesiHttpMethod :: Method , sesiHost :: B.ByteString } deriving (Show) -- HTTP is not supported right now, always use HTTPS instance DefaultServiceConfiguration (SesConfiguration NormalQuery) where defServiceConfig = sesHttpsPost sesUsEast1 instance DefaultServiceConfiguration (SesConfiguration UriOnlyQuery) where defServiceConfig = sesHttpsGet sesUsEast1 sesEuWest1 :: B.ByteString sesEuWest1 = "email.eu-west-1.amazonaws.com" sesUsEast :: B.ByteString sesUsEast = sesUsEast1 sesUsEast1 :: B.ByteString sesUsEast1 = "email.us-east-1.amazonaws.com" sesUsWest2 :: B.ByteString sesUsWest2 = "email.us-west-2.amazonaws.com" sesHttpsGet :: B.ByteString -> SesConfiguration qt sesHttpsGet endpoint = SesConfiguration Get endpoint sesHttpsPost :: B.ByteString -> SesConfiguration NormalQuery sesHttpsPost endpoint = SesConfiguration PostQuery endpoint sesSignQuery :: [(B.ByteString, B.ByteString)] -> SesConfiguration qt -> SignatureData -> SignedQuery sesSignQuery query si sd = SignedQuery { sqMethod = sesiHttpMethod si , sqProtocol = HTTPS , sqHost = sesiHost si , sqPort = defaultPort HTTPS , sqPath = "/" , sqQuery = HTTP.simpleQueryToQuery query' , sqDate = Just $ signatureTime sd , sqAuthorization = Nothing , sqContentType = Nothing , sqContentMd5 = Nothing , sqAmzHeaders = amzHeaders , sqOtherHeaders = [] , sqBody = Nothing , sqStringToSign = stringToSign } where stringToSign = fmtRfc822Time (signatureTime sd) credentials = signatureCredentials sd accessKeyId = accessKeyID credentials amzHeaders = catMaybes [ Just ("X-Amzn-Authorization", authorization) , ("x-amz-security-token",) `fmap` iamToken credentials ] authorization = B.concat [ "AWS3-HTTPS AWSAccessKeyId=" , accessKeyId , ", Algorithm=HmacSHA256, Signature=" , signature credentials HmacSHA256 stringToSign ] query' = ("AWSAccessKeyId", accessKeyId) : query sesResponseConsumer :: (Cu.Cursor -> Response SesMetadata a) -> IORef SesMetadata -> HTTPResponseConsumer a sesResponseConsumer inner metadataRef resp = xmlCursorConsumer parse metadataRef resp where parse cursor = do let requestId' = listToMaybe $ cursor $// elContent "RequestID" tellMetadata $ SesMetadata requestId' case cursor $/ Cu.laxElement "Error" of [] -> inner cursor (err:_) -> fromError err fromError cursor = do errCode <- force "Missing Error Code" $ cursor $// elContent "Code" errMessage <- force "Missing Error Message" $ cursor $// elContent "Message" throwM $ SesError (HTTP.responseStatus resp) errCode errMessage class SesAsQuery a where -- | Write a data type as a list of query parameters. sesAsQuery :: a -> [(B.ByteString, B.ByteString)] instance SesAsQuery a => SesAsQuery (Maybe a) where sesAsQuery = maybe [] sesAsQuery -- | A raw e-mail. data RawMessage = RawMessage { rawMessageData :: B.ByteString } deriving (Eq, Ord, Show, Typeable) instance SesAsQuery RawMessage where sesAsQuery = (:[]) . (,) "RawMessage.Data" . B64.encode . rawMessageData -- | The destinations of an e-mail. data Destination = Destination { destinationBccAddresses :: [EmailAddress] , destinationCcAddresses :: [EmailAddress] , destinationToAddresses :: [EmailAddress] } deriving (Eq, Ord, Show, Typeable) instance SesAsQuery Destination where sesAsQuery (Destination bcc cc to) = concat [ go (s "Bcc") bcc , go (s "Cc") cc , go (s "To") to ] where go kind = zipWith f (map Blaze8.fromShow [one..]) where txt = kind `mappend` s "Addresses.member." f n v = ( Blaze.toByteString (txt `mappend` n) , TE.encodeUtf8 v ) s = Blaze.fromByteString one = 1 :: Int instance Sem.Semigroup Destination where (Destination a1 a2 a3) <> (Destination b1 b2 b3) = Destination (a1 ++ b1) (a2 ++ b2) (a3 ++ b3) instance Monoid Destination where mempty = Destination [] [] [] mappend = (Sem.<>) -- | An e-mail address. type EmailAddress = Text -- | The sender's e-mail address. data Sender = Sender { senderAddress :: EmailAddress } deriving (Eq, Ord, Show, Typeable) instance SesAsQuery Sender where sesAsQuery = (:[]) . (,) "Source" . TE.encodeUtf8 . senderAddress
null
https://raw.githubusercontent.com/aristidb/aws/a99113ed7768f9758346052c0d8939b66c6efa87/Aws/Ses/Core.hs
haskell
IsString HTTP is not supported right now, always use HTTPS | Write a data type as a list of query parameters. | A raw e-mail. | The destinations of an e-mail. | An e-mail address. | The sender's e-mail address.
module Aws.Ses.Core ( SesError(..) , SesMetadata(..) , SesConfiguration(..) , sesEuWest1 , sesUsEast , sesUsEast1 , sesUsWest2 , sesHttpsGet , sesHttpsPost , sesSignQuery , sesResponseConsumer , RawMessage(..) , Destination(..) , EmailAddress , Sender(..) , sesAsQuery ) where import Aws.Core import qualified Blaze.ByteString.Builder as Blaze import qualified Blaze.ByteString.Builder.Char8 as Blaze8 import qualified Control.Exception as C import Control.Monad (mplus) import Control.Monad.Trans.Resource (throwM) import qualified Data.ByteString as B import qualified Data.ByteString.Base64 as B64 import Data.IORef import Data.Maybe import Data.Monoid import qualified Data.Semigroup as Sem import Data.Text (Text) import qualified Data.Text.Encoding as TE import Data.Typeable import Prelude import qualified Network.HTTP.Conduit as HTTP import qualified Network.HTTP.Types as HTTP import Text.XML.Cursor (($/), ($//)) import qualified Text.XML.Cursor as Cu data SesError = SesError { sesStatusCode :: HTTP.Status , sesErrorCode :: Text , sesErrorMessage :: Text } deriving (Show, Typeable) instance C.Exception SesError data SesMetadata = SesMetadata { requestId :: Maybe Text } deriving (Show, Typeable) instance Loggable SesMetadata where toLogText (SesMetadata rid) = "SES: request ID=" `mappend` fromMaybe "<none>" rid instance Sem.Semigroup SesMetadata where SesMetadata r1 <> SesMetadata r2 = SesMetadata (r1 `mplus` r2) instance Monoid SesMetadata where mempty = SesMetadata Nothing mappend = (Sem.<>) data SesConfiguration qt = SesConfiguration { sesiHttpMethod :: Method , sesiHost :: B.ByteString } deriving (Show) instance DefaultServiceConfiguration (SesConfiguration NormalQuery) where defServiceConfig = sesHttpsPost sesUsEast1 instance DefaultServiceConfiguration (SesConfiguration UriOnlyQuery) where defServiceConfig = sesHttpsGet sesUsEast1 sesEuWest1 :: B.ByteString sesEuWest1 = "email.eu-west-1.amazonaws.com" sesUsEast :: B.ByteString sesUsEast = sesUsEast1 sesUsEast1 :: B.ByteString sesUsEast1 = "email.us-east-1.amazonaws.com" sesUsWest2 :: B.ByteString sesUsWest2 = "email.us-west-2.amazonaws.com" sesHttpsGet :: B.ByteString -> SesConfiguration qt sesHttpsGet endpoint = SesConfiguration Get endpoint sesHttpsPost :: B.ByteString -> SesConfiguration NormalQuery sesHttpsPost endpoint = SesConfiguration PostQuery endpoint sesSignQuery :: [(B.ByteString, B.ByteString)] -> SesConfiguration qt -> SignatureData -> SignedQuery sesSignQuery query si sd = SignedQuery { sqMethod = sesiHttpMethod si , sqProtocol = HTTPS , sqHost = sesiHost si , sqPort = defaultPort HTTPS , sqPath = "/" , sqQuery = HTTP.simpleQueryToQuery query' , sqDate = Just $ signatureTime sd , sqAuthorization = Nothing , sqContentType = Nothing , sqContentMd5 = Nothing , sqAmzHeaders = amzHeaders , sqOtherHeaders = [] , sqBody = Nothing , sqStringToSign = stringToSign } where stringToSign = fmtRfc822Time (signatureTime sd) credentials = signatureCredentials sd accessKeyId = accessKeyID credentials amzHeaders = catMaybes [ Just ("X-Amzn-Authorization", authorization) , ("x-amz-security-token",) `fmap` iamToken credentials ] authorization = B.concat [ "AWS3-HTTPS AWSAccessKeyId=" , accessKeyId , ", Algorithm=HmacSHA256, Signature=" , signature credentials HmacSHA256 stringToSign ] query' = ("AWSAccessKeyId", accessKeyId) : query sesResponseConsumer :: (Cu.Cursor -> Response SesMetadata a) -> IORef SesMetadata -> HTTPResponseConsumer a sesResponseConsumer inner metadataRef resp = xmlCursorConsumer parse metadataRef resp where parse cursor = do let requestId' = listToMaybe $ cursor $// elContent "RequestID" tellMetadata $ SesMetadata requestId' case cursor $/ Cu.laxElement "Error" of [] -> inner cursor (err:_) -> fromError err fromError cursor = do errCode <- force "Missing Error Code" $ cursor $// elContent "Code" errMessage <- force "Missing Error Message" $ cursor $// elContent "Message" throwM $ SesError (HTTP.responseStatus resp) errCode errMessage class SesAsQuery a where sesAsQuery :: a -> [(B.ByteString, B.ByteString)] instance SesAsQuery a => SesAsQuery (Maybe a) where sesAsQuery = maybe [] sesAsQuery data RawMessage = RawMessage { rawMessageData :: B.ByteString } deriving (Eq, Ord, Show, Typeable) instance SesAsQuery RawMessage where sesAsQuery = (:[]) . (,) "RawMessage.Data" . B64.encode . rawMessageData data Destination = Destination { destinationBccAddresses :: [EmailAddress] , destinationCcAddresses :: [EmailAddress] , destinationToAddresses :: [EmailAddress] } deriving (Eq, Ord, Show, Typeable) instance SesAsQuery Destination where sesAsQuery (Destination bcc cc to) = concat [ go (s "Bcc") bcc , go (s "Cc") cc , go (s "To") to ] where go kind = zipWith f (map Blaze8.fromShow [one..]) where txt = kind `mappend` s "Addresses.member." f n v = ( Blaze.toByteString (txt `mappend` n) , TE.encodeUtf8 v ) s = Blaze.fromByteString one = 1 :: Int instance Sem.Semigroup Destination where (Destination a1 a2 a3) <> (Destination b1 b2 b3) = Destination (a1 ++ b1) (a2 ++ b2) (a3 ++ b3) instance Monoid Destination where mempty = Destination [] [] [] mappend = (Sem.<>) type EmailAddress = Text data Sender = Sender { senderAddress :: EmailAddress } deriving (Eq, Ord, Show, Typeable) instance SesAsQuery Sender where sesAsQuery = (:[]) . (,) "Source" . TE.encodeUtf8 . senderAddress
a01b1552c84106619a4b31739362584ef8bdfa27198737f9237152d51ff976cf
vbrankov/hdf5-ocaml
float_intf.ml
open Bigarray module type S = sig type t type float_elt (** Writes the given float array to the data set. *) val write_float_array : t -> string -> ?deflate:int -> float array -> unit (** Reads the data set into a float array. @param data If provided, the storage for the data. *) val read_float_array : t -> ?data:float array -> string -> float array val write_float_genarray : t -> string -> ?deflate:int -> (float, float_elt, _) Genarray.t -> unit * Reads the data set into a float Genarray.t . @param data If provided , the storage for the data . @param data If provided, the storage for the data. *) val read_float_genarray : t -> ?data:(float, float_elt, 'a) Genarray.t -> string -> 'a layout -> (float, float_elt, 'a) Genarray.t (** Writes the given float Array1.t to the data set. *) val write_float_array1 : t -> string -> ?deflate:int -> (float, float_elt, _) Array1.t -> unit (** Reads the data set into a float Array1.t. @param data If provided, the storage for the data. *) val read_float_array1 : t -> ?data:(float, float_elt, 'a) Array1.t -> string -> 'a layout -> (float, float_elt, 'a) Array1.t (** Writes the given float Array1.t to the data set. *) val write_float_array2 : t -> string -> ?deflate:int -> (float, float_elt, _) Array2.t -> unit (** Reads the data set into a float Array2.t. @param data If provided, the storage for the data. *) val read_float_array2 : t -> ?data:(float, float_elt, 'a) Array2.t -> string -> 'a layout -> (float, float_elt, 'a) Array2.t (** Writes the given float Array1.t to the data set. *) val write_float_array3 : t -> string -> ?deflate:int -> (float, float_elt, _) Array3.t -> unit (** Reads the data set into a float Array3.t. @param data If provided, the storage for the data. *) val read_float_array3 : t -> ?data:(float, float_elt, 'a) Array3.t -> string -> 'a layout -> (float, float_elt, 'a) Array3.t (** [write_attribute_float t name v] writes the given [float] as an attribute with the given name. *) val write_attribute_float : t -> string -> float -> unit (** [read_attribute_float t name] reads the attribute with the given name as a float. *) val read_attribute_float : t -> string -> float (** Writes the given [float] as an attribute with the given name. *) val write_attribute_float_array : t -> string -> float array -> unit (** Reads the attribute with the given name as a float. *) val read_attribute_float_array : t -> string -> float array end
null
https://raw.githubusercontent.com/vbrankov/hdf5-ocaml/7abc763189767cd6c92620f29ce98f6ee23ba88f/src/caml/float_intf.ml
ocaml
* Writes the given float array to the data set. * Reads the data set into a float array. @param data If provided, the storage for the data. * Writes the given float Array1.t to the data set. * Reads the data set into a float Array1.t. @param data If provided, the storage for the data. * Writes the given float Array1.t to the data set. * Reads the data set into a float Array2.t. @param data If provided, the storage for the data. * Writes the given float Array1.t to the data set. * Reads the data set into a float Array3.t. @param data If provided, the storage for the data. * [write_attribute_float t name v] writes the given [float] as an attribute with the given name. * [read_attribute_float t name] reads the attribute with the given name as a float. * Writes the given [float] as an attribute with the given name. * Reads the attribute with the given name as a float.
open Bigarray module type S = sig type t type float_elt val write_float_array : t -> string -> ?deflate:int -> float array -> unit val read_float_array : t -> ?data:float array -> string -> float array val write_float_genarray : t -> string -> ?deflate:int -> (float, float_elt, _) Genarray.t -> unit * Reads the data set into a float Genarray.t . @param data If provided , the storage for the data . @param data If provided, the storage for the data. *) val read_float_genarray : t -> ?data:(float, float_elt, 'a) Genarray.t -> string -> 'a layout -> (float, float_elt, 'a) Genarray.t val write_float_array1 : t -> string -> ?deflate:int -> (float, float_elt, _) Array1.t -> unit val read_float_array1 : t -> ?data:(float, float_elt, 'a) Array1.t -> string -> 'a layout -> (float, float_elt, 'a) Array1.t val write_float_array2 : t -> string -> ?deflate:int -> (float, float_elt, _) Array2.t -> unit val read_float_array2 : t -> ?data:(float, float_elt, 'a) Array2.t -> string -> 'a layout -> (float, float_elt, 'a) Array2.t val write_float_array3 : t -> string -> ?deflate:int -> (float, float_elt, _) Array3.t -> unit val read_float_array3 : t -> ?data:(float, float_elt, 'a) Array3.t -> string -> 'a layout -> (float, float_elt, 'a) Array3.t val write_attribute_float : t -> string -> float -> unit val read_attribute_float : t -> string -> float val write_attribute_float_array : t -> string -> float array -> unit val read_attribute_float_array : t -> string -> float array end
23bb955dc4f155423826cba9d8d7b3b1f2e0e20e035b170b73294366a8fabfb3
josefs/Gradualizer
absform.erl
@doc Module for extracting data from an Erlang parse tree . @private -module(absform). -export([normalize_record_field/1, normalize_function_type_list/1]). -include("gradualizer.hrl"). %% @doc Turns all record fields into typed record fields. Adds default %% 'undefined' if default value is missing. normalize_record_field({record_field, L, Name = {atom, _, _}}) -> {typed_record_field, {record_field, L, Name, {atom, L, undefined}}, {type, L, any, []}}; normalize_record_field({record_field, L, Name = {atom, _, _}, Default}) -> {typed_record_field, {record_field, L, Name, Default}, {type, L, any, []}}; normalize_record_field({typed_record_field, {record_field, L, Name = {atom, _, _}}, Type}) -> {typed_record_field, {record_field, L, Name, {atom, L, undefined}}, Type}; normalize_record_field({typed_record_field, {record_field, _L, {atom, _, _Name}, _Default}, _Type} = Complete) -> Complete. %% @doc Turns all function types into bounded function types. Add default empty %% constraints if missing. -spec normalize_function_type_list(FunTypeList) -> FunTypeList when FunTypeList :: gradualizer_type:af_function_type_list(). normalize_function_type_list(FunTypeList) -> ?assert_type(lists:map(fun normalize_function_type/1, FunTypeList), nonempty_list()). -spec normalize_function_type(BoundedFun | Fun) -> BoundedFun when BoundedFun :: gradualizer_type:af_constrained_function_type(), Fun :: gradualizer_type:af_fun_type(). normalize_function_type({type, L, 'fun', [{type, _, product, _ArgTypes}, _RetType]} = FunType) -> {type, L, bounded_fun, [FunType, _EmptyConst = []]}; normalize_function_type({type, _, 'bounded_fun', [_FunType, _FunConst]} = BoundedFun) -> BoundedFun.
null
https://raw.githubusercontent.com/josefs/Gradualizer/ba4476fd4ef8e715e49ddf038d5f9f08901a25da/src/absform.erl
erlang
@doc Turns all record fields into typed record fields. Adds default 'undefined' if default value is missing. @doc Turns all function types into bounded function types. Add default empty constraints if missing.
@doc Module for extracting data from an Erlang parse tree . @private -module(absform). -export([normalize_record_field/1, normalize_function_type_list/1]). -include("gradualizer.hrl"). normalize_record_field({record_field, L, Name = {atom, _, _}}) -> {typed_record_field, {record_field, L, Name, {atom, L, undefined}}, {type, L, any, []}}; normalize_record_field({record_field, L, Name = {atom, _, _}, Default}) -> {typed_record_field, {record_field, L, Name, Default}, {type, L, any, []}}; normalize_record_field({typed_record_field, {record_field, L, Name = {atom, _, _}}, Type}) -> {typed_record_field, {record_field, L, Name, {atom, L, undefined}}, Type}; normalize_record_field({typed_record_field, {record_field, _L, {atom, _, _Name}, _Default}, _Type} = Complete) -> Complete. -spec normalize_function_type_list(FunTypeList) -> FunTypeList when FunTypeList :: gradualizer_type:af_function_type_list(). normalize_function_type_list(FunTypeList) -> ?assert_type(lists:map(fun normalize_function_type/1, FunTypeList), nonempty_list()). -spec normalize_function_type(BoundedFun | Fun) -> BoundedFun when BoundedFun :: gradualizer_type:af_constrained_function_type(), Fun :: gradualizer_type:af_fun_type(). normalize_function_type({type, L, 'fun', [{type, _, product, _ArgTypes}, _RetType]} = FunType) -> {type, L, bounded_fun, [FunType, _EmptyConst = []]}; normalize_function_type({type, _, 'bounded_fun', [_FunType, _FunConst]} = BoundedFun) -> BoundedFun.
2b223d708cc4012f3f7a478af8c934ac2bc584b84338ee64e77d57bc4d674659
DSiSc/why3
lift_epsilon.ml
(********************************************************************) (* *) The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University (* *) (* This software is distributed under the terms of the GNU Lesser *) General Public License version 2.1 , with the special exception (* on linking described in file LICENSE. *) (* *) (********************************************************************) open Close_epsilon open Term open Theory open Task type lift_kind = (* | Goal (* prove the existence of a witness *) *) | Implied (* require the existence of a witness in an axiom *) | Implicit (* do not require a witness *) let lift kind = let rec term acc t = match t.t_node with | Teps fb -> let fv = Mvs.keys (t_vars t) in let x, f = t_open_bound fb in let acc, f = form acc f in let tys = List.map (fun x -> x.vs_ty) fv in let xs = Ident.id_derive "epsilon" x.vs_name in let xl = create_fsymbol xs tys x.vs_ty in let acc = add_decl acc (Decl.create_param_decl xl) in let axs = Decl.create_prsymbol (Ident.id_derive ("epsilon_def") x.vs_name) in let xlapp = t_app xl (List.map t_var fv) t.t_ty in let f = match kind with (* assume that lambdas always exist *) | Implied when not (is_lambda t) -> t_forall_close_merge fv (t_implies (t_exists_close [x] [] f) (t_subst_single x xlapp f)) | _ -> t_subst_single x xlapp f in let acc = add_decl acc (Decl.create_prop_decl Decl.Paxiom axs f) in acc, xlapp | _ -> TermTF.t_map_fold term form acc t and form acc f = TermTF.t_map_fold term form acc f in fun th acc -> let th = th.task_decl in match th.td_node with | Decl d -> let acc, d = Decl.DeclTF.decl_map_fold term form acc d in add_decl acc d | _ -> add_tdecl acc th let lift_epsilon kind = Trans.fold (lift kind) None let meta_epsilon = Theory.register_meta_excl "lift_epsilon" [MTstring] ~desc:"Specify@ whether@ the@ existence@ of@ a@ witness@ for@ the@ \ formula@ under@ epsilon@ is@ assumed:@; \ @[\ - @[<hov 2>implicit:@ implicitly@ assume@ existence@]@\n\ - @[<hov 2>implied:@ @ do@ not@ assume@ the@ existence@ \ of@ a@ witness.@]\ @]" let lift_epsilon = Trans.on_meta_excl meta_epsilon (fun alo -> let kind = match alo with | Some [MAstr "implicit"] -> Implicit | Some [MAstr "implied"] | None -> Implied | _ -> failwith "lift_epsilon accepts only 'implicit' and 'implied'" in lift_epsilon kind) let () = Trans.register_transform "lift_epsilon" lift_epsilon ~desc:"Move@ epsilon-terms@ into@ separate@ function@ definitions."
null
https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/transform/lift_epsilon.ml
ocaml
****************************************************************** This software is distributed under the terms of the GNU Lesser on linking described in file LICENSE. ****************************************************************** | Goal (* prove the existence of a witness require the existence of a witness in an axiom do not require a witness assume that lambdas always exist
The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University General Public License version 2.1 , with the special exception open Close_epsilon open Term open Theory open Task type lift_kind = let lift kind = let rec term acc t = match t.t_node with | Teps fb -> let fv = Mvs.keys (t_vars t) in let x, f = t_open_bound fb in let acc, f = form acc f in let tys = List.map (fun x -> x.vs_ty) fv in let xs = Ident.id_derive "epsilon" x.vs_name in let xl = create_fsymbol xs tys x.vs_ty in let acc = add_decl acc (Decl.create_param_decl xl) in let axs = Decl.create_prsymbol (Ident.id_derive ("epsilon_def") x.vs_name) in let xlapp = t_app xl (List.map t_var fv) t.t_ty in let f = match kind with | Implied when not (is_lambda t) -> t_forall_close_merge fv (t_implies (t_exists_close [x] [] f) (t_subst_single x xlapp f)) | _ -> t_subst_single x xlapp f in let acc = add_decl acc (Decl.create_prop_decl Decl.Paxiom axs f) in acc, xlapp | _ -> TermTF.t_map_fold term form acc t and form acc f = TermTF.t_map_fold term form acc f in fun th acc -> let th = th.task_decl in match th.td_node with | Decl d -> let acc, d = Decl.DeclTF.decl_map_fold term form acc d in add_decl acc d | _ -> add_tdecl acc th let lift_epsilon kind = Trans.fold (lift kind) None let meta_epsilon = Theory.register_meta_excl "lift_epsilon" [MTstring] ~desc:"Specify@ whether@ the@ existence@ of@ a@ witness@ for@ the@ \ formula@ under@ epsilon@ is@ assumed:@; \ @[\ - @[<hov 2>implicit:@ implicitly@ assume@ existence@]@\n\ - @[<hov 2>implied:@ @ do@ not@ assume@ the@ existence@ \ of@ a@ witness.@]\ @]" let lift_epsilon = Trans.on_meta_excl meta_epsilon (fun alo -> let kind = match alo with | Some [MAstr "implicit"] -> Implicit | Some [MAstr "implied"] | None -> Implied | _ -> failwith "lift_epsilon accepts only 'implicit' and 'implied'" in lift_epsilon kind) let () = Trans.register_transform "lift_epsilon" lift_epsilon ~desc:"Move@ epsilon-terms@ into@ separate@ function@ definitions."
b512bbdcdd9403f0bdfeaa13c81105daa52e9cb8599fb1719017a706a32c8db2
polytypic/f-omega-mu
Token.ml
open Grammar let[@warning "-32"] to_string = function | And -> "and" | ArrowRight -> "→" | BraceLhs -> "{" | BraceLhsNS -> "{" | BraceRhs -> "}" | BracketLhs -> "[" | BracketLhsNS -> "[" | BracketRhs -> "]" | Caret -> "^" | Case -> "case" | Colon -> ":" | Comma -> "," | Comment _ -> "# ..." | Diamond -> "◇" | Dot -> "." | DoubleAngleQuoteLhs -> "«" | DoubleAngleQuoteLhsNS -> "«" | DoubleAngleQuoteRhs -> "»" | DoubleComma -> "„" | EOF -> "<EOF>" | Ellipsis -> "…" | Else -> "else" | Equal -> "=" | Escape s -> s | Exists -> "∃" | ForAll -> "∀" | Greater -> ">" | GreaterEqual -> "≥" | Id id -> id | IdDollar id -> id | IdSub id -> id | IdTyp id -> id | If -> "if" | Import -> "import" | In -> "in" | Include -> "include" | LambdaLower -> "λ" | LambdaUpper -> "Λ" | Less -> "<" | LessEqual -> "≤" | Let -> "let" | LitNat n -> Bigint.to_string n | Local -> "local" | LogicalAnd -> "∧" | LogicalNot -> "¬" | LogicalOr -> "∨" | Minus -> "-" | MuLower -> "μ" | NotEqual -> "≠" | ParenLhs -> "(" | ParenLhsNS -> "(" | ParenRhs -> ")" | Percent -> "%" | Pipe -> "|" | Plus -> "+" | Semicolon -> ";" | Slash -> "/" | Star -> "*" | Target -> "target" | Then -> "then" | Tick -> "'" | TriangleLhs -> "◁" | TriangleRhs -> "▷" | TstrClose -> "\"...\"" | TstrEsc _ -> "\"...\"" | TstrOpen _ -> "\"...\"" | TstrOpenRaw -> "\"...\"" | TstrStr _ -> "\"...\"" | TstrStrPart -> "\"...\"" | Type -> "type" | Underscore -> "_"
null
https://raw.githubusercontent.com/polytypic/f-omega-mu/bba3a21a93bd0582fa5e75a414978e6428d3c674/src/main/FomParser/Token.ml
ocaml
open Grammar let[@warning "-32"] to_string = function | And -> "and" | ArrowRight -> "→" | BraceLhs -> "{" | BraceLhsNS -> "{" | BraceRhs -> "}" | BracketLhs -> "[" | BracketLhsNS -> "[" | BracketRhs -> "]" | Caret -> "^" | Case -> "case" | Colon -> ":" | Comma -> "," | Comment _ -> "# ..." | Diamond -> "◇" | Dot -> "." | DoubleAngleQuoteLhs -> "«" | DoubleAngleQuoteLhsNS -> "«" | DoubleAngleQuoteRhs -> "»" | DoubleComma -> "„" | EOF -> "<EOF>" | Ellipsis -> "…" | Else -> "else" | Equal -> "=" | Escape s -> s | Exists -> "∃" | ForAll -> "∀" | Greater -> ">" | GreaterEqual -> "≥" | Id id -> id | IdDollar id -> id | IdSub id -> id | IdTyp id -> id | If -> "if" | Import -> "import" | In -> "in" | Include -> "include" | LambdaLower -> "λ" | LambdaUpper -> "Λ" | Less -> "<" | LessEqual -> "≤" | Let -> "let" | LitNat n -> Bigint.to_string n | Local -> "local" | LogicalAnd -> "∧" | LogicalNot -> "¬" | LogicalOr -> "∨" | Minus -> "-" | MuLower -> "μ" | NotEqual -> "≠" | ParenLhs -> "(" | ParenLhsNS -> "(" | ParenRhs -> ")" | Percent -> "%" | Pipe -> "|" | Plus -> "+" | Semicolon -> ";" | Slash -> "/" | Star -> "*" | Target -> "target" | Then -> "then" | Tick -> "'" | TriangleLhs -> "◁" | TriangleRhs -> "▷" | TstrClose -> "\"...\"" | TstrEsc _ -> "\"...\"" | TstrOpen _ -> "\"...\"" | TstrOpenRaw -> "\"...\"" | TstrStr _ -> "\"...\"" | TstrStrPart -> "\"...\"" | Type -> "type" | Underscore -> "_"
980e65fe4fb0b3b7ee57c51befd91dd2e489971cf6ab3a353f1627f8000277dc
namin/mk-on-smt
helper.scm
This file needs to be loaded before mk.scm for Vicare . I ca n't figure ; out how to do loads relative to a source file rather than the working directory , else this file would load mk.scm . Trie implementation , due to . Used for substitution ; and constraint store. ;;; subst ::= (empty) ;;; | (node even odd) ;;; | (data idx val) (define-record-type node (fields e o)) (define-record-type data (fields idx val)) (define shift (lambda (n) (fxsra n 1))) (define unshift (lambda (n i) (fx+ (fxsll n 1) i))) ;;; interface (define t:size (lambda (x) (t:aux:size x))) (define t:bind (lambda (xi v s) (unless (and (fixnum? xi) (>= xi 0)) (error 't:bind "index must be a fixnum, got ~s" xi)) (t:aux:bind xi v s))) (define t:unbind (lambda (xi s) (unless (and (fixnum? xi) (>= xi 0)) (error 't:unbind "index must be a fixnum, got ~s" xi)) (t:aux:unbind xi s))) (define t:lookup (lambda (xi s) (unless (and (fixnum? xi) (>= xi 0)) (error 't:lookup "index must be a fixnum, got ~s" xi)) (t:aux:lookup xi s))) (define t:binding-value (lambda (s) (unless (data? s) (error 't:binding-value "not a binding ~s" s)) (data-val s))) ;;; helpers (define t:aux:push (lambda (xi vi xj vj) (if (fxeven? xi) (if (fxeven? xj) (make-node (t:aux:push (shift xi) vi (shift xj) vj) '()) (make-node (make-data (shift xi) vi) (make-data (shift xj) vj))) (if (fxeven? xj) (make-node (make-data (shift xj) vj) (make-data (shift xi) vi)) (make-node '() (t:aux:push (shift xi) vi (shift xj) vj)))))) (define t:aux:bind (lambda (xi vi s*) (cond [(node? s*) (if (fxeven? xi) (make-node (t:aux:bind (shift xi) vi (node-e s*)) (node-o s*)) (make-node (node-e s*) (t:aux:bind (shift xi) vi (node-o s*))))] [(data? s*) (let ([xj (data-idx s*)] [vj (data-val s*)]) (if (fx= xi xj) (make-data xi vi) (t:aux:push xi vi xj vj)))] [else (make-data xi vi)]))) (define t:aux:lookup (lambda (xi s*) (cond [(node? s*) (if (fxeven? xi) (t:aux:lookup (shift xi) (node-e s*)) (t:aux:lookup (shift xi) (node-o s*)))] [(data? s*) (if (fx= (data-idx s*) xi) s* #f)] [else #f]))) (define t:aux:size (lambda (s*) (cond [(node? s*) (fx+ (t:aux:size (node-e s*)) (t:aux:size (node-o s*)))] [(data? s*) 1] [else 0]))) (define t:aux:cons^ (lambda (e o) (cond [(or (node? e) (node? o)) (make-node e o)] [(data? e) (make-data (unshift (data-idx e) 0) (data-val e))] [(data? o) (make-data (unshift (data-idx o) 1) (data-val o))] [else '()]))) (define t:aux:unbind (lambda (xi s*) (cond [(node? s*) (if (fxeven? xi) (t:aux:cons^ (t:aux:unbind (shift xi) (node-e s*)) (node-o s*)) (t:aux:cons^ (node-e s*) (t:aux:unbind (shift xi) (node-o s*))))] [(and (data? s*) (fx= (data-idx s*) xi)) '()] [else s*]))) ; Misc. missing functions (define (remove-duplicates l) (cond ((null? l) '()) ((member (car l) (cdr l)) (remove-duplicates (cdr l))) (else (cons (car l) (remove-duplicates (cdr l)))))) (define (foldl f init seq) (if (null? seq) init (foldl f (f (car seq) init) (cdr seq))))
null
https://raw.githubusercontent.com/namin/mk-on-smt/90be60ee99d2f42f54195f5dd72605c9573715d9/helper.scm
scheme
out how to do loads relative to a source file rather than the working and constraint store. subst ::= (empty) | (node even odd) | (data idx val) interface helpers Misc. missing functions
This file needs to be loaded before mk.scm for Vicare . I ca n't figure directory , else this file would load mk.scm . Trie implementation , due to . Used for substitution (define-record-type node (fields e o)) (define-record-type data (fields idx val)) (define shift (lambda (n) (fxsra n 1))) (define unshift (lambda (n i) (fx+ (fxsll n 1) i))) (define t:size (lambda (x) (t:aux:size x))) (define t:bind (lambda (xi v s) (unless (and (fixnum? xi) (>= xi 0)) (error 't:bind "index must be a fixnum, got ~s" xi)) (t:aux:bind xi v s))) (define t:unbind (lambda (xi s) (unless (and (fixnum? xi) (>= xi 0)) (error 't:unbind "index must be a fixnum, got ~s" xi)) (t:aux:unbind xi s))) (define t:lookup (lambda (xi s) (unless (and (fixnum? xi) (>= xi 0)) (error 't:lookup "index must be a fixnum, got ~s" xi)) (t:aux:lookup xi s))) (define t:binding-value (lambda (s) (unless (data? s) (error 't:binding-value "not a binding ~s" s)) (data-val s))) (define t:aux:push (lambda (xi vi xj vj) (if (fxeven? xi) (if (fxeven? xj) (make-node (t:aux:push (shift xi) vi (shift xj) vj) '()) (make-node (make-data (shift xi) vi) (make-data (shift xj) vj))) (if (fxeven? xj) (make-node (make-data (shift xj) vj) (make-data (shift xi) vi)) (make-node '() (t:aux:push (shift xi) vi (shift xj) vj)))))) (define t:aux:bind (lambda (xi vi s*) (cond [(node? s*) (if (fxeven? xi) (make-node (t:aux:bind (shift xi) vi (node-e s*)) (node-o s*)) (make-node (node-e s*) (t:aux:bind (shift xi) vi (node-o s*))))] [(data? s*) (let ([xj (data-idx s*)] [vj (data-val s*)]) (if (fx= xi xj) (make-data xi vi) (t:aux:push xi vi xj vj)))] [else (make-data xi vi)]))) (define t:aux:lookup (lambda (xi s*) (cond [(node? s*) (if (fxeven? xi) (t:aux:lookup (shift xi) (node-e s*)) (t:aux:lookup (shift xi) (node-o s*)))] [(data? s*) (if (fx= (data-idx s*) xi) s* #f)] [else #f]))) (define t:aux:size (lambda (s*) (cond [(node? s*) (fx+ (t:aux:size (node-e s*)) (t:aux:size (node-o s*)))] [(data? s*) 1] [else 0]))) (define t:aux:cons^ (lambda (e o) (cond [(or (node? e) (node? o)) (make-node e o)] [(data? e) (make-data (unshift (data-idx e) 0) (data-val e))] [(data? o) (make-data (unshift (data-idx o) 1) (data-val o))] [else '()]))) (define t:aux:unbind (lambda (xi s*) (cond [(node? s*) (if (fxeven? xi) (t:aux:cons^ (t:aux:unbind (shift xi) (node-e s*)) (node-o s*)) (t:aux:cons^ (node-e s*) (t:aux:unbind (shift xi) (node-o s*))))] [(and (data? s*) (fx= (data-idx s*) xi)) '()] [else s*]))) (define (remove-duplicates l) (cond ((null? l) '()) ((member (car l) (cdr l)) (remove-duplicates (cdr l))) (else (cons (car l) (remove-duplicates (cdr l)))))) (define (foldl f init seq) (if (null? seq) init (foldl f (f (car seq) init) (cdr seq))))
bf4c29c5f846d60e532e408f5bcbdfc90badbaed4cd3b6b52b2a36c288d8fde2
rtoy/cmucl
insts.lisp
-*- Mode : LISP ; Syntax : Common - Lisp ; Base : 10 ; Package : x86 -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . If you want to use this code or any part of CMU Common Lisp , please contact or . ;;; (ext:file-comment "$Header: src/compiler/amd64/insts.lisp $") ;;; ;;; ********************************************************************** ;;; ;;; Description of the AMD64 instruction set. ;;; Written by ;;; by Spring / Summer 1995 . Debugging and enhancements by 1996 , 1997 , 1998 . AMD64 port by . ;;; (in-package :amd64) (use-package :new-assem) (def-assembler-params :scheduler-p nil) (disassem:set-disassem-params :instruction-alignment 8 :opcode-column-width 8) ;;;; Primitive emitters. (define-emitter emit-word 16 (byte 16 0)) (define-emitter emit-dword 32 (byte 32 0)) (define-emitter emit-qword 64 (byte 64 0)) (define-emitter emit-byte-with-reg 8 (byte 5 3) (byte 3 0)) (define-emitter emit-mod-reg-r/m-byte 8 (byte 2 6) (byte 3 3) (byte 3 0)) (define-emitter emit-sib-byte 8 (byte 2 6) (byte 3 3) (byte 3 0)) (define-emitter emit-rex-prefix 8 (byte 4 4) (byte 1 3) (byte 1 2) (byte 1 1) (byte 1 0)) Fixup emitters . (defun emit-absolute-fixup (segment fixup) absolute fixup should always be 64 bit . (note-fixup segment :absolute fixup) (let ((offset (fixup-offset fixup))) (if (label-p offset) (emit-back-patch segment 8 #'(lambda (segment posn) (declare (ignore posn)) (emit-qword segment (- (+ (component-header-length) (or (label-position offset) 0)) other-pointer-type)))) (emit-qword segment (or offset 0))))) (defun emit-relative-fixup (segment fixup) (note-fixup segment :relative fixup) (emit-dword segment (or (fixup-offset fixup) 0))) ;;;; The effective-address (ea) structure. (defun reg-tn-encoding (tn) (declare (type tn tn)) (assert (eq (sb-name (sc-sb (tn-sc tn))) 'registers)) (let ((offset (tn-offset tn))) (logior (ash (logand offset 1) 2) (ash offset -1)))) (defstruct (ea (:constructor make-ea (size &key base index scale disp)) (:print-function %print-ea)) (size nil :type (member :byte :word :dword :qword)) (base nil :type (or tn null)) (index nil :type (or tn null)) (scale 1 :type (member 1 2 4 8)) (disp 0 :type (or (signed-byte 32) fixup))) (defun valid-displacement-p (x) (typep x '(or (signed-byte 32) fixup))) (defun %print-ea (ea stream depth) (declare (ignore depth)) (cond ((or *print-escape* *print-readably*) (print-unreadable-object (ea stream :type t) (format stream "~S~@[ base=~S~]~@[ index=~S~]~@[ scale=~S~]~@[ disp=~S~]" (ea-size ea) (ea-base ea) (ea-index ea) (let ((scale (ea-scale ea))) (if (= scale 1) nil scale)) (ea-disp ea)))) (t (format stream "~A PTR [" (symbol-name (ea-size ea))) (when (ea-base ea) (write-string (amd64-location-print-name (ea-base ea)) stream) (when (ea-index ea) (write-string "+" stream))) (when (ea-index ea) (write-string (amd64-location-print-name (ea-index ea)) stream)) (unless (= (ea-scale ea) 1) (format stream "*~A" (ea-scale ea))) (typecase (ea-disp ea) (null) (integer (format stream "~@D" (ea-disp ea))) (t (format stream "+~A" (ea-disp ea)))) (write-char #\] stream)))) (defun absolute-ea-p (ea) (and (ea-p ea) (eq (ea-size ea) :qword) (null (ea-base ea)) (null (ea-index ea)) (= (ea-scale ea) 1))) (defun emit-absolute-ea (segment ea) (assert (absolute-ea-p ea)) (emit-qword segment (ea-disp ea))) (defun emit-ea (segment thing reg) (etypecase thing (tn (ecase (sb-name (sc-sb (tn-sc thing))) (registers (emit-mod-reg-r/m-byte segment #b11 reg (reg-lower-3-bits thing))) (stack Convert stack tns into an index off of RBP . (let ((disp (- (* (1+ (tn-offset thing)) word-bytes)))) (cond ((< -128 disp 127) (emit-mod-reg-r/m-byte segment #b01 reg #b101) (emit-byte segment disp)) (t (emit-mod-reg-r/m-byte segment #b10 reg #b101) (emit-dword segment disp))))) ;; don't allow constant ea )) (ea (let* ((base (ea-base thing)) (index (ea-index thing)) (scale (ea-scale thing)) (disp (ea-disp thing)) (mod (cond ((or (null base) ;; Using RBP or R13 without a displacement ;; must be done via mod = 01 with a displacement of 0 (and (eql disp 0) (not (= (reg-lower-3-bits base) #b101)))) #b00) ((and (fixnump disp) (<= -128 disp 127)) #b01) (t #b10))) (r/m (cond (index #b100) ((null base) #b101) (t (reg-lower-3-bits base))))) (emit-mod-reg-r/m-byte segment mod reg r/m) SIB byte is also required for R12 - based addressing (when (= r/m #b100) (let ((ss (1- (integer-length scale))) (index (if (null index) #b100 (if (= (reg-tn-encoding index) #b100) (error "Can't index off of RSP") (reg-lower-3-bits index)))) (base (if (null base) #b101 (reg-lower-3-bits base)))) (emit-sib-byte segment ss index base))) (cond ((= mod #b01) (emit-byte segment disp)) ((or (= mod #b10) (null base)) (if (fixup-p disp) (emit-absolute-fixup segment disp) (emit-dword segment disp)))))) ;; don't allow absolute fixup )) (defun fp-reg-tn-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'float-registers))) ;;; like the above , but for fp - instructions -- jrd ;;; (defun emit-fp-op (segment thing op) (if (fp-reg-tn-p thing) (emit-byte segment (dpb op (byte 3 3) (dpb (tn-offset thing) (byte 3 0) #b11000000))) (emit-ea segment thing op))) (defun byte-reg-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers) (member (sc-name (tn-sc thing)) byte-sc-names) t)) (defun byte-ea-p (thing) (typecase thing (ea (eq (ea-size thing) :byte)) (tn (and (member (sc-name (tn-sc thing)) byte-sc-names) t)) (t nil))) (defun word-reg-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers) (member (sc-name (tn-sc thing)) word-sc-names) t)) (defun word-ea-p (thing) (typecase thing (ea (eq (ea-size thing) :word)) (tn (and (member (sc-name (tn-sc thing)) word-sc-names) t)) (t nil))) (defun dword-reg-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers) (member (sc-name (tn-sc thing)) dword-sc-names) t)) (defun dword-ea-p (thing) (typecase thing (ea (eq (ea-size thing) :dword)) (tn (and (member (sc-name (tn-sc thing)) dword-sc-names) t)) (t nil))) (defun qword-reg-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers) (member (sc-name (tn-sc thing)) qword-sc-names) t)) (defun register-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers))) (defun accumulator-p (thing) (and (register-p thing) (= (tn-offset thing) 0))) (eval-when (compile load eval) (defconstant conditions '((:o . 0) (:no . 1) (:b . 2) (:nae . 2) (:c . 2) (:nb . 3) (:ae . 3) (:nc . 3) (:eq . 4) (:e . 4) (:z . 4) (:ne . 5) (:nz . 5) (:be . 6) (:na . 6) (:nbe . 7) (:a . 7) (:s . 8) (:ns . 9) (:p . 10) (:pe . 10) (:np . 11) (:po . 11) (:l . 12) (:nge . 12) (:nl . 13) (:ge . 13) (:le . 14) (:ng . 14) (:nle . 15) (:g . 15))) (defun conditional-opcode (condition) (cdr (assoc condition conditions :test #'eq)))) Utilities . #-lispworks3 (defconstant operand-size-prefix-byte #b01100110) #+lispworks3 (eval-when (compile load eval) (defconstant operand-size-prefix-byte #b01100110)) (defparameter *default-operand-size* :dword) (defun maybe-emit-operand-size-prefix (segment size &optional (default-operand-size *default-operand-size*)) (when (and (not (eq size default-operand-size)) (eq size :word)) (emit-byte segment operand-size-prefix-byte))) (defun maybe-emit-rex-prefix (segment size modrm-reg sib-index reg/modrm-rm/base) (when (or (eq size :qword) (and modrm-reg (> (reg-tn-encoding modrm-reg) 7)) (and sib-index (> (reg-tn-encoding sib-index) 7)) (and reg/modrm-rm/base (> (reg-tn-encoding reg/modrm-rm/base) 7))) (emit-rex-prefix segment #b0100 (if (eq size :qword) 1 0) (if (and modrm-reg (> (reg-tn-encoding modrm-reg) 7)) 1 0) (if (and sib-index (> (reg-tn-encoding sib-index) 7)) 1 0) (if (and reg/modrm-rm/base (> (reg-tn-encoding reg/modrm-rm/base) 7)) 1 0)))) (defun maybe-emit-ea-rex-prefix (segment size thing reg) ;; thing is an ea (etypecase thing (tn (ecase (sb-name (sc-sb (tn-sc thing))) (registers (maybe-emit-rex-prefix segment size reg nil thing)) (stack (maybe-emit-rex-prefix segment size reg nil nil)) ;; constant addresses are bad )) (ea (maybe-emit-rex-prefix segment size reg (ea-index thing) (ea-base thing))) ;; we shouldn't have absolute fixup's here )) (defun operand-size (thing) (typecase thing (tn (case (sc-name (tn-sc thing)) (#.qword-sc-names :qword) (#.dword-sc-names :dword) (#.word-sc-names :word) (#.byte-sc-names :byte) added by jrd . float - registers is a separate size ( ? ) (#.float-sc-names :float) (#.double-sc-names :double) (t (error "Can't tell the size of ~S ~S" thing (sc-name (tn-sc thing)))))) (ea (ea-size thing)) (t nil))) (defun matching-operand-size (dst src) (let ((dst-size (operand-size dst)) (src-size (operand-size src))) (if dst-size (if src-size (if (eq dst-size src-size) dst-size (error "Size mismatch: ~S is a ~S and ~S is a ~S" dst dst-size src src-size)) dst-size) (if src-size src-size (error "Can't tell the size of either ~S or ~S." dst src))))) (defun emit-sized-immediate (segment size value &optional allow-qword) (ecase size (:byte (emit-byte segment value)) (:word (emit-word segment value)) (:dword (emit-dword segment value)) (:qword (if allow-qword (emit-qword segment value) most instructions only allow 32 bit immediates (progn (assert (<= (integer-length value) 32)) (emit-dword segment value)))))) ;;;; Disassembler support stuff. (deftype reg () '(unsigned-byte 3)) #+cross-compiler (lisp:deftype reg () '(unsigned-byte 3)) (eval-when (compile eval load) (defparameter *default-address-size* Actually , : is the only one really supported . :qword) (defparameter byte-reg-names #(al cl dl bl ah ch dh bh)) (defparameter word-reg-names #(ax cx dx bx sp bp si di r8w r9w r10w r11w r12w r13w r14w r15w)) (defparameter dword-reg-names #(eax ecx edx ebx esp ebp esi edi r8d r9d r10d r11d r12d r13d r14d r15d)) (defparameter qword-reg-names #(rax rcx rdx rbx rsp rbp rsi rdi r9 r10 r11 r12 r13 r14 r15)) (defun print-reg-with-width (value width stream dstate) (declare (ignore dstate)) (princ (aref (ecase width (:byte byte-reg-names) (:word word-reg-names) (:dword dword-reg-names) (:qword qword-reg-names)) value) stream) ;; plus should do some source-var notes ) (defun print-reg (value stream dstate) (declare (type reg value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg-with-width value (disassem:dstate-get-prop dstate 'width) stream dstate)) (defun print-word-reg (value stream dstate) (declare (type reg value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg-with-width value (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*) stream dstate)) (defun print-byte-reg (value stream dstate) (declare (type reg value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg-with-width value :byte stream dstate)) (defun print-addr-reg (value stream dstate) (declare (type reg value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg-with-width value *default-address-size* stream dstate)) ;;; Value is a list of (BASE-REG OFFSET INDEX-REG INDEX-SCALE) (defun print-mem-access (value stream print-size-p dstate) (declare (type list value) (type stream stream) (type (member t nil) print-size-p) (type disassem:disassem-state dstate)) (when print-size-p (princ (disassem:dstate-get-prop dstate 'width) stream) (princ '| PTR | stream)) (write-char #\[ stream) (let ((firstp t)) (macrolet ((pel ((var val) &body body) ;; Print an element of the address, maybe with ;; a leading separator. `(let ((,var ,val)) (when ,var (unless firstp (write-char #\+ stream)) ,@body (setq firstp nil))))) (pel (base-reg (first value)) (print-addr-reg base-reg stream dstate)) (pel (index-reg (third value)) (print-addr-reg index-reg stream dstate) (let ((index-scale (fourth value))) (when (and index-scale (not (= index-scale 1))) (write-char #\* stream) (princ index-scale stream)))) (let ((offset (second value))) (when (and offset (or firstp (not (zerop offset)))) (unless (or firstp (minusp offset)) (write-char #\+ stream)) (if firstp (let ((unsigned-offset (if (minusp offset) (+ #x100000000 offset) offset))) (disassem:princ16 unsigned-offset stream) (or (nth-value 1 (disassem::note-code-constant-absolute unsigned-offset dstate)) (disassem:maybe-note-assembler-routine unsigned-offset stream dstate) (let ((offs (- offset disassem::nil-addr))) (when (typep offs 'disassem::offset) (or (disassem::maybe-note-nil-indexed-symbol-slot-ref offs dstate) (disassem::maybe-note-static-function offs dstate)))))) (princ offset stream)))))) (write-char #\] stream)) (defun print-imm-data (value stream dstate) (let ((offset (- value disassem::nil-addr))) (if (zerop offset) (format stream "#x~X" value) (format stream "~A" value)) (when (typep offset 'disassem::offset) (or (disassem::maybe-note-nil-indexed-object offset dstate) (let ((unsigned-offset (if (and (numberp value) (minusp value)) (+ value #x100000000) value))) (disassem::maybe-note-assembler-routine unsigned-offset stream dstate)) (nth-value 1 (disassem::note-code-constant-absolute offset dstate)))))) (defun print-reg/mem (value stream dstate) (declare (type (or list reg) value) (type stream stream) (type disassem:disassem-state dstate)) (if (typep value 'reg) (print-reg value stream dstate) (print-mem-access value stream nil dstate))) ;; Same as print-reg/mem, but prints an explicit size indicator for ;; memory references. (defun print-sized-reg/mem (value stream dstate) (declare (type (or list reg) value) (type stream stream) (type disassem:disassem-state dstate)) (if (typep value 'reg) (print-reg value stream dstate) (print-mem-access value stream t dstate))) (defun print-byte-reg/mem (value stream dstate) (declare (type (or list reg) value) (type stream stream) (type disassem:disassem-state dstate)) (if (typep value 'reg) (print-byte-reg value stream dstate) (print-mem-access value stream t dstate))) (defun print-label (value stream dstate) (declare (ignore dstate)) (disassem:princ16 value stream)) ;;; Returns either an integer, meaning a register, or a list of ;;; (BASE-REG OFFSET INDEX-REG INDEX-SCALE), where any component ;;; may be missing or nil to indicate that it's not used or has the obvious default value ( e.g. , 1 for the index - scale ) . (defun prefilter-reg/mem (value dstate) (declare (type list value) (type disassem:disassem-state dstate)) (let ((mod (car value)) (r/m (cadr value))) (declare (type (unsigned-byte 2) mod) (type (unsigned-byte 3) r/m)) (cond ((= mod #b11) ;; registers r/m) ((= r/m #b100) ;; sib byte (let ((sib (disassem:read-suffix 8 dstate))) (declare (type (unsigned-byte 8) sib)) (let ((base-reg (ldb (byte 3 0) sib)) (index-reg (ldb (byte 3 3) sib)) (index-scale (ldb (byte 2 6) sib))) (declare (type (unsigned-byte 3) base-reg index-reg) (type (unsigned-byte 2) index-scale)) (let* ((offset (case mod (#b00 (if (= base-reg #b101) (disassem:read-signed-suffix 32 dstate) nil)) (#b01 (disassem:read-signed-suffix 8 dstate)) (#b10 (disassem:read-signed-suffix 32 dstate))))) (list (if (and (= mod #b00) (= base-reg #b101)) nil base-reg) offset (if (= index-reg #b100) nil index-reg) (ash 1 index-scale)))))) ((and (= mod #b00) (= r/m #b101)) (list nil (disassem:read-signed-suffix 32 dstate)) ) ((= mod #b00) (list r/m)) ((= mod #b01) (list r/m (disassem:read-signed-suffix 8 dstate))) (t ; (= mod #b10) (list r/m (disassem:read-signed-suffix 32 dstate)))))) ;;; This is a sort of bogus prefilter that just ;;; stores the info globally for other people to use; it ;;; probably never gets printed. (defun prefilter-width (value dstate) (setf (disassem:dstate-get-prop dstate 'width) (if (zerop value) :byte (let ((word-width ;; set by a prefix instruction (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*))) (when (not (eql word-width *default-operand-size*)) ;; reset it (setf (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*)) word-width)))) (defun offset-next (value dstate) (declare (type integer value) (type disassem:disassem-state dstate)) (+ (disassem:dstate-next-addr dstate) value)) (defun read-address (value dstate) (declare (ignore value)) ; always nil anyway (disassem:read-suffix (width-bits *default-address-size*) dstate)) (defun width-bits (width) (ecase width (:byte 8) (:word 16) (:dword 32) (:qword 64) (:float 32) (:double 64))) ); eval-when argument types . (disassem:define-argument-type accum :printer #'(lambda (value stream dstate) (declare (ignore value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg 0 stream dstate)) ) (disassem:define-argument-type word-accum :printer #'(lambda (value stream dstate) (declare (ignore value) (type stream stream) (type disassem:disassem-state dstate)) (print-word-reg 0 stream dstate)) ) (disassem:define-argument-type reg :printer #'print-reg) (disassem:define-argument-type addr-reg :printer #'print-addr-reg) (disassem:define-argument-type word-reg :printer #'print-word-reg) (disassem:define-argument-type imm-addr :prefilter #'read-address :printer #'print-label) (disassem:define-argument-type imm-data :prefilter #'(lambda (value dstate) (declare (ignore value)) ; always nil anyway (disassem:read-suffix (width-bits (disassem:dstate-get-prop dstate 'width)) dstate)) :printer #'print-imm-data ) (disassem:define-argument-type signed-imm-data :prefilter #'(lambda (value dstate) (declare (ignore value)) ; always nil anyway (let ((width (disassem:dstate-get-prop dstate 'width))) (disassem:read-signed-suffix (width-bits width) dstate))) ) (disassem:define-argument-type signed-imm-byte :prefilter #'(lambda (value dstate) (declare (ignore value)) ; always nil anyway (disassem:read-signed-suffix 8 dstate))) (disassem:define-argument-type signed-imm-dword :prefilter #'(lambda (value dstate) (declare (ignore value)) ; always nil anyway (disassem:read-signed-suffix 32 dstate))) (disassem:define-argument-type imm-word :prefilter #'(lambda (value dstate) (declare (ignore value)) ; always nil anyway (let ((width (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*))) (disassem:read-suffix (width-bits width) dstate)))) Needed for the ret imm16 instruction (disassem:define-argument-type imm-word-16 :prefilter #'(lambda (value dstate) (declare (ignore value)) ; always nil anyway (disassem:read-suffix 16 dstate))) (disassem:define-argument-type reg/mem :prefilter #'prefilter-reg/mem :printer #'print-reg/mem) (disassem:define-argument-type sized-reg/mem ;; Same as reg/mem, but prints an explicit size indicator for ;; memory references. :prefilter #'prefilter-reg/mem :printer #'print-sized-reg/mem) (disassem:define-argument-type byte-reg/mem :prefilter #'prefilter-reg/mem :printer #'print-byte-reg/mem) ;;; added by jrd ;;; (eval-when (compile load eval) (defun print-fp-reg (value stream dstate) (declare (ignore dstate)) (format stream "~A(~D)" 'st value)) (defun prefilter-fp-reg (value dstate) ;; just return it (declare (ignore dstate)) value) ) (disassem:define-argument-type fp-reg :prefilter #'prefilter-fp-reg :printer #'print-fp-reg) (disassem:define-argument-type width :prefilter #'prefilter-width :printer #'(lambda (value stream dstate) ( zerop value ) zzz jrd (princ 'b stream) (let ((word-width ;; set by a prefix instruction (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*))) (princ (schar (symbol-name word-width) 0) stream))))) ;;;; Disassembler instruction formats. (eval-when (compile eval) (defun swap-if (direction field1 separator field2) `(:if (,direction :constant 0) (,field1 ,separator ,field2) (,field2 ,separator ,field1)))) (disassem:define-instruction-format (byte 8 :default-printer '(:name)) (op :field (byte 8 0)) ;; optional fields (accum :type 'accum) (imm)) (disassem:define-instruction-format (simple 8) (op :field (byte 7 1)) (width :field (byte 1 0) :type 'width) ;; optional fields (accum :type 'accum) (imm)) ;;; Same as simple, but with direction bit (disassem:define-instruction-format (simple-dir 8 :include 'simple) (op :field (byte 6 2)) (dir :field (byte 1 1))) ;;; Same as simple, but with the immediate value occuring by default, ;;; and with an appropiate printer. (disassem:define-instruction-format (accum-imm 8 :include 'simple :default-printer '(:name :tab accum ", " imm)) (imm :type 'imm-data)) (disassem:define-instruction-format (reg-no-width 8 :default-printer '(:name :tab reg)) (op :field (byte 5 3)) (reg :field (byte 3 0) :type 'word-reg) ;; optional fields (accum :type 'word-accum) (imm)) ;;; adds a width field to reg-no-width (disassem:define-instruction-format (reg 8 :default-printer '(:name :tab reg)) (op :field (byte 4 4)) (width :field (byte 1 3) :type 'width) (reg :field (byte 3 0) :type 'reg) ;; optional fields (accum :type 'accum) (imm) ) ;;; Same as reg, but with direction bit (disassem:define-instruction-format (reg-dir 8 :include 'reg) (op :field (byte 3 5)) (dir :field (byte 1 4))) (disassem:define-instruction-format (two-bytes 16 :default-printer '(:name)) (op :fields (list (byte 8 0) (byte 8 8)))) (disassem:define-instruction-format (reg-reg/mem 16 :default-printer `(:name :tab reg ", " reg/mem)) (op :field (byte 7 1)) (width :field (byte 1 0) :type 'width) (reg/mem :fields (list (byte 2 14) (byte 3 8)) :type 'reg/mem) (reg :field (byte 3 11) :type 'reg) ;; optional fields (imm)) same as reg - reg / mem , but with direction bit (disassem:define-instruction-format (reg-reg/mem-dir 16 :include 'reg-reg/mem :default-printer `(:name :tab ,(swap-if 'dir 'reg/mem ", " 'reg))) (op :field (byte 6 2)) (dir :field (byte 1 1))) Same as reg - rem / mem , but uses the reg field as a second op code . (disassem:define-instruction-format (reg/mem 16 :default-printer '(:name :tab reg/mem)) (op :fields (list (byte 7 1) (byte 3 11))) (width :field (byte 1 0) :type 'width) (reg/mem :fields (list (byte 2 14) (byte 3 8)) :type 'sized-reg/mem) ;; optional fields (imm)) ;;; Same as reg/mem, but with the immediate value occuring by default, ;;; and with an appropiate printer. (disassem:define-instruction-format (reg/mem-imm 16 :include 'reg/mem :default-printer '(:name :tab reg/mem ", " imm)) (reg/mem :type 'sized-reg/mem) (imm :type 'imm-data)) ;;; Same as reg/mem, but with using the accumulator in the default printer (disassem:define-instruction-format (accum-reg/mem 16 :include 'reg/mem :default-printer '(:name :tab accum ", " reg/mem)) (reg/mem :type 'reg/mem) ; don't need a size (accum :type 'accum)) Same as reg - reg / mem , but with a prefix of # b00001111 (disassem:define-instruction-format (ext-reg-reg/mem 24 :default-printer `(:name :tab reg ", " reg/mem)) (prefix :field (byte 8 0) :value #b00001111) (op :field (byte 7 9)) (width :field (byte 1 8) :type 'width) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'reg/mem) (reg :field (byte 3 19) :type 'reg) ;; optional fields (imm)) Same as reg / mem , but with a prefix of # b00001111 (disassem:define-instruction-format (ext-reg/mem 24 :default-printer '(:name :tab reg/mem)) (prefix :field (byte 8 0) :value #b00001111) (op :fields (list (byte 7 9) (byte 3 19))) (width :field (byte 1 8) :type 'width) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'sized-reg/mem) ;; optional fields (imm)) ;;; ---------------------------------------------------------------- this section added by jrd , for fp instructions . ;;; ;;; regular fp inst to/from registers/memory ;;; (disassem:define-instruction-format (floating-point 16 :default-printer `(:name :tab reg/mem)) (prefix :field (byte 5 3) :value #b11011) (op :fields (list (byte 3 0) (byte 3 11))) (reg/mem :fields (list (byte 2 14) (byte 3 8)) :type 'reg/mem)) ;;; fp insn to / from fp reg ;;; (disassem:define-instruction-format (floating-point-fp 16 :default-printer `(:name :tab fp-reg)) (prefix :field (byte 5 3) :value #b11011) (suffix :field (byte 2 14) :value #b11) (op :fields (list (byte 3 0) (byte 3 11))) (fp-reg :field (byte 3 8) :type 'fp-reg)) ;;; fp insn to / from fp reg , with the reversed source / destination flag . ;;; (disassem:define-instruction-format (floating-point-fp-d 16 :default-printer `(:name :tab ,(swap-if 'd "ST0" ", " 'fp-reg))) (prefix :field (byte 5 3) :value #b11011) (suffix :field (byte 2 14) :value #b11) (op :fields (list (byte 2 0) (byte 3 11))) (d :field (byte 1 2)) (fp-reg :field (byte 3 8) :type 'fp-reg)) pfw ;;; fp no operand isns ;;; (disassem:define-instruction-format (floating-point-no 16 :default-printer '(:name)) (prefix :field (byte 8 0) :value #b11011001) (suffix :field (byte 3 13) :value #b111) (op :field (byte 5 8))) (disassem:define-instruction-format (floating-point-3 16 :default-printer '(:name)) (prefix :field (byte 5 3) :value #b11011) (suffix :field (byte 2 14) :value #b11) (op :fields (list (byte 3 0) (byte 6 8)))) (disassem:define-instruction-format (floating-point-5 16 :default-printer '(:name)) (prefix :field (byte 8 0) :value #b11011011) (suffix :field (byte 3 13) :value #b111) (op :field (byte 5 8))) (disassem:define-instruction-format (floating-point-st 16 :default-printer '(:name)) (prefix :field (byte 8 0) :value #b11011111) (suffix :field (byte 3 13) :value #b111) (op :field (byte 5 8))) ;;; ---------------------------------------------------------------- General Data Transfer (eval-when (eval compile load) (defun toggle-word-width (chunk inst stream dstate) (declare (ignore chunk inst stream)) (let ((ww (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*))) (setf (disassem:dstate-get-prop dstate 'word-width) (ecase ww (:word :dword) (:dword :word) (:qword :dword)))))) ; not sure what this is for ;;; This isn't a really an instruction, but it's easier to deal with it this ;;; way. We assume that it's actually used. (define-instruction toggle-data-size (segment) (:printer byte ((op operand-size-prefix-byte)) nil ; don't actually print it :control #'toggle-word-width)) (defun reg-lower-3-bits (register) (let ((reg (reg-tn-encoding register))) (if (> reg 7) (- reg 8) reg))) (define-instruction mov (segment dst src) ;; immediate to register (:printer reg ((op #b1011) (imm nil :type 'imm-data)) '(:name :tab reg ", " imm)) ;; absolute mem to/from accumulator (:printer simple-dir ((op #b101000) (imm nil :type 'imm-addr)) `(:name :tab ,(swap-if 'dir 'accum ", " '("[" imm "]")))) ;; register to/from register/memory (:printer reg-reg/mem-dir ((op #b100010))) ;; immediate to register/memory (:printer reg/mem-imm ((op '(#b1100011 #b000)))) (:emitter (let ((size (matching-operand-size dst src))) (maybe-emit-operand-size-prefix segment size) (cond ((register-p dst) (cond ((integerp src) ;; integer -> register (maybe-emit-rex-prefix segment size nil nil dst) (emit-byte-with-reg segment (if (eq size :byte) B8 (reg-lower-3-bits dst)) allow qword ((and (accumulator-p dst) (or (fixup-p src) (and (tn-p src) (eq (sb-name (sc-sb (tn-sc src))) 'constant)) (absolute-ea-p src))) ;; absolute ea -> rax (assert (eq size :qword)) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment #b10100001) ; #xA1 (etypecase src 64 bit offset (tn (emit-absolute-fixup segment (make-fixup nil :code-object (- (* (tn-offset src) word-bytes) 64 bit offset (ea (emit-absolute-ea segment src)))) (t ;; ea -> other register (maybe-emit-ea-rex-prefix segment size src dst) (emit-byte segment (if (eq size :byte) #b10001010 #b10001011)) ; #x8b (emit-ea segment src (reg-lower-3-bits dst))))) ;; dst is not register ;; rax -> constant address ((and (accumulator-p src) (or (fixup-p dst) (absolute-ea-p dst))) (assert (eq size :qword)) (maybe-emit-rex-prefix segment size nil nil nil) # xA3 (etypecase dst (fixup (emit-absolute-fixup segment dst)) (ea (emit-absolute-ea segment dst)))) ;; constant -> ea ((integerp src) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11000110 #b11000111)) (emit-ea segment dst #b000) (emit-sized-immediate segment size src)) ;; register -> ea ((register-p src) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment (if (eq size :byte) #b10001000 #b10001001)) (emit-ea segment dst (reg-lower-3-bits src))) ;; fixup -> ea is not allowed (t (error "Bogus arguments to MOV: ~S ~S" dst src)))))) ;; Use this if we don't want indirect for fixup (define-instruction mov-imm (segment dst src) (:emitter (assert (qword-reg-p dst)) (assert (fixup-p src)) (maybe-emit-rex-prefix segment :qword nil nil dst) (emit-byte-with-reg segment B8 MOV (reg-lower-3-bits dst)) (emit-absolute-fixup segment src))) ; imm64 (defun emit-move-with-extension (segment dst src opcode) (assert (register-p dst)) (let ((dst-size (operand-size dst)) (src-size (operand-size src))) (ecase dst-size (:word ;; byte -> word (assert (eq src-size :byte)) (maybe-emit-operand-size-prefix segment :word) (maybe-emit-ea-rex-prefix segment :word src dst) (emit-byte segment #b00001111) (emit-byte segment opcode) (emit-ea segment src (reg-lower-3-bits dst))) (:dword (ecase src-size (:byte byte - > dword (maybe-emit-ea-rex-prefix segment :dword src dst) (emit-byte segment #b00001111) (emit-byte segment opcode) (emit-ea segment src (reg-lower-3-bits dst))) (:word (maybe-emit-ea-rex-prefix segment :dword src dst) (emit-byte segment #b00001111) (emit-byte segment (logior opcode 1)) (emit-ea segment src (reg-lower-3-bits dst))))) (:qword ; this needs to be looked at (ecase src-size (:byte (maybe-emit-ea-rex-prefix segment :qword src dst) (emit-byte segment #b00001111) (emit-byte segment opcode) (emit-ea segment src (reg-lower-3-bits dst))) (:word (maybe-emit-ea-rex-prefix segment :qword src dst) (emit-byte segment #b00001111) (emit-byte segment (logior opcode 1)) (emit-ea segment src (reg-lower-3-bits dst))) (:dword I think we do n't need a REX prefix here (maybe-emit-ea-rex-prefix segment :dword src dst) (emit-byte segment opcode) (emit-ea segment src (reg-lower-3-bits dst)))))))) (define-instruction movsx (segment dst src) (:printer ext-reg-reg/mem ((op #b1011111) (reg nil :type 'word-reg))) (:emitter (emit-move-with-extension segment dst src #b10111110))) (define-instruction movsxd (segment dst src) source size is dword ;; dest size is qword (:printer ext-reg-reg/mem ((op #b01100011) (reg nil :type 'word-reg))) (:emitter 63 (define-instruction movzx (segment dst src) (:printer ext-reg-reg/mem ((op #b1011011) (reg nil :type 'word-reg))) (:emitter (emit-move-with-extension segment dst src #b10110110))) (define-instruction push (segment src) ;; Register. (:printer reg-no-width ((op #b01010))) Register / Memory . (:printer reg/mem ((op '(#b1111111 #b110)) (width 1))) ;; Immediate. (:printer byte ((op #b01101010) (imm nil :type 'signed-imm-byte)) '(:name :tab imm)) (:printer byte ((op #b01101000) (imm nil :type 'imm-word)) '(:name :tab imm)) # # # Segment registers ? (:emitter Push ca n't take 64 - bit immediate ;; We cannot interpret a fixup as an immediate qword to push (if (integerp src) (cond ((<= -128 src 127) (emit-byte segment #b01101010) (emit-byte segment src)) (t (emit-byte segment #b01101000) (emit-dword segment src))) (let ((size (operand-size src))) (assert (not (eq size :byte))) (maybe-emit-operand-size-prefix segment size :qword) (cond ((register-p src) ;; push doesn't need a rex size prefix (maybe-emit-rex-prefix segment :dword nil nil src) (emit-byte-with-reg segment #b01010 (reg-lower-3-bits src))) (t (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment #b11111111) (emit-ea segment src #b110))))))) (define-instruction pusha (segment) (:printer byte ((op #b01100000))) (:emitter (emit-byte segment #b01100000))) (define-instruction pop (segment dst) (:printer reg-no-width ((op #b01011))) (:printer reg/mem ((op '(#b1000111 #b000)) (width 1))) (:emitter (let ((size (operand-size dst))) (assert (not (eq size :byte))) ;; pop doesn't need rex size prefix (maybe-emit-operand-size-prefix segment size :qword) (cond ((register-p dst) (maybe-emit-rex-prefix segment :dword nil nil dst) (emit-byte-with-reg segment #b01011 (reg-lower-3-bits dst))) (t (maybe-emit-ea-rex-prefix segment :dword dst nil) (emit-byte segment #b10001111) (emit-ea segment dst #b000)))))) (define-instruction popa (segment) (:printer byte ((op #b01100001))) (:emitter (emit-byte segment #b01100001))) (define-instruction xchg (segment operand1 operand2) ;; Register with accumulator. (:printer reg-no-width ((op #b10010)) '(:name :tab accum ", " reg)) Register / Memory with Register . (:printer reg-reg/mem ((op #b1000011))) (:emitter (let ((size (matching-operand-size operand1 operand2))) (maybe-emit-operand-size-prefix segment size) (labels ((xchg-acc-with-something (acc something) (if (and (not (eq size :byte)) (register-p something)) (progn (maybe-emit-rex-prefix segment size nil nil something) (emit-byte-with-reg segment #b10010 (reg-lower-3-bits something))) (xchg-reg-with-something acc something))) (xchg-reg-with-something (reg something) (maybe-emit-ea-rex-prefix segment size something reg) (emit-byte segment (if (eq size :byte) #b10000110 #b10000111)) (emit-ea segment something (reg-lower-3-bits reg)))) (cond ((accumulator-p operand1) (xchg-acc-with-something operand1 operand2)) ((accumulator-p operand2) (xchg-acc-with-something operand2 operand1)) ((register-p operand1) (xchg-reg-with-something operand1 operand2)) ((register-p operand2) (xchg-reg-with-something operand2 operand1)) (t (error "Bogus args to XCHG: ~S ~S" operand1 operand2))))))) ;; load effective address LEA can not take 64 bit argument . Sign extension does n't make sense here . (define-instruction lea (segment dst src) (:printer reg-reg/mem ((op #b1000110) (width 1))) (:emitter (assert (qword-reg-p dst)) (assert (not (fixup-p src))) (maybe-emit-ea-rex-prefix segment :qword src dst) (emit-byte segment #b10001101) (emit-ea segment src (reg-lower-3-bits dst)))) (define-instruction cmpxchg (segment dst src) Register / Memory with Register . (:printer ext-reg-reg/mem ((op #b1011000)) '(:name :tab reg/mem ", " reg)) (:emitter (assert (register-p src)) (let ((size (matching-operand-size src dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment #b00001111) (emit-byte segment (if (eq size :byte) #b10110000 #b10110001)) (emit-ea segment dst (reg-lower-3-bits src))))) ;;;; Flag control instructions. CLC -- Clear Carry Flag . ;;; (define-instruction clc (segment) (:printer byte ((op #b11111000))) (:emitter (emit-byte segment #b11111000))) ;;; CLD -- Clear Direction Flag. ;;; (define-instruction cld (segment) (:printer byte ((op #b11111100))) (:emitter (emit-byte segment #b11111100))) ;;; CLI -- Clear Iterrupt Enable Flag. ;;; (define-instruction cli (segment) (:printer byte ((op #b11111010))) (:emitter (emit-byte segment #b11111010))) CMC -- Complement Carry Flag . ;;; (define-instruction cmc (segment) (:printer byte ((op #b11110101))) (:emitter (emit-byte segment #b11110101))) LAHF -- Load AH into flags . ;;; (define-instruction lahf (segment) (:printer byte ((op #b10011111))) (:emitter (emit-byte segment #b10011111))) ;;; POPF -- Pop flags. ;;; (define-instruction popf (segment) (:printer byte ((op #b10011101))) (:emitter (emit-byte segment #b10011101))) ;;; PUSHF -- push flags. ;;; (define-instruction pushf (segment) (:printer byte ((op #b10011100))) (:emitter (emit-byte segment #b10011100))) SAHF -- Store AH into flags . ;;; (define-instruction sahf (segment) (:printer byte ((op #b10011110))) (:emitter (emit-byte segment #b10011110))) STC -- Set Carry Flag . ;;; (define-instruction stc (segment) (:printer byte ((op #b11111001))) (:emitter (emit-byte segment #b11111001))) STD -- Set Direction Flag . ;;; (define-instruction std (segment) (:printer byte ((op #b11111101))) (:emitter (emit-byte segment #b11111101))) ;;; STI -- Set Interrupt Enable Flag. ;;; (define-instruction sti (segment) (:printer byte ((op #b11111011))) (:emitter (emit-byte segment #b11111011))) ;;;; Arithmetic (defun emit-random-arith-inst (name segment dst src opcode) (let ((size (matching-operand-size dst src))) (maybe-emit-operand-size-prefix segment size) (cond ((integerp src) (cond ((and (not (eq size :byte)) (<= -128 src 127)) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment #b10000011) (emit-ea segment dst opcode) (emit-byte segment src)) ((accumulator-p dst) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (dpb opcode (byte 3 3) (if (eq size :byte) #b00000100 #b00000101))) (emit-sized-immediate segment size src)) (t (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b10000000 #b10000001)) (emit-ea segment dst opcode) (emit-sized-immediate segment size src)))) ((register-p src) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment (dpb opcode (byte 3 3) (if (eq size :byte) #b00000000 #b00000001))) (emit-ea segment dst (reg-lower-3-bits src))) ((register-p dst) (maybe-emit-ea-rex-prefix segment size src dst) (emit-byte segment (dpb opcode (byte 3 3) (if (eq size :byte) #b00000010 #b00000011))) (emit-ea segment src (reg-lower-3-bits dst))) (t (error "Bogus operands to ~A" name))))) (eval-when (compile eval) (defun arith-inst-printer-list (subop) `((accum-imm ((op ,(dpb subop (byte 3 2) #b0000010)))) (reg/mem-imm ((op (#b1000000 ,subop)))) (reg/mem-imm ((op (#b1000001 ,subop)) (imm nil :type signed-imm-byte))) (reg-reg/mem-dir ((op ,(dpb subop (byte 3 1) #b000000)))))) ) (define-instruction add (segment dst src) (:printer-list (arith-inst-printer-list #b000)) (:emitter (emit-random-arith-inst "ADD" segment dst src #b000))) (define-instruction adc (segment dst src) (:printer-list (arith-inst-printer-list #b010)) (:emitter (emit-random-arith-inst "ADC" segment dst src #b010))) (define-instruction sub (segment dst src) (:printer-list (arith-inst-printer-list #b101)) (:emitter (emit-random-arith-inst "SUB" segment dst src #b101))) (define-instruction sbb (segment dst src) (:printer-list (arith-inst-printer-list #b011)) (:emitter (emit-random-arith-inst "SBB" segment dst src #b011))) (define-instruction cmp (segment dst src) (:printer-list (arith-inst-printer-list #b111)) (:emitter (emit-random-arith-inst "CMP" segment dst src #b111))) (define-instruction inc (segment dst) ;; Register. (:printer reg-no-width ((op #b01000))) Register / Memory (:printer reg/mem ((op '(#b1111111 #b000)))) (:emitter (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) ;; Note that #x40 can't be used now. (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11111110 #b11111111)) (emit-ea segment dst #b000)))) (define-instruction dec (segment dst) ;; Register. (:printer reg-no-width ((op #b01001))) Register / Memory (:printer reg/mem ((op '(#b1111111 #b001)))) (:emitter (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) ;; Note that #x48 can't be used now. (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11111110 #b11111111)) (emit-ea segment dst #b001)))) (define-instruction neg (segment dst) (:printer reg/mem ((op '(#b1111011 #b011)))) (:emitter (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment dst #b011)))) (define-instruction aaa (segment) (:printer byte ((op #b00110111))) (:emitter (emit-byte segment #b00110111))) (define-instruction aas (segment) (:printer byte ((op #b00111111))) (:emitter (emit-byte segment #b00111111))) (define-instruction daa (segment) (:printer byte ((op #b00100111))) (:emitter (emit-byte segment #b00100111))) (define-instruction das (segment) (:printer byte ((op #b00101111))) (:emitter (emit-byte segment #b00101111))) (define-instruction mul (segment dst src) (:printer accum-reg/mem ((op '(#b1111011 #b100)))) (:emitter (let ((size (matching-operand-size dst src))) (assert (accumulator-p dst)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment src #b100)))) (define-instruction imul (segment dst &optional src1 src2) (:printer accum-reg/mem ((op '(#b1111011 #b101)))) (:printer ext-reg-reg/mem ((op #b1010111))) (:printer reg-reg/mem ((op #b0110100) (width 1) (imm nil :type 'imm-word)) '(:name :tab reg ", " reg/mem ", " imm)) (:printer reg-reg/mem ((op #b0110101) (width 1) (imm nil :type 'signed-imm-byte)) '(:name :tab reg ", " reg/mem ", " imm)) (:emitter (flet ((r/m-with-immed-to-reg (reg r/m immed) (let* ((size (matching-operand-size reg r/m)) (sx (and (not (eq size :byte)) (<= -128 immed 127)))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size r/m reg) (emit-byte segment (if sx #b01101011 #b01101001)) (emit-ea segment r/m (reg-lower-3-bits reg)) (if sx (emit-byte segment immed) (emit-sized-immediate segment size immed))))) (cond (src2 (r/m-with-immed-to-reg dst src1 src2)) (src1 (if (integerp src1) (r/m-with-immed-to-reg dst dst src1) (let ((size (matching-operand-size dst src1))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src1 dst) (emit-byte segment #b00001111) (emit-byte segment #b10101111) (emit-ea segment src1 (reg-lower-3-bits dst))))) (t (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment dst #b101))))))) (define-instruction div (segment dst src) (:printer accum-reg/mem ((op '(#b1111011 #b110)))) (:emitter (let ((size (matching-operand-size dst src))) (assert (accumulator-p dst)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment src #b110)))) (define-instruction idiv (segment dst src) (:printer accum-reg/mem ((op '(#b1111011 #b111)))) (:emitter (let ((size (matching-operand-size dst src))) (assert (accumulator-p dst)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment src #b111)))) (define-instruction aad (segment) (:printer two-bytes ((op '(#b11010101 #b00001010)))) (:emitter (emit-byte segment #b11010101) (emit-byte segment #b00001010))) (define-instruction aam (segment) (:printer two-bytes ((op '(#b11010100 #b00001010)))) (:emitter (emit-byte segment #b11010100) (emit-byte segment #b00001010))) ;;; CBW -- Convert Byte to Word. AX <- sign_xtnd(AL) ;;; (define-instruction cbw (segment) (:emitter (maybe-emit-operand-size-prefix segment :word) (emit-byte segment #b10011000))) CWDE -- Convert Word To Double Word Extened . EAX < - sign_xtnd(AX ) ;;; (define-instruction cwde (segment) (:emitter (maybe-emit-operand-size-prefix segment :dword) (emit-byte segment #b10011000))) CWD -- Convert Word to Double Word . DX : AX < - sign_xtnd(AX ) ;;; (define-instruction cwd (segment) (:emitter (maybe-emit-operand-size-prefix segment :word) (emit-byte segment #b10011001))) CDQ -- Convert Double Word to Quad Word . EDX : EAX < - sign_xtnd(EAX ) ;;; (define-instruction cdq (segment) (:printer byte ((op #b10011001))) (:emitter (maybe-emit-operand-size-prefix segment :dword) (emit-byte segment #b10011001))) CDO -- Convert Quad Word to Double Quad Word . RDX : RAX < - sign_xtnd(RAX ) ;;; (define-instruction cdo (segment) (:emitter (maybe-emit-rex-prefix segment :qword nil nil nil) (emit-byte segment #b10011001))) (define-instruction xadd (segment dst src) Register / Memory with Register . (:printer ext-reg-reg/mem ((op #b1100000)) '(:name :tab reg/mem ", " reg)) (:emitter (assert (register-p src)) (let ((size (matching-operand-size src dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment #b00001111) (emit-byte segment (if (eq size :byte) #b11000000 #b11000001)) (emit-ea segment dst (reg-lower-3-bits src))))) Logic . (defun emit-shift-inst (segment dst amount opcode) (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (multiple-value-bind (major-opcode immed) (case amount (:cl (values #b11010010 nil)) (1 (values #b11010000 nil)) (t (values #b11000000 t))) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) major-opcode (logior major-opcode 1))) (emit-ea segment dst opcode) (when immed (emit-byte segment amount))))) (eval-when (compile eval) (defun shift-inst-printer-list (subop) `((reg/mem ((op (#b1101000 ,subop))) (:name :tab reg/mem ", 1")) (reg/mem ((op (#b1101001 ,subop))) (:name :tab reg/mem ", " 'cl)) (reg/mem-imm ((op (#b1100000 ,subop)) (imm nil :type signed-imm-byte)))))) (define-instruction rol (segment dst amount) (:printer-list (shift-inst-printer-list #b000)) (:emitter (emit-shift-inst segment dst amount #b000))) (define-instruction ror (segment dst amount) (:printer-list (shift-inst-printer-list #b001)) (:emitter (emit-shift-inst segment dst amount #b001))) (define-instruction rcl (segment dst amount) (:printer-list (shift-inst-printer-list #b010)) (:emitter (emit-shift-inst segment dst amount #b010))) (define-instruction rcr (segment dst amount) (:printer-list (shift-inst-printer-list #b011)) (:emitter (emit-shift-inst segment dst amount #b011))) (define-instruction shl (segment dst amount) (:printer-list (shift-inst-printer-list #b100)) (:emitter (emit-shift-inst segment dst amount #b100))) (define-instruction shr (segment dst amount) (:printer-list (shift-inst-printer-list #b101)) (:emitter (emit-shift-inst segment dst amount #b101))) (define-instruction sar (segment dst amount) (:printer-list (shift-inst-printer-list #b111)) (:emitter (emit-shift-inst segment dst amount #b111))) (defun emit-double-shift (segment opcode dst src amt) (let ((size (matching-operand-size dst src))) (when (eq size :byte) (error "Double shifts can only be used with words.")) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment #b00001111) (emit-byte segment (dpb opcode (byte 1 3) (if (eq amt :cl) #b10100101 #b10100100))) (emit-ea segment dst (reg-lower-3-bits src)) (unless (eq amt :cl) (emit-byte segment amt)))) (eval-when (compile eval) (defun double-shift-inst-printer-list (op) `(#+nil (ext-reg-reg/mem-imm ((op ,(logior op #b100)) (imm nil :type signed-imm-byte))) (ext-reg-reg/mem ((op ,(logior op #b101))) (:name :tab reg/mem ", " 'cl))))) (define-instruction shld (segment dst src amt) (:declare (type (or (member :cl) (mod 32)) amt)) (:printer-list (double-shift-inst-printer-list #b10100000)) (:emitter (emit-double-shift segment #b0 dst src amt))) (define-instruction shrd (segment dst src amt) (:declare (type (or (member :cl) (mod 32)) amt)) (:printer-list (double-shift-inst-printer-list #b10101000)) (:emitter (emit-double-shift segment #b1 dst src amt))) (define-instruction and (segment dst src) (:printer-list (arith-inst-printer-list #b100)) (:emitter (emit-random-arith-inst "AND" segment dst src #b100))) (define-instruction test (segment this that) (:printer accum-imm ((op #b1010100))) (:printer reg/mem-imm ((op '(#b1111011 #b000)))) (:printer reg-reg/mem ((op #b1000010))) (:emitter (let ((size (matching-operand-size this that))) (maybe-emit-operand-size-prefix segment size) (flet ((test-immed-and-something (immed something) (cond ((accumulator-p something) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10101000 #b10101001)) (emit-sized-immediate segment size immed)) (t (maybe-emit-ea-rex-prefix segment size something nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment something #b000) (emit-sized-immediate segment size immed)))) (test-reg-and-something (reg something) (maybe-emit-ea-rex-prefix segment size something reg) (emit-byte segment (if (eq size :byte) #b10000100 #b10000101)) (emit-ea segment something (reg-lower-3-bits reg)))) (cond ((integerp that) (test-immed-and-something that this)) ((integerp this) (test-immed-and-something this that)) ((register-p this) (test-reg-and-something this that)) ((register-p that) (test-reg-and-something that this)) (t (error "Bogus operands for TEST: ~S and ~S" this that))))))) (define-instruction or (segment dst src) (:printer-list (arith-inst-printer-list #b001)) (:emitter (emit-random-arith-inst "OR" segment dst src #b001))) (define-instruction xor (segment dst src) (:printer-list (arith-inst-printer-list #b110)) (:emitter (emit-random-arith-inst "XOR" segment dst src #b110))) (define-instruction not (segment dst) (:printer reg/mem ((op '(#b1111011 #b010)))) (:emitter (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment dst #b010)))) ;;;; String manipulation. (disassem:define-instruction-format (string-op 8 :include 'simple :default-printer '(:name width))) (define-instruction cmps (segment size) (:printer string-op ((op #b1010011))) (:emitter (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10100110 #b10100111)))) (define-instruction ins (segment acc) (:printer string-op ((op #b0110110))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b01101100 #b01101101))))) (define-instruction lods (segment acc) (:printer string-op ((op #b1010110))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10101100 #b10101101))))) ;; move data from string to string (define-instruction movs (segment size) (:printer string-op ((op #b1010010))) (:emitter (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10100100 #b10100101)))) (define-instruction outs (segment acc) (:printer string-op ((op #b0110111))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b01101110 #b01101111))))) (define-instruction scas (segment acc) (:printer string-op ((op #b1010111))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10101110 #b10101111))))) (define-instruction stos (segment acc) (:printer string-op ((op #b1010101))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10101010 #b10101011))))) (define-instruction xlat (segment) (:printer byte ((op #b11010111))) (:emitter (emit-byte segment #b11010111))) (define-instruction rep (segment) (:emitter (emit-byte segment #b11110010))) (define-instruction repe (segment) (:printer byte ((op #b11110011))) (:emitter (emit-byte segment #b11110011))) (define-instruction repne (segment) (:printer byte ((op #b11110010))) (:emitter (emit-byte segment #b11110010))) ;;;; Bit Manipulation (define-instruction bsf (segment dst src) (:printer ext-reg-reg/mem ((op #b1011110) (width 0))) (:emitter (let ((size (matching-operand-size dst src))) (when (eq size :byte) (error "Can't scan bytes: ~S" src)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src dst) (emit-byte segment #b00001111) (emit-byte segment #b10111100) (emit-ea segment src (reg-lower-3-bits dst))))) (define-instruction bsr (segment dst src) (:printer ext-reg-reg/mem ((op #b1011110) (width 1))) (:emitter (let ((size (matching-operand-size dst src))) (when (eq size :byte) (error "Can't scan bytes: ~S" src)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src dst) (emit-byte segment #b00001111) (emit-byte segment #b10111101) (emit-ea segment src (reg-lower-3-bits dst))))) (defun emit-bit-test-and-mumble (segment src index opcode) (let ((size (operand-size src))) (when (eq size :byte) (error "Can't scan bytes: ~S" src)) (maybe-emit-operand-size-prefix segment size) (cond ((integerp index) (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment #b00001111) (emit-byte segment #b10111010) (emit-ea segment src opcode) (emit-byte segment index)) (t (maybe-emit-ea-rex-prefix segment size src index) (emit-byte segment #b00001111) (emit-byte segment (dpb opcode (byte 3 3) #b10000011)) (emit-ea segment src (reg-lower-3-bits index)))))) ;; Bit Test (BT) instructions ;; Ignoring the case with a src as a register, we have ;; ;; 0F A3 reg/mem BT ;; 0F BB reg/mem BTC ;; 0F B3 reg/mem 0F AB reg / mem ;; A3 = 10100011 BB = 10111011 B3 = 10110011 AB = 10101011 ;; ;; So the pattern is 10xxx011 ;; ;; The instruction format is then (little-endian) ;; ;; |reg/mem|10ooo011|00001111 (disassem:define-instruction-format (bit-test-reg/mem 24 :default-printer '(:name :tab reg/mem ", " reg)) (prefix :field (byte 8 0) :value #b0001111) (op :field (byte 3 11)) ( test : fields ( list ( byte 2 14 ) ( byte 3 8) ) ) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'reg/mem) (reg :field (byte 3 19) :type 'reg) ;; optional fields (imm)) (define-instruction bt (segment src index) (:printer bit-test-reg/mem ((op #b100))) (:emitter (emit-bit-test-and-mumble segment src index #b100))) (define-instruction btc (segment src index) (:printer bit-test-reg/mem ((op #b111))) (:emitter (emit-bit-test-and-mumble segment src index #b111))) (define-instruction btr (segment src index) (:printer bit-test-reg/mem ((op #b110))) (:emitter (emit-bit-test-and-mumble segment src index #b110))) (define-instruction bts (segment src index) (:printer bit-test-reg/mem ((op #b101))) (:emitter (emit-bit-test-and-mumble segment src index #b101))) ;;;; Control transfer. (eval-when (compile load eval) (defparameter condition-name-vec (let ((vec (make-array 16 :initial-element nil))) (dolist (cond conditions) (when (null (aref vec (cdr cond))) (setf (aref vec (cdr cond)) (car cond)))) vec))) (disassem:define-argument-type condition-code :printer condition-name-vec) (disassem:define-argument-type displacement :sign-extend t :use-label #'offset-next :printer #'(lambda (value stream dstate) (let ((unsigned-val (if (and (numberp value) (minusp value)) (+ value #x100000000) value))) (disassem:maybe-note-assembler-routine unsigned-val stream dstate)) (print-label value stream dstate))) (disassem:define-instruction-format (short-cond-jump 16) (op :field (byte 4 4)) (cc :field (byte 4 0) :type 'condition-code) (label :field (byte 8 8) :type 'displacement)) (disassem:define-instruction-format (short-jump 16 :default-printer '(:name :tab label)) (const :field (byte 4 4) :value #b1110) (op :field (byte 4 0)) (label :field (byte 8 8) :type 'displacement)) (disassem:define-instruction-format (near-cond-jump 16) (op :fields (list (byte 8 0) (byte 4 12)) :value '(#b00001111 #b1000)) (cc :field (byte 4 8) :type 'condition-code) The disassembler currently does n't let you have an instruction > 32 bits ;; long, so we fake it by using a prefilter to read the offset. (label :type 'displacement :prefilter #'(lambda (value dstate) (declare (ignore value)) ; always nil anyway (disassem:read-signed-suffix 32 dstate)))) (disassem:define-instruction-format (near-jump 8 :default-printer '(:name :tab label)) (op :field (byte 8 0)) The disassembler currently does n't let you have an instruction > 32 bits ;; long, so we fake it by using a prefilter to read the address. (label :type 'displacement :prefilter #'(lambda (value dstate) (declare (ignore value)) ; always nil anyway (disassem:read-signed-suffix 32 dstate)))) (define-instruction call (segment where) (:printer near-jump ((op #b11101000))) (:printer reg/mem ((op '(#b1111111 #b010)) (width 1))) (:emitter (typecase where (label (emit-byte segment #b11101000) (emit-back-patch segment 4 #'(lambda (segment posn) (emit-dword segment (- (label-position where) (+ posn 4)))))) (fixup (emit-byte segment #b11101000) Relative fixup is limited to 32 bits . This may not be enough . (emit-relative-fixup segment where)) (t REX is necessary for stuff like " callq * % rdi " (unless (ea-p where) (maybe-emit-ea-rex-prefix segment :qword where nil)) (emit-byte segment #b11111111) (emit-ea segment where #b010))))) (defun emit-byte-displacement-backpatch (segment target) (emit-back-patch segment 1 #'(lambda (segment posn) (let ((disp (- (label-position target) (1+ posn)))) (assert (<= -128 disp 127)) (emit-byte segment disp))))) fix it for 64 bit reg (define-instruction jmp (segment cond &optional where) ;; conditional jumps (:printer short-cond-jump ((op #b0111)) '('j cc :tab label)) (:printer near-cond-jump () '('j cc :tab label)) ;; unconditional jumps (:printer short-jump ((op #b1011))) (:printer near-jump ((op #b11101001)) ) (:printer reg/mem ((op '(#b1111111 #b100)) (width 1))) (:emitter (cond (where (emit-chooser segment 6 2 #'(lambda (segment posn delta-if-after) (let ((disp (- (label-position where posn delta-if-after) (+ posn 2)))) (when (<= -128 disp 127) (emit-byte segment (dpb (conditional-opcode cond) (byte 4 0) #b01110000)) (emit-byte-displacement-backpatch segment where) t))) #'(lambda (segment posn) (let ((disp (- (label-position where) (+ posn 6)))) (emit-byte segment #b00001111) (emit-byte segment (dpb (conditional-opcode cond) (byte 4 0) #b10000000)) (emit-dword segment disp))))) ((label-p (setq where cond)) (emit-chooser segment 5 0 #'(lambda (segment posn delta-if-after) (let ((disp (- (label-position where posn delta-if-after) (+ posn 2)))) (when (<= -128 disp 127) (emit-byte segment #b11101011) (emit-byte-displacement-backpatch segment where) t))) #'(lambda (segment posn) (let ((disp (- (label-position where) (+ posn 5)))) (emit-byte segment #b11101001) (emit-dword segment disp)) ))) ((fixup-p where) (emit-byte segment #b11101001) (emit-relative-fixup segment where)) (t (unless (or (ea-p where) (tn-p where)) (error "Don't know what to do with ~A" where)) (emit-byte segment #b11111111) (emit-ea segment where #b100))))) (define-instruction jmp-short (segment label) (:emitter (emit-byte segment #b11101011) (emit-byte-displacement-backpatch segment label))) (define-instruction ret (segment &optional stack-delta) (:printer byte ((op #b11000011))) (:printer byte ((op #b11000010) (imm nil :type 'imm-word-16)) '(:name :tab imm)) (:emitter (cond (stack-delta (emit-byte segment #b11000010) (emit-word segment stack-delta)) (t (emit-byte segment #b11000011))))) (define-instruction jrcxz (segment target) (:printer short-jump ((op #b0011))) (:emitter (emit-byte segment #b11100011) (emit-byte-displacement-backpatch segment target))) (define-instruction loop (segment target) (:printer short-jump ((op #b0010))) (:emitter (emit-byte segment #b11100010) (emit-byte-displacement-backpatch segment target))) (define-instruction loopz (segment target) (:printer short-jump ((op #b0001))) (:emitter (emit-byte segment #b11100001) (emit-byte-displacement-backpatch segment target))) (define-instruction loopnz (segment target) (:printer short-jump ((op #b0000))) (:emitter (emit-byte segment #b11100000) (emit-byte-displacement-backpatch segment target))) ;;; Conditional move. (disassem:define-instruction-format (cond-move 24 :default-printer '('cmov cond :tab reg ", " reg/mem)) (prefix :field (byte 8 0) :value #b00001111) (op :field (byte 4 12) :value #b0100) (cond :field (byte 4 8) :type 'condition-code) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'reg/mem) (reg :field (byte 3 19) :type 'reg)) (define-instruction cmov (segment cond dst src) (:printer cond-move ()) (:emitter (assert (register-p dst)) (let ((size (matching-operand-size dst src))) (assert (or (eq size :word) (eq size :dword))) (maybe-emit-operand-size-prefix segment size)) (emit-byte segment #b00001111) (emit-byte segment (dpb (conditional-opcode cond) (byte 4 0) #b01000000)) (emit-ea segment src (reg-tn-encoding dst)))) ;;;; Conditional byte set. (disassem:define-instruction-format (cond-set 24 :default-printer '('set cc :tab reg/mem)) (prefix :field (byte 8 0) :value #b00001111) (op :field (byte 4 12) :value #b1001) (cc :field (byte 4 8) :type 'condition-code) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'byte-reg/mem) (reg :field (byte 3 19) :value #b000)) (define-instruction set (segment dst cond) (:printer cond-set ()) (:emitter (emit-byte segment #b00001111) (emit-byte segment (dpb (conditional-opcode cond) (byte 4 0) #b10010000)) (emit-ea segment dst #b000))) Enter / Leave (disassem:define-instruction-format (enter-format 32 :default-printer '(:name :tab disp (:unless (:constant 0) ", " level))) (op :field (byte 8 0)) (disp :field (byte 16 8)) (level :field (byte 8 24))) (define-instruction enter (segment disp &optional (level 0)) (:declare (type (unsigned-byte 16) disp) (type (unsigned-byte 8) level)) (:printer enter-format ((op #b11001000))) (:emitter (emit-byte segment #b11001000) (emit-word segment disp) (emit-byte segment level))) (define-instruction leave (segment) (:printer byte ((op #b11001001))) (:emitter (emit-byte segment #b11001001))) ;;;; Interrupt instructions. ;;; Single byte instruction with an immediate byte argument. (disassem:define-instruction-format (byte-imm 16 :default-printer '(:name :tab code)) (op :field (byte 8 0)) (code :field (byte 8 8))) (defun snarf-error-junk (sap offset &optional length-only) (let* ((length (system:sap-ref-8 sap offset)) (vector (make-array length :element-type '(unsigned-byte 8)))) (declare (type system:system-area-pointer sap) (type (unsigned-byte 8) length) (type (simple-array (unsigned-byte 8) (*)) vector)) (cond (length-only (values 0 (1+ length) nil nil)) (t (kernel:copy-from-system-area sap (* byte-bits (1+ offset)) vector (* word-bits vector-data-offset) (* length byte-bits)) (collect ((sc-offsets) (lengths)) (lengths 1) ; the length byte (let* ((index 0) (error-number (c::read-var-integer vector index))) (lengths index) (loop (when (>= index length) (return)) (let ((old-index index)) (sc-offsets (c::read-var-integer vector index)) (lengths (- index old-index)))) (values error-number (1+ length) (sc-offsets) (lengths)))))))) (defmacro break-cases (breaknum &body cases) (let ((bn-temp (gensym))) (collect ((clauses)) (dolist (case cases) (clauses `((= ,bn-temp ,(car case)) ,@(cdr case)))) `(let ((,bn-temp ,breaknum)) (cond ,@(clauses)))))) (defun break-control (chunk inst stream dstate) (declare (ignore inst)) (flet ((nt (x) (if stream (disassem:note x dstate)))) (case (byte-imm-code chunk dstate) (#.vm:error-trap (nt "Error trap") (disassem:handle-break-args #'snarf-error-junk stream dstate)) (#.vm:cerror-trap (nt "Cerror trap") (disassem:handle-break-args #'snarf-error-junk stream dstate)) (#.vm:breakpoint-trap (nt "Breakpoint trap")) (#.vm:pending-interrupt-trap (nt "Pending interrupt trap")) (#.vm:halt-trap (nt "Halt trap")) (#.vm:function-end-breakpoint-trap (nt "Function end breakpoint trap")) ))) (define-instruction break (segment code) (:declare (type (unsigned-byte 8) code)) (:printer byte-imm ((op #b11001100)) '(:name :tab code) :control #'break-control) (:emitter (emit-byte segment #b11001100) (emit-byte segment code))) (define-instruction int (segment number) (:declare (type (unsigned-byte 8) number)) (:printer byte-imm ((op #b11001101))) (:emitter (etypecase number ((member 3) (emit-byte segment #b11001100)) ((unsigned-byte 8) (emit-byte segment #b11001101) (emit-byte segment number))))) (define-instruction into (segment) (:printer byte ((op #b11001110))) (:emitter (emit-byte segment #b11001110))) (define-instruction bound (segment reg bounds) (:emitter (let ((size (matching-operand-size reg bounds))) (when (eq size :byte) (error "Can't bounds-test bytes: ~S" reg)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size bounds reg) (emit-byte segment #b01100010) (emit-ea segment bounds (reg-lower-3-bits reg))))) (define-instruction iret (segment) (:printer byte ((op #b11001111))) (:emitter (emit-byte segment #b11001111))) ;; read-time-stamp instruction, that counts executed cycles, present from Pentium onwards (define-instruction rdtsc (segment) (:printer two-bytes ((op '(#x0f #x31)))) (:emitter (emit-byte segment #x0f) (emit-byte segment #x31))) (define-instruction cpuid (segment) (:printer two-bytes ((op '(#x0f #xa2)))) (:emitter (emit-byte segment #x0f) (emit-byte segment #xa2))) ;;;; Processor control (define-instruction hlt (segment) (:printer byte ((op #b11110100))) (:emitter (emit-byte segment #b11110100))) (define-instruction nop (segment) (:printer byte ((op #b10010000))) (:emitter (emit-byte segment #b10010000))) (define-instruction wait (segment) (:printer byte ((op #b10011011))) (:emitter (emit-byte segment #b10011011))) (define-instruction lock (segment) (:printer byte ((op #b11110000))) (:emitter (emit-byte segment #b11110000))) ;;;; Random hackery (define-instruction byte (segment byte) (:emitter (emit-byte segment byte))) (define-instruction word (segment word) (:emitter (emit-word segment word))) (define-instruction dword (segment dword) (:emitter (emit-dword segment dword))) (define-instruction qword (segment qword) (:emitter (emit-qword segment qword))) (defun emit-header-data (segment type) (emit-back-patch segment 8 #'(lambda (segment posn) (emit-qword segment (logior type (ash (+ posn (component-header-length)) (- type-bits word-shift))))))) (define-instruction function-header-word (segment) (:emitter (emit-header-data segment function-header-type))) (define-instruction lra-header-word (segment) (:emitter (emit-header-data segment return-pc-header-type))) ;;; ---------------------------------------------------------------- added by jrd . fp instructions ;;; ;;; ;;; we treat the single-precision and double-precision variants ;;; as separate instructions ;;; ;;; ;;; load single to st(0) ;;; (define-instruction fld (segment source) (:printer floating-point ((op '(#b001 #b000)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment source #b000))) ;;; ;;; load double to st(0) ;;; (define-instruction fldd (segment source) (:printer floating-point ((op '(#b101 #b000)))) (:printer floating-point-fp ((op '(#b001 #b000)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011001) (emit-byte segment #b11011101)) (emit-fp-op segment source #b000))) ;;; ;;; load long to st(0) ;;; (define-instruction fldl (segment source) (:printer floating-point ((op '(#b011 #b101)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment source #b101))) ;;; store single from st(0 ) ;;; (define-instruction fst (segment dest) (:printer floating-point ((op '(#b001 #b010)))) (:emitter (cond ((fp-reg-tn-p dest) (emit-byte segment #b11011101) (emit-fp-op segment dest #b010)) (t (emit-byte segment #b11011001) (emit-fp-op segment dest #b010))))) ;;; store double from st(0 ) ;;; (define-instruction fstd (segment dest) (:printer floating-point ((op '(#b101 #b010)))) (:printer floating-point-fp ((op '(#b101 #b010)))) (:emitter (cond ((fp-reg-tn-p dest) (emit-byte segment #b11011101) (emit-fp-op segment dest #b010)) (t (emit-byte segment #b11011101) (emit-fp-op segment dest #b010))))) Arithmetic ops are all done with at least one operand at top of stack . The other operand is is another register or a 32/64 bit memory . dtc : I 've tried to follow the Intel ASM386 conventions , but note that these conflict with the conventions for binops . To reduce ;;; the confusion I've added comments showing the mathamatical operation and the two syntaxes . By the ASM386 convention the ;;; instruction syntax is: ;;; ;;; Fop Source or Fop Destination , Source ;;; If only one operand is given then it is the source and the destination is ) . There are reversed forms of the fsub and ;;; fdiv instructions inducated by an 'R' suffix. ;;; ;;; The mathematical operation for the non-reverse form is always: ;;; destination = destination op source ;;; ;;; For the reversed form it is: ;;; destination = source op destination ;;; The instructions below only accept one operand at present which is ;;; usually the source. I've hack in extra instructions to implement ;;; the fops with a ST(i) destination, these have a -sti suffix and the operand is the destination with the source being ) . ;;; ;;; Add single ;;; st(0) = st(0) + memory or st(i) ;;; (define-instruction fadd (segment source) (:printer floating-point ((op '(#b000 #b000)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b000))) ;;; ;;; Add double ;;; st(0) = st(0) + memory or st(i) ;;; (define-instruction faddd (segment source) (:printer floating-point ((op '(#b100 #b000)))) (:printer floating-point-fp ((op '(#b000 #b000)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b000))) ;;; ;;; Add double destination st(i) ;;; st(i) = st(0) + st(i) ;;; (define-instruction fadd-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b000))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fadd) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b000))) ;;; With pop (define-instruction faddp-sti (segment destination) (:printer floating-point-fp ((op '(#b110 #b000))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'faddp) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011110) (emit-fp-op segment destination #b000))) ;;; ;;; Subtract single ;;; st(0) = st(0) - memory or st(i) ;;; (define-instruction fsub (segment source) (:printer floating-point ((op '(#b000 #b100)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b100))) ;;; ;;; Subtract single, reverse ;;; st(0) = memory or st(i) - st(0) ;;; (define-instruction fsubr (segment source) (:printer floating-point ((op '(#b000 #b101)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b101))) ;;; ;;; Subtract double ;;; st(0) = st(0) - memory or st(i) ;;; (define-instruction fsubd (segment source) (:printer floating-point ((op '(#b100 #b100)))) (:printer floating-point-fp ((op '(#b000 #b100)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b100))) ;;; ;;; Subtract double, reverse ;;; st(0) = memory or st(i) - st(0) ;;; (define-instruction fsubrd (segment source) (:printer floating-point ((op '(#b100 #b101)))) (:printer floating-point-fp ((op '(#b000 #b101)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b101))) ;;; ;;; Subtract double, destination st(i) ;;; st(i) = st(i) - st(0) ;;; ASM386 syntax : FSUB ST(i ) , ST ;;; Gdb syntax: fsubr %st,%st(i) ;;; (define-instruction fsub-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b101))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fsub) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b101))) ;;; With a pop (define-instruction fsubp-sti (segment destination) (:printer floating-point-fp ((op '(#b110 #b101))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fsubp) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011110) (emit-fp-op segment destination #b101))) ;;; ;;; Subtract double, reverse, destination st(i) ;;; st(i) = st(0) - st(i) ;;; ASM386 syntax : FSUBR ST(i ) , ST ;;; Gdb syntax: fsub %st,%st(i) ;;; (define-instruction fsubr-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b100))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fsubr) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b100))) ;;; With a pop (define-instruction fsubrp-sti (segment destination) (:printer floating-point-fp ((op '(#b110 #b100))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fsubrp) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011110) (emit-fp-op segment destination #b100))) ;;; ;;; Multiply single ;;; st(0) = st(0) * memory or st(i) ;;; (define-instruction fmul (segment source) (:printer floating-point ((op '(#b000 #b001)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b001))) ;;; ;;; Multiply double ;;; st(0) = st(0) * memory or st(i) ;;; (define-instruction fmuld (segment source) (:printer floating-point ((op '(#b100 #b001)))) (:printer floating-point-fp ((op '(#b000 #b001)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b001))) ;;; ;;; Multiply double, destination st(i) ;;; st(i) = st(i) * st(0) ;;; (define-instruction fmul-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b001))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fmul) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b001))) ;;; ;;; Divide single ;;; st(0) = st(0) / memory or st(i) ;;; (define-instruction fdiv (segment source) (:printer floating-point ((op '(#b000 #b110)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b110))) ;;; ;;; Divide single, reverse ;;; st(0) = memory or st(i) / st(0) ;;; (define-instruction fdivr (segment source) (:printer floating-point ((op '(#b000 #b111)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b111))) ;;; ;;; Divide double ;;; st(0) = st(0) / memory or st(i) ;;; (define-instruction fdivd (segment source) (:printer floating-point ((op '(#b100 #b110)))) (:printer floating-point-fp ((op '(#b000 #b110)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b110))) ;;; ;;; Divide double, reverse ;;; st(0) = memory or st(i) / st(0) ;;; (define-instruction fdivrd (segment source) (:printer floating-point ((op '(#b100 #b111)))) (:printer floating-point-fp ((op '(#b000 #b111)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b111))) ;;; ;;; Divide double, destination st(i) ;;; st(i) = st(i) / st(0) ;;; ASM386 syntax : FDIV ST(i ) , ST ;;; Gdb syntax: fdivr %st,%st(i) ;;; (define-instruction fdiv-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b111))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fdiv) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b111))) ;;; ;;; Divide double, reverse, destination st(i) ;;; st(i) = st(0) / st(i) ;;; ASM386 syntax : FDIVR ST(i ) , ST ;;; Gdb syntax: fdiv %st,%st(i) ;;; (define-instruction fdivr-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b110))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fdivr) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b110))) ;;; ;;; exchange fr0 with fr(n). no double variant ;;; (define-instruction fxch (segment source) (:printer floating-point-fp ((op '(#b001 #b001)))) (:emitter (unless (and (tn-p source) (eq (sb-name (sc-sb (tn-sc source))) 'float-registers)) (lisp:break)) (emit-byte segment #b11011001) (emit-fp-op segment source #b001))) ;;; ;;; push 32 - bit integer to st0 ;;; (define-instruction fild (segment source) (:printer floating-point ((op '(#b011 #b000)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment source #b000))) ;;; push 64 - bit integer to st0 ;;; (define-instruction fildl (segment source) (:printer floating-point ((op '(#b111 #b101)))) (:emitter (emit-byte segment #b11011111) (emit-fp-op segment source #b101))) ;;; store 32 - bit integer ;;; (define-instruction fist (segment dest) (:printer floating-point ((op '(#b011 #b010)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment dest #b010))) ;;; Store and pop 32 - bit integer ;;; (define-instruction fistp (segment dest) (:printer floating-point ((op '(#b011 #b011)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment dest #b011))) ;;; Store and pop 64 - bit integer ;;; (define-instruction fistpl (segment dest) (:printer floating-point ((op '(#b111 #b111)))) (:emitter (emit-byte segment #b11011111) (emit-fp-op segment dest #b111))) ;;; store single from st(0 ) and pop ;;; (define-instruction fstp (segment dest) (:printer floating-point ((op '(#b001 #b011)))) (:emitter (cond ((fp-reg-tn-p dest) (emit-byte segment #b11011101) (emit-fp-op segment dest #b011)) (t (emit-byte segment #b11011001) (emit-fp-op segment dest #b011))))) ;;; store double from st(0 ) and pop ;;; (define-instruction fstpd (segment dest) (:printer floating-point ((op '(#b101 #b011)))) (:printer floating-point-fp ((op '(#b101 #b011)))) (:emitter (cond ((fp-reg-tn-p dest) (emit-byte segment #b11011101) (emit-fp-op segment dest #b011)) (t (emit-byte segment #b11011101) (emit-fp-op segment dest #b011))))) ;;; ;;; store long from st(0) and pop ;;; (define-instruction fstpl (segment dest) (:printer floating-point ((op '(#b011 #b111)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment dest #b111))) ;;; ;;; decrement stack-top pointer ;;; (define-instruction fdecstp (segment) (:printer floating-point-no ((op #b10110))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110110))) ;;; ;;; increment stack-top pointer ;;; (define-instruction fincstp (segment) (:printer floating-point-no ((op #b10111))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110111))) ;;; ;;; free fp register ;;; (define-instruction ffree (segment dest) (:printer floating-point-fp ((op '(#b101 #b000)))) (:emitter (emit-byte segment #b11011101) (emit-fp-op segment dest #b000))) ;;; ;;; Free fp register and pop the stack. ;;; (define-instruction ffreep (segment dest) (:printer floating-point-fp ((op '(#b111 #b000)))) (:emitter (emit-byte segment #b11011111) (emit-fp-op segment dest #b000))) (define-instruction fabs (segment) (:printer floating-point-no ((op #b00001))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11100001))) (define-instruction fchs (segment) (:printer floating-point-no ((op #b00000))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11100000))) (define-instruction frndint(segment) (:printer floating-point-no ((op #b11100))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111100))) ;;; Initialize ;;; (define-instruction fninit(segment) (:printer floating-point-5 ((op #b00011))) (:emitter (emit-byte segment #b11011011) (emit-byte segment #b11100011))) ;;; Store Status Word to AX ;;; (define-instruction fnstsw(segment) (:printer floating-point-st ((op #b00000))) (:emitter (emit-byte segment #b11011111) (emit-byte segment #b11100000))) ;;; ;;; Load Control Word ;;; ;;; src must be a memory location (define-instruction fldcw(segment src) (:printer floating-point ((op '(#b001 #b101)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment src #b101))) ;;; ;;; Store Control Word ;;; (define-instruction fnstcw(segment dst) (:printer floating-point ((op '(#b001 #b111)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment dst #b111))) ;;; Store FP Environment ;;; (define-instruction fstenv(segment dst) (:printer floating-point ((op '(#b001 #b110)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment dst #b110))) ;;; Retore FP Environment ;;; (define-instruction fldenv(segment src) (:printer floating-point ((op '(#b001 #b100)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment src #b100))) ;;; Save FP State ;;; (define-instruction fsave(segment dst) (:printer floating-point ((op '(#b101 #b110)))) (:emitter (emit-byte segment #b11011101) (emit-fp-op segment dst #b110))) ;;; Restore FP State ;;; (define-instruction frstor (segment src) (:printer floating-point ((op '(#b101 #b100)))) (:emitter (emit-byte segment #b11011101) (emit-fp-op segment src #b100))) ;;; ;;; Clear exceptions ;;; (define-instruction fnclex (segment) (:printer floating-point-5 ((op #b00010))) (:emitter (emit-byte segment #b11011011) (emit-byte segment #b11100010))) ;;; Comparison ;;; (define-instruction fcom (segment src) (:printer floating-point ((op '(#b000 #b010)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment src #b010))) (define-instruction fcomd (segment src) (:printer floating-point ((op '(#b100 #b010)))) (:printer floating-point-fp ((op '(#b000 #b010)))) (:emitter (if (fp-reg-tn-p src) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment src #b010))) to ST0 , popping the stack twice . (define-instruction fcompp (segment) (:printer floating-point-3 ((op '(#b110 #b011001)))) (:emitter (emit-byte segment #b11011110) (emit-byte segment #b11011001))) ;;; Compare ST(i ) to ST0 and update the flags . ;;; Intel syntax : FCOMI ST , ST(i ) ;;; (define-instruction fcomi (segment src) (:printer floating-point-fp ((op '(#b011 #b110)))) (:emitter (assert (fp-reg-tn-p src)) (emit-byte segment #b11011011) (emit-fp-op segment src #b110))) ;;; ;;; Unordered comparison ;;; (define-instruction fucom (segment src) (:printer floating-point-fp ((op '(#b101 #b100)))) (:emitter (assert (fp-reg-tn-p src)) (emit-byte segment #b11011101) (emit-fp-op segment src #b100))) ;;; Unordered compare ST(i ) to ST0 and update the flags . ;;; Intel syntax : FUCOMI ST , ST(i ) ;;; (define-instruction fucomi (segment src) (:printer floating-point-fp ((op '(#b011 #b101)))) (:emitter (assert (fp-reg-tn-p src)) (emit-byte segment #b11011011) (emit-fp-op segment src #b101))) (define-instruction ftst (segment) (:printer floating-point-no ((op #b00100))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11100100))) Compare and move ST(i ) to ST0 . ;;; Intel syntal : FCMOVcc ST , ST(i ) ;;; (define-instruction fcmov (segment cond src) #+nil (:printer floating-point ((op '(#b01? #b???)))) (:emitter (assert (fp-reg-tn-p src)) (emit-byte segment (ecase cond ((:b :e :be :u) #b11011010) ((:nb :ne :nbe :nu) #b11011011))) (emit-fp-op segment src (ecase cond ((:b :nb) #b000) ((:e :ne) #b000) ((:be :nbe) #b000) ((:u nu) #b000))))) ;;; 80387 Specials ;;; ;;; (define-instruction fsqrt (segment) (:printer floating-point-no ((op #b11010))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111010))) (define-instruction fscale (segment) (:printer floating-point-no ((op #b11101))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111101))) (define-instruction fxtract (segment) (:printer floating-point-no ((op #b10100))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110100))) (define-instruction fsin (segment) (:printer floating-point-no ((op #b11110))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111110))) (define-instruction fcos (segment) (:printer floating-point-no ((op #b11111))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111111))) (define-instruction fprem1 (segment) (:printer floating-point-no ((op #b10101))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110101))) (define-instruction fprem (segment) (:printer floating-point-no ((op #b11000))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111000))) (define-instruction fxam (segment) (:printer floating-point-no ((op #b00101))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11100101))) ;;; These do push/pop to stack and need special handling ;;; in any VOPs that use them. See the book. ;; st0 <- st1*log2(st0) POPS STACK (:printer floating-point-no ((op #b10001))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110001))) (define-instruction fyl2xp1 (segment) (:printer floating-point-no ((op #b11001))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111001))) (define-instruction f2xm1 (segment) (:printer floating-point-no ((op #b10000))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110000))) (define-instruction fptan (segment) ; st(0) <- 1; st(1) <- tan (:printer floating-point-no ((op #b10010))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110010))) POPS STACK (:printer floating-point-no ((op #b10011))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110011))) ;;; load constant (define-instruction fldz (segment) (:printer floating-point-no ((op #b01110))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101110))) (define-instruction fld1 (segment) (:printer floating-point-no ((op #b01000))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101000))) (define-instruction fldpi (segment) (:printer floating-point-no ((op #b01011))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101011))) (define-instruction fldl2t (segment) (:printer floating-point-no ((op #b01001))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101001))) (define-instruction fldl2e (segment) (:printer floating-point-no ((op #b01010))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101010))) (define-instruction fldlg2 (segment) (:printer floating-point-no ((op #b01100))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101100))) (define-instruction fldln2 (segment) (:printer floating-point-no ((op #b01101))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101101)))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/amd64/insts.lisp
lisp
Syntax : Common - Lisp ; Base : 10 ; Package : x86 -*- ********************************************************************** ********************************************************************** Description of the AMD64 instruction set. Primitive emitters. The effective-address (ea) structure. don't allow constant ea Using RBP or R13 without a displacement must be done via mod = 01 with a displacement don't allow absolute fixup thing is an ea constant addresses are bad we shouldn't have absolute fixup's here Disassembler support stuff. plus should do some source-var notes Value is a list of (BASE-REG OFFSET INDEX-REG INDEX-SCALE) Print an element of the address, maybe with a leading separator. Same as print-reg/mem, but prints an explicit size indicator for memory references. Returns either an integer, meaning a register, or a list of (BASE-REG OFFSET INDEX-REG INDEX-SCALE), where any component may be missing or nil to indicate that it's not used or has the registers sib byte (= mod #b10) This is a sort of bogus prefilter that just stores the info globally for other people to use; it probably never gets printed. set by a prefix instruction reset it always nil anyway eval-when always nil anyway always nil anyway always nil anyway always nil anyway always nil anyway always nil anyway Same as reg/mem, but prints an explicit size indicator for memory references. just return it set by a prefix instruction Disassembler instruction formats. optional fields optional fields Same as simple, but with direction bit Same as simple, but with the immediate value occuring by default, and with an appropiate printer. optional fields adds a width field to reg-no-width optional fields Same as reg, but with direction bit optional fields optional fields Same as reg/mem, but with the immediate value occuring by default, and with an appropiate printer. Same as reg/mem, but with using the accumulator in the default printer don't need a size optional fields optional fields ---------------------------------------------------------------- regular fp inst to/from registers/memory fp no operand isns ---------------------------------------------------------------- not sure what this is for This isn't a really an instruction, but it's easier to deal with it this way. We assume that it's actually used. don't actually print it immediate to register absolute mem to/from accumulator register to/from register/memory immediate to register/memory integer -> register absolute ea -> rax #xA1 ea -> other register #x8b dst is not register rax -> constant address constant -> ea register -> ea fixup -> ea is not allowed Use this if we don't want indirect for fixup imm64 byte -> word this needs to be looked at dest size is qword Register. Immediate. We cannot interpret a fixup as an immediate qword to push push doesn't need a rex size prefix pop doesn't need rex size prefix Register with accumulator. load effective address Flag control instructions. CLD -- Clear Direction Flag. CLI -- Clear Iterrupt Enable Flag. POPF -- Pop flags. PUSHF -- push flags. STI -- Set Interrupt Enable Flag. Arithmetic Register. Note that #x40 can't be used now. Register. Note that #x48 can't be used now. CBW -- Convert Byte to Word. AX <- sign_xtnd(AL) String manipulation. move data from string to string Bit Manipulation Bit Test (BT) instructions Ignoring the case with a src as a register, we have 0F A3 reg/mem BT 0F BB reg/mem BTC 0F B3 reg/mem So the pattern is 10xxx011 The instruction format is then (little-endian) |reg/mem|10ooo011|00001111 optional fields Control transfer. long, so we fake it by using a prefilter to read the offset. always nil anyway long, so we fake it by using a prefilter to read the address. always nil anyway conditional jumps unconditional jumps Conditional move. Conditional byte set. Interrupt instructions. Single byte instruction with an immediate byte argument. the length byte read-time-stamp instruction, that counts executed cycles, present Processor control Random hackery ---------------------------------------------------------------- we treat the single-precision and double-precision variants as separate instructions load single to st(0) load double to st(0) load long to st(0) the confusion I've added comments showing the mathamatical instruction syntax is: Fop Source fdiv instructions inducated by an 'R' suffix. The mathematical operation for the non-reverse form is always: destination = destination op source For the reversed form it is: destination = source op destination usually the source. I've hack in extra instructions to implement the fops with a ST(i) destination, these have a -sti suffix and Add single st(0) = st(0) + memory or st(i) Add double st(0) = st(0) + memory or st(i) Add double destination st(i) st(i) = st(0) + st(i) With pop Subtract single st(0) = st(0) - memory or st(i) Subtract single, reverse st(0) = memory or st(i) - st(0) Subtract double st(0) = st(0) - memory or st(i) Subtract double, reverse st(0) = memory or st(i) - st(0) Subtract double, destination st(i) st(i) = st(i) - st(0) Gdb syntax: fsubr %st,%st(i) With a pop Subtract double, reverse, destination st(i) st(i) = st(0) - st(i) Gdb syntax: fsub %st,%st(i) With a pop Multiply single st(0) = st(0) * memory or st(i) Multiply double st(0) = st(0) * memory or st(i) Multiply double, destination st(i) st(i) = st(i) * st(0) Divide single st(0) = st(0) / memory or st(i) Divide single, reverse st(0) = memory or st(i) / st(0) Divide double st(0) = st(0) / memory or st(i) Divide double, reverse st(0) = memory or st(i) / st(0) Divide double, destination st(i) st(i) = st(i) / st(0) Gdb syntax: fdivr %st,%st(i) Divide double, reverse, destination st(i) st(i) = st(0) / st(i) Gdb syntax: fdiv %st,%st(i) exchange fr0 with fr(n). no double variant store long from st(0) and pop decrement stack-top pointer increment stack-top pointer free fp register Free fp register and pop the stack. Load Control Word src must be a memory location Store Control Word Clear exceptions Unordered comparison These do push/pop to stack and need special handling in any VOPs that use them. See the book. st0 <- st1*log2(st0) st(0) <- 1; st(1) <- tan load constant
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . If you want to use this code or any part of CMU Common Lisp , please contact or . (ext:file-comment "$Header: src/compiler/amd64/insts.lisp $") Written by by Spring / Summer 1995 . Debugging and enhancements by 1996 , 1997 , 1998 . AMD64 port by . (in-package :amd64) (use-package :new-assem) (def-assembler-params :scheduler-p nil) (disassem:set-disassem-params :instruction-alignment 8 :opcode-column-width 8) (define-emitter emit-word 16 (byte 16 0)) (define-emitter emit-dword 32 (byte 32 0)) (define-emitter emit-qword 64 (byte 64 0)) (define-emitter emit-byte-with-reg 8 (byte 5 3) (byte 3 0)) (define-emitter emit-mod-reg-r/m-byte 8 (byte 2 6) (byte 3 3) (byte 3 0)) (define-emitter emit-sib-byte 8 (byte 2 6) (byte 3 3) (byte 3 0)) (define-emitter emit-rex-prefix 8 (byte 4 4) (byte 1 3) (byte 1 2) (byte 1 1) (byte 1 0)) Fixup emitters . (defun emit-absolute-fixup (segment fixup) absolute fixup should always be 64 bit . (note-fixup segment :absolute fixup) (let ((offset (fixup-offset fixup))) (if (label-p offset) (emit-back-patch segment 8 #'(lambda (segment posn) (declare (ignore posn)) (emit-qword segment (- (+ (component-header-length) (or (label-position offset) 0)) other-pointer-type)))) (emit-qword segment (or offset 0))))) (defun emit-relative-fixup (segment fixup) (note-fixup segment :relative fixup) (emit-dword segment (or (fixup-offset fixup) 0))) (defun reg-tn-encoding (tn) (declare (type tn tn)) (assert (eq (sb-name (sc-sb (tn-sc tn))) 'registers)) (let ((offset (tn-offset tn))) (logior (ash (logand offset 1) 2) (ash offset -1)))) (defstruct (ea (:constructor make-ea (size &key base index scale disp)) (:print-function %print-ea)) (size nil :type (member :byte :word :dword :qword)) (base nil :type (or tn null)) (index nil :type (or tn null)) (scale 1 :type (member 1 2 4 8)) (disp 0 :type (or (signed-byte 32) fixup))) (defun valid-displacement-p (x) (typep x '(or (signed-byte 32) fixup))) (defun %print-ea (ea stream depth) (declare (ignore depth)) (cond ((or *print-escape* *print-readably*) (print-unreadable-object (ea stream :type t) (format stream "~S~@[ base=~S~]~@[ index=~S~]~@[ scale=~S~]~@[ disp=~S~]" (ea-size ea) (ea-base ea) (ea-index ea) (let ((scale (ea-scale ea))) (if (= scale 1) nil scale)) (ea-disp ea)))) (t (format stream "~A PTR [" (symbol-name (ea-size ea))) (when (ea-base ea) (write-string (amd64-location-print-name (ea-base ea)) stream) (when (ea-index ea) (write-string "+" stream))) (when (ea-index ea) (write-string (amd64-location-print-name (ea-index ea)) stream)) (unless (= (ea-scale ea) 1) (format stream "*~A" (ea-scale ea))) (typecase (ea-disp ea) (null) (integer (format stream "~@D" (ea-disp ea))) (t (format stream "+~A" (ea-disp ea)))) (write-char #\] stream)))) (defun absolute-ea-p (ea) (and (ea-p ea) (eq (ea-size ea) :qword) (null (ea-base ea)) (null (ea-index ea)) (= (ea-scale ea) 1))) (defun emit-absolute-ea (segment ea) (assert (absolute-ea-p ea)) (emit-qword segment (ea-disp ea))) (defun emit-ea (segment thing reg) (etypecase thing (tn (ecase (sb-name (sc-sb (tn-sc thing))) (registers (emit-mod-reg-r/m-byte segment #b11 reg (reg-lower-3-bits thing))) (stack Convert stack tns into an index off of RBP . (let ((disp (- (* (1+ (tn-offset thing)) word-bytes)))) (cond ((< -128 disp 127) (emit-mod-reg-r/m-byte segment #b01 reg #b101) (emit-byte segment disp)) (t (emit-mod-reg-r/m-byte segment #b10 reg #b101) (emit-dword segment disp))))) )) (ea (let* ((base (ea-base thing)) (index (ea-index thing)) (scale (ea-scale thing)) (disp (ea-disp thing)) (mod (cond ((or (null base) of 0 (and (eql disp 0) (not (= (reg-lower-3-bits base) #b101)))) #b00) ((and (fixnump disp) (<= -128 disp 127)) #b01) (t #b10))) (r/m (cond (index #b100) ((null base) #b101) (t (reg-lower-3-bits base))))) (emit-mod-reg-r/m-byte segment mod reg r/m) SIB byte is also required for R12 - based addressing (when (= r/m #b100) (let ((ss (1- (integer-length scale))) (index (if (null index) #b100 (if (= (reg-tn-encoding index) #b100) (error "Can't index off of RSP") (reg-lower-3-bits index)))) (base (if (null base) #b101 (reg-lower-3-bits base)))) (emit-sib-byte segment ss index base))) (cond ((= mod #b01) (emit-byte segment disp)) ((or (= mod #b10) (null base)) (if (fixup-p disp) (emit-absolute-fixup segment disp) (emit-dword segment disp)))))) )) (defun fp-reg-tn-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'float-registers))) like the above , but for fp - instructions -- jrd (defun emit-fp-op (segment thing op) (if (fp-reg-tn-p thing) (emit-byte segment (dpb op (byte 3 3) (dpb (tn-offset thing) (byte 3 0) #b11000000))) (emit-ea segment thing op))) (defun byte-reg-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers) (member (sc-name (tn-sc thing)) byte-sc-names) t)) (defun byte-ea-p (thing) (typecase thing (ea (eq (ea-size thing) :byte)) (tn (and (member (sc-name (tn-sc thing)) byte-sc-names) t)) (t nil))) (defun word-reg-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers) (member (sc-name (tn-sc thing)) word-sc-names) t)) (defun word-ea-p (thing) (typecase thing (ea (eq (ea-size thing) :word)) (tn (and (member (sc-name (tn-sc thing)) word-sc-names) t)) (t nil))) (defun dword-reg-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers) (member (sc-name (tn-sc thing)) dword-sc-names) t)) (defun dword-ea-p (thing) (typecase thing (ea (eq (ea-size thing) :dword)) (tn (and (member (sc-name (tn-sc thing)) dword-sc-names) t)) (t nil))) (defun qword-reg-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers) (member (sc-name (tn-sc thing)) qword-sc-names) t)) (defun register-p (thing) (and (tn-p thing) (eq (sb-name (sc-sb (tn-sc thing))) 'registers))) (defun accumulator-p (thing) (and (register-p thing) (= (tn-offset thing) 0))) (eval-when (compile load eval) (defconstant conditions '((:o . 0) (:no . 1) (:b . 2) (:nae . 2) (:c . 2) (:nb . 3) (:ae . 3) (:nc . 3) (:eq . 4) (:e . 4) (:z . 4) (:ne . 5) (:nz . 5) (:be . 6) (:na . 6) (:nbe . 7) (:a . 7) (:s . 8) (:ns . 9) (:p . 10) (:pe . 10) (:np . 11) (:po . 11) (:l . 12) (:nge . 12) (:nl . 13) (:ge . 13) (:le . 14) (:ng . 14) (:nle . 15) (:g . 15))) (defun conditional-opcode (condition) (cdr (assoc condition conditions :test #'eq)))) Utilities . #-lispworks3 (defconstant operand-size-prefix-byte #b01100110) #+lispworks3 (eval-when (compile load eval) (defconstant operand-size-prefix-byte #b01100110)) (defparameter *default-operand-size* :dword) (defun maybe-emit-operand-size-prefix (segment size &optional (default-operand-size *default-operand-size*)) (when (and (not (eq size default-operand-size)) (eq size :word)) (emit-byte segment operand-size-prefix-byte))) (defun maybe-emit-rex-prefix (segment size modrm-reg sib-index reg/modrm-rm/base) (when (or (eq size :qword) (and modrm-reg (> (reg-tn-encoding modrm-reg) 7)) (and sib-index (> (reg-tn-encoding sib-index) 7)) (and reg/modrm-rm/base (> (reg-tn-encoding reg/modrm-rm/base) 7))) (emit-rex-prefix segment #b0100 (if (eq size :qword) 1 0) (if (and modrm-reg (> (reg-tn-encoding modrm-reg) 7)) 1 0) (if (and sib-index (> (reg-tn-encoding sib-index) 7)) 1 0) (if (and reg/modrm-rm/base (> (reg-tn-encoding reg/modrm-rm/base) 7)) 1 0)))) (defun maybe-emit-ea-rex-prefix (segment size thing reg) (etypecase thing (tn (ecase (sb-name (sc-sb (tn-sc thing))) (registers (maybe-emit-rex-prefix segment size reg nil thing)) (stack (maybe-emit-rex-prefix segment size reg nil nil)) )) (ea (maybe-emit-rex-prefix segment size reg (ea-index thing) (ea-base thing))) )) (defun operand-size (thing) (typecase thing (tn (case (sc-name (tn-sc thing)) (#.qword-sc-names :qword) (#.dword-sc-names :dword) (#.word-sc-names :word) (#.byte-sc-names :byte) added by jrd . float - registers is a separate size ( ? ) (#.float-sc-names :float) (#.double-sc-names :double) (t (error "Can't tell the size of ~S ~S" thing (sc-name (tn-sc thing)))))) (ea (ea-size thing)) (t nil))) (defun matching-operand-size (dst src) (let ((dst-size (operand-size dst)) (src-size (operand-size src))) (if dst-size (if src-size (if (eq dst-size src-size) dst-size (error "Size mismatch: ~S is a ~S and ~S is a ~S" dst dst-size src src-size)) dst-size) (if src-size src-size (error "Can't tell the size of either ~S or ~S." dst src))))) (defun emit-sized-immediate (segment size value &optional allow-qword) (ecase size (:byte (emit-byte segment value)) (:word (emit-word segment value)) (:dword (emit-dword segment value)) (:qword (if allow-qword (emit-qword segment value) most instructions only allow 32 bit immediates (progn (assert (<= (integer-length value) 32)) (emit-dword segment value)))))) (deftype reg () '(unsigned-byte 3)) #+cross-compiler (lisp:deftype reg () '(unsigned-byte 3)) (eval-when (compile eval load) (defparameter *default-address-size* Actually , : is the only one really supported . :qword) (defparameter byte-reg-names #(al cl dl bl ah ch dh bh)) (defparameter word-reg-names #(ax cx dx bx sp bp si di r8w r9w r10w r11w r12w r13w r14w r15w)) (defparameter dword-reg-names #(eax ecx edx ebx esp ebp esi edi r8d r9d r10d r11d r12d r13d r14d r15d)) (defparameter qword-reg-names #(rax rcx rdx rbx rsp rbp rsi rdi r9 r10 r11 r12 r13 r14 r15)) (defun print-reg-with-width (value width stream dstate) (declare (ignore dstate)) (princ (aref (ecase width (:byte byte-reg-names) (:word word-reg-names) (:dword dword-reg-names) (:qword qword-reg-names)) value) stream) ) (defun print-reg (value stream dstate) (declare (type reg value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg-with-width value (disassem:dstate-get-prop dstate 'width) stream dstate)) (defun print-word-reg (value stream dstate) (declare (type reg value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg-with-width value (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*) stream dstate)) (defun print-byte-reg (value stream dstate) (declare (type reg value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg-with-width value :byte stream dstate)) (defun print-addr-reg (value stream dstate) (declare (type reg value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg-with-width value *default-address-size* stream dstate)) (defun print-mem-access (value stream print-size-p dstate) (declare (type list value) (type stream stream) (type (member t nil) print-size-p) (type disassem:disassem-state dstate)) (when print-size-p (princ (disassem:dstate-get-prop dstate 'width) stream) (princ '| PTR | stream)) (write-char #\[ stream) (let ((firstp t)) (macrolet ((pel ((var val) &body body) `(let ((,var ,val)) (when ,var (unless firstp (write-char #\+ stream)) ,@body (setq firstp nil))))) (pel (base-reg (first value)) (print-addr-reg base-reg stream dstate)) (pel (index-reg (third value)) (print-addr-reg index-reg stream dstate) (let ((index-scale (fourth value))) (when (and index-scale (not (= index-scale 1))) (write-char #\* stream) (princ index-scale stream)))) (let ((offset (second value))) (when (and offset (or firstp (not (zerop offset)))) (unless (or firstp (minusp offset)) (write-char #\+ stream)) (if firstp (let ((unsigned-offset (if (minusp offset) (+ #x100000000 offset) offset))) (disassem:princ16 unsigned-offset stream) (or (nth-value 1 (disassem::note-code-constant-absolute unsigned-offset dstate)) (disassem:maybe-note-assembler-routine unsigned-offset stream dstate) (let ((offs (- offset disassem::nil-addr))) (when (typep offs 'disassem::offset) (or (disassem::maybe-note-nil-indexed-symbol-slot-ref offs dstate) (disassem::maybe-note-static-function offs dstate)))))) (princ offset stream)))))) (write-char #\] stream)) (defun print-imm-data (value stream dstate) (let ((offset (- value disassem::nil-addr))) (if (zerop offset) (format stream "#x~X" value) (format stream "~A" value)) (when (typep offset 'disassem::offset) (or (disassem::maybe-note-nil-indexed-object offset dstate) (let ((unsigned-offset (if (and (numberp value) (minusp value)) (+ value #x100000000) value))) (disassem::maybe-note-assembler-routine unsigned-offset stream dstate)) (nth-value 1 (disassem::note-code-constant-absolute offset dstate)))))) (defun print-reg/mem (value stream dstate) (declare (type (or list reg) value) (type stream stream) (type disassem:disassem-state dstate)) (if (typep value 'reg) (print-reg value stream dstate) (print-mem-access value stream nil dstate))) (defun print-sized-reg/mem (value stream dstate) (declare (type (or list reg) value) (type stream stream) (type disassem:disassem-state dstate)) (if (typep value 'reg) (print-reg value stream dstate) (print-mem-access value stream t dstate))) (defun print-byte-reg/mem (value stream dstate) (declare (type (or list reg) value) (type stream stream) (type disassem:disassem-state dstate)) (if (typep value 'reg) (print-byte-reg value stream dstate) (print-mem-access value stream t dstate))) (defun print-label (value stream dstate) (declare (ignore dstate)) (disassem:princ16 value stream)) obvious default value ( e.g. , 1 for the index - scale ) . (defun prefilter-reg/mem (value dstate) (declare (type list value) (type disassem:disassem-state dstate)) (let ((mod (car value)) (r/m (cadr value))) (declare (type (unsigned-byte 2) mod) (type (unsigned-byte 3) r/m)) (cond ((= mod #b11) r/m) ((= r/m #b100) (let ((sib (disassem:read-suffix 8 dstate))) (declare (type (unsigned-byte 8) sib)) (let ((base-reg (ldb (byte 3 0) sib)) (index-reg (ldb (byte 3 3) sib)) (index-scale (ldb (byte 2 6) sib))) (declare (type (unsigned-byte 3) base-reg index-reg) (type (unsigned-byte 2) index-scale)) (let* ((offset (case mod (#b00 (if (= base-reg #b101) (disassem:read-signed-suffix 32 dstate) nil)) (#b01 (disassem:read-signed-suffix 8 dstate)) (#b10 (disassem:read-signed-suffix 32 dstate))))) (list (if (and (= mod #b00) (= base-reg #b101)) nil base-reg) offset (if (= index-reg #b100) nil index-reg) (ash 1 index-scale)))))) ((and (= mod #b00) (= r/m #b101)) (list nil (disassem:read-signed-suffix 32 dstate)) ) ((= mod #b00) (list r/m)) ((= mod #b01) (list r/m (disassem:read-signed-suffix 8 dstate))) (list r/m (disassem:read-signed-suffix 32 dstate)))))) (defun prefilter-width (value dstate) (setf (disassem:dstate-get-prop dstate 'width) (if (zerop value) :byte (let ((word-width (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*))) (when (not (eql word-width *default-operand-size*)) (setf (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*)) word-width)))) (defun offset-next (value dstate) (declare (type integer value) (type disassem:disassem-state dstate)) (+ (disassem:dstate-next-addr dstate) value)) (defun read-address (value dstate) (disassem:read-suffix (width-bits *default-address-size*) dstate)) (defun width-bits (width) (ecase width (:byte 8) (:word 16) (:dword 32) (:qword 64) (:float 32) (:double 64))) argument types . (disassem:define-argument-type accum :printer #'(lambda (value stream dstate) (declare (ignore value) (type stream stream) (type disassem:disassem-state dstate)) (print-reg 0 stream dstate)) ) (disassem:define-argument-type word-accum :printer #'(lambda (value stream dstate) (declare (ignore value) (type stream stream) (type disassem:disassem-state dstate)) (print-word-reg 0 stream dstate)) ) (disassem:define-argument-type reg :printer #'print-reg) (disassem:define-argument-type addr-reg :printer #'print-addr-reg) (disassem:define-argument-type word-reg :printer #'print-word-reg) (disassem:define-argument-type imm-addr :prefilter #'read-address :printer #'print-label) (disassem:define-argument-type imm-data :prefilter #'(lambda (value dstate) (disassem:read-suffix (width-bits (disassem:dstate-get-prop dstate 'width)) dstate)) :printer #'print-imm-data ) (disassem:define-argument-type signed-imm-data :prefilter #'(lambda (value dstate) (let ((width (disassem:dstate-get-prop dstate 'width))) (disassem:read-signed-suffix (width-bits width) dstate))) ) (disassem:define-argument-type signed-imm-byte :prefilter #'(lambda (value dstate) (disassem:read-signed-suffix 8 dstate))) (disassem:define-argument-type signed-imm-dword :prefilter #'(lambda (value dstate) (disassem:read-signed-suffix 32 dstate))) (disassem:define-argument-type imm-word :prefilter #'(lambda (value dstate) (let ((width (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*))) (disassem:read-suffix (width-bits width) dstate)))) Needed for the ret imm16 instruction (disassem:define-argument-type imm-word-16 :prefilter #'(lambda (value dstate) (disassem:read-suffix 16 dstate))) (disassem:define-argument-type reg/mem :prefilter #'prefilter-reg/mem :printer #'print-reg/mem) (disassem:define-argument-type sized-reg/mem :prefilter #'prefilter-reg/mem :printer #'print-sized-reg/mem) (disassem:define-argument-type byte-reg/mem :prefilter #'prefilter-reg/mem :printer #'print-byte-reg/mem) added by jrd (eval-when (compile load eval) (defun print-fp-reg (value stream dstate) (declare (ignore dstate)) (format stream "~A(~D)" 'st value)) (defun prefilter-fp-reg (value dstate) (declare (ignore dstate)) value) ) (disassem:define-argument-type fp-reg :prefilter #'prefilter-fp-reg :printer #'print-fp-reg) (disassem:define-argument-type width :prefilter #'prefilter-width :printer #'(lambda (value stream dstate) ( zerop value ) zzz jrd (princ 'b stream) (let ((word-width (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*))) (princ (schar (symbol-name word-width) 0) stream))))) (eval-when (compile eval) (defun swap-if (direction field1 separator field2) `(:if (,direction :constant 0) (,field1 ,separator ,field2) (,field2 ,separator ,field1)))) (disassem:define-instruction-format (byte 8 :default-printer '(:name)) (op :field (byte 8 0)) (accum :type 'accum) (imm)) (disassem:define-instruction-format (simple 8) (op :field (byte 7 1)) (width :field (byte 1 0) :type 'width) (accum :type 'accum) (imm)) (disassem:define-instruction-format (simple-dir 8 :include 'simple) (op :field (byte 6 2)) (dir :field (byte 1 1))) (disassem:define-instruction-format (accum-imm 8 :include 'simple :default-printer '(:name :tab accum ", " imm)) (imm :type 'imm-data)) (disassem:define-instruction-format (reg-no-width 8 :default-printer '(:name :tab reg)) (op :field (byte 5 3)) (reg :field (byte 3 0) :type 'word-reg) (accum :type 'word-accum) (imm)) (disassem:define-instruction-format (reg 8 :default-printer '(:name :tab reg)) (op :field (byte 4 4)) (width :field (byte 1 3) :type 'width) (reg :field (byte 3 0) :type 'reg) (accum :type 'accum) (imm) ) (disassem:define-instruction-format (reg-dir 8 :include 'reg) (op :field (byte 3 5)) (dir :field (byte 1 4))) (disassem:define-instruction-format (two-bytes 16 :default-printer '(:name)) (op :fields (list (byte 8 0) (byte 8 8)))) (disassem:define-instruction-format (reg-reg/mem 16 :default-printer `(:name :tab reg ", " reg/mem)) (op :field (byte 7 1)) (width :field (byte 1 0) :type 'width) (reg/mem :fields (list (byte 2 14) (byte 3 8)) :type 'reg/mem) (reg :field (byte 3 11) :type 'reg) (imm)) same as reg - reg / mem , but with direction bit (disassem:define-instruction-format (reg-reg/mem-dir 16 :include 'reg-reg/mem :default-printer `(:name :tab ,(swap-if 'dir 'reg/mem ", " 'reg))) (op :field (byte 6 2)) (dir :field (byte 1 1))) Same as reg - rem / mem , but uses the reg field as a second op code . (disassem:define-instruction-format (reg/mem 16 :default-printer '(:name :tab reg/mem)) (op :fields (list (byte 7 1) (byte 3 11))) (width :field (byte 1 0) :type 'width) (reg/mem :fields (list (byte 2 14) (byte 3 8)) :type 'sized-reg/mem) (imm)) (disassem:define-instruction-format (reg/mem-imm 16 :include 'reg/mem :default-printer '(:name :tab reg/mem ", " imm)) (reg/mem :type 'sized-reg/mem) (imm :type 'imm-data)) (disassem:define-instruction-format (accum-reg/mem 16 :include 'reg/mem :default-printer '(:name :tab accum ", " reg/mem)) (accum :type 'accum)) Same as reg - reg / mem , but with a prefix of # b00001111 (disassem:define-instruction-format (ext-reg-reg/mem 24 :default-printer `(:name :tab reg ", " reg/mem)) (prefix :field (byte 8 0) :value #b00001111) (op :field (byte 7 9)) (width :field (byte 1 8) :type 'width) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'reg/mem) (reg :field (byte 3 19) :type 'reg) (imm)) Same as reg / mem , but with a prefix of # b00001111 (disassem:define-instruction-format (ext-reg/mem 24 :default-printer '(:name :tab reg/mem)) (prefix :field (byte 8 0) :value #b00001111) (op :fields (list (byte 7 9) (byte 3 19))) (width :field (byte 1 8) :type 'width) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'sized-reg/mem) (imm)) this section added by jrd , for fp instructions . (disassem:define-instruction-format (floating-point 16 :default-printer `(:name :tab reg/mem)) (prefix :field (byte 5 3) :value #b11011) (op :fields (list (byte 3 0) (byte 3 11))) (reg/mem :fields (list (byte 2 14) (byte 3 8)) :type 'reg/mem)) fp insn to / from fp reg (disassem:define-instruction-format (floating-point-fp 16 :default-printer `(:name :tab fp-reg)) (prefix :field (byte 5 3) :value #b11011) (suffix :field (byte 2 14) :value #b11) (op :fields (list (byte 3 0) (byte 3 11))) (fp-reg :field (byte 3 8) :type 'fp-reg)) fp insn to / from fp reg , with the reversed source / destination flag . (disassem:define-instruction-format (floating-point-fp-d 16 :default-printer `(:name :tab ,(swap-if 'd "ST0" ", " 'fp-reg))) (prefix :field (byte 5 3) :value #b11011) (suffix :field (byte 2 14) :value #b11) (op :fields (list (byte 2 0) (byte 3 11))) (d :field (byte 1 2)) (fp-reg :field (byte 3 8) :type 'fp-reg)) pfw (disassem:define-instruction-format (floating-point-no 16 :default-printer '(:name)) (prefix :field (byte 8 0) :value #b11011001) (suffix :field (byte 3 13) :value #b111) (op :field (byte 5 8))) (disassem:define-instruction-format (floating-point-3 16 :default-printer '(:name)) (prefix :field (byte 5 3) :value #b11011) (suffix :field (byte 2 14) :value #b11) (op :fields (list (byte 3 0) (byte 6 8)))) (disassem:define-instruction-format (floating-point-5 16 :default-printer '(:name)) (prefix :field (byte 8 0) :value #b11011011) (suffix :field (byte 3 13) :value #b111) (op :field (byte 5 8))) (disassem:define-instruction-format (floating-point-st 16 :default-printer '(:name)) (prefix :field (byte 8 0) :value #b11011111) (suffix :field (byte 3 13) :value #b111) (op :field (byte 5 8))) General Data Transfer (eval-when (eval compile load) (defun toggle-word-width (chunk inst stream dstate) (declare (ignore chunk inst stream)) (let ((ww (or (disassem:dstate-get-prop dstate 'word-width) *default-operand-size*))) (setf (disassem:dstate-get-prop dstate 'word-width) (ecase ww (:word :dword) (:dword :word) (define-instruction toggle-data-size (segment) (:printer byte ((op operand-size-prefix-byte)) :control #'toggle-word-width)) (defun reg-lower-3-bits (register) (let ((reg (reg-tn-encoding register))) (if (> reg 7) (- reg 8) reg))) (define-instruction mov (segment dst src) (:printer reg ((op #b1011) (imm nil :type 'imm-data)) '(:name :tab reg ", " imm)) (:printer simple-dir ((op #b101000) (imm nil :type 'imm-addr)) `(:name :tab ,(swap-if 'dir 'accum ", " '("[" imm "]")))) (:printer reg-reg/mem-dir ((op #b100010))) (:printer reg/mem-imm ((op '(#b1100011 #b000)))) (:emitter (let ((size (matching-operand-size dst src))) (maybe-emit-operand-size-prefix segment size) (cond ((register-p dst) (cond ((integerp src) (maybe-emit-rex-prefix segment size nil nil dst) (emit-byte-with-reg segment (if (eq size :byte) B8 (reg-lower-3-bits dst)) allow qword ((and (accumulator-p dst) (or (fixup-p src) (and (tn-p src) (eq (sb-name (sc-sb (tn-sc src))) 'constant)) (absolute-ea-p src))) (assert (eq size :qword)) (maybe-emit-rex-prefix segment size nil nil nil) (etypecase src 64 bit offset (tn (emit-absolute-fixup segment (make-fixup nil :code-object (- (* (tn-offset src) word-bytes) 64 bit offset (ea (emit-absolute-ea segment src)))) (t (maybe-emit-ea-rex-prefix segment size src dst) (emit-byte segment (if (eq size :byte) #b10001010 (emit-ea segment src (reg-lower-3-bits dst))))) ((and (accumulator-p src) (or (fixup-p dst) (absolute-ea-p dst))) (assert (eq size :qword)) (maybe-emit-rex-prefix segment size nil nil nil) # xA3 (etypecase dst (fixup (emit-absolute-fixup segment dst)) (ea (emit-absolute-ea segment dst)))) ((integerp src) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11000110 #b11000111)) (emit-ea segment dst #b000) (emit-sized-immediate segment size src)) ((register-p src) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment (if (eq size :byte) #b10001000 #b10001001)) (emit-ea segment dst (reg-lower-3-bits src))) (t (error "Bogus arguments to MOV: ~S ~S" dst src)))))) (define-instruction mov-imm (segment dst src) (:emitter (assert (qword-reg-p dst)) (assert (fixup-p src)) (maybe-emit-rex-prefix segment :qword nil nil dst) (emit-byte-with-reg segment B8 MOV (reg-lower-3-bits dst)) (defun emit-move-with-extension (segment dst src opcode) (assert (register-p dst)) (let ((dst-size (operand-size dst)) (src-size (operand-size src))) (ecase dst-size (:word (assert (eq src-size :byte)) (maybe-emit-operand-size-prefix segment :word) (maybe-emit-ea-rex-prefix segment :word src dst) (emit-byte segment #b00001111) (emit-byte segment opcode) (emit-ea segment src (reg-lower-3-bits dst))) (:dword (ecase src-size (:byte byte - > dword (maybe-emit-ea-rex-prefix segment :dword src dst) (emit-byte segment #b00001111) (emit-byte segment opcode) (emit-ea segment src (reg-lower-3-bits dst))) (:word (maybe-emit-ea-rex-prefix segment :dword src dst) (emit-byte segment #b00001111) (emit-byte segment (logior opcode 1)) (emit-ea segment src (reg-lower-3-bits dst))))) (ecase src-size (:byte (maybe-emit-ea-rex-prefix segment :qword src dst) (emit-byte segment #b00001111) (emit-byte segment opcode) (emit-ea segment src (reg-lower-3-bits dst))) (:word (maybe-emit-ea-rex-prefix segment :qword src dst) (emit-byte segment #b00001111) (emit-byte segment (logior opcode 1)) (emit-ea segment src (reg-lower-3-bits dst))) (:dword I think we do n't need a REX prefix here (maybe-emit-ea-rex-prefix segment :dword src dst) (emit-byte segment opcode) (emit-ea segment src (reg-lower-3-bits dst)))))))) (define-instruction movsx (segment dst src) (:printer ext-reg-reg/mem ((op #b1011111) (reg nil :type 'word-reg))) (:emitter (emit-move-with-extension segment dst src #b10111110))) (define-instruction movsxd (segment dst src) source size is dword (:printer ext-reg-reg/mem ((op #b01100011) (reg nil :type 'word-reg))) (:emitter 63 (define-instruction movzx (segment dst src) (:printer ext-reg-reg/mem ((op #b1011011) (reg nil :type 'word-reg))) (:emitter (emit-move-with-extension segment dst src #b10110110))) (define-instruction push (segment src) (:printer reg-no-width ((op #b01010))) Register / Memory . (:printer reg/mem ((op '(#b1111111 #b110)) (width 1))) (:printer byte ((op #b01101010) (imm nil :type 'signed-imm-byte)) '(:name :tab imm)) (:printer byte ((op #b01101000) (imm nil :type 'imm-word)) '(:name :tab imm)) # # # Segment registers ? (:emitter Push ca n't take 64 - bit immediate (if (integerp src) (cond ((<= -128 src 127) (emit-byte segment #b01101010) (emit-byte segment src)) (t (emit-byte segment #b01101000) (emit-dword segment src))) (let ((size (operand-size src))) (assert (not (eq size :byte))) (maybe-emit-operand-size-prefix segment size :qword) (cond ((register-p src) (maybe-emit-rex-prefix segment :dword nil nil src) (emit-byte-with-reg segment #b01010 (reg-lower-3-bits src))) (t (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment #b11111111) (emit-ea segment src #b110))))))) (define-instruction pusha (segment) (:printer byte ((op #b01100000))) (:emitter (emit-byte segment #b01100000))) (define-instruction pop (segment dst) (:printer reg-no-width ((op #b01011))) (:printer reg/mem ((op '(#b1000111 #b000)) (width 1))) (:emitter (let ((size (operand-size dst))) (assert (not (eq size :byte))) (maybe-emit-operand-size-prefix segment size :qword) (cond ((register-p dst) (maybe-emit-rex-prefix segment :dword nil nil dst) (emit-byte-with-reg segment #b01011 (reg-lower-3-bits dst))) (t (maybe-emit-ea-rex-prefix segment :dword dst nil) (emit-byte segment #b10001111) (emit-ea segment dst #b000)))))) (define-instruction popa (segment) (:printer byte ((op #b01100001))) (:emitter (emit-byte segment #b01100001))) (define-instruction xchg (segment operand1 operand2) (:printer reg-no-width ((op #b10010)) '(:name :tab accum ", " reg)) Register / Memory with Register . (:printer reg-reg/mem ((op #b1000011))) (:emitter (let ((size (matching-operand-size operand1 operand2))) (maybe-emit-operand-size-prefix segment size) (labels ((xchg-acc-with-something (acc something) (if (and (not (eq size :byte)) (register-p something)) (progn (maybe-emit-rex-prefix segment size nil nil something) (emit-byte-with-reg segment #b10010 (reg-lower-3-bits something))) (xchg-reg-with-something acc something))) (xchg-reg-with-something (reg something) (maybe-emit-ea-rex-prefix segment size something reg) (emit-byte segment (if (eq size :byte) #b10000110 #b10000111)) (emit-ea segment something (reg-lower-3-bits reg)))) (cond ((accumulator-p operand1) (xchg-acc-with-something operand1 operand2)) ((accumulator-p operand2) (xchg-acc-with-something operand2 operand1)) ((register-p operand1) (xchg-reg-with-something operand1 operand2)) ((register-p operand2) (xchg-reg-with-something operand2 operand1)) (t (error "Bogus args to XCHG: ~S ~S" operand1 operand2))))))) LEA can not take 64 bit argument . Sign extension does n't make sense here . (define-instruction lea (segment dst src) (:printer reg-reg/mem ((op #b1000110) (width 1))) (:emitter (assert (qword-reg-p dst)) (assert (not (fixup-p src))) (maybe-emit-ea-rex-prefix segment :qword src dst) (emit-byte segment #b10001101) (emit-ea segment src (reg-lower-3-bits dst)))) (define-instruction cmpxchg (segment dst src) Register / Memory with Register . (:printer ext-reg-reg/mem ((op #b1011000)) '(:name :tab reg/mem ", " reg)) (:emitter (assert (register-p src)) (let ((size (matching-operand-size src dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment #b00001111) (emit-byte segment (if (eq size :byte) #b10110000 #b10110001)) (emit-ea segment dst (reg-lower-3-bits src))))) CLC -- Clear Carry Flag . (define-instruction clc (segment) (:printer byte ((op #b11111000))) (:emitter (emit-byte segment #b11111000))) (define-instruction cld (segment) (:printer byte ((op #b11111100))) (:emitter (emit-byte segment #b11111100))) (define-instruction cli (segment) (:printer byte ((op #b11111010))) (:emitter (emit-byte segment #b11111010))) CMC -- Complement Carry Flag . (define-instruction cmc (segment) (:printer byte ((op #b11110101))) (:emitter (emit-byte segment #b11110101))) LAHF -- Load AH into flags . (define-instruction lahf (segment) (:printer byte ((op #b10011111))) (:emitter (emit-byte segment #b10011111))) (define-instruction popf (segment) (:printer byte ((op #b10011101))) (:emitter (emit-byte segment #b10011101))) (define-instruction pushf (segment) (:printer byte ((op #b10011100))) (:emitter (emit-byte segment #b10011100))) SAHF -- Store AH into flags . (define-instruction sahf (segment) (:printer byte ((op #b10011110))) (:emitter (emit-byte segment #b10011110))) STC -- Set Carry Flag . (define-instruction stc (segment) (:printer byte ((op #b11111001))) (:emitter (emit-byte segment #b11111001))) STD -- Set Direction Flag . (define-instruction std (segment) (:printer byte ((op #b11111101))) (:emitter (emit-byte segment #b11111101))) (define-instruction sti (segment) (:printer byte ((op #b11111011))) (:emitter (emit-byte segment #b11111011))) (defun emit-random-arith-inst (name segment dst src opcode) (let ((size (matching-operand-size dst src))) (maybe-emit-operand-size-prefix segment size) (cond ((integerp src) (cond ((and (not (eq size :byte)) (<= -128 src 127)) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment #b10000011) (emit-ea segment dst opcode) (emit-byte segment src)) ((accumulator-p dst) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (dpb opcode (byte 3 3) (if (eq size :byte) #b00000100 #b00000101))) (emit-sized-immediate segment size src)) (t (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b10000000 #b10000001)) (emit-ea segment dst opcode) (emit-sized-immediate segment size src)))) ((register-p src) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment (dpb opcode (byte 3 3) (if (eq size :byte) #b00000000 #b00000001))) (emit-ea segment dst (reg-lower-3-bits src))) ((register-p dst) (maybe-emit-ea-rex-prefix segment size src dst) (emit-byte segment (dpb opcode (byte 3 3) (if (eq size :byte) #b00000010 #b00000011))) (emit-ea segment src (reg-lower-3-bits dst))) (t (error "Bogus operands to ~A" name))))) (eval-when (compile eval) (defun arith-inst-printer-list (subop) `((accum-imm ((op ,(dpb subop (byte 3 2) #b0000010)))) (reg/mem-imm ((op (#b1000000 ,subop)))) (reg/mem-imm ((op (#b1000001 ,subop)) (imm nil :type signed-imm-byte))) (reg-reg/mem-dir ((op ,(dpb subop (byte 3 1) #b000000)))))) ) (define-instruction add (segment dst src) (:printer-list (arith-inst-printer-list #b000)) (:emitter (emit-random-arith-inst "ADD" segment dst src #b000))) (define-instruction adc (segment dst src) (:printer-list (arith-inst-printer-list #b010)) (:emitter (emit-random-arith-inst "ADC" segment dst src #b010))) (define-instruction sub (segment dst src) (:printer-list (arith-inst-printer-list #b101)) (:emitter (emit-random-arith-inst "SUB" segment dst src #b101))) (define-instruction sbb (segment dst src) (:printer-list (arith-inst-printer-list #b011)) (:emitter (emit-random-arith-inst "SBB" segment dst src #b011))) (define-instruction cmp (segment dst src) (:printer-list (arith-inst-printer-list #b111)) (:emitter (emit-random-arith-inst "CMP" segment dst src #b111))) (define-instruction inc (segment dst) (:printer reg-no-width ((op #b01000))) Register / Memory (:printer reg/mem ((op '(#b1111111 #b000)))) (:emitter (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11111110 #b11111111)) (emit-ea segment dst #b000)))) (define-instruction dec (segment dst) (:printer reg-no-width ((op #b01001))) Register / Memory (:printer reg/mem ((op '(#b1111111 #b001)))) (:emitter (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11111110 #b11111111)) (emit-ea segment dst #b001)))) (define-instruction neg (segment dst) (:printer reg/mem ((op '(#b1111011 #b011)))) (:emitter (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment dst #b011)))) (define-instruction aaa (segment) (:printer byte ((op #b00110111))) (:emitter (emit-byte segment #b00110111))) (define-instruction aas (segment) (:printer byte ((op #b00111111))) (:emitter (emit-byte segment #b00111111))) (define-instruction daa (segment) (:printer byte ((op #b00100111))) (:emitter (emit-byte segment #b00100111))) (define-instruction das (segment) (:printer byte ((op #b00101111))) (:emitter (emit-byte segment #b00101111))) (define-instruction mul (segment dst src) (:printer accum-reg/mem ((op '(#b1111011 #b100)))) (:emitter (let ((size (matching-operand-size dst src))) (assert (accumulator-p dst)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment src #b100)))) (define-instruction imul (segment dst &optional src1 src2) (:printer accum-reg/mem ((op '(#b1111011 #b101)))) (:printer ext-reg-reg/mem ((op #b1010111))) (:printer reg-reg/mem ((op #b0110100) (width 1) (imm nil :type 'imm-word)) '(:name :tab reg ", " reg/mem ", " imm)) (:printer reg-reg/mem ((op #b0110101) (width 1) (imm nil :type 'signed-imm-byte)) '(:name :tab reg ", " reg/mem ", " imm)) (:emitter (flet ((r/m-with-immed-to-reg (reg r/m immed) (let* ((size (matching-operand-size reg r/m)) (sx (and (not (eq size :byte)) (<= -128 immed 127)))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size r/m reg) (emit-byte segment (if sx #b01101011 #b01101001)) (emit-ea segment r/m (reg-lower-3-bits reg)) (if sx (emit-byte segment immed) (emit-sized-immediate segment size immed))))) (cond (src2 (r/m-with-immed-to-reg dst src1 src2)) (src1 (if (integerp src1) (r/m-with-immed-to-reg dst dst src1) (let ((size (matching-operand-size dst src1))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src1 dst) (emit-byte segment #b00001111) (emit-byte segment #b10101111) (emit-ea segment src1 (reg-lower-3-bits dst))))) (t (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment dst #b101))))))) (define-instruction div (segment dst src) (:printer accum-reg/mem ((op '(#b1111011 #b110)))) (:emitter (let ((size (matching-operand-size dst src))) (assert (accumulator-p dst)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment src #b110)))) (define-instruction idiv (segment dst src) (:printer accum-reg/mem ((op '(#b1111011 #b111)))) (:emitter (let ((size (matching-operand-size dst src))) (assert (accumulator-p dst)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment src #b111)))) (define-instruction aad (segment) (:printer two-bytes ((op '(#b11010101 #b00001010)))) (:emitter (emit-byte segment #b11010101) (emit-byte segment #b00001010))) (define-instruction aam (segment) (:printer two-bytes ((op '(#b11010100 #b00001010)))) (:emitter (emit-byte segment #b11010100) (emit-byte segment #b00001010))) (define-instruction cbw (segment) (:emitter (maybe-emit-operand-size-prefix segment :word) (emit-byte segment #b10011000))) CWDE -- Convert Word To Double Word Extened . EAX < - sign_xtnd(AX ) (define-instruction cwde (segment) (:emitter (maybe-emit-operand-size-prefix segment :dword) (emit-byte segment #b10011000))) CWD -- Convert Word to Double Word . DX : AX < - sign_xtnd(AX ) (define-instruction cwd (segment) (:emitter (maybe-emit-operand-size-prefix segment :word) (emit-byte segment #b10011001))) CDQ -- Convert Double Word to Quad Word . EDX : EAX < - sign_xtnd(EAX ) (define-instruction cdq (segment) (:printer byte ((op #b10011001))) (:emitter (maybe-emit-operand-size-prefix segment :dword) (emit-byte segment #b10011001))) CDO -- Convert Quad Word to Double Quad Word . RDX : RAX < - sign_xtnd(RAX ) (define-instruction cdo (segment) (:emitter (maybe-emit-rex-prefix segment :qword nil nil nil) (emit-byte segment #b10011001))) (define-instruction xadd (segment dst src) Register / Memory with Register . (:printer ext-reg-reg/mem ((op #b1100000)) '(:name :tab reg/mem ", " reg)) (:emitter (assert (register-p src)) (let ((size (matching-operand-size src dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment #b00001111) (emit-byte segment (if (eq size :byte) #b11000000 #b11000001)) (emit-ea segment dst (reg-lower-3-bits src))))) Logic . (defun emit-shift-inst (segment dst amount opcode) (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (multiple-value-bind (major-opcode immed) (case amount (:cl (values #b11010010 nil)) (1 (values #b11010000 nil)) (t (values #b11000000 t))) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) major-opcode (logior major-opcode 1))) (emit-ea segment dst opcode) (when immed (emit-byte segment amount))))) (eval-when (compile eval) (defun shift-inst-printer-list (subop) `((reg/mem ((op (#b1101000 ,subop))) (:name :tab reg/mem ", 1")) (reg/mem ((op (#b1101001 ,subop))) (:name :tab reg/mem ", " 'cl)) (reg/mem-imm ((op (#b1100000 ,subop)) (imm nil :type signed-imm-byte)))))) (define-instruction rol (segment dst amount) (:printer-list (shift-inst-printer-list #b000)) (:emitter (emit-shift-inst segment dst amount #b000))) (define-instruction ror (segment dst amount) (:printer-list (shift-inst-printer-list #b001)) (:emitter (emit-shift-inst segment dst amount #b001))) (define-instruction rcl (segment dst amount) (:printer-list (shift-inst-printer-list #b010)) (:emitter (emit-shift-inst segment dst amount #b010))) (define-instruction rcr (segment dst amount) (:printer-list (shift-inst-printer-list #b011)) (:emitter (emit-shift-inst segment dst amount #b011))) (define-instruction shl (segment dst amount) (:printer-list (shift-inst-printer-list #b100)) (:emitter (emit-shift-inst segment dst amount #b100))) (define-instruction shr (segment dst amount) (:printer-list (shift-inst-printer-list #b101)) (:emitter (emit-shift-inst segment dst amount #b101))) (define-instruction sar (segment dst amount) (:printer-list (shift-inst-printer-list #b111)) (:emitter (emit-shift-inst segment dst amount #b111))) (defun emit-double-shift (segment opcode dst src amt) (let ((size (matching-operand-size dst src))) (when (eq size :byte) (error "Double shifts can only be used with words.")) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst src) (emit-byte segment #b00001111) (emit-byte segment (dpb opcode (byte 1 3) (if (eq amt :cl) #b10100101 #b10100100))) (emit-ea segment dst (reg-lower-3-bits src)) (unless (eq amt :cl) (emit-byte segment amt)))) (eval-when (compile eval) (defun double-shift-inst-printer-list (op) `(#+nil (ext-reg-reg/mem-imm ((op ,(logior op #b100)) (imm nil :type signed-imm-byte))) (ext-reg-reg/mem ((op ,(logior op #b101))) (:name :tab reg/mem ", " 'cl))))) (define-instruction shld (segment dst src amt) (:declare (type (or (member :cl) (mod 32)) amt)) (:printer-list (double-shift-inst-printer-list #b10100000)) (:emitter (emit-double-shift segment #b0 dst src amt))) (define-instruction shrd (segment dst src amt) (:declare (type (or (member :cl) (mod 32)) amt)) (:printer-list (double-shift-inst-printer-list #b10101000)) (:emitter (emit-double-shift segment #b1 dst src amt))) (define-instruction and (segment dst src) (:printer-list (arith-inst-printer-list #b100)) (:emitter (emit-random-arith-inst "AND" segment dst src #b100))) (define-instruction test (segment this that) (:printer accum-imm ((op #b1010100))) (:printer reg/mem-imm ((op '(#b1111011 #b000)))) (:printer reg-reg/mem ((op #b1000010))) (:emitter (let ((size (matching-operand-size this that))) (maybe-emit-operand-size-prefix segment size) (flet ((test-immed-and-something (immed something) (cond ((accumulator-p something) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10101000 #b10101001)) (emit-sized-immediate segment size immed)) (t (maybe-emit-ea-rex-prefix segment size something nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment something #b000) (emit-sized-immediate segment size immed)))) (test-reg-and-something (reg something) (maybe-emit-ea-rex-prefix segment size something reg) (emit-byte segment (if (eq size :byte) #b10000100 #b10000101)) (emit-ea segment something (reg-lower-3-bits reg)))) (cond ((integerp that) (test-immed-and-something that this)) ((integerp this) (test-immed-and-something this that)) ((register-p this) (test-reg-and-something this that)) ((register-p that) (test-reg-and-something that this)) (t (error "Bogus operands for TEST: ~S and ~S" this that))))))) (define-instruction or (segment dst src) (:printer-list (arith-inst-printer-list #b001)) (:emitter (emit-random-arith-inst "OR" segment dst src #b001))) (define-instruction xor (segment dst src) (:printer-list (arith-inst-printer-list #b110)) (:emitter (emit-random-arith-inst "XOR" segment dst src #b110))) (define-instruction not (segment dst) (:printer reg/mem ((op '(#b1111011 #b010)))) (:emitter (let ((size (operand-size dst))) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size dst nil) (emit-byte segment (if (eq size :byte) #b11110110 #b11110111)) (emit-ea segment dst #b010)))) (disassem:define-instruction-format (string-op 8 :include 'simple :default-printer '(:name width))) (define-instruction cmps (segment size) (:printer string-op ((op #b1010011))) (:emitter (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10100110 #b10100111)))) (define-instruction ins (segment acc) (:printer string-op ((op #b0110110))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b01101100 #b01101101))))) (define-instruction lods (segment acc) (:printer string-op ((op #b1010110))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10101100 #b10101101))))) (define-instruction movs (segment size) (:printer string-op ((op #b1010010))) (:emitter (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10100100 #b10100101)))) (define-instruction outs (segment acc) (:printer string-op ((op #b0110111))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b01101110 #b01101111))))) (define-instruction scas (segment acc) (:printer string-op ((op #b1010111))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10101110 #b10101111))))) (define-instruction stos (segment acc) (:printer string-op ((op #b1010101))) (:emitter (let ((size (operand-size acc))) (assert (accumulator-p acc)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-rex-prefix segment size nil nil nil) (emit-byte segment (if (eq size :byte) #b10101010 #b10101011))))) (define-instruction xlat (segment) (:printer byte ((op #b11010111))) (:emitter (emit-byte segment #b11010111))) (define-instruction rep (segment) (:emitter (emit-byte segment #b11110010))) (define-instruction repe (segment) (:printer byte ((op #b11110011))) (:emitter (emit-byte segment #b11110011))) (define-instruction repne (segment) (:printer byte ((op #b11110010))) (:emitter (emit-byte segment #b11110010))) (define-instruction bsf (segment dst src) (:printer ext-reg-reg/mem ((op #b1011110) (width 0))) (:emitter (let ((size (matching-operand-size dst src))) (when (eq size :byte) (error "Can't scan bytes: ~S" src)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src dst) (emit-byte segment #b00001111) (emit-byte segment #b10111100) (emit-ea segment src (reg-lower-3-bits dst))))) (define-instruction bsr (segment dst src) (:printer ext-reg-reg/mem ((op #b1011110) (width 1))) (:emitter (let ((size (matching-operand-size dst src))) (when (eq size :byte) (error "Can't scan bytes: ~S" src)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size src dst) (emit-byte segment #b00001111) (emit-byte segment #b10111101) (emit-ea segment src (reg-lower-3-bits dst))))) (defun emit-bit-test-and-mumble (segment src index opcode) (let ((size (operand-size src))) (when (eq size :byte) (error "Can't scan bytes: ~S" src)) (maybe-emit-operand-size-prefix segment size) (cond ((integerp index) (maybe-emit-ea-rex-prefix segment size src nil) (emit-byte segment #b00001111) (emit-byte segment #b10111010) (emit-ea segment src opcode) (emit-byte segment index)) (t (maybe-emit-ea-rex-prefix segment size src index) (emit-byte segment #b00001111) (emit-byte segment (dpb opcode (byte 3 3) #b10000011)) (emit-ea segment src (reg-lower-3-bits index)))))) 0F AB reg / mem A3 = 10100011 BB = 10111011 B3 = 10110011 AB = 10101011 (disassem:define-instruction-format (bit-test-reg/mem 24 :default-printer '(:name :tab reg/mem ", " reg)) (prefix :field (byte 8 0) :value #b0001111) (op :field (byte 3 11)) ( test : fields ( list ( byte 2 14 ) ( byte 3 8) ) ) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'reg/mem) (reg :field (byte 3 19) :type 'reg) (imm)) (define-instruction bt (segment src index) (:printer bit-test-reg/mem ((op #b100))) (:emitter (emit-bit-test-and-mumble segment src index #b100))) (define-instruction btc (segment src index) (:printer bit-test-reg/mem ((op #b111))) (:emitter (emit-bit-test-and-mumble segment src index #b111))) (define-instruction btr (segment src index) (:printer bit-test-reg/mem ((op #b110))) (:emitter (emit-bit-test-and-mumble segment src index #b110))) (define-instruction bts (segment src index) (:printer bit-test-reg/mem ((op #b101))) (:emitter (emit-bit-test-and-mumble segment src index #b101))) (eval-when (compile load eval) (defparameter condition-name-vec (let ((vec (make-array 16 :initial-element nil))) (dolist (cond conditions) (when (null (aref vec (cdr cond))) (setf (aref vec (cdr cond)) (car cond)))) vec))) (disassem:define-argument-type condition-code :printer condition-name-vec) (disassem:define-argument-type displacement :sign-extend t :use-label #'offset-next :printer #'(lambda (value stream dstate) (let ((unsigned-val (if (and (numberp value) (minusp value)) (+ value #x100000000) value))) (disassem:maybe-note-assembler-routine unsigned-val stream dstate)) (print-label value stream dstate))) (disassem:define-instruction-format (short-cond-jump 16) (op :field (byte 4 4)) (cc :field (byte 4 0) :type 'condition-code) (label :field (byte 8 8) :type 'displacement)) (disassem:define-instruction-format (short-jump 16 :default-printer '(:name :tab label)) (const :field (byte 4 4) :value #b1110) (op :field (byte 4 0)) (label :field (byte 8 8) :type 'displacement)) (disassem:define-instruction-format (near-cond-jump 16) (op :fields (list (byte 8 0) (byte 4 12)) :value '(#b00001111 #b1000)) (cc :field (byte 4 8) :type 'condition-code) The disassembler currently does n't let you have an instruction > 32 bits (label :type 'displacement :prefilter #'(lambda (value dstate) (disassem:read-signed-suffix 32 dstate)))) (disassem:define-instruction-format (near-jump 8 :default-printer '(:name :tab label)) (op :field (byte 8 0)) The disassembler currently does n't let you have an instruction > 32 bits (label :type 'displacement :prefilter #'(lambda (value dstate) (disassem:read-signed-suffix 32 dstate)))) (define-instruction call (segment where) (:printer near-jump ((op #b11101000))) (:printer reg/mem ((op '(#b1111111 #b010)) (width 1))) (:emitter (typecase where (label (emit-byte segment #b11101000) (emit-back-patch segment 4 #'(lambda (segment posn) (emit-dword segment (- (label-position where) (+ posn 4)))))) (fixup (emit-byte segment #b11101000) Relative fixup is limited to 32 bits . This may not be enough . (emit-relative-fixup segment where)) (t REX is necessary for stuff like " callq * % rdi " (unless (ea-p where) (maybe-emit-ea-rex-prefix segment :qword where nil)) (emit-byte segment #b11111111) (emit-ea segment where #b010))))) (defun emit-byte-displacement-backpatch (segment target) (emit-back-patch segment 1 #'(lambda (segment posn) (let ((disp (- (label-position target) (1+ posn)))) (assert (<= -128 disp 127)) (emit-byte segment disp))))) fix it for 64 bit reg (define-instruction jmp (segment cond &optional where) (:printer short-cond-jump ((op #b0111)) '('j cc :tab label)) (:printer near-cond-jump () '('j cc :tab label)) (:printer short-jump ((op #b1011))) (:printer near-jump ((op #b11101001)) ) (:printer reg/mem ((op '(#b1111111 #b100)) (width 1))) (:emitter (cond (where (emit-chooser segment 6 2 #'(lambda (segment posn delta-if-after) (let ((disp (- (label-position where posn delta-if-after) (+ posn 2)))) (when (<= -128 disp 127) (emit-byte segment (dpb (conditional-opcode cond) (byte 4 0) #b01110000)) (emit-byte-displacement-backpatch segment where) t))) #'(lambda (segment posn) (let ((disp (- (label-position where) (+ posn 6)))) (emit-byte segment #b00001111) (emit-byte segment (dpb (conditional-opcode cond) (byte 4 0) #b10000000)) (emit-dword segment disp))))) ((label-p (setq where cond)) (emit-chooser segment 5 0 #'(lambda (segment posn delta-if-after) (let ((disp (- (label-position where posn delta-if-after) (+ posn 2)))) (when (<= -128 disp 127) (emit-byte segment #b11101011) (emit-byte-displacement-backpatch segment where) t))) #'(lambda (segment posn) (let ((disp (- (label-position where) (+ posn 5)))) (emit-byte segment #b11101001) (emit-dword segment disp)) ))) ((fixup-p where) (emit-byte segment #b11101001) (emit-relative-fixup segment where)) (t (unless (or (ea-p where) (tn-p where)) (error "Don't know what to do with ~A" where)) (emit-byte segment #b11111111) (emit-ea segment where #b100))))) (define-instruction jmp-short (segment label) (:emitter (emit-byte segment #b11101011) (emit-byte-displacement-backpatch segment label))) (define-instruction ret (segment &optional stack-delta) (:printer byte ((op #b11000011))) (:printer byte ((op #b11000010) (imm nil :type 'imm-word-16)) '(:name :tab imm)) (:emitter (cond (stack-delta (emit-byte segment #b11000010) (emit-word segment stack-delta)) (t (emit-byte segment #b11000011))))) (define-instruction jrcxz (segment target) (:printer short-jump ((op #b0011))) (:emitter (emit-byte segment #b11100011) (emit-byte-displacement-backpatch segment target))) (define-instruction loop (segment target) (:printer short-jump ((op #b0010))) (:emitter (emit-byte segment #b11100010) (emit-byte-displacement-backpatch segment target))) (define-instruction loopz (segment target) (:printer short-jump ((op #b0001))) (:emitter (emit-byte segment #b11100001) (emit-byte-displacement-backpatch segment target))) (define-instruction loopnz (segment target) (:printer short-jump ((op #b0000))) (:emitter (emit-byte segment #b11100000) (emit-byte-displacement-backpatch segment target))) (disassem:define-instruction-format (cond-move 24 :default-printer '('cmov cond :tab reg ", " reg/mem)) (prefix :field (byte 8 0) :value #b00001111) (op :field (byte 4 12) :value #b0100) (cond :field (byte 4 8) :type 'condition-code) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'reg/mem) (reg :field (byte 3 19) :type 'reg)) (define-instruction cmov (segment cond dst src) (:printer cond-move ()) (:emitter (assert (register-p dst)) (let ((size (matching-operand-size dst src))) (assert (or (eq size :word) (eq size :dword))) (maybe-emit-operand-size-prefix segment size)) (emit-byte segment #b00001111) (emit-byte segment (dpb (conditional-opcode cond) (byte 4 0) #b01000000)) (emit-ea segment src (reg-tn-encoding dst)))) (disassem:define-instruction-format (cond-set 24 :default-printer '('set cc :tab reg/mem)) (prefix :field (byte 8 0) :value #b00001111) (op :field (byte 4 12) :value #b1001) (cc :field (byte 4 8) :type 'condition-code) (reg/mem :fields (list (byte 2 22) (byte 3 16)) :type 'byte-reg/mem) (reg :field (byte 3 19) :value #b000)) (define-instruction set (segment dst cond) (:printer cond-set ()) (:emitter (emit-byte segment #b00001111) (emit-byte segment (dpb (conditional-opcode cond) (byte 4 0) #b10010000)) (emit-ea segment dst #b000))) Enter / Leave (disassem:define-instruction-format (enter-format 32 :default-printer '(:name :tab disp (:unless (:constant 0) ", " level))) (op :field (byte 8 0)) (disp :field (byte 16 8)) (level :field (byte 8 24))) (define-instruction enter (segment disp &optional (level 0)) (:declare (type (unsigned-byte 16) disp) (type (unsigned-byte 8) level)) (:printer enter-format ((op #b11001000))) (:emitter (emit-byte segment #b11001000) (emit-word segment disp) (emit-byte segment level))) (define-instruction leave (segment) (:printer byte ((op #b11001001))) (:emitter (emit-byte segment #b11001001))) (disassem:define-instruction-format (byte-imm 16 :default-printer '(:name :tab code)) (op :field (byte 8 0)) (code :field (byte 8 8))) (defun snarf-error-junk (sap offset &optional length-only) (let* ((length (system:sap-ref-8 sap offset)) (vector (make-array length :element-type '(unsigned-byte 8)))) (declare (type system:system-area-pointer sap) (type (unsigned-byte 8) length) (type (simple-array (unsigned-byte 8) (*)) vector)) (cond (length-only (values 0 (1+ length) nil nil)) (t (kernel:copy-from-system-area sap (* byte-bits (1+ offset)) vector (* word-bits vector-data-offset) (* length byte-bits)) (collect ((sc-offsets) (lengths)) (let* ((index 0) (error-number (c::read-var-integer vector index))) (lengths index) (loop (when (>= index length) (return)) (let ((old-index index)) (sc-offsets (c::read-var-integer vector index)) (lengths (- index old-index)))) (values error-number (1+ length) (sc-offsets) (lengths)))))))) (defmacro break-cases (breaknum &body cases) (let ((bn-temp (gensym))) (collect ((clauses)) (dolist (case cases) (clauses `((= ,bn-temp ,(car case)) ,@(cdr case)))) `(let ((,bn-temp ,breaknum)) (cond ,@(clauses)))))) (defun break-control (chunk inst stream dstate) (declare (ignore inst)) (flet ((nt (x) (if stream (disassem:note x dstate)))) (case (byte-imm-code chunk dstate) (#.vm:error-trap (nt "Error trap") (disassem:handle-break-args #'snarf-error-junk stream dstate)) (#.vm:cerror-trap (nt "Cerror trap") (disassem:handle-break-args #'snarf-error-junk stream dstate)) (#.vm:breakpoint-trap (nt "Breakpoint trap")) (#.vm:pending-interrupt-trap (nt "Pending interrupt trap")) (#.vm:halt-trap (nt "Halt trap")) (#.vm:function-end-breakpoint-trap (nt "Function end breakpoint trap")) ))) (define-instruction break (segment code) (:declare (type (unsigned-byte 8) code)) (:printer byte-imm ((op #b11001100)) '(:name :tab code) :control #'break-control) (:emitter (emit-byte segment #b11001100) (emit-byte segment code))) (define-instruction int (segment number) (:declare (type (unsigned-byte 8) number)) (:printer byte-imm ((op #b11001101))) (:emitter (etypecase number ((member 3) (emit-byte segment #b11001100)) ((unsigned-byte 8) (emit-byte segment #b11001101) (emit-byte segment number))))) (define-instruction into (segment) (:printer byte ((op #b11001110))) (:emitter (emit-byte segment #b11001110))) (define-instruction bound (segment reg bounds) (:emitter (let ((size (matching-operand-size reg bounds))) (when (eq size :byte) (error "Can't bounds-test bytes: ~S" reg)) (maybe-emit-operand-size-prefix segment size) (maybe-emit-ea-rex-prefix segment size bounds reg) (emit-byte segment #b01100010) (emit-ea segment bounds (reg-lower-3-bits reg))))) (define-instruction iret (segment) (:printer byte ((op #b11001111))) (:emitter (emit-byte segment #b11001111))) from Pentium onwards (define-instruction rdtsc (segment) (:printer two-bytes ((op '(#x0f #x31)))) (:emitter (emit-byte segment #x0f) (emit-byte segment #x31))) (define-instruction cpuid (segment) (:printer two-bytes ((op '(#x0f #xa2)))) (:emitter (emit-byte segment #x0f) (emit-byte segment #xa2))) (define-instruction hlt (segment) (:printer byte ((op #b11110100))) (:emitter (emit-byte segment #b11110100))) (define-instruction nop (segment) (:printer byte ((op #b10010000))) (:emitter (emit-byte segment #b10010000))) (define-instruction wait (segment) (:printer byte ((op #b10011011))) (:emitter (emit-byte segment #b10011011))) (define-instruction lock (segment) (:printer byte ((op #b11110000))) (:emitter (emit-byte segment #b11110000))) (define-instruction byte (segment byte) (:emitter (emit-byte segment byte))) (define-instruction word (segment word) (:emitter (emit-word segment word))) (define-instruction dword (segment dword) (:emitter (emit-dword segment dword))) (define-instruction qword (segment qword) (:emitter (emit-qword segment qword))) (defun emit-header-data (segment type) (emit-back-patch segment 8 #'(lambda (segment posn) (emit-qword segment (logior type (ash (+ posn (component-header-length)) (- type-bits word-shift))))))) (define-instruction function-header-word (segment) (:emitter (emit-header-data segment function-header-type))) (define-instruction lra-header-word (segment) (:emitter (emit-header-data segment return-pc-header-type))) added by jrd . fp instructions (define-instruction fld (segment source) (:printer floating-point ((op '(#b001 #b000)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment source #b000))) (define-instruction fldd (segment source) (:printer floating-point ((op '(#b101 #b000)))) (:printer floating-point-fp ((op '(#b001 #b000)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011001) (emit-byte segment #b11011101)) (emit-fp-op segment source #b000))) (define-instruction fldl (segment source) (:printer floating-point ((op '(#b011 #b101)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment source #b101))) store single from st(0 ) (define-instruction fst (segment dest) (:printer floating-point ((op '(#b001 #b010)))) (:emitter (cond ((fp-reg-tn-p dest) (emit-byte segment #b11011101) (emit-fp-op segment dest #b010)) (t (emit-byte segment #b11011001) (emit-fp-op segment dest #b010))))) store double from st(0 ) (define-instruction fstd (segment dest) (:printer floating-point ((op '(#b101 #b010)))) (:printer floating-point-fp ((op '(#b101 #b010)))) (:emitter (cond ((fp-reg-tn-p dest) (emit-byte segment #b11011101) (emit-fp-op segment dest #b010)) (t (emit-byte segment #b11011101) (emit-fp-op segment dest #b010))))) Arithmetic ops are all done with at least one operand at top of stack . The other operand is is another register or a 32/64 bit memory . dtc : I 've tried to follow the Intel ASM386 conventions , but note that these conflict with the conventions for binops . To reduce operation and the two syntaxes . By the ASM386 convention the or Fop Destination , Source If only one operand is given then it is the source and the destination is ) . There are reversed forms of the fsub and The instructions below only accept one operand at present which is the operand is the destination with the source being ) . (define-instruction fadd (segment source) (:printer floating-point ((op '(#b000 #b000)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b000))) (define-instruction faddd (segment source) (:printer floating-point ((op '(#b100 #b000)))) (:printer floating-point-fp ((op '(#b000 #b000)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b000))) (define-instruction fadd-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b000))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fadd) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b000))) (define-instruction faddp-sti (segment destination) (:printer floating-point-fp ((op '(#b110 #b000))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'faddp) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011110) (emit-fp-op segment destination #b000))) (define-instruction fsub (segment source) (:printer floating-point ((op '(#b000 #b100)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b100))) (define-instruction fsubr (segment source) (:printer floating-point ((op '(#b000 #b101)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b101))) (define-instruction fsubd (segment source) (:printer floating-point ((op '(#b100 #b100)))) (:printer floating-point-fp ((op '(#b000 #b100)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b100))) (define-instruction fsubrd (segment source) (:printer floating-point ((op '(#b100 #b101)))) (:printer floating-point-fp ((op '(#b000 #b101)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b101))) ASM386 syntax : FSUB ST(i ) , ST (define-instruction fsub-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b101))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fsub) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b101))) (define-instruction fsubp-sti (segment destination) (:printer floating-point-fp ((op '(#b110 #b101))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fsubp) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011110) (emit-fp-op segment destination #b101))) ASM386 syntax : FSUBR ST(i ) , ST (define-instruction fsubr-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b100))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fsubr) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b100))) (define-instruction fsubrp-sti (segment destination) (:printer floating-point-fp ((op '(#b110 #b100))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fsubrp) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011110) (emit-fp-op segment destination #b100))) (define-instruction fmul (segment source) (:printer floating-point ((op '(#b000 #b001)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b001))) (define-instruction fmuld (segment source) (:printer floating-point ((op '(#b100 #b001)))) (:printer floating-point-fp ((op '(#b000 #b001)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b001))) (define-instruction fmul-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b001))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fmul) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b001))) (define-instruction fdiv (segment source) (:printer floating-point ((op '(#b000 #b110)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b110))) (define-instruction fdivr (segment source) (:printer floating-point ((op '(#b000 #b111)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment source #b111))) (define-instruction fdivd (segment source) (:printer floating-point ((op '(#b100 #b110)))) (:printer floating-point-fp ((op '(#b000 #b110)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b110))) (define-instruction fdivrd (segment source) (:printer floating-point ((op '(#b100 #b111)))) (:printer floating-point-fp ((op '(#b000 #b111)))) (:emitter (if (fp-reg-tn-p source) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment source #b111))) ASM386 syntax : FDIV ST(i ) , ST (define-instruction fdiv-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b111))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fdiv) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b111))) ASM386 syntax : FDIVR ST(i ) , ST (define-instruction fdivr-sti (segment destination) (:printer floating-point-fp ((op '(#b100 #b110))) '(:name :tab fp-reg ", " '|ST(0)|) :print-name 'fdivr) (:emitter (assert (fp-reg-tn-p destination)) (emit-byte segment #b11011100) (emit-fp-op segment destination #b110))) (define-instruction fxch (segment source) (:printer floating-point-fp ((op '(#b001 #b001)))) (:emitter (unless (and (tn-p source) (eq (sb-name (sc-sb (tn-sc source))) 'float-registers)) (lisp:break)) (emit-byte segment #b11011001) (emit-fp-op segment source #b001))) push 32 - bit integer to st0 (define-instruction fild (segment source) (:printer floating-point ((op '(#b011 #b000)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment source #b000))) push 64 - bit integer to st0 (define-instruction fildl (segment source) (:printer floating-point ((op '(#b111 #b101)))) (:emitter (emit-byte segment #b11011111) (emit-fp-op segment source #b101))) store 32 - bit integer (define-instruction fist (segment dest) (:printer floating-point ((op '(#b011 #b010)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment dest #b010))) Store and pop 32 - bit integer (define-instruction fistp (segment dest) (:printer floating-point ((op '(#b011 #b011)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment dest #b011))) Store and pop 64 - bit integer (define-instruction fistpl (segment dest) (:printer floating-point ((op '(#b111 #b111)))) (:emitter (emit-byte segment #b11011111) (emit-fp-op segment dest #b111))) store single from st(0 ) and pop (define-instruction fstp (segment dest) (:printer floating-point ((op '(#b001 #b011)))) (:emitter (cond ((fp-reg-tn-p dest) (emit-byte segment #b11011101) (emit-fp-op segment dest #b011)) (t (emit-byte segment #b11011001) (emit-fp-op segment dest #b011))))) store double from st(0 ) and pop (define-instruction fstpd (segment dest) (:printer floating-point ((op '(#b101 #b011)))) (:printer floating-point-fp ((op '(#b101 #b011)))) (:emitter (cond ((fp-reg-tn-p dest) (emit-byte segment #b11011101) (emit-fp-op segment dest #b011)) (t (emit-byte segment #b11011101) (emit-fp-op segment dest #b011))))) (define-instruction fstpl (segment dest) (:printer floating-point ((op '(#b011 #b111)))) (:emitter (emit-byte segment #b11011011) (emit-fp-op segment dest #b111))) (define-instruction fdecstp (segment) (:printer floating-point-no ((op #b10110))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110110))) (define-instruction fincstp (segment) (:printer floating-point-no ((op #b10111))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110111))) (define-instruction ffree (segment dest) (:printer floating-point-fp ((op '(#b101 #b000)))) (:emitter (emit-byte segment #b11011101) (emit-fp-op segment dest #b000))) (define-instruction ffreep (segment dest) (:printer floating-point-fp ((op '(#b111 #b000)))) (:emitter (emit-byte segment #b11011111) (emit-fp-op segment dest #b000))) (define-instruction fabs (segment) (:printer floating-point-no ((op #b00001))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11100001))) (define-instruction fchs (segment) (:printer floating-point-no ((op #b00000))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11100000))) (define-instruction frndint(segment) (:printer floating-point-no ((op #b11100))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111100))) Initialize (define-instruction fninit(segment) (:printer floating-point-5 ((op #b00011))) (:emitter (emit-byte segment #b11011011) (emit-byte segment #b11100011))) Store Status Word to AX (define-instruction fnstsw(segment) (:printer floating-point-st ((op #b00000))) (:emitter (emit-byte segment #b11011111) (emit-byte segment #b11100000))) (define-instruction fldcw(segment src) (:printer floating-point ((op '(#b001 #b101)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment src #b101))) (define-instruction fnstcw(segment dst) (:printer floating-point ((op '(#b001 #b111)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment dst #b111))) Store FP Environment (define-instruction fstenv(segment dst) (:printer floating-point ((op '(#b001 #b110)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment dst #b110))) Retore FP Environment (define-instruction fldenv(segment src) (:printer floating-point ((op '(#b001 #b100)))) (:emitter (emit-byte segment #b11011001) (emit-fp-op segment src #b100))) Save FP State (define-instruction fsave(segment dst) (:printer floating-point ((op '(#b101 #b110)))) (:emitter (emit-byte segment #b11011101) (emit-fp-op segment dst #b110))) Restore FP State (define-instruction frstor (segment src) (:printer floating-point ((op '(#b101 #b100)))) (:emitter (emit-byte segment #b11011101) (emit-fp-op segment src #b100))) (define-instruction fnclex (segment) (:printer floating-point-5 ((op #b00010))) (:emitter (emit-byte segment #b11011011) (emit-byte segment #b11100010))) Comparison (define-instruction fcom (segment src) (:printer floating-point ((op '(#b000 #b010)))) (:emitter (emit-byte segment #b11011000) (emit-fp-op segment src #b010))) (define-instruction fcomd (segment src) (:printer floating-point ((op '(#b100 #b010)))) (:printer floating-point-fp ((op '(#b000 #b010)))) (:emitter (if (fp-reg-tn-p src) (emit-byte segment #b11011000) (emit-byte segment #b11011100)) (emit-fp-op segment src #b010))) to ST0 , popping the stack twice . (define-instruction fcompp (segment) (:printer floating-point-3 ((op '(#b110 #b011001)))) (:emitter (emit-byte segment #b11011110) (emit-byte segment #b11011001))) Compare ST(i ) to ST0 and update the flags . Intel syntax : FCOMI ST , ST(i ) (define-instruction fcomi (segment src) (:printer floating-point-fp ((op '(#b011 #b110)))) (:emitter (assert (fp-reg-tn-p src)) (emit-byte segment #b11011011) (emit-fp-op segment src #b110))) (define-instruction fucom (segment src) (:printer floating-point-fp ((op '(#b101 #b100)))) (:emitter (assert (fp-reg-tn-p src)) (emit-byte segment #b11011101) (emit-fp-op segment src #b100))) Unordered compare ST(i ) to ST0 and update the flags . Intel syntax : FUCOMI ST , ST(i ) (define-instruction fucomi (segment src) (:printer floating-point-fp ((op '(#b011 #b101)))) (:emitter (assert (fp-reg-tn-p src)) (emit-byte segment #b11011011) (emit-fp-op segment src #b101))) (define-instruction ftst (segment) (:printer floating-point-no ((op #b00100))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11100100))) Compare and move ST(i ) to ST0 . Intel syntal : FCMOVcc ST , ST(i ) (define-instruction fcmov (segment cond src) #+nil (:printer floating-point ((op '(#b01? #b???)))) (:emitter (assert (fp-reg-tn-p src)) (emit-byte segment (ecase cond ((:b :e :be :u) #b11011010) ((:nb :ne :nbe :nu) #b11011011))) (emit-fp-op segment src (ecase cond ((:b :nb) #b000) ((:e :ne) #b000) ((:be :nbe) #b000) ((:u nu) #b000))))) 80387 Specials (define-instruction fsqrt (segment) (:printer floating-point-no ((op #b11010))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111010))) (define-instruction fscale (segment) (:printer floating-point-no ((op #b11101))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111101))) (define-instruction fxtract (segment) (:printer floating-point-no ((op #b10100))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110100))) (define-instruction fsin (segment) (:printer floating-point-no ((op #b11110))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111110))) (define-instruction fcos (segment) (:printer floating-point-no ((op #b11111))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111111))) (define-instruction fprem1 (segment) (:printer floating-point-no ((op #b10101))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110101))) (define-instruction fprem (segment) (:printer floating-point-no ((op #b11000))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111000))) (define-instruction fxam (segment) (:printer floating-point-no ((op #b00101))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11100101))) POPS STACK (:printer floating-point-no ((op #b10001))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110001))) (define-instruction fyl2xp1 (segment) (:printer floating-point-no ((op #b11001))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11111001))) (define-instruction f2xm1 (segment) (:printer floating-point-no ((op #b10000))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110000))) (:printer floating-point-no ((op #b10010))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110010))) POPS STACK (:printer floating-point-no ((op #b10011))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11110011))) (define-instruction fldz (segment) (:printer floating-point-no ((op #b01110))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101110))) (define-instruction fld1 (segment) (:printer floating-point-no ((op #b01000))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101000))) (define-instruction fldpi (segment) (:printer floating-point-no ((op #b01011))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101011))) (define-instruction fldl2t (segment) (:printer floating-point-no ((op #b01001))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101001))) (define-instruction fldl2e (segment) (:printer floating-point-no ((op #b01010))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101010))) (define-instruction fldlg2 (segment) (:printer floating-point-no ((op #b01100))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101100))) (define-instruction fldln2 (segment) (:printer floating-point-no ((op #b01101))) (:emitter (emit-byte segment #b11011001) (emit-byte segment #b11101101)))
4a66d43ac79711830b79d9273e15afa1824676055c3cd4b8a51200442470d64b
Incubaid/arakoon
registry.mli
Copyright ( 2010 - 2014 ) INCUBAID BVBA Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright (2010-2014) INCUBAID BVBA 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. *) class type cursor_db = object method get_key : unit -> Key.t method get_value : unit -> string method jump : ?inc:bool -> ?right:bool -> string -> bool method last : unit -> bool method next : unit -> bool method prev : unit -> bool end module Cursor_store : sig val fold_range : cursor_db -> string -> bool -> string option -> bool -> int -> (cursor_db -> Key.t -> int -> 'b -> 'b) -> 'b -> (int * 'b) val fold_rev_range : cursor_db -> string option -> bool -> string -> bool -> int -> (cursor_db -> Key.t -> int -> 'b -> 'b) -> 'b -> (int * 'b) end class type read_user_db = object method exists : string -> bool method get : string -> string option method get_exn : string -> string method with_cursor : (cursor_db -> 'a) -> 'a method get_interval : unit -> Interval.Interval.t end class type user_db = object inherit read_user_db method put : string -> string option -> unit end class type backend = object method read_allowed : Arakoon_client.consistency -> unit method push_update : Update.Update.t -> string option Lwt.t end module Registry : sig type f = user_db -> string option -> string option val register : string -> f -> unit val exists : string -> bool val lookup : string -> f end module HookRegistry : sig type h = (Llio.lwtic * Llio.lwtoc * string) -> read_user_db -> backend -> unit Lwt.t val register : string -> h -> unit val lookup : string -> h end
null
https://raw.githubusercontent.com/Incubaid/arakoon/43a8d0b26e4876ef91d9657149f105c7e57e0cb0/src/plugins/registry.mli
ocaml
Copyright ( 2010 - 2014 ) INCUBAID BVBA Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright (2010-2014) INCUBAID BVBA 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. *) class type cursor_db = object method get_key : unit -> Key.t method get_value : unit -> string method jump : ?inc:bool -> ?right:bool -> string -> bool method last : unit -> bool method next : unit -> bool method prev : unit -> bool end module Cursor_store : sig val fold_range : cursor_db -> string -> bool -> string option -> bool -> int -> (cursor_db -> Key.t -> int -> 'b -> 'b) -> 'b -> (int * 'b) val fold_rev_range : cursor_db -> string option -> bool -> string -> bool -> int -> (cursor_db -> Key.t -> int -> 'b -> 'b) -> 'b -> (int * 'b) end class type read_user_db = object method exists : string -> bool method get : string -> string option method get_exn : string -> string method with_cursor : (cursor_db -> 'a) -> 'a method get_interval : unit -> Interval.Interval.t end class type user_db = object inherit read_user_db method put : string -> string option -> unit end class type backend = object method read_allowed : Arakoon_client.consistency -> unit method push_update : Update.Update.t -> string option Lwt.t end module Registry : sig type f = user_db -> string option -> string option val register : string -> f -> unit val exists : string -> bool val lookup : string -> f end module HookRegistry : sig type h = (Llio.lwtic * Llio.lwtoc * string) -> read_user_db -> backend -> unit Lwt.t val register : string -> h -> unit val lookup : string -> h end
b3a6cd61c5cf45af160a758d9f3556ff3e8ec5d0a4e4f6ee48f1c44ec15e3d22
overtone/overtone
satie.clj
(ns ^:hw overtone.examples.monome.satie (:use [clojure.core.match :only [match]] [overtone.live] [overtone.inst sampled-piano]) (:require [polynome.core :as poly])) . 1 (def phrase1a [:iii :v :iv# :iii :iii :ii# :iii :ii#]) (def phrase1b [:iii :v :iv# :iii :v# :vi :v# :vi]) (def phrase1c [:iii :v :iv# :iii :iii :ii# :i :vii- :vi- :vii- :vi- :vii- :i :vii- :vii- :vi-]) (def phrase2 [:i :ii :i :vii- :i :ii :i :vii- :i :vii- :vii- :vi-]) (def phrase3 [:iii :iv# :v# :vi :vii :ii#+ :vii :vi :vii :vi :vii :vi :vi :v# :iv :iii :iii :ii# :i :vii- :vii- :vi-]) (def phrase1a-reprise [:iii :v :iv# :iii :iii :ii#]) (def phrase1b-reprise [:iii :v :iv# :iii :v# :vi]) (def phrase1-bass [:vi--- [:vi- :iii- :i-] [:vi- :iii- :i-]]) (def phrase2-bass [:iii-- [:iii- :vii-- :v--] [:iii- :vii-- :v--]]) (def phrase3-bass [:ii--- [:vi-- :ii- :iv-] [:vi-- :ii- :iv-]]) (def right-hand-degrees (concat phrase1a phrase1b phrase1c phrase1a phrase1b phrase1c phrase2 phrase2 phrase3 phrase3 phrase2 phrase2 phrase1a-reprise phrase1b-reprise phrase1a-reprise phrase1b-reprise phrase2 phrase2 phrase3 phrase3 phrase2 phrase2)) (def left-hand-degrees (concat (apply concat (repeat 6 phrase1-bass)) ;;A phrase2-bass ;;B (apply concat (repeat 8 phrase1-bass)) ;;C phrase2-bass ;;D (apply concat (repeat 2 phrase1-bass)) ;;E (apply concat (repeat 2 phrase3-bass)) ;;F (apply concat (repeat 2 phrase1-bass)) ;;G (apply concat (repeat 2 phrase3-bass)) ;;H (apply concat (repeat 14 phrase1-bass)) ;;I (apply concat (repeat 2 phrase3-bass)) ;;J (apply concat (repeat 2 phrase1-bass)) ;;K (apply concat (repeat 2 phrase3-bass)) ;;L (apply concat (repeat 10 phrase1-bass)) ;;M (apply concat (repeat 2 phrase3-bass)) ;;N (apply concat (repeat 2 phrase1-bass)) ;;O (apply concat (repeat 2 phrase3-bass)) ;;P (apply concat (repeat 14 phrase1-bass)) ;;Q (apply concat (repeat 2 phrase3-bass)) ;;R (apply concat (repeat 2 phrase1-bass)) ;;S (apply concat (repeat 2 phrase3-bass)) ;;T phrase1-bass ;;U )) (def lh-pitches (degrees->pitches left-hand-degrees :major :Ab4)) (def rh-pitches (degrees->pitches right-hand-degrees :major :Ab4)) (def cur-pitch-rh (atom -1)) (def cur-pitch-lh (atom -1)) (defn reset-pos [] (reset! cur-pitch-rh -1) (reset! cur-pitch-lh -1)) (defn vol-mul [amp] (* amp 0.002)) (defn play-next-rh [amp] (let [idx (swap! cur-pitch-rh inc) pitch (nth (cycle rh-pitches) idx)] (sampled-piano pitch (vol-mul amp)))) (defn play-next-lh [amp] (let [idx (swap! cur-pitch-lh inc) pitch (nth (cycle lh-pitches) idx)] (if (sequential? pitch) (doseq [p pitch] (sampled-piano p (vol-mul amp))) (sampled-piano pitch (vol-mul amp))))) (defonce m (poly/init "/dev/tty.usbserial-m64-0790")) (poly/on-press m (fn [x y s] (match [x y] [7 _] (reset-pos) [_ 0] (play-next-lh (+ (rand-int 5) (* 12 (+ x 4)))) [_ 7] (play-next-rh (+ (rand-int 5) (* 12 (+ x 4))))))) ;;(poly/remove-all-callbacks m) ;;(poly/disconnect m)
null
https://raw.githubusercontent.com/overtone/overtone/02f8cdd2817bf810ff390b6f91d3e84d61afcc85/src/overtone/examples/monome/satie.clj
clojure
A B C D E F G H I J K L M N O P Q R S T U (poly/remove-all-callbacks m) (poly/disconnect m)
(ns ^:hw overtone.examples.monome.satie (:use [clojure.core.match :only [match]] [overtone.live] [overtone.inst sampled-piano]) (:require [polynome.core :as poly])) . 1 (def phrase1a [:iii :v :iv# :iii :iii :ii# :iii :ii#]) (def phrase1b [:iii :v :iv# :iii :v# :vi :v# :vi]) (def phrase1c [:iii :v :iv# :iii :iii :ii# :i :vii- :vi- :vii- :vi- :vii- :i :vii- :vii- :vi-]) (def phrase2 [:i :ii :i :vii- :i :ii :i :vii- :i :vii- :vii- :vi-]) (def phrase3 [:iii :iv# :v# :vi :vii :ii#+ :vii :vi :vii :vi :vii :vi :vi :v# :iv :iii :iii :ii# :i :vii- :vii- :vi-]) (def phrase1a-reprise [:iii :v :iv# :iii :iii :ii#]) (def phrase1b-reprise [:iii :v :iv# :iii :v# :vi]) (def phrase1-bass [:vi--- [:vi- :iii- :i-] [:vi- :iii- :i-]]) (def phrase2-bass [:iii-- [:iii- :vii-- :v--] [:iii- :vii-- :v--]]) (def phrase3-bass [:ii--- [:vi-- :ii- :iv-] [:vi-- :ii- :iv-]]) (def right-hand-degrees (concat phrase1a phrase1b phrase1c phrase1a phrase1b phrase1c phrase2 phrase2 phrase3 phrase3 phrase2 phrase2 phrase1a-reprise phrase1b-reprise phrase1a-reprise phrase1b-reprise phrase2 phrase2 phrase3 phrase3 phrase2 phrase2)) )) (def lh-pitches (degrees->pitches left-hand-degrees :major :Ab4)) (def rh-pitches (degrees->pitches right-hand-degrees :major :Ab4)) (def cur-pitch-rh (atom -1)) (def cur-pitch-lh (atom -1)) (defn reset-pos [] (reset! cur-pitch-rh -1) (reset! cur-pitch-lh -1)) (defn vol-mul [amp] (* amp 0.002)) (defn play-next-rh [amp] (let [idx (swap! cur-pitch-rh inc) pitch (nth (cycle rh-pitches) idx)] (sampled-piano pitch (vol-mul amp)))) (defn play-next-lh [amp] (let [idx (swap! cur-pitch-lh inc) pitch (nth (cycle lh-pitches) idx)] (if (sequential? pitch) (doseq [p pitch] (sampled-piano p (vol-mul amp))) (sampled-piano pitch (vol-mul amp))))) (defonce m (poly/init "/dev/tty.usbserial-m64-0790")) (poly/on-press m (fn [x y s] (match [x y] [7 _] (reset-pos) [_ 0] (play-next-lh (+ (rand-int 5) (* 12 (+ x 4)))) [_ 7] (play-next-rh (+ (rand-int 5) (* 12 (+ x 4)))))))
684e5007dbd6faef549f5b7c2d634d8faa8713ec582e5973faf75c1175bd38ba
emqx/emqx
emqx_mgmt_api_publish.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. 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. %%-------------------------------------------------------------------- -module(emqx_mgmt_api_publish). -include_lib("emqx/include/emqx.hrl"). -include_lib("emqx/include/emqx_mqtt.hrl"). -include_lib("typerefl/include/types.hrl"). -include_lib("emqx/include/logger.hrl"). -include_lib("hocon/include/hoconsc.hrl"). -define(ALL_IS_WELL, 200). -define(PARTIALLY_OK, 202). -define(BAD_REQUEST, 400). -define(DISPATCH_ERROR, 503). -behaviour(minirest_api). -export([ api_spec/0, paths/0, schema/1, fields/1 ]). -export([ publish/2, publish_batch/2 ]). api_spec() -> emqx_dashboard_swagger:spec(?MODULE, #{check_schema => true, translate_body => true}). paths() -> ["/publish", "/publish/bulk"]. schema("/publish") -> #{ 'operationId' => publish, post => #{ description => ?DESC(publish_api), tags => [<<"Publish">>], 'requestBody' => hoconsc:mk(hoconsc:ref(?MODULE, publish_message)), responses => #{ ?ALL_IS_WELL => hoconsc:mk(hoconsc:ref(?MODULE, publish_ok)), ?PARTIALLY_OK => hoconsc:mk(hoconsc:ref(?MODULE, publish_error)), ?BAD_REQUEST => bad_request_schema(), ?DISPATCH_ERROR => hoconsc:mk(hoconsc:ref(?MODULE, publish_error)) } } }; schema("/publish/bulk") -> #{ 'operationId' => publish_batch, post => #{ description => ?DESC(publish_bulk_api), tags => [<<"Publish">>], 'requestBody' => hoconsc:mk(hoconsc:array(hoconsc:ref(?MODULE, publish_message)), #{}), responses => #{ ?ALL_IS_WELL => hoconsc:mk(hoconsc:array(hoconsc:ref(?MODULE, publish_ok)), #{}), ?PARTIALLY_OK => hoconsc:mk( hoconsc:array(hoconsc:ref(?MODULE, publish_error)), #{} ), ?BAD_REQUEST => bad_request_schema(), ?DISPATCH_ERROR => hoconsc:mk( hoconsc:array(hoconsc:ref(?MODULE, publish_error)), #{} ) } } }. bad_request_schema() -> Union = hoconsc:union([ hoconsc:ref(?MODULE, bad_request), hoconsc:array(hoconsc:ref(?MODULE, publish_error)) ]), hoconsc:mk(Union, #{}). fields(message) -> [ {topic, hoconsc:mk(binary(), #{ desc => ?DESC(topic_name), required => true, example => <<"api/example/topic">> })}, {qos, hoconsc:mk(emqx_schema:qos(), #{ desc => ?DESC(qos), required => false, default => 0 })}, {clientid, hoconsc:mk(binary(), #{ deprecated => {since, "v5.0.14"} })}, {payload, hoconsc:mk(binary(), #{ desc => ?DESC(payload), required => true, example => <<"hello emqx api">> })}, {properties, hoconsc:mk(hoconsc:ref(?MODULE, message_properties), #{ desc => ?DESC(message_properties), required => false })}, {retain, hoconsc:mk(boolean(), #{ desc => ?DESC(retain), required => false, default => false })} ]; fields(publish_message) -> [ {payload_encoding, hoconsc:mk(hoconsc:enum([plain, base64]), #{ desc => ?DESC(payload_encoding), required => false, default => plain })} ] ++ fields(message); fields(message_properties) -> [ {'payload_format_indicator', hoconsc:mk(typerefl:range(0, 1), #{ desc => ?DESC(msg_payload_format_indicator), required => false, example => 0 })}, {'message_expiry_interval', hoconsc:mk(integer(), #{ desc => ?DESC(msg_message_expiry_interval), required => false })}, {'response_topic', hoconsc:mk(binary(), #{ desc => ?DESC(msg_response_topic), required => false, example => <<"some_other_topic">> })}, {'correlation_data', hoconsc:mk(binary(), #{ desc => ?DESC(msg_correlation_data), required => false })}, {'user_properties', hoconsc:mk(map(), #{ desc => ?DESC(msg_user_properties), required => false, example => #{<<"foo">> => <<"bar">>} })}, {'content_type', hoconsc:mk(binary(), #{ desc => ?DESC(msg_content_type), required => false, example => <<"text/plain">> })} ]; fields(publish_ok) -> [ {id, hoconsc:mk(binary(), #{ desc => ?DESC(message_id) })} ]; fields(publish_error) -> [ {reason_code, hoconsc:mk(integer(), #{ desc => ?DESC(reason_code), example => 16 })}, {message, hoconsc:mk(binary(), #{ desc => ?DESC(error_message), example => <<"no_matching_subscribers">> })} ]; fields(bad_request) -> [ {code, hoconsc:mk(string(), #{ desc => <<"BAD_REQUEST">> })}, {message, hoconsc:mk(binary(), #{ desc => ?DESC(error_message) })} ]. publish(post, #{body := Body}) -> case message(Body) of {ok, Message} -> Res = emqx_mgmt:publish(Message), publish_result_to_http_reply(Message, Res); {error, Reason} -> {?BAD_REQUEST, make_bad_req_reply(Reason)} end. publish_batch(post, #{body := Body}) -> case messages(Body) of {ok, Messages} -> ResList = lists:map( fun(Message) -> Res = emqx_mgmt:publish(Message), publish_result_to_http_reply(Message, Res) end, Messages ), publish_results_to_http_reply(ResList); {error, Reason} -> {?BAD_REQUEST, make_bad_req_reply(Reason)} end. make_bad_req_reply(invalid_topic_name) -> make_publish_error_response(?RC_TOPIC_NAME_INVALID); make_bad_req_reply(packet_too_large) -> 0x95 RC_PACKET_TOO_LARGE is not a PUBACK reason code %% This is why we use RC_QUOTA_EXCEEDED instead make_publish_error_response(?RC_QUOTA_EXCEEDED, packet_too_large); make_bad_req_reply(Reason) -> make_publish_error_response(?RC_IMPLEMENTATION_SPECIFIC_ERROR, to_binary(Reason)). -spec is_ok_deliver({_NodeOrShare, _MatchedTopic, emqx_types:deliver_result()}) -> boolean(). is_ok_deliver({_NodeOrShare, _MatchedTopic, ok}) -> true; is_ok_deliver({_NodeOrShare, _MatchedTopic, {ok, _}}) -> true; is_ok_deliver({_NodeOrShare, _MatchedTopic, {error, _}}) -> false. %% @hidden Map MQTT publish result reason code to HTTP status code. %% MQTT reason code | Description | HTTP status code 0 Success 200 16 No matching subscribers 202 128 Unspecified error 406 131 Implementation specific error 406 144 Topic Name invalid 400 151 Quota exceeded 400 %% %% %%%%%% Below error codes are not implemented so far %%%% %% %% If HTTP request passes HTTP authentication, it is considered trusted. 135 Not authorized 401 %% % % % % % % Below error codes are not applicable % % % % % % % %% %% No user specified packet ID, so there should be no packet ID error 145 Packet identifier is in use 400 %% %% No preceding payload format indicator to compare against. %% Content-Type check should be done at HTTP layer but not here. 153 Payload format invalid 400 publish_result_to_http_reply(_Message, []) -> %% matched no subscriber {?PARTIALLY_OK, make_publish_error_response(?RC_NO_MATCHING_SUBSCRIBERS)}; publish_result_to_http_reply(Message, PublishResult) -> case lists:any(fun is_ok_deliver/1, PublishResult) of true -> delivered to at least one subscriber OkBody = make_publish_response(Message), {?ALL_IS_WELL, OkBody}; false -> %% this is quite unusual, matched, but failed to deliver %% if this happens, the publish result log can be helpful %% to idnetify the reason why publish failed %% e.g. during emqx restart ReasonString = <<"failed_to_dispatch">>, ErrorBody = make_publish_error_response( ?RC_IMPLEMENTATION_SPECIFIC_ERROR, ReasonString ), ?SLOG(warning, #{ msg => ReasonString, message_id => emqx_message:id(Message), results => PublishResult }), {?DISPATCH_ERROR, ErrorBody} end. %% @hidden Reply batch publish result. 200 if all published OK . 202 if at least one message matched no subscribers . 503 for temp errors duing EMQX restart publish_results_to_http_reply([_ | _] = ResList) -> {Codes0, BodyL} = lists:unzip(ResList), Codes = lists:usort(Codes0), HasFailure = lists:member(?DISPATCH_ERROR, Codes), All200 = (Codes =:= [?ALL_IS_WELL]), Code = case All200 of true -> %% All OK ?ALL_IS_WELL; false when not HasFailure -> %% Partially OK ?PARTIALLY_OK; false -> At least one failed ?DISPATCH_ERROR end, {Code, BodyL}. message(Map) -> try make_message(Map) catch throw:Reason -> {error, Reason} end. make_message(Map) -> Encoding = maps:get(<<"payload_encoding">>, Map, plain), case decode_payload(Encoding, maps:get(<<"payload">>, Map)) of {ok, Payload} -> QoS = maps:get(<<"qos">>, Map, 0), Topic = maps:get(<<"topic">>, Map), Retain = maps:get(<<"retain">>, Map, false), Headers = case maps:get(<<"properties">>, Map, #{}) of Properties when is_map(Properties) andalso map_size(Properties) > 0 -> #{properties => to_msg_properties(Properties)}; _ -> #{} end, try _ = emqx_topic:validate(name, Topic) catch error:_Reason -> throw(invalid_topic_name) end, Message = emqx_message:make( http_api, QoS, Topic, Payload, #{retain => Retain}, Headers ), Size = emqx_message:estimate_size(Message), (Size > size_limit()) andalso throw(packet_too_large), {ok, Message}; {error, R} -> {error, R} end. to_msg_properties(Properties) -> maps:fold( fun to_property/3, #{}, Properties ). to_property(<<"payload_format_indicator">>, V, M) -> M#{'Payload-Format-Indicator' => V}; to_property(<<"message_expiry_interval">>, V, M) -> M#{'Message-Expiry-Interval' => V}; to_property(<<"response_topic">>, V, M) -> M#{'Response-Topic' => V}; to_property(<<"correlation_data">>, V, M) -> M#{'Correlation-Data' => V}; to_property(<<"user_properties">>, V, M) -> M#{'User-Property' => maps:to_list(V)}; to_property(<<"content_type">>, V, M) -> M#{'Content-Type' => V}. %% get the global packet size limit since HTTP API does not belong to any zone. size_limit() -> try emqx_config:get([mqtt, max_packet_size]) catch _:_ -> leave 1000 bytes for topic name etc . ?MAX_PACKET_SIZE end. decode_payload(plain, Payload) -> {ok, Payload}; decode_payload(base64, Payload) -> try {ok, base64:decode(Payload)} catch _:_ -> {error, {decode_base64_payload_failed, Payload}} end. messages([]) -> {errror, <<"empty_batch">>}; messages(List) -> messages(List, []). messages([], Res) -> {ok, lists:reverse(Res)}; messages([MessageMap | List], Res) -> case message(MessageMap) of {ok, Message} -> messages(List, [Message | Res]); {error, R} -> {error, R} end. make_publish_response(#message{id = ID}) -> #{ id => emqx_guid:to_hexstr(ID) }. make_publish_error_response(ReasonCode) -> make_publish_error_response(ReasonCode, emqx_reason_codes:name(ReasonCode)). make_publish_error_response(ReasonCode, Msg) -> #{ reason_code => ReasonCode, message => to_binary(Msg) }. to_binary(Atom) when is_atom(Atom) -> atom_to_binary(Atom); to_binary(Msg) when is_binary(Msg) -> Msg; to_binary(Term) -> list_to_binary(io_lib:format("~0p", [Term])).
null
https://raw.githubusercontent.com/emqx/emqx/6bbb5edb536957425f11fc7f7ce38032cbf97208/apps/emqx_management/src/emqx_mgmt_api_publish.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. -------------------------------------------------------------------- This is why we use RC_QUOTA_EXCEEDED instead @hidden Map MQTT publish result reason code to HTTP status code. MQTT reason code | Description | HTTP status code %%%%%% Below error codes are not implemented so far %%%% If HTTP request passes HTTP authentication, it is considered trusted. % % % % % Below error codes are not applicable % % % % % % % No user specified packet ID, so there should be no packet ID error No preceding payload format indicator to compare against. Content-Type check should be done at HTTP layer but not here. matched no subscriber this is quite unusual, matched, but failed to deliver if this happens, the publish result log can be helpful to idnetify the reason why publish failed e.g. during emqx restart @hidden Reply batch publish result. All OK Partially OK get the global packet size limit since HTTP API does not belong to any zone.
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. 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(emqx_mgmt_api_publish). -include_lib("emqx/include/emqx.hrl"). -include_lib("emqx/include/emqx_mqtt.hrl"). -include_lib("typerefl/include/types.hrl"). -include_lib("emqx/include/logger.hrl"). -include_lib("hocon/include/hoconsc.hrl"). -define(ALL_IS_WELL, 200). -define(PARTIALLY_OK, 202). -define(BAD_REQUEST, 400). -define(DISPATCH_ERROR, 503). -behaviour(minirest_api). -export([ api_spec/0, paths/0, schema/1, fields/1 ]). -export([ publish/2, publish_batch/2 ]). api_spec() -> emqx_dashboard_swagger:spec(?MODULE, #{check_schema => true, translate_body => true}). paths() -> ["/publish", "/publish/bulk"]. schema("/publish") -> #{ 'operationId' => publish, post => #{ description => ?DESC(publish_api), tags => [<<"Publish">>], 'requestBody' => hoconsc:mk(hoconsc:ref(?MODULE, publish_message)), responses => #{ ?ALL_IS_WELL => hoconsc:mk(hoconsc:ref(?MODULE, publish_ok)), ?PARTIALLY_OK => hoconsc:mk(hoconsc:ref(?MODULE, publish_error)), ?BAD_REQUEST => bad_request_schema(), ?DISPATCH_ERROR => hoconsc:mk(hoconsc:ref(?MODULE, publish_error)) } } }; schema("/publish/bulk") -> #{ 'operationId' => publish_batch, post => #{ description => ?DESC(publish_bulk_api), tags => [<<"Publish">>], 'requestBody' => hoconsc:mk(hoconsc:array(hoconsc:ref(?MODULE, publish_message)), #{}), responses => #{ ?ALL_IS_WELL => hoconsc:mk(hoconsc:array(hoconsc:ref(?MODULE, publish_ok)), #{}), ?PARTIALLY_OK => hoconsc:mk( hoconsc:array(hoconsc:ref(?MODULE, publish_error)), #{} ), ?BAD_REQUEST => bad_request_schema(), ?DISPATCH_ERROR => hoconsc:mk( hoconsc:array(hoconsc:ref(?MODULE, publish_error)), #{} ) } } }. bad_request_schema() -> Union = hoconsc:union([ hoconsc:ref(?MODULE, bad_request), hoconsc:array(hoconsc:ref(?MODULE, publish_error)) ]), hoconsc:mk(Union, #{}). fields(message) -> [ {topic, hoconsc:mk(binary(), #{ desc => ?DESC(topic_name), required => true, example => <<"api/example/topic">> })}, {qos, hoconsc:mk(emqx_schema:qos(), #{ desc => ?DESC(qos), required => false, default => 0 })}, {clientid, hoconsc:mk(binary(), #{ deprecated => {since, "v5.0.14"} })}, {payload, hoconsc:mk(binary(), #{ desc => ?DESC(payload), required => true, example => <<"hello emqx api">> })}, {properties, hoconsc:mk(hoconsc:ref(?MODULE, message_properties), #{ desc => ?DESC(message_properties), required => false })}, {retain, hoconsc:mk(boolean(), #{ desc => ?DESC(retain), required => false, default => false })} ]; fields(publish_message) -> [ {payload_encoding, hoconsc:mk(hoconsc:enum([plain, base64]), #{ desc => ?DESC(payload_encoding), required => false, default => plain })} ] ++ fields(message); fields(message_properties) -> [ {'payload_format_indicator', hoconsc:mk(typerefl:range(0, 1), #{ desc => ?DESC(msg_payload_format_indicator), required => false, example => 0 })}, {'message_expiry_interval', hoconsc:mk(integer(), #{ desc => ?DESC(msg_message_expiry_interval), required => false })}, {'response_topic', hoconsc:mk(binary(), #{ desc => ?DESC(msg_response_topic), required => false, example => <<"some_other_topic">> })}, {'correlation_data', hoconsc:mk(binary(), #{ desc => ?DESC(msg_correlation_data), required => false })}, {'user_properties', hoconsc:mk(map(), #{ desc => ?DESC(msg_user_properties), required => false, example => #{<<"foo">> => <<"bar">>} })}, {'content_type', hoconsc:mk(binary(), #{ desc => ?DESC(msg_content_type), required => false, example => <<"text/plain">> })} ]; fields(publish_ok) -> [ {id, hoconsc:mk(binary(), #{ desc => ?DESC(message_id) })} ]; fields(publish_error) -> [ {reason_code, hoconsc:mk(integer(), #{ desc => ?DESC(reason_code), example => 16 })}, {message, hoconsc:mk(binary(), #{ desc => ?DESC(error_message), example => <<"no_matching_subscribers">> })} ]; fields(bad_request) -> [ {code, hoconsc:mk(string(), #{ desc => <<"BAD_REQUEST">> })}, {message, hoconsc:mk(binary(), #{ desc => ?DESC(error_message) })} ]. publish(post, #{body := Body}) -> case message(Body) of {ok, Message} -> Res = emqx_mgmt:publish(Message), publish_result_to_http_reply(Message, Res); {error, Reason} -> {?BAD_REQUEST, make_bad_req_reply(Reason)} end. publish_batch(post, #{body := Body}) -> case messages(Body) of {ok, Messages} -> ResList = lists:map( fun(Message) -> Res = emqx_mgmt:publish(Message), publish_result_to_http_reply(Message, Res) end, Messages ), publish_results_to_http_reply(ResList); {error, Reason} -> {?BAD_REQUEST, make_bad_req_reply(Reason)} end. make_bad_req_reply(invalid_topic_name) -> make_publish_error_response(?RC_TOPIC_NAME_INVALID); make_bad_req_reply(packet_too_large) -> 0x95 RC_PACKET_TOO_LARGE is not a PUBACK reason code make_publish_error_response(?RC_QUOTA_EXCEEDED, packet_too_large); make_bad_req_reply(Reason) -> make_publish_error_response(?RC_IMPLEMENTATION_SPECIFIC_ERROR, to_binary(Reason)). -spec is_ok_deliver({_NodeOrShare, _MatchedTopic, emqx_types:deliver_result()}) -> boolean(). is_ok_deliver({_NodeOrShare, _MatchedTopic, ok}) -> true; is_ok_deliver({_NodeOrShare, _MatchedTopic, {ok, _}}) -> true; is_ok_deliver({_NodeOrShare, _MatchedTopic, {error, _}}) -> false. 0 Success 200 16 No matching subscribers 202 128 Unspecified error 406 131 Implementation specific error 406 144 Topic Name invalid 400 151 Quota exceeded 400 135 Not authorized 401 145 Packet identifier is in use 400 153 Payload format invalid 400 publish_result_to_http_reply(_Message, []) -> {?PARTIALLY_OK, make_publish_error_response(?RC_NO_MATCHING_SUBSCRIBERS)}; publish_result_to_http_reply(Message, PublishResult) -> case lists:any(fun is_ok_deliver/1, PublishResult) of true -> delivered to at least one subscriber OkBody = make_publish_response(Message), {?ALL_IS_WELL, OkBody}; false -> ReasonString = <<"failed_to_dispatch">>, ErrorBody = make_publish_error_response( ?RC_IMPLEMENTATION_SPECIFIC_ERROR, ReasonString ), ?SLOG(warning, #{ msg => ReasonString, message_id => emqx_message:id(Message), results => PublishResult }), {?DISPATCH_ERROR, ErrorBody} end. 200 if all published OK . 202 if at least one message matched no subscribers . 503 for temp errors duing EMQX restart publish_results_to_http_reply([_ | _] = ResList) -> {Codes0, BodyL} = lists:unzip(ResList), Codes = lists:usort(Codes0), HasFailure = lists:member(?DISPATCH_ERROR, Codes), All200 = (Codes =:= [?ALL_IS_WELL]), Code = case All200 of true -> ?ALL_IS_WELL; false when not HasFailure -> ?PARTIALLY_OK; false -> At least one failed ?DISPATCH_ERROR end, {Code, BodyL}. message(Map) -> try make_message(Map) catch throw:Reason -> {error, Reason} end. make_message(Map) -> Encoding = maps:get(<<"payload_encoding">>, Map, plain), case decode_payload(Encoding, maps:get(<<"payload">>, Map)) of {ok, Payload} -> QoS = maps:get(<<"qos">>, Map, 0), Topic = maps:get(<<"topic">>, Map), Retain = maps:get(<<"retain">>, Map, false), Headers = case maps:get(<<"properties">>, Map, #{}) of Properties when is_map(Properties) andalso map_size(Properties) > 0 -> #{properties => to_msg_properties(Properties)}; _ -> #{} end, try _ = emqx_topic:validate(name, Topic) catch error:_Reason -> throw(invalid_topic_name) end, Message = emqx_message:make( http_api, QoS, Topic, Payload, #{retain => Retain}, Headers ), Size = emqx_message:estimate_size(Message), (Size > size_limit()) andalso throw(packet_too_large), {ok, Message}; {error, R} -> {error, R} end. to_msg_properties(Properties) -> maps:fold( fun to_property/3, #{}, Properties ). to_property(<<"payload_format_indicator">>, V, M) -> M#{'Payload-Format-Indicator' => V}; to_property(<<"message_expiry_interval">>, V, M) -> M#{'Message-Expiry-Interval' => V}; to_property(<<"response_topic">>, V, M) -> M#{'Response-Topic' => V}; to_property(<<"correlation_data">>, V, M) -> M#{'Correlation-Data' => V}; to_property(<<"user_properties">>, V, M) -> M#{'User-Property' => maps:to_list(V)}; to_property(<<"content_type">>, V, M) -> M#{'Content-Type' => V}. size_limit() -> try emqx_config:get([mqtt, max_packet_size]) catch _:_ -> leave 1000 bytes for topic name etc . ?MAX_PACKET_SIZE end. decode_payload(plain, Payload) -> {ok, Payload}; decode_payload(base64, Payload) -> try {ok, base64:decode(Payload)} catch _:_ -> {error, {decode_base64_payload_failed, Payload}} end. messages([]) -> {errror, <<"empty_batch">>}; messages(List) -> messages(List, []). messages([], Res) -> {ok, lists:reverse(Res)}; messages([MessageMap | List], Res) -> case message(MessageMap) of {ok, Message} -> messages(List, [Message | Res]); {error, R} -> {error, R} end. make_publish_response(#message{id = ID}) -> #{ id => emqx_guid:to_hexstr(ID) }. make_publish_error_response(ReasonCode) -> make_publish_error_response(ReasonCode, emqx_reason_codes:name(ReasonCode)). make_publish_error_response(ReasonCode, Msg) -> #{ reason_code => ReasonCode, message => to_binary(Msg) }. to_binary(Atom) when is_atom(Atom) -> atom_to_binary(Atom); to_binary(Msg) when is_binary(Msg) -> Msg; to_binary(Term) -> list_to_binary(io_lib:format("~0p", [Term])).
32b93f57e17468bf0a94b0c7da53c5e1c3da71464c2792f69327ef295394551b
ds-wizard/engine-backend
DocumentTemplateDraftChangeJM.hs
module Wizard.Api.Resource.DocumentTemplate.Draft.DocumentTemplateDraftChangeJM where import Data.Aeson import Shared.Model.DocumentTemplate.DocumentTemplateJM () import Shared.Util.Aeson import Wizard.Api.Resource.DocumentTemplate.Draft.DocumentTemplateDraftChangeDTO instance FromJSON DocumentTemplateDraftChangeDTO where parseJSON = genericParseJSON jsonOptions instance ToJSON DocumentTemplateDraftChangeDTO where toJSON = genericToJSON jsonOptions
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Api/Resource/DocumentTemplate/Draft/DocumentTemplateDraftChangeJM.hs
haskell
module Wizard.Api.Resource.DocumentTemplate.Draft.DocumentTemplateDraftChangeJM where import Data.Aeson import Shared.Model.DocumentTemplate.DocumentTemplateJM () import Shared.Util.Aeson import Wizard.Api.Resource.DocumentTemplate.Draft.DocumentTemplateDraftChangeDTO instance FromJSON DocumentTemplateDraftChangeDTO where parseJSON = genericParseJSON jsonOptions instance ToJSON DocumentTemplateDraftChangeDTO where toJSON = genericToJSON jsonOptions
a1c0b729b37ffdda4289583614b5f48dc9a3e51edf3459b4220dae38d5f8846b
clojure-interop/google-cloud-clients
GrpcApplicationServiceStub.clj
(ns com.google.cloud.talent.v4beta1.stub.GrpcApplicationServiceStub "gRPC stub implementation for Cloud Talent Solution API. This class is for advanced usage and reflects the underlying API directly." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.talent.v4beta1.stub GrpcApplicationServiceStub])) (defn *create "client-context - `com.google.api.gax.rpc.ClientContext` callable-factory - `com.google.api.gax.grpc.GrpcStubCallableFactory` returns: `com.google.cloud.talent.v4beta1.stub.GrpcApplicationServiceStub` throws: java.io.IOException" (^com.google.cloud.talent.v4beta1.stub.GrpcApplicationServiceStub [^com.google.api.gax.rpc.ClientContext client-context ^com.google.api.gax.grpc.GrpcStubCallableFactory callable-factory] (GrpcApplicationServiceStub/create client-context callable-factory)) (^com.google.cloud.talent.v4beta1.stub.GrpcApplicationServiceStub [^com.google.cloud.talent.v4beta1.stub.ApplicationServiceStubSettings settings] (GrpcApplicationServiceStub/create settings))) (defn get-application-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.GetApplicationRequest,com.google.cloud.talent.v4beta1.Application>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.getApplicationCallable)))) (defn shutdown? "returns: `boolean`" (^Boolean [^GrpcApplicationServiceStub this] (-> this (.isShutdown)))) (defn await-termination "duration - `long` unit - `java.util.concurrent.TimeUnit` returns: `boolean` throws: java.lang.InterruptedException" (^Boolean [^GrpcApplicationServiceStub this ^Long duration ^java.util.concurrent.TimeUnit unit] (-> this (.awaitTermination duration unit)))) (defn shutdown "" ([^GrpcApplicationServiceStub this] (-> this (.shutdown)))) (defn update-application-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.UpdateApplicationRequest,com.google.cloud.talent.v4beta1.Application>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.updateApplicationCallable)))) (defn close "" ([^GrpcApplicationServiceStub this] (-> this (.close)))) (defn create-application-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.CreateApplicationRequest,com.google.cloud.talent.v4beta1.Application>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.createApplicationCallable)))) (defn delete-application-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.DeleteApplicationRequest,com.google.protobuf.Empty>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.deleteApplicationCallable)))) (defn terminated? "returns: `boolean`" (^Boolean [^GrpcApplicationServiceStub this] (-> this (.isTerminated)))) (defn list-applications-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.ListApplicationsRequest,com.google.cloud.talent.v4beta1.ListApplicationsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.listApplicationsCallable)))) (defn shutdown-now "" ([^GrpcApplicationServiceStub this] (-> this (.shutdownNow)))) (defn list-applications-paged-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.ListApplicationsRequest,com.google.cloud.talent.v4beta1.ApplicationServiceClient$ListApplicationsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.listApplicationsPagedCallable))))
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.talent/src/com/google/cloud/talent/v4beta1/stub/GrpcApplicationServiceStub.clj
clojure
(ns com.google.cloud.talent.v4beta1.stub.GrpcApplicationServiceStub "gRPC stub implementation for Cloud Talent Solution API. This class is for advanced usage and reflects the underlying API directly." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.talent.v4beta1.stub GrpcApplicationServiceStub])) (defn *create "client-context - `com.google.api.gax.rpc.ClientContext` callable-factory - `com.google.api.gax.grpc.GrpcStubCallableFactory` returns: `com.google.cloud.talent.v4beta1.stub.GrpcApplicationServiceStub` throws: java.io.IOException" (^com.google.cloud.talent.v4beta1.stub.GrpcApplicationServiceStub [^com.google.api.gax.rpc.ClientContext client-context ^com.google.api.gax.grpc.GrpcStubCallableFactory callable-factory] (GrpcApplicationServiceStub/create client-context callable-factory)) (^com.google.cloud.talent.v4beta1.stub.GrpcApplicationServiceStub [^com.google.cloud.talent.v4beta1.stub.ApplicationServiceStubSettings settings] (GrpcApplicationServiceStub/create settings))) (defn get-application-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.GetApplicationRequest,com.google.cloud.talent.v4beta1.Application>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.getApplicationCallable)))) (defn shutdown? "returns: `boolean`" (^Boolean [^GrpcApplicationServiceStub this] (-> this (.isShutdown)))) (defn await-termination "duration - `long` unit - `java.util.concurrent.TimeUnit` returns: `boolean` throws: java.lang.InterruptedException" (^Boolean [^GrpcApplicationServiceStub this ^Long duration ^java.util.concurrent.TimeUnit unit] (-> this (.awaitTermination duration unit)))) (defn shutdown "" ([^GrpcApplicationServiceStub this] (-> this (.shutdown)))) (defn update-application-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.UpdateApplicationRequest,com.google.cloud.talent.v4beta1.Application>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.updateApplicationCallable)))) (defn close "" ([^GrpcApplicationServiceStub this] (-> this (.close)))) (defn create-application-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.CreateApplicationRequest,com.google.cloud.talent.v4beta1.Application>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.createApplicationCallable)))) (defn delete-application-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.DeleteApplicationRequest,com.google.protobuf.Empty>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.deleteApplicationCallable)))) (defn terminated? "returns: `boolean`" (^Boolean [^GrpcApplicationServiceStub this] (-> this (.isTerminated)))) (defn list-applications-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.ListApplicationsRequest,com.google.cloud.talent.v4beta1.ListApplicationsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.listApplicationsCallable)))) (defn shutdown-now "" ([^GrpcApplicationServiceStub this] (-> this (.shutdownNow)))) (defn list-applications-paged-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.ListApplicationsRequest,com.google.cloud.talent.v4beta1.ApplicationServiceClient$ListApplicationsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^GrpcApplicationServiceStub this] (-> this (.listApplicationsPagedCallable))))
24265c8fab7bf8c85217c893ea5e4e2c92265e1ebebecb3b04eb5061543d6f60
vaibhavsagar/experiments
Double.hs
module Dotnet.System.Double where import Dotnet import qualified Dotnet.System.ValueType data Double_ a type Double a = Dotnet.System.ValueType.ValueType (Double_ a)
null
https://raw.githubusercontent.com/vaibhavsagar/experiments/378d7ba97eabfc7bbeaa4116380369ea6612bfeb/hugs/dotnet/lib/Dotnet/System/Double.hs
haskell
module Dotnet.System.Double where import Dotnet import qualified Dotnet.System.ValueType data Double_ a type Double a = Dotnet.System.ValueType.ValueType (Double_ a)
71d8f578e08108eb2f2e4fb44239383ee21261563006741d2946e3d202703d8d
vimalloc/apfs-auto-snapshot
SnapshotDatabase.hs
{-# LANGUAGE OverloadedStrings #-} module SnapshotDatabase where import TMSnapshot import Database.SQLite.Simple import Database.SQLite.Simple.FromField import Database.SQLite.Simple.Internal (Field(..)) -- TODO not great... import Database.SQLite.Simple.Ok import Database.SQLite.Simple.ToField import Data.Text (unpack) TODO move from String to Text everywhere TODO make all imports explicit data SnapshotTimeline = Yearly | Monthly | Weekly | Daily | Hourly | QuaterHourly instance ToField SnapshotTimeline where toField Yearly = toField ("yearly" :: String) toField Monthly = toField ("monthly" :: String) toField Weekly = toField ("weekly" :: String) toField Daily = toField ("daily" :: String) toField Hourly = toField ("hourly" :: String) toField QuaterHourly = toField ("quater_hourly" :: String) data StoredSnapshot = StoredSnapshot { snapshotId :: Int , snapshotName :: String } instance FromRow StoredSnapshot where fromRow = StoredSnapshot <$> field <*> field data StoredTimeline = StoredTimeline { timelineId :: Int , snapshotId' :: Int , snapshotType :: String } instance FromRow StoredTimeline where fromRow = StoredTimeline <$> field <*> field <*> field data LastInsertedRowId = LastInsertedRowId { lastInsertedRowId :: Int } instance FromRow LastInsertedRowId where fromRow = LastInsertedRowId <$> field getStoredSnapshots :: Connection -> IO [StoredSnapshot] getStoredSnapshots conn = query_ conn "SELECT * FROM snapshots" storeSnapshot :: Connection -> TMSnapshot -> IO StoredSnapshot storeSnapshot conn tmSnap = do execute conn "INSERT INTO snapshots (name) VALUES (?)" (Only (tmId tmSnap)) lastRowIdRes <- query_ conn "SELECT last_insert_rowid()" let snapId = lastInsertedRowId $ head lastRowIdRes snapRes <- query conn "SELECT * FROM snapshots WHERE id = (?)" (Only snapId) return $ head snapRes storeTimelines :: Connection -> StoredSnapshot -> [SnapshotTimeline] -> IO () storeTimelines conn snap timelines = mapM_ (storeTimeline conn snap) timelines where storeTimeline :: Connection -> StoredSnapshot -> SnapshotTimeline -> IO () storeTimeline conn snap timeline = execute conn query args where query = "INSERT INTO timelines (snapshot_id, snapshot_type) VALUES (?, ?)" args = (snapshotId snap, timeline) deleteStoredSnapshot :: Connection -> StoredSnapshot -> IO () deleteStoredSnapshot conn snap = execute conn query args where query = "DELETE FROM snapshots WHERE id = (?)" args = (Only (snapshotId snap)) deleteTimelines :: Connection -> SnapshotTimeline -> Int -> IO () deleteTimelines conn timeline numToKeep = do let timelineQuery = "SELECT * FROM timelines WHERE snapshot_type = (?)\ \ ORDER BY snapshot_id DESC" timelines <- query conn timelineQuery (Only timeline) let toRemove = drop numToKeep timelines mapM_ (deleteTimeline conn) toRemove where deleteTimeline :: Connection -> StoredTimeline -> IO () deleteTimeline conn tl = execute conn query args where query = "DELETE FROM timelines WHERE id = (?)" args = (Only (timelineId tl)) snapshotsWithoutTimelines :: Connection -> IO [StoredSnapshot] snapshotsWithoutTimelines conn = query_ conn query where query = "SELECT snapshots.* FROM snapshots LEFT JOIN timelines \ \ON snapshots.id = timelines.snapshot_id \ \WHERE timelines.snapshot_id IS NULL"
null
https://raw.githubusercontent.com/vimalloc/apfs-auto-snapshot/c38c3ad7060b4cec9e0e24a2b9e258a634a189e5/src/SnapshotDatabase.hs
haskell
# LANGUAGE OverloadedStrings # TODO not great...
module SnapshotDatabase where import TMSnapshot import Database.SQLite.Simple import Database.SQLite.Simple.FromField import Database.SQLite.Simple.Ok import Database.SQLite.Simple.ToField import Data.Text (unpack) TODO move from String to Text everywhere TODO make all imports explicit data SnapshotTimeline = Yearly | Monthly | Weekly | Daily | Hourly | QuaterHourly instance ToField SnapshotTimeline where toField Yearly = toField ("yearly" :: String) toField Monthly = toField ("monthly" :: String) toField Weekly = toField ("weekly" :: String) toField Daily = toField ("daily" :: String) toField Hourly = toField ("hourly" :: String) toField QuaterHourly = toField ("quater_hourly" :: String) data StoredSnapshot = StoredSnapshot { snapshotId :: Int , snapshotName :: String } instance FromRow StoredSnapshot where fromRow = StoredSnapshot <$> field <*> field data StoredTimeline = StoredTimeline { timelineId :: Int , snapshotId' :: Int , snapshotType :: String } instance FromRow StoredTimeline where fromRow = StoredTimeline <$> field <*> field <*> field data LastInsertedRowId = LastInsertedRowId { lastInsertedRowId :: Int } instance FromRow LastInsertedRowId where fromRow = LastInsertedRowId <$> field getStoredSnapshots :: Connection -> IO [StoredSnapshot] getStoredSnapshots conn = query_ conn "SELECT * FROM snapshots" storeSnapshot :: Connection -> TMSnapshot -> IO StoredSnapshot storeSnapshot conn tmSnap = do execute conn "INSERT INTO snapshots (name) VALUES (?)" (Only (tmId tmSnap)) lastRowIdRes <- query_ conn "SELECT last_insert_rowid()" let snapId = lastInsertedRowId $ head lastRowIdRes snapRes <- query conn "SELECT * FROM snapshots WHERE id = (?)" (Only snapId) return $ head snapRes storeTimelines :: Connection -> StoredSnapshot -> [SnapshotTimeline] -> IO () storeTimelines conn snap timelines = mapM_ (storeTimeline conn snap) timelines where storeTimeline :: Connection -> StoredSnapshot -> SnapshotTimeline -> IO () storeTimeline conn snap timeline = execute conn query args where query = "INSERT INTO timelines (snapshot_id, snapshot_type) VALUES (?, ?)" args = (snapshotId snap, timeline) deleteStoredSnapshot :: Connection -> StoredSnapshot -> IO () deleteStoredSnapshot conn snap = execute conn query args where query = "DELETE FROM snapshots WHERE id = (?)" args = (Only (snapshotId snap)) deleteTimelines :: Connection -> SnapshotTimeline -> Int -> IO () deleteTimelines conn timeline numToKeep = do let timelineQuery = "SELECT * FROM timelines WHERE snapshot_type = (?)\ \ ORDER BY snapshot_id DESC" timelines <- query conn timelineQuery (Only timeline) let toRemove = drop numToKeep timelines mapM_ (deleteTimeline conn) toRemove where deleteTimeline :: Connection -> StoredTimeline -> IO () deleteTimeline conn tl = execute conn query args where query = "DELETE FROM timelines WHERE id = (?)" args = (Only (timelineId tl)) snapshotsWithoutTimelines :: Connection -> IO [StoredSnapshot] snapshotsWithoutTimelines conn = query_ conn query where query = "SELECT snapshots.* FROM snapshots LEFT JOIN timelines \ \ON snapshots.id = timelines.snapshot_id \ \WHERE timelines.snapshot_id IS NULL"
fd5eb8ab7e27f4f578d8209c8754d5544a8e99852bbabc3de913b8aeca32bc90
MyDataFlow/ttalk-server
ejabberd_router.erl
%%%---------------------------------------------------------------------- File : ejabberd_router.erl Author : < > %%% Purpose : Main router Created : 27 Nov 2002 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2011 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License %%% along with this program; if not, write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA %%% %%%---------------------------------------------------------------------- -module(ejabberd_router). -author(''). -behaviour(gen_server). -behaviour(xmpp_router). %% API -export([route/3, route_error/4, register_route/1, register_route/2, register_routes/1, unregister_route/1, unregister_routes/1, dirty_get_all_routes/0, dirty_get_all_domains/0 ]). -export([start_link/0]). %% xmpp_router callback -export([do_route/3]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("ejabberd.hrl"). -include("jlib.hrl"). -type handler() :: 'undefined' | {'apply_fun',fun((_,_,_) -> any())} | {'apply', M::atom(), F::atom()}. -type domain() :: binary(). -record(route, {domain :: domain(), handler :: handler() }). -record(state, {}). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- %% Description: Starts the server %%-------------------------------------------------------------------- -spec start_link() -> 'ignore' | {'error',_} | {'ok',pid()}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -spec route(From :: ejabberd:jid(), To :: ejabberd:jid(), Packet :: jlib:xmlel()) -> ok. route(From, To, Packet) -> xmpp_router:route(?MODULE, From, To, Packet). %% Route the error packet only if the originating packet is not an error itself. %% RFC3920 9.3.1 -spec route_error(From :: ejabberd:jid(), To :: ejabberd:jid(), ErrPacket :: jlib:xmlel(), OrigPacket :: jlib:xmlel()) -> ok. route_error(From, To, ErrPacket, OrigPacket) -> #xmlel{attrs = Attrs} = OrigPacket, case <<"error">> == xml:get_attr_s(<<"type">>, Attrs) of false -> route(From, To, ErrPacket); true -> ok end. -spec register_route(Domain :: domain()) -> any(). register_route(Domain) -> register_route(Domain, undefined). -spec register_route(Domain :: domain(), Handler :: handler()) -> any(). register_route(Domain, Handler) -> register_route_to_ldomain(jid:nameprep(Domain), Domain, Handler). -spec register_routes([domain()]) -> 'ok'. register_routes(Domains) -> lists:foreach(fun(Domain) -> register_route(Domain) end, Domains). %% 注册本地域路由 -spec register_route_to_ldomain(binary(), domain(), handler()) -> any(). register_route_to_ldomain(error, Domain, _) -> erlang:error({invalid_domain, Domain}); register_route_to_ldomain(LDomain, _, HandlerOrUndef) -> Handler = make_handler(HandlerOrUndef), mnesia:dirty_write(#route{domain = LDomain, handler = Handler}). -spec make_handler(handler()) -> handler(). %% 如果没有制定handler,我们创建一个handler make_handler(undefined) -> Pid = self(), {apply_fun, fun(From, To, Packet) -> Pid ! {route, From, To, Packet} end}; make_handler({apply_fun, Fun} = Handler) when is_function(Fun, 3) -> Handler; make_handler({apply, Module, Function} = Handler) when is_atom(Module), is_atom(Function) -> Handler. unregister_route(Domain) -> case jid:nameprep(Domain) of error -> erlang:error({invalid_domain, Domain}); LDomain -> mnesia:dirty_delete(route, LDomain) end. unregister_routes(Domains) -> lists:foreach(fun(Domain) -> unregister_route(Domain) end, Domains). dirty_get_all_routes() -> lists:usort(mnesia:dirty_all_keys(route)) -- ?MYHOSTS. dirty_get_all_domains() -> lists:usort(mnesia:dirty_all_keys(route)). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([]) -> update_tables(), mnesia:create_table(route, [{ram_copies, [node()]}, {type, set}, {attributes, record_info(fields, route)}, {local_content, true}]), mnesia:add_table_copy(route, node(), ram_copies), {ok, #state{}}. %%-------------------------------------------------------------------- Function : handle_call(Request , From , State ) %% -> {reply, Reply, State} | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info({route, From, To, Packet}, State) -> route(From, To, Packet), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- %% 进行消息路由 do_route(OrigFrom, OrigTo, OrigPacket) -> ?DEBUG("route~n\tfrom ~p~n\tto ~p~n\tpacket ~p~n", [OrigFrom, OrigTo, OrigPacket]), %% Filter globally %% 先进行全局过滤 case ejabberd_hooks:run_fold(filter_packet, {OrigFrom, OrigTo, OrigPacket}, []) of {From, To, Packet} -> LDstDomain = To#jid.lserver, case mnesia:dirty_read(route, LDstDomain) of [] -> %% 如果不是自己负责的域名 %% 就交给s2s进行路有 ejabberd_s2s:route(From, To, Packet); [#route{handler=Handler}] -> do_local_route(OrigFrom, OrigTo, OrigPacket, LDstDomain, Handler) end; %% 如果是drop的话,就直接丢弃 drop -> ejabberd_hooks:run(xmpp_stanza_dropped, OrigFrom#jid.lserver, [OrigFrom, OrigTo, OrigPacket]), ok end. do_local_route(OrigFrom, OrigTo, OrigPacket, LDstDomain, Handler) -> %% Filter locally case ejabberd_hooks:run_fold(filter_local_packet, LDstDomain, {OrigFrom, OrigTo, OrigPacket}, []) of {From, To, Packet} -> case Handler of {apply_fun, Fun} -> Fun(From, To, Packet); {apply, Module, Function} -> Module:Function(From, To, Packet) end; drop -> ejabberd_hooks:run(xmpp_stanza_dropped, OrigFrom#jid.lserver, [OrigFrom, OrigTo, OrigPacket]), ok end. update_tables() -> case catch mnesia:table_info(route, attributes) of [domain, node, pid] -> mnesia:delete_table(route); [domain, pid] -> mnesia:delete_table(route); [domain, pid, local_hint] -> mnesia:delete_table(route); [domain, handler] -> ok; {'EXIT', _} -> ok end, case lists:member(local_route, mnesia:system_info(tables)) of true -> mnesia:delete_table(local_route); false -> ok end.
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/apps/ejabberd/src/ejabberd_router.erl
erlang
---------------------------------------------------------------------- Purpose : Main router This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software ---------------------------------------------------------------------- API xmpp_router callback gen_server callbacks ==================================================================== API ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- Route the error packet only if the originating packet is not an error itself. RFC3920 9.3.1 注册本地域路由 如果没有制定handler,我们创建一个handler ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- -> {reply, Reply, State} | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling all non call/cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate(Reason, State) -> void() Description: This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- 进行消息路由 Filter globally 先进行全局过滤 如果不是自己负责的域名 就交给s2s进行路有 如果是drop的话,就直接丢弃 Filter locally
File : ejabberd_router.erl Author : < > Created : 27 Nov 2002 by < > ejabberd , Copyright ( C ) 2002 - 2011 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA -module(ejabberd_router). -author(''). -behaviour(gen_server). -behaviour(xmpp_router). -export([route/3, route_error/4, register_route/1, register_route/2, register_routes/1, unregister_route/1, unregister_routes/1, dirty_get_all_routes/0, dirty_get_all_domains/0 ]). -export([start_link/0]). -export([do_route/3]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("ejabberd.hrl"). -include("jlib.hrl"). -type handler() :: 'undefined' | {'apply_fun',fun((_,_,_) -> any())} | {'apply', M::atom(), F::atom()}. -type domain() :: binary(). -record(route, {domain :: domain(), handler :: handler() }). -record(state, {}). -spec start_link() -> 'ignore' | {'error',_} | {'ok',pid()}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -spec route(From :: ejabberd:jid(), To :: ejabberd:jid(), Packet :: jlib:xmlel()) -> ok. route(From, To, Packet) -> xmpp_router:route(?MODULE, From, To, Packet). -spec route_error(From :: ejabberd:jid(), To :: ejabberd:jid(), ErrPacket :: jlib:xmlel(), OrigPacket :: jlib:xmlel()) -> ok. route_error(From, To, ErrPacket, OrigPacket) -> #xmlel{attrs = Attrs} = OrigPacket, case <<"error">> == xml:get_attr_s(<<"type">>, Attrs) of false -> route(From, To, ErrPacket); true -> ok end. -spec register_route(Domain :: domain()) -> any(). register_route(Domain) -> register_route(Domain, undefined). -spec register_route(Domain :: domain(), Handler :: handler()) -> any(). register_route(Domain, Handler) -> register_route_to_ldomain(jid:nameprep(Domain), Domain, Handler). -spec register_routes([domain()]) -> 'ok'. register_routes(Domains) -> lists:foreach(fun(Domain) -> register_route(Domain) end, Domains). -spec register_route_to_ldomain(binary(), domain(), handler()) -> any(). register_route_to_ldomain(error, Domain, _) -> erlang:error({invalid_domain, Domain}); register_route_to_ldomain(LDomain, _, HandlerOrUndef) -> Handler = make_handler(HandlerOrUndef), mnesia:dirty_write(#route{domain = LDomain, handler = Handler}). -spec make_handler(handler()) -> handler(). make_handler(undefined) -> Pid = self(), {apply_fun, fun(From, To, Packet) -> Pid ! {route, From, To, Packet} end}; make_handler({apply_fun, Fun} = Handler) when is_function(Fun, 3) -> Handler; make_handler({apply, Module, Function} = Handler) when is_atom(Module), is_atom(Function) -> Handler. unregister_route(Domain) -> case jid:nameprep(Domain) of error -> erlang:error({invalid_domain, Domain}); LDomain -> mnesia:dirty_delete(route, LDomain) end. unregister_routes(Domains) -> lists:foreach(fun(Domain) -> unregister_route(Domain) end, Domains). dirty_get_all_routes() -> lists:usort(mnesia:dirty_all_keys(route)) -- ?MYHOSTS. dirty_get_all_domains() -> lists:usort(mnesia:dirty_all_keys(route)). { ok , State , Timeout } | init([]) -> update_tables(), mnesia:create_table(route, [{ram_copies, [node()]}, {type, set}, {attributes, record_info(fields, route)}, {local_content, true}]), mnesia:add_table_copy(route, node(), ram_copies), {ok, #state{}}. Function : handle_call(Request , From , State ) { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info({route, From, To, Packet}, State) -> route(From, To, Packet), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions do_route(OrigFrom, OrigTo, OrigPacket) -> ?DEBUG("route~n\tfrom ~p~n\tto ~p~n\tpacket ~p~n", [OrigFrom, OrigTo, OrigPacket]), case ejabberd_hooks:run_fold(filter_packet, {OrigFrom, OrigTo, OrigPacket}, []) of {From, To, Packet} -> LDstDomain = To#jid.lserver, case mnesia:dirty_read(route, LDstDomain) of [] -> ejabberd_s2s:route(From, To, Packet); [#route{handler=Handler}] -> do_local_route(OrigFrom, OrigTo, OrigPacket, LDstDomain, Handler) end; drop -> ejabberd_hooks:run(xmpp_stanza_dropped, OrigFrom#jid.lserver, [OrigFrom, OrigTo, OrigPacket]), ok end. do_local_route(OrigFrom, OrigTo, OrigPacket, LDstDomain, Handler) -> case ejabberd_hooks:run_fold(filter_local_packet, LDstDomain, {OrigFrom, OrigTo, OrigPacket}, []) of {From, To, Packet} -> case Handler of {apply_fun, Fun} -> Fun(From, To, Packet); {apply, Module, Function} -> Module:Function(From, To, Packet) end; drop -> ejabberd_hooks:run(xmpp_stanza_dropped, OrigFrom#jid.lserver, [OrigFrom, OrigTo, OrigPacket]), ok end. update_tables() -> case catch mnesia:table_info(route, attributes) of [domain, node, pid] -> mnesia:delete_table(route); [domain, pid] -> mnesia:delete_table(route); [domain, pid, local_hint] -> mnesia:delete_table(route); [domain, handler] -> ok; {'EXIT', _} -> ok end, case lists:member(local_route, mnesia:system_info(tables)) of true -> mnesia:delete_table(local_route); false -> ok end.
d613634ba44eb6fa4a52e37630e0436bbcc5223e820b51d244739c6853a7c7c5
Dretch/monomer-hagrid
Main.hs
# LANGUAGE EmptyCase # # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # module Main (main) where import Data.Function ((&)) import Data.Sequence (Seq) import qualified Data.Sequence as S import Data.Text (Text, dropWhile, dropWhileEnd, pack, splitOn, strip) import Data.Text.IO (readFile) import Monomer import Monomer.Hagrid (estimatedItemHeight, hagrid_, initialWidth, textColumn, widgetColumn) import Prelude hiding (dropWhile, readFile) newtype AppModel = AppModel { paragraphs :: Seq Text } deriving (Eq, Show) data AppEvent main :: IO () main = do paragraphs <- splitParagraphs <$> readFile "./assets/etc/war-and-peace.txt" startApp (model paragraphs) handleEvent buildUI config where config = [ appWindowTitle "Hagrid Big Grid Example", appFontDef "Bold" "./assets/fonts/Cantarell/Cantarell-Bold.ttf", appFontDef "Regular" "./assets/fonts/Cantarell/Cantarell-Regular.ttf", appTheme darkTheme, appDisableAutoScale True, appWindowState (MainWindowNormal (1200, 1000)) ] model paragraphs = AppModel { paragraphs } buildUI :: UIBuilder AppModel AppEvent buildUI _wenv model = tree where tree = hagrid_ [estimatedItemHeight 100] [ (textColumn "Author" (const "Leo Tolstoy")) {initialWidth = 180}, (textColumn "Title" (const "War and Peace")) {initialWidth = 160}, widgetColumn "Line Index" (\i _ -> label (pack (show i))), (widgetColumn "Line" (\_ para -> label_ para [multiline, ellipsis])) {initialWidth = 760} ] model.paragraphs handleEvent :: EventHandler AppModel AppEvent sp ep handleEvent _wenv _node _model = \case {} splitParagraphs :: Text -> Seq Text splitParagraphs s = splitOn "\n\n" s & S.fromList & fmap (dropWhile (== '\n') . dropWhileEnd (== '\n')) & S.filter ((/= mempty) . strip)
null
https://raw.githubusercontent.com/Dretch/monomer-hagrid/9e214d7450b790e292ef25a8b5c307c39ebe511b/example-big-grid/Main.hs
haskell
# LANGUAGE EmptyCase # # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # module Main (main) where import Data.Function ((&)) import Data.Sequence (Seq) import qualified Data.Sequence as S import Data.Text (Text, dropWhile, dropWhileEnd, pack, splitOn, strip) import Data.Text.IO (readFile) import Monomer import Monomer.Hagrid (estimatedItemHeight, hagrid_, initialWidth, textColumn, widgetColumn) import Prelude hiding (dropWhile, readFile) newtype AppModel = AppModel { paragraphs :: Seq Text } deriving (Eq, Show) data AppEvent main :: IO () main = do paragraphs <- splitParagraphs <$> readFile "./assets/etc/war-and-peace.txt" startApp (model paragraphs) handleEvent buildUI config where config = [ appWindowTitle "Hagrid Big Grid Example", appFontDef "Bold" "./assets/fonts/Cantarell/Cantarell-Bold.ttf", appFontDef "Regular" "./assets/fonts/Cantarell/Cantarell-Regular.ttf", appTheme darkTheme, appDisableAutoScale True, appWindowState (MainWindowNormal (1200, 1000)) ] model paragraphs = AppModel { paragraphs } buildUI :: UIBuilder AppModel AppEvent buildUI _wenv model = tree where tree = hagrid_ [estimatedItemHeight 100] [ (textColumn "Author" (const "Leo Tolstoy")) {initialWidth = 180}, (textColumn "Title" (const "War and Peace")) {initialWidth = 160}, widgetColumn "Line Index" (\i _ -> label (pack (show i))), (widgetColumn "Line" (\_ para -> label_ para [multiline, ellipsis])) {initialWidth = 760} ] model.paragraphs handleEvent :: EventHandler AppModel AppEvent sp ep handleEvent _wenv _node _model = \case {} splitParagraphs :: Text -> Seq Text splitParagraphs s = splitOn "\n\n" s & S.fromList & fmap (dropWhile (== '\n') . dropWhileEnd (== '\n')) & S.filter ((/= mempty) . strip)
8b8d17a0674d6d17f077681e7f25682727995a836c9d61a8aba17578426bf121
coq/coq
workerLoop.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) *) (************************************************************************) let kind_filter str = let kinds = [ "--kind=proof"; "--kind=tactic"; "--kind=query" ] in not (List.exists (String.equal str) kinds) let worker_parse_extra extra_args = let stm_opts, extra_args = Stmargs.parse_args ~init:Stm.AsyncOpts.default_opts extra_args in let extra_args = List.filter kind_filter extra_args in ((),stm_opts), extra_args let worker_init init ((),stm_opts) injections ~opts : Vernac.State.t = Flags.quiet := true; init (); Coqtop.init_toploop opts stm_opts injections let usage = Boot.Usage.{ executable_name = "coqworker"; extra_args = ""; extra_options = ("\n" ^ "coqworker" ^ " specific options:\ \n --xml_format=Ppcmds serialize pretty printing messages using the std_ppcmds format\n"); } let start ~init ~loop = let open Coqtop in let custom = { parse_extra = worker_parse_extra; usage; initial_args = Coqargs.default; init_extra = worker_init init; run = (fun ((),_) ~opts:_ (_state : Vernac.State.t) -> the state is not used since the worker will receive one from master loop ()); } in start_coq custom
null
https://raw.githubusercontent.com/coq/coq/c4587fa780c885fda25a38a2f16e84dc9011f9bd/toplevel/workerLoop.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) **********************************************************************
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 let kind_filter str = let kinds = [ "--kind=proof"; "--kind=tactic"; "--kind=query" ] in not (List.exists (String.equal str) kinds) let worker_parse_extra extra_args = let stm_opts, extra_args = Stmargs.parse_args ~init:Stm.AsyncOpts.default_opts extra_args in let extra_args = List.filter kind_filter extra_args in ((),stm_opts), extra_args let worker_init init ((),stm_opts) injections ~opts : Vernac.State.t = Flags.quiet := true; init (); Coqtop.init_toploop opts stm_opts injections let usage = Boot.Usage.{ executable_name = "coqworker"; extra_args = ""; extra_options = ("\n" ^ "coqworker" ^ " specific options:\ \n --xml_format=Ppcmds serialize pretty printing messages using the std_ppcmds format\n"); } let start ~init ~loop = let open Coqtop in let custom = { parse_extra = worker_parse_extra; usage; initial_args = Coqargs.default; init_extra = worker_init init; run = (fun ((),_) ~opts:_ (_state : Vernac.State.t) -> the state is not used since the worker will receive one from master loop ()); } in start_coq custom
b371850e0470f53e02e49285a7ca677553fd12a608d40d9cbcbc4bea607b296f
AbstractMachinesLab/caramel
config.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (***********************************************************************) (** **) (** WARNING WARNING WARNING **) (** **) (** When you change this file, you must make the parallel change **) (** in config.mlbuild **) (** **) (***********************************************************************) open Local_store.Compiler (* The main OCaml version string has moved to ../VERSION *) let version = Sys.ocaml_version let flambda = false let exec_magic_number = "Caml1999X023" and cmi_magic_number = "Caml1999I023" and cmo_magic_number = "Caml1999O023" and cma_magic_number = "Caml1999A023" and cmx_magic_number = if flambda then "Caml1999y023" else "Caml1999Y023" and cmxa_magic_number = if flambda then "Caml1999z023" else "Caml1999Z023" and ast_impl_magic_number = "Caml1999M023" and ast_intf_magic_number = "Caml1999N023" and cmxs_magic_number = "Caml1999D023" cmxs_magic_number is duplicated in otherlibs / dynlink / natdynlink.ml and cmt_magic_number = "Caml1999T023" let load_path = srefk ([] : string list) let interface_suffix = ref ".mli" let max_tag = 245 let safe_string = true let flat_float_array = false
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/src/ocaml/utils/407_0/config.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ ********************************************************************* * * * WARNING WARNING WARNING * * * * When you change this file, you must make the parallel change * * in config.mlbuild * * * ********************************************************************* The main OCaml version string has moved to ../VERSION
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Local_store.Compiler let version = Sys.ocaml_version let flambda = false let exec_magic_number = "Caml1999X023" and cmi_magic_number = "Caml1999I023" and cmo_magic_number = "Caml1999O023" and cma_magic_number = "Caml1999A023" and cmx_magic_number = if flambda then "Caml1999y023" else "Caml1999Y023" and cmxa_magic_number = if flambda then "Caml1999z023" else "Caml1999Z023" and ast_impl_magic_number = "Caml1999M023" and ast_intf_magic_number = "Caml1999N023" and cmxs_magic_number = "Caml1999D023" cmxs_magic_number is duplicated in otherlibs / dynlink / natdynlink.ml and cmt_magic_number = "Caml1999T023" let load_path = srefk ([] : string list) let interface_suffix = ref ".mli" let max_tag = 245 let safe_string = true let flat_float_array = false
2a62d561754b200f1917a297746bb7aef748c89c1d8a56a20da02a594270cac9
thattommyhall/offline-4clojure
p63.clj
Group a Sequence - Easy ;; Given a function f and a sequence s, write a function which returns a map. The keys should be the values of f applied to each item in s. The value at each key should be a vector of corresponding items in the order they appear in s. ;; tags - core-functions ;; restricted - group-by (ns offline-4clojure.p63 (:use clojure.test)) (def __ ;; your solution here ) (defn -main [] (are [soln] soln (= (__ #(> % 5) [1 3 6 8]) {false [1 3], true [6 8]}) (= (__ #(apply / %) [[1 2] [2 4] [4 6] [3 6]]) {1/2 [[1 2] [2 4] [3 6]], 2/3 [[4 6]]}) (= (__ count [[1] [1 2] [3] [1 2 3] [2 3]]) {1 [[1] [3]], 2 [[1 2] [2 3]], 3 [[1 2 3]]}) ))
null
https://raw.githubusercontent.com/thattommyhall/offline-4clojure/73e32fc6687816aea3c514767cef3916176589ab/src/offline_4clojure/p63.clj
clojure
Given a function f and a sequence s, write a function which returns a map. The keys should be the values of f applied to each item in s. The value at each key should be a vector of corresponding items in the order they appear in s. tags - core-functions restricted - group-by your solution here
Group a Sequence - Easy (ns offline-4clojure.p63 (:use clojure.test)) (def __ ) (defn -main [] (are [soln] soln (= (__ #(> % 5) [1 3 6 8]) {false [1 3], true [6 8]}) (= (__ #(apply / %) [[1 2] [2 4] [4 6] [3 6]]) {1/2 [[1 2] [2 4] [3 6]], 2/3 [[4 6]]}) (= (__ count [[1] [1 2] [3] [1 2 3] [2 3]]) {1 [[1] [3]], 2 [[1 2] [2 3]], 3 [[1 2 3]]}) ))
4655d9a0fb50a7123c509bb1dd50c91a220d8e5302420adededf4ba33998b17c
haskell-tools/haskell-tools
Helpers.hs
# LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # {-# LANGUAGE RankNTypes #-} -- | Helper functions for defining refactorings. module Language.Haskell.Tools.Refactor.Utils.Helpers where import Control.Monad.State () import Control.Reference import Data.Function (on) import Data.List (sortBy, nubBy, groupBy) import Data.Maybe (Maybe(..)) import Language.Haskell.Tools.AST as AST import Language.Haskell.Tools.Refactor.Utils.Lists (filterList) import Language.Haskell.Tools.Rewrite as AST import SrcLoc (srcSpanStart) replaceWithJust :: Ann e IdDom SrcTemplateStage -> AnnMaybe e -> AnnMaybe e replaceWithJust e = annMaybe .= Just e replaceWithNothing :: AnnMaybe e -> AnnMaybe e replaceWithNothing = annMaybe .= Nothing -- | Remove the container (where or let) when the last binding is removed. removeEmptyBnds :: Simple Traversal Module ValueBind -> Simple Traversal Module Expr -> AST.Module -> AST.Module removeEmptyBnds binds exprs = (binds .- removeEmptyBindsAndGuards) . (exprs .- removeEmptyLetsAndStmts) where removeEmptyBindsAndGuards sb@(SimpleBind _ _ _) = (valBindLocals .- removeIfEmpty) . (valBindRhs .- removeEmptyGuards) $ sb removeEmptyBindsAndGuards fb@(FunctionBind _) = (funBindMatches & annList & matchBinds .- removeIfEmpty) . (funBindMatches & annList & matchRhs .- removeEmptyGuards) $ fb removeEmptyGuards rhs = rhsGuards & annList & guardStmts .- filterList (\case GuardLet (AnnList []) -> False; _ -> True) $ rhs removeIfEmpty mb@(AnnJust (LocalBinds (AnnList []))) = annMaybe .= Nothing $ mb removeIfEmpty mb = mb removeEmptyLetsAndStmts (Let (AnnList []) e) = e removeEmptyLetsAndStmts e = exprStmts .- removeEmptyStmts $ e removeEmptyStmts ls = (annList & cmdStmtBinds .- removeEmptyStmts) . filterList (\case LetStmt (AnnList []) -> False; _ -> True) $ ls -- | Puts the elements in the orginal order and remove duplicates (elements with the same source range) normalizeElements :: [Ann e dom SrcTemplateStage] -> [Ann e dom SrcTemplateStage] normalizeElements elems = nubBy ((==) `on` getRange) $ sortBy (compare `on` srcSpanStart . getRange) elems -- | Groups elements together into equivalence groups. groupElemsBy :: Ord k => (a -> k) -> [a] -> [[a]] groupElemsBy f = map (map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst) . map ((,) <$> f <*> id) -- | Chooses a representative element for each equivalence group, -- and pairs them with their corresponding group. reprElems :: [[a]] -> [(a,[a])] reprElems = map ((,) <$> head <*> id) -- | Sorts the elements of a list into equivalence groups based on a function, -- then chooses a representative element for each group, -- and pairs them with their corresponding group. equivalenceGroupsBy :: Ord k => (a -> k) -> [a] -> [(a,[a])] equivalenceGroupsBy f = reprElems . groupElemsBy f
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/refactor/Language/Haskell/Tools/Refactor/Utils/Helpers.hs
haskell
# LANGUAGE RankNTypes # | Helper functions for defining refactorings. | Remove the container (where or let) when the last binding is removed. | Puts the elements in the orginal order and remove duplicates (elements with the same source range) | Groups elements together into equivalence groups. | Chooses a representative element for each equivalence group, and pairs them with their corresponding group. | Sorts the elements of a list into equivalence groups based on a function, then chooses a representative element for each group, and pairs them with their corresponding group.
# LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # module Language.Haskell.Tools.Refactor.Utils.Helpers where import Control.Monad.State () import Control.Reference import Data.Function (on) import Data.List (sortBy, nubBy, groupBy) import Data.Maybe (Maybe(..)) import Language.Haskell.Tools.AST as AST import Language.Haskell.Tools.Refactor.Utils.Lists (filterList) import Language.Haskell.Tools.Rewrite as AST import SrcLoc (srcSpanStart) replaceWithJust :: Ann e IdDom SrcTemplateStage -> AnnMaybe e -> AnnMaybe e replaceWithJust e = annMaybe .= Just e replaceWithNothing :: AnnMaybe e -> AnnMaybe e replaceWithNothing = annMaybe .= Nothing removeEmptyBnds :: Simple Traversal Module ValueBind -> Simple Traversal Module Expr -> AST.Module -> AST.Module removeEmptyBnds binds exprs = (binds .- removeEmptyBindsAndGuards) . (exprs .- removeEmptyLetsAndStmts) where removeEmptyBindsAndGuards sb@(SimpleBind _ _ _) = (valBindLocals .- removeIfEmpty) . (valBindRhs .- removeEmptyGuards) $ sb removeEmptyBindsAndGuards fb@(FunctionBind _) = (funBindMatches & annList & matchBinds .- removeIfEmpty) . (funBindMatches & annList & matchRhs .- removeEmptyGuards) $ fb removeEmptyGuards rhs = rhsGuards & annList & guardStmts .- filterList (\case GuardLet (AnnList []) -> False; _ -> True) $ rhs removeIfEmpty mb@(AnnJust (LocalBinds (AnnList []))) = annMaybe .= Nothing $ mb removeIfEmpty mb = mb removeEmptyLetsAndStmts (Let (AnnList []) e) = e removeEmptyLetsAndStmts e = exprStmts .- removeEmptyStmts $ e removeEmptyStmts ls = (annList & cmdStmtBinds .- removeEmptyStmts) . filterList (\case LetStmt (AnnList []) -> False; _ -> True) $ ls normalizeElements :: [Ann e dom SrcTemplateStage] -> [Ann e dom SrcTemplateStage] normalizeElements elems = nubBy ((==) `on` getRange) $ sortBy (compare `on` srcSpanStart . getRange) elems groupElemsBy :: Ord k => (a -> k) -> [a] -> [[a]] groupElemsBy f = map (map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst) . map ((,) <$> f <*> id) reprElems :: [[a]] -> [(a,[a])] reprElems = map ((,) <$> head <*> id) equivalenceGroupsBy :: Ord k => (a -> k) -> [a] -> [(a,[a])] equivalenceGroupsBy f = reprElems . groupElemsBy f
0eec3459365b00e9ceb09fa3cc30b4b8350a29a418bb48cd5060ec96a50b6aed
monadicsystems/okapi
Main.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # module Main where import Control.Applicative ((<|>)) import Data.Aeson (ToJSON) import Data.Function ((&)) import Data.Text import GHC.Generics (Generic) import Okapi main :: IO () main = run id calc type Okapi a = OkapiT IO a calc :: Okapi Response calc = do methodGET pathParam @Text `is` "calc" addOp <|> subOp <|> mulOp <|> divOp respond :: Response -> Okapi Response respond response = do methodEnd pathEnd queryEnd pure response addOp :: Okapi Response addOp = do pathParam @Text `is` "add" (x, y) <- getArgs ok & setJSON (x + y) & respond subOp :: Okapi Response subOp = do pathParam @Text `is` "sub" <|> pathParam @Text `is` "minus" (x, y) <- getArgs ok & setJSON (x - y) & respond mulOp :: Okapi Response mulOp = do pathParam @Text `is` "mul" (x, y) <- getArgs ok & setJSON (x * y) & respond data DivResult = DivResult { answer :: Int, remainder :: Int } deriving (Eq, Show, Generic, ToJSON) divOp :: Okapi Response divOp = do pathParam @Text `is` "div" (x, y) <- getArgs guardThrow forbidden (y == 0) ok & setJSON DivResult {answer = x `div` y, remainder = x `mod` y} & respond getArgs :: Okapi (Int, Int) getArgs = getArgsFromPath <|> getArgsFromQueryParams where getArgsFromPath :: Okapi (Int, Int) getArgsFromPath = do x <- pathParam y <- pathParam pure (x, y) getArgsFromQueryParams :: Okapi (Int, Int) getArgsFromQueryParams = do x <- queryParam "x" y <- queryParam "y" pure (x, y)
null
https://raw.githubusercontent.com/monadicsystems/okapi/3d7215ec954479b80322594dc4b89afd834e095e/examples/calculator/Main.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings #
# LANGUAGE DeriveGeneric # # LANGUAGE TypeApplications # module Main where import Control.Applicative ((<|>)) import Data.Aeson (ToJSON) import Data.Function ((&)) import Data.Text import GHC.Generics (Generic) import Okapi main :: IO () main = run id calc type Okapi a = OkapiT IO a calc :: Okapi Response calc = do methodGET pathParam @Text `is` "calc" addOp <|> subOp <|> mulOp <|> divOp respond :: Response -> Okapi Response respond response = do methodEnd pathEnd queryEnd pure response addOp :: Okapi Response addOp = do pathParam @Text `is` "add" (x, y) <- getArgs ok & setJSON (x + y) & respond subOp :: Okapi Response subOp = do pathParam @Text `is` "sub" <|> pathParam @Text `is` "minus" (x, y) <- getArgs ok & setJSON (x - y) & respond mulOp :: Okapi Response mulOp = do pathParam @Text `is` "mul" (x, y) <- getArgs ok & setJSON (x * y) & respond data DivResult = DivResult { answer :: Int, remainder :: Int } deriving (Eq, Show, Generic, ToJSON) divOp :: Okapi Response divOp = do pathParam @Text `is` "div" (x, y) <- getArgs guardThrow forbidden (y == 0) ok & setJSON DivResult {answer = x `div` y, remainder = x `mod` y} & respond getArgs :: Okapi (Int, Int) getArgs = getArgsFromPath <|> getArgsFromQueryParams where getArgsFromPath :: Okapi (Int, Int) getArgsFromPath = do x <- pathParam y <- pathParam pure (x, y) getArgsFromQueryParams :: Okapi (Int, Int) getArgsFromQueryParams = do x <- queryParam "x" y <- queryParam "y" pure (x, y)
9afd1b8702e9820fa72e4b81849cdc61ef40c4a171e291794808b4f0448d056d
zjhmale/Ntha
Logic.hs
-- | Predicates module Ntha.Z3.Logic (Pred(..)) where data Pred t ty a where PTrue :: Pred t ty a PFalse :: Pred t ty a PConj :: Pred t ty a -> Pred t ty a -> Pred t ty a PDisj :: Pred t ty a -> Pred t ty a -> Pred t ty a PXor :: Pred t ty a -> Pred t ty a -> Pred t ty a PNeg :: Pred t ty a -> Pred t ty a PForAll :: String -> ty -> Pred t ty a -> Pred t ty a PExists :: String -> ty -> Pred t ty a -> Pred t ty a PExists2 :: String -> String -> ty -> Pred t ty a -> Pred t ty a PImpli :: Pred t ty a -> Pred t ty a -> Pred t ty a PIff :: Pred t ty a -> Pred t ty a -> Pred t ty a PAssert :: a -> Pred t ty a deriving (Show)
null
https://raw.githubusercontent.com/zjhmale/Ntha/dc47fafddf67cf821c90c5cd72566de67d996238/src/Ntha/Z3/Logic.hs
haskell
| Predicates
module Ntha.Z3.Logic (Pred(..)) where data Pred t ty a where PTrue :: Pred t ty a PFalse :: Pred t ty a PConj :: Pred t ty a -> Pred t ty a -> Pred t ty a PDisj :: Pred t ty a -> Pred t ty a -> Pred t ty a PXor :: Pred t ty a -> Pred t ty a -> Pred t ty a PNeg :: Pred t ty a -> Pred t ty a PForAll :: String -> ty -> Pred t ty a -> Pred t ty a PExists :: String -> ty -> Pred t ty a -> Pred t ty a PExists2 :: String -> String -> ty -> Pred t ty a -> Pred t ty a PImpli :: Pred t ty a -> Pred t ty a -> Pred t ty a PIff :: Pred t ty a -> Pred t ty a -> Pred t ty a PAssert :: a -> Pred t ty a deriving (Show)
eaea81f69dd883f54e4a3e2f0e692f293bff357e87afbdd37bb12b1ebe4b5c60
clj-kondo/clj-kondo
compojure_test.clj
(ns clj-kondo.compojure-test (:require [clj-kondo.test-utils :refer [lint!]] [clojure.java.io :as io] [clojure.test :as t :refer [deftest is testing]] [missing.test.assertions])) (deftest compojure-test (is (empty? (lint! (io/file "corpus" "compojure" "core_test.clj")))))
null
https://raw.githubusercontent.com/clj-kondo/clj-kondo/626978461cbf113c376634cdf034d7262deb429f/test/clj_kondo/compojure_test.clj
clojure
(ns clj-kondo.compojure-test (:require [clj-kondo.test-utils :refer [lint!]] [clojure.java.io :as io] [clojure.test :as t :refer [deftest is testing]] [missing.test.assertions])) (deftest compojure-test (is (empty? (lint! (io/file "corpus" "compojure" "core_test.clj")))))