_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
2fcbd8f1ad316b685e6ca696505b0d8ee21d32cc09ef3344ef3cc2ae056812cf
project-oak/hafnium-verification
ClangQuotes.ml
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) (** module for escaping clang arguments on the command line and put them into files *) open! IStd module L = Logging (** quoting style of the arguments *) type style = | EscapedDoubleQuotes (** the arguments should be enclosed in "double quotes" and are already escaped *) | SingleQuotes (** the arguments should be enclosed in 'single quotes' and have to be escaped *) | EscapedNoQuotes (** the arguments should not be enclosed in quotes and are already escaped *) let quote style = match style with | EscapedNoQuotes -> fun s -> s | EscapedDoubleQuotes -> fun s -> "\"" ^ s ^ "\"" | SingleQuotes -> fun s -> Escape.escape_in_single_quotes s let mk_arg_file prefix style args = let file = Filename.temp_file prefix ".txt" in let write_args outc = List.iter ~f:(fun arg -> quote style arg |> Out_channel.output_string outc ; Out_channel.newline outc ) args in Utils.with_file_out file ~f:write_args ; L.(debug Capture Medium) "Clang options stored in file %s@\n" file ; if not Config.debug_mode then Utils.unlink_file_on_exit file ; file
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/integration/ClangQuotes.ml
ocaml
* module for escaping clang arguments on the command line and put them into files * quoting style of the arguments * the arguments should be enclosed in "double quotes" and are already escaped * the arguments should be enclosed in 'single quotes' and have to be escaped * the arguments should not be enclosed in quotes and are already escaped
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module L = Logging type style = | EscapedDoubleQuotes let quote style = match style with | EscapedNoQuotes -> fun s -> s | EscapedDoubleQuotes -> fun s -> "\"" ^ s ^ "\"" | SingleQuotes -> fun s -> Escape.escape_in_single_quotes s let mk_arg_file prefix style args = let file = Filename.temp_file prefix ".txt" in let write_args outc = List.iter ~f:(fun arg -> quote style arg |> Out_channel.output_string outc ; Out_channel.newline outc ) args in Utils.with_file_out file ~f:write_args ; L.(debug Capture Medium) "Clang options stored in file %s@\n" file ; if not Config.debug_mode then Utils.unlink_file_on_exit file ; file
ed1fbe0709de0117fd79af44e6d47689cf02948d2360f2613279ce86ee68f3e5
basho/riak_api
riak_api_test_util.erl
-module(riak_api_test_util). -compile([export_all, nowarn_export_all]). wait_for_application_shutdown(App) -> case lists:keymember(App, 1, application:which_applications()) of true -> timer:sleep(250), wait_for_application_shutdown(App); false -> ok end. The following three functions build a list of dependent %% applications. They will not handle circular or mutually-dependent %% applications. dep_apps(App) -> application:load(App), {ok, Apps} = application:get_key(App, applications), Apps. all_deps(App, Deps) -> [[ all_deps(Dep, [App|Deps]) || Dep <- dep_apps(App), not lists:member(Dep, Deps)], App]. resolve_deps(App) -> DepList = all_deps(App, []), {AppOrder, _} = lists:foldl(fun(A,{List,Set}) -> case sets:is_element(A, Set) of true -> {List, Set}; false -> {List ++ [A], sets:add_element(A, Set)} end end, {[], sets:new()}, lists:flatten(DepList)), AppOrder. is_otp_base_app(kernel) -> true; is_otp_base_app(stdlib) -> true; is_otp_base_app(_) -> false.
null
https://raw.githubusercontent.com/basho/riak_api/41f4b72d6a946c710e1523fd69b5b8deb5b57153/test/riak_api_test_util.erl
erlang
applications. They will not handle circular or mutually-dependent applications.
-module(riak_api_test_util). -compile([export_all, nowarn_export_all]). wait_for_application_shutdown(App) -> case lists:keymember(App, 1, application:which_applications()) of true -> timer:sleep(250), wait_for_application_shutdown(App); false -> ok end. The following three functions build a list of dependent dep_apps(App) -> application:load(App), {ok, Apps} = application:get_key(App, applications), Apps. all_deps(App, Deps) -> [[ all_deps(Dep, [App|Deps]) || Dep <- dep_apps(App), not lists:member(Dep, Deps)], App]. resolve_deps(App) -> DepList = all_deps(App, []), {AppOrder, _} = lists:foldl(fun(A,{List,Set}) -> case sets:is_element(A, Set) of true -> {List, Set}; false -> {List ++ [A], sets:add_element(A, Set)} end end, {[], sets:new()}, lists:flatten(DepList)), AppOrder. is_otp_base_app(kernel) -> true; is_otp_base_app(stdlib) -> true; is_otp_base_app(_) -> false.
5d1c8916e9ee05ed28d2051fb843133710c563d6e26478d4a4338fcd2b977e3d
stevenvar/OMicroB
jdlv.ml
open Pic32 class cell a = object val mutable v = (a : bool) method isAlive = v end ;; 4.2 class virtual absWorld n m = object(self) val mutable tcell = Array.create_matrix n m (new cell false) val maxx = n val maxy = m val mutable gen = 0 method private dessine(c) = (* if c#isAlive then print_string "*" else print_string "." *) if c#isAlive then digital_write PIN78 HIGH else digital_write PIN82 HIGH method display() = for i = 0 to (maxx-1) do for j=0 to (maxy -1) do (* print_string " " ; *) self#dessine(tcell.(i).(j)) done ; (* print_newline() *) done method getCell(i,j) = tcell.(i).(j) method setCell(i,j,c) = tcell.(i).(j) <- c method getCells = tcell end ;; 4.3 class world n m = object(self) inherit absWorld n m method neighbors(x,y) = let r = ref 0 in for i=x-1 to x+1 do let k = (i+maxx) mod maxx in for j=y-1 to y+1 do let l = (j + maxy) mod maxy in if tcell.(k).(l)#isAlive then incr r done done; if tcell.(x).(y)#isAlive then decr r ; !r method nextGen() = let w2 = new world maxx maxy in for i=0 to maxx-1 do for j=0 to maxy -1 do let n = self#neighbors(i,j) in if tcell.(i).(j)#isAlive then (if (n = 2) || (n = 3) then w2#setCell(i,j,new cell true)) else (if n = 3 then w2#setCell(i,j,new cell true)) done done ; tcell <- w2#getCells ; gen <- gen + 1 end ;; 4.4 exception Fin;; let main () = pin_mode PIN78 OUTPUT; pin_mode PIN82 OUTPUT; let a = 10 and b = 12 in let w = new world a b in w#setCell(4,4,new cell true) ; w#setCell(4,5,new cell true) ; w#setCell(4,6,new cell true) ; try while true do w#display() ; if ( ( read_line ( ) ) = " F " ) then raise Fin else ( ) w#nextGen() ; done with Fin -> () ;; main () ;;
null
https://raw.githubusercontent.com/stevenvar/OMicroB/e4324d0736ac677b3086741dfdefb0e46775642b/targets/pic32/tests/lchip/jdlv/jdlv.ml
ocaml
if c#isAlive then print_string "*" else print_string "." print_string " " ; print_newline()
open Pic32 class cell a = object val mutable v = (a : bool) method isAlive = v end ;; 4.2 class virtual absWorld n m = object(self) val mutable tcell = Array.create_matrix n m (new cell false) val maxx = n val maxy = m val mutable gen = 0 method private dessine(c) = if c#isAlive then digital_write PIN78 HIGH else digital_write PIN82 HIGH method display() = for i = 0 to (maxx-1) do for j=0 to (maxy -1) do self#dessine(tcell.(i).(j)) done ; done method getCell(i,j) = tcell.(i).(j) method setCell(i,j,c) = tcell.(i).(j) <- c method getCells = tcell end ;; 4.3 class world n m = object(self) inherit absWorld n m method neighbors(x,y) = let r = ref 0 in for i=x-1 to x+1 do let k = (i+maxx) mod maxx in for j=y-1 to y+1 do let l = (j + maxy) mod maxy in if tcell.(k).(l)#isAlive then incr r done done; if tcell.(x).(y)#isAlive then decr r ; !r method nextGen() = let w2 = new world maxx maxy in for i=0 to maxx-1 do for j=0 to maxy -1 do let n = self#neighbors(i,j) in if tcell.(i).(j)#isAlive then (if (n = 2) || (n = 3) then w2#setCell(i,j,new cell true)) else (if n = 3 then w2#setCell(i,j,new cell true)) done done ; tcell <- w2#getCells ; gen <- gen + 1 end ;; 4.4 exception Fin;; let main () = pin_mode PIN78 OUTPUT; pin_mode PIN82 OUTPUT; let a = 10 and b = 12 in let w = new world a b in w#setCell(4,4,new cell true) ; w#setCell(4,5,new cell true) ; w#setCell(4,6,new cell true) ; try while true do w#display() ; if ( ( read_line ( ) ) = " F " ) then raise Fin else ( ) w#nextGen() ; done with Fin -> () ;; main () ;;
e0af5025e2fba929e103ccb8aa9326572fa8b0ca011f47a3fec5f8f1b1adac7f
Kalimehtar/gtk-cffi
misc.lisp
(in-package :gtk-cffi) (defclass misc (widget) ()) (defcfun gtk-misc-set-alignment :void (misc pobject) (x :float) (y :float)) (defgeneric (setf alignment) (coords misc) (:method (coords (misc misc)) (gtk-misc-set-alignment misc (float (first coords)) (float (second coords))))) (save-setter misc alignment) (defcfun gtk-misc-get-alignment :void (misc pobject) (x :pointer) (y :pointer)) (defgeneric alignment (misc) (:method ((misc misc)) (with-foreign-outs-list ((x :float) (y :float)) :ignore (gtk-misc-get-alignment misc x y)))) (defcfun gtk-misc-set-padding :void (misc pobject) (x :int) (y :int)) (defgeneric (setf padding) (coords misc) (:method (coords (misc misc)) (gtk-misc-set-padding misc (first coords) (second coords)))) (save-setter misc padding) (defcfun gtk-misc-get-padding :void (misc pobject) (x :pointer) (y :pointer)) (defgeneric padding (misc) (:method ((misc misc)) (with-foreign-outs-list ((x :int) (y :int)) :ignore (gtk-misc-get-padding misc x y))))
null
https://raw.githubusercontent.com/Kalimehtar/gtk-cffi/fbd8a40a2bbda29f81b1a95ed2530debfe2afe9b/gtk/misc.lisp
lisp
(in-package :gtk-cffi) (defclass misc (widget) ()) (defcfun gtk-misc-set-alignment :void (misc pobject) (x :float) (y :float)) (defgeneric (setf alignment) (coords misc) (:method (coords (misc misc)) (gtk-misc-set-alignment misc (float (first coords)) (float (second coords))))) (save-setter misc alignment) (defcfun gtk-misc-get-alignment :void (misc pobject) (x :pointer) (y :pointer)) (defgeneric alignment (misc) (:method ((misc misc)) (with-foreign-outs-list ((x :float) (y :float)) :ignore (gtk-misc-get-alignment misc x y)))) (defcfun gtk-misc-set-padding :void (misc pobject) (x :int) (y :int)) (defgeneric (setf padding) (coords misc) (:method (coords (misc misc)) (gtk-misc-set-padding misc (first coords) (second coords)))) (save-setter misc padding) (defcfun gtk-misc-get-padding :void (misc pobject) (x :pointer) (y :pointer)) (defgeneric padding (misc) (:method ((misc misc)) (with-foreign-outs-list ((x :int) (y :int)) :ignore (gtk-misc-get-padding misc x y))))
3bd98ffe2e23fb17b88efe4d0edf6d0bc7154a18751baeac43b361a1b9c17278
opencog/pln
pln-utils.scm
(use-modules (srfi srfi-1)) (use-modules (ice-9 regex)) (use-modules (opencog)) (use-modules (opencog exec)) (use-modules (opencog logger)) (use-modules (opencog ure)) ;; Atomspace containing all PLN rules. All operations of loading ;; rules, etc, take place in this atomspace to not pollute the current ;; atomspace. (define-public pln-atomspace (cog-new-atomspace)) (define-public (pln-load-from-path FILENAME) " pln-load-from-path FILENAME Like load-from-path but load the content into pln-atomspace. Used to load PLN rules without polluting the current atomspace. " Switch to PLN atomspace (define current-as (cog-set-atomspace! pln-atomspace)) (load-from-path FILENAME) Switch back to previous space (cog-set-atomspace! current-as) ;; Avoid confusing the user with a return value *unspecified*) (define-public (pln-load-from-file FILENAME) " pln-load-from-file FILENAME Like primitive-load but load the content into pln-atomspace. Used to load PLN rules that are not in the load path without polluting the current atomspace. " Switch to PLN atomspace (define current-as (cog-set-atomspace! pln-atomspace)) (primitive-load FILENAME) Switch back to previous space (cog-set-atomspace! current-as) ;; Avoid confusing the user with a return value *unspecified*) (define-public (pln-rule-type->filename RULE-TYPE) " pln-rule-type->filename RULE-TYPE Turn a rule type string turn it into a filename ready to be loaded using load-from-path. More precisely returns opencog/pln/rules/<RULE-TYPE>.scm " (string-append "opencog/pln/rules/" RULE-TYPE ".scm")) (define-public (pln-meta-rule-type->filename META-RULE-TYPE) " pln-meta-rule-type->filename META-RULE-TYPE Turn a meta-rule type string turn it into a filename ready to be loaded using load-from-path. More precisely returns opencog/pln/meta-rules/<META-RULE-TYPE>.scm " (string-append "opencog/pln/meta-rules/" META-RULE-TYPE ".scm")) (define-public (pln-load-rule RULE-SYMBOL . TV) " WARNING: this function actually loads the scheme file associated with that rule, thus it is not recommanded to be called often, which might result in crashing guile. Rather, you should load all rules at the start of your program then add or remove rules with pln-add-rule or pln-rm-rule respectively. (pln-load-rule RULE-SYMBOL [TV]) Given the symbol of a rule, such as 'subset-direct-introduction, load the rule to the pln atomspace and add it to the pln rule base. To a load a meta rule just append meta at the end of the symbol, for instance (pln-load-rule 'conditional-total-instantiation-implication-meta) Finally, you can list of all supported rule symbols by calling (pln-supported-rule) " (define filepath (pln-rule-name->filepath (rule-symbol->rule-name RULE-SYMBOL))) (pln-load-from-path filepath) (apply pln-add-rule (cons RULE-SYMBOL TV))) (define-public (pln-load-meta-rule META-RULE-SYMBOL . TV) " pln-load-rule META-RULE-SYMBOL [TV] Given the symbol of a meta rule, such as 'conditional-total-instantiation-implication, load the rule to the pln atomspace and add it to the pln rule base. WARNING: this function actually loads the scheme file associated with that rule, thus it is not recommanded to be called often, which might result in crashing guile. Rather, you should load all rules at the start of your program then add or remove rules with pln-add-rule or pln-rm-rule respectively. Finally, you can list of all supported rule symbols by calling (pln-supported-rule) " (define filepath (pln-rule-name->filepath (rule-symbol->rule-name META-RULE-SYMBOL))) (pln-load-from-path filepath) (apply pln-add-rule (cons META-RULE-SYMBOL TV))) (define-public (pln-load-rules RULE-TYPE) " WARNING: likely deprecated, use pln-load-rule instead. pln-load-rules RULE-TYPE Loads the different variations of the rules known by RULE-TYPE in pln-atomspace. A RULE-TYPE may include the categorization of the rule. For example, 'term/deduction' implies that the rule to be loaded is the term-logic deduction rule. Notes: 1. If a rule needs formula defined in formulas.scm then the rule file should load it. 2. Rule files are assumed to be named as \"RULE-TYPE.scm\" 3. load-from-path is used so as to be able to use build_dir/opencog/scm, even when the module isn't installed. " (pln-load-from-path (pln-rule-type->filename RULE-TYPE))) (define-public (pln-load-meta-rules META-RULE-TYPE) " WARNING: likely deprecated, use pln-load-meta-rule instead. pln-load-meta-rules META-RULE-TYPE Loads the different variations of the meta rules known by META-RULE-TYPE in pln-atomspace. A META-RULE-TYPE may include the categorization of the rule. For example, 'predicate/conditional-total-instantiation' implies that the rule to be loaded is the predicate-logic conditional instantiation rule. Note: 1. If a rule needs formula defined in formulas.scm then the rule file should load it. 2. Rule files are assumed to be named as \"META-RULE-TYPE.scm\" 3. load-from-path is used so as to be able to use build_dir/opencog/scm, even when the module isn't installed. " (pln-load-from-path (pln-meta-rule-type->filename META-RULE-TYPE))) (define-public (pln-mk-rb) " Create (Concept \"pln-rb\") " (cog-new-node 'ConceptNode "pln-rb")) (define-public (pln-rb) " Get (Concept \"pln-rb\") from pln-atomspace " (define current-as (cog-set-atomspace! pln-atomspace)) (define pln-atomspace-rb (pln-mk-rb)) (cog-set-atomspace! current-as) pln-atomspace-rb) (define-public (pln-load . rule-bases) " Load and configure a PLN rule base. Usage: (pln-load rb) rb: [optional, default='standard] Rule base to load. 2 rule bases are supported so far 1. 'empty 2. 'standard The 'empty rule base contains no rule. In such case rules can be added using pln-add-rule or pln-add-rules. The 'standard rule base contains a few dozens of rules, such as deduction, modus ponens, contraposition, fuzzy conjunction and disjunction, as well as conditional instantiation, all in various declinations. To list all the rules one may use (pln-weighted-rules) Also, rules can be added or subtracted using the functions pln-add-rule, pln-add-rules, pln-rm-rule and pln-rm-rules. Remark: this function is not cumulative, that is it will clear the pln atomspace before loading rules. " (define rule-base (if (< 0 (length rule-bases)) (car rule-bases) 'standard)) ;; Clear PLN atomspace (pln-clear) ;; Attach rules to PLN rule-base (let ((rlst (cond ((equal? rule-base 'empty) (list)) ((equal? rule-base 'standard) (list ;; Deduction 'deduction-implication 'deduction-subset 'deduction-inheritance ;; Modus Ponens 'modus-ponens-inheritance 'modus-ponens-implication 'modus-ponens-subset Contraposition 'crisp-contraposition-implication-scope 'contraposition-implication 'contraposition-inheritance ;; Fuzzy Conjunction Introduction 'fuzzy-conjunction-introduction-1ary 'fuzzy-conjunction-introduction-2ary 'fuzzy-conjunction-introduction-3ary 'fuzzy-conjunction-introduction-4ary 'fuzzy-conjunction-introduction-5ary ;; Fuzzy Disjunction Introduction 'fuzzy-disjunction-introduction-1ary 'fuzzy-disjunction-introduction-2ary 'fuzzy-disjunction-introduction-3ary 'fuzzy-disjunction-introduction-4ary 'fuzzy-disjunction-introduction-5ary Conditional Total Instantiation 'conditional-total-instantiation-implication-scope-meta 'conditional-total-instantiation-implication-meta 'conditional-total-instantiation-inheritance-meta))))) (map pln-load-rule rlst)) ;; Avoid confusing the user with a return value *unspecified*) (define-public (pln-rule-name->filepath rn) " Given a rule name, such as \"deduction-subset-rule\", return the relative filepath of that rule, so that it can be loaded with pln-load-from-path. " ;; Make sure to order regex patterns from more specific to less ;; specific to avoid having the more abstract patterns shadow the ;; less abstract ones. (cond ;; Term [(string-match "^.*-present-deduction-rule$" rn) "opencog/pln/rules/term/present-deduction.scm"] [(string-match "^full-deduction-.*rule$" rn) "opencog/pln/rules/term/full-deduction.scm"] [(string-match "^.*-deduction-rule$" rn) "opencog/pln/rules/term/deduction.scm"] [(string-match "^.*condition-negation-.+-rule$" rn) "opencog/pln/rules/term/condition-negation.scm"] ;; Propositional [(string-match "^.*-modus-ponens-rule$" rn) "opencog/pln/rules/propositional/modus-ponens.scm"] [(string-match "^.*contraposition-.*rule$" rn) "opencog/pln/rules/propositional/contraposition.scm"] [(string-match "^fuzzy-conjunction-introduction-.+-rule$" rn) "opencog/pln/rules/propositional/fuzzy-conjunction-introduction.scm"] [(string-match "^fuzzy-disjunction-introduction-.+-rule$" rn) "opencog/pln/rules/propositional/fuzzy-disjunction-introduction.scm"] Extensional [(string-match "^extensional-similarity-direct-introduction-rule$" rn) "opencog/pln/rules/extensional/extensional-similarity-direct-introduction.scm"] [(string-match "^subset-direct-introduction-rule$" rn) "opencog/pln/rules/extensional/subset-direct-introduction.scm"] [(string-match "^conjunction-direct-introduction-rule$" rn) "opencog/pln/rules/extensional/conjunction-direct-introduction.scm"] [(string-match "^concept-direct-evaluation-rule$" rn) "opencog/pln/rules/extensional/concept-direct-introduction.scm"] [(string-match "^member-deduction-rule$" rn) "opencog/pln/rules/extensional/member-deduction.scm"] Intensional [(string-match "^.*attraction-introduction-rule$" rn) "opencog/pln/rules/intensional/attraction-introduction.scm"] [(string-match "^intensional-inheritance-direct-introduction-rule$" rn) "opencog/pln/rules/intensional/intensional-inheritance-direct-introduction.scm"] [(string-match "^intensional-similarity-direct-introduction-rule$" rn) "opencog/pln/rules/intensional/intensional-similarity-direct-introduction.scm"] [(string-match "^intensional-difference-direct-introduction-rule$" rn) "opencog/pln/rules/intensional/intensional-difference-direct-introduction.scm"] [(string-match "^intensional-difference-member-direct-introduction-rule$" rn) "opencog/pln/rules/intensional/intensional-difference-member-direct-introduction.scm"] ;; Temporal [(string-match "^back-predictive-implication-scope-deduction-cogscm-Q-conjunction-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-deduction-cogscm.scm"] [(string-match "^back-predictive-implication-scope-deduction-cogscm-Q-evaluation-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-deduction-cogscm.scm"] [(string-match "^back-predictive-implication-scope-direct-evaluation-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-direct-evaluation.scm"] [(string-match "^back-predictive-implication-scope-direct-introduction-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-direct-introduction.scm"] [(string-match "^predictive-implication-scope-direct-introduction-rule$" rn) "opencog/pln/rules/temporal/predictive-implication-scope-direct-introduction.scm"] [(string-match "predictive-implication-direct-evaluation-rule" rn) "opencog/pln/rules/temporal/predictive-implication-direct-evaluation.scm"] [(string-match "predictive-implication-scope-direct-evaluation-rule" rn) "opencog/pln/rules/temporal/predictive-implication-scope-direct-evaluation.scm"] [(string-match "predictive-implication-scope-deduction-rule" rn) "opencog/pln/rules/temporal/predictive-implication-scope-deduction.scm"] [(string-match "^back-predictive-implication-scope-conditional-conjunction-introduction-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-conditional-conjunction-introduction.scm"] Meta - rules [(string-match "^conditional-total-instantiation-.+-meta-rule$" rn) "opencog/pln/meta-rules/predicate/conditional-total-instantiation.scm"] [(string-match "^conditional-partial-instantiation-.+-meta-rule$" rn) "opencog/pln/meta-rules/predicate/conditional-partial-instantiation.scm"])) (define-public (pln-supported-rules) " List all rule symbols that are support by pln-load-rule " (list 'inheritance-deduction 'implication-deduction 'subset-deduction 'full-deduction-inheritance 'full-deduction-implication 'full-deduction-subset 'back-predictive-implication-scope-deduction-cogscm-Q-conjunction 'back-predictive-implication-scope-deduction-cogscm-Q-evaluation 'back-predictive-implication-scope-conditional-conjunction-introduction 'inheritance-present-deduction 'subset-condition-negation 'inheritance-modus-ponens 'implication-modus-ponens 'subset-modus-ponens 'crisp-contraposition-implication-scope 'contraposition-implication 'contraposition-inheritance 'fuzzy-conjunction-introduction-1ary 'fuzzy-conjunction-introduction-2ary 'fuzzy-conjunction-introduction-3ary 'fuzzy-conjunction-introduction-4ary 'fuzzy-conjunction-introduction-5ary 'fuzzy-disjunction-introduction-1ary 'fuzzy-disjunction-introduction-2ary 'fuzzy-disjunction-introduction-3ary 'fuzzy-disjunction-introduction-4ary 'fuzzy-disjunction-introduction-5ary 'extensional-similarity-direct-introduction 'subset-direct-introduction 'conjunction-direct-introduction 'concept-direct-evaluation 'member-deduction 'subset-attraction-introduction 'intensional-inheritance-direct-introduction 'intensional-similarity-direct-introduction 'intensional-difference-direct-introduction 'intensional-difference-member-introduction 'predictive-implication-scope-direct-introduction 'predictive-implication-direct-evaluation 'predictive-implication-scope-direct-evaluation 'predictive-implication-scope-deduction 'conditional-total-instantiation-implication-scope 'conditional-total-instantiation-implication 'conditional-total-instantiation-inheritance 'conditional-partial-instantiation)) (define-public (pln-prt-pln-atomspace) " Print all PLN rules loaded in pln-atomspace " (define current-as (cog-set-atomspace! pln-atomspace)) (cog-prt-atomspace) (cog-set-atomspace! current-as) ;; Avoid confusing the user with a return value *unspecified*) (define-public (pln-prt-atomspace) " Identical to pln-prt-pln-atomspace. " (pln-prt-pln-atomspace)) (define-public (pln-log-atomspace) " Like pln-prt-atomspace but log at info level instead of print " (define current-as (cog-set-atomspace! pln-atomspace)) (cog-logger-info "~a" (cog-get-all-roots)) (cog-set-atomspace! current-as) ;; Avoid confusing the user with a return value *unspecified*) (define-public (pln-rules) " List all rules in the PLN rule base. " (ure-rules (pln-rb))) (define-public (pln-weighted-rules) " List all weighted rules in the PLN rule base. " (ure-weighted-rules (pln-rb))) (define-public (pln-set-rule-tv! rule-alias tv) " Set the weight TV of a given rule alias, i.e. DefinedSchemaNode, associated to the PLN rule base. Under the hood this sets the TV of MemberLink rule-name (ConceptNode \"pln-rb\") " (define current-as (cog-set-atomspace! pln-atomspace)) (cog-set-tv! (MemberLink rule-name (pln-mk-rb)) tv) (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-add-rule rule . tv) " Call ure-add-rule on the PLN rule base. See (help ure-add-rule) for more info. " (define current-as (cog-set-atomspace! pln-atomspace)) (apply ure-add-rule (cons (pln-mk-rb) (cons rule tv))) (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-add-rules rules) " Call ure-add-rules on the PLN rule base. See (help ure-add-rules) for more info. " (define current-as (cog-set-atomspace! pln-atomspace)) (ure-add-rules (pln-mk-rb) rules) (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-rm-all-rules) " Remove all rules for the PLN rule base. See (help ure-rm-all-rules) for more info. " (ure-rm-all-rules (pln-rb))) (define-public (pln-set-attention-allocation value) " Wrapper around ure-set-attention-allocation using (pln-rb) as rule base. See (help ure-set-attention-allocation) for more info. " (ure-set-attention-allocation (pln-rb) value)) (define-public (pln-set-maximum-iterations value) " Wrapper around ure-set-maximum-iterations using (pln-rb) as rule base. See (help ure-set-maximum-iterations) for more info. " (ure-set-maximum-iterations (pln-rb) value)) (define-public (pln-set-complexity-penalty value) " Wrapper around ure-set-complexity-penalty using (pln-rb) as rule base. See (help ure-set-complexity-penalty) for more info. " (ure-set-complexity-penalty (pln-rb) value)) (define-public (pln-set-jobs value) " Wrapper around ure-set-jobs using (pln-rb) as rule base. See (help ure-set-jobs) for more info. " (ure-set-jobs (pln-rb) value)) (define-public (pln-set-fc-retry-exhausted-sources value) " Wrapper around ure-set-fc-retry-exhausted-sources using (pln-rb) as rule base. See (help ure-set-fc-retry-exhausted-sources) for more info. " (ure-set-fc-retry-exhausted-sources (pln-rb) value)) (define-public (pln-set-fc-full-rule-application value) " Wrapper around ure-set-fc-full-rule-application using (pln-rb) as rule base. See (help ure-set-fc-full-rule-application) for more info. " (ure-set-fc-full-rule-application (pln-rb) value)) (define-public (pln-set-bc-maximum-bit-size value) " Wrapper around ure-set-bc-maximum-bit-size using (pln-rb) as rule base. See (help ure-set-bc-maximum-bit-size) for more info. " (ure-set-bc-maximum-bit-size (pln-rb) value)) (define-public (pln-set-bc-mm-complexity-penalty value) " Wrapper around ure-set-bc-mm-complexity-penalty using (pln-rb) as rule base. See (help ure-set-bc-mm-complexity-penalty) for more info. " (ure-set-bc-mm-complexity-penalty (pln-rb) value)) (define-public (pln-set-bc-mm-compressiveness value) " Wrapper around ure-set-bc-mm-compressiveness using (pln-rb) as rule base. See (help ure-set-bc-mm-compressiveness) for more info. " (ure-set-bc-mm-compressiveness (pln-rb) value)) (define-public (pln-fc . args) " Wrapper around cog-fc using (pln-rb) as rule base. See (help cog-fc) for more info. " (apply cog-fc (cons (pln-rb) args))) (define-public (pln-bc . args) " Wrapper around cog-bc using (pln-rb) as rule base. See (help cog-bc) for more info. " (apply cog-bc (cons (pln-rb) args))) ;; TODO: move to ure (define-public (pln-apply-rule rule-symbol) " Execute a rule symbol, for instance (pln-apply-rule 'subset-deduction) " TODO ) (define-public (pln-clear) Switch to PLN atomspace and clear (define current-as (cog-set-atomspace! pln-atomspace)) (clear) Switch back to previous space (cog-set-atomspace! current-as) ;; Avoid confusing the user with a return value *unspecified*)
null
https://raw.githubusercontent.com/opencog/pln/e990f7c5d5c7a39c6fcc7a7eaedeebece8c6c4e8/opencog/pln/pln-utils.scm
scheme
Atomspace containing all PLN rules. All operations of loading rules, etc, take place in this atomspace to not pollute the current atomspace. Avoid confusing the user with a return value Avoid confusing the user with a return value Clear PLN atomspace Attach rules to PLN rule-base Deduction Modus Ponens Fuzzy Conjunction Introduction Fuzzy Disjunction Introduction Avoid confusing the user with a return value Make sure to order regex patterns from more specific to less specific to avoid having the more abstract patterns shadow the less abstract ones. Term Propositional Temporal Avoid confusing the user with a return value Avoid confusing the user with a return value TODO: move to ure Avoid confusing the user with a return value
(use-modules (srfi srfi-1)) (use-modules (ice-9 regex)) (use-modules (opencog)) (use-modules (opencog exec)) (use-modules (opencog logger)) (use-modules (opencog ure)) (define-public pln-atomspace (cog-new-atomspace)) (define-public (pln-load-from-path FILENAME) " pln-load-from-path FILENAME Like load-from-path but load the content into pln-atomspace. Used to load PLN rules without polluting the current atomspace. " Switch to PLN atomspace (define current-as (cog-set-atomspace! pln-atomspace)) (load-from-path FILENAME) Switch back to previous space (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-load-from-file FILENAME) " pln-load-from-file FILENAME Like primitive-load but load the content into pln-atomspace. Used to load PLN rules that are not in the load path without polluting the current atomspace. " Switch to PLN atomspace (define current-as (cog-set-atomspace! pln-atomspace)) (primitive-load FILENAME) Switch back to previous space (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-rule-type->filename RULE-TYPE) " pln-rule-type->filename RULE-TYPE Turn a rule type string turn it into a filename ready to be loaded using load-from-path. More precisely returns opencog/pln/rules/<RULE-TYPE>.scm " (string-append "opencog/pln/rules/" RULE-TYPE ".scm")) (define-public (pln-meta-rule-type->filename META-RULE-TYPE) " pln-meta-rule-type->filename META-RULE-TYPE Turn a meta-rule type string turn it into a filename ready to be loaded using load-from-path. More precisely returns opencog/pln/meta-rules/<META-RULE-TYPE>.scm " (string-append "opencog/pln/meta-rules/" META-RULE-TYPE ".scm")) (define-public (pln-load-rule RULE-SYMBOL . TV) " WARNING: this function actually loads the scheme file associated with that rule, thus it is not recommanded to be called often, which might result in crashing guile. Rather, you should load all rules at the start of your program then add or remove rules with pln-add-rule or pln-rm-rule respectively. (pln-load-rule RULE-SYMBOL [TV]) Given the symbol of a rule, such as 'subset-direct-introduction, load the rule to the pln atomspace and add it to the pln rule base. To a load a meta rule just append meta at the end of the symbol, for instance (pln-load-rule 'conditional-total-instantiation-implication-meta) Finally, you can list of all supported rule symbols by calling (pln-supported-rule) " (define filepath (pln-rule-name->filepath (rule-symbol->rule-name RULE-SYMBOL))) (pln-load-from-path filepath) (apply pln-add-rule (cons RULE-SYMBOL TV))) (define-public (pln-load-meta-rule META-RULE-SYMBOL . TV) " pln-load-rule META-RULE-SYMBOL [TV] Given the symbol of a meta rule, such as 'conditional-total-instantiation-implication, load the rule to the pln atomspace and add it to the pln rule base. WARNING: this function actually loads the scheme file associated with that rule, thus it is not recommanded to be called often, which might result in crashing guile. Rather, you should load all rules at the start of your program then add or remove rules with pln-add-rule or pln-rm-rule respectively. Finally, you can list of all supported rule symbols by calling (pln-supported-rule) " (define filepath (pln-rule-name->filepath (rule-symbol->rule-name META-RULE-SYMBOL))) (pln-load-from-path filepath) (apply pln-add-rule (cons META-RULE-SYMBOL TV))) (define-public (pln-load-rules RULE-TYPE) " WARNING: likely deprecated, use pln-load-rule instead. pln-load-rules RULE-TYPE Loads the different variations of the rules known by RULE-TYPE in pln-atomspace. A RULE-TYPE may include the categorization of the rule. For example, 'term/deduction' implies that the rule to be loaded is the term-logic deduction rule. Notes: 1. If a rule needs formula defined in formulas.scm then the rule file should load it. 2. Rule files are assumed to be named as \"RULE-TYPE.scm\" 3. load-from-path is used so as to be able to use build_dir/opencog/scm, even when the module isn't installed. " (pln-load-from-path (pln-rule-type->filename RULE-TYPE))) (define-public (pln-load-meta-rules META-RULE-TYPE) " WARNING: likely deprecated, use pln-load-meta-rule instead. pln-load-meta-rules META-RULE-TYPE Loads the different variations of the meta rules known by META-RULE-TYPE in pln-atomspace. A META-RULE-TYPE may include the categorization of the rule. For example, 'predicate/conditional-total-instantiation' implies that the rule to be loaded is the predicate-logic conditional instantiation rule. Note: 1. If a rule needs formula defined in formulas.scm then the rule file should load it. 2. Rule files are assumed to be named as \"META-RULE-TYPE.scm\" 3. load-from-path is used so as to be able to use build_dir/opencog/scm, even when the module isn't installed. " (pln-load-from-path (pln-meta-rule-type->filename META-RULE-TYPE))) (define-public (pln-mk-rb) " Create (Concept \"pln-rb\") " (cog-new-node 'ConceptNode "pln-rb")) (define-public (pln-rb) " Get (Concept \"pln-rb\") from pln-atomspace " (define current-as (cog-set-atomspace! pln-atomspace)) (define pln-atomspace-rb (pln-mk-rb)) (cog-set-atomspace! current-as) pln-atomspace-rb) (define-public (pln-load . rule-bases) " Load and configure a PLN rule base. Usage: (pln-load rb) rb: [optional, default='standard] Rule base to load. 2 rule bases are supported so far 1. 'empty 2. 'standard The 'empty rule base contains no rule. In such case rules can be added using pln-add-rule or pln-add-rules. The 'standard rule base contains a few dozens of rules, such as deduction, modus ponens, contraposition, fuzzy conjunction and disjunction, as well as conditional instantiation, all in various declinations. To list all the rules one may use (pln-weighted-rules) Also, rules can be added or subtracted using the functions pln-add-rule, pln-add-rules, pln-rm-rule and pln-rm-rules. Remark: this function is not cumulative, that is it will clear the pln atomspace before loading rules. " (define rule-base (if (< 0 (length rule-bases)) (car rule-bases) 'standard)) (pln-clear) (let ((rlst (cond ((equal? rule-base 'empty) (list)) ((equal? rule-base 'standard) (list 'deduction-implication 'deduction-subset 'deduction-inheritance 'modus-ponens-inheritance 'modus-ponens-implication 'modus-ponens-subset Contraposition 'crisp-contraposition-implication-scope 'contraposition-implication 'contraposition-inheritance 'fuzzy-conjunction-introduction-1ary 'fuzzy-conjunction-introduction-2ary 'fuzzy-conjunction-introduction-3ary 'fuzzy-conjunction-introduction-4ary 'fuzzy-conjunction-introduction-5ary 'fuzzy-disjunction-introduction-1ary 'fuzzy-disjunction-introduction-2ary 'fuzzy-disjunction-introduction-3ary 'fuzzy-disjunction-introduction-4ary 'fuzzy-disjunction-introduction-5ary Conditional Total Instantiation 'conditional-total-instantiation-implication-scope-meta 'conditional-total-instantiation-implication-meta 'conditional-total-instantiation-inheritance-meta))))) (map pln-load-rule rlst)) *unspecified*) (define-public (pln-rule-name->filepath rn) " Given a rule name, such as \"deduction-subset-rule\", return the relative filepath of that rule, so that it can be loaded with pln-load-from-path. " [(string-match "^.*-present-deduction-rule$" rn) "opencog/pln/rules/term/present-deduction.scm"] [(string-match "^full-deduction-.*rule$" rn) "opencog/pln/rules/term/full-deduction.scm"] [(string-match "^.*-deduction-rule$" rn) "opencog/pln/rules/term/deduction.scm"] [(string-match "^.*condition-negation-.+-rule$" rn) "opencog/pln/rules/term/condition-negation.scm"] [(string-match "^.*-modus-ponens-rule$" rn) "opencog/pln/rules/propositional/modus-ponens.scm"] [(string-match "^.*contraposition-.*rule$" rn) "opencog/pln/rules/propositional/contraposition.scm"] [(string-match "^fuzzy-conjunction-introduction-.+-rule$" rn) "opencog/pln/rules/propositional/fuzzy-conjunction-introduction.scm"] [(string-match "^fuzzy-disjunction-introduction-.+-rule$" rn) "opencog/pln/rules/propositional/fuzzy-disjunction-introduction.scm"] Extensional [(string-match "^extensional-similarity-direct-introduction-rule$" rn) "opencog/pln/rules/extensional/extensional-similarity-direct-introduction.scm"] [(string-match "^subset-direct-introduction-rule$" rn) "opencog/pln/rules/extensional/subset-direct-introduction.scm"] [(string-match "^conjunction-direct-introduction-rule$" rn) "opencog/pln/rules/extensional/conjunction-direct-introduction.scm"] [(string-match "^concept-direct-evaluation-rule$" rn) "opencog/pln/rules/extensional/concept-direct-introduction.scm"] [(string-match "^member-deduction-rule$" rn) "opencog/pln/rules/extensional/member-deduction.scm"] Intensional [(string-match "^.*attraction-introduction-rule$" rn) "opencog/pln/rules/intensional/attraction-introduction.scm"] [(string-match "^intensional-inheritance-direct-introduction-rule$" rn) "opencog/pln/rules/intensional/intensional-inheritance-direct-introduction.scm"] [(string-match "^intensional-similarity-direct-introduction-rule$" rn) "opencog/pln/rules/intensional/intensional-similarity-direct-introduction.scm"] [(string-match "^intensional-difference-direct-introduction-rule$" rn) "opencog/pln/rules/intensional/intensional-difference-direct-introduction.scm"] [(string-match "^intensional-difference-member-direct-introduction-rule$" rn) "opencog/pln/rules/intensional/intensional-difference-member-direct-introduction.scm"] [(string-match "^back-predictive-implication-scope-deduction-cogscm-Q-conjunction-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-deduction-cogscm.scm"] [(string-match "^back-predictive-implication-scope-deduction-cogscm-Q-evaluation-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-deduction-cogscm.scm"] [(string-match "^back-predictive-implication-scope-direct-evaluation-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-direct-evaluation.scm"] [(string-match "^back-predictive-implication-scope-direct-introduction-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-direct-introduction.scm"] [(string-match "^predictive-implication-scope-direct-introduction-rule$" rn) "opencog/pln/rules/temporal/predictive-implication-scope-direct-introduction.scm"] [(string-match "predictive-implication-direct-evaluation-rule" rn) "opencog/pln/rules/temporal/predictive-implication-direct-evaluation.scm"] [(string-match "predictive-implication-scope-direct-evaluation-rule" rn) "opencog/pln/rules/temporal/predictive-implication-scope-direct-evaluation.scm"] [(string-match "predictive-implication-scope-deduction-rule" rn) "opencog/pln/rules/temporal/predictive-implication-scope-deduction.scm"] [(string-match "^back-predictive-implication-scope-conditional-conjunction-introduction-rule$" rn) "opencog/pln/rules/temporal/back-predictive-implication-scope-conditional-conjunction-introduction.scm"] Meta - rules [(string-match "^conditional-total-instantiation-.+-meta-rule$" rn) "opencog/pln/meta-rules/predicate/conditional-total-instantiation.scm"] [(string-match "^conditional-partial-instantiation-.+-meta-rule$" rn) "opencog/pln/meta-rules/predicate/conditional-partial-instantiation.scm"])) (define-public (pln-supported-rules) " List all rule symbols that are support by pln-load-rule " (list 'inheritance-deduction 'implication-deduction 'subset-deduction 'full-deduction-inheritance 'full-deduction-implication 'full-deduction-subset 'back-predictive-implication-scope-deduction-cogscm-Q-conjunction 'back-predictive-implication-scope-deduction-cogscm-Q-evaluation 'back-predictive-implication-scope-conditional-conjunction-introduction 'inheritance-present-deduction 'subset-condition-negation 'inheritance-modus-ponens 'implication-modus-ponens 'subset-modus-ponens 'crisp-contraposition-implication-scope 'contraposition-implication 'contraposition-inheritance 'fuzzy-conjunction-introduction-1ary 'fuzzy-conjunction-introduction-2ary 'fuzzy-conjunction-introduction-3ary 'fuzzy-conjunction-introduction-4ary 'fuzzy-conjunction-introduction-5ary 'fuzzy-disjunction-introduction-1ary 'fuzzy-disjunction-introduction-2ary 'fuzzy-disjunction-introduction-3ary 'fuzzy-disjunction-introduction-4ary 'fuzzy-disjunction-introduction-5ary 'extensional-similarity-direct-introduction 'subset-direct-introduction 'conjunction-direct-introduction 'concept-direct-evaluation 'member-deduction 'subset-attraction-introduction 'intensional-inheritance-direct-introduction 'intensional-similarity-direct-introduction 'intensional-difference-direct-introduction 'intensional-difference-member-introduction 'predictive-implication-scope-direct-introduction 'predictive-implication-direct-evaluation 'predictive-implication-scope-direct-evaluation 'predictive-implication-scope-deduction 'conditional-total-instantiation-implication-scope 'conditional-total-instantiation-implication 'conditional-total-instantiation-inheritance 'conditional-partial-instantiation)) (define-public (pln-prt-pln-atomspace) " Print all PLN rules loaded in pln-atomspace " (define current-as (cog-set-atomspace! pln-atomspace)) (cog-prt-atomspace) (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-prt-atomspace) " Identical to pln-prt-pln-atomspace. " (pln-prt-pln-atomspace)) (define-public (pln-log-atomspace) " Like pln-prt-atomspace but log at info level instead of print " (define current-as (cog-set-atomspace! pln-atomspace)) (cog-logger-info "~a" (cog-get-all-roots)) (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-rules) " List all rules in the PLN rule base. " (ure-rules (pln-rb))) (define-public (pln-weighted-rules) " List all weighted rules in the PLN rule base. " (ure-weighted-rules (pln-rb))) (define-public (pln-set-rule-tv! rule-alias tv) " Set the weight TV of a given rule alias, i.e. DefinedSchemaNode, associated to the PLN rule base. Under the hood this sets the TV of MemberLink rule-name (ConceptNode \"pln-rb\") " (define current-as (cog-set-atomspace! pln-atomspace)) (cog-set-tv! (MemberLink rule-name (pln-mk-rb)) tv) (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-add-rule rule . tv) " Call ure-add-rule on the PLN rule base. See (help ure-add-rule) for more info. " (define current-as (cog-set-atomspace! pln-atomspace)) (apply ure-add-rule (cons (pln-mk-rb) (cons rule tv))) (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-add-rules rules) " Call ure-add-rules on the PLN rule base. See (help ure-add-rules) for more info. " (define current-as (cog-set-atomspace! pln-atomspace)) (ure-add-rules (pln-mk-rb) rules) (cog-set-atomspace! current-as) *unspecified*) (define-public (pln-rm-all-rules) " Remove all rules for the PLN rule base. See (help ure-rm-all-rules) for more info. " (ure-rm-all-rules (pln-rb))) (define-public (pln-set-attention-allocation value) " Wrapper around ure-set-attention-allocation using (pln-rb) as rule base. See (help ure-set-attention-allocation) for more info. " (ure-set-attention-allocation (pln-rb) value)) (define-public (pln-set-maximum-iterations value) " Wrapper around ure-set-maximum-iterations using (pln-rb) as rule base. See (help ure-set-maximum-iterations) for more info. " (ure-set-maximum-iterations (pln-rb) value)) (define-public (pln-set-complexity-penalty value) " Wrapper around ure-set-complexity-penalty using (pln-rb) as rule base. See (help ure-set-complexity-penalty) for more info. " (ure-set-complexity-penalty (pln-rb) value)) (define-public (pln-set-jobs value) " Wrapper around ure-set-jobs using (pln-rb) as rule base. See (help ure-set-jobs) for more info. " (ure-set-jobs (pln-rb) value)) (define-public (pln-set-fc-retry-exhausted-sources value) " Wrapper around ure-set-fc-retry-exhausted-sources using (pln-rb) as rule base. See (help ure-set-fc-retry-exhausted-sources) for more info. " (ure-set-fc-retry-exhausted-sources (pln-rb) value)) (define-public (pln-set-fc-full-rule-application value) " Wrapper around ure-set-fc-full-rule-application using (pln-rb) as rule base. See (help ure-set-fc-full-rule-application) for more info. " (ure-set-fc-full-rule-application (pln-rb) value)) (define-public (pln-set-bc-maximum-bit-size value) " Wrapper around ure-set-bc-maximum-bit-size using (pln-rb) as rule base. See (help ure-set-bc-maximum-bit-size) for more info. " (ure-set-bc-maximum-bit-size (pln-rb) value)) (define-public (pln-set-bc-mm-complexity-penalty value) " Wrapper around ure-set-bc-mm-complexity-penalty using (pln-rb) as rule base. See (help ure-set-bc-mm-complexity-penalty) for more info. " (ure-set-bc-mm-complexity-penalty (pln-rb) value)) (define-public (pln-set-bc-mm-compressiveness value) " Wrapper around ure-set-bc-mm-compressiveness using (pln-rb) as rule base. See (help ure-set-bc-mm-compressiveness) for more info. " (ure-set-bc-mm-compressiveness (pln-rb) value)) (define-public (pln-fc . args) " Wrapper around cog-fc using (pln-rb) as rule base. See (help cog-fc) for more info. " (apply cog-fc (cons (pln-rb) args))) (define-public (pln-bc . args) " Wrapper around cog-bc using (pln-rb) as rule base. See (help cog-bc) for more info. " (apply cog-bc (cons (pln-rb) args))) (define-public (pln-apply-rule rule-symbol) " Execute a rule symbol, for instance (pln-apply-rule 'subset-deduction) " TODO ) (define-public (pln-clear) Switch to PLN atomspace and clear (define current-as (cog-set-atomspace! pln-atomspace)) (clear) Switch back to previous space (cog-set-atomspace! current-as) *unspecified*)
0ac29d2cfba564b1eeda132018b0c8258ebcf6aa25c25170a3fc0671df560964
TrustInSoft/tis-kernel
GuiSource.ml
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (* -------------------------------------------------------------------------- *) (* --- Source Interaction for WP --- *) (* -------------------------------------------------------------------------- *) open Cil_types open Cil_datatype open Pretty_source open Wpo type selection = | S_none | S_fun of Kernel_function.t | S_prop of Property.t | S_call of call and call = { s_caller : Kernel_function.t ; s_called : Kernel_function.t ; s_stmt : Stmt.t ; } let selection_of_localizable = function | PStmt( kf , stmt ) | PLval( Some kf , Kstmt stmt , _ ) | PTermLval( Some kf , Kstmt stmt , _, _ ) -> begin match stmt with | { skind=Instr(Call(_,e,_,_)) } -> begin match Kernel_function.get_called e with | None -> S_none | Some called -> S_call { s_called = called ; s_caller = kf ; s_stmt = stmt ; } end | _ -> S_none end | PVDecl (Some kf,{vglob=true}) -> S_fun kf | PIP ip -> S_prop ip | PVDecl _ | PLval _ | PExp _ | PTermLval _ | PGlobal _ -> S_none let kind_of_property = function | Property.IPLemma _ -> "lemma" | Property.IPCodeAnnot _ -> "annotation" | Property.IPPredicate( Property.PKRequires _ , _ , Kglobal , _ ) -> "precondition for callers" | _ -> "property" (* -------------------------------------------------------------------------- *) (* --- Popup Menu for WP --- *) (* -------------------------------------------------------------------------- *) let is_rte_generated kf = List.for_all (fun (_, _, lookup) -> lookup kf) (!Db.RteGen.get_all_status ()) let is_rte_precond kf = let _, _, lookup = !Db.RteGen.get_precond_status () in lookup kf class popup () = object(self) val mutable click : selection -> unit = (fun _ -> ()) val mutable prove : selection -> unit = (fun _ -> ()) method on_click f = click <- f method on_prove f = prove <- f method private add_rte (menu : GMenu.menu GMenu.factory) (main : Design.main_window_extension_points) title action kf = ignore (menu#add_item title ~callback:(fun () -> !action kf ; main#redisplay ())) method private rte_popup menu main loc = match loc with | PVDecl (Some kf,{vglob=true}) -> if not (is_rte_generated kf) then self#add_rte menu main "Insert WP-safety guards" Db.RteGen.do_all_rte kf ; if not (is_rte_precond kf) then self#add_rte menu main "Insert all callees contract" Db.RteGen.do_precond kf; | PStmt(kf,({ skind=Instr(Call _) })) -> if not (is_rte_precond kf) then self#add_rte menu main "Insert callees contract (all calls)" Db.RteGen.do_precond kf; | _ -> () method private wp_popup (menu : GMenu.menu GMenu.factory) = function | S_none -> () | s -> let target = match s with | S_none -> "none" | S_prop ip -> kind_of_property ip | S_call _ -> "call preconditions" | S_fun _ -> "function annotations" in let title = Printf.sprintf "Prove %s by WP" target in ignore (menu#add_item title ~callback:(fun () -> prove s)) method register (menu : GMenu.menu GMenu.factory) (main : Design.main_window_extension_points) ~(button:int) (loc:Pretty_source.localizable) = begin match button with | 1 -> begin match selection_of_localizable loc with | S_none -> () | s -> click s end | 3 -> begin self#wp_popup menu (selection_of_localizable loc) ; self#rte_popup menu main loc ; end | _ -> () end end (* -------------------------------------------------------------------------- *) (* --- Source Highlighter for WP --- *) (* -------------------------------------------------------------------------- *) module PATH = Stmt.Set module DEPS = Property.Set let apply_tag name attr buffer start stop = let tg = Gtk_helper.make_tag buffer name attr in Gtk_helper.apply_tag buffer tg start stop let apply_goal = apply_tag "wp.goal" [`BACKGROUND "lightblue"] let apply_effect = apply_tag "wp.effect" [`BACKGROUND "lightblue"] let apply_path = apply_tag "wp.path" [`BACKGROUND "yellow"] let apply_depend = apply_tag "wp.depend" [`BACKGROUND "pink"] let instructions path = PATH.filter (fun s -> match s.skind with | Instr _ -> true | _ -> false) path let lemmas ls = List.fold_left (fun s l -> DEPS.add (LogicUsage.ip_lemma l) s) DEPS.empty ls class highlighter (main:Design.main_window_extension_points) = object(self) val mutable goal = None (* orange *) val mutable effect = None (* blue *) val mutable path = PATH.empty (* yellow *) val mutable deps = DEPS.empty (* green *) val mutable current = None method private clear = begin goal <- None ; effect <- None ; path <- PATH.empty ; deps <- DEPS.empty ; end method private scroll () = main#rehighlight () ; match goal with | None -> () | Some ip -> main#scroll (PIP ip) method set s = let moved = match current, s with | None , None -> false | Some s0 , Some s1 -> s0.po_gid <> s1.po_gid | None , Some _ | Some _ , None -> true in if moved then begin current <- s ; self#clear ; match s with | None -> Wutil.later main#rehighlight ; | Some { Wpo.po_pid = pid ; Wpo.po_formula = f } -> begin match f with | GoalCheck _ -> () | GoalLemma l -> deps <- lemmas l.VC_Lemma.depends | GoalAnnot a -> effect <- a.VC_Annot.effect ; path <- instructions a.VC_Annot.path ; deps <- a.VC_Annot.deps ; end ; if not (WpPropId.is_check pid) then ( let ip = WpPropId.property_of_id pid in goal <- Some ip ) ; Wutil.later self#scroll ; end method update = main#rehighlight () method highlight (buffer : Design.reactive_buffer) (loc : Pretty_source.localizable) ~(start:int) ~(stop:int) = let buffer = buffer#buffer in begin match loc with | PStmt( _ , stmt ) -> begin match effect with | Some(s,_) when Stmt.equal stmt s -> apply_effect buffer start stop | _ -> if PATH.mem stmt path then apply_path buffer start stop end | PIP ip -> begin match goal with | Some g when Property.equal g ip -> apply_goal buffer start stop | _ -> if DEPS.mem ip deps then apply_depend buffer start stop end | PGlobal _|PVDecl _|PTermLval _|PLval _| PExp _ -> () end end
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/wp/GuiSource.ml
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ -------------------------------------------------------------------------- --- Source Interaction for WP --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Popup Menu for WP --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Source Highlighter for WP --- -------------------------------------------------------------------------- orange blue yellow green
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cil_types open Cil_datatype open Pretty_source open Wpo type selection = | S_none | S_fun of Kernel_function.t | S_prop of Property.t | S_call of call and call = { s_caller : Kernel_function.t ; s_called : Kernel_function.t ; s_stmt : Stmt.t ; } let selection_of_localizable = function | PStmt( kf , stmt ) | PLval( Some kf , Kstmt stmt , _ ) | PTermLval( Some kf , Kstmt stmt , _, _ ) -> begin match stmt with | { skind=Instr(Call(_,e,_,_)) } -> begin match Kernel_function.get_called e with | None -> S_none | Some called -> S_call { s_called = called ; s_caller = kf ; s_stmt = stmt ; } end | _ -> S_none end | PVDecl (Some kf,{vglob=true}) -> S_fun kf | PIP ip -> S_prop ip | PVDecl _ | PLval _ | PExp _ | PTermLval _ | PGlobal _ -> S_none let kind_of_property = function | Property.IPLemma _ -> "lemma" | Property.IPCodeAnnot _ -> "annotation" | Property.IPPredicate( Property.PKRequires _ , _ , Kglobal , _ ) -> "precondition for callers" | _ -> "property" let is_rte_generated kf = List.for_all (fun (_, _, lookup) -> lookup kf) (!Db.RteGen.get_all_status ()) let is_rte_precond kf = let _, _, lookup = !Db.RteGen.get_precond_status () in lookup kf class popup () = object(self) val mutable click : selection -> unit = (fun _ -> ()) val mutable prove : selection -> unit = (fun _ -> ()) method on_click f = click <- f method on_prove f = prove <- f method private add_rte (menu : GMenu.menu GMenu.factory) (main : Design.main_window_extension_points) title action kf = ignore (menu#add_item title ~callback:(fun () -> !action kf ; main#redisplay ())) method private rte_popup menu main loc = match loc with | PVDecl (Some kf,{vglob=true}) -> if not (is_rte_generated kf) then self#add_rte menu main "Insert WP-safety guards" Db.RteGen.do_all_rte kf ; if not (is_rte_precond kf) then self#add_rte menu main "Insert all callees contract" Db.RteGen.do_precond kf; | PStmt(kf,({ skind=Instr(Call _) })) -> if not (is_rte_precond kf) then self#add_rte menu main "Insert callees contract (all calls)" Db.RteGen.do_precond kf; | _ -> () method private wp_popup (menu : GMenu.menu GMenu.factory) = function | S_none -> () | s -> let target = match s with | S_none -> "none" | S_prop ip -> kind_of_property ip | S_call _ -> "call preconditions" | S_fun _ -> "function annotations" in let title = Printf.sprintf "Prove %s by WP" target in ignore (menu#add_item title ~callback:(fun () -> prove s)) method register (menu : GMenu.menu GMenu.factory) (main : Design.main_window_extension_points) ~(button:int) (loc:Pretty_source.localizable) = begin match button with | 1 -> begin match selection_of_localizable loc with | S_none -> () | s -> click s end | 3 -> begin self#wp_popup menu (selection_of_localizable loc) ; self#rte_popup menu main loc ; end | _ -> () end end module PATH = Stmt.Set module DEPS = Property.Set let apply_tag name attr buffer start stop = let tg = Gtk_helper.make_tag buffer name attr in Gtk_helper.apply_tag buffer tg start stop let apply_goal = apply_tag "wp.goal" [`BACKGROUND "lightblue"] let apply_effect = apply_tag "wp.effect" [`BACKGROUND "lightblue"] let apply_path = apply_tag "wp.path" [`BACKGROUND "yellow"] let apply_depend = apply_tag "wp.depend" [`BACKGROUND "pink"] let instructions path = PATH.filter (fun s -> match s.skind with | Instr _ -> true | _ -> false) path let lemmas ls = List.fold_left (fun s l -> DEPS.add (LogicUsage.ip_lemma l) s) DEPS.empty ls class highlighter (main:Design.main_window_extension_points) = object(self) val mutable current = None method private clear = begin goal <- None ; effect <- None ; path <- PATH.empty ; deps <- DEPS.empty ; end method private scroll () = main#rehighlight () ; match goal with | None -> () | Some ip -> main#scroll (PIP ip) method set s = let moved = match current, s with | None , None -> false | Some s0 , Some s1 -> s0.po_gid <> s1.po_gid | None , Some _ | Some _ , None -> true in if moved then begin current <- s ; self#clear ; match s with | None -> Wutil.later main#rehighlight ; | Some { Wpo.po_pid = pid ; Wpo.po_formula = f } -> begin match f with | GoalCheck _ -> () | GoalLemma l -> deps <- lemmas l.VC_Lemma.depends | GoalAnnot a -> effect <- a.VC_Annot.effect ; path <- instructions a.VC_Annot.path ; deps <- a.VC_Annot.deps ; end ; if not (WpPropId.is_check pid) then ( let ip = WpPropId.property_of_id pid in goal <- Some ip ) ; Wutil.later self#scroll ; end method update = main#rehighlight () method highlight (buffer : Design.reactive_buffer) (loc : Pretty_source.localizable) ~(start:int) ~(stop:int) = let buffer = buffer#buffer in begin match loc with | PStmt( _ , stmt ) -> begin match effect with | Some(s,_) when Stmt.equal stmt s -> apply_effect buffer start stop | _ -> if PATH.mem stmt path then apply_path buffer start stop end | PIP ip -> begin match goal with | Some g when Property.equal g ip -> apply_goal buffer start stop | _ -> if DEPS.mem ip deps then apply_depend buffer start stop end | PGlobal _|PVDecl _|PTermLval _|PLval _| PExp _ -> () end end
0a04691e2d6f4432554585e9f1b582972ff982b2a94c4f07ef38d1d2bdb6aaf5
peterschwarz/clj-firmata
impl.cljs
(ns firmata.test.stream.impl (:require [cemerick.cljs.test :as t] [firmata.stream.impl :as impl] [firmata.test.mock-stream :refer [create-byte-stream]]) (:require-macros [cemerick.cljs.test :refer (is are deftest testing)])) (defn ->vec [buffer] (if (coll? buffer) (vec (map #(->vec %) buffer)) (vec (aclone buffer)))) (deftest test-preparsing (let [emit-buffer (atom []) error-atom (atom nil) on-complete-data #(swap! emit-buffer conj %) preparser (impl/create-preparser on-complete-data error-atom)] (testing "Zero should emit nothing" (preparser (create-byte-stream 0)) (is (= [] @emit-buffer))) (reset! emit-buffer []) (testing "Basic Version" (preparser (create-byte-stream 0xF9 2 3)) ;version (is (= [[0xF9 2 3]]) (->vec @emit-buffer))) (reset! emit-buffer []) (testing "Multiple messages" (preparser (create-byte-stream 0xF9 2 3 0xF0 0x79 2 3 "abc" 0xF7)) (is (= [[0xF9 2 3] [0xF0 0x79 2 3 97 98 99 0xF7]] (->vec @emit-buffer)))) (reset! emit-buffer []) (testing "Half-messages" half firmware (preparser (create-byte-stream 0xF0 0x79 2 3)) (is (= [] @emit-buffer)) (preparser (create-byte-stream "abc" 0xF7)) (is (= [[0xF0 0x79 2 3 97 98 99 0xF7]] (->vec @emit-buffer)))) (reset! emit-buffer []) (testing "errors" (reset! error-atom "an error") (preparser (create-byte-stream 0)) (is (= [(impl/ErrorReader. "an error")] @emit-buffer))) )) (deftest test-make-buffer (testing "basic numbers" (are [x y] (= x y) 0 (aget (impl/make-buffer 0) 0) 1 (aget (impl/make-buffer 1) 0))) (testing "strings" (is (= "hello" (.toString (impl/make-buffer "hello"))))) (testing "vectors" (is (= [1 2 97 98 99] (->vec (impl/make-buffer [1 2 "abc"]))))))
null
https://raw.githubusercontent.com/peterschwarz/clj-firmata/cd263fe4a1b6ffb4b0e817aac019e70fe84df629/test/cljs/firmata/test/stream/impl.cljs
clojure
version
(ns firmata.test.stream.impl (:require [cemerick.cljs.test :as t] [firmata.stream.impl :as impl] [firmata.test.mock-stream :refer [create-byte-stream]]) (:require-macros [cemerick.cljs.test :refer (is are deftest testing)])) (defn ->vec [buffer] (if (coll? buffer) (vec (map #(->vec %) buffer)) (vec (aclone buffer)))) (deftest test-preparsing (let [emit-buffer (atom []) error-atom (atom nil) on-complete-data #(swap! emit-buffer conj %) preparser (impl/create-preparser on-complete-data error-atom)] (testing "Zero should emit nothing" (preparser (create-byte-stream 0)) (is (= [] @emit-buffer))) (reset! emit-buffer []) (testing "Basic Version" (is (= [[0xF9 2 3]]) (->vec @emit-buffer))) (reset! emit-buffer []) (testing "Multiple messages" (preparser (create-byte-stream 0xF9 2 3 0xF0 0x79 2 3 "abc" 0xF7)) (is (= [[0xF9 2 3] [0xF0 0x79 2 3 97 98 99 0xF7]] (->vec @emit-buffer)))) (reset! emit-buffer []) (testing "Half-messages" half firmware (preparser (create-byte-stream 0xF0 0x79 2 3)) (is (= [] @emit-buffer)) (preparser (create-byte-stream "abc" 0xF7)) (is (= [[0xF0 0x79 2 3 97 98 99 0xF7]] (->vec @emit-buffer)))) (reset! emit-buffer []) (testing "errors" (reset! error-atom "an error") (preparser (create-byte-stream 0)) (is (= [(impl/ErrorReader. "an error")] @emit-buffer))) )) (deftest test-make-buffer (testing "basic numbers" (are [x y] (= x y) 0 (aget (impl/make-buffer 0) 0) 1 (aget (impl/make-buffer 1) 0))) (testing "strings" (is (= "hello" (.toString (impl/make-buffer "hello"))))) (testing "vectors" (is (= [1 2 97 98 99] (->vec (impl/make-buffer [1 2 "abc"]))))))
5d8bdc7c5351f827ea8e17ca0342aeb1e0a90b366bb3cff4c0d72d93f7802e5a
melange-re/melange
bs_ast_invariant.mli
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *) type iterator = Ast_iterator.iterator val mark_used_bs_attribute : Parsetree.attribute -> unit (** [warn_discarded_unused_attributes discarded] warn if [discarded] has unused bs attribute *) val warn_discarded_unused_attributes : Parsetree.attributes -> unit (** Ast invariant checking for detecting errors *) val iter_warnings_on_stru : Parsetree.structure -> unit val iter_warnings_on_sigi : Parsetree.signature -> unit val emit_external_warnings_on_structure : Parsetree.structure -> unit val emit_external_warnings_on_signature : Parsetree.signature -> unit
null
https://raw.githubusercontent.com/melange-re/melange/b595c2647a285e8bb8b16f109d0ab0fbfa22afa3/jscomp/common/bs_ast_invariant.mli
ocaml
* [warn_discarded_unused_attributes discarded] warn if [discarded] has unused bs attribute * Ast invariant checking for detecting errors
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *) type iterator = Ast_iterator.iterator val mark_used_bs_attribute : Parsetree.attribute -> unit val warn_discarded_unused_attributes : Parsetree.attributes -> unit val iter_warnings_on_stru : Parsetree.structure -> unit val iter_warnings_on_sigi : Parsetree.signature -> unit val emit_external_warnings_on_structure : Parsetree.structure -> unit val emit_external_warnings_on_signature : Parsetree.signature -> unit
e58ec3066d27f0037a5b6bdcd6fa49257a47e8e0352b66458bc31459959f6a2b
chvanikoff/webserver
webserver_app.erl
-module(webserver_app). -behaviour(application). %% Application callbacks -export([ start/2, stop/1 ]). %% API -export([dispatch_rules/0]). %% =================================================================== %% API functions %% =================================================================== dispatch_rules() -> Static = fun(Filetype) -> {lists:append(["/", Filetype, "/[...]"]), cowboy_static, [ {directory, {priv_dir, webserver, [list_to_binary(Filetype)]}}, {mimetypes, {fun mimetypes:path_to_mimes/2, default}} ]} end, cowboy_router:compile([ {'_', [ Static("css"), Static("js"), Static("img"), {"/", index_handler, []}, {'_', notfound_handler, []} ]} ]). %% =================================================================== %% Application callbacks %% =================================================================== start(_StartType, _StartArgs) -> Dispatch = dispatch_rules(), Port = 8008, {ok, _} = cowboy:start_http(http_listener, 100, [{port, Port}], [{env, [{dispatch, Dispatch}]}] ), webserver_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/chvanikoff/webserver/42b66ba0f0315eab2db9e95556c4ff80ae54b0ef/src/webserver_app.erl
erlang
Application callbacks API =================================================================== API functions =================================================================== =================================================================== Application callbacks ===================================================================
-module(webserver_app). -behaviour(application). -export([ start/2, stop/1 ]). -export([dispatch_rules/0]). dispatch_rules() -> Static = fun(Filetype) -> {lists:append(["/", Filetype, "/[...]"]), cowboy_static, [ {directory, {priv_dir, webserver, [list_to_binary(Filetype)]}}, {mimetypes, {fun mimetypes:path_to_mimes/2, default}} ]} end, cowboy_router:compile([ {'_', [ Static("css"), Static("js"), Static("img"), {"/", index_handler, []}, {'_', notfound_handler, []} ]} ]). start(_StartType, _StartArgs) -> Dispatch = dispatch_rules(), Port = 8008, {ok, _} = cowboy:start_http(http_listener, 100, [{port, Port}], [{env, [{dispatch, Dispatch}]}] ), webserver_sup:start_link(). stop(_State) -> ok.
05de62954615d3479c7aa908c12e39997bf168b0f6126ebf9354ca97d1d3c2e2
bitemyapp/esqueleto
ToAliasReference.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeFamilies # module Database.Esqueleto.Experimental.ToAliasReference where import Data.Coerce import Database.Esqueleto.Internal.Internal hiding (From, from, on) import Database.Esqueleto.Internal.PersistentImport {-# DEPRECATED ToAliasReferenceT "This type alias doesn't do anything. Please delete it. Will be removed in the next release." #-} type ToAliasReferenceT a = a -- more tedious tuple magic class ToAliasReference a where toAliasReference :: Ident -> a -> SqlQuery a instance ToAliasReference (SqlExpr (Value a)) where toAliasReference aliasSource (ERaw m _) | Just alias <- sqlExprMetaAlias m = pure $ ERaw m{sqlExprMetaIsReference = True} $ \_ info -> (useIdent info aliasSource <> "." <> useIdent info alias, []) toAliasReference _ e = pure e instance ToAliasReference (SqlExpr (Entity a)) where toAliasReference aliasSource (ERaw m _) | Just _ <- sqlExprMetaAlias m = pure $ ERaw m{sqlExprMetaIsReference = True} $ \_ info -> (useIdent info aliasSource, []) toAliasReference _ e = pure e instance ToAliasReference (SqlExpr (Maybe (Entity a))) where toAliasReference aliasSource e = coerce <$> toAliasReference aliasSource (coerce e :: SqlExpr (Entity a)) instance (ToAliasReference a, ToAliasReference b) => ToAliasReference (a, b) where toAliasReference ident (a,b) = (,) <$> (toAliasReference ident a) <*> (toAliasReference ident b) instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c ) => ToAliasReference (a,b,c) where toAliasReference ident x = fmap to3 $ toAliasReference ident $ from3 x instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d ) => ToAliasReference (a,b,c,d) where toAliasReference ident x = fmap to4 $ toAliasReference ident $ from4 x instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d , ToAliasReference e ) => ToAliasReference (a,b,c,d,e) where toAliasReference ident x = fmap to5 $ toAliasReference ident $ from5 x instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d , ToAliasReference e , ToAliasReference f ) => ToAliasReference (a,b,c,d,e,f) where toAliasReference ident x = to6 <$> (toAliasReference ident $ from6 x) instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d , ToAliasReference e , ToAliasReference f , ToAliasReference g ) => ToAliasReference (a,b,c,d,e,f,g) where toAliasReference ident x = to7 <$> (toAliasReference ident $ from7 x) instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d , ToAliasReference e , ToAliasReference f , ToAliasReference g , ToAliasReference h ) => ToAliasReference (a,b,c,d,e,f,g,h) where toAliasReference ident x = to8 <$> (toAliasReference ident $ from8 x)
null
https://raw.githubusercontent.com/bitemyapp/esqueleto/ea4ff33b9308360e10f450963bb1b15a4fbb1bec/src/Database/Esqueleto/Experimental/ToAliasReference.hs
haskell
# LANGUAGE OverloadedStrings # # DEPRECATED ToAliasReferenceT "This type alias doesn't do anything. Please delete it. Will be removed in the next release." # more tedious tuple magic
# LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # module Database.Esqueleto.Experimental.ToAliasReference where import Data.Coerce import Database.Esqueleto.Internal.Internal hiding (From, from, on) import Database.Esqueleto.Internal.PersistentImport type ToAliasReferenceT a = a class ToAliasReference a where toAliasReference :: Ident -> a -> SqlQuery a instance ToAliasReference (SqlExpr (Value a)) where toAliasReference aliasSource (ERaw m _) | Just alias <- sqlExprMetaAlias m = pure $ ERaw m{sqlExprMetaIsReference = True} $ \_ info -> (useIdent info aliasSource <> "." <> useIdent info alias, []) toAliasReference _ e = pure e instance ToAliasReference (SqlExpr (Entity a)) where toAliasReference aliasSource (ERaw m _) | Just _ <- sqlExprMetaAlias m = pure $ ERaw m{sqlExprMetaIsReference = True} $ \_ info -> (useIdent info aliasSource, []) toAliasReference _ e = pure e instance ToAliasReference (SqlExpr (Maybe (Entity a))) where toAliasReference aliasSource e = coerce <$> toAliasReference aliasSource (coerce e :: SqlExpr (Entity a)) instance (ToAliasReference a, ToAliasReference b) => ToAliasReference (a, b) where toAliasReference ident (a,b) = (,) <$> (toAliasReference ident a) <*> (toAliasReference ident b) instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c ) => ToAliasReference (a,b,c) where toAliasReference ident x = fmap to3 $ toAliasReference ident $ from3 x instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d ) => ToAliasReference (a,b,c,d) where toAliasReference ident x = fmap to4 $ toAliasReference ident $ from4 x instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d , ToAliasReference e ) => ToAliasReference (a,b,c,d,e) where toAliasReference ident x = fmap to5 $ toAliasReference ident $ from5 x instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d , ToAliasReference e , ToAliasReference f ) => ToAliasReference (a,b,c,d,e,f) where toAliasReference ident x = to6 <$> (toAliasReference ident $ from6 x) instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d , ToAliasReference e , ToAliasReference f , ToAliasReference g ) => ToAliasReference (a,b,c,d,e,f,g) where toAliasReference ident x = to7 <$> (toAliasReference ident $ from7 x) instance ( ToAliasReference a , ToAliasReference b , ToAliasReference c , ToAliasReference d , ToAliasReference e , ToAliasReference f , ToAliasReference g , ToAliasReference h ) => ToAliasReference (a,b,c,d,e,f,g,h) where toAliasReference ident x = to8 <$> (toAliasReference ident $ from8 x)
44fc91d016df4c081da42dd3417e1ea6e8dd08cd6b00dedc72c7b469ba964432
yrashk/erlang
typer_annotator.erl
-*- erlang - indent - level : 2 -*- %% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 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% %% %%============================================================================ %% File : typer_annotator.erl Author : Bingwen He < > %% Description : %% If file 'FILENAME' has been analyzed, then the output of command " diff -B typer_ann / FILENAME.ann.erl " should be exactly what TypEr has added , namely type info . %%============================================================================ -module(typer_annotator). -export([annotate/1]). %%---------------------------------------------------------------------------- -include("typer.hrl"). %%---------------------------------------------------------------------------- -define(TYPER_ANN_DIR, "typer_ann"). -type func_info() :: {non_neg_integer(), atom(), arity()}. -record(info, {recMap = typer_map:new() :: dict(), funcs = [] :: [func_info()], typeMap :: dict(), contracts :: bool()}). -record(inc, {map = typer_map:new() :: dict(), filter = [] :: [string()]}). %%---------------------------------------------------------------------------- -spec annotate(#typer_analysis{}) -> 'ok'. annotate(Analysis) -> case Analysis#typer_analysis.mode of ?SHOW -> show(Analysis); ?SHOW_EXPORTED -> show(Analysis); ?ANNOTATE -> Fun = fun({File, Module}) -> Info = get_final_info(File, Module, Analysis), write_typed_file(File, Info) end, lists:foreach(Fun, Analysis#typer_analysis.final_files); ?ANNOTATE_INC_FILES -> IncInfo = write_and_collect_inc_info(Analysis), write_inc_files(IncInfo) end. write_and_collect_inc_info(Analysis) -> Fun = fun({File, Module}, Inc) -> Info = get_final_info(File, Module, Analysis), write_typed_file(File, Info), IncFuns = get_functions(File, Analysis), collect_imported_funcs(IncFuns, Info#info.typeMap, Inc) end, NewInc = lists:foldl(Fun,#inc{}, Analysis#typer_analysis.final_files), clean_inc(NewInc). write_inc_files(Inc) -> Fun = fun (File) -> Val = typer_map:lookup(File,Inc#inc.map), %% Val is function with its type info in form [ { { Line , F , A},Type } ] Functions = [Key || {Key,_} <- Val], Val1 = [{{F,A},Type} || {{_Line,F,A},Type} <- Val], Info = #info{typeMap = typer_map:from_list(Val1), recMap = typer_map:new(), %% Note we need to sort functions here! funcs = lists:keysort(1, Functions)}, %% io:format("TypeMap ~p\n", [Info#info.typeMap]), %% io:format("Funcs ~p\n", [Info#info.funcs]), %% io:format("RecMap ~p\n", [Info#info.recMap]), write_typed_file(File, Info) end, lists:foreach(Fun, dict:fetch_keys(Inc#inc.map)). show(Analysis) -> Fun = fun({File, Module}) -> Info = get_final_info(File, Module, Analysis), show_type_info_only(File, Info) end, lists:foreach(Fun, Analysis#typer_analysis.final_files). get_final_info(File, Module, Analysis) -> RecMap = get_recMap(File, Analysis), TypeMap = get_typeMap(Module, Analysis,RecMap), Functions = get_functions(File, Analysis), Contracts = Analysis#typer_analysis.contracts, #info{recMap=RecMap, funcs=Functions, typeMap=TypeMap, contracts=Contracts}. collect_imported_funcs(Funcs, TypeMap, TmpInc) -> %% Coming from other sourses, including: %% FIXME: How to deal with yecc-generated file???? %% --.yrl (yecc-generated file)??? %% -- yeccpre.hrl (yecc-generated file)??? %% -- other cases Fun = fun({File,_} = Obj, Inc) -> case is_yecc_file(File, Inc) of {yecc_generated, NewInc} -> NewInc; {not_yecc, NewInc} -> check_imported_funcs(Obj, NewInc, TypeMap) end end, lists:foldl(Fun, TmpInc, Funcs). -spec is_yecc_file(string(), #inc{}) -> {'not_yecc', #inc{}} | {'yecc_generated', #inc{}}. is_yecc_file(File, Inc) -> case lists:member(File, Inc#inc.filter) of true -> {yecc_generated, Inc}; false -> case filename:extension(File) of ".yrl" -> Rootname = filename:rootname(File, ".yrl"), Obj = Rootname ++ ".erl", case lists:member(Obj, Inc#inc.filter) of true -> {yecc_generated, Inc}; false -> NewFilter = [Obj|Inc#inc.filter], NewInc = Inc#inc{filter = NewFilter}, {yecc_generated, NewInc} end; _ -> case filename:basename(File) of "yeccpre.hrl" -> {yecc_generated, Inc}; _ -> {not_yecc, Inc} end end end. check_imported_funcs({File, {Line, F, A}}, Inc, TypeMap) -> IncMap = Inc#inc.map, FA = {F, A}, Type = get_type_info(FA, TypeMap), case typer_map:lookup(File, IncMap) of none -> %% File is not added. Add it Obj = {File,[{FA, {Line, Type}}]}, NewMap = typer_map:insert(Obj, IncMap), Inc#inc{map = NewMap}; Val -> %% File is already in. Check. case lists:keyfind(FA, 1, Val) of false -> %% Function is not in; add it Obj = {File, Val ++ [{FA, {Line, Type}}]}, NewMap = typer_map:insert(Obj, IncMap), Inc#inc{map = NewMap}; Type -> %% Function is in and with same type Inc; _ -> %% Function is in but with diff type inc_warning(FA, File), Elem = lists:keydelete(FA, 1, Val), NewMap = case Elem of [] -> typer_map:remove(File, IncMap); _ -> typer_map:insert({File, Elem}, IncMap) end, Inc#inc{map = NewMap} end end. inc_warning({F, A}, File) -> io:format(" ***Warning: Skip function ~p/~p ", [F, A]), io:format("in file ~p because of inconsistent type\n", [File]). clean_inc(Inc) -> Inc1 = remove_yecc_generated_file(Inc), normalize_obj(Inc1). remove_yecc_generated_file(TmpInc) -> Fun = fun(Key, Inc) -> NewMap = typer_map:remove(Key, Inc#inc.map), Inc#inc{map = NewMap} end, lists:foldl(Fun, TmpInc, TmpInc#inc.filter). normalize_obj(TmpInc) -> Fun = fun(Key, Val, Inc) -> NewVal = [{{Line,F,A},Type} || {{F,A},{Line,Type}} <- Val], typer_map:insert({Key,NewVal},Inc) end, NewMap = typer_map:fold(Fun, typer_map:new(), TmpInc#inc.map), TmpInc#inc{map = NewMap}. get_recMap(File, Analysis) -> typer_map:lookup(File, Analysis#typer_analysis.record). get_typeMap(Module, Analysis, RecMap) -> TypeInfoPlt = Analysis#typer_analysis.trust_plt, TypeInfo = case dialyzer_plt:lookup_module(TypeInfoPlt, Module) of none -> []; {value, List} -> List end, CodeServer = Analysis#typer_analysis.code_server, TypeInfoList = [get_type(I, CodeServer, RecMap) || I <- TypeInfo], typer_map:from_list(TypeInfoList). get_type({MFA = {M,F,A}, Range, Arg}, CodeServer, RecMap) -> case dialyzer_codeserver:lookup_contract(MFA, CodeServer) of {ok, {_Line, C}} -> Sig = erl_types:t_fun(Arg, Range), case dialyzer_contracts:check_contract(C, Sig) of ok -> {{F, A}, {contract, C}}; {error, invalid_contract} -> CString = dialyzer_contracts:contract_to_string(C), SigString = dialyzer_utils:format_sig(Sig, RecMap), typer:error( io_lib:format("Error in contract of function ~w:~w/~w\n" "\t The contract is: " ++ CString ++ "\n" ++ "\t but the inferred signature is: ~s", [M, F, A, SigString])); {error, Msg} -> typer:error( io_lib:format("Error in contract of function ~w:~w/~w: ~s", [M, F, A, Msg])) end; error -> {{F, A}, {Range, Arg}} end. get_functions(File, Analysis) -> case Analysis#typer_analysis.mode of ?SHOW -> Funcs = typer_map:lookup(File, Analysis#typer_analysis.func), Inc_Funcs = typer_map:lookup(File, Analysis#typer_analysis.inc_func), remove_module_info(Funcs) ++ normalize_incFuncs(Inc_Funcs); ?SHOW_EXPORTED -> Ex_Funcs = typer_map:lookup(File, Analysis#typer_analysis.ex_func), remove_module_info(Ex_Funcs); ?ANNOTATE -> Funcs = typer_map:lookup(File, Analysis#typer_analysis.func), remove_module_info(Funcs); ?ANNOTATE_INC_FILES -> typer_map:lookup(File, Analysis#typer_analysis.inc_func) end. normalize_incFuncs(Funcs) -> [FuncInfo || {_FileName,FuncInfo} <- Funcs]. -spec remove_module_info([func_info()]) -> [func_info()]. remove_module_info(FuncInfoList) -> F = fun ({_,module_info,0}) -> false; ({_,module_info,1}) -> false; ({Line,F,A}) when is_integer(Line), is_atom(F), is_integer(A) -> true end, lists:filter(F, FuncInfoList). write_typed_file(File, Info) -> io:format(" Processing file: ~p\n", [File]), Dir = filename:dirname(File), RootName = filename:basename(filename:rootname(File)), Ext = filename:extension(File), TyperAnnDir = filename:join(Dir, ?TYPER_ANN_DIR), TmpNewFilename = lists:concat([RootName,".ann",Ext]), NewFileName = filename:join(TyperAnnDir, TmpNewFilename), case file:make_dir(TyperAnnDir) of {error, Reason} -> case Reason of TypEr dir exists ; remove old typer files ok = file:delete(NewFileName), write_typed_file(File, Info, NewFileName); enospc -> io:format(" Not enough space in ~p\n", [Dir]); eacces -> io:format(" No write permission in ~p\n", [Dir]); _ -> io:format("Unknown error when writing ~p\n", [Dir]), halt() end; does NOT exist write_typed_file(File, Info, NewFileName) end. write_typed_file(File, Info, NewFileName) -> {ok, Binary} = file:read_file(File), Chars = binary_to_list(Binary), write_typed_file(Chars, NewFileName, Info, 1, []), io:format(" Saved as: ~p\n", [NewFileName]). write_typed_file(Chars, File, #info{funcs = []}, _LNo, _Acc) -> ok = file:write_file(File, list_to_binary(Chars), [append]); write_typed_file([Ch|Chs] = Chars, File, Info, LineNo, Acc) -> [{Line,F,A}|RestFuncs] = Info#info.funcs, case Line of 1 -> %% This will happen only for inc files ok = raw_write(F, A, Info, File, []), NewInfo = Info#info{funcs = RestFuncs}, NewAcc = [], write_typed_file(Chars, File, NewInfo, Line, NewAcc); _ -> case Ch of 10 -> NewLineNo = LineNo + 1, {NewInfo, NewAcc} = case NewLineNo of Line -> ok = raw_write(F, A, Info, File, [Ch|Acc]), {Info#info{funcs = RestFuncs}, []}; _ -> {Info, [Ch|Acc]} end, write_typed_file(Chs, File, NewInfo, NewLineNo, NewAcc); _ -> write_typed_file(Chs, File, Info, LineNo, [Ch|Acc]) end end. raw_write(F, A, Info, File, Content) -> TypeInfo = get_type_string(F, A, Info, file), ContentList = lists:reverse(Content) ++ TypeInfo ++ "\n", ContentBin = list_to_binary(ContentList), file:write_file(File, ContentBin, [append]). get_type_string(F, A, Info, Mode) -> Type = get_type_info({F,A}, Info#info.typeMap), TypeStr = case Type of {contract, C} -> dialyzer_contracts:contract_to_string(C); {RetType, ArgType} -> dialyzer_utils:format_sig(erl_types:t_fun(ArgType, RetType), Info#info.recMap) end, case Info#info.contracts of true -> case {Mode, Type} of {file, {contract, _}} -> ""; _ -> Prefix = lists:concat(["-spec ", F]), lists:concat([Prefix, TypeStr, "."]) end; false -> Prefix = lists:concat(["%% @spec ", F]), lists:concat([Prefix, TypeStr, "."]) end. show_type_info_only(File, Info) -> io:format("\n%% File: ~p\n%% ", [File]), OutputString = lists:concat(["~.", length(File)+8, "c~n"]), io:fwrite(OutputString, [$-]), Fun = fun ({_LineNo, F, A}) -> TypeInfo = get_type_string(F, A, Info, show), io:format("~s\n", [TypeInfo]) end, lists:foreach(Fun, Info#info.funcs). get_type_info(Func, TypeMap) -> case typer_map:lookup(Func, TypeMap) of none -> %% Note: Typeinfo of any function should exist in the result offered by , otherwise there %% *must* be something wrong with the analysis io:format("No type info for function: ~p\n", [Func]), halt(); {contract, _Fun} = C -> C; {_RetType, _ArgType} = RA -> RA end.
null
https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/typer/src/typer_annotator.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% ============================================================================ File : typer_annotator.erl Description : If file 'FILENAME' has been analyzed, then the output of ============================================================================ ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Val is function with its type info Note we need to sort functions here! io:format("TypeMap ~p\n", [Info#info.typeMap]), io:format("Funcs ~p\n", [Info#info.funcs]), io:format("RecMap ~p\n", [Info#info.recMap]), Coming from other sourses, including: FIXME: How to deal with yecc-generated file???? --.yrl (yecc-generated file)??? -- yeccpre.hrl (yecc-generated file)??? -- other cases File is not added. Add it File is already in. Check. Function is not in; add it Function is in and with same type Function is in but with diff type This will happen only for inc files Note: Typeinfo of any function should exist in *must* be something wrong with the analysis
-*- erlang - indent - level : 2 -*- Copyright Ericsson AB 2008 - 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 " Author : Bingwen He < > command " diff -B typer_ann / FILENAME.ann.erl " should be exactly what TypEr has added , namely type info . -module(typer_annotator). -export([annotate/1]). -include("typer.hrl"). -define(TYPER_ANN_DIR, "typer_ann"). -type func_info() :: {non_neg_integer(), atom(), arity()}. -record(info, {recMap = typer_map:new() :: dict(), funcs = [] :: [func_info()], typeMap :: dict(), contracts :: bool()}). -record(inc, {map = typer_map:new() :: dict(), filter = [] :: [string()]}). -spec annotate(#typer_analysis{}) -> 'ok'. annotate(Analysis) -> case Analysis#typer_analysis.mode of ?SHOW -> show(Analysis); ?SHOW_EXPORTED -> show(Analysis); ?ANNOTATE -> Fun = fun({File, Module}) -> Info = get_final_info(File, Module, Analysis), write_typed_file(File, Info) end, lists:foreach(Fun, Analysis#typer_analysis.final_files); ?ANNOTATE_INC_FILES -> IncInfo = write_and_collect_inc_info(Analysis), write_inc_files(IncInfo) end. write_and_collect_inc_info(Analysis) -> Fun = fun({File, Module}, Inc) -> Info = get_final_info(File, Module, Analysis), write_typed_file(File, Info), IncFuns = get_functions(File, Analysis), collect_imported_funcs(IncFuns, Info#info.typeMap, Inc) end, NewInc = lists:foldl(Fun,#inc{}, Analysis#typer_analysis.final_files), clean_inc(NewInc). write_inc_files(Inc) -> Fun = fun (File) -> Val = typer_map:lookup(File,Inc#inc.map), in form [ { { Line , F , A},Type } ] Functions = [Key || {Key,_} <- Val], Val1 = [{{F,A},Type} || {{_Line,F,A},Type} <- Val], Info = #info{typeMap = typer_map:from_list(Val1), recMap = typer_map:new(), funcs = lists:keysort(1, Functions)}, write_typed_file(File, Info) end, lists:foreach(Fun, dict:fetch_keys(Inc#inc.map)). show(Analysis) -> Fun = fun({File, Module}) -> Info = get_final_info(File, Module, Analysis), show_type_info_only(File, Info) end, lists:foreach(Fun, Analysis#typer_analysis.final_files). get_final_info(File, Module, Analysis) -> RecMap = get_recMap(File, Analysis), TypeMap = get_typeMap(Module, Analysis,RecMap), Functions = get_functions(File, Analysis), Contracts = Analysis#typer_analysis.contracts, #info{recMap=RecMap, funcs=Functions, typeMap=TypeMap, contracts=Contracts}. collect_imported_funcs(Funcs, TypeMap, TmpInc) -> Fun = fun({File,_} = Obj, Inc) -> case is_yecc_file(File, Inc) of {yecc_generated, NewInc} -> NewInc; {not_yecc, NewInc} -> check_imported_funcs(Obj, NewInc, TypeMap) end end, lists:foldl(Fun, TmpInc, Funcs). -spec is_yecc_file(string(), #inc{}) -> {'not_yecc', #inc{}} | {'yecc_generated', #inc{}}. is_yecc_file(File, Inc) -> case lists:member(File, Inc#inc.filter) of true -> {yecc_generated, Inc}; false -> case filename:extension(File) of ".yrl" -> Rootname = filename:rootname(File, ".yrl"), Obj = Rootname ++ ".erl", case lists:member(Obj, Inc#inc.filter) of true -> {yecc_generated, Inc}; false -> NewFilter = [Obj|Inc#inc.filter], NewInc = Inc#inc{filter = NewFilter}, {yecc_generated, NewInc} end; _ -> case filename:basename(File) of "yeccpre.hrl" -> {yecc_generated, Inc}; _ -> {not_yecc, Inc} end end end. check_imported_funcs({File, {Line, F, A}}, Inc, TypeMap) -> IncMap = Inc#inc.map, FA = {F, A}, Type = get_type_info(FA, TypeMap), case typer_map:lookup(File, IncMap) of Obj = {File,[{FA, {Line, Type}}]}, NewMap = typer_map:insert(Obj, IncMap), Inc#inc{map = NewMap}; case lists:keyfind(FA, 1, Val) of false -> Obj = {File, Val ++ [{FA, {Line, Type}}]}, NewMap = typer_map:insert(Obj, IncMap), Inc#inc{map = NewMap}; Type -> Inc; _ -> inc_warning(FA, File), Elem = lists:keydelete(FA, 1, Val), NewMap = case Elem of [] -> typer_map:remove(File, IncMap); _ -> typer_map:insert({File, Elem}, IncMap) end, Inc#inc{map = NewMap} end end. inc_warning({F, A}, File) -> io:format(" ***Warning: Skip function ~p/~p ", [F, A]), io:format("in file ~p because of inconsistent type\n", [File]). clean_inc(Inc) -> Inc1 = remove_yecc_generated_file(Inc), normalize_obj(Inc1). remove_yecc_generated_file(TmpInc) -> Fun = fun(Key, Inc) -> NewMap = typer_map:remove(Key, Inc#inc.map), Inc#inc{map = NewMap} end, lists:foldl(Fun, TmpInc, TmpInc#inc.filter). normalize_obj(TmpInc) -> Fun = fun(Key, Val, Inc) -> NewVal = [{{Line,F,A},Type} || {{F,A},{Line,Type}} <- Val], typer_map:insert({Key,NewVal},Inc) end, NewMap = typer_map:fold(Fun, typer_map:new(), TmpInc#inc.map), TmpInc#inc{map = NewMap}. get_recMap(File, Analysis) -> typer_map:lookup(File, Analysis#typer_analysis.record). get_typeMap(Module, Analysis, RecMap) -> TypeInfoPlt = Analysis#typer_analysis.trust_plt, TypeInfo = case dialyzer_plt:lookup_module(TypeInfoPlt, Module) of none -> []; {value, List} -> List end, CodeServer = Analysis#typer_analysis.code_server, TypeInfoList = [get_type(I, CodeServer, RecMap) || I <- TypeInfo], typer_map:from_list(TypeInfoList). get_type({MFA = {M,F,A}, Range, Arg}, CodeServer, RecMap) -> case dialyzer_codeserver:lookup_contract(MFA, CodeServer) of {ok, {_Line, C}} -> Sig = erl_types:t_fun(Arg, Range), case dialyzer_contracts:check_contract(C, Sig) of ok -> {{F, A}, {contract, C}}; {error, invalid_contract} -> CString = dialyzer_contracts:contract_to_string(C), SigString = dialyzer_utils:format_sig(Sig, RecMap), typer:error( io_lib:format("Error in contract of function ~w:~w/~w\n" "\t The contract is: " ++ CString ++ "\n" ++ "\t but the inferred signature is: ~s", [M, F, A, SigString])); {error, Msg} -> typer:error( io_lib:format("Error in contract of function ~w:~w/~w: ~s", [M, F, A, Msg])) end; error -> {{F, A}, {Range, Arg}} end. get_functions(File, Analysis) -> case Analysis#typer_analysis.mode of ?SHOW -> Funcs = typer_map:lookup(File, Analysis#typer_analysis.func), Inc_Funcs = typer_map:lookup(File, Analysis#typer_analysis.inc_func), remove_module_info(Funcs) ++ normalize_incFuncs(Inc_Funcs); ?SHOW_EXPORTED -> Ex_Funcs = typer_map:lookup(File, Analysis#typer_analysis.ex_func), remove_module_info(Ex_Funcs); ?ANNOTATE -> Funcs = typer_map:lookup(File, Analysis#typer_analysis.func), remove_module_info(Funcs); ?ANNOTATE_INC_FILES -> typer_map:lookup(File, Analysis#typer_analysis.inc_func) end. normalize_incFuncs(Funcs) -> [FuncInfo || {_FileName,FuncInfo} <- Funcs]. -spec remove_module_info([func_info()]) -> [func_info()]. remove_module_info(FuncInfoList) -> F = fun ({_,module_info,0}) -> false; ({_,module_info,1}) -> false; ({Line,F,A}) when is_integer(Line), is_atom(F), is_integer(A) -> true end, lists:filter(F, FuncInfoList). write_typed_file(File, Info) -> io:format(" Processing file: ~p\n", [File]), Dir = filename:dirname(File), RootName = filename:basename(filename:rootname(File)), Ext = filename:extension(File), TyperAnnDir = filename:join(Dir, ?TYPER_ANN_DIR), TmpNewFilename = lists:concat([RootName,".ann",Ext]), NewFileName = filename:join(TyperAnnDir, TmpNewFilename), case file:make_dir(TyperAnnDir) of {error, Reason} -> case Reason of TypEr dir exists ; remove old typer files ok = file:delete(NewFileName), write_typed_file(File, Info, NewFileName); enospc -> io:format(" Not enough space in ~p\n", [Dir]); eacces -> io:format(" No write permission in ~p\n", [Dir]); _ -> io:format("Unknown error when writing ~p\n", [Dir]), halt() end; does NOT exist write_typed_file(File, Info, NewFileName) end. write_typed_file(File, Info, NewFileName) -> {ok, Binary} = file:read_file(File), Chars = binary_to_list(Binary), write_typed_file(Chars, NewFileName, Info, 1, []), io:format(" Saved as: ~p\n", [NewFileName]). write_typed_file(Chars, File, #info{funcs = []}, _LNo, _Acc) -> ok = file:write_file(File, list_to_binary(Chars), [append]); write_typed_file([Ch|Chs] = Chars, File, Info, LineNo, Acc) -> [{Line,F,A}|RestFuncs] = Info#info.funcs, case Line of ok = raw_write(F, A, Info, File, []), NewInfo = Info#info{funcs = RestFuncs}, NewAcc = [], write_typed_file(Chars, File, NewInfo, Line, NewAcc); _ -> case Ch of 10 -> NewLineNo = LineNo + 1, {NewInfo, NewAcc} = case NewLineNo of Line -> ok = raw_write(F, A, Info, File, [Ch|Acc]), {Info#info{funcs = RestFuncs}, []}; _ -> {Info, [Ch|Acc]} end, write_typed_file(Chs, File, NewInfo, NewLineNo, NewAcc); _ -> write_typed_file(Chs, File, Info, LineNo, [Ch|Acc]) end end. raw_write(F, A, Info, File, Content) -> TypeInfo = get_type_string(F, A, Info, file), ContentList = lists:reverse(Content) ++ TypeInfo ++ "\n", ContentBin = list_to_binary(ContentList), file:write_file(File, ContentBin, [append]). get_type_string(F, A, Info, Mode) -> Type = get_type_info({F,A}, Info#info.typeMap), TypeStr = case Type of {contract, C} -> dialyzer_contracts:contract_to_string(C); {RetType, ArgType} -> dialyzer_utils:format_sig(erl_types:t_fun(ArgType, RetType), Info#info.recMap) end, case Info#info.contracts of true -> case {Mode, Type} of {file, {contract, _}} -> ""; _ -> Prefix = lists:concat(["-spec ", F]), lists:concat([Prefix, TypeStr, "."]) end; false -> Prefix = lists:concat(["%% @spec ", F]), lists:concat([Prefix, TypeStr, "."]) end. show_type_info_only(File, Info) -> io:format("\n%% File: ~p\n%% ", [File]), OutputString = lists:concat(["~.", length(File)+8, "c~n"]), io:fwrite(OutputString, [$-]), Fun = fun ({_LineNo, F, A}) -> TypeInfo = get_type_string(F, A, Info, show), io:format("~s\n", [TypeInfo]) end, lists:foreach(Fun, Info#info.funcs). get_type_info(Func, TypeMap) -> case typer_map:lookup(Func, TypeMap) of none -> the result offered by , otherwise there io:format("No type info for function: ~p\n", [Func]), halt(); {contract, _Fun} = C -> C; {_RetType, _ArgType} = RA -> RA end.
b0bd7a029f9de450d56fabdd83df83a80d22245d1ca26cacc42900c70c95271a
coq/coq
vmbytegen.mli
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) * GNU Lesser General Public License Version 2.1 (* * (see LICENSE file for the text of the license) *) (************************************************************************) open Vmbytecodes open Vmemitcodes open Constr open Declarations open Environ (** Should only be used for monomorphic terms *) val compile : fail_on_error:bool -> ?universes:int -> env -> Genlambda.evars -> constr -> (to_patch * fv) option (** init, fun, fv *) val compile_constant_body : fail_on_error:bool -> env -> universes -> (Constr.t, 'opaque) constant_def -> body_code option (** Shortcut of the previous function used during module strengthening *) val compile_alias : Names.Constant.t -> body_code (** Dump the bytecode after compilation (for debugging purposes) *) val dump_bytecode : bool ref
null
https://raw.githubusercontent.com/coq/coq/1c739a0ddce17bda4198a5f988056019745213ca/kernel/vmbytegen.mli
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) ********************************************************************** * Should only be used for monomorphic terms * init, fun, fv * Shortcut of the previous function used during module strengthening * Dump the bytecode after compilation (for debugging purposes)
v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 open Vmbytecodes open Vmemitcodes open Constr open Declarations open Environ val compile : fail_on_error:bool -> ?universes:int -> env -> Genlambda.evars -> constr -> (to_patch * fv) option val compile_constant_body : fail_on_error:bool -> env -> universes -> (Constr.t, 'opaque) constant_def -> body_code option val compile_alias : Names.Constant.t -> body_code val dump_bytecode : bool ref
46484a6137b40e50348008bf4ecfc894cd4cc0130846b868c6b815d6b10f7fca
triffon/fp-2021-22
ex11-20211221-solutions.rkt
#lang racket (define head car) (define tail cdr) ; Стандартни, полезни функции (define (all? p? lst) (or (null? lst) (and (p? (head lst)) (all? p? (tail lst))))) (define (any? p? lst) (not (none? p? lst))) (define (none? p? lst) (all? (lambda (x) (not (p? x))) lst)) ацикличен граф (define G '((0 1 3) (1 2 5) (2) (3 4 5) (4 5) (5))) Интерфайс за графи , използващ представянето тип " асоциативен списък " (define (vertices g) (map head g)) (define (children u g) (define (tail-#f x) (if x (tail x) #f)) (tail-#f (assoc u g))) ; в случай на невалиден вход (define (edge? u v g) (member v (children u g))) (define (parents u g) (filter (lambda (v) (edge? v u g)) (vertices g))) ; [ v | v<-vertices g, edge? v u g ] ; Зад.1а) (define (family? f g) ; Локални помощни функции (define (all-in-f? lst) (all? (lambda (x) (member x f)) lst)) (define (none-in-f? lst) (none? (lambda (x) (member x f)) lst)) (all? (lambda (u) (or (and (all-in-f? (parents u g)) (none-in-f? (children u g))) (and (all-in-f? (children u g)) (none-in-f? (parents u g))))) f)) ( ( 1 2 3 ) ( 4 ) ( 5 6 ) ) - > ( 1 2 3 4 5 6 ) В Хаскел е (define (concat lsts) (apply append lsts)) (define (uniques lst) (foldr (lambda (el res) (if (member el res) res (cons el res))) '() lst)) ; Понякога са полезни и операции като с множества lst1 . lst2 (define (set-intersect lst1 lst2) (filter (lambda (x) (member x lst2)) lst1)) ; lst1 / lst2 (define (set-difference lst1 lst2) (filter (lambda (x) (not (member x lst2))) lst1)) ; Зад.1б) (define (min-including u g) (define (helper curr all flag) (let* [(next** (map (lambda (u) ((if flag parents children) u g)) curr)) (next* (uniques (concat next**))) (next (set-difference next* all))] (if (null? next) all (helper next (append all next) (not flag))))) Може би има и по - , не се сетих на момента (let [(try1 (helper (list u) (list u) #t)) (try2 (helper (list u) (list u) #f))] (cond [(family? try1 g) try1] [(family? try2 g) try2] [else #f]))) ; Зад.2 Можем да изброим върхове и да изберем най - доброто подходящо измежду тях . (define (subsets lst) (if (null? lst) (list '()) (let [(rest (subsets (tail lst)))] (append rest (map (lambda (s) (cons (head lst) s)) rest))))) ; (define (subsets lst) (combinations lst)) в Racket ; Зад.3 Добавяне на двойка ключ - стойност в асоциативен списък (define (add-assoc k v lst) (cond [(null? lst) (list (list k v))] [(and (equal? k (head (head lst))) (member v (tail (head lst)))) lst] [(equal? k (head (head lst))) (cons (cons k (cons v (tail (head lst)))) (tail lst))] [else (cons (head lst) (add-assoc k v (tail lst)))])) ; Зад.4 (define e '((0 . 1) (0 . 2) (1 . 2) (2 . 3) (1 . 3))) Проблем : ако от връх няма , няма да го включи (define (edges-to-neighbs edges) (foldr (lambda (el res) (add-assoc (car el) (cdr el) res)) '() e)) Решение - събираме върхове и правим асоциативен списък с тях като ключове , но без . (define (all-vertices e) ; (0 1 2 3) (uniques (append (map car e) (map cdr e)))) (define (edges-to-neighbs* edges) (let [(all-vertices ; (0 1 2 3) (uniques (append (map car e) (map cdr e))))] (foldr (lambda (el res) (add-assoc (car el) (cdr el) res)) ( ( 0 ) ( 1 ) ( 2 ) ( 3 ) ) e)))
null
https://raw.githubusercontent.com/triffon/fp-2021-22/fa2df63a654d37c7725bd5b888979a24acc48bee/exercises/5/ex11-20211221-solutions.rkt
racket
Стандартни, полезни функции в случай на невалиден вход [ v | v<-vertices g, edge? v u g ] Зад.1а) Локални помощни функции Понякога са полезни и операции като с множества lst1 / lst2 Зад.1б) Зад.2 (define (subsets lst) (combinations lst)) в Racket Зад.3 Зад.4 (0 1 2 3) (0 1 2 3)
#lang racket (define head car) (define tail cdr) (define (all? p? lst) (or (null? lst) (and (p? (head lst)) (all? p? (tail lst))))) (define (any? p? lst) (not (none? p? lst))) (define (none? p? lst) (all? (lambda (x) (not (p? x))) lst)) ацикличен граф (define G '((0 1 3) (1 2 5) (2) (3 4 5) (4 5) (5))) Интерфайс за графи , използващ представянето тип " асоциативен списък " (define (vertices g) (map head g)) (define (children u g) (define (tail-#f x) (if x (tail x) #f)) (define (edge? u v g) (member v (children u g))) (define (parents u g) (filter (lambda (v) (edge? v u g)) (vertices g))) (define (family? f g) (define (all-in-f? lst) (all? (lambda (x) (member x f)) lst)) (define (none-in-f? lst) (none? (lambda (x) (member x f)) lst)) (all? (lambda (u) (or (and (all-in-f? (parents u g)) (none-in-f? (children u g))) (and (all-in-f? (children u g)) (none-in-f? (parents u g))))) f)) ( ( 1 2 3 ) ( 4 ) ( 5 6 ) ) - > ( 1 2 3 4 5 6 ) В Хаскел е (define (concat lsts) (apply append lsts)) (define (uniques lst) (foldr (lambda (el res) (if (member el res) res (cons el res))) '() lst)) lst1 . lst2 (define (set-intersect lst1 lst2) (filter (lambda (x) (member x lst2)) lst1)) (define (set-difference lst1 lst2) (filter (lambda (x) (not (member x lst2))) lst1)) (define (min-including u g) (define (helper curr all flag) (let* [(next** (map (lambda (u) ((if flag parents children) u g)) curr)) (next* (uniques (concat next**))) (next (set-difference next* all))] (if (null? next) all (helper next (append all next) (not flag))))) Може би има и по - , не се сетих на момента (let [(try1 (helper (list u) (list u) #t)) (try2 (helper (list u) (list u) #f))] (cond [(family? try1 g) try1] [(family? try2 g) try2] [else #f]))) Можем да изброим върхове и да изберем най - доброто подходящо измежду тях . (define (subsets lst) (if (null? lst) (list '()) (let [(rest (subsets (tail lst)))] (append rest (map (lambda (s) (cons (head lst) s)) rest))))) Добавяне на двойка ключ - стойност в асоциативен списък (define (add-assoc k v lst) (cond [(null? lst) (list (list k v))] [(and (equal? k (head (head lst))) (member v (tail (head lst)))) lst] [(equal? k (head (head lst))) (cons (cons k (cons v (tail (head lst)))) (tail lst))] [else (cons (head lst) (add-assoc k v (tail lst)))])) (define e '((0 . 1) (0 . 2) (1 . 2) (2 . 3) (1 . 3))) Проблем : ако от връх няма , няма да го включи (define (edges-to-neighbs edges) (foldr (lambda (el res) (add-assoc (car el) (cdr el) res)) '() e)) Решение - събираме върхове и правим асоциативен списък с тях като ключове , но без . (uniques (append (map car e) (map cdr e)))) (define (edges-to-neighbs* edges) (uniques (append (map car e) (map cdr e))))] (foldr (lambda (el res) (add-assoc (car el) (cdr el) res)) ( ( 0 ) ( 1 ) ( 2 ) ( 3 ) ) e)))
b4000a9195c08d6f8be147bf3bb9ae6a8286a4b3210da465aa91234a66d0ff7f
wireapp/saml2-web-sso
Util.hs
{-# LANGUAGE OverloadedStrings #-} module SAML2.Util ( module SAML2.Util, module Text.XML.Util, ) where import Control.Lens import Control.Monad.Except import Data.String.Conversions import qualified Data.Text as ST import Data.Typeable import GHC.Stack import Text.XML.Util import URI.ByteString renderURI :: URI -> ST renderURI = cs . serializeURIRef' parseURI' :: MonadError String m => ST -> m URI parseURI' uri = either (die' (Just $ show uri) (Proxy @URI)) pure . parseURI laxURIParserOptions . cs . ST.strip $ uri -- | You probably should not use this. If you have a string literal, consider "URI.ByteString.QQ". unsafeParseURI :: ST -> URI unsafeParseURI = either (error . ("could not parse config: " <>) . show) id . parseURI' | @uriSegments " /one / two " = = uriSegments " one / two/ " = = uriSegments " ///one//two/// " = = [ " one " , " two"]@ uriSegments :: ST -> [ST] uriSegments = filter (not . ST.null) . ST.splitOn "/" uriUnSegments :: [ST] -> ST uriUnSegments = ("/" <>) . ST.intercalate "/" (-/) :: HasCallStack => ST -> ST -> ST oldpath -/ pathext = uriUnSegments . uriSegments $ oldpath <> "/" <> pathext (=/) :: HasCallStack => URI -> ST -> URI uri =/ pathext = normURI $ uri & pathL %~ (<> "/" <> cs pathext) normURI :: URI -> URI normURI = unsafeParseURI . cs . normalizeURIRef' URINormalizationOptions { unoDowncaseScheme = True, unoDowncaseHost = True, unoDropDefPort = False, unoSlashEmptyPath = True, unoDropExtraSlashes = True, unoSortParameters = True, unoRemoveDotSegments = True, unoDefaultPorts = mempty }
null
https://raw.githubusercontent.com/wireapp/saml2-web-sso/ac88b934bb4a91d4d4bb90c620277188e4087043/src/SAML2/Util.hs
haskell
# LANGUAGE OverloadedStrings # | You probably should not use this. If you have a string literal, consider "URI.ByteString.QQ".
module SAML2.Util ( module SAML2.Util, module Text.XML.Util, ) where import Control.Lens import Control.Monad.Except import Data.String.Conversions import qualified Data.Text as ST import Data.Typeable import GHC.Stack import Text.XML.Util import URI.ByteString renderURI :: URI -> ST renderURI = cs . serializeURIRef' parseURI' :: MonadError String m => ST -> m URI parseURI' uri = either (die' (Just $ show uri) (Proxy @URI)) pure . parseURI laxURIParserOptions . cs . ST.strip $ uri unsafeParseURI :: ST -> URI unsafeParseURI = either (error . ("could not parse config: " <>) . show) id . parseURI' | @uriSegments " /one / two " = = uriSegments " one / two/ " = = uriSegments " ///one//two/// " = = [ " one " , " two"]@ uriSegments :: ST -> [ST] uriSegments = filter (not . ST.null) . ST.splitOn "/" uriUnSegments :: [ST] -> ST uriUnSegments = ("/" <>) . ST.intercalate "/" (-/) :: HasCallStack => ST -> ST -> ST oldpath -/ pathext = uriUnSegments . uriSegments $ oldpath <> "/" <> pathext (=/) :: HasCallStack => URI -> ST -> URI uri =/ pathext = normURI $ uri & pathL %~ (<> "/" <> cs pathext) normURI :: URI -> URI normURI = unsafeParseURI . cs . normalizeURIRef' URINormalizationOptions { unoDowncaseScheme = True, unoDowncaseHost = True, unoDropDefPort = False, unoSlashEmptyPath = True, unoDropExtraSlashes = True, unoSortParameters = True, unoRemoveDotSegments = True, unoDefaultPorts = mempty }
bd4356ed3e51f62a6d6b1d69f86e4efa2426485581c4e96c34f8024ebcaebe2c
tomahawkins/atom
Tokens.hs
module Parser.Tokens ( Token (..) , TokenName (..) , tokenString ) where import Common tokenString :: Token -> String tokenString (Token _ s _) = s data Token = Token TokenName String Location deriving (Show, Eq) instance Locate Token where locate (Token _ _ l) = l data TokenName = InfixL9 | InfixR9 | Infix9 | InfixL8 | InfixR8 | Infix8 | InfixL7 | InfixR7 | Infix7 | InfixL6 | InfixR6 | Infix6 | InfixL5 | InfixR5 | Infix5 | InfixL4 | InfixR4 | Infix4 | InfixL3 | InfixR3 | Infix3 | InfixL2 | InfixR2 | Infix2 | InfixL1 | InfixR1 | Infix1 | InfixL0 | InfixR0 | Infix0 | ParenL | ParenR | Equal | ColonColon | Semi | Tic | Pipe | Backslash | Underscore | At | Unit | KW_case | KW_class | KW_datatype | KW_do | KW_else | KW_if | KW_instance | KW_intrinsic | KW_let | KW_of | KW_then | KW_where | IdUpper | IdLower | Unknown deriving (Show, Eq)
null
https://raw.githubusercontent.com/tomahawkins/atom/e552e18859c6d249af4b293e9d2197878c0fd4fd/src/Parser/Tokens.hs
haskell
module Parser.Tokens ( Token (..) , TokenName (..) , tokenString ) where import Common tokenString :: Token -> String tokenString (Token _ s _) = s data Token = Token TokenName String Location deriving (Show, Eq) instance Locate Token where locate (Token _ _ l) = l data TokenName = InfixL9 | InfixR9 | Infix9 | InfixL8 | InfixR8 | Infix8 | InfixL7 | InfixR7 | Infix7 | InfixL6 | InfixR6 | Infix6 | InfixL5 | InfixR5 | Infix5 | InfixL4 | InfixR4 | Infix4 | InfixL3 | InfixR3 | Infix3 | InfixL2 | InfixR2 | Infix2 | InfixL1 | InfixR1 | Infix1 | InfixL0 | InfixR0 | Infix0 | ParenL | ParenR | Equal | ColonColon | Semi | Tic | Pipe | Backslash | Underscore | At | Unit | KW_case | KW_class | KW_datatype | KW_do | KW_else | KW_if | KW_instance | KW_intrinsic | KW_let | KW_of | KW_then | KW_where | IdUpper | IdLower | Unknown deriving (Show, Eq)
c7a812d10a181cbda96232b9a3a90b301a9edd7d962ea5d0c324f53fbdfc6e45
mitchellwrosen/planet-mitchell
Semigroupoid.hs
module Alg.Semigroupoid * Semigroupoid(..) -- ** Newtypes , Semi(..) , Dual(..) ) where import Data.Semigroupoid (Semi(Semi, getSemi), Semigroupoid(o)) import Data.Semigroupoid.Dual (Dual(Dual, getDual))
null
https://raw.githubusercontent.com/mitchellwrosen/planet-mitchell/18dd83204e70fffcd23fe12dd3a80f70b7fa409b/planet-mitchell/src/Alg/Semigroupoid.hs
haskell
** Newtypes
module Alg.Semigroupoid * Semigroupoid(..) , Semi(..) , Dual(..) ) where import Data.Semigroupoid (Semi(Semi, getSemi), Semigroupoid(o)) import Data.Semigroupoid.Dual (Dual(Dual, getDual))
42d52d270e27db5a7d7f06a3ed5f72e96eedf953a9e6bc1a6c1c63297a48551d
fukamachi/clozure-cl
compile-hemlock.lisp
(in-package "CCL") (defparameter *hemlock-src-dir-pathname* "ccl:cocoa-ide;hemlock;src;") (defparameter *hemlock-binary-dir-pathname* "ccl:cocoa-ide;hemlock;bin;openmcl;") (defparameter *hemlock-binary-file-extension* (pathname-type (compile-file-pathname "foo.lisp"))) (defun hemlock-source-pathname (name) (make-pathname :name name :type "lisp" :defaults *hemlock-src-dir-pathname*)) (defun hemlock-binary-pathname (name) (make-pathname :name name :type *hemlock-binary-file-extension* :defaults *hemlock-binary-dir-pathname*)) (defun compile-and-load-hemlock-file (name &optional force) (let* ((source-pathname (hemlock-source-pathname name)) (binary-pathname (hemlock-binary-pathname name))) (when (or force (not (probe-file binary-pathname)) (> (file-write-date source-pathname) (file-write-date binary-pathname))) (compile-file source-pathname :output-file binary-pathname :verbose t)) (load binary-pathname :verbose t))) (defparameter *hemlock-files* '("package" "hemlock-ext" "decls" ;early declarations of functions and stuff "struct" "charmacs" "key-event" "keysym-defs" "cocoa-hemlock" "rompsite" "macros" "views" "line" "ring" "vars" "interp" "syntax" "htext1" "buffer" "charprops" "htext2" "htext3" "htext4" "files" "search1" "search2" "table" "modeline" "pop-up-stream" "font" "streams" "main" "echo" "echocoms" "command" "indent" ;; moved "comments" "morecoms" "undo" "killcoms" "searchcoms" "isearchcoms" "filecoms" "doccoms" "fill" "text" "lispmode" "listener" "comments" "icom" "defsyn" "edit-defs" "register" "completion" "symbol-completion" "bindings" )) (defun compile-hemlock (&optional force) (with-compilation-unit () (dolist (name *hemlock-files*) (compile-and-load-hemlock-file name force))) (fasl-concatenate "ccl:cocoa-ide;hemlock" (mapcar #'hemlock-binary-pathname *hemlock-files*) :if-exists :supersede) (provide "HEMLOCK") ) (provide "COMPILE-HEMLOCK")
null
https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/cocoa-ide/compile-hemlock.lisp
lisp
early declarations of functions and stuff moved "comments"
(in-package "CCL") (defparameter *hemlock-src-dir-pathname* "ccl:cocoa-ide;hemlock;src;") (defparameter *hemlock-binary-dir-pathname* "ccl:cocoa-ide;hemlock;bin;openmcl;") (defparameter *hemlock-binary-file-extension* (pathname-type (compile-file-pathname "foo.lisp"))) (defun hemlock-source-pathname (name) (make-pathname :name name :type "lisp" :defaults *hemlock-src-dir-pathname*)) (defun hemlock-binary-pathname (name) (make-pathname :name name :type *hemlock-binary-file-extension* :defaults *hemlock-binary-dir-pathname*)) (defun compile-and-load-hemlock-file (name &optional force) (let* ((source-pathname (hemlock-source-pathname name)) (binary-pathname (hemlock-binary-pathname name))) (when (or force (not (probe-file binary-pathname)) (> (file-write-date source-pathname) (file-write-date binary-pathname))) (compile-file source-pathname :output-file binary-pathname :verbose t)) (load binary-pathname :verbose t))) (defparameter *hemlock-files* '("package" "hemlock-ext" "struct" "charmacs" "key-event" "keysym-defs" "cocoa-hemlock" "rompsite" "macros" "views" "line" "ring" "vars" "interp" "syntax" "htext1" "buffer" "charprops" "htext2" "htext3" "htext4" "files" "search1" "search2" "table" "modeline" "pop-up-stream" "font" "streams" "main" "echo" "echocoms" "command" "indent" "morecoms" "undo" "killcoms" "searchcoms" "isearchcoms" "filecoms" "doccoms" "fill" "text" "lispmode" "listener" "comments" "icom" "defsyn" "edit-defs" "register" "completion" "symbol-completion" "bindings" )) (defun compile-hemlock (&optional force) (with-compilation-unit () (dolist (name *hemlock-files*) (compile-and-load-hemlock-file name force))) (fasl-concatenate "ccl:cocoa-ide;hemlock" (mapcar #'hemlock-binary-pathname *hemlock-files*) :if-exists :supersede) (provide "HEMLOCK") ) (provide "COMPILE-HEMLOCK")
3cf36749518e367ae966e146b45fa252c2036a2a4c4edb8b16f12f3c7b650878
2600hz/kazoo
knm_rename_carrier.erl
%%%----------------------------------------------------------------------------- ( C ) 2010 - 2020 , 2600Hz %%% @doc Handle renaming module_name for admins @author 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 /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(knm_rename_carrier). -behaviour(knm_gen_provider). -export([save/1]). -export([delete/1]). -include("knm.hrl"). -define(KEY, ?FEATURE_RENAME_CARRIER). %%------------------------------------------------------------------------------ %% @doc This function is called each time a number is saved, and will %% add the prepend route (for in service numbers only) %% @end %%------------------------------------------------------------------------------ -spec save(knm_phone_number:record()) -> knm_phone_number:record(). save(PN) -> Doc = knm_phone_number:doc(PN), Value = kz_json:get_ne_value(?KEY, Doc), Carrier = maybe_prefix_carrier(Value), case is_valid(Carrier, PN) of 'false' -> Msg = <<"'", Value/binary, "' is not known by the system">>, knm_errors:invalid(PN, Msg); 'true' -> NewDoc = kz_json:delete_key(?KEY, Doc), Updates = [{fun knm_phone_number:set_module_name/2, Carrier} ,{fun knm_phone_number:reset_doc/2, NewDoc} ], {'ok', NewPN} = knm_phone_number:setters(PN, Updates), NewPN end. %%------------------------------------------------------------------------------ %% @doc This function is called each time a number is deleted, and will %% remove the prepend route %% @end %%------------------------------------------------------------------------------ -spec delete(knm_phone_number:record()) -> knm_phone_number:record(). delete(PN) -> PN. -spec maybe_prefix_carrier(kz_term:ne_binary()) -> kz_term:ne_binary(). maybe_prefix_carrier(<<"knm_", Carrier/binary>>) -> maybe_prefix_carrier(Carrier); maybe_prefix_carrier(<<"wnm_", Carrier/binary>>) -> maybe_prefix_carrier(Carrier); maybe_prefix_carrier(Carrier=?NE_BINARY) -> <<"knm_", Carrier/binary>>. -spec is_valid(kz_term:ne_binary(), knm_phone_number:record()) -> boolean(). is_valid(CarrierModule, PN) -> case knm_phone_number:is_admin(PN) of 'false' -> knm_errors:unauthorized(); 'true' -> case kz_module:ensure_loaded(CarrierModule) of 'false' -> 'false'; _M -> lager:debug("allowing setting carrier to ~p", [CarrierModule]), 'true' end end.
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_numbers/src/providers/knm_rename_carrier.erl
erlang
----------------------------------------------------------------------------- @doc Handle renaming module_name for admins @end ----------------------------------------------------------------------------- ------------------------------------------------------------------------------ @doc This function is called each time a number is saved, and will add the prepend route (for in service numbers only) @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc This function is called each time a number is deleted, and will remove the prepend route @end ------------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz @author 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 /. -module(knm_rename_carrier). -behaviour(knm_gen_provider). -export([save/1]). -export([delete/1]). -include("knm.hrl"). -define(KEY, ?FEATURE_RENAME_CARRIER). -spec save(knm_phone_number:record()) -> knm_phone_number:record(). save(PN) -> Doc = knm_phone_number:doc(PN), Value = kz_json:get_ne_value(?KEY, Doc), Carrier = maybe_prefix_carrier(Value), case is_valid(Carrier, PN) of 'false' -> Msg = <<"'", Value/binary, "' is not known by the system">>, knm_errors:invalid(PN, Msg); 'true' -> NewDoc = kz_json:delete_key(?KEY, Doc), Updates = [{fun knm_phone_number:set_module_name/2, Carrier} ,{fun knm_phone_number:reset_doc/2, NewDoc} ], {'ok', NewPN} = knm_phone_number:setters(PN, Updates), NewPN end. -spec delete(knm_phone_number:record()) -> knm_phone_number:record(). delete(PN) -> PN. -spec maybe_prefix_carrier(kz_term:ne_binary()) -> kz_term:ne_binary(). maybe_prefix_carrier(<<"knm_", Carrier/binary>>) -> maybe_prefix_carrier(Carrier); maybe_prefix_carrier(<<"wnm_", Carrier/binary>>) -> maybe_prefix_carrier(Carrier); maybe_prefix_carrier(Carrier=?NE_BINARY) -> <<"knm_", Carrier/binary>>. -spec is_valid(kz_term:ne_binary(), knm_phone_number:record()) -> boolean(). is_valid(CarrierModule, PN) -> case knm_phone_number:is_admin(PN) of 'false' -> knm_errors:unauthorized(); 'true' -> case kz_module:ensure_loaded(CarrierModule) of 'false' -> 'false'; _M -> lager:debug("allowing setting carrier to ~p", [CarrierModule]), 'true' end end.
efed132c83eb7311d447210249ca853ff857284560ffd2d38f15b3e688cfc432
ryanpbrewster/haskell
SumFullSet.hs
-- SumFullSet.hs import qualified System.Environment as Env import qualified Data.ByteString.Char8 as BS import Data.Maybe (fromJust) main = do args <- Env.getArgs inps <- fmap concat (mapM parseInput args) mapM_ putStrLn [ if isClosed inp then "closed" else "not closed" | inp <- inps ] parseInput :: String -> IO [[Int]] parseInput fn = do lns <- fmap BS.lines (BS.readFile fn) return [ map (fst . fromJust . BS.readInt) (BS.words ln) | ln <- lns ] isClosed :: [Int] -> Bool isClosed xs = all (`elem` xs) (allPairSums xs) allPairSums [] = [] allPairSums (x:xs) = map (+x) xs ++ allPairSums xs
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/TopCoder/SumFullSet/SumFullSet.hs
haskell
SumFullSet.hs
import qualified System.Environment as Env import qualified Data.ByteString.Char8 as BS import Data.Maybe (fromJust) main = do args <- Env.getArgs inps <- fmap concat (mapM parseInput args) mapM_ putStrLn [ if isClosed inp then "closed" else "not closed" | inp <- inps ] parseInput :: String -> IO [[Int]] parseInput fn = do lns <- fmap BS.lines (BS.readFile fn) return [ map (fst . fromJust . BS.readInt) (BS.words ln) | ln <- lns ] isClosed :: [Int] -> Bool isClosed xs = all (`elem` xs) (allPairSums xs) allPairSums [] = [] allPairSums (x:xs) = map (+x) xs ++ allPairSums xs
6b01de37ffa212641b23155aee9b03610c39f76f5729b8c61ae44e27ae02ec4c
r-willis/biten
protocol.erl
%%% -------------------------------------------------------------------------- @author < @doc Protocol related bits - message construction and parsing %%% @end %%% -------------------------------------------------------------------------- -module(protocol). -compile([export_all]). -include("include/records.hrl"). -define(MAIN_MAGIC, <<16#F9BEB4D9:32/big>>). -define(MAGIC, ?MAIN_MAGIC). -define(PROTOCOL_VERSION, <<16#62EA0000:32/big>>). hexstr_to_binary(S) -> T = string:tokens(S, " "), list_to_binary([list_to_integer(X, 16) || X <- T]). binary_to_hexstr(B, D) -> util:bin_to_hex(B, D). binary_to_hexstr(B) -> binary_to_hexstr(B, " "). make_message(Magic, Command, Payload) -> Len = byte_size(Payload), CRC = b_crypto:crc(Payload), CommandBin = case Command of version -> atom_to_cmd(version); getaddr -> atom_to_cmd(getaddr); getdata -> atom_to_cmd(getdata); getheaders -> atom_to_cmd(getheaders); headers -> atom_to_cmd(headers); verack -> atom_to_cmd(verack); addr -> atom_to_cmd(addr); ping -> atom_to_cmd(ping); pong -> atom_to_cmd(pong); inv -> atom_to_cmd(inv); tx -> atom_to_cmd(tx) end, <<Magic/binary, CommandBin/binary, Len:32/little, CRC/binary, Payload/binary>>. atom_to_cmd(A) -> S = list_to_binary(atom_to_list(A)), L = byte_size(S), <<S/binary, 0:((12-L)*8)>>. get_message(<<Hdr:16/binary, Len:32/little, CRC:4/binary, Payload:Len/binary, Rest/binary>>) -> case b_crypto:crc(Payload) of CRC -> {ok, <<Hdr/binary, Len:32/little, CRC/binary>>, Payload, Rest}; _ -> {error, crc} end; get_message(_B) -> {error, incomplete}. %get_message(B) -> util : ) , 1 = 2 . cmd_to_list(B) -> L = binary_to_list(B), string:strip(L, right, 0). parse_varint(<<16#fd, X:16/little, Rest/binary>>) -> {X, Rest}; parse_varint(<<16#fe, X:32/little, Rest/binary>>) -> {X, Rest}; parse_varint(<<16#ff, X:64/little, Rest/binary>>) -> {X, Rest}; parse_varint(<<X:8, Rest/binary>>) -> {X, Rest}. varint(X) when X < 16#fd -> <<X>>; varint(X) when X =< 16#ffff -> <<16#fd, X:16/little>>; varint(X) when X =< 16#ffffffff -> <<16#fe, X:32/little>>; varint(X) when X =< 16#ffffffffffffffff -> <<16#ff, X:64/little>>. format_pk_script(<<118, 169, 20, H160:20/bytes, 136, 172>>) -> io_lib:format("OP_DUP OP_HASH160 20 ~s OP_EQUALVERIFY OP_CHECKSIG", [util:base58_enc(0, H160)]); format_pk_script(<<B/bytes>>) -> io_lib:format("~s", [binary_to_hexstr(B, "")]). format_tx_in({H, I, Scr, Seq}) -> [io_lib:format(" tx_in~n hash ~s~n index ~b~n", [binary_to_hexstr(H, ""), I]), io_lib:format(" script ~s~n seq ~b~n", [binary_to_hexstr(Scr), Seq])]. format_tx_out({Val, PK_script}) -> [io_lib:format(" tx_out~n value ~b~n pk_script ~s~n", [Val, format_pk_script(PK_script)])]. format_tx(TX) -> [ io_lib:format("Transaction version ~b~n tx_in_count = ~p~n", [ TX#tx.ver, TX#tx.tx_in_count]), [ format_tx_in(TX_in) || TX_in <- TX#tx.tx_in ], io_lib:format(" tx_out_count = ~b~n", [TX#tx.tx_out_count]), [ format_tx_out(TX_out) || TX_out <- TX#tx.tx_out ], io_lib:format(" lock time ~b~n", [TX#tx.lock_time]), "" ]. parse_tx_in(Rest, R, 0) -> {lists:reverse(R), Rest}; parse_tx_in(<<TX_ref:32/bytes, Index:32/little, P/bytes>>, R, N) when N > 0 -> {L, R1} = parse_varint(P), <<Script:L/bytes, Seq:32/little, Rest/bytes>> = R1, parse_tx_in(Rest, [{TX_ref, Index, Script, Seq}|R], N - 1). parse_tx_out(Rest, R, 0) -> {lists:reverse(R), Rest}; parse_tx_out(<<Value:64/little, P/bytes>>, R, N) when N > 0 -> {L, R1} = parse_varint(P), <<PK_script:L/bytes, Rest/bytes>> = R1, parse_tx_out(Rest, [{Value, PK_script}|R], N - 1). parse_tx(<<Ver:32/little, B/bytes>>) -> {TX_in_count, R1} = parse_varint(B), {TX_in, R2} = parse_tx_in(R1, [], TX_in_count), {TX_out_count, R3} = parse_varint(R2), {TX_out, R4} = parse_tx_out(R3, [], TX_out_count), <<Lock_time:32/little>> = R4, #tx{ver = Ver, tx_in_count = TX_in_count, tx_in = TX_in, tx_out_count = TX_out_count, tx_out = TX_out, lock_time = Lock_time}. parse_headers(B) -> {N, R} = parse_varint(B), {ok, N, [H || <<H:80/bytes, _C:1/bytes>> <= R ]}. parse_block_header(<<Ver:32/little, PrevBlock:32/bytes, MerkleRoot:32/bytes, Time:32/little, Diff:4/bytes, Nonce:32/little>>) -> {Ver, PrevBlock, MerkleRoot, Time, Diff, Nonce}. prev_block_header(<<_:4/bytes, PrevBlock:32/bytes, _:44/bytes>>) -> PrevBlock. parse_inv(B) -> {N, R} = parse_varint(B), {ok, N, [{T,H} || <<T:32/little, H:32/bytes>> <= R ]}. parse_getdata(B) -> {N, R} = parse_varint(B), {ok, N, [{T,H} || <<T:32/little, H:32/bytes>> <= R ]}. parse_addr(B) -> {N, R} = parse_varint(B), {ok, N, parse_addr(R, [])}. parse_addr(<<_Time:32/little, _Services:8/binary, IPv6:16/binary, Port:16/big, Rest/binary>>, L) -> <<_:12/binary, IPv4_A:8, IPv4_B:8, IPv4_C:8, IPv4_D:8>> = IPv6, parse_addr(Rest, [{{IPv4_A, IPv4_B, IPv4_C, IPv4_D}, Port}|L]); parse_addr(<<>>, L) -> L. parse_header(<<Magic:4/binary, Command:12/binary, Len:32/little, CRC:4/binary>>) -> Cmd = cmd_to_list(Command), CommandAtom = case lists:member(Cmd, [ "version", "verack", "addr", "ping", "pong", "inv", "alert", "getdata", "getblocks", "getheaders", "headers", "notfound", "getaddr", "tx" ]) of true -> list_to_atom(Cmd); false -> unknown end, {ok, Magic, CommandAtom, Len, CRC}. parse_message(<<Magic:4/binary, Command:12/binary, Len:32/little, CRC:4/binary, Payload:Len/binary, Rest/binary>>) -> case b_crypto:crc(Payload) of CRC -> {ok, Magic, Command, CRC, Payload, Rest}; _ -> {error, crc, Rest} end; parse_message(Rest) -> {error, parse, Rest}. getheaders_msg(L, StopHash) -> N = varint(length(L)), HL = << <<Hash/bytes>> || Hash <- L >>, make_message(?MAGIC, getheaders, <<?PROTOCOL_VERSION/bytes, N/bytes, HL/bytes, StopHash/bytes>>). getdata_msg(L) -> N = varint(length(L)), Body = <<<<Type:32/little, Hash/bytes>> || {Hash, Type} <- L>>, make_message(?MAGIC, getdata, <<N/bytes, Body/bytes>>). inv_msg(L) -> N = varint(length(L)), Body = <<<<Type:32/little, Hash/bytes>> || {Type, Hash} <- L>>, make_message(?MAGIC, inv, <<N/bytes, Body/bytes>>). getaddr_msg() -> make_message(?MAGIC, getaddr, <<>>). tx_msg(B) -> make_message(?MAGIC, tx, B). ping_msg() -> PayloadStr = [ "00 00 00 00 00 00 00 00" ], Payload = msgstr_to_binary(PayloadStr), make_message(?MAGIC, ping, Payload). pong_msg(Payload) -> make_message(?MAGIC, pong, Payload). addr_msg() -> {MegaS, S, _MicroS} = now(), T = MegaS*1000000 + S, make_message(?MAGIC, addr, <<1, T:32/little, 1, 0:(7*8), %service IPv6 addr ( first part ) IPv4 addr ( or rest of IPv6 addr ) 8333:16/big %port >>). verack_msg() -> make_message(?MAGIC, verack, <<>>). version_msg() -> PayloadStr1 = [ "62 EA 00 00", "01 00 00 00 00 00 00 00", "11 B2 D0 50 00 00 00 00", "01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF 00 00 00 00 00 00", "01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF 00 00 00 00 00 00"], PayloadStr2 = [ "0D 2f 62 69 74 65 6e 3a 30 2e 30 2e 31 2f", % /biten:0.0.1/ "C0 3E 03 00" ], Payload = list_to_binary([ msgstr_to_binary(PayloadStr1), crypto:rand_bytes(8), msgstr_to_binary(PayloadStr2) ]), make_message(?MAGIC, version, Payload). msgstr_to_binary(M) -> list_to_binary([hexstr_to_binary(X) || X <- M]).
null
https://raw.githubusercontent.com/r-willis/biten/75b13ea296992f8fa749646b9d7c15c5ef23d94d/apps/biten/src/protocol.erl
erlang
-------------------------------------------------------------------------- @end -------------------------------------------------------------------------- get_message(B) -> service port /biten:0.0.1/
@author < @doc Protocol related bits - message construction and parsing -module(protocol). -compile([export_all]). -include("include/records.hrl"). -define(MAIN_MAGIC, <<16#F9BEB4D9:32/big>>). -define(MAGIC, ?MAIN_MAGIC). -define(PROTOCOL_VERSION, <<16#62EA0000:32/big>>). hexstr_to_binary(S) -> T = string:tokens(S, " "), list_to_binary([list_to_integer(X, 16) || X <- T]). binary_to_hexstr(B, D) -> util:bin_to_hex(B, D). binary_to_hexstr(B) -> binary_to_hexstr(B, " "). make_message(Magic, Command, Payload) -> Len = byte_size(Payload), CRC = b_crypto:crc(Payload), CommandBin = case Command of version -> atom_to_cmd(version); getaddr -> atom_to_cmd(getaddr); getdata -> atom_to_cmd(getdata); getheaders -> atom_to_cmd(getheaders); headers -> atom_to_cmd(headers); verack -> atom_to_cmd(verack); addr -> atom_to_cmd(addr); ping -> atom_to_cmd(ping); pong -> atom_to_cmd(pong); inv -> atom_to_cmd(inv); tx -> atom_to_cmd(tx) end, <<Magic/binary, CommandBin/binary, Len:32/little, CRC/binary, Payload/binary>>. atom_to_cmd(A) -> S = list_to_binary(atom_to_list(A)), L = byte_size(S), <<S/binary, 0:((12-L)*8)>>. get_message(<<Hdr:16/binary, Len:32/little, CRC:4/binary, Payload:Len/binary, Rest/binary>>) -> case b_crypto:crc(Payload) of CRC -> {ok, <<Hdr/binary, Len:32/little, CRC/binary>>, Payload, Rest}; _ -> {error, crc} end; get_message(_B) -> {error, incomplete}. util : ) , 1 = 2 . cmd_to_list(B) -> L = binary_to_list(B), string:strip(L, right, 0). parse_varint(<<16#fd, X:16/little, Rest/binary>>) -> {X, Rest}; parse_varint(<<16#fe, X:32/little, Rest/binary>>) -> {X, Rest}; parse_varint(<<16#ff, X:64/little, Rest/binary>>) -> {X, Rest}; parse_varint(<<X:8, Rest/binary>>) -> {X, Rest}. varint(X) when X < 16#fd -> <<X>>; varint(X) when X =< 16#ffff -> <<16#fd, X:16/little>>; varint(X) when X =< 16#ffffffff -> <<16#fe, X:32/little>>; varint(X) when X =< 16#ffffffffffffffff -> <<16#ff, X:64/little>>. format_pk_script(<<118, 169, 20, H160:20/bytes, 136, 172>>) -> io_lib:format("OP_DUP OP_HASH160 20 ~s OP_EQUALVERIFY OP_CHECKSIG", [util:base58_enc(0, H160)]); format_pk_script(<<B/bytes>>) -> io_lib:format("~s", [binary_to_hexstr(B, "")]). format_tx_in({H, I, Scr, Seq}) -> [io_lib:format(" tx_in~n hash ~s~n index ~b~n", [binary_to_hexstr(H, ""), I]), io_lib:format(" script ~s~n seq ~b~n", [binary_to_hexstr(Scr), Seq])]. format_tx_out({Val, PK_script}) -> [io_lib:format(" tx_out~n value ~b~n pk_script ~s~n", [Val, format_pk_script(PK_script)])]. format_tx(TX) -> [ io_lib:format("Transaction version ~b~n tx_in_count = ~p~n", [ TX#tx.ver, TX#tx.tx_in_count]), [ format_tx_in(TX_in) || TX_in <- TX#tx.tx_in ], io_lib:format(" tx_out_count = ~b~n", [TX#tx.tx_out_count]), [ format_tx_out(TX_out) || TX_out <- TX#tx.tx_out ], io_lib:format(" lock time ~b~n", [TX#tx.lock_time]), "" ]. parse_tx_in(Rest, R, 0) -> {lists:reverse(R), Rest}; parse_tx_in(<<TX_ref:32/bytes, Index:32/little, P/bytes>>, R, N) when N > 0 -> {L, R1} = parse_varint(P), <<Script:L/bytes, Seq:32/little, Rest/bytes>> = R1, parse_tx_in(Rest, [{TX_ref, Index, Script, Seq}|R], N - 1). parse_tx_out(Rest, R, 0) -> {lists:reverse(R), Rest}; parse_tx_out(<<Value:64/little, P/bytes>>, R, N) when N > 0 -> {L, R1} = parse_varint(P), <<PK_script:L/bytes, Rest/bytes>> = R1, parse_tx_out(Rest, [{Value, PK_script}|R], N - 1). parse_tx(<<Ver:32/little, B/bytes>>) -> {TX_in_count, R1} = parse_varint(B), {TX_in, R2} = parse_tx_in(R1, [], TX_in_count), {TX_out_count, R3} = parse_varint(R2), {TX_out, R4} = parse_tx_out(R3, [], TX_out_count), <<Lock_time:32/little>> = R4, #tx{ver = Ver, tx_in_count = TX_in_count, tx_in = TX_in, tx_out_count = TX_out_count, tx_out = TX_out, lock_time = Lock_time}. parse_headers(B) -> {N, R} = parse_varint(B), {ok, N, [H || <<H:80/bytes, _C:1/bytes>> <= R ]}. parse_block_header(<<Ver:32/little, PrevBlock:32/bytes, MerkleRoot:32/bytes, Time:32/little, Diff:4/bytes, Nonce:32/little>>) -> {Ver, PrevBlock, MerkleRoot, Time, Diff, Nonce}. prev_block_header(<<_:4/bytes, PrevBlock:32/bytes, _:44/bytes>>) -> PrevBlock. parse_inv(B) -> {N, R} = parse_varint(B), {ok, N, [{T,H} || <<T:32/little, H:32/bytes>> <= R ]}. parse_getdata(B) -> {N, R} = parse_varint(B), {ok, N, [{T,H} || <<T:32/little, H:32/bytes>> <= R ]}. parse_addr(B) -> {N, R} = parse_varint(B), {ok, N, parse_addr(R, [])}. parse_addr(<<_Time:32/little, _Services:8/binary, IPv6:16/binary, Port:16/big, Rest/binary>>, L) -> <<_:12/binary, IPv4_A:8, IPv4_B:8, IPv4_C:8, IPv4_D:8>> = IPv6, parse_addr(Rest, [{{IPv4_A, IPv4_B, IPv4_C, IPv4_D}, Port}|L]); parse_addr(<<>>, L) -> L. parse_header(<<Magic:4/binary, Command:12/binary, Len:32/little, CRC:4/binary>>) -> Cmd = cmd_to_list(Command), CommandAtom = case lists:member(Cmd, [ "version", "verack", "addr", "ping", "pong", "inv", "alert", "getdata", "getblocks", "getheaders", "headers", "notfound", "getaddr", "tx" ]) of true -> list_to_atom(Cmd); false -> unknown end, {ok, Magic, CommandAtom, Len, CRC}. parse_message(<<Magic:4/binary, Command:12/binary, Len:32/little, CRC:4/binary, Payload:Len/binary, Rest/binary>>) -> case b_crypto:crc(Payload) of CRC -> {ok, Magic, Command, CRC, Payload, Rest}; _ -> {error, crc, Rest} end; parse_message(Rest) -> {error, parse, Rest}. getheaders_msg(L, StopHash) -> N = varint(length(L)), HL = << <<Hash/bytes>> || Hash <- L >>, make_message(?MAGIC, getheaders, <<?PROTOCOL_VERSION/bytes, N/bytes, HL/bytes, StopHash/bytes>>). getdata_msg(L) -> N = varint(length(L)), Body = <<<<Type:32/little, Hash/bytes>> || {Hash, Type} <- L>>, make_message(?MAGIC, getdata, <<N/bytes, Body/bytes>>). inv_msg(L) -> N = varint(length(L)), Body = <<<<Type:32/little, Hash/bytes>> || {Type, Hash} <- L>>, make_message(?MAGIC, inv, <<N/bytes, Body/bytes>>). getaddr_msg() -> make_message(?MAGIC, getaddr, <<>>). tx_msg(B) -> make_message(?MAGIC, tx, B). ping_msg() -> PayloadStr = [ "00 00 00 00 00 00 00 00" ], Payload = msgstr_to_binary(PayloadStr), make_message(?MAGIC, ping, Payload). pong_msg(Payload) -> make_message(?MAGIC, pong, Payload). addr_msg() -> {MegaS, S, _MicroS} = now(), T = MegaS*1000000 + S, make_message(?MAGIC, addr, <<1, T:32/little, IPv6 addr ( first part ) IPv4 addr ( or rest of IPv6 addr ) >>). verack_msg() -> make_message(?MAGIC, verack, <<>>). version_msg() -> PayloadStr1 = [ "62 EA 00 00", "01 00 00 00 00 00 00 00", "11 B2 D0 50 00 00 00 00", "01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF 00 00 00 00 00 00", "01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF 00 00 00 00 00 00"], PayloadStr2 = [ "C0 3E 03 00" ], Payload = list_to_binary([ msgstr_to_binary(PayloadStr1), crypto:rand_bytes(8), msgstr_to_binary(PayloadStr2) ]), make_message(?MAGIC, version, Payload). msgstr_to_binary(M) -> list_to_binary([hexstr_to_binary(X) || X <- M]).
9f3b8239c624fff876e9e44e4beb7913fec326fc10ea27f184df894b3a868f00
JoeKennedy/fantasy
Application.hs
# OPTIONS_GHC -fno - warn - orphans # module Application ( getApplicationDev , appMain , develMain , makeFoundation -- * for DevelMain , getApplicationRepl , shutdownApp -- * for GHCI , handler , db ) where import Control.Monad.Logger (liftLoc, runLoggingT) import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr, pgPoolSize, runSqlPool) import Import import Language.Haskell.TH.Syntax (qLocation) import LoadEnv (loadEnv) import Network.Mail.Mime.SES import Network.Wai.Handler.Warp (Settings, defaultSettings, defaultShouldDisplayException, runSettings, setHost, setOnException, setPort, getPort) import Network.Wai.Middleware.RequestLogger (Destination (Logger), IPAddrSource (..), OutputFormat (..), destination, mkRequestLogger, outputFormat) import System.Cron import System.Environment (getEnv) import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet, toLogStr) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as S8 import qualified Data.Proxy as P import qualified Web.ServerSession.Core as SS import qualified Web.ServerSession.Backend.Persistent as SS -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Common import Handler.Admin.Blurb import Handler.Admin.Character import Handler.Admin.Common import Handler.Admin.Episode import Handler.Admin.Event import Handler.Admin.House import Handler.Admin.Score import Handler.Admin.Series import Handler.Admin.Species import Handler.Character import Handler.Episode import Handler.Home import Handler.House import Handler.League import Handler.League.ConfirmSettings import Handler.League.DraftSettings import Handler.League.GeneralSettings import Handler.League.Player import Handler.League.Scoring import Handler.League.Season import Handler.League.Team import Handler.League.Transaction import Handler.Series import Handler.Species import Handler.League.Week This line actually creates our YesodDispatch instance . It is the second half of the call to mkYesodData which occurs in Foundation.hs . Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- Create migration function using both our entities and the -- serversession-persistent-backend ones. mkMigrate "migrateAll" (SS.serverSessionDefs (P.Proxy :: P.Proxy SS.SessionMap) ++ entityDefs) -- | This function allocates resources (such as a database connection pool), -- performs initialization and returns a foundation datatype value. This is also -- the place to put your migrate statements to have automatic database migrations handled by Yesod . makeFoundation :: AppSettings -> IO App makeFoundation appSettings = do loadEnv -- Some basic initializations: HTTP connection manager, logger, and static -- subsite. appHttpManager <- newManager appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger appStatic <- (if appMutableStatic appSettings then staticDevel else static) (appStaticDir appSettings) (appAcmeChallenge, appLetsEncrypt) <- getLetsEncrypt appFacebookOAuth2Keys <- getOAuth2Keys "FACEBOOK_OAUTH2_APP_ID" "FACEBOOK_OAUTH2_APP_SECRET" appGoogleOAuth2Keys <- getOAuth2Keys "GOOGLE_OAUTH2_CLIENT_ID" "GOOGLE_OAUTH2_CLIENT_SECRET" (appAmazonAccessKey, appAmazonSecretKey) <- getAmazonKeys let appSesCreds = \email -> SES { sesFrom = "" , sesTo = [encodeUtf8 email] , sesAccessKey = S8.pack appAmazonAccessKey , sesSecretKey = S8.pack appAmazonSecretKey , sesRegion = usEast1 } -- We need a log function to create a connection pool. We need a connection -- pool to create our foundation. And we need our foundation to get a -- logging function. To get out of this loop, we initially create a -- temporary foundation without a real connection pool, get a log function -- from there, and then create the real foundation. let mkFoundation appConnPool = App {..} -- The App {..} syntax is an example of record wild cards. For more -- information, see: -- -12-04-record-wildcards.html tempFoundation = mkFoundation $ error "connPool forced in tempFoundation" logFunc = messageLoggerSource tempFoundation appLogger -- Create the database connection pool TODO make the DB connect to DATABASE_URL if not in development let connStr = catMaybes [ Just (pgConnStr $ appDatabaseConf appSettings) , toPgConnStrParamMaybe "sslmode" (appSSLMode appSettings) , toPgConnStrParamMaybe "sslrootcert" (appSSLRootCert appSettings) ] pool <- flip runLoggingT logFunc $ createPostgresqlPool (BS.intercalate " " connStr) (pgPoolSize $ appDatabaseConf appSettings) -- Perform database migration using our application's logging settings. runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc let foundation = mkFoundation pool threadIds <- execSchedule $ do 9 am UTC daily 1 am UTC Monday 2 am UTC Monday print threadIds -- Return the foundation return foundation where getOAuth2Keys :: String -> String -> IO OAuth2Keys getOAuth2Keys clientIdEnvVar clientSecretEnvVar = OAuth2Keys <$> fmap pack (getEnv clientIdEnvVar) <*> fmap pack (getEnv clientSecretEnvVar) getAmazonKeys :: IO (String, String) getAmazonKeys = do accessKey <- getEnv ("AWS_ACCESS_KEY") secretKey <- getEnv ("AWS_SECRET_KEY") return (accessKey, secretKey) getLetsEncrypt :: IO (Text, Text) getLetsEncrypt = do acmeChallenge <- getEnv "LETS_ENCRYPT_ACME_CHALLENGE" letsEncrypt <- getEnv "LETS_ENCRYPT_SECRET" return (pack acmeChallenge, pack letsEncrypt) toPgConnStrParamMaybe :: Text -> Maybe Text -> Maybe ByteString toPgConnStrParamMaybe _ Nothing = Nothing toPgConnStrParamMaybe name (Just value) = Just $ encodeUtf8 $ intercalate "=" [name, value] | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and -- applying some additional middlewares. makeApplication :: App -> IO Application makeApplication foundation = do logWare <- mkRequestLogger def { outputFormat = if appDetailedRequestLogging $ appSettings foundation then Detailed True else Apache (if appIpFromHeader $ appSettings foundation then FromFallback else FromSocket) , destination = Logger $ loggerSet $ appLogger foundation } -- Create the WAI application and apply middlewares appPlain <- toWaiAppPlain foundation return $ logWare $ defaultMiddlewaresNoLogging appPlain -- | Warp settings for the given foundation value. warpSettings :: App -> Settings warpSettings foundation = setPort (appPort $ appSettings foundation) $ setHost (appHost $ appSettings foundation) $ setOnException (\_req e -> when (defaultShouldDisplayException e) $ messageLoggerSource foundation (appLogger foundation) $(qLocation >>= liftLoc) "yesod" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) defaultSettings | For yesod devel , return the Warp settings and WAI Application . getApplicationDev :: IO (Settings, Application) getApplicationDev = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app <- makeApplication foundation return (wsettings, app) getAppSettings :: IO AppSettings getAppSettings = loadYamlSettings [configSettingsYml] [] useEnv | main function for use by yesod devel develMain :: IO () develMain = develMainHelper getApplicationDev -- | The @main@ function for an executable running this site. appMain :: IO () appMain = do -- Get the settings from all relevant sources settings <- loadYamlSettingsArgs -- fall back to compile-time values, set to [] to require values at runtime [configSettingsYmlValue] -- allow environment variables to override useEnv -- Generate the foundation from the settings foundation <- makeFoundation settings -- Generate a WAI Application from the foundation app <- makeApplication foundation -- Run the application with Warp runSettings (warpSettings foundation) app -------------------------------------------------------------- -- Functions for DevelMain.hs (a way to run the app from GHCi) -------------------------------------------------------------- getApplicationRepl :: IO (Int, App, Application) getApplicationRepl = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app1 <- makeApplication foundation return (getPort wsettings, foundation, app1) shutdownApp :: App -> IO () shutdownApp _ = return () --------------------------------------------- -- Functions for use in development with GHCi --------------------------------------------- -- | Run a handler handler :: Handler a -> IO a handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h -- | Run DB queries db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a db = handler . runDB
null
https://raw.githubusercontent.com/JoeKennedy/fantasy/eb9dc9bf6074be5c5ca951e323c6497676424dda/Application.hs
haskell
* for DevelMain * for GHCI Import all relevant handler modules here. Don't forget to add new modules to your cabal file! comments there for more details. Create migration function using both our entities and the serversession-persistent-backend ones. | This function allocates resources (such as a database connection pool), performs initialization and returns a foundation datatype value. This is also the place to put your migrate statements to have automatic database Some basic initializations: HTTP connection manager, logger, and static subsite. We need a log function to create a connection pool. We need a connection pool to create our foundation. And we need our foundation to get a logging function. To get out of this loop, we initially create a temporary foundation without a real connection pool, get a log function from there, and then create the real foundation. The App {..} syntax is an example of record wild cards. For more information, see: -12-04-record-wildcards.html Create the database connection pool Perform database migration using our application's logging settings. Return the foundation applying some additional middlewares. Create the WAI application and apply middlewares | Warp settings for the given foundation value. | The @main@ function for an executable running this site. Get the settings from all relevant sources fall back to compile-time values, set to [] to require values at runtime allow environment variables to override Generate the foundation from the settings Generate a WAI Application from the foundation Run the application with Warp ------------------------------------------------------------ Functions for DevelMain.hs (a way to run the app from GHCi) ------------------------------------------------------------ ------------------------------------------- Functions for use in development with GHCi ------------------------------------------- | Run a handler | Run DB queries
# OPTIONS_GHC -fno - warn - orphans # module Application ( getApplicationDev , appMain , develMain , makeFoundation , getApplicationRepl , shutdownApp , handler , db ) where import Control.Monad.Logger (liftLoc, runLoggingT) import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr, pgPoolSize, runSqlPool) import Import import Language.Haskell.TH.Syntax (qLocation) import LoadEnv (loadEnv) import Network.Mail.Mime.SES import Network.Wai.Handler.Warp (Settings, defaultSettings, defaultShouldDisplayException, runSettings, setHost, setOnException, setPort, getPort) import Network.Wai.Middleware.RequestLogger (Destination (Logger), IPAddrSource (..), OutputFormat (..), destination, mkRequestLogger, outputFormat) import System.Cron import System.Environment (getEnv) import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet, toLogStr) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as S8 import qualified Data.Proxy as P import qualified Web.ServerSession.Core as SS import qualified Web.ServerSession.Backend.Persistent as SS import Handler.Common import Handler.Admin.Blurb import Handler.Admin.Character import Handler.Admin.Common import Handler.Admin.Episode import Handler.Admin.Event import Handler.Admin.House import Handler.Admin.Score import Handler.Admin.Series import Handler.Admin.Species import Handler.Character import Handler.Episode import Handler.Home import Handler.House import Handler.League import Handler.League.ConfirmSettings import Handler.League.DraftSettings import Handler.League.GeneralSettings import Handler.League.Player import Handler.League.Scoring import Handler.League.Season import Handler.League.Team import Handler.League.Transaction import Handler.Series import Handler.Species import Handler.League.Week This line actually creates our YesodDispatch instance . It is the second half of the call to mkYesodData which occurs in Foundation.hs . Please see the mkYesodDispatch "App" resourcesApp mkMigrate "migrateAll" (SS.serverSessionDefs (P.Proxy :: P.Proxy SS.SessionMap) ++ entityDefs) migrations handled by Yesod . makeFoundation :: AppSettings -> IO App makeFoundation appSettings = do loadEnv appHttpManager <- newManager appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger appStatic <- (if appMutableStatic appSettings then staticDevel else static) (appStaticDir appSettings) (appAcmeChallenge, appLetsEncrypt) <- getLetsEncrypt appFacebookOAuth2Keys <- getOAuth2Keys "FACEBOOK_OAUTH2_APP_ID" "FACEBOOK_OAUTH2_APP_SECRET" appGoogleOAuth2Keys <- getOAuth2Keys "GOOGLE_OAUTH2_CLIENT_ID" "GOOGLE_OAUTH2_CLIENT_SECRET" (appAmazonAccessKey, appAmazonSecretKey) <- getAmazonKeys let appSesCreds = \email -> SES { sesFrom = "" , sesTo = [encodeUtf8 email] , sesAccessKey = S8.pack appAmazonAccessKey , sesSecretKey = S8.pack appAmazonSecretKey , sesRegion = usEast1 } let mkFoundation appConnPool = App {..} tempFoundation = mkFoundation $ error "connPool forced in tempFoundation" logFunc = messageLoggerSource tempFoundation appLogger TODO make the DB connect to DATABASE_URL if not in development let connStr = catMaybes [ Just (pgConnStr $ appDatabaseConf appSettings) , toPgConnStrParamMaybe "sslmode" (appSSLMode appSettings) , toPgConnStrParamMaybe "sslrootcert" (appSSLRootCert appSettings) ] pool <- flip runLoggingT logFunc $ createPostgresqlPool (BS.intercalate " " connStr) (pgPoolSize $ appDatabaseConf appSettings) runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc let foundation = mkFoundation pool threadIds <- execSchedule $ do 9 am UTC daily 1 am UTC Monday 2 am UTC Monday print threadIds return foundation where getOAuth2Keys :: String -> String -> IO OAuth2Keys getOAuth2Keys clientIdEnvVar clientSecretEnvVar = OAuth2Keys <$> fmap pack (getEnv clientIdEnvVar) <*> fmap pack (getEnv clientSecretEnvVar) getAmazonKeys :: IO (String, String) getAmazonKeys = do accessKey <- getEnv ("AWS_ACCESS_KEY") secretKey <- getEnv ("AWS_SECRET_KEY") return (accessKey, secretKey) getLetsEncrypt :: IO (Text, Text) getLetsEncrypt = do acmeChallenge <- getEnv "LETS_ENCRYPT_ACME_CHALLENGE" letsEncrypt <- getEnv "LETS_ENCRYPT_SECRET" return (pack acmeChallenge, pack letsEncrypt) toPgConnStrParamMaybe :: Text -> Maybe Text -> Maybe ByteString toPgConnStrParamMaybe _ Nothing = Nothing toPgConnStrParamMaybe name (Just value) = Just $ encodeUtf8 $ intercalate "=" [name, value] | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and makeApplication :: App -> IO Application makeApplication foundation = do logWare <- mkRequestLogger def { outputFormat = if appDetailedRequestLogging $ appSettings foundation then Detailed True else Apache (if appIpFromHeader $ appSettings foundation then FromFallback else FromSocket) , destination = Logger $ loggerSet $ appLogger foundation } appPlain <- toWaiAppPlain foundation return $ logWare $ defaultMiddlewaresNoLogging appPlain warpSettings :: App -> Settings warpSettings foundation = setPort (appPort $ appSettings foundation) $ setHost (appHost $ appSettings foundation) $ setOnException (\_req e -> when (defaultShouldDisplayException e) $ messageLoggerSource foundation (appLogger foundation) $(qLocation >>= liftLoc) "yesod" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) defaultSettings | For yesod devel , return the Warp settings and WAI Application . getApplicationDev :: IO (Settings, Application) getApplicationDev = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app <- makeApplication foundation return (wsettings, app) getAppSettings :: IO AppSettings getAppSettings = loadYamlSettings [configSettingsYml] [] useEnv | main function for use by yesod devel develMain :: IO () develMain = develMainHelper getApplicationDev appMain :: IO () appMain = do settings <- loadYamlSettingsArgs [configSettingsYmlValue] useEnv foundation <- makeFoundation settings app <- makeApplication foundation runSettings (warpSettings foundation) app getApplicationRepl :: IO (Int, App, Application) getApplicationRepl = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app1 <- makeApplication foundation return (getPort wsettings, foundation, app1) shutdownApp :: App -> IO () shutdownApp _ = return () handler :: Handler a -> IO a handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a db = handler . runDB
a5a56f318d7307e365a21f6cc80394fd56d72e921cf534256567987563046b93
silky/quipper
BooleanFormula.hs
This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the -- file COPYRIGHT for a list of authors, copyright holders, licensing, -- and other details. All rights reserved. -- -- ====================================================================== # LANGUAGE MultiParamTypeClasses # # LANGUAGE UndecidableInstances # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE FlexibleInstances # {-# LANGUAGE DeriveDataTypeable #-} -- | This module contains the implementation of the various quantum circuits -- that make up the boolean formula algorithm. Please see "Algorithms.BF.Main" -- for an overview of the boolean formula algorithm. module Algorithms.BF.BooleanFormula where import Quipper import Quipper.Internal import Algorithms.BF.QuantumIf import Algorithms.BF.Hex import QuipperLib.QFT import QuipperLib.Simulation import QuipperLib.Decompose import Libraries.Auxiliary (mmap) import Data.Typeable -- ---------------------------------------------------------------------- -- * Classical data structures * * Oracle description -- $ We define a data structure to hold the various parameters that -- are used to define an oracle. | The input to the BF Algorithm is the description of an oracle to -- represent a given size of hex board, and a given size for the phase -- estimation register. data BooleanFormulaOracle = BFO { oracle_x_max :: Int, -- ^ The /x/-dimension of hex board. oracle_y_max :: Int, -- ^ The /y/-dimension of hex board. oracle_t :: Int, -- ^ Size of phase estimation register. -- The number of moves remaining can depend on the starting state of the HexBoard oracle_s :: Int, -- ^ Number of moves remaining. -- This should start as /x/⋅/y/, if no moves have been made. oracle_m :: Int, -- ^ Size of the direction register, -- i.e., size of labels on the BF tree. -- This should be the ceiling of log(/x/⋅/y/). start_board :: HexBoard, -- ^ A description of the starting state of the -- board, and can be used to calculate /s/. oracle_hex :: HexCircuit -- ^ An extra flag that we can use so that different -- HEX circuits can be used instead of the full circuit. } -- | A type to define which Hex circuit to use. data HexCircuit = Hex -- ^ The actual Hex circuit. | Dummy -- ^ A Dummy Hex circuit. | EmptyHex -- ^ Nothing. -- | Create an oracle description. This only requires /x/, /y/, and -- /t/ to be specified, as the remaining values can be calculated. The number of -- moves remaining, /s/, is calculated as the total number of squares on the board, and /m/ is calculated as the number of bits required to represent /s/+1 . createOracle :: Int -> Int -> Int -> BooleanFormulaOracle createOracle x y t = BFO { oracle_x_max = x, oracle_y_max = y, oracle_t = t, oracle_s = s, oracle_m = m, start_board = (empty,empty), oracle_hex = Hex } where s = x * y m = ceiling (log (fromIntegral (s+1)) / log 2) empty = replicate s False | A function to set the \"Dummy\ " flag in the given oracle to the given ' HexCircuit ' value . update_hex :: BooleanFormulaOracle -> HexCircuit -> BooleanFormulaOracle update_hex bfo hex = bfo {oracle_hex = hex} | Update the ' start_board ' in the given oracle , with the given ' HexBoard ' . This -- also updates the 'oracle_s' field of the oracle to be in line with -- the new 'start_board'. update_start_board :: BooleanFormulaOracle -> HexBoard -> BooleanFormulaOracle update_start_board bfo start = bfo { oracle_s = s, start_board = start } where x = oracle_x_max bfo y = oracle_y_max bfo s = (x*y) - (moves_made start) | An oracle for a 9 by 7 Hex board , with the parameters : /x/=9 , /y/=7 , /t/=189 . The calculated values are : /s/=63 , /m/=6 . full_oracle :: BooleanFormulaOracle full_oracle = createOracle 9 7 189 -- | A smaller oracle for testing purposes. The numbers should be chosen such that /x/⋅/y/ = 2[sup /n/]−1 for some /n/. Here , we set /x/=3 and , to give . We arbitrarily set the size of -- the phase estimation register to /t/=4. test_oracle :: BooleanFormulaOracle test_oracle = createOracle 5 3 4 -- ** Hex boards -- | A hex board is specified by a pair of lists of booleans. For a -- board of size /x/ by /y/, each list should contain /x/⋅/y/ elements . The first list is the \"blue\ " bitmap , and the second is the \"red\ " . type HexBoard = ([Bool],[Bool]) | A function to determine how many moves have been made on a given HexBoard . This function assumes that the given ' HexBoard ' is valid , in the sense that -- no duplicate moves have been made. moves_made :: HexBoard -> Int moves_made (blue,red) = moves blue + moves red where moves color = length (filter id color) | A function to determine which spaces are still empty in the given HexBoard . This function assumes that the given ' HexBoard ' is valid , in the sense that -- no duplicate moves have been made. This function will return a list of all the -- empty spaces remaining, in strictly increasing order. empty_spaces :: HexBoard -> [Int] empty_spaces (blue,red) = empty_spaces' blue red 0 where empty_spaces' [] [] _ = [] empty_spaces' [] _ _ = error "empty_spaces: Red and Blue boards of different length" empty_spaces' _ [] _ = error "empty_spaces: Red and Blue boards of different length" empty_spaces' (b:bs) (r:rs) n = if (b || r) then rest else (n:rest) where rest = empty_spaces' bs rs (n+1) -- ---------------------------------------------------------------------- * Quantum data structures -- $ Some data structures to help in defining the algorithm. -- | The phase estimation register is a simple register of qubits. This is kept -- separate from the rest of the 'BooleanFormulaRegister' as it is this register -- which will be measured at the end of the algorithm. type PhaseEstimationRegister = [Qubit] -- | The direction register is a simple register of qubits, -- made explicit here so we can see that a \"position\" is a list of directions. type GenericDirectionRegister a = [a] -- | A type synonym defined as the 'Qubit' instance of a -- 'GenericDirectionRegister'. type DirectionRegister = GenericDirectionRegister Qubit -- | The rest of the boolean formula algorithm requires a register which is split into 3 main parts . data GenericBooleanFormulaRegister a = BFR { | The position register is split into two parts : the leaf and paraleaf \"flags\ " . position_flags :: (a,a), -- | The current position, and how we got there, i.e., directions we followed. -- Any position can be reached by at most /x/⋅/y/ directions. position :: [GenericDirectionRegister a], work_leaf :: a, work_paraleaf :: a, work_binary :: a, work_height :: a, work_r :: a, work_rp :: a, ^ Seven flags that make up the work register . direction :: GenericDirectionRegister a -- ^ The direction register. } deriving (Typeable, Show) -- | A type synonym defined as the 'Qubit' instantiation of a -- 'GenericBooleanFormulaRegister'. type BooleanFormulaRegister = GenericBooleanFormulaRegister Qubit -- | A function to add labels to the wires that make up a 'BooleanFormulaRegister'. -- These labels correspond to the parts of the register. labelBFR :: BooleanFormulaRegister -> Circ () labelBFR reg = do let tuple = toTuple reg label tuple (("pos-leaf","pos-paraleaf"), "pos", ("leaf","paraleaf","binary","height","r","rp","rpp"), "dir") -- | A type synonym defined as the 'Bool' instantiation of a -- 'GenericBooleanFormulaRegister'. type BoolRegister = GenericBooleanFormulaRegister Bool | Helper function to simplify the ' QCData ' instance for ' BooleanFormulaRegister ' . -- Create a tuple from a 'GenericBooleanFormulaRegister'. toTuple :: GenericBooleanFormulaRegister a -> ((a,a),[[a]],(a,a,a,a,a,a,a),[a]) toTuple r = (position_flags r,position r,(work_leaf r,work_paraleaf r,work_binary r,work_height r,work_r r,work_rp r,work_rpp r),direction r) | Helper function to simplify the ' QCData ' instance for ' BooleanFormulaRegister ' . -- Create a 'GenericBooleanFormulaRegister' from a tuple. fromTuple :: ((a,a),[[a]],(a,a,a,a,a,a,a),[a]) -> GenericBooleanFormulaRegister a fromTuple (pf,p,(wl,wp,wb,wh,wr,wrp,wrpp),d) = BFR { position_flags = pf, position = p, work_leaf = wl, work_paraleaf = wp, work_binary = wb, work_height = wh, work_r = wr, work_rp = wrp, work_rpp = wrpp, direction = d } type instance QCType x y (GenericBooleanFormulaRegister a) = GenericBooleanFormulaRegister (QCType x y a) type instance QTypeB (GenericBooleanFormulaRegister a) = GenericBooleanFormulaRegister (QTypeB a) instance QCData a => QCData (GenericBooleanFormulaRegister a) where qcdata_mapM s f g xs = mmap fromTuple $ qcdata_mapM (toTuple s) f g (toTuple xs) qcdata_zip s q c q' c' xs ys e = fromTuple $ qcdata_zip (toTuple s) q c q' c' (toTuple xs) (toTuple ys) e qcdata_promote a x s = fromTuple $ qcdata_promote (toTuple a) (toTuple x) s instance (Labelable a String) => Labelable (GenericBooleanFormulaRegister a) String where label_rec r s = do label_rec (position_flags r) s `dotted_indexed` "posflag" label_rec (position r) s `dotted_indexed` "pos" label_rec (work_leaf r) s `dotted_indexed` "leaf" label_rec (work_paraleaf r) s `dotted_indexed` "paraleaf" label_rec (work_binary r) s `dotted_indexed` "binary" label_rec (work_height r) s `dotted_indexed` "height" label_rec (work_r r) s `dotted_indexed` "r" label_rec (work_rp r) s `dotted_indexed` "rp" label_rec (work_rpp r) s `dotted_indexed` "rpp" label_rec (direction r) s `dotted_indexed` "dir" -- | Create an initial classical 'BooleanFormulaRegister' for a given oracle description. The register is initialized in the /zero/ state that represents being at label , or node /rpp/ in the tree . The work qubits are all initialized to /zero/ , as the first call to the /oracle/ circuit will set them accordingly for the /position/ we are currently in . The /direction/ register is also set to -- as this is the direction in which the node /rp/ is in. The given -- 'BooleanFormulaOracle' is used to make sure the registers are of the correct -- size, i.e., number of qubits. createRegister :: BooleanFormulaOracle -> BoolRegister createRegister oracle = BFR { position_flags = (False,False), position = replicate s (replicate m False), work_leaf = False, work_paraleaf = False, work_binary = False, work_height = False, work_r = False, work_rp = False, work_rpp = False, direction = replicate m False } where s = oracle_s oracle m = oracle_m oracle -- | Create a shape parameter for a 'BooleanFormulaRegister' of the -- correct size. registerShape :: BooleanFormulaOracle -> BooleanFormulaRegister registerShape oracle = qshape (createRegister oracle) -- | Initialize a 'BooleanFormulaRegister' from a 'BooleanFormulaOracle'. initializeRegister :: BooleanFormulaOracle -> Circ BooleanFormulaRegister initializeRegister oracle = qinit (createRegister oracle) -- ====================================================================== * Oracle implementation -- $ The functions in this implementation follow a separation of the boolean formula algorithm into two parts . The first part corresponds to the algorithms defined in this module . The second part consists of the algorithms defined in " Algorithms . " . This separation relates to the first part defining the quantum parts of the algorithm , including the phase estimation , and the quantum walk , whereas the remaining four define -- the classical implementation of the circuit for determining which player -- has won a completed game of Hex, which is converted to a quantum circuit using Quipper 's \"build_circuit\ " keyword . -- -- Note that the circuits for the algorithms in this module have been tested -- for performing a quantum walk on the tree defined for a given oracle (but -- with a dummy function taking the place of the call to HEX). -- | The overall Boolean Formula Algorithm. It initializes the phase estimation register into an equal super - position of all 2[sup t ] states , -- and the other registers as defined previously. It then maps the exponentiated -- version of the unitary /u/, as per phase estimation, before applying the -- inverse QFT, and measuring the result. qw_bf :: BooleanFormulaOracle -> Circ [Bit] qw_bf oracle = do -- initialize the phase estimation register, -- and put it in an equal super-position let t = oracle_t oracle a <- qinit (replicate t False) label a "a" a <- mapUnary hadamard a -- initialize the other boolean formula registers b <- initializeRegister oracle labelBFR b we can use a separate recursive function to map the exp_u algorithm over a let t = oracle_t oracle map_exp_u oracle a b (t-1) -- qft is defined, so we reverse it to get inverse qft a <- (subroutine_inverse_qft oracle) a -- we're only interested in the result of measuring a, -- so we can discard all the qubits in the rest of the register qdiscard b measure a -- | The inverse quantum Fourier transform as a boxed subroutine. subroutine_inverse_qft :: BooleanFormulaOracle -> [Qubit] -> Circ [Qubit] subroutine_inverse_qft o = box "QFT*" (reverse_generic_endo qft_little_endian) -- | \"Map\" the application of the exponentiated unitary /u/ -- over the phase estimation register. That is, each qubit in the phase estimation -- register is used as a control over a call to the unitary /u/, exponentiated to -- the appropriate power. map_exp_u :: BooleanFormulaOracle -> [Qubit] -> BooleanFormulaRegister -> Int -> Circ () map_exp_u _ [] _ _ = return () map_exp_u o (a:as) b l = do let x_max = oracle_x_max o -- we can move the control out of the exp_u function exp_u o (2^(l-(length as))) b `controlled` a map_exp_u o as b l -- | Exponentiate the unitary /u/. In this implementation, this is -- achieved by repeated application of /u/. exp_u :: BooleanFormulaOracle -> Integer -> BooleanFormulaRegister -> Circ () exp_u _ 0 _ = return () exp_u o n_steps b = do (subroutine_u o) b exp_u o (n_steps-1) b -- | The unitary /u/ represents a single step in the walk on the NAND tree. A call -- to the oracle determines what type of node we are at (so we know which directions -- are valid to step to), the call to diffuse sets the direction register to be a -- super-position of all valid directions, the call to walk performs the step, and then -- the call to undo oracle has to clean up the work registers that were set by the -- call to the oracle. Note that the undo oracle step is not simply the inverse of the -- oracle, as we have walked since the oracle was called. u :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () u o b = do comment "U" labelBFR b (subroutine_oracle o) b (subroutine_diffuse o) b (subroutine_walk o) b (subroutine_undo_oracle o) b -- | The circuit for 'u' as a boxed subroutine. subroutine_u :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_u o = box "U" (u o) -- | Call the oracle to determine some extra information about where we are in the tree . Essentially , the special cases are when were are at one of the three \"low height\ " nodes , or when we are at a node representing a complete -- game of Hex, and we need to determine if this is a leaf, by calling the hex circuit, -- which determines whether the node represents a completed game of hex in which -- the red player has won. oracle :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () oracle o register = do comment "ORACLE" labelBFR register let init = start_board o let x_max = oracle_x_max o let (is_leaf,is_paraleaf) = position_flags register with_controls (is_leaf) ( -- if is_leaf -- we are at a leaf node, so set "leaf" do let leaf = work_leaf register qnot_at leaf ) with_controls (is_leaf .==. False .&&. is_paraleaf .==. True) ( -- else if is_paraleaf -- we are at a paraleaf node, so set "paraleaf" do let paraleaf = work_paraleaf register qnot_at paraleaf let binary = work_binary register qnot_at binary let pos = position register let hex_subroutine = case oracle_hex o of Hex -> box "HEX" (hex_oracle init (oracle_s o) x_max) Dummy -> hex_oracle_dummy EmptyHex -> \x -> return x -- hex sets "binary" flag depending on whether the paraleaf is attached to a -- a leaf, i.e., whether red has won or lost the game of hex. hex_subroutine (pos,binary) return () ) with_controls (is_leaf .==. False .&&. is_paraleaf .==. False) ( -- else -- we're not at a leaf node, or paraleaf node do let pos = position register -- are we at a "low height" node? with_controls (controls is_paraleaf pos) ( -- we're at a "low height" node do let pos'' = pos !! (length pos - 2) let pos_m = last pos'' with_controls pos_m if pos_m = = 1 do let height = work_height register qnot_at height ) let pos' = last pos let pos_1 = pos' !! (length pos' - 2) with_controls (pos_m .==. False .&&. pos_1 .==. True) else if = = 1 do let r = work_r register qnot_at r ) let pos_0 = last pos' with_controls (pos_m .==. False .&&. pos_1 .==. False .&&. pos_0 .==. True) else if pos_0 = = 1 do let rp = work_rp register qnot_at rp let binary = work_binary register qnot_at binary ) with_controls (pos_m .==. False .&&. pos_1 .==. False .&&. pos_0 .==. False) ( -- else do let rpp = work_rpp register qnot_at rpp ) ) ) -- | The circuit for the 'oracle' as a boxed subroutine. subroutine_oracle :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_oracle o = box "Oracle" (oracle o) -- | The controls to use, to see if we're at a \"low height\" node. controls :: Qubit -> [DirectionRegister] -> [ControlList] controls is_paraleaf pos = (is_paraleaf .==. False) : ctrls pos where ctrls [] = [] ctrls [p] = [] ctrls [p,q] = [] ctrls (p:ps) = (last p .==. False) : ctrls ps -- | Diffuse the direction register, to be a super-position of all valid -- directions from the current node. Note, that this implementation of the boolean -- formula algorithm does not applying the correct weighting scheme to the NAND graph, -- which would require this function to diffuse with respect to the weighting scheme. diffuse :: BooleanFormulaRegister -> Circ () diffuse register = do comment "DIFFUSE" labelBFR register let binary = work_binary register let dir = direction register with_controls binary if binary = = 1 do let dir_0 = last dir hadamard_at dir_0 ) let leaf = work_leaf register let rpp = work_rpp register with_controls (binary .==. False .&&. leaf .==. False .&&. rpp .==. False) ( -- else (controlled on binary == 0, leaf == 0, rpp == 0) do mapUnary hadamard dir ) return () -- | The circuit for 'diffuse' as a boxed subroutine. subroutine_diffuse :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_diffuse o = box "Diffuse" diffuse -- | A datatype to use instead of passing integers to 'toParent' and 'toChild' to define what needs to be shifted . This is used as only three different -- shift widths are ever used in the algorithm. data Where = Width -- ^ corresponds to shifting all qubits. | M -- ^ corresponds to shifting only /m/+1 qubits. ^ corresponds to shifting only 2 / m/+1 qubits . deriving Eq -- | Define a step on the NAND graph, in the direction specified -- by the direction register, and updates the direction register to be where -- we have stepped from. -- For this algorithm we have developed the 'if_then_elseQ' construct, which -- gives us a nice way of constructing if/else statements acting on \"boolean statements\ " over qubits ( see " Algorithms . " ) . walk :: BooleanFormulaRegister -> Circ () walk register = do comment "WALK" labelBFR register let leaf = work_leaf register let paraleaf = work_paraleaf register let dir = direction register let dir_0 = last dir let (is_leaf,is_paraleaf) = position_flags register let pos = position register let pos_0 = last (last pos) let pos_1 = last (init (last pos)) let height_1 = work_height register let rpp = work_rpp register let rp = work_rp register let r = work_r register let dir_all_1 = foldr1 (\x y -> And x y) (map A dir) let boolean_statement_in = Or (A leaf) (And (A paraleaf) (Not (A dir_0))) let boolean_statement_out = Or (A leaf) (And (A paraleaf) (A is_leaf)) if_then_elseQinv boolean_statement_in if leaf = = 1 or ( paraleaf = = 1 and dir_0 = = 0 ) do qnot_at is_leaf ) else ( leaf = = 0 and ( paraleaf = = 0 or dir_0 = = 1 ) ) do let boolean_statement_in = And (A paraleaf) (A dir_0) let boolean_statement_out = And (A paraleaf) (Not (dir_all_1)) if_then_elseQinv boolean_statement_in if paraleaf = = 1 and dir_0 = = 1 toParent Width register now , dir /= 1 .. 1 , so dir_0 could be either 0 or 1 ) ( -- else (paraleaf == 0 or dir_0 == 0) do let boolean_statement_in = Or (A rpp) (And (A rp) (A dir_0)) let boolean_statement_out = Or (A rpp) (And (A rp) (Not (A dir_0))) if_then_elseQinv boolean_statement_in if rpp = = 1 or ( rp = = 1 and dir_0 = = 1 ) do qnot_at pos_0 -- dir_0 should be changed, as we 're moving from rp to rpp , and rpp only has a child at 0 or we 're moving from rpp to rp , and dir_0 should be set to 1 as -- we have come from a parent qnot_at dir_0 ) ( -- else (rpp == 0 and (rp == 0 or dir_0 == 0)) do let boolean_statement_in = Or (And (A rp) (Not (A dir_0))) (And (A r) dir_all_1) let pos_m = last (last (init pos)) let boolean_statement_out = Or (And (A rp) dir_all_1) (And (A r) (And (Not dir_all_1) (Not (A pos_m)))) if_then_elseQinv boolean_statement_in if ( rp = = 1 and dir_0 = = 0 ) or ( r = = 1 and dir = = 1 .. 1 ) do qnot_at pos_1 we know that pos_m = = 0 -- dir is should be changed -- when we move from rp to r, and when we move from r to rp mapUnary qnot dir return () ) else ( ( rp = = 0 or dir_0 = = 1 ) and ( r = = 0 or dir /= 1 .. 1 ) ) do let boolean_statement = A r if_then_elseQ boolean_statement if r = = 1 do qnot_at pos_1 toChild M register now dir = = 1 .. 1 we also know that pos_m = = 1 ) ( -- else do let boolean_statement_in = And (A height_1) (dir_all_1) let boolean_statement_out = And (A height_1) (Not dir_all_1) if_then_elseQinv boolean_statement_in if height_1 = = 1 and dir = = 1 .. 1 do toParent M register qnot_at pos_1 now , dir /= 1 .. 1 ) else height_1 = = 0 or dir /= 1 .. 1 do let boolean_statement = A height_1 if_then_elseQ boolean_statement if height_1 = = 1 ( and dir /= 1 .. 1 ) do toChild M2 register now dir = = 1 .. 1 ) ( -- else (if height_1 == 0) do let boolean_statement_in = dir_all_1 let boolean_statement_out = Not dir_all_1 if_then_elseQinv boolean_statement_in if dir = 1 .. 1 do toParent Width register now dir /= 1 .. 1 ) else ( dir /= 1 .. 1 ) do toChild Width register now dir = = 1 .. 1 ) boolean_statement_out ) ) boolean_statement_out ) ) boolean_statement_out ) boolean_statement_out ) boolean_statement_out ) boolean_statement_out return () -- | The circuit for 'walk' as a boxed subroutine. subroutine_walk :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_walk o = box "Walk" walk -- | Uncompute the various flags that were set by the initial call -- to the oracle. It has to uncompute the flags depending on where we were before -- the walk step, so isn't just the inverse of the oracle. undo_oracle :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () undo_oracle o register = do comment "UNDO_ORACLE" labelBFR register let initHB = start_board o let x_max = oracle_x_max o let paraleaf = work_paraleaf register let (is_leaf,is_paraleaf) = position_flags register with_controls paraleaf ( do let binary = work_binary register let pos = position register let dir = direction register let hex_subroutine = case oracle_hex o of Hex -> box "HEX" (hex_oracle initHB (oracle_s o) x_max) Dummy -> hex_oracle_dummy EmptyHex -> \x -> return x hex_subroutine (pos,binary) return () ) let leaf = work_leaf register let dir = direction register let dir_0 = last dir let boolean_statement = And (Not (A is_leaf)) (And (A is_paraleaf) (Not (A dir_0))) if_then_elseQ boolean_statement if is_leaf = = 0 and is_paraleaf = = 1 and dir_0 = = 0 -- we went from a leaf to a paraleaf, so we can unset leaf do qnot_at leaf ) ( -- else do let binary = work_binary register let pos = position register let pos_w_2_m = last (head pos) let dir_all_1 = foldr1 (\x y -> And x y) (map A dir) let boolean_statement = Or (A is_leaf) (And (Not (A is_leaf)) (And (Not (A is_paraleaf)) (And (A pos_w_2_m) (Not (dir_all_1))))) if_then_elseQ boolean_statement if is_leaf = = 1 or ( is_leaf = = 0 and is_paraleaf = = 0 and pos_w_2_m = = 1 and dir /= 1 .. 1 ) -- we went from a paraleaf to a leaf, so unset binary and paraleaf -- or we went from a paraleaf to its parent... do qnot_at binary qnot_at paraleaf ) ( -- else do with_controls (init (controls is_paraleaf pos)) ( -- if pos_sm,pos_(s-1)m,...,3. == 00...0 do let height = work_height register let r = work_r register let rp = work_rp register let pos_0 = last (last pos) let pos_1 = last (init (last pos)) let pos_m = last (last (init pos)) let pos_2m = last (last (init (init pos))) let boolean_statement = dir_all_1 if_then_elseQ boolean_statement if dir = 1 ... 1 do qnot_at height `controlled` pos_2m qnot_at r `controlled` (pos_2m .==. False .&&. pos_m .==. True) with_controls (pos_2m .==. False .&&. pos_m .==. False .&&. pos_1 .==. True) ( do qnot_at rp qnot_at binary ) ) ( -- else with_controls (pos_2m .==. False .&&. pos_m .==. False) ( do let rpp = work_rpp register qnot_at height `controlled` pos_1 qnot_at rpp `controlled` (pos_1 .==. False .&&. dir_0 .==. True) qnot_at r `controlled` (pos_1 .==. False .&&. dir_0 .==. False .&&. pos_0 .==. True) with_controls (pos_1 .==. False .&&. dir_0 .==. False .&&. pos_0 .==. False) ( do qnot_at rp qnot_at binary ) ) ) ) -- end if ) ) return () -- | The circuit for 'undo_oracle' as a boxed subroutine. subroutine_undo_oracle :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_undo_oracle o = box "Undo Oracle" (undo_oracle o) -- | Define the circuit that updates the position register to be the -- parent node of the current position. toParent :: Where -> BooleanFormulaRegister -> Circ () toParent M2 _ = error "TOPARENT should never be called with 2m+1 as width" toParent w register = do let pos = position register :: [[Qubit]] -- of length x*y let pos_firstM = last pos :: [Qubit] -- of length m let pos_secondM = last (init pos) :: [Qubit] -- of length m let pos_0 = last pos_firstM :: Qubit let pos_m = last pos_secondM :: Qubit let dir = direction register :: [Qubit] -- of length m let (_,is_paraleaf) = position_flags register :: (Qubit,Qubit) mapUnary qnot dir mapBinary copy_from_to (reverse pos_firstM) (reverse dir) if (w == Width) then ( do -- width -- we need to shift everything to the right by m shift_right pos we need to shift is_paraleaf to x*y*m copy_from_to is_paraleaf (last (head pos)) return () ) else return () if (w == M) then m+1 we need to " shift " pos_m to pos_0 copy_from_to pos_m pos_0 return () ) else return () -- | @'copy_from_to' a b@: Sets the state of qubit /b/ to be the state of qubit /a/, -- (and the state of /a/ is lost in the process, so this is not cloning). It falls short of swapping /a/ and /b/ , as we 're not interested in preserving /a/. copy_from_to :: Qubit -> Qubit -> Circ (Qubit,Qubit) copy_from_to from to = do qnot_at to `controlled` from qnot_at from `controlled` to return (from,to) -- | Define the circuit that updates the position register to be the -- child node of the current position. toChild :: Where -> BooleanFormulaRegister -> Circ () toChild w register = do let pos = position register :: [[Qubit]] -- of length x*y let pos_firstM = last pos :: [Qubit] -- of length m let pos_secondM = last (init pos) :: [Qubit] -- of length m let pos_thirdM = last (init (init pos)) :: [Qubit] -- of length m let pos_0 = last pos_firstM :: Qubit let pos_m = last pos_secondM :: Qubit let pos_2m = last pos_thirdM :: Qubit let dir = direction register :: [Qubit] -- of length m let (_,is_paraleaf) = position_flags register :: (Qubit,Qubit) if (w == Width) then ( do -- width -- we need to "shift" x*y*m to is_paraleaf copy_from_to (last (head pos)) is_paraleaf -- we need to "shift" everything to the left by "m" shift_left pos ) else return () if (w == M2) then 2m+1 -- we need to "shift" pos_m to pos_2m copy_from_to pos_m pos_2m -- we need to "shift" 0.. to m.. to shift_left [pos_secondM,pos_firstM] ) else return () if (w == M) then ( do we need to " shift " pos_0 to pos_m copy_from_to pos_0 pos_m return () ) else return () mapBinary copy_from_to dir pos_firstM mapUnary qnot dir return () -- | Shift every qubit in a register to the left by one. shift_left :: [DirectionRegister] -> Circ () shift_left [] = return () shift_left [d] = return () shift_left (d:d':ds) = do mapBinary copy_from_to d' d shift_left (d':ds) -- | Shift every qubit in a register to the right by one. shift_right :: [DirectionRegister] -> Circ () shift_right [] = return () shift_right [d] = return () shift_right (d:d':ds) = do shift_right (d':ds) mapBinary copy_from_to (reverse d) (reverse d') -- the arguments are reversed to give a nice symmetry to the circuits -- and should be equivalent to if they're not reversed return () -- ---------------------------------------------------------------------- -- * Possible main functions -- $ The following functions define various \main\ functions that can be called -- from an overall \main\ function to display various parts of the overall Boolean Formula Algorithm . The Boolean Formula Algorithm is split into 13 sub - algorithms , each of which can be -- displayed separately, or in various combinations. -- | Displays the overall Boolean Formula circuit for a given oracle description. main_circuit :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_circuit f g oracle = print_simple f (decompose_generic g (qw_bf oracle)) | Display just 1 time - step of the given oracle , i.e. , one iteration of the ' u ' from ' exp_u ' , with no controls . main_u :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_u f g o = print_generic f (decompose_generic g (u o)) (registerShape o) | Display just 1 time - step of the ' walk ' algorithm for the given oracle , i.e. , one iteration of /walk/ , with no controls . main_walk :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_walk f g o = print_generic f (decompose_generic g walk) (registerShape o) | Display just 1 time - step of the ' diffuse ' algorithm for the given oracle , i.e. , one iteration of /diffuse/ , with no controls . main_diffuse :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_diffuse f g o = print_generic f (decompose_generic g diffuse) (registerShape o) | Display just 1 time - step of the ' oracle ' algorithm for the given oracle , i.e. , one iteration of /oracle/ , with no controls . main_oracle :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_oracle f g o = print_generic f (decompose_generic g (oracle o)) (registerShape o) | Display just 1 time - step of the ' undo_oracle ' algorithm for the given oracle , i.e. , one iteration of /undo_oracle/ , with no controls . main_undo_oracle :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_undo_oracle f g o = print_generic f (decompose_generic g (undo_oracle o)) (registerShape o) -- | Display the circuit for the Hex algorithm, for the given oracle, i.e. , one iteration of ' hex_oracle ' , with no controls . main_hex :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_hex f g o = print_generic f (decompose_generic g (hex_oracle init s x_max)) (pos,binary) where init = start_board o s = oracle_s o x_max = oracle_x_max o reg = registerShape o pos = position reg binary = work_binary reg -- | Display the circuit for the Checkwin_red algorithm, for the given oracle, i.e. , one iteration of ' checkwin_red_circuit ' , with no controls . main_checkwin_red :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_checkwin_red f g o = print_generic f (decompose_generic g (checkwin_red_circuit x_max)) (qshape redboard,qubit) where (redboard,_) = start_board o x_max = oracle_x_max o -- ---------------------------------------------------------------------- -- * Running the Boolean Formula Algorithm $ The following functions define the way that the Boolean Formula Algorithm -- would be run, if we had access to a quantum computer. Indeed, the functions -- here interface with the "QuantumSimulation" quantum simulator so that they -- can be built. -- | Approximation of how the algorithm would be run if we had a quantum computer: -- uses QuantumSimulation run_generic_io function. The output of the algorithm will be all False only in the instance that the Blue player wins the game . main_bf :: BooleanFormulaOracle -> IO Bool main_bf oracle = do output <- run_generic_io (undefined :: Double) (qw_bf oracle) let result = if (or output) then True -- a /= 0 (Red Wins) a = = 0 ( Blue Wins ) return result | Display the result of ' ' , -- i.e., either \"Red Wins\", or \"Blue Wins\" is the output. whoWins :: BooleanFormulaOracle -> IO () whoWins oracle = do result <- main_bf oracle if result then putStrLn "Red Wins" else putStrLn "Blue Wins" | Run ' whoWins ' for the given oracle , and its \"initial\ " board . main_whoWins :: BooleanFormulaOracle -> IO () main_whoWins o = whoWins o
null
https://raw.githubusercontent.com/silky/quipper/1ef6d031984923d8b7ded1c14f05db0995791633/Algorithms/BF/BooleanFormula.hs
haskell
file COPYRIGHT for a list of authors, copyright holders, licensing, and other details. All rights reserved. ====================================================================== # LANGUAGE TypeSynonymInstances # # LANGUAGE DeriveDataTypeable # | This module contains the implementation of the various quantum circuits that make up the boolean formula algorithm. Please see "Algorithms.BF.Main" for an overview of the boolean formula algorithm. ---------------------------------------------------------------------- * Classical data structures $ We define a data structure to hold the various parameters that are used to define an oracle. represent a given size of hex board, and a given size for the phase estimation register. ^ The /x/-dimension of hex board. ^ The /y/-dimension of hex board. ^ Size of phase estimation register. The number of moves remaining can ^ Number of moves remaining. This should start as /x/⋅/y/, if no moves have been made. ^ Size of the direction register, i.e., size of labels on the BF tree. This should be the ceiling of log(/x/⋅/y/). ^ A description of the starting state of the board, and can be used to calculate /s/. ^ An extra flag that we can use so that different HEX circuits can be used instead of the full circuit. | A type to define which Hex circuit to use. ^ The actual Hex circuit. ^ A Dummy Hex circuit. ^ Nothing. | Create an oracle description. This only requires /x/, /y/, and /t/ to be specified, as the remaining values can be calculated. The number of moves remaining, /s/, is calculated as the total number of squares on the board, also updates the 'oracle_s' field of the oracle to be in line with the new 'start_board'. | A smaller oracle for testing purposes. The numbers should be the phase estimation register to /t/=4. ** Hex boards | A hex board is specified by a pair of lists of booleans. For a board of size /x/ by /y/, each list should contain /x/⋅/y/ no duplicate moves have been made. no duplicate moves have been made. This function will return a list of all the empty spaces remaining, in strictly increasing order. ---------------------------------------------------------------------- $ Some data structures to help in defining the algorithm. | The phase estimation register is a simple register of qubits. This is kept separate from the rest of the 'BooleanFormulaRegister' as it is this register which will be measured at the end of the algorithm. | The direction register is a simple register of qubits, made explicit here so we can see that a \"position\" is a list of directions. | A type synonym defined as the 'Qubit' instance of a 'GenericDirectionRegister'. | The rest of the boolean formula algorithm requires a register which is | The current position, and how we got there, i.e., directions we followed. Any position can be reached by at most /x/⋅/y/ directions. ^ The direction register. | A type synonym defined as the 'Qubit' instantiation of a 'GenericBooleanFormulaRegister'. | A function to add labels to the wires that make up a 'BooleanFormulaRegister'. These labels correspond to the parts of the register. | A type synonym defined as the 'Bool' instantiation of a 'GenericBooleanFormulaRegister'. Create a tuple from a 'GenericBooleanFormulaRegister'. Create a 'GenericBooleanFormulaRegister' from a tuple. | Create an initial classical 'BooleanFormulaRegister' for a given oracle description. as this is the direction in which the node /rp/ is in. The given 'BooleanFormulaOracle' is used to make sure the registers are of the correct size, i.e., number of qubits. | Create a shape parameter for a 'BooleanFormulaRegister' of the correct size. | Initialize a 'BooleanFormulaRegister' from a 'BooleanFormulaOracle'. ====================================================================== $ The functions in this implementation follow a separation of the boolean the classical implementation of the circuit for determining which player has won a completed game of Hex, which is converted to a quantum circuit Note that the circuits for the algorithms in this module have been tested for performing a quantum walk on the tree defined for a given oracle (but with a dummy function taking the place of the call to HEX). | The overall Boolean Formula Algorithm. It initializes the and the other registers as defined previously. It then maps the exponentiated version of the unitary /u/, as per phase estimation, before applying the inverse QFT, and measuring the result. initialize the phase estimation register, and put it in an equal super-position initialize the other boolean formula registers qft is defined, so we reverse it to get inverse qft we're only interested in the result of measuring a, so we can discard all the qubits in the rest of the register | The inverse quantum Fourier transform as a boxed subroutine. | \"Map\" the application of the exponentiated unitary /u/ over the phase estimation register. That is, each qubit in the phase estimation register is used as a control over a call to the unitary /u/, exponentiated to the appropriate power. we can move the control out of the exp_u function | Exponentiate the unitary /u/. In this implementation, this is achieved by repeated application of /u/. | The unitary /u/ represents a single step in the walk on the NAND tree. A call to the oracle determines what type of node we are at (so we know which directions are valid to step to), the call to diffuse sets the direction register to be a super-position of all valid directions, the call to walk performs the step, and then the call to undo oracle has to clean up the work registers that were set by the call to the oracle. Note that the undo oracle step is not simply the inverse of the oracle, as we have walked since the oracle was called. | The circuit for 'u' as a boxed subroutine. | Call the oracle to determine some extra information about where game of Hex, and we need to determine if this is a leaf, by calling the hex circuit, which determines whether the node represents a completed game of hex in which the red player has won. if is_leaf we are at a leaf node, so set "leaf" else if is_paraleaf we are at a paraleaf node, so set "paraleaf" hex sets "binary" flag depending on whether the paraleaf is attached to a a leaf, i.e., whether red has won or lost the game of hex. else we're not at a leaf node, or paraleaf node are we at a "low height" node? we're at a "low height" node else | The circuit for the 'oracle' as a boxed subroutine. | The controls to use, to see if we're at a \"low height\" node. | Diffuse the direction register, to be a super-position of all valid directions from the current node. Note, that this implementation of the boolean formula algorithm does not applying the correct weighting scheme to the NAND graph, which would require this function to diffuse with respect to the weighting scheme. else (controlled on binary == 0, leaf == 0, rpp == 0) | The circuit for 'diffuse' as a boxed subroutine. | A datatype to use instead of passing integers to 'toParent' and 'toChild' shift widths are ever used in the algorithm. ^ corresponds to shifting all qubits. ^ corresponds to shifting only /m/+1 qubits. | Define a step on the NAND graph, in the direction specified by the direction register, and updates the direction register to be where we have stepped from. For this algorithm we have developed the 'if_then_elseQ' construct, which gives us a nice way of constructing if/else statements acting on else (paraleaf == 0 or dir_0 == 0) dir_0 should be changed, we have come from a parent else (rpp == 0 and (rp == 0 or dir_0 == 0)) dir is should be changed when we move from rp to r, and when we move from r to rp else else (if height_1 == 0) | The circuit for 'walk' as a boxed subroutine. | Uncompute the various flags that were set by the initial call to the oracle. It has to uncompute the flags depending on where we were before the walk step, so isn't just the inverse of the oracle. we went from a leaf to a paraleaf, so we can unset leaf else we went from a paraleaf to a leaf, so unset binary and paraleaf or we went from a paraleaf to its parent... else if pos_sm,pos_(s-1)m,...,3. == 00...0 else end if | The circuit for 'undo_oracle' as a boxed subroutine. | Define the circuit that updates the position register to be the parent node of the current position. of length x*y of length m of length m of length m width we need to shift everything to the right by m | @'copy_from_to' a b@: Sets the state of qubit /b/ to be the state of qubit /a/, (and the state of /a/ is lost in the process, so this is not cloning). | Define the circuit that updates the position register to be the child node of the current position. of length x*y of length m of length m of length m of length m width we need to "shift" x*y*m to is_paraleaf we need to "shift" everything to the left by "m" we need to "shift" pos_m to pos_2m we need to "shift" 0.. to m.. to | Shift every qubit in a register to the left by one. | Shift every qubit in a register to the right by one. the arguments are reversed to give a nice symmetry to the circuits and should be equivalent to if they're not reversed ---------------------------------------------------------------------- * Possible main functions $ The following functions define various \main\ functions that can be called from an overall \main\ function to display various parts of the displayed separately, or in various combinations. | Displays the overall Boolean Formula circuit for a given oracle description. | Display the circuit for the Hex algorithm, for the given oracle, | Display the circuit for the Checkwin_red algorithm, for the given oracle, ---------------------------------------------------------------------- * Running the Boolean Formula Algorithm would be run, if we had access to a quantum computer. Indeed, the functions here interface with the "QuantumSimulation" quantum simulator so that they can be built. | Approximation of how the algorithm would be run if we had a quantum computer: uses QuantumSimulation run_generic_io function. The output of the algorithm will a /= 0 (Red Wins) i.e., either \"Red Wins\", or \"Blue Wins\" is the output.
This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the # LANGUAGE MultiParamTypeClasses # # LANGUAGE UndecidableInstances # # LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # module Algorithms.BF.BooleanFormula where import Quipper import Quipper.Internal import Algorithms.BF.QuantumIf import Algorithms.BF.Hex import QuipperLib.QFT import QuipperLib.Simulation import QuipperLib.Decompose import Libraries.Auxiliary (mmap) import Data.Typeable * * Oracle description | The input to the BF Algorithm is the description of an oracle to data BooleanFormulaOracle = BFO { depend on the starting state of the HexBoard } and /m/ is calculated as the number of bits required to represent /s/+1 . createOracle :: Int -> Int -> Int -> BooleanFormulaOracle createOracle x y t = BFO { oracle_x_max = x, oracle_y_max = y, oracle_t = t, oracle_s = s, oracle_m = m, start_board = (empty,empty), oracle_hex = Hex } where s = x * y m = ceiling (log (fromIntegral (s+1)) / log 2) empty = replicate s False | A function to set the \"Dummy\ " flag in the given oracle to the given ' HexCircuit ' value . update_hex :: BooleanFormulaOracle -> HexCircuit -> BooleanFormulaOracle update_hex bfo hex = bfo {oracle_hex = hex} | Update the ' start_board ' in the given oracle , with the given ' HexBoard ' . This update_start_board :: BooleanFormulaOracle -> HexBoard -> BooleanFormulaOracle update_start_board bfo start = bfo { oracle_s = s, start_board = start } where x = oracle_x_max bfo y = oracle_y_max bfo s = (x*y) - (moves_made start) | An oracle for a 9 by 7 Hex board , with the parameters : /x/=9 , /y/=7 , /t/=189 . The calculated values are : /s/=63 , /m/=6 . full_oracle :: BooleanFormulaOracle full_oracle = createOracle 9 7 189 chosen such that /x/⋅/y/ = 2[sup /n/]−1 for some /n/. Here , we set /x/=3 and , to give . We arbitrarily set the size of test_oracle :: BooleanFormulaOracle test_oracle = createOracle 5 3 4 elements . The first list is the \"blue\ " bitmap , and the second is the \"red\ " . type HexBoard = ([Bool],[Bool]) | A function to determine how many moves have been made on a given HexBoard . This function assumes that the given ' HexBoard ' is valid , in the sense that moves_made :: HexBoard -> Int moves_made (blue,red) = moves blue + moves red where moves color = length (filter id color) | A function to determine which spaces are still empty in the given HexBoard . This function assumes that the given ' HexBoard ' is valid , in the sense that empty_spaces :: HexBoard -> [Int] empty_spaces (blue,red) = empty_spaces' blue red 0 where empty_spaces' [] [] _ = [] empty_spaces' [] _ _ = error "empty_spaces: Red and Blue boards of different length" empty_spaces' _ [] _ = error "empty_spaces: Red and Blue boards of different length" empty_spaces' (b:bs) (r:rs) n = if (b || r) then rest else (n:rest) where rest = empty_spaces' bs rs (n+1) * Quantum data structures type PhaseEstimationRegister = [Qubit] type GenericDirectionRegister a = [a] type DirectionRegister = GenericDirectionRegister Qubit split into 3 main parts . data GenericBooleanFormulaRegister a = BFR { | The position register is split into two parts : the leaf and paraleaf \"flags\ " . position_flags :: (a,a), position :: [GenericDirectionRegister a], work_leaf :: a, work_paraleaf :: a, work_binary :: a, work_height :: a, work_r :: a, work_rp :: a, ^ Seven flags that make up the work register . } deriving (Typeable, Show) type BooleanFormulaRegister = GenericBooleanFormulaRegister Qubit labelBFR :: BooleanFormulaRegister -> Circ () labelBFR reg = do let tuple = toTuple reg label tuple (("pos-leaf","pos-paraleaf"), "pos", ("leaf","paraleaf","binary","height","r","rp","rpp"), "dir") type BoolRegister = GenericBooleanFormulaRegister Bool | Helper function to simplify the ' QCData ' instance for ' BooleanFormulaRegister ' . toTuple :: GenericBooleanFormulaRegister a -> ((a,a),[[a]],(a,a,a,a,a,a,a),[a]) toTuple r = (position_flags r,position r,(work_leaf r,work_paraleaf r,work_binary r,work_height r,work_r r,work_rp r,work_rpp r),direction r) | Helper function to simplify the ' QCData ' instance for ' BooleanFormulaRegister ' . fromTuple :: ((a,a),[[a]],(a,a,a,a,a,a,a),[a]) -> GenericBooleanFormulaRegister a fromTuple (pf,p,(wl,wp,wb,wh,wr,wrp,wrpp),d) = BFR { position_flags = pf, position = p, work_leaf = wl, work_paraleaf = wp, work_binary = wb, work_height = wh, work_r = wr, work_rp = wrp, work_rpp = wrpp, direction = d } type instance QCType x y (GenericBooleanFormulaRegister a) = GenericBooleanFormulaRegister (QCType x y a) type instance QTypeB (GenericBooleanFormulaRegister a) = GenericBooleanFormulaRegister (QTypeB a) instance QCData a => QCData (GenericBooleanFormulaRegister a) where qcdata_mapM s f g xs = mmap fromTuple $ qcdata_mapM (toTuple s) f g (toTuple xs) qcdata_zip s q c q' c' xs ys e = fromTuple $ qcdata_zip (toTuple s) q c q' c' (toTuple xs) (toTuple ys) e qcdata_promote a x s = fromTuple $ qcdata_promote (toTuple a) (toTuple x) s instance (Labelable a String) => Labelable (GenericBooleanFormulaRegister a) String where label_rec r s = do label_rec (position_flags r) s `dotted_indexed` "posflag" label_rec (position r) s `dotted_indexed` "pos" label_rec (work_leaf r) s `dotted_indexed` "leaf" label_rec (work_paraleaf r) s `dotted_indexed` "paraleaf" label_rec (work_binary r) s `dotted_indexed` "binary" label_rec (work_height r) s `dotted_indexed` "height" label_rec (work_r r) s `dotted_indexed` "r" label_rec (work_rp r) s `dotted_indexed` "rp" label_rec (work_rpp r) s `dotted_indexed` "rpp" label_rec (direction r) s `dotted_indexed` "dir" The register is initialized in the /zero/ state that represents being at label , or node /rpp/ in the tree . The work qubits are all initialized to /zero/ , as the first call to the /oracle/ circuit will set them accordingly for the /position/ we are currently in . The /direction/ register is also set to createRegister :: BooleanFormulaOracle -> BoolRegister createRegister oracle = BFR { position_flags = (False,False), position = replicate s (replicate m False), work_leaf = False, work_paraleaf = False, work_binary = False, work_height = False, work_r = False, work_rp = False, work_rpp = False, direction = replicate m False } where s = oracle_s oracle m = oracle_m oracle registerShape :: BooleanFormulaOracle -> BooleanFormulaRegister registerShape oracle = qshape (createRegister oracle) initializeRegister :: BooleanFormulaOracle -> Circ BooleanFormulaRegister initializeRegister oracle = qinit (createRegister oracle) * Oracle implementation formula algorithm into two parts . The first part corresponds to the algorithms defined in this module . The second part consists of the algorithms defined in " Algorithms . " . This separation relates to the first part defining the quantum parts of the algorithm , including the phase estimation , and the quantum walk , whereas the remaining four define using Quipper 's \"build_circuit\ " keyword . phase estimation register into an equal super - position of all 2[sup t ] states , qw_bf :: BooleanFormulaOracle -> Circ [Bit] qw_bf oracle = do let t = oracle_t oracle a <- qinit (replicate t False) label a "a" a <- mapUnary hadamard a b <- initializeRegister oracle labelBFR b we can use a separate recursive function to map the exp_u algorithm over a let t = oracle_t oracle map_exp_u oracle a b (t-1) a <- (subroutine_inverse_qft oracle) a qdiscard b measure a subroutine_inverse_qft :: BooleanFormulaOracle -> [Qubit] -> Circ [Qubit] subroutine_inverse_qft o = box "QFT*" (reverse_generic_endo qft_little_endian) map_exp_u :: BooleanFormulaOracle -> [Qubit] -> BooleanFormulaRegister -> Int -> Circ () map_exp_u _ [] _ _ = return () map_exp_u o (a:as) b l = do let x_max = oracle_x_max o exp_u o (2^(l-(length as))) b `controlled` a map_exp_u o as b l exp_u :: BooleanFormulaOracle -> Integer -> BooleanFormulaRegister -> Circ () exp_u _ 0 _ = return () exp_u o n_steps b = do (subroutine_u o) b exp_u o (n_steps-1) b u :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () u o b = do comment "U" labelBFR b (subroutine_oracle o) b (subroutine_diffuse o) b (subroutine_walk o) b (subroutine_undo_oracle o) b subroutine_u :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_u o = box "U" (u o) we are in the tree . Essentially , the special cases are when were are at one of the three \"low height\ " nodes , or when we are at a node representing a complete oracle :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () oracle o register = do comment "ORACLE" labelBFR register let init = start_board o let x_max = oracle_x_max o let (is_leaf,is_paraleaf) = position_flags register with_controls (is_leaf) do let leaf = work_leaf register qnot_at leaf ) with_controls (is_leaf .==. False .&&. is_paraleaf .==. True) do let paraleaf = work_paraleaf register qnot_at paraleaf let binary = work_binary register qnot_at binary let pos = position register let hex_subroutine = case oracle_hex o of Hex -> box "HEX" (hex_oracle init (oracle_s o) x_max) Dummy -> hex_oracle_dummy EmptyHex -> \x -> return x hex_subroutine (pos,binary) return () ) with_controls (is_leaf .==. False .&&. is_paraleaf .==. False) do let pos = position register with_controls (controls is_paraleaf pos) do let pos'' = pos !! (length pos - 2) let pos_m = last pos'' with_controls pos_m if pos_m = = 1 do let height = work_height register qnot_at height ) let pos' = last pos let pos_1 = pos' !! (length pos' - 2) with_controls (pos_m .==. False .&&. pos_1 .==. True) else if = = 1 do let r = work_r register qnot_at r ) let pos_0 = last pos' with_controls (pos_m .==. False .&&. pos_1 .==. False .&&. pos_0 .==. True) else if pos_0 = = 1 do let rp = work_rp register qnot_at rp let binary = work_binary register qnot_at binary ) with_controls (pos_m .==. False .&&. pos_1 .==. False .&&. pos_0 .==. False) do let rpp = work_rpp register qnot_at rpp ) ) ) subroutine_oracle :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_oracle o = box "Oracle" (oracle o) controls :: Qubit -> [DirectionRegister] -> [ControlList] controls is_paraleaf pos = (is_paraleaf .==. False) : ctrls pos where ctrls [] = [] ctrls [p] = [] ctrls [p,q] = [] ctrls (p:ps) = (last p .==. False) : ctrls ps diffuse :: BooleanFormulaRegister -> Circ () diffuse register = do comment "DIFFUSE" labelBFR register let binary = work_binary register let dir = direction register with_controls binary if binary = = 1 do let dir_0 = last dir hadamard_at dir_0 ) let leaf = work_leaf register let rpp = work_rpp register with_controls (binary .==. False .&&. leaf .==. False .&&. rpp .==. False) do mapUnary hadamard dir ) return () subroutine_diffuse :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_diffuse o = box "Diffuse" diffuse to define what needs to be shifted . This is used as only three different ^ corresponds to shifting only 2 / m/+1 qubits . deriving Eq \"boolean statements\ " over qubits ( see " Algorithms . " ) . walk :: BooleanFormulaRegister -> Circ () walk register = do comment "WALK" labelBFR register let leaf = work_leaf register let paraleaf = work_paraleaf register let dir = direction register let dir_0 = last dir let (is_leaf,is_paraleaf) = position_flags register let pos = position register let pos_0 = last (last pos) let pos_1 = last (init (last pos)) let height_1 = work_height register let rpp = work_rpp register let rp = work_rp register let r = work_r register let dir_all_1 = foldr1 (\x y -> And x y) (map A dir) let boolean_statement_in = Or (A leaf) (And (A paraleaf) (Not (A dir_0))) let boolean_statement_out = Or (A leaf) (And (A paraleaf) (A is_leaf)) if_then_elseQinv boolean_statement_in if leaf = = 1 or ( paraleaf = = 1 and dir_0 = = 0 ) do qnot_at is_leaf ) else ( leaf = = 0 and ( paraleaf = = 0 or dir_0 = = 1 ) ) do let boolean_statement_in = And (A paraleaf) (A dir_0) let boolean_statement_out = And (A paraleaf) (Not (dir_all_1)) if_then_elseQinv boolean_statement_in if paraleaf = = 1 and dir_0 = = 1 toParent Width register now , dir /= 1 .. 1 , so dir_0 could be either 0 or 1 ) do let boolean_statement_in = Or (A rpp) (And (A rp) (A dir_0)) let boolean_statement_out = Or (A rpp) (And (A rp) (Not (A dir_0))) if_then_elseQinv boolean_statement_in if rpp = = 1 or ( rp = = 1 and dir_0 = = 1 ) do qnot_at pos_0 as we 're moving from rp to rpp , and rpp only has a child at 0 or we 're moving from rpp to rp , and dir_0 should be set to 1 as qnot_at dir_0 ) do let boolean_statement_in = Or (And (A rp) (Not (A dir_0))) (And (A r) dir_all_1) let pos_m = last (last (init pos)) let boolean_statement_out = Or (And (A rp) dir_all_1) (And (A r) (And (Not dir_all_1) (Not (A pos_m)))) if_then_elseQinv boolean_statement_in if ( rp = = 1 and dir_0 = = 0 ) or ( r = = 1 and dir = = 1 .. 1 ) do qnot_at pos_1 we know that pos_m = = 0 mapUnary qnot dir return () ) else ( ( rp = = 0 or dir_0 = = 1 ) and ( r = = 0 or dir /= 1 .. 1 ) ) do let boolean_statement = A r if_then_elseQ boolean_statement if r = = 1 do qnot_at pos_1 toChild M register now dir = = 1 .. 1 we also know that pos_m = = 1 ) do let boolean_statement_in = And (A height_1) (dir_all_1) let boolean_statement_out = And (A height_1) (Not dir_all_1) if_then_elseQinv boolean_statement_in if height_1 = = 1 and dir = = 1 .. 1 do toParent M register qnot_at pos_1 now , dir /= 1 .. 1 ) else height_1 = = 0 or dir /= 1 .. 1 do let boolean_statement = A height_1 if_then_elseQ boolean_statement if height_1 = = 1 ( and dir /= 1 .. 1 ) do toChild M2 register now dir = = 1 .. 1 ) do let boolean_statement_in = dir_all_1 let boolean_statement_out = Not dir_all_1 if_then_elseQinv boolean_statement_in if dir = 1 .. 1 do toParent Width register now dir /= 1 .. 1 ) else ( dir /= 1 .. 1 ) do toChild Width register now dir = = 1 .. 1 ) boolean_statement_out ) ) boolean_statement_out ) ) boolean_statement_out ) boolean_statement_out ) boolean_statement_out ) boolean_statement_out return () subroutine_walk :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_walk o = box "Walk" walk undo_oracle :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () undo_oracle o register = do comment "UNDO_ORACLE" labelBFR register let initHB = start_board o let x_max = oracle_x_max o let paraleaf = work_paraleaf register let (is_leaf,is_paraleaf) = position_flags register with_controls paraleaf ( do let binary = work_binary register let pos = position register let dir = direction register let hex_subroutine = case oracle_hex o of Hex -> box "HEX" (hex_oracle initHB (oracle_s o) x_max) Dummy -> hex_oracle_dummy EmptyHex -> \x -> return x hex_subroutine (pos,binary) return () ) let leaf = work_leaf register let dir = direction register let dir_0 = last dir let boolean_statement = And (Not (A is_leaf)) (And (A is_paraleaf) (Not (A dir_0))) if_then_elseQ boolean_statement if is_leaf = = 0 and is_paraleaf = = 1 and dir_0 = = 0 do qnot_at leaf ) do let binary = work_binary register let pos = position register let pos_w_2_m = last (head pos) let dir_all_1 = foldr1 (\x y -> And x y) (map A dir) let boolean_statement = Or (A is_leaf) (And (Not (A is_leaf)) (And (Not (A is_paraleaf)) (And (A pos_w_2_m) (Not (dir_all_1))))) if_then_elseQ boolean_statement if is_leaf = = 1 or ( is_leaf = = 0 and is_paraleaf = = 0 and pos_w_2_m = = 1 and dir /= 1 .. 1 ) do qnot_at binary qnot_at paraleaf ) do with_controls (init (controls is_paraleaf pos)) do let height = work_height register let r = work_r register let rp = work_rp register let pos_0 = last (last pos) let pos_1 = last (init (last pos)) let pos_m = last (last (init pos)) let pos_2m = last (last (init (init pos))) let boolean_statement = dir_all_1 if_then_elseQ boolean_statement if dir = 1 ... 1 do qnot_at height `controlled` pos_2m qnot_at r `controlled` (pos_2m .==. False .&&. pos_m .==. True) with_controls (pos_2m .==. False .&&. pos_m .==. False .&&. pos_1 .==. True) ( do qnot_at rp qnot_at binary ) ) with_controls (pos_2m .==. False .&&. pos_m .==. False) ( do let rpp = work_rpp register qnot_at height `controlled` pos_1 qnot_at rpp `controlled` (pos_1 .==. False .&&. dir_0 .==. True) qnot_at r `controlled` (pos_1 .==. False .&&. dir_0 .==. False .&&. pos_0 .==. True) with_controls (pos_1 .==. False .&&. dir_0 .==. False .&&. pos_0 .==. False) ( do qnot_at rp qnot_at binary ) ) ) ) ) return () subroutine_undo_oracle :: BooleanFormulaOracle -> BooleanFormulaRegister -> Circ () subroutine_undo_oracle o = box "Undo Oracle" (undo_oracle o) toParent :: Where -> BooleanFormulaRegister -> Circ () toParent M2 _ = error "TOPARENT should never be called with 2m+1 as width" toParent w register = do let pos_0 = last pos_firstM :: Qubit let pos_m = last pos_secondM :: Qubit let (_,is_paraleaf) = position_flags register :: (Qubit,Qubit) mapUnary qnot dir mapBinary copy_from_to (reverse pos_firstM) (reverse dir) if (w == Width) then shift_right pos we need to shift is_paraleaf to x*y*m copy_from_to is_paraleaf (last (head pos)) return () ) else return () if (w == M) then m+1 we need to " shift " pos_m to pos_0 copy_from_to pos_m pos_0 return () ) else return () It falls short of swapping /a/ and /b/ , as we 're not interested in preserving /a/. copy_from_to :: Qubit -> Qubit -> Circ (Qubit,Qubit) copy_from_to from to = do qnot_at to `controlled` from qnot_at from `controlled` to return (from,to) toChild :: Where -> BooleanFormulaRegister -> Circ () toChild w register = do let pos_0 = last pos_firstM :: Qubit let pos_m = last pos_secondM :: Qubit let pos_2m = last pos_thirdM :: Qubit let (_,is_paraleaf) = position_flags register :: (Qubit,Qubit) if (w == Width) then copy_from_to (last (head pos)) is_paraleaf shift_left pos ) else return () if (w == M2) then 2m+1 copy_from_to pos_m pos_2m shift_left [pos_secondM,pos_firstM] ) else return () if (w == M) then ( do we need to " shift " pos_0 to pos_m copy_from_to pos_0 pos_m return () ) else return () mapBinary copy_from_to dir pos_firstM mapUnary qnot dir return () shift_left :: [DirectionRegister] -> Circ () shift_left [] = return () shift_left [d] = return () shift_left (d:d':ds) = do mapBinary copy_from_to d' d shift_left (d':ds) shift_right :: [DirectionRegister] -> Circ () shift_right [] = return () shift_right [d] = return () shift_right (d:d':ds) = do shift_right (d':ds) mapBinary copy_from_to (reverse d) (reverse d') return () overall Boolean Formula Algorithm . The Boolean Formula Algorithm is split into 13 sub - algorithms , each of which can be main_circuit :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_circuit f g oracle = print_simple f (decompose_generic g (qw_bf oracle)) | Display just 1 time - step of the given oracle , i.e. , one iteration of the ' u ' from ' exp_u ' , with no controls . main_u :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_u f g o = print_generic f (decompose_generic g (u o)) (registerShape o) | Display just 1 time - step of the ' walk ' algorithm for the given oracle , i.e. , one iteration of /walk/ , with no controls . main_walk :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_walk f g o = print_generic f (decompose_generic g walk) (registerShape o) | Display just 1 time - step of the ' diffuse ' algorithm for the given oracle , i.e. , one iteration of /diffuse/ , with no controls . main_diffuse :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_diffuse f g o = print_generic f (decompose_generic g diffuse) (registerShape o) | Display just 1 time - step of the ' oracle ' algorithm for the given oracle , i.e. , one iteration of /oracle/ , with no controls . main_oracle :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_oracle f g o = print_generic f (decompose_generic g (oracle o)) (registerShape o) | Display just 1 time - step of the ' undo_oracle ' algorithm for the given oracle , i.e. , one iteration of /undo_oracle/ , with no controls . main_undo_oracle :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_undo_oracle f g o = print_generic f (decompose_generic g (undo_oracle o)) (registerShape o) i.e. , one iteration of ' hex_oracle ' , with no controls . main_hex :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_hex f g o = print_generic f (decompose_generic g (hex_oracle init s x_max)) (pos,binary) where init = start_board o s = oracle_s o x_max = oracle_x_max o reg = registerShape o pos = position reg binary = work_binary reg i.e. , one iteration of ' checkwin_red_circuit ' , with no controls . main_checkwin_red :: Format -> GateBase -> BooleanFormulaOracle -> IO () main_checkwin_red f g o = print_generic f (decompose_generic g (checkwin_red_circuit x_max)) (qshape redboard,qubit) where (redboard,_) = start_board o x_max = oracle_x_max o $ The following functions define the way that the Boolean Formula Algorithm be all False only in the instance that the Blue player wins the game . main_bf :: BooleanFormulaOracle -> IO Bool main_bf oracle = do output <- run_generic_io (undefined :: Double) (qw_bf oracle) a = = 0 ( Blue Wins ) return result | Display the result of ' ' , whoWins :: BooleanFormulaOracle -> IO () whoWins oracle = do result <- main_bf oracle if result then putStrLn "Red Wins" else putStrLn "Blue Wins" | Run ' whoWins ' for the given oracle , and its \"initial\ " board . main_whoWins :: BooleanFormulaOracle -> IO () main_whoWins o = whoWins o
7a9a334e7fd8a115a02d9a6a49144fbd9d9a01c9b77489305c96f4ad069932b8
heraldry/heraldicon
humetty.cljs
(ns heraldicon.heraldry.ordinary.humetty (:require [heraldicon.context :as c] [heraldicon.heraldry.field.environment :as environment] [heraldicon.interface :as interface])) (defn options [context] (let [humetty? (interface/get-raw-data (c/++ context :humetty?))] (cond-> {:humetty? {:type :option.type/boolean :ui/label :string.option/humetty} :ui/label :string.option/humetty :ui/tooltip :string.tooltip/humetty-warning :ui/element :ui.element/humetty} humetty? (assoc :corner {:type :option.type/choice :choices [[:string.option.corner-choice/round :round] [:string.option.corner-choice/sharp :sharp] [:string.option.corner-choice/bevel :bevel]] :default :round :ui/label :string.option/corner} :distance {:type :option.type/range :min 1 :max 45 :default 5 :ui/label :string.option/distance})))) (defn coup [shape parent-shape {:keys [humetty? distance corner]}] (if humetty? (let [shape (if (vector? shape) shape [shape]) shrunken-environment-shape (environment/shrink-shape parent-shape distance corner) shrink (fn shrink [path] (environment/intersect-shapes path shrunken-environment-shape))] (if (vector? shape) (mapv shrink shape) (shrink shape))) shape))
null
https://raw.githubusercontent.com/heraldry/heraldicon/3b52869f611023b496a29473a98c35ca89262aab/src/heraldicon/heraldry/ordinary/humetty.cljs
clojure
(ns heraldicon.heraldry.ordinary.humetty (:require [heraldicon.context :as c] [heraldicon.heraldry.field.environment :as environment] [heraldicon.interface :as interface])) (defn options [context] (let [humetty? (interface/get-raw-data (c/++ context :humetty?))] (cond-> {:humetty? {:type :option.type/boolean :ui/label :string.option/humetty} :ui/label :string.option/humetty :ui/tooltip :string.tooltip/humetty-warning :ui/element :ui.element/humetty} humetty? (assoc :corner {:type :option.type/choice :choices [[:string.option.corner-choice/round :round] [:string.option.corner-choice/sharp :sharp] [:string.option.corner-choice/bevel :bevel]] :default :round :ui/label :string.option/corner} :distance {:type :option.type/range :min 1 :max 45 :default 5 :ui/label :string.option/distance})))) (defn coup [shape parent-shape {:keys [humetty? distance corner]}] (if humetty? (let [shape (if (vector? shape) shape [shape]) shrunken-environment-shape (environment/shrink-shape parent-shape distance corner) shrink (fn shrink [path] (environment/intersect-shapes path shrunken-environment-shape))] (if (vector? shape) (mapv shrink shape) (shrink shape))) shape))
d4685a43d81796e5d3c1a516bdbe9b6194c32fc6bc75e2de2b8ab8f39e369315
discus-lang/salt
Term.hs
module Salt.Core.Codec.Text.Pretty.Term where import Salt.Core.Codec.Text.Pretty.Type import Salt.Core.Codec.Text.Pretty.Base import Salt.Core.Exp import Salt.Data.Pretty import qualified Data.Set as Set import qualified Data.Map as Map ------------------------------------------------------------------------------------------- Term -- instance Pretty c (Term a) where ppr c m = pprTerm c m pprTerm :: c -> Term a -> Doc pprTerm c (MAnn _ m) = ppr c m pprTerm c (MRef r) = ppr c r pprTerm c (MVar u) = ppr c u pprTerm c (MAbs p m) | isSomeMProc m = align $ text "λ" % ppr c p %% text "→" % line % ppr c m | otherwise = text "λ" % ppr c p %% text "→" %% ppr c m pprTerm c (MRec bms mBody) = text "rec" %% braced (map (ppr c) bms) %% text "in" %% ppr c mBody -- terms pprTerm c (MTerms ms) = squared (map (ppr c) ms) -- the pprTerm c (MThe [t] m) = align $ text "the" %% ppr c t %% text "of" %% line % ppr c m pprTerm c (MThe ts m) = align $ text "the" %% squared (map (ppr c) ts ) %% text "of" %% line % ppr c m -- app pprTerm c (MAps mFun mgssArg) = pprMFun c mFun %% hcat (punctuate (text " ") $ map (pprMArgs c) mgssArg) -- let pprTerm c (MLet mps mBind mBody) | Just bts <- takeMPTerms mps = let pp (b, THole) = ppr c b pp (b, t) = ppr c b % text ":" %% ppr c t in case bts of [bt] -> text "let" %% pp bt %% text "=" %% ppr c mBind % text ";" %% ppr c mBody _ -> text "let" %% squared (map pp bts) %% text "=" %% ppr c mBind % text ";" %% ppr c mBody -- record / project pprTerm c (MRecord ns ms) | length ns == length ms = text "∏" % squared [ pprLbl n %% text "=" %% ppr c m | n <- ns | m <- ms ] pprTerm c (MProject l m) = pprMArg c m % text "." % pprLbl l variant / pprTerm c (MVariant l m t) = text "the" %% ppr c t %% text "of" %% text "`" % pprLbl l %% pprMArg c m pprTerm c (MVarCase mScrut msAlt []) = text "case" %% ppr c mScrut %% text "of" %% braced (map (pprMAlt c) msAlt) pprTerm c (MVarCase mScrut msAlt [mElse]) = text "case" %% ppr c mScrut %% text "of" %% braced (map (pprMAlt c) msAlt) %% text "else" %% ppr c mElse -- data pprTerm c (MData n ts ms) = pprCon n %% hsep (map (pprTArg c) ts) %% hsep (map (pprMArg c) ms) -- box / run pprTerm c (MBox m) = text "box" %% ppr c m pprTerm c (MRun m) = text "run" %% ppr c m -- list / set / map pprTerm c (MList t ms) = brackets $ text "list" %% pprTArg c t % text "| " % hcat (punctuate (text ", ") (map (ppr c) ms)) pprTerm c (MSet t ms) = brackets $ text "set" %% pprTArg c t % text "| " % hcat (punctuate (text ", ") (map (ppr c) ms)) pprTerm c (MMap tk tv msKey msVal) = brackets $ text "map" %% pprTArg c tk %% pprTArg c tv % text "| " % hcat (punctuate (text ", ") [ ppr c mk %% text ":=" %% ppr c mv | mk <- msKey | mv <- msVal ]) -- proc launch / return pprTerm c (MLaunch tsRet mRest) = align $ text "launch" %% squared (map (ppr c) tsRet) %% text "of" %% line % ppr c mRest pprTerm c (MReturn mRet) = text "return" %% ppr c mRet -- proc cell / update pprTerm c (MCell nCell tCell mInit mRest) = align $ text "cell" %% pprVar nCell % text ":" %% ppr c tCell %% text "←" %% ppr c mInit % semi %% line % ppr c mRest pprTerm c (MUpdate nCell mValue mRest) = align $ text "update" %% pprVar nCell %% text "←" %% ppr c mValue % semi %% line % ppr c mRest -- proc when / whens pprTerm c (MWhens [mCond] [mThen] mRest) = align $ text "when" %% pprMArg c mCond %% ppr c mThen % semi %% line % ppr c mRest -- proc loop / break / continue pprTerm c (MLoop mBody mRest) = align $ text "loop" %% pprMArg c mBody % semi %% line % ppr c mRest pprTerm _c MBreak = text "break" pprTerm _c MContinue = text "continue" -- key pprTerm c (MKey k mgs) = ppr c k %% (hsep $ map (ppr c) mgs) pprMFun c mm = case mm of MAnn _ m -> pprMFun c m MRef{} -> ppr c mm MVar{} -> ppr c mm MApp{} -> ppr c mm MAbs{} -> parens $ ppr c mm MRec{} -> parens $ ppr c mm MTerms{} -> ppr c mm MRecord{} -> ppr c mm MProject{} -> ppr c mm MList{} -> ppr c mm MSet{} -> ppr c mm MMap{} -> ppr c mm MKey{} -> parens $ ppr c mm pprMArg c mm = case mm of MAnn _ m -> pprMArg c m MRef{} -> ppr c mm MVar{} -> ppr c mm MAbs{} -> parens $ ppr c mm MRec{} -> parens $ ppr c mm MTerms{} -> ppr c mm MRecord{} -> ppr c mm MProject{} -> ppr c mm MList{} -> ppr c mm MSet{} -> ppr c mm MMap{} -> ppr c mm MKey{} -> parens $ ppr c mm pprMAlt c mm = case mm of MVarAlt n mps mBody | Just bts <- takeMPTerms mps -> pprLbl n %% squared [ppr c b % text ":" %% ppr c t | (b, t) <- bts] %% text "→" %% ppr c mBody _ -> parens (ppr c mm) pprMArgs :: c -> TermArgs a -> Doc pprMArgs c mgs = case mgs of MGAnn _ mgs' -> pprMArgs c mgs' MGTerm m -> pprMArg c m MGTerms [m] -> pprMArg c m MGTerms ms -> squared $ map (pprTerm c) ms MGTypes [t] -> text "@" % pprTArg c t MGTypes ts -> text "@" % (squared $ map (pprTArg c) ts) --------------------------------------------------------------------------------------- TermBind -- instance Pretty c (TermBind a) where ppr c (MBind b mpss tResult mBind) = ppr c b %% hcat (map (ppr c) mpss) % text ":" %% ppr c tResult %% text "=" %% ppr c mBind ---------------------------------------------------------------------------------------- TermRef -- instance Pretty c (TermRef a) where ppr c mr = case mr of MRVal v -> ppr c v MRPrm n -> pprPrm n MRCon n -> text "%" % pprCon n ------------------------------------------------------------------------------ TermParams / Args -- instance Pretty c (TermParams a) where ppr c mp = case mp of MPAnn _ mps -> ppr c mps MPTerms nts -> squared [ ppr c n % text ":" %% ppr c t | (n, t) <- nts] MPTypes nts -> text "@" % squared [ ppr c n % text ":" %% ppr c t | (n, t) <- nts] instance Pretty c (TermArgs a) where ppr c ma = case ma of MGAnn _ mgs -> ppr c mgs MGTerm m -> parens $ ppr c m MGTerms ms -> squared $ map (ppr c) ms MGTypes ts -> text "@" % (squared $ map (ppr c) ts) ---------------------------------------------------------------------------------------- TermKey -- instance Pretty c TermKey where ppr _ mk = case mk of MKTerms -> text "##terms" MKThe -> text "##the" MKApp -> text "##app" MKLet -> text "##let" MKPrivate -> text "##private" MKExtend -> text "##extend" MKPack -> text "##pack" MKUnpack -> text "##unpack" MKCon n -> text "##con" %% pprCon n MKRecord ns -> text "##record" %% braced (map pprCon ns) MKProject n -> text "##project" %% pprLbl n MKVariant n -> text "##variant" %% pprCon n MKVarCase -> text "##var'case" MKVarAlt n -> text "##var'alt" %% pprLbl n MKIf -> text "##if" MKBox -> text "##box" MKRun -> text "##run" MKList -> text "##list" MKSet -> text "##set" MKMap -> text "##map" MKSeq -> text "##seq" MKLaunch -> text "##launch" MKReturn -> text "##return" MKCell -> text "##cell" MKUpdate -> text "##update" MKWhens -> text "##whens" MKMatch -> text "##match" MKLoop -> text "##loop" MKBreak -> text "##break" MKContinue -> text "##continue" MKWhile -> text "##while" MKEnter -> text "##enter" MKLeave -> text "##leave" ------------------------------------------------------------------------------------ TermClosure -- instance Pretty c (TermClosure a) where ppr c (TermClosure (TermEnv []) ps m) | isSomeMProc m = bracketed' "mclo_" [ align $ text "λ" % ppr c ps %% text "→" % line % ppr c m ] | otherwise = bracketed' "mclo_" [ text "λ" % ppr c ps %% text "→" %% ppr c m ] ppr c (TermClosure env ps m) | isSomeMProc m = bracketed' "mclo" [ ppr c env , align $ text "λ" % ppr c ps %% text "→" % line % ppr c m ] | otherwise = bracketed' "mclo" [ ppr c env , text "λ" % ppr c ps %% text "→" %% ppr c m ] ------------------------------------------------------------------------------ TermEnv / Binds -- instance Pretty c (TermEnv a) where ppr c (TermEnv ebs) = bracketed' "menv" (punctuate (text " ") $ map (ppr c) ebs) instance Pretty c (TermEnvBinds a) where ppr c eb = case eb of TermEnvTypes nts -> text "@" % squared [ pprVar n %% text "=" %% ppr c t | (n, t) <- Map.toList nts ] TermEnvValues nvs -> squared [ pprVar n %% text "=" %% ppr c v | (n, v) <- Map.toList nvs ] TermEnvValuesRec ncs -> text "μ" % squared [ pprVar n %% text "=" %% ppr c v | (n, v) <- Map.toList ncs ] ------------------------------------------------------------------------------------------ Value -- instance Pretty c (Value a) where ppr c = \case VUnit -> text "#unit" VSymbol s -> pprSym s VText tx -> string $ show tx VBool b -> case b of True -> text "#true" False -> text "#false" VNat i -> string $ show i VInt i -> string $ show i VWord i -> string $ show i VInt8 i -> string $ show i VInt16 i -> string $ show i VInt32 i -> string $ show i VInt64 i -> string $ show i VWord8 i -> string $ show i VWord16 i -> string $ show i VWord32 i -> string $ show i VWord64 i -> string $ show i VData n ts vs -> pprCon n %% hsep (map (pprTArg c) ts) %% hsep (map (pprVArg c) vs) VRecord nvs -> bracketed [ pprLbl n %% text "=" %% ppr c v | (n, v) <- nvs ] VVariant n t vs -> text "the" %% ppr c t %% text "of" %% text "`" % pprLbl n %% squared (map (ppr c) vs) VList t vs -> brackets $ text "list" %% pprTArg c t % text "| " % hcat (punctuate (text ", ") (map (ppr c) vs)) VSet t vs -> brackets $ text "set" %% pprTArg c t % text "| " % hcat (punctuate (text ", ") (map (ppr c) $ Set.toList vs)) VMap tk tv kvs -> brackets $ text "map" %% pprTArg c tk %% pprTArg c tv % text "| " % hcat (punctuate (text ", ") [ ppr c vk %% text ":=" %% ppr c vv | (vk, vv) <- Map.toList kvs ]) VClosure clo -> ppr c clo VBundle bun -> ppr c bun VLoc t i -> brackets $ text "#loc" %% pprTArg c t %% int i VAddr a -> brackets $ text "address" % string (show a) VPtr r t a -> brackets $ text "pointer" %% pprTArg c r %% pprTArg c t % string (show a) { Value , , Ascription } VExtPair v t a -> brackets $ text "pack" %% pprVArg c v %% text "with" %% squared (map (ppr c) t) %% text "as" %% ppr c a pprVArg c vv = case vv of VData{} -> parens $ ppr c vv VVariant{} -> parens $ ppr c vv _ -> ppr c vv ----------------------------------------------------------------------------------------- Bundle -- instance Pretty c (Bundle a) where ppr c (Bundle nts nms) = brackets $ align $ text "bundle|" % line % vcat (punctuate (text ",") ( (map (ppr c) $ Map.elems nts) ++ (map (ppr c) $ Map.elems nms))) instance Pretty c (BundleType a) where ppr c (BundleType _a n tpsParam kResult tBody) = vcat [ text "type" %% pprVar n %% hcat (map (ppr c) tpsParam) % text ":" %% ppr c kResult , text " = " % (align $ ppr c tBody) ] instance Pretty c (BundleTerm a) where ppr c (BundleTerm _a n tmsParam tResult mBody) = vcat [ text "term" %% pprVar n %% hcat (map (ppr c) tmsParam) % text ":" %% ppr c tResult , text " = " % (align $ ppr c mBody) ] -- | Pretty print the guts of a bundle, with declarations on sequential -- lines, without the `[bundle| ]` wrapper. ppBundleGuts :: Bundle a -> Doc ppBundleGuts (Bundle nts nms) = vcat ( (map (ppr ()) $ Map.elems nts) ++ (map (ppr ()) $ Map.elems nms))
null
https://raw.githubusercontent.com/discus-lang/salt/33c14414ac7e238fdbd8161971b8b8ac67fff569/src/salt/Salt/Core/Codec/Text/Pretty/Term.hs
haskell
----------------------------------------------------------------------------------------- Term -- terms the app let record / project data box / run list / set / map proc launch / return proc cell / update proc when / whens proc loop / break / continue key ------------------------------------------------------------------------------------- TermBind -- -------------------------------------------------------------------------------------- TermRef -- ---------------------------------------------------------------------------- TermParams / Args -- -------------------------------------------------------------------------------------- TermKey -- ---------------------------------------------------------------------------------- TermClosure -- ---------------------------------------------------------------------------- TermEnv / Binds -- ---------------------------------------------------------------------------------------- Value -- --------------------------------------------------------------------------------------- Bundle -- | Pretty print the guts of a bundle, with declarations on sequential lines, without the `[bundle| ]` wrapper.
module Salt.Core.Codec.Text.Pretty.Term where import Salt.Core.Codec.Text.Pretty.Type import Salt.Core.Codec.Text.Pretty.Base import Salt.Core.Exp import Salt.Data.Pretty import qualified Data.Set as Set import qualified Data.Map as Map instance Pretty c (Term a) where ppr c m = pprTerm c m pprTerm :: c -> Term a -> Doc pprTerm c (MAnn _ m) = ppr c m pprTerm c (MRef r) = ppr c r pprTerm c (MVar u) = ppr c u pprTerm c (MAbs p m) | isSomeMProc m = align $ text "λ" % ppr c p %% text "→" % line % ppr c m | otherwise = text "λ" % ppr c p %% text "→" %% ppr c m pprTerm c (MRec bms mBody) = text "rec" %% braced (map (ppr c) bms) %% text "in" %% ppr c mBody pprTerm c (MTerms ms) = squared (map (ppr c) ms) pprTerm c (MThe [t] m) = align $ text "the" %% ppr c t %% text "of" %% line % ppr c m pprTerm c (MThe ts m) = align $ text "the" %% squared (map (ppr c) ts ) %% text "of" %% line % ppr c m pprTerm c (MAps mFun mgssArg) = pprMFun c mFun %% hcat (punctuate (text " ") $ map (pprMArgs c) mgssArg) pprTerm c (MLet mps mBind mBody) | Just bts <- takeMPTerms mps = let pp (b, THole) = ppr c b pp (b, t) = ppr c b % text ":" %% ppr c t in case bts of [bt] -> text "let" %% pp bt %% text "=" %% ppr c mBind % text ";" %% ppr c mBody _ -> text "let" %% squared (map pp bts) %% text "=" %% ppr c mBind % text ";" %% ppr c mBody pprTerm c (MRecord ns ms) | length ns == length ms = text "∏" % squared [ pprLbl n %% text "=" %% ppr c m | n <- ns | m <- ms ] pprTerm c (MProject l m) = pprMArg c m % text "." % pprLbl l variant / pprTerm c (MVariant l m t) = text "the" %% ppr c t %% text "of" %% text "`" % pprLbl l %% pprMArg c m pprTerm c (MVarCase mScrut msAlt []) = text "case" %% ppr c mScrut %% text "of" %% braced (map (pprMAlt c) msAlt) pprTerm c (MVarCase mScrut msAlt [mElse]) = text "case" %% ppr c mScrut %% text "of" %% braced (map (pprMAlt c) msAlt) %% text "else" %% ppr c mElse pprTerm c (MData n ts ms) = pprCon n %% hsep (map (pprTArg c) ts) %% hsep (map (pprMArg c) ms) pprTerm c (MBox m) = text "box" %% ppr c m pprTerm c (MRun m) = text "run" %% ppr c m pprTerm c (MList t ms) = brackets $ text "list" %% pprTArg c t % text "| " % hcat (punctuate (text ", ") (map (ppr c) ms)) pprTerm c (MSet t ms) = brackets $ text "set" %% pprTArg c t % text "| " % hcat (punctuate (text ", ") (map (ppr c) ms)) pprTerm c (MMap tk tv msKey msVal) = brackets $ text "map" %% pprTArg c tk %% pprTArg c tv % text "| " % hcat (punctuate (text ", ") [ ppr c mk %% text ":=" %% ppr c mv | mk <- msKey | mv <- msVal ]) pprTerm c (MLaunch tsRet mRest) = align $ text "launch" %% squared (map (ppr c) tsRet) %% text "of" %% line % ppr c mRest pprTerm c (MReturn mRet) = text "return" %% ppr c mRet pprTerm c (MCell nCell tCell mInit mRest) = align $ text "cell" %% pprVar nCell % text ":" %% ppr c tCell %% text "←" %% ppr c mInit % semi %% line % ppr c mRest pprTerm c (MUpdate nCell mValue mRest) = align $ text "update" %% pprVar nCell %% text "←" %% ppr c mValue % semi %% line % ppr c mRest pprTerm c (MWhens [mCond] [mThen] mRest) = align $ text "when" %% pprMArg c mCond %% ppr c mThen % semi %% line % ppr c mRest pprTerm c (MLoop mBody mRest) = align $ text "loop" %% pprMArg c mBody % semi %% line % ppr c mRest pprTerm _c MBreak = text "break" pprTerm _c MContinue = text "continue" pprTerm c (MKey k mgs) = ppr c k %% (hsep $ map (ppr c) mgs) pprMFun c mm = case mm of MAnn _ m -> pprMFun c m MRef{} -> ppr c mm MVar{} -> ppr c mm MApp{} -> ppr c mm MAbs{} -> parens $ ppr c mm MRec{} -> parens $ ppr c mm MTerms{} -> ppr c mm MRecord{} -> ppr c mm MProject{} -> ppr c mm MList{} -> ppr c mm MSet{} -> ppr c mm MMap{} -> ppr c mm MKey{} -> parens $ ppr c mm pprMArg c mm = case mm of MAnn _ m -> pprMArg c m MRef{} -> ppr c mm MVar{} -> ppr c mm MAbs{} -> parens $ ppr c mm MRec{} -> parens $ ppr c mm MTerms{} -> ppr c mm MRecord{} -> ppr c mm MProject{} -> ppr c mm MList{} -> ppr c mm MSet{} -> ppr c mm MMap{} -> ppr c mm MKey{} -> parens $ ppr c mm pprMAlt c mm = case mm of MVarAlt n mps mBody | Just bts <- takeMPTerms mps -> pprLbl n %% squared [ppr c b % text ":" %% ppr c t | (b, t) <- bts] %% text "→" %% ppr c mBody _ -> parens (ppr c mm) pprMArgs :: c -> TermArgs a -> Doc pprMArgs c mgs = case mgs of MGAnn _ mgs' -> pprMArgs c mgs' MGTerm m -> pprMArg c m MGTerms [m] -> pprMArg c m MGTerms ms -> squared $ map (pprTerm c) ms MGTypes [t] -> text "@" % pprTArg c t MGTypes ts -> text "@" % (squared $ map (pprTArg c) ts) instance Pretty c (TermBind a) where ppr c (MBind b mpss tResult mBind) = ppr c b %% hcat (map (ppr c) mpss) % text ":" %% ppr c tResult %% text "=" %% ppr c mBind instance Pretty c (TermRef a) where ppr c mr = case mr of MRVal v -> ppr c v MRPrm n -> pprPrm n MRCon n -> text "%" % pprCon n instance Pretty c (TermParams a) where ppr c mp = case mp of MPAnn _ mps -> ppr c mps MPTerms nts -> squared [ ppr c n % text ":" %% ppr c t | (n, t) <- nts] MPTypes nts -> text "@" % squared [ ppr c n % text ":" %% ppr c t | (n, t) <- nts] instance Pretty c (TermArgs a) where ppr c ma = case ma of MGAnn _ mgs -> ppr c mgs MGTerm m -> parens $ ppr c m MGTerms ms -> squared $ map (ppr c) ms MGTypes ts -> text "@" % (squared $ map (ppr c) ts) instance Pretty c TermKey where ppr _ mk = case mk of MKTerms -> text "##terms" MKThe -> text "##the" MKApp -> text "##app" MKLet -> text "##let" MKPrivate -> text "##private" MKExtend -> text "##extend" MKPack -> text "##pack" MKUnpack -> text "##unpack" MKCon n -> text "##con" %% pprCon n MKRecord ns -> text "##record" %% braced (map pprCon ns) MKProject n -> text "##project" %% pprLbl n MKVariant n -> text "##variant" %% pprCon n MKVarCase -> text "##var'case" MKVarAlt n -> text "##var'alt" %% pprLbl n MKIf -> text "##if" MKBox -> text "##box" MKRun -> text "##run" MKList -> text "##list" MKSet -> text "##set" MKMap -> text "##map" MKSeq -> text "##seq" MKLaunch -> text "##launch" MKReturn -> text "##return" MKCell -> text "##cell" MKUpdate -> text "##update" MKWhens -> text "##whens" MKMatch -> text "##match" MKLoop -> text "##loop" MKBreak -> text "##break" MKContinue -> text "##continue" MKWhile -> text "##while" MKEnter -> text "##enter" MKLeave -> text "##leave" instance Pretty c (TermClosure a) where ppr c (TermClosure (TermEnv []) ps m) | isSomeMProc m = bracketed' "mclo_" [ align $ text "λ" % ppr c ps %% text "→" % line % ppr c m ] | otherwise = bracketed' "mclo_" [ text "λ" % ppr c ps %% text "→" %% ppr c m ] ppr c (TermClosure env ps m) | isSomeMProc m = bracketed' "mclo" [ ppr c env , align $ text "λ" % ppr c ps %% text "→" % line % ppr c m ] | otherwise = bracketed' "mclo" [ ppr c env , text "λ" % ppr c ps %% text "→" %% ppr c m ] instance Pretty c (TermEnv a) where ppr c (TermEnv ebs) = bracketed' "menv" (punctuate (text " ") $ map (ppr c) ebs) instance Pretty c (TermEnvBinds a) where ppr c eb = case eb of TermEnvTypes nts -> text "@" % squared [ pprVar n %% text "=" %% ppr c t | (n, t) <- Map.toList nts ] TermEnvValues nvs -> squared [ pprVar n %% text "=" %% ppr c v | (n, v) <- Map.toList nvs ] TermEnvValuesRec ncs -> text "μ" % squared [ pprVar n %% text "=" %% ppr c v | (n, v) <- Map.toList ncs ] instance Pretty c (Value a) where ppr c = \case VUnit -> text "#unit" VSymbol s -> pprSym s VText tx -> string $ show tx VBool b -> case b of True -> text "#true" False -> text "#false" VNat i -> string $ show i VInt i -> string $ show i VWord i -> string $ show i VInt8 i -> string $ show i VInt16 i -> string $ show i VInt32 i -> string $ show i VInt64 i -> string $ show i VWord8 i -> string $ show i VWord16 i -> string $ show i VWord32 i -> string $ show i VWord64 i -> string $ show i VData n ts vs -> pprCon n %% hsep (map (pprTArg c) ts) %% hsep (map (pprVArg c) vs) VRecord nvs -> bracketed [ pprLbl n %% text "=" %% ppr c v | (n, v) <- nvs ] VVariant n t vs -> text "the" %% ppr c t %% text "of" %% text "`" % pprLbl n %% squared (map (ppr c) vs) VList t vs -> brackets $ text "list" %% pprTArg c t % text "| " % hcat (punctuate (text ", ") (map (ppr c) vs)) VSet t vs -> brackets $ text "set" %% pprTArg c t % text "| " % hcat (punctuate (text ", ") (map (ppr c) $ Set.toList vs)) VMap tk tv kvs -> brackets $ text "map" %% pprTArg c tk %% pprTArg c tv % text "| " % hcat (punctuate (text ", ") [ ppr c vk %% text ":=" %% ppr c vv | (vk, vv) <- Map.toList kvs ]) VClosure clo -> ppr c clo VBundle bun -> ppr c bun VLoc t i -> brackets $ text "#loc" %% pprTArg c t %% int i VAddr a -> brackets $ text "address" % string (show a) VPtr r t a -> brackets $ text "pointer" %% pprTArg c r %% pprTArg c t % string (show a) { Value , , Ascription } VExtPair v t a -> brackets $ text "pack" %% pprVArg c v %% text "with" %% squared (map (ppr c) t) %% text "as" %% ppr c a pprVArg c vv = case vv of VData{} -> parens $ ppr c vv VVariant{} -> parens $ ppr c vv _ -> ppr c vv instance Pretty c (Bundle a) where ppr c (Bundle nts nms) = brackets $ align $ text "bundle|" % line % vcat (punctuate (text ",") ( (map (ppr c) $ Map.elems nts) ++ (map (ppr c) $ Map.elems nms))) instance Pretty c (BundleType a) where ppr c (BundleType _a n tpsParam kResult tBody) = vcat [ text "type" %% pprVar n %% hcat (map (ppr c) tpsParam) % text ":" %% ppr c kResult , text " = " % (align $ ppr c tBody) ] instance Pretty c (BundleTerm a) where ppr c (BundleTerm _a n tmsParam tResult mBody) = vcat [ text "term" %% pprVar n %% hcat (map (ppr c) tmsParam) % text ":" %% ppr c tResult , text " = " % (align $ ppr c mBody) ] ppBundleGuts :: Bundle a -> Doc ppBundleGuts (Bundle nts nms) = vcat ( (map (ppr ()) $ Map.elems nts) ++ (map (ppr ()) $ Map.elems nms))
9eac7fdc8ee545a6d217c57236e9c067f9c9e5dcf4cd1cd5d1ab367430940594
matterhorn-chat/matterhorn
Channels.hs
# LANGUAGE LambdaCase # {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE RankNTypes #-} module Matterhorn.State.Channels ( updateViewed , refreshChannel , refreshChannelsAndUsers , setFocus , refreshChannelById , applyPreferenceChange , leaveChannel , leaveCurrentChannel , getNextUnreadChannel , getNextUnreadUserOrChannel , nextUnreadChannel , nextUnreadUserOrChannel , createOrFocusDMChannel , prevChannel , nextChannel , recentChannel , setReturnChannel , resetReturnChannel , hideDMChannel , createGroupChannel , showGroupChannelPref , inputHistoryForward , inputHistoryBackward , handleNewChannel , createOrdinaryChannel , handleChannelInvite , addUserByNameToCurrentChannel , addUserToCurrentChannel , removeUserFromCurrentChannel , removeChannelFromState , isRecentChannel , isReturnChannel , isCurrentChannel , deleteCurrentChannel , startLeaveCurrentChannel , joinChannel , joinChannel' , joinChannelByName , changeChannelByName , setChannelTopic , getCurrentChannelTopic , beginCurrentChannelDeleteConfirm , toggleExpandedChannelTopics , updateChannelNotifyProps , renameChannelUrl , toggleChannelFavoriteStatus , toggleChannelListGroupVisibility , toggleCurrentChannelChannelListGroup , toggleCurrentChannelChannelListGroupByName , cycleChannelListSortingMode ) where import Prelude () import Matterhorn.Prelude import Brick.Main ( invalidateCache, invalidateCacheEntry , makeVisible, vScrollToBeginning , viewportScroll ) import Brick.Widgets.Edit ( applyEdit, getEditContents, editContentsL ) import Control.Concurrent.Async ( runConcurrently, Concurrently(..) ) import Control.Exception ( SomeException, try ) import Data.Char ( isAlphaNum ) import qualified Data.HashMap.Strict as HM import qualified Data.Foldable as F import Data.List ( nub ) import Data.Maybe ( fromJust ) import qualified Data.Set as S import qualified Data.Sequence as Seq import qualified Data.Text as T import Data.Text.Zipper ( textZipper, clearZipper, insertMany, gotoEOL ) import Data.Time.Clock ( getCurrentTime ) import Lens.Micro.Platform import qualified Network.Mattermost.Endpoints as MM import Network.Mattermost.Lenses hiding ( Lens' ) import Network.Mattermost.Types import Matterhorn.Constants ( normalChannelSigil ) import Matterhorn.InputHistory import Matterhorn.State.Common import {-# SOURCE #-} Matterhorn.State.Messages ( fetchVisibleIfNeeded ) import Matterhorn.State.ChannelList import Matterhorn.State.Users import {-# SOURCE #-} Matterhorn.State.Teams import Matterhorn.State.Flagging import Matterhorn.Types import Matterhorn.Types.Common import Matterhorn.Zipper ( Zipper ) import qualified Matterhorn.Zipper as Z updateViewed :: Bool -> MH () updateViewed updatePrev = do withCurrentTeam $ \tId -> do withCurrentChannel tId $ \cId _ -> do csChannel(cId).ccInfo.cdMentionCount .= 0 updateViewedChan updatePrev cId -- | When a new channel has been selected for viewing, this will -- notify the server of the change, and also update the local channel -- state to set the last-viewed time for the previous channel and -- update the viewed time to now for the newly selected channel. -- -- The boolean argument indicates whether the view time of the previous -- channel (if any) should be updated, too. We typically want to do that -- only on channel switching; when we just want to update the view time -- of the specified channel, False should be provided. updateViewedChan :: Bool -> ChannelId -> MH () updateViewedChan updatePrev cId = use csConnectionStatus >>= \case -- Only do this if we're connected to avoid triggering noisy -- exceptions. Connected -> do withChannel cId $ \chan -> do pId <- if updatePrev then do case chan^.ccInfo.cdTeamId of Just tId -> use (csTeam(tId).tsRecentChannel) Nothing -> do mtId <- use csCurrentTeamId case mtId of Nothing -> return Nothing Just tId -> use (csTeam(tId).tsRecentChannel) else return Nothing doAsyncChannelMM Preempt cId (\s c -> MM.mmViewChannel UserMe c pId s) (\c () -> Just $ setLastViewedFor pId c) Disconnected -> -- Cannot update server; make no local updates to avoid getting -- out of sync with the server. Assumes that this is a temporary -- break in connectivity and that after the connection is -- restored, the user's normal activities will update state as -- appropriate. If connectivity is permanently lost, managing -- this state is irrelevant. return () toggleExpandedChannelTopics :: MH () toggleExpandedChannelTopics = do mh invalidateCache csResources.crConfiguration.configShowExpandedChannelTopicsL %= not | If the current channel is a DM channel with a single user or a -- group of users, hide it from the sidebar and adjust the server-side -- preference to hide it persistently. Note that this does not actually -- hide the channel in our UI; we hide it in response to the preference -- change websocket event triggered by this function's API interaction -- with the server. -- -- If the current channel is any other kind of channel, complain with a -- usage error. hideDMChannel :: ChannelId -> MH () hideDMChannel cId = do me <- gets myUser session <- getSession withChannel cId $ \chan -> do case chan^.ccInfo.cdType of Direct -> do let pref = showDirectChannelPref (me^.userIdL) uId False uId = fromJust $ chan^.ccInfo.cdDMUserId csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing doAsyncWith Preempt $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return Nothing Group -> do let pref = hideGroupChannelPref cId (me^.userIdL) csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing doAsyncWith Preempt $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return Nothing _ -> do mhError $ GenericError "Cannot hide this channel. Consider using /leave instead." -- | Called on async completion when the currently viewed channel has -- been updated (i.e., just switched to this channel) to update local -- state. setLastViewedFor :: Maybe ChannelId -> ChannelId -> MH () setLastViewedFor prevId cId = do chan <- use (csChannels.to (findChannelById cId)) -- Update new channel's viewed time, creating the channel if needed case chan of Nothing -> -- It's possible for us to get spurious WMChannelViewed -- events from the server, e.g. for channels that have been -- deleted. So here we ignore the request since it's hard to -- detect it before this point. return () Just _ -> -- The server has been sent a viewed POST update, but there is -- no local information on what timestamp the server actually -- recorded. There are a couple of options for setting the -- local value of the viewed time: -- -- 1. Attempting to locally construct a value, which would -- involve scanning all (User) messages in the channel -- to find the maximum of the created date, the modified -- date, or the deleted date, and assuming that maximum -- mostly matched the server's viewed time. -- -- 2. Issuing a channel metadata request to get the server's -- new concept of the viewed time. -- -- 3. Having the "chan/viewed" POST that was just issued -- return a value from the server. See . -- Method 3 would be the best and most lightweight . Until that is available , Method 2 will be used . The downside to Method 2 is additional client - server messaging , and a delay in -- updating the client data, but it's also immune to any new -- or removed Message date fields, or anything else that would -- contribute to the viewed/updated times on the server. doAsyncChannelMM Preempt cId (\ s _ -> (,) <$> MM.mmGetChannel cId s <*> MM.mmGetChannelMember cId UserMe s) (\pcid (cwd, member) -> Just $ csChannel(pcid).ccInfo %= channelInfoFromChannelWithData cwd member) -- Update the old channel's previous viewed time (allows tracking of -- new messages) case prevId of Nothing -> return () Just p -> clearChannelUnreadStatus p -- | Refresh information about all channels and users. This is usually -- triggered when a reconnect event for the WebSocket to the server -- occurs. refreshChannelsAndUsers :: MH () refreshChannelsAndUsers = do session <- getSession me <- gets myUser knownUsers <- gets allUserIds ts <- use csTeams doAsyncWith Preempt $ do pairs <- forM (HM.keys ts) $ \tId -> do runConcurrently $ (,) <$> Concurrently (MM.mmGetChannelsForUser UserMe tId session) <*> Concurrently (MM.mmGetChannelMembersForUser UserMe tId session) let (chans, datas) = (mconcat $ fst <$> pairs, mconcat $ snd <$> pairs) Collect all user IDs associated with DM channels so we can -- bulk-fetch their user records. let dmUsers = catMaybes $ flip map (F.toList chans) $ \chan -> case chan^.channelTypeL of Direct -> case userIdForDMChannel (userId me) (sanitizeUserText $ channelName chan) of Nothing -> Nothing Just otherUserId -> Just otherUserId _ -> Nothing uIdsToFetch = nub $ userId me : knownUsers <> dmUsers dataMap = HM.fromList $ toList $ (\d -> (channelMemberChannelId d, d)) <$> datas mkPair chan = (chan, fromJust $ HM.lookup (channelId chan) dataMap) chansWithData = mkPair <$> chans return $ Just $ Fetch user data associated with DM channels handleNewUsers (Seq.fromList uIdsToFetch) $ do -- Then refresh all loaded channels forM_ chansWithData $ uncurry (refreshChannel SidebarUpdateDeferred) updateSidebar Nothing -- | Refresh information about a specific channel. The channel -- metadata is refreshed, and if this is a loaded channel, the -- scrollback is updated as well. -- -- The sidebar update argument indicates whether this refresh should -- also update the sidebar. Ordinarily you want this, so pass SidebarUpdateImmediate unless you are very sure you know what you are -- doing, i.e., you are very sure that a call to refreshChannel will -- be followed immediately by a call to updateSidebar. We provide this -- control so that channel refreshes can be batched and then a single -- updateSidebar call can be used instead of the default behavior of -- calling it once per refreshChannel call, which is the behavior if the -- immediate setting is passed here. refreshChannel :: SidebarUpdate -> Channel -> ChannelMember -> MH () refreshChannel upd chan member = do ts <- use csTeams let ourTeams = HM.keys ts isOurTeam = case channelTeamId chan of Nothing -> True Just tId -> tId `elem` ourTeams case isOurTeam of False -> return () True -> do let cId = getId chan If this channel is unknown , register it first . mChan <- preuse (csChannel(cId)) when (isNothing mChan) $ handleNewChannel False upd chan member updateChannelInfo cId chan member handleNewChannel :: Bool -> SidebarUpdate -> Channel -> ChannelMember -> MH () handleNewChannel = handleNewChannel_ True handleNewChannel_ :: Bool -- ^ Whether to permit this call to recursively -- schedule itself for later if it can't locate a DM channel user record . This is to prevent -- uncontrolled recursion. -> Bool -- ^ Whether to switch to the new channel once it has -- been installed. -> SidebarUpdate -- ^ Whether to update the sidebar, in case the caller -- wants to batch these before updating it. Pass SidebarUpdateImmediate unless you know what -- you are doing, i.e., unless you intend to call -- updateSidebar yourself after calling this. -> Channel -- ^ The channel to install. -> ChannelMember -> MH () handleNewChannel_ permitPostpone switch sbUpdate nc member = do -- Only add the channel to the state if it isn't already known. me <- gets myUser mChan <- preuse (csChannel(getId nc)) case mChan of Just ch -> do mtId <- case ch^.ccInfo.cdTeamId of Nothing -> use csCurrentTeamId Just i -> return $ Just i when switch $ case mtId of Nothing -> return () Just tId -> setFocus tId (getId nc) Nothing -> do eventQueue <- use (csResources.crEventQueue) spellChecker <- use (csResources.crSpellChecker) Create a new ClientChannel structure cChannel <- (ccInfo %~ channelInfoFromChannelWithData nc member) <$> makeClientChannel eventQueue spellChecker (me^.userIdL) (channelTeamId nc) nc st <- use id -- Add it to the message map, and to the name map so we -- can look it up by name. The name we use for the channel -- depends on its type: let chType = nc^.channelTypeL -- Get the channel name. If we couldn't, that means we have -- async work to do before we can register this channel (in -- which case abort because we got rescheduled). register <- case chType of Direct -> case userIdForDMChannel (myUserId st) (sanitizeUserText $ channelName nc) of Nothing -> return True Just otherUserId -> case userById otherUserId st of -- If we found a user ID in the channel -- name string but don't have that user's -- metadata, postpone adding this channel -- until we have fetched the metadata. This -- can happen when we have a channel record -- for a user that is no longer in the -- current team. To avoid recursion due to a -- problem, ensure that the rescheduled new -- channel handler is not permitted to try -- this again. -- -- If we're already in a recursive attempt -- to register this channel and still -- couldn't find a username, just bail and -- use the synthetic name (this has the same -- problems as above). Nothing -> do case permitPostpone of False -> return True True -> do mhLog LogAPI $ T.pack $ "handleNewChannel_: about to call handleNewUsers for " <> show otherUserId handleNewUsers (Seq.singleton otherUserId) (return ()) doAsyncWith Normal $ return $ Just $ handleNewChannel_ False switch sbUpdate nc member return False Just _ -> return True _ -> return True when register $ do csChannels %= addChannel (getId nc) cChannel when (sbUpdate == SidebarUpdateImmediate) $ do -- Note that we only check for whether we should -- switch to this channel when doing a sidebar -- update, since that's the only case where it's -- possible to do so. updateSidebar (cChannel^.ccInfo.cdTeamId) chanTeam <- case cChannel^.ccInfo.cdTeamId of Nothing -> use csCurrentTeamId Just i -> return $ Just i -- Finally, set our focus to the newly created -- channel if the caller requested a change of -- channel. Also consider the last join request -- state field in case this is an asynchronous channel addition triggered by a /join . case chanTeam of Nothing -> return () Just tId -> do pending1 <- checkPendingChannelChange tId (getId nc) pending2 <- case cChannel^.ccInfo.cdDMUserId of Nothing -> return False Just uId -> checkPendingChannelChangeByUserId tId uId when (switch || isJust pending1 || pending2) $ do setFocus tId (getId nc) case pending1 of Just (Just act) -> act _ -> return () -- | Check to see whether the specified channel has been queued up to -- be switched to. Note that this condition is only cleared by the actual setFocus switch to the channel because there may be multiple -- operations that must complete before the channel is fully ready for -- display/use. -- -- Returns Just if the specified channel has a pending switch. The -- result is an optional action to invoke after changing to the -- specified channel. checkPendingChannelChange :: TeamId -> ChannelId -> MH (Maybe (Maybe (MH ()))) checkPendingChannelChange curTid cId = do ch <- use (csTeam(curTid).tsPendingChannelChange) return $ case ch of Just (ChangeByChannelId tId i act) -> if i == cId && curTid == tId then Just act else Nothing _ -> Nothing -- | Check to see whether the specified channel has been queued up to -- be switched to. Note that this condition is only cleared by the actual setFocus switch to the channel because there may be multiple -- operations that must complete before the channel is fully ready for -- display/use. -- -- Returns Just if the specified channel has a pending switch. The -- result is an optional action to invoke after changing to the -- specified channel. checkPendingChannelChangeByUserId :: TeamId -> UserId -> MH Bool checkPendingChannelChangeByUserId tId uId = do ch <- use (csTeam(tId).tsPendingChannelChange) return $ case ch of Just (ChangeByUserId i) -> i == uId _ -> False -- | Update the indicated Channel entry with the new data retrieved from -- the Mattermost server. Also update the channel name if it changed. updateChannelInfo :: ChannelId -> Channel -> ChannelMember -> MH () updateChannelInfo cid new member = do invalidateChannelRenderingCache cid csChannel(cid).ccInfo %= channelInfoFromChannelWithData new member withChannel cid $ \chan -> updateSidebar (chan^.ccInfo.cdTeamId) setFocus :: TeamId -> ChannelId -> MH () setFocus tId cId = do showChannelInSidebar cId True setFocusWith tId True (Z.findRight ((== cId) . channelListEntryChannelId)) (return ()) (return ()) setFocusWith :: TeamId -> Bool -> (Zipper ChannelListGroup ChannelListEntry -> Zipper ChannelListGroup ChannelListEntry) -> MH () -> MH () -> MH () setFocusWith tId updatePrev f onChange onNoChange = do oldZipper <- use (csTeam(tId).tsFocus) mOldCid <- use (csCurrentChannelId tId) let newZipper = f oldZipper newFocus = Z.focus newZipper oldFocus = Z.focus oldZipper -- If we aren't changing anything, skip all the book-keeping because -- we'll end up clobbering things like tsRecentChannel. if newFocus /= oldFocus then do mh $ invalidateCacheEntry $ ChannelSidebar tId case mOldCid of Nothing -> return () Just cId -> resetAutocomplete (channelEditor(cId)) preChangeChannelCommon tId csTeam(tId).tsFocus .= newZipper now <- liftIO getCurrentTime mNewCid <- use (csCurrentChannelId tId) case mNewCid of Nothing -> return () Just newCid -> do csChannel(newCid).ccInfo.cdSidebarShowOverride .= Just now updateViewed updatePrev postChangeChannelCommon tId case newFocus of Nothing -> return () Just _ -> mh $ makeVisible $ SelectedChannelListEntry tId onChange else onNoChange postChangeChannelCommon :: TeamId -> MH () postChangeChannelCommon tId = do -- resetEditorState cId -- loadLastEdit tId fetchVisibleIfNeeded tId loadLastChannelInput :: Lens' ChatState (MessageInterface n i) -> MH () loadLastChannelInput which = do inputHistoryPos <- use (which.miEditor.esEphemeral.eesInputHistoryPosition) case inputHistoryPos of Just i -> void $ loadHistoryEntryToEditor which i Nothing -> do (lastEdit, lastEditMode) <- use (which.miEditor.esEphemeral.eesLastInput) which.miEditor.esEditor %= (applyEdit $ insertMany lastEdit . clearZipper) which.miEditor.esEditMode .= lastEditMode preChangeChannelCommon :: TeamId -> MH () preChangeChannelCommon tId = do withCurrentChannel tId $ \cId _ -> do csTeam(tId).tsRecentChannel .= Just cId saveEditorInput :: Lens' ChatState (MessageInterface n i) -> MH () saveEditorInput which = do cmdLine <- use (which.miEditor.esEditor) mode <- use (which.miEditor.esEditMode) -- Only save the editor contents if the user is not navigating the -- history. inputHistoryPos <- use (which.miEditor.esEphemeral.eesInputHistoryPosition) when (isNothing inputHistoryPos) $ which.miEditor.esEphemeral.eesLastInput .= (T.intercalate "\n" $ getEditContents $ cmdLine, mode) applyPreferenceChange :: Preference -> MH () applyPreferenceChange pref = do -- always update our user preferences accordingly csResources.crUserPreferences %= setUserPreferences (Seq.singleton pref) Invalidate the entire rendering cache since many things depend on -- user preferences mh invalidateCache if | Just f <- preferenceToFlaggedPost pref -> do updateMessageFlag (flaggedPostId f) (flaggedPostStatus f) | Just tIds <- preferenceToTeamOrder pref -> applyTeamOrder tIds | Just d <- preferenceToDirectChannelShowStatus pref -> do updateSidebar Nothing cs <- use csChannels -- We need to check on whether this preference was to show a -- channel and, if so, whether it was the one we attempted to -- switch to (thus triggering the preference change). If so, -- we need to switch to it now. let cId = fromJust $ getDmChannelFor (directChannelShowUserId d) cs case directChannelShowValue d of True -> do withCurrentTeam $ \tId -> do pending <- checkPendingChannelChange tId cId case pending of Just mAct -> do setFocus tId cId fromMaybe (return ()) mAct Nothing -> return () False -> do csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing | Just g <- preferenceToGroupChannelPreference pref -> do updateSidebar Nothing -- We need to check on whether this preference was to show a -- channel and, if so, whether it was the one we attempted to -- switch to (thus triggering the preference change). If so, -- we need to switch to it now. let cId = groupChannelId g case groupChannelShow g of True -> do withCurrentTeam $ \tId -> do pending <- checkPendingChannelChange tId cId case pending of Just mAct -> do setFocus tId cId fromMaybe (return ()) mAct Nothing -> return () False -> do csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing | Just f <- preferenceToFavoriteChannelPreference pref -> do updateSidebar Nothing -- We need to check on whether this preference was to show a -- channel and, if so, whether it was the one we attempted to -- switch to (thus triggering the preference change). If so, -- we need to switch to it now. let cId = favoriteChannelId f case favoriteChannelShow f of True -> do withCurrentTeam $ \tId -> do pending <- checkPendingChannelChange tId cId case pending of Just mAct -> do setFocus tId cId fromMaybe (return ()) mAct Nothing -> return () False -> do csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing | otherwise -> return () refreshChannelById :: ChannelId -> MH () refreshChannelById cId = do session <- getSession doAsyncWith Preempt $ do cwd <- MM.mmGetChannel cId session member <- MM.mmGetChannelMember cId UserMe session return $ Just $ do refreshChannel SidebarUpdateImmediate cwd member removeChannelFromState :: ChannelId -> MH () removeChannelFromState cId = do withChannel cId $ \ chan -> do when (chan^.ccInfo.cdType /= Direct) $ do case chan^.ccInfo.cdTeamId of Nothing -> return () Just tId -> do origFocus <- use (csCurrentChannelId tId) when (origFocus == Just cId) (nextChannelSkipPrevView tId) -- Update input history csInputHistory %= removeChannelHistory cId -- Update msgMap csChannels %= removeChannel cId case chan^.ccInfo.cdTeamId of Nothing -> do ts <- use csTeams forM_ (HM.keys ts) $ \tId -> csTeam(tId).tsFocus %= Z.filterZipper ((/= cId) . channelListEntryChannelId) Just tId -> do csTeam(tId).tsFocus %= Z.filterZipper ((/= cId) . channelListEntryChannelId) updateSidebar $ chan^.ccInfo.cdTeamId nextChannel :: TeamId -> MH () nextChannel tId = do resetReturnChannel tId let checkForFirst = do z <- use (csTeam(tId).tsFocus) case Z.focus z of Nothing -> return () Just entry -> do If the newly - selected channel is the first -- visible entry in the channel list, we also want -- to scroll the channel list up far enough to show -- the topmost section header. when (entry == (head $ concat $ snd <$> Z.toList z)) $ do mh $ vScrollToBeginning $ viewportScroll (ChannelListViewport tId) setFocusWith tId True Z.right checkForFirst (return ()) -- | This is almost never what you want; we use this when we delete a -- channel and we don't want to update the deleted channel's view time. nextChannelSkipPrevView :: TeamId -> MH () nextChannelSkipPrevView tId = setFocusWith tId False Z.right (return ()) (return ()) prevChannel :: TeamId -> MH () prevChannel tId = do resetReturnChannel tId setFocusWith tId True Z.left (return ()) (return ()) recentChannel :: TeamId -> MH () recentChannel tId = do recent <- use (csTeam(tId).tsRecentChannel) case recent of Nothing -> return () Just cId -> do ret <- use (csTeam(tId).tsReturnChannel) when (ret == Just cId) (resetReturnChannel tId) setFocus tId cId resetReturnChannel :: TeamId -> MH () resetReturnChannel tId = do val <- use (csTeam(tId).tsReturnChannel) case val of Nothing -> return () Just _ -> do mh $ invalidateCacheEntry $ ChannelSidebar tId csTeam(tId).tsReturnChannel .= Nothing gotoReturnChannel :: TeamId -> MH () gotoReturnChannel tId = do ret <- use (csTeam(tId).tsReturnChannel) case ret of Nothing -> return () Just cId -> do resetReturnChannel tId setFocus tId cId setReturnChannel :: TeamId -> MH () setReturnChannel tId = do ret <- use (csTeam(tId).tsReturnChannel) case ret of Nothing -> do withCurrentChannel tId $ \cId _ -> do csTeam(tId).tsReturnChannel .= Just cId mh $ invalidateCacheEntry $ ChannelSidebar tId Just _ -> return () nextUnreadChannel :: TeamId -> MH () nextUnreadChannel tId = do st <- use id setReturnChannel tId setFocusWith tId True (getNextUnreadChannel st tId) (return ()) (gotoReturnChannel tId) nextUnreadUserOrChannel :: TeamId -> MH () nextUnreadUserOrChannel tId = do st <- use id setReturnChannel tId setFocusWith tId True (getNextUnreadUserOrChannel st tId) (return ()) (gotoReturnChannel tId) leaveChannel :: ChannelId -> MH () leaveChannel cId = leaveChannelIfPossible cId False leaveChannelIfPossible :: ChannelId -> Bool -> MH () leaveChannelIfPossible cId delete = do st <- use id me <- gets myUser let isMe u = u^.userIdL == me^.userIdL case st ^? csChannel(cId).ccInfo of Nothing -> return () Just cInfo -> case canLeaveChannel cInfo of False -> return () True -> -- The server will reject an attempt to leave a private -- channel if we're the only member. To check this, we just ask for the first two members of the channel . If there is only one , it must be us : hence the " all isMe " check below . If there are two members , it -- doesn't matter who they are, because we just know -- that we aren't the only remaining member, so we can't -- delete the channel. doAsyncChannelMM Preempt cId (\s _ -> let query = MM.defaultUserQuery { MM.userQueryPage = Just 0 , MM.userQueryPerPage = Just 2 , MM.userQueryInChannel = Just cId } in toList <$> MM.mmGetUsers query s) (\_ members -> Just $ do -- If the channel is private: -- * leave it if we aren't the last member. -- * delete it if we are. -- -- Otherwise: -- * leave (or delete) the channel as specified -- by the delete argument. let func = case cInfo^.cdType of Private -> case all isMe members of True -> (\ s c -> MM.mmDeleteChannel c s) False -> (\ s c -> MM.mmRemoveUserFromChannel c UserMe s) Group -> \s _ -> let pref = hideGroupChannelPref cId (me^.userIdL) in MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) s _ -> if delete then (\ s c -> MM.mmDeleteChannel c s) else (\ s c -> MM.mmRemoveUserFromChannel c UserMe s) doAsyncChannelMM Preempt cId func endAsyncNOP ) getNextUnreadChannel :: ChatState -> TeamId -> (Zipper a ChannelListEntry -> Zipper a ChannelListEntry) getNextUnreadChannel st tId = -- The next channel with unread messages must also be a channel -- other than the current one, since the zipper may be on a channel -- that has unread messages and will stay that way until we leave -- it- so we need to skip that channel when doing the zipper search -- for the next candidate channel. Z.findRight (\e -> let cId = channelListEntryChannelId e in channelListEntryUnread e && (Just cId /= st^.csCurrentChannelId(tId))) getNextUnreadUserOrChannel :: ChatState -> TeamId -> Zipper a ChannelListEntry -> Zipper a ChannelListEntry getNextUnreadUserOrChannel st tId z = -- Find the next unread channel, prefering direct messages let cur = st^.csCurrentChannelId(tId) matches e = entryIsDMEntry e && isFresh e isFresh e = channelListEntryUnread e && (Just (channelListEntryChannelId e) /= cur) in fromMaybe (Z.findRight isFresh z) (Z.maybeFindRight matches z) leaveCurrentChannel :: TeamId -> MH () leaveCurrentChannel tId = do withCurrentChannel tId $ \cId _ -> do leaveChannel cId createGroupChannel :: TeamId -> Text -> MH () createGroupChannel tId usernameList = do me <- gets myUser session <- getSession cs <- use csChannels doAsyncWith Preempt $ do let usernames = Seq.fromList $ fmap trimUserSigil $ T.words usernameList results <- MM.mmGetUsersByUsernames usernames session -- If we found all of the users mentioned, then create the group -- channel. case length results == length usernames of True -> do chan <- MM.mmCreateGroupMessageChannel (userId <$> results) session return $ Just $ do case findChannelById (channelId chan) cs of Just _ -> -- If we already know about the channel ID, -- that means the channel already exists so -- we can just switch to it. setFocus tId (channelId chan) Nothing -> do csTeam(tId).tsPendingChannelChange .= (Just $ ChangeByChannelId tId (channelId chan) Nothing) let pref = showGroupChannelPref (channelId chan) (me^.userIdL) doAsyncWith Normal $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return $ Just $ applyPreferenceChange pref False -> do let foundUsernames = userUsername <$> results missingUsernames = S.toList $ S.difference (S.fromList $ F.toList usernames) (S.fromList $ F.toList foundUsernames) return $ Just $ do forM_ missingUsernames (mhError . NoSuchUser) inputHistoryForward :: Lens' ChatState (MessageInterface n i) -> MH () inputHistoryForward which = do resetAutocomplete (which.miEditor) inputHistoryPos <- use (which.miEditor.esEphemeral.eesInputHistoryPosition) case inputHistoryPos of Just i | i == 0 -> do -- Transition out of history navigation which.miEditor.esEphemeral.eesInputHistoryPosition .= Nothing loadLastChannelInput which | otherwise -> do let newI = i - 1 loaded <- loadHistoryEntryToEditor which newI when loaded $ which.miEditor.esEphemeral.eesInputHistoryPosition .= (Just newI) _ -> return () loadHistoryEntryToEditor :: Lens' ChatState (MessageInterface n i) -> Int -> MH Bool loadHistoryEntryToEditor which idx = do cId <- use (which.miChannelId) inputHistory <- use csInputHistory case getHistoryEntry cId idx inputHistory of Nothing -> return False Just entry -> do let eLines = T.lines entry mv = if length eLines == 1 then gotoEOL else id which.miEditor.esEditor.editContentsL .= (mv $ textZipper eLines Nothing) cfg <- use (csResources.crConfiguration) when (configShowMessagePreview cfg) $ invalidateChannelRenderingCache cId return True inputHistoryBackward :: Lens' ChatState (MessageInterface n i) -> MH () inputHistoryBackward which = do resetAutocomplete (which.miEditor) inputHistoryPos <- use (which.miEditor.esEphemeral.eesInputHistoryPosition) saveEditorInput which let newI = maybe 0 (+ 1) inputHistoryPos loaded <- loadHistoryEntryToEditor which newI when loaded $ which.miEditor.esEphemeral.eesInputHistoryPosition .= (Just newI) createOrdinaryChannel :: TeamId -> Bool -> Text -> MH () createOrdinaryChannel myTId public name = do session <- getSession doAsyncWith Preempt $ do -- create a new chat channel let slug = T.map (\ c -> if isAlphaNum c then c else '-') (T.toLower name) minChannel = MinChannel { minChannelName = slug , minChannelDisplayName = name , minChannelPurpose = Nothing , minChannelHeader = Nothing , minChannelType = if public then Ordinary else Private , minChannelTeamId = myTId } tryMM (do c <- MM.mmCreateChannel minChannel session chan <- MM.mmGetChannel (getId c) session member <- MM.mmGetChannelMember (getId c) UserMe session return (chan, member) ) (return . Just . uncurry (handleNewChannel True SidebarUpdateImmediate)) -- | When we are added to a channel not locally known about, we need -- to fetch the channel info for that channel. handleChannelInvite :: ChannelId -> MH () handleChannelInvite cId = do session <- getSession doAsyncWith Normal $ do member <- MM.mmGetChannelMember cId UserMe session tryMM (MM.mmGetChannel cId session) (\cwd -> return $ Just $ do mtId <- case channelTeamId cwd of Nothing -> use csCurrentTeamId Just i -> return $ Just i pending <- case mtId of Nothing -> return Nothing Just tId -> checkPendingChannelChange tId cId handleNewChannel (isJust pending) SidebarUpdateImmediate cwd member) addUserByNameToCurrentChannel :: TeamId -> Text -> MH () addUserByNameToCurrentChannel tId uname = withFetchedUser (UserFetchByUsername uname) (addUserToCurrentChannel tId) addUserToCurrentChannel :: TeamId -> UserInfo -> MH () addUserToCurrentChannel tId u = do withCurrentChannel tId $ \cId _ -> do session <- getSession let channelMember = MinChannelMember (u^.uiId) cId doAsyncWith Normal $ do tryMM (void $ MM.mmAddUser cId channelMember session) (const $ return Nothing) removeUserFromCurrentChannel :: TeamId -> Text -> MH () removeUserFromCurrentChannel tId uname = withCurrentChannel tId $ \cId _ -> do withFetchedUser (UserFetchByUsername uname) $ \u -> do session <- getSession doAsyncWith Normal $ do tryMM (void $ MM.mmRemoveUserFromChannel cId (UserById $ u^.uiId) session) (const $ return Nothing) startLeaveCurrentChannel :: TeamId -> MH () startLeaveCurrentChannel tId = do withCurrentChannel tId $ \_ ch -> do case ch^.ccInfo.cdType of Direct -> hideDMChannel (ch^.ccInfo.cdChannelId) Group -> hideDMChannel (ch^.ccInfo.cdChannelId) _ -> pushMode tId LeaveChannelConfirm deleteCurrentChannel :: TeamId -> MH () deleteCurrentChannel tId = do withCurrentChannel tId $ \cId _ -> do leaveChannelIfPossible cId True isCurrentChannel :: ChatState -> TeamId -> ChannelId -> Bool isCurrentChannel st tId cId = st^.csCurrentChannelId(tId) == Just cId isRecentChannel :: ChatState -> TeamId -> ChannelId -> Bool isRecentChannel st tId cId = st^.csTeam(tId).tsRecentChannel == Just cId isReturnChannel :: ChatState -> TeamId -> ChannelId -> Bool isReturnChannel st tId cId = st^.csTeam(tId).tsReturnChannel == Just cId joinChannelByName :: TeamId -> Text -> MH () joinChannelByName tId rawName = do session <- getSession doAsyncWith Preempt $ do result <- try $ MM.mmGetChannelByName tId (trimChannelSigil rawName) session return $ Just $ case result of Left (_::SomeException) -> mhError $ NoSuchChannel rawName Right chan -> joinChannel tId $ getId chan -- | If the user is not a member of the specified channel, submit a -- request to join it. Otherwise switch to the channel. joinChannel :: TeamId -> ChannelId -> MH () joinChannel tId chanId = joinChannel' tId chanId Nothing joinChannel' :: TeamId -> ChannelId -> Maybe (MH ()) -> MH () joinChannel' tId chanId act = do mChan <- preuse (csChannel(chanId)) case mChan of Just _ -> do setFocus tId chanId fromMaybe (return ()) act Nothing -> do myId <- gets myUserId let member = MinChannelMember myId chanId csTeam(tId).tsPendingChannelChange .= (Just $ ChangeByChannelId tId chanId act) doAsyncChannelMM Preempt chanId (\ s c -> MM.mmAddUser c member s) (const $ return act) createOrFocusDMChannel :: TeamId -> UserInfo -> Maybe (ChannelId -> MH ()) -> MH () createOrFocusDMChannel tId user successAct = do cs <- use csChannels case getDmChannelFor (user^.uiId) cs of Just cId -> do setFocus tId cId case successAct of Nothing -> return () Just act -> act cId Nothing -> do -- We have a user of that name but no channel. Time to make one! myId <- gets myUserId session <- getSession csTeam(tId).tsPendingChannelChange .= (Just $ ChangeByUserId $ user^.uiId) doAsyncWith Normal $ do -- create a new channel chan <- MM.mmCreateDirectMessageChannel (user^.uiId, myId) session return $ successAct <*> pure (channelId chan) -- | This switches to the named channel or creates it if it is a missing -- but valid user channel. changeChannelByName :: TeamId -> Text -> MH () changeChannelByName tId name = do myId <- gets myUserId mCId <- gets (channelIdByChannelName tId name) mDMCId <- gets (channelIdByUsername name) withFetchedUserMaybe (UserFetchByUsername name) $ \foundUser -> do if (_uiId <$> foundUser) == Just myId then return () else do let err = mhError $ AmbiguousName name case (mCId, mDMCId) of (Nothing, Nothing) -> case foundUser of We know about the user but there is n't already a DM -- channel, so create one. Just user -> createOrFocusDMChannel tId user Nothing -- There were no matches of any kind. Nothing -> mhError $ NoSuchChannel name (Just cId, Nothing) -- We matched a channel and there was an explicit sigil, so we -- don't care about the username match. | normalChannelSigil `T.isPrefixOf` name -> setFocus tId cId -- We matched both a channel and a user, even though there is no DM channel . | Just _ <- foundUser -> err -- We matched a channel only. | otherwise -> setFocus tId cId (Nothing, Just cId) -> We matched a DM channel only . setFocus tId cId (Just _, Just _) -> We matched both a channel and a DM channel . err setChannelTopic :: TeamId -> Text -> MH () setChannelTopic tId msg = do withCurrentChannel tId $ \cId _ -> do let patch = defaultChannelPatch { channelPatchHeader = Just msg } doAsyncChannelMM Preempt cId (\s _ -> MM.mmPatchChannel cId patch s) (\_ _ -> Nothing) -- | This renames the current channel's url name. It makes a request -- to the server to change the name, but does not actually change the name in Matterhorn yet ; that is handled by a websocket event handled -- asynchronously. renameChannelUrl :: TeamId -> Text -> MH () renameChannelUrl tId name = do withCurrentChannel tId $ \cId _ -> do s <- getSession let patch = defaultChannelPatch { channelPatchName = Just name } doAsyncWith Normal $ do _ <- MM.mmPatchChannel cId patch s return Nothing getCurrentChannelTopic :: TeamId -> MH (Maybe Text) getCurrentChannelTopic tId = withCurrentChannel' tId $ \_ c -> do return $ Just $ c^.ccInfo.cdHeader beginCurrentChannelDeleteConfirm :: TeamId -> MH () beginCurrentChannelDeleteConfirm tId = do withCurrentChannel tId $ \_ chan -> do let chType = chan^.ccInfo.cdType if chType /= Direct then pushMode tId DeleteChannelConfirm else mhError $ GenericError "Direct message channels cannot be deleted." updateChannelNotifyProps :: ChannelId -> ChannelNotifyProps -> MH () updateChannelNotifyProps cId notifyProps = do withChannel cId $ \chan -> do csChannel(cId).ccInfo.cdNotifyProps .= notifyProps updateSidebar (chan^.ccInfo.cdTeamId) toggleChannelFavoriteStatus :: TeamId -> MH () toggleChannelFavoriteStatus tId = do myId <- gets myUserId withCurrentChannel tId $ \cId _ -> do userPrefs <- use (csResources.crUserPreferences) session <- getSession let favPref = favoriteChannelPreference userPrefs cId trueVal = "true" prefVal = case favPref of Just True -> "" Just False -> trueVal Nothing -> trueVal pref = Preference { preferenceUserId = myId , preferenceCategory = PreferenceCategoryFavoriteChannel , preferenceName = PreferenceName $ idString cId , preferenceValue = PreferenceValue prefVal } doAsyncWith Normal $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return Nothing toggleChannelListGroupVisibility :: ChannelListGroupLabel -> MH () toggleChannelListGroupVisibility label = do withCurrentTeam $ \tId -> do -- Get all channel list groups in the current sidebar that are -- currently not collapsed csHiddenChannelGroups %= \hidden -> let s' = case HM.lookup tId hidden of Nothing -> S.singleton label Just s -> if S.member label s then S.delete label s else S.insert label s in HM.insert tId s' hidden updateSidebar Nothing toggleCurrentChannelChannelListGroup :: TeamId -> MH () toggleCurrentChannelChannelListGroup tId = do withCurrentChannel tId $ \_ _ -> do z <- use (csTeam(tId).tsFocus) case Z.focusHeading z of Nothing -> return () Just grp -> toggleChannelListGroupVisibility $ channelListGroupLabel grp toggleCurrentChannelChannelListGroupByName :: T.Text -> TeamId -> MH () toggleCurrentChannelChannelListGroupByName name tId = do withCurrentChannel tId $ \_ _ -> do case lookup (T.toLower $ T.strip name) channelListGroupNames of Nothing -> postErrorMessage' $ "Invalid group name: " <> name Just l -> toggleChannelListGroupVisibility l channelListSortingModes :: [(ChannelListSorting, T.Text)] channelListSortingModes = [ (ChannelListSortDefault, "alphabetic") , (ChannelListSortUnreadFirst, "alphabetic with unread channels first") ] cycleChannelListSortingMode :: TeamId -> MH () cycleChannelListSortingMode tId = do curMode <- use (csTeam(tId).tsChannelListSorting) when (curMode `notElem` (fst <$> channelListSortingModes)) $ error $ "BUG: active channel list sorting mode unknown (" <> show curMode <> ")" let (newMode, newModeDesc) = sortingModeAfter curMode sortingModeAfter m = head $ drop 1 $ snd $ span ((/= m) . fst) $ cycle channelListSortingModes postInfoMessage $ "Sorting channel list: " <> newModeDesc csTeam(tId).tsChannelListSorting .= newMode updateSidebar $ Just tId
null
https://raw.githubusercontent.com/matterhorn-chat/matterhorn/19a73ce833a8a8de3616cf884c03e9f08a4db0a7/src/Matterhorn/State/Channels.hs
haskell
# LANGUAGE MultiWayIf # # LANGUAGE RankNTypes # # SOURCE # # SOURCE # | When a new channel has been selected for viewing, this will notify the server of the change, and also update the local channel state to set the last-viewed time for the previous channel and update the viewed time to now for the newly selected channel. The boolean argument indicates whether the view time of the previous channel (if any) should be updated, too. We typically want to do that only on channel switching; when we just want to update the view time of the specified channel, False should be provided. Only do this if we're connected to avoid triggering noisy exceptions. Cannot update server; make no local updates to avoid getting out of sync with the server. Assumes that this is a temporary break in connectivity and that after the connection is restored, the user's normal activities will update state as appropriate. If connectivity is permanently lost, managing this state is irrelevant. group of users, hide it from the sidebar and adjust the server-side preference to hide it persistently. Note that this does not actually hide the channel in our UI; we hide it in response to the preference change websocket event triggered by this function's API interaction with the server. If the current channel is any other kind of channel, complain with a usage error. | Called on async completion when the currently viewed channel has been updated (i.e., just switched to this channel) to update local state. Update new channel's viewed time, creating the channel if needed It's possible for us to get spurious WMChannelViewed events from the server, e.g. for channels that have been deleted. So here we ignore the request since it's hard to detect it before this point. The server has been sent a viewed POST update, but there is no local information on what timestamp the server actually recorded. There are a couple of options for setting the local value of the viewed time: 1. Attempting to locally construct a value, which would involve scanning all (User) messages in the channel to find the maximum of the created date, the modified date, or the deleted date, and assuming that maximum mostly matched the server's viewed time. 2. Issuing a channel metadata request to get the server's new concept of the viewed time. 3. Having the "chan/viewed" POST that was just issued return a value from the server. See updating the client data, but it's also immune to any new or removed Message date fields, or anything else that would contribute to the viewed/updated times on the server. Update the old channel's previous viewed time (allows tracking of new messages) | Refresh information about all channels and users. This is usually triggered when a reconnect event for the WebSocket to the server occurs. bulk-fetch their user records. Then refresh all loaded channels | Refresh information about a specific channel. The channel metadata is refreshed, and if this is a loaded channel, the scrollback is updated as well. The sidebar update argument indicates whether this refresh should also update the sidebar. Ordinarily you want this, so pass doing, i.e., you are very sure that a call to refreshChannel will be followed immediately by a call to updateSidebar. We provide this control so that channel refreshes can be batched and then a single updateSidebar call can be used instead of the default behavior of calling it once per refreshChannel call, which is the behavior if the immediate setting is passed here. ^ Whether to permit this call to recursively schedule itself for later if it can't locate uncontrolled recursion. ^ Whether to switch to the new channel once it has been installed. ^ Whether to update the sidebar, in case the caller wants to batch these before updating it. Pass you are doing, i.e., unless you intend to call updateSidebar yourself after calling this. ^ The channel to install. Only add the channel to the state if it isn't already known. Add it to the message map, and to the name map so we can look it up by name. The name we use for the channel depends on its type: Get the channel name. If we couldn't, that means we have async work to do before we can register this channel (in which case abort because we got rescheduled). If we found a user ID in the channel name string but don't have that user's metadata, postpone adding this channel until we have fetched the metadata. This can happen when we have a channel record for a user that is no longer in the current team. To avoid recursion due to a problem, ensure that the rescheduled new channel handler is not permitted to try this again. If we're already in a recursive attempt to register this channel and still couldn't find a username, just bail and use the synthetic name (this has the same problems as above). Note that we only check for whether we should switch to this channel when doing a sidebar update, since that's the only case where it's possible to do so. Finally, set our focus to the newly created channel if the caller requested a change of channel. Also consider the last join request state field in case this is an asynchronous | Check to see whether the specified channel has been queued up to be switched to. Note that this condition is only cleared by the operations that must complete before the channel is fully ready for display/use. Returns Just if the specified channel has a pending switch. The result is an optional action to invoke after changing to the specified channel. | Check to see whether the specified channel has been queued up to be switched to. Note that this condition is only cleared by the operations that must complete before the channel is fully ready for display/use. Returns Just if the specified channel has a pending switch. The result is an optional action to invoke after changing to the specified channel. | Update the indicated Channel entry with the new data retrieved from the Mattermost server. Also update the channel name if it changed. If we aren't changing anything, skip all the book-keeping because we'll end up clobbering things like tsRecentChannel. resetEditorState cId loadLastEdit tId Only save the editor contents if the user is not navigating the history. always update our user preferences accordingly user preferences We need to check on whether this preference was to show a channel and, if so, whether it was the one we attempted to switch to (thus triggering the preference change). If so, we need to switch to it now. We need to check on whether this preference was to show a channel and, if so, whether it was the one we attempted to switch to (thus triggering the preference change). If so, we need to switch to it now. We need to check on whether this preference was to show a channel and, if so, whether it was the one we attempted to switch to (thus triggering the preference change). If so, we need to switch to it now. Update input history Update msgMap visible entry in the channel list, we also want to scroll the channel list up far enough to show the topmost section header. | This is almost never what you want; we use this when we delete a channel and we don't want to update the deleted channel's view time. The server will reject an attempt to leave a private channel if we're the only member. To check this, we doesn't matter who they are, because we just know that we aren't the only remaining member, so we can't delete the channel. If the channel is private: * leave it if we aren't the last member. * delete it if we are. Otherwise: * leave (or delete) the channel as specified by the delete argument. The next channel with unread messages must also be a channel other than the current one, since the zipper may be on a channel that has unread messages and will stay that way until we leave it- so we need to skip that channel when doing the zipper search for the next candidate channel. Find the next unread channel, prefering direct messages If we found all of the users mentioned, then create the group channel. If we already know about the channel ID, that means the channel already exists so we can just switch to it. Transition out of history navigation create a new chat channel | When we are added to a channel not locally known about, we need to fetch the channel info for that channel. | If the user is not a member of the specified channel, submit a request to join it. Otherwise switch to the channel. We have a user of that name but no channel. Time to make one! create a new channel | This switches to the named channel or creates it if it is a missing but valid user channel. channel, so create one. There were no matches of any kind. We matched a channel and there was an explicit sigil, so we don't care about the username match. We matched both a channel and a user, even though there is We matched a channel only. | This renames the current channel's url name. It makes a request to the server to change the name, but does not actually change the asynchronously. Get all channel list groups in the current sidebar that are currently not collapsed
# LANGUAGE LambdaCase # module Matterhorn.State.Channels ( updateViewed , refreshChannel , refreshChannelsAndUsers , setFocus , refreshChannelById , applyPreferenceChange , leaveChannel , leaveCurrentChannel , getNextUnreadChannel , getNextUnreadUserOrChannel , nextUnreadChannel , nextUnreadUserOrChannel , createOrFocusDMChannel , prevChannel , nextChannel , recentChannel , setReturnChannel , resetReturnChannel , hideDMChannel , createGroupChannel , showGroupChannelPref , inputHistoryForward , inputHistoryBackward , handleNewChannel , createOrdinaryChannel , handleChannelInvite , addUserByNameToCurrentChannel , addUserToCurrentChannel , removeUserFromCurrentChannel , removeChannelFromState , isRecentChannel , isReturnChannel , isCurrentChannel , deleteCurrentChannel , startLeaveCurrentChannel , joinChannel , joinChannel' , joinChannelByName , changeChannelByName , setChannelTopic , getCurrentChannelTopic , beginCurrentChannelDeleteConfirm , toggleExpandedChannelTopics , updateChannelNotifyProps , renameChannelUrl , toggleChannelFavoriteStatus , toggleChannelListGroupVisibility , toggleCurrentChannelChannelListGroup , toggleCurrentChannelChannelListGroupByName , cycleChannelListSortingMode ) where import Prelude () import Matterhorn.Prelude import Brick.Main ( invalidateCache, invalidateCacheEntry , makeVisible, vScrollToBeginning , viewportScroll ) import Brick.Widgets.Edit ( applyEdit, getEditContents, editContentsL ) import Control.Concurrent.Async ( runConcurrently, Concurrently(..) ) import Control.Exception ( SomeException, try ) import Data.Char ( isAlphaNum ) import qualified Data.HashMap.Strict as HM import qualified Data.Foldable as F import Data.List ( nub ) import Data.Maybe ( fromJust ) import qualified Data.Set as S import qualified Data.Sequence as Seq import qualified Data.Text as T import Data.Text.Zipper ( textZipper, clearZipper, insertMany, gotoEOL ) import Data.Time.Clock ( getCurrentTime ) import Lens.Micro.Platform import qualified Network.Mattermost.Endpoints as MM import Network.Mattermost.Lenses hiding ( Lens' ) import Network.Mattermost.Types import Matterhorn.Constants ( normalChannelSigil ) import Matterhorn.InputHistory import Matterhorn.State.Common import Matterhorn.State.ChannelList import Matterhorn.State.Users import Matterhorn.State.Flagging import Matterhorn.Types import Matterhorn.Types.Common import Matterhorn.Zipper ( Zipper ) import qualified Matterhorn.Zipper as Z updateViewed :: Bool -> MH () updateViewed updatePrev = do withCurrentTeam $ \tId -> do withCurrentChannel tId $ \cId _ -> do csChannel(cId).ccInfo.cdMentionCount .= 0 updateViewedChan updatePrev cId updateViewedChan :: Bool -> ChannelId -> MH () updateViewedChan updatePrev cId = use csConnectionStatus >>= \case Connected -> do withChannel cId $ \chan -> do pId <- if updatePrev then do case chan^.ccInfo.cdTeamId of Just tId -> use (csTeam(tId).tsRecentChannel) Nothing -> do mtId <- use csCurrentTeamId case mtId of Nothing -> return Nothing Just tId -> use (csTeam(tId).tsRecentChannel) else return Nothing doAsyncChannelMM Preempt cId (\s c -> MM.mmViewChannel UserMe c pId s) (\c () -> Just $ setLastViewedFor pId c) Disconnected -> return () toggleExpandedChannelTopics :: MH () toggleExpandedChannelTopics = do mh invalidateCache csResources.crConfiguration.configShowExpandedChannelTopicsL %= not | If the current channel is a DM channel with a single user or a hideDMChannel :: ChannelId -> MH () hideDMChannel cId = do me <- gets myUser session <- getSession withChannel cId $ \chan -> do case chan^.ccInfo.cdType of Direct -> do let pref = showDirectChannelPref (me^.userIdL) uId False uId = fromJust $ chan^.ccInfo.cdDMUserId csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing doAsyncWith Preempt $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return Nothing Group -> do let pref = hideGroupChannelPref cId (me^.userIdL) csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing doAsyncWith Preempt $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return Nothing _ -> do mhError $ GenericError "Cannot hide this channel. Consider using /leave instead." setLastViewedFor :: Maybe ChannelId -> ChannelId -> MH () setLastViewedFor prevId cId = do chan <- use (csChannels.to (findChannelById cId)) case chan of Nothing -> return () Just _ -> . Method 3 would be the best and most lightweight . Until that is available , Method 2 will be used . The downside to Method 2 is additional client - server messaging , and a delay in doAsyncChannelMM Preempt cId (\ s _ -> (,) <$> MM.mmGetChannel cId s <*> MM.mmGetChannelMember cId UserMe s) (\pcid (cwd, member) -> Just $ csChannel(pcid).ccInfo %= channelInfoFromChannelWithData cwd member) case prevId of Nothing -> return () Just p -> clearChannelUnreadStatus p refreshChannelsAndUsers :: MH () refreshChannelsAndUsers = do session <- getSession me <- gets myUser knownUsers <- gets allUserIds ts <- use csTeams doAsyncWith Preempt $ do pairs <- forM (HM.keys ts) $ \tId -> do runConcurrently $ (,) <$> Concurrently (MM.mmGetChannelsForUser UserMe tId session) <*> Concurrently (MM.mmGetChannelMembersForUser UserMe tId session) let (chans, datas) = (mconcat $ fst <$> pairs, mconcat $ snd <$> pairs) Collect all user IDs associated with DM channels so we can let dmUsers = catMaybes $ flip map (F.toList chans) $ \chan -> case chan^.channelTypeL of Direct -> case userIdForDMChannel (userId me) (sanitizeUserText $ channelName chan) of Nothing -> Nothing Just otherUserId -> Just otherUserId _ -> Nothing uIdsToFetch = nub $ userId me : knownUsers <> dmUsers dataMap = HM.fromList $ toList $ (\d -> (channelMemberChannelId d, d)) <$> datas mkPair chan = (chan, fromJust $ HM.lookup (channelId chan) dataMap) chansWithData = mkPair <$> chans return $ Just $ Fetch user data associated with DM channels handleNewUsers (Seq.fromList uIdsToFetch) $ do forM_ chansWithData $ uncurry (refreshChannel SidebarUpdateDeferred) updateSidebar Nothing SidebarUpdateImmediate unless you are very sure you know what you are refreshChannel :: SidebarUpdate -> Channel -> ChannelMember -> MH () refreshChannel upd chan member = do ts <- use csTeams let ourTeams = HM.keys ts isOurTeam = case channelTeamId chan of Nothing -> True Just tId -> tId `elem` ourTeams case isOurTeam of False -> return () True -> do let cId = getId chan If this channel is unknown , register it first . mChan <- preuse (csChannel(cId)) when (isNothing mChan) $ handleNewChannel False upd chan member updateChannelInfo cId chan member handleNewChannel :: Bool -> SidebarUpdate -> Channel -> ChannelMember -> MH () handleNewChannel = handleNewChannel_ True handleNewChannel_ :: Bool a DM channel user record . This is to prevent -> Bool -> SidebarUpdate SidebarUpdateImmediate unless you know what -> Channel -> ChannelMember -> MH () handleNewChannel_ permitPostpone switch sbUpdate nc member = do me <- gets myUser mChan <- preuse (csChannel(getId nc)) case mChan of Just ch -> do mtId <- case ch^.ccInfo.cdTeamId of Nothing -> use csCurrentTeamId Just i -> return $ Just i when switch $ case mtId of Nothing -> return () Just tId -> setFocus tId (getId nc) Nothing -> do eventQueue <- use (csResources.crEventQueue) spellChecker <- use (csResources.crSpellChecker) Create a new ClientChannel structure cChannel <- (ccInfo %~ channelInfoFromChannelWithData nc member) <$> makeClientChannel eventQueue spellChecker (me^.userIdL) (channelTeamId nc) nc st <- use id let chType = nc^.channelTypeL register <- case chType of Direct -> case userIdForDMChannel (myUserId st) (sanitizeUserText $ channelName nc) of Nothing -> return True Just otherUserId -> case userById otherUserId st of Nothing -> do case permitPostpone of False -> return True True -> do mhLog LogAPI $ T.pack $ "handleNewChannel_: about to call handleNewUsers for " <> show otherUserId handleNewUsers (Seq.singleton otherUserId) (return ()) doAsyncWith Normal $ return $ Just $ handleNewChannel_ False switch sbUpdate nc member return False Just _ -> return True _ -> return True when register $ do csChannels %= addChannel (getId nc) cChannel when (sbUpdate == SidebarUpdateImmediate) $ do updateSidebar (cChannel^.ccInfo.cdTeamId) chanTeam <- case cChannel^.ccInfo.cdTeamId of Nothing -> use csCurrentTeamId Just i -> return $ Just i channel addition triggered by a /join . case chanTeam of Nothing -> return () Just tId -> do pending1 <- checkPendingChannelChange tId (getId nc) pending2 <- case cChannel^.ccInfo.cdDMUserId of Nothing -> return False Just uId -> checkPendingChannelChangeByUserId tId uId when (switch || isJust pending1 || pending2) $ do setFocus tId (getId nc) case pending1 of Just (Just act) -> act _ -> return () actual setFocus switch to the channel because there may be multiple checkPendingChannelChange :: TeamId -> ChannelId -> MH (Maybe (Maybe (MH ()))) checkPendingChannelChange curTid cId = do ch <- use (csTeam(curTid).tsPendingChannelChange) return $ case ch of Just (ChangeByChannelId tId i act) -> if i == cId && curTid == tId then Just act else Nothing _ -> Nothing actual setFocus switch to the channel because there may be multiple checkPendingChannelChangeByUserId :: TeamId -> UserId -> MH Bool checkPendingChannelChangeByUserId tId uId = do ch <- use (csTeam(tId).tsPendingChannelChange) return $ case ch of Just (ChangeByUserId i) -> i == uId _ -> False updateChannelInfo :: ChannelId -> Channel -> ChannelMember -> MH () updateChannelInfo cid new member = do invalidateChannelRenderingCache cid csChannel(cid).ccInfo %= channelInfoFromChannelWithData new member withChannel cid $ \chan -> updateSidebar (chan^.ccInfo.cdTeamId) setFocus :: TeamId -> ChannelId -> MH () setFocus tId cId = do showChannelInSidebar cId True setFocusWith tId True (Z.findRight ((== cId) . channelListEntryChannelId)) (return ()) (return ()) setFocusWith :: TeamId -> Bool -> (Zipper ChannelListGroup ChannelListEntry -> Zipper ChannelListGroup ChannelListEntry) -> MH () -> MH () -> MH () setFocusWith tId updatePrev f onChange onNoChange = do oldZipper <- use (csTeam(tId).tsFocus) mOldCid <- use (csCurrentChannelId tId) let newZipper = f oldZipper newFocus = Z.focus newZipper oldFocus = Z.focus oldZipper if newFocus /= oldFocus then do mh $ invalidateCacheEntry $ ChannelSidebar tId case mOldCid of Nothing -> return () Just cId -> resetAutocomplete (channelEditor(cId)) preChangeChannelCommon tId csTeam(tId).tsFocus .= newZipper now <- liftIO getCurrentTime mNewCid <- use (csCurrentChannelId tId) case mNewCid of Nothing -> return () Just newCid -> do csChannel(newCid).ccInfo.cdSidebarShowOverride .= Just now updateViewed updatePrev postChangeChannelCommon tId case newFocus of Nothing -> return () Just _ -> mh $ makeVisible $ SelectedChannelListEntry tId onChange else onNoChange postChangeChannelCommon :: TeamId -> MH () postChangeChannelCommon tId = do fetchVisibleIfNeeded tId loadLastChannelInput :: Lens' ChatState (MessageInterface n i) -> MH () loadLastChannelInput which = do inputHistoryPos <- use (which.miEditor.esEphemeral.eesInputHistoryPosition) case inputHistoryPos of Just i -> void $ loadHistoryEntryToEditor which i Nothing -> do (lastEdit, lastEditMode) <- use (which.miEditor.esEphemeral.eesLastInput) which.miEditor.esEditor %= (applyEdit $ insertMany lastEdit . clearZipper) which.miEditor.esEditMode .= lastEditMode preChangeChannelCommon :: TeamId -> MH () preChangeChannelCommon tId = do withCurrentChannel tId $ \cId _ -> do csTeam(tId).tsRecentChannel .= Just cId saveEditorInput :: Lens' ChatState (MessageInterface n i) -> MH () saveEditorInput which = do cmdLine <- use (which.miEditor.esEditor) mode <- use (which.miEditor.esEditMode) inputHistoryPos <- use (which.miEditor.esEphemeral.eesInputHistoryPosition) when (isNothing inputHistoryPos) $ which.miEditor.esEphemeral.eesLastInput .= (T.intercalate "\n" $ getEditContents $ cmdLine, mode) applyPreferenceChange :: Preference -> MH () applyPreferenceChange pref = do csResources.crUserPreferences %= setUserPreferences (Seq.singleton pref) Invalidate the entire rendering cache since many things depend on mh invalidateCache if | Just f <- preferenceToFlaggedPost pref -> do updateMessageFlag (flaggedPostId f) (flaggedPostStatus f) | Just tIds <- preferenceToTeamOrder pref -> applyTeamOrder tIds | Just d <- preferenceToDirectChannelShowStatus pref -> do updateSidebar Nothing cs <- use csChannels let cId = fromJust $ getDmChannelFor (directChannelShowUserId d) cs case directChannelShowValue d of True -> do withCurrentTeam $ \tId -> do pending <- checkPendingChannelChange tId cId case pending of Just mAct -> do setFocus tId cId fromMaybe (return ()) mAct Nothing -> return () False -> do csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing | Just g <- preferenceToGroupChannelPreference pref -> do updateSidebar Nothing let cId = groupChannelId g case groupChannelShow g of True -> do withCurrentTeam $ \tId -> do pending <- checkPendingChannelChange tId cId case pending of Just mAct -> do setFocus tId cId fromMaybe (return ()) mAct Nothing -> return () False -> do csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing | Just f <- preferenceToFavoriteChannelPreference pref -> do updateSidebar Nothing let cId = favoriteChannelId f case favoriteChannelShow f of True -> do withCurrentTeam $ \tId -> do pending <- checkPendingChannelChange tId cId case pending of Just mAct -> do setFocus tId cId fromMaybe (return ()) mAct Nothing -> return () False -> do csChannel(cId).ccInfo.cdSidebarShowOverride .= Nothing | otherwise -> return () refreshChannelById :: ChannelId -> MH () refreshChannelById cId = do session <- getSession doAsyncWith Preempt $ do cwd <- MM.mmGetChannel cId session member <- MM.mmGetChannelMember cId UserMe session return $ Just $ do refreshChannel SidebarUpdateImmediate cwd member removeChannelFromState :: ChannelId -> MH () removeChannelFromState cId = do withChannel cId $ \ chan -> do when (chan^.ccInfo.cdType /= Direct) $ do case chan^.ccInfo.cdTeamId of Nothing -> return () Just tId -> do origFocus <- use (csCurrentChannelId tId) when (origFocus == Just cId) (nextChannelSkipPrevView tId) csInputHistory %= removeChannelHistory cId csChannels %= removeChannel cId case chan^.ccInfo.cdTeamId of Nothing -> do ts <- use csTeams forM_ (HM.keys ts) $ \tId -> csTeam(tId).tsFocus %= Z.filterZipper ((/= cId) . channelListEntryChannelId) Just tId -> do csTeam(tId).tsFocus %= Z.filterZipper ((/= cId) . channelListEntryChannelId) updateSidebar $ chan^.ccInfo.cdTeamId nextChannel :: TeamId -> MH () nextChannel tId = do resetReturnChannel tId let checkForFirst = do z <- use (csTeam(tId).tsFocus) case Z.focus z of Nothing -> return () Just entry -> do If the newly - selected channel is the first when (entry == (head $ concat $ snd <$> Z.toList z)) $ do mh $ vScrollToBeginning $ viewportScroll (ChannelListViewport tId) setFocusWith tId True Z.right checkForFirst (return ()) nextChannelSkipPrevView :: TeamId -> MH () nextChannelSkipPrevView tId = setFocusWith tId False Z.right (return ()) (return ()) prevChannel :: TeamId -> MH () prevChannel tId = do resetReturnChannel tId setFocusWith tId True Z.left (return ()) (return ()) recentChannel :: TeamId -> MH () recentChannel tId = do recent <- use (csTeam(tId).tsRecentChannel) case recent of Nothing -> return () Just cId -> do ret <- use (csTeam(tId).tsReturnChannel) when (ret == Just cId) (resetReturnChannel tId) setFocus tId cId resetReturnChannel :: TeamId -> MH () resetReturnChannel tId = do val <- use (csTeam(tId).tsReturnChannel) case val of Nothing -> return () Just _ -> do mh $ invalidateCacheEntry $ ChannelSidebar tId csTeam(tId).tsReturnChannel .= Nothing gotoReturnChannel :: TeamId -> MH () gotoReturnChannel tId = do ret <- use (csTeam(tId).tsReturnChannel) case ret of Nothing -> return () Just cId -> do resetReturnChannel tId setFocus tId cId setReturnChannel :: TeamId -> MH () setReturnChannel tId = do ret <- use (csTeam(tId).tsReturnChannel) case ret of Nothing -> do withCurrentChannel tId $ \cId _ -> do csTeam(tId).tsReturnChannel .= Just cId mh $ invalidateCacheEntry $ ChannelSidebar tId Just _ -> return () nextUnreadChannel :: TeamId -> MH () nextUnreadChannel tId = do st <- use id setReturnChannel tId setFocusWith tId True (getNextUnreadChannel st tId) (return ()) (gotoReturnChannel tId) nextUnreadUserOrChannel :: TeamId -> MH () nextUnreadUserOrChannel tId = do st <- use id setReturnChannel tId setFocusWith tId True (getNextUnreadUserOrChannel st tId) (return ()) (gotoReturnChannel tId) leaveChannel :: ChannelId -> MH () leaveChannel cId = leaveChannelIfPossible cId False leaveChannelIfPossible :: ChannelId -> Bool -> MH () leaveChannelIfPossible cId delete = do st <- use id me <- gets myUser let isMe u = u^.userIdL == me^.userIdL case st ^? csChannel(cId).ccInfo of Nothing -> return () Just cInfo -> case canLeaveChannel cInfo of False -> return () True -> just ask for the first two members of the channel . If there is only one , it must be us : hence the " all isMe " check below . If there are two members , it doAsyncChannelMM Preempt cId (\s _ -> let query = MM.defaultUserQuery { MM.userQueryPage = Just 0 , MM.userQueryPerPage = Just 2 , MM.userQueryInChannel = Just cId } in toList <$> MM.mmGetUsers query s) (\_ members -> Just $ do let func = case cInfo^.cdType of Private -> case all isMe members of True -> (\ s c -> MM.mmDeleteChannel c s) False -> (\ s c -> MM.mmRemoveUserFromChannel c UserMe s) Group -> \s _ -> let pref = hideGroupChannelPref cId (me^.userIdL) in MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) s _ -> if delete then (\ s c -> MM.mmDeleteChannel c s) else (\ s c -> MM.mmRemoveUserFromChannel c UserMe s) doAsyncChannelMM Preempt cId func endAsyncNOP ) getNextUnreadChannel :: ChatState -> TeamId -> (Zipper a ChannelListEntry -> Zipper a ChannelListEntry) getNextUnreadChannel st tId = Z.findRight (\e -> let cId = channelListEntryChannelId e in channelListEntryUnread e && (Just cId /= st^.csCurrentChannelId(tId))) getNextUnreadUserOrChannel :: ChatState -> TeamId -> Zipper a ChannelListEntry -> Zipper a ChannelListEntry getNextUnreadUserOrChannel st tId z = let cur = st^.csCurrentChannelId(tId) matches e = entryIsDMEntry e && isFresh e isFresh e = channelListEntryUnread e && (Just (channelListEntryChannelId e) /= cur) in fromMaybe (Z.findRight isFresh z) (Z.maybeFindRight matches z) leaveCurrentChannel :: TeamId -> MH () leaveCurrentChannel tId = do withCurrentChannel tId $ \cId _ -> do leaveChannel cId createGroupChannel :: TeamId -> Text -> MH () createGroupChannel tId usernameList = do me <- gets myUser session <- getSession cs <- use csChannels doAsyncWith Preempt $ do let usernames = Seq.fromList $ fmap trimUserSigil $ T.words usernameList results <- MM.mmGetUsersByUsernames usernames session case length results == length usernames of True -> do chan <- MM.mmCreateGroupMessageChannel (userId <$> results) session return $ Just $ do case findChannelById (channelId chan) cs of Just _ -> setFocus tId (channelId chan) Nothing -> do csTeam(tId).tsPendingChannelChange .= (Just $ ChangeByChannelId tId (channelId chan) Nothing) let pref = showGroupChannelPref (channelId chan) (me^.userIdL) doAsyncWith Normal $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return $ Just $ applyPreferenceChange pref False -> do let foundUsernames = userUsername <$> results missingUsernames = S.toList $ S.difference (S.fromList $ F.toList usernames) (S.fromList $ F.toList foundUsernames) return $ Just $ do forM_ missingUsernames (mhError . NoSuchUser) inputHistoryForward :: Lens' ChatState (MessageInterface n i) -> MH () inputHistoryForward which = do resetAutocomplete (which.miEditor) inputHistoryPos <- use (which.miEditor.esEphemeral.eesInputHistoryPosition) case inputHistoryPos of Just i | i == 0 -> do which.miEditor.esEphemeral.eesInputHistoryPosition .= Nothing loadLastChannelInput which | otherwise -> do let newI = i - 1 loaded <- loadHistoryEntryToEditor which newI when loaded $ which.miEditor.esEphemeral.eesInputHistoryPosition .= (Just newI) _ -> return () loadHistoryEntryToEditor :: Lens' ChatState (MessageInterface n i) -> Int -> MH Bool loadHistoryEntryToEditor which idx = do cId <- use (which.miChannelId) inputHistory <- use csInputHistory case getHistoryEntry cId idx inputHistory of Nothing -> return False Just entry -> do let eLines = T.lines entry mv = if length eLines == 1 then gotoEOL else id which.miEditor.esEditor.editContentsL .= (mv $ textZipper eLines Nothing) cfg <- use (csResources.crConfiguration) when (configShowMessagePreview cfg) $ invalidateChannelRenderingCache cId return True inputHistoryBackward :: Lens' ChatState (MessageInterface n i) -> MH () inputHistoryBackward which = do resetAutocomplete (which.miEditor) inputHistoryPos <- use (which.miEditor.esEphemeral.eesInputHistoryPosition) saveEditorInput which let newI = maybe 0 (+ 1) inputHistoryPos loaded <- loadHistoryEntryToEditor which newI when loaded $ which.miEditor.esEphemeral.eesInputHistoryPosition .= (Just newI) createOrdinaryChannel :: TeamId -> Bool -> Text -> MH () createOrdinaryChannel myTId public name = do session <- getSession doAsyncWith Preempt $ do let slug = T.map (\ c -> if isAlphaNum c then c else '-') (T.toLower name) minChannel = MinChannel { minChannelName = slug , minChannelDisplayName = name , minChannelPurpose = Nothing , minChannelHeader = Nothing , minChannelType = if public then Ordinary else Private , minChannelTeamId = myTId } tryMM (do c <- MM.mmCreateChannel minChannel session chan <- MM.mmGetChannel (getId c) session member <- MM.mmGetChannelMember (getId c) UserMe session return (chan, member) ) (return . Just . uncurry (handleNewChannel True SidebarUpdateImmediate)) handleChannelInvite :: ChannelId -> MH () handleChannelInvite cId = do session <- getSession doAsyncWith Normal $ do member <- MM.mmGetChannelMember cId UserMe session tryMM (MM.mmGetChannel cId session) (\cwd -> return $ Just $ do mtId <- case channelTeamId cwd of Nothing -> use csCurrentTeamId Just i -> return $ Just i pending <- case mtId of Nothing -> return Nothing Just tId -> checkPendingChannelChange tId cId handleNewChannel (isJust pending) SidebarUpdateImmediate cwd member) addUserByNameToCurrentChannel :: TeamId -> Text -> MH () addUserByNameToCurrentChannel tId uname = withFetchedUser (UserFetchByUsername uname) (addUserToCurrentChannel tId) addUserToCurrentChannel :: TeamId -> UserInfo -> MH () addUserToCurrentChannel tId u = do withCurrentChannel tId $ \cId _ -> do session <- getSession let channelMember = MinChannelMember (u^.uiId) cId doAsyncWith Normal $ do tryMM (void $ MM.mmAddUser cId channelMember session) (const $ return Nothing) removeUserFromCurrentChannel :: TeamId -> Text -> MH () removeUserFromCurrentChannel tId uname = withCurrentChannel tId $ \cId _ -> do withFetchedUser (UserFetchByUsername uname) $ \u -> do session <- getSession doAsyncWith Normal $ do tryMM (void $ MM.mmRemoveUserFromChannel cId (UserById $ u^.uiId) session) (const $ return Nothing) startLeaveCurrentChannel :: TeamId -> MH () startLeaveCurrentChannel tId = do withCurrentChannel tId $ \_ ch -> do case ch^.ccInfo.cdType of Direct -> hideDMChannel (ch^.ccInfo.cdChannelId) Group -> hideDMChannel (ch^.ccInfo.cdChannelId) _ -> pushMode tId LeaveChannelConfirm deleteCurrentChannel :: TeamId -> MH () deleteCurrentChannel tId = do withCurrentChannel tId $ \cId _ -> do leaveChannelIfPossible cId True isCurrentChannel :: ChatState -> TeamId -> ChannelId -> Bool isCurrentChannel st tId cId = st^.csCurrentChannelId(tId) == Just cId isRecentChannel :: ChatState -> TeamId -> ChannelId -> Bool isRecentChannel st tId cId = st^.csTeam(tId).tsRecentChannel == Just cId isReturnChannel :: ChatState -> TeamId -> ChannelId -> Bool isReturnChannel st tId cId = st^.csTeam(tId).tsReturnChannel == Just cId joinChannelByName :: TeamId -> Text -> MH () joinChannelByName tId rawName = do session <- getSession doAsyncWith Preempt $ do result <- try $ MM.mmGetChannelByName tId (trimChannelSigil rawName) session return $ Just $ case result of Left (_::SomeException) -> mhError $ NoSuchChannel rawName Right chan -> joinChannel tId $ getId chan joinChannel :: TeamId -> ChannelId -> MH () joinChannel tId chanId = joinChannel' tId chanId Nothing joinChannel' :: TeamId -> ChannelId -> Maybe (MH ()) -> MH () joinChannel' tId chanId act = do mChan <- preuse (csChannel(chanId)) case mChan of Just _ -> do setFocus tId chanId fromMaybe (return ()) act Nothing -> do myId <- gets myUserId let member = MinChannelMember myId chanId csTeam(tId).tsPendingChannelChange .= (Just $ ChangeByChannelId tId chanId act) doAsyncChannelMM Preempt chanId (\ s c -> MM.mmAddUser c member s) (const $ return act) createOrFocusDMChannel :: TeamId -> UserInfo -> Maybe (ChannelId -> MH ()) -> MH () createOrFocusDMChannel tId user successAct = do cs <- use csChannels case getDmChannelFor (user^.uiId) cs of Just cId -> do setFocus tId cId case successAct of Nothing -> return () Just act -> act cId Nothing -> do myId <- gets myUserId session <- getSession csTeam(tId).tsPendingChannelChange .= (Just $ ChangeByUserId $ user^.uiId) doAsyncWith Normal $ do chan <- MM.mmCreateDirectMessageChannel (user^.uiId, myId) session return $ successAct <*> pure (channelId chan) changeChannelByName :: TeamId -> Text -> MH () changeChannelByName tId name = do myId <- gets myUserId mCId <- gets (channelIdByChannelName tId name) mDMCId <- gets (channelIdByUsername name) withFetchedUserMaybe (UserFetchByUsername name) $ \foundUser -> do if (_uiId <$> foundUser) == Just myId then return () else do let err = mhError $ AmbiguousName name case (mCId, mDMCId) of (Nothing, Nothing) -> case foundUser of We know about the user but there is n't already a DM Just user -> createOrFocusDMChannel tId user Nothing Nothing -> mhError $ NoSuchChannel name (Just cId, Nothing) | normalChannelSigil `T.isPrefixOf` name -> setFocus tId cId no DM channel . | Just _ <- foundUser -> err | otherwise -> setFocus tId cId (Nothing, Just cId) -> We matched a DM channel only . setFocus tId cId (Just _, Just _) -> We matched both a channel and a DM channel . err setChannelTopic :: TeamId -> Text -> MH () setChannelTopic tId msg = do withCurrentChannel tId $ \cId _ -> do let patch = defaultChannelPatch { channelPatchHeader = Just msg } doAsyncChannelMM Preempt cId (\s _ -> MM.mmPatchChannel cId patch s) (\_ _ -> Nothing) name in Matterhorn yet ; that is handled by a websocket event handled renameChannelUrl :: TeamId -> Text -> MH () renameChannelUrl tId name = do withCurrentChannel tId $ \cId _ -> do s <- getSession let patch = defaultChannelPatch { channelPatchName = Just name } doAsyncWith Normal $ do _ <- MM.mmPatchChannel cId patch s return Nothing getCurrentChannelTopic :: TeamId -> MH (Maybe Text) getCurrentChannelTopic tId = withCurrentChannel' tId $ \_ c -> do return $ Just $ c^.ccInfo.cdHeader beginCurrentChannelDeleteConfirm :: TeamId -> MH () beginCurrentChannelDeleteConfirm tId = do withCurrentChannel tId $ \_ chan -> do let chType = chan^.ccInfo.cdType if chType /= Direct then pushMode tId DeleteChannelConfirm else mhError $ GenericError "Direct message channels cannot be deleted." updateChannelNotifyProps :: ChannelId -> ChannelNotifyProps -> MH () updateChannelNotifyProps cId notifyProps = do withChannel cId $ \chan -> do csChannel(cId).ccInfo.cdNotifyProps .= notifyProps updateSidebar (chan^.ccInfo.cdTeamId) toggleChannelFavoriteStatus :: TeamId -> MH () toggleChannelFavoriteStatus tId = do myId <- gets myUserId withCurrentChannel tId $ \cId _ -> do userPrefs <- use (csResources.crUserPreferences) session <- getSession let favPref = favoriteChannelPreference userPrefs cId trueVal = "true" prefVal = case favPref of Just True -> "" Just False -> trueVal Nothing -> trueVal pref = Preference { preferenceUserId = myId , preferenceCategory = PreferenceCategoryFavoriteChannel , preferenceName = PreferenceName $ idString cId , preferenceValue = PreferenceValue prefVal } doAsyncWith Normal $ do MM.mmSaveUsersPreferences UserMe (Seq.singleton pref) session return Nothing toggleChannelListGroupVisibility :: ChannelListGroupLabel -> MH () toggleChannelListGroupVisibility label = do withCurrentTeam $ \tId -> do csHiddenChannelGroups %= \hidden -> let s' = case HM.lookup tId hidden of Nothing -> S.singleton label Just s -> if S.member label s then S.delete label s else S.insert label s in HM.insert tId s' hidden updateSidebar Nothing toggleCurrentChannelChannelListGroup :: TeamId -> MH () toggleCurrentChannelChannelListGroup tId = do withCurrentChannel tId $ \_ _ -> do z <- use (csTeam(tId).tsFocus) case Z.focusHeading z of Nothing -> return () Just grp -> toggleChannelListGroupVisibility $ channelListGroupLabel grp toggleCurrentChannelChannelListGroupByName :: T.Text -> TeamId -> MH () toggleCurrentChannelChannelListGroupByName name tId = do withCurrentChannel tId $ \_ _ -> do case lookup (T.toLower $ T.strip name) channelListGroupNames of Nothing -> postErrorMessage' $ "Invalid group name: " <> name Just l -> toggleChannelListGroupVisibility l channelListSortingModes :: [(ChannelListSorting, T.Text)] channelListSortingModes = [ (ChannelListSortDefault, "alphabetic") , (ChannelListSortUnreadFirst, "alphabetic with unread channels first") ] cycleChannelListSortingMode :: TeamId -> MH () cycleChannelListSortingMode tId = do curMode <- use (csTeam(tId).tsChannelListSorting) when (curMode `notElem` (fst <$> channelListSortingModes)) $ error $ "BUG: active channel list sorting mode unknown (" <> show curMode <> ")" let (newMode, newModeDesc) = sortingModeAfter curMode sortingModeAfter m = head $ drop 1 $ snd $ span ((/= m) . fst) $ cycle channelListSortingModes postInfoMessage $ "Sorting channel list: " <> newModeDesc csTeam(tId).tsChannelListSorting .= newMode updateSidebar $ Just tId
fc73b64a8186ed99d69387927cc8154bb7d00f459b618d14ac03485a50660f3a
expipiplus1/vulkan
VK_AMD_texture_gather_bias_lod.hs
{-# language CPP #-} -- | = Name -- -- VK_AMD_texture_gather_bias_lod - device extension -- -- == VK_AMD_texture_gather_bias_lod -- -- [__Name String__] -- @VK_AMD_texture_gather_bias_lod@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] 42 -- -- [__Revision__] 1 -- -- [__Extension and Version Dependencies__] -- - Requires support for Vulkan 1.0 -- -- - Requires @VK_KHR_get_physical_device_properties2@ to be enabled -- for any device-level functionality -- -- [__Contact__] -- - -- <-Docs/issues/new?body=[VK_AMD_texture_gather_bias_lod] @amdrexu%0A*Here describe the issue or question you have about the VK_AMD_texture_gather_bias_lod extension* > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] 2017 - 03 - 21 -- -- [__IP Status__] -- No known IP claims. -- -- [__Interactions and External Dependencies__] -- -- - This extension requires -- <-Registry/blob/master/extensions/AMD/SPV_AMD_texture_gather_bias_lod.html SPV_AMD_texture_gather_bias_lod> -- -- - This extension provides API support for < > -- -- [__Contributors__] -- - , AMD -- - , AMD -- - , AMD -- - , AMD -- - , AMD -- - , AMD -- - , AMD -- -- == Description -- This extension adds two related features . -- Firstly , support for the following SPIR - V extension in Vulkan is added : -- -- - @SPV_AMD_texture_gather_bias_lod@ -- Secondly , the extension allows the application to query which formats -- can be used together with the new function prototypes introduced by the -- SPIR-V extension. -- -- == New Structures -- -- - Extending ' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.ImageFormatProperties2 ' : -- - ' ' -- -- == New Enum Constants -- -- - 'AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME' -- - ' ' -- - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : -- - ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD ' -- -- == New SPIR-V Capabilities -- - < ImageGatherBiasLodAMD > -- -- == Examples -- -- > struct VkTextureLODGatherFormatPropertiesAMD -- > { > ; > const void * pNext ; > VkBool32 supportsTextureGatherLODBiasAMD ; -- > }; -- > -- > // ---------------------------------------------------------------------------------------- -- > // How to detect if an image format can be used with the new function prototypes. -- > VkPhysicalDeviceImageFormatInfo2 formatInfo; > VkImageFormatProperties2 formatProps ; -- > VkTextureLODGatherFormatPropertiesAMD textureLODGatherSupport; -- > -- > textureLODGatherSupport.sType = VK_STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD; -- > textureLODGatherSupport.pNext = nullptr; -- > -- > formatInfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2; > formatInfo.pNext = nullptr ; > = ... ; -- > formatInfo.type = ...; -- > formatInfo.tiling = ...; -- > formatInfo.usage = ...; > = ... ; -- > > formatProps.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2 ; -- > formatProps.pNext = &textureLODGatherSupport; -- > -- > vkGetPhysicalDeviceImageFormatProperties2(physical_device, &formatInfo, &formatProps); -- > -- > if (textureLODGatherSupport.supportsTextureGatherLODBiasAMD == VK_TRUE) -- > { -- > // physical device supports SPV_AMD_texture_gather_bias_lod for the specified -- > // format configuration. -- > } -- > else -- > { -- > // physical device does not support SPV_AMD_texture_gather_bias_lod for the -- > // specified format configuration. -- > } -- -- == Version History -- - Revision 1 , 2017 - 03 - 21 ( ) -- -- - Initial draft -- -- == See Also -- ' ' -- -- == Document Notes -- -- For more information, see the -- <-extensions/html/vkspec.html#VK_AMD_texture_gather_bias_lod Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_AMD_texture_gather_bias_lod ( TextureLODGatherFormatPropertiesAMD(..) , AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION , pattern AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION , AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME , pattern AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME ) where import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) 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.Kind (Type) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD)) -- | VkTextureLODGatherFormatPropertiesAMD - Structure informing whether or -- not texture gather bias\/LOD functionality is supported for a given -- image format and a given physical device. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_AMD_texture_gather_bias_lod VK_AMD_texture_gather_bias_lod>, ' Vulkan . Core10.FundamentalTypes . Bool32 ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data TextureLODGatherFormatPropertiesAMD = TextureLODGatherFormatPropertiesAMD | tells if the image format can be used -- with texture gather bias\/LOD functions, as introduced by the -- @VK_AMD_texture_gather_bias_lod@ extension. This field is set by the -- implementation. User-specified value is ignored. supportsTextureGatherLODBiasAMD :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (TextureLODGatherFormatPropertiesAMD) #endif deriving instance Show TextureLODGatherFormatPropertiesAMD instance ToCStruct TextureLODGatherFormatPropertiesAMD where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p TextureLODGatherFormatPropertiesAMD{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (supportsTextureGatherLODBiasAMD)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct TextureLODGatherFormatPropertiesAMD where peekCStruct p = do supportsTextureGatherLODBiasAMD <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) pure $ TextureLODGatherFormatPropertiesAMD (bool32ToBool supportsTextureGatherLODBiasAMD) instance Storable TextureLODGatherFormatPropertiesAMD where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero TextureLODGatherFormatPropertiesAMD where zero = TextureLODGatherFormatPropertiesAMD zero type AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION = 1 No documentation found for TopLevel " VK_AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION " pattern AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION :: forall a . Integral a => a pattern AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION = 1 type AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME = "VK_AMD_texture_gather_bias_lod" No documentation found for TopLevel " VK_AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME " pattern AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME = "VK_AMD_texture_gather_bias_lod"
null
https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/src/Vulkan/Extensions/VK_AMD_texture_gather_bias_lod.hs
haskell
# language CPP # | = Name VK_AMD_texture_gather_bias_lod - device extension == VK_AMD_texture_gather_bias_lod [__Name String__] @VK_AMD_texture_gather_bias_lod@ [__Extension Type__] Device extension [__Registered Extension Number__] [__Revision__] [__Extension and Version Dependencies__] - Requires @VK_KHR_get_physical_device_properties2@ to be enabled for any device-level functionality [__Contact__] <-Docs/issues/new?body=[VK_AMD_texture_gather_bias_lod] @amdrexu%0A*Here describe the issue or question you have about the VK_AMD_texture_gather_bias_lod extension* > == Other Extension Metadata [__Last Modified Date__] [__IP Status__] No known IP claims. [__Interactions and External Dependencies__] - This extension requires <-Registry/blob/master/extensions/AMD/SPV_AMD_texture_gather_bias_lod.html SPV_AMD_texture_gather_bias_lod> - This extension provides API support for [__Contributors__] == Description - @SPV_AMD_texture_gather_bias_lod@ can be used together with the new function prototypes introduced by the SPIR-V extension. == New Structures - Extending == New Enum Constants - 'AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME' == New SPIR-V Capabilities == Examples > struct VkTextureLODGatherFormatPropertiesAMD > { > }; > > // ---------------------------------------------------------------------------------------- > // How to detect if an image format can be used with the new function prototypes. > VkPhysicalDeviceImageFormatInfo2 formatInfo; > VkTextureLODGatherFormatPropertiesAMD textureLODGatherSupport; > > textureLODGatherSupport.sType = VK_STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD; > textureLODGatherSupport.pNext = nullptr; > > formatInfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2; > formatInfo.type = ...; > formatInfo.tiling = ...; > formatInfo.usage = ...; > > formatProps.pNext = &textureLODGatherSupport; > > vkGetPhysicalDeviceImageFormatProperties2(physical_device, &formatInfo, &formatProps); > > if (textureLODGatherSupport.supportsTextureGatherLODBiasAMD == VK_TRUE) > { > // physical device supports SPV_AMD_texture_gather_bias_lod for the specified > // format configuration. > } > else > { > // physical device does not support SPV_AMD_texture_gather_bias_lod for the > // specified format configuration. > } == Version History - Initial draft == See Also == Document Notes For more information, see the <-extensions/html/vkspec.html#VK_AMD_texture_gather_bias_lod Vulkan Specification> This page is a generated document. Fixes and changes should be made to the generator scripts, not directly. | VkTextureLODGatherFormatPropertiesAMD - Structure informing whether or not texture gather bias\/LOD functionality is supported for a given image format and a given physical device. == Valid Usage (Implicit) = See Also <-extensions/html/vkspec.html#VK_AMD_texture_gather_bias_lod VK_AMD_texture_gather_bias_lod>, with texture gather bias\/LOD functions, as introduced by the @VK_AMD_texture_gather_bias_lod@ extension. This field is set by the implementation. User-specified value is ignored.
42 1 - Requires support for Vulkan 1.0 - 2017 - 03 - 21 < > - , AMD - , AMD - , AMD - , AMD - , AMD - , AMD - , AMD This extension adds two related features . Firstly , support for the following SPIR - V extension in Vulkan is added : Secondly , the extension allows the application to query which formats ' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.ImageFormatProperties2 ' : - ' ' - ' ' - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : - ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD ' - < ImageGatherBiasLodAMD > > ; > const void * pNext ; > VkBool32 supportsTextureGatherLODBiasAMD ; > VkImageFormatProperties2 formatProps ; > formatInfo.pNext = nullptr ; > = ... ; > = ... ; > formatProps.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2 ; - Revision 1 , 2017 - 03 - 21 ( ) ' ' module Vulkan.Extensions.VK_AMD_texture_gather_bias_lod ( TextureLODGatherFormatPropertiesAMD(..) , AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION , pattern AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION , AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME , pattern AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME ) where import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) 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.Kind (Type) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD)) ' Vulkan . Core10.FundamentalTypes . Bool32 ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data TextureLODGatherFormatPropertiesAMD = TextureLODGatherFormatPropertiesAMD | tells if the image format can be used supportsTextureGatherLODBiasAMD :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (TextureLODGatherFormatPropertiesAMD) #endif deriving instance Show TextureLODGatherFormatPropertiesAMD instance ToCStruct TextureLODGatherFormatPropertiesAMD where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p TextureLODGatherFormatPropertiesAMD{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (supportsTextureGatherLODBiasAMD)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct TextureLODGatherFormatPropertiesAMD where peekCStruct p = do supportsTextureGatherLODBiasAMD <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) pure $ TextureLODGatherFormatPropertiesAMD (bool32ToBool supportsTextureGatherLODBiasAMD) instance Storable TextureLODGatherFormatPropertiesAMD where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero TextureLODGatherFormatPropertiesAMD where zero = TextureLODGatherFormatPropertiesAMD zero type AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION = 1 No documentation found for TopLevel " VK_AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION " pattern AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION :: forall a . Integral a => a pattern AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION = 1 type AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME = "VK_AMD_texture_gather_bias_lod" No documentation found for TopLevel " VK_AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME " pattern AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME = "VK_AMD_texture_gather_bias_lod"
3cbe0172740589759424be778b75ac310dd4e0fe4ac4c0f11e865bda3c8c9fc4
aryx/xix
preprocessor.mli
type cmdline_defs = (string * string) list type system_paths = Common.filename list type include_paths = Common.filename * system_paths
null
https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/macroprocessor/preprocessor.mli
ocaml
type cmdline_defs = (string * string) list type system_paths = Common.filename list type include_paths = Common.filename * system_paths
a084ab48fcc754c938b7bbf616c9c78dd24ef8af28c15d3630a99bba57affaa2
replikativ/datahike-frontend
client.cljs
(ns app.client (:require [app.application :refer [SPA]] [app.ui.root :as root] [app.dashboard.ui.queries.datoms :as dui] [app.dashboard.ui.queries.schema :as sui] [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.networking.http-remote :as net] [com.fulcrologic.fulcro.data-fetch :as df] [com.fulcrologic.fulcro.ui-state-machines :as uism] [com.fulcrologic.fulcro.components :as comp] [com.fulcrologic.fulcro-css.css-injection :as cssi] [app.model.session :as session] [taoensso.timbre :as log] [com.fulcrologic.fulcro.algorithms.denormalize :as fdn] [com.fulcrologic.fulcro.algorithms.merge :as merge] [com.fulcrologic.fulcro.routing.dynamic-routing :as dr] [com.fulcrologic.fulcro.inspect.inspect-client :as inspect])) (defn ^:export refresh [] (log/info "Hot code Remount") (cssi/upsert-css "componentcss" {:component root/Root}) (app/mount! SPA root/Root "app")) (defn ^:export init [] (log/info "Application starting.") (cssi/upsert-css "componentcss" {:component root/Root}) ( inspect / app - started ! SPA ) (app/set-root! SPA root/Root {:initialize-state? true}) (dr/initialize! SPA) (log/info "Starting session machine.") (uism/begin! SPA session/session-machine ::session/session {:actor/login-form root/Login :actor/current-session root/Session}) (app/mount! SPA root/Root "app" {:initialize-state? false}) (df/load! SPA :the-schema sui/Schema {:remote :rest-remote}) TODO : now that the table shows an entity on ONE row , this needs to be updated (df/load! SPA :the-datoms dui/Datoms {:remote :rest-remote})) (comment (inspect/app-started! SPA) (app/mounted? SPA) (app/set-root! SPA root/Root {:initialize-state? true}) (uism/begin! SPA session/session-machine ::session/session {:actor/login-form root/Login :actor/current-session root/Session}) (reset! (::app/state-atom SPA) {}) (merge/merge-component! SPA root/Settings {:account/time-zone "America/Los_Angeles" :account/real-name "Joe Schmoe"}) (dr/initialize! SPA) (app/current-state SPA) (dr/change-route SPA ["settings"]) (dr/change-route SPA ["main" "datoms"]) (dr/path-to root/Schema) (app/mount! SPA root/Root "app") (comp/get-query root/Root {}) (comp/get-query root/Root (app/current-state SPA)) (-> SPA ::app/runtime-atom deref ::app/indexes) (comp/class->any SPA root/Root) (let [s (app/current-state SPA)] (fdn/db->tree [{[:component/id :login] [:ui/open? :ui/error :account/email {[:root/current-session '_] (comp/get-query root/Session)} [::uism/asm-id ::session/session]]}] {} s)))
null
https://raw.githubusercontent.com/replikativ/datahike-frontend/6e3ab3bb761b41c4ffea792297286f8942a27909/src/main/app/client.cljs
clojure
(ns app.client (:require [app.application :refer [SPA]] [app.ui.root :as root] [app.dashboard.ui.queries.datoms :as dui] [app.dashboard.ui.queries.schema :as sui] [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.networking.http-remote :as net] [com.fulcrologic.fulcro.data-fetch :as df] [com.fulcrologic.fulcro.ui-state-machines :as uism] [com.fulcrologic.fulcro.components :as comp] [com.fulcrologic.fulcro-css.css-injection :as cssi] [app.model.session :as session] [taoensso.timbre :as log] [com.fulcrologic.fulcro.algorithms.denormalize :as fdn] [com.fulcrologic.fulcro.algorithms.merge :as merge] [com.fulcrologic.fulcro.routing.dynamic-routing :as dr] [com.fulcrologic.fulcro.inspect.inspect-client :as inspect])) (defn ^:export refresh [] (log/info "Hot code Remount") (cssi/upsert-css "componentcss" {:component root/Root}) (app/mount! SPA root/Root "app")) (defn ^:export init [] (log/info "Application starting.") (cssi/upsert-css "componentcss" {:component root/Root}) ( inspect / app - started ! SPA ) (app/set-root! SPA root/Root {:initialize-state? true}) (dr/initialize! SPA) (log/info "Starting session machine.") (uism/begin! SPA session/session-machine ::session/session {:actor/login-form root/Login :actor/current-session root/Session}) (app/mount! SPA root/Root "app" {:initialize-state? false}) (df/load! SPA :the-schema sui/Schema {:remote :rest-remote}) TODO : now that the table shows an entity on ONE row , this needs to be updated (df/load! SPA :the-datoms dui/Datoms {:remote :rest-remote})) (comment (inspect/app-started! SPA) (app/mounted? SPA) (app/set-root! SPA root/Root {:initialize-state? true}) (uism/begin! SPA session/session-machine ::session/session {:actor/login-form root/Login :actor/current-session root/Session}) (reset! (::app/state-atom SPA) {}) (merge/merge-component! SPA root/Settings {:account/time-zone "America/Los_Angeles" :account/real-name "Joe Schmoe"}) (dr/initialize! SPA) (app/current-state SPA) (dr/change-route SPA ["settings"]) (dr/change-route SPA ["main" "datoms"]) (dr/path-to root/Schema) (app/mount! SPA root/Root "app") (comp/get-query root/Root {}) (comp/get-query root/Root (app/current-state SPA)) (-> SPA ::app/runtime-atom deref ::app/indexes) (comp/class->any SPA root/Root) (let [s (app/current-state SPA)] (fdn/db->tree [{[:component/id :login] [:ui/open? :ui/error :account/email {[:root/current-session '_] (comp/get-query root/Session)} [::uism/asm-id ::session/session]]}] {} s)))
61f9293e959503e65fe3c00f6f06bf8346170d6653676da3214fe6c0b7b74410
esl/MongooseIM
mod_event_pusher_push_plugin.erl
%%%------------------------------------------------------------------- @author ( C ) 2017 Erlang Solutions Ltd. This software is released under the Apache License , Version 2.0 cited in ' LICENSE.txt ' . %%% @end %%%------------------------------------------------------------------- %%% @doc %%% Plugin behaviour module for mod_event_pusher_push. %%% This module defines API for some dynamic customizations. %%% @end %%%------------------------------------------------------------------- -module(mod_event_pusher_push_plugin). -author(''). %% API -export([init/2, should_publish/3, prepare_notification/2, publish_notification/4, default_plugin_module/0]). -callback should_publish(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event(), Services :: [mod_event_pusher_push:publish_service()]) -> [mod_event_pusher_push:publish_service()]. -callback prepare_notification(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event()) -> push_payload() | skip. -callback publish_notification(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event(), Payload :: push_payload(), Services :: [mod_event_pusher_push:publish_service()]) -> mongoose_acc:t(). -optional_callbacks([should_publish/3, prepare_notification/2, publish_notification/4]). -type push_payload() :: mod_event_pusher_push:form(). -export_type([push_payload/0]). %%-------------------------------------------------------------------- %% API %%-------------------------------------------------------------------- -spec init(mongooseim:host_type(), gen_mod:module_opts()) -> ok. init(_HostType, #{plugin_module := PluginModule}) -> ensure_loaded(PluginModule), ok. %% @doc used for filtering push notifications. A push notification is triggered for a given %% message only if this callback returns `true'. -spec should_publish(mongoose_acc:t(), mod_event_pusher:event(), [mod_event_pusher_push:publish_service()]) -> [mod_event_pusher_push:publish_service()]. should_publish(Acc, Event, Services) -> HostType = mongoose_acc:host_type(Acc), PluginModule = plugin_module(HostType, should_publish, 3), PluginModule:should_publish(Acc, Event, Services). %% @doc a separate interface for rejecting the event publishing (e.g. when %% message doesn't have a body) or creating push notification payload. -spec prepare_notification(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event()) -> push_payload() | skip. prepare_notification(Acc, Event) -> HostType = mongoose_acc:host_type(Acc), PluginModule = plugin_module(HostType, prepare_notification, 2), PluginModule:prepare_notification(Acc, Event). %% @doc does the actual push. By default it pushes to the registered pubsub %% nodes (or executes the internal hook in case of a publish to a virtual domain). -spec publish_notification(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event(), Payload :: push_payload(), Services :: [mod_event_pusher_push:publish_service()]) -> mongoose_acc:t(). publish_notification(Acc, _Event, _Payload, []) -> Acc; publish_notification(Acc, Event, Payload, Services) -> HostType = mongoose_acc:host_type(Acc), PluginModule = plugin_module(HostType, publish_notification, 4), PluginModule:publish_notification(Acc, Event, Payload, Services). %%-------------------------------------------------------------------- %% Helper functions %%-------------------------------------------------------------------- -spec plugin_module(mongooseim:host_type(), atom(), arity()) -> module(). plugin_module(HostType, Func, Arity) -> Mod = plugin_module(HostType), case erlang:function_exported(Mod, Func, Arity) of true -> Mod; false -> default_plugin_module() end. -spec plugin_module(mongooseim:host_type()) -> module(). plugin_module(HostType) -> gen_mod:get_module_opt(HostType, mod_event_pusher_push, plugin_module). default_plugin_module() -> mod_event_pusher_push_plugin_defaults. -spec ensure_loaded(module()) -> {module, module()}. ensure_loaded(PluginModule) -> {module, PluginModule} = code:ensure_loaded(PluginModule).
null
https://raw.githubusercontent.com/esl/MongooseIM/dda03c16c83f5ea9f5c9b87c3b36c989813b9250/src/event_pusher/mod_event_pusher_push_plugin.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- @doc Plugin behaviour module for mod_event_pusher_push. This module defines API for some dynamic customizations. @end ------------------------------------------------------------------- API -------------------------------------------------------------------- API -------------------------------------------------------------------- @doc used for filtering push notifications. A push notification is triggered for a given message only if this callback returns `true'. @doc a separate interface for rejecting the event publishing (e.g. when message doesn't have a body) or creating push notification payload. @doc does the actual push. By default it pushes to the registered pubsub nodes (or executes the internal hook in case of a publish to a virtual domain). -------------------------------------------------------------------- Helper functions --------------------------------------------------------------------
@author ( C ) 2017 Erlang Solutions Ltd. This software is released under the Apache License , Version 2.0 cited in ' LICENSE.txt ' . -module(mod_event_pusher_push_plugin). -author(''). -export([init/2, should_publish/3, prepare_notification/2, publish_notification/4, default_plugin_module/0]). -callback should_publish(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event(), Services :: [mod_event_pusher_push:publish_service()]) -> [mod_event_pusher_push:publish_service()]. -callback prepare_notification(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event()) -> push_payload() | skip. -callback publish_notification(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event(), Payload :: push_payload(), Services :: [mod_event_pusher_push:publish_service()]) -> mongoose_acc:t(). -optional_callbacks([should_publish/3, prepare_notification/2, publish_notification/4]). -type push_payload() :: mod_event_pusher_push:form(). -export_type([push_payload/0]). -spec init(mongooseim:host_type(), gen_mod:module_opts()) -> ok. init(_HostType, #{plugin_module := PluginModule}) -> ensure_loaded(PluginModule), ok. -spec should_publish(mongoose_acc:t(), mod_event_pusher:event(), [mod_event_pusher_push:publish_service()]) -> [mod_event_pusher_push:publish_service()]. should_publish(Acc, Event, Services) -> HostType = mongoose_acc:host_type(Acc), PluginModule = plugin_module(HostType, should_publish, 3), PluginModule:should_publish(Acc, Event, Services). -spec prepare_notification(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event()) -> push_payload() | skip. prepare_notification(Acc, Event) -> HostType = mongoose_acc:host_type(Acc), PluginModule = plugin_module(HostType, prepare_notification, 2), PluginModule:prepare_notification(Acc, Event). -spec publish_notification(Acc :: mongoose_acc:t(), Event :: mod_event_pusher:event(), Payload :: push_payload(), Services :: [mod_event_pusher_push:publish_service()]) -> mongoose_acc:t(). publish_notification(Acc, _Event, _Payload, []) -> Acc; publish_notification(Acc, Event, Payload, Services) -> HostType = mongoose_acc:host_type(Acc), PluginModule = plugin_module(HostType, publish_notification, 4), PluginModule:publish_notification(Acc, Event, Payload, Services). -spec plugin_module(mongooseim:host_type(), atom(), arity()) -> module(). plugin_module(HostType, Func, Arity) -> Mod = plugin_module(HostType), case erlang:function_exported(Mod, Func, Arity) of true -> Mod; false -> default_plugin_module() end. -spec plugin_module(mongooseim:host_type()) -> module(). plugin_module(HostType) -> gen_mod:get_module_opt(HostType, mod_event_pusher_push, plugin_module). default_plugin_module() -> mod_event_pusher_push_plugin_defaults. -spec ensure_loaded(module()) -> {module, module()}. ensure_loaded(PluginModule) -> {module, PluginModule} = code:ensure_loaded(PluginModule).
940731b745004fcf8a66f2254289ec8c3d73caacda1c8495ff97fc34bb8ccfa1
jyp/glpk-hs
Internal.hs
# LANGUAGE RecordWildCards , ScopedTypeVariables , ForeignFunctionInterface , BangPatterns # module Data.LinearProgram.GLPK.Internal (writeProblem, solveSimplex, mipSolve, getObjVal, getRowPrim, getColPrim, mipObjVal, mipRowVal, mipColVal, getBadRay) where ( writeProblem , addCols , addRows , createIndex , findCol , findRow , getColPrim , getRowPrim , getObjVal , mipColVal , mipRowVal , mipObjVal , mipSolve , setColBounds , setColKind , setColName , setMatRow , , setObjectiveDirection , setRowBounds , setRowName , ) where addRows, createIndex, findCol, findRow, getColPrim, getRowPrim, getObjVal, mipColVal, mipRowVal, mipObjVal, mipSolve, setColBounds, setColKind, setColName, setMatRow, setObjCoef, setObjectiveDirection, setRowBounds, setRowName, solveSimplex) where-} import Control.Monad import Prelude hiding ((+),(*)) import Foreign.Ptr import Foreign.C import Foreign.Marshal.Array import Data.Bits import Data.Map hiding (map) import Data . Bounds import Data.LinearProgram.Common import Data.LinearProgram.GLPK.Types -- foreign import ccall "c_glp_set_obj_name" glpSetObjName :: Ptr GlpProb -> CString -> IO () -- foreign import ccall unsafe "c_glp_set_obj_dir" glpSetObjDir :: Ptr GlpProb -> CInt -> IO () foreign import ccall unsafe "c_glp_minimize" glpMinimize :: Ptr GlpProb -> IO () foreign import ccall unsafe "c_glp_maximize" glpMaximize :: Ptr GlpProb -> IO () foreign import ccall unsafe "c_glp_add_rows" glpAddRows :: Ptr GlpProb -> CInt -> IO CInt foreign import ccall unsafe "c_glp_add_cols" glpAddCols :: Ptr GlpProb -> CInt -> IO CInt foreign import ccall unsafe "c_glp_set_row_bnds" glpSetRowBnds :: Ptr GlpProb -> CInt -> CInt -> CDouble -> CDouble -> IO () foreign import ccall unsafe "c_glp_set_col_bnds" glpSetColBnds :: Ptr GlpProb -> CInt -> CInt -> CDouble -> CDouble -> IO () foreign import ccall unsafe "c_glp_set_obj_coef" glpSetObjCoef :: Ptr GlpProb -> CInt -> CDouble -> IO () foreign import ccall unsafe "c_glp_set_mat_row" glpSetMatRow :: Ptr GlpProb -> CInt -> CInt -> Ptr CInt -> Ptr CDouble -> IO () -- foreign import ccall unsafe "c_glp_create_index" glpCreateIndex :: Ptr GlpProb -> IO () foreign import ccall unsafe " c_glp_find_row " glpFindRow : : Ptr GlpProb - > CString - > IO CInt foreign import ccall unsafe " c_glp_find_col " : : Ptr GlpProb - > CString - > IO CInt foreign import ccall unsafe "c_glp_solve_simplex" glpSolveSimplex :: Ptr GlpProb -> CInt -> CInt -> CInt -> IO CInt foreign import ccall unsafe "c_glp_get_obj_val" glpGetObjVal :: Ptr GlpProb -> IO CDouble foreign import ccall unsafe "c_glp_get_row_prim" glpGetRowPrim :: Ptr GlpProb -> CInt -> IO CDouble foreign import ccall unsafe "c_glp_get_col_prim" glpGetColPrim :: Ptr GlpProb -> CInt -> IO CDouble foreign import ccall unsafe "c_glp_set_col_kind" glpSetColKind :: Ptr GlpProb -> CInt -> CInt -> IO () foreign import ccall unsafe "c_glp_mip_solve" glpMipSolve :: Ptr GlpProb -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CDouble -> CInt -> IO CInt foreign import ccall unsafe "c_glp_mip_obj_val" glpMIPObjVal :: Ptr GlpProb -> IO CDouble foreign import ccall unsafe "c_glp_mip_row_val" glpMIPRowVal :: Ptr GlpProb -> CInt -> IO CDouble foreign import ccall unsafe "c_glp_mip_col_val" glpMIPColVal :: Ptr GlpProb -> CInt -> IO CDouble foreign import ccall unsafe "c_glp_set_row_name" glpSetRowName :: Ptr GlpProb -> CInt -> CString -> IO () foreign import ccall unsafe "c_glp_get_bad_ray" glpGetBadRay :: Ptr GlpProb -> IO CInt setObjectiveDirection :: Direction -> GLPK () setObjectiveDirection dir = GLP $ case dir of Min -> glpMinimize Max -> glpMaximize getBadRay :: GLPK (Maybe Int) getBadRay = liftM (\ x -> guard (x /= 0) >> return (fromIntegral x)) $ GLP glpGetBadRay addRows :: Int -> GLPK Int addRows n = GLP $ liftM fromIntegral . flip glpAddRows (fromIntegral n) addCols :: Int -> GLPK Int addCols n = GLP $ liftM fromIntegral . flip glpAddCols (fromIntegral n) setRowBounds :: Real a => Int -> Bounds a -> GLPK () setRowBounds i bds = GLP $ \ lp -> onBounds (glpSetRowBnds lp (fromIntegral i)) bds setColBounds :: Real a => Int -> Bounds a -> GLPK () setColBounds i bds = GLP $ \ lp -> onBounds (glpSetColBnds lp (fromIntegral i)) bds onBounds :: Real a => (CInt -> CDouble -> CDouble -> x) -> Bounds a -> x onBounds f bds = case bds of Free -> f 1 0 0 LBound a -> f 2 (realToFrac a) 0 UBound a -> f 3 0 (realToFrac a) Bound a b -> f 4 (realToFrac a) (realToFrac b) Equ a -> f 5 (realToFrac a) 0 # SPECIALIZE : : Int - > Double - > GLPK ( ) , Int - > Int - > GLPK ( ) # setObjCoef :: Real a => Int -> a -> GLPK () setObjCoef i v = GLP $ \ lp -> glpSetObjCoef lp (fromIntegral i) (realToFrac v) {-# SPECIALIZE setMatRow :: Int -> [(Int, Double)] -> GLPK (), Int -> [(Int, Int)] -> GLPK () #-} setMatRow :: Real a => Int -> [(Int, a)] -> GLPK () setMatRow i row = GLP $ \ lp -> allocaArray (len+1) $ \ (ixs :: Ptr CInt) -> allocaArray (len+1) $ \ (coeffs :: Ptr CDouble) -> do pokeArray ixs (0:map (fromIntegral . fst) row) pokeArray coeffs (0:map (realToFrac . snd) row) glpSetMatRow lp (fromIntegral i) (fromIntegral len) ixs coeffs where len = length row -- createIndex :: GLPK () createIndex = GLP glpCreateIndex -- findRow :: String -> GLPK Int findRow nam = GLP $ liftM fromIntegral . withCString nam . glpFindRow -- findCol :: String -> GLPK Int findCol nam = GLP $ liftM fromIntegral . withCString . solveSimplex :: MsgLev -> Int -> Bool -> GLPK ReturnCode solveSimplex msglev tmLim presolve = GLP $ \ lp -> liftM (toEnum . fromIntegral) $ glpSolveSimplex lp (getMsgLev msglev) tmLim' (if presolve then 1 else 0) where tmLim' = fromIntegral (tmLim * 1000) getMsgLev :: MsgLev -> CInt getMsgLev = fromIntegral . fromEnum getObjVal :: GLPK Double getObjVal = liftM realToFrac $ GLP glpGetObjVal getRowPrim :: Int -> GLPK Double getRowPrim i = liftM realToFrac $ GLP (`glpGetRowPrim` fromIntegral i) getColPrim :: Int -> GLPK Double getColPrim i = liftM realToFrac $ GLP (`glpGetColPrim` fromIntegral i) setColKind :: Int -> VarKind -> GLPK () setColKind i kind = GLP $ \ lp -> glpSetColKind lp (fromIntegral i) (fromIntegral $ 1 + fromEnum kind) mipSolve :: MsgLev -> BranchingTechnique -> BacktrackTechnique -> Preprocessing -> Bool -> [Cuts] -> Double -> Int -> Bool -> GLPK ReturnCode mipSolve msglev brt btt pp fp cuts mipgap tmlim presol = liftM (toEnum . fromIntegral) $ GLP $ \ lp -> glpMipSolve lp msglev' brt' btt' pp' fp' tmlim' cuts' mipgap' presol' where !msglev' = getMsgLev msglev !brt' = 1 + fromIntegral (fromEnum brt) !btt' = 1 + fromIntegral (fromEnum btt) !pp' = fromIntegral (fromEnum pp) !fp' = fromIntegral (fromEnum fp) !cuts' = (if GMI `elem` cuts then 1 else 0) .|. (if MIR `elem` cuts then 2 else 0) .|. (if Cov `elem` cuts then 4 else 0) .|. (if Clq `elem` cuts then 8 else 0) !mipgap' = realToFrac mipgap !tmlim' = fromIntegral (1000 * tmlim) !presol' = fromIntegral (fromEnum presol) mipObjVal :: GLPK Double mipObjVal = liftM realToFrac $ GLP glpMIPObjVal mipRowVal :: Int -> GLPK Double mipRowVal i = liftM realToFrac $ GLP (`glpMIPRowVal` fromIntegral i) mipColVal :: Int -> GLPK Double mipColVal i = liftM realToFrac $ GLP (`glpMIPColVal` fromIntegral i) setRowName :: Int -> String -> GLPK () setRowName i nam = GLP $ withCString nam . flip glpSetRowName (fromIntegral i) # SPECIALIZE writeProblem : : v = > LP v Double - > GLPK ( Map v Int ) , v = > LP v Int - > GLPK ( Map v Int ) # Ord v => LP v Int -> GLPK (Map v Int) #-} writeProblem :: (Ord v, Real c) => LP v c -> GLPK (Map v Int) writeProblem LP{..} = do setObjectiveDirection direction i0 <- addCols nVars let allVars' = fmap (i0 +) allVars sequence_ [setObjCoef i v | (i, v) <- elems $ intersectionWith (,) allVars' objective] j0 <- addRows (length constraints) sequence_ [do maybe (return ()) (setRowName j) lab setMatRow j [(i, v) | (i, v) <- elems (intersectionWith (,) allVars' f)] setRowBounds j bnds | (j, Constr lab f bnds) <- zip [j0..] constraints] createIndex sequence_ [setColBounds i bnds | (i, bnds) <- elems $ intersectionWith (,) allVars' varBounds] sequence_ [setColBounds i Free | i <- elems $ difference allVars' varBounds] sequence_ [setColKind i knd | (i, knd) <- elems $ intersectionWith (,) allVars' varTypes] return allVars' where allVars0 = fmap (const ()) objective `union` unions [fmap (const ()) f | Constr _ f _ <- constraints] `union` fmap (const ()) varBounds `union` fmap (const ()) varTypes (nVars, allVars) = mapAccum (\ n _ -> (n+1, n)) (0 :: Int) allVars0
null
https://raw.githubusercontent.com/jyp/glpk-hs/a1f4410e93eb76047bafa58583c31b8c8a404860/src/Data/LinearProgram/GLPK/Internal.hs
haskell
foreign import ccall "c_glp_set_obj_name" glpSetObjName :: Ptr GlpProb -> CString -> IO () foreign import ccall unsafe "c_glp_set_obj_dir" glpSetObjDir :: Ptr GlpProb -> CInt -> IO () foreign import ccall unsafe "c_glp_create_index" glpCreateIndex :: Ptr GlpProb -> IO () # SPECIALIZE setMatRow :: Int -> [(Int, Double)] -> GLPK (), Int -> [(Int, Int)] -> GLPK () # createIndex :: GLPK () findRow :: String -> GLPK Int findCol :: String -> GLPK Int
# LANGUAGE RecordWildCards , ScopedTypeVariables , ForeignFunctionInterface , BangPatterns # module Data.LinearProgram.GLPK.Internal (writeProblem, solveSimplex, mipSolve, getObjVal, getRowPrim, getColPrim, mipObjVal, mipRowVal, mipColVal, getBadRay) where ( writeProblem , addCols , addRows , createIndex , findCol , findRow , getColPrim , getRowPrim , getObjVal , mipColVal , mipRowVal , mipObjVal , mipSolve , setColBounds , setColKind , setColName , setMatRow , , setObjectiveDirection , setRowBounds , setRowName , ) where addRows, createIndex, findCol, findRow, getColPrim, getRowPrim, getObjVal, mipColVal, mipRowVal, mipObjVal, mipSolve, setColBounds, setColKind, setColName, setMatRow, setObjCoef, setObjectiveDirection, setRowBounds, setRowName, solveSimplex) where-} import Control.Monad import Prelude hiding ((+),(*)) import Foreign.Ptr import Foreign.C import Foreign.Marshal.Array import Data.Bits import Data.Map hiding (map) import Data . Bounds import Data.LinearProgram.Common import Data.LinearProgram.GLPK.Types foreign import ccall unsafe "c_glp_minimize" glpMinimize :: Ptr GlpProb -> IO () foreign import ccall unsafe "c_glp_maximize" glpMaximize :: Ptr GlpProb -> IO () foreign import ccall unsafe "c_glp_add_rows" glpAddRows :: Ptr GlpProb -> CInt -> IO CInt foreign import ccall unsafe "c_glp_add_cols" glpAddCols :: Ptr GlpProb -> CInt -> IO CInt foreign import ccall unsafe "c_glp_set_row_bnds" glpSetRowBnds :: Ptr GlpProb -> CInt -> CInt -> CDouble -> CDouble -> IO () foreign import ccall unsafe "c_glp_set_col_bnds" glpSetColBnds :: Ptr GlpProb -> CInt -> CInt -> CDouble -> CDouble -> IO () foreign import ccall unsafe "c_glp_set_obj_coef" glpSetObjCoef :: Ptr GlpProb -> CInt -> CDouble -> IO () foreign import ccall unsafe "c_glp_set_mat_row" glpSetMatRow :: Ptr GlpProb -> CInt -> CInt -> Ptr CInt -> Ptr CDouble -> IO () foreign import ccall unsafe " c_glp_find_row " glpFindRow : : Ptr GlpProb - > CString - > IO CInt foreign import ccall unsafe " c_glp_find_col " : : Ptr GlpProb - > CString - > IO CInt foreign import ccall unsafe "c_glp_solve_simplex" glpSolveSimplex :: Ptr GlpProb -> CInt -> CInt -> CInt -> IO CInt foreign import ccall unsafe "c_glp_get_obj_val" glpGetObjVal :: Ptr GlpProb -> IO CDouble foreign import ccall unsafe "c_glp_get_row_prim" glpGetRowPrim :: Ptr GlpProb -> CInt -> IO CDouble foreign import ccall unsafe "c_glp_get_col_prim" glpGetColPrim :: Ptr GlpProb -> CInt -> IO CDouble foreign import ccall unsafe "c_glp_set_col_kind" glpSetColKind :: Ptr GlpProb -> CInt -> CInt -> IO () foreign import ccall unsafe "c_glp_mip_solve" glpMipSolve :: Ptr GlpProb -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CDouble -> CInt -> IO CInt foreign import ccall unsafe "c_glp_mip_obj_val" glpMIPObjVal :: Ptr GlpProb -> IO CDouble foreign import ccall unsafe "c_glp_mip_row_val" glpMIPRowVal :: Ptr GlpProb -> CInt -> IO CDouble foreign import ccall unsafe "c_glp_mip_col_val" glpMIPColVal :: Ptr GlpProb -> CInt -> IO CDouble foreign import ccall unsafe "c_glp_set_row_name" glpSetRowName :: Ptr GlpProb -> CInt -> CString -> IO () foreign import ccall unsafe "c_glp_get_bad_ray" glpGetBadRay :: Ptr GlpProb -> IO CInt setObjectiveDirection :: Direction -> GLPK () setObjectiveDirection dir = GLP $ case dir of Min -> glpMinimize Max -> glpMaximize getBadRay :: GLPK (Maybe Int) getBadRay = liftM (\ x -> guard (x /= 0) >> return (fromIntegral x)) $ GLP glpGetBadRay addRows :: Int -> GLPK Int addRows n = GLP $ liftM fromIntegral . flip glpAddRows (fromIntegral n) addCols :: Int -> GLPK Int addCols n = GLP $ liftM fromIntegral . flip glpAddCols (fromIntegral n) setRowBounds :: Real a => Int -> Bounds a -> GLPK () setRowBounds i bds = GLP $ \ lp -> onBounds (glpSetRowBnds lp (fromIntegral i)) bds setColBounds :: Real a => Int -> Bounds a -> GLPK () setColBounds i bds = GLP $ \ lp -> onBounds (glpSetColBnds lp (fromIntegral i)) bds onBounds :: Real a => (CInt -> CDouble -> CDouble -> x) -> Bounds a -> x onBounds f bds = case bds of Free -> f 1 0 0 LBound a -> f 2 (realToFrac a) 0 UBound a -> f 3 0 (realToFrac a) Bound a b -> f 4 (realToFrac a) (realToFrac b) Equ a -> f 5 (realToFrac a) 0 # SPECIALIZE : : Int - > Double - > GLPK ( ) , Int - > Int - > GLPK ( ) # setObjCoef :: Real a => Int -> a -> GLPK () setObjCoef i v = GLP $ \ lp -> glpSetObjCoef lp (fromIntegral i) (realToFrac v) setMatRow :: Real a => Int -> [(Int, a)] -> GLPK () setMatRow i row = GLP $ \ lp -> allocaArray (len+1) $ \ (ixs :: Ptr CInt) -> allocaArray (len+1) $ \ (coeffs :: Ptr CDouble) -> do pokeArray ixs (0:map (fromIntegral . fst) row) pokeArray coeffs (0:map (realToFrac . snd) row) glpSetMatRow lp (fromIntegral i) (fromIntegral len) ixs coeffs where len = length row createIndex = GLP glpCreateIndex findRow nam = GLP $ liftM fromIntegral . withCString nam . glpFindRow findCol nam = GLP $ liftM fromIntegral . withCString . solveSimplex :: MsgLev -> Int -> Bool -> GLPK ReturnCode solveSimplex msglev tmLim presolve = GLP $ \ lp -> liftM (toEnum . fromIntegral) $ glpSolveSimplex lp (getMsgLev msglev) tmLim' (if presolve then 1 else 0) where tmLim' = fromIntegral (tmLim * 1000) getMsgLev :: MsgLev -> CInt getMsgLev = fromIntegral . fromEnum getObjVal :: GLPK Double getObjVal = liftM realToFrac $ GLP glpGetObjVal getRowPrim :: Int -> GLPK Double getRowPrim i = liftM realToFrac $ GLP (`glpGetRowPrim` fromIntegral i) getColPrim :: Int -> GLPK Double getColPrim i = liftM realToFrac $ GLP (`glpGetColPrim` fromIntegral i) setColKind :: Int -> VarKind -> GLPK () setColKind i kind = GLP $ \ lp -> glpSetColKind lp (fromIntegral i) (fromIntegral $ 1 + fromEnum kind) mipSolve :: MsgLev -> BranchingTechnique -> BacktrackTechnique -> Preprocessing -> Bool -> [Cuts] -> Double -> Int -> Bool -> GLPK ReturnCode mipSolve msglev brt btt pp fp cuts mipgap tmlim presol = liftM (toEnum . fromIntegral) $ GLP $ \ lp -> glpMipSolve lp msglev' brt' btt' pp' fp' tmlim' cuts' mipgap' presol' where !msglev' = getMsgLev msglev !brt' = 1 + fromIntegral (fromEnum brt) !btt' = 1 + fromIntegral (fromEnum btt) !pp' = fromIntegral (fromEnum pp) !fp' = fromIntegral (fromEnum fp) !cuts' = (if GMI `elem` cuts then 1 else 0) .|. (if MIR `elem` cuts then 2 else 0) .|. (if Cov `elem` cuts then 4 else 0) .|. (if Clq `elem` cuts then 8 else 0) !mipgap' = realToFrac mipgap !tmlim' = fromIntegral (1000 * tmlim) !presol' = fromIntegral (fromEnum presol) mipObjVal :: GLPK Double mipObjVal = liftM realToFrac $ GLP glpMIPObjVal mipRowVal :: Int -> GLPK Double mipRowVal i = liftM realToFrac $ GLP (`glpMIPRowVal` fromIntegral i) mipColVal :: Int -> GLPK Double mipColVal i = liftM realToFrac $ GLP (`glpMIPColVal` fromIntegral i) setRowName :: Int -> String -> GLPK () setRowName i nam = GLP $ withCString nam . flip glpSetRowName (fromIntegral i) # SPECIALIZE writeProblem : : v = > LP v Double - > GLPK ( Map v Int ) , v = > LP v Int - > GLPK ( Map v Int ) # Ord v => LP v Int -> GLPK (Map v Int) #-} writeProblem :: (Ord v, Real c) => LP v c -> GLPK (Map v Int) writeProblem LP{..} = do setObjectiveDirection direction i0 <- addCols nVars let allVars' = fmap (i0 +) allVars sequence_ [setObjCoef i v | (i, v) <- elems $ intersectionWith (,) allVars' objective] j0 <- addRows (length constraints) sequence_ [do maybe (return ()) (setRowName j) lab setMatRow j [(i, v) | (i, v) <- elems (intersectionWith (,) allVars' f)] setRowBounds j bnds | (j, Constr lab f bnds) <- zip [j0..] constraints] createIndex sequence_ [setColBounds i bnds | (i, bnds) <- elems $ intersectionWith (,) allVars' varBounds] sequence_ [setColBounds i Free | i <- elems $ difference allVars' varBounds] sequence_ [setColKind i knd | (i, knd) <- elems $ intersectionWith (,) allVars' varTypes] return allVars' where allVars0 = fmap (const ()) objective `union` unions [fmap (const ()) f | Constr _ f _ <- constraints] `union` fmap (const ()) varBounds `union` fmap (const ()) varTypes (nVars, allVars) = mapAccum (\ n _ -> (n+1, n)) (0 :: Int) allVars0
4b0442d63040af209fbb2e581c214458cbd49d07766bd408eb4f6fe3451ccdec
KavehYousefi/Esoteric-programming-languages
main.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Remarks ;; ======= ;; = = ENSURE A VALUE OF ZERO = = ;; When proceeding from left to right, the following code fragment ensures that the current cell contains the value zero ( 0 ): ;; [+-] ;; = = ENSURE A VALUE OF ONE = = ;; When proceeding from left to right, the following code fragment ensures that the current cell contains the value one ( 1 ): ;; [+-]+- ;; ;; -------------------------------------------------------------------- ;; Author : Date : 2022 - 03 - 28 ;; ;; Sources: ;; -> "" ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; -- Declaration of types. -- ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftype hash-table-of (&optional (key-type T) (value-type T)) "The ``hash-table-of'' type defines a hash table of zero or more entries, each key of which conforms to the KEY-TYPE, associated with a value of the VALUE-TYPE." (let ((predicate (gensym))) (declare (type symbol predicate)) (setf (symbol-function predicate) #'(lambda (object) (declare (type T object)) (and (hash-table-p object) (loop for key of-type T being the hash-keys in (the hash-table object) using (hash-value value) always (and (typep key key-type) (typep value value-type)))))) `(satisfies ,predicate))) ;;; ------------------------------------------------------- (deftype octet () "The ``octet'' type defines an eight-bit unsigned integer value." '(unsigned-byte 8)) ;;; ------------------------------------------------------- (deftype memory () "The ``memory'' type defines the program memory as a hash table mapping to each signed integer cell index a single bit as the respective cell value." '(hash-table-of integer bit)) ;;; ------------------------------------------------------- (deftype direction () "The ``direction'' type enumerates the recognized directions into which the program counter may move." '(member :left :right)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; -- Implementation of interpreter. -- ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun interpret-Yaren (code) "Interprets the piece of Yaren CODE and returns no value." (declare (type string code)) (when (plusp (length code)) (let ((ip-location 0) (ip-direction :right) (character (char code 0)) (memory (make-hash-table :test #'eql)) (cell-pointer 0)) (declare (type fixnum ip-location)) (declare (type direction ip-direction)) (declare (type (or null character) character)) (declare (type memory memory)) (declare (type integer cell-pointer)) (labels ((advance () "Moves the IP-LOCATION cursor one character into the IP-DIRECTION, updates the current CHARACTER, and returns no value." (case ip-direction (:right (setf character (when (array-in-bounds-p code (1+ ip-location)) (char code (incf ip-location))))) (:left (setf character (when (array-in-bounds-p code (1- ip-location)) (char code (decf ip-location))))) (otherwise (error "Invalid IP direction: ~s." ip-direction))) (values)) (recede () "Moves the IP-LOCATION cusor one character widdershins the IP-DIRECTION, updates the current CHARACTER, and returns no value." (case ip-direction (:right (setf character (when (array-in-bounds-p code (1- ip-location)) (char code (decf ip-location))))) (:left (setf character (when (array-in-bounds-p code (1+ ip-location)) (char code (incf ip-location))))) (otherwise (error "Invalid IP direction: ~s." ip-direction))) (values)) (jump-to-terminator (starter terminator) "Starting at the current IP-LOCATION, searches in the IP-DIRECTION for the TERMINATOR character matching the STARTER with respect to the correct nesting, finally moving the IP-LOCATION cursor one character past the detected TERMINATOR, and returns no value." (declare (type character starter)) (declare (type character terminator)) (loop with level of-type integer = 0 do (cond ((null character) (error "Unmatched starter '~a'." starter)) ((char= character terminator) (cond ((zerop level) (advance) (loop-finish)) (T (decf level) (advance)))) ((char= character starter) (incf level) (advance)) (T (advance)))) (values)) (jump-to-starter (starter terminator) "Starting at the current IP-LOCATION, searches in the IP-DIRECTION for the STARTER character matching the TERMINATOR with respect to the correct nesting, finally moving the IP-LOCATION cursor to the detected position, and returns no value. --- Please note that the IP-LOCATION is settled on the STARTER itself, not translated past it." (declare (type character starter)) (declare (type character terminator)) (loop with level of-type integer = 0 do (cond ((null character) (error "Unmatched terminator '~a'." terminator)) ((char= character starter) (cond ((zerop level) (loop-finish)) (T (decf level) (recede)))) ((char= character terminator) (incf level) (recede)) (T (recede)))) (values)) (current-cell () "Returns the bit stored in the current cell." (the bit (gethash cell-pointer memory 0))) ((setf current-cell) (new-value) "Sets the bit stored in the current cell to the NEW-VALUE and returns no value." (declare (type bit new-value)) (setf (gethash cell-pointer memory) new-value) (values)) (cell-at (index) "Returns the bit stored in the cell at the INDEX." (declare (type integer index)) (the bit (gethash index memory 0))) ((setf cell-at) (new-value index) "Sets the bit stored in the cell at the INDEX to the NEW-VALUE and returns no value." (declare (type integer index)) (declare (type bit new-value)) (setf (gethash index memory 0) new-value) (values)) (read-integer () "Reads from the standard input a line and attempts to parse the same as an integer object, returning on success the parsed integer, otherwise ``NIL''." (the (or null integer) (handler-case (parse-integer (read-line)) (error () NIL)))) (prompt-for-byte () "Prompts the user for a byte until the same is specified, finally returning the value as an ``octet''." (the octet (loop do (format T "~&Please input a byte: ") (let ((input (read-integer))) (declare (type (or null integer) input)) (clear-input) (when (and input (typep input 'octet)) (return input))))))) (loop do (case character ;; End of CODE. ((NIL) (loop-finish)) ;; Toggle the current cell value, and increment the cell ;; pointer. (#\+ (setf (current-cell) (- 1 (current-cell))) (incf cell-pointer) (advance)) ;; Decrement the cell pointer. (#\- (decf cell-pointer) (advance)) Jump to the matching " ] " if the current cell is zero . (#\[ (case ip-direction (:right If current cell is zero : jump past matching " ] " . (cond ((zerop (current-cell)) (advance) (jump-to-terminator #\[ #\])) (T (advance)))) ;; This is a terminating bracket? (:left (cond ((zerop (current-cell)) (advance)) (T (recede) (jump-to-starter #\] #\[)))) (otherwise (error "Invalid direction: ~s." ip-direction)))) ;; Jump back to the matching "[" is necessary. (#\] (case ip-direction ;; This is a terminating bracket? (:right (cond ((zerop (current-cell)) (advance)) (T (recede) (jump-to-starter #\[ #\])))) (:left If current cell is zero : jump past matching " [ " . (cond ((zerop (current-cell)) (advance) (jump-to-terminator #\] #\[)) (T (advance)))) (otherwise (error "Invalid direction: ~s." ip-direction)))) ;; Direct the program counter to the left. (#\< (setf ip-direction :left) (advance)) ;; Direct the program counter to the right. (#\> (setf ip-direction :right) (advance)) ;; Input a byte. (#\, (let ((input (prompt-for-byte))) (declare (type octet input)) (clear-input) (dotimes (bit-index 8) (declare (type octet bit-index)) (setf (cell-at (+ cell-pointer bit-index)) (ldb (byte 1 bit-index) input)))) (advance)) ;; Output a byte. (#\. (let ((byte 0)) (declare (type octet byte)) (dotimes (bit-index 8) (declare (type octet bit-index)) (setf (ldb (byte 1 bit-index) byte) (cell-at (+ cell-pointer bit-index)))) (write byte)) (advance)) ;; Ignore unknown characters. (otherwise (advance))))))) (values)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; -- Test cases. -- ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; One - time cat program . (interpret-Yaren ",.") ;;; ------------------------------------------------------- Cat program which repeats until the current cell contains zero . (interpret-Yaren ",.[,.]") ;;; ------------------------------------------------------- ;; Infinitely repeating cat program which does not cease when the current cell contains zero . (interpret-Yaren ",.[+-]+-[,.[+-]+-]") ;;; ------------------------------------------------------- ;; Truth-machine. (interpret-Yaren ",[>.<].")
null
https://raw.githubusercontent.com/KavehYousefi/Esoteric-programming-languages/62f7280ada463846eb7c8ba338af32aff25fc420/Yaren/Yaren_001/main.lisp
lisp
Remarks ======= When proceeding from left to right, the following code fragment [+-] When proceeding from left to right, the following code fragment [+-]+- -------------------------------------------------------------------- Sources: -> "" -- Declaration of types. -- ;; ------------------------------------------------------- ------------------------------------------------------- ------------------------------------------------------- -- Implementation of interpreter. -- ;; End of CODE. Toggle the current cell value, and increment the cell pointer. Decrement the cell pointer. This is a terminating bracket? Jump back to the matching "[" is necessary. This is a terminating bracket? Direct the program counter to the left. Direct the program counter to the right. Input a byte. Output a byte. Ignore unknown characters. -- Test cases. -- ;; ------------------------------------------------------- ------------------------------------------------------- Infinitely repeating cat program which does not cease when the ------------------------------------------------------- Truth-machine.
= = ENSURE A VALUE OF ZERO = = ensures that the current cell contains the value zero ( 0 ): = = ENSURE A VALUE OF ONE = = ensures that the current cell contains the value one ( 1 ): Author : Date : 2022 - 03 - 28 (deftype hash-table-of (&optional (key-type T) (value-type T)) "The ``hash-table-of'' type defines a hash table of zero or more entries, each key of which conforms to the KEY-TYPE, associated with a value of the VALUE-TYPE." (let ((predicate (gensym))) (declare (type symbol predicate)) (setf (symbol-function predicate) #'(lambda (object) (declare (type T object)) (and (hash-table-p object) (loop for key of-type T being the hash-keys in (the hash-table object) using (hash-value value) always (and (typep key key-type) (typep value value-type)))))) `(satisfies ,predicate))) (deftype octet () "The ``octet'' type defines an eight-bit unsigned integer value." '(unsigned-byte 8)) (deftype memory () "The ``memory'' type defines the program memory as a hash table mapping to each signed integer cell index a single bit as the respective cell value." '(hash-table-of integer bit)) (deftype direction () "The ``direction'' type enumerates the recognized directions into which the program counter may move." '(member :left :right)) (defun interpret-Yaren (code) "Interprets the piece of Yaren CODE and returns no value." (declare (type string code)) (when (plusp (length code)) (let ((ip-location 0) (ip-direction :right) (character (char code 0)) (memory (make-hash-table :test #'eql)) (cell-pointer 0)) (declare (type fixnum ip-location)) (declare (type direction ip-direction)) (declare (type (or null character) character)) (declare (type memory memory)) (declare (type integer cell-pointer)) (labels ((advance () "Moves the IP-LOCATION cursor one character into the IP-DIRECTION, updates the current CHARACTER, and returns no value." (case ip-direction (:right (setf character (when (array-in-bounds-p code (1+ ip-location)) (char code (incf ip-location))))) (:left (setf character (when (array-in-bounds-p code (1- ip-location)) (char code (decf ip-location))))) (otherwise (error "Invalid IP direction: ~s." ip-direction))) (values)) (recede () "Moves the IP-LOCATION cusor one character widdershins the IP-DIRECTION, updates the current CHARACTER, and returns no value." (case ip-direction (:right (setf character (when (array-in-bounds-p code (1- ip-location)) (char code (decf ip-location))))) (:left (setf character (when (array-in-bounds-p code (1+ ip-location)) (char code (incf ip-location))))) (otherwise (error "Invalid IP direction: ~s." ip-direction))) (values)) (jump-to-terminator (starter terminator) "Starting at the current IP-LOCATION, searches in the IP-DIRECTION for the TERMINATOR character matching the STARTER with respect to the correct nesting, finally moving the IP-LOCATION cursor one character past the detected TERMINATOR, and returns no value." (declare (type character starter)) (declare (type character terminator)) (loop with level of-type integer = 0 do (cond ((null character) (error "Unmatched starter '~a'." starter)) ((char= character terminator) (cond ((zerop level) (advance) (loop-finish)) (T (decf level) (advance)))) ((char= character starter) (incf level) (advance)) (T (advance)))) (values)) (jump-to-starter (starter terminator) "Starting at the current IP-LOCATION, searches in the IP-DIRECTION for the STARTER character matching the TERMINATOR with respect to the correct nesting, finally moving the IP-LOCATION cursor to the detected position, and returns no value. --- Please note that the IP-LOCATION is settled on the STARTER itself, not translated past it." (declare (type character starter)) (declare (type character terminator)) (loop with level of-type integer = 0 do (cond ((null character) (error "Unmatched terminator '~a'." terminator)) ((char= character starter) (cond ((zerop level) (loop-finish)) (T (decf level) (recede)))) ((char= character terminator) (incf level) (recede)) (T (recede)))) (values)) (current-cell () "Returns the bit stored in the current cell." (the bit (gethash cell-pointer memory 0))) ((setf current-cell) (new-value) "Sets the bit stored in the current cell to the NEW-VALUE and returns no value." (declare (type bit new-value)) (setf (gethash cell-pointer memory) new-value) (values)) (cell-at (index) "Returns the bit stored in the cell at the INDEX." (declare (type integer index)) (the bit (gethash index memory 0))) ((setf cell-at) (new-value index) "Sets the bit stored in the cell at the INDEX to the NEW-VALUE and returns no value." (declare (type integer index)) (declare (type bit new-value)) (setf (gethash index memory 0) new-value) (values)) (read-integer () "Reads from the standard input a line and attempts to parse the same as an integer object, returning on success the parsed integer, otherwise ``NIL''." (the (or null integer) (handler-case (parse-integer (read-line)) (error () NIL)))) (prompt-for-byte () "Prompts the user for a byte until the same is specified, finally returning the value as an ``octet''." (the octet (loop do (format T "~&Please input a byte: ") (let ((input (read-integer))) (declare (type (or null integer) input)) (clear-input) (when (and input (typep input 'octet)) (return input))))))) (loop do (case character ((NIL) (loop-finish)) (#\+ (setf (current-cell) (- 1 (current-cell))) (incf cell-pointer) (advance)) (#\- (decf cell-pointer) (advance)) Jump to the matching " ] " if the current cell is zero . (#\[ (case ip-direction (:right If current cell is zero : jump past matching " ] " . (cond ((zerop (current-cell)) (advance) (jump-to-terminator #\[ #\])) (T (advance)))) (:left (cond ((zerop (current-cell)) (advance)) (T (recede) (jump-to-starter #\] #\[)))) (otherwise (error "Invalid direction: ~s." ip-direction)))) (#\] (case ip-direction (:right (cond ((zerop (current-cell)) (advance)) (T (recede) (jump-to-starter #\[ #\])))) (:left If current cell is zero : jump past matching " [ " . (cond ((zerop (current-cell)) (advance) (jump-to-terminator #\] #\[)) (T (advance)))) (otherwise (error "Invalid direction: ~s." ip-direction)))) (#\< (setf ip-direction :left) (advance)) (#\> (setf ip-direction :right) (advance)) (#\, (let ((input (prompt-for-byte))) (declare (type octet input)) (clear-input) (dotimes (bit-index 8) (declare (type octet bit-index)) (setf (cell-at (+ cell-pointer bit-index)) (ldb (byte 1 bit-index) input)))) (advance)) (#\. (let ((byte 0)) (declare (type octet byte)) (dotimes (bit-index 8) (declare (type octet bit-index)) (setf (ldb (byte 1 bit-index) byte) (cell-at (+ cell-pointer bit-index)))) (write byte)) (advance)) (otherwise (advance))))))) (values)) One - time cat program . (interpret-Yaren ",.") Cat program which repeats until the current cell contains zero . (interpret-Yaren ",.[,.]") current cell contains zero . (interpret-Yaren ",.[+-]+-[,.[+-]+-]") (interpret-Yaren ",[>.<].")
9d6e03de56da2953c2cc396cd94436eab8cc5d752c497e443b2d7aefdd023d53
kappamodeler/kappa
annotated_contact_map.ml
open Data_structures open Pb_sig open Tools open Output_contact_map open Ode_print_sig open Ode_print open Error_handler let debug = false type template_piece = {kept_sites:StringSet.t} type ode_skeleton = {subviews:(template_piece list) StringMap.t; solid_edges: String22Set.t } type compression_mode = Compressed | Flat | Approximated | Stoc let error i = unsafe_frozen None (Some "Complx") (Some "Annotated_contact_map.ml") None (Some ("line "^(string_of_int i))) (fun () -> raise Exit) let keep_this_link (a,b) (c,d) skeleton = a<>c & & && *) (String22Set.mem ((a,b),(c,d)) skeleton.solid_edges or String22Set.mem ((c,d),(a,b)) skeleton.solid_edges) let dump_template print x = let _ = pprint_string print "Passing sites: \n" in let _ = String22Set.iter (fun ((a,b),(c,d)) -> pprint_string print a; pprint_string print "."; pprint_string print b; pprint_string print "--"; pprint_string print d; pprint_string print "."; pprint_string print c; pprint_newline print) x.solid_edges in let _ = pprint_string print "\nTemplates: \n\n" in let _ = StringMap.iter (fun x l -> let _ = pprint_string print "Agent: " in let _ = pprint_string print x in let _ = pprint_newline print in let _ = List.iter (fun x -> let _ = pprint_string print "Template\nSites\n" in let _ = StringSet.iter (fun x -> pprint_string print x; pprint_string print ",") x.kept_sites in let _ = pprint_newline print in let _ = pprint_newline print in let _ = pprint_newline print in ()) l in let _ = pprint_newline print in ()) x.subviews in () let sub_template a b = StringSet.subset a.kept_sites b.kept_sites let normalize_site_list l = List.sort compare l let get_sitesets_of_solution t agentmap = Solution.AA.fold (fun _ a agentmap -> let interface = Agent.fold_interface (fun s (m1,m2) int -> match s,m1,m2 with "_",_,_ | _,Agent.Wildcard,Agent.Wildcard -> int | _ -> s::int) a [] in let interface = normalize_site_list interface in let agent_name = Agent.name a in let old = try StringMap.find agent_name agentmap with Not_found -> StringListSet.empty in StringMap.add agent_name (StringListSet.add interface old) agentmap) t.Solution.agents agentmap let get_links_of_solution t solid_edges = let speciemap = Solution.AA.fold (fun i a -> IntMap.add i (Agent.name a)) t.Solution.agents IntMap.empty in Solution.PA.fold (fun (i,s) (i',s') solid_edges -> let a = IntMap.find i speciemap in let a' = IntMap.find i' speciemap in String22Set.add ((a,s),(a',s')) (String22Set.add ((a',s'),(a,s)) solid_edges)) t.Solution.links solid_edges let compute_annotated_contact_map_init cpb = List.fold_left (fun (local_map,site_map) (a,b,c) -> let set = List.fold_left (fun set a -> StringSet.add a set) (List.fold_left (fun set a -> StringSet.add a set) StringSet.empty b) c in let list,list2 = StringSet.fold (fun x (l,l2) -> {kept_sites = StringSet.singleton x}::l,x::l2) set ([{kept_sites = StringSet.empty}],[]) in StringMap.add a list local_map, StringMap.add a list2 site_map) (StringMap.empty,StringMap.empty) cpb.Pb_sig.cpb_interface let compute_annotated_contact_map_in_approximated_mode system cpb contact_map = let local_map,_ = compute_annotated_contact_map_init cpb in List.fold_left (fun (sol,passing_sites) rs -> let passive = rs.Pb_sig.passive_species in let passing_sites = List.fold_left (fun sol ((a,b,c),(d,e,f)) -> let fadd x y sol = if List.exists (fun a -> (List.exists (fun b -> match b with M((a',b',_),_),_ when x=(a',b') -> true | B(a',b',c'),_ | AL((a',b',c'),_),_ when x=(a',b') && c'<>y -> true | L((a',b',c'),_),_ when x=(a',b') && c'<>y -> true | L(_,(a',b',c')),_ when x=(a',b') && c'<>y -> true | _ -> false ) a.Pb_sig.injective_guard)) rs.Pb_sig.rules then String2Set.add (snd x,y) sol else sol in fadd (a,b) c (fadd (d,e) f passing_sites)) passing_sites passive in let local_map = List.fold_left (fun sol a -> List.fold_left (fun sol a -> let fadd x y sol = let old' = try String2Map.find x sol with Not_found -> StringSet.empty in String2Map.add x (StringSet.add y old') sol in match a with H (x,x'),true -> (try (let _ = String2Map.find (x,x') sol in sol) with Not_found -> (String2Map.add (x,x') StringSet.empty sol)) | H _,_ -> sol | Connected _,_ -> sol | B(a,a',b),_ -> fadd (a,a') b sol | AL((a,a',b),_),_ -> fadd (a,a') b sol | L((a,a',b),(c,c',d)),_ -> fadd (a,a') b (fadd (c,c') d sol) | M((a,a',b),c),_ -> fadd (a,a') b sol | _ -> error 923 ) sol a.Pb_sig.injective_guard) String2Map.empty rs.Pb_sig.rules in String2Map.fold (fun (_,a) b sol -> let old = try StringMap.find a sol with Not_found -> [] in StringMap.add a ({kept_sites=b}::old) sol) local_map sol,passing_sites ) (local_map,String2Set.empty) system let trivial_rule rs = let control = rs.Pb_sig.control in let context = control.Pb_sig.context_update in let uncontext = control.Pb_sig.uncontext_update in match context,uncontext with _,[a,b,c] -> begin (List.for_all (fun rule -> List.for_all (fun (bb,bool) -> match bb,bool with B(x,y,z),true when x=a && y=b && z=c -> true | H(_),_ -> true | _ -> false ) rule.Pb_sig.injective_guard ) rs.Pb_sig.rules ) && (List.for_all (fun (bb,bool) -> match (bb,bool) with B(x,y,z),false when x=a && y=b && z=c -> true | _ -> false) context) end | _,[] -> begin let rec aux context rep = match context with (AL(_),_)::q | (B(_),_)::q-> aux q rep | (L((a,b,c),(d,e,f)),false)::q -> begin match rep with None -> aux q (Some((a,b,c),(d,e,f))) | Some _ -> false,None end | [] -> begin match rep with None -> false,None | x -> true,x end | _ -> false,None in let b,binding = aux context None in if b then match binding with None -> error 958 | Some ((a,b,c),(d,e,f)) -> List.for_all (fun rule -> List.for_all (fun (bb,bool) -> match bb,bool with B(x,y,z),true when (x=a && y=b && z=c) or (x=d && y=e && z=f) -> true | AL((x,y,z),(xx,yy)),true when (x=a && y=b && z=c && xx=e && yy=f) or (x=d && y=e && z=f && xx=b & yy=c) -> true | L((x,y,z),(xx,yy,zz)),true when (x=a && y=b && z=c && xx=d && yy=e && zz=f) or (xx=a && yy=b && zz=c && x=d && y=e && z=f) -> true | H(_),_ -> true | _ -> false ) rule.Pb_sig.injective_guard ) rs.Pb_sig.rules else false end | _ -> false type tr = Half of string*string | Unbind of string*string*string*string let which_trivial_rule rs = let control = rs.Pb_sig.control in let context = control.Pb_sig.context_update in let uncontext = control.Pb_sig.uncontext_update in match context,uncontext with _,[a,b,c] -> Half(b,c) | _,[] -> begin let rec aux context rep = match context with (AL(_),_)::q | (B(_),_)::q-> aux q rep | (L((a,b,c),(d,e,f)),false)::q -> begin match rep with None -> Some (Unbind(b,c,e,f)) | Some _ -> None end | _ -> None in (match aux context None with None -> error 256 | Some a -> a ) end | _ -> error 259 let trivial_rule2 (contact,keep_this_link) rule = trivial_rule rule && begin match which_trivial_rule rule with Half(a,b) -> List.for_all (fun (_,c,d) -> not (keep_this_link (a,b) (c,d))) (contact (a,b)) | Unbind(a,b,c,d) -> not (keep_this_link (a,b) (c,d)) end let compute_annotated_contact_map_in_compression_mode system cpb contact_map = let local_map,site_map = compute_annotated_contact_map_init cpb in let classes = StringMap.map (fun l -> List.fold_left (fun sol a -> StringListSet.add (StringSet.elements a.kept_sites) sol) StringListSet.empty l) local_map in let fadd ag x y map = let old1,old2 = try StringMap.find ag map with Not_found -> (StringMap.empty,StringMap.empty) in let old1_image = try StringMap.find x old1 with Not_found -> StringSet.empty in let new1_image = StringSet.add y old1_image in let old2_image = try StringMap.find y old2 with Not_found -> StringSet.empty in let new2_image = StringSet.add x old2_image in let new1_map = StringMap.add x new1_image old1 in let new2_map = StringMap.add y new2_image old2 in StringMap.add ag (new1_map,new2_map) map in let site_relation,classes,dangerous_sites = List.fold_left (fun (relation,classes,dangerous_sites) rs -> let modified_sites = let fadd a b sol = let old = try String2Map.find a sol with Not_found -> StringSet.empty in String2Map.add a (StringSet.add b old) sol in let modif = List.fold_left (fun modif a -> match a with H _,_ -> modif | Connected _,_ -> modif | B(a,a',b),_ -> fadd (a,a') b modif | AL((a,a',b),_),_ -> fadd (a,a') b modif | L((a,a',b),(c,c',d)),_ -> fadd (a,a') b (fadd (c,c') d modif) | M((a,a',b),c),_ -> fadd (a,a') b modif | _ -> error 964 ) String2Map.empty rs.Pb_sig.control.Pb_sig.context_update in let modif = List.fold_left (fun modif (a,b,c) -> fadd (a,b) c modif) modif rs.Pb_sig.control.Pb_sig.uncontext_update in let modif = List.fold_left (fun modif ((a,b,c),_) -> fadd (a,b) c modif) modif rs.passive_species in modif in List.fold_left (fun (relation,classes,dangerous_sites) rule -> let tested_sites,free_sites = List.fold_left (fun (sol1,sol2) a -> let fadd x y sol = let old' = try String2Map.find x sol with Not_found -> StringSet.empty in String2Map.add x (StringSet.add y old') sol in match a with H (x,x'),true -> (try (let _ = String2Map.find (x,x') sol1 in sol1,sol2) with Not_found -> (String2Map.add (x,x') StringSet.empty sol1,sol2)) | H _,_ -> sol1,sol2 | Connected _,_ -> sol1,sol2 | B(a,a',b),false -> fadd (a,a') b sol1,fadd (a,a') b sol2 | B(a,a',b),_ -> fadd (a,a') b sol1,sol2 | AL((a,a',b),_),true -> fadd (a,a') b sol1,fadd (a,a') b sol2 | AL((a,a',b),_),_ -> fadd (a,a') b sol1,sol2 | L((a,a',b),(c,c',d)),true -> fadd (a,a') b (fadd (c,c') d sol1),fadd (a,a') b (fadd (c,c') d sol2) | L((a,a',b),(c,c',d)),_ -> fadd (a,a') b (fadd (c,c') d sol1),sol2 | M((a,a',b),c),_ -> fadd (a,a') b sol1,sol2 | _ -> error 964 ) (String2Map.empty,String2Map.empty) rule.Pb_sig.injective_guard in let classes = String2Map.fold (fun (_,a) set classes -> let tested_list = StringSet.elements set in let old = try StringMap.find a classes with Not_found -> StringListSet.empty in StringMap.add a (StringListSet.add tested_list old) classes ) tested_sites classes in let relation,dangerous_sites = List.fold_left (fun (relation,dangerous_sites) a_id -> let a = try StringMap.find a_id rs.Pb_sig.specie_of_id with Not_found -> error 394 in let tested = try String2Map.find (a_id,a) tested_sites with Not_found -> StringSet.empty in let relation = StringSet.fold (fun site relation -> StringSet.fold (fun site' relation -> if site==site' then relation else (fadd a site site' relation)) ( try List.fold_left (fun sol s -> StringSet.add s sol) (StringSet.empty) (StringMap.find a site_map) with Not_found -> StringSet.empty ) relation) tested relation in let dangerous_sites = let free_sites = try String2Map.find (a_id,a) free_sites with Not_found -> StringSet.empty in let sites = try List.fold_left (fun sol s -> StringSet.add s sol) (StringSet.empty) (StringMap.find a site_map) with Not_found -> StringSet.empty in let diff = StringSet.diff sites free_sites in StringSet.fold (fun s -> String2Set.add (a,s)) diff dangerous_sites in relation,dangerous_sites) (relation,dangerous_sites) rs.Pb_sig.control.Pb_sig.remove in let relation = String2Map.fold2 (fun _ _ x -> x) (fun _ _ x -> x) (fun (a,a') tested modified rel -> StringSet.fold (fun test rel -> StringSet.fold (fun control rel -> if test=control then rel else fadd a' test control rel) modified rel) tested rel) tested_sites modified_sites relation in relation,classes,dangerous_sites) (relation,classes,dangerous_sites) rs.Pb_sig.rules) (StringMap.empty,classes,String2Set.empty) system in let local_map = StringMap.map (fun lset -> StringListSet.fold (fun a b -> {kept_sites=(List.fold_left (fun set b -> StringSet.add b set) StringSet.empty a)}::b) lset []) classes in (* let classes = List.fold_left (fun classes obs -> get_sitesets_of_solution obs classes) classes obs in *) let _ = if debug then let _ = StringMap.iter (fun a (map1,map2) -> let _ = print_string "AGENT " in let _ = print_string a in let _ = print_newline () in let _ = StringMap.iter (fun b s -> let _ = print_string "map1\n " in let _ = StringSet.iter (fun c -> print_string b; print_string "->"; print_string c; print_newline ()) s in ()) map1 in let _ = StringMap.iter (fun b s -> let _ = print_string "map2\n" in let _ = StringSet.iter (fun c -> print_string b; print_string "->"; print_string c; print_newline ()) s in ()) map2 in ()) site_relation in () in let local_map = StringMap.fold (fun a (map1,map2) local_map -> let _ = if debug then let _ = print_string a in let _ = StringMap.iter (fun b s -> let _ = print_string "map2\n" in let _ = StringSet.iter (fun c -> print_string b; print_string "->"; print_string c; print_newline ()) s in ()) map2 in let _ = print_newline () in () in let rec aux to_visit rep = match to_visit with [] -> rep | t::q when StringSet.mem t rep -> aux q rep | t::q -> let rep = StringSet.add t rep in let to_visit = StringSet.fold (fun a l -> a::l) (try StringMap.find t map2 with Not_found -> StringSet.empty) to_visit in aux to_visit rep in let covering_classes = StringMap.fold (fun a _ l -> ({kept_sites= aux [a] StringSet.empty})::l) map2 [] in let l2 = StringMap.find a classes in let covering_classes = StringListSet.fold (fun a l -> ({kept_sites = aux a StringSet.empty})::l) l2 covering_classes in let old = try StringMap.find a local_map with Not_found -> [] in StringMap.add a (covering_classes@old) local_map) site_relation local_map in let solid_edges = String22Set.empty in (* let solid_edges = List.fold_left (fun solid_edges obs -> get_links_of_solution obs solid_edges) solid_edges obs in *) let solid_edges = List.fold_left (fun solid_edges rs -> if trivial_rule rs then solid_edges else let guard = rs.Pb_sig.rules in let solid_edges = List.fold_left (fun solid_edges guard -> List.fold_left (fun solid_edges x -> match x with L((_,b,c),(_,e,f)),true |AL((_,b , c),(e , f)),true : : Binding type do not cause information leakage ! ! ! -> String22Set.add ((b,c),(e,f)) solid_edges | _ -> solid_edges) solid_edges guard.injective_guard) solid_edges guard in let solid_edges = List.fold_left (fun solid_edges b -> match b with L((a,b,c),(d,e,f)),false -> String22Set.add ((b,c),(e,f)) (String22Set.add ((e,f),(b,c)) solid_edges) | _ -> solid_edges) solid_edges rs.Pb_sig.control.Pb_sig.context_update in let solid_edges = List.fold_left (fun solid_edges (a,b,c) -> List.fold_left (fun solid_edges (_,d,e) -> String22Set.add ((b,c),(d,e)) (String22Set.add ((d,e),(b,c)) solid_edges)) solid_edges (contact_map (b,c))) solid_edges rs.Pb_sig.control.Pb_sig.uncontext_update in let solid_edges = String2Set.fold (fun (b,c) solid_edges -> List.fold_left (fun solid_edges (_,d,e) -> String22Set.add ((b,c),(d,e)) (String22Set.add ((d,e),(b,c)) solid_edges)) solid_edges (contact_map (b,c))) dangerous_sites solid_edges in solid_edges) solid_edges system in (local_map,solid_edges) let compute_annotated_contact_map_in_flat_mode system cpb contact_map = let passing_sites = List.fold_left (fun sol (a,b,c) -> List.fold_left (fun sol x -> String2Set.add (a,x) sol) sol c) String2Set.empty cpb.cpb_interface in let local_views = List.fold_left (fun sol (a,b,c) -> let site_set = List.fold_left (fun sol x -> StringSet.add x sol) (List.fold_left (fun sol x -> StringSet.add x sol) StringSet.empty c) b in StringMap.add a [{kept_sites=site_set}] sol) StringMap.empty cpb.cpb_interface in (local_views,passing_sites) let upgrade (x,y) cpb = (x, String2Map.fold (fun (a,b) l sol -> List.fold_left (fun sol (c,d) -> if String2Set.mem (a,b) y && String2Set.mem (c,d) y then String22Set.add ((a,b),(c,d)) sol else sol) sol l) (match cpb.cpb_contact with None -> error 1327 | Some a -> a) String22Set.empty )
null
https://raw.githubusercontent.com/kappamodeler/kappa/de63d1857898b1fc3b7f112f1027768b851ce14d/complx_rep/ODE/annotated_contact_map.ml
ocaml
let classes = List.fold_left (fun classes obs -> get_sitesets_of_solution obs classes) classes obs in let solid_edges = List.fold_left (fun solid_edges obs -> get_links_of_solution obs solid_edges) solid_edges obs in
open Data_structures open Pb_sig open Tools open Output_contact_map open Ode_print_sig open Ode_print open Error_handler let debug = false type template_piece = {kept_sites:StringSet.t} type ode_skeleton = {subviews:(template_piece list) StringMap.t; solid_edges: String22Set.t } type compression_mode = Compressed | Flat | Approximated | Stoc let error i = unsafe_frozen None (Some "Complx") (Some "Annotated_contact_map.ml") None (Some ("line "^(string_of_int i))) (fun () -> raise Exit) let keep_this_link (a,b) (c,d) skeleton = a<>c & & && *) (String22Set.mem ((a,b),(c,d)) skeleton.solid_edges or String22Set.mem ((c,d),(a,b)) skeleton.solid_edges) let dump_template print x = let _ = pprint_string print "Passing sites: \n" in let _ = String22Set.iter (fun ((a,b),(c,d)) -> pprint_string print a; pprint_string print "."; pprint_string print b; pprint_string print "--"; pprint_string print d; pprint_string print "."; pprint_string print c; pprint_newline print) x.solid_edges in let _ = pprint_string print "\nTemplates: \n\n" in let _ = StringMap.iter (fun x l -> let _ = pprint_string print "Agent: " in let _ = pprint_string print x in let _ = pprint_newline print in let _ = List.iter (fun x -> let _ = pprint_string print "Template\nSites\n" in let _ = StringSet.iter (fun x -> pprint_string print x; pprint_string print ",") x.kept_sites in let _ = pprint_newline print in let _ = pprint_newline print in let _ = pprint_newline print in ()) l in let _ = pprint_newline print in ()) x.subviews in () let sub_template a b = StringSet.subset a.kept_sites b.kept_sites let normalize_site_list l = List.sort compare l let get_sitesets_of_solution t agentmap = Solution.AA.fold (fun _ a agentmap -> let interface = Agent.fold_interface (fun s (m1,m2) int -> match s,m1,m2 with "_",_,_ | _,Agent.Wildcard,Agent.Wildcard -> int | _ -> s::int) a [] in let interface = normalize_site_list interface in let agent_name = Agent.name a in let old = try StringMap.find agent_name agentmap with Not_found -> StringListSet.empty in StringMap.add agent_name (StringListSet.add interface old) agentmap) t.Solution.agents agentmap let get_links_of_solution t solid_edges = let speciemap = Solution.AA.fold (fun i a -> IntMap.add i (Agent.name a)) t.Solution.agents IntMap.empty in Solution.PA.fold (fun (i,s) (i',s') solid_edges -> let a = IntMap.find i speciemap in let a' = IntMap.find i' speciemap in String22Set.add ((a,s),(a',s')) (String22Set.add ((a',s'),(a,s)) solid_edges)) t.Solution.links solid_edges let compute_annotated_contact_map_init cpb = List.fold_left (fun (local_map,site_map) (a,b,c) -> let set = List.fold_left (fun set a -> StringSet.add a set) (List.fold_left (fun set a -> StringSet.add a set) StringSet.empty b) c in let list,list2 = StringSet.fold (fun x (l,l2) -> {kept_sites = StringSet.singleton x}::l,x::l2) set ([{kept_sites = StringSet.empty}],[]) in StringMap.add a list local_map, StringMap.add a list2 site_map) (StringMap.empty,StringMap.empty) cpb.Pb_sig.cpb_interface let compute_annotated_contact_map_in_approximated_mode system cpb contact_map = let local_map,_ = compute_annotated_contact_map_init cpb in List.fold_left (fun (sol,passing_sites) rs -> let passive = rs.Pb_sig.passive_species in let passing_sites = List.fold_left (fun sol ((a,b,c),(d,e,f)) -> let fadd x y sol = if List.exists (fun a -> (List.exists (fun b -> match b with M((a',b',_),_),_ when x=(a',b') -> true | B(a',b',c'),_ | AL((a',b',c'),_),_ when x=(a',b') && c'<>y -> true | L((a',b',c'),_),_ when x=(a',b') && c'<>y -> true | L(_,(a',b',c')),_ when x=(a',b') && c'<>y -> true | _ -> false ) a.Pb_sig.injective_guard)) rs.Pb_sig.rules then String2Set.add (snd x,y) sol else sol in fadd (a,b) c (fadd (d,e) f passing_sites)) passing_sites passive in let local_map = List.fold_left (fun sol a -> List.fold_left (fun sol a -> let fadd x y sol = let old' = try String2Map.find x sol with Not_found -> StringSet.empty in String2Map.add x (StringSet.add y old') sol in match a with H (x,x'),true -> (try (let _ = String2Map.find (x,x') sol in sol) with Not_found -> (String2Map.add (x,x') StringSet.empty sol)) | H _,_ -> sol | Connected _,_ -> sol | B(a,a',b),_ -> fadd (a,a') b sol | AL((a,a',b),_),_ -> fadd (a,a') b sol | L((a,a',b),(c,c',d)),_ -> fadd (a,a') b (fadd (c,c') d sol) | M((a,a',b),c),_ -> fadd (a,a') b sol | _ -> error 923 ) sol a.Pb_sig.injective_guard) String2Map.empty rs.Pb_sig.rules in String2Map.fold (fun (_,a) b sol -> let old = try StringMap.find a sol with Not_found -> [] in StringMap.add a ({kept_sites=b}::old) sol) local_map sol,passing_sites ) (local_map,String2Set.empty) system let trivial_rule rs = let control = rs.Pb_sig.control in let context = control.Pb_sig.context_update in let uncontext = control.Pb_sig.uncontext_update in match context,uncontext with _,[a,b,c] -> begin (List.for_all (fun rule -> List.for_all (fun (bb,bool) -> match bb,bool with B(x,y,z),true when x=a && y=b && z=c -> true | H(_),_ -> true | _ -> false ) rule.Pb_sig.injective_guard ) rs.Pb_sig.rules ) && (List.for_all (fun (bb,bool) -> match (bb,bool) with B(x,y,z),false when x=a && y=b && z=c -> true | _ -> false) context) end | _,[] -> begin let rec aux context rep = match context with (AL(_),_)::q | (B(_),_)::q-> aux q rep | (L((a,b,c),(d,e,f)),false)::q -> begin match rep with None -> aux q (Some((a,b,c),(d,e,f))) | Some _ -> false,None end | [] -> begin match rep with None -> false,None | x -> true,x end | _ -> false,None in let b,binding = aux context None in if b then match binding with None -> error 958 | Some ((a,b,c),(d,e,f)) -> List.for_all (fun rule -> List.for_all (fun (bb,bool) -> match bb,bool with B(x,y,z),true when (x=a && y=b && z=c) or (x=d && y=e && z=f) -> true | AL((x,y,z),(xx,yy)),true when (x=a && y=b && z=c && xx=e && yy=f) or (x=d && y=e && z=f && xx=b & yy=c) -> true | L((x,y,z),(xx,yy,zz)),true when (x=a && y=b && z=c && xx=d && yy=e && zz=f) or (xx=a && yy=b && zz=c && x=d && y=e && z=f) -> true | H(_),_ -> true | _ -> false ) rule.Pb_sig.injective_guard ) rs.Pb_sig.rules else false end | _ -> false type tr = Half of string*string | Unbind of string*string*string*string let which_trivial_rule rs = let control = rs.Pb_sig.control in let context = control.Pb_sig.context_update in let uncontext = control.Pb_sig.uncontext_update in match context,uncontext with _,[a,b,c] -> Half(b,c) | _,[] -> begin let rec aux context rep = match context with (AL(_),_)::q | (B(_),_)::q-> aux q rep | (L((a,b,c),(d,e,f)),false)::q -> begin match rep with None -> Some (Unbind(b,c,e,f)) | Some _ -> None end | _ -> None in (match aux context None with None -> error 256 | Some a -> a ) end | _ -> error 259 let trivial_rule2 (contact,keep_this_link) rule = trivial_rule rule && begin match which_trivial_rule rule with Half(a,b) -> List.for_all (fun (_,c,d) -> not (keep_this_link (a,b) (c,d))) (contact (a,b)) | Unbind(a,b,c,d) -> not (keep_this_link (a,b) (c,d)) end let compute_annotated_contact_map_in_compression_mode system cpb contact_map = let local_map,site_map = compute_annotated_contact_map_init cpb in let classes = StringMap.map (fun l -> List.fold_left (fun sol a -> StringListSet.add (StringSet.elements a.kept_sites) sol) StringListSet.empty l) local_map in let fadd ag x y map = let old1,old2 = try StringMap.find ag map with Not_found -> (StringMap.empty,StringMap.empty) in let old1_image = try StringMap.find x old1 with Not_found -> StringSet.empty in let new1_image = StringSet.add y old1_image in let old2_image = try StringMap.find y old2 with Not_found -> StringSet.empty in let new2_image = StringSet.add x old2_image in let new1_map = StringMap.add x new1_image old1 in let new2_map = StringMap.add y new2_image old2 in StringMap.add ag (new1_map,new2_map) map in let site_relation,classes,dangerous_sites = List.fold_left (fun (relation,classes,dangerous_sites) rs -> let modified_sites = let fadd a b sol = let old = try String2Map.find a sol with Not_found -> StringSet.empty in String2Map.add a (StringSet.add b old) sol in let modif = List.fold_left (fun modif a -> match a with H _,_ -> modif | Connected _,_ -> modif | B(a,a',b),_ -> fadd (a,a') b modif | AL((a,a',b),_),_ -> fadd (a,a') b modif | L((a,a',b),(c,c',d)),_ -> fadd (a,a') b (fadd (c,c') d modif) | M((a,a',b),c),_ -> fadd (a,a') b modif | _ -> error 964 ) String2Map.empty rs.Pb_sig.control.Pb_sig.context_update in let modif = List.fold_left (fun modif (a,b,c) -> fadd (a,b) c modif) modif rs.Pb_sig.control.Pb_sig.uncontext_update in let modif = List.fold_left (fun modif ((a,b,c),_) -> fadd (a,b) c modif) modif rs.passive_species in modif in List.fold_left (fun (relation,classes,dangerous_sites) rule -> let tested_sites,free_sites = List.fold_left (fun (sol1,sol2) a -> let fadd x y sol = let old' = try String2Map.find x sol with Not_found -> StringSet.empty in String2Map.add x (StringSet.add y old') sol in match a with H (x,x'),true -> (try (let _ = String2Map.find (x,x') sol1 in sol1,sol2) with Not_found -> (String2Map.add (x,x') StringSet.empty sol1,sol2)) | H _,_ -> sol1,sol2 | Connected _,_ -> sol1,sol2 | B(a,a',b),false -> fadd (a,a') b sol1,fadd (a,a') b sol2 | B(a,a',b),_ -> fadd (a,a') b sol1,sol2 | AL((a,a',b),_),true -> fadd (a,a') b sol1,fadd (a,a') b sol2 | AL((a,a',b),_),_ -> fadd (a,a') b sol1,sol2 | L((a,a',b),(c,c',d)),true -> fadd (a,a') b (fadd (c,c') d sol1),fadd (a,a') b (fadd (c,c') d sol2) | L((a,a',b),(c,c',d)),_ -> fadd (a,a') b (fadd (c,c') d sol1),sol2 | M((a,a',b),c),_ -> fadd (a,a') b sol1,sol2 | _ -> error 964 ) (String2Map.empty,String2Map.empty) rule.Pb_sig.injective_guard in let classes = String2Map.fold (fun (_,a) set classes -> let tested_list = StringSet.elements set in let old = try StringMap.find a classes with Not_found -> StringListSet.empty in StringMap.add a (StringListSet.add tested_list old) classes ) tested_sites classes in let relation,dangerous_sites = List.fold_left (fun (relation,dangerous_sites) a_id -> let a = try StringMap.find a_id rs.Pb_sig.specie_of_id with Not_found -> error 394 in let tested = try String2Map.find (a_id,a) tested_sites with Not_found -> StringSet.empty in let relation = StringSet.fold (fun site relation -> StringSet.fold (fun site' relation -> if site==site' then relation else (fadd a site site' relation)) ( try List.fold_left (fun sol s -> StringSet.add s sol) (StringSet.empty) (StringMap.find a site_map) with Not_found -> StringSet.empty ) relation) tested relation in let dangerous_sites = let free_sites = try String2Map.find (a_id,a) free_sites with Not_found -> StringSet.empty in let sites = try List.fold_left (fun sol s -> StringSet.add s sol) (StringSet.empty) (StringMap.find a site_map) with Not_found -> StringSet.empty in let diff = StringSet.diff sites free_sites in StringSet.fold (fun s -> String2Set.add (a,s)) diff dangerous_sites in relation,dangerous_sites) (relation,dangerous_sites) rs.Pb_sig.control.Pb_sig.remove in let relation = String2Map.fold2 (fun _ _ x -> x) (fun _ _ x -> x) (fun (a,a') tested modified rel -> StringSet.fold (fun test rel -> StringSet.fold (fun control rel -> if test=control then rel else fadd a' test control rel) modified rel) tested rel) tested_sites modified_sites relation in relation,classes,dangerous_sites) (relation,classes,dangerous_sites) rs.Pb_sig.rules) (StringMap.empty,classes,String2Set.empty) system in let local_map = StringMap.map (fun lset -> StringListSet.fold (fun a b -> {kept_sites=(List.fold_left (fun set b -> StringSet.add b set) StringSet.empty a)}::b) lset []) classes in let _ = if debug then let _ = StringMap.iter (fun a (map1,map2) -> let _ = print_string "AGENT " in let _ = print_string a in let _ = print_newline () in let _ = StringMap.iter (fun b s -> let _ = print_string "map1\n " in let _ = StringSet.iter (fun c -> print_string b; print_string "->"; print_string c; print_newline ()) s in ()) map1 in let _ = StringMap.iter (fun b s -> let _ = print_string "map2\n" in let _ = StringSet.iter (fun c -> print_string b; print_string "->"; print_string c; print_newline ()) s in ()) map2 in ()) site_relation in () in let local_map = StringMap.fold (fun a (map1,map2) local_map -> let _ = if debug then let _ = print_string a in let _ = StringMap.iter (fun b s -> let _ = print_string "map2\n" in let _ = StringSet.iter (fun c -> print_string b; print_string "->"; print_string c; print_newline ()) s in ()) map2 in let _ = print_newline () in () in let rec aux to_visit rep = match to_visit with [] -> rep | t::q when StringSet.mem t rep -> aux q rep | t::q -> let rep = StringSet.add t rep in let to_visit = StringSet.fold (fun a l -> a::l) (try StringMap.find t map2 with Not_found -> StringSet.empty) to_visit in aux to_visit rep in let covering_classes = StringMap.fold (fun a _ l -> ({kept_sites= aux [a] StringSet.empty})::l) map2 [] in let l2 = StringMap.find a classes in let covering_classes = StringListSet.fold (fun a l -> ({kept_sites = aux a StringSet.empty})::l) l2 covering_classes in let old = try StringMap.find a local_map with Not_found -> [] in StringMap.add a (covering_classes@old) local_map) site_relation local_map in let solid_edges = String22Set.empty in let solid_edges = List.fold_left (fun solid_edges rs -> if trivial_rule rs then solid_edges else let guard = rs.Pb_sig.rules in let solid_edges = List.fold_left (fun solid_edges guard -> List.fold_left (fun solid_edges x -> match x with L((_,b,c),(_,e,f)),true |AL((_,b , c),(e , f)),true : : Binding type do not cause information leakage ! ! ! -> String22Set.add ((b,c),(e,f)) solid_edges | _ -> solid_edges) solid_edges guard.injective_guard) solid_edges guard in let solid_edges = List.fold_left (fun solid_edges b -> match b with L((a,b,c),(d,e,f)),false -> String22Set.add ((b,c),(e,f)) (String22Set.add ((e,f),(b,c)) solid_edges) | _ -> solid_edges) solid_edges rs.Pb_sig.control.Pb_sig.context_update in let solid_edges = List.fold_left (fun solid_edges (a,b,c) -> List.fold_left (fun solid_edges (_,d,e) -> String22Set.add ((b,c),(d,e)) (String22Set.add ((d,e),(b,c)) solid_edges)) solid_edges (contact_map (b,c))) solid_edges rs.Pb_sig.control.Pb_sig.uncontext_update in let solid_edges = String2Set.fold (fun (b,c) solid_edges -> List.fold_left (fun solid_edges (_,d,e) -> String22Set.add ((b,c),(d,e)) (String22Set.add ((d,e),(b,c)) solid_edges)) solid_edges (contact_map (b,c))) dangerous_sites solid_edges in solid_edges) solid_edges system in (local_map,solid_edges) let compute_annotated_contact_map_in_flat_mode system cpb contact_map = let passing_sites = List.fold_left (fun sol (a,b,c) -> List.fold_left (fun sol x -> String2Set.add (a,x) sol) sol c) String2Set.empty cpb.cpb_interface in let local_views = List.fold_left (fun sol (a,b,c) -> let site_set = List.fold_left (fun sol x -> StringSet.add x sol) (List.fold_left (fun sol x -> StringSet.add x sol) StringSet.empty c) b in StringMap.add a [{kept_sites=site_set}] sol) StringMap.empty cpb.cpb_interface in (local_views,passing_sites) let upgrade (x,y) cpb = (x, String2Map.fold (fun (a,b) l sol -> List.fold_left (fun sol (c,d) -> if String2Set.mem (a,b) y && String2Set.mem (c,d) y then String22Set.add ((a,b),(c,d)) sol else sol) sol l) (match cpb.cpb_contact with None -> error 1327 | Some a -> a) String22Set.empty )
6cd4ea91374644bfcc0763307f4651b61ec6dbbc248d869ec142882609019a41
5HT/ant
Parser.mli
open XNum; open Runtime; open Unicode.Types; open Unicode.SymbolTable; open Lexer; Priorities : 2 right || 3 right & & 4 non = = < > > < > = < = 5 left land lor lxor lsr lsl 6 left + - 7 left * / mod 8 left ^ 9 left function application 11 right prefix operations 12 left postfix operations Priorities: 2 right || 3 right && 4 non == <> > < >= <= 5 left land lor lxor lsr lsl 6 left + - 7 left * / mod 8 left ^ 9 left function application 11 right prefix operations 12 left postfix operations *) type pattern = [ PAnything | PId of symbol | PNumber of num | PChar of uc_char | PSymbol of symbol | PTuple of list pattern | PList of list pattern | PListTail of list pattern and pattern | PAssign of symbol and pattern ]; type term = [ TUnbound | TId of symbol | TNumber of num | TChar of uc_char | TSymbol of symbol | TApp of term and list term | TTuple of list term | TList of list term | TListTail of list term and term | TFun of list (list pattern * option term * term) | TLocal of list decl and term | TSequence of list stmt and term | TDo of list stmt | TIfThenElse of term and term and term | TMatch of term and list (pattern * option term * term) ] and decl = [ DFun of symbol and list pattern and option term and term | DPattern of pattern and term ] and stmt = [ SEquation of term and term | SIfThen of term and stmt | SIfThenElse of term and stmt and stmt (*| SForce of array term*) | SFunction of term ]; value parse_program : lexer -> list decl; value parse_expression : lexer -> term;
null
https://raw.githubusercontent.com/5HT/ant/6acf51f4c4ebcc06c52c595776e0293cfa2f1da4/VM/Private/Parser.mli
ocaml
| SForce of array term
open XNum; open Runtime; open Unicode.Types; open Unicode.SymbolTable; open Lexer; Priorities : 2 right || 3 right & & 4 non = = < > > < > = < = 5 left land lor lxor lsr lsl 6 left + - 7 left * / mod 8 left ^ 9 left function application 11 right prefix operations 12 left postfix operations Priorities: 2 right || 3 right && 4 non == <> > < >= <= 5 left land lor lxor lsr lsl 6 left + - 7 left * / mod 8 left ^ 9 left function application 11 right prefix operations 12 left postfix operations *) type pattern = [ PAnything | PId of symbol | PNumber of num | PChar of uc_char | PSymbol of symbol | PTuple of list pattern | PList of list pattern | PListTail of list pattern and pattern | PAssign of symbol and pattern ]; type term = [ TUnbound | TId of symbol | TNumber of num | TChar of uc_char | TSymbol of symbol | TApp of term and list term | TTuple of list term | TList of list term | TListTail of list term and term | TFun of list (list pattern * option term * term) | TLocal of list decl and term | TSequence of list stmt and term | TDo of list stmt | TIfThenElse of term and term and term | TMatch of term and list (pattern * option term * term) ] and decl = [ DFun of symbol and list pattern and option term and term | DPattern of pattern and term ] and stmt = [ SEquation of term and term | SIfThen of term and stmt | SIfThenElse of term and stmt and stmt | SFunction of term ]; value parse_program : lexer -> list decl; value parse_expression : lexer -> term;
b46bc82bb753c83c8bb27ec02ea3d847915c390bc48aaff865ca73d9ce2145f7
thheller/shadow-cljsjs
moment_timezone.cljs
(ns cljsjs.moment-timezone (:require ["moment-timezone"]))
null
https://raw.githubusercontent.com/thheller/shadow-cljsjs/eaf350d29d45adb85c0753dff77e276e7925a744/src/main/cljsjs/moment_timezone.cljs
clojure
(ns cljsjs.moment-timezone (:require ["moment-timezone"]))
f8804459673a053413e8b598bc15e352e483e19785b25e4f57a43811619276d5
kupl/FixML
sub5.ml
type formula = | True | False | Not of formula | AndAlso of formula * formula | OrElse of formula * formula | Imply of formula * formula | Equal of exp * exp and exp = | Num of int | Plus of exp * exp | Minus of exp * exp let rec eval : formula -> bool = fun f -> match f with | True -> true | False -> false | Not p -> not ( eval (p) ) | AndAlso (p, q) -> eval (p) && eval (q) | OrElse (p, q) -> eval (p) || eval (q) | Imply (p, q) -> not ( eval (p) ) || eval(q) | Equal (p, q) -> p = q ;;
null
https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/formula/formula1/submissions/sub5.ml
ocaml
type formula = | True | False | Not of formula | AndAlso of formula * formula | OrElse of formula * formula | Imply of formula * formula | Equal of exp * exp and exp = | Num of int | Plus of exp * exp | Minus of exp * exp let rec eval : formula -> bool = fun f -> match f with | True -> true | False -> false | Not p -> not ( eval (p) ) | AndAlso (p, q) -> eval (p) && eval (q) | OrElse (p, q) -> eval (p) || eval (q) | Imply (p, q) -> not ( eval (p) ) || eval(q) | Equal (p, q) -> p = q ;;
fd6c397e7027c581c5715251bec9cc6df8eb31f865e73a133e6b5d3cfd38777a
KaroshiBee/weevil
dap_terminate.ml
module D = Dap_messages.Data module On_request = Dap_handlers.Request_response.Make (struct type enum = Dap_commands.terminate type contents = D.TerminateArguments.t option type presence = D.Presence.opt type msg = (enum, contents, presence) Dap_request.Message.t type t = msg Dap_request.t let ctor = Dap_request.terminateRequest let enc = Dap_request.Message.enc_opt Dap_commands.terminate D.TerminateArguments.enc end) (struct type enum = Dap_commands.terminate type contents = D.EmptyObject.t option type presence = D.Presence.opt type msg = (enum, contents, presence) Dap_response.Message.t type t = msg Dap_response.t let ctor = Dap_response.terminateResponse let enc = Dap_response.Message.enc_opt Dap_commands.terminate D.EmptyObject.enc end) module Raise_terminated = Dap_handlers.Raise_event.Make (struct type enum = Dap_events.terminated type contents = D.TerminatedEvent_body.t option type presence = D.Presence.opt type msg = (enum, contents, presence) Dap_event.Message.t type t = msg Dap_event.t let ctor = Dap_event.terminatedEvent let enc = Dap_event.Message.enc_opt Dap_events.terminated D.TerminatedEvent_body.enc end)
null
https://raw.githubusercontent.com/KaroshiBee/weevil/1b166ba053062498c1ec05c885e04fba4ae7d831/lib/dapper/dap_terminate.ml
ocaml
module D = Dap_messages.Data module On_request = Dap_handlers.Request_response.Make (struct type enum = Dap_commands.terminate type contents = D.TerminateArguments.t option type presence = D.Presence.opt type msg = (enum, contents, presence) Dap_request.Message.t type t = msg Dap_request.t let ctor = Dap_request.terminateRequest let enc = Dap_request.Message.enc_opt Dap_commands.terminate D.TerminateArguments.enc end) (struct type enum = Dap_commands.terminate type contents = D.EmptyObject.t option type presence = D.Presence.opt type msg = (enum, contents, presence) Dap_response.Message.t type t = msg Dap_response.t let ctor = Dap_response.terminateResponse let enc = Dap_response.Message.enc_opt Dap_commands.terminate D.EmptyObject.enc end) module Raise_terminated = Dap_handlers.Raise_event.Make (struct type enum = Dap_events.terminated type contents = D.TerminatedEvent_body.t option type presence = D.Presence.opt type msg = (enum, contents, presence) Dap_event.Message.t type t = msg Dap_event.t let ctor = Dap_event.terminatedEvent let enc = Dap_event.Message.enc_opt Dap_events.terminated D.TerminatedEvent_body.enc end)
d320ba289ac530b9fe4b2327f57f750ae3106c02d316db3007a746f844cf0695
Vaguery/klapaucius
print_test.clj
(ns push.type.modules.print_test (:use midje.sweet) (:use [push.util.test-helpers]) (:use [push.type.module.print]) ) (fact "print-module has :name ':print'" (:name print-module) => :print) (fact "print-module has the expected :attributes" (:attributes print-module) => (contains #{:io})) (fact "print-module knows how to print some literals" (keys (:instructions print-module)) => (contains [:print-newline :print-space]))
null
https://raw.githubusercontent.com/Vaguery/klapaucius/17b55eb76feaa520a85d4df93597cccffe6bdba4/test/push/type/modules/print_test.clj
clojure
(ns push.type.modules.print_test (:use midje.sweet) (:use [push.util.test-helpers]) (:use [push.type.module.print]) ) (fact "print-module has :name ':print'" (:name print-module) => :print) (fact "print-module has the expected :attributes" (:attributes print-module) => (contains #{:io})) (fact "print-module knows how to print some literals" (keys (:instructions print-module)) => (contains [:print-newline :print-space]))
483791612b59437a25fdf17d9a654d7568dd93fc40608c2be52353337ff840fc
acl2/acl2
(SYMBOL-TO-INTEGER-ALISTP) (SUM-VALS (542 40 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (404 37 (:DEFINITION TRUE-LIST-LISTP)) (227 227 (:REWRITE DEFAULT-CAR)) (197 44 (:DEFINITION TRUE-LISTP)) (168 168 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (62 2 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-1)) (45 45 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (40 40 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (37 37 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (36 2 (:DEFINITION LOOP$-AS)) (16 8 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (12 2 (:DEFINITION CDR-LOOP$-AS-TUPLE)) (12 2 (:DEFINITION CAR-LOOP$-AS-TUPLE)) (10 2 (:DEFINITION EMPTY-LOOP$-AS-TUPLEP)) (8 8 (:TYPE-PRESCRIPTION LOOP$-AS)) (8 8 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (8 8 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-3)) (2 2 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-2)) ) (SUM-VALS-LOOP$ (95 5 (:DEFINITION ALWAYS$)) (75 5 (:REWRITE APPLY$-CONSP-ARITY-1)) (68 7 (:DEFINITION MEMBER-EQUAL)) (60 4 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (57 57 (:REWRITE DEFAULT-CDR)) (50 10 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (48 4 (:DEFINITION TRUE-LIST-LISTP)) (46 46 (:REWRITE DEFAULT-CAR)) (30 9 (:DEFINITION TRUE-LISTP)) (20 20 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (20 10 (:REWRITE APPLY$-PRIMITIVE)) (14 14 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (13 13 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (10 10 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (5 5 (:TYPE-PRESCRIPTION LEN)) (2 1 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (1 1 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (1 1 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) ) (SYMBOL-TO-INTEGER-ALISTP-IS-A-LOOP$ (103 103 (:REWRITE DEFAULT-CAR)) (78 78 (:REWRITE DEFAULT-CDR)) (27 27 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (25 25 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (18 9 (:REWRITE APPLY$-PRIMITIVE)) (9 9 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (9 9 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) ) (SUM-VALS-LOOP$-IS-SUM-VALS) (ARGLISTP1-LOOP$-V1) (ARGLISTP1-LOOP$-V1-IS-ARGLISTP1 (48 24 (:REWRITE LEGAL-VARIABLE-OR-CONSTANT-NAMEP-IMPLIES-SYMBOLP)) (36 36 (:REWRITE DEFAULT-CDR)) (29 29 (:REWRITE DEFAULT-CAR)) (24 24 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (12 6 (:REWRITE APPLY$-PRIMITIVE)) (6 6 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (6 6 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) ) (ARGLISTP1-LOOP$-V2 (413 6 (:REWRITE NOT-MEMBER-TAILS-INTEGER-LISTP)) (397 6 (:DEFINITION INTEGER-LISTP)) (367 6 (:REWRITE APPLY$-BADGEP-PROPERTIES . 1)) (363 2 (:DEFINITION APPLY$-BADGEP)) (250 13 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (224 18 (:DEFINITION TRUE-LIST-LISTP)) (195 2 (:DEFINITION SUBSETP-EQUAL)) (187 183 (:REWRITE DEFAULT-CDR)) (129 28 (:DEFINITION TRUE-LISTP)) (106 8 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-1)) (100 100 (:TYPE-PRESCRIPTION TRUE-LISTP)) (75 75 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (72 68 (:REWRITE DEFAULT-CAR)) (66 6 (:REWRITE NOT-MEMBER-TAILS-TRUE-LIST-LISTP)) (54 6 (:REWRITE NOT-MEMBER-TAILS-ACL2-NUMBER-LISTP)) (46 6 (:REWRITE NOT-MEMBER-TAILS-SYMBOL-LISTP)) (46 6 (:REWRITE NOT-MEMBER-TAILS-RATIONAL-LISTP)) (40 8 (:REWRITE TRUE-LIST-LISTP-TAILS)) (40 4 (:DEFINITION NATP)) (38 6 (:DEFINITION ACL2-NUMBER-LISTP)) (30 6 (:DEFINITION SYMBOL-LISTP)) (30 6 (:DEFINITION RATIONAL-LISTP)) (24 24 (:TYPE-PRESCRIPTION APPLY$-BADGEP)) (24 24 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-3)) (22 22 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (22 22 (:TYPE-PRESCRIPTION RATIONAL-LISTP)) (22 22 (:TYPE-PRESCRIPTION INTEGER-LISTP)) (22 22 (:TYPE-PRESCRIPTION ACL2-NUMBER-LISTP)) (16 16 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-2)) (16 8 (:REWRITE APPLY$-BADGEP-PROPERTIES . 3)) (14 14 (:TYPE-PRESCRIPTION LEN)) (14 2 (:DEFINITION LEN)) (13 13 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (12 6 (:LINEAR APPLY$-BADGEP-PROPERTIES . 1)) (12 2 (:DEFINITION ALL-NILS)) (10 10 (:TYPE-PRESCRIPTION ALL-NILS)) (8 8 (:TYPE-PRESCRIPTION SUBSETP-EQUAL)) (8 8 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (8 8 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (8 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (8 2 (:DEFINITION WEAK-APPLY$-BADGE-P)) (4 4 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (4 2 (:REWRITE DEFAULT-+-2)) (4 2 (:REWRITE APPLY$-BADGEP-PROPERTIES . 2)) (4 2 (:LINEAR APPLY$-BADGEP-PROPERTIES . 2)) (2 2 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS)) (2 2 (:REWRITE DEFAULT-+-1)) ) (ARGLISTP1-LOOP$-V2-IS-ARGLISTP1 (102 5 (:REWRITE APPLY$-CONSP-ARITY-1)) (80 78 (:REWRITE DEFAULT-CDR)) (60 30 (:REWRITE LEGAL-VARIABLE-OR-CONSTANT-NAMEP-IMPLIES-SYMBOLP)) (54 51 (:REWRITE DEFAULT-CAR)) (30 30 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (16 8 (:REWRITE APPLY$-PRIMITIVE)) (8 8 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (8 8 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (5 5 (:TYPE-PRESCRIPTION LEN)) ) (PACKN1-LOOP$ (370 1 (:DEFINITION EXPLODE-ATOM)) (310 3 (:DEFINITION EXPLODE-NONNEGATIVE-INTEGER)) (174 6 (:DEFINITION FLOOR)) (123 3 (:DEFINITION MOD)) (108 108 (:TYPE-PRESCRIPTION NONNEGATIVE-INTEGER-QUOTIENT)) (96 6 (:DEFINITION NONNEGATIVE-INTEGER-QUOTIENT)) (93 3 (:DEFINITION DIGIT-TO-CHAR)) (60 4 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (57 3 (:DEFINITION ALWAYS$)) (56 5 (:DEFINITION MEMBER-EQUAL)) (48 4 (:DEFINITION TRUE-LIST-LISTP)) (45 3 (:REWRITE APPLY$-CONSP-ARITY-1)) (38 38 (:REWRITE DEFAULT-CDR)) (31 31 (:REWRITE DEFAULT-CAR)) (30 21 (:REWRITE DEFAULT-+-2)) (30 9 (:REWRITE COMMUTATIVITY-OF-*)) (30 6 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (29 13 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (29 10 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (28 12 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (26 7 (:DEFINITION TRUE-LISTP)) (21 21 (:REWRITE DEFAULT-+-1)) (21 18 (:REWRITE DEFAULT-*-2)) (21 18 (:REWRITE DEFAULT-*-1)) (20 20 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (20 10 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (19 19 (:REWRITE DEFAULT-<-2)) (19 19 (:REWRITE DEFAULT-<-1)) (18 6 (:REWRITE COMMUTATIVITY-OF-+)) (18 6 (:DEFINITION NFIX)) (16 8 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (15 3 (:DEFINITION BINARY-APPEND)) (14 2 (:DEFINITION SYMBOL-LISTP)) (14 2 (:DEFINITION RATIONAL-LISTP)) (13 10 (:REWRITE DEFAULT-UNARY-MINUS)) (12 6 (:REWRITE APPLY$-PRIMITIVE)) (11 1 (:REWRITE DEFAULT-SYMBOL-NAME)) (10 10 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (10 10 (:TYPE-PRESCRIPTION RATIONAL-LISTP)) (10 7 (:REWRITE INTEGERP==>NUMERATOR-=-X)) (10 7 (:REWRITE INTEGERP==>DENOMINATOR-=-1)) (9 1 (:DEFINITION ACL2-NUMBER-LISTP)) (7 7 (:REWRITE DEFAULT-NUMERATOR)) (7 7 (:REWRITE DEFAULT-DENOMINATOR)) (7 1 (:DEFINITION INTEGER-LISTP)) (6 6 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (6 6 (:DEFINITION IFIX)) (5 5 (:TYPE-PRESCRIPTION INTEGER-LISTP)) (5 5 (:TYPE-PRESCRIPTION ACL2-NUMBER-LISTP)) (3 3 (:TYPE-PRESCRIPTION LEN)) (2 2 (:REWRITE DEFAULT-COERCE-2)) (2 2 (:REWRITE DEFAULT-COERCE-1)) (1 1 (:REWRITE ZP-OPEN)) (1 1 (:REWRITE DEFAULT-REALPART)) (1 1 (:REWRITE DEFAULT-IMAGPART)) ) (PACKN1-LOOP$-IS-PACKN1 (2076 6 (:DEFINITION EXPLODE-ATOM)) (1878 18 (:DEFINITION EXPLODE-NONNEGATIVE-INTEGER)) (1044 36 (:DEFINITION FLOOR)) (738 18 (:DEFINITION MOD)) (648 648 (:TYPE-PRESCRIPTION NONNEGATIVE-INTEGER-QUOTIENT)) (576 36 (:DEFINITION NONNEGATIVE-INTEGER-QUOTIENT)) (558 18 (:DEFINITION DIGIT-TO-CHAR)) (180 126 (:REWRITE DEFAULT-+-2)) (180 54 (:REWRITE COMMUTATIVITY-OF-*)) (126 126 (:REWRITE DEFAULT-+-1)) (126 108 (:REWRITE DEFAULT-*-2)) (126 108 (:REWRITE DEFAULT-*-1)) (120 120 (:REWRITE DEFAULT-<-2)) (120 120 (:REWRITE DEFAULT-<-1)) (120 24 (:DEFINITION BINARY-APPEND)) (108 36 (:REWRITE COMMUTATIVITY-OF-+)) (108 36 (:DEFINITION NFIX)) (78 60 (:REWRITE DEFAULT-UNARY-MINUS)) (60 42 (:REWRITE INTEGERP==>NUMERATOR-=-X)) (60 42 (:REWRITE INTEGERP==>DENOMINATOR-=-1)) (42 42 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (42 42 (:REWRITE DEFAULT-NUMERATOR)) (42 42 (:REWRITE DEFAULT-DENOMINATOR)) (36 36 (:REWRITE DEFAULT-CAR)) (36 36 (:DEFINITION IFIX)) (34 34 (:REWRITE DEFAULT-CDR)) (24 6 (:REWRITE ZP-OPEN)) (12 12 (:REWRITE DEFAULT-COERCE-2)) (12 12 (:REWRITE DEFAULT-COERCE-1)) (12 6 (:REWRITE DEFAULT-SYMBOL-NAME)) (6 6 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (6 6 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (6 6 (:REWRITE DEFAULT-REALPART)) (6 6 (:REWRITE DEFAULT-IMAGPART)) (6 3 (:REWRITE APPLY$-PRIMITIVE)) (3 3 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) ) (SELECT-CORRESPONDING-ELEMENT (49 2 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (44 3 (:DEFINITION TRUE-LIST-LISTP)) (20 4 (:DEFINITION TRUE-LISTP)) (12 12 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (9 9 (:REWRITE DEFAULT-CDR)) (5 5 (:REWRITE DEFAULT-CAR)) (2 2 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) ) (SELECT-CORRESPONDING-ELEMENT-LOOP$ (504 2 (:DEFINITION APPLY$-BADGEP)) (391 31 (:DEFINITION MEMBER-EQUAL)) (354 2 (:DEFINITION SUBSETP-EQUAL)) (279 279 (:REWRITE DEFAULT-CDR)) (274 4 (:DEFINITION NATP)) (267 1 (:REWRITE NOT-MEMBER-LOOP$-AS-INTEGER-2)) (264 4 (:REWRITE APPLY$-BADGEP-PROPERTIES . 1)) (257 16 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-1)) (254 1 (:REWRITE NOT-MEMBER-LOOP$-AS-NATP-2)) (251 4 (:LINEAR APPLY$-BADGEP-PROPERTIES . 1)) (147 5 (:DEFINITION LOOP$-AS)) (131 131 (:REWRITE DEFAULT-CAR)) (87 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ALWAYS$-2)) (74 5 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (60 4 (:DEFINITION ALWAYS$)) (58 5 (:REWRITE APPLY$-CONSP-ARITY-1)) (54 16 (:DEFINITION TRUE-LISTP)) (51 8 (:DEFINITION CDR-LOOP$-AS-TUPLE)) (51 8 (:DEFINITION CAR-LOOP$-AS-TUPLE)) (46 46 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-3)) (40 8 (:DEFINITION EMPTY-LOOP$-AS-TUPLEP)) (38 5 (:REWRITE BETA-REDUCTION)) (32 32 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-2)) (32 10 (:DEFINITION PAIRLIS$)) (28 4 (:DEFINITION RATIONAL-LISTP)) (24 2 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-LISTP-2)) (22 2 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-LISTP-1)) (20 20 (:TYPE-PRESCRIPTION RATIONAL-LISTP)) (17 17 (:TYPE-PRESCRIPTION APPLY$-BADGEP)) (16 8 (:REWRITE APPLY$-BADGEP-PROPERTIES . 3)) (16 2 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (14 7 (:REWRITE DEFAULT-+-2)) (12 2 (:DEFINITION ALL-NILS)) (10 10 (:TYPE-PRESCRIPTION ALL-NILS)) (10 5 (:REWRITE APPLY$-PRIMITIVE)) (10 1 (:REWRITE NOT-MEMBER-LOOP$-AS-TRUE-LIST-2)) (9 1 (:REWRITE NOT-MEMBER-LOOP$-AS-TRUE-LIST-1)) (8 8 (:TYPE-PRESCRIPTION SUBSETP-EQUAL)) (8 8 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (8 2 (:DEFINITION WEAK-APPLY$-BADGE-P)) (7 7 (:REWRITE DEFAULT-+-1)) (7 1 (:REWRITE NOT-MEMBER-LOOP$-AS-NATP-1)) (6 6 (:TYPE-PRESCRIPTION NATP)) (6 6 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (6 2 (:REWRITE NOT-MEMBER-LOOP$-AS-IDENTITY-2)) (6 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ACL2-NUMBER-2)) (5 5 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (5 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ACL2-NUMBER-1)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 2 (:REWRITE NOT-MEMBER-LOOP$-AS-IDENTITY-1)) (4 1 (:REWRITE NOT-MEMBER-LOOP$-AS-SYMBOL-2)) (4 1 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-2)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-SYMBOL-1)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-1)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-INTEGER-1)) (2 2 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (2 2 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (2 2 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (2 1 (:REWRITE APPLY$-BADGEP-PROPERTIES . 2)) (2 1 (:LINEAR APPLY$-BADGEP-PROPERTIES . 2)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-GENERAL)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ALWAYS$-1)) ) (SELECT-CORRESPONDING-ELEMENT-LOOP$-IS-SELECT-CORRESPONDING-ELEMENT (214 10 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (188 14 (:DEFINITION TRUE-LIST-LISTP)) (181 179 (:REWRITE DEFAULT-CAR)) (144 143 (:REWRITE DEFAULT-CDR)) (58 58 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (12 8 (:REWRITE APPLY$-PRIMITIVE)) (11 11 (:META RELINK-FANCY-SCION-CORRECT)) (10 10 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (4 4 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) ) (COUNTEREXAMPLE-TO-UNCONDITIONAL-EQUIVALENCE) (SAME-MOD-WILDCARD (36 36 (:REWRITE DEFAULT-CDR)) (36 18 (:REWRITE DEFAULT-+-2)) (18 18 (:REWRITE DEFAULT-+-1)) (14 14 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS)) (4 4 (:REWRITE DEFAULT-CAR)) ) (SAME-MOD-WILDCARD-LOOP$ (504 2 (:DEFINITION APPLY$-BADGEP)) (354 2 (:DEFINITION SUBSETP-EQUAL)) (349 29 (:DEFINITION MEMBER-EQUAL)) (274 4 (:DEFINITION NATP)) (267 1 (:REWRITE NOT-MEMBER-LOOP$-AS-INTEGER-2)) (264 4 (:REWRITE APPLY$-BADGEP-PROPERTIES . 1)) (259 259 (:REWRITE DEFAULT-CDR)) (254 1 (:REWRITE NOT-MEMBER-LOOP$-AS-NATP-2)) (251 4 (:LINEAR APPLY$-BADGEP-PROPERTIES . 1)) (204 14 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-1)) (111 3 (:DEFINITION LOOP$-AS)) (105 105 (:REWRITE DEFAULT-CAR)) (54 16 (:DEFINITION TRUE-LISTP)) (42 42 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-3)) (39 6 (:DEFINITION CDR-LOOP$-AS-TUPLE)) (39 6 (:DEFINITION CAR-LOOP$-AS-TUPLE)) (30 15 (:REWRITE DEFAULT-+-2)) (30 6 (:DEFINITION EMPTY-LOOP$-AS-TUPLEP)) (28 28 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-2)) (28 4 (:DEFINITION RATIONAL-LISTP)) (24 2 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-LISTP-2)) (22 2 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-LISTP-1)) (20 20 (:TYPE-PRESCRIPTION RATIONAL-LISTP)) (17 17 (:TYPE-PRESCRIPTION APPLY$-BADGEP)) (16 8 (:REWRITE APPLY$-BADGEP-PROPERTIES . 3)) (16 2 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (15 15 (:REWRITE DEFAULT-+-1)) (12 2 (:DEFINITION ALL-NILS)) (10 10 (:TYPE-PRESCRIPTION ALL-NILS)) (10 1 (:REWRITE NOT-MEMBER-LOOP$-AS-TRUE-LIST-2)) (9 1 (:REWRITE NOT-MEMBER-LOOP$-AS-TRUE-LIST-1)) (8 8 (:TYPE-PRESCRIPTION SUBSETP-EQUAL)) (8 8 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (8 2 (:DEFINITION WEAK-APPLY$-BADGE-P)) (7 1 (:REWRITE NOT-MEMBER-LOOP$-AS-NATP-1)) (6 6 (:TYPE-PRESCRIPTION NATP)) (6 6 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (6 2 (:REWRITE NOT-MEMBER-LOOP$-AS-IDENTITY-2)) (6 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ACL2-NUMBER-2)) (5 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ACL2-NUMBER-1)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 2 (:REWRITE NOT-MEMBER-LOOP$-AS-IDENTITY-1)) (4 1 (:REWRITE NOT-MEMBER-LOOP$-AS-SYMBOL-2)) (4 1 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-2)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-SYMBOL-1)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-1)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-INTEGER-1)) (2 2 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (2 2 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (2 2 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (2 1 (:REWRITE APPLY$-BADGEP-PROPERTIES . 2)) (2 1 (:LINEAR APPLY$-BADGEP-PROPERTIES . 2)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-GENERAL)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ALWAYS$-2)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ALWAYS$-1)) ) (SAME-MOD-WILDCARD-LOOP$-IS-SAME-MOD-WILDCARD (424 417 (:REWRITE DEFAULT-CAR)) (355 349 (:REWRITE DEFAULT-CDR)) (58 30 (:REWRITE DEFAULT-+-2)) (32 16 (:REWRITE APPLY$-PRIMITIVE)) (31 31 (:META RELINK-FANCY-SCION-CORRECT)) (30 30 (:REWRITE DEFAULT-+-1)) (26 26 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS)) (16 16 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) ) (GETPROPS1-LOOP$ (10 2 (:DEFINITION TRUE-LIST-LISTP)) (4 4 (:REWRITE DEFAULT-CDR)) (4 2 (:DEFINITION TRUE-LISTP)) (2 2 (:REWRITE DEFAULT-CAR)) (2 2 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) ) (GETPROPS1-LOOP$-IS-GETPROPS1 (176 175 (:REWRITE DEFAULT-CAR)) (169 168 (:REWRITE DEFAULT-CDR)) (42 21 (:REWRITE APPLY$-PRIMITIVE)) (21 21 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (12 12 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) ) (TRUE-LIST-LISTP-CAN-BE-REWRITTEN (29 29 (:REWRITE DEFAULT-CDR)) (24 24 (:REWRITE DEFAULT-CAR)) (10 5 (:REWRITE APPLY$-PRIMITIVE)) (5 5 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (5 5 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) ) (GETPROPS1-LOOP$-LOOP$ (34 2 (:DEFINITION ALWAYS$)) (26 2 (:REWRITE APPLY$-CONSP-ARITY-1)) (20 4 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (14 14 (:REWRITE DEFAULT-CDR)) (12 2 (:DEFINITION MEMBER-EQUAL)) (10 10 (:REWRITE DEFAULT-CAR)) (8 4 (:REWRITE APPLY$-PRIMITIVE)) (8 4 (:DEFINITION TRUE-LISTP)) (4 4 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (2 2 (:TYPE-PRESCRIPTION LEN)) ) (GETPROPS1-LOOP$-LOOP$-IS-GETPROPS1 (176 175 (:REWRITE DEFAULT-CAR)) (169 168 (:REWRITE DEFAULT-CDR)) (42 21 (:REWRITE APPLY$-PRIMITIVE)) (21 21 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (12 12 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) )
null
https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/demos/loop-primer/.sys/lp8%40useless-runes.lsp
lisp
(SYMBOL-TO-INTEGER-ALISTP) (SUM-VALS (542 40 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (404 37 (:DEFINITION TRUE-LIST-LISTP)) (227 227 (:REWRITE DEFAULT-CAR)) (197 44 (:DEFINITION TRUE-LISTP)) (168 168 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (62 2 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-1)) (45 45 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (40 40 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (37 37 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (36 2 (:DEFINITION LOOP$-AS)) (16 8 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (12 2 (:DEFINITION CDR-LOOP$-AS-TUPLE)) (12 2 (:DEFINITION CAR-LOOP$-AS-TUPLE)) (10 2 (:DEFINITION EMPTY-LOOP$-AS-TUPLEP)) (8 8 (:TYPE-PRESCRIPTION LOOP$-AS)) (8 8 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (8 8 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-3)) (2 2 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-2)) ) (SUM-VALS-LOOP$ (95 5 (:DEFINITION ALWAYS$)) (75 5 (:REWRITE APPLY$-CONSP-ARITY-1)) (68 7 (:DEFINITION MEMBER-EQUAL)) (60 4 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (57 57 (:REWRITE DEFAULT-CDR)) (50 10 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (48 4 (:DEFINITION TRUE-LIST-LISTP)) (46 46 (:REWRITE DEFAULT-CAR)) (30 9 (:DEFINITION TRUE-LISTP)) (20 20 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (20 10 (:REWRITE APPLY$-PRIMITIVE)) (14 14 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (13 13 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (10 10 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (5 5 (:TYPE-PRESCRIPTION LEN)) (2 1 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (1 1 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (1 1 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) ) (SYMBOL-TO-INTEGER-ALISTP-IS-A-LOOP$ (103 103 (:REWRITE DEFAULT-CAR)) (78 78 (:REWRITE DEFAULT-CDR)) (27 27 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (25 25 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (18 9 (:REWRITE APPLY$-PRIMITIVE)) (9 9 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (9 9 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) ) (SUM-VALS-LOOP$-IS-SUM-VALS) (ARGLISTP1-LOOP$-V1) (ARGLISTP1-LOOP$-V1-IS-ARGLISTP1 (48 24 (:REWRITE LEGAL-VARIABLE-OR-CONSTANT-NAMEP-IMPLIES-SYMBOLP)) (36 36 (:REWRITE DEFAULT-CDR)) (29 29 (:REWRITE DEFAULT-CAR)) (24 24 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (12 6 (:REWRITE APPLY$-PRIMITIVE)) (6 6 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (6 6 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) ) (ARGLISTP1-LOOP$-V2 (413 6 (:REWRITE NOT-MEMBER-TAILS-INTEGER-LISTP)) (397 6 (:DEFINITION INTEGER-LISTP)) (367 6 (:REWRITE APPLY$-BADGEP-PROPERTIES . 1)) (363 2 (:DEFINITION APPLY$-BADGEP)) (250 13 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (224 18 (:DEFINITION TRUE-LIST-LISTP)) (195 2 (:DEFINITION SUBSETP-EQUAL)) (187 183 (:REWRITE DEFAULT-CDR)) (129 28 (:DEFINITION TRUE-LISTP)) (106 8 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-1)) (100 100 (:TYPE-PRESCRIPTION TRUE-LISTP)) (75 75 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (72 68 (:REWRITE DEFAULT-CAR)) (66 6 (:REWRITE NOT-MEMBER-TAILS-TRUE-LIST-LISTP)) (54 6 (:REWRITE NOT-MEMBER-TAILS-ACL2-NUMBER-LISTP)) (46 6 (:REWRITE NOT-MEMBER-TAILS-SYMBOL-LISTP)) (46 6 (:REWRITE NOT-MEMBER-TAILS-RATIONAL-LISTP)) (40 8 (:REWRITE TRUE-LIST-LISTP-TAILS)) (40 4 (:DEFINITION NATP)) (38 6 (:DEFINITION ACL2-NUMBER-LISTP)) (30 6 (:DEFINITION SYMBOL-LISTP)) (30 6 (:DEFINITION RATIONAL-LISTP)) (24 24 (:TYPE-PRESCRIPTION APPLY$-BADGEP)) (24 24 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-3)) (22 22 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (22 22 (:TYPE-PRESCRIPTION RATIONAL-LISTP)) (22 22 (:TYPE-PRESCRIPTION INTEGER-LISTP)) (22 22 (:TYPE-PRESCRIPTION ACL2-NUMBER-LISTP)) (16 16 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-2)) (16 8 (:REWRITE APPLY$-BADGEP-PROPERTIES . 3)) (14 14 (:TYPE-PRESCRIPTION LEN)) (14 2 (:DEFINITION LEN)) (13 13 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (12 6 (:LINEAR APPLY$-BADGEP-PROPERTIES . 1)) (12 2 (:DEFINITION ALL-NILS)) (10 10 (:TYPE-PRESCRIPTION ALL-NILS)) (8 8 (:TYPE-PRESCRIPTION SUBSETP-EQUAL)) (8 8 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (8 8 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (8 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (8 2 (:DEFINITION WEAK-APPLY$-BADGE-P)) (4 4 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (4 2 (:REWRITE DEFAULT-+-2)) (4 2 (:REWRITE APPLY$-BADGEP-PROPERTIES . 2)) (4 2 (:LINEAR APPLY$-BADGEP-PROPERTIES . 2)) (2 2 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS)) (2 2 (:REWRITE DEFAULT-+-1)) ) (ARGLISTP1-LOOP$-V2-IS-ARGLISTP1 (102 5 (:REWRITE APPLY$-CONSP-ARITY-1)) (80 78 (:REWRITE DEFAULT-CDR)) (60 30 (:REWRITE LEGAL-VARIABLE-OR-CONSTANT-NAMEP-IMPLIES-SYMBOLP)) (54 51 (:REWRITE DEFAULT-CAR)) (30 30 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (16 8 (:REWRITE APPLY$-PRIMITIVE)) (8 8 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (8 8 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (5 5 (:TYPE-PRESCRIPTION LEN)) ) (PACKN1-LOOP$ (370 1 (:DEFINITION EXPLODE-ATOM)) (310 3 (:DEFINITION EXPLODE-NONNEGATIVE-INTEGER)) (174 6 (:DEFINITION FLOOR)) (123 3 (:DEFINITION MOD)) (108 108 (:TYPE-PRESCRIPTION NONNEGATIVE-INTEGER-QUOTIENT)) (96 6 (:DEFINITION NONNEGATIVE-INTEGER-QUOTIENT)) (93 3 (:DEFINITION DIGIT-TO-CHAR)) (60 4 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (57 3 (:DEFINITION ALWAYS$)) (56 5 (:DEFINITION MEMBER-EQUAL)) (48 4 (:DEFINITION TRUE-LIST-LISTP)) (45 3 (:REWRITE APPLY$-CONSP-ARITY-1)) (38 38 (:REWRITE DEFAULT-CDR)) (31 31 (:REWRITE DEFAULT-CAR)) (30 21 (:REWRITE DEFAULT-+-2)) (30 9 (:REWRITE COMMUTATIVITY-OF-*)) (30 6 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (29 13 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (29 10 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (28 12 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (26 7 (:DEFINITION TRUE-LISTP)) (21 21 (:REWRITE DEFAULT-+-1)) (21 18 (:REWRITE DEFAULT-*-2)) (21 18 (:REWRITE DEFAULT-*-1)) (20 20 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (20 10 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (19 19 (:REWRITE DEFAULT-<-2)) (19 19 (:REWRITE DEFAULT-<-1)) (18 6 (:REWRITE COMMUTATIVITY-OF-+)) (18 6 (:DEFINITION NFIX)) (16 8 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (15 3 (:DEFINITION BINARY-APPEND)) (14 2 (:DEFINITION SYMBOL-LISTP)) (14 2 (:DEFINITION RATIONAL-LISTP)) (13 10 (:REWRITE DEFAULT-UNARY-MINUS)) (12 6 (:REWRITE APPLY$-PRIMITIVE)) (11 1 (:REWRITE DEFAULT-SYMBOL-NAME)) (10 10 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (10 10 (:TYPE-PRESCRIPTION RATIONAL-LISTP)) (10 7 (:REWRITE INTEGERP==>NUMERATOR-=-X)) (10 7 (:REWRITE INTEGERP==>DENOMINATOR-=-1)) (9 1 (:DEFINITION ACL2-NUMBER-LISTP)) (7 7 (:REWRITE DEFAULT-NUMERATOR)) (7 7 (:REWRITE DEFAULT-DENOMINATOR)) (7 1 (:DEFINITION INTEGER-LISTP)) (6 6 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (6 6 (:DEFINITION IFIX)) (5 5 (:TYPE-PRESCRIPTION INTEGER-LISTP)) (5 5 (:TYPE-PRESCRIPTION ACL2-NUMBER-LISTP)) (3 3 (:TYPE-PRESCRIPTION LEN)) (2 2 (:REWRITE DEFAULT-COERCE-2)) (2 2 (:REWRITE DEFAULT-COERCE-1)) (1 1 (:REWRITE ZP-OPEN)) (1 1 (:REWRITE DEFAULT-REALPART)) (1 1 (:REWRITE DEFAULT-IMAGPART)) ) (PACKN1-LOOP$-IS-PACKN1 (2076 6 (:DEFINITION EXPLODE-ATOM)) (1878 18 (:DEFINITION EXPLODE-NONNEGATIVE-INTEGER)) (1044 36 (:DEFINITION FLOOR)) (738 18 (:DEFINITION MOD)) (648 648 (:TYPE-PRESCRIPTION NONNEGATIVE-INTEGER-QUOTIENT)) (576 36 (:DEFINITION NONNEGATIVE-INTEGER-QUOTIENT)) (558 18 (:DEFINITION DIGIT-TO-CHAR)) (180 126 (:REWRITE DEFAULT-+-2)) (180 54 (:REWRITE COMMUTATIVITY-OF-*)) (126 126 (:REWRITE DEFAULT-+-1)) (126 108 (:REWRITE DEFAULT-*-2)) (126 108 (:REWRITE DEFAULT-*-1)) (120 120 (:REWRITE DEFAULT-<-2)) (120 120 (:REWRITE DEFAULT-<-1)) (120 24 (:DEFINITION BINARY-APPEND)) (108 36 (:REWRITE COMMUTATIVITY-OF-+)) (108 36 (:DEFINITION NFIX)) (78 60 (:REWRITE DEFAULT-UNARY-MINUS)) (60 42 (:REWRITE INTEGERP==>NUMERATOR-=-X)) (60 42 (:REWRITE INTEGERP==>DENOMINATOR-=-1)) (42 42 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (42 42 (:REWRITE DEFAULT-NUMERATOR)) (42 42 (:REWRITE DEFAULT-DENOMINATOR)) (36 36 (:REWRITE DEFAULT-CAR)) (36 36 (:DEFINITION IFIX)) (34 34 (:REWRITE DEFAULT-CDR)) (24 6 (:REWRITE ZP-OPEN)) (12 12 (:REWRITE DEFAULT-COERCE-2)) (12 12 (:REWRITE DEFAULT-COERCE-1)) (12 6 (:REWRITE DEFAULT-SYMBOL-NAME)) (6 6 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (6 6 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (6 6 (:REWRITE DEFAULT-REALPART)) (6 6 (:REWRITE DEFAULT-IMAGPART)) (6 3 (:REWRITE APPLY$-PRIMITIVE)) (3 3 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) ) (SELECT-CORRESPONDING-ELEMENT (49 2 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (44 3 (:DEFINITION TRUE-LIST-LISTP)) (20 4 (:DEFINITION TRUE-LISTP)) (12 12 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (9 9 (:REWRITE DEFAULT-CDR)) (5 5 (:REWRITE DEFAULT-CAR)) (2 2 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) ) (SELECT-CORRESPONDING-ELEMENT-LOOP$ (504 2 (:DEFINITION APPLY$-BADGEP)) (391 31 (:DEFINITION MEMBER-EQUAL)) (354 2 (:DEFINITION SUBSETP-EQUAL)) (279 279 (:REWRITE DEFAULT-CDR)) (274 4 (:DEFINITION NATP)) (267 1 (:REWRITE NOT-MEMBER-LOOP$-AS-INTEGER-2)) (264 4 (:REWRITE APPLY$-BADGEP-PROPERTIES . 1)) (257 16 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-1)) (254 1 (:REWRITE NOT-MEMBER-LOOP$-AS-NATP-2)) (251 4 (:LINEAR APPLY$-BADGEP-PROPERTIES . 1)) (147 5 (:DEFINITION LOOP$-AS)) (131 131 (:REWRITE DEFAULT-CAR)) (87 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ALWAYS$-2)) (74 5 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (60 4 (:DEFINITION ALWAYS$)) (58 5 (:REWRITE APPLY$-CONSP-ARITY-1)) (54 16 (:DEFINITION TRUE-LISTP)) (51 8 (:DEFINITION CDR-LOOP$-AS-TUPLE)) (51 8 (:DEFINITION CAR-LOOP$-AS-TUPLE)) (46 46 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-3)) (40 8 (:DEFINITION EMPTY-LOOP$-AS-TUPLEP)) (38 5 (:REWRITE BETA-REDUCTION)) (32 32 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-2)) (32 10 (:DEFINITION PAIRLIS$)) (28 4 (:DEFINITION RATIONAL-LISTP)) (24 2 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-LISTP-2)) (22 2 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-LISTP-1)) (20 20 (:TYPE-PRESCRIPTION RATIONAL-LISTP)) (17 17 (:TYPE-PRESCRIPTION APPLY$-BADGEP)) (16 8 (:REWRITE APPLY$-BADGEP-PROPERTIES . 3)) (16 2 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (14 7 (:REWRITE DEFAULT-+-2)) (12 2 (:DEFINITION ALL-NILS)) (10 10 (:TYPE-PRESCRIPTION ALL-NILS)) (10 5 (:REWRITE APPLY$-PRIMITIVE)) (10 1 (:REWRITE NOT-MEMBER-LOOP$-AS-TRUE-LIST-2)) (9 1 (:REWRITE NOT-MEMBER-LOOP$-AS-TRUE-LIST-1)) (8 8 (:TYPE-PRESCRIPTION SUBSETP-EQUAL)) (8 8 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (8 2 (:DEFINITION WEAK-APPLY$-BADGE-P)) (7 7 (:REWRITE DEFAULT-+-1)) (7 1 (:REWRITE NOT-MEMBER-LOOP$-AS-NATP-1)) (6 6 (:TYPE-PRESCRIPTION NATP)) (6 6 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (6 2 (:REWRITE NOT-MEMBER-LOOP$-AS-IDENTITY-2)) (6 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ACL2-NUMBER-2)) (5 5 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (5 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ACL2-NUMBER-1)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 2 (:REWRITE NOT-MEMBER-LOOP$-AS-IDENTITY-1)) (4 1 (:REWRITE NOT-MEMBER-LOOP$-AS-SYMBOL-2)) (4 1 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-2)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-SYMBOL-1)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-1)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-INTEGER-1)) (2 2 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (2 2 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (2 2 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (2 1 (:REWRITE APPLY$-BADGEP-PROPERTIES . 2)) (2 1 (:LINEAR APPLY$-BADGEP-PROPERTIES . 2)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-GENERAL)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ALWAYS$-1)) ) (SELECT-CORRESPONDING-ELEMENT-LOOP$-IS-SELECT-CORRESPONDING-ELEMENT (214 10 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (188 14 (:DEFINITION TRUE-LIST-LISTP)) (181 179 (:REWRITE DEFAULT-CAR)) (144 143 (:REWRITE DEFAULT-CDR)) (58 58 (:TYPE-PRESCRIPTION TRUE-LIST-LISTP)) (12 8 (:REWRITE APPLY$-PRIMITIVE)) (11 11 (:META RELINK-FANCY-SCION-CORRECT)) (10 10 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (4 4 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) ) (COUNTEREXAMPLE-TO-UNCONDITIONAL-EQUIVALENCE) (SAME-MOD-WILDCARD (36 36 (:REWRITE DEFAULT-CDR)) (36 18 (:REWRITE DEFAULT-+-2)) (18 18 (:REWRITE DEFAULT-+-1)) (14 14 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS)) (4 4 (:REWRITE DEFAULT-CAR)) ) (SAME-MOD-WILDCARD-LOOP$ (504 2 (:DEFINITION APPLY$-BADGEP)) (354 2 (:DEFINITION SUBSETP-EQUAL)) (349 29 (:DEFINITION MEMBER-EQUAL)) (274 4 (:DEFINITION NATP)) (267 1 (:REWRITE NOT-MEMBER-LOOP$-AS-INTEGER-2)) (264 4 (:REWRITE APPLY$-BADGEP-PROPERTIES . 1)) (259 259 (:REWRITE DEFAULT-CDR)) (254 1 (:REWRITE NOT-MEMBER-LOOP$-AS-NATP-2)) (251 4 (:LINEAR APPLY$-BADGEP-PROPERTIES . 1)) (204 14 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-1)) (111 3 (:DEFINITION LOOP$-AS)) (105 105 (:REWRITE DEFAULT-CAR)) (54 16 (:DEFINITION TRUE-LISTP)) (42 42 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-3)) (39 6 (:DEFINITION CDR-LOOP$-AS-TUPLE)) (39 6 (:DEFINITION CAR-LOOP$-AS-TUPLE)) (30 15 (:REWRITE DEFAULT-+-2)) (30 6 (:DEFINITION EMPTY-LOOP$-AS-TUPLEP)) (28 28 (:REWRITE MEMBER-EQUAL-NEWVAR-COMPONENTS-2)) (28 4 (:DEFINITION RATIONAL-LISTP)) (24 2 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-LISTP-2)) (22 2 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-LISTP-1)) (20 20 (:TYPE-PRESCRIPTION RATIONAL-LISTP)) (17 17 (:TYPE-PRESCRIPTION APPLY$-BADGEP)) (16 8 (:REWRITE APPLY$-BADGEP-PROPERTIES . 3)) (16 2 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX)) (15 15 (:REWRITE DEFAULT-+-1)) (12 2 (:DEFINITION ALL-NILS)) (10 10 (:TYPE-PRESCRIPTION ALL-NILS)) (10 1 (:REWRITE NOT-MEMBER-LOOP$-AS-TRUE-LIST-2)) (9 1 (:REWRITE NOT-MEMBER-LOOP$-AS-TRUE-LIST-1)) (8 8 (:TYPE-PRESCRIPTION SUBSETP-EQUAL)) (8 8 (:REWRITE RATIONAL-LISTP-IMPLIES-RATIONALP)) (8 2 (:DEFINITION WEAK-APPLY$-BADGE-P)) (7 1 (:REWRITE NOT-MEMBER-LOOP$-AS-NATP-1)) (6 6 (:TYPE-PRESCRIPTION NATP)) (6 6 (:REWRITE INTEGER-LISTP-IMPLIES-INTEGERP)) (6 2 (:REWRITE NOT-MEMBER-LOOP$-AS-IDENTITY-2)) (6 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ACL2-NUMBER-2)) (5 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ACL2-NUMBER-1)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 2 (:REWRITE NOT-MEMBER-LOOP$-AS-IDENTITY-1)) (4 1 (:REWRITE NOT-MEMBER-LOOP$-AS-SYMBOL-2)) (4 1 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-2)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-SYMBOL-1)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-RATIONAL-1)) (3 1 (:REWRITE NOT-MEMBER-LOOP$-AS-INTEGER-1)) (2 2 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP)) (2 2 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) (2 2 (:REWRITE ACL2-NUMBER-LISTP-IMPLIES-ACL2-NUMBERP)) (2 1 (:REWRITE APPLY$-BADGEP-PROPERTIES . 2)) (2 1 (:LINEAR APPLY$-BADGEP-PROPERTIES . 2)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-GENERAL)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ALWAYS$-2)) (1 1 (:REWRITE NOT-MEMBER-LOOP$-AS-ALWAYS$-1)) ) (SAME-MOD-WILDCARD-LOOP$-IS-SAME-MOD-WILDCARD (424 417 (:REWRITE DEFAULT-CAR)) (355 349 (:REWRITE DEFAULT-CDR)) (58 30 (:REWRITE DEFAULT-+-2)) (32 16 (:REWRITE APPLY$-PRIMITIVE)) (31 31 (:META RELINK-FANCY-SCION-CORRECT)) (30 30 (:REWRITE DEFAULT-+-1)) (26 26 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS)) (16 16 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) ) (GETPROPS1-LOOP$ (10 2 (:DEFINITION TRUE-LIST-LISTP)) (4 4 (:REWRITE DEFAULT-CDR)) (4 2 (:DEFINITION TRUE-LISTP)) (2 2 (:REWRITE DEFAULT-CAR)) (2 2 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY)) ) (GETPROPS1-LOOP$-IS-GETPROPS1 (176 175 (:REWRITE DEFAULT-CAR)) (169 168 (:REWRITE DEFAULT-CDR)) (42 21 (:REWRITE APPLY$-PRIMITIVE)) (21 21 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (12 12 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) ) (TRUE-LIST-LISTP-CAN-BE-REWRITTEN (29 29 (:REWRITE DEFAULT-CDR)) (24 24 (:REWRITE DEFAULT-CAR)) (10 5 (:REWRITE APPLY$-PRIMITIVE)) (5 5 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (5 5 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) ) (GETPROPS1-LOOP$-LOOP$ (34 2 (:DEFINITION ALWAYS$)) (26 2 (:REWRITE APPLY$-CONSP-ARITY-1)) (20 4 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) (14 14 (:REWRITE DEFAULT-CDR)) (12 2 (:DEFINITION MEMBER-EQUAL)) (10 10 (:REWRITE DEFAULT-CAR)) (8 4 (:REWRITE APPLY$-PRIMITIVE)) (8 4 (:DEFINITION TRUE-LISTP)) (4 4 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (2 2 (:TYPE-PRESCRIPTION LEN)) ) (GETPROPS1-LOOP$-LOOP$-IS-GETPROPS1 (176 175 (:REWRITE DEFAULT-CAR)) (169 168 (:REWRITE DEFAULT-CDR)) (42 21 (:REWRITE APPLY$-PRIMITIVE)) (21 21 (:TYPE-PRESCRIPTION APPLY$-PRIMP)) (12 12 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT)) )
de8f22840063366feb776ee585cd02533c2412f1cbdc474cdb10f3489a50fe30
pjotrp/guix
linux-container.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2015 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu system linux-container) #:use-module (ice-9 match) #:use-module (srfi srfi-1) #:use-module (guix config) #:use-module (guix store) #:use-module (guix gexp) #:use-module (guix derivations) #:use-module (guix monads) #:use-module (gnu build linux-container) #:use-module (gnu services) #:use-module (gnu system) #:use-module (gnu system file-systems) #:export (mapping->file-system system-container containerized-operating-system container-script)) (define (mapping->file-system mapping) "Return a file system that realizes MAPPING." (match mapping (($ <file-system-mapping> source target writable?) (file-system (mount-point target) (device source) (type "none") (flags (if writable? '(bind-mount) '(bind-mount read-only))) (check? #f) (create-mount-point? #t))))) (define (containerized-operating-system os mappings) "Return an operating system based on OS for use in a Linux container environment. MAPPINGS is a list of <file-system-mapping> to realize in the containerized OS." (define user-file-systems (remove (lambda (fs) (let ((target (file-system-mount-point fs)) (source (file-system-device fs))) (or (string=? target (%store-prefix)) (string=? target "/") (string-prefix? "/dev/" source) (string-prefix? "/dev" target) (string-prefix? "/sys" target)))) (operating-system-file-systems os))) (define (mapping->fs fs) (file-system (inherit (mapping->file-system fs)) (needed-for-boot? #t))) (operating-system (inherit os) (swap-devices '()) ; disable swap (file-systems (append (map mapping->fs (cons %store-mapping mappings)) %container-file-systems user-file-systems)))) (define* (container-script os #:key (mappings '())) "Return a derivation of a script that runs OS as a Linux container. MAPPINGS is a list of <file-system> objects that specify the files/directories that will be shared with the host system." (let* ((os (containerized-operating-system os mappings)) (file-systems (filter file-system-needed-for-boot? (operating-system-file-systems os))) (specs (map file-system->spec file-systems))) (mlet* %store-monad ((os-drv (operating-system-derivation os #:container? #t))) (define script #~(begin (use-modules (gnu build linux-container) (guix build utils)) (call-with-container '#$specs (lambda () (setenv "HOME" "/root") (setenv "TMPDIR" "/tmp") (setenv "GUIX_NEW_SYSTEM" #$os-drv) (for-each mkdir-p '("/run" "/bin" "/etc" "/home" "/var")) (primitive-load (string-append #$os-drv "/boot"))) A range of 65536 uid / gids is used to cover 16 bits worth of ;; users and groups, which is sufficient for most cases. ;; ;; See: -nspawn.html#--private-users= #:host-uids 65536))) (gexp->script "run-container" script #:modules '((ice-9 match) (srfi srfi-98) (guix config) (guix utils) (guix build utils) (guix build syscalls) (gnu build file-systems) (gnu build linux-container))))))
null
https://raw.githubusercontent.com/pjotrp/guix/96250294012c2f1520b67f12ea80bfd6b98075a2/gnu/system/linux-container.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. disable swap users and groups, which is sufficient for most cases. See: -nspawn.html#--private-users=
Copyright © 2015 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu system linux-container) #:use-module (ice-9 match) #:use-module (srfi srfi-1) #:use-module (guix config) #:use-module (guix store) #:use-module (guix gexp) #:use-module (guix derivations) #:use-module (guix monads) #:use-module (gnu build linux-container) #:use-module (gnu services) #:use-module (gnu system) #:use-module (gnu system file-systems) #:export (mapping->file-system system-container containerized-operating-system container-script)) (define (mapping->file-system mapping) "Return a file system that realizes MAPPING." (match mapping (($ <file-system-mapping> source target writable?) (file-system (mount-point target) (device source) (type "none") (flags (if writable? '(bind-mount) '(bind-mount read-only))) (check? #f) (create-mount-point? #t))))) (define (containerized-operating-system os mappings) "Return an operating system based on OS for use in a Linux container environment. MAPPINGS is a list of <file-system-mapping> to realize in the containerized OS." (define user-file-systems (remove (lambda (fs) (let ((target (file-system-mount-point fs)) (source (file-system-device fs))) (or (string=? target (%store-prefix)) (string=? target "/") (string-prefix? "/dev/" source) (string-prefix? "/dev" target) (string-prefix? "/sys" target)))) (operating-system-file-systems os))) (define (mapping->fs fs) (file-system (inherit (mapping->file-system fs)) (needed-for-boot? #t))) (operating-system (inherit os) (file-systems (append (map mapping->fs (cons %store-mapping mappings)) %container-file-systems user-file-systems)))) (define* (container-script os #:key (mappings '())) "Return a derivation of a script that runs OS as a Linux container. MAPPINGS is a list of <file-system> objects that specify the files/directories that will be shared with the host system." (let* ((os (containerized-operating-system os mappings)) (file-systems (filter file-system-needed-for-boot? (operating-system-file-systems os))) (specs (map file-system->spec file-systems))) (mlet* %store-monad ((os-drv (operating-system-derivation os #:container? #t))) (define script #~(begin (use-modules (gnu build linux-container) (guix build utils)) (call-with-container '#$specs (lambda () (setenv "HOME" "/root") (setenv "TMPDIR" "/tmp") (setenv "GUIX_NEW_SYSTEM" #$os-drv) (for-each mkdir-p '("/run" "/bin" "/etc" "/home" "/var")) (primitive-load (string-append #$os-drv "/boot"))) A range of 65536 uid / gids is used to cover 16 bits worth of #:host-uids 65536))) (gexp->script "run-container" script #:modules '((ice-9 match) (srfi srfi-98) (guix config) (guix utils) (guix build utils) (guix build syscalls) (gnu build file-systems) (gnu build linux-container))))))
fc2eab69caf61781d6e9bb366bad718d1aba353f24d6b8dbe8ed6f3e65eebeed
thelema/ocaml-community
common.mli
(***********************************************************************) (* *) (* OCaml *) (* *) , projet , INRIA Rocquencourt (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) type line_tracker;; val open_tracker : string -> out_channel -> line_tracker val close_tracker : line_tracker -> unit val copy_chunk : string -> in_channel -> out_channel -> line_tracker -> Syntax.location -> bool -> unit val output_mem_access : out_channel -> int -> unit val output_memory_actions : string -> out_channel -> Lexgen.memory_action list -> unit val output_env : string -> in_channel -> out_channel -> line_tracker -> (Lexgen.ident * Lexgen.ident_info) list -> unit val output_args : out_channel -> string list -> unit val quiet_mode : bool ref;;
null
https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/lex/common.mli
ocaml
********************************************************************* OCaml *********************************************************************
, projet , INRIA Rocquencourt Copyright 2002 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . type line_tracker;; val open_tracker : string -> out_channel -> line_tracker val close_tracker : line_tracker -> unit val copy_chunk : string -> in_channel -> out_channel -> line_tracker -> Syntax.location -> bool -> unit val output_mem_access : out_channel -> int -> unit val output_memory_actions : string -> out_channel -> Lexgen.memory_action list -> unit val output_env : string -> in_channel -> out_channel -> line_tracker -> (Lexgen.ident * Lexgen.ident_info) list -> unit val output_args : out_channel -> string list -> unit val quiet_mode : bool ref;;
a718c04f42ec8438cb84cb6f98339097e43cdf1b9cf80f8886f50ac67416e7b0
5outh/Molecule
mi.hs
import Parser import Typechecker import Evaluator import Types import Control.Monad.Random import Control.Monad.Trans import System.Console.Haskeline main :: IO () main = runInputT defaultSettings loop where loop :: InputT IO () loop = do minput <- getInputLine "> " case minput of Nothing -> return () Just ":q" -> do -- we're just having fun here, right? bye <- liftIO $ evalRandIO $ uniform goodbyes outputStrLn bye Just (':':'t':' ':input) -> do case parseMolecule input of Left (ParseError err) -> outputStrLn err Right expr -> do case typecheck expr of Left (TypeError err) -> outputStrLn ("error: " ++ err) Right typ -> outputStrLn (show expr ++ " : " ++ show typ) loop Just input -> do case parseMolecule input of Left (ParseError err) -> outputStrLn err Right expr -> case typecheck expr of Left (TypeError err) -> outputStrLn ("error: " ++ err) Right _ -> case evaluate expr of Left (RuntimeError err) -> outputStrLn ("error: " ++ err) Right val -> outputStrLn $ show val loop goodbyes = [ "bye!" , "goodbye!" , "see ya later!" , "peace!" , "have a nice day!" , "catch ya on the flip-flop!" ]
null
https://raw.githubusercontent.com/5outh/Molecule/48effd7d3b4323b3678fd3a5cf1ee31aff41dbfb/mi.hs
haskell
we're just having fun here, right?
import Parser import Typechecker import Evaluator import Types import Control.Monad.Random import Control.Monad.Trans import System.Console.Haskeline main :: IO () main = runInputT defaultSettings loop where loop :: InputT IO () loop = do minput <- getInputLine "> " case minput of Nothing -> return () Just ":q" -> do bye <- liftIO $ evalRandIO $ uniform goodbyes outputStrLn bye Just (':':'t':' ':input) -> do case parseMolecule input of Left (ParseError err) -> outputStrLn err Right expr -> do case typecheck expr of Left (TypeError err) -> outputStrLn ("error: " ++ err) Right typ -> outputStrLn (show expr ++ " : " ++ show typ) loop Just input -> do case parseMolecule input of Left (ParseError err) -> outputStrLn err Right expr -> case typecheck expr of Left (TypeError err) -> outputStrLn ("error: " ++ err) Right _ -> case evaluate expr of Left (RuntimeError err) -> outputStrLn ("error: " ++ err) Right val -> outputStrLn $ show val loop goodbyes = [ "bye!" , "goodbye!" , "see ya later!" , "peace!" , "have a nice day!" , "catch ya on the flip-flop!" ]
9a4ac6b245fc1e97d5941585169f62d499f9a753d73ff95ba24b689a6f82bbb2
bytekid/mkbtt
pss.ml
Copyright 2008 , Christian Sternagel , * GNU Lesser General Public License * * This file is part of TTT2 . * * TTT2 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 . * * TTT2 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 TTT2 . If not , see < / > . * GNU Lesser General Public License * * This file is part of TTT2. * * TTT2 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. * * TTT2 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 TTT2. If not, see </>. *) (*** FUNCTIONS ****************************************************************) include Map.Make (P);;
null
https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/logic/src/pss.ml
ocaml
** FUNCTIONS ***************************************************************
Copyright 2008 , Christian Sternagel , * GNU Lesser General Public License * * This file is part of TTT2 . * * TTT2 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 . * * TTT2 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 TTT2 . If not , see < / > . * GNU Lesser General Public License * * This file is part of TTT2. * * TTT2 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. * * TTT2 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 TTT2. If not, see </>. *) include Map.Make (P);;
1e52242a3075664507146ec5088f3c1907234a4da375235f8bfd808aad7a6237
babashka/scittle
core.cljs
(ns scittle.core (:refer-clojure :exclude [time]) (:require [cljs.reader :refer [read-string]] [goog.object :as gobject] [goog.string] [sci.core :as sci] [sci.impl.unrestrict] [scittle.impl.common :refer [cljns]] [scittle.impl.error :as error])) (set! sci.impl.unrestrict/*unrestricted* true) (clojure.core/defmacro time "Evaluates expr and prints the time it took. Returns the value of expr." [expr] `(let [start# (cljs.core/system-time) ret# ~expr] (prn (cljs.core/str "Elapsed time: " (.toFixed (- (system-time) start#) 6) " msecs")) ret#)) (def stns (sci/create-ns 'sci.script-tag nil)) (def rns (sci/create-ns 'cljs.reader nil)) (def namespaces {'clojure.core {'time (sci/copy-var time cljns) 'system-time (sci/copy-var system-time cljns) 'random-uuid random-uuid 'read-string (sci/copy-var read-string rns)} 'goog.object {'set gobject/set 'get gobject/get} 'sci.core {'stacktrace sci/stacktrace 'format-stacktrace sci/format-stacktrace}}) (def !sci-ctx (atom (sci/init {:namespaces namespaces :classes {'js js/globalThis :allow :all 'Math js/Math} :ns-aliases {'clojure.pprint 'cljs.pprint}}))) (def !last-ns (volatile! @sci/ns)) (defn- -eval-string [s] (sci/binding [sci/ns @!last-ns] (let [rdr (sci/reader s)] (loop [res nil] (let [form (sci/parse-next @!sci-ctx rdr)] (if (= :sci.core/eof form) (do (vreset! !last-ns @sci/ns) res) (recur (sci/eval-form @!sci-ctx form)))))))) (defn ^:export eval-string [s] (try (-eval-string s) (catch :default e (error/error-handler e (:src @!sci-ctx)) (throw e)))) (defn register-plugin! [_plug-in-name sci-opts] (swap! !sci-ctx sci/merge-opts sci-opts)) (defn- eval-script-tags* [script-tags] (when-let [tag (first script-tags)] (if-let [text (not-empty (gobject/get tag "textContent"))] (let [scittle-id (str (gensym "scittle-tag-"))] (gobject/set tag "scittle_id" scittle-id) (swap! !sci-ctx assoc-in [:src scittle-id] text) (sci/binding [sci/file scittle-id] (eval-string text)) (eval-script-tags* (rest script-tags))) (let [src (.getAttribute tag "src") req (js/XMLHttpRequest.) _ (.open req "GET" src true) _ (gobject/set req "onload" (fn [] (this-as this (let [response (gobject/get this "response")] (gobject/set tag "scittle_id" src) ;; save source for error messages (swap! !sci-ctx assoc-in [:src src] response) (sci/binding [sci/file src] (eval-string response))) (eval-script-tags* (rest script-tags)))))] (.send req))))) (defn ^:export eval-script-tags [] (let [script-tags (js/document.querySelectorAll "script[type='application/x-scittle']")] (eval-script-tags* script-tags))) (def auto-load-disabled? (volatile! false)) (defn ^:export disable-auto-eval "By default, scittle evaluates script nodes on the DOMContentLoaded event using the eval-script-tags function. This function disables that behavior." [] (vreset! auto-load-disabled? true)) (js/document.addEventListener "DOMContentLoaded" (fn [] (when-not @auto-load-disabled? (eval-script-tags))), false) (enable-console-print!) (sci/alter-var-root sci/print-fn (constantly *print-fn*))
null
https://raw.githubusercontent.com/babashka/scittle/11b7a56ab8073efd7e9e123b74f10bd38e6e4f16/src/scittle/core.cljs
clojure
save source for error messages
(ns scittle.core (:refer-clojure :exclude [time]) (:require [cljs.reader :refer [read-string]] [goog.object :as gobject] [goog.string] [sci.core :as sci] [sci.impl.unrestrict] [scittle.impl.common :refer [cljns]] [scittle.impl.error :as error])) (set! sci.impl.unrestrict/*unrestricted* true) (clojure.core/defmacro time "Evaluates expr and prints the time it took. Returns the value of expr." [expr] `(let [start# (cljs.core/system-time) ret# ~expr] (prn (cljs.core/str "Elapsed time: " (.toFixed (- (system-time) start#) 6) " msecs")) ret#)) (def stns (sci/create-ns 'sci.script-tag nil)) (def rns (sci/create-ns 'cljs.reader nil)) (def namespaces {'clojure.core {'time (sci/copy-var time cljns) 'system-time (sci/copy-var system-time cljns) 'random-uuid random-uuid 'read-string (sci/copy-var read-string rns)} 'goog.object {'set gobject/set 'get gobject/get} 'sci.core {'stacktrace sci/stacktrace 'format-stacktrace sci/format-stacktrace}}) (def !sci-ctx (atom (sci/init {:namespaces namespaces :classes {'js js/globalThis :allow :all 'Math js/Math} :ns-aliases {'clojure.pprint 'cljs.pprint}}))) (def !last-ns (volatile! @sci/ns)) (defn- -eval-string [s] (sci/binding [sci/ns @!last-ns] (let [rdr (sci/reader s)] (loop [res nil] (let [form (sci/parse-next @!sci-ctx rdr)] (if (= :sci.core/eof form) (do (vreset! !last-ns @sci/ns) res) (recur (sci/eval-form @!sci-ctx form)))))))) (defn ^:export eval-string [s] (try (-eval-string s) (catch :default e (error/error-handler e (:src @!sci-ctx)) (throw e)))) (defn register-plugin! [_plug-in-name sci-opts] (swap! !sci-ctx sci/merge-opts sci-opts)) (defn- eval-script-tags* [script-tags] (when-let [tag (first script-tags)] (if-let [text (not-empty (gobject/get tag "textContent"))] (let [scittle-id (str (gensym "scittle-tag-"))] (gobject/set tag "scittle_id" scittle-id) (swap! !sci-ctx assoc-in [:src scittle-id] text) (sci/binding [sci/file scittle-id] (eval-string text)) (eval-script-tags* (rest script-tags))) (let [src (.getAttribute tag "src") req (js/XMLHttpRequest.) _ (.open req "GET" src true) _ (gobject/set req "onload" (fn [] (this-as this (let [response (gobject/get this "response")] (gobject/set tag "scittle_id" src) (swap! !sci-ctx assoc-in [:src src] response) (sci/binding [sci/file src] (eval-string response))) (eval-script-tags* (rest script-tags)))))] (.send req))))) (defn ^:export eval-script-tags [] (let [script-tags (js/document.querySelectorAll "script[type='application/x-scittle']")] (eval-script-tags* script-tags))) (def auto-load-disabled? (volatile! false)) (defn ^:export disable-auto-eval "By default, scittle evaluates script nodes on the DOMContentLoaded event using the eval-script-tags function. This function disables that behavior." [] (vreset! auto-load-disabled? true)) (js/document.addEventListener "DOMContentLoaded" (fn [] (when-not @auto-load-disabled? (eval-script-tags))), false) (enable-console-print!) (sci/alter-var-root sci/print-fn (constantly *print-fn*))
7f361adefe015730121b8b46b7887812e2f01d810ead10b2dedc0944deab2be8
CryptoKami/cryptokami-core
Update.hs
-- | Binary serialization of core Update types. module Pos.Binary.Core.Update ( ) where import Universum import Control.Lens (_Left) import Data.Time.Units (Millisecond) import Serokell.Data.Memory.Units (Byte) import Pos.Binary.Class (Bi (..), Cons (..), Field (..), Raw, deriveSimpleBi, deriveSimpleBiCxt, encodeListLen, enforceSize) import Pos.Binary.Core.Common () import Pos.Binary.Core.Fee () import Pos.Binary.Core.Script () import Pos.Core.Common (CoinPortion, ScriptVersion, TxFeePolicy) import Pos.Core.Configuration (HasConfiguration) import Pos.Core.Slotting.Types (EpochIndex, FlatSlotId) import qualified Pos.Core.Update as U import Pos.Core.Update.Types (BlockVersion, BlockVersionData (..), SoftforkRule (..), SoftwareVersion) import Pos.Crypto (Hash) import Pos.Util.Util (toCborError) instance Bi U.ApplicationName where encode appName = encode (U.getApplicationName appName) decode = do appName <- decode toCborError $ U.mkApplicationName appName deriveSimpleBi ''U.BlockVersion [ Cons 'U.BlockVersion [ Field [| U.bvMajor :: Word16 |], Field [| U.bvMinor :: Word16 |], Field [| U.bvAlt :: Word8 |] ]] deriveSimpleBi ''U.SoftwareVersion [ Cons 'U.SoftwareVersion [ Field [| U.svAppName :: U.ApplicationName |], Field [| U.svNumber :: U.NumSoftwareVersion |] ]] deriveSimpleBi ''SoftforkRule [ Cons 'SoftforkRule [ Field [| srInitThd :: CoinPortion |], Field [| srMinThd :: CoinPortion |], Field [| srThdDecrement :: CoinPortion |] ]] deriveSimpleBi ''BlockVersionData [ Cons 'BlockVersionData [ Field [| bvdScriptVersion :: ScriptVersion |], Field [| bvdSlotDuration :: Millisecond |], Field [| bvdMaxBlockSize :: Byte |], Field [| bvdMaxHeaderSize :: Byte |], Field [| bvdMaxTxSize :: Byte |], Field [| bvdMaxProposalSize :: Byte |], Field [| bvdMpcThd :: CoinPortion |], Field [| bvdHeavyDelThd :: CoinPortion |], Field [| bvdUpdateVoteThd :: CoinPortion |], Field [| bvdUpdateProposalThd :: CoinPortion |], Field [| bvdUpdateImplicit :: FlatSlotId |], Field [| bvdSoftforkRule :: SoftforkRule |], Field [| bvdTxFeePolicy :: TxFeePolicy |], Field [| bvdUnlockStakeEpoch :: EpochIndex |] ]] deriveSimpleBi ''U.BlockVersionModifier [ Cons 'U.BlockVersionModifier [ Field [| U.bvmScriptVersion :: Maybe ScriptVersion |], Field [| U.bvmSlotDuration :: Maybe Millisecond |], Field [| U.bvmMaxBlockSize :: Maybe Byte |], Field [| U.bvmMaxHeaderSize :: Maybe Byte |], Field [| U.bvmMaxTxSize :: Maybe Byte |], Field [| U.bvmMaxProposalSize :: Maybe Byte |], Field [| U.bvmMpcThd :: Maybe CoinPortion |], Field [| U.bvmHeavyDelThd :: Maybe CoinPortion |], Field [| U.bvmUpdateVoteThd :: Maybe CoinPortion |], Field [| U.bvmUpdateProposalThd :: Maybe CoinPortion |], Field [| U.bvmUpdateImplicit :: Maybe FlatSlotId |], Field [| U.bvmSoftforkRule :: Maybe SoftforkRule |], Field [| U.bvmTxFeePolicy :: Maybe TxFeePolicy |], Field [| U.bvmUnlockStakeEpoch :: Maybe EpochIndex |] ]] instance Bi U.SystemTag where encode = encode . U.getSystemTag decode = decode >>= toCborError . U.mkSystemTag deriveSimpleBi ''U.UpdateData [ Cons 'U.UpdateData [ Field [| U.udAppDiffHash :: Hash Raw |], Field [| U.udPkgHash :: Hash Raw |], Field [| U.udUpdaterHash :: Hash Raw |], Field [| U.udMetadataHash :: Hash Raw |] ]] deriveSimpleBi ''U.UpdateProposalToSign [ Cons 'U.UpdateProposalToSign [ Field [| U.upsBV :: BlockVersion |], Field [| U.upsBVM :: U.BlockVersionModifier |], Field [| U.upsSV :: SoftwareVersion |], Field [| U.upsData :: HashMap U.SystemTag U.UpdateData |], Field [| U.upsAttr :: U.UpAttributes |] ]] instance HasConfiguration => Bi U.UpdateProposal where encode up = encodeListLen 7 <> encode (U.upBlockVersion up) <> encode (U.upBlockVersionMod up) <> encode (U.upSoftwareVersion up) <> encode (U.upData up) <> encode (U.upAttributes up) <> encode (U.upFrom up) <> encode (U.upSignature up) decode = do enforceSize "UpdateProposal" 7 toCborError =<< (U.mkUpdateProposal <$> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode) instance HasConfiguration => Bi U.UpdateVote where encode uv = encodeListLen 4 <> encode (U.uvKey uv) <> encode (U.uvProposalId uv) <> encode (U.uvDecision uv) <> encode (U.uvSignature uv) decode = do enforceSize "UpdateVote" 4 uvKey <- decode uvProposalId <- decode uvDecision <- decode uvSignature <- decode toCborError $ over _Left ("decode@UpdateVote: " <>) $ U.validateUpdateVote U.UnsafeUpdateVote{..} deriveSimpleBiCxt [t|HasConfiguration|] ''U.UpdatePayload [ Cons 'U.UpdatePayload [ Field [| U.upProposal :: Maybe U.UpdateProposal |], Field [| U.upVotes :: [U.UpdateVote] |] ]]
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/core/Pos/Binary/Core/Update.hs
haskell
| Binary serialization of core Update types.
module Pos.Binary.Core.Update ( ) where import Universum import Control.Lens (_Left) import Data.Time.Units (Millisecond) import Serokell.Data.Memory.Units (Byte) import Pos.Binary.Class (Bi (..), Cons (..), Field (..), Raw, deriveSimpleBi, deriveSimpleBiCxt, encodeListLen, enforceSize) import Pos.Binary.Core.Common () import Pos.Binary.Core.Fee () import Pos.Binary.Core.Script () import Pos.Core.Common (CoinPortion, ScriptVersion, TxFeePolicy) import Pos.Core.Configuration (HasConfiguration) import Pos.Core.Slotting.Types (EpochIndex, FlatSlotId) import qualified Pos.Core.Update as U import Pos.Core.Update.Types (BlockVersion, BlockVersionData (..), SoftforkRule (..), SoftwareVersion) import Pos.Crypto (Hash) import Pos.Util.Util (toCborError) instance Bi U.ApplicationName where encode appName = encode (U.getApplicationName appName) decode = do appName <- decode toCborError $ U.mkApplicationName appName deriveSimpleBi ''U.BlockVersion [ Cons 'U.BlockVersion [ Field [| U.bvMajor :: Word16 |], Field [| U.bvMinor :: Word16 |], Field [| U.bvAlt :: Word8 |] ]] deriveSimpleBi ''U.SoftwareVersion [ Cons 'U.SoftwareVersion [ Field [| U.svAppName :: U.ApplicationName |], Field [| U.svNumber :: U.NumSoftwareVersion |] ]] deriveSimpleBi ''SoftforkRule [ Cons 'SoftforkRule [ Field [| srInitThd :: CoinPortion |], Field [| srMinThd :: CoinPortion |], Field [| srThdDecrement :: CoinPortion |] ]] deriveSimpleBi ''BlockVersionData [ Cons 'BlockVersionData [ Field [| bvdScriptVersion :: ScriptVersion |], Field [| bvdSlotDuration :: Millisecond |], Field [| bvdMaxBlockSize :: Byte |], Field [| bvdMaxHeaderSize :: Byte |], Field [| bvdMaxTxSize :: Byte |], Field [| bvdMaxProposalSize :: Byte |], Field [| bvdMpcThd :: CoinPortion |], Field [| bvdHeavyDelThd :: CoinPortion |], Field [| bvdUpdateVoteThd :: CoinPortion |], Field [| bvdUpdateProposalThd :: CoinPortion |], Field [| bvdUpdateImplicit :: FlatSlotId |], Field [| bvdSoftforkRule :: SoftforkRule |], Field [| bvdTxFeePolicy :: TxFeePolicy |], Field [| bvdUnlockStakeEpoch :: EpochIndex |] ]] deriveSimpleBi ''U.BlockVersionModifier [ Cons 'U.BlockVersionModifier [ Field [| U.bvmScriptVersion :: Maybe ScriptVersion |], Field [| U.bvmSlotDuration :: Maybe Millisecond |], Field [| U.bvmMaxBlockSize :: Maybe Byte |], Field [| U.bvmMaxHeaderSize :: Maybe Byte |], Field [| U.bvmMaxTxSize :: Maybe Byte |], Field [| U.bvmMaxProposalSize :: Maybe Byte |], Field [| U.bvmMpcThd :: Maybe CoinPortion |], Field [| U.bvmHeavyDelThd :: Maybe CoinPortion |], Field [| U.bvmUpdateVoteThd :: Maybe CoinPortion |], Field [| U.bvmUpdateProposalThd :: Maybe CoinPortion |], Field [| U.bvmUpdateImplicit :: Maybe FlatSlotId |], Field [| U.bvmSoftforkRule :: Maybe SoftforkRule |], Field [| U.bvmTxFeePolicy :: Maybe TxFeePolicy |], Field [| U.bvmUnlockStakeEpoch :: Maybe EpochIndex |] ]] instance Bi U.SystemTag where encode = encode . U.getSystemTag decode = decode >>= toCborError . U.mkSystemTag deriveSimpleBi ''U.UpdateData [ Cons 'U.UpdateData [ Field [| U.udAppDiffHash :: Hash Raw |], Field [| U.udPkgHash :: Hash Raw |], Field [| U.udUpdaterHash :: Hash Raw |], Field [| U.udMetadataHash :: Hash Raw |] ]] deriveSimpleBi ''U.UpdateProposalToSign [ Cons 'U.UpdateProposalToSign [ Field [| U.upsBV :: BlockVersion |], Field [| U.upsBVM :: U.BlockVersionModifier |], Field [| U.upsSV :: SoftwareVersion |], Field [| U.upsData :: HashMap U.SystemTag U.UpdateData |], Field [| U.upsAttr :: U.UpAttributes |] ]] instance HasConfiguration => Bi U.UpdateProposal where encode up = encodeListLen 7 <> encode (U.upBlockVersion up) <> encode (U.upBlockVersionMod up) <> encode (U.upSoftwareVersion up) <> encode (U.upData up) <> encode (U.upAttributes up) <> encode (U.upFrom up) <> encode (U.upSignature up) decode = do enforceSize "UpdateProposal" 7 toCborError =<< (U.mkUpdateProposal <$> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode) instance HasConfiguration => Bi U.UpdateVote where encode uv = encodeListLen 4 <> encode (U.uvKey uv) <> encode (U.uvProposalId uv) <> encode (U.uvDecision uv) <> encode (U.uvSignature uv) decode = do enforceSize "UpdateVote" 4 uvKey <- decode uvProposalId <- decode uvDecision <- decode uvSignature <- decode toCborError $ over _Left ("decode@UpdateVote: " <>) $ U.validateUpdateVote U.UnsafeUpdateVote{..} deriveSimpleBiCxt [t|HasConfiguration|] ''U.UpdatePayload [ Cons 'U.UpdatePayload [ Field [| U.upProposal :: Maybe U.UpdateProposal |], Field [| U.upVotes :: [U.UpdateVote] |] ]]
81c04388b48aff87f49152990298243efc6b502f7d102b5bde6ad1dce1d2e769
erlang/otp
gen_tcp_api_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1998 - 2022 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% -module(gen_tcp_api_SUITE). Tests the documented API for the gen_tcp functions . The " normal " cases %% are not tested here, because they are tested indirectly in this and %% and other test suites. -include_lib("common_test/include/ct.hrl"). -include_lib("kernel/include/inet.hrl"). -include("kernel_test_lib.hrl"). -export([ all/0, suite/0, groups/0, init_per_suite/1, end_per_suite/1, init_per_group/2, end_per_group/2, init_per_testcase/2, end_per_testcase/2, t_connect_timeout/1, t_accept_timeout/1, t_connect_src_port/1, t_connect_bad/1, t_recv_timeout/1, t_recv_eof/1, t_recv_delim/1, t_shutdown_write/1, t_shutdown_both/1, t_shutdown_error/1, t_shutdown_async/1, t_fdopen/1, t_fdconnect/1, t_implicit_inet6/1, t_local_basic/1, t_local_unbound/1, t_local_fdopen/1, t_local_fdopen_listen/1, t_local_fdopen_listen_unbound/1, t_local_fdopen_connect/1, t_local_fdopen_connect_unbound/1, t_local_abstract/1, t_accept_inet6_tclass/1, s_accept_with_explicit_socket_backend/1, t_simple_local_sockaddr_in_send_recv/1, t_simple_link_local_sockaddr_in_send_recv/1, t_simple_local_sockaddr_in6_send_recv/1, t_simple_link_local_sockaddr_in6_send_recv/1 ]). -export([getsockfd/0, closesockfd/1]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% suite() -> [ {ct_hooks,[ts_install_cth]}, {timetrap,{minutes,1}} ]. all() -> %% This is a temporary measure to ensure that we can %% test the socket backend without effecting *all* %% applications on *all* machines. This flag is set only for * one * host . case ?TEST_INET_BACKENDS() of true -> [ {group, inet_backend_default}, {group, inet_backend_inet}, {group, inet_backend_socket}, {group, s_misc} ]; _ -> [ {group, inet_backend_default}, {group, s_misc} ] end. groups() -> [ {inet_backend_default, [], inet_backend_default_cases()}, {inet_backend_inet, [], inet_backend_inet_cases()}, {inet_backend_socket, [], inet_backend_socket_cases()}, {t_accept, [], t_accept_cases()}, {t_connect, [], t_connect_cases()}, {t_recv, [], t_recv_cases()}, {t_shutdown, [], t_shutdown_cases()}, {t_misc, [], t_misc_cases()}, {sockaddr, [], sockaddr_cases()}, {t_local, [], t_local_cases()}, {s_misc, [], s_misc_cases()} ]. inet_backend_default_cases() -> [ {group, t_accept}, {group, t_connect}, {group, t_recv}, {group, t_shutdown}, {group, t_misc}, {group, t_local} ]. inet_backend_inet_cases() -> inet_backend_default_cases(). inet_backend_socket_cases() -> inet_backend_default_cases(). t_accept_cases() -> [ t_accept_timeout ]. t_connect_cases() -> [ t_connect_timeout, t_connect_src_port, t_connect_bad ]. t_recv_cases() -> [ t_recv_timeout, t_recv_eof, t_recv_delim ]. t_shutdown_cases() -> [ t_shutdown_write, t_shutdown_both, t_shutdown_error, t_shutdown_async ]. t_misc_cases() -> [ t_fdopen, t_fdconnect, t_implicit_inet6, t_accept_inet6_tclass, {group, sockaddr} ]. sockaddr_cases() -> [ t_simple_local_sockaddr_in_send_recv, t_simple_link_local_sockaddr_in_send_recv, t_simple_local_sockaddr_in6_send_recv, t_simple_link_local_sockaddr_in6_send_recv ]. t_local_cases() -> [ t_local_basic, t_local_unbound, t_local_fdopen, t_local_fdopen_listen, t_local_fdopen_listen_unbound, t_local_fdopen_connect, t_local_fdopen_connect_unbound, t_local_abstract ]. s_misc_cases() -> [ s_accept_with_explicit_socket_backend ]. init_per_suite(Config0) -> ?P("init_per_suite -> entry with" "~n Config: ~p" "~n Nodes: ~p", [Config0, erlang:nodes()]), case ?LIB:init_per_suite(Config0) of {skip, _} = SKIP -> SKIP; Config1 when is_list(Config1) -> ?P("init_per_suite -> end when " "~n Config: ~p", [Config1]), %% We need a monitor on this node also kernel_test_sys_monitor:start(), Config1 end. end_per_suite(Config0) -> ?P("end_per_suite -> entry with" "~n Config: ~p" "~n Nodes: ~p", [Config0, erlang:nodes()]), %% Stop the local monitor kernel_test_sys_monitor:stop(), Config1 = ?LIB:end_per_suite(Config0), ?P("end_per_suite -> " "~n Nodes: ~p", [erlang:nodes()]), Config1. init_per_group(inet_backend_default = _GroupName, Config) -> [{socket_create_opts, []} | Config]; init_per_group(inet_backend_inet = _GroupName, Config) -> case ?EXPLICIT_INET_BACKEND() of true -> The environment us , %% so only the default group should be run! {skip, "explicit inet backend"}; false -> [{socket_create_opts, [{inet_backend, inet}]} | Config] end; init_per_group(inet_backend_socket = _GroupName, Config) -> case ?EXPLICIT_INET_BACKEND() of true -> The environment us , %% so only the default group should be run! {skip, "explicit inet backend"}; false -> [{socket_create_opts, [{inet_backend, socket}]} | Config] end; init_per_group(t_local = _GroupName, Config) -> try gen_tcp:connect({local,<<"/">>}, 0, []) of {error, eafnosupport} -> {skip, "AF_LOCAL not supported"}; {error,_} -> Config catch _C:_E:_S -> {skip, "AF_LOCAL not supported"} end; init_per_group(sockaddr = _GroupName, Config) -> case is_socket_supported() of ok -> Config; {skip, _} = SKIP -> SKIP end; init_per_group(_GroupName, Config) -> Config. end_per_group(t_local, _Config) -> delete_local_filenames(); end_per_group(_, _Config) -> ok. init_per_testcase(Func, Config) when Func =:= undefined -> % Insert your testcase name here dbg:tracer(), dbg:p(self(), c), dbg:tpl(prim_inet, cx), dbg:tpl(local_tcp, cx), dbg:tpl(inet, cx), dbg:tpl(gen_tcp, cx), Config; init_per_testcase(_Func, Config) -> ?P("init_per_testcase -> entry with" "~n Config: ~p" "~n Nodes: ~p" "~n Links: ~p" "~n Monitors: ~p", [Config, erlang:nodes(), pi(links), pi(monitors)]), kernel_test_global_sys_monitor:reset_events(), ?P("init_per_testcase -> done when" "~n Nodes: ~p" "~n Links: ~p" "~n Monitors: ~p", [erlang:nodes(), pi(links), pi(monitors)]), Config. end_per_testcase(Func, _Config) when Func =:= undefined -> % Insert your testcase name here dbg:stop(); end_per_testcase(_Func, Config) -> ?P("end_per_testcase -> entry with" "~n Config: ~p" "~n Nodes: ~p" "~n Links: ~p" "~n Monitors: ~p", [Config, erlang:nodes(), pi(links), pi(monitors)]), ?P("system events during test: " "~n ~p", [kernel_test_global_sys_monitor:events()]), ?P("end_per_testcase -> done with" "~n Nodes: ~p" "~n Links: ~p" "~n Monitors: ~p", [erlang:nodes(), pi(links), pi(monitors)]), ok. %%% gen_tcp:accept/1,2 Test that gen_tcp : ( with timeout ) works . t_accept_timeout(Config) when is_list(Config) -> {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), timeout({gen_tcp, accept, [L, 200]}, 0.2, 1.0). %%% gen_tcp:connect/X Test that gen_tcp : connect/4 ( with timeout ) works . t_connect_timeout(Config) when is_list(Config) -> ?TC_TRY(t_connect_timeout, fun() -> do_connect_timeout(Config) end). do_connect_timeout(Config)-> %%BadAddr = {134,138,177,16}, TcpPort = 80 , {ok, BadAddr} = unused_ip(), TcpPort = 45638, ok = ?P("Connecting to ~p, port ~p", [BadAddr, TcpPort]), connect_timeout({gen_tcp,connect, [BadAddr,TcpPort, ?INET_BACKEND_OPTS(Config),200]}, 0.2, 5.0). %% Test that setting only the source port for a connection works. t_connect_src_port(Config) when is_list(Config) -> Timeout = 1000, Loopback = {127,0,0,1}, %% Allocate a port to later use as source port {ok, Tmp} = gen_tcp:listen(0, [{ip,Loopback}, {linger,{true,0}}]), {ok, SrcPort} = inet:port(Tmp), io:format("SrcPort = ~w~n", [SrcPort]), {ok, L} = gen_tcp:listen(0, [{ip,Loopback}]), ok = gen_tcp:close(Tmp), {ok, DstPort} = inet:port(L), io:format("DstPort = ~w~n", [DstPort]), ConnectOpts = [{port,SrcPort}, {linger,{true,0}}], {ok, C} = gen_tcp:connect(Loopback, DstPort, ConnectOpts, Timeout), {ok, A} = gen_tcp:accept(L, Timeout), {ok, {_, SrcPort}} = inet:peername(A), ok = gen_tcp:close(L), ok = gen_tcp:close(C), ok = gen_tcp:close(A). %% Test that gen_tcp:connect/3 handles non-existings hosts, and other %% invalid things. t_connect_bad(Config) when is_list(Config) -> NonExistingPort = 45638, % Not in use, I hope. {error, Reason1} = gen_tcp:connect(localhost, NonExistingPort, ?INET_BACKEND_OPTS(Config)), io:format("Error for connection attempt to port not in use: ~p", [Reason1]), {error, Reason2} = gen_tcp:connect("non-existing-host-xxx", 7, ?INET_BACKEND_OPTS(Config)), io:format("Error for connection attempt to non-existing host: ~p", [Reason2]), ok. gen_tcp : Test that gen_tcp : ( with timeout works ) . t_recv_timeout(Config) when is_list(Config) -> {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), {ok, Client} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), {ok, _A} = gen_tcp:accept(L), timeout({gen_tcp, recv, [Client, 0, 200]}, 0.2, 5.0). %% Test that end of file on a socket is reported correctly. t_recv_eof(Config) when is_list(Config) -> {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), {ok, Client} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), {ok, A} = gen_tcp:accept(L), ok = gen_tcp:close(A), {error, closed} = gen_tcp:recv(Client, 0), ok. %% Test using message delimiter $X. t_recv_delim(Config) when is_list(Config) -> ?TC_TRY(t_recv_delim, fun() -> do_recv_delim(Config) end). do_recv_delim(Config) -> ?P("init"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), Opts = ?INET_BACKEND_OPTS(Config) ++ [{active,false}, {packet,line}, {line_delimiter,$X}], {ok, Client} = gen_tcp:connect(localhost, Port, Opts), {ok, A} = gen_tcp:accept(L), ?P("send the data"), ok = gen_tcp:send(A, "abcXefgX"), %% Why do we need a timeout? %% Sure, normally there would be no delay, %% but this testcase has nothing to do with timeouts? ?P("read the first chunk"), 200 ) , ?P("read the second chunk"), 200 ) , ?P("set active = 2"), ok = inet:setopts(Client, [{active,2}]), ?P("send the data again"), ok = gen_tcp:send(A, "abcXefgX"), ?P("await the first chunk"), receive {tcp, Client, "abcX"} -> ?P("received first chunk") end, ?P("await the second chunk"), receive {tcp, Client, "efgX"} -> ?P("received second chunk") end, ?P("cleanup"), ok = gen_tcp:close(Client), ok = gen_tcp:close(A), ?P("done"), ok. %%% gen_tcp:shutdown/2 t_shutdown_write(Config) when is_list(Config) -> ?P("create listen socket"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), ?P("create connect socket (C)"), {ok, C} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), ?P("create accept socket (A)"), {ok, A} = gen_tcp:accept(L), ?P("send message A -> C"), ok = gen_tcp:send(A, "Hej Client"), ?P("socket A shutdown(write)"), ok = gen_tcp:shutdown(A, write), ?P("socket C recv - expect message"), {ok, "Hej Client"} = gen_tcp:recv(C, 0), ?P("socket C recv - expect closed"), {error, closed} = gen_tcp:recv(C, 0), ?P("done"), ok. t_shutdown_both(Config) when is_list(Config) -> ?P("create listen socket"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), ?P("create connect socket (C)"), {ok, C} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), ?P("create accept socket (A)"), {ok, A} = gen_tcp:accept(L), ?P("send message A -> C"), ok = gen_tcp:send(A, "Hej Client"), ?P("socket A shutdown(read_write)"), ok = gen_tcp:shutdown(A, read_write), ?P("socket C recv - expect message"), {ok, "Hej Client"} = gen_tcp:recv(C, 0), ?P("socket C recv - expect closed"), {error, closed} = gen_tcp:recv(C, 0), ?P("done"), ok. t_shutdown_error(Config) when is_list(Config) -> ?TC_TRY(t_shutdown_error, fun() -> do_shutdown_error(Config) end). do_shutdown_error(Config) -> ?P("create listen socket"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), ?P("shutdown socket (with How = read_write)"), {error, enotconn} = gen_tcp:shutdown(L, read_write), ?P("close socket"), ok = gen_tcp:close(L), ?P("shutdown socket again (with How = read_write)"), {error, closed} = gen_tcp:shutdown(L, read_write), ?P("done"), ok. t_shutdown_async(Config) when is_list(Config) -> ?TC_TRY(t_shutdown_async, fun() -> do_shutdown_async(Config) end). do_shutdown_async(Config) -> ?P("create listen socket"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config) ++ [{sndbuf, 4096}]), if is_port(L) -> do_shutdown_async2(Config, L); true -> (catch gen_tcp:close(L)), exit({skip, "inet-only testcase"}) end. do_shutdown_async2(Config, L) -> {OS, _} = os:type(), {ok, Port} = inet:port(L), ?P("connect"), {ok, Client} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{recbuf, 4096}, {active, false}]), ?P("accept connection"), {ok, S} = gen_tcp:accept(L), ?P("create payload"), PayloadSize = 1024 * 1024, Payload = lists:duplicate(PayloadSize, $.), ?P("send payload"), ok = gen_tcp:send(S, Payload), ?P("verify queue size"), case erlang:port_info(S, queue_size) of {queue_size, N} when N > 0 -> ok; {queue_size, 0} when OS =:= win32 -> ok; {queue_size, 0} = T -> ct:fail({unexpected, T}) end, ?P("shutdown(write) accepted socket"), ok = gen_tcp:shutdown(S, write), ?P("recv from connected socket"), {ok, Buf} = gen_tcp:recv(Client, PayloadSize), ?P("recv(0) from connected socket (expect closed)"), {error, closed} = gen_tcp:recv(Client, 0), ?P("verify recv data"), case length(Buf) of PayloadSize -> ?P("done"), ok; Sz -> ?P("ERROR: " "~n extected: ~p" "~n received: ~p", [PayloadSize, Sz]), ct:fail({payload_size, {expected, PayloadSize}, {received, Sz}}) end. %%% gen_tcp:fdopen/2 t_fdopen(Config) when is_list(Config) -> Question = "Aaaa... Long time ago in a small town in Germany,", Question1 = list_to_binary(Question), Question2 = [<<"Aaaa">>, "... ", $L, <<>>, $o, "ng time ago ", ["in ", [], <<"a small town">>, [" in Germany,", <<>>]]], Question1 = iolist_to_binary(Question2), Answer = "there was a shoemaker, Schumacher was his name.", {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), {ok, Port} = inet:port(L), {ok, Client} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), {A, FD} = case gen_tcp:accept(L) of {ok, ASock} when is_port(ASock) -> {ok, FileDesc} = prim_inet:getfd(ASock), {ASock, FileDesc}; {ok, ASock} -> % socket {ok, [{fd, FileDesc}]} = gen_tcp_socket:getopts(ASock, [fd]), {ASock, FileDesc} end, ?P("fdopen -> accepted: " "~n A: ~p" "~n FD: ~p", [A, FD]), {ok, Server} = gen_tcp:fdopen(FD, ?INET_BACKEND_OPTS(Config)), ok = gen_tcp:send(Client, Question), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Client, Question1), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Client, Question2), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Server, Answer), {ok, Answer} = gen_tcp:recv(Client, length(Answer), 2000), ok = gen_tcp:close(Client), {error, closed} = gen_tcp:recv(A, 1, 2000), ok = gen_tcp:close(Server), ok = gen_tcp:close(A), ok = gen_tcp:close(L), ok. t_fdconnect(Config) when is_list(Config) -> Cond = fun() -> ?P("Try verify if IPv4 is supported"), ?HAS_SUPPORT_IPV4() end, Pre = fun() -> {ok, Addr} = ?WHICH_LOCAL_ADDR(inet), ?P("Use (local) address: ~p", [Addr]), #{local_addr => Addr} end, Case = fun(#{local_addr := Addr}) -> do_t_fdconnect(Addr, Config) end, Post = fun(_) -> ok end, ?TC_TRY(?FUNCTION_NAME, Cond, Pre, Case, Post). do_t_fdconnect(Addr, Config) -> Question = "Aaaa... Long time ago in a small town in Germany,", Question1 = list_to_binary(Question), Question2 = [<<"Aaaa">>, "... ", $L, <<>>, $o, "ng time ago ", ["in ", [], <<"a small town">>, [" in Germany,", <<>>]]], Question1 = iolist_to_binary(Question2), Answer = "there was a shoemaker, Schumacher was his name.", Path = proplists:get_value(data_dir, Config), Lib = "gen_tcp_api_SUITE", ?P("try load util nif lib"), case erlang:load_nif(filename:join(Path, Lib), []) of ok -> ok; {error, {reload, ReasonStr}} -> ?P("already loaded: " "~n ~s", [ReasonStr]), ok; {error, Reason} -> ?P("UNEXPECTED - failed loading util nif lib: " "~n ~p", [Reason]), ?SKIPT("failed loading util nif lib") end, ?P("try create listen socket"), LOpts = ?INET_BACKEND_OPTS(Config) ++ [{ifaddr, Addr}, {active, false}], L = try gen_tcp:listen(0, LOpts) of {ok, LSock} -> LSock; {error, eaddrnotavail = LReason} -> ?SKIPT(listen_failed_str(LReason)); {error, LReason} -> ?P("UNEXPECTED ERROR - listen error: " "~n COpts: ~p" "~n Reason: ~p", [LReason]), ct:fail({unexpected_listen_error, LReason, LOpts}) catch LC : LE : LS -> ?P("UNEXPECTED ERROR - caught listen: " "~n LOpts: ~p" "~n C: ~p" "~n E: ~p" "~n S: ~p", [LOpts, LC, LE, LS]), ct:fail({listen_failure, {LC, LE, LS}, LOpts}) end, {ok, LPort} = inet:port(L), ?P("try create file descriptor"), FD = gen_tcp_api_SUITE:getsockfd(), ?P("try connect (to port ~w) using file descriptor ~w", [LPort, FD]), COpts = ?INET_BACKEND_OPTS(Config) ++ [{fd, FD}, {ifaddr, Addr}, {active, false}], %% The debug is just to "see" that it (debug) "works"... Client = try gen_tcp:connect(Addr, LPort, COpts ++ [{debug, true}]) of {ok, CSock} -> ok = inet:setopts(CSock, [{debug, false}]), CSock; {error, eaddrnotavail = CReason} -> gen_tcp:close(L), gen_tcp_api_SUITE:closesockfd(FD), ?SKIPT(connect_failed_str(CReason)); {error, CReason} -> ?P("UNEXPECTED ERROR - connect error: " "~n COpts: ~p" "~n Reason: ~p", [COpts, CReason]), ct:fail({unexpected_connect_error, CReason, COpts}) catch CC : CE : CS -> ?P("UNEXPECTED ERROR - caught connect: " "~n COpts: ~p" "~n C: ~p" "~n E: ~p" "~n S: ~p", [COpts, CC, CE, CS]), ct:fail({connect_failure, {CC, CE, CS}, COpts}) end, ?P("try accept connection"), Server = try gen_tcp:accept(L) of {ok, ASock} -> ASock; {error, eaddrnotavail = AReason} -> gen_tcp:close(Client), gen_tcp:close(L), gen_tcp_api_SUITE:closesockfd(FD), ?SKIPT(accept_failed_str(AReason)); {error, AReason} -> ?P("UNEXPECTED ERROR - accept error: " "~n Reason: ~p", [AReason]), ct:fail({unexpected_accept_error, AReason}) catch AC : AE : AS -> ?P("UNEXPECTED ERROR - caught accept: " "~n C: ~p" "~n E: ~p" "~n S: ~p", [AC, AE, AS]), ct:fail({accept_failure, {AC, AE, AS}}) end, ?P("begin validation"), ok = gen_tcp:send(Client, Question), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Client, Question1), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Client, Question2), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Server, Answer), {ok, Answer} = gen_tcp:recv(Client, length(Answer), 2000), ?P("cleanup"), ok = gen_tcp:close(Client), FD = gen_tcp_api_SUITE:closesockfd(FD), {error, closed} = gen_tcp:recv(Server, 1, 2000), ok = gen_tcp:close(Server), ok = gen_tcp:close(L), ?P("done"), ok. implicit option to api functions t_implicit_inet6(Config) when is_list(Config) -> ?TC_TRY(t_implicit_inet6, fun() -> do_t_implicit_inet6(Config) end). do_t_implicit_inet6(Config) -> ?P("try get hostname"), Host = ok(inet:gethostname()), ?P("try get address for host ~p", [Host]), case inet:getaddr(Host, inet6) of {ok, Addr} -> ?P("address: ~p", [Addr]), t_implicit_inet6(Config, Host, Addr); {error, Reason} -> {skip, "Can not look up IPv6 address: " ++atom_to_list(Reason)} end. t_implicit_inet6(Config, Host, Addr) -> Loopback = {0,0,0,0,0,0,0,1}, InetBackendOpts = ?INET_BACKEND_OPTS(Config), case gen_tcp:listen(0, InetBackendOpts ++ [inet6, {ip,Loopback}]) of {ok, S1} -> ?P("try ~s ~p", ["::1", Loopback]), implicit_inet6(Config, S1, Loopback), ok = gen_tcp:close(S1), %% LocalAddr = ok(get_localaddr()), S2 = case gen_tcp:listen(0, InetBackendOpts ++ [{ip, LocalAddr}]) of {ok, LSock2} -> LSock2; {error, Reason2} -> ?P("Listen failed (ip):" "~n Reason2: ~p", [Reason2]), ?SKIPT(listen_failed_str(Reason2)) end, implicit_inet6(Config, S2, LocalAddr), ok = gen_tcp:close(S2), %% ?P("try ~s ~p", [Host, Addr]), S3 = case gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,Addr}]) of {ok, LSock3} -> LSock3; {error, Reason3} -> ?P("Listen failed (ifaddr):" "~n Reason3: ~p", [Reason3]), ?SKIPT(listen_failed_str(Reason3)) end, implicit_inet6(Config, S3, Addr), ok = gen_tcp:close(S3), ?P("done"), ok; {error, Reason1} -> ?SKIPT(listen_failed_str(Reason1)) end. implicit_inet6(Config, S, Addr) -> P = ok(inet:port(S)), S2 = case gen_tcp:connect(Addr, P, ?INET_BACKEND_OPTS(Config)) of {ok, CSock} -> CSock; {error, CReason} -> ?SKIPT(connect_failed_str(CReason)) end, P2 = ok(inet:port(S2)), S1 = case gen_tcp:accept(S) of {ok, ASock} -> ASock; {error, AReason} -> ?SKIPT(accept_failed_str(AReason)) end, P1 = P = ok(inet:port(S1)), {Addr,P2} = ok(inet:peername(S1)), {Addr,P1} = ok(inet:peername(S2)), {Addr,P1} = ok(inet:sockname(S1)), {Addr,P2} = ok(inet:sockname(S2)), ok = gen_tcp:close(S2), ok = gen_tcp:close(S1). t_local_basic(Config) -> SFile = local_filename(server), SAddr = {local, bin_filename(SFile)}, CFile = local_filename(client), CAddr = {local,bin_filename(CFile)}, _ = file:delete(SFile), _ = file:delete(CFile), %% ?P("try create listen socket"), InetBackendOpts = ?INET_BACKEND_OPTS(Config), L = ok( gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,{local,SFile}},{active,false}])), ?P("try connect"), C = ok( gen_tcp:connect( {local,SFile}, 0, InetBackendOpts ++ [{ifaddr,{local,CFile}},{active,false}])), ?P("try accept connection"), S = ok(gen_tcp:accept(L)), ?P("try get sockname for listen socket"), %% SAddr = ok(inet:sockname(L)), case inet:sockname(L) of {ok, SAddr} -> ok; {ok, SAddr2} -> ?P("Invalid sockname: " "~n Expected: ~p" "~n Actual: ~p", [SAddr, SAddr2]), exit({sockename, SAddr, SAddr2}); {error, Reason} -> exit({sockname, Reason}) end, ?P("try get peername for listen socket"), {error, enotconn} = inet:peername(L), ?P("try handshake"), local_handshake(S, SAddr, C, CAddr), ?P("try close listen socket"), ok = gen_tcp:close(L), ?P("try close accept socket"), ok = gen_tcp:close(S), ?P("try close connect socket"), ok = gen_tcp:close(C), %% ?P("try 'local' files"), ok = file:delete(SFile), ok = file:delete(CFile), ?P("done"), ok. t_local_unbound(Config) -> ?TC_TRY(t_local_unbound, fun() -> do_local_unbound(Config) end). do_local_unbound(Config) -> ?P("create local (server) filename"), SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), %% InetBackendOpts = ?INET_BACKEND_OPTS(Config), ?P("create listen socket with ifaddr ~p", [SAddr]), L = ok(gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,SAddr},{active,false}])), ?P("listen socket created: ~p" "~n => try connect", [L]), C = ok(gen_tcp:connect(SAddr, 0, InetBackendOpts ++ [{active,false}])), ?P("connected: ~p" "~n => try accept", [C]), S = ok(gen_tcp:accept(L)), ?P("accepted: ~p" "~n => sockname", [S]), SAddr = ok(inet:sockname(L)), ?P("sockname: ~p" "~n => peername (expect enotconn)", [SAddr]), {error, enotconn} = inet:peername(L), ?P("try local handshake"), local_handshake(S, SAddr, C, {local,<<>>}), ?P("close listen socket"), ok = gen_tcp:close(L), ?P("close accepted socket"), ok = gen_tcp:close(S), ?P("close connected socket"), ok = gen_tcp:close(C), ?P("delete (local) file"), ok = file:delete(SFile), ?P("done"), ok. t_local_fdopen(Config) -> ?TC_TRY(t_local_fdopen, fun() -> do_local_fdopen(Config) end). do_local_fdopen(Config) -> ?P("create local (server) filename"), SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), %% InetBackendOpts = ?INET_BACKEND_OPTS(Config), ListenOpts = InetBackendOpts ++ [{ifaddr,SAddr},{active,false}], ?P("create listen socket with ListenOpts ~p", [ListenOpts]), L = ok(gen_tcp:listen(0, ListenOpts)), ConnectOpts = InetBackendOpts ++ [{active,false}], ?P("listen socket created: ~p" "~n => try connect ~p", [L, ConnectOpts]), C0 = ok(gen_tcp:connect(SAddr, 0, ConnectOpts)), ok = inet:setopts(C0, [{debug, true}]), ?P("connected: ~p" "~n => get fd", [C0]), Fd = if is_port(C0) -> FD0 = ok(prim_inet:getfd(C0)), ?P("FD: ~p" "~n => ignore fd", [FD0]), %% Turn off C0, so it does not generate any events! ok = prim_inet:ignorefd(C0, true), FD0; true -> [{fd, FD0}] = ok(inet:getopts(C0, [fd])), ?P("FD: ~p", [FD0]), FD0 end, ?P("ignored fd:" "~n => try fdopen (local)"), C = ok(gen_tcp:fdopen(Fd, ?INET_BACKEND_OPTS(Config) ++ [local])), ?P("fd open: ~p" "~n => try accept", [C]), S = ok(gen_tcp:accept(L)), ?P("accepted: ~p" "~n => get sockname", [S]), SAddr = ok(inet:sockname(L)), ?P("sockname: ~p" "~n => try get peername (expect enotconn)", [SAddr]), {error,enotconn} = inet:peername(L), ?P("try local handshake"), local_handshake(S, SAddr, C, {local,<<>>}), ?P("close listen socket"), ok = gen_tcp:close(L), ?P("close accepted socket"), ok = gen_tcp:close(S), ?P("close connected socket (final)"), ok = gen_tcp:close(C), ?P("close connected socket (pre)"), ok = gen_tcp:close(C0), ?P("delete (local) file"), ok = file:delete(SFile), ?P("done"), ok. t_local_fdopen_listen(Config) -> ?TC_TRY(t_local_fdopen_listen, fun() -> do_local_fdopen_listen(Config) end). do_local_fdopen_listen(Config) -> ?P("create local (server) filename"), SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), InetBackendOpts = ?INET_BACKEND_OPTS(Config), ?P("create dummy listen socket with ifaddr ~p", [SAddr]), L0 = ok(gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,SAddr},{active,false}])), ?P("dummy listen socket created: ~p" "~n => try get FD", [L0]), Fd = if is_port(L0) -> ok(prim_inet:getfd(L0)); true -> [{fd, FD0}] = ok(inet:getopts(L0, [fd])), FD0 end, ?P("FD: ~p" "~n => try create proper listen socket (using fd)", [Fd]), L = ok(gen_tcp:listen(0, InetBackendOpts ++ [{fd,Fd},local,{active,false}])), ?P("try connect"), C = ok(gen_tcp:connect(SAddr, 0, InetBackendOpts ++ [{active,false}])), ?P("try accept (connection)"), S = ok(gen_tcp:accept(L)), ?P("verify (proper) listen socket sockname"), SAddr = ok(inet:sockname(L)), ?P("verify (proper) listen socket peername (expect enotconn)"), {error, enotconn} = inet:peername(L), ?P("perform handshake"), local_handshake(S, SAddr, C, {local,<<>>}), ?P("close (proper) listen socket"), ok = gen_tcp:close(L), ?P("close (dummy) listen socket"), ok = gen_tcp:close(L0), ?P("close accepted socket"), ok = gen_tcp:close(S), ?P("close connected socket"), ok = gen_tcp:close(C), ?P("delete file (used for socket)"), ok = file:delete(SFile), ?P("done"), ok. t_local_fdopen_listen_unbound(Config) -> SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), P = ok(prim_inet:open(tcp, local, stream)), Fd = ok(prim_inet:getfd(P)), InetBackendOpts = ?INET_BACKEND_OPTS(Config), L = ok(gen_tcp:listen( 0, InetBackendOpts ++ [{fd,Fd},{ifaddr,SAddr},{active,false}])), C = ok(gen_tcp:connect(SAddr, 0, InetBackendOpts ++ [{active,false}])), S = ok(gen_tcp:accept(L)), SAddr = ok(inet:sockname(L)), {error,enotconn} = inet:peername(L), local_handshake(S, SAddr, C, {local,<<>>}), ok = gen_tcp:close(L), ok = gen_tcp:close(P), ok = gen_tcp:close(S), ok = gen_tcp:close(C), ok = file:delete(SFile), ok. t_local_fdopen_connect(Config) -> SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, CFile = local_filename(client), CAddr = {local,bin_filename(CFile)}, _ = file:delete(SFile), _ = file:delete(CFile), InetBackendOpts = ?INET_BACKEND_OPTS(Config), L = ok(gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,SAddr},{active,false}])), P = ok(prim_inet:open(tcp, local, stream)), Fd = ok(prim_inet:getfd(P)), C = ok(gen_tcp:connect( SAddr, 0, InetBackendOpts ++ [{fd,Fd},{ifaddr,CAddr},{active,false}])), S = ok(gen_tcp:accept(L)), SAddr = ok(inet:sockname(L)), {error,enotconn} = inet:peername(L), local_handshake(S, SAddr, C, CAddr), ok = gen_tcp:close(L), ok = gen_tcp:close(S), ok = gen_tcp:close(C), ok = gen_tcp:close(P), ok = file:delete(SFile), ok. t_local_fdopen_connect_unbound(Config) -> SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), InetBackendOpts = ?INET_BACKEND_OPTS(Config), L = ok(gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,SAddr},{active,false}])), P = ok(prim_inet:open(tcp, local, stream)), Fd = ok(prim_inet:getfd(P)), C = ok(gen_tcp:connect(SAddr, 0, InetBackendOpts ++ [{fd,Fd},{active,false}])), S = ok(gen_tcp:accept(L)), SAddr = ok(inet:sockname(L)), {error,enotconn} = inet:peername(L), local_handshake(S, SAddr, C, {local,<<>>}), ok = gen_tcp:close(L), ok = gen_tcp:close(S), ok = gen_tcp:close(C), ok = gen_tcp:close(P), ok = file:delete(SFile), ok. t_local_abstract(Config) -> ?TC_TRY(t_local_abstract, fun() -> do_local_abstract(Config) end). do_local_abstract(Config) -> ?P("only run on linux"), case os:type() of {unix, linux} -> AbstAddr = {local,<<>>}, InetBackendOpts = ?INET_BACKEND_OPTS(Config), ?P("create listen socket"), L = ok(gen_tcp:listen( 0, InetBackendOpts ++ [{ifaddr,AbstAddr},{active,false}])), ?P("listen socket created: ~p" "~n => sockname", [L]), {local, _} = SAddr = ok(inet:sockname(L)), ?P("(listen socket) sockname verified" "~n => try connect"), C = ok(gen_tcp:connect( SAddr, 0, InetBackendOpts ++ [{ifaddr,AbstAddr},{active,false}])), ?P("connected: ~p" "~n => sockname", [C]), {local,_} = CAddr = ok(inet:sockname(C)), ?P("(connected socket) sockname verified" "~n => try accept"), S = ok(gen_tcp:accept(L)), ?P("accepted: ~p" "~n => peername (expect enotconn)", [S]), {error,enotconn} = inet:peername(L), ?P("try local handshake"), local_handshake(S, SAddr, C, CAddr), ?P("close listen socket"), ok = gen_tcp:close(L), ?P("close accepted socket"), ok = gen_tcp:close(S), ?P("close connected socket"), ok = gen_tcp:close(C), ?P("done"), ok; _ -> ?P("skip (unless linux)"), {skip,"AF_LOCAL Abstract Addresses only supported on Linux"} end. local_handshake(S, SAddr, C, CAddr) -> ?P("~w(~p, ~p, ~p, ~p)~n", [?FUNCTION_NAME, S, SAddr, C, CAddr]), SData = "9876543210", CData = "0123456789", SAddr = ok(inet:sockname(S)), CAddr = ok(inet:sockname(C)), CAddr = ok(inet:peername(S)), SAddr = ok(inet:peername(C)), ok = gen_tcp:send(C, CData), ok = gen_tcp:send(S, SData), CData = ok(gen_tcp:recv(S, length(CData))), SData = ok(gen_tcp:recv(C, length(SData))), ok. t_accept_inet6_tclass(Config) when is_list(Config) -> ?TC_TRY(t_accept_inet6_tclass, fun() -> do_accept_inet6_tclass(Config) end). do_accept_inet6_tclass(Config) -> TClassOpt = {tclass, 8#56 bsl 2}, % Expedited forwarding Loopback = {0,0,0,0,0,0,0,1}, ?P("create listen socket with tclass: ~p", [TClassOpt]), case gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config) ++ [inet6, {ip, Loopback}, TClassOpt]) of {ok, L} -> ?P("listen socket created: " "~n ~p", [L]), LPort = ok(inet:port(L)), ?P("try to connect to port ~p", [LPort]), Sa = ok(gen_tcp:connect(Loopback, LPort, ?INET_BACKEND_OPTS(Config))), ?P("connected: ~p" "~n => accept connection", [Sa]), Sb = ok(gen_tcp:accept(L)), ?P("accepted: ~p" "~n => getopts (tclass)", [Sb]), [TClassOpt] = ok(inet:getopts(Sb, [tclass])), ?P("tclass verified => close accepted socket"), ok = gen_tcp:close(Sb), ?P("close connected socket"), ok = gen_tcp:close(Sa), ?P("close listen socket"), ok = gen_tcp:close(L), ?P("done"), ok; {error, _Reason} -> ?P("ERROR: Failed create listen socket" "~n ~p", [_Reason]), {skip,"IPv6 TCLASS not supported"} end. %% Here we use socket:sockaddr_in6() when creating and using the %% socket(s). %% t_simple_local_sockaddr_in6_send_recv(Config) when is_list(Config) -> ?TC_TRY(?FUNCTION_NAME, fun() -> ?LIB:has_support_ipv6() end, fun() -> Domain = inet6, {ok, LocalAddr} = ?LIB:which_local_addr(Domain), SockAddr = #{family => Domain, addr => LocalAddr, port => 0}, do_simple_sockaddr_send_recv(SockAddr, Config) end). t_simple_link_local_sockaddr_in6_send_recv(Config) when is_list(Config) -> ?TC_TRY(?FUNCTION_NAME, fun() -> ?LIB:has_support_ipv6(), is_net_supported() end, fun() -> Domain = inet6, LinkLocalAddr = case ?LIB:which_link_local_addr(Domain) of {ok, LLA} -> LLA; {error, _} -> skip("No link local address") end, Filter = fun(#{addr := #{family := D, addr := A}}) -> (D =:= Domain) andalso (A =:= LinkLocalAddr); (_) -> false end, case net:getifaddrs(Filter) of {ok, [#{addr := #{scope_id := ScopeID}}|_]} -> SockAddr = #{family => Domain, addr => LinkLocalAddr, port => 0, scope_id => ScopeID}, do_simple_sockaddr_send_recv(SockAddr, Config); {ok, _} -> skip("Scope ID not found"); {error, R} -> skip({failed_getifaddrs, R}) end end). %% Here we use socket:sockaddr_in() when creating and using the %% socket(s). %% t_simple_local_sockaddr_in_send_recv(Config) when is_list(Config) -> ?TC_TRY(?FUNCTION_NAME, fun() -> ok end, fun() -> Domain = inet, {ok, LocalAddr} = ?LIB:which_local_addr(Domain), SockAddr = #{family => Domain, addr => LocalAddr, port => 0}, do_simple_sockaddr_send_recv(SockAddr, Config) end). t_simple_link_local_sockaddr_in_send_recv(Config) when is_list(Config) -> ?TC_TRY(?FUNCTION_NAME, fun() -> ok end, fun() -> Domain = inet, LinkLocalAddr = case ?LIB:which_link_local_addr(Domain) of {ok, LLA} -> LLA; {error, _} -> skip("No link local address") end, SockAddr = #{family => Domain, addr => LinkLocalAddr, port => 0}, do_simple_sockaddr_send_recv(SockAddr, Config) end). do_simple_sockaddr_send_recv(SockAddr, _) -> %% Create the server Self = self(), ?P("~n SockAddr: ~p", [SockAddr]), ServerF = fun() -> ?P("try create listen socket"), LSock = try gen_tcp:listen(0, [{ifaddr, SockAddr}, {active, true}, binary]) of {ok, LS} -> LS; {error, LReason} -> ?P("listen error: " "~n Reason: ~p", [LReason]), exit({listen_error, LReason}) catch LC:LE:LS -> ?P("listen failure: " "~n Error Class: ~p" "~n Error: ~p" "~n Call Stack: ~p", [LC, LE, LS]), exit({listen_failure, {LC, LE, LS}}) end, ?P("try get listen port"), {ok, Port} = inet:port(LSock), ?P("listen port: ~w", [Port]), Self ! {{port, Port}, self()}, ?P("try accept"), {ok, ASock} = gen_tcp:accept(LSock), ?P("accepted: " "~n ~p", [ASock]), receive {tcp, ASock, <<"hej">>} -> ?P("received expected message - send reply"), ok = gen_tcp:send(ASock, "hopp") end, ?P("await termination command"), receive {die, Self} -> ?P("terminating"), (catch gen_tcp:close(ASock)), (catch gen_tcp:close(LSock)), exit(normal) end end, ?P("try start server"), Server = spawn_link(ServerF), ?P("server started - await port "), ServerPort = receive {{port, Port}, Server} -> Port; {'EXIT', Server, Reason} -> ?P("server died unexpectedly: " "~n ~p", [Reason]), exit({unexpected_listen_failure, Reason}) end, ?P("server port received: ~p", [ServerPort]), ?P("try connect to server"), ServerSockAddr = SockAddr#{port => ServerPort}, {ok, CSock} = gen_tcp:connect(ServerSockAddr, [{ifaddr, SockAddr}, {active, true}, binary]), ?P("connected to server: " "~n CSock: ~p" "~n CPort: ~p", [CSock, inet:port(CSock)]), ?P("try send message"), ok = gen_tcp:send(CSock, "hej"), ?P("await reply message"), receive {tcp, CSock, <<"hopp">>} -> ?P("received expected reply message") end, ?P("terminate server"), Server ! {die, self()}, ?P("await server termination"), receive {'EXIT', Server, normal} -> ok end, ?P("cleanup"), (catch gen_tcp:close(CSock)), ?P("done"), ok. %% On MacOS (maybe more), accepting a connection resulted in a crash. %% Note that since 'socket' currently does not work on windows %% we have to skip on that platform. s_accept_with_explicit_socket_backend(Config) when is_list(Config) -> ?TC_TRY(s_accept_with_explicit_socket_backend, fun() -> is_socket_supported() end, fun() -> do_s_accept_with_explicit_socket_backend() end). do_s_accept_with_explicit_socket_backend() -> ?P("try create listen socket"), {ok, S} = gen_tcp:listen(0, [{inet_backend, socket}]), ?P("try get port number (via sockname)"), {ok, {_, Port}} = inet:sockname(S), ClientF = fun() -> ?P("[client] try connect (tp ~p)", [Port]), {ok, _} = gen_tcp:connect("localhost", Port, []), ?P("[client] connected - wait for termination command"), receive die -> ?P("[client] termination command received"), exit(normal) after infinity -> ok end end, ?P("create client"), Client = spawn_link(ClientF), ?P("try accept"), {ok, _} = gen_tcp:accept(S), ?P("accepted - command client to terminate"), Client ! die, ?P("done"), ok. Utilities is_socket_supported() -> try socket:info() of _ -> ok catch error : notsup -> {skip, "esock not supported"}; error : undef -> {skip, "esock not configured"} end. Calls M : F / length(A ) , which should return a timeout error , and complete %% within the given time. timeout({M,F,A}, Lower, Upper) -> case test_server:timecall(M, F, A) of {Time, Result} when Time < Lower -> ct:fail({too_short_time, Time, Result}); {Time, Result} when Time > Upper -> ct:fail({too_long_time, Time, Result}); {_, {error, timeout}} -> ok; {_, Result} -> ct:fail({unexpected_result, Result}) end. connect_timeout({M,F,A}, Lower, Upper) -> case test_server:timecall(M, F, A) of {Time, Result} when Time < Lower -> case Result of {error, econnrefused = E} -> {skip, "Not tested -- got error " ++ atom_to_list(E)}; {error, enetunreach = E} -> {skip, "Not tested -- got error " ++ atom_to_list(E)}; {error, ehostunreach = E} -> {skip, "Not tested -- got error " ++ atom_to_list(E)}; {ok, Socket} -> % What the... Pinfo = erlang:port_info(Socket), Db = inet_db:lookup_socket(Socket), Peer = inet:peername(Socket), ct:fail({too_short_time, Time, [Result,Pinfo,Db,Peer]}); _ -> ct:fail({too_short_time, Time, Result}) end; {Time, Result} when Time > Upper -> ct:fail({too_long_time, Time, Result}); {_, {error, timeout}} -> ok; {_, Result} -> ct:fail({unexpected_result, Result}) end. %% Try to obtain an unused IP address in the local network. unused_ip() -> {ok, Host} = inet:gethostname(), {ok, Hent} = inet:gethostbyname(Host), #hostent{h_addr_list=[{A, B, C, _D}|_]} = Hent, Note : In our net , addresses below 16 are reserved for routers and %% other strange creatures. IP = unused_ip(A, B, C, 16), if (IP =:= error) -> %% This is not supported on all platforms (yet), so... try net:getifaddrs() of {ok, IfAddrs} -> ?P("~n we = ~p" "~n unused_ip = ~p" "~n ~p", [Hent, IP, IfAddrs]); {error, _} -> ?P("~n we: ~p" "~n unused_ip: ~p", [Hent, IP]) catch _:_:_ -> ?P("~n we: ~p" "~n unused_ip: ~p", [Hent, IP]) end; true -> ?P("~n we: ~p" "~n unused_ip: ~p", [Hent, IP]) end, IP. unused_ip(255, 255, 255, 255) -> error; unused_ip(255, B, C, D) -> unused_ip(1, B + 1, C, D); unused_ip(A, 255, C, D) -> unused_ip(A, 1, C + 1, D); unused_ip(A, B, 255, D) -> unused_ip(A, B, 1, D + 1); unused_ip(A, B, C, D) -> case inet:gethostbyaddr({A, B, C, D}) of {ok, _} -> unused_ip(A + 1, B, C, D); {error, _} -> {ok, {A, B, C, D}} end. ok({ok,V}) -> V; ok(NotOk) -> try throw(not_ok) catch throw:Thrown:Stacktrace -> erlang:raise( error, {Thrown, NotOk}, tl(Stacktrace)) end. get_localaddr() -> get_localaddr(["localhost", "localhost6", "ip6-localhost"]). get_localaddr([]) -> {error, localaddr_not_found}; get_localaddr([Localhost|Ls]) -> case inet:getaddr(Localhost, inet6) of {ok, LocalAddr} -> ?P("~s ~p", [Localhost, LocalAddr]), {ok, LocalAddr}; _ -> get_localaddr(Ls) end. getsockfd() -> undefined. closesockfd(_FD) -> undefined. local_filename(Tag) -> "/tmp/" ?MODULE_STRING "_" ++ os:getpid() ++ "_" ++ atom_to_list(Tag). bin_filename(String) -> unicode:characters_to_binary(String, file:native_name_encoding()). delete_local_filenames() -> _ = [file:delete(F) || F <- filelib:wildcard( "/tmp/" ?MODULE_STRING "_" ++ os:getpid() ++ "_*")], ok. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% is_net_supported() -> try net:info() of #{} -> ok catch error : notsup -> not_supported(net) end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% not_supported(What) -> skip({not_supported, What}). skip(Reason) -> throw({skip, Reason}). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% pi(Item) -> {Item, Val} = process_info(self(), Item), Val. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% connect_failed_str(Reason) -> ?F("Connect failed: ~w", [Reason]). listen_failed_str(Reason) -> ?F("Listen failed: ~w", [Reason]). accept_failed_str(Reason) -> ?F("Accept failed: ~w", [Reason]).
null
https://raw.githubusercontent.com/erlang/otp/12283bef143829a53593484eb28b87c1df57cef9/lib/kernel/test/gen_tcp_api_SUITE.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% are not tested here, because they are tested indirectly in this and and other test suites. This is a temporary measure to ensure that we can test the socket backend without effecting *all* applications on *all* machines. We need a monitor on this node also Stop the local monitor so only the default group should be run! so only the default group should be run! Insert your testcase name here Insert your testcase name here gen_tcp:accept/1,2 gen_tcp:connect/X BadAddr = {134,138,177,16}, Test that setting only the source port for a connection works. Allocate a port to later use as source port Test that gen_tcp:connect/3 handles non-existings hosts, and other invalid things. Not in use, I hope. Test that end of file on a socket is reported correctly. Test using message delimiter $X. Why do we need a timeout? Sure, normally there would be no delay, but this testcase has nothing to do with timeouts? gen_tcp:shutdown/2 gen_tcp:fdopen/2 socket The debug is just to "see" that it (debug) "works"... SAddr = ok(inet:sockname(L)), Turn off C0, so it does not generate any events! Expedited forwarding Here we use socket:sockaddr_in6() when creating and using the socket(s). Here we use socket:sockaddr_in() when creating and using the socket(s). Create the server On MacOS (maybe more), accepting a connection resulted in a crash. Note that since 'socket' currently does not work on windows we have to skip on that platform. within the given time. What the... Try to obtain an unused IP address in the local network. other strange creatures. This is not supported on all platforms (yet), so...
Copyright Ericsson AB 1998 - 2022 . 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(gen_tcp_api_SUITE). Tests the documented API for the gen_tcp functions . The " normal " cases -include_lib("common_test/include/ct.hrl"). -include_lib("kernel/include/inet.hrl"). -include("kernel_test_lib.hrl"). -export([ all/0, suite/0, groups/0, init_per_suite/1, end_per_suite/1, init_per_group/2, end_per_group/2, init_per_testcase/2, end_per_testcase/2, t_connect_timeout/1, t_accept_timeout/1, t_connect_src_port/1, t_connect_bad/1, t_recv_timeout/1, t_recv_eof/1, t_recv_delim/1, t_shutdown_write/1, t_shutdown_both/1, t_shutdown_error/1, t_shutdown_async/1, t_fdopen/1, t_fdconnect/1, t_implicit_inet6/1, t_local_basic/1, t_local_unbound/1, t_local_fdopen/1, t_local_fdopen_listen/1, t_local_fdopen_listen_unbound/1, t_local_fdopen_connect/1, t_local_fdopen_connect_unbound/1, t_local_abstract/1, t_accept_inet6_tclass/1, s_accept_with_explicit_socket_backend/1, t_simple_local_sockaddr_in_send_recv/1, t_simple_link_local_sockaddr_in_send_recv/1, t_simple_local_sockaddr_in6_send_recv/1, t_simple_link_local_sockaddr_in6_send_recv/1 ]). -export([getsockfd/0, closesockfd/1]). suite() -> [ {ct_hooks,[ts_install_cth]}, {timetrap,{minutes,1}} ]. all() -> This flag is set only for * one * host . case ?TEST_INET_BACKENDS() of true -> [ {group, inet_backend_default}, {group, inet_backend_inet}, {group, inet_backend_socket}, {group, s_misc} ]; _ -> [ {group, inet_backend_default}, {group, s_misc} ] end. groups() -> [ {inet_backend_default, [], inet_backend_default_cases()}, {inet_backend_inet, [], inet_backend_inet_cases()}, {inet_backend_socket, [], inet_backend_socket_cases()}, {t_accept, [], t_accept_cases()}, {t_connect, [], t_connect_cases()}, {t_recv, [], t_recv_cases()}, {t_shutdown, [], t_shutdown_cases()}, {t_misc, [], t_misc_cases()}, {sockaddr, [], sockaddr_cases()}, {t_local, [], t_local_cases()}, {s_misc, [], s_misc_cases()} ]. inet_backend_default_cases() -> [ {group, t_accept}, {group, t_connect}, {group, t_recv}, {group, t_shutdown}, {group, t_misc}, {group, t_local} ]. inet_backend_inet_cases() -> inet_backend_default_cases(). inet_backend_socket_cases() -> inet_backend_default_cases(). t_accept_cases() -> [ t_accept_timeout ]. t_connect_cases() -> [ t_connect_timeout, t_connect_src_port, t_connect_bad ]. t_recv_cases() -> [ t_recv_timeout, t_recv_eof, t_recv_delim ]. t_shutdown_cases() -> [ t_shutdown_write, t_shutdown_both, t_shutdown_error, t_shutdown_async ]. t_misc_cases() -> [ t_fdopen, t_fdconnect, t_implicit_inet6, t_accept_inet6_tclass, {group, sockaddr} ]. sockaddr_cases() -> [ t_simple_local_sockaddr_in_send_recv, t_simple_link_local_sockaddr_in_send_recv, t_simple_local_sockaddr_in6_send_recv, t_simple_link_local_sockaddr_in6_send_recv ]. t_local_cases() -> [ t_local_basic, t_local_unbound, t_local_fdopen, t_local_fdopen_listen, t_local_fdopen_listen_unbound, t_local_fdopen_connect, t_local_fdopen_connect_unbound, t_local_abstract ]. s_misc_cases() -> [ s_accept_with_explicit_socket_backend ]. init_per_suite(Config0) -> ?P("init_per_suite -> entry with" "~n Config: ~p" "~n Nodes: ~p", [Config0, erlang:nodes()]), case ?LIB:init_per_suite(Config0) of {skip, _} = SKIP -> SKIP; Config1 when is_list(Config1) -> ?P("init_per_suite -> end when " "~n Config: ~p", [Config1]), kernel_test_sys_monitor:start(), Config1 end. end_per_suite(Config0) -> ?P("end_per_suite -> entry with" "~n Config: ~p" "~n Nodes: ~p", [Config0, erlang:nodes()]), kernel_test_sys_monitor:stop(), Config1 = ?LIB:end_per_suite(Config0), ?P("end_per_suite -> " "~n Nodes: ~p", [erlang:nodes()]), Config1. init_per_group(inet_backend_default = _GroupName, Config) -> [{socket_create_opts, []} | Config]; init_per_group(inet_backend_inet = _GroupName, Config) -> case ?EXPLICIT_INET_BACKEND() of true -> The environment us , {skip, "explicit inet backend"}; false -> [{socket_create_opts, [{inet_backend, inet}]} | Config] end; init_per_group(inet_backend_socket = _GroupName, Config) -> case ?EXPLICIT_INET_BACKEND() of true -> The environment us , {skip, "explicit inet backend"}; false -> [{socket_create_opts, [{inet_backend, socket}]} | Config] end; init_per_group(t_local = _GroupName, Config) -> try gen_tcp:connect({local,<<"/">>}, 0, []) of {error, eafnosupport} -> {skip, "AF_LOCAL not supported"}; {error,_} -> Config catch _C:_E:_S -> {skip, "AF_LOCAL not supported"} end; init_per_group(sockaddr = _GroupName, Config) -> case is_socket_supported() of ok -> Config; {skip, _} = SKIP -> SKIP end; init_per_group(_GroupName, Config) -> Config. end_per_group(t_local, _Config) -> delete_local_filenames(); end_per_group(_, _Config) -> ok. init_per_testcase(Func, Config) dbg:tracer(), dbg:p(self(), c), dbg:tpl(prim_inet, cx), dbg:tpl(local_tcp, cx), dbg:tpl(inet, cx), dbg:tpl(gen_tcp, cx), Config; init_per_testcase(_Func, Config) -> ?P("init_per_testcase -> entry with" "~n Config: ~p" "~n Nodes: ~p" "~n Links: ~p" "~n Monitors: ~p", [Config, erlang:nodes(), pi(links), pi(monitors)]), kernel_test_global_sys_monitor:reset_events(), ?P("init_per_testcase -> done when" "~n Nodes: ~p" "~n Links: ~p" "~n Monitors: ~p", [erlang:nodes(), pi(links), pi(monitors)]), Config. end_per_testcase(Func, _Config) dbg:stop(); end_per_testcase(_Func, Config) -> ?P("end_per_testcase -> entry with" "~n Config: ~p" "~n Nodes: ~p" "~n Links: ~p" "~n Monitors: ~p", [Config, erlang:nodes(), pi(links), pi(monitors)]), ?P("system events during test: " "~n ~p", [kernel_test_global_sys_monitor:events()]), ?P("end_per_testcase -> done with" "~n Nodes: ~p" "~n Links: ~p" "~n Monitors: ~p", [erlang:nodes(), pi(links), pi(monitors)]), ok. Test that gen_tcp : ( with timeout ) works . t_accept_timeout(Config) when is_list(Config) -> {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), timeout({gen_tcp, accept, [L, 200]}, 0.2, 1.0). Test that gen_tcp : connect/4 ( with timeout ) works . t_connect_timeout(Config) when is_list(Config) -> ?TC_TRY(t_connect_timeout, fun() -> do_connect_timeout(Config) end). do_connect_timeout(Config)-> TcpPort = 80 , {ok, BadAddr} = unused_ip(), TcpPort = 45638, ok = ?P("Connecting to ~p, port ~p", [BadAddr, TcpPort]), connect_timeout({gen_tcp,connect, [BadAddr,TcpPort, ?INET_BACKEND_OPTS(Config),200]}, 0.2, 5.0). t_connect_src_port(Config) when is_list(Config) -> Timeout = 1000, Loopback = {127,0,0,1}, {ok, Tmp} = gen_tcp:listen(0, [{ip,Loopback}, {linger,{true,0}}]), {ok, SrcPort} = inet:port(Tmp), io:format("SrcPort = ~w~n", [SrcPort]), {ok, L} = gen_tcp:listen(0, [{ip,Loopback}]), ok = gen_tcp:close(Tmp), {ok, DstPort} = inet:port(L), io:format("DstPort = ~w~n", [DstPort]), ConnectOpts = [{port,SrcPort}, {linger,{true,0}}], {ok, C} = gen_tcp:connect(Loopback, DstPort, ConnectOpts, Timeout), {ok, A} = gen_tcp:accept(L, Timeout), {ok, {_, SrcPort}} = inet:peername(A), ok = gen_tcp:close(L), ok = gen_tcp:close(C), ok = gen_tcp:close(A). t_connect_bad(Config) when is_list(Config) -> {error, Reason1} = gen_tcp:connect(localhost, NonExistingPort, ?INET_BACKEND_OPTS(Config)), io:format("Error for connection attempt to port not in use: ~p", [Reason1]), {error, Reason2} = gen_tcp:connect("non-existing-host-xxx", 7, ?INET_BACKEND_OPTS(Config)), io:format("Error for connection attempt to non-existing host: ~p", [Reason2]), ok. gen_tcp : Test that gen_tcp : ( with timeout works ) . t_recv_timeout(Config) when is_list(Config) -> {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), {ok, Client} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), {ok, _A} = gen_tcp:accept(L), timeout({gen_tcp, recv, [Client, 0, 200]}, 0.2, 5.0). t_recv_eof(Config) when is_list(Config) -> {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), {ok, Client} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), {ok, A} = gen_tcp:accept(L), ok = gen_tcp:close(A), {error, closed} = gen_tcp:recv(Client, 0), ok. t_recv_delim(Config) when is_list(Config) -> ?TC_TRY(t_recv_delim, fun() -> do_recv_delim(Config) end). do_recv_delim(Config) -> ?P("init"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), Opts = ?INET_BACKEND_OPTS(Config) ++ [{active,false}, {packet,line}, {line_delimiter,$X}], {ok, Client} = gen_tcp:connect(localhost, Port, Opts), {ok, A} = gen_tcp:accept(L), ?P("send the data"), ok = gen_tcp:send(A, "abcXefgX"), ?P("read the first chunk"), 200 ) , ?P("read the second chunk"), 200 ) , ?P("set active = 2"), ok = inet:setopts(Client, [{active,2}]), ?P("send the data again"), ok = gen_tcp:send(A, "abcXefgX"), ?P("await the first chunk"), receive {tcp, Client, "abcX"} -> ?P("received first chunk") end, ?P("await the second chunk"), receive {tcp, Client, "efgX"} -> ?P("received second chunk") end, ?P("cleanup"), ok = gen_tcp:close(Client), ok = gen_tcp:close(A), ?P("done"), ok. t_shutdown_write(Config) when is_list(Config) -> ?P("create listen socket"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), ?P("create connect socket (C)"), {ok, C} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), ?P("create accept socket (A)"), {ok, A} = gen_tcp:accept(L), ?P("send message A -> C"), ok = gen_tcp:send(A, "Hej Client"), ?P("socket A shutdown(write)"), ok = gen_tcp:shutdown(A, write), ?P("socket C recv - expect message"), {ok, "Hej Client"} = gen_tcp:recv(C, 0), ?P("socket C recv - expect closed"), {error, closed} = gen_tcp:recv(C, 0), ?P("done"), ok. t_shutdown_both(Config) when is_list(Config) -> ?P("create listen socket"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), {ok, Port} = inet:port(L), ?P("create connect socket (C)"), {ok, C} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), ?P("create accept socket (A)"), {ok, A} = gen_tcp:accept(L), ?P("send message A -> C"), ok = gen_tcp:send(A, "Hej Client"), ?P("socket A shutdown(read_write)"), ok = gen_tcp:shutdown(A, read_write), ?P("socket C recv - expect message"), {ok, "Hej Client"} = gen_tcp:recv(C, 0), ?P("socket C recv - expect closed"), {error, closed} = gen_tcp:recv(C, 0), ?P("done"), ok. t_shutdown_error(Config) when is_list(Config) -> ?TC_TRY(t_shutdown_error, fun() -> do_shutdown_error(Config) end). do_shutdown_error(Config) -> ?P("create listen socket"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config)), ?P("shutdown socket (with How = read_write)"), {error, enotconn} = gen_tcp:shutdown(L, read_write), ?P("close socket"), ok = gen_tcp:close(L), ?P("shutdown socket again (with How = read_write)"), {error, closed} = gen_tcp:shutdown(L, read_write), ?P("done"), ok. t_shutdown_async(Config) when is_list(Config) -> ?TC_TRY(t_shutdown_async, fun() -> do_shutdown_async(Config) end). do_shutdown_async(Config) -> ?P("create listen socket"), {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config) ++ [{sndbuf, 4096}]), if is_port(L) -> do_shutdown_async2(Config, L); true -> (catch gen_tcp:close(L)), exit({skip, "inet-only testcase"}) end. do_shutdown_async2(Config, L) -> {OS, _} = os:type(), {ok, Port} = inet:port(L), ?P("connect"), {ok, Client} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{recbuf, 4096}, {active, false}]), ?P("accept connection"), {ok, S} = gen_tcp:accept(L), ?P("create payload"), PayloadSize = 1024 * 1024, Payload = lists:duplicate(PayloadSize, $.), ?P("send payload"), ok = gen_tcp:send(S, Payload), ?P("verify queue size"), case erlang:port_info(S, queue_size) of {queue_size, N} when N > 0 -> ok; {queue_size, 0} when OS =:= win32 -> ok; {queue_size, 0} = T -> ct:fail({unexpected, T}) end, ?P("shutdown(write) accepted socket"), ok = gen_tcp:shutdown(S, write), ?P("recv from connected socket"), {ok, Buf} = gen_tcp:recv(Client, PayloadSize), ?P("recv(0) from connected socket (expect closed)"), {error, closed} = gen_tcp:recv(Client, 0), ?P("verify recv data"), case length(Buf) of PayloadSize -> ?P("done"), ok; Sz -> ?P("ERROR: " "~n extected: ~p" "~n received: ~p", [PayloadSize, Sz]), ct:fail({payload_size, {expected, PayloadSize}, {received, Sz}}) end. t_fdopen(Config) when is_list(Config) -> Question = "Aaaa... Long time ago in a small town in Germany,", Question1 = list_to_binary(Question), Question2 = [<<"Aaaa">>, "... ", $L, <<>>, $o, "ng time ago ", ["in ", [], <<"a small town">>, [" in Germany,", <<>>]]], Question1 = iolist_to_binary(Question2), Answer = "there was a shoemaker, Schumacher was his name.", {ok, L} = gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), {ok, Port} = inet:port(L), {ok, Client} = gen_tcp:connect(localhost, Port, ?INET_BACKEND_OPTS(Config) ++ [{active, false}]), {A, FD} = case gen_tcp:accept(L) of {ok, ASock} when is_port(ASock) -> {ok, FileDesc} = prim_inet:getfd(ASock), {ASock, FileDesc}; {ok, [{fd, FileDesc}]} = gen_tcp_socket:getopts(ASock, [fd]), {ASock, FileDesc} end, ?P("fdopen -> accepted: " "~n A: ~p" "~n FD: ~p", [A, FD]), {ok, Server} = gen_tcp:fdopen(FD, ?INET_BACKEND_OPTS(Config)), ok = gen_tcp:send(Client, Question), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Client, Question1), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Client, Question2), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Server, Answer), {ok, Answer} = gen_tcp:recv(Client, length(Answer), 2000), ok = gen_tcp:close(Client), {error, closed} = gen_tcp:recv(A, 1, 2000), ok = gen_tcp:close(Server), ok = gen_tcp:close(A), ok = gen_tcp:close(L), ok. t_fdconnect(Config) when is_list(Config) -> Cond = fun() -> ?P("Try verify if IPv4 is supported"), ?HAS_SUPPORT_IPV4() end, Pre = fun() -> {ok, Addr} = ?WHICH_LOCAL_ADDR(inet), ?P("Use (local) address: ~p", [Addr]), #{local_addr => Addr} end, Case = fun(#{local_addr := Addr}) -> do_t_fdconnect(Addr, Config) end, Post = fun(_) -> ok end, ?TC_TRY(?FUNCTION_NAME, Cond, Pre, Case, Post). do_t_fdconnect(Addr, Config) -> Question = "Aaaa... Long time ago in a small town in Germany,", Question1 = list_to_binary(Question), Question2 = [<<"Aaaa">>, "... ", $L, <<>>, $o, "ng time ago ", ["in ", [], <<"a small town">>, [" in Germany,", <<>>]]], Question1 = iolist_to_binary(Question2), Answer = "there was a shoemaker, Schumacher was his name.", Path = proplists:get_value(data_dir, Config), Lib = "gen_tcp_api_SUITE", ?P("try load util nif lib"), case erlang:load_nif(filename:join(Path, Lib), []) of ok -> ok; {error, {reload, ReasonStr}} -> ?P("already loaded: " "~n ~s", [ReasonStr]), ok; {error, Reason} -> ?P("UNEXPECTED - failed loading util nif lib: " "~n ~p", [Reason]), ?SKIPT("failed loading util nif lib") end, ?P("try create listen socket"), LOpts = ?INET_BACKEND_OPTS(Config) ++ [{ifaddr, Addr}, {active, false}], L = try gen_tcp:listen(0, LOpts) of {ok, LSock} -> LSock; {error, eaddrnotavail = LReason} -> ?SKIPT(listen_failed_str(LReason)); {error, LReason} -> ?P("UNEXPECTED ERROR - listen error: " "~n COpts: ~p" "~n Reason: ~p", [LReason]), ct:fail({unexpected_listen_error, LReason, LOpts}) catch LC : LE : LS -> ?P("UNEXPECTED ERROR - caught listen: " "~n LOpts: ~p" "~n C: ~p" "~n E: ~p" "~n S: ~p", [LOpts, LC, LE, LS]), ct:fail({listen_failure, {LC, LE, LS}, LOpts}) end, {ok, LPort} = inet:port(L), ?P("try create file descriptor"), FD = gen_tcp_api_SUITE:getsockfd(), ?P("try connect (to port ~w) using file descriptor ~w", [LPort, FD]), COpts = ?INET_BACKEND_OPTS(Config) ++ [{fd, FD}, {ifaddr, Addr}, {active, false}], Client = try gen_tcp:connect(Addr, LPort, COpts ++ [{debug, true}]) of {ok, CSock} -> ok = inet:setopts(CSock, [{debug, false}]), CSock; {error, eaddrnotavail = CReason} -> gen_tcp:close(L), gen_tcp_api_SUITE:closesockfd(FD), ?SKIPT(connect_failed_str(CReason)); {error, CReason} -> ?P("UNEXPECTED ERROR - connect error: " "~n COpts: ~p" "~n Reason: ~p", [COpts, CReason]), ct:fail({unexpected_connect_error, CReason, COpts}) catch CC : CE : CS -> ?P("UNEXPECTED ERROR - caught connect: " "~n COpts: ~p" "~n C: ~p" "~n E: ~p" "~n S: ~p", [COpts, CC, CE, CS]), ct:fail({connect_failure, {CC, CE, CS}, COpts}) end, ?P("try accept connection"), Server = try gen_tcp:accept(L) of {ok, ASock} -> ASock; {error, eaddrnotavail = AReason} -> gen_tcp:close(Client), gen_tcp:close(L), gen_tcp_api_SUITE:closesockfd(FD), ?SKIPT(accept_failed_str(AReason)); {error, AReason} -> ?P("UNEXPECTED ERROR - accept error: " "~n Reason: ~p", [AReason]), ct:fail({unexpected_accept_error, AReason}) catch AC : AE : AS -> ?P("UNEXPECTED ERROR - caught accept: " "~n C: ~p" "~n E: ~p" "~n S: ~p", [AC, AE, AS]), ct:fail({accept_failure, {AC, AE, AS}}) end, ?P("begin validation"), ok = gen_tcp:send(Client, Question), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Client, Question1), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Client, Question2), {ok, Question} = gen_tcp:recv(Server, length(Question), 2000), ok = gen_tcp:send(Server, Answer), {ok, Answer} = gen_tcp:recv(Client, length(Answer), 2000), ?P("cleanup"), ok = gen_tcp:close(Client), FD = gen_tcp_api_SUITE:closesockfd(FD), {error, closed} = gen_tcp:recv(Server, 1, 2000), ok = gen_tcp:close(Server), ok = gen_tcp:close(L), ?P("done"), ok. implicit option to api functions t_implicit_inet6(Config) when is_list(Config) -> ?TC_TRY(t_implicit_inet6, fun() -> do_t_implicit_inet6(Config) end). do_t_implicit_inet6(Config) -> ?P("try get hostname"), Host = ok(inet:gethostname()), ?P("try get address for host ~p", [Host]), case inet:getaddr(Host, inet6) of {ok, Addr} -> ?P("address: ~p", [Addr]), t_implicit_inet6(Config, Host, Addr); {error, Reason} -> {skip, "Can not look up IPv6 address: " ++atom_to_list(Reason)} end. t_implicit_inet6(Config, Host, Addr) -> Loopback = {0,0,0,0,0,0,0,1}, InetBackendOpts = ?INET_BACKEND_OPTS(Config), case gen_tcp:listen(0, InetBackendOpts ++ [inet6, {ip,Loopback}]) of {ok, S1} -> ?P("try ~s ~p", ["::1", Loopback]), implicit_inet6(Config, S1, Loopback), ok = gen_tcp:close(S1), LocalAddr = ok(get_localaddr()), S2 = case gen_tcp:listen(0, InetBackendOpts ++ [{ip, LocalAddr}]) of {ok, LSock2} -> LSock2; {error, Reason2} -> ?P("Listen failed (ip):" "~n Reason2: ~p", [Reason2]), ?SKIPT(listen_failed_str(Reason2)) end, implicit_inet6(Config, S2, LocalAddr), ok = gen_tcp:close(S2), ?P("try ~s ~p", [Host, Addr]), S3 = case gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,Addr}]) of {ok, LSock3} -> LSock3; {error, Reason3} -> ?P("Listen failed (ifaddr):" "~n Reason3: ~p", [Reason3]), ?SKIPT(listen_failed_str(Reason3)) end, implicit_inet6(Config, S3, Addr), ok = gen_tcp:close(S3), ?P("done"), ok; {error, Reason1} -> ?SKIPT(listen_failed_str(Reason1)) end. implicit_inet6(Config, S, Addr) -> P = ok(inet:port(S)), S2 = case gen_tcp:connect(Addr, P, ?INET_BACKEND_OPTS(Config)) of {ok, CSock} -> CSock; {error, CReason} -> ?SKIPT(connect_failed_str(CReason)) end, P2 = ok(inet:port(S2)), S1 = case gen_tcp:accept(S) of {ok, ASock} -> ASock; {error, AReason} -> ?SKIPT(accept_failed_str(AReason)) end, P1 = P = ok(inet:port(S1)), {Addr,P2} = ok(inet:peername(S1)), {Addr,P1} = ok(inet:peername(S2)), {Addr,P1} = ok(inet:sockname(S1)), {Addr,P2} = ok(inet:sockname(S2)), ok = gen_tcp:close(S2), ok = gen_tcp:close(S1). t_local_basic(Config) -> SFile = local_filename(server), SAddr = {local, bin_filename(SFile)}, CFile = local_filename(client), CAddr = {local,bin_filename(CFile)}, _ = file:delete(SFile), _ = file:delete(CFile), ?P("try create listen socket"), InetBackendOpts = ?INET_BACKEND_OPTS(Config), L = ok( gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,{local,SFile}},{active,false}])), ?P("try connect"), C = ok( gen_tcp:connect( {local,SFile}, 0, InetBackendOpts ++ [{ifaddr,{local,CFile}},{active,false}])), ?P("try accept connection"), S = ok(gen_tcp:accept(L)), ?P("try get sockname for listen socket"), case inet:sockname(L) of {ok, SAddr} -> ok; {ok, SAddr2} -> ?P("Invalid sockname: " "~n Expected: ~p" "~n Actual: ~p", [SAddr, SAddr2]), exit({sockename, SAddr, SAddr2}); {error, Reason} -> exit({sockname, Reason}) end, ?P("try get peername for listen socket"), {error, enotconn} = inet:peername(L), ?P("try handshake"), local_handshake(S, SAddr, C, CAddr), ?P("try close listen socket"), ok = gen_tcp:close(L), ?P("try close accept socket"), ok = gen_tcp:close(S), ?P("try close connect socket"), ok = gen_tcp:close(C), ?P("try 'local' files"), ok = file:delete(SFile), ok = file:delete(CFile), ?P("done"), ok. t_local_unbound(Config) -> ?TC_TRY(t_local_unbound, fun() -> do_local_unbound(Config) end). do_local_unbound(Config) -> ?P("create local (server) filename"), SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), InetBackendOpts = ?INET_BACKEND_OPTS(Config), ?P("create listen socket with ifaddr ~p", [SAddr]), L = ok(gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,SAddr},{active,false}])), ?P("listen socket created: ~p" "~n => try connect", [L]), C = ok(gen_tcp:connect(SAddr, 0, InetBackendOpts ++ [{active,false}])), ?P("connected: ~p" "~n => try accept", [C]), S = ok(gen_tcp:accept(L)), ?P("accepted: ~p" "~n => sockname", [S]), SAddr = ok(inet:sockname(L)), ?P("sockname: ~p" "~n => peername (expect enotconn)", [SAddr]), {error, enotconn} = inet:peername(L), ?P("try local handshake"), local_handshake(S, SAddr, C, {local,<<>>}), ?P("close listen socket"), ok = gen_tcp:close(L), ?P("close accepted socket"), ok = gen_tcp:close(S), ?P("close connected socket"), ok = gen_tcp:close(C), ?P("delete (local) file"), ok = file:delete(SFile), ?P("done"), ok. t_local_fdopen(Config) -> ?TC_TRY(t_local_fdopen, fun() -> do_local_fdopen(Config) end). do_local_fdopen(Config) -> ?P("create local (server) filename"), SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), InetBackendOpts = ?INET_BACKEND_OPTS(Config), ListenOpts = InetBackendOpts ++ [{ifaddr,SAddr},{active,false}], ?P("create listen socket with ListenOpts ~p", [ListenOpts]), L = ok(gen_tcp:listen(0, ListenOpts)), ConnectOpts = InetBackendOpts ++ [{active,false}], ?P("listen socket created: ~p" "~n => try connect ~p", [L, ConnectOpts]), C0 = ok(gen_tcp:connect(SAddr, 0, ConnectOpts)), ok = inet:setopts(C0, [{debug, true}]), ?P("connected: ~p" "~n => get fd", [C0]), Fd = if is_port(C0) -> FD0 = ok(prim_inet:getfd(C0)), ?P("FD: ~p" "~n => ignore fd", [FD0]), ok = prim_inet:ignorefd(C0, true), FD0; true -> [{fd, FD0}] = ok(inet:getopts(C0, [fd])), ?P("FD: ~p", [FD0]), FD0 end, ?P("ignored fd:" "~n => try fdopen (local)"), C = ok(gen_tcp:fdopen(Fd, ?INET_BACKEND_OPTS(Config) ++ [local])), ?P("fd open: ~p" "~n => try accept", [C]), S = ok(gen_tcp:accept(L)), ?P("accepted: ~p" "~n => get sockname", [S]), SAddr = ok(inet:sockname(L)), ?P("sockname: ~p" "~n => try get peername (expect enotconn)", [SAddr]), {error,enotconn} = inet:peername(L), ?P("try local handshake"), local_handshake(S, SAddr, C, {local,<<>>}), ?P("close listen socket"), ok = gen_tcp:close(L), ?P("close accepted socket"), ok = gen_tcp:close(S), ?P("close connected socket (final)"), ok = gen_tcp:close(C), ?P("close connected socket (pre)"), ok = gen_tcp:close(C0), ?P("delete (local) file"), ok = file:delete(SFile), ?P("done"), ok. t_local_fdopen_listen(Config) -> ?TC_TRY(t_local_fdopen_listen, fun() -> do_local_fdopen_listen(Config) end). do_local_fdopen_listen(Config) -> ?P("create local (server) filename"), SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), InetBackendOpts = ?INET_BACKEND_OPTS(Config), ?P("create dummy listen socket with ifaddr ~p", [SAddr]), L0 = ok(gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,SAddr},{active,false}])), ?P("dummy listen socket created: ~p" "~n => try get FD", [L0]), Fd = if is_port(L0) -> ok(prim_inet:getfd(L0)); true -> [{fd, FD0}] = ok(inet:getopts(L0, [fd])), FD0 end, ?P("FD: ~p" "~n => try create proper listen socket (using fd)", [Fd]), L = ok(gen_tcp:listen(0, InetBackendOpts ++ [{fd,Fd},local,{active,false}])), ?P("try connect"), C = ok(gen_tcp:connect(SAddr, 0, InetBackendOpts ++ [{active,false}])), ?P("try accept (connection)"), S = ok(gen_tcp:accept(L)), ?P("verify (proper) listen socket sockname"), SAddr = ok(inet:sockname(L)), ?P("verify (proper) listen socket peername (expect enotconn)"), {error, enotconn} = inet:peername(L), ?P("perform handshake"), local_handshake(S, SAddr, C, {local,<<>>}), ?P("close (proper) listen socket"), ok = gen_tcp:close(L), ?P("close (dummy) listen socket"), ok = gen_tcp:close(L0), ?P("close accepted socket"), ok = gen_tcp:close(S), ?P("close connected socket"), ok = gen_tcp:close(C), ?P("delete file (used for socket)"), ok = file:delete(SFile), ?P("done"), ok. t_local_fdopen_listen_unbound(Config) -> SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), P = ok(prim_inet:open(tcp, local, stream)), Fd = ok(prim_inet:getfd(P)), InetBackendOpts = ?INET_BACKEND_OPTS(Config), L = ok(gen_tcp:listen( 0, InetBackendOpts ++ [{fd,Fd},{ifaddr,SAddr},{active,false}])), C = ok(gen_tcp:connect(SAddr, 0, InetBackendOpts ++ [{active,false}])), S = ok(gen_tcp:accept(L)), SAddr = ok(inet:sockname(L)), {error,enotconn} = inet:peername(L), local_handshake(S, SAddr, C, {local,<<>>}), ok = gen_tcp:close(L), ok = gen_tcp:close(P), ok = gen_tcp:close(S), ok = gen_tcp:close(C), ok = file:delete(SFile), ok. t_local_fdopen_connect(Config) -> SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, CFile = local_filename(client), CAddr = {local,bin_filename(CFile)}, _ = file:delete(SFile), _ = file:delete(CFile), InetBackendOpts = ?INET_BACKEND_OPTS(Config), L = ok(gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,SAddr},{active,false}])), P = ok(prim_inet:open(tcp, local, stream)), Fd = ok(prim_inet:getfd(P)), C = ok(gen_tcp:connect( SAddr, 0, InetBackendOpts ++ [{fd,Fd},{ifaddr,CAddr},{active,false}])), S = ok(gen_tcp:accept(L)), SAddr = ok(inet:sockname(L)), {error,enotconn} = inet:peername(L), local_handshake(S, SAddr, C, CAddr), ok = gen_tcp:close(L), ok = gen_tcp:close(S), ok = gen_tcp:close(C), ok = gen_tcp:close(P), ok = file:delete(SFile), ok. t_local_fdopen_connect_unbound(Config) -> SFile = local_filename(server), SAddr = {local,bin_filename(SFile)}, _ = file:delete(SFile), InetBackendOpts = ?INET_BACKEND_OPTS(Config), L = ok(gen_tcp:listen(0, InetBackendOpts ++ [{ifaddr,SAddr},{active,false}])), P = ok(prim_inet:open(tcp, local, stream)), Fd = ok(prim_inet:getfd(P)), C = ok(gen_tcp:connect(SAddr, 0, InetBackendOpts ++ [{fd,Fd},{active,false}])), S = ok(gen_tcp:accept(L)), SAddr = ok(inet:sockname(L)), {error,enotconn} = inet:peername(L), local_handshake(S, SAddr, C, {local,<<>>}), ok = gen_tcp:close(L), ok = gen_tcp:close(S), ok = gen_tcp:close(C), ok = gen_tcp:close(P), ok = file:delete(SFile), ok. t_local_abstract(Config) -> ?TC_TRY(t_local_abstract, fun() -> do_local_abstract(Config) end). do_local_abstract(Config) -> ?P("only run on linux"), case os:type() of {unix, linux} -> AbstAddr = {local,<<>>}, InetBackendOpts = ?INET_BACKEND_OPTS(Config), ?P("create listen socket"), L = ok(gen_tcp:listen( 0, InetBackendOpts ++ [{ifaddr,AbstAddr},{active,false}])), ?P("listen socket created: ~p" "~n => sockname", [L]), {local, _} = SAddr = ok(inet:sockname(L)), ?P("(listen socket) sockname verified" "~n => try connect"), C = ok(gen_tcp:connect( SAddr, 0, InetBackendOpts ++ [{ifaddr,AbstAddr},{active,false}])), ?P("connected: ~p" "~n => sockname", [C]), {local,_} = CAddr = ok(inet:sockname(C)), ?P("(connected socket) sockname verified" "~n => try accept"), S = ok(gen_tcp:accept(L)), ?P("accepted: ~p" "~n => peername (expect enotconn)", [S]), {error,enotconn} = inet:peername(L), ?P("try local handshake"), local_handshake(S, SAddr, C, CAddr), ?P("close listen socket"), ok = gen_tcp:close(L), ?P("close accepted socket"), ok = gen_tcp:close(S), ?P("close connected socket"), ok = gen_tcp:close(C), ?P("done"), ok; _ -> ?P("skip (unless linux)"), {skip,"AF_LOCAL Abstract Addresses only supported on Linux"} end. local_handshake(S, SAddr, C, CAddr) -> ?P("~w(~p, ~p, ~p, ~p)~n", [?FUNCTION_NAME, S, SAddr, C, CAddr]), SData = "9876543210", CData = "0123456789", SAddr = ok(inet:sockname(S)), CAddr = ok(inet:sockname(C)), CAddr = ok(inet:peername(S)), SAddr = ok(inet:peername(C)), ok = gen_tcp:send(C, CData), ok = gen_tcp:send(S, SData), CData = ok(gen_tcp:recv(S, length(CData))), SData = ok(gen_tcp:recv(C, length(SData))), ok. t_accept_inet6_tclass(Config) when is_list(Config) -> ?TC_TRY(t_accept_inet6_tclass, fun() -> do_accept_inet6_tclass(Config) end). do_accept_inet6_tclass(Config) -> Loopback = {0,0,0,0,0,0,0,1}, ?P("create listen socket with tclass: ~p", [TClassOpt]), case gen_tcp:listen(0, ?INET_BACKEND_OPTS(Config) ++ [inet6, {ip, Loopback}, TClassOpt]) of {ok, L} -> ?P("listen socket created: " "~n ~p", [L]), LPort = ok(inet:port(L)), ?P("try to connect to port ~p", [LPort]), Sa = ok(gen_tcp:connect(Loopback, LPort, ?INET_BACKEND_OPTS(Config))), ?P("connected: ~p" "~n => accept connection", [Sa]), Sb = ok(gen_tcp:accept(L)), ?P("accepted: ~p" "~n => getopts (tclass)", [Sb]), [TClassOpt] = ok(inet:getopts(Sb, [tclass])), ?P("tclass verified => close accepted socket"), ok = gen_tcp:close(Sb), ?P("close connected socket"), ok = gen_tcp:close(Sa), ?P("close listen socket"), ok = gen_tcp:close(L), ?P("done"), ok; {error, _Reason} -> ?P("ERROR: Failed create listen socket" "~n ~p", [_Reason]), {skip,"IPv6 TCLASS not supported"} end. t_simple_local_sockaddr_in6_send_recv(Config) when is_list(Config) -> ?TC_TRY(?FUNCTION_NAME, fun() -> ?LIB:has_support_ipv6() end, fun() -> Domain = inet6, {ok, LocalAddr} = ?LIB:which_local_addr(Domain), SockAddr = #{family => Domain, addr => LocalAddr, port => 0}, do_simple_sockaddr_send_recv(SockAddr, Config) end). t_simple_link_local_sockaddr_in6_send_recv(Config) when is_list(Config) -> ?TC_TRY(?FUNCTION_NAME, fun() -> ?LIB:has_support_ipv6(), is_net_supported() end, fun() -> Domain = inet6, LinkLocalAddr = case ?LIB:which_link_local_addr(Domain) of {ok, LLA} -> LLA; {error, _} -> skip("No link local address") end, Filter = fun(#{addr := #{family := D, addr := A}}) -> (D =:= Domain) andalso (A =:= LinkLocalAddr); (_) -> false end, case net:getifaddrs(Filter) of {ok, [#{addr := #{scope_id := ScopeID}}|_]} -> SockAddr = #{family => Domain, addr => LinkLocalAddr, port => 0, scope_id => ScopeID}, do_simple_sockaddr_send_recv(SockAddr, Config); {ok, _} -> skip("Scope ID not found"); {error, R} -> skip({failed_getifaddrs, R}) end end). t_simple_local_sockaddr_in_send_recv(Config) when is_list(Config) -> ?TC_TRY(?FUNCTION_NAME, fun() -> ok end, fun() -> Domain = inet, {ok, LocalAddr} = ?LIB:which_local_addr(Domain), SockAddr = #{family => Domain, addr => LocalAddr, port => 0}, do_simple_sockaddr_send_recv(SockAddr, Config) end). t_simple_link_local_sockaddr_in_send_recv(Config) when is_list(Config) -> ?TC_TRY(?FUNCTION_NAME, fun() -> ok end, fun() -> Domain = inet, LinkLocalAddr = case ?LIB:which_link_local_addr(Domain) of {ok, LLA} -> LLA; {error, _} -> skip("No link local address") end, SockAddr = #{family => Domain, addr => LinkLocalAddr, port => 0}, do_simple_sockaddr_send_recv(SockAddr, Config) end). do_simple_sockaddr_send_recv(SockAddr, _) -> Self = self(), ?P("~n SockAddr: ~p", [SockAddr]), ServerF = fun() -> ?P("try create listen socket"), LSock = try gen_tcp:listen(0, [{ifaddr, SockAddr}, {active, true}, binary]) of {ok, LS} -> LS; {error, LReason} -> ?P("listen error: " "~n Reason: ~p", [LReason]), exit({listen_error, LReason}) catch LC:LE:LS -> ?P("listen failure: " "~n Error Class: ~p" "~n Error: ~p" "~n Call Stack: ~p", [LC, LE, LS]), exit({listen_failure, {LC, LE, LS}}) end, ?P("try get listen port"), {ok, Port} = inet:port(LSock), ?P("listen port: ~w", [Port]), Self ! {{port, Port}, self()}, ?P("try accept"), {ok, ASock} = gen_tcp:accept(LSock), ?P("accepted: " "~n ~p", [ASock]), receive {tcp, ASock, <<"hej">>} -> ?P("received expected message - send reply"), ok = gen_tcp:send(ASock, "hopp") end, ?P("await termination command"), receive {die, Self} -> ?P("terminating"), (catch gen_tcp:close(ASock)), (catch gen_tcp:close(LSock)), exit(normal) end end, ?P("try start server"), Server = spawn_link(ServerF), ?P("server started - await port "), ServerPort = receive {{port, Port}, Server} -> Port; {'EXIT', Server, Reason} -> ?P("server died unexpectedly: " "~n ~p", [Reason]), exit({unexpected_listen_failure, Reason}) end, ?P("server port received: ~p", [ServerPort]), ?P("try connect to server"), ServerSockAddr = SockAddr#{port => ServerPort}, {ok, CSock} = gen_tcp:connect(ServerSockAddr, [{ifaddr, SockAddr}, {active, true}, binary]), ?P("connected to server: " "~n CSock: ~p" "~n CPort: ~p", [CSock, inet:port(CSock)]), ?P("try send message"), ok = gen_tcp:send(CSock, "hej"), ?P("await reply message"), receive {tcp, CSock, <<"hopp">>} -> ?P("received expected reply message") end, ?P("terminate server"), Server ! {die, self()}, ?P("await server termination"), receive {'EXIT', Server, normal} -> ok end, ?P("cleanup"), (catch gen_tcp:close(CSock)), ?P("done"), ok. s_accept_with_explicit_socket_backend(Config) when is_list(Config) -> ?TC_TRY(s_accept_with_explicit_socket_backend, fun() -> is_socket_supported() end, fun() -> do_s_accept_with_explicit_socket_backend() end). do_s_accept_with_explicit_socket_backend() -> ?P("try create listen socket"), {ok, S} = gen_tcp:listen(0, [{inet_backend, socket}]), ?P("try get port number (via sockname)"), {ok, {_, Port}} = inet:sockname(S), ClientF = fun() -> ?P("[client] try connect (tp ~p)", [Port]), {ok, _} = gen_tcp:connect("localhost", Port, []), ?P("[client] connected - wait for termination command"), receive die -> ?P("[client] termination command received"), exit(normal) after infinity -> ok end end, ?P("create client"), Client = spawn_link(ClientF), ?P("try accept"), {ok, _} = gen_tcp:accept(S), ?P("accepted - command client to terminate"), Client ! die, ?P("done"), ok. Utilities is_socket_supported() -> try socket:info() of _ -> ok catch error : notsup -> {skip, "esock not supported"}; error : undef -> {skip, "esock not configured"} end. Calls M : F / length(A ) , which should return a timeout error , and complete timeout({M,F,A}, Lower, Upper) -> case test_server:timecall(M, F, A) of {Time, Result} when Time < Lower -> ct:fail({too_short_time, Time, Result}); {Time, Result} when Time > Upper -> ct:fail({too_long_time, Time, Result}); {_, {error, timeout}} -> ok; {_, Result} -> ct:fail({unexpected_result, Result}) end. connect_timeout({M,F,A}, Lower, Upper) -> case test_server:timecall(M, F, A) of {Time, Result} when Time < Lower -> case Result of {error, econnrefused = E} -> {skip, "Not tested -- got error " ++ atom_to_list(E)}; {error, enetunreach = E} -> {skip, "Not tested -- got error " ++ atom_to_list(E)}; {error, ehostunreach = E} -> {skip, "Not tested -- got error " ++ atom_to_list(E)}; Pinfo = erlang:port_info(Socket), Db = inet_db:lookup_socket(Socket), Peer = inet:peername(Socket), ct:fail({too_short_time, Time, [Result,Pinfo,Db,Peer]}); _ -> ct:fail({too_short_time, Time, Result}) end; {Time, Result} when Time > Upper -> ct:fail({too_long_time, Time, Result}); {_, {error, timeout}} -> ok; {_, Result} -> ct:fail({unexpected_result, Result}) end. unused_ip() -> {ok, Host} = inet:gethostname(), {ok, Hent} = inet:gethostbyname(Host), #hostent{h_addr_list=[{A, B, C, _D}|_]} = Hent, Note : In our net , addresses below 16 are reserved for routers and IP = unused_ip(A, B, C, 16), if (IP =:= error) -> try net:getifaddrs() of {ok, IfAddrs} -> ?P("~n we = ~p" "~n unused_ip = ~p" "~n ~p", [Hent, IP, IfAddrs]); {error, _} -> ?P("~n we: ~p" "~n unused_ip: ~p", [Hent, IP]) catch _:_:_ -> ?P("~n we: ~p" "~n unused_ip: ~p", [Hent, IP]) end; true -> ?P("~n we: ~p" "~n unused_ip: ~p", [Hent, IP]) end, IP. unused_ip(255, 255, 255, 255) -> error; unused_ip(255, B, C, D) -> unused_ip(1, B + 1, C, D); unused_ip(A, 255, C, D) -> unused_ip(A, 1, C + 1, D); unused_ip(A, B, 255, D) -> unused_ip(A, B, 1, D + 1); unused_ip(A, B, C, D) -> case inet:gethostbyaddr({A, B, C, D}) of {ok, _} -> unused_ip(A + 1, B, C, D); {error, _} -> {ok, {A, B, C, D}} end. ok({ok,V}) -> V; ok(NotOk) -> try throw(not_ok) catch throw:Thrown:Stacktrace -> erlang:raise( error, {Thrown, NotOk}, tl(Stacktrace)) end. get_localaddr() -> get_localaddr(["localhost", "localhost6", "ip6-localhost"]). get_localaddr([]) -> {error, localaddr_not_found}; get_localaddr([Localhost|Ls]) -> case inet:getaddr(Localhost, inet6) of {ok, LocalAddr} -> ?P("~s ~p", [Localhost, LocalAddr]), {ok, LocalAddr}; _ -> get_localaddr(Ls) end. getsockfd() -> undefined. closesockfd(_FD) -> undefined. local_filename(Tag) -> "/tmp/" ?MODULE_STRING "_" ++ os:getpid() ++ "_" ++ atom_to_list(Tag). bin_filename(String) -> unicode:characters_to_binary(String, file:native_name_encoding()). delete_local_filenames() -> _ = [file:delete(F) || F <- filelib:wildcard( "/tmp/" ?MODULE_STRING "_" ++ os:getpid() ++ "_*")], ok. is_net_supported() -> try net:info() of #{} -> ok catch error : notsup -> not_supported(net) end. not_supported(What) -> skip({not_supported, What}). skip(Reason) -> throw({skip, Reason}). pi(Item) -> {Item, Val} = process_info(self(), Item), Val. connect_failed_str(Reason) -> ?F("Connect failed: ~w", [Reason]). listen_failed_str(Reason) -> ?F("Listen failed: ~w", [Reason]). accept_failed_str(Reason) -> ?F("Accept failed: ~w", [Reason]).
abbcf7268e83dcaa45883176418d4d9263a3b35b23cd09c636b45201f392712f
haskell-waargonaut/waargonaut
JObject.hs
# LANGUAGE DeriveFoldable # {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # {-# LANGUAGE CPP #-} # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoImplicitPrelude # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} -- | Types and functions for handling our representation of a JSON object. module Waargonaut.Types.JObject ( -- * Object Type JObject (..) , HasJObject (..) -- * Key/value pair type , JAssoc (..) , HasJAssoc (..) -- * Map-like object representation , MapLikeObj , toMapLikeObj , fromMapLikeObj , _MapLikeObj * , parseJObject ) where import Prelude (Eq, Int, Show, elem, fst, not, otherwise, (==)) import Control.Category (id, (.)) import Control.Lens (AsEmpty (..), At (..), Index, IxValue, Ixed (..), Lens', Prism', Rewrapped, Wrapped (..), cons, iso, nearly, prism', to, ( # ), (<&>), (^.), _Wrapped) import Control.Lens.Extras (is) import Control.Monad (Monad) import Data.Bifoldable (Bifoldable (bifoldMap)) import Data.Bifunctor (Bifunctor (bimap)) import Data.Bitraversable (Bitraversable (bitraverse)) import Data.Bool (Bool (..)) import Data.Foldable (Foldable, find, foldr) import Data.Function (($)) import Data.Functor (Functor, (<$>)) import Data.Maybe (Maybe (..), maybe) import Data.Monoid (Monoid (mappend, mempty)) import Data.Semigroup (Semigroup ((<>))) import Data.Text (Text) import Data.Traversable (Traversable, traverse) #if MIN_VERSION_witherable(0,4,0) import qualified Witherable as W #else import qualified Data.Witherable as W #endif import Text.Parser.Char (CharParsing, char) import Waargonaut.Types.CommaSep (CommaSeparated (..), parseCommaSeparated) import Waargonaut.Types.JObject.JAssoc (HasJAssoc (..), JAssoc (..), jAssocAlterF, parseJAssoc) import Waargonaut.Types.JString (_JStringText) -- $setup -- >>> :set -XOverloadedStrings > > > import Utils > > > import . Types . Json > > > import . Types . Whitespace > > > import Control . ( return ) -- >>> import Data.Either (Either (..), isLeft) > > > import . Decode . Error ( DecodeError ) > > > import Data . Digit ( ) ---- -- | The representation of a JSON object. -- -- The <#section-4 JSON RFC8259> indicates -- that names within an object "should" be unique. But the standard does not -- enforce this, leaving it to the various implementations to decide how to -- handle it. -- -- As there are multiple possibilities for deciding which key to use when enforcing uniqueness , accepts duplicate keys , allowing you to -- decide how to handle it. -- -- This type is the "list of tuples of key and value" structure, as such it is a wrapper around the ' CommaSeparated ' data type . -- newtype JObject ws a = JObject (CommaSeparated ws (JAssoc ws a)) deriving (Eq, Show, Functor, Foldable, Traversable) instance (Semigroup ws, Monoid ws) => AsEmpty (JObject ws a) where _Empty = nearly (_Wrapped # _Empty # ()) (^. _Wrapped . to (is _Empty)) # INLINE _ Empty # instance JObject ws a ~ t => Rewrapped (JObject ws a) t instance Wrapped (JObject ws a) where type Unwrapped (JObject ws a) = CommaSeparated ws (JAssoc ws a) _Wrapped' = iso (\ (JObject x) -> x) JObject type instance IxValue (JObject ws a) = a type instance Index (JObject ws a) = Int instance (Semigroup ws, Monoid ws) => Semigroup (JObject ws a) where (JObject a) <> (JObject b) = JObject (a <> b) instance (Semigroup ws, Monoid ws) => Monoid (JObject ws a) where mempty = JObject mempty mappend = (<>) instance Bifunctor JObject where bimap f g (JObject c) = JObject (bimap f (bimap f g) c) instance Bifoldable JObject where bifoldMap f g (JObject c) = bifoldMap f (bifoldMap f g) c instance Bitraversable JObject where bitraverse f g (JObject c) = JObject <$> bitraverse f (bitraverse f g) c | Without having an obviously correct " first " or " last " decision on which ' Waargonaut . Types . ' key is the " right " one to use , a ' JObject ' can only be indexed by a -- numeric value. instance Monoid ws => Ixed (JObject ws a) where ix i f (JObject cs) = JObject <$> ix i (traverse f) cs -- | Type class to represent something that has a 'JObject' within it. class HasJObject c ws a | c -> ws a where jObject :: Lens' c (JObject ws a) instance HasJObject (JObject ws a) ws a where jObject = id -- | This is a newtype around our 'JObject' for when we want to use the -- "map-like" representation of our JSON object. This data type will enforce that the first key found is treated as the desired element , and all subsequent -- occurrences of that key are discarded. newtype MapLikeObj ws a = MLO { fromMapLikeObj :: JObject ws a -- ^ Access the underlying 'JObject'. } deriving (Eq, Show, Functor, Foldable, Traversable) -- | -- 'Control.Lens.Prism' for working with a 'JObject' as a 'MapLikeObj'. This optic will keep the first unique key on a given ' JObject ' and this information is not -- recoverable. If you want to create a 'MapLikeObj' from a 'JObject' and keep -- what is removed, then use the 'toMapLikeObj' function. -- _MapLikeObj :: (Semigroup ws, Monoid ws) => Prism' (JObject ws a) (MapLikeObj ws a) _MapLikeObj = prism' fromMapLikeObj (Just . fst . toMapLikeObj) instance MapLikeObj ws a ~ t => Rewrapped (MapLikeObj ws a) t instance Wrapped (MapLikeObj ws a) where type Unwrapped (MapLikeObj ws a) = JObject ws a _Wrapped' = iso (\ (MLO x) -> x) MLO instance (Monoid ws, Semigroup ws) => AsEmpty (MapLikeObj ws a) where _Empty = nearly (_Wrapped # _Empty # ()) (^. _Wrapped . to (is _Empty)) # INLINE _ Empty # type instance IxValue (MapLikeObj ws a) = a type instance Index (MapLikeObj ws a) = Text instance Monoid ws => Ixed (MapLikeObj ws a) where | Unlike ' JObject ' this type has an opinionated stance on which key is the -- "correct" one, so we're able to have an 'At' instance. instance Monoid ws => At (MapLikeObj ws a) where at k f (MLO (JObject cs)) = jAssocAlterF k f (find (textKeyMatch k) cs) <&> MLO . JObject . maybe (W.filter (not . textKeyMatch k) cs) (`cons` cs) instance Bifunctor MapLikeObj where bimap f g (MLO o) = MLO (bimap f g o) instance Bifoldable MapLikeObj where bifoldMap f g (MLO o) = bifoldMap f g o instance Bitraversable MapLikeObj where bitraverse f g (MLO o) = MLO <$> bitraverse f g o | Take a ' JObject ' and produce a ' MapLikeObj ' where the first key is -- considered the unique value. Subsequence occurrences of that key and it's value -- are collected and returned as a list. toMapLikeObj :: (Semigroup ws, Monoid ws) => JObject ws a -> (MapLikeObj ws a, [JAssoc ws a]) toMapLikeObj (JObject xs) = (\(_,a,b) -> (MLO (JObject a), b)) $ foldr f (mempty,mempty,mempty) xs where f x (ys,acc,discards) | _jsonAssocKey x `elem` ys = (ys, acc, x:discards) | otherwise = (_jsonAssocKey x:ys, cons x acc, discards) -- Compare a 'Text' to the key for a 'JAssoc' value. textKeyMatch :: Text -> JAssoc ws a -> Bool textKeyMatch k = (== k) . (^. jsonAssocKey . _JStringText) -- | -- > > > ( parseJObject parseWhitespace parseWaargonaut ) " { \"foo\":null } " Right ( JObject ( CommaSeparated ( WS [ ] ) ( Just ( Elems { _ elemsElems = [ ] , _ elemsLast = Elem { _ elemVal = JAssoc { _ jsonAssocKey = ' [ UnescapedJChar ( Unescaped ' f'),UnescapedJChar ( Unescaped ' o'),UnescapedJChar ( Unescaped ' o ' ) ] , _ jsonAssocKeyTrailingWS = WS [ ] , _ jsonAssocValPreceedingWS = WS [ ] , _ jsonAssocVal = Json ( JNull ( WS [ Space ] ) ) } , _ elemTrailing = Nothing } } ) ) ) ) -- > > > ( parseJObject parseWhitespace parseWaargonaut ) " { \"foo\":null , } " Right ( JObject ( CommaSeparated ( WS [ ] ) ( Just ( Elems { _ elemsElems = [ ] , _ elemsLast = Elem { _ elemVal = JAssoc { _ jsonAssocKey = ' [ UnescapedJChar ( Unescaped ' f'),UnescapedJChar ( Unescaped ' o'),UnescapedJChar ( Unescaped ' o ' ) ] , _ jsonAssocKeyTrailingWS = WS [ ] , _ jsonAssocValPreceedingWS = WS [ ] , _ jsonAssocVal = Json ( JNull ( WS [ ] ) ) } , _ elemTrailing = Just ( Comma , WS [ Space ] ) } } ) ) ) ) -- parseJObject :: ( Monad f , CharParsing f ) => f ws -> f a -> f (JObject ws a) parseJObject ws a = JObject <$> parseCommaSeparated (char '{') (char '}') ws (parseJAssoc ws a)
null
https://raw.githubusercontent.com/haskell-waargonaut/waargonaut/4671958c7d8557c72bf881fabed5612ace1ec936/src/Waargonaut/Types/JObject.hs
haskell
# LANGUAGE DeriveFunctor # # LANGUAGE DeriveTraversable # # LANGUAGE FlexibleContexts # # LANGUAGE CPP # # LANGUAGE RankNTypes # # LANGUAGE TypeFamilies # | Types and functions for handling our representation of a JSON object. * Object Type * Key/value pair type * Map-like object representation $setup >>> :set -XOverloadedStrings >>> import Data.Either (Either (..), isLeft) -- | The representation of a JSON object. The <#section-4 JSON RFC8259> indicates that names within an object "should" be unique. But the standard does not enforce this, leaving it to the various implementations to decide how to handle it. As there are multiple possibilities for deciding which key to use when decide how to handle it. This type is the "list of tuples of key and value" structure, as such it is a numeric value. | Type class to represent something that has a 'JObject' within it. | This is a newtype around our 'JObject' for when we want to use the "map-like" representation of our JSON object. This data type will enforce that occurrences of that key are discarded. ^ Access the underlying 'JObject'. | 'Control.Lens.Prism' for working with a 'JObject' as a 'MapLikeObj'. This optic will keep recoverable. If you want to create a 'MapLikeObj' from a 'JObject' and keep what is removed, then use the 'toMapLikeObj' function. "correct" one, so we're able to have an 'At' instance. considered the unique value. Subsequence occurrences of that key and it's value are collected and returned as a list. Compare a 'Text' to the key for a 'JAssoc' value. |
# LANGUAGE DeriveFoldable # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoImplicitPrelude # module Waargonaut.Types.JObject ( JObject (..) , HasJObject (..) , JAssoc (..) , HasJAssoc (..) , MapLikeObj , toMapLikeObj , fromMapLikeObj , _MapLikeObj * , parseJObject ) where import Prelude (Eq, Int, Show, elem, fst, not, otherwise, (==)) import Control.Category (id, (.)) import Control.Lens (AsEmpty (..), At (..), Index, IxValue, Ixed (..), Lens', Prism', Rewrapped, Wrapped (..), cons, iso, nearly, prism', to, ( # ), (<&>), (^.), _Wrapped) import Control.Lens.Extras (is) import Control.Monad (Monad) import Data.Bifoldable (Bifoldable (bifoldMap)) import Data.Bifunctor (Bifunctor (bimap)) import Data.Bitraversable (Bitraversable (bitraverse)) import Data.Bool (Bool (..)) import Data.Foldable (Foldable, find, foldr) import Data.Function (($)) import Data.Functor (Functor, (<$>)) import Data.Maybe (Maybe (..), maybe) import Data.Monoid (Monoid (mappend, mempty)) import Data.Semigroup (Semigroup ((<>))) import Data.Text (Text) import Data.Traversable (Traversable, traverse) #if MIN_VERSION_witherable(0,4,0) import qualified Witherable as W #else import qualified Data.Witherable as W #endif import Text.Parser.Char (CharParsing, char) import Waargonaut.Types.CommaSep (CommaSeparated (..), parseCommaSeparated) import Waargonaut.Types.JObject.JAssoc (HasJAssoc (..), JAssoc (..), jAssocAlterF, parseJAssoc) import Waargonaut.Types.JString (_JStringText) > > > import Utils > > > import . Types . Json > > > import . Types . Whitespace > > > import Control . ( return ) > > > import . Decode . Error ( DecodeError ) > > > import Data . Digit ( ) enforcing uniqueness , accepts duplicate keys , allowing you to wrapper around the ' CommaSeparated ' data type . newtype JObject ws a = JObject (CommaSeparated ws (JAssoc ws a)) deriving (Eq, Show, Functor, Foldable, Traversable) instance (Semigroup ws, Monoid ws) => AsEmpty (JObject ws a) where _Empty = nearly (_Wrapped # _Empty # ()) (^. _Wrapped . to (is _Empty)) # INLINE _ Empty # instance JObject ws a ~ t => Rewrapped (JObject ws a) t instance Wrapped (JObject ws a) where type Unwrapped (JObject ws a) = CommaSeparated ws (JAssoc ws a) _Wrapped' = iso (\ (JObject x) -> x) JObject type instance IxValue (JObject ws a) = a type instance Index (JObject ws a) = Int instance (Semigroup ws, Monoid ws) => Semigroup (JObject ws a) where (JObject a) <> (JObject b) = JObject (a <> b) instance (Semigroup ws, Monoid ws) => Monoid (JObject ws a) where mempty = JObject mempty mappend = (<>) instance Bifunctor JObject where bimap f g (JObject c) = JObject (bimap f (bimap f g) c) instance Bifoldable JObject where bifoldMap f g (JObject c) = bifoldMap f (bifoldMap f g) c instance Bitraversable JObject where bitraverse f g (JObject c) = JObject <$> bitraverse f (bitraverse f g) c | Without having an obviously correct " first " or " last " decision on which ' Waargonaut . Types . ' key is the " right " one to use , a ' JObject ' can only be indexed by a instance Monoid ws => Ixed (JObject ws a) where ix i f (JObject cs) = JObject <$> ix i (traverse f) cs class HasJObject c ws a | c -> ws a where jObject :: Lens' c (JObject ws a) instance HasJObject (JObject ws a) ws a where jObject = id the first key found is treated as the desired element , and all subsequent newtype MapLikeObj ws a = MLO } deriving (Eq, Show, Functor, Foldable, Traversable) the first unique key on a given ' JObject ' and this information is not _MapLikeObj :: (Semigroup ws, Monoid ws) => Prism' (JObject ws a) (MapLikeObj ws a) _MapLikeObj = prism' fromMapLikeObj (Just . fst . toMapLikeObj) instance MapLikeObj ws a ~ t => Rewrapped (MapLikeObj ws a) t instance Wrapped (MapLikeObj ws a) where type Unwrapped (MapLikeObj ws a) = JObject ws a _Wrapped' = iso (\ (MLO x) -> x) MLO instance (Monoid ws, Semigroup ws) => AsEmpty (MapLikeObj ws a) where _Empty = nearly (_Wrapped # _Empty # ()) (^. _Wrapped . to (is _Empty)) # INLINE _ Empty # type instance IxValue (MapLikeObj ws a) = a type instance Index (MapLikeObj ws a) = Text instance Monoid ws => Ixed (MapLikeObj ws a) where | Unlike ' JObject ' this type has an opinionated stance on which key is the instance Monoid ws => At (MapLikeObj ws a) where at k f (MLO (JObject cs)) = jAssocAlterF k f (find (textKeyMatch k) cs) <&> MLO . JObject . maybe (W.filter (not . textKeyMatch k) cs) (`cons` cs) instance Bifunctor MapLikeObj where bimap f g (MLO o) = MLO (bimap f g o) instance Bifoldable MapLikeObj where bifoldMap f g (MLO o) = bifoldMap f g o instance Bitraversable MapLikeObj where bitraverse f g (MLO o) = MLO <$> bitraverse f g o | Take a ' JObject ' and produce a ' MapLikeObj ' where the first key is toMapLikeObj :: (Semigroup ws, Monoid ws) => JObject ws a -> (MapLikeObj ws a, [JAssoc ws a]) toMapLikeObj (JObject xs) = (\(_,a,b) -> (MLO (JObject a), b)) $ foldr f (mempty,mempty,mempty) xs where f x (ys,acc,discards) | _jsonAssocKey x `elem` ys = (ys, acc, x:discards) | otherwise = (_jsonAssocKey x:ys, cons x acc, discards) textKeyMatch :: Text -> JAssoc ws a -> Bool textKeyMatch k = (== k) . (^. jsonAssocKey . _JStringText) > > > ( parseJObject parseWhitespace parseWaargonaut ) " { \"foo\":null } " Right ( JObject ( CommaSeparated ( WS [ ] ) ( Just ( Elems { _ elemsElems = [ ] , _ elemsLast = Elem { _ elemVal = JAssoc { _ jsonAssocKey = ' [ UnescapedJChar ( Unescaped ' f'),UnescapedJChar ( Unescaped ' o'),UnescapedJChar ( Unescaped ' o ' ) ] , _ jsonAssocKeyTrailingWS = WS [ ] , _ jsonAssocValPreceedingWS = WS [ ] , _ jsonAssocVal = Json ( JNull ( WS [ Space ] ) ) } , _ elemTrailing = Nothing } } ) ) ) ) > > > ( parseJObject parseWhitespace parseWaargonaut ) " { \"foo\":null , } " Right ( JObject ( CommaSeparated ( WS [ ] ) ( Just ( Elems { _ elemsElems = [ ] , _ elemsLast = Elem { _ elemVal = JAssoc { _ jsonAssocKey = ' [ UnescapedJChar ( Unescaped ' f'),UnescapedJChar ( Unescaped ' o'),UnescapedJChar ( Unescaped ' o ' ) ] , _ jsonAssocKeyTrailingWS = WS [ ] , _ jsonAssocValPreceedingWS = WS [ ] , _ jsonAssocVal = Json ( JNull ( WS [ ] ) ) } , _ elemTrailing = Just ( Comma , WS [ Space ] ) } } ) ) ) ) parseJObject :: ( Monad f , CharParsing f ) => f ws -> f a -> f (JObject ws a) parseJObject ws a = JObject <$> parseCommaSeparated (char '{') (char '}') ws (parseJAssoc ws a)
b082e5dc5d23b3a008c030a0340a1267d3fb12008081863e3357d52bd1fcf086
scymtym/architecture.builder-protocol
variables.lisp
;;;; variables.lisp --- Variables provided by the architecture.builder-protocol system. ;;;; Copyright ( C ) 2014 , 2015 Jan Moringen ;;;; Author : < > (cl:in-package #:architecture.builder-protocol) (defvar *builder* nil "Stores the builder object which should be used for constructing the result.")
null
https://raw.githubusercontent.com/scymtym/architecture.builder-protocol/a48abddff7f6e0779b89666f46ab87ef918488f0/src/variables.lisp
lisp
variables.lisp --- Variables provided by the architecture.builder-protocol system.
Copyright ( C ) 2014 , 2015 Jan Moringen Author : < > (cl:in-package #:architecture.builder-protocol) (defvar *builder* nil "Stores the builder object which should be used for constructing the result.")
73e98c6b3f665be3693e6a548133343a8229390ab77b444efca6d82838101090
tonatona-project/tonatona
Postgresql.hs
module Tonatona.Persist.Postgresql ( run , TonaDbM , Config(..) , DbConnStr(..) , DbConnNum(..) , runMigrate ) where import RIO import Control.Monad.Logger as Logger (Loc, LoggingT(..), LogLevel, LogSource, LogStr, runStdoutLoggingT) import Data.Pool (Pool) import Database.Persist.Postgresql (withPostgresqlPool) import Database.Persist.Sql (Migration, SqlBackend, runMigration, runSqlPool) import Tonatona (HasConfig(..), HasParser(..)) import TonaParser ((.||), argLong, envVar, liftWith, optionalVal) type TonaDbM env = ReaderT SqlBackend (RIO env) runMigrate :: (HasConfig env Config) => Migration -> RIO env () runMigrate migration = run $ runMigration migration -- | Main function. run :: (HasConfig env Config) => TonaDbM env a -> RIO env a run query = do pool <- asks (connPool . config) runSqlPool query pool ------------ -- Config -- ------------ newtype DbConnStr = DbConnStr { unDbConnStr :: ByteString } deriving (Eq, IsString, Read, Show) instance HasParser DbConnStr where parser = DbConnStr <$> optionalVal "Formatted string to connect postgreSQL" (argLong "db-conn-string" .|| envVar "DB_CONN_STRING") "postgresql:mypass@localhost:5432/mydb" newtype DbConnNum = DbConnNum { unDbConnNum :: Int } deriving (Eq, Num, Read, Show) instance HasParser DbConnNum where parser = DbConnNum <$> optionalVal "Number of connections which connection pool uses" ( argLong "db-conn-num" .|| envVar "DB_CONN_NUM") 10 data Config = Config { connString :: DbConnStr , connNum :: DbConnNum , connPool :: Pool SqlBackend } deriving (Show) instance HasParser Config where parser = do connStr <- parser connNum <- parser liftWith $ \action -> do runLoggingT (withPostgresqlPool (unDbConnStr connStr) (unDbConnNum connNum) (lift . action . Config connStr connNum)) stdoutLogger stdoutLogger :: Loc -> Logger.LogSource -> Logger.LogLevel -> LogStr -> IO () stdoutLogger loc source level msg = do func <- runStdoutLoggingT $ LoggingT pure func loc source level msg
null
https://raw.githubusercontent.com/tonatona-project/tonatona/b6b67bf0f14d345c01dcf9ea7870b657891f032c/tonatona-persistent-postgresql/src/Tonatona/Persist/Postgresql.hs
haskell
| Main function. ---------- Config -- ----------
module Tonatona.Persist.Postgresql ( run , TonaDbM , Config(..) , DbConnStr(..) , DbConnNum(..) , runMigrate ) where import RIO import Control.Monad.Logger as Logger (Loc, LoggingT(..), LogLevel, LogSource, LogStr, runStdoutLoggingT) import Data.Pool (Pool) import Database.Persist.Postgresql (withPostgresqlPool) import Database.Persist.Sql (Migration, SqlBackend, runMigration, runSqlPool) import Tonatona (HasConfig(..), HasParser(..)) import TonaParser ((.||), argLong, envVar, liftWith, optionalVal) type TonaDbM env = ReaderT SqlBackend (RIO env) runMigrate :: (HasConfig env Config) => Migration -> RIO env () runMigrate migration = run $ runMigration migration run :: (HasConfig env Config) => TonaDbM env a -> RIO env a run query = do pool <- asks (connPool . config) runSqlPool query pool newtype DbConnStr = DbConnStr { unDbConnStr :: ByteString } deriving (Eq, IsString, Read, Show) instance HasParser DbConnStr where parser = DbConnStr <$> optionalVal "Formatted string to connect postgreSQL" (argLong "db-conn-string" .|| envVar "DB_CONN_STRING") "postgresql:mypass@localhost:5432/mydb" newtype DbConnNum = DbConnNum { unDbConnNum :: Int } deriving (Eq, Num, Read, Show) instance HasParser DbConnNum where parser = DbConnNum <$> optionalVal "Number of connections which connection pool uses" ( argLong "db-conn-num" .|| envVar "DB_CONN_NUM") 10 data Config = Config { connString :: DbConnStr , connNum :: DbConnNum , connPool :: Pool SqlBackend } deriving (Show) instance HasParser Config where parser = do connStr <- parser connNum <- parser liftWith $ \action -> do runLoggingT (withPostgresqlPool (unDbConnStr connStr) (unDbConnNum connNum) (lift . action . Config connStr connNum)) stdoutLogger stdoutLogger :: Loc -> Logger.LogSource -> Logger.LogLevel -> LogStr -> IO () stdoutLogger loc source level msg = do func <- runStdoutLoggingT $ LoggingT pure func loc source level msg
30f182caccc967133e8ef8615600739bed214ee26484074952402914a9a320a4
wireapp/wire-server
Budget.hs
# LANGUAGE GeneralizedNewtypeDeriving # -- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. module Brig.Budget ( Budget (..), BudgetKey (..), Budgeted (..), withBudget, checkBudget, lookupBudget, insertBudget, ) where import Cassandra import Data.Time.Clock import Imports data Budget = Budget { budgetTimeout :: !NominalDiffTime, budgetValue :: !Int32 } deriving (Eq, Show, Generic) data Budgeted a = BudgetExhausted NominalDiffTime | BudgetedValue a Int32 deriving (Eq, Show, Generic) newtype BudgetKey = BudgetKey Text deriving (Eq, Show, Cql) | @withBudget ( BudgetKey " k " ) ( Budget 30 5 ) action@ runs @action@ at most 5 times every 30 -- seconds. @"k"@ is used for keeping different calls to 'withBudget' apart; use something -- there that's unique to your context, like @"login#" <> uid@. -- See the docs in " Gundeck . ThreadBudget " for related work . -- -- FUTUREWORK: encourage caller to define their own type for budget keys (rather than using an -- untyped text), and represent the types in a way that guarantees that if i'm using a local -- type that i don't export, then nobody will be able to use my namespace. -- -- FUTUREWORK: exceptions are not handled very nicely, but it's not clear what it would mean -- to improve this. withBudget :: MonadClient m => BudgetKey -> Budget -> m a -> m (Budgeted a) withBudget k b ma = do Budget ttl val <- fromMaybe b <$> lookupBudget k let remaining = val - 1 if remaining < 0 then pure (BudgetExhausted ttl) else do a <- ma insertBudget k (Budget ttl remaining) pure (BudgetedValue a remaining) -- | Like 'withBudget', but does not decrease budget, only takes a look. checkBudget :: MonadClient m => BudgetKey -> Budget -> m (Budgeted ()) checkBudget k b = do Budget ttl val <- fromMaybe b <$> lookupBudget k let remaining = val - 1 pure $ if remaining < 0 then BudgetExhausted ttl else BudgetedValue () remaining lookupBudget :: MonadClient m => BudgetKey -> m (Maybe Budget) lookupBudget k = fmap mk <$> query1 budgetSelect (params One (Identity k)) where mk (val, ttl) = Budget (fromIntegral ttl) val insertBudget :: MonadClient m => BudgetKey -> Budget -> m () insertBudget k (Budget ttl val) = retry x5 $ write budgetInsert (params One (k, val, round ttl)) ------------------------------------------------------------------------------- Queries budgetInsert :: PrepQuery W (BudgetKey, Int32, Int32) () budgetInsert = "INSERT INTO budget (key, budget) VALUES (?, ?) USING TTL ?" budgetSelect :: PrepQuery R (Identity BudgetKey) (Int32, Int32) budgetSelect = "SELECT budget, ttl(budget) FROM budget where key = ?"
null
https://raw.githubusercontent.com/wireapp/wire-server/97286de4e9745b89e0146c0cb556b1f90e660133/services/brig/src/Brig/Budget.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. with this program. If not, see </>. seconds. @"k"@ is used for keeping different calls to 'withBudget' apart; use something there that's unique to your context, like @"login#" <> uid@. FUTUREWORK: encourage caller to define their own type for budget keys (rather than using an untyped text), and represent the types in a way that guarantees that if i'm using a local type that i don't export, then nobody will be able to use my namespace. FUTUREWORK: exceptions are not handled very nicely, but it's not clear what it would mean to improve this. | Like 'withBudget', but does not decrease budget, only takes a look. -----------------------------------------------------------------------------
# LANGUAGE GeneralizedNewtypeDeriving # Copyright ( C ) 2022 Wire Swiss GmbH < > the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along module Brig.Budget ( Budget (..), BudgetKey (..), Budgeted (..), withBudget, checkBudget, lookupBudget, insertBudget, ) where import Cassandra import Data.Time.Clock import Imports data Budget = Budget { budgetTimeout :: !NominalDiffTime, budgetValue :: !Int32 } deriving (Eq, Show, Generic) data Budgeted a = BudgetExhausted NominalDiffTime | BudgetedValue a Int32 deriving (Eq, Show, Generic) newtype BudgetKey = BudgetKey Text deriving (Eq, Show, Cql) | @withBudget ( BudgetKey " k " ) ( Budget 30 5 ) action@ runs @action@ at most 5 times every 30 See the docs in " Gundeck . ThreadBudget " for related work . withBudget :: MonadClient m => BudgetKey -> Budget -> m a -> m (Budgeted a) withBudget k b ma = do Budget ttl val <- fromMaybe b <$> lookupBudget k let remaining = val - 1 if remaining < 0 then pure (BudgetExhausted ttl) else do a <- ma insertBudget k (Budget ttl remaining) pure (BudgetedValue a remaining) checkBudget :: MonadClient m => BudgetKey -> Budget -> m (Budgeted ()) checkBudget k b = do Budget ttl val <- fromMaybe b <$> lookupBudget k let remaining = val - 1 pure $ if remaining < 0 then BudgetExhausted ttl else BudgetedValue () remaining lookupBudget :: MonadClient m => BudgetKey -> m (Maybe Budget) lookupBudget k = fmap mk <$> query1 budgetSelect (params One (Identity k)) where mk (val, ttl) = Budget (fromIntegral ttl) val insertBudget :: MonadClient m => BudgetKey -> Budget -> m () insertBudget k (Budget ttl val) = retry x5 $ write budgetInsert (params One (k, val, round ttl)) Queries budgetInsert :: PrepQuery W (BudgetKey, Int32, Int32) () budgetInsert = "INSERT INTO budget (key, budget) VALUES (?, ?) USING TTL ?" budgetSelect :: PrepQuery R (Identity BudgetKey) (Int32, Int32) budgetSelect = "SELECT budget, ttl(budget) FROM budget where key = ?"
f083b886a3c09aa16259feaca30080dd40469bff856c56e9d4a88bd5626ac055
ddmcdonald/sparser
dispatch.lisp
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*- copyright ( c ) 1994 - 1996,2011 - 2019 -- all rights reserved extensions copyright ( c ) 2010 BBNT Solutions LLC . All Rights Reserved ;;; ;;; File: "dispatch" ;;; Module: "analyzers;traversal:" Version : November 2019 initiated 6/15/94 v2.3 . 9/26 Fixed : multiple - initial - edges bug 9/13/95 fleshed out stub for hook being a cfr . 9/15 fixed a bug . 1/1/96 put in a trap for the ' span - is - longer - than - segment ' case , which seems to consistently indicate that there are embedded punct 's ;; and the pair passed in to here aren't the ones that are intended ;; to match. 2/23/07 Removed the ecases. Added flag to permit long segments . 2/22/10 Added a form category identical to the the edge ;; category so that we can write form rules against these if we want. 0.1 ( 8/28/11 ) Cleaned up . Requiring : single - span to allow hook . ( 9/12/11 ) Added function for creating the obvious edge . 0.2 ( 2/11/13 ) Adding check for an ordinary word needing to be ;; reanalyzed when it appears in all caps or capitalized ;; (7/23/13) Extended criteria for suspecting a hook. 0.3 ( 8/8/15 ) Added * special - acronym - handling * to stop it always ;; converting acronyms to proper nouns. (in-package :sparser) (unless (boundp '*allow-large-paired-interiors*) (defparameter *allow-large-paired-interiors* t)) (defparameter *special-acronym-handling* nil "Flag what will prohibit the creation of a proper name over single-spans of :all-caps. Set when the caller want to do the handling itself.") ;; (trace-sections) (defun do-paired-punctuation-interior (type pos-before-open pos-after-open pos-before-close pos-after-close) (declare (special *special-acronym-handling* *allow-large-paired-interiors* *treat-single-Capitalized-words-as-names*)) (tr :paired-punct-interior type pos-after-open pos-before-close) (let ((layout (analyze-segment-layout pos-after-open pos-before-close)) ;; when there are multiple single-term edges this choice ;; of accessor gives us the topmost (most recent) of ;; those edges (first-edge (right-treetop-at/edge pos-after-open))) (when (word-p first-edge) ;; these are irrelevant, so we turn off the flag that controls ;; later operations. (setq first-edge nil)) (case layout (:single-span This check probably dates from the original DM&P work (when (eq (edge-category first-edge) (category-named 'segment)) ;; then it's a dummy and we have to look underneath it (setq first-edge (leftmost-daughter-edge first-edge) layout (analyze-segment-layout pos-after-open pos-before-close t))) ;; Some stock tickers and such are ordinary words and could ;; be captured as such. But they will be capitalized and ;; we can overrule that with another edge (when (one-word-long? first-edge) (when (eq (pos-capitalization (pos-edge-starts-at first-edge)) :all-caps) ;; That's enough evidence to recast the edge and take it ;; as an acronym or ticker symbol, but we'll leave that to context to determine which one (unless (or *special-acronym-handling* ;; set by sweep-to-span-parentheses (eq (edge-form first-edge) (category-named 'proper-name)) (eq (edge-form first-edge) (category-named 'np))) ;; if so, then there's probably a hook for it and ;; we leave it alone. ;; Alternatively, in some text-types it's the thing to do . C.f . WHO for the World Health Organization (unless *treat-single-Capitalized-words-as-names* (lsp-break "About to convert ordinary word to proper name")) (convert-ordinary-word-edge-to-proper-name first-edge))))) (:contiguous-edges (parse-between-parentheses-boundaries pos-after-open pos-before-close) ;;(break "finished between parens parse") (setq first-edge ;; update the flag that controls the hook (right-treetop-at/edge pos-after-open))) (:span-is-longer-than-segment (unless *allow-large-paired-interiors* (error "~&~%Paired Punctuation:~ ~%The span of text between the ~A~ ~%at p~A and p~A is unreasonably large.~ ~%Probably there is some sort of undetected imbalance.~%" type (pos-token-index pos-before-open) (pos-token-index pos-before-close)))) ((or :null-span :no-edges :some-edges :has-unknown-words)) (otherwise (push-debug `(,pos-before-open ,pos-after-open ,pos-before-close ,pos-after-close)) (error "Unexpected layout between paired punctuation: ~a" layout))) (setq layout (analyze-segment-layout pos-after-open pos-before-close)) (tr :layout-between-punct layout) (labels ((referent-for-vanila-edge () "Edges need referents, even when they are semantically vacuous" (if (and first-edge (edge-p first-edge)) (edge-referent first-edge) (let ((type-category (category-named (if (eq type :quotation-marks) 'QUOTATION type)))) (find-or-make-individual type-category)))) (vanila-edge (pos-before-open pos-after-close type &key referent) "Just cover the span between the punctuation (inclusive) with an edge labeled according to the type of bracket." (tr :vanila-paired-edge pos-before-open pos-after-close) (let ((edge (make-edge-over-long-span pos-before-open pos-after-close (case type (:angle-brackets (category-named 'angle-brackets)) (:square-brackets (category-named 'square-brackets)) (:curly-brackets (category-named 'curly-brackets)) (:parentheses (category-named 'parentheses)) (:quotation-marks (category-named 'quotation)) (otherwise (break "unexpected type: ~a" type))) :form (case type (:angle-brackets (category-named 'angle-brackets)) (:square-brackets (category-named 'square-brackets)) (:curly-brackets (category-named 'curly-brackets)) (:parentheses (category-named 'parentheses)) (:quotation-marks (category-named 'quotation)) (otherwise (break "unexpected type: ~a" type))) :referent (or referent (referent-for-vanila-edge)) :rule :default-edge-over-paired-punctuation))) (note? edge))) (interior-hook (label) "Does this label have an 'interior action' associated with it. Goes with define-interior-action and ties the label to the function to be executed." (cadr (member (case type (:angle-brackets :interior-of-angle-brackets) (:square-brackets :interior-of-square-brackets) (:curly-brackets :interior-of-curly-brackets) (:parentheses :interior-of-parentheses) (:quotation-marks :interior-of-quotation-marks) (otherwise (break "unexpected type: ~a" type))) (plist-for label))))) (cond ((eq type :single-quotation-marks) ;; these can be transparent (handle-single-quotes-span layout pos-before-open pos-after-close pos-after-open pos-before-close)) ((and first-edge (eq layout :single-span)) ;; Look for an action that's been defined for the category ;; on this edge for this type of punctuation. ;; See define-interior-action in analyzers/traversal/form.lisp (let ((hook (or (interior-hook (edge-category first-edge)) (interior-hook (edge-form first-edge))))) (if hook (then (tr :paired-punct-hook hook) (if (cfr-p hook) (do-paired-punct-cfr hook first-edge pos-before-open pos-after-close) (funcall hook first-edge pos-before-open pos-after-close pos-after-open pos-before-close layout))) (else ;; There's no special action for this edge label ;; so just make the default edge (tr :no-paired-punct-hook first-edge) (vanila-edge pos-before-open pos-after-close type :referent (edge-referent first-edge)) #+ignore (elevate-spanning-edge-over-paired-punctuation first-edge pos-before-open pos-after-close pos-after-open pos-before-close layout))))) (t ;; A more complex layout, which doesn't have a scheme for ;; hooks yet. (tr :pp-not-single-span layout) (vanila-edge pos-before-open pos-after-close type)))))) (defun do-paired-punct-cfr (cfr first-edge pos-before-leading-punct pos-after-closing-punct ;pos-after-leading-punct ;pos-before-closing-punct ) ;; Called from Do-paired-punctuation-interior when there is ;; a value for the paired-punct hook for the category of the ;; first edge and that value has been systematized into a cfr. ;; We make an edge from before the open punctuation mark to ;; after the closing mark following the directives on the cfr. (let ((label (cfr-category cfr)) (form (cfr-form cfr)) (referent (compute-paired-punct-referent cfr first-edge))) (let ((edge (make-edge-over-long-span pos-before-leading-punct pos-after-closing-punct label :form form :referent referent :rule cfr ))) edge ))) (defun compute-paired-punct-referent (cfr first-edge) This is written to finish a hook that was stubbed in 10/91 so it 's not clear that it 's the right thing to do today . ;; We're in the process of making an edge over a bracket pair ;; on the basis of the edge within it -- sort of cloning it. ;; To that end we want here to copy up the established referent ;; of that edge. (declare (special *break-on-unexpected-cases*)) (let ((referent-expression (cfr-referent cfr))) (case referent-expression (:the-single-edge (edge-referent first-edge)) (:right-daughter (let ((right-daughter (edge-right-daughter first-edge))) (unless (edge-p right-daughter) (when *break-on-unexpected-cases* (break "Doing the referent of the first edge within ~ paired punctuation~%for the case of the right-~ daughter but that field~%in ~A~%isn't an edge~%~%" right-daughter) (return-from compute-paired-punct-referent :error-in-trying-to-compute-referent))) (edge-referent right-daughter))) (otherwise (break "Unexpected referent-expression: ~a" referent-expression))))) ;;; function for edges spaning the paired punct. (defun elevate-spanning-edge-over-paired-punctuation (first-edge pos-before-open pos-after-close pos-after-open pos-before-close layout ) "Used by do-paired-punctuation-interior as a version of 'vanila-edge'. It just exposes the 'first-edge' as though the punctuation wasn't there" (declare (ignore layout ;; do-paired-punctuation-interior requires :single-span pos-after-open pos-before-close)) (make-chart-edge :category (edge-category first-edge) :form (edge-form first-edge) ;;(category-named 'paired-punctuation) ;; :referent (edge-referent first-edge) :starting-position pos-before-open :ending-position pos-after-close :left-daughter first-edge :right-daughter :single-term :rule 'elevate-spanning-edge-over-paired-punctuation))
null
https://raw.githubusercontent.com/ddmcdonald/sparser/5a16c18417f725575e8c8c4a58fde433519e86cb/Sparser/code/s/analyzers/traversal/dispatch.lisp
lisp
-*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*- File: "dispatch" Module: "analyzers;traversal:" and the pair passed in to here aren't the ones that are intended to match. 2/23/07 Removed the ecases. Added flag to permit long category so that we can write form rules against these if we want. reanalyzed when it appears in all caps or capitalized (7/23/13) Extended criteria for suspecting a hook. converting acronyms to proper nouns. (trace-sections) when there are multiple single-term edges this choice of accessor gives us the topmost (most recent) of those edges these are irrelevant, so we turn off the flag that controls later operations. then it's a dummy and we have to look underneath it Some stock tickers and such are ordinary words and could be captured as such. But they will be capitalized and we can overrule that with another edge That's enough evidence to recast the edge and take it as an acronym or ticker symbol, but we'll leave that set by sweep-to-span-parentheses if so, then there's probably a hook for it and we leave it alone. Alternatively, in some text-types it's the thing (break "finished between parens parse") update the flag that controls the hook these can be transparent Look for an action that's been defined for the category on this edge for this type of punctuation. See define-interior-action in analyzers/traversal/form.lisp There's no special action for this edge label so just make the default edge A more complex layout, which doesn't have a scheme for hooks yet. pos-after-leading-punct pos-before-closing-punct Called from Do-paired-punctuation-interior when there is a value for the paired-punct hook for the category of the first edge and that value has been systematized into a cfr. We make an edge from before the open punctuation mark to after the closing mark following the directives on the cfr. We're in the process of making an edge over a bracket pair on the basis of the edge within it -- sort of cloning it. To that end we want here to copy up the established referent of that edge. function for edges spaning the paired punct. do-paired-punctuation-interior requires :single-span (category-named 'paired-punctuation) ;;
copyright ( c ) 1994 - 1996,2011 - 2019 -- all rights reserved extensions copyright ( c ) 2010 BBNT Solutions LLC . All Rights Reserved Version : November 2019 initiated 6/15/94 v2.3 . 9/26 Fixed : multiple - initial - edges bug 9/13/95 fleshed out stub for hook being a cfr . 9/15 fixed a bug . 1/1/96 put in a trap for the ' span - is - longer - than - segment ' case , which seems to consistently indicate that there are embedded punct 's segments . 2/22/10 Added a form category identical to the the edge 0.1 ( 8/28/11 ) Cleaned up . Requiring : single - span to allow hook . ( 9/12/11 ) Added function for creating the obvious edge . 0.2 ( 2/11/13 ) Adding check for an ordinary word needing to be 0.3 ( 8/8/15 ) Added * special - acronym - handling * to stop it always (in-package :sparser) (unless (boundp '*allow-large-paired-interiors*) (defparameter *allow-large-paired-interiors* t)) (defparameter *special-acronym-handling* nil "Flag what will prohibit the creation of a proper name over single-spans of :all-caps. Set when the caller want to do the handling itself.") (defun do-paired-punctuation-interior (type pos-before-open pos-after-open pos-before-close pos-after-close) (declare (special *special-acronym-handling* *allow-large-paired-interiors* *treat-single-Capitalized-words-as-names*)) (tr :paired-punct-interior type pos-after-open pos-before-close) (let ((layout (analyze-segment-layout pos-after-open pos-before-close)) (first-edge (right-treetop-at/edge pos-after-open))) (when (word-p first-edge) (setq first-edge nil)) (case layout (:single-span This check probably dates from the original DM&P work (when (eq (edge-category first-edge) (category-named 'segment)) (setq first-edge (leftmost-daughter-edge first-edge) layout (analyze-segment-layout pos-after-open pos-before-close t))) (when (one-word-long? first-edge) (when (eq (pos-capitalization (pos-edge-starts-at first-edge)) :all-caps) to context to determine which one (eq (edge-form first-edge) (category-named 'proper-name)) (eq (edge-form first-edge) (category-named 'np))) to do . C.f . WHO for the World Health Organization (unless *treat-single-Capitalized-words-as-names* (lsp-break "About to convert ordinary word to proper name")) (convert-ordinary-word-edge-to-proper-name first-edge))))) (:contiguous-edges (parse-between-parentheses-boundaries pos-after-open pos-before-close) (right-treetop-at/edge pos-after-open))) (:span-is-longer-than-segment (unless *allow-large-paired-interiors* (error "~&~%Paired Punctuation:~ ~%The span of text between the ~A~ ~%at p~A and p~A is unreasonably large.~ ~%Probably there is some sort of undetected imbalance.~%" type (pos-token-index pos-before-open) (pos-token-index pos-before-close)))) ((or :null-span :no-edges :some-edges :has-unknown-words)) (otherwise (push-debug `(,pos-before-open ,pos-after-open ,pos-before-close ,pos-after-close)) (error "Unexpected layout between paired punctuation: ~a" layout))) (setq layout (analyze-segment-layout pos-after-open pos-before-close)) (tr :layout-between-punct layout) (labels ((referent-for-vanila-edge () "Edges need referents, even when they are semantically vacuous" (if (and first-edge (edge-p first-edge)) (edge-referent first-edge) (let ((type-category (category-named (if (eq type :quotation-marks) 'QUOTATION type)))) (find-or-make-individual type-category)))) (vanila-edge (pos-before-open pos-after-close type &key referent) "Just cover the span between the punctuation (inclusive) with an edge labeled according to the type of bracket." (tr :vanila-paired-edge pos-before-open pos-after-close) (let ((edge (make-edge-over-long-span pos-before-open pos-after-close (case type (:angle-brackets (category-named 'angle-brackets)) (:square-brackets (category-named 'square-brackets)) (:curly-brackets (category-named 'curly-brackets)) (:parentheses (category-named 'parentheses)) (:quotation-marks (category-named 'quotation)) (otherwise (break "unexpected type: ~a" type))) :form (case type (:angle-brackets (category-named 'angle-brackets)) (:square-brackets (category-named 'square-brackets)) (:curly-brackets (category-named 'curly-brackets)) (:parentheses (category-named 'parentheses)) (:quotation-marks (category-named 'quotation)) (otherwise (break "unexpected type: ~a" type))) :referent (or referent (referent-for-vanila-edge)) :rule :default-edge-over-paired-punctuation))) (note? edge))) (interior-hook (label) "Does this label have an 'interior action' associated with it. Goes with define-interior-action and ties the label to the function to be executed." (cadr (member (case type (:angle-brackets :interior-of-angle-brackets) (:square-brackets :interior-of-square-brackets) (:curly-brackets :interior-of-curly-brackets) (:parentheses :interior-of-parentheses) (:quotation-marks :interior-of-quotation-marks) (otherwise (break "unexpected type: ~a" type))) (plist-for label))))) (cond ((eq type :single-quotation-marks) (handle-single-quotes-span layout pos-before-open pos-after-close pos-after-open pos-before-close)) ((and first-edge (eq layout :single-span)) (let ((hook (or (interior-hook (edge-category first-edge)) (interior-hook (edge-form first-edge))))) (if hook (then (tr :paired-punct-hook hook) (if (cfr-p hook) (do-paired-punct-cfr hook first-edge pos-before-open pos-after-close) (funcall hook first-edge pos-before-open pos-after-close pos-after-open pos-before-close layout))) (else (tr :no-paired-punct-hook first-edge) (vanila-edge pos-before-open pos-after-close type :referent (edge-referent first-edge)) #+ignore (elevate-spanning-edge-over-paired-punctuation first-edge pos-before-open pos-after-close pos-after-open pos-before-close layout))))) (t (tr :pp-not-single-span layout) (vanila-edge pos-before-open pos-after-close type)))))) (defun do-paired-punct-cfr (cfr first-edge pos-before-leading-punct pos-after-closing-punct ) (let ((label (cfr-category cfr)) (form (cfr-form cfr)) (referent (compute-paired-punct-referent cfr first-edge))) (let ((edge (make-edge-over-long-span pos-before-leading-punct pos-after-closing-punct label :form form :referent referent :rule cfr ))) edge ))) (defun compute-paired-punct-referent (cfr first-edge) This is written to finish a hook that was stubbed in 10/91 so it 's not clear that it 's the right thing to do today . (declare (special *break-on-unexpected-cases*)) (let ((referent-expression (cfr-referent cfr))) (case referent-expression (:the-single-edge (edge-referent first-edge)) (:right-daughter (let ((right-daughter (edge-right-daughter first-edge))) (unless (edge-p right-daughter) (when *break-on-unexpected-cases* (break "Doing the referent of the first edge within ~ paired punctuation~%for the case of the right-~ daughter but that field~%in ~A~%isn't an edge~%~%" right-daughter) (return-from compute-paired-punct-referent :error-in-trying-to-compute-referent))) (edge-referent right-daughter))) (otherwise (break "Unexpected referent-expression: ~a" referent-expression))))) (defun elevate-spanning-edge-over-paired-punctuation (first-edge pos-before-open pos-after-close pos-after-open pos-before-close layout ) "Used by do-paired-punctuation-interior as a version of 'vanila-edge'. It just exposes the 'first-edge' as though the punctuation wasn't there" pos-after-open pos-before-close)) (make-chart-edge :category (edge-category first-edge) :referent (edge-referent first-edge) :starting-position pos-before-open :ending-position pos-after-close :left-daughter first-edge :right-daughter :single-term :rule 'elevate-spanning-edge-over-paired-punctuation))
b46c128db5e655f4be5d1fa6a92791057ebd7793fa22215ccbafdc0f25573831
notduncansmith/factfold
core.cljc
(ns factfold.core) (defn evaluate "Given a model, a state, and a new fact, return the model's next state" [model state fact] (reduce (fn [new-state property-map] (reduce-kv (fn [order-values property-name property-formula] (assoc order-values property-name (if (= (type property-formula) #?(:clj clojure.lang.PersistentVector :cljs cljs.core/PersistentVector)) (evaluate property-formula (get new-state property-name) fact) (property-formula new-state fact)))) new-state property-map)) state model)) (defn evaluate-all "Evaluate a sequence of facts in the same context" [model state facts] (reduce (partial evaluate model) state facts)) (defn advance! "Update the model state in a given atom with a given model and fact" [state-atom model fact] (swap! state-atom (partial evaluate model) fact)) ; commented until tested ( defn advance - async ! ; "Update the state in an agent (as opposed to an atom) with a given model and fact" ; [state-agent model fact] ; (send state-agent (partial evaluate model) fact)) (defn evolve! "Update the state in an atom with a model extracted from the state with `get-model` and a given fact (aka poor-man's π-calculus)" [state-atom get-model fact] (swap! state-atom #(evaluate (get-model %) % fact)))
null
https://raw.githubusercontent.com/notduncansmith/factfold/240f68018f32cd2c69396894e1c337dbe859fd03/src/factfold/core.cljc
clojure
commented until tested "Update the state in an agent (as opposed to an atom) with a given model and fact" [state-agent model fact] (send state-agent (partial evaluate model) fact))
(ns factfold.core) (defn evaluate "Given a model, a state, and a new fact, return the model's next state" [model state fact] (reduce (fn [new-state property-map] (reduce-kv (fn [order-values property-name property-formula] (assoc order-values property-name (if (= (type property-formula) #?(:clj clojure.lang.PersistentVector :cljs cljs.core/PersistentVector)) (evaluate property-formula (get new-state property-name) fact) (property-formula new-state fact)))) new-state property-map)) state model)) (defn evaluate-all "Evaluate a sequence of facts in the same context" [model state facts] (reduce (partial evaluate model) state facts)) (defn advance! "Update the model state in a given atom with a given model and fact" [state-atom model fact] (swap! state-atom (partial evaluate model) fact)) ( defn advance - async ! (defn evolve! "Update the state in an atom with a model extracted from the state with `get-model` and a given fact (aka poor-man's π-calculus)" [state-atom get-model fact] (swap! state-atom #(evaluate (get-model %) % fact)))
2788ed75757043527ef3c45b5417a57981ca6440214b7b61cd782bfa5ec459ad
anurudhp/CPHaskell
Heap.hs
module Heap where import Control.Monad import Control.Monad.ST import Data.Array.ST import Data.Array.Unboxed import Data.List (sort) import Data.Maybe (catMaybes) import Data.STRef data Heap a s = Heap {size :: STRef s Int, heapST :: STArray s Int a} mkHeap :: (Ord a) => Int -> ST s (Heap a s) mkHeap n = Heap <$> newSTRef 0 <*> newArray_ (0, n) swap :: Int -> Int -> Heap a s -> ST s () swap i j (Heap _ arr) = do u <- readArray arr i v <- readArray arr j writeArray arr i v writeArray arr j u reheap :: (Ord a) => Int -> Int -> Heap a s -> ST s () reheap idx lim heap@(Heap szptr arr) = when (idx < lim) $ do u <- readArray arr idx when (idx > 0) $ do let pidx = idx `div` 2 v <- readArray arr pidx when (u < v) $ do swap idx pidx heap reheap pidx lim heap cidx <- snd . minimum . catMaybes <$> forM [idx, 2 * idx, 2 * idx + 1] (\cidx -> do if cidx >= lim then return Nothing else do v <- readArray arr cidx return $ Just (v, cidx)) when (cidx /= idx) $ do swap idx cidx heap reheap cidx lim heap insert :: (Ord a) => a -> Heap a s -> ST s () insert a heap@(Heap szptr arr) = do sz <- readSTRef szptr writeArray arr sz a writeSTRef szptr (sz + 1) reheap sz (sz + 1) heap top :: Heap a s -> ST s a top (Heap _ arr) = readArray arr 0 empty :: Heap a s -> ST s Bool empty (Heap sz _) = (== 0) <$> readSTRef sz pop :: (Ord a) => Heap a s -> ST s a pop heap@(Heap szptr arr) = do t <- top heap sz <- subtract 1 <$> readSTRef szptr readArray arr sz >>= writeArray arr 0 writeSTRef szptr sz reheap 0 sz heap return t heapSortST :: (Ord a) => [a] -> ST s [a] heapSortST xs = do let n = length xs h <- mkHeap n forM_ xs (`insert` h) replicateM n (pop h) heapSort :: (Ord a) => [a] -> [a] heapSort xs = runST (heapSortST xs)
null
https://raw.githubusercontent.com/anurudhp/CPHaskell/67a55ab34c0365d42fb092c2378bc3972186970c/Templates/DataStructures/Heap.hs
haskell
module Heap where import Control.Monad import Control.Monad.ST import Data.Array.ST import Data.Array.Unboxed import Data.List (sort) import Data.Maybe (catMaybes) import Data.STRef data Heap a s = Heap {size :: STRef s Int, heapST :: STArray s Int a} mkHeap :: (Ord a) => Int -> ST s (Heap a s) mkHeap n = Heap <$> newSTRef 0 <*> newArray_ (0, n) swap :: Int -> Int -> Heap a s -> ST s () swap i j (Heap _ arr) = do u <- readArray arr i v <- readArray arr j writeArray arr i v writeArray arr j u reheap :: (Ord a) => Int -> Int -> Heap a s -> ST s () reheap idx lim heap@(Heap szptr arr) = when (idx < lim) $ do u <- readArray arr idx when (idx > 0) $ do let pidx = idx `div` 2 v <- readArray arr pidx when (u < v) $ do swap idx pidx heap reheap pidx lim heap cidx <- snd . minimum . catMaybes <$> forM [idx, 2 * idx, 2 * idx + 1] (\cidx -> do if cidx >= lim then return Nothing else do v <- readArray arr cidx return $ Just (v, cidx)) when (cidx /= idx) $ do swap idx cidx heap reheap cidx lim heap insert :: (Ord a) => a -> Heap a s -> ST s () insert a heap@(Heap szptr arr) = do sz <- readSTRef szptr writeArray arr sz a writeSTRef szptr (sz + 1) reheap sz (sz + 1) heap top :: Heap a s -> ST s a top (Heap _ arr) = readArray arr 0 empty :: Heap a s -> ST s Bool empty (Heap sz _) = (== 0) <$> readSTRef sz pop :: (Ord a) => Heap a s -> ST s a pop heap@(Heap szptr arr) = do t <- top heap sz <- subtract 1 <$> readSTRef szptr readArray arr sz >>= writeArray arr 0 writeSTRef szptr sz reheap 0 sz heap return t heapSortST :: (Ord a) => [a] -> ST s [a] heapSortST xs = do let n = length xs h <- mkHeap n forM_ xs (`insert` h) replicateM n (pop h) heapSort :: (Ord a) => [a] -> [a] heapSort xs = runST (heapSortST xs)
2e5c597dac57a8b59a04b0cac057f7841e0ca64ac51baca6243bfba240f8afd6
yariv/twoorl
twoorl_eng.erl
This file is part of Twoorl . %% %% Twoorl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or %% (at your option) any later version. %% %% Twoorl 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 . If not , see < / > . -module(twoorl_eng). -export([bundle/1]). bundle(Tag) -> case Tag of language -> <<"english">>; %% layout login -> <<"login">>; register -> <<"register">>; logged_in_as -> <<"logged in as">>; settings -> <<"settings">>; logout -> <<"logout">>; get_source -> <<"Get the <a href=\"\">" "source code</a>">>; %% navbar home -> <<"home">>; replies -> <<"replies">>; me -> <<"me">>; everyone -> <<"everyone">>; %% login page login_cap -> <<"Login">>; username -> <<"username">>; password -> <<"password">>; not_member -> <<"Not a member?">>; login_submit -> <<"login">>; %% register page note : ' username ' , ' password ' and ' Login_cap ' are taken from % login page section register_cap -> <<"Register">>; email -> <<"email">>; password2 -> <<"re-enter password">>; already_member -> <<"Already a member?">>; %% home page upto -> <<"What are you up to?">>; twitter_msg -> <<"Automatic posting to Twitter enabled for " "non-replies">>; send -> <<"send">>; %% main page public_timeline -> <<"Public timeline">>; %% users page {no_user, Username} -> [<<"The user '">>, Username, <<"' doesn't exist">>]; {timeline_of, Username} -> [Username, <<"'s timeline">>]; following -> <<"following">>; followers -> <<"followers">>; follow -> <<"follow">>; unfollow -> <<"unfollow">>; %% friends page {friends_of, Userlink} -> [<<"People ">>, Userlink, <<" follows">>]; {followers_of, Userlink} -> [Userlink, <<"'s followers">>]; {no_friends, Username} -> [Username, <<" isn't following anyone">>]; {no_followers, Username} -> [Username, <<" has no followers">>]; %% settings page settings_cap -> <<"Settings">>; use_gravatar -> <<"Use <a href=\"\" " "target=\"_blank\">Gravatar</a>?">>; profile_bg -> <<"Profile background">>; profile_bg_help -> <<"Enter the url for your profile background image " "(leave blank to use the default background):">>; twitter_help -> <<"You may provide your Twitter account details to have " "your twoorls automatically posted to Twitter.<br/><br/>" "Only twoorls that don't contain replies (e.g." "\"@sergey\") will be posted to Twitter.">>; twitter_username -> <<"Twitter username:">>; twitter_password -> <<"Twitter password:">>; twitter_auto -> <<"Automatically post my Twoorls to Twitter?">>; submit -> <<"submit">>; %% error messages {missing_field, Field} -> [<<"The ">>, Field, <<" field is required">>]; {username_taken, Val} -> [<<"The username '">>, Val, <<"' is taken">>]; {invalid_username, Val} -> [<<"The username '">>, Val, <<"' is invalid. Only letters, numbers and underscore ('_') " "are accepted">>]; invalid_login -> <<"Invalid username or password">>; {too_short, Field, Min} -> [<<"The ">>, Field, <<" is too short (">>, Min, <<" chars minimum)">>]; password_mismatch -> <<"The password values didn't match">>; twitter_unauthorized -> <<"Twitter rejected the username/password combination you " "provided">>; twitter_authorization_error -> <<"Couldn't connect to Twitter. Please try again later.">>; {invalid_url, Field} -> [<<"The ">>, Field, <<" URL must start with 'http://'">>]; %% confirmation messages settings_updated -> [<<"Your settings have been updated successfully">>]; %% miscellaneous {seconds_ago, Val} -> [Val, <<" seconds ago">>]; {minutes_ago, Val} -> [Val, <<" minutes ago">>]; {hours_ago, Val} -> [Val, <<" hours ago">>]; {days_ago, Val} -> [Val, <<" days ago">>] end.
null
https://raw.githubusercontent.com/yariv/twoorl/77b6bea2e29283d09a95d8db131b916e16d2960b/src/bundles/twoorl_eng.erl
erlang
Twoorl is free software: you can redistribute it and/or modify (at your option) any later version. Twoorl 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. layout navbar login page register page login page section home page main page users page friends page settings page error messages confirmation messages miscellaneous
This file is part of Twoorl . it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License along with . If not , see < / > . -module(twoorl_eng). -export([bundle/1]). bundle(Tag) -> case Tag of language -> <<"english">>; login -> <<"login">>; register -> <<"register">>; logged_in_as -> <<"logged in as">>; settings -> <<"settings">>; logout -> <<"logout">>; get_source -> <<"Get the <a href=\"\">" "source code</a>">>; home -> <<"home">>; replies -> <<"replies">>; me -> <<"me">>; everyone -> <<"everyone">>; login_cap -> <<"Login">>; username -> <<"username">>; password -> <<"password">>; not_member -> <<"Not a member?">>; login_submit -> <<"login">>; note : ' username ' , ' password ' and ' Login_cap ' are taken from register_cap -> <<"Register">>; email -> <<"email">>; password2 -> <<"re-enter password">>; already_member -> <<"Already a member?">>; upto -> <<"What are you up to?">>; twitter_msg -> <<"Automatic posting to Twitter enabled for " "non-replies">>; send -> <<"send">>; public_timeline -> <<"Public timeline">>; {no_user, Username} -> [<<"The user '">>, Username, <<"' doesn't exist">>]; {timeline_of, Username} -> [Username, <<"'s timeline">>]; following -> <<"following">>; followers -> <<"followers">>; follow -> <<"follow">>; unfollow -> <<"unfollow">>; {friends_of, Userlink} -> [<<"People ">>, Userlink, <<" follows">>]; {followers_of, Userlink} -> [Userlink, <<"'s followers">>]; {no_friends, Username} -> [Username, <<" isn't following anyone">>]; {no_followers, Username} -> [Username, <<" has no followers">>]; settings_cap -> <<"Settings">>; use_gravatar -> <<"Use <a href=\"\" " "target=\"_blank\">Gravatar</a>?">>; profile_bg -> <<"Profile background">>; profile_bg_help -> <<"Enter the url for your profile background image " "(leave blank to use the default background):">>; twitter_help -> <<"You may provide your Twitter account details to have " "your twoorls automatically posted to Twitter.<br/><br/>" "Only twoorls that don't contain replies (e.g." "\"@sergey\") will be posted to Twitter.">>; twitter_username -> <<"Twitter username:">>; twitter_password -> <<"Twitter password:">>; twitter_auto -> <<"Automatically post my Twoorls to Twitter?">>; submit -> <<"submit">>; {missing_field, Field} -> [<<"The ">>, Field, <<" field is required">>]; {username_taken, Val} -> [<<"The username '">>, Val, <<"' is taken">>]; {invalid_username, Val} -> [<<"The username '">>, Val, <<"' is invalid. Only letters, numbers and underscore ('_') " "are accepted">>]; invalid_login -> <<"Invalid username or password">>; {too_short, Field, Min} -> [<<"The ">>, Field, <<" is too short (">>, Min, <<" chars minimum)">>]; password_mismatch -> <<"The password values didn't match">>; twitter_unauthorized -> <<"Twitter rejected the username/password combination you " "provided">>; twitter_authorization_error -> <<"Couldn't connect to Twitter. Please try again later.">>; {invalid_url, Field} -> [<<"The ">>, Field, <<" URL must start with 'http://'">>]; settings_updated -> [<<"Your settings have been updated successfully">>]; {seconds_ago, Val} -> [Val, <<" seconds ago">>]; {minutes_ago, Val} -> [Val, <<" minutes ago">>]; {hours_ago, Val} -> [Val, <<" hours ago">>]; {days_ago, Val} -> [Val, <<" days ago">>] end.
42551c6f1ef2fd395da8daa6d3c6d40896b0d89808663f26f7c0cd4736fff45e
shnarazk/mios
Mios.hs
# LANGUAGE TupleSections , ViewPatterns # TupleSections , ViewPatterns #-} {-# LANGUAGE Safe #-} | Minisat - based Implementation and Optimization Study on SAT solver module SAT.Mios ( -- * Interface to the core of solver versionId , CNFDescription (..) , module SAT.Mios.OptionParser , runSolver , solveSAT , solveSATWithConfiguration , solve , getModel -- * Assignment Validator , validateAssignment , validate -- * For standalone programs , executeSolverOn , executeSolver , executeValidatorOn , executeValidator -- * File IO , parseCNFfile , dumpAssigmentAsCNF ) where import Control.Monad ((<=<), unless, void, when) import Data.Char import qualified Data.ByteString.Char8 as B import Data.List import Data.Maybe (fromMaybe) import Numeric (showFFloat) import System.CPUTime import System.Exit import System.IO import SAT.Mios.Types import SAT.Mios.Solver import SAT.Mios.Main import SAT.Mios.OptionParser import SAT.Mios.Validator -- | version name versionId :: String versionId = "Mios #MultiConflict based on 1.4.0 -- " reportElapsedTime :: Bool -> String -> Integer -> IO Integer reportElapsedTime False _ _ = return 0 reportElapsedTime _ _ 0 = getCPUTime reportElapsedTime _ mes t = do now <- getCPUTime let toSecond = 1000000000000 :: Double hPutStr stderr mes hPutStrLn stderr $ showFFloat (Just 3) (fromIntegral (now - t) / toSecond) " sec" return now -- | executes a solver on the given CNF file. This is the simplest entry to standalone programs ; not for programs . executeSolverOn :: FilePath -> IO () executeSolverOn path = executeSolver (miosDefaultOption { _targetFile = Just path }) | executes a solver on the given ' arg : : ' . -- This is another entry point for standalone programs. executeSolver :: MiosProgramOption -> IO () executeSolver opts@(_targetFile -> target@(Just cnfFile)) = do t0 <- reportElapsedTime (_confTimeProbe opts) "" 0 (desc, cls) <- parseHeader target <$> B.readFile cnfFile when (_numberOfVariables desc == 0) $ error $ "couldn't load " ++ show cnfFile let header = "## " ++ pathHeader cnfFile s <- newSolver (toMiosConf opts) desc injectClauses s desc cls t1 <- reportElapsedTime (_confTimeProbe opts) (header ++ showPath cnfFile ++ ", Parse: ") t0 when (_confVerbose opts) $ do nc <- nClauses s hPutStrLn stderr $ cnfFile ++ " was loaded: #v = " ++ show (nVars s, _numberOfVariables desc) ++ " #c = " ++ show (nc, _numberOfClauses desc) res <- simplifyDB s when ( _ confVerbose opts ) $ hPutStrLn stderr $ " ` simplifyDB ` : " + + show res when ( _ confVerbose opts ) $ hPutStrLn stderr $ " ` simplifyDB ` : " + + show res result <- if res then solve s [] else return False aborted <- (0 ==) <$> getStat s SatisfiabilityValue let debug = _confDebugPath opts case result of _ | debug && aborted && _confDumpStat opts -> return () _ | debug && aborted && _confStatProbe opts -> hPutStrLn stderr "ABORT" _ | debug && aborted && _confNoAnswer opts -> hPutStrLn stderr "ABORT" _ | debug && aborted -> putStrLn $ "ABORT: " ++ show result True | _confNoAnswer opts -> when (_confVerbose opts) $ hPutStrLn stderr "SATISFIABLE" True | _confStatProbe opts -> hPrint stderr =<< getModel s True -> print =<< getModel s False | _confNoAnswer opts -> when (_confVerbose opts) $ hPutStrLn stderr "UNSATISFIABLE" False | _confStatProbe opts -> hPutStrLn stderr "UNSAT" False -> putStrLn "[]" case _outputFile opts of Just fname -> dumpAssigmentAsCNF fname result =<< getModel s Nothing -> return () t2 <- reportElapsedTime (_confTimeProbe opts) (header ++ showPath cnfFile ++ ", Solve: ") t1 when (result && _confCheckAnswer opts) $ do asg <- getModel s s' <- newSolver (toMiosConf opts) desc injectClauses s' desc cls good <- validate s' desc asg if _confVerbose opts then hPutStrLn stderr $ if good then "A vaild answer" else "Internal error: mios returns a wrong answer" else unless good $ hPutStrLn stderr "Internal error: mios returns a wrong answer" void $ reportElapsedTime (_confTimeProbe opts) (header ++ showPath cnfFile ++ ", Validate: ") t2 void $ reportElapsedTime (_confTimeProbe opts) (header ++ showPath cnfFile ++ ", Total: ") t0 when (_confStatProbe opts) $ do let output = stdout hPutStr output $ fromMaybe "" ((++ ", ") <$> _confStatHeader opts) hPutStr output $ "Solver: " ++ show versionId ++ ", " hPutStr output $ showConf (config s) ++ ", " hPutStr output $ "File: \"" ++ showPath cnfFile ++ "\", " hPutStr output $ "NumOfVariables: " ++ show (_numberOfVariables desc) ++ ", " hPutStr output $ "NumOfClauses: " ++ show (_numberOfClauses desc) ++ ", " stat1 <- intercalate ", " . map (\(k, v) -> show k ++ ": " ++ show v) <$> getStats s hPutStr output stat1 hPutStrLn output "" when (_confDumpStat opts) $ do asg <- getModel s s' <- newSolver (toMiosConf opts) desc injectClauses s' desc cls good <- validate s' desc asg unless good $ setStat s SatisfiabilityValue BottomBool putStrLn =<< dumpToString (fromMaybe versionId (_confStatHeader opts)) s desc executeSolver _ = return () -- | new top-level interface that returns: -- -- * conflicting literal set :: Left [Int] -- * satisfiable assignment :: Right [Int] -- runSolver :: Traversable t => MiosConfiguration -> CNFDescription -> t [Int] -> IO (Either [Int] [Int]) runSolver m d c = do s <- newSolver m d mapM_ ((s `addClause`) <=< (newStackFromList . map int2lit)) c noConf <- simplifyDB s if noConf then do x <- solve s [] if x then Right <$> getModel s else Left . map lit2int <$> asList (conflicts s) else return $ Left [] | The easiest interface for programs . This returns the result @::[[Int]]@ for a given @(CNFDescription , [ [ Int]])@. The first argument @target@ can be build by @Just target < - cnfFromFile targetfile@. The second part of the first argument is a list of vector , which 0th element is the number of its real elements . solveSAT :: Traversable m => CNFDescription -> m [Int] -> IO [Int] solveSAT = solveSATWithConfiguration defaultConfiguration | solves the problem ( 2rd arg ) under the configuration ( 1st arg ) . -- and returns an assignment as list of literals :: Int. solveSATWithConfiguration :: Traversable m => MiosConfiguration -> CNFDescription -> m [Int] -> IO [Int] solveSATWithConfiguration conf desc cls = do s <- newSolver conf desc mapM _ ( const ( newVar s ) ) [ 0 .. _ numberOfVariables desc - 1 ] mapM_ ((s `addClause`) <=< (newStackFromList . map int2lit)) cls noConf <- simplifyDB s if noConf then do result <- solve s [] if result then getModel s else return [] else return [] | validates a given assignment from STDIN for the CNF file ( 2nd arg ) . -- this is the entry point for standalone programs. executeValidatorOn :: FilePath -> IO () executeValidatorOn path = executeValidator (miosDefaultOption { _targetFile = Just path }) | validates a given assignment for the problem ( 2nd arg ) . -- This is another entry point for standalone programs; see app/mios.hs. executeValidator :: MiosProgramOption -> IO () executeValidator opts@(_targetFile -> target@(Just cnfFile)) = do (desc, cls) <- parseHeader target <$> B.readFile cnfFile when (_numberOfVariables desc == 0) . error $ "couldn't load " ++ show cnfFile s <- newSolver (toMiosConf opts) desc injectClauses s desc cls when (_confVerbose opts) $ hPutStrLn stderr $ cnfFile ++ " was loaded: #v = " ++ show (_numberOfVariables desc) ++ " #c = " ++ show (_numberOfClauses desc) when (_confVerbose opts) $ do nc <- nClauses s nl <- nLearnts s hPutStrLn stderr $ "(nv, nc, nl) = " ++ show (nVars s, nc, nl) asg <- read <$> getContents unless (_confNoAnswer opts) $ print asg result <- validate s desc (asg :: [Int]) if result then putStrLn ("It's a valid assignment for " ++ cnfFile ++ ".") >> exitSuccess else putStrLn ("It's an invalid assignment for " ++ cnfFile ++ ".") >> exitFailure executeValidator _ = return () | returns True if a given assignment ( 2nd arg ) satisfies the problem ( 1st arg ) . if you want to check the @answer@ which a @slover@ returned , run @solver ` validate ` answer@ , where ' validate ' @ : : t = > Solver - > t Lit - > IO Bool@. validateAssignment :: (Traversable m, Traversable n) => CNFDescription -> m [Int] -> n Int -> IO Bool validateAssignment desc cls asg = do s <- newSolver defaultConfiguration desc mapM_ ((s `addClause`) <=< (newStackFromList . map int2lit)) cls validate s desc asg -- | dumps an assigment to file. 2nd arg is -- * if the assigment is satisfiable assigment -- -- * @False@ if not -- -- >>> do y <- solve s ... ; dumpAssigmentAsCNF "result.cnf" y <$> model s -- dumpAssigmentAsCNF :: FilePath -> Bool -> [Int] -> IO () dumpAssigmentAsCNF fname False _ = withFile fname WriteMode $ \h -> hPutStrLn h "UNSAT" dumpAssigmentAsCNF fname True l = withFile fname WriteMode $ \h -> do hPutStrLn h "SAT"; hPutStrLn h . unwords $ map show l -------------------------------------------------------------------------------- DIMACS CNF Reader -------------------------------------------------------------------------------- -- | parse a cnf file parseCNFfile :: Maybe FilePath -> IO (CNFDescription, [[Int]]) parseCNFfile (Just cnfFile) = do (desc, bytes) <- parseHeader (Just cnfFile) <$> B.readFile cnfFile (desc, ) <$> parseClauses desc bytes parseCNFfile Nothing = error "no file designated" parseHeader :: Maybe FilePath -> B.ByteString -> (CNFDescription, B.ByteString) parseHeader target bs = if B.head bs == 'p' then (parseP l, B.tail bs') else parseHeader target (B.tail bs') where (l, bs') = B.span ('\n' /=) bs format : p cnf n m , length " p cnf " = = 5 parseP line = case B.readInt $ B.dropWhile (`elem` " \t") (B.drop 5 line) of Just (x, second) -> case B.readInt (B.dropWhile (`elem` " \t") second) of Just (y, _) -> CNFDescription target x y _ -> CNFDescription target 0 0 _ -> CNFDescription target 0 0 parseClauses :: CNFDescription -> B.ByteString -> IO [[Int]] parseClauses (CNFDescription _ nv nc) bs = do let maxLit = int2lit $ negate nv buffer <- newVec (maxLit + 1) 0 let loop :: Int -> B.ByteString -> [[Int]] -> IO [[Int]] loop ((< nc) -> False) _ l = return l loop i b l = do (c, b') <- readClause' buffer b loop (i + 1) b' (c : l) loop 0 bs [] injectClauses :: Solver -> CNFDescription -> B.ByteString -> IO () injectClauses s (CNFDescription _ nv nc) bs = do let maxLit = int2lit $ negate nv buffer <- newVec (maxLit + 1) 0 polvec <- newVec (maxLit + 1) 0 let loop :: Int -> B.ByteString -> IO () loop ((< nc) -> False) _ = return () loop i b = loop (i + 1) =<< readClause s buffer polvec b loop 0 bs -- static polarity let asg = assigns s checkPolarity :: Int -> IO () checkPolarity ((< nv) -> False) = return () checkPolarity v = do p <- getNth polvec $ var2lit v True n <- getNth polvec $ var2lit v False when (p == LiftedFalse || n == LiftedFalse) $ setNth asg v p checkPolarity $ v + 1 checkPolarity 1 skipWhitespace :: B.ByteString -> B.ByteString skipWhitespace s | elem c " \t\n" = skipWhitespace $ B.tail s | otherwise = s where c = B.head s -- | skip comment lines -- __Pre-condition:__ we are on the benngining of a line skipComments :: B.ByteString -> B.ByteString skipComments s | c == 'c' = skipComments . B.tail . B.dropWhile (/= '\n') $ s | otherwise = s where c = B.head s parseInt :: B.ByteString -> (Int, B.ByteString) parseInt st = do let zero = ord '0' loop :: B.ByteString -> Int -> (Int, B.ByteString) loop s val = case B.head s of c | '0' <= c && c <= '9' -> loop (B.tail s) (val * 10 + ord c - zero) _ -> (val, B.tail s) case B.head st of '-' -> let (k, x) = loop (B.tail st) 0 in (negate k, x) '+' -> loop st (0 :: Int) c | '0' <= c && c <= '9' -> loop st 0 _ -> error "PARSE ERROR! Unexpected char" readClause :: Solver -> Stack -> Vec Int -> B.ByteString -> IO B.ByteString readClause s buffer bvec stream = do let loop :: Int -> B.ByteString -> IO B.ByteString loop i b = do let (k, b') = parseInt $ skipWhitespace b if k == 0 then do putStrLn . ( " clause : " + + ) . show . map lit2int = < < asList stack setNth buffer 0 $ i - 1 void $ addClause s buffer return b' else do let l = int2lit k setNth buffer i l setNth bvec l LiftedTrue loop (i + 1) b' loop 1 . skipComments . skipWhitespace $ stream readClause' :: Stack -> B.ByteString -> IO ([Int], B.ByteString) readClause' buffer stream = do let loop :: Int -> B.ByteString -> IO ([Int], B.ByteString) loop i b = do let (k, b') = parseInt $ skipWhitespace b if k == 0 then do putStrLn . ( " clause : " + + ) . show . map lit2int = < < asList stack setNth buffer 0 $ i - 1 (, b') <$> (take <$> get' buffer <*> asList buffer) else do setNth buffer i k loop (i + 1) b' loop 1 . skipComments . skipWhitespace $ stream showPath :: FilePath -> String showPath str = {- replicate (len - length basename) ' ' ++ -} if elem '/' str then basename else basename' where len = 32 basename = reverse . takeWhile (/= '/') . reverse $ str basename' = take len str pathHeader :: FilePath -> String pathHeader str = replicate (len - length basename) ' ' where len = 32 basename = reverse . takeWhile (/= '/') . reverse $ str showConf :: MiosConfiguration -> String showConf (MiosConfiguration vr pl _ _ _ _) = "VarDecayRate: " ++ showFFloat (Just 3) vr "" ++ ", PropagationLimit: " ++ show pl
null
https://raw.githubusercontent.com/shnarazk/mios/d032d761d73224f981a07ec2ea90936db6f495e8/MultiConflict/SAT/Mios.hs
haskell
# LANGUAGE Safe # * Interface to the core of solver * Assignment Validator * For standalone programs * File IO | version name | executes a solver on the given CNF file. This is another entry point for standalone programs. | new top-level interface that returns: * conflicting literal set :: Left [Int] * satisfiable assignment :: Right [Int] and returns an assignment as list of literals :: Int. this is the entry point for standalone programs. This is another entry point for standalone programs; see app/mios.hs. | dumps an assigment to file. * @False@ if not >>> do y <- solve s ... ; dumpAssigmentAsCNF "result.cnf" y <$> model s ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ | parse a cnf file static polarity | skip comment lines __Pre-condition:__ we are on the benngining of a line replicate (len - length basename) ' ' ++
# LANGUAGE TupleSections , ViewPatterns # TupleSections , ViewPatterns #-} | Minisat - based Implementation and Optimization Study on SAT solver module SAT.Mios ( versionId , CNFDescription (..) , module SAT.Mios.OptionParser , runSolver , solveSAT , solveSATWithConfiguration , solve , getModel , validateAssignment , validate , executeSolverOn , executeSolver , executeValidatorOn , executeValidator , parseCNFfile , dumpAssigmentAsCNF ) where import Control.Monad ((<=<), unless, void, when) import Data.Char import qualified Data.ByteString.Char8 as B import Data.List import Data.Maybe (fromMaybe) import Numeric (showFFloat) import System.CPUTime import System.Exit import System.IO import SAT.Mios.Types import SAT.Mios.Solver import SAT.Mios.Main import SAT.Mios.OptionParser import SAT.Mios.Validator versionId :: String versionId = "Mios #MultiConflict based on 1.4.0 -- " reportElapsedTime :: Bool -> String -> Integer -> IO Integer reportElapsedTime False _ _ = return 0 reportElapsedTime _ _ 0 = getCPUTime reportElapsedTime _ mes t = do now <- getCPUTime let toSecond = 1000000000000 :: Double hPutStr stderr mes hPutStrLn stderr $ showFFloat (Just 3) (fromIntegral (now - t) / toSecond) " sec" return now This is the simplest entry to standalone programs ; not for programs . executeSolverOn :: FilePath -> IO () executeSolverOn path = executeSolver (miosDefaultOption { _targetFile = Just path }) | executes a solver on the given ' arg : : ' . executeSolver :: MiosProgramOption -> IO () executeSolver opts@(_targetFile -> target@(Just cnfFile)) = do t0 <- reportElapsedTime (_confTimeProbe opts) "" 0 (desc, cls) <- parseHeader target <$> B.readFile cnfFile when (_numberOfVariables desc == 0) $ error $ "couldn't load " ++ show cnfFile let header = "## " ++ pathHeader cnfFile s <- newSolver (toMiosConf opts) desc injectClauses s desc cls t1 <- reportElapsedTime (_confTimeProbe opts) (header ++ showPath cnfFile ++ ", Parse: ") t0 when (_confVerbose opts) $ do nc <- nClauses s hPutStrLn stderr $ cnfFile ++ " was loaded: #v = " ++ show (nVars s, _numberOfVariables desc) ++ " #c = " ++ show (nc, _numberOfClauses desc) res <- simplifyDB s when ( _ confVerbose opts ) $ hPutStrLn stderr $ " ` simplifyDB ` : " + + show res when ( _ confVerbose opts ) $ hPutStrLn stderr $ " ` simplifyDB ` : " + + show res result <- if res then solve s [] else return False aborted <- (0 ==) <$> getStat s SatisfiabilityValue let debug = _confDebugPath opts case result of _ | debug && aborted && _confDumpStat opts -> return () _ | debug && aborted && _confStatProbe opts -> hPutStrLn stderr "ABORT" _ | debug && aborted && _confNoAnswer opts -> hPutStrLn stderr "ABORT" _ | debug && aborted -> putStrLn $ "ABORT: " ++ show result True | _confNoAnswer opts -> when (_confVerbose opts) $ hPutStrLn stderr "SATISFIABLE" True | _confStatProbe opts -> hPrint stderr =<< getModel s True -> print =<< getModel s False | _confNoAnswer opts -> when (_confVerbose opts) $ hPutStrLn stderr "UNSATISFIABLE" False | _confStatProbe opts -> hPutStrLn stderr "UNSAT" False -> putStrLn "[]" case _outputFile opts of Just fname -> dumpAssigmentAsCNF fname result =<< getModel s Nothing -> return () t2 <- reportElapsedTime (_confTimeProbe opts) (header ++ showPath cnfFile ++ ", Solve: ") t1 when (result && _confCheckAnswer opts) $ do asg <- getModel s s' <- newSolver (toMiosConf opts) desc injectClauses s' desc cls good <- validate s' desc asg if _confVerbose opts then hPutStrLn stderr $ if good then "A vaild answer" else "Internal error: mios returns a wrong answer" else unless good $ hPutStrLn stderr "Internal error: mios returns a wrong answer" void $ reportElapsedTime (_confTimeProbe opts) (header ++ showPath cnfFile ++ ", Validate: ") t2 void $ reportElapsedTime (_confTimeProbe opts) (header ++ showPath cnfFile ++ ", Total: ") t0 when (_confStatProbe opts) $ do let output = stdout hPutStr output $ fromMaybe "" ((++ ", ") <$> _confStatHeader opts) hPutStr output $ "Solver: " ++ show versionId ++ ", " hPutStr output $ showConf (config s) ++ ", " hPutStr output $ "File: \"" ++ showPath cnfFile ++ "\", " hPutStr output $ "NumOfVariables: " ++ show (_numberOfVariables desc) ++ ", " hPutStr output $ "NumOfClauses: " ++ show (_numberOfClauses desc) ++ ", " stat1 <- intercalate ", " . map (\(k, v) -> show k ++ ": " ++ show v) <$> getStats s hPutStr output stat1 hPutStrLn output "" when (_confDumpStat opts) $ do asg <- getModel s s' <- newSolver (toMiosConf opts) desc injectClauses s' desc cls good <- validate s' desc asg unless good $ setStat s SatisfiabilityValue BottomBool putStrLn =<< dumpToString (fromMaybe versionId (_confStatHeader opts)) s desc executeSolver _ = return () runSolver :: Traversable t => MiosConfiguration -> CNFDescription -> t [Int] -> IO (Either [Int] [Int]) runSolver m d c = do s <- newSolver m d mapM_ ((s `addClause`) <=< (newStackFromList . map int2lit)) c noConf <- simplifyDB s if noConf then do x <- solve s [] if x then Right <$> getModel s else Left . map lit2int <$> asList (conflicts s) else return $ Left [] | The easiest interface for programs . This returns the result @::[[Int]]@ for a given @(CNFDescription , [ [ Int]])@. The first argument @target@ can be build by @Just target < - cnfFromFile targetfile@. The second part of the first argument is a list of vector , which 0th element is the number of its real elements . solveSAT :: Traversable m => CNFDescription -> m [Int] -> IO [Int] solveSAT = solveSATWithConfiguration defaultConfiguration | solves the problem ( 2rd arg ) under the configuration ( 1st arg ) . solveSATWithConfiguration :: Traversable m => MiosConfiguration -> CNFDescription -> m [Int] -> IO [Int] solveSATWithConfiguration conf desc cls = do s <- newSolver conf desc mapM _ ( const ( newVar s ) ) [ 0 .. _ numberOfVariables desc - 1 ] mapM_ ((s `addClause`) <=< (newStackFromList . map int2lit)) cls noConf <- simplifyDB s if noConf then do result <- solve s [] if result then getModel s else return [] else return [] | validates a given assignment from STDIN for the CNF file ( 2nd arg ) . executeValidatorOn :: FilePath -> IO () executeValidatorOn path = executeValidator (miosDefaultOption { _targetFile = Just path }) | validates a given assignment for the problem ( 2nd arg ) . executeValidator :: MiosProgramOption -> IO () executeValidator opts@(_targetFile -> target@(Just cnfFile)) = do (desc, cls) <- parseHeader target <$> B.readFile cnfFile when (_numberOfVariables desc == 0) . error $ "couldn't load " ++ show cnfFile s <- newSolver (toMiosConf opts) desc injectClauses s desc cls when (_confVerbose opts) $ hPutStrLn stderr $ cnfFile ++ " was loaded: #v = " ++ show (_numberOfVariables desc) ++ " #c = " ++ show (_numberOfClauses desc) when (_confVerbose opts) $ do nc <- nClauses s nl <- nLearnts s hPutStrLn stderr $ "(nv, nc, nl) = " ++ show (nVars s, nc, nl) asg <- read <$> getContents unless (_confNoAnswer opts) $ print asg result <- validate s desc (asg :: [Int]) if result then putStrLn ("It's a valid assignment for " ++ cnfFile ++ ".") >> exitSuccess else putStrLn ("It's an invalid assignment for " ++ cnfFile ++ ".") >> exitFailure executeValidator _ = return () | returns True if a given assignment ( 2nd arg ) satisfies the problem ( 1st arg ) . if you want to check the @answer@ which a @slover@ returned , run @solver ` validate ` answer@ , where ' validate ' @ : : t = > Solver - > t Lit - > IO Bool@. validateAssignment :: (Traversable m, Traversable n) => CNFDescription -> m [Int] -> n Int -> IO Bool validateAssignment desc cls asg = do s <- newSolver defaultConfiguration desc mapM_ ((s `addClause`) <=< (newStackFromList . map int2lit)) cls validate s desc asg 2nd arg is * if the assigment is satisfiable assigment dumpAssigmentAsCNF :: FilePath -> Bool -> [Int] -> IO () dumpAssigmentAsCNF fname False _ = withFile fname WriteMode $ \h -> hPutStrLn h "UNSAT" dumpAssigmentAsCNF fname True l = withFile fname WriteMode $ \h -> do hPutStrLn h "SAT"; hPutStrLn h . unwords $ map show l DIMACS CNF Reader parseCNFfile :: Maybe FilePath -> IO (CNFDescription, [[Int]]) parseCNFfile (Just cnfFile) = do (desc, bytes) <- parseHeader (Just cnfFile) <$> B.readFile cnfFile (desc, ) <$> parseClauses desc bytes parseCNFfile Nothing = error "no file designated" parseHeader :: Maybe FilePath -> B.ByteString -> (CNFDescription, B.ByteString) parseHeader target bs = if B.head bs == 'p' then (parseP l, B.tail bs') else parseHeader target (B.tail bs') where (l, bs') = B.span ('\n' /=) bs format : p cnf n m , length " p cnf " = = 5 parseP line = case B.readInt $ B.dropWhile (`elem` " \t") (B.drop 5 line) of Just (x, second) -> case B.readInt (B.dropWhile (`elem` " \t") second) of Just (y, _) -> CNFDescription target x y _ -> CNFDescription target 0 0 _ -> CNFDescription target 0 0 parseClauses :: CNFDescription -> B.ByteString -> IO [[Int]] parseClauses (CNFDescription _ nv nc) bs = do let maxLit = int2lit $ negate nv buffer <- newVec (maxLit + 1) 0 let loop :: Int -> B.ByteString -> [[Int]] -> IO [[Int]] loop ((< nc) -> False) _ l = return l loop i b l = do (c, b') <- readClause' buffer b loop (i + 1) b' (c : l) loop 0 bs [] injectClauses :: Solver -> CNFDescription -> B.ByteString -> IO () injectClauses s (CNFDescription _ nv nc) bs = do let maxLit = int2lit $ negate nv buffer <- newVec (maxLit + 1) 0 polvec <- newVec (maxLit + 1) 0 let loop :: Int -> B.ByteString -> IO () loop ((< nc) -> False) _ = return () loop i b = loop (i + 1) =<< readClause s buffer polvec b loop 0 bs let asg = assigns s checkPolarity :: Int -> IO () checkPolarity ((< nv) -> False) = return () checkPolarity v = do p <- getNth polvec $ var2lit v True n <- getNth polvec $ var2lit v False when (p == LiftedFalse || n == LiftedFalse) $ setNth asg v p checkPolarity $ v + 1 checkPolarity 1 skipWhitespace :: B.ByteString -> B.ByteString skipWhitespace s | elem c " \t\n" = skipWhitespace $ B.tail s | otherwise = s where c = B.head s skipComments :: B.ByteString -> B.ByteString skipComments s | c == 'c' = skipComments . B.tail . B.dropWhile (/= '\n') $ s | otherwise = s where c = B.head s parseInt :: B.ByteString -> (Int, B.ByteString) parseInt st = do let zero = ord '0' loop :: B.ByteString -> Int -> (Int, B.ByteString) loop s val = case B.head s of c | '0' <= c && c <= '9' -> loop (B.tail s) (val * 10 + ord c - zero) _ -> (val, B.tail s) case B.head st of '-' -> let (k, x) = loop (B.tail st) 0 in (negate k, x) '+' -> loop st (0 :: Int) c | '0' <= c && c <= '9' -> loop st 0 _ -> error "PARSE ERROR! Unexpected char" readClause :: Solver -> Stack -> Vec Int -> B.ByteString -> IO B.ByteString readClause s buffer bvec stream = do let loop :: Int -> B.ByteString -> IO B.ByteString loop i b = do let (k, b') = parseInt $ skipWhitespace b if k == 0 then do putStrLn . ( " clause : " + + ) . show . map lit2int = < < asList stack setNth buffer 0 $ i - 1 void $ addClause s buffer return b' else do let l = int2lit k setNth buffer i l setNth bvec l LiftedTrue loop (i + 1) b' loop 1 . skipComments . skipWhitespace $ stream readClause' :: Stack -> B.ByteString -> IO ([Int], B.ByteString) readClause' buffer stream = do let loop :: Int -> B.ByteString -> IO ([Int], B.ByteString) loop i b = do let (k, b') = parseInt $ skipWhitespace b if k == 0 then do putStrLn . ( " clause : " + + ) . show . map lit2int = < < asList stack setNth buffer 0 $ i - 1 (, b') <$> (take <$> get' buffer <*> asList buffer) else do setNth buffer i k loop (i + 1) b' loop 1 . skipComments . skipWhitespace $ stream showPath :: FilePath -> String where len = 32 basename = reverse . takeWhile (/= '/') . reverse $ str basename' = take len str pathHeader :: FilePath -> String pathHeader str = replicate (len - length basename) ' ' where len = 32 basename = reverse . takeWhile (/= '/') . reverse $ str showConf :: MiosConfiguration -> String showConf (MiosConfiguration vr pl _ _ _ _) = "VarDecayRate: " ++ showFFloat (Just 3) vr "" ++ ", PropagationLimit: " ++ show pl
1f7452e74303af56dd0d2f296ec638e44cc7569eb2965743bb38ba92fa686675
dreixel/syb
Perm.hs
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # module Perm (tests) where {- This module illustrates permutation phrases. Disclaimer: this is a perhaps naive, certainly undebugged example. -} import Test.Tasty.HUnit import Control.Applicative (Alternative(..), Applicative(..)) import Control.Monad import Data.Generics --------------------------------------------------------------------------- -- We want to read terms of type T3 regardless of the order T1 and T2. --------------------------------------------------------------------------- data T1 = T1 deriving (Show, Eq, Typeable, Data) data T2 = T2 deriving (Show, Eq, Typeable, Data) data T3 = T3 T1 T2 deriving (Show, Eq, Typeable, Data) --------------------------------------------------------------------------- -- A silly monad that we use to read lists of constructor strings. --------------------------------------------------------------------------- -- Type constructor newtype ReadT a = ReadT { unReadT :: [String] -> Maybe ([String],a) } -- Run a computation runReadT x y = case unReadT x y of Just ([],y) -> Just y _ -> Nothing -- Read one string readT :: ReadT String readT = ReadT (\x -> if null x then Nothing else Just (tail x, head x) ) instance Functor ReadT where fmap = liftM instance Applicative ReadT where pure x = ReadT (\y -> Just (y,x)) (<*>) = ap instance Alternative ReadT where (<|>) = mplus empty = mzero ReadT is a monad ! instance Monad ReadT where return = pure c >>= f = ReadT (\x -> case unReadT c x of Nothing -> Nothing Just (x', a) -> unReadT (f a) x' ) ReadT also accommodates mzero and mplus ! instance MonadPlus ReadT where mzero = ReadT (const Nothing) f `mplus` g = ReadT (\x -> case unReadT f x of Nothing -> unReadT g x y -> y ) --------------------------------------------------------------------------- -- A helper type to appeal to predicative type system. --------------------------------------------------------------------------- newtype GenM = GenM { unGenM :: forall a. Data a => a -> ReadT a } --------------------------------------------------------------------------- -- The function that reads and copes with all permutations. --------------------------------------------------------------------------- buildT :: forall a. Data a => ReadT a buildT = result where result = do str <- readT con <- string2constr str ske <- return $ fromConstr con fs <- return $ gmapQ buildT' ske perm [] fs ske -- Determine type of data to be constructed myType = myTypeOf result where myTypeOf :: forall a. ReadT a -> a myTypeOf = undefined -- Turn string into constructor string2constr str = maybe mzero return (readConstr (dataTypeOf myType) str) -- Specialise buildT per kid type buildT' :: forall a. Data a => a -> GenM buildT' (_::a) = GenM (const mzero `extM` const (buildT::ReadT a)) -- The permutation exploration function perm :: forall a. Data a => [GenM] -> [GenM] -> a -> ReadT a perm [] [] a = return a perm fs [] a = perm [] fs a perm fs (f:fs') a = ( do a' <- gmapMo (unGenM f) a perm fs fs' a' ) `mplus` ( do guard (not (null fs')) perm (f:fs) fs' a ) --------------------------------------------------------------------------- -- The main function for testing --------------------------------------------------------------------------- tests = ( runReadT buildT ["T1"] :: Maybe T1 -- should parse fine , ( runReadT buildT ["T2"] :: Maybe T2 -- should parse fine , ( runReadT buildT ["T3","T1","T2"] :: Maybe T3 -- should parse fine , ( runReadT buildT ["T3","T2","T1"] :: Maybe T3 -- should parse fine , ( runReadT buildT ["T3","T2","T2"] :: Maybe T3 -- should fail ))))) @=? output output = (Just T1,(Just T2,(Just (T3 T1 T2),(Just (T3 T1 T2),Nothing))))
null
https://raw.githubusercontent.com/dreixel/syb/4806afeb2ea824a3ea9969e23ca2c9569cd20d84/tests/Perm.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE RankNTypes # This module illustrates permutation phrases. Disclaimer: this is a perhaps naive, certainly undebugged example. ------------------------------------------------------------------------- We want to read terms of type T3 regardless of the order T1 and T2. ------------------------------------------------------------------------- ------------------------------------------------------------------------- A silly monad that we use to read lists of constructor strings. ------------------------------------------------------------------------- Type constructor Run a computation Read one string ------------------------------------------------------------------------- A helper type to appeal to predicative type system. ------------------------------------------------------------------------- ------------------------------------------------------------------------- The function that reads and copes with all permutations. ------------------------------------------------------------------------- Determine type of data to be constructed Turn string into constructor Specialise buildT per kid type The permutation exploration function ------------------------------------------------------------------------- The main function for testing ------------------------------------------------------------------------- should parse fine should parse fine should parse fine should parse fine should fail
# LANGUAGE ScopedTypeVariables # module Perm (tests) where import Test.Tasty.HUnit import Control.Applicative (Alternative(..), Applicative(..)) import Control.Monad import Data.Generics data T1 = T1 deriving (Show, Eq, Typeable, Data) data T2 = T2 deriving (Show, Eq, Typeable, Data) data T3 = T3 T1 T2 deriving (Show, Eq, Typeable, Data) newtype ReadT a = ReadT { unReadT :: [String] -> Maybe ([String],a) } runReadT x y = case unReadT x y of Just ([],y) -> Just y _ -> Nothing readT :: ReadT String readT = ReadT (\x -> if null x then Nothing else Just (tail x, head x) ) instance Functor ReadT where fmap = liftM instance Applicative ReadT where pure x = ReadT (\y -> Just (y,x)) (<*>) = ap instance Alternative ReadT where (<|>) = mplus empty = mzero ReadT is a monad ! instance Monad ReadT where return = pure c >>= f = ReadT (\x -> case unReadT c x of Nothing -> Nothing Just (x', a) -> unReadT (f a) x' ) ReadT also accommodates mzero and mplus ! instance MonadPlus ReadT where mzero = ReadT (const Nothing) f `mplus` g = ReadT (\x -> case unReadT f x of Nothing -> unReadT g x y -> y ) newtype GenM = GenM { unGenM :: forall a. Data a => a -> ReadT a } buildT :: forall a. Data a => ReadT a buildT = result where result = do str <- readT con <- string2constr str ske <- return $ fromConstr con fs <- return $ gmapQ buildT' ske perm [] fs ske myType = myTypeOf result where myTypeOf :: forall a. ReadT a -> a myTypeOf = undefined string2constr str = maybe mzero return (readConstr (dataTypeOf myType) str) buildT' :: forall a. Data a => a -> GenM buildT' (_::a) = GenM (const mzero `extM` const (buildT::ReadT a)) perm :: forall a. Data a => [GenM] -> [GenM] -> a -> ReadT a perm [] [] a = return a perm fs [] a = perm [] fs a perm fs (f:fs') a = ( do a' <- gmapMo (unGenM f) a perm fs fs' a' ) `mplus` ( do guard (not (null fs')) perm (f:fs) fs' a ) tests = ))))) @=? output output = (Just T1,(Just T2,(Just (T3 T1 T2),(Just (T3 T1 T2),Nothing))))
636656658e85945970e77ad86f2f1eecea867b31be7adf76d082df18307a482e
mbenke/zpf2013
MyParsec2a.hs
module MyParsec2a ( testP, parse, Parser, char, eof, (<|>), module MyParsec2a.Combinators, )where import MyParsec2a.Prim import MyParsec2a.Combinators import Data.Char(isDigit,digitToInt) parse :: Parser a -> String -> String -> Either ParseError a parse p fname input = case runParser p input of Ok a st -> Right a Error e -> Left e testP :: Show a => Parser a -> State -> Reply a testP = runParser p0 = return () test0 = testP p0 "" p2 = item >> item expect " EOF " test2 = testP p2 "abc" -- "'b', c" p3 :: Parser String p3 = p <|> q where p = char 'p' >> eof >> return "p" q = char 'p' >> char 'q' >> eof >> return "q" test3 = testP p3 "pq" p4 :: Parser Int p4 = fmap digitToInt (digit) test4a = testP p4 "7" test4b = testP p4 "x"
null
https://raw.githubusercontent.com/mbenke/zpf2013/85f32747e17f07a74e1c3cb064b1d6acaca3f2f0/Code/Parse1/MyParsec2a.hs
haskell
"'b', c"
module MyParsec2a ( testP, parse, Parser, char, eof, (<|>), module MyParsec2a.Combinators, )where import MyParsec2a.Prim import MyParsec2a.Combinators import Data.Char(isDigit,digitToInt) parse :: Parser a -> String -> String -> Either ParseError a parse p fname input = case runParser p input of Ok a st -> Right a Error e -> Left e testP :: Show a => Parser a -> State -> Reply a testP = runParser p0 = return () test0 = testP p0 "" p2 = item >> item expect " EOF " p3 :: Parser String p3 = p <|> q where p = char 'p' >> eof >> return "p" q = char 'p' >> char 'q' >> eof >> return "q" test3 = testP p3 "pq" p4 :: Parser Int p4 = fmap digitToInt (digit) test4a = testP p4 "7" test4b = testP p4 "x"
df8aba563c162c6247f701abcf194b593b2caaa7515285cb33d8ddb010669e75
finnishtransportagency/harja
listings.cljs
(ns harja.ui.listings (:require [reagent.core :as reagent :refer [atom]] [clojure.string :as s] [harja.loki :refer [log tarkkaile!]] [harja.ui.yleiset :refer [nuolivalinta]])) (defn suodatettu-lista "Luettelo, jossa on hakukenttä filtteröinnille. opts voi sisältää :term hakutermin atomi :selection valitun listaitemin atomi :format funktio jolla itemi muutetaan stringiksi, oletus str :haku funktio jolla haetaan itemistä, kenttä jota vasten hakusuodatus (oletus :name) :on-select funktio, jolla valinta tehdään (oletuksena reset! valinta-atomille) :aputeksti :tunniste :ryhmittely funktio jonka mukaan listan itemit ryhmitellään ja aliotsikoidaan (optionaalinen) :ryhman-otsikko funktio joka palauttaa otsikon ryhmittely-funktion antamalle ryhmälle :nayta-ryhmat optionaalinen sekvenssi ryhmäavaimia, jonka mukaisessa järjestyksessa ryhmät näytetään. Jos ei annettu, näytetään kaikki ei missään tietyssä järjestyksessä. :vinkki funktio, joka palauttaa vinkkitekstin hakukentän alle lista sisältää luettelon josta hakea." [opts lista] (let [termi-atom (or (:term opts) (atom "")) valittu (or (:selection opts) (atom nil)) fmt (or (:format opts) str) , oletuksena : name haku (or (:haku opts) :name) tekemiseen on määritelty funktio , käytä sitä . Muuten reset ! . on-select (or (:on-select opts) #(reset! valittu %)) Indeksi korostettuun elementtiin ( nil jos ei korostettua ) korostus-idx (atom nil)] (fn [opts lista] (let [term (or (:term opts) termi-atom) termi @term itemit (filter #(s/includes? (s/lower-case (or (haku %) "")) (s/lower-case (or termi ""))) lista) korostus @korostus-idx tunniste (if (:tunniste opts) (:tunniste opts) :id) ryhmitellyt-itemit (when (:ryhmittely opts) (group-by (:ryhmittely opts) itemit)) ryhmissa? (not (nil? ryhmitellyt-itemit)) ryhmat (when ryhmissa? (if-let [nr (:nayta-ryhmat opts)] (map (juxt identity #(get ryhmitellyt-itemit %)) nr) (seq ryhmitellyt-itemit))) kaikki-kamppeet (if ryhmissa? (mapcat second ryhmat) itemit)] [:div.haku-container [:input.haku-input.form-control {:type "text" :value @term :placeholder (:aputeksti opts) / enter näppäimet , näppäimistöllä :on-key-down (nuolivalinta Ylös #(swap! korostus-idx (fn [k] (if (or (nil? k) (= 0 k)) (dec (count kaikki-kamppeet)) (dec k)))) ;; Alas #(swap! korostus-idx (fn [k] (if (or (nil? k) (= (dec (count kaikki-kamppeet)) k)) 0 (inc k)))) ;; Enter #(when-let [k @korostus-idx] (on-select (nth kaikki-kamppeet k)) (reset! korostus-idx nil))) :on-change #(do (reset! korostus-idx nil) (reset! term (.-value (.-target %))))}] [:div.haku-lista-container (when-let [vinkki-fn (:vinkki opts)] (when (vinkki-fn) [:div.haku-vinkki (vinkki-fn)])) (when-not (empty? lista) (let [selected @valittu itemilista (fn [itemit alkuidx] [:ul.haku-lista (map-indexed (fn [i item] ^{:key (tunniste item)} [:li.haku-lista-item.klikattava {:on-click #(on-select item) :class (str (when (= item selected) "selected ") (when (= (+ alkuidx i) korostus) "korostettu "))} [:div.haku-lista-item-nimi (fmt item)]]) itemit)])] (if ryhmissa? (loop [alkuidx 0 acc nil [[ryhman-nimi ryhman-kamppeet] & ryhmat] ryhmat] (if (nil? ryhman-nimi) (reverse acc) (recur (+ alkuidx (count ryhman-kamppeet)) (conj acc ^{:key ryhman-nimi} [:div.haku-lista-ryhma [:div.haku-lista-ryhman-otsikko ((:ryhman-otsikko opts) ryhman-nimi)] (itemilista ryhman-kamppeet alkuidx)]) ryhmat))) (itemilista itemit 0))))]]))))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/488b1e096f0611e175221d74ba4f2ffed6bea8f1/src/cljs/harja/ui/listings.cljs
clojure
Alas Enter
(ns harja.ui.listings (:require [reagent.core :as reagent :refer [atom]] [clojure.string :as s] [harja.loki :refer [log tarkkaile!]] [harja.ui.yleiset :refer [nuolivalinta]])) (defn suodatettu-lista "Luettelo, jossa on hakukenttä filtteröinnille. opts voi sisältää :term hakutermin atomi :selection valitun listaitemin atomi :format funktio jolla itemi muutetaan stringiksi, oletus str :haku funktio jolla haetaan itemistä, kenttä jota vasten hakusuodatus (oletus :name) :on-select funktio, jolla valinta tehdään (oletuksena reset! valinta-atomille) :aputeksti :tunniste :ryhmittely funktio jonka mukaan listan itemit ryhmitellään ja aliotsikoidaan (optionaalinen) :ryhman-otsikko funktio joka palauttaa otsikon ryhmittely-funktion antamalle ryhmälle :nayta-ryhmat optionaalinen sekvenssi ryhmäavaimia, jonka mukaisessa järjestyksessa ryhmät näytetään. Jos ei annettu, näytetään kaikki ei missään tietyssä järjestyksessä. :vinkki funktio, joka palauttaa vinkkitekstin hakukentän alle lista sisältää luettelon josta hakea." [opts lista] (let [termi-atom (or (:term opts) (atom "")) valittu (or (:selection opts) (atom nil)) fmt (or (:format opts) str) , oletuksena : name haku (or (:haku opts) :name) tekemiseen on määritelty funktio , käytä sitä . Muuten reset ! . on-select (or (:on-select opts) #(reset! valittu %)) Indeksi korostettuun elementtiin ( nil jos ei korostettua ) korostus-idx (atom nil)] (fn [opts lista] (let [term (or (:term opts) termi-atom) termi @term itemit (filter #(s/includes? (s/lower-case (or (haku %) "")) (s/lower-case (or termi ""))) lista) korostus @korostus-idx tunniste (if (:tunniste opts) (:tunniste opts) :id) ryhmitellyt-itemit (when (:ryhmittely opts) (group-by (:ryhmittely opts) itemit)) ryhmissa? (not (nil? ryhmitellyt-itemit)) ryhmat (when ryhmissa? (if-let [nr (:nayta-ryhmat opts)] (map (juxt identity #(get ryhmitellyt-itemit %)) nr) (seq ryhmitellyt-itemit))) kaikki-kamppeet (if ryhmissa? (mapcat second ryhmat) itemit)] [:div.haku-container [:input.haku-input.form-control {:type "text" :value @term :placeholder (:aputeksti opts) / enter näppäimet , näppäimistöllä :on-key-down (nuolivalinta Ylös #(swap! korostus-idx (fn [k] (if (or (nil? k) (= 0 k)) (dec (count kaikki-kamppeet)) (dec k)))) #(swap! korostus-idx (fn [k] (if (or (nil? k) (= (dec (count kaikki-kamppeet)) k)) 0 (inc k)))) #(when-let [k @korostus-idx] (on-select (nth kaikki-kamppeet k)) (reset! korostus-idx nil))) :on-change #(do (reset! korostus-idx nil) (reset! term (.-value (.-target %))))}] [:div.haku-lista-container (when-let [vinkki-fn (:vinkki opts)] (when (vinkki-fn) [:div.haku-vinkki (vinkki-fn)])) (when-not (empty? lista) (let [selected @valittu itemilista (fn [itemit alkuidx] [:ul.haku-lista (map-indexed (fn [i item] ^{:key (tunniste item)} [:li.haku-lista-item.klikattava {:on-click #(on-select item) :class (str (when (= item selected) "selected ") (when (= (+ alkuidx i) korostus) "korostettu "))} [:div.haku-lista-item-nimi (fmt item)]]) itemit)])] (if ryhmissa? (loop [alkuidx 0 acc nil [[ryhman-nimi ryhman-kamppeet] & ryhmat] ryhmat] (if (nil? ryhman-nimi) (reverse acc) (recur (+ alkuidx (count ryhman-kamppeet)) (conj acc ^{:key ryhman-nimi} [:div.haku-lista-ryhma [:div.haku-lista-ryhman-otsikko ((:ryhman-otsikko opts) ryhman-nimi)] (itemilista ryhman-kamppeet alkuidx)]) ryhmat))) (itemilista itemit 0))))]]))))
15783b3204f7b0765902bff92066dba8729e9be10bbabec17c1a0793f7644da8
8c6794b6/guile-tjit
canonicalize.scm
;;; Tree-il canonicalizer Copyright ( C ) 2011 , 2012 , 2013 Free Software Foundation , Inc. ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; Lesser General Public License for more details. ;;;; You should have received a copy of the GNU Lesser General Public ;;;; License along with this library; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA ;;; Code: (define-module (language tree-il canonicalize) #:use-module (language tree-il) #:use-module (ice-9 match) #:use-module (srfi srfi-1) #:export (canonicalize)) (define (tree-il-any proc exp) (tree-il-fold (lambda (exp res) (or res (proc exp))) (lambda (exp res) res) #f exp)) (define (canonicalize x) (post-order (lambda (x) (match x (($ <let> src () () () body) body) (($ <letrec> src _ () () () body) body) (($ <fix> src () () () body) body) (($ <lambda> src meta #f) ;; Give a body to case-lambda with no clauses. (make-lambda src meta (make-lambda-case #f '() #f #f #f '() '() (make-primcall #f 'throw (list (make-const #f 'wrong-number-of-args) (make-const #f #f) (make-const #f "Wrong number of arguments") (make-const #f '()) (make-const #f #f))) #f))) (($ <prompt> src escape-only? tag body handler) ;; The prompt handler should be a simple lambda, so that we ;; can inline it. (match handler (($ <lambda> _ _ ($ <lambda-case> _ req #f rest #f () syms body #f)) x) (else (let ((handler-sym (gensym)) (args-sym (gensym))) (make-let #f (list 'handler) (list handler-sym) (list handler) (make-prompt src escape-only? tag body (make-lambda #f '() (make-lambda-case #f '() #f 'args #f '() (list args-sym) (make-primcall #f 'apply (list (make-lexical-ref #f 'handler handler-sym) (make-lexical-ref #f 'args args-sym))) #f)))))))) (_ x))) x))
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/language/tree-il/canonicalize.scm
scheme
Tree-il canonicalizer This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public either This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with this library; if not, write to the Free Software Code: Give a body to case-lambda with no clauses. The prompt handler should be a simple lambda, so that we can inline it.
Copyright ( C ) 2011 , 2012 , 2013 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 (language tree-il canonicalize) #:use-module (language tree-il) #:use-module (ice-9 match) #:use-module (srfi srfi-1) #:export (canonicalize)) (define (tree-il-any proc exp) (tree-il-fold (lambda (exp res) (or res (proc exp))) (lambda (exp res) res) #f exp)) (define (canonicalize x) (post-order (lambda (x) (match x (($ <let> src () () () body) body) (($ <letrec> src _ () () () body) body) (($ <fix> src () () () body) body) (($ <lambda> src meta #f) (make-lambda src meta (make-lambda-case #f '() #f #f #f '() '() (make-primcall #f 'throw (list (make-const #f 'wrong-number-of-args) (make-const #f #f) (make-const #f "Wrong number of arguments") (make-const #f '()) (make-const #f #f))) #f))) (($ <prompt> src escape-only? tag body handler) (match handler (($ <lambda> _ _ ($ <lambda-case> _ req #f rest #f () syms body #f)) x) (else (let ((handler-sym (gensym)) (args-sym (gensym))) (make-let #f (list 'handler) (list handler-sym) (list handler) (make-prompt src escape-only? tag body (make-lambda #f '() (make-lambda-case #f '() #f 'args #f '() (list args-sym) (make-primcall #f 'apply (list (make-lexical-ref #f 'handler handler-sym) (make-lexical-ref #f 'args args-sym))) #f)))))))) (_ x))) x))
3750e2c07429e5297f886985fcbcb9070eb61cd8f6ccb8537bfa08e5c8587e49
jvf/scalaris
sup_dht_node.erl
2007 - 2015 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @author < > %% @doc Supervisor for each DHT node that is responsible for keeping %% processes running that run for themselves. %% If one of the supervised processes fails , only the failed process %% will be re-started! %% @end %% @version $Id$ -module(sup_dht_node). -author(''). -vsn('$Id$'). -behaviour(supervisor). -include("scalaris.hrl"). -export([start_link/1, init/1]). -export([supspec/1, childs/1]). -spec start_link({DHTNodeGroup::pid_groups:groupname(), Options::[tuple()]}) -> {ok, Pid::pid(), pid_groups:groupname()} | ignore | {error, Error::{already_started, Pid::pid()} | shutdown | term()}. start_link({DHTNodeGroup, Options}) -> case supervisor:start_link(?MODULE, [{DHTNodeGroup, Options}]) of {ok, Pid} -> {ok, Pid, DHTNodeGroup}; X -> X end. %% userdevguide-begin sup_dht_node:init -spec init([{pid_groups:groupname(), [tuple()]}]) -> {ok, {{one_for_one, MaxRetries::pos_integer(), PeriodInSeconds::pos_integer()}, []}}. init([{DHTNodeGroup, _Options}] = X) -> pid_groups:join_as(DHTNodeGroup, ?MODULE), supspec(X). %% userdevguide-end sup_dht_node:init -spec supspec(any()) -> {ok, {{one_for_one, MaxRetries::pos_integer(), PeriodInSeconds::pos_integer()}, []}}. supspec(_) -> {ok, {{one_for_one, 10, 1}, []}}. -spec childs([{pid_groups:groupname(), Options::[tuple()]}]) -> [ProcessDescr::supervisor:child_spec()]. childs([{DHTNodeGroup, Options}]) -> Autoscale = case config:read(autoscale) of true -> sup:worker_desc(autoscale, autoscale, start_link, [DHTNodeGroup]); _ -> [] end, DBValCache = sup:worker_desc(dht_node_db_cache, dht_node_db_cache, start_link, [DHTNodeGroup]), DC_Clustering = sup:worker_desc(dc_clustering, dc_clustering, start_link, [DHTNodeGroup]), DeadNodeCache = sup:worker_desc(deadnodecache, dn_cache, start_link, [DHTNodeGroup]), Delayer = sup:worker_desc(msg_delay, msg_delay, start_link, [DHTNodeGroup]), Gossip = sup:worker_desc(gossip, gossip, start_link, [DHTNodeGroup]), GossipCyclonFeeder = sup:worker_desc(gossip_cyclon_feeder, gossip_cyclon_feeder, start_link, [DHTNodeGroup]), LBActive = case config:read(lb_active) of true -> sup:worker_desc(lb_active, lb_active, start_link, [DHTNodeGroup]); _ -> [] end, Reregister = sup:worker_desc(dht_node_reregister, dht_node_reregister, start_link, [DHTNodeGroup]), RMLeases = sup:worker_desc(rm_leases, rm_leases, start_link, [DHTNodeGroup]), RoutingTable = sup:worker_desc(routing_table, rt_loop, start_link, [DHTNodeGroup]), SupDHTNodeCore_AND = sup:supervisor_desc(sup_dht_node_core, sup_dht_node_core, start_link, [DHTNodeGroup, Options]), SupMr = case config : ) of %% true -> util : , sup_mr , start_link , ) ; %% _ -> [] %% end, Monitor = sup:worker_desc(monitor, monitor, start_link, [DHTNodeGroup]), RepUpdate = case config:read(rrepair_enabled) of true -> sup:worker_desc(rrepair, rrepair, start_link, [DHTNodeGroup]); _ -> [] end, SnapshotLeader = sup:worker_desc(snapshot_leader, snapshot_leader, start_link, [DHTNodeGroup]), SupWPool = sup:supervisor_desc(sup_wpool, sup_wpool, start_link, [DHTNodeGroup]), WPool = sup:worker_desc(wpool, wpool, start_link, [DHTNodeGroup, Options]), RepUpd may be [ ] and lists : flatten eliminates this Monitor, Delayer, Reregister, DBValCache, DeadNodeCache, RoutingTable, DC_Clustering, Gossip, GossipCyclonFeeder, SnapshotLeader, SupWPool, WPool, SupDHTNodeCore_AND, RepUpdate, Autoscale, RMLeases, LBActive ]).
null
https://raw.githubusercontent.com/jvf/scalaris/c069f44cf149ea6c69e24bdb08714bda242e7ee0/src/sup_dht_node.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc Supervisor for each DHT node that is responsible for keeping processes running that run for themselves. will be re-started! @end @version $Id$ userdevguide-begin sup_dht_node:init userdevguide-end sup_dht_node:init true -> _ -> [] end,
2007 - 2015 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > If one of the supervised processes fails , only the failed process -module(sup_dht_node). -author(''). -vsn('$Id$'). -behaviour(supervisor). -include("scalaris.hrl"). -export([start_link/1, init/1]). -export([supspec/1, childs/1]). -spec start_link({DHTNodeGroup::pid_groups:groupname(), Options::[tuple()]}) -> {ok, Pid::pid(), pid_groups:groupname()} | ignore | {error, Error::{already_started, Pid::pid()} | shutdown | term()}. start_link({DHTNodeGroup, Options}) -> case supervisor:start_link(?MODULE, [{DHTNodeGroup, Options}]) of {ok, Pid} -> {ok, Pid, DHTNodeGroup}; X -> X end. -spec init([{pid_groups:groupname(), [tuple()]}]) -> {ok, {{one_for_one, MaxRetries::pos_integer(), PeriodInSeconds::pos_integer()}, []}}. init([{DHTNodeGroup, _Options}] = X) -> pid_groups:join_as(DHTNodeGroup, ?MODULE), supspec(X). -spec supspec(any()) -> {ok, {{one_for_one, MaxRetries::pos_integer(), PeriodInSeconds::pos_integer()}, []}}. supspec(_) -> {ok, {{one_for_one, 10, 1}, []}}. -spec childs([{pid_groups:groupname(), Options::[tuple()]}]) -> [ProcessDescr::supervisor:child_spec()]. childs([{DHTNodeGroup, Options}]) -> Autoscale = case config:read(autoscale) of true -> sup:worker_desc(autoscale, autoscale, start_link, [DHTNodeGroup]); _ -> [] end, DBValCache = sup:worker_desc(dht_node_db_cache, dht_node_db_cache, start_link, [DHTNodeGroup]), DC_Clustering = sup:worker_desc(dc_clustering, dc_clustering, start_link, [DHTNodeGroup]), DeadNodeCache = sup:worker_desc(deadnodecache, dn_cache, start_link, [DHTNodeGroup]), Delayer = sup:worker_desc(msg_delay, msg_delay, start_link, [DHTNodeGroup]), Gossip = sup:worker_desc(gossip, gossip, start_link, [DHTNodeGroup]), GossipCyclonFeeder = sup:worker_desc(gossip_cyclon_feeder, gossip_cyclon_feeder, start_link, [DHTNodeGroup]), LBActive = case config:read(lb_active) of true -> sup:worker_desc(lb_active, lb_active, start_link, [DHTNodeGroup]); _ -> [] end, Reregister = sup:worker_desc(dht_node_reregister, dht_node_reregister, start_link, [DHTNodeGroup]), RMLeases = sup:worker_desc(rm_leases, rm_leases, start_link, [DHTNodeGroup]), RoutingTable = sup:worker_desc(routing_table, rt_loop, start_link, [DHTNodeGroup]), SupDHTNodeCore_AND = sup:supervisor_desc(sup_dht_node_core, sup_dht_node_core, start_link, [DHTNodeGroup, Options]), SupMr = case config : ) of util : , sup_mr , start_link , ) ; Monitor = sup:worker_desc(monitor, monitor, start_link, [DHTNodeGroup]), RepUpdate = case config:read(rrepair_enabled) of true -> sup:worker_desc(rrepair, rrepair, start_link, [DHTNodeGroup]); _ -> [] end, SnapshotLeader = sup:worker_desc(snapshot_leader, snapshot_leader, start_link, [DHTNodeGroup]), SupWPool = sup:supervisor_desc(sup_wpool, sup_wpool, start_link, [DHTNodeGroup]), WPool = sup:worker_desc(wpool, wpool, start_link, [DHTNodeGroup, Options]), RepUpd may be [ ] and lists : flatten eliminates this Monitor, Delayer, Reregister, DBValCache, DeadNodeCache, RoutingTable, DC_Clustering, Gossip, GossipCyclonFeeder, SnapshotLeader, SupWPool, WPool, SupDHTNodeCore_AND, RepUpdate, Autoscale, RMLeases, LBActive ]).
419e40af428c2cf59cc9941562301798f098fbde83189f8be5795a1c79d89786
marick/Midje
t_tap.clj
(ns midje.emission.plugins.t-tap (:require [midje [sweet :refer :all] [util :refer :all] [test-util :refer :all]] [midje.emission.plugins.tap :as tap] [midje.config :as config] [midje.emission.plugins.default-failure-lines :as failure-lines] [midje.emission.plugins.util :as util])) (defn innocuously [key & args] (config/with-augmented-config {:emitter 'midje.emission.plugins.tap :print-level :print-facts} (captured-output (apply (key tap/emission-map) args)))) (def test-fact (with-meta (fn[]) {:midje/name "named" :midje/description "desc" :midje/namespace "blah"})) (def test-failure-map {:type :some-prerequisites-were-called-the-wrong-number-of-times, :namespace "midje.emission.plugins.t-tap"}) (fact "starting a fact stream resets fact-counter and last-namespace-shown" (innocuously :starting-fact-stream) => "" @tap/fact-counter => 0 @tap/last-namespace-shown => nil) (fact "starting to check fact emits a message" (innocuously :starting-to-check-fact test-fact) => "# Checking named\n") (fact "closing a fact stream generates the closing report" (innocuously :finishing-fact-stream {:midje-passes 1 :midje-failures 1} ..ignored..) => (contains "1..0 # midje count: 2") (fact "with empty midje-counters set to 0" (innocuously :finishing-fact-stream {:midje-passes 0 :midje-failures 0} ..ignored..) => (contains "# No facts were checked. Is that what you wanted?")) (fact "with empty midje-counters" (innocuously :finishing-fact-stream {} ..ignored..) => (contains "# No facts were checked. Is that what you wanted?"))) (with-state-changes [(before :facts (do (reset! tap/fact-counter 0) (tap/set-last-namespace-shown! nil)))] (fact "pass produces ok with the index of the test" (innocuously :pass) => (contains "ok 1\n") (innocuously :pass) => (contains "ok 2\n"))) (with-state-changes [(before :facts (do (reset! tap/fact-counter 0) (tap/set-last-namespace-shown! nil)))] (fact "failure produces not ok with the index of the test" (innocuously :fail test-failure-map) => (contains "\nnot ok 1") (innocuously :fail test-failure-map) => (contains "\nnot ok 2"))) (with-state-changes [(before :facts (do (reset! tap/fact-counter 0) (tap/set-last-namespace-shown! nil)))] (fact "failure also produces not ok" (innocuously :fail test-failure-map) => (contains "\nnot ok 1")))
null
https://raw.githubusercontent.com/marick/Midje/2b9bcb117442d3bd2d16446b47540888d683c717/test/midje/emission/plugins/t_tap.clj
clojure
(ns midje.emission.plugins.t-tap (:require [midje [sweet :refer :all] [util :refer :all] [test-util :refer :all]] [midje.emission.plugins.tap :as tap] [midje.config :as config] [midje.emission.plugins.default-failure-lines :as failure-lines] [midje.emission.plugins.util :as util])) (defn innocuously [key & args] (config/with-augmented-config {:emitter 'midje.emission.plugins.tap :print-level :print-facts} (captured-output (apply (key tap/emission-map) args)))) (def test-fact (with-meta (fn[]) {:midje/name "named" :midje/description "desc" :midje/namespace "blah"})) (def test-failure-map {:type :some-prerequisites-were-called-the-wrong-number-of-times, :namespace "midje.emission.plugins.t-tap"}) (fact "starting a fact stream resets fact-counter and last-namespace-shown" (innocuously :starting-fact-stream) => "" @tap/fact-counter => 0 @tap/last-namespace-shown => nil) (fact "starting to check fact emits a message" (innocuously :starting-to-check-fact test-fact) => "# Checking named\n") (fact "closing a fact stream generates the closing report" (innocuously :finishing-fact-stream {:midje-passes 1 :midje-failures 1} ..ignored..) => (contains "1..0 # midje count: 2") (fact "with empty midje-counters set to 0" (innocuously :finishing-fact-stream {:midje-passes 0 :midje-failures 0} ..ignored..) => (contains "# No facts were checked. Is that what you wanted?")) (fact "with empty midje-counters" (innocuously :finishing-fact-stream {} ..ignored..) => (contains "# No facts were checked. Is that what you wanted?"))) (with-state-changes [(before :facts (do (reset! tap/fact-counter 0) (tap/set-last-namespace-shown! nil)))] (fact "pass produces ok with the index of the test" (innocuously :pass) => (contains "ok 1\n") (innocuously :pass) => (contains "ok 2\n"))) (with-state-changes [(before :facts (do (reset! tap/fact-counter 0) (tap/set-last-namespace-shown! nil)))] (fact "failure produces not ok with the index of the test" (innocuously :fail test-failure-map) => (contains "\nnot ok 1") (innocuously :fail test-failure-map) => (contains "\nnot ok 2"))) (with-state-changes [(before :facts (do (reset! tap/fact-counter 0) (tap/set-last-namespace-shown! nil)))] (fact "failure also produces not ok" (innocuously :fail test-failure-map) => (contains "\nnot ok 1")))
418d28a2670b5c225035284fae3ca97714aab09b89daf611f950c73fa5537e59
remyoudompheng/hs-language-go
Lexer.hs
-- | Module : Tests . Copyright : ( c ) 2013 License : ( see COPYING ) -- -- This module provides tests for the lexer. module Tests.Lexer (testsLexer) where import Test.Tasty import Test.Tasty.HUnit import Language.Go.Parser.Lexer import Language.Go.Parser.Tokens ( GoToken(..) , GoTokenPos(..) , insertSemi ) testLex :: String -> String -> [GoToken] -> TestTree testLex desc text ref = testCase desc $ assertEqual desc ref toks where toks = map strip $ insertSemi $ alexScanTokens text strip (GoTokenPos _ tok) = tok testRawString1 = testLex "raw string" "`hello`" [ GoTokStr (Just "`hello`") "hello" , GoTokSemicolon] testRawString2 = testLex "raw multiline string" "`hello\n\tworld`" [ GoTokStr (Just "`hello\n\tworld`") "hello\n\tworld" , GoTokSemicolon] testCharLit1 = testLex "rune literal for backslash" "'\\\\'" [ GoTokChar (Just "'\\\\'") '\\' , GoTokSemicolon] testCharLit2 = testLex "rune literal for newline" "'\\n'" [ GoTokChar (Just "'\\n'") '\n' , GoTokSemicolon] testCharLit3 = testLex "rune literal for e-acute" "'é'" [ GoTokChar (Just "'é'") 'é' , GoTokSemicolon] testCharLit4 = testLex "rune literal with octal escaping" "'\\377'" [ GoTokChar (Just "'\\377'") '\xff' , GoTokSemicolon] testString1 = testLex "string with backslash" "\"\\\\\"" [ GoTokStr (Just "\"\\\\\"") "\\" , GoTokSemicolon] testString2 = testLex "long string with backslash" "{\"\\\\\", \"a\", false, ErrBadPattern}," [ GoTokLBrace , GoTokStr (Just "\"\\\\\"") "\\" , GoTokComma,GoTokStr (Just "\"a\"") "a" , GoTokComma , GoTokId "false" , GoTokComma , GoTokId "ErrBadPattern" , GoTokRBrace , GoTokComma ] testString3 = testLex "string with tab" "\"\t\"" [ GoTokStr (Just "\"\t\"") "\t" , GoTokSemicolon] testString4 = testLex "string literal with octal escaping" "\"\\377\"" [ GoTokStr (Just "\"\\377\"") "\xff" , GoTokSemicolon] testFloat1 = testLex "floating point" "11." [ GoTokReal (Just "11.") 11 , GoTokSemicolon] testFloat2 = testLex "floating point" "11.e+3" [ GoTokReal (Just "11.e+3") 11e+3 , GoTokSemicolon] testFloat3 = testLex "floating point" ".5" [ GoTokReal (Just ".5") 0.5 , GoTokSemicolon] testId1 = testLex "non-ASCII identifier" "α := 2" [ GoTokId "α" , GoTokColonEq , GoTokInt (Just "2") 2 , GoTokSemicolon ] testComment1 = testLex "comment with non-ASCII characters" "/* αβ */" [ GoTokComment True " αβ " ] testComment2 = testLex "comment with non-ASCII characters" "/*\n\tαβ\n*/" [ GoTokComment True "\n\tαβ\n" ] testComment3 = testLex "comment with odd number of stars" "/***/" [ GoTokComment True "*" ] testComment4 = testLex "comment with many stars" "/******\n ******/" [ GoTokComment True "*****\n *****" ] testsLexer :: TestTree testsLexer = testGroup "lexer tests" [ testRawString1 , testRawString2 , testCharLit1 , testCharLit2 , testCharLit3 , testCharLit4 , testString1 , testString2 , testString3 , testString4 , testFloat1 , testFloat2 , testFloat3 , testId1 , testComment1 , testComment2 , testComment3 , testComment4 ]
null
https://raw.githubusercontent.com/remyoudompheng/hs-language-go/5440485f6404356892eab4832cff4f1378c11670/tests/Tests/Lexer.hs
haskell
| This module provides tests for the lexer.
Module : Tests . Copyright : ( c ) 2013 License : ( see COPYING ) module Tests.Lexer (testsLexer) where import Test.Tasty import Test.Tasty.HUnit import Language.Go.Parser.Lexer import Language.Go.Parser.Tokens ( GoToken(..) , GoTokenPos(..) , insertSemi ) testLex :: String -> String -> [GoToken] -> TestTree testLex desc text ref = testCase desc $ assertEqual desc ref toks where toks = map strip $ insertSemi $ alexScanTokens text strip (GoTokenPos _ tok) = tok testRawString1 = testLex "raw string" "`hello`" [ GoTokStr (Just "`hello`") "hello" , GoTokSemicolon] testRawString2 = testLex "raw multiline string" "`hello\n\tworld`" [ GoTokStr (Just "`hello\n\tworld`") "hello\n\tworld" , GoTokSemicolon] testCharLit1 = testLex "rune literal for backslash" "'\\\\'" [ GoTokChar (Just "'\\\\'") '\\' , GoTokSemicolon] testCharLit2 = testLex "rune literal for newline" "'\\n'" [ GoTokChar (Just "'\\n'") '\n' , GoTokSemicolon] testCharLit3 = testLex "rune literal for e-acute" "'é'" [ GoTokChar (Just "'é'") 'é' , GoTokSemicolon] testCharLit4 = testLex "rune literal with octal escaping" "'\\377'" [ GoTokChar (Just "'\\377'") '\xff' , GoTokSemicolon] testString1 = testLex "string with backslash" "\"\\\\\"" [ GoTokStr (Just "\"\\\\\"") "\\" , GoTokSemicolon] testString2 = testLex "long string with backslash" "{\"\\\\\", \"a\", false, ErrBadPattern}," [ GoTokLBrace , GoTokStr (Just "\"\\\\\"") "\\" , GoTokComma,GoTokStr (Just "\"a\"") "a" , GoTokComma , GoTokId "false" , GoTokComma , GoTokId "ErrBadPattern" , GoTokRBrace , GoTokComma ] testString3 = testLex "string with tab" "\"\t\"" [ GoTokStr (Just "\"\t\"") "\t" , GoTokSemicolon] testString4 = testLex "string literal with octal escaping" "\"\\377\"" [ GoTokStr (Just "\"\\377\"") "\xff" , GoTokSemicolon] testFloat1 = testLex "floating point" "11." [ GoTokReal (Just "11.") 11 , GoTokSemicolon] testFloat2 = testLex "floating point" "11.e+3" [ GoTokReal (Just "11.e+3") 11e+3 , GoTokSemicolon] testFloat3 = testLex "floating point" ".5" [ GoTokReal (Just ".5") 0.5 , GoTokSemicolon] testId1 = testLex "non-ASCII identifier" "α := 2" [ GoTokId "α" , GoTokColonEq , GoTokInt (Just "2") 2 , GoTokSemicolon ] testComment1 = testLex "comment with non-ASCII characters" "/* αβ */" [ GoTokComment True " αβ " ] testComment2 = testLex "comment with non-ASCII characters" "/*\n\tαβ\n*/" [ GoTokComment True "\n\tαβ\n" ] testComment3 = testLex "comment with odd number of stars" "/***/" [ GoTokComment True "*" ] testComment4 = testLex "comment with many stars" "/******\n ******/" [ GoTokComment True "*****\n *****" ] testsLexer :: TestTree testsLexer = testGroup "lexer tests" [ testRawString1 , testRawString2 , testCharLit1 , testCharLit2 , testCharLit3 , testCharLit4 , testString1 , testString2 , testString3 , testString4 , testFloat1 , testFloat2 , testFloat3 , testId1 , testComment1 , testComment2 , testComment3 , testComment4 ]
04934910503adb6c15251f998c07a0d4946a9355a8b2d36a4bdb2bde9b45ef13
ocaml-batteries-team/batteries-included
batteriesExceptionless.ml
open this to extend all with and . Exceptionless if available include (Batteries : module type of Batteries with module Array := Batteries.Array and module Hashtbl := Batteries.Hashtbl and module List := Batteries.List and module Map := Batteries.Map and module Queue := Batteries.Queue and module Stack := Batteries.Stack and module String := Batteries.String and module Enum := Batteries.Enum and module LazyList := Batteries.LazyList and module Seq := Batteries.Seq and module Splay := Batteries.Splay ) module Array = struct include (BatArray : module type of BatArray with module Labels := BatArray.Labels and module Cap := BatArray.Cap ) include BatArray.Exceptionless module Labels = struct include BatArray.Labels include BatArray.Labels.LExceptionless end module Cap = struct include BatArray.Cap include BatArray.Cap.Exceptionless end end module Hashtbl = struct include BatHashtbl include BatHashtbl.Exceptionless TODO end module List = struct include (BatList : module type of BatList with module Labels := BatList.Labels ) include BatList.Exceptionless module Labels = struct include BatList.Labels include BatList.Labels.LExceptionless end end module Map = struct include (BatMap : module type of BatMap with module PMap := BatMap.PMap ) include Exceptionless module PMap = struct include BatMap.PMap include BatMap.PMap.Exceptionless end TODO end module Queue = struct include BatQueue include BatQueue.Exceptionless end module Set = BatSet ( * TODO module Stack = struct include BatStack include BatStack.Exceptionless end module String = struct include (BatString : module type of BatString with module : = . ) include BatString.Exceptionless module = struct include . include . . Exceptionless (* end *) end Extlib modules not replacing stdlib module Enum = struct include (BatEnum : module type of Batteries.Enum with module Labels := Batteries.Enum.Labels ) include BatEnum.Exceptionless module Labels = struct include BatEnum.Labels include BatEnum.Labels.LExceptionless end end module LazyList = struct include (BatLazyList : module type of Batteries.LazyList with module Labels := Batteries.LazyList.Labels ) include BatLazyList.Exceptionless module Labels = struct include BatLazyList.Labels include BatLazyList.Labels.Exceptionless end end (* Batteries specific modules *) module Seq = struct include BatSeq include BatSeq.Exceptionless end module Splay = struct include (BatSplay : module type of BatSplay with module Map := BatSplay.Map ) module Map (Ord : BatInterfaces.OrderedType) = struct include BatSplay.Map(Ord) include Exceptionless end end
null
https://raw.githubusercontent.com/ocaml-batteries-team/batteries-included/f143ef5ec583d87d538b8f06f06d046d64555e90/src/batteriesExceptionless.ml
ocaml
end Batteries specific modules
open this to extend all with and . Exceptionless if available include (Batteries : module type of Batteries with module Array := Batteries.Array and module Hashtbl := Batteries.Hashtbl and module List := Batteries.List and module Map := Batteries.Map and module Queue := Batteries.Queue and module Stack := Batteries.Stack and module String := Batteries.String and module Enum := Batteries.Enum and module LazyList := Batteries.LazyList and module Seq := Batteries.Seq and module Splay := Batteries.Splay ) module Array = struct include (BatArray : module type of BatArray with module Labels := BatArray.Labels and module Cap := BatArray.Cap ) include BatArray.Exceptionless module Labels = struct include BatArray.Labels include BatArray.Labels.LExceptionless end module Cap = struct include BatArray.Cap include BatArray.Cap.Exceptionless end end module Hashtbl = struct include BatHashtbl include BatHashtbl.Exceptionless TODO end module List = struct include (BatList : module type of BatList with module Labels := BatList.Labels ) include BatList.Exceptionless module Labels = struct include BatList.Labels include BatList.Labels.LExceptionless end end module Map = struct include (BatMap : module type of BatMap with module PMap := BatMap.PMap ) include Exceptionless module PMap = struct include BatMap.PMap include BatMap.PMap.Exceptionless end TODO end module Queue = struct include BatQueue include BatQueue.Exceptionless end module Set = BatSet ( * TODO module Stack = struct include BatStack include BatStack.Exceptionless end module String = struct include (BatString : module type of BatString with module : = . ) include BatString.Exceptionless module = struct include . include . . Exceptionless end Extlib modules not replacing stdlib module Enum = struct include (BatEnum : module type of Batteries.Enum with module Labels := Batteries.Enum.Labels ) include BatEnum.Exceptionless module Labels = struct include BatEnum.Labels include BatEnum.Labels.LExceptionless end end module LazyList = struct include (BatLazyList : module type of Batteries.LazyList with module Labels := Batteries.LazyList.Labels ) include BatLazyList.Exceptionless module Labels = struct include BatLazyList.Labels include BatLazyList.Labels.Exceptionless end end module Seq = struct include BatSeq include BatSeq.Exceptionless end module Splay = struct include (BatSplay : module type of BatSplay with module Map := BatSplay.Map ) module Map (Ord : BatInterfaces.OrderedType) = struct include BatSplay.Map(Ord) include Exceptionless end end
6cf3a9fc9b2922c45b708b7e3612e63f7b8d2a6a991c16f00d907a089ea72fe9
jellelicht/guix
suckless.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2013 < > Copyright © 2015 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages suckless) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu) #:use-module (gnu packages) #:use-module (gnu packages xorg) #:use-module (gnu packages fonts) #:use-module (gnu packages pkg-config) #:use-module (gnu packages fontutils)) (define-public dwm (package (name "dwm") (version "6.0") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0mpbivy9j80l1jqq4bd4g4z8s5c54fxrjj44avmfwncjwqylifdj")))) (build-system gnu-build-system) (arguments `(#:tests? #f #:phases (alist-replace 'configure (lambda _ (substitute* "Makefile" (("\\$\\{CC\\}") "gcc")) #t) (alist-replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (zero? (system* "make" "install" (string-append "DESTDIR=" out) "PREFIX=")))) %standard-phases)))) (inputs `(("libx11" ,libx11) ("libxinerama" ,libxinerama))) (home-page "/") (synopsis "Dynamic window manager") (description "dwm is a dynamic window manager for X. It manages windows in tiled, monocle and floating layouts. All of the layouts can be applied dynamically, optimising the environment for the application in use and the task performed. In tiled layout windows are managed in a master and stacking area. The master area contains the window which currently needs most attention, whereas the stacking area contains all other windows. In monocle layout all windows are maximised to the screen size. In floating layout windows can be resized and moved freely. Dialog windows are always managed floating, regardless of the layout applied. Windows are grouped by tags. Each window can be tagged with one or multiple tags. Selecting certain tags displays all windows with these tags. Each screen contains a small status bar which displays all available tags, the layout, the number of visible windows, the title of the focused window, and the text read from the root window name property, if the screen is focused. A floating window is indicated with an empty square and a maximised floating window is indicated with a filled square before the windows title. The selected tags are indicated with a different color. The tags of the focused window are indicated with a filled square in the top left corner. The tags which are applied to one or more windows are indicated with an empty square in the top left corner. dwm draws a small customizable border around windows to indicate the focus state.") (license license:x11))) (define-public dmenu (package (name "dmenu") (version "4.5") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0l58jpxrr80fmyw5pgw5alm5qry49aw6y049745wl991v2cdcb08")))) (build-system gnu-build-system) (arguments '(#:tests? #f ; no tests #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:phases (alist-delete 'configure %standard-phases))) (inputs `(("libx11" ,libx11) ("libxinerama" ,libxinerama))) (home-page "/") (synopsis "Dynamic menu") (description "A dynamic menu for X, originally designed for dwm. It manages large numbers of user-defined menu items efficiently.") (license license:x11))) (define-public slock (package (name "slock") (version "1.2") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "1crkyr4vblhciy6vnbjwwjnlkm9yg2hzq16v6hzxm20ai67na0il")))) (build-system gnu-build-system) (arguments '(#:tests? #f ; no tests #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:phases (alist-delete 'configure %standard-phases))) (inputs `(("libx11" ,libx11) ("libxext" ,libxext) ("libxinerama" ,libxinerama))) (home-page "/") (synopsis "Simple X session lock") (description "Simple X session lock with trivial feedback on password entry.") (license license:x11))) (define-public st (package (name "st") (version "0.5") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0knxpzaa86pprng6hak8hx8bw22yw22rpz1ffxjpcvqlz3xdv05f")))) (build-system gnu-build-system) (arguments '(#:tests? #f ; no tests #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:phases (modify-phases %standard-phases (delete 'configure) (add-after 'unpack 'inhibit-terminfo-install (lambda _ (substitute* "Makefile" (("\t@tic -s st.info") "")) #t))))) (inputs `(("libx11" ,libx11) ("libxft" ,libxft) ("libxcomposite" ,libxcomposite) ("compositeproto" ,compositeproto) ("libxext" ,libxext) ("xextproto" ,xextproto) ("libxrender" ,libxrender) ("fontconfig" ,fontconfig) ("freetype" ,freetype) ("font-liberation" ,font-liberation))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "/") (synopsis "Simple terminal emulator") (description "St implements a simple and lightweight terminal emulator. It implements 256 colors, most VT10X escape sequences, utf8, X11 copy/paste, antialiased fonts (using fontconfig), fallback fonts, resizing, and line drawing.") (license license:x11)))
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/gnu/packages/suckless.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. no tests no tests no tests
Copyright © 2013 < > Copyright © 2015 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages suckless) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu) #:use-module (gnu packages) #:use-module (gnu packages xorg) #:use-module (gnu packages fonts) #:use-module (gnu packages pkg-config) #:use-module (gnu packages fontutils)) (define-public dwm (package (name "dwm") (version "6.0") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0mpbivy9j80l1jqq4bd4g4z8s5c54fxrjj44avmfwncjwqylifdj")))) (build-system gnu-build-system) (arguments `(#:tests? #f #:phases (alist-replace 'configure (lambda _ (substitute* "Makefile" (("\\$\\{CC\\}") "gcc")) #t) (alist-replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (zero? (system* "make" "install" (string-append "DESTDIR=" out) "PREFIX=")))) %standard-phases)))) (inputs `(("libx11" ,libx11) ("libxinerama" ,libxinerama))) (home-page "/") (synopsis "Dynamic window manager") (description "dwm is a dynamic window manager for X. It manages windows in tiled, monocle and floating layouts. All of the layouts can be applied dynamically, optimising the environment for the application in use and the task performed. In tiled layout windows are managed in a master and stacking area. The master area contains the window which currently needs most attention, whereas the stacking area contains all other windows. In monocle layout all windows are maximised to the screen size. In floating layout windows can be resized and moved freely. Dialog windows are always managed floating, regardless of the layout applied. Windows are grouped by tags. Each window can be tagged with one or multiple tags. Selecting certain tags displays all windows with these tags. Each screen contains a small status bar which displays all available tags, the layout, the number of visible windows, the title of the focused window, and the text read from the root window name property, if the screen is focused. A floating window is indicated with an empty square and a maximised floating window is indicated with a filled square before the windows title. The selected tags are indicated with a different color. The tags of the focused window are indicated with a filled square in the top left corner. The tags which are applied to one or more windows are indicated with an empty square in the top left corner. dwm draws a small customizable border around windows to indicate the focus state.") (license license:x11))) (define-public dmenu (package (name "dmenu") (version "4.5") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0l58jpxrr80fmyw5pgw5alm5qry49aw6y049745wl991v2cdcb08")))) (build-system gnu-build-system) (arguments #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:phases (alist-delete 'configure %standard-phases))) (inputs `(("libx11" ,libx11) ("libxinerama" ,libxinerama))) (home-page "/") (synopsis "Dynamic menu") (description "A dynamic menu for X, originally designed for dwm. It manages large numbers of user-defined menu items efficiently.") (license license:x11))) (define-public slock (package (name "slock") (version "1.2") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "1crkyr4vblhciy6vnbjwwjnlkm9yg2hzq16v6hzxm20ai67na0il")))) (build-system gnu-build-system) (arguments #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:phases (alist-delete 'configure %standard-phases))) (inputs `(("libx11" ,libx11) ("libxext" ,libxext) ("libxinerama" ,libxinerama))) (home-page "/") (synopsis "Simple X session lock") (description "Simple X session lock with trivial feedback on password entry.") (license license:x11))) (define-public st (package (name "st") (version "0.5") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0knxpzaa86pprng6hak8hx8bw22yw22rpz1ffxjpcvqlz3xdv05f")))) (build-system gnu-build-system) (arguments #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:phases (modify-phases %standard-phases (delete 'configure) (add-after 'unpack 'inhibit-terminfo-install (lambda _ (substitute* "Makefile" (("\t@tic -s st.info") "")) #t))))) (inputs `(("libx11" ,libx11) ("libxft" ,libxft) ("libxcomposite" ,libxcomposite) ("compositeproto" ,compositeproto) ("libxext" ,libxext) ("xextproto" ,xextproto) ("libxrender" ,libxrender) ("fontconfig" ,fontconfig) ("freetype" ,freetype) ("font-liberation" ,font-liberation))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "/") (synopsis "Simple terminal emulator") (description "St implements a simple and lightweight terminal emulator. It implements 256 colors, most VT10X escape sequences, utf8, X11 copy/paste, antialiased fonts (using fontconfig), fallback fonts, resizing, and line drawing.") (license license:x11)))
a1e61cf96fd0e1beeb9fac3781302057cadca0c2c4a1978f242f2a1a66bd9e9c
ocurrent/ocaml-multicore-ci
test.ml
let () = Unix.putenv "HOME" "/idontexist"; (* Ignore user's git configuration *) Unix.putenv "GIT_AUTHOR_NAME" "test"; Unix.putenv "GIT_COMMITTER_NAME" "test"; Unix.putenv "EMAIL" ""; Lwt_main.run @@ Alcotest_lwt.run "ocaml-multicore-ci" [ ("index", Test_index.tests); ("analyse", Test_analyse.tests) ]
null
https://raw.githubusercontent.com/ocurrent/ocaml-multicore-ci/d46eecaf7269283a4b95ee40d2a9d6c7ec34a7bf/test/test.ml
ocaml
Ignore user's git configuration
let () = Unix.putenv "HOME" "/idontexist"; Unix.putenv "GIT_AUTHOR_NAME" "test"; Unix.putenv "GIT_COMMITTER_NAME" "test"; Unix.putenv "EMAIL" ""; Lwt_main.run @@ Alcotest_lwt.run "ocaml-multicore-ci" [ ("index", Test_index.tests); ("analyse", Test_analyse.tests) ]
054da9ef5db4141dd72a2992fc44ec3fa22a888f253622ad771c5059964891a5
jordanthayer/ocaml-search
recording_dfs.ml
* @author jtd7 @since 2010 - 08 - 17 Recording version of depth first search , for the kids @author jtd7 @since 2010-08-17 Recording version of depth first search, for the kids *) type 'a node = { parent : 'a node; data : 'a; g : float; f : float; depth : int; h : float; d : float; } let wrap f = (** takes a function to be applied to the data payload such as the goal-test or the domain heuristic and wraps it so that it can be applied to the entire node *) (fun n -> f n.data) let unwrap_sol s = (** Unwraps a solution which is in the form of a search node and presents it in the format the domain expects it, which is domain data followed by cost *) match s with Limit.Nothing -> None | Limit.Incumbent (q,n) -> Some (n.data, n.g) let better_p a b = (** Sorts nodes solely on total cost information *) a.f <= b.f let ordered_p a b = (a.f -. a.g) < (b.f -. b.g) let make_expand recorder expand hd = (** Takes the domain expand function and a heuristic calculator and creates an expand function which returns search nodes. *) (fun n -> let children = List.map (fun (dat, g) -> let h,d = hd dat in { parent = n; data = dat; g = g; f = g +. h; depth = n.depth + 1; h = h; d = d; }) (expand n.data n.g) in recorder n n.parent children; children) let make_root dat f_hd = let h,d = f_hd dat in let rec root = { data = dat; parent = root; f = h; g = 0.; h = h; d = d; depth = 0;} in root let make_iface node_record sface = let init = Search_interface.make ~goal_p:(fun n -> sface.Search_interface.goal_p n.data) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~key:(wrap sface.Search_interface.key) ~equals:sface.Search_interface.equals sface.Search_interface.domain (make_root sface.Search_interface.initial sface.Search_interface.hd) better_p (Limit.make_default_logger (fun n -> n.f) (wrap sface.Search_interface.get_sol_length)) in let recorder = node_record init.Search_interface.info in (Search_interface.alter ~node_expand:(Some (make_expand recorder sface.Search_interface.domain_expand sface.Search_interface.hd)) ~goal_p:(Some (fun n -> let goal = sface.Search_interface.goal_p n.data in if goal then recorder n n.parent []; goal)) init) let child_order better_p = (fun a b -> if better_p a b then 1 else (if better_p b a then -1 else 0)) let no_dups_checking ?(record_q = Fn.no_op2) sface better_p = let i = sface.Search_interface.info in let feasible_p n = (match i.Limit.incumbent with Limit.Incumbent(float,m) -> better_p n m | _ -> true) in let rec expand_best n = if not (Limit.halt_p i) then (Limit.incr_exp i; if sface.Search_interface.goal_p n then Limit.new_incumbent i (Limit.Incumbent (0.,n)) else (let children = sface.Search_interface.node_expand n in List.iter (fun c -> Limit.incr_gen i; if feasible_p c then expand_best c) (List.sort (child_order better_p) children))) in expand_best sface.Search_interface.initial; Limit.results6 i let dups_hash ?(continue = false) ?(record_q = Fn.no_op2) ?ordered_p sface better_p = let i = sface.Search_interface.info and closed = Htable.create sface.Search_interface.hash sface.Search_interface.equals 100 and co = child_order (match ordered_p with None -> better_p | Some pred -> pred) and solved = ref false and openlist = Stack.create() in let feasible_p n = try let best = Htable.find closed (sface.Search_interface.key n) in Limit.incr_dups i; if better_p n best && continue then (Htable.replace closed (sface.Search_interface.key n) n; true) else false with Not_found -> Htable.replace closed (sface.Search_interface.key n) n; (match i.Limit.incumbent with Limit.Incumbent(float,m) -> better_p n m | _ -> true) in let rec expand_best () = if not (Limit.halt_p i) then (record_q i openlist; let n = Stack.pop openlist in Limit.incr_exp i; if sface.Search_interface.goal_p n then (solved := true; Verb.pe Verb.always "Solved!\n"; Limit.new_incumbent i (Limit.Incumbent (0.,n))) else (let children = List.sort co (sface.Search_interface.node_expand n) in List.iter (fun c -> Limit.incr_gen i; if feasible_p c then Stack.push c openlist else Limit.incr_prune i) children); if (not !solved) || continue then expand_best ()) in Stack.push sface.Search_interface.initial openlist; expand_best (); Limit.results6 i (***************************************************************************) let dups sface node_record queue_record = (** Performs an A* search from the initial state to a goal, for domains where duplicates are frequently encountered. *) let search_interface = make_iface node_record sface in Limit.unwrap_sol6 unwrap_sol (dups_hash ~record_q:queue_record search_interface better_p) let exp_rec key_printer key = Recorders.expansion_recorder key_printer (wrap key) (fun n -> n.g) (fun n -> n.depth) (fun n -> n.f) let queue_rec key_printer key = Recorders.stack_recorder key_printer (wrap key) let expand_recorder_dups sface args = Search_args.is_empty "Recording_dfs.expand_recorder_dups" args; let expand_rec = (exp_rec sface.Search_interface.key_printer sface.Search_interface.key) in dups sface expand_rec Recorders.none let stack_recorder_dups sface args = Search_args.is_empty "Recording_astar.queue_recorder_dups" args; dups sface Recorders.no_node_record (queue_rec sface.Search_interface.key_printer sface.Search_interface.key) EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/recording/recording_dfs.ml
ocaml
* takes a function to be applied to the data payload such as the goal-test or the domain heuristic and wraps it so that it can be applied to the entire node * Unwraps a solution which is in the form of a search node and presents it in the format the domain expects it, which is domain data followed by cost * Sorts nodes solely on total cost information * Takes the domain expand function and a heuristic calculator and creates an expand function which returns search nodes. ************************************************************************* * Performs an A* search from the initial state to a goal, for domains where duplicates are frequently encountered.
* @author jtd7 @since 2010 - 08 - 17 Recording version of depth first search , for the kids @author jtd7 @since 2010-08-17 Recording version of depth first search, for the kids *) type 'a node = { parent : 'a node; data : 'a; g : float; f : float; depth : int; h : float; d : float; } let wrap f = (fun n -> f n.data) let unwrap_sol s = match s with Limit.Nothing -> None | Limit.Incumbent (q,n) -> Some (n.data, n.g) let better_p a b = a.f <= b.f let ordered_p a b = (a.f -. a.g) < (b.f -. b.g) let make_expand recorder expand hd = (fun n -> let children = List.map (fun (dat, g) -> let h,d = hd dat in { parent = n; data = dat; g = g; f = g +. h; depth = n.depth + 1; h = h; d = d; }) (expand n.data n.g) in recorder n n.parent children; children) let make_root dat f_hd = let h,d = f_hd dat in let rec root = { data = dat; parent = root; f = h; g = 0.; h = h; d = d; depth = 0;} in root let make_iface node_record sface = let init = Search_interface.make ~goal_p:(fun n -> sface.Search_interface.goal_p n.data) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~key:(wrap sface.Search_interface.key) ~equals:sface.Search_interface.equals sface.Search_interface.domain (make_root sface.Search_interface.initial sface.Search_interface.hd) better_p (Limit.make_default_logger (fun n -> n.f) (wrap sface.Search_interface.get_sol_length)) in let recorder = node_record init.Search_interface.info in (Search_interface.alter ~node_expand:(Some (make_expand recorder sface.Search_interface.domain_expand sface.Search_interface.hd)) ~goal_p:(Some (fun n -> let goal = sface.Search_interface.goal_p n.data in if goal then recorder n n.parent []; goal)) init) let child_order better_p = (fun a b -> if better_p a b then 1 else (if better_p b a then -1 else 0)) let no_dups_checking ?(record_q = Fn.no_op2) sface better_p = let i = sface.Search_interface.info in let feasible_p n = (match i.Limit.incumbent with Limit.Incumbent(float,m) -> better_p n m | _ -> true) in let rec expand_best n = if not (Limit.halt_p i) then (Limit.incr_exp i; if sface.Search_interface.goal_p n then Limit.new_incumbent i (Limit.Incumbent (0.,n)) else (let children = sface.Search_interface.node_expand n in List.iter (fun c -> Limit.incr_gen i; if feasible_p c then expand_best c) (List.sort (child_order better_p) children))) in expand_best sface.Search_interface.initial; Limit.results6 i let dups_hash ?(continue = false) ?(record_q = Fn.no_op2) ?ordered_p sface better_p = let i = sface.Search_interface.info and closed = Htable.create sface.Search_interface.hash sface.Search_interface.equals 100 and co = child_order (match ordered_p with None -> better_p | Some pred -> pred) and solved = ref false and openlist = Stack.create() in let feasible_p n = try let best = Htable.find closed (sface.Search_interface.key n) in Limit.incr_dups i; if better_p n best && continue then (Htable.replace closed (sface.Search_interface.key n) n; true) else false with Not_found -> Htable.replace closed (sface.Search_interface.key n) n; (match i.Limit.incumbent with Limit.Incumbent(float,m) -> better_p n m | _ -> true) in let rec expand_best () = if not (Limit.halt_p i) then (record_q i openlist; let n = Stack.pop openlist in Limit.incr_exp i; if sface.Search_interface.goal_p n then (solved := true; Verb.pe Verb.always "Solved!\n"; Limit.new_incumbent i (Limit.Incumbent (0.,n))) else (let children = List.sort co (sface.Search_interface.node_expand n) in List.iter (fun c -> Limit.incr_gen i; if feasible_p c then Stack.push c openlist else Limit.incr_prune i) children); if (not !solved) || continue then expand_best ()) in Stack.push sface.Search_interface.initial openlist; expand_best (); Limit.results6 i let dups sface node_record queue_record = let search_interface = make_iface node_record sface in Limit.unwrap_sol6 unwrap_sol (dups_hash ~record_q:queue_record search_interface better_p) let exp_rec key_printer key = Recorders.expansion_recorder key_printer (wrap key) (fun n -> n.g) (fun n -> n.depth) (fun n -> n.f) let queue_rec key_printer key = Recorders.stack_recorder key_printer (wrap key) let expand_recorder_dups sface args = Search_args.is_empty "Recording_dfs.expand_recorder_dups" args; let expand_rec = (exp_rec sface.Search_interface.key_printer sface.Search_interface.key) in dups sface expand_rec Recorders.none let stack_recorder_dups sface args = Search_args.is_empty "Recording_astar.queue_recorder_dups" args; dups sface Recorders.no_node_record (queue_rec sface.Search_interface.key_printer sface.Search_interface.key) EOF
7e46a6a915609585e3724b7f9f77baf483929754e8719df6ff5d66295b75b73b
aratare-jp/shinsetsu
server.clj
(ns shinsetsu.server (:require [aleph.http :as http] [mount.core :as m] [clojure.tools.cli :as cli] [taoensso.timbre :as log] [shinsetsu.config :refer [env]] [shinsetsu.app :refer [app]] [shinsetsu.nrepl :as nrepl]) (:gen-class)) ;; log uncaught exceptions in threads (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (log/error {:what :uncaught-exception :exception ex :where (str "Uncaught exception on" (.getName thread))})))) (def cli-options [["-p" "--port PORT" "Port number" :parse-fn #(Integer/parseInt %)]]) (defonce server (atom nil)) (m/defstate ^{:on-reload :noop} http-server :start (reset! server (http/start-server app (assoc env :port (or (:port env) 3000)))) :stop (when @server (.close @server) (reset! server nil))) (m/defstate ^{:on-reload :noop} repl-server :start (when (:nrepl-port env) (nrepl/start {:bind (:nrepl-bind env) :port (:nrepl-port env)})) :stop (when repl-server (nrepl/stop repl-server))) (defn stop-app "Stops everything and shutdown the web app." [] (doseq [component (:stopped (m/stop))] (log/info component "stopped")) (shutdown-agents)) (defn start-app "Initialise everything and start the web app." ([] (start-app {})) ([args] (m/start #'shinsetsu.config/env) (doseq [component (-> args (cli/parse-opts cli-options) m/start-with-args :started)] (log/info component "started")))) (defn -main [& args] (.addShutdownHook (Runtime/getRuntime) (Thread. stop-app)) (start-app args)) (comment (require '[user]) (user/restart) {:a 1 :b 2 :c {:d 3}} (+ 1 2))
null
https://raw.githubusercontent.com/aratare-jp/shinsetsu/22b9add9f52716fc4e13c83cf667695be8a3e06f/src/clj/shinsetsu/server.clj
clojure
log uncaught exceptions in threads
(ns shinsetsu.server (:require [aleph.http :as http] [mount.core :as m] [clojure.tools.cli :as cli] [taoensso.timbre :as log] [shinsetsu.config :refer [env]] [shinsetsu.app :refer [app]] [shinsetsu.nrepl :as nrepl]) (:gen-class)) (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (log/error {:what :uncaught-exception :exception ex :where (str "Uncaught exception on" (.getName thread))})))) (def cli-options [["-p" "--port PORT" "Port number" :parse-fn #(Integer/parseInt %)]]) (defonce server (atom nil)) (m/defstate ^{:on-reload :noop} http-server :start (reset! server (http/start-server app (assoc env :port (or (:port env) 3000)))) :stop (when @server (.close @server) (reset! server nil))) (m/defstate ^{:on-reload :noop} repl-server :start (when (:nrepl-port env) (nrepl/start {:bind (:nrepl-bind env) :port (:nrepl-port env)})) :stop (when repl-server (nrepl/stop repl-server))) (defn stop-app "Stops everything and shutdown the web app." [] (doseq [component (:stopped (m/stop))] (log/info component "stopped")) (shutdown-agents)) (defn start-app "Initialise everything and start the web app." ([] (start-app {})) ([args] (m/start #'shinsetsu.config/env) (doseq [component (-> args (cli/parse-opts cli-options) m/start-with-args :started)] (log/info component "started")))) (defn -main [& args] (.addShutdownHook (Runtime/getRuntime) (Thread. stop-app)) (start-app args)) (comment (require '[user]) (user/restart) {:a 1 :b 2 :c {:d 3}} (+ 1 2))
7042d5d059d1ff9a0b272de9200246f3ab4d1c91a4f63a78b94a411c5449bd8f
ocamllabs/ocaml-modular-implicits
t240-c_call3.ml
open Lib;; if Hashtbl.hash_param 5 6 [1;2;3] <> 697606130 then raise Not_found;; * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 9 CONSTINT 196799 11 PUSHGETGLOBAL < 0>(1 , < 0>(2 , < 0>(3 , 0 ) ) ) 13 PUSHCONSTINT 6 15 PUSHCONSTINT 5 17 C_CALL3 hash_univ_param 19 NEQ 20 BRANCHIFNOT 27 22 GETGLOBAL Not_found 24 MAKEBLOCK1 0 26 RAISE 27 ATOM0 28 SETGLOBAL T240 - c_call3 30 STOP * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 SETGLOBAL Lib 9 CONSTINT 196799 11 PUSHGETGLOBAL <0>(1, <0>(2, <0>(3, 0))) 13 PUSHCONSTINT 6 15 PUSHCONSTINT 5 17 C_CALL3 hash_univ_param 19 NEQ 20 BRANCHIFNOT 27 22 GETGLOBAL Not_found 24 MAKEBLOCK1 0 26 RAISE 27 ATOM0 28 SETGLOBAL T240-c_call3 30 STOP **)
null
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-ocaml/t240-c_call3.ml
ocaml
open Lib;; if Hashtbl.hash_param 5 6 [1;2;3] <> 697606130 then raise Not_found;; * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 9 CONSTINT 196799 11 PUSHGETGLOBAL < 0>(1 , < 0>(2 , < 0>(3 , 0 ) ) ) 13 PUSHCONSTINT 6 15 PUSHCONSTINT 5 17 C_CALL3 hash_univ_param 19 NEQ 20 BRANCHIFNOT 27 22 GETGLOBAL Not_found 24 MAKEBLOCK1 0 26 RAISE 27 ATOM0 28 SETGLOBAL T240 - c_call3 30 STOP * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 SETGLOBAL Lib 9 CONSTINT 196799 11 PUSHGETGLOBAL <0>(1, <0>(2, <0>(3, 0))) 13 PUSHCONSTINT 6 15 PUSHCONSTINT 5 17 C_CALL3 hash_univ_param 19 NEQ 20 BRANCHIFNOT 27 22 GETGLOBAL Not_found 24 MAKEBLOCK1 0 26 RAISE 27 ATOM0 28 SETGLOBAL T240-c_call3 30 STOP **)
b31f568e77f0df956ebe4f005fbe4806f1acb467f658125ea42e9038a8eb1a5c
haskell-suite/haskell-src-exts
FFIInterruptible.hs
# LANGUAGE InterruptibleFFI # foo = interruptible
null
https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/FFIInterruptible.hs
haskell
# LANGUAGE InterruptibleFFI # foo = interruptible
9a315444e7defd787d94bd9f0210ade88f3678b62f40ccd67900449e3db998da
chef/sqerl
gobot_tests.erl
-module(gobot_tests). -include_lib("eunit/include/eunit.hrl"). exports_test() -> Exports = gobot_test_object1:module_info(exports), ExpectedExports = [ {'#new', 0}, {getval, 2}, {fromlist, 1}, {'fields', 0}, {'#insert_fields', 0}, {'#update_fields', 0}, {'#statements', 0}, {'#table_name', 0}, {module_info, 0}, {module_info, 1}, {'#is', 1}, {setvals, 2} ], [assert_export(X, Exports) || X <- ExpectedExports], ?assertEqual({export_length, length(ExpectedExports)}, {export_length, length(Exports)}), ok. assert_export({FuncName, Arity}, Exports) -> Any = lists:member({FuncName, Arity}, Exports), ?assertEqual({true, {FuncName, Arity}}, {Any, {FuncName, Arity}}).
null
https://raw.githubusercontent.com/chef/sqerl/a27e3e58da53240dc9925ec03ecdb894b8231cf9/test/gobot_tests.erl
erlang
-module(gobot_tests). -include_lib("eunit/include/eunit.hrl"). exports_test() -> Exports = gobot_test_object1:module_info(exports), ExpectedExports = [ {'#new', 0}, {getval, 2}, {fromlist, 1}, {'fields', 0}, {'#insert_fields', 0}, {'#update_fields', 0}, {'#statements', 0}, {'#table_name', 0}, {module_info, 0}, {module_info, 1}, {'#is', 1}, {setvals, 2} ], [assert_export(X, Exports) || X <- ExpectedExports], ?assertEqual({export_length, length(ExpectedExports)}, {export_length, length(Exports)}), ok. assert_export({FuncName, Arity}, Exports) -> Any = lists:member({FuncName, Arity}, Exports), ?assertEqual({true, {FuncName, Arity}}, {Any, {FuncName, Arity}}).
a9c18ed812a3fbf57f69359b6d028cbd9e2b98367b34de1f83e7bd33b0890cae
ppaml-op3/insomnia
Type.hs
{-# LANGUAGE OverloadedStrings #-} -- | Kind checking for types. -- Well-formed kind checking is also here because it is trivial. module Insomnia.Typecheck.Type where import Control.Lens import Control.Monad (zipWithM_, forM) import Control.Monad.Reader.Class (MonadReader(..)) import Data.List (intersperse) import Data.Monoid (Monoid(..),(<>)) import qualified Data.Set as S import qualified Unbound.Generics.LocallyNameless as U import Insomnia.TypeDefn (TypeAlias(..)) import Insomnia.Types import Insomnia.Typecheck.Env import {-# SOURCE #-} Insomnia.Typecheck.ModuleType (checkModuleType) -- | Check that a kind is well-formed. Note that for now, all kinds -- are well-formed. checkKind :: Kind -> TC () checkKind _k = return () -- | The subkinding relation. For our simple kinds it is reflexive. isSubkind :: Kind -> Kind -> Bool isSubkind = U.aeq | ensure that the first kind is a subtype of the second . ensureSubkind :: (Type, Kind) -> Kind -> TC () ensureSubkind (tblame, ksub) ksup = if (isSubkind ksub ksup) then return () else typeError (formatErr tblame <> " has kind " <> formatErr ksub <> " which is not a subkind of " <> formatErr ksup) -- | Ensure that the given kind is of the form (k1 → k2). ensureKArr :: Kind -> Type -> TC (Kind, Kind) ensureKArr k t = case k of KType -> typeError ("expected an arrow kind, got ⋆ when checking " <> formatErr t) KArr k1 k2 -> return (k1, k2) -- | Check that a type has the given kind checkType :: Type -> Kind -> TC Type checkType t k = do tk@(t', _) <- inferType t ensureSubkind tk k return t' -- | Given a type, infer its kind. inferType :: Type -> TC (Type, Kind) inferType t = case t of TC {} -> expandAliasApplication t [] TApp t1 t2 -> expandAliasApplication t1 [t2] TUVar u -> typeError ("unexpected unification variable " <> formatErr u) TV v -> do k' <- lookupTyVar v return (t, k') TAnn t1 k1 -> do checkKind k1 t1' <- checkType t1 k1 return (TAnn t1' k1, k1) TForall bnd -> do U.lunbind bnd $ \((v, kdom), tcod) -> do checkKind kdom tcod' <- extendTyVarCtx v kdom $ checkType tcod KType return (TForall (U.bind (v, kdom) tcod'), KType) TRecord row -> do row' <- checkRow row return (TRecord row', KType) TPack modTy -> do (modTy', _) <- checkModuleType modTy return (TPack modTy', KType) checkRow :: Row -> TC Row checkRow r@(Row ts) = do checkUniqueLabels r ts' <- forM ts $ \(lbl, ty) -> do ty' <- checkType ty KType return (lbl, ty') return $ Row $ canonicalOrderRowLabels ts' checkUniqueLabels :: Row -> TC () checkUniqueLabels r@(Row ls0) = case dups S.empty ls0 of Just l -> typeError ("duplicate label " <> formatErr l <> " in row type " <> formatErr r) Nothing -> return () where dups _seen [] = Nothing dups seen ((l,_ty):ls) = if l `S.member` seen then Just l else dups (S.insert l seen) ls -- | @expandAliasApplication t targs@ recursively unfolds t until a -- type alias is exposed which is then expanded with the given -- arguments and the resulting type is returned. If the head is some -- other higher-kinded type, the sequence of type applications is -- typechecked in the normal manner and the result type is just the -- sequence of type applcations. -- Notes : 1 . It is an error to apply a type alias to fewer arguments than it expects . 2 . The result of expanding a type alias may be higher - kinded , so the alias -- could appear under _more_ applications than its number of arguments. 3 . The result of expanding an alias may itself be an alias . Cycles are -- assumed not to occur, so we expand recursively until there are no more -- aliases at the head. expandAliasApplication :: Type -> [Type] -> TC (Type, Kind) expandAliasApplication t targs = case t of TApp t' targ -> expandAliasApplication t' (targ:targs) TC dcon -> do desc <- lookupDCon dcon case desc of GenerativeTyCon gt -> do k' <- inferGenerativeType gt reconstructApplication (t,k') targs AliasTyCon aliasInfo aliasClosure -> do m <- checkAliasInfoArgs aliasInfo targs case m of Left (_wantMoreArgs, kt) -> reconstructApplication (t, kt) targs Right (tsubArgs, tAppArgs) -> do tRHS <- expandAliasClosure aliasClosure tsubArgs maybe RHS is also an alias , expand it again . expandAliasApplication tRHS tAppArgs TV v -> do k' <- lookupTyVar v reconstructApplication (t, k') targs _ -> case targs of [] -> inferType t _ -> typeError ("Type " <> formatErr t <> " cannot be applied to " <> mconcat (intersperse ", " $ map formatErr targs)) type RequiredArgsCount = Int -- | Given a type alias and some number of types to which it is applied, -- split up the arguments into the set that's required by the alias, -- and the rest to which the RHS of the alias will be applied. -- Also check that the mandatory args are of the correct kind. checkAliasInfoArgs :: TypeAliasInfo -> [Type] -> TC (Either (RequiredArgsCount, Kind) ([Type], [Type])) checkAliasInfoArgs (TypeAliasInfo kargs kRHS) targs = do let n = length kargs if (length targs < n) then return $ Left (n, kargs `kArrs` kRHS) else let (tsubArgs, tAppArgs) = splitAt n targs in do zipWithM_ checkType tsubArgs kargs return $ Right (tsubArgs, tAppArgs) expandAliasClosure :: TypeAliasClosure -> [Type] -> TC Type expandAliasClosure (TypeAliasClosure env (ManifestTypeAlias bnd)) targs = local (const env) $ U.lunbind bnd $ \(tvks, ty) -> return $ let tvs = map fst tvks substitution = zip tvs targs in U.substs substitution ty expandAliasClosure (TypeAliasClosure _env (DataCopyTypeAlias tp _defn)) targs = return $ (TC $ TCGlobal tp) `tApps` targs | @reconstructApplication ( thead , khead ) [ t1, ... ,tN]@ returns the type @thead ` TApp ` t1 ` TApp ` ... ` TApp ` tN@ and its infered kind -- after checking that each argument checks against its corresponding -- kind in @khead@ reconstructApplication :: (Type, Kind) -> [Type] -> TC (Type, Kind) reconstructApplication (thead, k) targs = case targs of [] -> return (thead, k) (targ:targs') -> do (kdom, kcod) <- ensureKArr k thead targ' <- checkType targ kdom reconstructApplication (TApp thead targ', kcod) targs' inferGenerativeType :: GenerativeType -> TC Kind inferGenerativeType (AlgebraicType algTy) = let k = foldr KArr KType (algTy^.algTypeParams) in return k inferGenerativeType (EnumerationType {}) = return KType inferGenerativeType (AbstractType k) = return k
null
https://raw.githubusercontent.com/ppaml-op3/insomnia/5fc6eb1d554e8853d2fc929a957c7edce9e8867d/src/Insomnia/Typecheck/Type.hs
haskell
# LANGUAGE OverloadedStrings # | Kind checking for types. Well-formed kind checking is also here because it is trivial. # SOURCE # | Check that a kind is well-formed. Note that for now, all kinds are well-formed. | The subkinding relation. For our simple kinds it is reflexive. | Ensure that the given kind is of the form (k1 → k2). | Check that a type has the given kind | Given a type, infer its kind. | @expandAliasApplication t targs@ recursively unfolds t until a type alias is exposed which is then expanded with the given arguments and the resulting type is returned. If the head is some other higher-kinded type, the sequence of type applications is typechecked in the normal manner and the result type is just the sequence of type applcations. could appear under _more_ applications than its number of arguments. assumed not to occur, so we expand recursively until there are no more aliases at the head. | Given a type alias and some number of types to which it is applied, split up the arguments into the set that's required by the alias, and the rest to which the RHS of the alias will be applied. Also check that the mandatory args are of the correct kind. after checking that each argument checks against its corresponding kind in @khead@
module Insomnia.Typecheck.Type where import Control.Lens import Control.Monad (zipWithM_, forM) import Control.Monad.Reader.Class (MonadReader(..)) import Data.List (intersperse) import Data.Monoid (Monoid(..),(<>)) import qualified Data.Set as S import qualified Unbound.Generics.LocallyNameless as U import Insomnia.TypeDefn (TypeAlias(..)) import Insomnia.Types import Insomnia.Typecheck.Env checkKind :: Kind -> TC () checkKind _k = return () isSubkind :: Kind -> Kind -> Bool isSubkind = U.aeq | ensure that the first kind is a subtype of the second . ensureSubkind :: (Type, Kind) -> Kind -> TC () ensureSubkind (tblame, ksub) ksup = if (isSubkind ksub ksup) then return () else typeError (formatErr tblame <> " has kind " <> formatErr ksub <> " which is not a subkind of " <> formatErr ksup) ensureKArr :: Kind -> Type -> TC (Kind, Kind) ensureKArr k t = case k of KType -> typeError ("expected an arrow kind, got ⋆ when checking " <> formatErr t) KArr k1 k2 -> return (k1, k2) checkType :: Type -> Kind -> TC Type checkType t k = do tk@(t', _) <- inferType t ensureSubkind tk k return t' inferType :: Type -> TC (Type, Kind) inferType t = case t of TC {} -> expandAliasApplication t [] TApp t1 t2 -> expandAliasApplication t1 [t2] TUVar u -> typeError ("unexpected unification variable " <> formatErr u) TV v -> do k' <- lookupTyVar v return (t, k') TAnn t1 k1 -> do checkKind k1 t1' <- checkType t1 k1 return (TAnn t1' k1, k1) TForall bnd -> do U.lunbind bnd $ \((v, kdom), tcod) -> do checkKind kdom tcod' <- extendTyVarCtx v kdom $ checkType tcod KType return (TForall (U.bind (v, kdom) tcod'), KType) TRecord row -> do row' <- checkRow row return (TRecord row', KType) TPack modTy -> do (modTy', _) <- checkModuleType modTy return (TPack modTy', KType) checkRow :: Row -> TC Row checkRow r@(Row ts) = do checkUniqueLabels r ts' <- forM ts $ \(lbl, ty) -> do ty' <- checkType ty KType return (lbl, ty') return $ Row $ canonicalOrderRowLabels ts' checkUniqueLabels :: Row -> TC () checkUniqueLabels r@(Row ls0) = case dups S.empty ls0 of Just l -> typeError ("duplicate label " <> formatErr l <> " in row type " <> formatErr r) Nothing -> return () where dups _seen [] = Nothing dups seen ((l,_ty):ls) = if l `S.member` seen then Just l else dups (S.insert l seen) ls Notes : 1 . It is an error to apply a type alias to fewer arguments than it expects . 2 . The result of expanding a type alias may be higher - kinded , so the alias 3 . The result of expanding an alias may itself be an alias . Cycles are expandAliasApplication :: Type -> [Type] -> TC (Type, Kind) expandAliasApplication t targs = case t of TApp t' targ -> expandAliasApplication t' (targ:targs) TC dcon -> do desc <- lookupDCon dcon case desc of GenerativeTyCon gt -> do k' <- inferGenerativeType gt reconstructApplication (t,k') targs AliasTyCon aliasInfo aliasClosure -> do m <- checkAliasInfoArgs aliasInfo targs case m of Left (_wantMoreArgs, kt) -> reconstructApplication (t, kt) targs Right (tsubArgs, tAppArgs) -> do tRHS <- expandAliasClosure aliasClosure tsubArgs maybe RHS is also an alias , expand it again . expandAliasApplication tRHS tAppArgs TV v -> do k' <- lookupTyVar v reconstructApplication (t, k') targs _ -> case targs of [] -> inferType t _ -> typeError ("Type " <> formatErr t <> " cannot be applied to " <> mconcat (intersperse ", " $ map formatErr targs)) type RequiredArgsCount = Int checkAliasInfoArgs :: TypeAliasInfo -> [Type] -> TC (Either (RequiredArgsCount, Kind) ([Type], [Type])) checkAliasInfoArgs (TypeAliasInfo kargs kRHS) targs = do let n = length kargs if (length targs < n) then return $ Left (n, kargs `kArrs` kRHS) else let (tsubArgs, tAppArgs) = splitAt n targs in do zipWithM_ checkType tsubArgs kargs return $ Right (tsubArgs, tAppArgs) expandAliasClosure :: TypeAliasClosure -> [Type] -> TC Type expandAliasClosure (TypeAliasClosure env (ManifestTypeAlias bnd)) targs = local (const env) $ U.lunbind bnd $ \(tvks, ty) -> return $ let tvs = map fst tvks substitution = zip tvs targs in U.substs substitution ty expandAliasClosure (TypeAliasClosure _env (DataCopyTypeAlias tp _defn)) targs = return $ (TC $ TCGlobal tp) `tApps` targs | @reconstructApplication ( thead , khead ) [ t1, ... ,tN]@ returns the type @thead ` TApp ` t1 ` TApp ` ... ` TApp ` tN@ and its infered kind reconstructApplication :: (Type, Kind) -> [Type] -> TC (Type, Kind) reconstructApplication (thead, k) targs = case targs of [] -> return (thead, k) (targ:targs') -> do (kdom, kcod) <- ensureKArr k thead targ' <- checkType targ kdom reconstructApplication (TApp thead targ', kcod) targs' inferGenerativeType :: GenerativeType -> TC Kind inferGenerativeType (AlgebraicType algTy) = let k = foldr KArr KType (algTy^.algTypeParams) in return k inferGenerativeType (EnumerationType {}) = return KType inferGenerativeType (AbstractType k) = return k
6714feeac28038a9263c6091a78ce1e265f0f04597df8a7914db4b37a39f8468
rmculpepper/crypto
all.rkt
Copyright 2018 ;; ;; 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, see </>. #lang racket/base (require "main.rkt" "libcrypto.rkt" "gcrypt.rkt" "nettle.rkt" "argon2.rkt" "b2.rkt" "decaf.rkt" "sodium.rkt") (provide all-factories use-all-factories! libcrypto-factory gcrypt-factory nettle-factory argon2-factory b2-factory decaf-factory sodium-factory) (define all-factories (list nettle-factory libcrypto-factory gcrypt-factory b2-factory argon2-factory sodium-factory decaf-factory)) (define (use-all-factories!) (crypto-factories all-factories))
null
https://raw.githubusercontent.com/rmculpepper/crypto/fec745e8af7e3f4d5eaf83407dde2817de4c2eb0/crypto-lib/all.rkt
racket
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 (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 along with this library. If not, see </>.
Copyright 2018 by the Free Software Foundation , either version 3 of the License , or GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License #lang racket/base (require "main.rkt" "libcrypto.rkt" "gcrypt.rkt" "nettle.rkt" "argon2.rkt" "b2.rkt" "decaf.rkt" "sodium.rkt") (provide all-factories use-all-factories! libcrypto-factory gcrypt-factory nettle-factory argon2-factory b2-factory decaf-factory sodium-factory) (define all-factories (list nettle-factory libcrypto-factory gcrypt-factory b2-factory argon2-factory sodium-factory decaf-factory)) (define (use-all-factories!) (crypto-factories all-factories))
fce83ec8e99e79810bc388ed2b898b07252f23ef0d2bf4280415bcba817d4fd0
nuprl/gradual-typing-performance
moment-base.rkt
#lang typed/racket/base ;; Support for moment.rkt ;; (Works together with offset-resolvers.rkt) (provide moment->iso8601 moment->iso8601/tzid make-moment (struct-out Moment) ) ;; ----------------------------------------------------------------------------- (require benchmark-util racket/match (only-in racket/format ~r) "datetime-adapted.rkt" ) ;; ============================================================================= (struct Moment ([datetime/local : DateTime] [utc-offset : Integer] [zone : (U String #f)])) (: moment->iso8601/tzid (-> Moment String)) (define (moment->iso8601/tzid m) (: iso String) (define iso (moment->iso8601 m)) (match m [(Moment _ _ z) #:when z (format "~a[~a]" iso z)] [_ iso])) (: moment->iso8601 (-> Moment String)) (define (moment->iso8601 m) (match m [(Moment d 0 _) (string-append (datetime->iso8601 d) "Z")] [(Moment d o _) (define sign (if (< o 0) "-" "+")) (define sec (abs o)) (define hrs (quotient sec 3600)) (define min (quotient (- sec (* hrs 3600)) 60)) (format "~a~a~a:~a" (datetime->iso8601 d) sign (~r hrs #:min-width 2 #:pad-string "0" #:sign #f) (~r min #:min-width 2 #:pad-string "0" #:sign #f))])) (: make-moment (-> DateTime Integer (U String #f) Moment)) (define (make-moment dt off z) (Moment dt off (and z (string->immutable-string z))))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/experimental/postmortem/experiments/adaptor/many-adaptor/gregor/typed/moment-base.rkt
racket
Support for moment.rkt (Works together with offset-resolvers.rkt) ----------------------------------------------------------------------------- =============================================================================
#lang typed/racket/base (provide moment->iso8601 moment->iso8601/tzid make-moment (struct-out Moment) ) (require benchmark-util racket/match (only-in racket/format ~r) "datetime-adapted.rkt" ) (struct Moment ([datetime/local : DateTime] [utc-offset : Integer] [zone : (U String #f)])) (: moment->iso8601/tzid (-> Moment String)) (define (moment->iso8601/tzid m) (: iso String) (define iso (moment->iso8601 m)) (match m [(Moment _ _ z) #:when z (format "~a[~a]" iso z)] [_ iso])) (: moment->iso8601 (-> Moment String)) (define (moment->iso8601 m) (match m [(Moment d 0 _) (string-append (datetime->iso8601 d) "Z")] [(Moment d o _) (define sign (if (< o 0) "-" "+")) (define sec (abs o)) (define hrs (quotient sec 3600)) (define min (quotient (- sec (* hrs 3600)) 60)) (format "~a~a~a:~a" (datetime->iso8601 d) sign (~r hrs #:min-width 2 #:pad-string "0" #:sign #f) (~r min #:min-width 2 #:pad-string "0" #:sign #f))])) (: make-moment (-> DateTime Integer (U String #f) Moment)) (define (make-moment dt off z) (Moment dt off (and z (string->immutable-string z))))
2996eee2d16de53848270570b2019e1e051eb88ed318467a3ae14f4196103320
haskell-tools/haskell-tools
PatternBind.hs
module Decl.PatternBind where (x,y) | 1 == 1 = (1,2)
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/refactor/examples/Decl/PatternBind.hs
haskell
module Decl.PatternBind where (x,y) | 1 == 1 = (1,2)
9ef4d1b0c42897e37788b5cadb1a073e2a40ddf6a2391144207b47fdfb143d78
janestreet/ecaml
input_event0.ml
open! Core open! Import0 include Value.Make_subtype (struct let name = "input-event" let here = [%here] let is_in_subtype = Value.is_event end) let description = Funcall.Wrap.("single-key-description" <: t @-> return string) let sexp_of_t t = [%sexp (description t : string)]
null
https://raw.githubusercontent.com/janestreet/ecaml/da88f7ddde41838f6ad0ef90c85d81fbfb1526c3/src/input_event0.ml
ocaml
open! Core open! Import0 include Value.Make_subtype (struct let name = "input-event" let here = [%here] let is_in_subtype = Value.is_event end) let description = Funcall.Wrap.("single-key-description" <: t @-> return string) let sexp_of_t t = [%sexp (description t : string)]
011f3d9ab8f49aa2d5b9f36f452042e8cd846ca7e68bbb296713c7dc28e9960f
gwkkwg/metatilities-base
generic-interface.lisp
(in-package #:metatilities) ;;; System variables (declaim (special *development-mode* *use-native-debugger*)) (defvar *development-mode* t) (defvar *use-native-debugger* nil) ;;; progress bars (defvar *dummy-progress-variable*) (defvar *progress-bar-count* 0) (defmacro with-progress-bar ((min max &rest args &key (title "Progress") (verbose? t) (desired-interface nil interface-supplied?) (determinate-p t) &allow-other-keys) &body body) (remf args :title) (remf args :desired-interface) (remf args :verbose?) (with-variables (bar window interface) `(let ((,interface (if ,interface-supplied? ,desired-interface *default-interface*))) (if (and ,verbose? (is-interface-available-p ,interface)) (macrolet ((progress () ;; avoid compiler warnings `(progress-bar-value ,',interface ,',bar))) (multiple-value-bind (,window ,bar) (make-progress-bar ,interface ,min ,max ,title :determinate-p ,determinate-p ,@args) (declare (ignorable ,bar)) (unwind-protect (progn (incf *progress-bar-count*) (setf (progress-bar-value ,interface ,bar) ,min) ,@body) ;; cleanup (close-progress-bar ,interface ,window) (decf *progress-bar-count*)))) ;; just execute body (macrolet ((progress () '*dummy-progress-variable*)) (let ((*dummy-progress-variable* 0)) (progn ,@body))))))) (defmacro with-process-message ((&rest args &key (title "Please wait...") &allow-other-keys) &body body) (remf args :title) `(with-progress-bar (0 0 :title ,title :determinate-p nil ,@args) ,@body)) ;;; Error handling (defmacro handle-errors (standard-message &body body) `(catch 'recover (if *use-native-debugger* (progn . ,body) ;; Otherwise set up our nice error handlers... (handler-bind ((error #'(lambda (condition) (gui-error condition "ERROR: " ,standard-message) (throw 'recover NIL))) #+(or ccl mcl) (warning #'(lambda (condition) (gui-error condition "WARNING: ") (muffle-warning condition)))) ,@body)))) ;;; beeping (defmethod interface-beep* (interface &rest args) (declare (ignore interface args))) (defun interface-beep (&rest args) (apply #'interface-beep* *default-interface* args)) ;;; no interface interface implementations ;;; Progress bars (defmethod make-progress-bar (interface min max title &key &allow-other-keys) (declare (ignore interface min max title)) (values nil)) (defmethod progress-bar-value (interface bar) (declare (ignore interface bar)) (values 0)) (defmethod (setf progress-bar-value) (value interface bar) (declare (ignore interface bar)) (values value)) (defmethod close-progress-bar (interface bar) (declare (ignore interface bar)) (values)) #+Test (with-progress-bar (0 20) (loop repeat 20 do (incf (progress)) (sleep .1))) ;;; Errors and warnings #-(or digitool openmcl) (defmethod report-condition ((condition condition) stream) (write-string (cond ((typep condition 'error) "Error") ((typep condition 'warning) "Warning") (t "Unknown Condition")) stream) (print-object condition stream)) (defmethod gui-error* (interface condition &optional (prefix "") (standard-message nil)) (gui-warn* interface (if *development-mode* (with-output-to-string (stream) (let ((*print-array* nil) (*print-length* 10) (*print-level* 4)) (#+(or digitool openmcl) ccl::report-condition #-(or digitool openmcl) report-condition condition stream))) (format nil "~A~A" prefix (if standard-message standard-message condition))))) (defun gui-error (condition &optional (prefix "") (standard-message nil)) (gui-error* *default-interface* condition prefix standard-message)) (defmethod gui-warn* (interface string &rest args) (declare (ignore interface)) (apply #'warn string args)) (defun gui-warn (string &rest args) (apply #'gui-warn* *default-interface* string args)) Color (defmethod make-color** (interface red green blue) (declare (ignore interface red green blue)) (values 0)) (defun make-color* (red green blue) ;;; Make-color with sensible arguments "given red, green, and blue, returns an encoded rgb value" (make-color** (default-interface) red green blue)) (defmethod make-gray* (interface level) (make-color** interface level level level)) (defun make-gray (level) These use a 0 - 255 scale for component levels (make-gray* (default-interface) level)) (defmethod make-scaled-color* (interface red green blue scale) (make-color** interface (round (* red scale)) (round (* green scale)) (round (* blue scale)))) (defun make-scaled-color (red green blue scale) (make-scaled-color* (default-interface) red green blue scale)) ;;; y-or-n-dialog (defmethod y-or-n-question* (interface message &rest args) (declare (ignore interface args)) (y-or-n-p message)) (defun y-or-n-question (message &rest args) (apply #'y-or-n-question* *default-interface* message args)) ;;; choose-file-question (defmethod choose-file-question* (interface &rest args) (declare (ignore interface args)) (print "I would love to choose a file for you, but I'm not sure how?")) (defun choose-file-question (&rest args) (apply #'choose-file-question* *default-interface* args)) ;;; choose-new-file-question (defmethod choose-new-file-question* (interface &rest args) (declare (ignore interface args)) (print "I would love to choose a new file name for you, but I'm not sure how?")) (defun choose-new-file-question (&rest args) (apply #'choose-new-file-question* *default-interface* args)) ;;; choose-directory-question (defmethod choose-directory-question* (interface &rest args) (declare (ignore interface args)) (print "I would love to choose a directory name for you, but I'm not sure how?")) (defun choose-directory-question (&rest args) (apply #'choose-directory-question* *default-interface* args)) ;;; choose-item-question (defmethod choose-item-question* (interface list &rest args &key &allow-other-keys) (declare (ignore interface list args)) (print "I would love to choose an item for you, but I'm not sure how?")) (defun choose-item-question (list &rest args &key &allow-other-keys) (apply #'choose-item-question* *default-interface* list args)) ;;; choose-item-from-pup ;; defaults to choose-item-question: (defmethod choose-item-from-pup* (interface the-list &rest args &key &allow-other-keys) (apply #'choose-item-question* interface the-list args)) (defun choose-item-from-pup (the-list &rest args &key &allow-other-keys) "Present an interface to allow a choice from a list. Can throw :cancel." (apply #'choose-item-from-pup* *default-interface* the-list args)) (defun choose-item-from-pup-no-singletons (the-list-or-atom &rest args &key &allow-other-keys) "Like choose-item-from-pup, but just returns the datum if it is an atom or a singleton list." (cond ((atom the-list-or-atom) (values the-list-or-atom)) ((= (length the-list-or-atom) 1) (values (first the-list-or-atom))) (t (apply #'choose-item-from-pup the-list-or-atom args)))) ;;; make-ui-point (defmethod make-ui-point* (interface x y) (declare (ignore interface x y)) (values)) (defun make-ui-point (x y) (make-ui-point* *default-interface* x y)) ;;; process-parameters (defmethod process-parameters* (interface &rest args) (declare (ignore interface args)) (values)) (defun process-parameters (&rest args) (apply #'process-parameters* *default-interface* args) (values)) ;;; put-item-on-clipboard (defmethod put-item-on-clipboard* (interface thing) (declare (ignore interface thing)) (error "I don't know anything about clipboards.")) (defun put-item-on-clipboard (thing) (put-item-on-clipboard* *default-interface* thing) thing) ;;; inspect-thing (defmethod inspect-thing* (interface thing &rest args) (declare (ignore interface args)) (error "I don't know how toinspect ~S" thing)) (defun inspect-thing (thing &rest args) (apply #'inspect-thing* *default-interface* thing args) (values thing)) (defun inspect-things (&rest things) (let ((result nil)) (mapc (lambda (thing) (setf result (inspect-thing thing))) things) (values result))) (defmethod sound-note* (interface pitch velocity &rest args) (declare (ignore interface pitch velocity args)) (interface-beep)) (defun sound-note (pitch velocity &rest args) (apply #'sound-note* *default-interface* pitch velocity args)) (defmethod stop-notes* (interface) (declare (ignore interface)) (error "I don't know how to stop music.")) (defun stop-notes () (stop-notes* *default-interface*)) (defmethod select-instrument* (interface instrument &rest args) (declare (ignore interface instrument args)) (error "I don't know how to select instruments.")) (defun select-instrument (instrument &rest args) (apply #'select-instrument* *default-interface* instrument args)) ;;; query-user-for-string (defun query-user-for-string (prompt &rest args &key &allow-other-keys) (apply #'prompt-for 'string prompt args)) (defun query-user-for-integer (prompt &optional minimum maximum) (catch :cancel (loop do (let ((number (parse-integer (query-user-for-string prompt) :junk-allowed t))) (cond ((null number) ) ((and minimum (< number minimum)) ) ((and maximum (> number maximum)) ) (t (return-from query-user-for-integer number))))))) ;;; prompt-for (defmethod prompt-for* (interface type message &rest args) (declare (ignore interface message args)) (warn "I don't know how to prompt for ~A" type)) (defmethod prompt-for* (interface (type (eql 'string)) message &rest args) (declare (ignore interface)) (apply #'format *query-io* message args) (finish-output *query-io*) (read-line *query-io* nil :eof)) (defmethod prompt-for* (interface (type (eql 'fixnum)) message &rest args) (declare (ignore interface)) (apply #'query-user-for-integer message args)) (defun prompt-for (type message &rest args) (apply #'prompt-for* *default-interface* type message args)) ;;; *************************************************************************** ;;; * End of File * ;;; ***************************************************************************
null
https://raw.githubusercontent.com/gwkkwg/metatilities-base/ef04337759972fd622c9b27b53149f3d594a841f/dev/generic-interface.lisp
lisp
System variables progress bars avoid compiler warnings cleanup just execute body Error handling Otherwise set up our nice error handlers... beeping no interface interface implementations Progress bars Errors and warnings Make-color with sensible arguments y-or-n-dialog choose-file-question choose-new-file-question choose-directory-question choose-item-question choose-item-from-pup defaults to choose-item-question: make-ui-point process-parameters put-item-on-clipboard inspect-thing query-user-for-string prompt-for *************************************************************************** * End of File * ***************************************************************************
(in-package #:metatilities) (declaim (special *development-mode* *use-native-debugger*)) (defvar *development-mode* t) (defvar *use-native-debugger* nil) (defvar *dummy-progress-variable*) (defvar *progress-bar-count* 0) (defmacro with-progress-bar ((min max &rest args &key (title "Progress") (verbose? t) (desired-interface nil interface-supplied?) (determinate-p t) &allow-other-keys) &body body) (remf args :title) (remf args :desired-interface) (remf args :verbose?) (with-variables (bar window interface) `(let ((,interface (if ,interface-supplied? ,desired-interface *default-interface*))) (if (and ,verbose? (is-interface-available-p ,interface)) (macrolet ((progress () `(progress-bar-value ,',interface ,',bar))) (multiple-value-bind (,window ,bar) (make-progress-bar ,interface ,min ,max ,title :determinate-p ,determinate-p ,@args) (declare (ignorable ,bar)) (unwind-protect (progn (incf *progress-bar-count*) (setf (progress-bar-value ,interface ,bar) ,min) ,@body) (close-progress-bar ,interface ,window) (decf *progress-bar-count*)))) (macrolet ((progress () '*dummy-progress-variable*)) (let ((*dummy-progress-variable* 0)) (progn ,@body))))))) (defmacro with-process-message ((&rest args &key (title "Please wait...") &allow-other-keys) &body body) (remf args :title) `(with-progress-bar (0 0 :title ,title :determinate-p nil ,@args) ,@body)) (defmacro handle-errors (standard-message &body body) `(catch 'recover (if *use-native-debugger* (progn . ,body) (handler-bind ((error #'(lambda (condition) (gui-error condition "ERROR: " ,standard-message) (throw 'recover NIL))) #+(or ccl mcl) (warning #'(lambda (condition) (gui-error condition "WARNING: ") (muffle-warning condition)))) ,@body)))) (defmethod interface-beep* (interface &rest args) (declare (ignore interface args))) (defun interface-beep (&rest args) (apply #'interface-beep* *default-interface* args)) (defmethod make-progress-bar (interface min max title &key &allow-other-keys) (declare (ignore interface min max title)) (values nil)) (defmethod progress-bar-value (interface bar) (declare (ignore interface bar)) (values 0)) (defmethod (setf progress-bar-value) (value interface bar) (declare (ignore interface bar)) (values value)) (defmethod close-progress-bar (interface bar) (declare (ignore interface bar)) (values)) #+Test (with-progress-bar (0 20) (loop repeat 20 do (incf (progress)) (sleep .1))) #-(or digitool openmcl) (defmethod report-condition ((condition condition) stream) (write-string (cond ((typep condition 'error) "Error") ((typep condition 'warning) "Warning") (t "Unknown Condition")) stream) (print-object condition stream)) (defmethod gui-error* (interface condition &optional (prefix "") (standard-message nil)) (gui-warn* interface (if *development-mode* (with-output-to-string (stream) (let ((*print-array* nil) (*print-length* 10) (*print-level* 4)) (#+(or digitool openmcl) ccl::report-condition #-(or digitool openmcl) report-condition condition stream))) (format nil "~A~A" prefix (if standard-message standard-message condition))))) (defun gui-error (condition &optional (prefix "") (standard-message nil)) (gui-error* *default-interface* condition prefix standard-message)) (defmethod gui-warn* (interface string &rest args) (declare (ignore interface)) (apply #'warn string args)) (defun gui-warn (string &rest args) (apply #'gui-warn* *default-interface* string args)) Color (defmethod make-color** (interface red green blue) (declare (ignore interface red green blue)) (values 0)) (defun make-color* (red green blue) "given red, green, and blue, returns an encoded rgb value" (make-color** (default-interface) red green blue)) (defmethod make-gray* (interface level) (make-color** interface level level level)) (defun make-gray (level) These use a 0 - 255 scale for component levels (make-gray* (default-interface) level)) (defmethod make-scaled-color* (interface red green blue scale) (make-color** interface (round (* red scale)) (round (* green scale)) (round (* blue scale)))) (defun make-scaled-color (red green blue scale) (make-scaled-color* (default-interface) red green blue scale)) (defmethod y-or-n-question* (interface message &rest args) (declare (ignore interface args)) (y-or-n-p message)) (defun y-or-n-question (message &rest args) (apply #'y-or-n-question* *default-interface* message args)) (defmethod choose-file-question* (interface &rest args) (declare (ignore interface args)) (print "I would love to choose a file for you, but I'm not sure how?")) (defun choose-file-question (&rest args) (apply #'choose-file-question* *default-interface* args)) (defmethod choose-new-file-question* (interface &rest args) (declare (ignore interface args)) (print "I would love to choose a new file name for you, but I'm not sure how?")) (defun choose-new-file-question (&rest args) (apply #'choose-new-file-question* *default-interface* args)) (defmethod choose-directory-question* (interface &rest args) (declare (ignore interface args)) (print "I would love to choose a directory name for you, but I'm not sure how?")) (defun choose-directory-question (&rest args) (apply #'choose-directory-question* *default-interface* args)) (defmethod choose-item-question* (interface list &rest args &key &allow-other-keys) (declare (ignore interface list args)) (print "I would love to choose an item for you, but I'm not sure how?")) (defun choose-item-question (list &rest args &key &allow-other-keys) (apply #'choose-item-question* *default-interface* list args)) (defmethod choose-item-from-pup* (interface the-list &rest args &key &allow-other-keys) (apply #'choose-item-question* interface the-list args)) (defun choose-item-from-pup (the-list &rest args &key &allow-other-keys) "Present an interface to allow a choice from a list. Can throw :cancel." (apply #'choose-item-from-pup* *default-interface* the-list args)) (defun choose-item-from-pup-no-singletons (the-list-or-atom &rest args &key &allow-other-keys) "Like choose-item-from-pup, but just returns the datum if it is an atom or a singleton list." (cond ((atom the-list-or-atom) (values the-list-or-atom)) ((= (length the-list-or-atom) 1) (values (first the-list-or-atom))) (t (apply #'choose-item-from-pup the-list-or-atom args)))) (defmethod make-ui-point* (interface x y) (declare (ignore interface x y)) (values)) (defun make-ui-point (x y) (make-ui-point* *default-interface* x y)) (defmethod process-parameters* (interface &rest args) (declare (ignore interface args)) (values)) (defun process-parameters (&rest args) (apply #'process-parameters* *default-interface* args) (values)) (defmethod put-item-on-clipboard* (interface thing) (declare (ignore interface thing)) (error "I don't know anything about clipboards.")) (defun put-item-on-clipboard (thing) (put-item-on-clipboard* *default-interface* thing) thing) (defmethod inspect-thing* (interface thing &rest args) (declare (ignore interface args)) (error "I don't know how toinspect ~S" thing)) (defun inspect-thing (thing &rest args) (apply #'inspect-thing* *default-interface* thing args) (values thing)) (defun inspect-things (&rest things) (let ((result nil)) (mapc (lambda (thing) (setf result (inspect-thing thing))) things) (values result))) (defmethod sound-note* (interface pitch velocity &rest args) (declare (ignore interface pitch velocity args)) (interface-beep)) (defun sound-note (pitch velocity &rest args) (apply #'sound-note* *default-interface* pitch velocity args)) (defmethod stop-notes* (interface) (declare (ignore interface)) (error "I don't know how to stop music.")) (defun stop-notes () (stop-notes* *default-interface*)) (defmethod select-instrument* (interface instrument &rest args) (declare (ignore interface instrument args)) (error "I don't know how to select instruments.")) (defun select-instrument (instrument &rest args) (apply #'select-instrument* *default-interface* instrument args)) (defun query-user-for-string (prompt &rest args &key &allow-other-keys) (apply #'prompt-for 'string prompt args)) (defun query-user-for-integer (prompt &optional minimum maximum) (catch :cancel (loop do (let ((number (parse-integer (query-user-for-string prompt) :junk-allowed t))) (cond ((null number) ) ((and minimum (< number minimum)) ) ((and maximum (> number maximum)) ) (t (return-from query-user-for-integer number))))))) (defmethod prompt-for* (interface type message &rest args) (declare (ignore interface message args)) (warn "I don't know how to prompt for ~A" type)) (defmethod prompt-for* (interface (type (eql 'string)) message &rest args) (declare (ignore interface)) (apply #'format *query-io* message args) (finish-output *query-io*) (read-line *query-io* nil :eof)) (defmethod prompt-for* (interface (type (eql 'fixnum)) message &rest args) (declare (ignore interface)) (apply #'query-user-for-integer message args)) (defun prompt-for (type message &rest args) (apply #'prompt-for* *default-interface* type message args))
2769b19e33a5ec3eb522f6d977b23a1a5dc38794a1de30c396a3a483e8969442
nixeagle/nisp
alerts.lisp
We d Mar 20 17:24:00 1991 by < > ;;; alerts.lisp ;;; **************************************************************** ;;; Alerts: A Convenient Debugging Status Indicator **************** ;;; **************************************************************** ;;; Written by < > ;;; From -cgi.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/lisp/code/ext/alerts/alerts.cl ;;; ;;; Copying/distribution/modification are all allowed by original author. ;;; See: -cgi.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/lisp/code/ext/alerts/0.html ;;; Modifications made to make this compile on sbcl by Copyright ( C ) 2010 , released under the same terms as original author . (in-package :cl-user) (defpackage #:alerts (:use :common-lisp) (:export :set-alert-level :set-alert-stream :alert :query-user)) (in-package :alerts) ;;; ******************************** ;;; Alert Functions **************** ;;; ******************************** ;;; Alert functions (defvar *alert-level* 0 "If alert-level is nil, then expressions within an alert are not defined or invoked. Use (set-alert-level nil) before functions are loaded or defined to do this. If it is done afterwards, they will not be invoked, but their code will still exist.") (defun set-alert-level (&optional (x 0)) (when (numberp x) (setq *alert-level* x))) (defvar *alert-stream* *standard-output* "*standard-output* is redirected to *alert-stream* for all alert output. If nil, output is sent to *standard-output*.") (defun set-alert-stream (&optional x) (cond ((output-stream-p x) (setq *alert-stream* x)) ((null x) (setq *alert-stream* *error-output*)))) (defmacro alert (level &rest ops) "Alert user macro -- (alert level (operation1) (operation2)...) When *alert-level* is less than or equal to level, perform the specified operations. If LEVEL is t, always perform them (equivalent to progn) and ignore the alert-level setting. Typically: level = 0 interesting comments of no real importance level = 1 minor status notes level = 2 major status notes level = 3 warnings level = 4 real problems level = t fatal errors If the first argument after the level is a string, there is an implicit format command. (alert 4 \"~%Alert! ~A is bad\" arg) = (alert 4 (format t \"~%Alert! ~A is bad\" arg))" (when (stringp (car ops)) (setq ops `((format t ,@ops)))) (when (or (eq level t) (numberp *alert-level*)) `(when ,(if (numberp level) `(and (numberp *alert-level*) (>= ,level *alert-level*)) level) (let ((*standard-output* (or *alert-stream* *standard-output*))) (fresh-line *standard-output*) ,@ops (force-output *standard-output*))))) (defmacro query-user (&rest ops) "Query user macro -- (query (operation1) (operation2)...) If the first argument after the level is a string, there is an implicit format command. (alert 4 \"~%Alert! ~A is bad\" arg) = (alert 4 (format t \"~%Alert! ~A is bad\" arg))" (when (stringp (car ops)) (setq ops `((format t ,@ops)))) `(progn ,@ops (force-output) (read))) ;;; *EOF*
null
https://raw.githubusercontent.com/nixeagle/nisp/680b40b3b9ea4c33db0455ac73cbe3756afdbb1e/3rd-party/alerts.lisp
lisp
alerts.lisp **************************************************************** Alerts: A Convenient Debugging Status Indicator **************** **************************************************************** Copying/distribution/modification are all allowed by original author. See: -cgi.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/lisp/code/ext/alerts/0.html ******************************** Alert Functions **************** ******************************** Alert functions *EOF*
We d Mar 20 17:24:00 1991 by < > Written by < > From -cgi.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/lisp/code/ext/alerts/alerts.cl Modifications made to make this compile on sbcl by Copyright ( C ) 2010 , released under the same terms as original author . (in-package :cl-user) (defpackage #:alerts (:use :common-lisp) (:export :set-alert-level :set-alert-stream :alert :query-user)) (in-package :alerts) (defvar *alert-level* 0 "If alert-level is nil, then expressions within an alert are not defined or invoked. Use (set-alert-level nil) before functions are loaded or defined to do this. If it is done afterwards, they will not be invoked, but their code will still exist.") (defun set-alert-level (&optional (x 0)) (when (numberp x) (setq *alert-level* x))) (defvar *alert-stream* *standard-output* "*standard-output* is redirected to *alert-stream* for all alert output. If nil, output is sent to *standard-output*.") (defun set-alert-stream (&optional x) (cond ((output-stream-p x) (setq *alert-stream* x)) ((null x) (setq *alert-stream* *error-output*)))) (defmacro alert (level &rest ops) "Alert user macro -- (alert level (operation1) (operation2)...) When *alert-level* is less than or equal to level, perform the specified operations. If LEVEL is t, always perform them (equivalent to progn) and ignore the alert-level setting. Typically: level = 0 interesting comments of no real importance level = 1 minor status notes level = 2 major status notes level = 3 warnings level = 4 real problems level = t fatal errors If the first argument after the level is a string, there is an implicit format command. (alert 4 \"~%Alert! ~A is bad\" arg) = (alert 4 (format t \"~%Alert! ~A is bad\" arg))" (when (stringp (car ops)) (setq ops `((format t ,@ops)))) (when (or (eq level t) (numberp *alert-level*)) `(when ,(if (numberp level) `(and (numberp *alert-level*) (>= ,level *alert-level*)) level) (let ((*standard-output* (or *alert-stream* *standard-output*))) (fresh-line *standard-output*) ,@ops (force-output *standard-output*))))) (defmacro query-user (&rest ops) "Query user macro -- (query (operation1) (operation2)...) If the first argument after the level is a string, there is an implicit format command. (alert 4 \"~%Alert! ~A is bad\" arg) = (alert 4 (format t \"~%Alert! ~A is bad\" arg))" (when (stringp (car ops)) (setq ops `((format t ,@ops)))) `(progn ,@ops (force-output) (read)))
17e0193576dcd464036eef0364ffbc745494d2442f2e7cb617ff77e761a98770
HealthSamurai/us-npi
beat_test.clj
(ns usnpi.beat-test (:require [clojure.test :refer :all] [usnpi.db :as db] [usnpi.error :refer [error!]] [usnpi.beat :as beat] [usnpi.tasks :as tasks] [usnpi.time :as time])) (defn task-test-ok [] (/ 2 1)) (defn task-test-err [] (error! "Failure example")) (deftest test-beat-start-stop (when (beat/status) (beat/stop)) (is (not (beat/status))) (beat/start) (is (beat/status)) (is (thrown? Exception (beat/start))) (beat/stop) (is (not (beat/status))) (is (thrown? Exception (beat/stop)))) (deftest test-beat-scheduler (db/execute! "truncate tasks") (tasks/seed-task "usnpi.beat-test/task-test-ok" 60) (tasks/seed-task "usnpi.beat-test/task-test-err" 60) (when-not (beat/status) (beat/start)) (Thread/sleep (* 1000 1)) (let [tasks (db/query "select * from tasks order by id") [task1 task2] tasks] (-> task1 :success is) (-> task2 :success not is) (-> task2 :message (= "java.lang.Exception: Failure example") is) (is (= (compare (:next_run_at task1) (time/now)) 1)) (is (= (compare (:next_run_at task2) (time/now)) 1)) (db/execute! "truncate tasks")) (beat/stop))
null
https://raw.githubusercontent.com/HealthSamurai/us-npi/a28a8ec8d45e19fadab0528791e7de78f19dc87e/test/usnpi/beat_test.clj
clojure
(ns usnpi.beat-test (:require [clojure.test :refer :all] [usnpi.db :as db] [usnpi.error :refer [error!]] [usnpi.beat :as beat] [usnpi.tasks :as tasks] [usnpi.time :as time])) (defn task-test-ok [] (/ 2 1)) (defn task-test-err [] (error! "Failure example")) (deftest test-beat-start-stop (when (beat/status) (beat/stop)) (is (not (beat/status))) (beat/start) (is (beat/status)) (is (thrown? Exception (beat/start))) (beat/stop) (is (not (beat/status))) (is (thrown? Exception (beat/stop)))) (deftest test-beat-scheduler (db/execute! "truncate tasks") (tasks/seed-task "usnpi.beat-test/task-test-ok" 60) (tasks/seed-task "usnpi.beat-test/task-test-err" 60) (when-not (beat/status) (beat/start)) (Thread/sleep (* 1000 1)) (let [tasks (db/query "select * from tasks order by id") [task1 task2] tasks] (-> task1 :success is) (-> task2 :success not is) (-> task2 :message (= "java.lang.Exception: Failure example") is) (is (= (compare (:next_run_at task1) (time/now)) 1)) (is (= (compare (:next_run_at task2) (time/now)) 1)) (db/execute! "truncate tasks")) (beat/stop))
072eed850b006aa852f201d23987c2d71958f49dcc2c91cde2d5d7d8053bccbf
input-output-hk/rscoin-core
CoinSpec.hs
# LANGUAGE ViewPatterns # | RSCoin . Core . Coin specification module Test.RSCoin.Core.CoinSpec ( spec ) where import qualified Data.IntMap.Strict as M (mapWithKey, member, size, (!)) import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck (NonEmptyList (..)) import qualified RSCoin.Core as C spec :: Spec spec = describe "Coin" $ do describe "sameColor" $ prop "returns true iff coins have same color" sameColorCorrect describe "sumCoin" $ prop description_sumCoinReturnsSum sumCoinReturnsSum describe "coinsToMap" $ prop description_coinsToMapTest verifyStructureCoinsListToMap describe "addCoinsMap" $ prop description_coinsMapSum verifyCoinsMapSum describe "subtractCoinsMap" $ prop description_coinsMapSubtract verifyCoinsMapSubtract where description_sumCoinReturnsSum = "given non-empty list of coins with " ++ "the same color, returns coin with the same color and value equal to " ++ "sum of values" description_coinsToMapTest = "given list of coins with the color, returns map with one element " ++ "(key is this color, value is sum of coins)" description_coinsMapSum = "for each color in the first map, if there exists this color in " ++ "the second map, then value in the first map is increased by " ++ "corresponding value from the second map." description_coinsMapSubtract = "for each color in the first map, if there exists this color in " ++ "the second map, then value in the first map is decreased by " ++ "corresponding value from the second map." sameColorCorrect :: C.Coin -> C.Coin -> Bool sameColorCorrect c1 c2 = (C.coinColor c1 == C.coinColor c2) == C.sameColor c1 c2 sumCoinReturnsSum :: C.Color -> NonEmptyList Rational -> Bool sumCoinReturnsSum color (getNonEmpty -> values) = let coins = map (C.Coin color . C.CoinAmount) values s = C.sumCoin coins expected = C.Coin color $ C.CoinAmount $ sum values in s == expected -- | This property does the following: -- * generate list of coins, giving them all the same color; * transform this list into a CoinMap cmap ; * check that cmap has size one ( only one color as a key ) . verifyStructureCoinsListToMap :: [C.Coin] -> Bool verifyStructureCoinsListToMap coins = let coins' = filter ((/=0) . C.coinAmount) coins col = C.coinColor $ head coins' sameCol = map (\(C.Coin _ c) -> C.Coin col c) coins' cMap = C.coinsToMap sameCol in null coins' || (M.size cMap == 1) -- | These properties do the following: * generate two CoinsMap m1 and -- * for every color in the map: -- * give its corresponding coin that color (so the operations are safe); * perform addCoinsMap ( subtractCoinsMap , respectively ) on these two maps ; * for every color in this third map : -- * verify it's the sum (subtraction, respectively) of -- * the corresponding values in m1 and m2. verifyCoinsMapSum :: C.CoinsMap -> C.CoinsMap -> Bool verifyCoinsMapSum = coinsMapOperation (+) C.addCoinsMap verifyCoinsMapSubtract :: C.CoinsMap -> C.CoinsMap -> Bool verifyCoinsMapSubtract = coinsMapOperation (-) C.subtractCoinsMap coinsMapOperation :: (C.Coin -> C.Coin -> C.Coin) -> (C.CoinsMap -> C.CoinsMap -> C.CoinsMap) -> C.CoinsMap -> C.CoinsMap -> Bool coinsMapOperation op mapFun mp1 mp2 = let f = M.mapWithKey (\col (C.Coin _ cn) -> C.Coin (C.Color col) cn) (m1,m2) = (f mp1, f mp2) opMap = mapFun m1 m2 step col coin = if col `M.member` m2 then coin == (m1 M.! col) `op` (m2 M.! col) else True in and $ M.mapWithKey step opMap
null
https://raw.githubusercontent.com/input-output-hk/rscoin-core/5b3fde8de1bdce71ee6ea0e8f1582ea28f451171/test/Test/RSCoin/Core/CoinSpec.hs
haskell
| This property does the following: * generate list of coins, giving them all the same color; | These properties do the following: * for every color in the map: * give its corresponding coin that color (so the operations are safe); * verify it's the sum (subtraction, respectively) of * the corresponding values in m1 and m2.
# LANGUAGE ViewPatterns # | RSCoin . Core . Coin specification module Test.RSCoin.Core.CoinSpec ( spec ) where import qualified Data.IntMap.Strict as M (mapWithKey, member, size, (!)) import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck (NonEmptyList (..)) import qualified RSCoin.Core as C spec :: Spec spec = describe "Coin" $ do describe "sameColor" $ prop "returns true iff coins have same color" sameColorCorrect describe "sumCoin" $ prop description_sumCoinReturnsSum sumCoinReturnsSum describe "coinsToMap" $ prop description_coinsToMapTest verifyStructureCoinsListToMap describe "addCoinsMap" $ prop description_coinsMapSum verifyCoinsMapSum describe "subtractCoinsMap" $ prop description_coinsMapSubtract verifyCoinsMapSubtract where description_sumCoinReturnsSum = "given non-empty list of coins with " ++ "the same color, returns coin with the same color and value equal to " ++ "sum of values" description_coinsToMapTest = "given list of coins with the color, returns map with one element " ++ "(key is this color, value is sum of coins)" description_coinsMapSum = "for each color in the first map, if there exists this color in " ++ "the second map, then value in the first map is increased by " ++ "corresponding value from the second map." description_coinsMapSubtract = "for each color in the first map, if there exists this color in " ++ "the second map, then value in the first map is decreased by " ++ "corresponding value from the second map." sameColorCorrect :: C.Coin -> C.Coin -> Bool sameColorCorrect c1 c2 = (C.coinColor c1 == C.coinColor c2) == C.sameColor c1 c2 sumCoinReturnsSum :: C.Color -> NonEmptyList Rational -> Bool sumCoinReturnsSum color (getNonEmpty -> values) = let coins = map (C.Coin color . C.CoinAmount) values s = C.sumCoin coins expected = C.Coin color $ C.CoinAmount $ sum values in s == expected * transform this list into a CoinMap cmap ; * check that cmap has size one ( only one color as a key ) . verifyStructureCoinsListToMap :: [C.Coin] -> Bool verifyStructureCoinsListToMap coins = let coins' = filter ((/=0) . C.coinAmount) coins col = C.coinColor $ head coins' sameCol = map (\(C.Coin _ c) -> C.Coin col c) coins' cMap = C.coinsToMap sameCol in null coins' || (M.size cMap == 1) * generate two CoinsMap m1 and * perform addCoinsMap ( subtractCoinsMap , respectively ) on these two maps ; * for every color in this third map : verifyCoinsMapSum :: C.CoinsMap -> C.CoinsMap -> Bool verifyCoinsMapSum = coinsMapOperation (+) C.addCoinsMap verifyCoinsMapSubtract :: C.CoinsMap -> C.CoinsMap -> Bool verifyCoinsMapSubtract = coinsMapOperation (-) C.subtractCoinsMap coinsMapOperation :: (C.Coin -> C.Coin -> C.Coin) -> (C.CoinsMap -> C.CoinsMap -> C.CoinsMap) -> C.CoinsMap -> C.CoinsMap -> Bool coinsMapOperation op mapFun mp1 mp2 = let f = M.mapWithKey (\col (C.Coin _ cn) -> C.Coin (C.Color col) cn) (m1,m2) = (f mp1, f mp2) opMap = mapFun m1 m2 step col coin = if col `M.member` m2 then coin == (m1 M.! col) `op` (m2 M.! col) else True in and $ M.mapWithKey step opMap
7829285382dc44a72e2faf4b0c08a758d441dafe57d7b354da36695cf2fe1f06
ucsd-progsys/liquidhaskell
Records.hs
{-@ LIQUID "--expect-any-error" @-} module Records where import qualified Data.Set as S import GHC.CString -- This import interprets Strings as constants! import DataBase data Value = I Int @ rec : : { v : Dict < { \x y - > true } > String Value | listElts ( ddom v ) ~~ ( Set_sng " bar " ) } @ rec :: Dict String Value rec = ("foo" := I 8) += empty unsafe :: Dict String Value unsafe = ("bar" := I 8) += empty
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/benchmarks/icfp15/neg/Records.hs
haskell
@ LIQUID "--expect-any-error" @ This import interprets Strings as constants!
module Records where import qualified Data.Set as S import DataBase data Value = I Int @ rec : : { v : Dict < { \x y - > true } > String Value | listElts ( ddom v ) ~~ ( Set_sng " bar " ) } @ rec :: Dict String Value rec = ("foo" := I 8) += empty unsafe :: Dict String Value unsafe = ("bar" := I 8) += empty
2007043b661673a282600dbb0f4ea53fd543243863bb57e20acd14a4f2500428
monadfix/ormolu-live
ForeignCall.hs
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998 \section[Foreign]{Foreign calls } (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[Foreign]{Foreign calls} -} {-# LANGUAGE DeriveDataTypeable #-} module ForeignCall ( ForeignCall(..), isSafeForeignCall, Safety(..), playSafe, playInterruptible, CExportSpec(..), CLabelString, isCLabelString, pprCLabelString, CCallSpec(..), CCallTarget(..), isDynamicTarget, CCallConv(..), defaultCCallConv, ccallConvToInt, ccallConvAttribute, Header(..), CType(..), ) where import GhcPrelude import FastString import Binary import Outputable import Module import BasicTypes ( SourceText, pprWithSourceText ) import Data.Char import Data.Data {- ************************************************************************ * * \subsubsection{Data types} * * ************************************************************************ -} newtype ForeignCall = CCall CCallSpec deriving Eq isSafeForeignCall :: ForeignCall -> Bool isSafeForeignCall (CCall (CCallSpec _ _ safe)) = playSafe safe -- We may need more clues to distinguish foreign calls -- but this simple printer will do for now instance Outputable ForeignCall where ppr (CCall cc) = ppr cc data Safety Might invoke Haskell GC , or do a call back , or -- switch threads, etc. So make sure things are -- tidy before the call. Additionally, in the threaded -- RTS we arrange for the external call to be executed -- by a separate OS thread, i.e., _concurrently_ to the execution of other threads . | PlayInterruptible -- Like PlaySafe, but additionally -- the worker thread running this foreign call may -- be unceremoniously killed, so it must be scheduled -- on an unbound thread. | PlayRisky -- None of the above can happen; the call will return -- without interacting with the runtime system at all deriving ( Eq, Show, Data ) Show used just for Show Lex . , I think instance Outputable Safety where ppr PlaySafe = text "safe" ppr PlayInterruptible = text "interruptible" ppr PlayRisky = text "unsafe" playSafe :: Safety -> Bool playSafe PlaySafe = True playSafe PlayInterruptible = True playSafe PlayRisky = False playInterruptible :: Safety -> Bool playInterruptible PlayInterruptible = True playInterruptible _ = False {- ************************************************************************ * * \subsubsection{Calling C} * * ************************************************************************ -} data CExportSpec = CExportStatic -- foreign export ccall foo :: ty SourceText -- of the CLabelString. See note [ Pragma source text ] in CLabelString -- C Name of exported function CCallConv deriving Data data CCallSpec = CCallSpec CCallTarget -- What to call CCallConv -- Calling convention to use. Safety deriving( Eq ) -- The call target: -- | How to call a particular function in C-land. data CCallTarget -- An "unboxed" ccall# to named function in a particular package. = StaticTarget SourceText -- of the CLabelString. See note [ Pragma source text ] in CLabelString -- C-land name of label. (Maybe UnitId) -- What package the function is in. -- If Nothing, then it's taken to be in the current package. Note : This information is only used for PrimCalls on Windows . See CLabel.labelDynamic and CoreToStg.coreToStgApp for the difference in representation between PrimCalls and ForeignCalls . If the CCallTarget is representing a regular ForeignCall then it 's safe to set this to Nothing . The first argument of the import is the name of a function pointer ( an Addr # ) . -- Used when importing a label as "foreign import ccall "dynamic" ..." Bool -- True => really a function -- False => a value; only allowed in CAPI imports | DynamicTarget deriving( Eq, Data ) isDynamicTarget :: CCallTarget -> Bool isDynamicTarget DynamicTarget = True isDynamicTarget _ = False Stuff to do with calling convention : ccall : Caller allocates parameters , * and * deallocates them . stdcall : Caller allocates parameters , callee deallocates . Function name has @N after it , where N is number of arg bytes e.g. _ Foo@8 . This convention is x86 ( win32 ) specific . See : Stuff to do with calling convention: ccall: Caller allocates parameters, *and* deallocates them. stdcall: Caller allocates parameters, callee deallocates. Function name has @N after it, where N is number of arg bytes e.g. _Foo@8. This convention is x86 (win32) specific. See: -conventions -} any changes here should be replicated in the CallConv type in template haskell data CCallConv = CCallConv | CApiConv | StdCallConv | PrimCallConv | JavaScriptCallConv deriving (Eq, Data) instance Outputable CCallConv where ppr StdCallConv = text "stdcall" ppr CCallConv = text "ccall" ppr CApiConv = text "capi" ppr PrimCallConv = text "prim" ppr JavaScriptCallConv = text "javascript" defaultCCallConv :: CCallConv defaultCCallConv = CCallConv ccallConvToInt :: CCallConv -> Int ccallConvToInt StdCallConv = 0 ccallConvToInt CCallConv = 1 ccallConvToInt CApiConv = panic "ccallConvToInt CApiConv" ccallConvToInt (PrimCallConv {}) = panic "ccallConvToInt PrimCallConv" ccallConvToInt JavaScriptCallConv = panic "ccallConvToInt JavaScriptCallConv" Generate the gcc attribute corresponding to the given calling convention ( used by PprAbsC ): Generate the gcc attribute corresponding to the given calling convention (used by PprAbsC): -} ccallConvAttribute :: CCallConv -> SDoc ccallConvAttribute StdCallConv = text "__attribute__((__stdcall__))" ccallConvAttribute CCallConv = empty ccallConvAttribute CApiConv = empty ccallConvAttribute (PrimCallConv {}) = panic "ccallConvAttribute PrimCallConv" ccallConvAttribute JavaScriptCallConv = panic "ccallConvAttribute JavaScriptCallConv" type CLabelString = FastString -- A C label, completely unencoded pprCLabelString :: CLabelString -> SDoc pprCLabelString lbl = ftext lbl isCLabelString :: CLabelString -> Bool -- Checks to see if this is a valid C label isCLabelString lbl = all ok (unpackFS lbl) where ok c = isAlphaNum c || c == '_' || c == '.' The ' . ' appears in e.g. " " in the -- module part of a ExtName. Maybe it should be separate -- Printing into C files: instance Outputable CExportSpec where ppr (CExportStatic _ str _) = pprCLabelString str instance Outputable CCallSpec where ppr (CCallSpec fun cconv safety) = hcat [ whenPprDebug callconv, ppr_fun fun ] where callconv = text "{-" <> ppr cconv <> text "-}" gc_suf | playSafe safety = text "_GC" | otherwise = empty ppr_fun (StaticTarget st _fn mPkgId isFun) = text (if isFun then "__pkg_ccall" else "__pkg_ccall_value") <> gc_suf <+> (case mPkgId of Nothing -> empty Just pkgId -> ppr pkgId) <+> (pprWithSourceText st empty) ppr_fun DynamicTarget = text "__dyn_ccall" <> gc_suf <+> text "\"\"" -- The filename for a C header file Note [ Pragma source text ] in data Header = Header SourceText FastString deriving (Eq, Data) instance Outputable Header where ppr (Header st h) = pprWithSourceText st (doubleQuotes $ ppr h) | A C type , used in CAPI FFI calls -- - ' ApiAnnotation . AnnKeywordId ' : ' ApiAnnotation . AnnOpen ' @'{-\ , -- 'ApiAnnotation.AnnHeader','ApiAnnotation.AnnVal', ' ApiAnnotation . ' @'\#-}'@ , -- For details on above see note [Api annotations] in ApiAnnotation Note [ Pragma source text ] in (Maybe Header) -- header to include for this type (SourceText,FastString) -- the type itself deriving (Eq, Data) instance Outputable CType where ppr (CType stp mh (stct,ct)) = pprWithSourceText stp (text "{-# CTYPE") <+> hDoc <+> pprWithSourceText stct (doubleQuotes (ftext ct)) <+> text "#-}" where hDoc = case mh of Nothing -> empty Just h -> ppr h {- ************************************************************************ * * \subsubsection{Misc} * * ************************************************************************ -} instance Binary ForeignCall where put_ bh (CCall aa) = put_ bh aa get bh = do aa <- get bh; return (CCall aa) instance Binary Safety where put_ bh PlaySafe = do putByte bh 0 put_ bh PlayInterruptible = do putByte bh 1 put_ bh PlayRisky = do putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do return PlaySafe 1 -> do return PlayInterruptible _ -> do return PlayRisky instance Binary CExportSpec where put_ bh (CExportStatic ss aa ab) = do put_ bh ss put_ bh aa put_ bh ab get bh = do ss <- get bh aa <- get bh ab <- get bh return (CExportStatic ss aa ab) instance Binary CCallSpec where put_ bh (CCallSpec aa ab ac) = do put_ bh aa put_ bh ab put_ bh ac get bh = do aa <- get bh ab <- get bh ac <- get bh return (CCallSpec aa ab ac) instance Binary CCallTarget where put_ bh (StaticTarget ss aa ab ac) = do putByte bh 0 put_ bh ss put_ bh aa put_ bh ab put_ bh ac put_ bh DynamicTarget = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do ss <- get bh aa <- get bh ab <- get bh ac <- get bh return (StaticTarget ss aa ab ac) _ -> do return DynamicTarget instance Binary CCallConv where put_ bh CCallConv = do putByte bh 0 put_ bh StdCallConv = do putByte bh 1 put_ bh PrimCallConv = do putByte bh 2 put_ bh CApiConv = do putByte bh 3 put_ bh JavaScriptCallConv = do putByte bh 4 get bh = do h <- getByte bh case h of 0 -> do return CCallConv 1 -> do return StdCallConv 2 -> do return PrimCallConv 3 -> do return CApiConv _ -> do return JavaScriptCallConv instance Binary CType where put_ bh (CType s mh fs) = do put_ bh s put_ bh mh put_ bh fs get bh = do s <- get bh mh <- get bh fs <- get bh return (CType s mh fs) instance Binary Header where put_ bh (Header s h) = put_ bh s >> put_ bh h get bh = do s <- get bh h <- get bh return (Header s h)
null
https://raw.githubusercontent.com/monadfix/ormolu-live/d8ae72ef168b98a8d179d642f70352c88b3ac226/ghc-lib-parser-8.10.1.20200412/compiler/prelude/ForeignCall.hs
haskell
# LANGUAGE DeriveDataTypeable # ************************************************************************ * * \subsubsection{Data types} * * ************************************************************************ We may need more clues to distinguish foreign calls but this simple printer will do for now switch threads, etc. So make sure things are tidy before the call. Additionally, in the threaded RTS we arrange for the external call to be executed by a separate OS thread, i.e., _concurrently_ to the Like PlaySafe, but additionally the worker thread running this foreign call may be unceremoniously killed, so it must be scheduled on an unbound thread. None of the above can happen; the call will return without interacting with the runtime system at all ************************************************************************ * * \subsubsection{Calling C} * * ************************************************************************ foreign export ccall foo :: ty of the CLabelString. C Name of exported function What to call Calling convention to use. The call target: | How to call a particular function in C-land. An "unboxed" ccall# to named function in a particular package. of the CLabelString. C-land name of label. What package the function is in. If Nothing, then it's taken to be in the current package. Used when importing a label as "foreign import ccall "dynamic" ..." True => really a function False => a value; only A C label, completely unencoded Checks to see if this is a valid C label module part of a ExtName. Maybe it should be separate Printing into C files: The filename for a C header file \ , -- 'ApiAnnotation.AnnHeader','ApiAnnotation.AnnVal', ' ApiAnnotation . ' @'\# For details on above see note [Api annotations] in ApiAnnotation header to include for this type the type itself ************************************************************************ * * \subsubsection{Misc} * * ************************************************************************
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998 \section[Foreign]{Foreign calls } (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[Foreign]{Foreign calls} -} module ForeignCall ( ForeignCall(..), isSafeForeignCall, Safety(..), playSafe, playInterruptible, CExportSpec(..), CLabelString, isCLabelString, pprCLabelString, CCallSpec(..), CCallTarget(..), isDynamicTarget, CCallConv(..), defaultCCallConv, ccallConvToInt, ccallConvAttribute, Header(..), CType(..), ) where import GhcPrelude import FastString import Binary import Outputable import Module import BasicTypes ( SourceText, pprWithSourceText ) import Data.Char import Data.Data newtype ForeignCall = CCall CCallSpec deriving Eq isSafeForeignCall :: ForeignCall -> Bool isSafeForeignCall (CCall (CCallSpec _ _ safe)) = playSafe safe instance Outputable ForeignCall where ppr (CCall cc) = ppr cc data Safety Might invoke Haskell GC , or do a call back , or execution of other threads . deriving ( Eq, Show, Data ) Show used just for Show Lex . , I think instance Outputable Safety where ppr PlaySafe = text "safe" ppr PlayInterruptible = text "interruptible" ppr PlayRisky = text "unsafe" playSafe :: Safety -> Bool playSafe PlaySafe = True playSafe PlayInterruptible = True playSafe PlayRisky = False playInterruptible :: Safety -> Bool playInterruptible PlayInterruptible = True playInterruptible _ = False data CExportSpec See note [ Pragma source text ] in CCallConv deriving Data data CCallSpec Safety deriving( Eq ) data CCallTarget = StaticTarget See note [ Pragma source text ] in Note : This information is only used for PrimCalls on Windows . See CLabel.labelDynamic and CoreToStg.coreToStgApp for the difference in representation between PrimCalls and ForeignCalls . If the CCallTarget is representing a regular ForeignCall then it 's safe to set this to Nothing . The first argument of the import is the name of a function pointer ( an Addr # ) . allowed in CAPI imports | DynamicTarget deriving( Eq, Data ) isDynamicTarget :: CCallTarget -> Bool isDynamicTarget DynamicTarget = True isDynamicTarget _ = False Stuff to do with calling convention : ccall : Caller allocates parameters , * and * deallocates them . stdcall : Caller allocates parameters , callee deallocates . Function name has @N after it , where N is number of arg bytes e.g. _ Foo@8 . This convention is x86 ( win32 ) specific . See : Stuff to do with calling convention: ccall: Caller allocates parameters, *and* deallocates them. stdcall: Caller allocates parameters, callee deallocates. Function name has @N after it, where N is number of arg bytes e.g. _Foo@8. This convention is x86 (win32) specific. See: -conventions -} any changes here should be replicated in the CallConv type in template haskell data CCallConv = CCallConv | CApiConv | StdCallConv | PrimCallConv | JavaScriptCallConv deriving (Eq, Data) instance Outputable CCallConv where ppr StdCallConv = text "stdcall" ppr CCallConv = text "ccall" ppr CApiConv = text "capi" ppr PrimCallConv = text "prim" ppr JavaScriptCallConv = text "javascript" defaultCCallConv :: CCallConv defaultCCallConv = CCallConv ccallConvToInt :: CCallConv -> Int ccallConvToInt StdCallConv = 0 ccallConvToInt CCallConv = 1 ccallConvToInt CApiConv = panic "ccallConvToInt CApiConv" ccallConvToInt (PrimCallConv {}) = panic "ccallConvToInt PrimCallConv" ccallConvToInt JavaScriptCallConv = panic "ccallConvToInt JavaScriptCallConv" Generate the gcc attribute corresponding to the given calling convention ( used by PprAbsC ): Generate the gcc attribute corresponding to the given calling convention (used by PprAbsC): -} ccallConvAttribute :: CCallConv -> SDoc ccallConvAttribute StdCallConv = text "__attribute__((__stdcall__))" ccallConvAttribute CCallConv = empty ccallConvAttribute CApiConv = empty ccallConvAttribute (PrimCallConv {}) = panic "ccallConvAttribute PrimCallConv" ccallConvAttribute JavaScriptCallConv = panic "ccallConvAttribute JavaScriptCallConv" pprCLabelString :: CLabelString -> SDoc pprCLabelString lbl = ftext lbl isCLabelString lbl = all ok (unpackFS lbl) where ok c = isAlphaNum c || c == '_' || c == '.' The ' . ' appears in e.g. " " in the instance Outputable CExportSpec where ppr (CExportStatic _ str _) = pprCLabelString str instance Outputable CCallSpec where ppr (CCallSpec fun cconv safety) = hcat [ whenPprDebug callconv, ppr_fun fun ] where callconv = text "{-" <> ppr cconv <> text "-}" gc_suf | playSafe safety = text "_GC" | otherwise = empty ppr_fun (StaticTarget st _fn mPkgId isFun) = text (if isFun then "__pkg_ccall" else "__pkg_ccall_value") <> gc_suf <+> (case mPkgId of Nothing -> empty Just pkgId -> ppr pkgId) <+> (pprWithSourceText st empty) ppr_fun DynamicTarget = text "__dyn_ccall" <> gc_suf <+> text "\"\"" Note [ Pragma source text ] in data Header = Header SourceText FastString deriving (Eq, Data) instance Outputable Header where ppr (Header st h) = pprWithSourceText st (doubleQuotes $ ppr h) | A C type , used in CAPI FFI calls Note [ Pragma source text ] in deriving (Eq, Data) instance Outputable CType where ppr (CType stp mh (stct,ct)) = pprWithSourceText stp (text "{-# CTYPE") <+> hDoc <+> pprWithSourceText stct (doubleQuotes (ftext ct)) <+> text "#-}" where hDoc = case mh of Nothing -> empty Just h -> ppr h instance Binary ForeignCall where put_ bh (CCall aa) = put_ bh aa get bh = do aa <- get bh; return (CCall aa) instance Binary Safety where put_ bh PlaySafe = do putByte bh 0 put_ bh PlayInterruptible = do putByte bh 1 put_ bh PlayRisky = do putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do return PlaySafe 1 -> do return PlayInterruptible _ -> do return PlayRisky instance Binary CExportSpec where put_ bh (CExportStatic ss aa ab) = do put_ bh ss put_ bh aa put_ bh ab get bh = do ss <- get bh aa <- get bh ab <- get bh return (CExportStatic ss aa ab) instance Binary CCallSpec where put_ bh (CCallSpec aa ab ac) = do put_ bh aa put_ bh ab put_ bh ac get bh = do aa <- get bh ab <- get bh ac <- get bh return (CCallSpec aa ab ac) instance Binary CCallTarget where put_ bh (StaticTarget ss aa ab ac) = do putByte bh 0 put_ bh ss put_ bh aa put_ bh ab put_ bh ac put_ bh DynamicTarget = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do ss <- get bh aa <- get bh ab <- get bh ac <- get bh return (StaticTarget ss aa ab ac) _ -> do return DynamicTarget instance Binary CCallConv where put_ bh CCallConv = do putByte bh 0 put_ bh StdCallConv = do putByte bh 1 put_ bh PrimCallConv = do putByte bh 2 put_ bh CApiConv = do putByte bh 3 put_ bh JavaScriptCallConv = do putByte bh 4 get bh = do h <- getByte bh case h of 0 -> do return CCallConv 1 -> do return StdCallConv 2 -> do return PrimCallConv 3 -> do return CApiConv _ -> do return JavaScriptCallConv instance Binary CType where put_ bh (CType s mh fs) = do put_ bh s put_ bh mh put_ bh fs get bh = do s <- get bh mh <- get bh fs <- get bh return (CType s mh fs) instance Binary Header where put_ bh (Header s h) = put_ bh s >> put_ bh h get bh = do s <- get bh h <- get bh return (Header s h)
8f7ec9a3c3e9a3203b823ee643b69e659caa1de0c049e85d83a3c7dffe15c38c
cbilson/Camp
package.clj
(ns camp.tasks.package "Package up project artifacts into a nupkg." (:require [camp.nuget :as nuget])) (defn package "Packages up project targets into a nuget package. The equivalent of `nuget pack'. ***NOT IMPLEMENTED YET***" [project & _] (println "TODO: Gather dlls, exes, and other content in targets/") (println "TODO: Generate manifest") (println "TODO: Create a new OptimizedZipPackage"))
null
https://raw.githubusercontent.com/cbilson/Camp/57320423a4a78df32d8edee58a6e3857e03f7af2/src/camp/tasks/package.clj
clojure
(ns camp.tasks.package "Package up project artifacts into a nupkg." (:require [camp.nuget :as nuget])) (defn package "Packages up project targets into a nuget package. The equivalent of `nuget pack'. ***NOT IMPLEMENTED YET***" [project & _] (println "TODO: Gather dlls, exes, and other content in targets/") (println "TODO: Generate manifest") (println "TODO: Create a new OptimizedZipPackage"))
478187ad2238dd495f1837ea02c4006da726b53aeac8f5bd2a90b13b5aafaa35
acowley/GLUtil
Drawing.hs
-- | Simplify common drawing commands. module Graphics.GLUtil.Drawing where import Foreign.Ptr (nullPtr) import Graphics.Rendering.OpenGL | @drawIndexedTris n@ draws @n@ ' Triangles ' using vertex data from -- the currently bound 'ArrayBuffer' and indices from the beginning of -- the currently bound 'ElementArrayBuffer'. Note that there must be -- at least @n * 3@ indices in the 'ElementArrayBuffer'! drawIndexedTris :: GLsizei -> IO () drawIndexedTris n = drawElements Triangles (n*3) UnsignedInt nullPtr
null
https://raw.githubusercontent.com/acowley/GLUtil/09faac00072b08c72ab12bcc57d4ab2a02ff1c88/src/Graphics/GLUtil/Drawing.hs
haskell
| Simplify common drawing commands. the currently bound 'ArrayBuffer' and indices from the beginning of the currently bound 'ElementArrayBuffer'. Note that there must be at least @n * 3@ indices in the 'ElementArrayBuffer'!
module Graphics.GLUtil.Drawing where import Foreign.Ptr (nullPtr) import Graphics.Rendering.OpenGL | @drawIndexedTris n@ draws @n@ ' Triangles ' using vertex data from drawIndexedTris :: GLsizei -> IO () drawIndexedTris n = drawElements Triangles (n*3) UnsignedInt nullPtr
c7e1694006c48915b0964ff9c53bff6fdde49f6ddd6ea40b669c47ef37ac9431
charlieg/Sparser
fill.lisp
;;; -*- Mode:Lisp; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- copyright ( c ) 1991 Content Technologies Inc. copyright ( c ) 1992 -- all rights reserved ;;; ;;; File: "fill" ;;; module: "interface;windows:articles:" Version : 1.0 January 1991 initiated 1/92 , added file version 3/29/92 (in-package :sparser) ;;;-------------------------------------------- ;;; recording significant segments of the text ;;;-------------------------------------------- (defvar *significant-text-segments* nil "Accumulates records of significant text segments in the article(s) under analysis.") (defun record-significant-text-segment (label start end &rest other-arguments ) (declare (ignore other-arguments)) (push (list label start end) *significant-text-segments*)) ;;;------------------------------------------------- ;;; getting an analyzed text into an article window ;;;------------------------------------------------- (defun fill-article-window/string (string window &key select ) (write-string string window) (ask window (window-update)) (when select (ask window (window-select))) :filled ) (defun fill-article-window/file (file window &key select) (read-from-source-to-window file window) (ask window (window-update)) (when select (ask window (window-select))) :filled )
null
https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/interface/workbench/fill.lisp
lisp
-*- Mode:Lisp; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- File: "fill" module: "interface;windows:articles:" -------------------------------------------- recording significant segments of the text -------------------------------------------- ------------------------------------------------- getting an analyzed text into an article window -------------------------------------------------
copyright ( c ) 1991 Content Technologies Inc. copyright ( c ) 1992 -- all rights reserved Version : 1.0 January 1991 initiated 1/92 , added file version 3/29/92 (in-package :sparser) (defvar *significant-text-segments* nil "Accumulates records of significant text segments in the article(s) under analysis.") (defun record-significant-text-segment (label start end &rest other-arguments ) (declare (ignore other-arguments)) (push (list label start end) *significant-text-segments*)) (defun fill-article-window/string (string window &key select ) (write-string string window) (ask window (window-update)) (when select (ask window (window-select))) :filled ) (defun fill-article-window/file (file window &key select) (read-from-source-to-window file window) (ask window (window-update)) (when select (ask window (window-select))) :filled )
9e26728d64b83018079a2018c0f6ca11372e69ea3352d8e9c4406d9684d0a78a
lvh/caesium
aead.clj
(ns caesium.crypto.aead (:require [caesium.binding :as b] [caesium.byte-bufs :as bb] [caesium.randombytes :as r])) (b/defconsts [chacha20poly1305-ietf-keybytes chacha20poly1305-ietf-nsecbytes chacha20poly1305-ietf-npubbytes chacha20poly1305-ietf-abytes chacha20poly1305-keybytes chacha20poly1305-nsecbytes chacha20poly1305-npubbytes chacha20poly1305-abytes xchacha20poly1305-ietf-keybytes xchacha20poly1305-ietf-nsecbytes xchacha20poly1305-ietf-npubbytes xchacha20poly1305-ietf-abytes]) (defn ^:private chacha20poly1305-ietf-keygen-to-buf! [k] (b/call! chacha20poly1305-ietf-keygen k)) (defn chacha20poly1305-ietf-keygen "Generates a new random key." [] (let [k (bb/alloc chacha20poly1305-ietf-keybytes)] (chacha20poly1305-ietf-keygen-to-buf! k) k)) (defn new-chacha20poly1305-ietf-nonce "Generates a new random nonce." [] (r/randombytes chacha20poly1305-ietf-npubbytes)) (defn ^:private chacha20poly1305-ietf-encrypt-to-buf! [c m ad nsec npub k] (b/call! chacha20poly1305-ietf-encrypt c m ad nsec npub k) c) (defn chacha20poly1305-ietf-encrypt "Encrypts a message using a secret key and public nonce." [m ad npub k] (let [c (bb/alloc (+ (bb/buflen m) chacha20poly1305-ietf-abytes))] (chacha20poly1305-ietf-encrypt-to-buf! c (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes c))) (defn ^:private chacha20poly1305-ietf-decrypt-to-buf! [m nsec c ad npub k] (let [res (b/call! chacha20poly1305-ietf-decrypt m nsec c ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn chacha20poly1305-ietf-decrypt [c ad npub k] (let [m (bb/alloc (- (bb/buflen c) chacha20poly1305-ietf-abytes))] (chacha20poly1305-ietf-decrypt-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private chacha20poly1305-ietf-encrypt-detached-to-buf! [c mac m ad nsec npub k] (b/call! chacha20poly1305-ietf-encrypt-detached c mac m ad nsec npub k)) (defn chacha20poly1305-ietf-encrypt-detached "Encrypts a message using a secret key and public nonce. It returns the cyphertext and auth tag in different hash keys" [m ad npub k] (let [c (bb/alloc (bb/buflen m)) mac (bb/alloc chacha20poly1305-ietf-abytes)] (chacha20poly1305-ietf-encrypt-detached-to-buf! c mac (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) {:c (bb/->bytes c) :mac (bb/->bytes mac)})) (defn ^:private chacha20poly1305-ietf-decrypt-detached-to-buf! [m nsec c mac ad npub k] (let [res (b/call! chacha20poly1305-ietf-decrypt-detached m nsec c mac ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn chacha20poly1305-ietf-decrypt-detached [c mac ad npub k] (let [m (bb/alloc (bb/buflen c))] (chacha20poly1305-ietf-decrypt-detached-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf mac) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private chacha20poly1305-keygen-to-buf! [k] (b/call! chacha20poly1305-keygen k)) (defn chacha20poly1305-keygen "Generates a new random key." [] (let [k (bb/alloc chacha20poly1305-keybytes)] (chacha20poly1305-keygen-to-buf! k) k)) (defn new-chacha20poly1305-nonce "Generates a new random nonce." [] (r/randombytes chacha20poly1305-npubbytes)) (defn ^:private chacha20poly1305-encrypt-to-buf! [c m ad nsec npub k] (b/call! chacha20poly1305-encrypt c m ad nsec npub k) c) (defn chacha20poly1305-encrypt "Encrypts a message using a secret key and public nonce." [m ad npub k] (let [c (bb/alloc (+ (bb/buflen m) chacha20poly1305-abytes))] (chacha20poly1305-encrypt-to-buf! c (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes c))) (defn ^:private chacha20poly1305-decrypt-to-buf! [m nsec c ad npub k] (let [res (b/call! chacha20poly1305-decrypt m nsec c ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn chacha20poly1305-decrypt [c ad npub k] (let [m (bb/alloc (- (bb/buflen c) chacha20poly1305-abytes))] (chacha20poly1305-decrypt-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private chacha20poly1305-encrypt-detached-to-buf! [c mac m ad nsec npub k] (b/call! chacha20poly1305-encrypt-detached c mac m ad nsec npub k)) (defn chacha20poly1305-encrypt-detached "Encrypts a message using a secret key and public nonce. It returns the cyphertext and auth tag in different hash keys" [m ad npub k] (let [c (bb/alloc (bb/buflen m)) mac (bb/alloc chacha20poly1305-abytes)] (chacha20poly1305-encrypt-detached-to-buf! c mac (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) {:c (bb/->bytes c) :mac (bb/->bytes mac)})) (defn ^:private chacha20poly1305-decrypt-detached-to-buf! [m nsec c mac ad npub k] (let [res (b/call! chacha20poly1305-decrypt-detached m nsec c mac ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn chacha20poly1305-decrypt-detached [c mac ad npub k] (let [m (bb/alloc (bb/buflen c))] (chacha20poly1305-decrypt-detached-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf mac) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private xchacha20poly1305-ietf-keygen-to-buf! [k] (b/call! xchacha20poly1305-ietf-keygen k)) (defn xchacha20poly1305-ietf-keygen "Generates a new random key." [] (let [k (bb/alloc xchacha20poly1305-ietf-keybytes)] (xchacha20poly1305-ietf-keygen-to-buf! k) k)) (defn new-xchacha20poly1305-ietf-nonce "Generates a new random nonce." [] (r/randombytes xchacha20poly1305-ietf-npubbytes)) (defn ^:private xchacha20poly1305-encrypt-to-buf! [c m ad nsec npub k] (b/call! xchacha20poly1305-ietf-encrypt c m ad nsec npub k) c) (defn xchacha20poly1305-ietf-encrypt "Encrypts a message using a secret key and public nonce." [m ad npub k] (let [c (bb/alloc (+ (bb/buflen m) xchacha20poly1305-ietf-abytes))] (xchacha20poly1305-encrypt-to-buf! c (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes c))) (defn ^:private xchacha20poly1305-ietf-decrypt-to-buf! [m nsec c ad npub k] (let [res (b/call! xchacha20poly1305-ietf-decrypt m nsec c ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn xchacha20poly1305-ietf-decrypt [c ad npub k] (let [m (bb/alloc (- (bb/buflen c) xchacha20poly1305-ietf-abytes))] (xchacha20poly1305-ietf-decrypt-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private xchacha20poly1305-ietf-encrypt-detached-to-buf! [c mac m ad nsec npub k] (b/call! xchacha20poly1305-ietf-encrypt-detached c mac m ad nsec npub k)) (defn xchacha20poly1305-ietf-encrypt-detached "Encrypts a message using a secret key and public nonce. It returns the cyphertext and auth tag in different hash keys" [m ad npub k] (let [c (bb/alloc (bb/buflen m)) mac (bb/alloc xchacha20poly1305-ietf-abytes)] (xchacha20poly1305-ietf-encrypt-detached-to-buf! c mac (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) {:c (bb/->bytes c) :mac (bb/->bytes mac)})) (defn ^:private xchacha20poly1305-ietf-decrypt-detached-to-buf! [m nsec c mac ad npub k] (let [res (b/call! xchacha20poly1305-ietf-decrypt-detached m nsec c mac ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn xchacha20poly1305-ietf-decrypt-detached [c mac ad npub k] (let [m (bb/alloc (bb/buflen c))] (xchacha20poly1305-ietf-decrypt-detached-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf mac) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m)))
null
https://raw.githubusercontent.com/lvh/caesium/cb90a4325fa48a2e4fb6cad810f340125a53fc57/src/caesium/crypto/aead.clj
clojure
(ns caesium.crypto.aead (:require [caesium.binding :as b] [caesium.byte-bufs :as bb] [caesium.randombytes :as r])) (b/defconsts [chacha20poly1305-ietf-keybytes chacha20poly1305-ietf-nsecbytes chacha20poly1305-ietf-npubbytes chacha20poly1305-ietf-abytes chacha20poly1305-keybytes chacha20poly1305-nsecbytes chacha20poly1305-npubbytes chacha20poly1305-abytes xchacha20poly1305-ietf-keybytes xchacha20poly1305-ietf-nsecbytes xchacha20poly1305-ietf-npubbytes xchacha20poly1305-ietf-abytes]) (defn ^:private chacha20poly1305-ietf-keygen-to-buf! [k] (b/call! chacha20poly1305-ietf-keygen k)) (defn chacha20poly1305-ietf-keygen "Generates a new random key." [] (let [k (bb/alloc chacha20poly1305-ietf-keybytes)] (chacha20poly1305-ietf-keygen-to-buf! k) k)) (defn new-chacha20poly1305-ietf-nonce "Generates a new random nonce." [] (r/randombytes chacha20poly1305-ietf-npubbytes)) (defn ^:private chacha20poly1305-ietf-encrypt-to-buf! [c m ad nsec npub k] (b/call! chacha20poly1305-ietf-encrypt c m ad nsec npub k) c) (defn chacha20poly1305-ietf-encrypt "Encrypts a message using a secret key and public nonce." [m ad npub k] (let [c (bb/alloc (+ (bb/buflen m) chacha20poly1305-ietf-abytes))] (chacha20poly1305-ietf-encrypt-to-buf! c (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes c))) (defn ^:private chacha20poly1305-ietf-decrypt-to-buf! [m nsec c ad npub k] (let [res (b/call! chacha20poly1305-ietf-decrypt m nsec c ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn chacha20poly1305-ietf-decrypt [c ad npub k] (let [m (bb/alloc (- (bb/buflen c) chacha20poly1305-ietf-abytes))] (chacha20poly1305-ietf-decrypt-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private chacha20poly1305-ietf-encrypt-detached-to-buf! [c mac m ad nsec npub k] (b/call! chacha20poly1305-ietf-encrypt-detached c mac m ad nsec npub k)) (defn chacha20poly1305-ietf-encrypt-detached "Encrypts a message using a secret key and public nonce. It returns the cyphertext and auth tag in different hash keys" [m ad npub k] (let [c (bb/alloc (bb/buflen m)) mac (bb/alloc chacha20poly1305-ietf-abytes)] (chacha20poly1305-ietf-encrypt-detached-to-buf! c mac (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) {:c (bb/->bytes c) :mac (bb/->bytes mac)})) (defn ^:private chacha20poly1305-ietf-decrypt-detached-to-buf! [m nsec c mac ad npub k] (let [res (b/call! chacha20poly1305-ietf-decrypt-detached m nsec c mac ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn chacha20poly1305-ietf-decrypt-detached [c mac ad npub k] (let [m (bb/alloc (bb/buflen c))] (chacha20poly1305-ietf-decrypt-detached-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf mac) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private chacha20poly1305-keygen-to-buf! [k] (b/call! chacha20poly1305-keygen k)) (defn chacha20poly1305-keygen "Generates a new random key." [] (let [k (bb/alloc chacha20poly1305-keybytes)] (chacha20poly1305-keygen-to-buf! k) k)) (defn new-chacha20poly1305-nonce "Generates a new random nonce." [] (r/randombytes chacha20poly1305-npubbytes)) (defn ^:private chacha20poly1305-encrypt-to-buf! [c m ad nsec npub k] (b/call! chacha20poly1305-encrypt c m ad nsec npub k) c) (defn chacha20poly1305-encrypt "Encrypts a message using a secret key and public nonce." [m ad npub k] (let [c (bb/alloc (+ (bb/buflen m) chacha20poly1305-abytes))] (chacha20poly1305-encrypt-to-buf! c (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes c))) (defn ^:private chacha20poly1305-decrypt-to-buf! [m nsec c ad npub k] (let [res (b/call! chacha20poly1305-decrypt m nsec c ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn chacha20poly1305-decrypt [c ad npub k] (let [m (bb/alloc (- (bb/buflen c) chacha20poly1305-abytes))] (chacha20poly1305-decrypt-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private chacha20poly1305-encrypt-detached-to-buf! [c mac m ad nsec npub k] (b/call! chacha20poly1305-encrypt-detached c mac m ad nsec npub k)) (defn chacha20poly1305-encrypt-detached "Encrypts a message using a secret key and public nonce. It returns the cyphertext and auth tag in different hash keys" [m ad npub k] (let [c (bb/alloc (bb/buflen m)) mac (bb/alloc chacha20poly1305-abytes)] (chacha20poly1305-encrypt-detached-to-buf! c mac (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) {:c (bb/->bytes c) :mac (bb/->bytes mac)})) (defn ^:private chacha20poly1305-decrypt-detached-to-buf! [m nsec c mac ad npub k] (let [res (b/call! chacha20poly1305-decrypt-detached m nsec c mac ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn chacha20poly1305-decrypt-detached [c mac ad npub k] (let [m (bb/alloc (bb/buflen c))] (chacha20poly1305-decrypt-detached-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf mac) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private xchacha20poly1305-ietf-keygen-to-buf! [k] (b/call! xchacha20poly1305-ietf-keygen k)) (defn xchacha20poly1305-ietf-keygen "Generates a new random key." [] (let [k (bb/alloc xchacha20poly1305-ietf-keybytes)] (xchacha20poly1305-ietf-keygen-to-buf! k) k)) (defn new-xchacha20poly1305-ietf-nonce "Generates a new random nonce." [] (r/randombytes xchacha20poly1305-ietf-npubbytes)) (defn ^:private xchacha20poly1305-encrypt-to-buf! [c m ad nsec npub k] (b/call! xchacha20poly1305-ietf-encrypt c m ad nsec npub k) c) (defn xchacha20poly1305-ietf-encrypt "Encrypts a message using a secret key and public nonce." [m ad npub k] (let [c (bb/alloc (+ (bb/buflen m) xchacha20poly1305-ietf-abytes))] (xchacha20poly1305-encrypt-to-buf! c (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes c))) (defn ^:private xchacha20poly1305-ietf-decrypt-to-buf! [m nsec c ad npub k] (let [res (b/call! xchacha20poly1305-ietf-decrypt m nsec c ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn xchacha20poly1305-ietf-decrypt [c ad npub k] (let [m (bb/alloc (- (bb/buflen c) xchacha20poly1305-ietf-abytes))] (xchacha20poly1305-ietf-decrypt-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m))) (defn ^:private xchacha20poly1305-ietf-encrypt-detached-to-buf! [c mac m ad nsec npub k] (b/call! xchacha20poly1305-ietf-encrypt-detached c mac m ad nsec npub k)) (defn xchacha20poly1305-ietf-encrypt-detached "Encrypts a message using a secret key and public nonce. It returns the cyphertext and auth tag in different hash keys" [m ad npub k] (let [c (bb/alloc (bb/buflen m)) mac (bb/alloc xchacha20poly1305-ietf-abytes)] (xchacha20poly1305-ietf-encrypt-detached-to-buf! c mac (bb/->indirect-byte-buf m) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) {:c (bb/->bytes c) :mac (bb/->bytes mac)})) (defn ^:private xchacha20poly1305-ietf-decrypt-detached-to-buf! [m nsec c mac ad npub k] (let [res (b/call! xchacha20poly1305-ietf-decrypt-detached m nsec c mac ad npub k)] (if (zero? res) c (throw (RuntimeException. "Ciphertext verification failed"))))) (defn xchacha20poly1305-ietf-decrypt-detached [c mac ad npub k] (let [m (bb/alloc (bb/buflen c))] (xchacha20poly1305-ietf-decrypt-detached-to-buf! m (bb/->indirect-byte-buf (bb/alloc 0)) (bb/->indirect-byte-buf c) (bb/->indirect-byte-buf mac) (bb/->indirect-byte-buf ad) (bb/->indirect-byte-buf npub) (bb/->indirect-byte-buf k)) (bb/->bytes m)))
fbcc0e54ec3e72f8dc082898162e3288fa29b276a02f5b740abf2b423e00c752
facebook/infer
ErlangBlock.mli
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module Env = ErlangEnvironment type t = {start: Procdesc.Node.t; exit_success: Procdesc.Node.t; exit_failure: Procdesc.Node.t} val ( |~~> ) : Procdesc.Node.t -> Procdesc.Node.t list -> unit val make_success : (Procdesc.t Env.present, _) Env.t -> t * Two nodes : start = exit_success , and exit_failure is distinct . val make_stuck : (Procdesc.t Env.present, _) Env.t -> t * Like , but start / exit_success contains " prune false " . val make_fail : (Procdesc.t Env.present, _) Env.t -> Procname.t -> t * Like , but start / exit_success calls the given function . The name is " fail " because the given function is supposed to be later ( e.g. , in Pulse ) modeled by a crash . the given function is supposed to be later (e.g., in Pulse) modeled by a crash. *) val all : (Procdesc.t Env.present, _) Env.t -> t list -> t (** Chain a list of blocks together in a conjunctive style: a failure in any block leads to a global failure, and successes lead to the next block. *) val any : (Procdesc.t Env.present, _) Env.t -> t list -> t (** Chain a list of blocks together in a disjunctive style: a success in any block leads to a global success, and failures lead to the next block. *) val make_instruction : (Procdesc.t Env.present, _) Env.t -> ?kind:Procdesc.Node.stmt_nodekind -> Sil.instr list -> t val make_load : (Procdesc.t Env.present, _) Env.t -> Ident.t -> Exp.t -> Typ.t -> t val make_branch : (Procdesc.t Env.present, _) Env.t -> Exp.t -> t (** Make a branch based on the condition: go to success if true, go to failure if false *)
null
https://raw.githubusercontent.com/facebook/infer/fbf40c8bd6fdf492df48ade70b270ad04aad7be0/infer/src/erlang/ErlangBlock.mli
ocaml
* Chain a list of blocks together in a conjunctive style: a failure in any block leads to a global failure, and successes lead to the next block. * Chain a list of blocks together in a disjunctive style: a success in any block leads to a global success, and failures lead to the next block. * Make a branch based on the condition: go to success if true, go to failure if false
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module Env = ErlangEnvironment type t = {start: Procdesc.Node.t; exit_success: Procdesc.Node.t; exit_failure: Procdesc.Node.t} val ( |~~> ) : Procdesc.Node.t -> Procdesc.Node.t list -> unit val make_success : (Procdesc.t Env.present, _) Env.t -> t * Two nodes : start = exit_success , and exit_failure is distinct . val make_stuck : (Procdesc.t Env.present, _) Env.t -> t * Like , but start / exit_success contains " prune false " . val make_fail : (Procdesc.t Env.present, _) Env.t -> Procname.t -> t * Like , but start / exit_success calls the given function . The name is " fail " because the given function is supposed to be later ( e.g. , in Pulse ) modeled by a crash . the given function is supposed to be later (e.g., in Pulse) modeled by a crash. *) val all : (Procdesc.t Env.present, _) Env.t -> t list -> t val any : (Procdesc.t Env.present, _) Env.t -> t list -> t val make_instruction : (Procdesc.t Env.present, _) Env.t -> ?kind:Procdesc.Node.stmt_nodekind -> Sil.instr list -> t val make_load : (Procdesc.t Env.present, _) Env.t -> Ident.t -> Exp.t -> Typ.t -> t val make_branch : (Procdesc.t Env.present, _) Env.t -> Exp.t -> t
bdff0fff010a6b8b966602d14d6923865dc3e1c16e73f9e6181d78a6ca6491da
abengoa/clj-stripe
customers.clj
Copyright ( c ) 2011 . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clj-stripe.test.customers (:use [clj-stripe common customers]) (:require [clojure.test :as test])) (with-token "sk_test_BQokikJOvBiI2HlWgH4olfQ2:" (def test-card (card (number "4242424242424242") (expiration 12 2020) (cvc 123) (owner-name "Mr. Owner"))) (def create-customer-op (create-customer test-card (email "") (description "A test customer") ( trial - end ( + 10000 ( System / currentTimeMillis ) ) ) )) (def customer-result (execute create-customer-op)) (def get-customer-op (get-customer (:id customer-result))) (def get-customer-result (execute get-customer-op)) (def get-all-customers-op (get-customers)) (def get-all-customers-result (execute get-all-customers-op)) (test/deftest customers-test (test/is (= get-customer-result customer-result)) (test/is (some #{(:id get-customer-result)} (map :id (:data get-all-customers-result)))) ) (def new-email (email "a new email")) (def update-customer-op (update-customer (:id customer-result) new-email)) (def update-customer-result (execute update-customer-op)) (def get-customer-op-2 (get-customer (:id customer-result))) (def get-customer-result-2 (execute get-customer-op-2)) (test/deftest modify-customer-test (test/is (= (assoc customer-result :email (get new-email "email")) get-customer-result-2))) (def delete-customer-op (delete-customer (:id customer-result))) (def delete-customer-result (execute delete-customer-op)) (def get-all-customers-result-2 (execute get-all-customers-op)) ;; This test worked at the start of Stripe business, but now there are too many users in the test account ;; and pagination should be used to search for the newly created user. ;(test/deftest delete-customer-test ; (test/is (not (nil? (some #{(:id get-customer-result)} (map :id (:data get-all-customers-result-2))))))) )
null
https://raw.githubusercontent.com/abengoa/clj-stripe/d4870d6ea57140d23385878bcf7faea21cf90da8/test/clj_stripe/test/customers.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. This test worked at the start of Stripe business, but now there are too many users in the test account and pagination should be used to search for the newly created user. (test/deftest delete-customer-test (test/is (not (nil? (some #{(:id get-customer-result)} (map :id (:data get-all-customers-result-2)))))))
Copyright ( c ) 2011 . All rights reserved . (ns clj-stripe.test.customers (:use [clj-stripe common customers]) (:require [clojure.test :as test])) (with-token "sk_test_BQokikJOvBiI2HlWgH4olfQ2:" (def test-card (card (number "4242424242424242") (expiration 12 2020) (cvc 123) (owner-name "Mr. Owner"))) (def create-customer-op (create-customer test-card (email "") (description "A test customer") ( trial - end ( + 10000 ( System / currentTimeMillis ) ) ) )) (def customer-result (execute create-customer-op)) (def get-customer-op (get-customer (:id customer-result))) (def get-customer-result (execute get-customer-op)) (def get-all-customers-op (get-customers)) (def get-all-customers-result (execute get-all-customers-op)) (test/deftest customers-test (test/is (= get-customer-result customer-result)) (test/is (some #{(:id get-customer-result)} (map :id (:data get-all-customers-result)))) ) (def new-email (email "a new email")) (def update-customer-op (update-customer (:id customer-result) new-email)) (def update-customer-result (execute update-customer-op)) (def get-customer-op-2 (get-customer (:id customer-result))) (def get-customer-result-2 (execute get-customer-op-2)) (test/deftest modify-customer-test (test/is (= (assoc customer-result :email (get new-email "email")) get-customer-result-2))) (def delete-customer-op (delete-customer (:id customer-result))) (def delete-customer-result (execute delete-customer-op)) (def get-all-customers-result-2 (execute get-all-customers-op)) )
de0d4051798072933d598eff866b3fb78e92679a8a3ba4921154fa743eabd74d
cognesence/planner
core_test.clj
(ns planner.core-test (:require [clojure.test :refer :all] [planner.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
null
https://raw.githubusercontent.com/cognesence/planner/f8f7d8048d609a248a1a4c1060c17c8784c43b5b/test/planner/core_test.clj
clojure
(ns planner.core-test (:require [clojure.test :refer :all] [planner.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
aeb44a4ab6f54dee865547f5a8b64f26becaa1bd0ecaa34abdd01e584ddf1dfe
dsorokin/aivika
Process.hs
-- | -- Module : Simulation.Aivika.Internal.Process Copyright : Copyright ( c ) 2009 - 2017 , < > -- License : BSD3 Maintainer : < > -- Stability : experimental Tested with : GHC 8.0.1 -- -- This is an internal implementation module that should never be used directly. -- -- A value in the 'Process' monad represents a discontinuous process that -- can suspend in any simulation time point and then resume later in the same -- or another time point. -- -- The process of this type can involve the 'Event', 'Dynamics' and 'Simulation' computations . Moreover , a value in the can be run within -- the @Event@ computation. -- -- A value of the 'ProcessId' type is just an identifier of such a process. -- The characteristic property of the @Process@ type is function ' holdProcess ' -- that suspends the current process for the specified time interval. -- module Simulation.Aivika.Internal.Process (-- * Process Monad ProcessId, Process(..), ProcessLift(..), invokeProcess, -- * Running Process runProcess, runProcessUsingId, runProcessInStartTime, runProcessInStartTimeUsingId, runProcessInStopTime, runProcessInStopTimeUsingId, -- * Spawning Processes spawnProcess, spawnProcessUsingId, spawnProcessWith, spawnProcessUsingIdWith, -- * Enqueuing Process enqueueProcess, enqueueProcessUsingId, -- * Creating Process Identifier newProcessId, processId, processUsingId, -- * Holding, Interrupting, Passivating and Canceling Process holdProcess, interruptProcess, processInterrupted, processInterruptionTime, passivateProcess, passivateProcessBefore, processPassive, reactivateProcess, reactivateProcessImmediately, cancelProcessWithId, cancelProcess, processCancelled, processCancelling, whenCancellingProcess, -- * Awaiting Signal processAwait, -- * Preemption processPreemptionBegin, processPreemptionEnd, processPreemptionBeginning, processPreemptionEnding, -- * Yield of Process processYield, -- * Process Timeout timeoutProcess, timeoutProcessUsingId, -- * Parallelizing Processes processParallel, processParallelUsingIds, processParallel_, processParallelUsingIds_, -- * Exception Handling catchProcess, finallyProcess, throwProcess, -- * Utilities zipProcessParallel, zip3ProcessParallel, unzipProcess, * memoProcess, -- * Never Ending Process neverProcess, * retryProcess, * Statement transferProcess, -- * Debugging traceProcess) where import Data.Maybe import Data.IORef import Control.Exception import Control.Monad import Control.Monad.Trans import Control.Monad.Fail import qualified Control.Monad.Catch as MC import Control.Applicative import Simulation.Aivika.Internal.Specs import Simulation.Aivika.Internal.Parameter import Simulation.Aivika.Internal.Simulation import Simulation.Aivika.Internal.Dynamics import Simulation.Aivika.Internal.Event import Simulation.Aivika.Internal.Cont import Simulation.Aivika.Signal -- | Represents a process identifier. data ProcessId = ProcessId { processStarted :: IORef Bool, processReactCont :: IORef (Maybe (ContParams ())), processContId :: ContId, processInterruptRef :: IORef Bool, processInterruptCont :: IORef (Maybe (ContParams ())), processInterruptTime :: IORef Double, processInterruptVersion :: IORef Int } -- | Specifies a discontinuous process that can suspend at any time -- and then resume later. newtype Process a = Process (ProcessId -> Cont a) -- | A type class to lift the 'Process' computation to other computations. class ProcessLift m where -- | Lift the specified 'Process' computation to another computation. liftProcess :: Process a -> m a instance ProcessLift Process where liftProcess = id -- | Invoke the process computation. invokeProcess :: ProcessId -> Process a -> Cont a # INLINE invokeProcess # invokeProcess pid (Process m) = m pid -- | Hold the process for the specified time period. holdProcess :: Double -> Process () holdProcess dt = Process $ \pid -> Cont $ \c -> Event $ \p -> do when (dt < 0) $ error "Time period dt < 0: holdProcess" let x = processInterruptCont pid t = pointTime p + dt writeIORef x $ Just c writeIORef (processInterruptRef pid) False writeIORef (processInterruptTime pid) t v <- readIORef (processInterruptVersion pid) invokeEvent p $ enqueueEvent t $ Event $ \p -> do v' <- readIORef (processInterruptVersion pid) when (v == v') $ do writeIORef x Nothing invokeEvent p $ resumeCont c () -- | Interrupt a process with the specified identifier if the process -- is held by computation 'holdProcess'. interruptProcess :: ProcessId -> Event () interruptProcess pid = Event $ \p -> do let x = processInterruptCont pid a <- readIORef x case a of Nothing -> return () Just c -> do writeIORef x Nothing writeIORef (processInterruptRef pid) True modifyIORef (processInterruptVersion pid) $ (+) 1 invokeEvent p $ enqueueEvent (pointTime p) $ resumeCont c () -- | Test whether the process with the specified identifier was interrupted. processInterrupted :: ProcessId -> Event Bool processInterrupted pid = Event $ \p -> readIORef (processInterruptRef pid) -- | Return the expected interruption time after finishing the 'holdProcess' computation, -- which value may change if the corresponding process is preempted. processInterruptionTime :: ProcessId -> Event (Maybe Double) processInterruptionTime pid = Event $ \p -> do let x = processInterruptCont pid a <- readIORef x case a of Just c -> do t <- readIORef (processInterruptTime pid) return (Just t) Nothing -> return Nothing -- | Define a reaction when the process with the specified identifier is preempted. processPreempted :: ProcessId -> Event () processPreempted pid = Event $ \p -> do let x = processInterruptCont pid a <- readIORef x case a of Just c -> do writeIORef x Nothing writeIORef (processInterruptRef pid) True modifyIORef (processInterruptVersion pid) $ (+) 1 t <- readIORef (processInterruptTime pid) let dt = t - pointTime p c' = substituteCont c $ \a -> Event $ \p -> invokeEvent p $ invokeCont c $ invokeProcess pid $ holdProcess dt invokeEvent p $ reenterCont c' () Nothing -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> return () Just c -> do let c' = substituteCont c $ reenterCont c writeIORef x $ Just c' -- | Passivate the process. passivateProcess :: Process () passivateProcess = Process $ \pid -> Cont $ \c -> Event $ \p -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> writeIORef x $ Just c Just _ -> error "Cannot passivate the process twice: passivateProcess" -- | Passivate the process before performing some action. passivateProcessBefore :: Event () -> Process () passivateProcessBefore m = Process $ \pid -> Cont $ \c -> Event $ \p -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> do writeIORef x $ Just c invokeEvent p m Just _ -> error "Cannot passivate the process twice: passivateProcessBefore" -- | Test whether the process with the specified identifier is passivated. processPassive :: ProcessId -> Event Bool processPassive pid = Event $ \p -> do let x = processReactCont pid a <- readIORef x return $ isJust a -- | Reactivate a process with the specified identifier. reactivateProcess :: ProcessId -> Event () reactivateProcess pid = Event $ \p -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> return () Just c -> do writeIORef x Nothing invokeEvent p $ enqueueEvent (pointTime p) $ resumeCont c () -- | Reactivate a process with the specified identifier immediately. reactivateProcessImmediately :: ProcessId -> Event () reactivateProcessImmediately pid = Event $ \p -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> return () Just c -> do writeIORef x Nothing invokeEvent p $ resumeCont c () -- | Prepare the processes identifier for running. processIdPrepare :: ProcessId -> Event () processIdPrepare pid = Event $ \p -> do y <- readIORef (processStarted pid) if y then error $ "Another process with the specified identifier " ++ "has been started already: processIdPrepare" else writeIORef (processStarted pid) True let signal = contSignal $ processContId pid invokeEvent p $ handleSignal_ signal $ \e -> Event $ \p -> case e of ContCancellationInitiating -> do z <- contCancellationActivated $ processContId pid when z $ do invokeEvent p $ interruptProcess pid invokeEvent p $ reactivateProcess pid ContPreemptionBeginning -> invokeEvent p $ processPreempted pid ContPreemptionEnding -> return () -- | Run immediately the process. A new 'ProcessId' identifier will be -- assigned to the process. -- -- To run the process at the specified time, you can use -- the 'enqueueProcess' function. runProcess :: Process () -> Event () runProcess p = do pid <- liftSimulation newProcessId runProcessUsingId pid p -- | Run immediately the process with the specified identifier. -- It will be more efficient than as you would specify the process identifier -- with help of the 'processUsingId' combinator and then would call 'runProcess'. -- -- To run the process at the specified time, you can use -- the 'enqueueProcessUsingId' function. runProcessUsingId :: ProcessId -> Process () -> Event () runProcessUsingId pid p = do processIdPrepare pid runCont m cont econt ccont (processContId pid) False where cont = return econt = throwEvent ccont = return m = invokeProcess pid p -- | Run the process in the start time immediately involving all pending -- 'CurrentEvents' in the computation too. runProcessInStartTime :: Process () -> Simulation () runProcessInStartTime = runEventInStartTime . runProcess -- | Run the process in the start time immediately using the specified identifier and involving all pending ' CurrentEvents ' in the computation too . runProcessInStartTimeUsingId :: ProcessId -> Process () -> Simulation () runProcessInStartTimeUsingId pid p = runEventInStartTime $ runProcessUsingId pid p -- | Run the process in the final simulation time immediately involving all pending ' CurrentEvents ' in the computation too . runProcessInStopTime :: Process () -> Simulation () runProcessInStopTime = runEventInStopTime . runProcess -- | Run the process in the final simulation time immediately using the specified identifier and involving all pending ' CurrentEvents ' -- in the computation too. runProcessInStopTimeUsingId :: ProcessId -> Process () -> Simulation () runProcessInStopTimeUsingId pid p = runEventInStopTime $ runProcessUsingId pid p -- | Enqueue the process that will be then started at the specified time -- from the event queue. enqueueProcess :: Double -> Process () -> Event () enqueueProcess t p = enqueueEvent t $ runProcess p -- | Enqueue the process that will be then started at the specified time -- from the event queue. enqueueProcessUsingId :: Double -> ProcessId -> Process () -> Event () enqueueProcessUsingId t pid p = enqueueEvent t $ runProcessUsingId pid p -- | Return the current process identifier. processId :: Process ProcessId processId = Process return -- | Create a new process identifier. newProcessId :: Simulation ProcessId newProcessId = do x <- liftIO $ newIORef Nothing y <- liftIO $ newIORef False c <- newContId i <- liftIO $ newIORef False z <- liftIO $ newIORef Nothing t <- liftIO $ newIORef 0 v <- liftIO $ newIORef 0 return ProcessId { processStarted = y, processReactCont = x, processContId = c, processInterruptRef = i, processInterruptCont = z, processInterruptTime = t, processInterruptVersion = v } -- | Cancel a process with the specified identifier, interrupting it if needed. cancelProcessWithId :: ProcessId -> Event () cancelProcessWithId pid = contCancellationInitiate (processContId pid) -- | The process cancels itself. cancelProcess :: Process a cancelProcess = do pid <- processId liftEvent $ cancelProcessWithId pid throwProcess $ (error "The process must be cancelled already: cancelProcess." :: SomeException) -- | Test whether the process with the specified identifier was cancelled. processCancelled :: ProcessId -> Event Bool processCancelled pid = contCancellationInitiated (processContId pid) -- | Return a signal that notifies about cancelling the process with -- the specified identifier. processCancelling :: ProcessId -> Signal () processCancelling pid = contCancellationInitiating (processContId pid) -- | Register a handler that will be invoked in case of cancelling the current process. whenCancellingProcess :: Event () -> Process () whenCancellingProcess h = Process $ \pid -> liftEvent $ handleSignal_ (processCancelling pid) $ \() -> h -- | Preempt a process with the specified identifier. processPreemptionBegin :: ProcessId -> Event () processPreemptionBegin pid = contPreemptionBegin (processContId pid) -- | Proceed with the process with the specified identifier after it was preempted with help of 'preemptProcessBegin'. processPreemptionEnd :: ProcessId -> Event () processPreemptionEnd pid = contPreemptionEnd (processContId pid) -- | Return a signal when the process is preempted. processPreemptionBeginning :: ProcessId -> Signal () processPreemptionBeginning pid = contPreemptionBeginning (processContId pid) -- | Return a signal when the process is proceeded after it was preempted earlier. processPreemptionEnding :: ProcessId -> Signal () processPreemptionEnding pid = contPreemptionEnding (processContId pid) instance Eq ProcessId where x == y = processReactCont x == processReactCont y -- for the references are unique instance Monad Process where return = returnP m >>= k = bindP m k instance Functor Process where fmap = liftM instance Applicative Process where pure = return (<*>) = ap instance MonadFail Process where fail = error instance ParameterLift Process where liftParameter = liftPP instance SimulationLift Process where liftSimulation = liftSP instance DynamicsLift Process where liftDynamics = liftDP instance EventLift Process where liftEvent = liftEP instance MonadIO Process where liftIO = liftIOP instance MC.MonadThrow Process where throwM = throwProcess instance MC.MonadCatch Process where catch = catchProcess returnP :: a -> Process a # INLINE returnP # returnP a = Process $ \pid -> return a bindP :: Process a -> (a -> Process b) -> Process b # INLINE bindP # bindP (Process m) k = Process $ \pid -> do a <- m pid let Process m' = k a m' pid liftPP :: Parameter a -> Process a # INLINE liftPP # liftPP m = Process $ \pid -> liftParameter m liftSP :: Simulation a -> Process a # INLINE liftSP # liftSP m = Process $ \pid -> liftSimulation m liftDP :: Dynamics a -> Process a # INLINE liftDP # liftDP m = Process $ \pid -> liftDynamics m liftEP :: Event a -> Process a # INLINE liftEP # liftEP m = Process $ \pid -> liftEvent m liftIOP :: IO a -> Process a # INLINE liftIOP # liftIOP m = Process $ \pid -> liftIO m -- | Exception handling within 'Process' computations. catchProcess :: Exception e => Process a -> (e -> Process a) -> Process a catchProcess (Process m) h = Process $ \pid -> catchCont (m pid) $ \e -> let Process m' = h e in m' pid -- | A computation with finalization part. finallyProcess :: Process a -> Process b -> Process a finallyProcess (Process m) (Process m') = Process $ \pid -> finallyCont (m pid) (m' pid) -- | Throw the exception with the further exception handling. -- -- By some reason, an exception raised with help of the standard 'throw' function -- is not handled properly within 'Process' computation, altough it will be still handled -- if it will be wrapped in the 'IO' monad. Therefore, you should use specialised -- functions like the stated one that use the 'throw' function but within the 'IO' computation, -- which allows already handling the exception. throwProcess :: Exception e => e -> Process a throwProcess = liftIO . throw -- | Execute the specified computations in parallel within -- the current computation and return their results. The cancellation -- of any of the nested computations affects the current computation. -- The exception raised in any of the nested computations is propagated -- to the current computation as well. -- -- Here word @parallel@ literally means that the computations are -- actually executed on a single operating system thread but -- they are processed simultaneously by the event queue. -- -- New 'ProcessId' identifiers will be assigned to the started processes. processParallel :: [Process a] -> Process [a] processParallel xs = liftSimulation (processParallelCreateIds xs) >>= processParallelUsingIds | Like ' ' but allows specifying the process identifiers . -- It will be more efficient than as you would specify the process identifiers with help of the ' processUsingId ' combinator and then would call ' ' . processParallelUsingIds :: [(ProcessId, Process a)] -> Process [a] processParallelUsingIds xs = Process $ \pid -> do liftEvent $ processParallelPrepare xs contParallel $ flip map xs $ \(pid, m) -> (invokeProcess pid m, processContId pid) | Like ' ' but ignores the result . processParallel_ :: [Process a] -> Process () processParallel_ xs = liftSimulation (processParallelCreateIds xs) >>= processParallelUsingIds_ -- | Like 'processParallelUsingIds' but ignores the result. processParallelUsingIds_ :: [(ProcessId, Process a)] -> Process () processParallelUsingIds_ xs = Process $ \pid -> do liftEvent $ processParallelPrepare xs contParallel_ $ flip map xs $ \(pid, m) -> (invokeProcess pid m, processContId pid) -- | Create the new process identifiers. processParallelCreateIds :: [Process a] -> Simulation [(ProcessId, Process a)] processParallelCreateIds xs = do pids <- liftSimulation $ forM xs $ const newProcessId return $ zip pids xs -- | Prepare the processes for parallel execution. processParallelPrepare :: [(ProcessId, Process a)] -> Event () processParallelPrepare xs = Event $ \p -> forM_ xs $ invokeEvent p . processIdPrepare . fst -- | Allow calling the process with the specified identifier. It creates a nested process when canceling any of two , or raising an -- @IO@ exception in any of the both, affects the 'Process' computation. -- -- At the same time, the interruption has no such effect as it requires -- explicit specifying the 'ProcessId' identifier of the nested process itself, -- that is the nested process cannot be interrupted using only the parent -- process identifier. processUsingId :: ProcessId -> Process a -> Process a processUsingId pid x = Process $ \pid' -> do liftEvent $ processIdPrepare pid rerunCont (invokeProcess pid x) (processContId pid) | Spawn the child process . In case of cancelling one of the processes , -- other process will be cancelled too. spawnProcess :: Process () -> Process () spawnProcess = spawnProcessWith CancelTogether -- | Spawn the child process with the specified process identifier. In case of cancelling one of the processes , other process will -- be cancelled too. spawnProcessUsingId :: ProcessId -> Process () -> Process () spawnProcessUsingId = spawnProcessUsingIdWith CancelTogether -- | Spawn the child process specifying how the child and parent processes -- should be cancelled in case of need. spawnProcessWith :: ContCancellation -> Process () -> Process () spawnProcessWith cancellation x = do pid <- liftSimulation newProcessId spawnProcessUsingIdWith cancellation pid x -- | Spawn the child process specifying how the child and parent processes -- should be cancelled in case of need. spawnProcessUsingIdWith :: ContCancellation -> ProcessId -> Process () -> Process () spawnProcessUsingIdWith cancellation pid x = Process $ \pid' -> do liftEvent $ processIdPrepare pid spawnCont cancellation (invokeProcess pid x) (processContId pid) -- | Await the signal. processAwait :: Signal a -> Process a processAwait signal = Process $ \pid -> contAwait signal -- | The result of memoization. data MemoResult a = MemoComputed a | MemoError IOException | MemoCancelled -- | Memoize the process so that it would always return the same value -- within the simulation run. memoProcess :: Process a -> Simulation (Process a) memoProcess x = do started <- liftIO $ newIORef False computed <- newSignalSource value <- liftIO $ newIORef Nothing let result = do Just x <- liftIO $ readIORef value case x of MemoComputed a -> return a MemoError e -> throwProcess e MemoCancelled -> cancelProcess return $ do v <- liftIO $ readIORef value case v of Just _ -> result Nothing -> do f <- liftIO $ readIORef started case f of True -> do processAwait $ publishSignal computed result False -> do liftIO $ writeIORef started True r <- liftIO $ newIORef MemoCancelled finallyProcess (catchProcess (do a <- x -- compute only once! liftIO $ writeIORef r (MemoComputed a)) (\e -> liftIO $ writeIORef r (MemoError e))) (liftEvent $ do liftIO $ do x <- readIORef r writeIORef value (Just x) triggerSignal computed ()) result | Zip two parallel processes waiting for the both . zipProcessParallel :: Process a -> Process b -> Process (a, b) zipProcessParallel x y = do [Left a, Right b] <- processParallel [fmap Left x, fmap Right y] return (a, b) | Zip three parallel processes waiting for their results . zip3ProcessParallel :: Process a -> Process b -> Process c -> Process (a, b, c) zip3ProcessParallel x y z = do [Left a, Right (Left b), Right (Right c)] <- processParallel [fmap Left x, fmap (Right . Left) y, fmap (Right . Right) z] return (a, b, c) -- | Unzip the process using memoization so that the both returned -- processes could be applied independently, although they will refer -- to the same pair of values. unzipProcess :: Process (a, b) -> Simulation (Process a, Process b) unzipProcess xy = do xy' <- memoProcess xy return (fmap fst xy', fmap snd xy') -- | Try to run the child process within the specified timeout. -- If the process will finish successfully within this time interval then -- the result wrapped in 'Just' will be returned; otherwise, the child process -- will be cancelled and 'Nothing' will be returned. -- -- If an exception is raised in the child process then it is propagated to -- the parent computation as well. -- -- A cancellation of the child process doesn't lead to cancelling the parent process. -- Then 'Nothing' is returned within the computation. -- -- This is a heavy-weight operation destined for working with arbitrary discontinuous -- processes. Please consider using a more light-weight function 'interruptProcess' or else -- 'cancelProcessWithId' whenever possible. timeoutProcess :: Double -> Process a -> Process (Maybe a) timeoutProcess timeout p = do pid <- liftSimulation newProcessId timeoutProcessUsingId timeout pid p -- | Try to run the child process with the given identifier within the specified timeout. -- If the process will finish successfully within this time interval then -- the result wrapped in 'Just' will be returned; otherwise, the child process -- will be cancelled and 'Nothing' will be returned. -- -- If an exception is raised in the child process then it is propagated to -- the parent computation as well. -- -- A cancellation of the child process doesn't lead to cancelling the parent process. -- Then 'Nothing' is returned within the computation. -- -- This is a heavy-weight operation destined for working with arbitrary discontinuous -- processes. Please consider using a more light-weight function 'interruptProcess' or else -- 'cancelProcessWithId' whenever possible. timeoutProcessUsingId :: Double -> ProcessId -> Process a -> Process (Maybe a) timeoutProcessUsingId timeout pid p = do s <- liftSimulation newSignalSource timeoutPid <- liftSimulation newProcessId spawnProcessUsingIdWith CancelChildAfterParent timeoutPid $ do holdProcess timeout liftEvent $ cancelProcessWithId pid spawnProcessUsingIdWith CancelChildAfterParent pid $ do r <- liftIO $ newIORef Nothing finallyProcess (catchProcess (do a <- p liftIO $ writeIORef r $ Just (Right a)) (\e -> liftIO $ writeIORef r $ Just (Left e))) (liftEvent $ do cancelProcessWithId timeoutPid x <- liftIO $ readIORef r triggerSignal s x) x <- processAwait $ publishSignal s case x of Nothing -> return Nothing Just (Right a) -> return (Just a) Just (Left (SomeException e)) -> throwProcess e -- | Yield to allow other 'Process' and 'Event' computations to run -- at the current simulation time point. processYield :: Process () processYield = Process $ \pid -> Cont $ \c -> Event $ \p -> invokeEvent p $ enqueueEvent (pointTime p) $ resumeCont c () -- | A computation that never computes the result. It behaves like a black hole for -- the discontinuous process, although such a process can still be canceled outside -- (see 'cancelProcessWithId'), but then only its finalization parts (see 'finallyProcess') -- will be called, usually, to release the resources acquired before. neverProcess :: Process a neverProcess = Process $ \pid -> Cont $ \c -> let signal = processCancelling pid in handleSignal_ signal $ \_ -> resumeCont c $ error "It must never be computed: neverProcess" -- | Retry the current computation as possible, using the specified argument -- as a 'SimulationRetry' exception message in case of failure. retryProcess :: String -> Process a retryProcess = liftEvent . retryEvent | Like the GoTo statement it transfers the direction of computation , -- but raises an exception when used within 'catchProcess' or 'finallyProcess'. transferProcess :: Process () -> Process a transferProcess (Process m) = Process $ \pid -> transferCont (m pid) -- | Show the debug message with the current simulation time. traceProcess :: String -> Process a -> Process a traceProcess message m = Process $ \pid -> traceCont message $ invokeProcess pid m
null
https://raw.githubusercontent.com/dsorokin/aivika/7a14f460ab114b0f8cdfcd05d5cc889fdc2db0a4/Simulation/Aivika/Internal/Process.hs
haskell
| Module : Simulation.Aivika.Internal.Process License : BSD3 Stability : experimental This is an internal implementation module that should never be used directly. A value in the 'Process' monad represents a discontinuous process that can suspend in any simulation time point and then resume later in the same or another time point. The process of this type can involve the 'Event', 'Dynamics' and 'Simulation' the @Event@ computation. A value of the 'ProcessId' type is just an identifier of such a process. that suspends the current process for the specified time interval. * Process Monad * Running Process * Spawning Processes * Enqueuing Process * Creating Process Identifier * Holding, Interrupting, Passivating and Canceling Process * Awaiting Signal * Preemption * Yield of Process * Process Timeout * Parallelizing Processes * Exception Handling * Utilities * Never Ending Process * Debugging | Represents a process identifier. | Specifies a discontinuous process that can suspend at any time and then resume later. | A type class to lift the 'Process' computation to other computations. | Lift the specified 'Process' computation to another computation. | Invoke the process computation. | Hold the process for the specified time period. | Interrupt a process with the specified identifier if the process is held by computation 'holdProcess'. | Test whether the process with the specified identifier was interrupted. | Return the expected interruption time after finishing the 'holdProcess' computation, which value may change if the corresponding process is preempted. | Define a reaction when the process with the specified identifier is preempted. | Passivate the process. | Passivate the process before performing some action. | Test whether the process with the specified identifier is passivated. | Reactivate a process with the specified identifier. | Reactivate a process with the specified identifier immediately. | Prepare the processes identifier for running. | Run immediately the process. A new 'ProcessId' identifier will be assigned to the process. To run the process at the specified time, you can use the 'enqueueProcess' function. | Run immediately the process with the specified identifier. It will be more efficient than as you would specify the process identifier with help of the 'processUsingId' combinator and then would call 'runProcess'. To run the process at the specified time, you can use the 'enqueueProcessUsingId' function. | Run the process in the start time immediately involving all pending 'CurrentEvents' in the computation too. | Run the process in the start time immediately using the specified identifier | Run the process in the final simulation time immediately involving all | Run the process in the final simulation time immediately using in the computation too. | Enqueue the process that will be then started at the specified time from the event queue. | Enqueue the process that will be then started at the specified time from the event queue. | Return the current process identifier. | Create a new process identifier. | Cancel a process with the specified identifier, interrupting it if needed. | The process cancels itself. | Test whether the process with the specified identifier was cancelled. | Return a signal that notifies about cancelling the process with the specified identifier. | Register a handler that will be invoked in case of cancelling the current process. | Preempt a process with the specified identifier. | Proceed with the process with the specified identifier after it was preempted with help of 'preemptProcessBegin'. | Return a signal when the process is preempted. | Return a signal when the process is proceeded after it was preempted earlier. for the references are unique | Exception handling within 'Process' computations. | A computation with finalization part. | Throw the exception with the further exception handling. By some reason, an exception raised with help of the standard 'throw' function is not handled properly within 'Process' computation, altough it will be still handled if it will be wrapped in the 'IO' monad. Therefore, you should use specialised functions like the stated one that use the 'throw' function but within the 'IO' computation, which allows already handling the exception. | Execute the specified computations in parallel within the current computation and return their results. The cancellation of any of the nested computations affects the current computation. The exception raised in any of the nested computations is propagated to the current computation as well. Here word @parallel@ literally means that the computations are actually executed on a single operating system thread but they are processed simultaneously by the event queue. New 'ProcessId' identifiers will be assigned to the started processes. It will be more efficient than as you would specify the process identifiers | Like 'processParallelUsingIds' but ignores the result. | Create the new process identifiers. | Prepare the processes for parallel execution. | Allow calling the process with the specified identifier. @IO@ exception in any of the both, affects the 'Process' computation. At the same time, the interruption has no such effect as it requires explicit specifying the 'ProcessId' identifier of the nested process itself, that is the nested process cannot be interrupted using only the parent process identifier. other process will be cancelled too. | Spawn the child process with the specified process identifier. be cancelled too. | Spawn the child process specifying how the child and parent processes should be cancelled in case of need. | Spawn the child process specifying how the child and parent processes should be cancelled in case of need. | Await the signal. | The result of memoization. | Memoize the process so that it would always return the same value within the simulation run. compute only once! | Unzip the process using memoization so that the both returned processes could be applied independently, although they will refer to the same pair of values. | Try to run the child process within the specified timeout. If the process will finish successfully within this time interval then the result wrapped in 'Just' will be returned; otherwise, the child process will be cancelled and 'Nothing' will be returned. If an exception is raised in the child process then it is propagated to the parent computation as well. A cancellation of the child process doesn't lead to cancelling the parent process. Then 'Nothing' is returned within the computation. This is a heavy-weight operation destined for working with arbitrary discontinuous processes. Please consider using a more light-weight function 'interruptProcess' or else 'cancelProcessWithId' whenever possible. | Try to run the child process with the given identifier within the specified timeout. If the process will finish successfully within this time interval then the result wrapped in 'Just' will be returned; otherwise, the child process will be cancelled and 'Nothing' will be returned. If an exception is raised in the child process then it is propagated to the parent computation as well. A cancellation of the child process doesn't lead to cancelling the parent process. Then 'Nothing' is returned within the computation. This is a heavy-weight operation destined for working with arbitrary discontinuous processes. Please consider using a more light-weight function 'interruptProcess' or else 'cancelProcessWithId' whenever possible. | Yield to allow other 'Process' and 'Event' computations to run at the current simulation time point. | A computation that never computes the result. It behaves like a black hole for the discontinuous process, although such a process can still be canceled outside (see 'cancelProcessWithId'), but then only its finalization parts (see 'finallyProcess') will be called, usually, to release the resources acquired before. | Retry the current computation as possible, using the specified argument as a 'SimulationRetry' exception message in case of failure. but raises an exception when used within 'catchProcess' or 'finallyProcess'. | Show the debug message with the current simulation time.
Copyright : Copyright ( c ) 2009 - 2017 , < > Maintainer : < > Tested with : GHC 8.0.1 computations . Moreover , a value in the can be run within The characteristic property of the @Process@ type is function ' holdProcess ' module Simulation.Aivika.Internal.Process ProcessId, Process(..), ProcessLift(..), invokeProcess, runProcess, runProcessUsingId, runProcessInStartTime, runProcessInStartTimeUsingId, runProcessInStopTime, runProcessInStopTimeUsingId, spawnProcess, spawnProcessUsingId, spawnProcessWith, spawnProcessUsingIdWith, enqueueProcess, enqueueProcessUsingId, newProcessId, processId, processUsingId, holdProcess, interruptProcess, processInterrupted, processInterruptionTime, passivateProcess, passivateProcessBefore, processPassive, reactivateProcess, reactivateProcessImmediately, cancelProcessWithId, cancelProcess, processCancelled, processCancelling, whenCancellingProcess, processAwait, processPreemptionBegin, processPreemptionEnd, processPreemptionBeginning, processPreemptionEnding, processYield, timeoutProcess, timeoutProcessUsingId, processParallel, processParallelUsingIds, processParallel_, processParallelUsingIds_, catchProcess, finallyProcess, throwProcess, zipProcessParallel, zip3ProcessParallel, unzipProcess, * memoProcess, neverProcess, * retryProcess, * Statement transferProcess, traceProcess) where import Data.Maybe import Data.IORef import Control.Exception import Control.Monad import Control.Monad.Trans import Control.Monad.Fail import qualified Control.Monad.Catch as MC import Control.Applicative import Simulation.Aivika.Internal.Specs import Simulation.Aivika.Internal.Parameter import Simulation.Aivika.Internal.Simulation import Simulation.Aivika.Internal.Dynamics import Simulation.Aivika.Internal.Event import Simulation.Aivika.Internal.Cont import Simulation.Aivika.Signal data ProcessId = ProcessId { processStarted :: IORef Bool, processReactCont :: IORef (Maybe (ContParams ())), processContId :: ContId, processInterruptRef :: IORef Bool, processInterruptCont :: IORef (Maybe (ContParams ())), processInterruptTime :: IORef Double, processInterruptVersion :: IORef Int } newtype Process a = Process (ProcessId -> Cont a) class ProcessLift m where liftProcess :: Process a -> m a instance ProcessLift Process where liftProcess = id invokeProcess :: ProcessId -> Process a -> Cont a # INLINE invokeProcess # invokeProcess pid (Process m) = m pid holdProcess :: Double -> Process () holdProcess dt = Process $ \pid -> Cont $ \c -> Event $ \p -> do when (dt < 0) $ error "Time period dt < 0: holdProcess" let x = processInterruptCont pid t = pointTime p + dt writeIORef x $ Just c writeIORef (processInterruptRef pid) False writeIORef (processInterruptTime pid) t v <- readIORef (processInterruptVersion pid) invokeEvent p $ enqueueEvent t $ Event $ \p -> do v' <- readIORef (processInterruptVersion pid) when (v == v') $ do writeIORef x Nothing invokeEvent p $ resumeCont c () interruptProcess :: ProcessId -> Event () interruptProcess pid = Event $ \p -> do let x = processInterruptCont pid a <- readIORef x case a of Nothing -> return () Just c -> do writeIORef x Nothing writeIORef (processInterruptRef pid) True modifyIORef (processInterruptVersion pid) $ (+) 1 invokeEvent p $ enqueueEvent (pointTime p) $ resumeCont c () processInterrupted :: ProcessId -> Event Bool processInterrupted pid = Event $ \p -> readIORef (processInterruptRef pid) processInterruptionTime :: ProcessId -> Event (Maybe Double) processInterruptionTime pid = Event $ \p -> do let x = processInterruptCont pid a <- readIORef x case a of Just c -> do t <- readIORef (processInterruptTime pid) return (Just t) Nothing -> return Nothing processPreempted :: ProcessId -> Event () processPreempted pid = Event $ \p -> do let x = processInterruptCont pid a <- readIORef x case a of Just c -> do writeIORef x Nothing writeIORef (processInterruptRef pid) True modifyIORef (processInterruptVersion pid) $ (+) 1 t <- readIORef (processInterruptTime pid) let dt = t - pointTime p c' = substituteCont c $ \a -> Event $ \p -> invokeEvent p $ invokeCont c $ invokeProcess pid $ holdProcess dt invokeEvent p $ reenterCont c' () Nothing -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> return () Just c -> do let c' = substituteCont c $ reenterCont c writeIORef x $ Just c' passivateProcess :: Process () passivateProcess = Process $ \pid -> Cont $ \c -> Event $ \p -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> writeIORef x $ Just c Just _ -> error "Cannot passivate the process twice: passivateProcess" passivateProcessBefore :: Event () -> Process () passivateProcessBefore m = Process $ \pid -> Cont $ \c -> Event $ \p -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> do writeIORef x $ Just c invokeEvent p m Just _ -> error "Cannot passivate the process twice: passivateProcessBefore" processPassive :: ProcessId -> Event Bool processPassive pid = Event $ \p -> do let x = processReactCont pid a <- readIORef x return $ isJust a reactivateProcess :: ProcessId -> Event () reactivateProcess pid = Event $ \p -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> return () Just c -> do writeIORef x Nothing invokeEvent p $ enqueueEvent (pointTime p) $ resumeCont c () reactivateProcessImmediately :: ProcessId -> Event () reactivateProcessImmediately pid = Event $ \p -> do let x = processReactCont pid a <- readIORef x case a of Nothing -> return () Just c -> do writeIORef x Nothing invokeEvent p $ resumeCont c () processIdPrepare :: ProcessId -> Event () processIdPrepare pid = Event $ \p -> do y <- readIORef (processStarted pid) if y then error $ "Another process with the specified identifier " ++ "has been started already: processIdPrepare" else writeIORef (processStarted pid) True let signal = contSignal $ processContId pid invokeEvent p $ handleSignal_ signal $ \e -> Event $ \p -> case e of ContCancellationInitiating -> do z <- contCancellationActivated $ processContId pid when z $ do invokeEvent p $ interruptProcess pid invokeEvent p $ reactivateProcess pid ContPreemptionBeginning -> invokeEvent p $ processPreempted pid ContPreemptionEnding -> return () runProcess :: Process () -> Event () runProcess p = do pid <- liftSimulation newProcessId runProcessUsingId pid p runProcessUsingId :: ProcessId -> Process () -> Event () runProcessUsingId pid p = do processIdPrepare pid runCont m cont econt ccont (processContId pid) False where cont = return econt = throwEvent ccont = return m = invokeProcess pid p runProcessInStartTime :: Process () -> Simulation () runProcessInStartTime = runEventInStartTime . runProcess and involving all pending ' CurrentEvents ' in the computation too . runProcessInStartTimeUsingId :: ProcessId -> Process () -> Simulation () runProcessInStartTimeUsingId pid p = runEventInStartTime $ runProcessUsingId pid p pending ' CurrentEvents ' in the computation too . runProcessInStopTime :: Process () -> Simulation () runProcessInStopTime = runEventInStopTime . runProcess the specified identifier and involving all pending ' CurrentEvents ' runProcessInStopTimeUsingId :: ProcessId -> Process () -> Simulation () runProcessInStopTimeUsingId pid p = runEventInStopTime $ runProcessUsingId pid p enqueueProcess :: Double -> Process () -> Event () enqueueProcess t p = enqueueEvent t $ runProcess p enqueueProcessUsingId :: Double -> ProcessId -> Process () -> Event () enqueueProcessUsingId t pid p = enqueueEvent t $ runProcessUsingId pid p processId :: Process ProcessId processId = Process return newProcessId :: Simulation ProcessId newProcessId = do x <- liftIO $ newIORef Nothing y <- liftIO $ newIORef False c <- newContId i <- liftIO $ newIORef False z <- liftIO $ newIORef Nothing t <- liftIO $ newIORef 0 v <- liftIO $ newIORef 0 return ProcessId { processStarted = y, processReactCont = x, processContId = c, processInterruptRef = i, processInterruptCont = z, processInterruptTime = t, processInterruptVersion = v } cancelProcessWithId :: ProcessId -> Event () cancelProcessWithId pid = contCancellationInitiate (processContId pid) cancelProcess :: Process a cancelProcess = do pid <- processId liftEvent $ cancelProcessWithId pid throwProcess $ (error "The process must be cancelled already: cancelProcess." :: SomeException) processCancelled :: ProcessId -> Event Bool processCancelled pid = contCancellationInitiated (processContId pid) processCancelling :: ProcessId -> Signal () processCancelling pid = contCancellationInitiating (processContId pid) whenCancellingProcess :: Event () -> Process () whenCancellingProcess h = Process $ \pid -> liftEvent $ handleSignal_ (processCancelling pid) $ \() -> h processPreemptionBegin :: ProcessId -> Event () processPreemptionBegin pid = contPreemptionBegin (processContId pid) processPreemptionEnd :: ProcessId -> Event () processPreemptionEnd pid = contPreemptionEnd (processContId pid) processPreemptionBeginning :: ProcessId -> Signal () processPreemptionBeginning pid = contPreemptionBeginning (processContId pid) processPreemptionEnding :: ProcessId -> Signal () processPreemptionEnding pid = contPreemptionEnding (processContId pid) instance Eq ProcessId where instance Monad Process where return = returnP m >>= k = bindP m k instance Functor Process where fmap = liftM instance Applicative Process where pure = return (<*>) = ap instance MonadFail Process where fail = error instance ParameterLift Process where liftParameter = liftPP instance SimulationLift Process where liftSimulation = liftSP instance DynamicsLift Process where liftDynamics = liftDP instance EventLift Process where liftEvent = liftEP instance MonadIO Process where liftIO = liftIOP instance MC.MonadThrow Process where throwM = throwProcess instance MC.MonadCatch Process where catch = catchProcess returnP :: a -> Process a # INLINE returnP # returnP a = Process $ \pid -> return a bindP :: Process a -> (a -> Process b) -> Process b # INLINE bindP # bindP (Process m) k = Process $ \pid -> do a <- m pid let Process m' = k a m' pid liftPP :: Parameter a -> Process a # INLINE liftPP # liftPP m = Process $ \pid -> liftParameter m liftSP :: Simulation a -> Process a # INLINE liftSP # liftSP m = Process $ \pid -> liftSimulation m liftDP :: Dynamics a -> Process a # INLINE liftDP # liftDP m = Process $ \pid -> liftDynamics m liftEP :: Event a -> Process a # INLINE liftEP # liftEP m = Process $ \pid -> liftEvent m liftIOP :: IO a -> Process a # INLINE liftIOP # liftIOP m = Process $ \pid -> liftIO m catchProcess :: Exception e => Process a -> (e -> Process a) -> Process a catchProcess (Process m) h = Process $ \pid -> catchCont (m pid) $ \e -> let Process m' = h e in m' pid finallyProcess :: Process a -> Process b -> Process a finallyProcess (Process m) (Process m') = Process $ \pid -> finallyCont (m pid) (m' pid) throwProcess :: Exception e => e -> Process a throwProcess = liftIO . throw processParallel :: [Process a] -> Process [a] processParallel xs = liftSimulation (processParallelCreateIds xs) >>= processParallelUsingIds | Like ' ' but allows specifying the process identifiers . with help of the ' processUsingId ' combinator and then would call ' ' . processParallelUsingIds :: [(ProcessId, Process a)] -> Process [a] processParallelUsingIds xs = Process $ \pid -> do liftEvent $ processParallelPrepare xs contParallel $ flip map xs $ \(pid, m) -> (invokeProcess pid m, processContId pid) | Like ' ' but ignores the result . processParallel_ :: [Process a] -> Process () processParallel_ xs = liftSimulation (processParallelCreateIds xs) >>= processParallelUsingIds_ processParallelUsingIds_ :: [(ProcessId, Process a)] -> Process () processParallelUsingIds_ xs = Process $ \pid -> do liftEvent $ processParallelPrepare xs contParallel_ $ flip map xs $ \(pid, m) -> (invokeProcess pid m, processContId pid) processParallelCreateIds :: [Process a] -> Simulation [(ProcessId, Process a)] processParallelCreateIds xs = do pids <- liftSimulation $ forM xs $ const newProcessId return $ zip pids xs processParallelPrepare :: [(ProcessId, Process a)] -> Event () processParallelPrepare xs = Event $ \p -> forM_ xs $ invokeEvent p . processIdPrepare . fst It creates a nested process when canceling any of two , or raising an processUsingId :: ProcessId -> Process a -> Process a processUsingId pid x = Process $ \pid' -> do liftEvent $ processIdPrepare pid rerunCont (invokeProcess pid x) (processContId pid) | Spawn the child process . In case of cancelling one of the processes , spawnProcess :: Process () -> Process () spawnProcess = spawnProcessWith CancelTogether In case of cancelling one of the processes , other process will spawnProcessUsingId :: ProcessId -> Process () -> Process () spawnProcessUsingId = spawnProcessUsingIdWith CancelTogether spawnProcessWith :: ContCancellation -> Process () -> Process () spawnProcessWith cancellation x = do pid <- liftSimulation newProcessId spawnProcessUsingIdWith cancellation pid x spawnProcessUsingIdWith :: ContCancellation -> ProcessId -> Process () -> Process () spawnProcessUsingIdWith cancellation pid x = Process $ \pid' -> do liftEvent $ processIdPrepare pid spawnCont cancellation (invokeProcess pid x) (processContId pid) processAwait :: Signal a -> Process a processAwait signal = Process $ \pid -> contAwait signal data MemoResult a = MemoComputed a | MemoError IOException | MemoCancelled memoProcess :: Process a -> Simulation (Process a) memoProcess x = do started <- liftIO $ newIORef False computed <- newSignalSource value <- liftIO $ newIORef Nothing let result = do Just x <- liftIO $ readIORef value case x of MemoComputed a -> return a MemoError e -> throwProcess e MemoCancelled -> cancelProcess return $ do v <- liftIO $ readIORef value case v of Just _ -> result Nothing -> do f <- liftIO $ readIORef started case f of True -> do processAwait $ publishSignal computed result False -> do liftIO $ writeIORef started True r <- liftIO $ newIORef MemoCancelled finallyProcess (catchProcess liftIO $ writeIORef r (MemoComputed a)) (\e -> liftIO $ writeIORef r (MemoError e))) (liftEvent $ do liftIO $ do x <- readIORef r writeIORef value (Just x) triggerSignal computed ()) result | Zip two parallel processes waiting for the both . zipProcessParallel :: Process a -> Process b -> Process (a, b) zipProcessParallel x y = do [Left a, Right b] <- processParallel [fmap Left x, fmap Right y] return (a, b) | Zip three parallel processes waiting for their results . zip3ProcessParallel :: Process a -> Process b -> Process c -> Process (a, b, c) zip3ProcessParallel x y z = do [Left a, Right (Left b), Right (Right c)] <- processParallel [fmap Left x, fmap (Right . Left) y, fmap (Right . Right) z] return (a, b, c) unzipProcess :: Process (a, b) -> Simulation (Process a, Process b) unzipProcess xy = do xy' <- memoProcess xy return (fmap fst xy', fmap snd xy') timeoutProcess :: Double -> Process a -> Process (Maybe a) timeoutProcess timeout p = do pid <- liftSimulation newProcessId timeoutProcessUsingId timeout pid p timeoutProcessUsingId :: Double -> ProcessId -> Process a -> Process (Maybe a) timeoutProcessUsingId timeout pid p = do s <- liftSimulation newSignalSource timeoutPid <- liftSimulation newProcessId spawnProcessUsingIdWith CancelChildAfterParent timeoutPid $ do holdProcess timeout liftEvent $ cancelProcessWithId pid spawnProcessUsingIdWith CancelChildAfterParent pid $ do r <- liftIO $ newIORef Nothing finallyProcess (catchProcess (do a <- p liftIO $ writeIORef r $ Just (Right a)) (\e -> liftIO $ writeIORef r $ Just (Left e))) (liftEvent $ do cancelProcessWithId timeoutPid x <- liftIO $ readIORef r triggerSignal s x) x <- processAwait $ publishSignal s case x of Nothing -> return Nothing Just (Right a) -> return (Just a) Just (Left (SomeException e)) -> throwProcess e processYield :: Process () processYield = Process $ \pid -> Cont $ \c -> Event $ \p -> invokeEvent p $ enqueueEvent (pointTime p) $ resumeCont c () neverProcess :: Process a neverProcess = Process $ \pid -> Cont $ \c -> let signal = processCancelling pid in handleSignal_ signal $ \_ -> resumeCont c $ error "It must never be computed: neverProcess" retryProcess :: String -> Process a retryProcess = liftEvent . retryEvent | Like the GoTo statement it transfers the direction of computation , transferProcess :: Process () -> Process a transferProcess (Process m) = Process $ \pid -> transferCont (m pid) traceProcess :: String -> Process a -> Process a traceProcess message m = Process $ \pid -> traceCont message $ invokeProcess pid m
782bd73f55d0ae63acb89839dc18ff19f3ba0a0c0fd7c0bd088d758e2c739997
realworldocaml/examples
blow_up.ml
open Core.Std exception Empty_list let list_max = function | [] -> raise Empty_list | hd :: tl -> List.fold tl ~init:hd ~f:(Int.max) let () = printf "%d\n" (list_max [1;2;3]); printf "%d\n" (list_max [])
null
https://raw.githubusercontent.com/realworldocaml/examples/32ea926861a0b728813a29b0e4cf20dd15eb486e/code/error-handling/blow_up.ml
ocaml
open Core.Std exception Empty_list let list_max = function | [] -> raise Empty_list | hd :: tl -> List.fold tl ~init:hd ~f:(Int.max) let () = printf "%d\n" (list_max [1;2;3]); printf "%d\n" (list_max [])
447483dfa8f08a8bb1f8200eb7e80f7c1b8f99e359f2c9659f1c36adb1c80f7f
antoniogarrote/jobim
events.clj
(ns jobim.events (:use [lamina.core]) (:use [clojure.contrib.logging :only [log]]) (:import [java.util LinkedList HashMap]) (:import [java.util.concurrent LinkedBlockingQueue])) (defonce ^LinkedBlockingQueue *reactor-thread* (LinkedBlockingQueue.)) (defonce ^HashMap *events-handlers* (HashMap.)) (defonce ^HashMap *events-queues* (HashMap.)) ;;; Reactor (defn- do-handler ([handler data] (try (handler data) (catch Exception ex (do (println (str "*** Exception handling event in reactor thread: " (.getMessage ex) " " (vec (.getStackTrace ex))))))))) (defn- process-listen ([{:keys [key handler]}] (do (.put *events-handlers* key {:handler handler :kind :persistent}) (let [^LinkedList evts-queue (get *events-queues* key)] (if (nil? evts-queue) (.put *events-queues* key (LinkedList.)) (when (not (.isEmpty evts-queue)) (let [data (.removeFirst evts-queue)] (do-handler handler {:key key :data data})))))))) (defn- process-finish ([{:keys [key]}] (.remove *events-handlers* key) (.remove *events-queues* key))) (defn- process-listen-once ([{:keys [key handler]}] (let [_ (when (nil? (get *events-queues* key)) (.put *events-queues* key (LinkedList.))) ^LinkedList queue (get *events-queues* key)] (if (.isEmpty queue) (.put *events-handlers* key {:handler (fn [data] (.remove *events-handlers* key) (.remove *events-queues* key) (do-handler handler data)) :kind :ephemeral}) (let [evt (.removeFirst queue)] (.remove *events-handlers* key) (.remove *events-queues* key) (do-handler handler {:key key :data evt})))))) (defn- process-publish ([key data] (let [^LinkedList queue (get *events-queues* key) handler (get *events-handlers* key)] (when (and (nil? queue) (nil? handler)) (let [queue (LinkedList.)] (.add queue data) (.put *events-queues* key queue))) (when (and (nil? queue) (not (nil? handler))) (let [{:keys [handler kind]} handler] (if (= :persistent kind) (do-handler handler {:key key :data data}) (do (.remove *events-handlers* key) (do-handler handler {:key key :data data}))))) (when (and (not (nil? queue)) (nil? handler)) (.add queue data)) (when (and (not (nil? queue)) (not (nil? handler))) (let [{:keys [handler kind]} handler] (if (= :persistent kind) (do-handler handler {:key key :data data}) (do (.remove *events-handlers* key) (.remove *events-queues* key) (do-handler handler {:key key :data data})))))))) (defn- do-reactor-thread ([key data] (condp = key :listen (process-listen data) :finish (process-finish data) :listen-once (process-listen-once data) (process-publish key data)))) (defn- reactor-thread ([^LinkedBlockingQueue reactor-queue] (.start (Thread. #(do (.setName (Thread/currentThread) (str "Jobim Reactor Thread - " (.getId (Thread/currentThread)))) (loop [[key data] (.take reactor-queue)] (do (do-reactor-thread key data) (recur (.take reactor-queue))))))))) (defn run-multiplexer ([num-threads] (let [reactor-queues (take num-threads (repeatedly #(LinkedBlockingQueue.)))] ;; create queues ;; create reactor threads (doseq [channel reactor-queues] (reactor-thread channel)) ;; multiplexer thread (.start (Thread. #(do (.setName (Thread/currentThread) "Jobim Multiplexer Thread") (doseq [^LinkedBlockingQueue ch (cycle reactor-queues)] (let [item (.take *reactor-thread*)] ;(.put ch item) ; Not using reactor threads (do-reactor-thread (first item) (second item)) )))))))) ;; - register events + handlers as lambda + closures (defn publish "Sends a new data to the events queue" ([key data] (.put *reactor-thread* [key data]))) (defn listen "Starts listening for events" ([key handler] (publish :listen {:key key :handler handler}) :ok)) (defn finish "Closes a channel and removes it from the channels map" ([key] (publish :finish {:key key }) :ok)) (defn listen-once "Starts listening for a single event occurrence" ([key handler] (publish :listen-once {:key key :handler handler}) :ok))
null
https://raw.githubusercontent.com/antoniogarrote/jobim/f041331d2c02cf38741e8604263bd08a3a1f11a5/jobim-core/src/jobim/events.clj
clojure
Reactor create queues create reactor threads multiplexer thread (.put ch item) Not using reactor threads - register events + handlers as lambda + closures
(ns jobim.events (:use [lamina.core]) (:use [clojure.contrib.logging :only [log]]) (:import [java.util LinkedList HashMap]) (:import [java.util.concurrent LinkedBlockingQueue])) (defonce ^LinkedBlockingQueue *reactor-thread* (LinkedBlockingQueue.)) (defonce ^HashMap *events-handlers* (HashMap.)) (defonce ^HashMap *events-queues* (HashMap.)) (defn- do-handler ([handler data] (try (handler data) (catch Exception ex (do (println (str "*** Exception handling event in reactor thread: " (.getMessage ex) " " (vec (.getStackTrace ex))))))))) (defn- process-listen ([{:keys [key handler]}] (do (.put *events-handlers* key {:handler handler :kind :persistent}) (let [^LinkedList evts-queue (get *events-queues* key)] (if (nil? evts-queue) (.put *events-queues* key (LinkedList.)) (when (not (.isEmpty evts-queue)) (let [data (.removeFirst evts-queue)] (do-handler handler {:key key :data data})))))))) (defn- process-finish ([{:keys [key]}] (.remove *events-handlers* key) (.remove *events-queues* key))) (defn- process-listen-once ([{:keys [key handler]}] (let [_ (when (nil? (get *events-queues* key)) (.put *events-queues* key (LinkedList.))) ^LinkedList queue (get *events-queues* key)] (if (.isEmpty queue) (.put *events-handlers* key {:handler (fn [data] (.remove *events-handlers* key) (.remove *events-queues* key) (do-handler handler data)) :kind :ephemeral}) (let [evt (.removeFirst queue)] (.remove *events-handlers* key) (.remove *events-queues* key) (do-handler handler {:key key :data evt})))))) (defn- process-publish ([key data] (let [^LinkedList queue (get *events-queues* key) handler (get *events-handlers* key)] (when (and (nil? queue) (nil? handler)) (let [queue (LinkedList.)] (.add queue data) (.put *events-queues* key queue))) (when (and (nil? queue) (not (nil? handler))) (let [{:keys [handler kind]} handler] (if (= :persistent kind) (do-handler handler {:key key :data data}) (do (.remove *events-handlers* key) (do-handler handler {:key key :data data}))))) (when (and (not (nil? queue)) (nil? handler)) (.add queue data)) (when (and (not (nil? queue)) (not (nil? handler))) (let [{:keys [handler kind]} handler] (if (= :persistent kind) (do-handler handler {:key key :data data}) (do (.remove *events-handlers* key) (.remove *events-queues* key) (do-handler handler {:key key :data data})))))))) (defn- do-reactor-thread ([key data] (condp = key :listen (process-listen data) :finish (process-finish data) :listen-once (process-listen-once data) (process-publish key data)))) (defn- reactor-thread ([^LinkedBlockingQueue reactor-queue] (.start (Thread. #(do (.setName (Thread/currentThread) (str "Jobim Reactor Thread - " (.getId (Thread/currentThread)))) (loop [[key data] (.take reactor-queue)] (do (do-reactor-thread key data) (recur (.take reactor-queue))))))))) (defn run-multiplexer ([num-threads] (doseq [channel reactor-queues] (reactor-thread channel)) (.start (Thread. #(do (.setName (Thread/currentThread) "Jobim Multiplexer Thread") (doseq [^LinkedBlockingQueue ch (cycle reactor-queues)] (let [item (.take *reactor-thread*)] (do-reactor-thread (first item) (second item)) )))))))) (defn publish "Sends a new data to the events queue" ([key data] (.put *reactor-thread* [key data]))) (defn listen "Starts listening for events" ([key handler] (publish :listen {:key key :handler handler}) :ok)) (defn finish "Closes a channel and removes it from the channels map" ([key] (publish :finish {:key key }) :ok)) (defn listen-once "Starts listening for a single event occurrence" ([key handler] (publish :listen-once {:key key :handler handler}) :ok))
459630565ec4f5d817af50d08993e72d7ee46eb2b9e12349ddb3a2c6ecf1ddb7
juspay/medea
Array.hs
# LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # module Data.Medea.Parser.Spec.Array ( Specification (..), defaultSpec, parseSpecification, ) where import Control.Applicative ((<|>)) import Control.Applicative.Permutations (runPermutation, toPermutationWithDefault) import Data.Medea.Parser.Primitive ( Identifier, Natural, ReservedIdentifier (..), parseIdentifier, parseKeyVal, parseLine, parseNatural, parseReserved, ) import Data.Medea.Parser.Types (MedeaParser, ParseError (..)) import Text.Megaparsec (MonadParsec (..), customFailure, many, try) data Specification = Specification { minLength :: !(Maybe Natural), maxLength :: !(Maybe Natural), elementType :: !(Maybe Identifier), tupleSpec :: !(Maybe [Identifier]) } deriving stock (Eq, Show) -- tupleSpec with an empty list indicates an empty tuple/encoding of unit -- tupleSpec of Nothing indicates that there is no tuple spec at all defaultSpec :: Specification defaultSpec = Specification Nothing Nothing Nothing Nothing parseSpecification :: MedeaParser Specification parseSpecification = do spec <- try permute case spec of Specification Nothing Nothing Nothing Nothing -> -- the user must specify length, or a type, or a tuple spec customFailure EmptyLengthArraySpec Specification _ _ (Just _) (Just _) -> -- the user has defined both element type and tuple. -- this is illegal behaviour customFailure ConflictingSpecRequirements Specification (Just _) _ _ (Just _) -> -- the user cannot specify length and tuples customFailure ConflictingSpecRequirements Specification _ (Just _) _ (Just _) -> customFailure ConflictingSpecRequirements _ -> pure spec where permute = runPermutation $ Specification <$> toPermutationWithDefault Nothing (try parseMinSpec) <*> toPermutationWithDefault Nothing (try parseMaxSpec) <*> toPermutationWithDefault Nothing (try parseElementType) <*> toPermutationWithDefault Nothing (try parseTupleSpec) parseMinSpec :: MedeaParser (Maybe Natural) parseMinSpec = parseLine 4 $ Just <$> parseKeyVal RMinLength parseNatural parseMaxSpec :: MedeaParser (Maybe Natural) parseMaxSpec = parseLine 4 $ Just <$> parseKeyVal RMaxLength parseNatural parseElementType :: MedeaParser (Maybe Identifier) parseElementType = do _ <- parseLine 4 $ parseReserved RElementType element <- parseLine 8 parseIdentifier <|> customFailure EmptyArrayElements pure $ Just element parseTupleSpec :: MedeaParser (Maybe [Identifier]) parseTupleSpec = do _ <- parseLine 4 $ parseReserved RTuple elemList <- many $ try $ parseLine 8 parseIdentifier pure $ Just elemList
null
https://raw.githubusercontent.com/juspay/medea/b493dd96f7f8d465ec95d3dafa0da430625c9c87/src/Data/Medea/Parser/Spec/Array.hs
haskell
tupleSpec with an empty list indicates an empty tuple/encoding of unit tupleSpec of Nothing indicates that there is no tuple spec at all the user must specify length, or a type, or a tuple spec the user has defined both element type and tuple. this is illegal behaviour the user cannot specify length and tuples
# LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # module Data.Medea.Parser.Spec.Array ( Specification (..), defaultSpec, parseSpecification, ) where import Control.Applicative ((<|>)) import Control.Applicative.Permutations (runPermutation, toPermutationWithDefault) import Data.Medea.Parser.Primitive ( Identifier, Natural, ReservedIdentifier (..), parseIdentifier, parseKeyVal, parseLine, parseNatural, parseReserved, ) import Data.Medea.Parser.Types (MedeaParser, ParseError (..)) import Text.Megaparsec (MonadParsec (..), customFailure, many, try) data Specification = Specification { minLength :: !(Maybe Natural), maxLength :: !(Maybe Natural), elementType :: !(Maybe Identifier), tupleSpec :: !(Maybe [Identifier]) } deriving stock (Eq, Show) defaultSpec :: Specification defaultSpec = Specification Nothing Nothing Nothing Nothing parseSpecification :: MedeaParser Specification parseSpecification = do spec <- try permute case spec of Specification Nothing Nothing Nothing Nothing -> customFailure EmptyLengthArraySpec Specification _ _ (Just _) (Just _) -> customFailure ConflictingSpecRequirements Specification (Just _) _ _ (Just _) -> customFailure ConflictingSpecRequirements Specification _ (Just _) _ (Just _) -> customFailure ConflictingSpecRequirements _ -> pure spec where permute = runPermutation $ Specification <$> toPermutationWithDefault Nothing (try parseMinSpec) <*> toPermutationWithDefault Nothing (try parseMaxSpec) <*> toPermutationWithDefault Nothing (try parseElementType) <*> toPermutationWithDefault Nothing (try parseTupleSpec) parseMinSpec :: MedeaParser (Maybe Natural) parseMinSpec = parseLine 4 $ Just <$> parseKeyVal RMinLength parseNatural parseMaxSpec :: MedeaParser (Maybe Natural) parseMaxSpec = parseLine 4 $ Just <$> parseKeyVal RMaxLength parseNatural parseElementType :: MedeaParser (Maybe Identifier) parseElementType = do _ <- parseLine 4 $ parseReserved RElementType element <- parseLine 8 parseIdentifier <|> customFailure EmptyArrayElements pure $ Just element parseTupleSpec :: MedeaParser (Maybe [Identifier]) parseTupleSpec = do _ <- parseLine 4 $ parseReserved RTuple elemList <- many $ try $ parseLine 8 parseIdentifier pure $ Just elemList
207cb1d5f4f112feeb7ba7e808e317e3ae7b2666c00ab6193d43ce0c146499a9
danieljharvey/mimsa
Typecheck.hs
# LANGUAGE BlockArguments # # LANGUAGE DerivingStrategies # module Language.Mimsa.Typechecker.Typecheck ( typecheck, ) where import Control.Monad.Except import Control.Monad.State (State, runState) import Control.Monad.Writer.CPS import Data.Map.Strict (Map) import Language.Mimsa.Core import Language.Mimsa.Typechecker.Elaborate import Language.Mimsa.Typechecker.Solve import Language.Mimsa.Typechecker.TcMonad import Language.Mimsa.Typechecker.TypedHoles import Language.Mimsa.Types.Error import Language.Mimsa.Types.Typechecker import Language.Mimsa.Types.Typechecker.Substitutions import Language.Mimsa.Types.Typechecker.Unique type ElabM = ExceptT TypeError ( WriterT [Constraint] (State TypecheckState) ) runElabM :: TypecheckState -> ElabM a -> Either TypeError ([Constraint], TypecheckState, a) runElabM tcState value = case either' of ((Right a, constraints), newTcState) -> Right (constraints, newTcState, a) ((Left e, _), _) -> Left e where either' = runState (runWriterT (runExceptT value)) tcState -- run inference, and substitute everything possible typecheck :: Map Name MonoType -> Environment -> Expr (Name, Unique) Annotation -> Either TypeError ( Substitutions, [Constraint], Expr (Name, Unique) MonoType, MonoType ) typecheck typeMap env expr = do let tcAction = do (elabExpr, constraints) <- listen (elab env expr) subs <- solve constraints typedHolesCheck typeMap subs pure (subs, constraints, elabExpr) (_, _, (subs, constraints, tyExpr)) <- runElabM (defaultTcState env) tcAction let typedExpr = applySubst subs tyExpr pure (subs, constraints, typedExpr, getTypeFromAnn typedExpr)
null
https://raw.githubusercontent.com/danieljharvey/mimsa/97421f00f4487dc7d4988eb1dcddd65c4e379538/compiler/src/Language/Mimsa/Typechecker/Typecheck.hs
haskell
run inference, and substitute everything possible
# LANGUAGE BlockArguments # # LANGUAGE DerivingStrategies # module Language.Mimsa.Typechecker.Typecheck ( typecheck, ) where import Control.Monad.Except import Control.Monad.State (State, runState) import Control.Monad.Writer.CPS import Data.Map.Strict (Map) import Language.Mimsa.Core import Language.Mimsa.Typechecker.Elaborate import Language.Mimsa.Typechecker.Solve import Language.Mimsa.Typechecker.TcMonad import Language.Mimsa.Typechecker.TypedHoles import Language.Mimsa.Types.Error import Language.Mimsa.Types.Typechecker import Language.Mimsa.Types.Typechecker.Substitutions import Language.Mimsa.Types.Typechecker.Unique type ElabM = ExceptT TypeError ( WriterT [Constraint] (State TypecheckState) ) runElabM :: TypecheckState -> ElabM a -> Either TypeError ([Constraint], TypecheckState, a) runElabM tcState value = case either' of ((Right a, constraints), newTcState) -> Right (constraints, newTcState, a) ((Left e, _), _) -> Left e where either' = runState (runWriterT (runExceptT value)) tcState typecheck :: Map Name MonoType -> Environment -> Expr (Name, Unique) Annotation -> Either TypeError ( Substitutions, [Constraint], Expr (Name, Unique) MonoType, MonoType ) typecheck typeMap env expr = do let tcAction = do (elabExpr, constraints) <- listen (elab env expr) subs <- solve constraints typedHolesCheck typeMap subs pure (subs, constraints, elabExpr) (_, _, (subs, constraints, tyExpr)) <- runElabM (defaultTcState env) tcAction let typedExpr = applySubst subs tyExpr pure (subs, constraints, typedExpr, getTypeFromAnn typedExpr)
6621e1c3d8ad755ba7c24a847a2df17a89b0b481984167a223637124d008a3e8
RefactoringTools/HaRe
pfe.hs
import System(getArgs ) import PPU(getPPopts) import HsParser(parse) import HsLexerPass1(lexerPass0) import DefinedNamesBase ( ) import FreeNamesBase() import ScopeNamesBase() import NameMapsBase() import ReAssocBase() import RemoveListCompBase() import SimpPatMatchBase() import TiDecorate(TiDecls) -- to choose result type from the type checker import HsModule import Pfe0Cmds(addHelpCmd) import Pfe4Cmds(pfe4Cmds) import PFE4(PFE4Info) import Pfe3Metrics(pfe3MetricsCmds) import PFEdeps(clean5) import PfeHtmlCmds(pfeHtmlCmds) import PfeChase(pfeChaseCmds) import PfeTransformCmds(pfeTransformCmds) import PfeDepCmds(runPFE5Cmds,pfeDepCmds) import PfeCleanCmd(pfeCleanCmd) import PfeInteractive(pfeiAllCmds,runSIO) import MapDeclMBase() -- for removing pattern bindings in PfeTransformCmds. import RemoveIrrefPatsBase ( ) main = do ao@(opts,prg,args) <- getPPopts let lp = (const lexerPass0,parse) runSIO (runPFE5Cmds () (pfeiAllCmds pfeCmds prg) lp ao) pfeCmds = pfe4Cmds tcOutput++pfe3MetricsCmds++pfeTransformCmds ++pfeChaseCmds++pfeHtmlCmds++pfeDepCmds++pfeCleanCmd clean5 tcOutput = id :: I (PFE4Info i2 (TiDecls i2)) --tcOutput = id :: I [[HsModuleR]] type I a = a->a
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/pfe/pfe.hs
haskell
to choose result type from the type checker for removing pattern bindings in PfeTransformCmds. tcOutput = id :: I [[HsModuleR]]
import System(getArgs ) import PPU(getPPopts) import HsParser(parse) import HsLexerPass1(lexerPass0) import DefinedNamesBase ( ) import FreeNamesBase() import ScopeNamesBase() import NameMapsBase() import ReAssocBase() import RemoveListCompBase() import SimpPatMatchBase() import HsModule import Pfe0Cmds(addHelpCmd) import Pfe4Cmds(pfe4Cmds) import PFE4(PFE4Info) import Pfe3Metrics(pfe3MetricsCmds) import PFEdeps(clean5) import PfeHtmlCmds(pfeHtmlCmds) import PfeChase(pfeChaseCmds) import PfeTransformCmds(pfeTransformCmds) import PfeDepCmds(runPFE5Cmds,pfeDepCmds) import PfeCleanCmd(pfeCleanCmd) import PfeInteractive(pfeiAllCmds,runSIO) import RemoveIrrefPatsBase ( ) main = do ao@(opts,prg,args) <- getPPopts let lp = (const lexerPass0,parse) runSIO (runPFE5Cmds () (pfeiAllCmds pfeCmds prg) lp ao) pfeCmds = pfe4Cmds tcOutput++pfe3MetricsCmds++pfeTransformCmds ++pfeChaseCmds++pfeHtmlCmds++pfeDepCmds++pfeCleanCmd clean5 tcOutput = id :: I (PFE4Info i2 (TiDecls i2)) type I a = a->a
bc4ea9e6bbe47599cc1fb09eeb0b0163cc3eb0c4dc5dfd42557a0cc1b2cac333
haslab/HAAP
plab.hs
# LANGUAGE FlexibleContexts , TypeOperators , RankNTypes , DoAndIfThenElse , TypeFamilies , TupleSections , TemplateHaskell , DeriveDataTypeable , EmptyDataDecls , DeriveGeneric , OverloadedStrings , ScopedTypeVariables # module Main where import HAAP hiding ((.=)) import qualified Data.Vector as Vector import qualified Data.HashMap.Strict as HashMap import Data.Maybe import Data.Default import Data.IORef import Data.Acid import Data.Map (Map(..)) import qualified Data.Map as Map import Data.List.Split import Data.Traversable import Data.Unique import Data.Foldable import Data.SafeCopy import Data.String import Data.Time.LocalTime import Data.Time.Format import Data.Time.Calendar import Data.List import Data.Proxy import Data.Binary import qualified Data.ByteString.Lazy as ByteString import System.Random.Shuffle import System.Environment import System.FilePath import System.Directory import System.Timeout import System.Random import System.Process import Control.DeepSeq import Control.Monad import Control.Monad.Except import qualified Control.Monad.Reader as Reader import qualified Control.Monad.State as State import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A hiding (lang) import Test.QuickCheck.Gen import LI11718 import OracleT1 as T1 import OracleT2 as T2 import OracleT3 as T3 import OracleT4 as T4 import OracleT6 as T6 import SimulateT6 as SimT6 import Mapas import Text.Printf import GHC.Generics (Generic(..)) import GHC.Exception import Safe import qualified Shelly -- * Data types data PLab type PLab_Tourney = HaapTourneyDB TourneyGroup newtype TourneyGroup = TourneyGroup { unTourneyGroup :: (Either Group Unique,Maybe Link) } deriving (Generic) --lookupTourneyGroup :: Int -> [TourneyGroup] -> TourneyGroup --lookupTourneyGroup i [] = error $ "lookupTourneyGroup " ++ show i --lookupTourneyGroup i (tg@(TourneyGroup (Left g,_)):xs) | plabGroupId = = i = tg -- | otherwise = lookupTourneyGroup i xs --lookupTourneyGroup i (tg@(TourneyGroup (Right _,_)):xs) = lookupTourneyGroup i xs instance Eq TourneyGroup where (TourneyGroup x) == (TourneyGroup y) = fst x == fst y instance Ord TourneyGroup where compare (TourneyGroup x) (TourneyGroup y) = fst x `compare` fst y instance Pretty TourneyGroup where pretty (TourneyGroup (Right i,_)) = text "random" pretty (TourneyGroup (Left g,_)) = doc $ plabGroupId g instance NFData TourneyGroup instance TourneyPlayer TourneyGroup where defaultPlayer = do i <- newUnique return $ TourneyGroup (Right i,Just "") isDefaultPlayer = isJust . snd . unTourneyGroup renderPlayer g@(TourneyGroup (Right i,_)) = H.preEscapedToMarkup (fromString $ ("random") :: String) renderPlayer g@(TourneyGroup (_,Nothing)) = H.preEscapedToMarkup (pretty g) renderPlayer g@(TourneyGroup (_,Just link)) = H.a ! A.href (fromString link) $ fromString $ pretty g data PLab_DB = PLab_DB { plabGroups :: Map PLab_GroupId PLab_Group , plabTourney :: PLab_Tourney } type PLab_DBArgs = AcidDBArgs PLab_DB data PLab_Group = PLab_Group { groupSource :: FilePathSource , groupT3Rank :: [PercentageScore] } type PLab_GroupId = Int plabGroupId :: Group -> PLab_GroupId plabGroupId = read . drop 8 . groupId -- * DB instances $(deriveSafeCopy 0 'base ''Unique) $(deriveSafeCopy 0 'base ''PLab_DB) $(deriveSafeCopy 0 'base ''PLab_Group) $(deriveSafeCopy 0 'base ''TourneyGroup) queryTourney :: Query PLab_DB PLab_Tourney queryTourney = do db <- Reader.ask return $ (plabTourney db) updateTourney :: PLab_Tourney -> Update PLab_DB () updateTourney v = State.modify $ \db -> db { plabTourney = v } queryGroupSource :: Group -> Query PLab_DB (Maybe FilePathSource) queryGroupSource g = do db <- Reader.ask return $ fmap groupSource $ Map.lookup (plabGroupId g) (plabGroups db) queryGroupT3Rank :: Group -> Query PLab_DB [PercentageScore] queryGroupT3Rank g = do db <- Reader.ask return $ maybe [] id $ fmap groupT3Rank $ Map.lookup (plabGroupId g) (plabGroups db) updateGroupT3Rank :: Group -> [PercentageScore] -> Update PLab_DB () updateGroupT3Rank g i = updateGroup g (\s -> s { groupT3Rank = i }) updateGroup :: Group -> (PLab_Group -> PLab_Group) -> Update PLab_DB () updateGroup g f = do State.modify $ \st -> st { plabGroups = Map.update (Just . f) (plabGroupId g) (plabGroups st) } $(makeAcidic ''PLab_DB ['queryGroupSource,'queryGroupT3Rank ,'updateGroupT3Rank,'queryTourney,'updateTourney] ) lnsTourney :: DBLens (AcidDB PLab_DB) PLab_Tourney lnsTourney = DBLens (AcidDBQuery QueryTourney) (\st -> AcidDBUpdate $ UpdateTourney st ) -- * Project mkPLab_DBArgs :: FilePath -> PLab_DB -> PLab_DBArgs mkPLab_DBArgs file db = AcidDBArgs { acidDBFile = file , acidDBInit = db, acidDBIOArgs = def { ioTimeout = Just 1000} } mkPLab_Group :: FilePathSource -> PLab_Group mkPLab_Group src = PLab_Group src [] plab_Groups :: IO [(Group,PLab_Group)] plab_Groups = do folders <- runShCoreIO def $ shFindGlob "svn" "2017li1g*" let groups = map mkGroup folders return groups mkGroup :: (String) -> (Group,PLab_Group) mkGroup (g) = (group,mkPLab_Group source) where group = Group (takeFileName g) [] source = FilePathSource ("svn" </> takeFileName g) plab_Tasks :: [Task] plab_Tasks = [t1,t2,t3,t4,t5,t6] where mkTarefa :: Int -> HaapFile mkTarefa i = HaapFile (mkLocal i) (mkRemote i) HaapTemplateFile mkLocal i = "oracle" </> "Tarefa" ++ show i ++ ".hs" mkRemote i = "src" </> "Tarefa" ++ show i ++ "_${group}.hs" mkLib = HaapFile "oracle/LI11718.hs" "src/LI11718.hs" HaapLibraryFile mkMapas = HaapFile "oracle/Mapas.hs" "src/Mapas.hs" HaapLibraryFile mkRel1 = HaapFile "oracle/relatorio/calvin.jpg" "relatorio/calvin.jpg" HaapBinaryFile mkRel2 = HaapFile "oracle/relatorio/relatorio.tex" "relatorio/relatorio.tex" HaapBinaryFile mkOracle f = HaapFile ("oracle" </> f) ("src" </> f) HaapOracleFile t1 = Task "Task 1" [mkTarefa 1,mkLib,mkOracle "RunT1.hs"] t2 = Task "Task 2" [mkTarefa 2,mkLib,mkOracle "RunT2.hs"] t3 = Task "Task 3" [mkTarefa 3,mkLib,mkOracle "RunT3.hs",mkOracle "CollisionSimulator.hs"] t4 = Task "Task 4" [mkTarefa 4,mkLib,mkOracle "RunT4.hs"] t5 = Task "Task 5" [mkTarefa 5,mkLib] t6 = Task "Task 6" [mkTarefa 6,mkLib,mkMapas,mkRel1,mkRel2] plab_ProjectDB :: IO (Project,PLab_DB) plab_ProjectDB = do groups <- plab_Groups let proj = Project { projectName = "PLab" , projectPath = "." , projectTmpPath = "tmp" , projectGroups = map fst groups , projectTasks = plab_Tasks } let db = PLab_DB (Map.fromList $ map (mapFst plabGroupId) groups) emptyHaapTourneyDB return (proj,db) -- * Main main = do (project,db) <- plab_ProjectDB let dbargs = mkPLab_DBArgs "acidDB" db runHaap project $ do useAcidDB (dbargs) (script) return () -- * Script cwImgPath = "images" cwImgs = [("lava",cwImgPath </> "lava.jpg") ,("nitro1",cwImgPath </> "nitro1.png") ,("nitro2",cwImgPath </> "nitro2.png") ,("nitro3",cwImgPath </> "nitro3.png") ,("nitro4",cwImgPath </> "nitro4.png") ,("puff","images/puff.png") ,("bar1","images/bar1.png") ,("bar2","images/bar2.png") ,("bar3","images/bar3.png") ,("bar4","images/bar4.png") ,("p1",cwImgPath </> "p1.png") ,("p2",cwImgPath </> "p2.png") ,("p3",cwImgPath </> "p3.png") ,("p4",cwImgPath </> "p4.png") ,("c1",cwImgPath </> "c1.png") ,("c2",cwImgPath </> "c2.png") ,("c3",cwImgPath </> "c3.png") ,("c4",cwImgPath </> "c4.png") ,("n1","images/1.png") ,("n2","images/2.png") ,("n3","images/3.png") ,("n4","images/4.png") ,("btt","images/btt.png") ,("mrt","images/mrt.png") ,("timer","images/timer.png") ,("f0","images/fonts/0.bmp") ,("f1","images/fonts/1.bmp") ,("f2","images/fonts/2.bmp") ,("f3","images/fonts/3.bmp") ,("f4","images/fonts/4.bmp") ,("f5","images/fonts/5.bmp") ,("f6","images/fonts/6.bmp") ,("f7","images/fonts/7.bmp") ,("f8","images/fonts/8.bmp") ,("f9","images/fonts/9.bmp") ,("fa","images/fonts/a.bmp") ,("fb","images/fonts/b.bmp") ,("fc","images/fonts/c.bmp") ,("fd","images/fonts/d.bmp") ,("fe","images/fonts/e.bmp") ,("ff","images/fonts/f.bmp") ,("fg","images/fonts/g.bmp") ,("fh","images/fonts/h.bmp") ,("fi","images/fonts/i.bmp") ,("fj","images/fonts/j.bmp") ,("fk","images/fonts/k.bmp") ,("fl","images/fonts/l.bmp") ,("fm","images/fonts/m.bmp") ,("fn","images/fonts/n.bmp") ,("fo","images/fonts/o.bmp") ,("fp","images/fonts/p.bmp") ,("fq","images/fonts/q.bmp") ,("fr","images/fonts/r.bmp") ,("fs","images/fonts/s.bmp") ,("ft","images/fonts/t.bmp") ,("fu","images/fonts/u.bmp") ,("fv","images/fonts/v.bmp") ,("fw","images/fonts/w.bmp") ,("fx","images/fonts/x.bmp") ,("fy","images/fonts/y.bmp") ,("fz","images/fonts/z.bmp") ] newtype T3Group = T3Group (Group,(FilePath,[PercentageScore])) instance Pretty T3Group where docPrec i = doc doc (T3Group (g,p)) = text $ groupId g plabGroupString,plabGroupStringPad :: Group -> String plabGroupString g = "2017li1g" ++ pretty (plabGroupId g) plabGroupStringPad g = "2017li1g" ++ printf "%03.0f" ((realToFrac $ plabGroupId g) :: Float) groupFile g = "svn" </> plabGroupStringPad g </> "src" </> "Tarefa6_" ++ plabGroupString g ++ ".hs" tourneyGroupFile (TourneyGroup (_,Just _)) = "oracle/Tarefa6_random.hs" tourneyGroupFile (TourneyGroup (Left g,Nothing)) = groupFile g groupModule g = "Tarefa6_" ++ plabGroupString g tourneyGroupModule (TourneyGroup (_,Just _)) = "Tarefa6_random" tourneyGroupModule (TourneyGroup (Left g,Nothing)) = groupModule g tourneyGroupName (TourneyGroup (Right i,_)) = "random" tourneyGroupName (TourneyGroup (Left g,_)) = plabGroupString g tourneyGroupBot (TourneyGroup (_,Just _)) i = "GUINone" tourneyGroupBot (TourneyGroup (Left g,Nothing)) i = "(GUIBot P" ++ show i ++ ".bot)" groupBot g i = "(GUIBot P" ++ show i ++ ".bot)" refreshTmp :: (MonadIO m,HaapStack t m) => Haap t m () refreshTmp = do projpath <- getProjectPath projtmp <- getProjectTmpPath orDefault () $ runBaseSh $ shRm $ projpath </> projtmp orDefault () $ runBaseIO $ createDirectoryIfMissing True $ projpath </> projtmp script :: (MonadIO m,HasPlugin (AcidDB PLab_DB) t m) => Haap t m () script = do lastupdate <- runBaseIO' $ getZonedTime let hp0 = defaultHakyllP projpath <- getProjectPath projtmp <- getProjectTmpPath -- initialization orDefault () $ runBaseIO $ createDirectoryIfMissing True $ projpath </> "svn" refreshTmp let ghcjsargs = def { ghcjsSafe = False } let iocmd = Just "env" --else Nothing let ioenv = [] let ioargs = addIOCmd iocmd $ addIOEnv ioenv $ def { ioTimeout = Just 60 } let cwioargs = ioargs { ioTimeout = Just 120 } grupos <- getProjectGroups do let emptypath = "nothing.html" let runHakyll :: forall t m a . (MonadIO m,HaapStack t m) => Bool -> Bool -> HakyllP -> Haap (HakyllT :..: t) m a -> Haap t m a runHakyll doClean doCopy hp m = useHakyll (HakyllArgs def doClean doCopy hp) $ do -- load images let loadImages = do hakyllRules $ do match (fromGlob ("images" </> "*")) $ do route idRoute compile copyFileCompiler match (fromGlob ("images" </> "fonts" </> "*")) $ do route idRoute compile copyFileCompiler match (fromGlob ("images" </> "xmas" </> "*")) $ do route idRoute compile copyFileCompiler loadImages m -- T1 map viewer mapviewerpath <- runHakyll True True hp0 $ do let tip = "Mapa ((1,0),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]" let mapviewer = CodeWorldArgs (Left "oracle/MapViewer.hs") "Visualiser of Paths/Maps" (CWDraw CWDrawButton tip) (ghcjsargs) (cwioargs) "mapviewer" cwImgs [] useAndRunCodeWorld mapviewer -- T3 collision viewer collisionviewerpath <- runHakyll False False hp0 $ do let tip = "(3,Carro {posicao = (6.8,3.3), direcao = 45, velocidade = (0.5,1)})" let collisionviewer = CodeWorldArgs (Left "oracle/CollisionViewer.hs") "Colision Visualiser" (CWDraw CWDrawButton tip) (ghcjsargs) (cwioargs) "collisionviewer" cwImgs [] useAndRunCodeWorld collisionviewer -- T4 move viewer moveviewerpath <- runHakyll False False hp0 $ do let tip = "(0.4, Jogo {mapa = Mapa ((2,1),Este) [[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0],[Peca Lava 0,Peca (Curva Norte) 0,Peca (Curva Este) 0,Peca Lava 0],[Peca Lava 0,Peca (Curva Oeste) 0,Peca (Curva Sul) 0,Peca Lava 0],[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0]], pista = (Propriedades {k_atrito = 2, k_pneus = 1, k_acel = 4, k_peso = 2, k_nitro = 5, k_roda = 90}), carros = [Carro {posicao = (1.7,2.3), direcao = 5, velocidade = (1,0)}], nitros = [5], historico = [[(1,2)]]}, Acao {acelerar = True, travar = False, esquerda = True, direita = False, nitro = Nothing})" let moveviewer = CodeWorldArgs (Left "oracle/MoveViewer.hs") "Visualiser of Movements" (CWDraw CWDrawButton tip) (ghcjsargs) (cwioargs) "moveviewer" cwImgs [] useAndRunCodeWorld moveviewer -- run for each group groups <- groupsFeedback grupos (runHakyll False False hp0) ghcjsargs cwioargs ioargs mapviewerpath collisionviewerpath moveviewerpath runHakyll False False hp0 $ groupsPage $ map (mapSnd fst) groups do -- T3 ranking runHakyll False False hp0 $ do let t3Rank = HaapRank "ranks/t3.html" "Rankings (Task 3)" "Group" Nothing "Ranking" (map T3Group groups) rankT3Group rankT3Group (T3Group (g,(path,scores))) = return scores useRank $ renderHaapRank t3Rank return () do -- T6 pre-processing tourneyplayers <- runHakyll False False hp0 $ forM groups $ \(p,_) -> orDo (\e -> return $ TourneyGroup (Left p,Just $ pretty e)) $ do let modu = (groupModule p) let tourneyioargs folder = ioargs { ioSandbox = Sandbox $ Just $ dirToRoot folder </> sandboxcfg, ioTimeout = Just 120 } let ghcargs folder = def { ghcRTS = True, ghcArgs = [], ghcSafe = False, ghcIO = tourneyioargs folder } let (dir,path) = splitFileName (groupFile p) iores <- orIOResult $ runBaseShWith' (tourneyioargs dir) $ do shCd dir shGhcWith (ghcargs dir) [path] if (resOk iores) then return $ TourneyGroup (Left p,Nothing) else addMessageToError (pretty iores) $ do tno <- liftM tourneyNo $ queryDB $ AcidDBQuery QueryTourney let groupfile = addExtension ("tourney" ++ pretty tno </> plabGroupString p) "html" hakyllRules $ create [fromString $ "tourneys/t6" </> groupfile] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp0) compile $ do makeItem (pretty iores) >>= hakyllCompile hp0 return $ TourneyGroup (Left p,Just groupfile) tourneyplayersLR <- return $ Left tourneyplayers -- T6 tourney tourneymaps <- runBaseIO $ shuffleM mapas4 tourneyprops <- runBaseIO $ shuffleM propriedades let tourneyrandoms = zip (concat $ repeat tourneymaps) (concat $ repeat tourneyprops) tourneynum <- runBaseIO $ newIORef 0 runHakyll False False hp0 $ do let t6bestof :: Int -> Int t6bestof 128 = 1 t6bestof 64 = 1 t6bestof 16 = 1 t6bestof 4 = 3 let match tno rno mno ps@[p1,p2,p3,p4] = do let tourneyioargs folder = ioargs { ioSandbox = Sandbox $ Just $ dirToRoot folder </> sandboxcfg, ioTimeout = Just 240 } let rts = ["+RTS","-K800m","-M800m","-RTS"] :: [String] let tpath = "tourney" ++ pretty tno </> "round" ++ pretty rno </> "match" ++ pretty mno let folder = projtmp </> "t6" </> tpath let root = dirToRoot folder let files = map (takeDirectory . tourneyGroupFile) $ filter (not . isDefaultPlayer) ps let tourneyincludes = "-i"++ unSplitOn ":" (map (root </>) (files++["oracle"])) let ghcargs folder = def { ghcSafe = False, ghcRTS = True, ghcArgs = [tourneyincludes], ghcIO = tourneyioargs folder } let matchhtml = "tourneys/t6" </> addExtension ( tpath) "html" let rnoindex :: Int -> Int rnoindex 128 = 0 rnoindex 64 = 1 rnoindex 16 = 2 rnoindex 4 = 3 (mapa,pista) <- do n <- runBaseIO $ readIORef tourneynum runBaseIO $ writeIORef tourneynum $ succ n return $ tourneyrandoms !! n -- run simulator mb_sim <- orEither $ haapRetry 2 $ do runBaseSh $ shMkDir folder let simulatectx = fieldContext "mapa" (show mapa) `mappend` fieldContext "pista" (show pista) `mappend` fieldContext "player1" (tourneyGroupModule p1) `mappend` fieldContext "player2" (tourneyGroupModule p2) `mappend` fieldContext "player3" (tourneyGroupModule p3) `mappend` fieldContext "player4" (tourneyGroupModule p4) `mappend` fieldContext "bot1" (tourneyGroupBot p1 1) `mappend` fieldContext "bot2" (tourneyGroupBot p2 2) `mappend` fieldContext "bot3" (tourneyGroupBot p3 3) `mappend` fieldContext "bot4" (tourneyGroupBot p4 4) let simulatefile = "Simulate.hs" haapRetry 2 $ runBaseShWith' (tourneyioargs folder) $ do shLoadApplyAndCopyTemplate simulatectx ("oracle/SimulateT6Match.hs") (folder </> simulatefile) ghcres <- orIOResult $ runBaseShWith' (tourneyioargs folder) $ do shCd folder shGhcWith (ghcargs folder) [simulatefile] (frames,positions) :: (Frames,[Int]) <- addMessageToError (pretty ghcres) $ do runBaseShWith' (tourneyioargs folder) $ do shCd folder exec <- shExec "Simulate" shCommandToFileWith_ (tourneyioargs folder) exec (rts) (folder </> "bin") runBaseIOWith (tourneyioargs folder) $ decodeFile (folder </> "bin") let rank = zip ps positions return (frames,rank) -- run animator haapRetry 3 $ do case mb_sim of Left err -> throwError err Right (frames,rank) -> do let players = map (tourneyGroupName . fst) rank let animatectx = fieldContext "mapa" (show mapa) `mappend` fieldContext "pista" (show pista) `mappend` fieldContext "frames" (show frames) `mappend` fieldContext "players" (show players) let animatefile = "Animate.hs" haapRetry 2 $ runBaseShWith' (tourneyioargs folder) $ do shLoadApplyAndCopyTemplate animatectx ("oracle/AnimateT6Match.hs") (folder </> animatefile) -- T6 match viewer let ghcjsargs' = ghcjsargs { ghcjsArgs = ghcjsArgs ghcjsargs ++ [tourneyincludes] } matchviewerpath <- do let tip = "" let title = "Race Viewer" let matchviewer = CodeWorldArgs (Left $ folder </> animatefile) title (CWDraw CWDrawFullscreen tip) (ghcjsargs') (cwioargs) ("tourneys/t6" </> tpath) cwImgs [] useAndRunCodeWorld matchviewer return (rank, "../.." </> matchviewerpath) let render link = return link let delete tno = do runBaseSh $ shRm $ projtmp </> "t6" </> "tourney" ++ pretty tno orIOResult $ runBaseShWith' (ioargs) $ shCommandWith ioargs "rsync" ["-vr","--delete","$(mktemp -d)/",":public/tourneys/t6/tourney" ++ pretty tno] return () let t6Tourney = HaapTourney 10 "Task 6" t6bestof "Group" tourneyplayersLR "tourneys/t6" lnsTourney match render delete withHakyllP hp0 $ useRank $ useTourney $ renderHaapTourney t6Tourney return () libfiles <- liftM (nub . filter ((/= HaapOracleFile) . haapFileType)) $ getProjectTaskFiles runHakyll False False hp0 $ hakyllRules $ do forM_ libfiles $ \libfile -> do match (fromGlob $ haapLocalFile libfile) $ do route $ customRoute (const $ haapRemoteFile libfile) compile copyFileCompiler let title = "PLab 2017/18" create ["nothing.html"] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp0) compile $ do let indexCtx = constField "projectname" title `mappend` constField "projectpath" projpath makeItem "" >>= loadAndApplyHTMLTemplate "templates/nothing.html" indexCtx >>= hakyllCompile hp0 create ["index.html"] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp0) compile $ do let libCtx = field "libpath" (return . haapRemoteFile . itemBody) `mappend` field "libname" (return . haapRemoteFile . itemBody) let indexCtx = constField "title" title `mappend` constField "lastupdate" (show lastupdate) `mappend` constField "projectpath" projpath `mappend` listField "libfiles" libCtx (mapM makeItem libfiles) makeItem "" >>= loadAndApplyHTMLTemplate "templates/index.html" indexCtx >>= hakyllCompile hp0 return () : : [ TourneyGroup ] - > IO [ [ TourneyGroup ] ] ) brackets_final -- where : : Int - > IO TourneyGroup = defaultPlayer i = return $ lookupTourneyGroup i gs -- generate groups feedback groupsFeedback :: (MonadIO m,HasPlugin (AcidDB PLab_DB) t m) => [Group] -> (forall a. Haap (HakyllT :..: t) m a -> Haap t m a) -> GHCJSArgs -> IOArgs -> IOArgs -> FilePath -> FilePath -> FilePath -> Haap t m [(Group,(FilePath,[PercentageScore]))] groupsFeedback grupos run ghcjsargs cwioargs ioargs mapviewerpath collisionviewerpath moveviewerpath = do forM grupos $ \g -> liftM (g,) $ groupFeedback run ghcjsargs cwioargs ioargs mapviewerpath collisionviewerpath moveviewerpath g sandboxcfg = "cabal.sandbox.config" groupFeedback :: (MonadIO m,HasPlugin (AcidDB PLab_DB) t m) => (forall a. Haap (HakyllT :..: t) m a -> Haap t m a) -> GHCJSArgs -> IOArgs -> IOArgs -> FilePath -> FilePath -> FilePath -> Group -> Haap t m (FilePath,[PercentageScore]) groupFeedback run ghcjsargs cwioargs ioargs mapviewerpath collisionviewerpath moveviewerpath g = do -- refreshSvn run $ do -- initialization let hpRoute f = if isRelative f then case splitOn "#" f of (x:xs) -> unSplitOn "#" (phpFunRoute x:xs) otherwise -> f else f let hpLogin = defaultHakyllP hp0 <- readHakyllP let hp = hp0 `mappend` hpLogin projname <- getProjectName projpath <- getProjectPath let gpage = "grupos" </> addExtension (show $ plabGroupId g) "html" let svnargs = def { svnHidden = False } let gctx = fieldContext "group" (plabGroupString g) let emptygrouppath = "../nothing.html" let emptypath = "nothing.html" let testsioargs = ioargs { ioTimeout = Just 100 } let testioargs = ioargs { ioTimeout = Just 10 } let feedbackmode = HaapSpecArgs HaapSpecQuickCheck Nothing testioargs mbsource <- queryDB $ AcidDBQuery $ QueryGroupSource g orErrorHakyllPage gpage (gpage,[]) $ case mbsource of Nothing -> throwError $ HaapException $ "Group source not found" Just source -> useFilePathSource def $ do -- update the source getSource source newfiles <- orLogDefault [] $ populateGroupSource gctx False g source do gfiles <- listGroupSourceFiles gctx True g source let gsrcfiles = map (makeRelative "src") gfiles let gpath = sourcePath source let gsrcpath = gpath </> "src" let ghcioargs = ioargs { ioSandbox = Sandbox $ Just $ dirToRoot gsrcpath </> sandboxcfg } let ghcargs = def { ghcIO = ghcioargs } let ghtml = "grupos" </> show (plabGroupId g) --let gdate = fmap svnDate info let rts = ["+RTS","-K100m","-M100m","-RTS"] :: [String] -- run feedback script -- T1 let gt1html = (ghtml </> "t1.html") (specT1path,hpcT1path) <- withHakyllP hp $ do let hpcpath1 = Just (ghtml </> "hpcT1") let hpcT1 = HpcArgs (gsrcpath </> "RunT1") (ghcargs) (ghcioargs) hpcpath1 True (specT1path,hpcT1path) <- useAndRunHpc hpcT1 gt1html $ \ghcT1res -> orErrorHakyllPage gt1html (hakyllRoute hp $ ghtml </> "t1.html") $ addMessageToError (pretty ghcT1res) $ do testsT1 <- haapRetry 2 $ runBaseShWith' (testsioargs) $ do shCd $ gsrcpath exec <- shExec "RunT1" shPipeWith testsioargs exec ("testes":rts) () testsT1' <- forM (zip [1..] testsT1) $ \(i,caminho) -> do let tip = show caminho let title = "Track Viewer" let mapviewer = CodeWorldArgs (Right $ "mapviewer" </> "MapViewer.jsexe") title (CWDraw CWDrawFixed tip) (ghcjsargs) (cwioargs) (ghtml </> "t1" </> show i) cwImgs [] mapviewerpathT1 <- withHakyllP hp0 $ useAndRunCodeWorld mapviewer let url = dirToRoot ghtml </> mapviewerpathT1 let prettyT1 c = doc $ H.a ! A.href (fromString url) $ do H.preEscapedToMarkup $ pretty c return $ Pretty prettyT1 caminho let specT1 = bounded "Caminho" testsT1' $ \(Pretty _ c) -> testEqualIO (return $ PrettyMapa $ constroi c) $ do runShCoreIO ioargs $ do shCd $ gsrcpath exec <- shExec "RunT1" liftM PrettyMapa $ shPipeWith testioargs exec ("constroi":rts) c useSpec feedbackmode $ renderHaapSpec gt1html "Task 1" (pretty ghcT1res) specT1 return (specT1path,hpcT1path) -- T2 let gt2html = (ghtml </> "t2.html") (specT2path,hpcT2path) <- withHakyllP hp $ do let hpcpath2 = Just (ghtml </> "hpcT2") let hpcT2 = HpcArgs (gsrcpath </> "RunT2") (ghcargs) (ghcioargs) hpcpath2 True (specT2path,hpcT2path) <- useAndRunHpc hpcT2 gt2html $ \ghcT2res -> orErrorHakyllPage gt2html (hakyllRoute hp $ ghtml </> "t2.html") $ addMessageToError (pretty ghcT2res) $ do testsT2 <- haapRetry 2 $ runBaseShWith' (testsioargs) $ do shCd $ gsrcpath exec <- shExec "RunT2" shPipeWith testsioargs exec ("testes":rts) () testsT2' <- forM (zip [1..] testsT2) $ \(i,tab) -> do let tip = show tab let title = "Track Viewer" let mapviewer = CodeWorldArgs (Right $ "mapviewer" </> "MapViewer.jsexe") title (CWDraw CWDrawFixed tip) (ghcjsargs) (cwioargs) (ghtml </> "t2" </> show i) cwImgs [] mapviewerpathT2 <- withHakyllP hp0 $ useAndRunCodeWorld mapviewer let url = dirToRoot ghtml </> mapviewerpathT2 let prettyT2 t = doc $ H.a ! A.href (fromString url) $ do H.preEscapedToMarkup $ pretty t return $ Pretty prettyT2 tab let specT2 = bounded "Tabuleiro" testsT2' $ \(Pretty _ t) -> unbounded "Posicao" [] (genPosicao t) $ \p -> unbounded "Orientação" [] genOrientacao $ \o -> let m = Mapa (p,o) t in testEqualIO (return $ valida m) $ do runShCoreIO ioargs $ do shCd $ gsrcpath exec <- shExec "RunT2" shPipeWith testioargs exec ("valida":rts) m useSpec feedbackmode $ renderHaapSpec gt2html "Task 2" (pretty ghcT2res) specT2 return (specT2path,hpcT2path) -- T3 let gt3html = (ghtml </> "t3.html") (specT3path,hpcT3path) <- withHakyllP hp $ do let hpcpath3 = Just (ghtml </> "hpcT3") let hpcT3 = HpcArgs (gsrcpath </> "RunT3") (ghcargs) (ghcioargs) hpcpath3 True (specT3path,hpcT3path) <- useAndRunHpc hpcT3 gt3html $ \ghcT3res -> orErrorHakyllPage gt3html (hakyllRoute hp $ ghtml </> "t3.html") $ addMessageToError (pretty ghcT3res) $ do testsT3 <- haapRetry 2 $ runBaseShWith' (testsioargs) $ do shCd $ gsrcpath exec <- shExec "RunT3" shPipeWith testsioargs exec ("testes":rts) () testsT3' <- forM (zip [1..] testsT3) $ \(i,(tab,tempo,carro)) -> do let tip = show (tab,tempo,carro) let title = "Physics Viewer" let collisionviewer = CodeWorldArgs (Right $ "collisionviewer" </> "CollisionViewer.jsexe") title (CWDraw CWDrawFixed tip) (ghcjsargs) (cwioargs) (ghtml </> "t3" </> show i) cwImgs [] collisionviewerpath <- withHakyllP hp0 $ useAndRunCodeWorld collisionviewer let url = dirToRoot ghtml </> collisionviewerpath let prettyT3 t = doc $ do H.preEscapedToMarkup ("("::String) H.a ! A.href (fromString url) $ do H.preEscapedToMarkup $ pretty tab H.preEscapedToMarkup $ "\n"++printTab tab H.preEscapedToMarkup $ "," ++ pretty tempo H.preEscapedToMarkup $ "," ++ pretty carro H.preEscapedToMarkup (")"::String) return $ Pretty prettyT3 (tab,tempo,carro) let specT3 = bounded "(Tabuleiro,Tempo,Carro)" testsT3' $ \(Pretty _ (tab,tempo,carro)) -> testMessageIO $ do unless (validaCarro tab carro) $ do + + " : " + + show idealsol unless (validaTabuleiro tab) $ do error $ "Tabuleiro inválido:\n" ++ pretty tab groupsol <- runShCoreIO ioargs $ do shCd $ gsrcpath exec <- shExec "RunT3" shPipeWith testioargs exec ("movimenta":rts) (tab,tempo,carro) unless (maybe True (validaCarro tab) groupsol) $ do + + " : " + + show idealsol idealranks <- traceCarros 20 tab (carTracing) carro $ \carro' -> do let idealsol = T3.colide tab tempo carro' let maxdistance = dist (posicao carro') (posicao carro' .+. (tempo .*. velocidade carro')) let rank = T3.compareT3Solutions maxdistance groupsol idealsol return (idealsol,rank) let (idealsol,idealrank) = headNote "no solution" $ sortBy (flip compareSnd) idealranks let msg = "precision: " ++ printDouble idealrank 2 ++ "%\n"++"oracle: "++pretty idealsol++"\nsolution: "++ pretty groupsol return msg useSpec feedbackmode $ renderHaapSpec gt3html "Task 3" (pretty ghcT3res) specT3 return (specT3path,hpcT3path) -- T4 let feedbackmodeT4 = HaapSpecArgs HaapSpecQuickCheck (Just 4) testioargs let gt4html = (ghtml </> "t4.html") (specT4path,hpcT4path) <- withHakyllP hp $ do let hpcpath4 = Just (ghtml </> "hpcT4") let hpcT4 = HpcArgs (gsrcpath </> "RunT4") (ghcargs) (ghcioargs) hpcpath4 True (specT4path,hpcT4path) <- useAndRunHpc hpcT4 gt4html $ \ghcT4res -> orErrorHakyllPage gt4html (hakyllRoute hp $ ghtml </> "t4.html") $ addMessageToError (pretty ghcT4res) $ do testsT4 <- haapRetry 2 $ runBaseShWith' (testsioargs) $ do shCd $ gsrcpath exec <- shExec "RunT4" shPipeWith testsioargs exec ("testes":rts) () testsT4' <- forM (zip [1..] testsT4) $ \(i,(tempo,jogo,acao)) -> do let tip = show (tempo,jogo,acao) let title = "Command Viewer" let moveviewer = CodeWorldArgs (Right $ "moveviewer" </> "MoveViewer.jsexe") title (CWDraw CWDrawFixed tip) (ghcjsargs) (cwioargs) (ghtml </> "t4" </> show i) cwImgs [] moveviewerpathT4 <- withHakyllP hp0 $ useAndRunCodeWorld moveviewer let url = dirToRoot ghtml </> moveviewerpathT4 let prettyT4 t = doc $ H.a ! A.href (fromString url) $ do H.preEscapedToMarkup $ pretty t return $ Pretty prettyT4 (tempo,jogo,acao) let specT4 = bounded "(Tempo,Jogo,Acao)" testsT4' $ \(Pretty _ (tempo,jogo,acao)) -> unbounded "Jogador" [] (genJogadores jogo) $ \jogador -> do if validaJogo tempo jogo jogador then do let jogo' = T4.atualiza tempo jogo jogador acao testEqualIOWith (comparaJogo 0.2) (return jogo') $ do runShCoreIO ioargs $ do shCd $ gsrcpath exec <- shExec "RunT4" shPipeWith testioargs exec ("atualiza":rts) (tempo,jogo,jogador,acao) else testMessage $ "invalid test: " ++ pretty (tempo,jogo,acao) ++ "\nplayer: " ++ pretty jogador let = " < b > : O visualizador aplica a mesma ação a todos os jogadores.</b><br > " nota2 = " < b > : O sistema de feedback testa a ação individualmente para cada jogador.</b><br > " nota3 = " < b > : O sistema de feedback considera testes de cada grupo . < /b><br > " let notes = unlines [pretty ghcT4res] useSpec feedbackmodeT4 $ renderHaapSpec gt4html "Task 4" notes specT4 return (specT4path,hpcT4path) -- T3 collision simulator collisionsimulatorpath <- withHakyllP hp $ do let ghcjsargs = def { ghcjsSafe = False, ghcjsArgs = ["-i"++dirToRoot gsrcpath++"/oracle"]} let ioargs = def let cwioargs = ioargs let title = "Physics Viewer" let collisionsimulator = CodeWorldArgs (Left $ gsrcpath </> "CollisionSimulator.hs") title (CWGame CWGameConsole) (ghcjsargs) (cwioargs) (ghtml </> "collisionsimulator") cwImgs [] useAndRunCodeWorld collisionsimulator -- haddock haddockpaths <- withHakyllP hp $ do let haddock = HaddockArgs (Sandbox $ Just sandboxcfg) (projname ++ " - Group Documentation " ++ show (plabGroupId g)) [] (gsrcpath) gsrcfiles (ghtml </> "doc") useAndRunHaddock haddock -- hlint hlintpath <- withHakyllP hp $ do let hlint = HLintArgs (Sandbox $ Just sandboxcfg) [] gsrcpath gsrcfiles (ghtml </> "hlint.html") useAndRunHLint hlint -- homplexity homplexitypath <- withHakyllP hp $ do let homplexity = HomplexityArgs (Sandbox $ Just sandboxcfg) [] gsrcpath gsrcfiles (ghtml </> "homplexity.html") useAndRunHomplexity homplexity -- T3 ranking t3rank <- do forM T3.solutionsT3 $ \((tab,tempo,carro),solution) -> do mbsol <- orMaybe $ runBaseSh $ do shCd gsrcpath exec <- shExec "RunT3" shPipeWith testioargs exec ("movimenta":rts) (tab,tempo,carro) case mbsol of Nothing -> return $ PercentageScore 0 Just groupsol -> runBaseIOWithTimeout (5 * 60) $ do idealranks <- traceCarros 20 tab (carTracing) carro $ \carro' -> do let idealsol = T3.colide tab tempo carro' let maxdistance = dist (posicao carro') (posicao carro' .+. (tempo .*. velocidade carro')) let rank = T3.compareT3Solutions maxdistance groupsol idealsol return (idealsol,rank) let (idealsol,idealrank) = headNote "no solution" $ sortBy (flip compareSnd) idealranks return $ PercentageScore idealrank -- finalization time <- runBaseIO' getZonedTime hp0 <- readHakyllP hakyllRules $ create [fromFilePath gpage] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp0) compile $ do let pageCtx = constField "group" (show $ plabGroupId g) `mappend` constField "projectname" (projname) `mappend` constField "projectpath" (".." </> projpath) `mappend` constField "date" (show time) `mappend` listField "haddocks" (field "haddock" (return . makeRelative "grupos" . itemBody)) (mapM makeItem haddockpaths) `mappend` constField "hlint" (makeRelative "grupos" hlintpath) `mappend` constField "homplexity" (makeRelative "grupos" homplexitypath) `mappend` constField "specT1path" (makeRelative "grupos" specT1path) `mappend` constField "hpcT1path" (makeRelative "grupos" hpcT1path) `mappend` constField "mapviewerpath" (dirToRoot "grupos" </> mapviewerpath) `mappend` constField "specT2path" (makeRelative "grupos" specT2path) `mappend` constField "hpcT2path" (makeRelative "grupos" hpcT2path) `mappend` constField "specT3path" (makeRelative "grupos" specT3path) `mappend` constField "hpcT3path" (makeRelative "grupos" hpcT3path) `mappend` constField "specT4path" (makeRelative "grupos" specT4path) `mappend` constField "hpcT4path" (makeRelative "grupos" hpcT4path) `mappend` constField "collisionsimulatorpath" (dirToRoot "grupos" </> collisionsimulatorpath) `mappend` constField "collisionviewerpath" (dirToRoot "grupos" </> collisionviewerpath) `mappend` constField "moveviewerpath" (dirToRoot "grupos" </> moveviewerpath) makeItem "" >>= loadAndApplyHTMLTemplate "templates/grupo.html" pageCtx >>= hakyllCompile hp0 updateDB $ AcidDBUpdate $ UpdateGroupT3Rank g t3rank return (gpage,t3rank) traceCarros n tab 0 carro f = liftM (:[]) (f carro) traceCarros n tab delta carro f = forAllIO n (randomizeCarro tab delta carro) f -- generate groups page groupsPage :: HasPlugin Hakyll t m => [(Group,FilePath)] -> Haap t m FilePath groupsPage groupsfeed = do projname <- getProjectName let makeRow (g,path) = [show (plabGroupId g),pretty $ H.a ! A.href (fromString path) $ "ver"] let groupstable = HaapTable (projname ++ " - Feedback by Grupo") ["Group","Feedback"] (map makeRow groupsfeed) "grupos.html" renderHaapTable groupstable carTracing :: Double carTracing = 0.05
null
https://raw.githubusercontent.com/haslab/HAAP/5acf9efaf0e5f6cba1c2482e51bda703f405a86f/examples/plab/plab.hs
haskell
* Data types lookupTourneyGroup :: Int -> [TourneyGroup] -> TourneyGroup lookupTourneyGroup i [] = error $ "lookupTourneyGroup " ++ show i lookupTourneyGroup i (tg@(TourneyGroup (Left g,_)):xs) | otherwise = lookupTourneyGroup i xs lookupTourneyGroup i (tg@(TourneyGroup (Right _,_)):xs) = lookupTourneyGroup i xs * DB instances * Project * Main * Script initialization else Nothing load images T1 map viewer T3 collision viewer T4 move viewer run for each group T3 ranking T6 pre-processing T6 tourney run simulator run animator T6 match viewer where generate groups feedback refreshSvn initialization update the source let gdate = fmap svnDate info run feedback script T1 T2 T3 T4 T3 collision simulator haddock hlint homplexity T3 ranking finalization generate groups page
# LANGUAGE FlexibleContexts , TypeOperators , RankNTypes , DoAndIfThenElse , TypeFamilies , TupleSections , TemplateHaskell , DeriveDataTypeable , EmptyDataDecls , DeriveGeneric , OverloadedStrings , ScopedTypeVariables # module Main where import HAAP hiding ((.=)) import qualified Data.Vector as Vector import qualified Data.HashMap.Strict as HashMap import Data.Maybe import Data.Default import Data.IORef import Data.Acid import Data.Map (Map(..)) import qualified Data.Map as Map import Data.List.Split import Data.Traversable import Data.Unique import Data.Foldable import Data.SafeCopy import Data.String import Data.Time.LocalTime import Data.Time.Format import Data.Time.Calendar import Data.List import Data.Proxy import Data.Binary import qualified Data.ByteString.Lazy as ByteString import System.Random.Shuffle import System.Environment import System.FilePath import System.Directory import System.Timeout import System.Random import System.Process import Control.DeepSeq import Control.Monad import Control.Monad.Except import qualified Control.Monad.Reader as Reader import qualified Control.Monad.State as State import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A hiding (lang) import Test.QuickCheck.Gen import LI11718 import OracleT1 as T1 import OracleT2 as T2 import OracleT3 as T3 import OracleT4 as T4 import OracleT6 as T6 import SimulateT6 as SimT6 import Mapas import Text.Printf import GHC.Generics (Generic(..)) import GHC.Exception import Safe import qualified Shelly data PLab type PLab_Tourney = HaapTourneyDB TourneyGroup newtype TourneyGroup = TourneyGroup { unTourneyGroup :: (Either Group Unique,Maybe Link) } deriving (Generic) | plabGroupId = = i = tg instance Eq TourneyGroup where (TourneyGroup x) == (TourneyGroup y) = fst x == fst y instance Ord TourneyGroup where compare (TourneyGroup x) (TourneyGroup y) = fst x `compare` fst y instance Pretty TourneyGroup where pretty (TourneyGroup (Right i,_)) = text "random" pretty (TourneyGroup (Left g,_)) = doc $ plabGroupId g instance NFData TourneyGroup instance TourneyPlayer TourneyGroup where defaultPlayer = do i <- newUnique return $ TourneyGroup (Right i,Just "") isDefaultPlayer = isJust . snd . unTourneyGroup renderPlayer g@(TourneyGroup (Right i,_)) = H.preEscapedToMarkup (fromString $ ("random") :: String) renderPlayer g@(TourneyGroup (_,Nothing)) = H.preEscapedToMarkup (pretty g) renderPlayer g@(TourneyGroup (_,Just link)) = H.a ! A.href (fromString link) $ fromString $ pretty g data PLab_DB = PLab_DB { plabGroups :: Map PLab_GroupId PLab_Group , plabTourney :: PLab_Tourney } type PLab_DBArgs = AcidDBArgs PLab_DB data PLab_Group = PLab_Group { groupSource :: FilePathSource , groupT3Rank :: [PercentageScore] } type PLab_GroupId = Int plabGroupId :: Group -> PLab_GroupId plabGroupId = read . drop 8 . groupId $(deriveSafeCopy 0 'base ''Unique) $(deriveSafeCopy 0 'base ''PLab_DB) $(deriveSafeCopy 0 'base ''PLab_Group) $(deriveSafeCopy 0 'base ''TourneyGroup) queryTourney :: Query PLab_DB PLab_Tourney queryTourney = do db <- Reader.ask return $ (plabTourney db) updateTourney :: PLab_Tourney -> Update PLab_DB () updateTourney v = State.modify $ \db -> db { plabTourney = v } queryGroupSource :: Group -> Query PLab_DB (Maybe FilePathSource) queryGroupSource g = do db <- Reader.ask return $ fmap groupSource $ Map.lookup (plabGroupId g) (plabGroups db) queryGroupT3Rank :: Group -> Query PLab_DB [PercentageScore] queryGroupT3Rank g = do db <- Reader.ask return $ maybe [] id $ fmap groupT3Rank $ Map.lookup (plabGroupId g) (plabGroups db) updateGroupT3Rank :: Group -> [PercentageScore] -> Update PLab_DB () updateGroupT3Rank g i = updateGroup g (\s -> s { groupT3Rank = i }) updateGroup :: Group -> (PLab_Group -> PLab_Group) -> Update PLab_DB () updateGroup g f = do State.modify $ \st -> st { plabGroups = Map.update (Just . f) (plabGroupId g) (plabGroups st) } $(makeAcidic ''PLab_DB ['queryGroupSource,'queryGroupT3Rank ,'updateGroupT3Rank,'queryTourney,'updateTourney] ) lnsTourney :: DBLens (AcidDB PLab_DB) PLab_Tourney lnsTourney = DBLens (AcidDBQuery QueryTourney) (\st -> AcidDBUpdate $ UpdateTourney st ) mkPLab_DBArgs :: FilePath -> PLab_DB -> PLab_DBArgs mkPLab_DBArgs file db = AcidDBArgs { acidDBFile = file , acidDBInit = db, acidDBIOArgs = def { ioTimeout = Just 1000} } mkPLab_Group :: FilePathSource -> PLab_Group mkPLab_Group src = PLab_Group src [] plab_Groups :: IO [(Group,PLab_Group)] plab_Groups = do folders <- runShCoreIO def $ shFindGlob "svn" "2017li1g*" let groups = map mkGroup folders return groups mkGroup :: (String) -> (Group,PLab_Group) mkGroup (g) = (group,mkPLab_Group source) where group = Group (takeFileName g) [] source = FilePathSource ("svn" </> takeFileName g) plab_Tasks :: [Task] plab_Tasks = [t1,t2,t3,t4,t5,t6] where mkTarefa :: Int -> HaapFile mkTarefa i = HaapFile (mkLocal i) (mkRemote i) HaapTemplateFile mkLocal i = "oracle" </> "Tarefa" ++ show i ++ ".hs" mkRemote i = "src" </> "Tarefa" ++ show i ++ "_${group}.hs" mkLib = HaapFile "oracle/LI11718.hs" "src/LI11718.hs" HaapLibraryFile mkMapas = HaapFile "oracle/Mapas.hs" "src/Mapas.hs" HaapLibraryFile mkRel1 = HaapFile "oracle/relatorio/calvin.jpg" "relatorio/calvin.jpg" HaapBinaryFile mkRel2 = HaapFile "oracle/relatorio/relatorio.tex" "relatorio/relatorio.tex" HaapBinaryFile mkOracle f = HaapFile ("oracle" </> f) ("src" </> f) HaapOracleFile t1 = Task "Task 1" [mkTarefa 1,mkLib,mkOracle "RunT1.hs"] t2 = Task "Task 2" [mkTarefa 2,mkLib,mkOracle "RunT2.hs"] t3 = Task "Task 3" [mkTarefa 3,mkLib,mkOracle "RunT3.hs",mkOracle "CollisionSimulator.hs"] t4 = Task "Task 4" [mkTarefa 4,mkLib,mkOracle "RunT4.hs"] t5 = Task "Task 5" [mkTarefa 5,mkLib] t6 = Task "Task 6" [mkTarefa 6,mkLib,mkMapas,mkRel1,mkRel2] plab_ProjectDB :: IO (Project,PLab_DB) plab_ProjectDB = do groups <- plab_Groups let proj = Project { projectName = "PLab" , projectPath = "." , projectTmpPath = "tmp" , projectGroups = map fst groups , projectTasks = plab_Tasks } let db = PLab_DB (Map.fromList $ map (mapFst plabGroupId) groups) emptyHaapTourneyDB return (proj,db) main = do (project,db) <- plab_ProjectDB let dbargs = mkPLab_DBArgs "acidDB" db runHaap project $ do useAcidDB (dbargs) (script) return () cwImgPath = "images" cwImgs = [("lava",cwImgPath </> "lava.jpg") ,("nitro1",cwImgPath </> "nitro1.png") ,("nitro2",cwImgPath </> "nitro2.png") ,("nitro3",cwImgPath </> "nitro3.png") ,("nitro4",cwImgPath </> "nitro4.png") ,("puff","images/puff.png") ,("bar1","images/bar1.png") ,("bar2","images/bar2.png") ,("bar3","images/bar3.png") ,("bar4","images/bar4.png") ,("p1",cwImgPath </> "p1.png") ,("p2",cwImgPath </> "p2.png") ,("p3",cwImgPath </> "p3.png") ,("p4",cwImgPath </> "p4.png") ,("c1",cwImgPath </> "c1.png") ,("c2",cwImgPath </> "c2.png") ,("c3",cwImgPath </> "c3.png") ,("c4",cwImgPath </> "c4.png") ,("n1","images/1.png") ,("n2","images/2.png") ,("n3","images/3.png") ,("n4","images/4.png") ,("btt","images/btt.png") ,("mrt","images/mrt.png") ,("timer","images/timer.png") ,("f0","images/fonts/0.bmp") ,("f1","images/fonts/1.bmp") ,("f2","images/fonts/2.bmp") ,("f3","images/fonts/3.bmp") ,("f4","images/fonts/4.bmp") ,("f5","images/fonts/5.bmp") ,("f6","images/fonts/6.bmp") ,("f7","images/fonts/7.bmp") ,("f8","images/fonts/8.bmp") ,("f9","images/fonts/9.bmp") ,("fa","images/fonts/a.bmp") ,("fb","images/fonts/b.bmp") ,("fc","images/fonts/c.bmp") ,("fd","images/fonts/d.bmp") ,("fe","images/fonts/e.bmp") ,("ff","images/fonts/f.bmp") ,("fg","images/fonts/g.bmp") ,("fh","images/fonts/h.bmp") ,("fi","images/fonts/i.bmp") ,("fj","images/fonts/j.bmp") ,("fk","images/fonts/k.bmp") ,("fl","images/fonts/l.bmp") ,("fm","images/fonts/m.bmp") ,("fn","images/fonts/n.bmp") ,("fo","images/fonts/o.bmp") ,("fp","images/fonts/p.bmp") ,("fq","images/fonts/q.bmp") ,("fr","images/fonts/r.bmp") ,("fs","images/fonts/s.bmp") ,("ft","images/fonts/t.bmp") ,("fu","images/fonts/u.bmp") ,("fv","images/fonts/v.bmp") ,("fw","images/fonts/w.bmp") ,("fx","images/fonts/x.bmp") ,("fy","images/fonts/y.bmp") ,("fz","images/fonts/z.bmp") ] newtype T3Group = T3Group (Group,(FilePath,[PercentageScore])) instance Pretty T3Group where docPrec i = doc doc (T3Group (g,p)) = text $ groupId g plabGroupString,plabGroupStringPad :: Group -> String plabGroupString g = "2017li1g" ++ pretty (plabGroupId g) plabGroupStringPad g = "2017li1g" ++ printf "%03.0f" ((realToFrac $ plabGroupId g) :: Float) groupFile g = "svn" </> plabGroupStringPad g </> "src" </> "Tarefa6_" ++ plabGroupString g ++ ".hs" tourneyGroupFile (TourneyGroup (_,Just _)) = "oracle/Tarefa6_random.hs" tourneyGroupFile (TourneyGroup (Left g,Nothing)) = groupFile g groupModule g = "Tarefa6_" ++ plabGroupString g tourneyGroupModule (TourneyGroup (_,Just _)) = "Tarefa6_random" tourneyGroupModule (TourneyGroup (Left g,Nothing)) = groupModule g tourneyGroupName (TourneyGroup (Right i,_)) = "random" tourneyGroupName (TourneyGroup (Left g,_)) = plabGroupString g tourneyGroupBot (TourneyGroup (_,Just _)) i = "GUINone" tourneyGroupBot (TourneyGroup (Left g,Nothing)) i = "(GUIBot P" ++ show i ++ ".bot)" groupBot g i = "(GUIBot P" ++ show i ++ ".bot)" refreshTmp :: (MonadIO m,HaapStack t m) => Haap t m () refreshTmp = do projpath <- getProjectPath projtmp <- getProjectTmpPath orDefault () $ runBaseSh $ shRm $ projpath </> projtmp orDefault () $ runBaseIO $ createDirectoryIfMissing True $ projpath </> projtmp script :: (MonadIO m,HasPlugin (AcidDB PLab_DB) t m) => Haap t m () script = do lastupdate <- runBaseIO' $ getZonedTime let hp0 = defaultHakyllP projpath <- getProjectPath projtmp <- getProjectTmpPath orDefault () $ runBaseIO $ createDirectoryIfMissing True $ projpath </> "svn" refreshTmp let ghcjsargs = def { ghcjsSafe = False } let ioenv = [] let ioargs = addIOCmd iocmd $ addIOEnv ioenv $ def { ioTimeout = Just 60 } let cwioargs = ioargs { ioTimeout = Just 120 } grupos <- getProjectGroups do let emptypath = "nothing.html" let runHakyll :: forall t m a . (MonadIO m,HaapStack t m) => Bool -> Bool -> HakyllP -> Haap (HakyllT :..: t) m a -> Haap t m a runHakyll doClean doCopy hp m = useHakyll (HakyllArgs def doClean doCopy hp) $ do let loadImages = do hakyllRules $ do match (fromGlob ("images" </> "*")) $ do route idRoute compile copyFileCompiler match (fromGlob ("images" </> "fonts" </> "*")) $ do route idRoute compile copyFileCompiler match (fromGlob ("images" </> "xmas" </> "*")) $ do route idRoute compile copyFileCompiler loadImages m mapviewerpath <- runHakyll True True hp0 $ do let tip = "Mapa ((1,0),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]]" let mapviewer = CodeWorldArgs (Left "oracle/MapViewer.hs") "Visualiser of Paths/Maps" (CWDraw CWDrawButton tip) (ghcjsargs) (cwioargs) "mapviewer" cwImgs [] useAndRunCodeWorld mapviewer collisionviewerpath <- runHakyll False False hp0 $ do let tip = "(3,Carro {posicao = (6.8,3.3), direcao = 45, velocidade = (0.5,1)})" let collisionviewer = CodeWorldArgs (Left "oracle/CollisionViewer.hs") "Colision Visualiser" (CWDraw CWDrawButton tip) (ghcjsargs) (cwioargs) "collisionviewer" cwImgs [] useAndRunCodeWorld collisionviewer moveviewerpath <- runHakyll False False hp0 $ do let tip = "(0.4, Jogo {mapa = Mapa ((2,1),Este) [[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0],[Peca Lava 0,Peca (Curva Norte) 0,Peca (Curva Este) 0,Peca Lava 0],[Peca Lava 0,Peca (Curva Oeste) 0,Peca (Curva Sul) 0,Peca Lava 0],[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0]], pista = (Propriedades {k_atrito = 2, k_pneus = 1, k_acel = 4, k_peso = 2, k_nitro = 5, k_roda = 90}), carros = [Carro {posicao = (1.7,2.3), direcao = 5, velocidade = (1,0)}], nitros = [5], historico = [[(1,2)]]}, Acao {acelerar = True, travar = False, esquerda = True, direita = False, nitro = Nothing})" let moveviewer = CodeWorldArgs (Left "oracle/MoveViewer.hs") "Visualiser of Movements" (CWDraw CWDrawButton tip) (ghcjsargs) (cwioargs) "moveviewer" cwImgs [] useAndRunCodeWorld moveviewer groups <- groupsFeedback grupos (runHakyll False False hp0) ghcjsargs cwioargs ioargs mapviewerpath collisionviewerpath moveviewerpath runHakyll False False hp0 $ groupsPage $ map (mapSnd fst) groups do runHakyll False False hp0 $ do let t3Rank = HaapRank "ranks/t3.html" "Rankings (Task 3)" "Group" Nothing "Ranking" (map T3Group groups) rankT3Group rankT3Group (T3Group (g,(path,scores))) = return scores useRank $ renderHaapRank t3Rank return () do tourneyplayers <- runHakyll False False hp0 $ forM groups $ \(p,_) -> orDo (\e -> return $ TourneyGroup (Left p,Just $ pretty e)) $ do let modu = (groupModule p) let tourneyioargs folder = ioargs { ioSandbox = Sandbox $ Just $ dirToRoot folder </> sandboxcfg, ioTimeout = Just 120 } let ghcargs folder = def { ghcRTS = True, ghcArgs = [], ghcSafe = False, ghcIO = tourneyioargs folder } let (dir,path) = splitFileName (groupFile p) iores <- orIOResult $ runBaseShWith' (tourneyioargs dir) $ do shCd dir shGhcWith (ghcargs dir) [path] if (resOk iores) then return $ TourneyGroup (Left p,Nothing) else addMessageToError (pretty iores) $ do tno <- liftM tourneyNo $ queryDB $ AcidDBQuery QueryTourney let groupfile = addExtension ("tourney" ++ pretty tno </> plabGroupString p) "html" hakyllRules $ create [fromString $ "tourneys/t6" </> groupfile] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp0) compile $ do makeItem (pretty iores) >>= hakyllCompile hp0 return $ TourneyGroup (Left p,Just groupfile) tourneyplayersLR <- return $ Left tourneyplayers tourneymaps <- runBaseIO $ shuffleM mapas4 tourneyprops <- runBaseIO $ shuffleM propriedades let tourneyrandoms = zip (concat $ repeat tourneymaps) (concat $ repeat tourneyprops) tourneynum <- runBaseIO $ newIORef 0 runHakyll False False hp0 $ do let t6bestof :: Int -> Int t6bestof 128 = 1 t6bestof 64 = 1 t6bestof 16 = 1 t6bestof 4 = 3 let match tno rno mno ps@[p1,p2,p3,p4] = do let tourneyioargs folder = ioargs { ioSandbox = Sandbox $ Just $ dirToRoot folder </> sandboxcfg, ioTimeout = Just 240 } let rts = ["+RTS","-K800m","-M800m","-RTS"] :: [String] let tpath = "tourney" ++ pretty tno </> "round" ++ pretty rno </> "match" ++ pretty mno let folder = projtmp </> "t6" </> tpath let root = dirToRoot folder let files = map (takeDirectory . tourneyGroupFile) $ filter (not . isDefaultPlayer) ps let tourneyincludes = "-i"++ unSplitOn ":" (map (root </>) (files++["oracle"])) let ghcargs folder = def { ghcSafe = False, ghcRTS = True, ghcArgs = [tourneyincludes], ghcIO = tourneyioargs folder } let matchhtml = "tourneys/t6" </> addExtension ( tpath) "html" let rnoindex :: Int -> Int rnoindex 128 = 0 rnoindex 64 = 1 rnoindex 16 = 2 rnoindex 4 = 3 (mapa,pista) <- do n <- runBaseIO $ readIORef tourneynum runBaseIO $ writeIORef tourneynum $ succ n return $ tourneyrandoms !! n mb_sim <- orEither $ haapRetry 2 $ do runBaseSh $ shMkDir folder let simulatectx = fieldContext "mapa" (show mapa) `mappend` fieldContext "pista" (show pista) `mappend` fieldContext "player1" (tourneyGroupModule p1) `mappend` fieldContext "player2" (tourneyGroupModule p2) `mappend` fieldContext "player3" (tourneyGroupModule p3) `mappend` fieldContext "player4" (tourneyGroupModule p4) `mappend` fieldContext "bot1" (tourneyGroupBot p1 1) `mappend` fieldContext "bot2" (tourneyGroupBot p2 2) `mappend` fieldContext "bot3" (tourneyGroupBot p3 3) `mappend` fieldContext "bot4" (tourneyGroupBot p4 4) let simulatefile = "Simulate.hs" haapRetry 2 $ runBaseShWith' (tourneyioargs folder) $ do shLoadApplyAndCopyTemplate simulatectx ("oracle/SimulateT6Match.hs") (folder </> simulatefile) ghcres <- orIOResult $ runBaseShWith' (tourneyioargs folder) $ do shCd folder shGhcWith (ghcargs folder) [simulatefile] (frames,positions) :: (Frames,[Int]) <- addMessageToError (pretty ghcres) $ do runBaseShWith' (tourneyioargs folder) $ do shCd folder exec <- shExec "Simulate" shCommandToFileWith_ (tourneyioargs folder) exec (rts) (folder </> "bin") runBaseIOWith (tourneyioargs folder) $ decodeFile (folder </> "bin") let rank = zip ps positions return (frames,rank) haapRetry 3 $ do case mb_sim of Left err -> throwError err Right (frames,rank) -> do let players = map (tourneyGroupName . fst) rank let animatectx = fieldContext "mapa" (show mapa) `mappend` fieldContext "pista" (show pista) `mappend` fieldContext "frames" (show frames) `mappend` fieldContext "players" (show players) let animatefile = "Animate.hs" haapRetry 2 $ runBaseShWith' (tourneyioargs folder) $ do shLoadApplyAndCopyTemplate animatectx ("oracle/AnimateT6Match.hs") (folder </> animatefile) let ghcjsargs' = ghcjsargs { ghcjsArgs = ghcjsArgs ghcjsargs ++ [tourneyincludes] } matchviewerpath <- do let tip = "" let title = "Race Viewer" let matchviewer = CodeWorldArgs (Left $ folder </> animatefile) title (CWDraw CWDrawFullscreen tip) (ghcjsargs') (cwioargs) ("tourneys/t6" </> tpath) cwImgs [] useAndRunCodeWorld matchviewer return (rank, "../.." </> matchviewerpath) let render link = return link let delete tno = do runBaseSh $ shRm $ projtmp </> "t6" </> "tourney" ++ pretty tno orIOResult $ runBaseShWith' (ioargs) $ shCommandWith ioargs "rsync" ["-vr","--delete","$(mktemp -d)/",":public/tourneys/t6/tourney" ++ pretty tno] return () let t6Tourney = HaapTourney 10 "Task 6" t6bestof "Group" tourneyplayersLR "tourneys/t6" lnsTourney match render delete withHakyllP hp0 $ useRank $ useTourney $ renderHaapTourney t6Tourney return () libfiles <- liftM (nub . filter ((/= HaapOracleFile) . haapFileType)) $ getProjectTaskFiles runHakyll False False hp0 $ hakyllRules $ do forM_ libfiles $ \libfile -> do match (fromGlob $ haapLocalFile libfile) $ do route $ customRoute (const $ haapRemoteFile libfile) compile copyFileCompiler let title = "PLab 2017/18" create ["nothing.html"] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp0) compile $ do let indexCtx = constField "projectname" title `mappend` constField "projectpath" projpath makeItem "" >>= loadAndApplyHTMLTemplate "templates/nothing.html" indexCtx >>= hakyllCompile hp0 create ["index.html"] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp0) compile $ do let libCtx = field "libpath" (return . haapRemoteFile . itemBody) `mappend` field "libname" (return . haapRemoteFile . itemBody) let indexCtx = constField "title" title `mappend` constField "lastupdate" (show lastupdate) `mappend` constField "projectpath" projpath `mappend` listField "libfiles" libCtx (mapM makeItem libfiles) makeItem "" >>= loadAndApplyHTMLTemplate "templates/index.html" indexCtx >>= hakyllCompile hp0 return () : : [ TourneyGroup ] - > IO [ [ TourneyGroup ] ] ) brackets_final : : Int - > IO TourneyGroup = defaultPlayer i = return $ lookupTourneyGroup i gs groupsFeedback :: (MonadIO m,HasPlugin (AcidDB PLab_DB) t m) => [Group] -> (forall a. Haap (HakyllT :..: t) m a -> Haap t m a) -> GHCJSArgs -> IOArgs -> IOArgs -> FilePath -> FilePath -> FilePath -> Haap t m [(Group,(FilePath,[PercentageScore]))] groupsFeedback grupos run ghcjsargs cwioargs ioargs mapviewerpath collisionviewerpath moveviewerpath = do forM grupos $ \g -> liftM (g,) $ groupFeedback run ghcjsargs cwioargs ioargs mapviewerpath collisionviewerpath moveviewerpath g sandboxcfg = "cabal.sandbox.config" groupFeedback :: (MonadIO m,HasPlugin (AcidDB PLab_DB) t m) => (forall a. Haap (HakyllT :..: t) m a -> Haap t m a) -> GHCJSArgs -> IOArgs -> IOArgs -> FilePath -> FilePath -> FilePath -> Group -> Haap t m (FilePath,[PercentageScore]) groupFeedback run ghcjsargs cwioargs ioargs mapviewerpath collisionviewerpath moveviewerpath g = do run $ do let hpRoute f = if isRelative f then case splitOn "#" f of (x:xs) -> unSplitOn "#" (phpFunRoute x:xs) otherwise -> f else f let hpLogin = defaultHakyllP hp0 <- readHakyllP let hp = hp0 `mappend` hpLogin projname <- getProjectName projpath <- getProjectPath let gpage = "grupos" </> addExtension (show $ plabGroupId g) "html" let svnargs = def { svnHidden = False } let gctx = fieldContext "group" (plabGroupString g) let emptygrouppath = "../nothing.html" let emptypath = "nothing.html" let testsioargs = ioargs { ioTimeout = Just 100 } let testioargs = ioargs { ioTimeout = Just 10 } let feedbackmode = HaapSpecArgs HaapSpecQuickCheck Nothing testioargs mbsource <- queryDB $ AcidDBQuery $ QueryGroupSource g orErrorHakyllPage gpage (gpage,[]) $ case mbsource of Nothing -> throwError $ HaapException $ "Group source not found" Just source -> useFilePathSource def $ do getSource source newfiles <- orLogDefault [] $ populateGroupSource gctx False g source do gfiles <- listGroupSourceFiles gctx True g source let gsrcfiles = map (makeRelative "src") gfiles let gpath = sourcePath source let gsrcpath = gpath </> "src" let ghcioargs = ioargs { ioSandbox = Sandbox $ Just $ dirToRoot gsrcpath </> sandboxcfg } let ghcargs = def { ghcIO = ghcioargs } let ghtml = "grupos" </> show (plabGroupId g) let rts = ["+RTS","-K100m","-M100m","-RTS"] :: [String] let gt1html = (ghtml </> "t1.html") (specT1path,hpcT1path) <- withHakyllP hp $ do let hpcpath1 = Just (ghtml </> "hpcT1") let hpcT1 = HpcArgs (gsrcpath </> "RunT1") (ghcargs) (ghcioargs) hpcpath1 True (specT1path,hpcT1path) <- useAndRunHpc hpcT1 gt1html $ \ghcT1res -> orErrorHakyllPage gt1html (hakyllRoute hp $ ghtml </> "t1.html") $ addMessageToError (pretty ghcT1res) $ do testsT1 <- haapRetry 2 $ runBaseShWith' (testsioargs) $ do shCd $ gsrcpath exec <- shExec "RunT1" shPipeWith testsioargs exec ("testes":rts) () testsT1' <- forM (zip [1..] testsT1) $ \(i,caminho) -> do let tip = show caminho let title = "Track Viewer" let mapviewer = CodeWorldArgs (Right $ "mapviewer" </> "MapViewer.jsexe") title (CWDraw CWDrawFixed tip) (ghcjsargs) (cwioargs) (ghtml </> "t1" </> show i) cwImgs [] mapviewerpathT1 <- withHakyllP hp0 $ useAndRunCodeWorld mapviewer let url = dirToRoot ghtml </> mapviewerpathT1 let prettyT1 c = doc $ H.a ! A.href (fromString url) $ do H.preEscapedToMarkup $ pretty c return $ Pretty prettyT1 caminho let specT1 = bounded "Caminho" testsT1' $ \(Pretty _ c) -> testEqualIO (return $ PrettyMapa $ constroi c) $ do runShCoreIO ioargs $ do shCd $ gsrcpath exec <- shExec "RunT1" liftM PrettyMapa $ shPipeWith testioargs exec ("constroi":rts) c useSpec feedbackmode $ renderHaapSpec gt1html "Task 1" (pretty ghcT1res) specT1 return (specT1path,hpcT1path) let gt2html = (ghtml </> "t2.html") (specT2path,hpcT2path) <- withHakyllP hp $ do let hpcpath2 = Just (ghtml </> "hpcT2") let hpcT2 = HpcArgs (gsrcpath </> "RunT2") (ghcargs) (ghcioargs) hpcpath2 True (specT2path,hpcT2path) <- useAndRunHpc hpcT2 gt2html $ \ghcT2res -> orErrorHakyllPage gt2html (hakyllRoute hp $ ghtml </> "t2.html") $ addMessageToError (pretty ghcT2res) $ do testsT2 <- haapRetry 2 $ runBaseShWith' (testsioargs) $ do shCd $ gsrcpath exec <- shExec "RunT2" shPipeWith testsioargs exec ("testes":rts) () testsT2' <- forM (zip [1..] testsT2) $ \(i,tab) -> do let tip = show tab let title = "Track Viewer" let mapviewer = CodeWorldArgs (Right $ "mapviewer" </> "MapViewer.jsexe") title (CWDraw CWDrawFixed tip) (ghcjsargs) (cwioargs) (ghtml </> "t2" </> show i) cwImgs [] mapviewerpathT2 <- withHakyllP hp0 $ useAndRunCodeWorld mapviewer let url = dirToRoot ghtml </> mapviewerpathT2 let prettyT2 t = doc $ H.a ! A.href (fromString url) $ do H.preEscapedToMarkup $ pretty t return $ Pretty prettyT2 tab let specT2 = bounded "Tabuleiro" testsT2' $ \(Pretty _ t) -> unbounded "Posicao" [] (genPosicao t) $ \p -> unbounded "Orientação" [] genOrientacao $ \o -> let m = Mapa (p,o) t in testEqualIO (return $ valida m) $ do runShCoreIO ioargs $ do shCd $ gsrcpath exec <- shExec "RunT2" shPipeWith testioargs exec ("valida":rts) m useSpec feedbackmode $ renderHaapSpec gt2html "Task 2" (pretty ghcT2res) specT2 return (specT2path,hpcT2path) let gt3html = (ghtml </> "t3.html") (specT3path,hpcT3path) <- withHakyllP hp $ do let hpcpath3 = Just (ghtml </> "hpcT3") let hpcT3 = HpcArgs (gsrcpath </> "RunT3") (ghcargs) (ghcioargs) hpcpath3 True (specT3path,hpcT3path) <- useAndRunHpc hpcT3 gt3html $ \ghcT3res -> orErrorHakyllPage gt3html (hakyllRoute hp $ ghtml </> "t3.html") $ addMessageToError (pretty ghcT3res) $ do testsT3 <- haapRetry 2 $ runBaseShWith' (testsioargs) $ do shCd $ gsrcpath exec <- shExec "RunT3" shPipeWith testsioargs exec ("testes":rts) () testsT3' <- forM (zip [1..] testsT3) $ \(i,(tab,tempo,carro)) -> do let tip = show (tab,tempo,carro) let title = "Physics Viewer" let collisionviewer = CodeWorldArgs (Right $ "collisionviewer" </> "CollisionViewer.jsexe") title (CWDraw CWDrawFixed tip) (ghcjsargs) (cwioargs) (ghtml </> "t3" </> show i) cwImgs [] collisionviewerpath <- withHakyllP hp0 $ useAndRunCodeWorld collisionviewer let url = dirToRoot ghtml </> collisionviewerpath let prettyT3 t = doc $ do H.preEscapedToMarkup ("("::String) H.a ! A.href (fromString url) $ do H.preEscapedToMarkup $ pretty tab H.preEscapedToMarkup $ "\n"++printTab tab H.preEscapedToMarkup $ "," ++ pretty tempo H.preEscapedToMarkup $ "," ++ pretty carro H.preEscapedToMarkup (")"::String) return $ Pretty prettyT3 (tab,tempo,carro) let specT3 = bounded "(Tabuleiro,Tempo,Carro)" testsT3' $ \(Pretty _ (tab,tempo,carro)) -> testMessageIO $ do unless (validaCarro tab carro) $ do + + " : " + + show idealsol unless (validaTabuleiro tab) $ do error $ "Tabuleiro inválido:\n" ++ pretty tab groupsol <- runShCoreIO ioargs $ do shCd $ gsrcpath exec <- shExec "RunT3" shPipeWith testioargs exec ("movimenta":rts) (tab,tempo,carro) unless (maybe True (validaCarro tab) groupsol) $ do + + " : " + + show idealsol idealranks <- traceCarros 20 tab (carTracing) carro $ \carro' -> do let idealsol = T3.colide tab tempo carro' let maxdistance = dist (posicao carro') (posicao carro' .+. (tempo .*. velocidade carro')) let rank = T3.compareT3Solutions maxdistance groupsol idealsol return (idealsol,rank) let (idealsol,idealrank) = headNote "no solution" $ sortBy (flip compareSnd) idealranks let msg = "precision: " ++ printDouble idealrank 2 ++ "%\n"++"oracle: "++pretty idealsol++"\nsolution: "++ pretty groupsol return msg useSpec feedbackmode $ renderHaapSpec gt3html "Task 3" (pretty ghcT3res) specT3 return (specT3path,hpcT3path) let feedbackmodeT4 = HaapSpecArgs HaapSpecQuickCheck (Just 4) testioargs let gt4html = (ghtml </> "t4.html") (specT4path,hpcT4path) <- withHakyllP hp $ do let hpcpath4 = Just (ghtml </> "hpcT4") let hpcT4 = HpcArgs (gsrcpath </> "RunT4") (ghcargs) (ghcioargs) hpcpath4 True (specT4path,hpcT4path) <- useAndRunHpc hpcT4 gt4html $ \ghcT4res -> orErrorHakyllPage gt4html (hakyllRoute hp $ ghtml </> "t4.html") $ addMessageToError (pretty ghcT4res) $ do testsT4 <- haapRetry 2 $ runBaseShWith' (testsioargs) $ do shCd $ gsrcpath exec <- shExec "RunT4" shPipeWith testsioargs exec ("testes":rts) () testsT4' <- forM (zip [1..] testsT4) $ \(i,(tempo,jogo,acao)) -> do let tip = show (tempo,jogo,acao) let title = "Command Viewer" let moveviewer = CodeWorldArgs (Right $ "moveviewer" </> "MoveViewer.jsexe") title (CWDraw CWDrawFixed tip) (ghcjsargs) (cwioargs) (ghtml </> "t4" </> show i) cwImgs [] moveviewerpathT4 <- withHakyllP hp0 $ useAndRunCodeWorld moveviewer let url = dirToRoot ghtml </> moveviewerpathT4 let prettyT4 t = doc $ H.a ! A.href (fromString url) $ do H.preEscapedToMarkup $ pretty t return $ Pretty prettyT4 (tempo,jogo,acao) let specT4 = bounded "(Tempo,Jogo,Acao)" testsT4' $ \(Pretty _ (tempo,jogo,acao)) -> unbounded "Jogador" [] (genJogadores jogo) $ \jogador -> do if validaJogo tempo jogo jogador then do let jogo' = T4.atualiza tempo jogo jogador acao testEqualIOWith (comparaJogo 0.2) (return jogo') $ do runShCoreIO ioargs $ do shCd $ gsrcpath exec <- shExec "RunT4" shPipeWith testioargs exec ("atualiza":rts) (tempo,jogo,jogador,acao) else testMessage $ "invalid test: " ++ pretty (tempo,jogo,acao) ++ "\nplayer: " ++ pretty jogador let = " < b > : O visualizador aplica a mesma ação a todos os jogadores.</b><br > " nota2 = " < b > : O sistema de feedback testa a ação individualmente para cada jogador.</b><br > " nota3 = " < b > : O sistema de feedback considera testes de cada grupo . < /b><br > " let notes = unlines [pretty ghcT4res] useSpec feedbackmodeT4 $ renderHaapSpec gt4html "Task 4" notes specT4 return (specT4path,hpcT4path) collisionsimulatorpath <- withHakyllP hp $ do let ghcjsargs = def { ghcjsSafe = False, ghcjsArgs = ["-i"++dirToRoot gsrcpath++"/oracle"]} let ioargs = def let cwioargs = ioargs let title = "Physics Viewer" let collisionsimulator = CodeWorldArgs (Left $ gsrcpath </> "CollisionSimulator.hs") title (CWGame CWGameConsole) (ghcjsargs) (cwioargs) (ghtml </> "collisionsimulator") cwImgs [] useAndRunCodeWorld collisionsimulator haddockpaths <- withHakyllP hp $ do let haddock = HaddockArgs (Sandbox $ Just sandboxcfg) (projname ++ " - Group Documentation " ++ show (plabGroupId g)) [] (gsrcpath) gsrcfiles (ghtml </> "doc") useAndRunHaddock haddock hlintpath <- withHakyllP hp $ do let hlint = HLintArgs (Sandbox $ Just sandboxcfg) [] gsrcpath gsrcfiles (ghtml </> "hlint.html") useAndRunHLint hlint homplexitypath <- withHakyllP hp $ do let homplexity = HomplexityArgs (Sandbox $ Just sandboxcfg) [] gsrcpath gsrcfiles (ghtml </> "homplexity.html") useAndRunHomplexity homplexity t3rank <- do forM T3.solutionsT3 $ \((tab,tempo,carro),solution) -> do mbsol <- orMaybe $ runBaseSh $ do shCd gsrcpath exec <- shExec "RunT3" shPipeWith testioargs exec ("movimenta":rts) (tab,tempo,carro) case mbsol of Nothing -> return $ PercentageScore 0 Just groupsol -> runBaseIOWithTimeout (5 * 60) $ do idealranks <- traceCarros 20 tab (carTracing) carro $ \carro' -> do let idealsol = T3.colide tab tempo carro' let maxdistance = dist (posicao carro') (posicao carro' .+. (tempo .*. velocidade carro')) let rank = T3.compareT3Solutions maxdistance groupsol idealsol return (idealsol,rank) let (idealsol,idealrank) = headNote "no solution" $ sortBy (flip compareSnd) idealranks return $ PercentageScore idealrank time <- runBaseIO' getZonedTime hp0 <- readHakyllP hakyllRules $ create [fromFilePath gpage] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp0) compile $ do let pageCtx = constField "group" (show $ plabGroupId g) `mappend` constField "projectname" (projname) `mappend` constField "projectpath" (".." </> projpath) `mappend` constField "date" (show time) `mappend` listField "haddocks" (field "haddock" (return . makeRelative "grupos" . itemBody)) (mapM makeItem haddockpaths) `mappend` constField "hlint" (makeRelative "grupos" hlintpath) `mappend` constField "homplexity" (makeRelative "grupos" homplexitypath) `mappend` constField "specT1path" (makeRelative "grupos" specT1path) `mappend` constField "hpcT1path" (makeRelative "grupos" hpcT1path) `mappend` constField "mapviewerpath" (dirToRoot "grupos" </> mapviewerpath) `mappend` constField "specT2path" (makeRelative "grupos" specT2path) `mappend` constField "hpcT2path" (makeRelative "grupos" hpcT2path) `mappend` constField "specT3path" (makeRelative "grupos" specT3path) `mappend` constField "hpcT3path" (makeRelative "grupos" hpcT3path) `mappend` constField "specT4path" (makeRelative "grupos" specT4path) `mappend` constField "hpcT4path" (makeRelative "grupos" hpcT4path) `mappend` constField "collisionsimulatorpath" (dirToRoot "grupos" </> collisionsimulatorpath) `mappend` constField "collisionviewerpath" (dirToRoot "grupos" </> collisionviewerpath) `mappend` constField "moveviewerpath" (dirToRoot "grupos" </> moveviewerpath) makeItem "" >>= loadAndApplyHTMLTemplate "templates/grupo.html" pageCtx >>= hakyllCompile hp0 updateDB $ AcidDBUpdate $ UpdateGroupT3Rank g t3rank return (gpage,t3rank) traceCarros n tab 0 carro f = liftM (:[]) (f carro) traceCarros n tab delta carro f = forAllIO n (randomizeCarro tab delta carro) f groupsPage :: HasPlugin Hakyll t m => [(Group,FilePath)] -> Haap t m FilePath groupsPage groupsfeed = do projname <- getProjectName let makeRow (g,path) = [show (plabGroupId g),pretty $ H.a ! A.href (fromString path) $ "ver"] let groupstable = HaapTable (projname ++ " - Feedback by Grupo") ["Group","Feedback"] (map makeRow groupsfeed) "grupos.html" renderHaapTable groupstable carTracing :: Double carTracing = 0.05
570f415574808ac246f82a5b3cb7ded1fe057b5c47b1ae705c1dc98b790a908a
LesBoloss-es/ppx_deriving_madcast
show.ml
open Ppxlib (** Compile a type to a caster **********************************************) let compile typ = try let itype, otype = Lexing.from_string typ |> Parse.core_type |> Madcast.split_arrow in let cast = Madcast.find_caster itype otype in Format.printf "%a@." Pprintast.expression cast with | Madcast.NoCastFound -> Format.printf "no cast found!@." | Madcast.SeveralCastsFound -> Format.printf "Several casts found!@." | Invalid_argument msg when msg = "split_arrow" -> Format.printf "expected an arrow type!@." | exn -> Location.report_exception Format.std_formatter exn * command line arguments * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * let usage = Format.sprintf "usage: %s <ocaml arrow type>" Sys.argv.(0) let parse_cmd_line () = let typ = ref None in let nb_args = ref 0 in let set s = incr nb_args; match !nb_args with | 1 -> typ := Some s | _ -> raise (Arg.Bad "Too many arguments") in Arg.parse [] set usage; match !typ with | None -> Arg.usage [] usage; exit 1 | Some typ -> typ (** Run show.ml *************************************************************) let () = parse_cmd_line () |> compile
null
https://raw.githubusercontent.com/LesBoloss-es/ppx_deriving_madcast/2c728604cf87c07c937b18d9b599fc6785670a9b/test/show.ml
ocaml
* Compile a type to a caster ********************************************* * Run show.ml ************************************************************
open Ppxlib let compile typ = try let itype, otype = Lexing.from_string typ |> Parse.core_type |> Madcast.split_arrow in let cast = Madcast.find_caster itype otype in Format.printf "%a@." Pprintast.expression cast with | Madcast.NoCastFound -> Format.printf "no cast found!@." | Madcast.SeveralCastsFound -> Format.printf "Several casts found!@." | Invalid_argument msg when msg = "split_arrow" -> Format.printf "expected an arrow type!@." | exn -> Location.report_exception Format.std_formatter exn * command line arguments * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * let usage = Format.sprintf "usage: %s <ocaml arrow type>" Sys.argv.(0) let parse_cmd_line () = let typ = ref None in let nb_args = ref 0 in let set s = incr nb_args; match !nb_args with | 1 -> typ := Some s | _ -> raise (Arg.Bad "Too many arguments") in Arg.parse [] set usage; match !typ with | None -> Arg.usage [] usage; exit 1 | Some typ -> typ let () = parse_cmd_line () |> compile
3326dccb09121c9d2621150bac508f06dc32260285bb13c35f3b5d46d46620a3
flora-pm/flora-server
Orphans.hs
# OPTIONS_GHC -Wno - orphans # module Data.Password.Orphans where import Control.DeepSeq import Data.Password.Argon2 instance NFData (PasswordHash Argon2) where rnf :: PasswordHash Argon2 -> () rnf a = seq a ()
null
https://raw.githubusercontent.com/flora-pm/flora-server/c214c0b5d5db71a8330eb69326284be5a4d5e858/src/orphans/Data/Password/Orphans.hs
haskell
# OPTIONS_GHC -Wno - orphans # module Data.Password.Orphans where import Control.DeepSeq import Data.Password.Argon2 instance NFData (PasswordHash Argon2) where rnf :: PasswordHash Argon2 -> () rnf a = seq a ()
d509380c4dfbc50af07734111b293a698ab62d88c4463a53c662f92428662397
huangjs/cl
fnwrap-tests.lisp
(defpackage #:fnwrap-tests (:use #:common-lisp #:lisp-unit #:fnwrap) ) (in-package #:fnwrap-tests) ;;; Tests to make sure wrapping produces the ;;; correct behavior (define-test fnwrap-effects (let ((fn-name (gensym))) (setf (symbol-function fn-name) (lambda (x) (* x x))) (assert-equal 9 (funcall fn-name 3)) ;; wrapper replaces old code (set-wrapper fn-name (lambda (fn x) (+ x x))) (assert-equal 6 (funcall fn-name 3)) ;; wrapper modifies return value of old code (set-wrapper fn-name (lambda (fn x) (+ 8 (funcall fn x)))) (assert-equal 17 (funcall fn-name 3)) ;; wrapper tests arguments (set-wrapper fn-name (lambda (fn x) (if (oddp x) 0 (funcall fn x)))) (assert-equal 0 (funcall fn-name 3)) (assert-equal 16 (funcall fn-name 4)) ;; unwrap restores original code (remove-wrapper fn-name) (assert-equal 9 (funcall fn-name 3)) )) ;;; Tests to make sure wrapping, unwrapping, ;;; and redefining interact correctly (define-test fnwrap-wrap-unwrap (let ((fn-name (gensym)) (fn-2 (lambda (x) (+ x x))) (fn (lambda (x) (* x x))) (wrapper (lambda (fn x) (list 'wrapper x))) (wrapper-2 (lambda (fn x) (list 'wrapper-2 x))) ) ;; After wrapping, the function should be changed (setf (symbol-function fn-name) fn) (assert-equal fn (symbol-function fn-name)) (set-wrapper fn-name wrapper) (assert-false (equal fn (symbol-function fn-name))) ;; After unwrapping, it should be itself again (remove-wrapper fn-name) (assert-equal fn (symbol-function fn-name)) ;; Wrapping a wrapped function should have the new wrapper , and only one wrapper needs to be removed . (set-wrapper fn-name wrapper) (let ((stored (symbol-function fn-name))) (assert-false (equal fn stored)) (set-wrapper fn-name wrapper-2) (assert-false (equal stored (symbol-function fn-name))) (remove-wrapper fn-name) (assert-equal fn (symbol-function fn-name))) ;; Unwrapping should not affect a function redefined ;; since wrapping (set-wrapper fn-name wrapper) (assert-false (equal fn (symbol-function fn-name))) (setf (symbol-function fn-name) fn-2) (remove-wrapper fn-name nil) (assert-equal fn-2 (symbol-function fn-name)) ))
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/other-code/cs325/www.cs.northwestern.edu/academics/courses/325/programs/fnwrap-tests.lisp
lisp
Tests to make sure wrapping produces the correct behavior wrapper replaces old code wrapper modifies return value of old code wrapper tests arguments unwrap restores original code Tests to make sure wrapping, unwrapping, and redefining interact correctly After wrapping, the function should be changed After unwrapping, it should be itself again Wrapping a wrapped function should have the new Unwrapping should not affect a function redefined since wrapping
(defpackage #:fnwrap-tests (:use #:common-lisp #:lisp-unit #:fnwrap) ) (in-package #:fnwrap-tests) (define-test fnwrap-effects (let ((fn-name (gensym))) (setf (symbol-function fn-name) (lambda (x) (* x x))) (assert-equal 9 (funcall fn-name 3)) (set-wrapper fn-name (lambda (fn x) (+ x x))) (assert-equal 6 (funcall fn-name 3)) (set-wrapper fn-name (lambda (fn x) (+ 8 (funcall fn x)))) (assert-equal 17 (funcall fn-name 3)) (set-wrapper fn-name (lambda (fn x) (if (oddp x) 0 (funcall fn x)))) (assert-equal 0 (funcall fn-name 3)) (assert-equal 16 (funcall fn-name 4)) (remove-wrapper fn-name) (assert-equal 9 (funcall fn-name 3)) )) (define-test fnwrap-wrap-unwrap (let ((fn-name (gensym)) (fn-2 (lambda (x) (+ x x))) (fn (lambda (x) (* x x))) (wrapper (lambda (fn x) (list 'wrapper x))) (wrapper-2 (lambda (fn x) (list 'wrapper-2 x))) ) (setf (symbol-function fn-name) fn) (assert-equal fn (symbol-function fn-name)) (set-wrapper fn-name wrapper) (assert-false (equal fn (symbol-function fn-name))) (remove-wrapper fn-name) (assert-equal fn (symbol-function fn-name)) wrapper , and only one wrapper needs to be removed . (set-wrapper fn-name wrapper) (let ((stored (symbol-function fn-name))) (assert-false (equal fn stored)) (set-wrapper fn-name wrapper-2) (assert-false (equal stored (symbol-function fn-name))) (remove-wrapper fn-name) (assert-equal fn (symbol-function fn-name))) (set-wrapper fn-name wrapper) (assert-false (equal fn (symbol-function fn-name))) (setf (symbol-function fn-name) fn-2) (remove-wrapper fn-name nil) (assert-equal fn-2 (symbol-function fn-name)) ))
0f0f006cbc727e58389fd55618bd7ff49d3b48959aa9e24dc57edf34d57581d5
arttuka/reagent-material-ui
stack.cljs
(ns reagent-mui.material.stack "Imports @mui/material/Stack as a Reagent component. Original documentation is at -ui/api/stack/ ." (:require [reagent.core :as r] ["@mui/material/Stack" :as MuiStack])) (def stack (r/adapt-react-class (.-default MuiStack)))
null
https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/core/reagent_mui/material/stack.cljs
clojure
(ns reagent-mui.material.stack "Imports @mui/material/Stack as a Reagent component. Original documentation is at -ui/api/stack/ ." (:require [reagent.core :as r] ["@mui/material/Stack" :as MuiStack])) (def stack (r/adapt-react-class (.-default MuiStack)))
c3b64e52fbbe5d84869c42b3f11b0615bb8e0caec3b3f62d638ed4ee20b11430
nyu-acsys/drift
a-copy-print.ml
(* USED: PLDI2011 as a-cppr USED: PEPM2013 as a-cppr *) let make_array n i = assert (0 <= i && i < n); 0 let update (i:int) (n:int) des x : int -> int = des i; let a j = if i=j then x else des j in a let print_int (n:int) = () let f (m:int) src des = let rec bcopy (m:int) src des i = if i >= m then des else let des = update i m des (src i) in bcopy m src des (i+1) in let rec print_array m (array:int->int) i = if i >= m then () else (print_int (array i); print_array m array (i + 1)) in let array : int -> int = bcopy m src des 0 in print_array m array 0 let main_p (n:int) = let array1 = make_array n in let array2 = make_array n in if n > 0 then f n array1 array2 else () let main (w:unit) = let _ = main_p 5 in let _ = main_p 10 in let _ = for i = 1 to 1000 do main_p ( Random.int 1000 ) done in for i = 1 to 1000 do main_p (Random.int 1000) done in *) () let _ = main ()
null
https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks_call/r_type/array/a-copy-print.ml
ocaml
USED: PLDI2011 as a-cppr USED: PEPM2013 as a-cppr
let make_array n i = assert (0 <= i && i < n); 0 let update (i:int) (n:int) des x : int -> int = des i; let a j = if i=j then x else des j in a let print_int (n:int) = () let f (m:int) src des = let rec bcopy (m:int) src des i = if i >= m then des else let des = update i m des (src i) in bcopy m src des (i+1) in let rec print_array m (array:int->int) i = if i >= m then () else (print_int (array i); print_array m array (i + 1)) in let array : int -> int = bcopy m src des 0 in print_array m array 0 let main_p (n:int) = let array1 = make_array n in let array2 = make_array n in if n > 0 then f n array1 array2 else () let main (w:unit) = let _ = main_p 5 in let _ = main_p 10 in let _ = for i = 1 to 1000 do main_p ( Random.int 1000 ) done in for i = 1 to 1000 do main_p (Random.int 1000) done in *) () let _ = main ()
68d2dd99b9deef22bd63bb69198052c75158b86fc74204d757ed499dd4988437
marcoheisig/cl-mpi
package.lisp
(defpackage :cl-mpi-extensions (:nicknames :mpi-extensions) (:use :cl :cl-mpi :static-vectors :alexandria) (:export #:mpi-send-anything #:mpi-recv-anything #:mpi-waitall-anything #:mpi-isend-anything #:mpi-irecv-anything #:mpi-broadcast-anything))
null
https://raw.githubusercontent.com/marcoheisig/cl-mpi/ba92be06ec1dca74d0ca5256aa387d8a28c8ad86/extensions/package.lisp
lisp
(defpackage :cl-mpi-extensions (:nicknames :mpi-extensions) (:use :cl :cl-mpi :static-vectors :alexandria) (:export #:mpi-send-anything #:mpi-recv-anything #:mpi-waitall-anything #:mpi-isend-anything #:mpi-irecv-anything #:mpi-broadcast-anything))