_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
79d11b47a868bfab1c53e2797df2e95cc6cdd1feabcd4241a01f58625ffd7fce
heraldry/heraldicon
copy_to_new.cljs
(ns heraldicon.frontend.entity.action.copy-to-new (:require [heraldicon.entity.attribution :as attribution] [heraldicon.frontend.entity.form :as form] [heraldicon.frontend.macros :as macros] [heraldicon.frontend.message :as message] [heraldicon.frontend.user.session :as session] [re-frame.core :as rf] [reitit.frontend.easy :as reife])) (defn- copy-data-path [entity-type] [:copy-data entity-type]) (defn- set-attribution [entity source-entity set-attribution?] (let [{source-id :id} source-entity {:keys [license license-version]} (:attribution source-entity) {:keys [attribution] creator :username source-name :name} source-entity] (assoc entity :attribution (if (and set-attribution? source-id) {:nature :derivative :license license :license-version license-version :source-name source-name :source-link (attribution/full-url-for-entity-data source-entity) :source-license license :source-license-version license-version :source-creator-name creator :source-creator-link (attribution/full-url-for-username creator)} (dissoc attribution :source-modification))))) (rf/reg-sub ::copy-data (fn [db [_ entity-type]] (get-in db (copy-data-path entity-type)))) (macros/reg-event-db ::copy (fn [db [_ entity-type target-path]] (let [data-path (copy-data-path entity-type) data (get-in db data-path)] (cond-> db data (-> (assoc-in target-path data) (assoc-in data-path nil)))))) (defn- copy-entity [source-entity set-attribution?] (-> source-entity (select-keys [:type :name :tags :metadata :data]) (set-attribution source-entity set-attribution?))) (defn- create-route [entity-type] (case entity-type :heraldicon.entity.type/arms :route.arms.details/create :heraldicon.entity.type/charge :route.charge.details/create :heraldicon.entity.type/ribbon :route.ribbon.details/create :heraldicon.entity.type/collection :route.collection.details/create)) (rf/reg-fx ::set-create-entity-route (fn [entity-type] (reife/push-state (create-route entity-type)))) (rf/reg-event-fx ::invoke (fn [{:keys [db]} [_ entity-type]] (let [form-db-path (form/data-path entity-type) source-entity (get-in db form-db-path) session (session/data-from-db db) set-attribution? (not= (:user-id source-entity) (:user-id session)) new-entity (copy-entity source-entity set-attribution?)] {:db (assoc-in db (copy-data-path entity-type) new-entity) :fx [[:dispatch [::message/set-success entity-type :string.user.message/created-unsaved-copy]] [::set-create-entity-route entity-type]]}))) (defn action [entity-type] {:title :string.button/copy-to-new :icon "fas fa-clone" :handler #(rf/dispatch [::invoke entity-type]) :disabled? false})
null
https://raw.githubusercontent.com/heraldry/heraldicon/7bf4dd4149e1f69c9e4f9a0b6b826f73f532a01d/src/heraldicon/frontend/entity/action/copy_to_new.cljs
clojure
(ns heraldicon.frontend.entity.action.copy-to-new (:require [heraldicon.entity.attribution :as attribution] [heraldicon.frontend.entity.form :as form] [heraldicon.frontend.macros :as macros] [heraldicon.frontend.message :as message] [heraldicon.frontend.user.session :as session] [re-frame.core :as rf] [reitit.frontend.easy :as reife])) (defn- copy-data-path [entity-type] [:copy-data entity-type]) (defn- set-attribution [entity source-entity set-attribution?] (let [{source-id :id} source-entity {:keys [license license-version]} (:attribution source-entity) {:keys [attribution] creator :username source-name :name} source-entity] (assoc entity :attribution (if (and set-attribution? source-id) {:nature :derivative :license license :license-version license-version :source-name source-name :source-link (attribution/full-url-for-entity-data source-entity) :source-license license :source-license-version license-version :source-creator-name creator :source-creator-link (attribution/full-url-for-username creator)} (dissoc attribution :source-modification))))) (rf/reg-sub ::copy-data (fn [db [_ entity-type]] (get-in db (copy-data-path entity-type)))) (macros/reg-event-db ::copy (fn [db [_ entity-type target-path]] (let [data-path (copy-data-path entity-type) data (get-in db data-path)] (cond-> db data (-> (assoc-in target-path data) (assoc-in data-path nil)))))) (defn- copy-entity [source-entity set-attribution?] (-> source-entity (select-keys [:type :name :tags :metadata :data]) (set-attribution source-entity set-attribution?))) (defn- create-route [entity-type] (case entity-type :heraldicon.entity.type/arms :route.arms.details/create :heraldicon.entity.type/charge :route.charge.details/create :heraldicon.entity.type/ribbon :route.ribbon.details/create :heraldicon.entity.type/collection :route.collection.details/create)) (rf/reg-fx ::set-create-entity-route (fn [entity-type] (reife/push-state (create-route entity-type)))) (rf/reg-event-fx ::invoke (fn [{:keys [db]} [_ entity-type]] (let [form-db-path (form/data-path entity-type) source-entity (get-in db form-db-path) session (session/data-from-db db) set-attribution? (not= (:user-id source-entity) (:user-id session)) new-entity (copy-entity source-entity set-attribution?)] {:db (assoc-in db (copy-data-path entity-type) new-entity) :fx [[:dispatch [::message/set-success entity-type :string.user.message/created-unsaved-copy]] [::set-create-entity-route entity-type]]}))) (defn action [entity-type] {:title :string.button/copy-to-new :icon "fas fa-clone" :handler #(rf/dispatch [::invoke entity-type]) :disabled? false})
0601a7dee6ad72ad5f7dd0b0737cf9590cc2ae7b51e0713182e0180d941eb793
GrammaTech/sel
test-parse.lisp
;;; test-parse.lisp -- command line utility to test parsing (defpackage :software-evolution-library/components/test-parse (:nicknames :sel/components/test-parse :sel/cp/test-parse) (:use :gt/full :software-evolution-library :software-evolution-library/command-line :cl-ppcre :software-evolution-library/software/parseable) (:import-from :software-evolution-library/software/tree-sitter :rule-matching-error :parse-error-ast) (:export :test-parse :run-test-parse)) (in-package :software-evolution-library/components/test-parse) (in-readtable :curry-compose-reader-macros) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter +command-line-options+ '((("help" #\h #\?) :type boolean :optional t :documentation "display help output") (("load" #\l) :type string :action #'handle-load :documentation "load FILE as lisp code") (("eval" #\e) :type string :action #'handle-eval :documentation "eval STRING as lisp code") (("error-type" #\E) :type string :action #'read-from-string :documentation "type of errors to be recognized as interesting") (("error-pattern" #\P) :type string :action #'identity :documentation "CL-PPCRE pattern for errors to be considered interesting") (("round-trip" #\r) :type boolean :optional t :documentation "Attempt round trip comparison (ignoring whitespace)") (("idempotent" #\I) :type boolean :optional t :documentation "Attempt to print, reread, then print, and confirm these are the same") (("language" #\L) :type string :initial-value "c" :documentation "language of input files (e.g. c, c++, lisp, or javascript)")))) (define-command test-parse (source &spec +command-line-options+) "Read a source file and check if there's an error. If there is an error, exit with code 0, otherwise, exit with code 1. These codes are chosen to work with creduce." #.(format nil "Usage examples: test-parse --error-type=\"serapeum::econd-failure\" foo.c test-parse --error-pattern=\"unknown type specifier\" --language=cpp bar.cpp Built from SEL ~a, and ~a ~a.~%" +software-evolution-library-version+ (lisp-implementation-type) (lisp-implementation-version)) (declare (ignorable load eval)) (flet ((interesting? (e) (or (typep e error-type) (and error-pattern (cl-ppcre:scan error-pattern (format nil "~s" e))) (and (not error-type) (not error-pattern))))) (handler-case (let ((g (genome (create-software source :language language))) (trimmed-file (remove-if #'whitespacep (read-file-into-string source)))) (when (emptyp trimmed-file) (exit-command test-parse 1 nil)) (when round-trip (let ((trimmed-genome (remove-if #'whitespacep (source-text g)))) (unless (and (not (emptyp trimmed-genome)) (eql (search trimmed-genome trimmed-file) 0)) (exit-command test-parse 0 nil)))) (when idempotent (when (member-if {typep _ 'parse-error-ast} (convert 'list g)) (exit-command test-parse 1 nil)) (let* ((s (source-text g)) (g2 (genome (from-string (make-instance (resolve-language-from-language-and-source language)) s))) (s2 (source-text g2))) (unless (equal s s2) (exit-command test-parse 0 nil)))) (exit-command test-parse 1 nil)) (error (e) (format t "~s~%" e) (if (interesting? e) A return value of 0 indicates that a partially reduced file is ;; interesting to creduce. (exit-command test-parse 0 e) ;; A return value that isn't 0 indicates that a partially reduced ;; file is not interesting to creduce. (exit-command test-parse 1 e))))))
null
https://raw.githubusercontent.com/GrammaTech/sel/52e037780e877467b0bff60bd0625f4be49557a1/components/test-parse.lisp
lisp
test-parse.lisp -- command line utility to test parsing interesting to creduce. A return value that isn't 0 indicates that a partially reduced file is not interesting to creduce.
(defpackage :software-evolution-library/components/test-parse (:nicknames :sel/components/test-parse :sel/cp/test-parse) (:use :gt/full :software-evolution-library :software-evolution-library/command-line :cl-ppcre :software-evolution-library/software/parseable) (:import-from :software-evolution-library/software/tree-sitter :rule-matching-error :parse-error-ast) (:export :test-parse :run-test-parse)) (in-package :software-evolution-library/components/test-parse) (in-readtable :curry-compose-reader-macros) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter +command-line-options+ '((("help" #\h #\?) :type boolean :optional t :documentation "display help output") (("load" #\l) :type string :action #'handle-load :documentation "load FILE as lisp code") (("eval" #\e) :type string :action #'handle-eval :documentation "eval STRING as lisp code") (("error-type" #\E) :type string :action #'read-from-string :documentation "type of errors to be recognized as interesting") (("error-pattern" #\P) :type string :action #'identity :documentation "CL-PPCRE pattern for errors to be considered interesting") (("round-trip" #\r) :type boolean :optional t :documentation "Attempt round trip comparison (ignoring whitespace)") (("idempotent" #\I) :type boolean :optional t :documentation "Attempt to print, reread, then print, and confirm these are the same") (("language" #\L) :type string :initial-value "c" :documentation "language of input files (e.g. c, c++, lisp, or javascript)")))) (define-command test-parse (source &spec +command-line-options+) "Read a source file and check if there's an error. If there is an error, exit with code 0, otherwise, exit with code 1. These codes are chosen to work with creduce." #.(format nil "Usage examples: test-parse --error-type=\"serapeum::econd-failure\" foo.c test-parse --error-pattern=\"unknown type specifier\" --language=cpp bar.cpp Built from SEL ~a, and ~a ~a.~%" +software-evolution-library-version+ (lisp-implementation-type) (lisp-implementation-version)) (declare (ignorable load eval)) (flet ((interesting? (e) (or (typep e error-type) (and error-pattern (cl-ppcre:scan error-pattern (format nil "~s" e))) (and (not error-type) (not error-pattern))))) (handler-case (let ((g (genome (create-software source :language language))) (trimmed-file (remove-if #'whitespacep (read-file-into-string source)))) (when (emptyp trimmed-file) (exit-command test-parse 1 nil)) (when round-trip (let ((trimmed-genome (remove-if #'whitespacep (source-text g)))) (unless (and (not (emptyp trimmed-genome)) (eql (search trimmed-genome trimmed-file) 0)) (exit-command test-parse 0 nil)))) (when idempotent (when (member-if {typep _ 'parse-error-ast} (convert 'list g)) (exit-command test-parse 1 nil)) (let* ((s (source-text g)) (g2 (genome (from-string (make-instance (resolve-language-from-language-and-source language)) s))) (s2 (source-text g2))) (unless (equal s s2) (exit-command test-parse 0 nil)))) (exit-command test-parse 1 nil)) (error (e) (format t "~s~%" e) (if (interesting? e) A return value of 0 indicates that a partially reduced file is (exit-command test-parse 0 e) (exit-command test-parse 1 e))))))
560e6f1049ff61b4a5169a67294e536b6a9bc0fa920790df6ce86c15b8dbbcce
Leberwurscht/Diaspora-User-Directory
pstyle.ml
(************************************************************************) This file is part of SKS . SKS is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (***********************************************************************) (** Allows for some python-like tricks, at the expense of some performance and indirection *) open StdLabels open MoreLabels module Array = struct include Array let normalize ar i = if i < 0 then length ar + i else i let get ar i = get ar (normalize ar i) let slice start stop ar = let stop = if stop = 0 then length ar else stop in let pos = normalize ar start in let len = (normalize ar stop) - pos in sub ar ~pos ~len end module String = struct include String let normalize str i = if i < 0 then length str + i else i let get str i = get str (normalize str i) let slice start stop str = let stop = if stop = 0 then length str else stop in let pos = normalize str start in let len = (normalize str stop) - pos in sub str ~pos ~len end let rec range ?(stride=1) ?(start=0) stop = if start >= stop then [] else start::(range ~stride ~start:(start+stride) stop) let ( </> ) string (start,stop) = String.slice start stop string let ( <|> ) ar (start,stop) = Array.slice start stop ar
null
https://raw.githubusercontent.com/Leberwurscht/Diaspora-User-Directory/1ca4a06a67d591760516edffddb0308b86b6314c/trie_manager/pstyle.ml
ocaml
********************************************************************** ********************************************************************* * Allows for some python-like tricks, at the expense of some performance and indirection
This file is part of SKS . SKS is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) open StdLabels open MoreLabels module Array = struct include Array let normalize ar i = if i < 0 then length ar + i else i let get ar i = get ar (normalize ar i) let slice start stop ar = let stop = if stop = 0 then length ar else stop in let pos = normalize ar start in let len = (normalize ar stop) - pos in sub ar ~pos ~len end module String = struct include String let normalize str i = if i < 0 then length str + i else i let get str i = get str (normalize str i) let slice start stop str = let stop = if stop = 0 then length str else stop in let pos = normalize str start in let len = (normalize str stop) - pos in sub str ~pos ~len end let rec range ?(stride=1) ?(start=0) stop = if start >= stop then [] else start::(range ~stride ~start:(start+stride) stop) let ( </> ) string (start,stop) = String.slice start stop string let ( <|> ) ar (start,stop) = Array.slice start stop ar
d164051217feac9f5fc4d86dacc88fcf4dfd2d1a3c8bffc09440814fc3144409
erlangonrails/devdb
webmachine_demo_sup.erl
@author author < > YYYY author . %% @doc Supervisor for the webmachine_demo application. -module(webmachine_demo_sup). -author('author <>'). -behaviour(supervisor). %% External exports -export([start_link/0, upgrade/0]). %% supervisor callbacks -export([init/1]). ( ) - > ServerRet %% @doc API for starting the supervisor. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). @spec upgrade ( ) - > ok %% @doc Add processes if necessary. upgrade() -> {ok, {_, Specs}} = init([]), Old = sets:from_list( [Name || {Name, _, _, _} <- supervisor:which_children(?MODULE)]), New = sets:from_list([Name || {Name, _, _, _, _, _} <- Specs]), Kill = sets:subtract(Old, New), sets:fold(fun (Id, ok) -> supervisor:terminate_child(?MODULE, Id), supervisor:delete_child(?MODULE, Id), ok end, ok, Kill), [supervisor:start_child(?MODULE, Spec) || Spec <- Specs], ok. @spec init ( [ ] ) - > SupervisorTree %% @doc supervisor callback. init([]) -> Ip = case os:getenv("WEBMACHINE_IP") of false -> "0.0.0.0"; Any -> Any end, {ok, Dispatch} = file:consult(filename:join( [filename:dirname(code:which(?MODULE)), "..", "priv", "dispatch.conf"])), WebConfig = [ {ip, Ip}, {backlog, 1000}, {port, 8000}, {log_dir, "priv/log"}, {dispatch, Dispatch}], Web = {webmachine_mochiweb, {webmachine_mochiweb, start, [WebConfig]}, permanent, 5000, worker, dynamic}, Processes = [Web], {ok, { {one_for_one, 10, 10}, Processes} }.
null
https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/riak-0.11.0/deps/webmachine/demo/src/webmachine_demo_sup.erl
erlang
@doc Supervisor for the webmachine_demo application. External exports supervisor callbacks @doc API for starting the supervisor. @doc Add processes if necessary. @doc supervisor callback.
@author author < > YYYY author . -module(webmachine_demo_sup). -author('author <>'). -behaviour(supervisor). -export([start_link/0, upgrade/0]). -export([init/1]). ( ) - > ServerRet start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). @spec upgrade ( ) - > ok upgrade() -> {ok, {_, Specs}} = init([]), Old = sets:from_list( [Name || {Name, _, _, _} <- supervisor:which_children(?MODULE)]), New = sets:from_list([Name || {Name, _, _, _, _, _} <- Specs]), Kill = sets:subtract(Old, New), sets:fold(fun (Id, ok) -> supervisor:terminate_child(?MODULE, Id), supervisor:delete_child(?MODULE, Id), ok end, ok, Kill), [supervisor:start_child(?MODULE, Spec) || Spec <- Specs], ok. @spec init ( [ ] ) - > SupervisorTree init([]) -> Ip = case os:getenv("WEBMACHINE_IP") of false -> "0.0.0.0"; Any -> Any end, {ok, Dispatch} = file:consult(filename:join( [filename:dirname(code:which(?MODULE)), "..", "priv", "dispatch.conf"])), WebConfig = [ {ip, Ip}, {backlog, 1000}, {port, 8000}, {log_dir, "priv/log"}, {dispatch, Dispatch}], Web = {webmachine_mochiweb, {webmachine_mochiweb, start, [WebConfig]}, permanent, 5000, worker, dynamic}, Processes = [Web], {ok, { {one_for_one, 10, 10}, Processes} }.
15030f23ad93e1915d64f1e617a286a50be1ad59961d1bb63dc9ceb5af0fad96
nuprl/gradual-typing-performance
shadow-side-west.rkt
#lang racket/base (provide shadow-side-west) (require racket/draw racket/runtime-path) (define-runtime-path shadow-side-west-img "shadow-side-west.png") (define shadow-side-west (read-bitmap shadow-side-west-img))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/htdp-lib/2htdp/planetcute/shadow-side-west.rkt
racket
#lang racket/base (provide shadow-side-west) (require racket/draw racket/runtime-path) (define-runtime-path shadow-side-west-img "shadow-side-west.png") (define shadow-side-west (read-bitmap shadow-side-west-img))
d72b910ece8e815481d8ec08a8de3c522fc0470305a8a6dbe3b90498352902ef
funkywork/yourbones
yourbones_common_test.ml
MIT License Copyright ( c ) 2023 funkywork Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . Copyright (c) 2023 funkywork Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) let () = Alcotest.run "Yourbones.Common" [ Test_tez.cases ]
null
https://raw.githubusercontent.com/funkywork/yourbones/da34f7ee9d465633d19ca949abca12303ed0b609/test/common_test/yourbones_common_test.ml
ocaml
MIT License Copyright ( c ) 2023 funkywork Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . Copyright (c) 2023 funkywork Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) let () = Alcotest.run "Yourbones.Common" [ Test_tez.cases ]
855b9c7b568ee40b1e9798be874694256170aeba5bee971755986a74040c9f14
BitGameEN/bitgamex
erlcloud_kinesis_impl.erl
-*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*- %%% Inspired by, and some code taken from , which is: %%% Copyright ( C ) 2012 Issuu ApS. All rights reserved . %%% %%% Redistribution and use in source and binary forms, with or without %%% modification, are permitted provided that the following conditions %%% are met: 1 . Redistributions of source code must retain the above copyright %%% notice, this list of conditions and the following disclaimer. 2 . Redistributions in binary form must reproduce the above copyright %%% notice, this list of conditions and the following disclaimer in the %%% documentation and/or other materials provided with the distribution. %%% THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ` ` AS IS '' AND %%% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL AUTHOR OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL %%% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS %%% OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT %%% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY %%% OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF %%% SUCH DAMAGE. @author > %% @doc %% %% Implementation of requests to DynamoDB. This code is shared accross %% all API versions. %% %% @end -module(erlcloud_kinesis_impl). -include("erlcloud.hrl"). -include("erlcloud_aws.hrl"). %% Helpers -export([backoff/1, retry/2]). Internal impl api -export([request/3, request/4]). -export_type([json_return/0, attempt/0, retry_fun/0]). -type json_return() :: {ok, jsx:json_term() | binary()} | {error, term()}. -type operation() :: string(). -spec request(aws_config(), operation(), jsx:json_term()) -> json_return(). request(Config, Operation, Json) -> request(Config, Operation, Json, true). -spec request(aws_config(), operation(), jsx:json_term(), boolean()) -> json_return(). request(Config0, Operation, Json, ShouldDecode) -> Body = case Json of [] -> <<"{}">>; _ -> jsx:encode(Json) end, case erlcloud_aws:update_config(Config0) of {ok, Config} -> Headers = headers(Config, Operation, Body), request_and_retry(Config, Headers, Body, ShouldDecode, {attempt, 1}); {error, Reason} -> {error, Reason} end. %% Error handling %% see %% Although it is documented that you should use exponential backoff, exact delays or number of retries %% are not specified. boto ( if I read the code correctly ) waits 2^(Attempt - 2)*50ms before an attempt and will make 10 attempts , which means it will wait up to 12.8 seconds before the last attempt . This algorithm is similar , except that it waits a random interval up to 2^(Attempt-2)*100ms . The average wait time should be the same as boto . TODO make delay configurable TODO refactor retry logic so that it can be used by all requests and move to erlcloud_aws -define(NUM_ATTEMPTS, 10). %% Sleep after an attempt -spec backoff(pos_integer()) -> ok. backoff(1) -> ok; backoff(Attempt) -> timer:sleep(erlcloud_util:rand_uniform((1 bsl (Attempt - 1)) * 100)). -type attempt() :: {attempt, pos_integer()} | {error, term()}. -type retry_fun() :: fun((pos_integer(), term()) -> attempt()). -spec retry(pos_integer(), term()) -> attempt(). retry(Attempt, Reason) when Attempt >= ?NUM_ATTEMPTS -> {error, Reason}; retry(Attempt, _) -> backoff(Attempt), {attempt, Attempt + 1}. -type headers() :: [{string(), string()}]. -spec request_and_retry(aws_config(), headers(), jsx:json_text(), boolean(), attempt()) -> {ok, jsx:json_term() | binary()} | {error, term()}. request_and_retry(_, _, _, _, {error, Reason}) -> {error, Reason}; request_and_retry(Config, Headers, Body, ShouldDecode, {attempt, Attempt}) -> RetryFun = Config#aws_config.kinesis_retry, case erlcloud_httpc:request( url(Config), post, [{<<"content-type">>, <<"application/x-amz-json-1.1">>} | Headers], Body, erlcloud_aws:get_timeout(Config), Config) of {ok, {{200, _}, _, RespBody}} -> Result = case ShouldDecode of true -> decode(RespBody); false -> RespBody end, {ok, Result}; {ok, {{Status, StatusLine}, _, RespBody}} when Status >= 400 andalso Status < 500 -> case client_error(Status, StatusLine, RespBody) of {retry, Reason} -> request_and_retry(Config, Headers, Body, ShouldDecode, RetryFun(Attempt, Reason)); {error, Reason} -> {error, Reason} end; {ok, {{Status, StatusLine}, _, RespBody}} when Status >= 500 -> request_and_retry(Config, Headers, Body, ShouldDecode, RetryFun(Attempt, {http_error, Status, StatusLine, RespBody})); {ok, {{Status, StatusLine}, _, RespBody}} -> {error, {http_error, Status, StatusLine, RespBody}}; {error, Reason} -> TODO there may be some http errors , such as certificate error , that we do n't want to retry request_and_retry(Config, Headers, Body, ShouldDecode, RetryFun(Attempt, Reason)) end. -spec client_error(pos_integer(), string(), binary()) -> {retry, term()} | {error, term()}. client_error(Status, StatusLine, Body) -> try jsx:decode(Body) of Json -> Message = proplists:get_value(<<"message">>, Json, <<>>), case proplists:get_value(<<"__type">>, Json) of undefined -> {error, {http_error, Status, StatusLine, Body}}; <<"ProvisionedThroughputExceededException">> = Type -> {retry, {Type, Message}}; <<"ThrottlingException">> = Type -> {retry, {Type, Message}}; Other -> {error, {Other, Message}} end catch error:badarg -> {error, {http_error, Status, StatusLine, Body}} end. -spec headers(aws_config(), string(), binary()) -> headers(). headers(Config, Operation, Body) -> Headers = [{"host", Config#aws_config.kinesis_host}, {"x-amz-target", Operation}], erlcloud_aws:sign_v4_headers(Config, Headers, Body, erlcloud_aws:aws_region_from_host(Config#aws_config.kinesis_host), "kinesis"). url(#aws_config{kinesis_scheme = Scheme, kinesis_host = Host} = Config) -> lists:flatten([Scheme, Host, port_spec(Config)]). port_spec(#aws_config{kinesis_port=80}) -> ""; port_spec(#aws_config{kinesis_port=Port}) -> [":", erlang:integer_to_list(Port)]. decode(<<>>) -> []; decode(JSON) -> jsx:decode(JSON).
null
https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/deps/erlcloud/src/erlcloud_kinesis_impl.erl
erlang
Inspired by, and some code taken from , which is: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @doc Implementation of requests to DynamoDB. This code is shared accross all API versions. @end Helpers Error handling see Although it is documented that you should use exponential backoff, exact delays or number of retries are not specified. Sleep after an attempt
-*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*- Copyright ( C ) 2012 Issuu ApS. All rights reserved . 1 . Redistributions of source code must retain the above copyright 2 . Redistributions in binary form must reproduce the above copyright THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ` ` AS IS '' AND IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL AUTHOR OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT @author > -module(erlcloud_kinesis_impl). -include("erlcloud.hrl"). -include("erlcloud_aws.hrl"). -export([backoff/1, retry/2]). Internal impl api -export([request/3, request/4]). -export_type([json_return/0, attempt/0, retry_fun/0]). -type json_return() :: {ok, jsx:json_term() | binary()} | {error, term()}. -type operation() :: string(). -spec request(aws_config(), operation(), jsx:json_term()) -> json_return(). request(Config, Operation, Json) -> request(Config, Operation, Json, true). -spec request(aws_config(), operation(), jsx:json_term(), boolean()) -> json_return(). request(Config0, Operation, Json, ShouldDecode) -> Body = case Json of [] -> <<"{}">>; _ -> jsx:encode(Json) end, case erlcloud_aws:update_config(Config0) of {ok, Config} -> Headers = headers(Config, Operation, Body), request_and_retry(Config, Headers, Body, ShouldDecode, {attempt, 1}); {error, Reason} -> {error, Reason} end. boto ( if I read the code correctly ) waits 2^(Attempt - 2)*50ms before an attempt and will make 10 attempts , which means it will wait up to 12.8 seconds before the last attempt . This algorithm is similar , except that it waits a random interval up to 2^(Attempt-2)*100ms . The average wait time should be the same as boto . TODO make delay configurable TODO refactor retry logic so that it can be used by all requests and move to erlcloud_aws -define(NUM_ATTEMPTS, 10). -spec backoff(pos_integer()) -> ok. backoff(1) -> ok; backoff(Attempt) -> timer:sleep(erlcloud_util:rand_uniform((1 bsl (Attempt - 1)) * 100)). -type attempt() :: {attempt, pos_integer()} | {error, term()}. -type retry_fun() :: fun((pos_integer(), term()) -> attempt()). -spec retry(pos_integer(), term()) -> attempt(). retry(Attempt, Reason) when Attempt >= ?NUM_ATTEMPTS -> {error, Reason}; retry(Attempt, _) -> backoff(Attempt), {attempt, Attempt + 1}. -type headers() :: [{string(), string()}]. -spec request_and_retry(aws_config(), headers(), jsx:json_text(), boolean(), attempt()) -> {ok, jsx:json_term() | binary()} | {error, term()}. request_and_retry(_, _, _, _, {error, Reason}) -> {error, Reason}; request_and_retry(Config, Headers, Body, ShouldDecode, {attempt, Attempt}) -> RetryFun = Config#aws_config.kinesis_retry, case erlcloud_httpc:request( url(Config), post, [{<<"content-type">>, <<"application/x-amz-json-1.1">>} | Headers], Body, erlcloud_aws:get_timeout(Config), Config) of {ok, {{200, _}, _, RespBody}} -> Result = case ShouldDecode of true -> decode(RespBody); false -> RespBody end, {ok, Result}; {ok, {{Status, StatusLine}, _, RespBody}} when Status >= 400 andalso Status < 500 -> case client_error(Status, StatusLine, RespBody) of {retry, Reason} -> request_and_retry(Config, Headers, Body, ShouldDecode, RetryFun(Attempt, Reason)); {error, Reason} -> {error, Reason} end; {ok, {{Status, StatusLine}, _, RespBody}} when Status >= 500 -> request_and_retry(Config, Headers, Body, ShouldDecode, RetryFun(Attempt, {http_error, Status, StatusLine, RespBody})); {ok, {{Status, StatusLine}, _, RespBody}} -> {error, {http_error, Status, StatusLine, RespBody}}; {error, Reason} -> TODO there may be some http errors , such as certificate error , that we do n't want to retry request_and_retry(Config, Headers, Body, ShouldDecode, RetryFun(Attempt, Reason)) end. -spec client_error(pos_integer(), string(), binary()) -> {retry, term()} | {error, term()}. client_error(Status, StatusLine, Body) -> try jsx:decode(Body) of Json -> Message = proplists:get_value(<<"message">>, Json, <<>>), case proplists:get_value(<<"__type">>, Json) of undefined -> {error, {http_error, Status, StatusLine, Body}}; <<"ProvisionedThroughputExceededException">> = Type -> {retry, {Type, Message}}; <<"ThrottlingException">> = Type -> {retry, {Type, Message}}; Other -> {error, {Other, Message}} end catch error:badarg -> {error, {http_error, Status, StatusLine, Body}} end. -spec headers(aws_config(), string(), binary()) -> headers(). headers(Config, Operation, Body) -> Headers = [{"host", Config#aws_config.kinesis_host}, {"x-amz-target", Operation}], erlcloud_aws:sign_v4_headers(Config, Headers, Body, erlcloud_aws:aws_region_from_host(Config#aws_config.kinesis_host), "kinesis"). url(#aws_config{kinesis_scheme = Scheme, kinesis_host = Host} = Config) -> lists:flatten([Scheme, Host, port_spec(Config)]). port_spec(#aws_config{kinesis_port=80}) -> ""; port_spec(#aws_config{kinesis_port=Port}) -> [":", erlang:integer_to_list(Port)]. decode(<<>>) -> []; decode(JSON) -> jsx:decode(JSON).
ea6e626c8708d658d5be29b9905df174f4f3617d22b01165e86340c783cb148d
kingcons/cl-store
mop.lisp
(in-package :cl-store) (defun slot-definition-name (slot) (nth 0 slot)) (defun slot-definition-allocation (slot) (nth 6 slot)) (defun slot-definition-initform (slot) (nth 2 slot)) (defun slot-definition-initargs (slot) (nth 1 slot)) (defun slot-accessors (slot) (nth 3 slot)) (defun slot-definition-writers (slot) (append (slot-accessors slot) (nth 5 slot))) (defun slot-definition-readers (slot) (append (slot-accessors slot) (nth 4 slot))) (defun slot-definition-type (slot) (nth 7 slot)) EOF
null
https://raw.githubusercontent.com/kingcons/cl-store/e9328632cd6bf51cb79adeb5d40c6ee5c6f805b4/ecl/mop.lisp
lisp
(in-package :cl-store) (defun slot-definition-name (slot) (nth 0 slot)) (defun slot-definition-allocation (slot) (nth 6 slot)) (defun slot-definition-initform (slot) (nth 2 slot)) (defun slot-definition-initargs (slot) (nth 1 slot)) (defun slot-accessors (slot) (nth 3 slot)) (defun slot-definition-writers (slot) (append (slot-accessors slot) (nth 5 slot))) (defun slot-definition-readers (slot) (append (slot-accessors slot) (nth 4 slot))) (defun slot-definition-type (slot) (nth 7 slot)) EOF
076bddf7c419aa545c0d0a36d74a45bdd9b6d6e6955022ecb9405149218bfba9
jarcane/heresy
fact.rkt
#lang heresy Classical recursive (def fn fact (n) (select ((zero? n) 1) (else (* n (fact (- n 1)))))) W/ Heresy 's for w / carry (def fn fact-2 (n) (for (x in (range n to 1 step -1) with 1) (carry (* cry x)))) ; Folding over a range (def fn fact-3 (n) (foldl * 1 (range 1 to n))) ; Using the m-block (def fn fact-4 (n) (if (zero? n) then 1 else (m let next = n - 1 let x = (fact-4 next) in x * n)))
null
https://raw.githubusercontent.com/jarcane/heresy/a736b69178dffa2ef97f5eb5204f3e06840088c2/examples/fact.rkt
racket
Folding over a range Using the m-block
#lang heresy Classical recursive (def fn fact (n) (select ((zero? n) 1) (else (* n (fact (- n 1)))))) W/ Heresy 's for w / carry (def fn fact-2 (n) (for (x in (range n to 1 step -1) with 1) (carry (* cry x)))) (def fn fact-3 (n) (foldl * 1 (range 1 to n))) (def fn fact-4 (n) (if (zero? n) then 1 else (m let next = n - 1 let x = (fact-4 next) in x * n)))
baaa95784b5c35a18ed12c3dbd2ecfa1ac65153913e701de1f36cfe2b8e46ff0
master-q/carettah
Runner.hs
import System.FilePath import System.Environment import System.Cmd import Paths_carettah (getBinDir) main :: IO () main = do as <- getArgs d <- getBinDir _ <- rawSystem (d </> "_carettah_main_") (as ++ ["+RTS", "-V0"]) return ()
null
https://raw.githubusercontent.com/master-q/carettah/355cadf8e5e957fd7df1d8281c29adf1d22fd399/src/Runner.hs
haskell
import System.FilePath import System.Environment import System.Cmd import Paths_carettah (getBinDir) main :: IO () main = do as <- getArgs d <- getBinDir _ <- rawSystem (d </> "_carettah_main_") (as ++ ["+RTS", "-V0"]) return ()
5395666ef394a6e0aa6a66394db457b77b7dedbe83d79c8daf490215c528e951
ta0kira/zeolite
Paths.hs
----------------------------------------------------------------------------- Copyright 2020 under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . ----------------------------------------------------------------------------- Copyright 2020 Kevin P. Barry 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 : [ ] {-# LANGUAGE Safe #-} module Module.Paths ( PathIOHandler(..), fixPath, fixPaths, ) where import Control.Monad.IO.Class import Data.List (nub,isSuffixOf) import System.FilePath import Base.CompilerError class PathIOHandler r where resolveModule :: (MonadIO m, CollectErrorsM m) => r -> FilePath -> FilePath -> m FilePath isSystemModule :: (MonadIO m, CollectErrorsM m) => r -> FilePath -> FilePath -> m Bool resolveBaseModule :: (MonadIO m, CollectErrorsM m) => r -> m FilePath isBaseModule :: (MonadIO m, CollectErrorsM m) => r -> FilePath -> m Bool zipWithContents :: (MonadIO m, CollectErrorsM m) => r -> FilePath -> [FilePath] -> m [(FilePath,String)] fixPath :: FilePath -> FilePath fixPath = foldl (</>) "" . process [] . map dropSlash . splitPath where dropSlash "/" = "/" dropSlash d | isSuffixOf "/" d = reverse $ tail $ reverse d | otherwise = d process rs (".":ds) = process rs ds process ("..":rs) ("..":ds) = process ("..":"..":rs) ds process ("/":[]) ("..":ds) = process ("/":[]) ds process (_:rs) ("..":ds) = process rs ds process rs (d:ds) = process (d:rs) ds process rs _ = reverse rs fixPaths :: [FilePath] -> [FilePath] fixPaths = nub . map fixPath
null
https://raw.githubusercontent.com/ta0kira/zeolite/6741e1fa38bdb7feaad10780290275cd5282fcbc/src/Module/Paths.hs
haskell
--------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- -} # LANGUAGE Safe #
Copyright 2020 under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2020 Kevin P. Barry 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 : [ ] module Module.Paths ( PathIOHandler(..), fixPath, fixPaths, ) where import Control.Monad.IO.Class import Data.List (nub,isSuffixOf) import System.FilePath import Base.CompilerError class PathIOHandler r where resolveModule :: (MonadIO m, CollectErrorsM m) => r -> FilePath -> FilePath -> m FilePath isSystemModule :: (MonadIO m, CollectErrorsM m) => r -> FilePath -> FilePath -> m Bool resolveBaseModule :: (MonadIO m, CollectErrorsM m) => r -> m FilePath isBaseModule :: (MonadIO m, CollectErrorsM m) => r -> FilePath -> m Bool zipWithContents :: (MonadIO m, CollectErrorsM m) => r -> FilePath -> [FilePath] -> m [(FilePath,String)] fixPath :: FilePath -> FilePath fixPath = foldl (</>) "" . process [] . map dropSlash . splitPath where dropSlash "/" = "/" dropSlash d | isSuffixOf "/" d = reverse $ tail $ reverse d | otherwise = d process rs (".":ds) = process rs ds process ("..":rs) ("..":ds) = process ("..":"..":rs) ds process ("/":[]) ("..":ds) = process ("/":[]) ds process (_:rs) ("..":ds) = process rs ds process rs (d:ds) = process (d:rs) ds process rs _ = reverse rs fixPaths :: [FilePath] -> [FilePath] fixPaths = nub . map fixPath
5b50ddcfc96dfe432fd955a0dd33d138df08968d612f3099f89b7806edc666ec
f-me/carma-public
New.hs
{-# LANGUAGE OverloadedStrings #-} {-| carma-models-style dictionaries interface -} module Data.Dict.New ( NewDict , PreDict , loadNewDict , loadNewDict' , labelOfValue , valueOfLabel ) where import Data.Aeson import qualified Data.HashMap.Strict as HM import Data.Text (Text) import qualified Data.Vector as V -- | Pre-dictionary parsed from JSON (@/_/DictName/@ response). type PreDict = V.Vector (HM.HashMap Text Value) -- | Similar to 'Dict', but with integer values and Text labels. newtype NewDict = NewDict ( HM.HashMap Int Text , HM.HashMap Text Int ) -- | Standard 'loadNewDict' version with @id@ as the value key and -- @label@ as the label key. loadNewDict' :: PreDict -> NewDict loadNewDict' = loadNewDict "id" "label" loadNewDict :: Text -- ^ Internal value key. -> Text -- ^ External label key. -> PreDict -> NewDict loadNewDict kv kl entries = NewDict $ V.foldl' (\(fm, im) e -> case (HM.lookup kv e, HM.lookup kl e) of (Just (Number val), Just (String lab)) -> (HM.insert v lab fm, HM.insert lab v im) where v = round val :: Int _ -> (fm, im)) (HM.empty, HM.empty) entries -- | Given value, lookup label in the dictionary. labelOfValue :: Int -- ^ Value. -> NewDict -> Maybe Text labelOfValue k (NewDict (fm, _)) = HM.lookup k fm -- | Given label, lookup value in the dictionary. valueOfLabel :: Text -- ^ Label. -> NewDict -> Maybe Int valueOfLabel v (NewDict (_, rm)) = HM.lookup v rm
null
https://raw.githubusercontent.com/f-me/carma-public/82a9f44f7d919e54daa4114aa08dfec58b01009b/carma-dict/src/Data/Dict/New.hs
haskell
# LANGUAGE OverloadedStrings # | carma-models-style dictionaries interface | Pre-dictionary parsed from JSON (@/_/DictName/@ response). | Similar to 'Dict', but with integer values and Text labels. | Standard 'loadNewDict' version with @id@ as the value key and @label@ as the label key. ^ Internal value key. ^ External label key. | Given value, lookup label in the dictionary. ^ Value. | Given label, lookup value in the dictionary. ^ Label.
module Data.Dict.New ( NewDict , PreDict , loadNewDict , loadNewDict' , labelOfValue , valueOfLabel ) where import Data.Aeson import qualified Data.HashMap.Strict as HM import Data.Text (Text) import qualified Data.Vector as V type PreDict = V.Vector (HM.HashMap Text Value) newtype NewDict = NewDict ( HM.HashMap Int Text , HM.HashMap Text Int ) loadNewDict' :: PreDict -> NewDict loadNewDict' = loadNewDict "id" "label" loadNewDict :: Text -> Text -> PreDict -> NewDict loadNewDict kv kl entries = NewDict $ V.foldl' (\(fm, im) e -> case (HM.lookup kv e, HM.lookup kl e) of (Just (Number val), Just (String lab)) -> (HM.insert v lab fm, HM.insert lab v im) where v = round val :: Int _ -> (fm, im)) (HM.empty, HM.empty) entries labelOfValue :: Int -> NewDict -> Maybe Text labelOfValue k (NewDict (fm, _)) = HM.lookup k fm valueOfLabel :: Text -> NewDict -> Maybe Int valueOfLabel v (NewDict (_, rm)) = HM.lookup v rm
e034d3e22e7fa05edef7ac51dbc08a1644aec4e908fd1c4b2a530fded5a5f59e
input-output-hk/rscoin-haskell
Acidic.hs
# LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # -- | This module generates Acidic instance. It's separated from the main AcidState only in this way extending AcidState is possible -- (and it's done in testing framework) module RSCoin.Mintette.Acidic ( State , closeState , getStatistics , openState , openMemState , tidyState , GetUtxoPset (..) , GetPreviousMintetteId (..) , CheckNotDoubleSpent (..) , CommitTx (..) , FinishPeriod (..) , StartPeriod (..) , FinishEpoch (..) , ApplyExtraAddresses (..) , ApplyExtraUtxo (..) , GetLastLBlocks (..) , GetLogs (..) , GetPeriodId (..) ) where import Control.Lens (to) import Control.Monad.Trans (MonadIO) import Data.Acid (makeAcidic) import Data.Text (Text) import Formatting (bprint, stext, (%)) import Serokell.AcidState (closeExtendedState, openLocalExtendedState, openMemoryExtendedState, tidyExtendedState) import Serokell.AcidState.Statistics (StoragePart (..), estimateMemoryUsage) import Serokell.Data.Memory.Units (Byte, memory) import Serokell.Util.Text (listBuilderJSONIndent, show') import RSCoin.Mintette.AcidState (State) import qualified RSCoin.Mintette.AcidState as S import qualified RSCoin.Mintette.Storage as MS openState :: MonadIO m => Bool -> FilePath -> m State openState deleteIfExists fp = openLocalExtendedState deleteIfExists fp MS.mkStorage openMemState :: MonadIO m => m State openMemState = openMemoryExtendedState MS.mkStorage closeState :: MonadIO m => State -> m () closeState = closeExtendedState tidyState :: MonadIO m => State -> m () tidyState = tidyExtendedState $(makeAcidic ''MS.Storage [ 'S.getUtxoPset , 'S.getPreviousMintetteId , 'S.getLastLBlocks , 'S.getLogs , 'S.getPeriodId , 'S.getStorage , 'S.checkNotDoubleSpent , 'S.commitTx , 'S.finishPeriod , 'S.startPeriod , 'S.finishEpoch , 'S.applyExtraAddresses , 'S.applyExtraUtxo ]) getStatistics :: MonadIO m => State -> m Text getStatistics st = show' . listBuilderJSONIndent 3 . map toBuilder . estimateMemoryUsage parts <$> S.query st GetStorage where parts = [ StoragePart "utxo" MS.utxo , StoragePart "utxoAdded" MS.utxoAdded , StoragePart "utxoDeleted" MS.utxoDeleted , StoragePart "pset" MS.pset , StoragePart "txset" MS.txset , StoragePart "lBlocks" MS.lBlocks , StoragePart "actionLogs" MS.actionLogs , StoragePart "logHeads" MS.logHeads , StoragePart "Storage" (to id) ] toBuilder (name,size :: Byte) = bprint (stext % ": " % memory) name size
null
https://raw.githubusercontent.com/input-output-hk/rscoin-haskell/109d8f6f226e9d0b360fcaac14c5a90da112a810/src/RSCoin/Mintette/Acidic.hs
haskell
| This module generates Acidic instance. It's separated from the (and it's done in testing framework)
# LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # main AcidState only in this way extending AcidState is possible module RSCoin.Mintette.Acidic ( State , closeState , getStatistics , openState , openMemState , tidyState , GetUtxoPset (..) , GetPreviousMintetteId (..) , CheckNotDoubleSpent (..) , CommitTx (..) , FinishPeriod (..) , StartPeriod (..) , FinishEpoch (..) , ApplyExtraAddresses (..) , ApplyExtraUtxo (..) , GetLastLBlocks (..) , GetLogs (..) , GetPeriodId (..) ) where import Control.Lens (to) import Control.Monad.Trans (MonadIO) import Data.Acid (makeAcidic) import Data.Text (Text) import Formatting (bprint, stext, (%)) import Serokell.AcidState (closeExtendedState, openLocalExtendedState, openMemoryExtendedState, tidyExtendedState) import Serokell.AcidState.Statistics (StoragePart (..), estimateMemoryUsage) import Serokell.Data.Memory.Units (Byte, memory) import Serokell.Util.Text (listBuilderJSONIndent, show') import RSCoin.Mintette.AcidState (State) import qualified RSCoin.Mintette.AcidState as S import qualified RSCoin.Mintette.Storage as MS openState :: MonadIO m => Bool -> FilePath -> m State openState deleteIfExists fp = openLocalExtendedState deleteIfExists fp MS.mkStorage openMemState :: MonadIO m => m State openMemState = openMemoryExtendedState MS.mkStorage closeState :: MonadIO m => State -> m () closeState = closeExtendedState tidyState :: MonadIO m => State -> m () tidyState = tidyExtendedState $(makeAcidic ''MS.Storage [ 'S.getUtxoPset , 'S.getPreviousMintetteId , 'S.getLastLBlocks , 'S.getLogs , 'S.getPeriodId , 'S.getStorage , 'S.checkNotDoubleSpent , 'S.commitTx , 'S.finishPeriod , 'S.startPeriod , 'S.finishEpoch , 'S.applyExtraAddresses , 'S.applyExtraUtxo ]) getStatistics :: MonadIO m => State -> m Text getStatistics st = show' . listBuilderJSONIndent 3 . map toBuilder . estimateMemoryUsage parts <$> S.query st GetStorage where parts = [ StoragePart "utxo" MS.utxo , StoragePart "utxoAdded" MS.utxoAdded , StoragePart "utxoDeleted" MS.utxoDeleted , StoragePart "pset" MS.pset , StoragePart "txset" MS.txset , StoragePart "lBlocks" MS.lBlocks , StoragePart "actionLogs" MS.actionLogs , StoragePart "logHeads" MS.logHeads , StoragePart "Storage" (to id) ] toBuilder (name,size :: Byte) = bprint (stext % ": " % memory) name size
270b098db77f9921aebe2bf563232d9f4bf3a4e609aa16910b9df83f6730b4e5
roman01la/cljs-worklet
lib.cljs
(ns worklet.lib (:refer-clojure :exclude [map filter reduce]) (:require [worklet.core :as w])) (w/defn map [f coll] (.map coll f)) (w/defn filter [f coll] (.filter coll f)) (w/defn reduce [f init coll] (.reduce coll f init))
null
https://raw.githubusercontent.com/roman01la/cljs-worklet/f8fadd6d0acd9e77cd4c32deac1dd9e96bef5ad9/src/worklet/lib.cljs
clojure
(ns worklet.lib (:refer-clojure :exclude [map filter reduce]) (:require [worklet.core :as w])) (w/defn map [f coll] (.map coll f)) (w/defn filter [f coll] (.filter coll f)) (w/defn reduce [f init coll] (.reduce coll f init))
408d4e58274fa50f236b0a8c6e3607b1e53adadc551ec4689c3065ae43b39025
vbmithr/ocaml-bitstamp-api
bitstamp_top.ml
module B = Bitstamp.API(Bitstamp_lwt) let printers = [ "B.Ticker.pp"; "B.Order_book.pp"; "B.Transaction.pp"; "B.Eur_usd.pp"; "B.Balance.pp"; "B.User_transaction.pp"; "B.Order.pp"; "B.Withdraw.pp"; "B.Deposit.pp"; ] let eval_string ?(print_outcome = false) ?(err_formatter = Format.err_formatter) str = let lexbuf = Lexing.from_string str in let phrase = !Toploop.parse_toplevel_phrase lexbuf in Toploop.execute_phrase print_outcome err_formatter phrase let rec install_printers = function | [] -> true | printer :: printers -> let cmd = Printf.sprintf "#install_printer %s;;" printer in eval_string cmd && install_printers printers let () = if not (install_printers printers) then Format.eprintf "Problem installing Bitstamp-printers@."
null
https://raw.githubusercontent.com/vbmithr/ocaml-bitstamp-api/22d503236e7ec725dbdd0e0fdd0116970882b567/top/bitstamp_top.ml
ocaml
module B = Bitstamp.API(Bitstamp_lwt) let printers = [ "B.Ticker.pp"; "B.Order_book.pp"; "B.Transaction.pp"; "B.Eur_usd.pp"; "B.Balance.pp"; "B.User_transaction.pp"; "B.Order.pp"; "B.Withdraw.pp"; "B.Deposit.pp"; ] let eval_string ?(print_outcome = false) ?(err_formatter = Format.err_formatter) str = let lexbuf = Lexing.from_string str in let phrase = !Toploop.parse_toplevel_phrase lexbuf in Toploop.execute_phrase print_outcome err_formatter phrase let rec install_printers = function | [] -> true | printer :: printers -> let cmd = Printf.sprintf "#install_printer %s;;" printer in eval_string cmd && install_printers printers let () = if not (install_printers printers) then Format.eprintf "Problem installing Bitstamp-printers@."
4cebbaaab56acbc27dc32ffeba6a43b4844bd7da30e7c2873e2d3ea0ee549277
janegca/htdp2e
Exercise-016-StringLast.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname Exercise-016-StringLast) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))))) Exercise 16 . ; Define the function string-last, which extracts the last character from a ; non-empty string. Don’t worry about empty strings. (define (string-last str) (string-ith str (- (string-length str) 1))) (string-last "hello")
null
https://raw.githubusercontent.com/janegca/htdp2e/2d50378135edc2b8b1816204021f8763f8b2707b/01-FixedSizeData/Exercise-016-StringLast.rkt
racket
about the language level of this file in a form that our tools can easily process. Define the function string-last, which extracts the last character from a non-empty string. Don’t worry about empty strings.
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname Exercise-016-StringLast) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))))) Exercise 16 . (define (string-last str) (string-ith str (- (string-length str) 1))) (string-last "hello")
1f069228fd67903efdaf84384138885e7387d26e85648f2eda179a7c431e7f74
Engil/Goodboy
disassembly_window.ml
open Notty open Goodboy open Pretty_opcodes type t = int let some s = Some s let get_instr is_extended opcode = try if is_extended then some @@ get_ext_opcode_repr opcode else some @@ get_opcode_repr opcode with | Not_found -> None let image_of_opcode addr v (o : opcode) = let addr = I.string A.(fg (gray 10)) (Utils.show_hex_i16 addr) in let opcode = I.string A.(fg yellow) (Utils.show_hex_i8 v) in let mnemo = I.string A.(fg green) o.mnemo in let operands = match o.operand1, o.operand2 with | None, None -> I.string A.(fg white) "" | Some o1, None -> I.string A.(fg white) (Printf.sprintf "%s" o1) | Some o1, Some o2 -> I.string A.(fg white) (Printf.sprintf "%s,%s" o1 o2) | _ -> assert false in let size = I.string A.(fg blue) (string_of_int o.size) in addr, opcode, mnemo, operands, size let image_of_memory addr value = let addr = I.string A.(fg (gray 10)) (Utils.show_hex_i16 addr) in let value = I.string A.(fg yellow) (Uint8.show_hex value) in addr, value let breakpoint_reached breakpoints i = List.exists (fun (b, _) -> i = b) breakpoints let status_image is_extended pc breakpoints i = if i = pc then I.string A.(fg green) "■ " else if is_extended && (i + 1 = pc) then I.string A.(fg green) "■ " else if breakpoint_reached breakpoints i then I.string A.(fg red) "● " else I.void 2 1 let compile_instructions ~h ~pos ~breakpoints state = let init_array sz = Array.init sz (fun _ -> I.empty) in let get = Mmu.get_n state in let start, until = let start = pos - (h / 2) in let until = pos + (h / 2) in if start < 0 then 0, h else if (pos + (h / 2)) > 0xFFFF then (0xFFFF - h), 0xFFFF else start, until in let sz = until - start + 1 in let status_i = init_array sz in let addr_i = init_array sz in let opcode_i = init_array sz in let mnemo_i = init_array sz in let operands_i = init_array sz in let size_i = init_array sz in let update_instr_arrays i status (addr, opcode, mnemo, operands, size) = status_i.(i) <- status; addr_i.(i) <- addr; opcode_i.(i) <- opcode; mnemo_i.(i) <- mnemo; operands_i.(i) <- operands; size_i.(i) <- size; in let update_memory_arrays i (addr, v) = addr_i.(i) <- addr; opcode_i.(i) <- v; mnemo_i.(i) <- I.string A.(fg white) ""; operands_i.(i) <- I.string A.(fg white) ""; size_i.(i) <- I.string A.(fg white) ""; status_i.(i) <- I.void 2 1 in let get_from_rom is_extended i cursor = let opcode = get cursor |> Uint8.code in let instr = get_instr is_extended opcode in match instr with | Some instr -> begin let status = status_image is_extended state.cpu.pc breakpoints cursor in image_of_opcode cursor opcode instr |> update_instr_arrays i status; let next_is_extended = if opcode = 0xCB && not is_extended then true else false in match instr.size with | 1 -> i + 1, cursor + 1, next_is_extended | 2 -> if (i + 1) < sz then image_of_memory (cursor + 1) (get (cursor + 1)) |> update_memory_arrays (i + 1); i + 2, cursor + 2, next_is_extended | 3 -> if (i + 1) < sz then image_of_memory (cursor + 1) (get (cursor + 1)) |> update_memory_arrays (i + 1); if (i + 2) < sz then image_of_memory (cursor + 2) (get (cursor + 2)) |> update_memory_arrays (i + 2); i + 3, cursor + 3, next_is_extended | _ -> assert false end | None -> begin image_of_memory cursor (Uint8.chr opcode) |> update_memory_arrays i; i + 1, cursor + 1, false end in let rec walk is_extended i cur until = let open Mmu in match cur with | _ when cur >= until -> () | _ when (is_between' cur Memory.cartridge || is_between' cur Memory.wram0 || is_between' cur Memory.wram1) -> let (i, cur, next_is_extended) = get_from_rom is_extended i cur in walk next_is_extended i cur until | _ -> image_of_memory cur (get cur) |> update_memory_arrays i; walk false (succ i) (cur + 1) until in walk false 0 start until; let col a = Array.fold_left I.(<->) I.empty a in let image = I.( col status_i <|> col addr_i |> hpad 2 5 <|> col opcode_i |> hpad 0 5 <|> col mnemo_i |> hpad 0 5 <|> col operands_i |> hpad 0 5 <|> col size_i ) in Window.with_window ~title:"instructions" (I.vsnap (h - 10) image) let help_window = let keys = [ I.string A.(fg white) "P"; I.string A.(fg white) "R"; I.string A.(fg white) "S"; I.string A.(fg white) "F1"; I.string A.(fg white) "F2"; ] |> I.vcat in let descr = [ I.string A.(fg white) "Pause emulation"; I.string A.(fg white) "Run"; I.string A.(fg white) "Single step"; I.string A.(fg white) "Switch to game window"; I.string A.(fg white) "Switch to debugger view"; ] |> I.vcat in I.(keys |> hpad 1 4 <|> descr) |> Window.with_window ~title:"halp"
null
https://raw.githubusercontent.com/Engil/Goodboy/2e9abc243b929d8bdfb7c5d4874ddb8a07c55fac/debugger/disassembly_window.ml
ocaml
open Notty open Goodboy open Pretty_opcodes type t = int let some s = Some s let get_instr is_extended opcode = try if is_extended then some @@ get_ext_opcode_repr opcode else some @@ get_opcode_repr opcode with | Not_found -> None let image_of_opcode addr v (o : opcode) = let addr = I.string A.(fg (gray 10)) (Utils.show_hex_i16 addr) in let opcode = I.string A.(fg yellow) (Utils.show_hex_i8 v) in let mnemo = I.string A.(fg green) o.mnemo in let operands = match o.operand1, o.operand2 with | None, None -> I.string A.(fg white) "" | Some o1, None -> I.string A.(fg white) (Printf.sprintf "%s" o1) | Some o1, Some o2 -> I.string A.(fg white) (Printf.sprintf "%s,%s" o1 o2) | _ -> assert false in let size = I.string A.(fg blue) (string_of_int o.size) in addr, opcode, mnemo, operands, size let image_of_memory addr value = let addr = I.string A.(fg (gray 10)) (Utils.show_hex_i16 addr) in let value = I.string A.(fg yellow) (Uint8.show_hex value) in addr, value let breakpoint_reached breakpoints i = List.exists (fun (b, _) -> i = b) breakpoints let status_image is_extended pc breakpoints i = if i = pc then I.string A.(fg green) "■ " else if is_extended && (i + 1 = pc) then I.string A.(fg green) "■ " else if breakpoint_reached breakpoints i then I.string A.(fg red) "● " else I.void 2 1 let compile_instructions ~h ~pos ~breakpoints state = let init_array sz = Array.init sz (fun _ -> I.empty) in let get = Mmu.get_n state in let start, until = let start = pos - (h / 2) in let until = pos + (h / 2) in if start < 0 then 0, h else if (pos + (h / 2)) > 0xFFFF then (0xFFFF - h), 0xFFFF else start, until in let sz = until - start + 1 in let status_i = init_array sz in let addr_i = init_array sz in let opcode_i = init_array sz in let mnemo_i = init_array sz in let operands_i = init_array sz in let size_i = init_array sz in let update_instr_arrays i status (addr, opcode, mnemo, operands, size) = status_i.(i) <- status; addr_i.(i) <- addr; opcode_i.(i) <- opcode; mnemo_i.(i) <- mnemo; operands_i.(i) <- operands; size_i.(i) <- size; in let update_memory_arrays i (addr, v) = addr_i.(i) <- addr; opcode_i.(i) <- v; mnemo_i.(i) <- I.string A.(fg white) ""; operands_i.(i) <- I.string A.(fg white) ""; size_i.(i) <- I.string A.(fg white) ""; status_i.(i) <- I.void 2 1 in let get_from_rom is_extended i cursor = let opcode = get cursor |> Uint8.code in let instr = get_instr is_extended opcode in match instr with | Some instr -> begin let status = status_image is_extended state.cpu.pc breakpoints cursor in image_of_opcode cursor opcode instr |> update_instr_arrays i status; let next_is_extended = if opcode = 0xCB && not is_extended then true else false in match instr.size with | 1 -> i + 1, cursor + 1, next_is_extended | 2 -> if (i + 1) < sz then image_of_memory (cursor + 1) (get (cursor + 1)) |> update_memory_arrays (i + 1); i + 2, cursor + 2, next_is_extended | 3 -> if (i + 1) < sz then image_of_memory (cursor + 1) (get (cursor + 1)) |> update_memory_arrays (i + 1); if (i + 2) < sz then image_of_memory (cursor + 2) (get (cursor + 2)) |> update_memory_arrays (i + 2); i + 3, cursor + 3, next_is_extended | _ -> assert false end | None -> begin image_of_memory cursor (Uint8.chr opcode) |> update_memory_arrays i; i + 1, cursor + 1, false end in let rec walk is_extended i cur until = let open Mmu in match cur with | _ when cur >= until -> () | _ when (is_between' cur Memory.cartridge || is_between' cur Memory.wram0 || is_between' cur Memory.wram1) -> let (i, cur, next_is_extended) = get_from_rom is_extended i cur in walk next_is_extended i cur until | _ -> image_of_memory cur (get cur) |> update_memory_arrays i; walk false (succ i) (cur + 1) until in walk false 0 start until; let col a = Array.fold_left I.(<->) I.empty a in let image = I.( col status_i <|> col addr_i |> hpad 2 5 <|> col opcode_i |> hpad 0 5 <|> col mnemo_i |> hpad 0 5 <|> col operands_i |> hpad 0 5 <|> col size_i ) in Window.with_window ~title:"instructions" (I.vsnap (h - 10) image) let help_window = let keys = [ I.string A.(fg white) "P"; I.string A.(fg white) "R"; I.string A.(fg white) "S"; I.string A.(fg white) "F1"; I.string A.(fg white) "F2"; ] |> I.vcat in let descr = [ I.string A.(fg white) "Pause emulation"; I.string A.(fg white) "Run"; I.string A.(fg white) "Single step"; I.string A.(fg white) "Switch to game window"; I.string A.(fg white) "Switch to debugger view"; ] |> I.vcat in I.(keys |> hpad 1 4 <|> descr) |> Window.with_window ~title:"halp"
4188e26b798aff8e3a52aa3a3d6a68072a5c61a859f6899f91476aaf55ae4d65
ssor/erlangDemos
link_ex.erl
-module(link_ex). -behaviour(gen_server). -export([start_link/0, ping/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -record(state, {}). start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). ping() -> gen_server:cast(?SERVER, ping). init([]) -> {ok, #state{}}. handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast(ping, State) -> io:format("Got It!~n"), {noreply, State}. handle_info(timeout, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
null
https://raw.githubusercontent.com/ssor/erlangDemos/632cd905be2c4f275f1c1ae15238e711d7bb9147/erlware-Erlang-and-OTP-in-Action-Source/link_ex.erl
erlang
gen_server callbacks
-module(link_ex). -behaviour(gen_server). -export([start_link/0, ping/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -record(state, {}). start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). ping() -> gen_server:cast(?SERVER, ping). init([]) -> {ok, #state{}}. handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast(ping, State) -> io:format("Got It!~n"), {noreply, State}. handle_info(timeout, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
042d924a25ba399ac28c4fec74f94289bc17385a31836a446d60dc213d01834e
sharplispers/montezuma
tc-stop-filter.lisp
(in-package #:montezuma) (defun asdf-system-directory (asdf-system-name) "Computes the directory in which the .asdf file for a given ASDF system resides." (make-pathname :directory (pathname-directory (truename (asdf:system-definition-pathname (asdf:find-system asdf-system-name)))))) (defun montezuma.asd-relative (path) (merge-pathnames path (asdf-system-directory :montezuma))) ;; This seems kind of ridiculous. See ;; <#utime_requested>; ;; even Lisp implementors find it surprising. (defparameter *word-file-path* (montezuma.asd-relative (make-pathname :name "wordfile" :type nil :defaults (make-pathname :directory '(:relative "tests" "unit" "analysis" "data"))))) (deftestfun test-stop-filter (with-input-from-string (input "The Quick AND the DEAD the and to it there their") (let ((filter (make-instance 'stop-filter :input (make-instance 'lowercase-tokenizer :input input) :file *word-file-path*))) (test stop-filter-1 (next-token filter) (make-token "quick" 4 9) #'token=) (test stop-filter-2 (next-token filter) (make-token "dead" 18 22) #'token=) (test stop-filter-3 (next-token filter) nil))))
null
https://raw.githubusercontent.com/sharplispers/montezuma/ee2129eece7065760de4ebbaeffaadcb27644738/tests/unit/analysis/tc-stop-filter.lisp
lisp
This seems kind of ridiculous. See <#utime_requested>; even Lisp implementors find it surprising.
(in-package #:montezuma) (defun asdf-system-directory (asdf-system-name) "Computes the directory in which the .asdf file for a given ASDF system resides." (make-pathname :directory (pathname-directory (truename (asdf:system-definition-pathname (asdf:find-system asdf-system-name)))))) (defun montezuma.asd-relative (path) (merge-pathnames path (asdf-system-directory :montezuma))) (defparameter *word-file-path* (montezuma.asd-relative (make-pathname :name "wordfile" :type nil :defaults (make-pathname :directory '(:relative "tests" "unit" "analysis" "data"))))) (deftestfun test-stop-filter (with-input-from-string (input "The Quick AND the DEAD the and to it there their") (let ((filter (make-instance 'stop-filter :input (make-instance 'lowercase-tokenizer :input input) :file *word-file-path*))) (test stop-filter-1 (next-token filter) (make-token "quick" 4 9) #'token=) (test stop-filter-2 (next-token filter) (make-token "dead" 18 22) #'token=) (test stop-filter-3 (next-token filter) nil))))
c3286427b75634f0f62bd197901e22401314f32121248d3a4377af57e523ef96
pedestal/pedestal
route.clj
Copyright 2013 Relevance , Inc. Copyright 2014 - 2022 Cognitect , Inc. ; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( ) ; 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 io.pedestal.http.route (:require [clojure.string :as str] [clojure.core.incubator :refer [dissoc-in]] [io.pedestal.interceptor :as interceptor] [io.pedestal.interceptor.chain :as interceptor.chain] [io.pedestal.log :as log] [io.pedestal.http.route.definition :as definition] [io.pedestal.http.route.definition.terse :as terse] [io.pedestal.http.route.definition.table :as table] [io.pedestal.http.route.router :as router] [io.pedestal.http.route.linear-search :as linear-search] [io.pedestal.http.route.map-tree :as map-tree] [io.pedestal.http.route.prefix-tree :as prefix-tree]) (:import (java.net URLEncoder URLDecoder))) (comment ;; Structure of a route. 'tree' returns a list of these. {:route-name :new-user :app-name :example-app ; optional like Ruby on Rails ; (catch-all route is "/*path") :method :post ; or :any, :get, :put, ... :scheme :https ; optional :host "example.com" ; optional :port "8080" ; optional :interceptors [...] ; vector of interceptors to ; be enqueued on the context ;; Generated for path-matching: :path-re #"/\Quser\E/([^/]+)/(.+)" :path-parts ["user" :id :blah] :path-params [:id :blah] :path-constraints {:id "([^/]+)" :blah "(.+)"} :query-constraints {:name #".+" :search #"[0-9]+"} ;; Generated for routing: :matcher (fn [request] ...) ; returns map from path-params to string ; values on match, nil on non-match }) ;;; Parsing URL query strings (RFC 3986) Java 's URLEncoder / URLDecoder are only correct when applied on * parts * of a query string . You must specify UTF-8 as the encoding . ;; ;; See -research.com/archives/2009/02/03/what-every-web-developer-must-know-about-url-encoding (defn decode-query-part "Decodes one key or value of URL-encoded UTF-8 characters in a URL query string." [string] (URLDecoder/decode string "UTF-8")) (defn encode-query-part "Encodes one key or value for a UTF-8 URL-encoded query string. Encodes space as +." [string] (URLEncoder/encode string "UTF-8")) (defn- add! "Like 'assoc!' but creates a vector of values if the key already exists in the map. Ignores nil values." [m k v] (assoc! m k (if-let [p (get m k)] (if (vector? p) (conj p v) [p v]) v))) (defn parse-query-string "Parses URL query string (not including the leading '?') into a map. options are key-value pairs, valid options are: :key-fn Function to call on parameter keys (after URL decoding), returns key for the map, default converts to a keyword. :value-fn Function to call on the key (after passing through key-fn) and parameter value (after URL decoding), returns value for the map, default does nothing." [^String string & options] (let [{:keys [key-fn value-fn] :or {key-fn keyword value-fn (fn [_ v] v)}} options] (let [end (count string)] (loop [i 0 m (transient {}) key nil b (StringBuilder.)] (if (= end i) (persistent! (add! m key (value-fn key (decode-query-part (str b))))) (let [c (.charAt string i)] (cond (and (= \= c) (not key)) ; unescaped = is allowed in values (recur (inc i) m (key-fn (decode-query-part (str b))) (StringBuilder.)) (= \& c) (recur (inc i) (add! m key (value-fn key (decode-query-part (str b)))) nil (StringBuilder.)) :else (recur (inc i) m key (.append b c))))))))) (defn- parse-query-string-params "Some platforms decode the query string automatically, providing a map of parameters instead. Process that map, returning an immutable map and supporting the same options as parse-query-string" [params & options] (let [{:keys [key-fn value-fn] :or {key-fn keyword value-fn (fn [_ v] v)}} options] (persistent! (reduce-kv (fn [acc k v] (let [newk (key-fn k)] (assoc! acc newk (value-fn newk v)))) (transient {}) params)))) (defn parse-query-params [request] (merge-with merge request (if-let [params (:query-string-params request)] (let [parsed-params (parse-query-string-params params)] {:query-params parsed-params :params parsed-params}) (when-let [string (:query-string request)] (let [params (parse-query-string string)] {:query-params params :params params}))))) (defn parse-param-map [m] (persistent! (reduce-kv (fn [acc k v] (assoc! acc k (decode-query-part v))) (transient {}) m))) (defn parse-path-params [request] (if-let [m (:path-params request)] (let [res (assoc request :path-params (parse-param-map m))] res) request)) Combined matcher & request handler (defn- replace-method "Replace the HTTP method of a request with the value provided at param-path (if provided). Removes the value found at param-path." [param-path request] (let [{:keys [request-method]} request] (if-let [method (get-in request param-path)] (-> request (assoc :request-method (keyword method)) (dissoc-in param-path)) request))) ;;; Linker (defn- merge-param-options "Merges the :params map into :path-params and :query-params. The :path-params keys are taken from the route, any other keys in :params are added to :query-params. Returns updated opts." [opts route] (let [{:keys [params request]} opts] (log/debug :msg "MERGE-PARAM-OPTIONS" :opts opts :params params :request request) (-> opts (dissoc :params) (update-in [:path-params] #(merge (:path-params request) params %)) (update-in [:query-params] #(merge (apply dissoc params (:path-params route)) %))))) (defn- merge-method-param "If the route's method is other than GET or POST and opts contains non-nil :method-param, adds the method name on to the :query-params map. Returns updated opts map. If opts does not contain :method-param, defaults to :_method." [opts route] (let [{:keys [method]} route {:keys [method-param]} opts] (if (and (not= :get method) (not= :post method) method-param) (assoc-in opts [:query-params method-param] (name method)) opts))) (defn- combine-opts [opts default-opts route] (-> (merge default-opts opts) (merge-param-options route) (merge-method-param route))) (defn- context-path [{:keys [context request] :as opts}] (log/debug :in :context-path :context context :context-type (type context) :resolved-context (when (symbol? context) (resolve context)) :request request) (when-let [context-str (cond (string? context) context (fn? context) (context) (symbol? context) ((resolve context)) :else (:context-path request))] (str/split context-str #"/"))) (def ^{:private true} standard-scheme->port {:http 80 :https 443}) (defn- non-standard-port? [scheme port] (not= port (standard-scheme->port scheme))) (defn- link-str "Returns a string for a route, providing the minimum URL necessary given the route and opts. opts is a map as described in the docstring for 'url-for'." [route opts] (let [{:keys [path-params strict-path-params? query-params request fragment override absolute?] override-host :host override-port :port override-scheme :scheme} opts {:keys [scheme host port path-parts path]} route context-path-parts (context-path opts) path-parts (do (log/debug :in :link-str :path-parts path-parts :context-path-parts context-path-parts) ;;(concat context-path-parts path-parts) (cond (and context-path-parts (empty? (first path-parts))) (concat context-path-parts (rest path-parts)) context-path-parts (concat context-path-parts path-parts) :else path-parts)) _ (when (and (true? strict-path-params?) (or (not= (set (keys path-params)) ;; Do the params passed in... (set (seq (:path-params route))) ;; match the params from the route? `seq` is used to handle cases where no `path-params` are required ) ;; nils are not allowed. (reduce-kv #(if (nil? %3) (reduced true) false) nil path-params))) (throw (ex-info "Attempted to create a URL with `url-for`, but missing required :path-params - :strict-path-params was set to true. Either include all path-params (`nil` is not allowed), or if your URL actually contains ':' in the path, set :strict-path-params to false in the options" {:path-parts path-parts :path-params path-params :options opts :route route}))) path-chunk (str/join \/ (map #(get path-params % %) path-parts)) path (if (and (= \/ (last path)) (not= \/ (last path-chunk))) (str path-chunk "/") path-chunk) request-scheme (:scheme request) request-host (:server-name request) request-port (:server-port request) scheme (or override-scheme scheme request-scheme) host (or override-host host request-host) port (or override-port port request-port) scheme-mismatch (not= scheme request-scheme) host-mismatch (not= host request-host) port-mismatch (not= port request-port)] (str (when (or absolute? scheme-mismatch host-mismatch port-mismatch) (str (when (or absolute? scheme-mismatch) (str (name scheme) \:)) "//" host (when (non-standard-port? scheme port) (str \: port)))) (str (when-not (.startsWith path "/") "/") path) (when-not (str/blank? fragment) (str "#" fragment)) (when (seq query-params) (str \? (str/join \& (map (fn [[k v]] (str (encode-query-part (name k)) \= (encode-query-part (str v)))) query-params))))))) (defn- linker-map "Returns a map like {app-name {route-name route}}. Routes without an application name will have nil as the app-name key." [routes] (reduce (fn [m route] (let [{:keys [app-name route-name]} route] (assoc-in m [app-name route-name] route))) {} routes)) (defn- find-route "Finds and returns a route in the map returned by linker-map, or throws an exception if not found." [m app-name route-name] (or (get-in m [app-name route-name]) (get-in m [nil route-name]) (throw (ex-info "Route not found" {:app-name app-name :route-name route-name})))) (defn url-for-routes "Returns a function that generates URL routes (as strings) from the routes table. The returned function has the signature: [route-name & options] Where 'options' are key-value pairs from: :app-name Application name specified for this route :request The original request; it will be merged into the generated link. :params A map of all parameters; any params not used as path parameters will be added to the query string :path-params A map of path parameters only :strict-path-params? A boolean, when true will throw an exception if all path-params aren't fulfilled for the url :query-params A map of query-string parameters only :method-param Keyword naming the query-string parameter in which to place the HTTP method name, if it is neither GET nor POST. If nil, the HTTP method name will not be included in the query string. Default is nil. :context A string, function that returns a string, or symbol that resolves to a function that returns a string that specifies a root context for the URL. Default is nil. :fragment A string for the fragment part of the url. :absolute? Boolean, whether or not to force an absolute URL :scheme Keyword (:http | :https) used to override the scheme portion of the url. :host A string used to override the host portion of the URL. :port An integer used to override the port in the URL. In addition, you may supply default-options to the 'url-for-routes' function, which are merged with the options supplied to the returned function." [routes & default-options] (let [{:as default-opts} default-options m (linker-map routes)] (fn [route-name & options] (let [{:keys [app-name] :as options-map} options default-app-name (:app-name default-opts) route (find-route m (or app-name default-app-name) route-name) opts (combine-opts options-map default-opts route)] (link-str route opts))))) (def ^:private ^:dynamic *url-for* "Dynamic var which holds the 'contextual' linker. The contextual linker is created by the router at routing time. The router will create the linker based on. - The routing table it is routing against. - The incoming request it has just routed." nil) (defn url-for "Invokes currently bound contextual linker to generate url based on - The routing table in use. - The incoming request being routed. where `options` are as described in `url-for-routes`." [route-name & options] (if *url-for* (apply (if (delay? *url-for*) (deref *url-for*) *url-for*) route-name options) (throw (ex-info "*url-for* not bound" {})))) (defprotocol ExpandableRoutes (-expand-routes [expandable-route-spec] "Generate and return the routing table from a given expandable form of routing data.")) (extend-protocol ExpandableRoutes clojure.lang.APersistentVector (-expand-routes [route-spec] (terse/terse-routes route-spec)) clojure.lang.APersistentMap (-expand-routes [route-spec] (-expand-routes [[(terse/map-routes->vec-routes route-spec)]])) clojure.lang.APersistentSet (-expand-routes [route-spec] (table/table-routes route-spec))) (defn expand-routes "Given a value (the route specification), produce and return a sequence of route-maps -- the expanded routes from the specification. Ensure the integrity of the sequence of route maps (even if they've already been checked). - Constraints are correctly ordered (most specific to least specific) - Route names are unique" [route-spec] {:pre [(if-not (satisfies? ExpandableRoutes route-spec) (throw (ex-info "You're trying to use something as a route specification that isn't supported by the protocol; Perhaps you need to extend it?" {:routes route-spec :type (type route-spec)})) true)] :post [(seq? %) (every? (every-pred map? :path :route-name :method) %)]} (definition/ensure-routes-integrity (-expand-routes route-spec))) (defprotocol RouterSpecification (router-spec [specification router-ctor] "Returns an interceptor which attempts to match each route against a :request in context. For the first route that matches, it will: - enqueue the matched route's interceptors - associate the route into the context at :route - associate a map of :path-params into the :request If no route matches, returns context with :route nil.")) (defn- route-context [context router routes] (if-let [route (router/find-route router (:request context))] This is where path - params are added to the request . (let [request-with-path-params (assoc (:request context) :path-params (:path-params route)) linker (delay (url-for-routes routes :request request-with-path-params))] (-> context (assoc :route route :request (assoc request-with-path-params :url-for linker) :url-for linker) (assoc-in [:bindings #'*url-for*] linker) (interceptor.chain/enqueue (:interceptors route)))) (assoc context :route nil))) (extend-protocol RouterSpecification clojure.lang.Sequential (router-spec [seq router-ctor] (let [router (router-ctor seq)] (interceptor/interceptor {:name ::router :enter #(route-context % router seq)}))) clojure.lang.Fn (router-spec [f router-ctor] ;; Caution: This could be very slow becuase it has to build the routing data ;; structure every time it routes a request. ;; This is only intended if you wanted to dynamically dispatch in a dynamic router ;; or completely control all routing aspects. (interceptor/interceptor {:name ::router :enter (fn [context] (let [routes (f) router (router-ctor routes)] (route-context context router routes)))}))) (def router-implementations {:map-tree map-tree/router :prefix-tree prefix-tree/router :linear-search linear-search/router}) (defn router "Delegating fn for router-specification." ([spec] (router spec :map-tree)) ([spec router-impl-key-or-fn] (assert (or (contains? router-implementations router-impl-key-or-fn) (fn? router-impl-key-or-fn)) (format "No router implementation exists for key %s. Please use one of %s." router-impl-key-or-fn (keys router-implementations))) (let [router-ctor (if (fn? router-impl-key-or-fn) router-impl-key-or-fn (router-impl-key-or-fn router-implementations))] (router-spec spec router-ctor)))) (def query-params "Returns an interceptor which parses query-string parameters from an HTTP request into a map. Keys in the map are query-string parameter names, as keywords, and values are strings. The map is assoc'd into the request at :query-params." ;; This doesn't need to be a function but it's done that way for ;; consistency with 'method-param' (interceptor/interceptor {:name ::query-params :enter (fn [ctx] (try (update-in ctx [:request] parse-query-params) (catch IllegalArgumentException iae (interceptor.chain/terminate (assoc ctx :response {:status 400 :body (str "Bad Request - " (.getMessage iae))})))))})) (def path-params-decoder "An Interceptor which URL-decodes path parameters." (interceptor/interceptor {:name ::path-params-decoder :enter (fn [ctx] (try (update-in ctx [:request] parse-path-params) (catch IllegalArgumentException iae (interceptor.chain/terminate (assoc ctx :response {:status 400 :body (str "Bad Request - " (.getMessage iae))})))))})) (defn method-param "Returns an interceptor that smuggles HTTP verbs through a value in the request. Must come *after* the interceptor that populates that value (e.g. query-params or body-params). query-param-or-param-path may be one of two things: - The parameter inside :query-params where the verb will reside. - A complete path to a value elsewhere in the request, such as [:query-params :_method] or [:body-params \"_method\"] The path [:query-params :_method] is used by default." ([] (method-param [:query-params :_method])) ([query-param-or-param-path] (let [param-path (if (vector? query-param-or-param-path) query-param-or-param-path [:query-params query-param-or-param-path])] (interceptor/interceptor {:name ::method-param :enter (fn [ctx] (update-in ctx [:request] #(replace-method param-path %)))})))) (defn form-action-for-routes "Like 'url-for-routes' but the returned function returns a map with the keys :action, the URL string; and :method, the HTTP verb as a lower-case string. Also, the :method-param is :_method by default, so HTTP verbs other than GET and POST will be converted to POST with the actual verb in the query string." [routes & default-options] (let [{:as default-opts} default-options m (linker-map routes)] (fn [route-name & options] (let [{:keys [app-name] :as options-map} options {:keys [method] :as route} (find-route m app-name route-name) opts (combine-opts options-map (merge {:method-param :_method} default-opts) route)] {:action (link-str route opts) :method (name (if (and (:method-param opts) (not (= :get method))) :post method))})))) ;;; Help for debugging (defn print-routes "Prints route table `routes` in easier to read format." [routes] (doseq [r (map (fn [{:keys [method path route-name]}] [method path route-name]) routes)] (println r))) (defn try-routing-for [spec router-type query-string verb] (let [router (router spec router-type) context {:request {:path-info query-string :request-method verb}} context ((:enter router) context)] (:route context)))
null
https://raw.githubusercontent.com/pedestal/pedestal/53bfe70143a22cdfd2f0d183023334a199c9e9a2/route/src/io/pedestal/http/route.clj
clojure
The use and distribution terms for this software are covered by the which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. Structure of a route. 'tree' returns a list of these. optional (catch-all route is "/*path") or :any, :get, :put, ... optional optional optional vector of interceptors to be enqueued on the context Generated for path-matching: Generated for routing: returns map from path-params to string values on match, nil on non-match Parsing URL query strings (RFC 3986) See -research.com/archives/2009/02/03/what-every-web-developer-must-know-about-url-encoding unescaped = is allowed in values Linker (concat context-path-parts path-parts) Do the params passed in... match the params from the route? `seq` is used to handle cases where no `path-params` are required nils are not allowed. it will be merged into the any params not used as Caution: This could be very slow becuase it has to build the routing data structure every time it routes a request. This is only intended if you wanted to dynamically dispatch in a dynamic router or completely control all routing aspects. This doesn't need to be a function but it's done that way for consistency with 'method-param' and :method, the HTTP verb as a lower-case Help for debugging
Copyright 2013 Relevance , Inc. Copyright 2014 - 2022 Cognitect , Inc. Eclipse Public License 1.0 ( ) (ns io.pedestal.http.route (:require [clojure.string :as str] [clojure.core.incubator :refer [dissoc-in]] [io.pedestal.interceptor :as interceptor] [io.pedestal.interceptor.chain :as interceptor.chain] [io.pedestal.log :as log] [io.pedestal.http.route.definition :as definition] [io.pedestal.http.route.definition.terse :as terse] [io.pedestal.http.route.definition.table :as table] [io.pedestal.http.route.router :as router] [io.pedestal.http.route.linear-search :as linear-search] [io.pedestal.http.route.map-tree :as map-tree] [io.pedestal.http.route.prefix-tree :as prefix-tree]) (:import (java.net URLEncoder URLDecoder))) (comment {:route-name :new-user like Ruby on Rails :path-re #"/\Quser\E/([^/]+)/(.+)" :path-parts ["user" :id :blah] :path-params [:id :blah] :path-constraints {:id "([^/]+)" :blah "(.+)"} :query-constraints {:name #".+" :search #"[0-9]+"} }) Java 's URLEncoder / URLDecoder are only correct when applied on * parts * of a query string . You must specify UTF-8 as the encoding . (defn decode-query-part "Decodes one key or value of URL-encoded UTF-8 characters in a URL query string." [string] (URLDecoder/decode string "UTF-8")) (defn encode-query-part "Encodes one key or value for a UTF-8 URL-encoded query string. Encodes space as +." [string] (URLEncoder/encode string "UTF-8")) (defn- add! "Like 'assoc!' but creates a vector of values if the key already exists in the map. Ignores nil values." [m k v] (assoc! m k (if-let [p (get m k)] (if (vector? p) (conj p v) [p v]) v))) (defn parse-query-string "Parses URL query string (not including the leading '?') into a map. options are key-value pairs, valid options are: :key-fn Function to call on parameter keys (after URL decoding), returns key for the map, default converts to a keyword. :value-fn Function to call on the key (after passing through key-fn) and parameter value (after URL decoding), returns value for the map, default does nothing." [^String string & options] (let [{:keys [key-fn value-fn] :or {key-fn keyword value-fn (fn [_ v] v)}} options] (let [end (count string)] (loop [i 0 m (transient {}) key nil b (StringBuilder.)] (if (= end i) (persistent! (add! m key (value-fn key (decode-query-part (str b))))) (let [c (.charAt string i)] (cond (recur (inc i) m (key-fn (decode-query-part (str b))) (StringBuilder.)) (= \& c) (recur (inc i) (add! m key (value-fn key (decode-query-part (str b)))) nil (StringBuilder.)) :else (recur (inc i) m key (.append b c))))))))) (defn- parse-query-string-params "Some platforms decode the query string automatically, providing a map of parameters instead. Process that map, returning an immutable map and supporting the same options as parse-query-string" [params & options] (let [{:keys [key-fn value-fn] :or {key-fn keyword value-fn (fn [_ v] v)}} options] (persistent! (reduce-kv (fn [acc k v] (let [newk (key-fn k)] (assoc! acc newk (value-fn newk v)))) (transient {}) params)))) (defn parse-query-params [request] (merge-with merge request (if-let [params (:query-string-params request)] (let [parsed-params (parse-query-string-params params)] {:query-params parsed-params :params parsed-params}) (when-let [string (:query-string request)] (let [params (parse-query-string string)] {:query-params params :params params}))))) (defn parse-param-map [m] (persistent! (reduce-kv (fn [acc k v] (assoc! acc k (decode-query-part v))) (transient {}) m))) (defn parse-path-params [request] (if-let [m (:path-params request)] (let [res (assoc request :path-params (parse-param-map m))] res) request)) Combined matcher & request handler (defn- replace-method "Replace the HTTP method of a request with the value provided at param-path (if provided). Removes the value found at param-path." [param-path request] (let [{:keys [request-method]} request] (if-let [method (get-in request param-path)] (-> request (assoc :request-method (keyword method)) (dissoc-in param-path)) request))) (defn- merge-param-options "Merges the :params map into :path-params and :query-params. The :path-params keys are taken from the route, any other keys in :params are added to :query-params. Returns updated opts." [opts route] (let [{:keys [params request]} opts] (log/debug :msg "MERGE-PARAM-OPTIONS" :opts opts :params params :request request) (-> opts (dissoc :params) (update-in [:path-params] #(merge (:path-params request) params %)) (update-in [:query-params] #(merge (apply dissoc params (:path-params route)) %))))) (defn- merge-method-param "If the route's method is other than GET or POST and opts contains non-nil :method-param, adds the method name on to the :query-params map. Returns updated opts map. If opts does not contain :method-param, defaults to :_method." [opts route] (let [{:keys [method]} route {:keys [method-param]} opts] (if (and (not= :get method) (not= :post method) method-param) (assoc-in opts [:query-params method-param] (name method)) opts))) (defn- combine-opts [opts default-opts route] (-> (merge default-opts opts) (merge-param-options route) (merge-method-param route))) (defn- context-path [{:keys [context request] :as opts}] (log/debug :in :context-path :context context :context-type (type context) :resolved-context (when (symbol? context) (resolve context)) :request request) (when-let [context-str (cond (string? context) context (fn? context) (context) (symbol? context) ((resolve context)) :else (:context-path request))] (str/split context-str #"/"))) (def ^{:private true} standard-scheme->port {:http 80 :https 443}) (defn- non-standard-port? [scheme port] (not= port (standard-scheme->port scheme))) (defn- link-str "Returns a string for a route, providing the minimum URL necessary given the route and opts. opts is a map as described in the docstring for 'url-for'." [route opts] (let [{:keys [path-params strict-path-params? query-params request fragment override absolute?] override-host :host override-port :port override-scheme :scheme} opts {:keys [scheme host port path-parts path]} route context-path-parts (context-path opts) path-parts (do (log/debug :in :link-str :path-parts path-parts :context-path-parts context-path-parts) (cond (and context-path-parts (empty? (first path-parts))) (concat context-path-parts (rest path-parts)) context-path-parts (concat context-path-parts path-parts) :else path-parts)) _ (when (and (true? strict-path-params?) (or ) (reduce-kv #(if (nil? %3) (reduced true) false) nil path-params))) (throw (ex-info "Attempted to create a URL with `url-for`, but missing required :path-params - :strict-path-params was set to true. Either include all path-params (`nil` is not allowed), or if your URL actually contains ':' in the path, set :strict-path-params to false in the options" {:path-parts path-parts :path-params path-params :options opts :route route}))) path-chunk (str/join \/ (map #(get path-params % %) path-parts)) path (if (and (= \/ (last path)) (not= \/ (last path-chunk))) (str path-chunk "/") path-chunk) request-scheme (:scheme request) request-host (:server-name request) request-port (:server-port request) scheme (or override-scheme scheme request-scheme) host (or override-host host request-host) port (or override-port port request-port) scheme-mismatch (not= scheme request-scheme) host-mismatch (not= host request-host) port-mismatch (not= port request-port)] (str (when (or absolute? scheme-mismatch host-mismatch port-mismatch) (str (when (or absolute? scheme-mismatch) (str (name scheme) \:)) "//" host (when (non-standard-port? scheme port) (str \: port)))) (str (when-not (.startsWith path "/") "/") path) (when-not (str/blank? fragment) (str "#" fragment)) (when (seq query-params) (str \? (str/join \& (map (fn [[k v]] (str (encode-query-part (name k)) \= (encode-query-part (str v)))) query-params))))))) (defn- linker-map "Returns a map like {app-name {route-name route}}. Routes without an application name will have nil as the app-name key." [routes] (reduce (fn [m route] (let [{:keys [app-name route-name]} route] (assoc-in m [app-name route-name] route))) {} routes)) (defn- find-route "Finds and returns a route in the map returned by linker-map, or throws an exception if not found." [m app-name route-name] (or (get-in m [app-name route-name]) (get-in m [nil route-name]) (throw (ex-info "Route not found" {:app-name app-name :route-name route-name})))) (defn url-for-routes "Returns a function that generates URL routes (as strings) from the routes table. The returned function has the signature: [route-name & options] Where 'options' are key-value pairs from: :app-name Application name specified for this route generated link. path parameters will be added to the query string :path-params A map of path parameters only :strict-path-params? A boolean, when true will throw an exception if all path-params aren't fulfilled for the url :query-params A map of query-string parameters only :method-param Keyword naming the query-string parameter in which to place the HTTP method name, if it is neither GET nor POST. If nil, the HTTP method name will not be included in the query string. Default is nil. :context A string, function that returns a string, or symbol that resolves to a function that returns a string that specifies a root context for the URL. Default is nil. :fragment A string for the fragment part of the url. :absolute? Boolean, whether or not to force an absolute URL :scheme Keyword (:http | :https) used to override the scheme portion of the url. :host A string used to override the host portion of the URL. :port An integer used to override the port in the URL. In addition, you may supply default-options to the 'url-for-routes' function, which are merged with the options supplied to the returned function." [routes & default-options] (let [{:as default-opts} default-options m (linker-map routes)] (fn [route-name & options] (let [{:keys [app-name] :as options-map} options default-app-name (:app-name default-opts) route (find-route m (or app-name default-app-name) route-name) opts (combine-opts options-map default-opts route)] (link-str route opts))))) (def ^:private ^:dynamic *url-for* "Dynamic var which holds the 'contextual' linker. The contextual linker is created by the router at routing time. The router will create the linker based on. - The routing table it is routing against. - The incoming request it has just routed." nil) (defn url-for "Invokes currently bound contextual linker to generate url based on - The routing table in use. - The incoming request being routed. where `options` are as described in `url-for-routes`." [route-name & options] (if *url-for* (apply (if (delay? *url-for*) (deref *url-for*) *url-for*) route-name options) (throw (ex-info "*url-for* not bound" {})))) (defprotocol ExpandableRoutes (-expand-routes [expandable-route-spec] "Generate and return the routing table from a given expandable form of routing data.")) (extend-protocol ExpandableRoutes clojure.lang.APersistentVector (-expand-routes [route-spec] (terse/terse-routes route-spec)) clojure.lang.APersistentMap (-expand-routes [route-spec] (-expand-routes [[(terse/map-routes->vec-routes route-spec)]])) clojure.lang.APersistentSet (-expand-routes [route-spec] (table/table-routes route-spec))) (defn expand-routes "Given a value (the route specification), produce and return a sequence of route-maps -- the expanded routes from the specification. Ensure the integrity of the sequence of route maps (even if they've already been checked). - Constraints are correctly ordered (most specific to least specific) - Route names are unique" [route-spec] {:pre [(if-not (satisfies? ExpandableRoutes route-spec) (throw (ex-info "You're trying to use something as a route specification that isn't supported by the protocol; Perhaps you need to extend it?" {:routes route-spec :type (type route-spec)})) true)] :post [(seq? %) (every? (every-pred map? :path :route-name :method) %)]} (definition/ensure-routes-integrity (-expand-routes route-spec))) (defprotocol RouterSpecification (router-spec [specification router-ctor] "Returns an interceptor which attempts to match each route against a :request in context. For the first route that matches, it will: - enqueue the matched route's interceptors - associate the route into the context at :route - associate a map of :path-params into the :request If no route matches, returns context with :route nil.")) (defn- route-context [context router routes] (if-let [route (router/find-route router (:request context))] This is where path - params are added to the request . (let [request-with-path-params (assoc (:request context) :path-params (:path-params route)) linker (delay (url-for-routes routes :request request-with-path-params))] (-> context (assoc :route route :request (assoc request-with-path-params :url-for linker) :url-for linker) (assoc-in [:bindings #'*url-for*] linker) (interceptor.chain/enqueue (:interceptors route)))) (assoc context :route nil))) (extend-protocol RouterSpecification clojure.lang.Sequential (router-spec [seq router-ctor] (let [router (router-ctor seq)] (interceptor/interceptor {:name ::router :enter #(route-context % router seq)}))) clojure.lang.Fn (router-spec [f router-ctor] (interceptor/interceptor {:name ::router :enter (fn [context] (let [routes (f) router (router-ctor routes)] (route-context context router routes)))}))) (def router-implementations {:map-tree map-tree/router :prefix-tree prefix-tree/router :linear-search linear-search/router}) (defn router "Delegating fn for router-specification." ([spec] (router spec :map-tree)) ([spec router-impl-key-or-fn] (assert (or (contains? router-implementations router-impl-key-or-fn) (fn? router-impl-key-or-fn)) (format "No router implementation exists for key %s. Please use one of %s." router-impl-key-or-fn (keys router-implementations))) (let [router-ctor (if (fn? router-impl-key-or-fn) router-impl-key-or-fn (router-impl-key-or-fn router-implementations))] (router-spec spec router-ctor)))) (def query-params "Returns an interceptor which parses query-string parameters from an HTTP request into a map. Keys in the map are query-string parameter names, as keywords, and values are strings. The map is assoc'd into the request at :query-params." (interceptor/interceptor {:name ::query-params :enter (fn [ctx] (try (update-in ctx [:request] parse-query-params) (catch IllegalArgumentException iae (interceptor.chain/terminate (assoc ctx :response {:status 400 :body (str "Bad Request - " (.getMessage iae))})))))})) (def path-params-decoder "An Interceptor which URL-decodes path parameters." (interceptor/interceptor {:name ::path-params-decoder :enter (fn [ctx] (try (update-in ctx [:request] parse-path-params) (catch IllegalArgumentException iae (interceptor.chain/terminate (assoc ctx :response {:status 400 :body (str "Bad Request - " (.getMessage iae))})))))})) (defn method-param "Returns an interceptor that smuggles HTTP verbs through a value in the request. Must come *after* the interceptor that populates that value (e.g. query-params or body-params). query-param-or-param-path may be one of two things: - The parameter inside :query-params where the verb will reside. - A complete path to a value elsewhere in the request, such as [:query-params :_method] or [:body-params \"_method\"] The path [:query-params :_method] is used by default." ([] (method-param [:query-params :_method])) ([query-param-or-param-path] (let [param-path (if (vector? query-param-or-param-path) query-param-or-param-path [:query-params query-param-or-param-path])] (interceptor/interceptor {:name ::method-param :enter (fn [ctx] (update-in ctx [:request] #(replace-method param-path %)))})))) (defn form-action-for-routes "Like 'url-for-routes' but the returned function returns a map with the keys string. Also, the :method-param is :_method by default, so HTTP verbs other than GET and POST will be converted to POST with the actual verb in the query string." [routes & default-options] (let [{:as default-opts} default-options m (linker-map routes)] (fn [route-name & options] (let [{:keys [app-name] :as options-map} options {:keys [method] :as route} (find-route m app-name route-name) opts (combine-opts options-map (merge {:method-param :_method} default-opts) route)] {:action (link-str route opts) :method (name (if (and (:method-param opts) (not (= :get method))) :post method))})))) (defn print-routes "Prints route table `routes` in easier to read format." [routes] (doseq [r (map (fn [{:keys [method path route-name]}] [method path route-name]) routes)] (println r))) (defn try-routing-for [spec router-type query-string verb] (let [router (router spec router-type) context {:request {:path-info query-string :request-method verb}} context ((:enter router) context)] (:route context)))
d2358156f45c368f85fe47d74a92aef8c02f30f84d404e888431c134963c290b
MyPost/cassius
core.clj
(ns cassius.core (:require [cassius.common :refer :all] [cassius.protocols] [cassius.api.connection] [cassius.api.pool] [cassius.component] [hara.namespace.import :refer [import]] [clojure.pprint :as pp]) (:refer-clojure :exclude [import])) (import cassius.protocols [create connect disconnect put-in peek-in keys-in drop-in set-in select-in mutate-in init-schema schema stream-in to-bbuff] cassius.component [database]) (defn conn? [conn] (instance? cassius.protocols.IMap conn)) (defn diff-inserts ([m1 m2] (diff-inserts m1 m2 [] (atom {}))) ([m1 m2 pv summary] (let [ks (keys m1)] (doseq [k ks] (let [v1 (get m1 k) v2 (get m2 k)] (cond (and (hash-map? v1) (hash-map? v2)) (diff-inserts v1 v2 (conj pv k) summary) (nil? v2) (swap! summary conj [(conj pv k) v1])))) @summary))) (defn diff-changes ([m1 m2] (diff-changes m1 m2 [] (atom {}))) ([m1 m2 pv summary] (let [ks (keys m1)] (doseq [k ks] (let [v1 (get m1 k) v2 (get m2 k)] (cond (and (hash-map? v1) (hash-map? v2)) (diff-changes v1 v2 (conj pv k) summary) (nil? v2) nil (not= v1 v2) (swap! summary conj [(conj pv k) [v1 v2]])))) @summary))) (defn diff [old new] (let [v+ (diff-inserts new old) v- (diff-inserts old new) v* (diff-changes old new) m (assoc-full {} :+ v+ :- v- :* v*)] (if-not (empty? m) m))) (defn patch [conn changes] (if-let [adds (:+ changes)] (doseq [e adds] (apply put-in conn e))) (if-let [subs (:- changes)] (doseq [e subs] (drop-in conn (first e)))) (if-let [reps (:* changes)] (doseq [e reps] (set-in conn (first e) (first (second 2))))) conn) (defn rollback [conn changes] (if-let [adds (:- changes)] (doseq [e adds] (apply put-in conn e))) (if-let [subs (:+ changes)] (doseq [e subs] (drop-in conn (first e)))) (if-let [reps (:* changes)] (doseq [e reps] (set-in conn (first e) (first e)))) conn) (defn restore ([conn source] (cond (atom? source) (apply restore @source) (conn? source) (let [sch (schema source) data (peek-in source)] (restore conn sch data)) (and (vector? source) (= [String String] (map type source))) (let [sch (read-string (slurp (first source))) data (read-string (slurp (second source)))] (restore conn sch data)))) ([conn schema data] (drop-in conn) (init-schema schema) (set-in conn data) conn)) (defn pprint-str [m] (with-out-str (pp/pprint m))) (defn backup [conn source] (let [sch (schema conn) data (peek-in conn)] (cond (atom? source) (reset! source [sch data]) (and (vector? source) (= [String String] (map type source))) (do (spit (first source) (pprint-str sch)) (spit (second source) (pprint-str data))) (conn? source) (restore source conn))) conn)
null
https://raw.githubusercontent.com/MyPost/cassius/7b5f550fa8e8f825d4ecd7ba6a0d34c5ff606a7c/src/cassius/core.clj
clojure
(ns cassius.core (:require [cassius.common :refer :all] [cassius.protocols] [cassius.api.connection] [cassius.api.pool] [cassius.component] [hara.namespace.import :refer [import]] [clojure.pprint :as pp]) (:refer-clojure :exclude [import])) (import cassius.protocols [create connect disconnect put-in peek-in keys-in drop-in set-in select-in mutate-in init-schema schema stream-in to-bbuff] cassius.component [database]) (defn conn? [conn] (instance? cassius.protocols.IMap conn)) (defn diff-inserts ([m1 m2] (diff-inserts m1 m2 [] (atom {}))) ([m1 m2 pv summary] (let [ks (keys m1)] (doseq [k ks] (let [v1 (get m1 k) v2 (get m2 k)] (cond (and (hash-map? v1) (hash-map? v2)) (diff-inserts v1 v2 (conj pv k) summary) (nil? v2) (swap! summary conj [(conj pv k) v1])))) @summary))) (defn diff-changes ([m1 m2] (diff-changes m1 m2 [] (atom {}))) ([m1 m2 pv summary] (let [ks (keys m1)] (doseq [k ks] (let [v1 (get m1 k) v2 (get m2 k)] (cond (and (hash-map? v1) (hash-map? v2)) (diff-changes v1 v2 (conj pv k) summary) (nil? v2) nil (not= v1 v2) (swap! summary conj [(conj pv k) [v1 v2]])))) @summary))) (defn diff [old new] (let [v+ (diff-inserts new old) v- (diff-inserts old new) v* (diff-changes old new) m (assoc-full {} :+ v+ :- v- :* v*)] (if-not (empty? m) m))) (defn patch [conn changes] (if-let [adds (:+ changes)] (doseq [e adds] (apply put-in conn e))) (if-let [subs (:- changes)] (doseq [e subs] (drop-in conn (first e)))) (if-let [reps (:* changes)] (doseq [e reps] (set-in conn (first e) (first (second 2))))) conn) (defn rollback [conn changes] (if-let [adds (:- changes)] (doseq [e adds] (apply put-in conn e))) (if-let [subs (:+ changes)] (doseq [e subs] (drop-in conn (first e)))) (if-let [reps (:* changes)] (doseq [e reps] (set-in conn (first e) (first e)))) conn) (defn restore ([conn source] (cond (atom? source) (apply restore @source) (conn? source) (let [sch (schema source) data (peek-in source)] (restore conn sch data)) (and (vector? source) (= [String String] (map type source))) (let [sch (read-string (slurp (first source))) data (read-string (slurp (second source)))] (restore conn sch data)))) ([conn schema data] (drop-in conn) (init-schema schema) (set-in conn data) conn)) (defn pprint-str [m] (with-out-str (pp/pprint m))) (defn backup [conn source] (let [sch (schema conn) data (peek-in conn)] (cond (atom? source) (reset! source [sch data]) (and (vector? source) (= [String String] (map type source))) (do (spit (first source) (pprint-str sch)) (spit (second source) (pprint-str data))) (conn? source) (restore source conn))) conn)
a765c9bc1aaafbd6dcbb38133c3db6ddcbe1b451233249f1af6451daa577b150
gilith/hol-light
group-abelian-monoid.ml
(*BEGIN-PARAMETRIC*) let group_add_comm' = new_axiom `!x y z. group_add x (group_add y z) = group_add y (group_add x z)`;; (*END-PARAMETRIC*)
null
https://raw.githubusercontent.com/gilith/hol-light/f3f131963f2298b4d65ee5fead6e986a4a14237a/opentheory/theories/group/group-abelian-monoid.ml
ocaml
BEGIN-PARAMETRIC END-PARAMETRIC
let group_add_comm' = new_axiom `!x y z. group_add x (group_add y z) = group_add y (group_add x z)`;;
59dd0aa104c85e2ebb7b2b76da4b27f4841b6c2b780786721a94f9a1ebd92a30
restyled-io/restyled.io
LogLines.hs
module Restyled.Handlers.Repos.Jobs.LogLines ( getRepoJobLogLinesR ) where import Restyled.Prelude import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Restyled.DB import Restyled.Foundation import Restyled.JobOutput import Restyled.Models import Restyled.WebSockets import qualified Restyled.Widgets.Job as Widgets import Restyled.Yesod import Text.Blaze.Html.Renderer.Text (renderHtml) getRepoJobLogLinesR :: OwnerName -> RepoName -> JobId -> Handler Text getRepoJobLogLinesR _owner _name jobId = do job <- runDB $ getEntity404 jobId Use 28s to be just under the Heroku 30s timeout let keepAlivePeriod :: Int keepAlivePeriod = 28 keepAliveMsg <- renderKeepAliveMessage webSockets keepAlivePeriod keepAliveMsg $ \send -> do conn <- ask lift $ followJobOutput job $ \jobLogLines -> do htmls <- mconcat <$> traverse renderJobLogLine (excludePatchLines jobLogLines) runReaderT (void $ send htmls) conn If not accessed via WebSockets , respond with plain text Job log jobLogLines <- fetchJobOutput job pure $ T.unlines $ map jobLogLineContent $ excludePatchLines jobLogLines renderJobLogLine :: JobLogLine -> Handler LT.Text renderJobLogLine ln = do pc <- widgetToPageContent $ Widgets.jobLogLine ln renderHtml <$> withUrlRenderer (pageBody pc) renderKeepAliveMessage :: Handler LT.Text renderKeepAliveMessage = do now <- getCurrentTime renderJobLogLine $ jobLogLine now "No output in the last 30 seconds. Continuing to wait..." excludePatchLines :: [JobLogLine] -> [JobLogLine] excludePatchLines = filter (not . jobLogLineIsPatch)
null
https://raw.githubusercontent.com/restyled-io/restyled.io/f9f34b6ad572d2c9ee5689367329916e65596581/src/Restyled/Handlers/Repos/Jobs/LogLines.hs
haskell
module Restyled.Handlers.Repos.Jobs.LogLines ( getRepoJobLogLinesR ) where import Restyled.Prelude import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Restyled.DB import Restyled.Foundation import Restyled.JobOutput import Restyled.Models import Restyled.WebSockets import qualified Restyled.Widgets.Job as Widgets import Restyled.Yesod import Text.Blaze.Html.Renderer.Text (renderHtml) getRepoJobLogLinesR :: OwnerName -> RepoName -> JobId -> Handler Text getRepoJobLogLinesR _owner _name jobId = do job <- runDB $ getEntity404 jobId Use 28s to be just under the Heroku 30s timeout let keepAlivePeriod :: Int keepAlivePeriod = 28 keepAliveMsg <- renderKeepAliveMessage webSockets keepAlivePeriod keepAliveMsg $ \send -> do conn <- ask lift $ followJobOutput job $ \jobLogLines -> do htmls <- mconcat <$> traverse renderJobLogLine (excludePatchLines jobLogLines) runReaderT (void $ send htmls) conn If not accessed via WebSockets , respond with plain text Job log jobLogLines <- fetchJobOutput job pure $ T.unlines $ map jobLogLineContent $ excludePatchLines jobLogLines renderJobLogLine :: JobLogLine -> Handler LT.Text renderJobLogLine ln = do pc <- widgetToPageContent $ Widgets.jobLogLine ln renderHtml <$> withUrlRenderer (pageBody pc) renderKeepAliveMessage :: Handler LT.Text renderKeepAliveMessage = do now <- getCurrentTime renderJobLogLine $ jobLogLine now "No output in the last 30 seconds. Continuing to wait..." excludePatchLines :: [JobLogLine] -> [JobLogLine] excludePatchLines = filter (not . jobLogLineIsPatch)
256305084ecd3a77e59c1f68126081be818e86193a8b1fca15db3292f1d17e3d
mbj/stratosphere
DBParameterGroup.hs
module Stratosphere.Neptune.DBParameterGroup ( DBParameterGroup(..), mkDBParameterGroup ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Tag import Stratosphere.Value data DBParameterGroup = DBParameterGroup {description :: (Value Prelude.Text), family :: (Value Prelude.Text), name :: (Prelude.Maybe (Value Prelude.Text)), parameters :: JSON.Object, tags :: (Prelude.Maybe [Tag])} mkDBParameterGroup :: Value Prelude.Text -> Value Prelude.Text -> JSON.Object -> DBParameterGroup mkDBParameterGroup description family parameters = DBParameterGroup {description = description, family = family, parameters = parameters, name = Prelude.Nothing, tags = Prelude.Nothing} instance ToResourceProperties DBParameterGroup where toResourceProperties DBParameterGroup {..} = ResourceProperties {awsType = "AWS::Neptune::DBParameterGroup", supportsTags = Prelude.True, properties = Prelude.fromList ((Prelude.<>) ["Description" JSON..= description, "Family" JSON..= family, "Parameters" JSON..= parameters] (Prelude.catMaybes [(JSON..=) "Name" Prelude.<$> name, (JSON..=) "Tags" Prelude.<$> tags]))} instance JSON.ToJSON DBParameterGroup where toJSON DBParameterGroup {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["Description" JSON..= description, "Family" JSON..= family, "Parameters" JSON..= parameters] (Prelude.catMaybes [(JSON..=) "Name" Prelude.<$> name, (JSON..=) "Tags" Prelude.<$> tags]))) instance Property "Description" DBParameterGroup where type PropertyType "Description" DBParameterGroup = Value Prelude.Text set newValue DBParameterGroup {..} = DBParameterGroup {description = newValue, ..} instance Property "Family" DBParameterGroup where type PropertyType "Family" DBParameterGroup = Value Prelude.Text set newValue DBParameterGroup {..} = DBParameterGroup {family = newValue, ..} instance Property "Name" DBParameterGroup where type PropertyType "Name" DBParameterGroup = Value Prelude.Text set newValue DBParameterGroup {..} = DBParameterGroup {name = Prelude.pure newValue, ..} instance Property "Parameters" DBParameterGroup where type PropertyType "Parameters" DBParameterGroup = JSON.Object set newValue DBParameterGroup {..} = DBParameterGroup {parameters = newValue, ..} instance Property "Tags" DBParameterGroup where type PropertyType "Tags" DBParameterGroup = [Tag] set newValue DBParameterGroup {..} = DBParameterGroup {tags = Prelude.pure newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/neptune/gen/Stratosphere/Neptune/DBParameterGroup.hs
haskell
module Stratosphere.Neptune.DBParameterGroup ( DBParameterGroup(..), mkDBParameterGroup ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Tag import Stratosphere.Value data DBParameterGroup = DBParameterGroup {description :: (Value Prelude.Text), family :: (Value Prelude.Text), name :: (Prelude.Maybe (Value Prelude.Text)), parameters :: JSON.Object, tags :: (Prelude.Maybe [Tag])} mkDBParameterGroup :: Value Prelude.Text -> Value Prelude.Text -> JSON.Object -> DBParameterGroup mkDBParameterGroup description family parameters = DBParameterGroup {description = description, family = family, parameters = parameters, name = Prelude.Nothing, tags = Prelude.Nothing} instance ToResourceProperties DBParameterGroup where toResourceProperties DBParameterGroup {..} = ResourceProperties {awsType = "AWS::Neptune::DBParameterGroup", supportsTags = Prelude.True, properties = Prelude.fromList ((Prelude.<>) ["Description" JSON..= description, "Family" JSON..= family, "Parameters" JSON..= parameters] (Prelude.catMaybes [(JSON..=) "Name" Prelude.<$> name, (JSON..=) "Tags" Prelude.<$> tags]))} instance JSON.ToJSON DBParameterGroup where toJSON DBParameterGroup {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["Description" JSON..= description, "Family" JSON..= family, "Parameters" JSON..= parameters] (Prelude.catMaybes [(JSON..=) "Name" Prelude.<$> name, (JSON..=) "Tags" Prelude.<$> tags]))) instance Property "Description" DBParameterGroup where type PropertyType "Description" DBParameterGroup = Value Prelude.Text set newValue DBParameterGroup {..} = DBParameterGroup {description = newValue, ..} instance Property "Family" DBParameterGroup where type PropertyType "Family" DBParameterGroup = Value Prelude.Text set newValue DBParameterGroup {..} = DBParameterGroup {family = newValue, ..} instance Property "Name" DBParameterGroup where type PropertyType "Name" DBParameterGroup = Value Prelude.Text set newValue DBParameterGroup {..} = DBParameterGroup {name = Prelude.pure newValue, ..} instance Property "Parameters" DBParameterGroup where type PropertyType "Parameters" DBParameterGroup = JSON.Object set newValue DBParameterGroup {..} = DBParameterGroup {parameters = newValue, ..} instance Property "Tags" DBParameterGroup where type PropertyType "Tags" DBParameterGroup = [Tag] set newValue DBParameterGroup {..} = DBParameterGroup {tags = Prelude.pure newValue, ..}
454f0cfe83df88576b904fe4cf99045685e5236bed72e09031ec35dc620f9e6a
6502/JSLisp
forms-server.lisp
(import * from gui) (import * from rpc-server) (import examples/forms) (defun main () (start-server "127.0.0.1" 1337)) (main)
null
https://raw.githubusercontent.com/6502/JSLisp/9a4aa1a9116f0cfc598ec9f3f30b59d99810a728/examples/forms-server.lisp
lisp
(import * from gui) (import * from rpc-server) (import examples/forms) (defun main () (start-server "127.0.0.1" 1337)) (main)
60bc8ac049b60a770b2e979042db32389350a6bb4973e3c52940dade973a2b88
privet-kitty/cl-competitive
xorshift.lisp
(defpackage :cp/xorshift (:use :cl) (:export #:xorshift #:randi #:randprob #:randprob1 #:xorshift-seed! #:randf) (:documentation "Provides a random number generator that focuses only on efficiency.")) (in-package :cp/xorshift) (eval-when (:compile-toplevel :load-toplevel :execute) (assert (= 64 sb-vm:n-word-bits))) (declaim ((unsigned-byte 64) *state*)) (sb-ext:defglobal *state* (ash 88172645463325252 -1)) ;; TODO: investigate the safety of this weird hack (declaim (inline xorshift)) (defun xorshift (arg) "Returns an integer within [0, ARG). Note that this RNG is not strictly uniform due to modulo bias." (declare (optimize (speed 3)) ((integer 1 #.(ash 1 64)) arg)) (locally (declare (optimize (safety 0))) (let* ((x (sb-kernel:get-lisp-obj-address *state*))) (declare ((unsigned-byte 64) x)) (setq x (ldb (byte 64 0) (logxor x (ash x 7)))) (setq x (ldb (byte 64 0) (logxor x (ash x -9)))) (setq *state* (sb-kernel:%make-lisp-obj x)) (mod x arg)))) (defconstant +skip-count+ 50) ; FIXME: this is not based on any evidence (defun xorshift-seed! (seed &optional (skip +skip-count+)) (declare (optimize (speed 3)) ((integer 1 #.most-positive-fixnum) seed) ; avoid trouble ((integer 0 #.most-positive-fixnum) skip)) (setq *state* seed) (dotimes (_ skip) (xorshift 1))) (declaim (inline randi)) (defun randi (l r) "Returns an integer within [L, R)." (declare (optimize (speed 3)) (fixnum l r)) (+ l (xorshift (- r l)))) (defconstant +epsilon+ (float (/ (ash 1 53)) 1d0)) (declaim (inline randprob) (ftype (function * (values (double-float 0d0 (1d0)) &optional)) randprob)) (defun randprob () "Returns a double-float within [0, 1)." (* +epsilon+ (xorshift #.(ash 1 53)))) (declaim (inline randprob1)) (defun randprob1 () "Returns a double-float within [0, 1]." (* double-float-epsilon (xorshift #.(ash 1 53)))) (declaim (inline randf)) (defun randf (l r) (+ l (* (- r l) (randprob))))
null
https://raw.githubusercontent.com/privet-kitty/cl-competitive/4691a18ccfa627e6795cc35844b82ca28bb416b3/module/xorshift.lisp
lisp
TODO: investigate the safety of this weird hack FIXME: this is not based on any evidence avoid trouble
(defpackage :cp/xorshift (:use :cl) (:export #:xorshift #:randi #:randprob #:randprob1 #:xorshift-seed! #:randf) (:documentation "Provides a random number generator that focuses only on efficiency.")) (in-package :cp/xorshift) (eval-when (:compile-toplevel :load-toplevel :execute) (assert (= 64 sb-vm:n-word-bits))) (declaim ((unsigned-byte 64) *state*)) (sb-ext:defglobal *state* (ash 88172645463325252 -1)) (declaim (inline xorshift)) (defun xorshift (arg) "Returns an integer within [0, ARG). Note that this RNG is not strictly uniform due to modulo bias." (declare (optimize (speed 3)) ((integer 1 #.(ash 1 64)) arg)) (locally (declare (optimize (safety 0))) (let* ((x (sb-kernel:get-lisp-obj-address *state*))) (declare ((unsigned-byte 64) x)) (setq x (ldb (byte 64 0) (logxor x (ash x 7)))) (setq x (ldb (byte 64 0) (logxor x (ash x -9)))) (setq *state* (sb-kernel:%make-lisp-obj x)) (mod x arg)))) (defun xorshift-seed! (seed &optional (skip +skip-count+)) (declare (optimize (speed 3)) ((integer 0 #.most-positive-fixnum) skip)) (setq *state* seed) (dotimes (_ skip) (xorshift 1))) (declaim (inline randi)) (defun randi (l r) "Returns an integer within [L, R)." (declare (optimize (speed 3)) (fixnum l r)) (+ l (xorshift (- r l)))) (defconstant +epsilon+ (float (/ (ash 1 53)) 1d0)) (declaim (inline randprob) (ftype (function * (values (double-float 0d0 (1d0)) &optional)) randprob)) (defun randprob () "Returns a double-float within [0, 1)." (* +epsilon+ (xorshift #.(ash 1 53)))) (declaim (inline randprob1)) (defun randprob1 () "Returns a double-float within [0, 1]." (* double-float-epsilon (xorshift #.(ash 1 53)))) (declaim (inline randf)) (defun randf (l r) (+ l (* (- r l) (randprob))))
5ed374dbae8ce9e13241561c5cf1c2fdb0167d9a398bafc84333b855ad50d845
jship/monad-logger-aeson
MetadataNoThreadContextNo.hs
# LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # module TestCase.LogDebugNS.MetadataNoThreadContextNo ( testCase ) where import Control.Monad.Logger.Aeson (Loc(..), LogLevel(..), LoggedMessage(..), logDebugNS) import Data.Aeson.QQ.Simple (aesonQQ) import Data.Time (UTCTime(..)) import TestCase (TestCase(..)) import qualified Control.Monad.Logger.Aeson.Internal as Internal import qualified Data.Time as Time testCase :: FilePath -> TestCase testCase logFilePath = TestCase { actionUnderTest = do logDebugNS "tests" "No metadata" , logFilePath , expectedValue = [aesonQQ| { "time": "2022-05-07T20:03:54.0000000Z", "level": "debug", "location": { "package": "main", "module": "TestCase.LogDebugNS.MetadataNoThreadContextNo", "file": "test-suite/TestCase/LogDebugNS/MetadataNoThreadContextNo.hs", "line": 19, "char": 9 }, "source": "tests", "message": { "text": "No metadata" } } |] , expectedPatch = [aesonQQ| [ { "op": "replace", "path": "/time", "value": "2022-05-07T20:03:54.0000000Z" } ] |] , expectedLoggedMessage = LoggedMessage { loggedMessageTimestamp = UTCTime { utctDay = Time.fromGregorian 2022 05 07 , utctDayTime = 72234 } , loggedMessageLevel = LevelDebug , loggedMessageLoc = Just Loc { loc_package = "main" , loc_module = "TestCase.LogDebugNS.MetadataNoThreadContextNo" , loc_filename = "test-suite/TestCase/LogDebugNS/MetadataNoThreadContextNo.hs" , loc_start = (19, 9) , loc_end = (0, 0) } , loggedMessageLogSource = Just "tests" , loggedMessageThreadContext = Internal.emptyKeyMap , loggedMessageText = "No metadata" , loggedMessageMeta = Internal.emptyKeyMap } }
null
https://raw.githubusercontent.com/jship/monad-logger-aeson/218dd4a1fd9fd7f86514322dd529444a55001443/monad-logger-aeson/test-suite/TestCase/LogDebugNS/MetadataNoThreadContextNo.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE NamedFieldPuns # # LANGUAGE QuasiQuotes # module TestCase.LogDebugNS.MetadataNoThreadContextNo ( testCase ) where import Control.Monad.Logger.Aeson (Loc(..), LogLevel(..), LoggedMessage(..), logDebugNS) import Data.Aeson.QQ.Simple (aesonQQ) import Data.Time (UTCTime(..)) import TestCase (TestCase(..)) import qualified Control.Monad.Logger.Aeson.Internal as Internal import qualified Data.Time as Time testCase :: FilePath -> TestCase testCase logFilePath = TestCase { actionUnderTest = do logDebugNS "tests" "No metadata" , logFilePath , expectedValue = [aesonQQ| { "time": "2022-05-07T20:03:54.0000000Z", "level": "debug", "location": { "package": "main", "module": "TestCase.LogDebugNS.MetadataNoThreadContextNo", "file": "test-suite/TestCase/LogDebugNS/MetadataNoThreadContextNo.hs", "line": 19, "char": 9 }, "source": "tests", "message": { "text": "No metadata" } } |] , expectedPatch = [aesonQQ| [ { "op": "replace", "path": "/time", "value": "2022-05-07T20:03:54.0000000Z" } ] |] , expectedLoggedMessage = LoggedMessage { loggedMessageTimestamp = UTCTime { utctDay = Time.fromGregorian 2022 05 07 , utctDayTime = 72234 } , loggedMessageLevel = LevelDebug , loggedMessageLoc = Just Loc { loc_package = "main" , loc_module = "TestCase.LogDebugNS.MetadataNoThreadContextNo" , loc_filename = "test-suite/TestCase/LogDebugNS/MetadataNoThreadContextNo.hs" , loc_start = (19, 9) , loc_end = (0, 0) } , loggedMessageLogSource = Just "tests" , loggedMessageThreadContext = Internal.emptyKeyMap , loggedMessageText = "No metadata" , loggedMessageMeta = Internal.emptyKeyMap } }
f81329b1aec14904a01faca655f7b4e24b0919af607f5629552b9263337f466a
cl-rabbit/cl-bunny
receive-logs-direct.lisp
(ql:quickload :cl-bunny.examples) (in-package :cl-bunny.examples) (if-let ((args (rest sb-ext:*posix-argv*))) (with-connection () (with-channel () (let ((q (queue.declare :auto-delete t)) (x (exchange.direct "direct_logs"))) (loop for severity in args do (queue.bind q x :routing-key severity)) (format t " [*] Waiting for logs. To exit type (exit)~%") (subscribe q (lambda (message) (let ((body (message-body-string message))) (format t " [x] #~a~%" body))) :type :sync) (consume)))) TODO : wtf is # { $ 0 } ?
null
https://raw.githubusercontent.com/cl-rabbit/cl-bunny/6da7fe161efc8d6bb0b8b09ac8efad03553d765c/examples/tutorials/receive-logs-direct.lisp
lisp
(ql:quickload :cl-bunny.examples) (in-package :cl-bunny.examples) (if-let ((args (rest sb-ext:*posix-argv*))) (with-connection () (with-channel () (let ((q (queue.declare :auto-delete t)) (x (exchange.direct "direct_logs"))) (loop for severity in args do (queue.bind q x :routing-key severity)) (format t " [*] Waiting for logs. To exit type (exit)~%") (subscribe q (lambda (message) (let ((body (message-body-string message))) (format t " [x] #~a~%" body))) :type :sync) (consume)))) TODO : wtf is # { $ 0 } ?
ab286d6c4481197e213f307b2e16a41a8d5670fa1db6f7bc9b394a1fc3d52ee4
coq-tactician/coq-tactician
tactician_util.ml
let mapi f s : 'a IStream.t = let rec mapi_node f i = function | IStream.Nil -> IStream.Nil | IStream.Cons (x, s) -> Cons (f i x, mapi f (i + 1) s) and mapi f i s = IStream.thunk (fun () -> mapi_node f i (IStream.peek s)) in mapi f 0 s let rec to_list n s = match n, IStream.peek s with | _, Nil | 0, _ -> [] | n, Cons (x, s) -> x :: (to_list (n - 1) s) exception PredictionsEnd exception DepthEnd let record_map (f : Proofview.Goal.t -> 'a) (gls : Proofview.Goal.t Proofview.tactic list) : 'a list Proofview.tactic = let rec aux gls acc = let open Proofview.Notations in match gls with | [] -> Proofview.tclUNIT (acc) | gl::gls' -> gl >>= fun gl' -> aux gls' (f gl' :: acc) in aux gls [] let proof_state_to_string hyps goal env evar_map = let constr_str t = Sexpr.format_oneline (Printer.pr_econstr_env env evar_map t) in let goal = constr_str goal in let hyps = List.map (function | Context.Named.Declaration.LocalAssum (id, typ) -> let id_str = Names.Id.print id.binder_name in let typ_str = constr_str typ in Pp.(id_str ++ str " : " ++ typ_str) | Context.Named.Declaration.LocalDef (id, term, typ) -> let id_str = Names.Id.print id.binder_name in let term_str = Pp.(str " := " ++ constr_str term) in let typ_str = constr_str typ in Pp.(id_str ++ term_str ++ str " : " ++ typ_str) ) hyps in Pp.(prlist_with_sep (fun () -> str ", ") (fun x -> x) hyps ++ str " |- " ++ goal) let pr_proof_tac () = let open Proofview in let open Notations in Goal.goals >>= record_map (fun x -> x) >>= fun gls -> let gls_string = List.map (fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let hyps = Goal.hyps gl in let goal = Goal.concl gl in proof_state_to_string hyps goal env sigma) gls in List.iter Feedback.msg_notice gls_string; tclUNIT () let safe_index0 f x l = try Some (CList.index0 f x l) with Not_found -> None let constr_size c = let rec aux c = Constr.fold (fun i c -> i + aux c + 1) 1 c in aux c let econstr_size evd c = constr_size @@ EConstr.to_constr evd c let goal_size (gl : Proofview.Goal.t) = let open Proofview in let sigma = Proofview.Goal.sigma gl in let hyps = Goal.hyps gl in let goal = Goal.concl gl in let hyps = Context.Named.fold_inside (fun i d -> Context.Named.Declaration.fold_constr (fun c i -> i + econstr_size sigma c) d i ) ~init:0 hyps in let goal = econstr_size sigma goal in hyps + goal (* Find the current file name *) open Loadpath let select_v_file ~warn loadpath base = let find ext = let loadpath = List.map fst loadpath in try let name = Names.Id.to_string base ^ ext in let lpath, file = System.where_in_path ~warn loadpath name in Some (lpath, file) with Not_found -> None in match find ".v" with | None -> Error LibNotFound | Some res -> Ok res let load_path_to_physical t = let printed = pp t in let path = match Pp.repr printed with | Pp.Ppcmd_box (_, k) -> (match Pp.repr k with | Pp.Ppcmd_glue ks -> (match Pp.repr (List.nth ks 2) with | Pp.Ppcmd_string s -> s | _ -> assert false) | _ -> assert false) | _ -> assert false in path let filter_path f = let rec aux = function | [] -> [] | p :: l -> if f (logical p) then (load_path_to_physical p, logical p) :: aux l else aux l in aux (get_load_paths ()) let locate_absolute_library dir : CUnix.physical_path locate_result = (* Search in loadpath *) let pref, base = Libnames.split_dirpath dir in let loadpath = filter_path (fun dir -> Names.DirPath.equal dir pref) in match loadpath with | [] -> Error LibUnmappedDir | _ -> match select_v_file ~warn:false loadpath base with | Ok (_, file) -> Ok file | Error fail -> Error fail let try_locate_absolute_library dir = match locate_absolute_library dir with | Ok res -> Some res | Error LibUnmappedDir -> None | Error LibNotFound -> None let base_filename = let dirpath = Global.current_dirpath () in Option.map (fun f -> Filename.remove_extension f) (try_locate_absolute_library dirpath) let with_flag flg f = let original = CWarnings.get_flags () in let added = original ^ "," ^ flg in Fun.protect ~finally:(fun () -> CWarnings.set_flags original) (fun () -> CWarnings.set_flags added; f ()) let map_named f = function | Context.Named.Declaration.LocalAssum (id, ty) -> let ty' = f ty in Context.Named.Declaration.LocalAssum (id, ty') | Context.Named.Declaration.LocalDef (id, v, ty) -> let v' = f v in let ty' = f ty in Context.Named.Declaration.LocalDef (id, v', ty')
null
https://raw.githubusercontent.com/coq-tactician/coq-tactician/db3de79f46cb53d3613290d5fa7426b0e85e1362/src/tactician_util.ml
ocaml
Find the current file name Search in loadpath
let mapi f s : 'a IStream.t = let rec mapi_node f i = function | IStream.Nil -> IStream.Nil | IStream.Cons (x, s) -> Cons (f i x, mapi f (i + 1) s) and mapi f i s = IStream.thunk (fun () -> mapi_node f i (IStream.peek s)) in mapi f 0 s let rec to_list n s = match n, IStream.peek s with | _, Nil | 0, _ -> [] | n, Cons (x, s) -> x :: (to_list (n - 1) s) exception PredictionsEnd exception DepthEnd let record_map (f : Proofview.Goal.t -> 'a) (gls : Proofview.Goal.t Proofview.tactic list) : 'a list Proofview.tactic = let rec aux gls acc = let open Proofview.Notations in match gls with | [] -> Proofview.tclUNIT (acc) | gl::gls' -> gl >>= fun gl' -> aux gls' (f gl' :: acc) in aux gls [] let proof_state_to_string hyps goal env evar_map = let constr_str t = Sexpr.format_oneline (Printer.pr_econstr_env env evar_map t) in let goal = constr_str goal in let hyps = List.map (function | Context.Named.Declaration.LocalAssum (id, typ) -> let id_str = Names.Id.print id.binder_name in let typ_str = constr_str typ in Pp.(id_str ++ str " : " ++ typ_str) | Context.Named.Declaration.LocalDef (id, term, typ) -> let id_str = Names.Id.print id.binder_name in let term_str = Pp.(str " := " ++ constr_str term) in let typ_str = constr_str typ in Pp.(id_str ++ term_str ++ str " : " ++ typ_str) ) hyps in Pp.(prlist_with_sep (fun () -> str ", ") (fun x -> x) hyps ++ str " |- " ++ goal) let pr_proof_tac () = let open Proofview in let open Notations in Goal.goals >>= record_map (fun x -> x) >>= fun gls -> let gls_string = List.map (fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let hyps = Goal.hyps gl in let goal = Goal.concl gl in proof_state_to_string hyps goal env sigma) gls in List.iter Feedback.msg_notice gls_string; tclUNIT () let safe_index0 f x l = try Some (CList.index0 f x l) with Not_found -> None let constr_size c = let rec aux c = Constr.fold (fun i c -> i + aux c + 1) 1 c in aux c let econstr_size evd c = constr_size @@ EConstr.to_constr evd c let goal_size (gl : Proofview.Goal.t) = let open Proofview in let sigma = Proofview.Goal.sigma gl in let hyps = Goal.hyps gl in let goal = Goal.concl gl in let hyps = Context.Named.fold_inside (fun i d -> Context.Named.Declaration.fold_constr (fun c i -> i + econstr_size sigma c) d i ) ~init:0 hyps in let goal = econstr_size sigma goal in hyps + goal open Loadpath let select_v_file ~warn loadpath base = let find ext = let loadpath = List.map fst loadpath in try let name = Names.Id.to_string base ^ ext in let lpath, file = System.where_in_path ~warn loadpath name in Some (lpath, file) with Not_found -> None in match find ".v" with | None -> Error LibNotFound | Some res -> Ok res let load_path_to_physical t = let printed = pp t in let path = match Pp.repr printed with | Pp.Ppcmd_box (_, k) -> (match Pp.repr k with | Pp.Ppcmd_glue ks -> (match Pp.repr (List.nth ks 2) with | Pp.Ppcmd_string s -> s | _ -> assert false) | _ -> assert false) | _ -> assert false in path let filter_path f = let rec aux = function | [] -> [] | p :: l -> if f (logical p) then (load_path_to_physical p, logical p) :: aux l else aux l in aux (get_load_paths ()) let locate_absolute_library dir : CUnix.physical_path locate_result = let pref, base = Libnames.split_dirpath dir in let loadpath = filter_path (fun dir -> Names.DirPath.equal dir pref) in match loadpath with | [] -> Error LibUnmappedDir | _ -> match select_v_file ~warn:false loadpath base with | Ok (_, file) -> Ok file | Error fail -> Error fail let try_locate_absolute_library dir = match locate_absolute_library dir with | Ok res -> Some res | Error LibUnmappedDir -> None | Error LibNotFound -> None let base_filename = let dirpath = Global.current_dirpath () in Option.map (fun f -> Filename.remove_extension f) (try_locate_absolute_library dirpath) let with_flag flg f = let original = CWarnings.get_flags () in let added = original ^ "," ^ flg in Fun.protect ~finally:(fun () -> CWarnings.set_flags original) (fun () -> CWarnings.set_flags added; f ()) let map_named f = function | Context.Named.Declaration.LocalAssum (id, ty) -> let ty' = f ty in Context.Named.Declaration.LocalAssum (id, ty') | Context.Named.Declaration.LocalDef (id, v, ty) -> let v' = f v in let ty' = f ty in Context.Named.Declaration.LocalDef (id, v', ty')
12cebaed4867e4a1f676fd6d93c6f46bc3d777593b83a5b817182e0f0cb9cc6e
Netflix/mantis-mql
test_query.clj
; Copyright 2022 Netflix , Inc. ; 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. ; (ns io.mantisrx.mql.test-query "The objective of this namespace is to verify correct functionality with non-aggregate queries." (:require [clojure.test :refer :all] [io.mantisrx.mql.jvm.core :refer :all] [instaparse.core :as insta] [rx.lang.clojure.core :as rx] [rx.lang.clojure.blocking :as rxb] ) (:import rx.Observable java.util.concurrent.TimeUnit)) (deftest test-simple-query (testing "select * from stream returns everything." (let [q "select * from stream" context {"stream" (Observable/just {"a" 1} {"b" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1} {"b" 2}] result))))) (deftest test-query-where-clause (testing "select * from stream where a == 1 filters out non-matching data." (let [q "select * from stream where a == 1" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1}] result)))) (testing "`select * from stream where a ==~ /ab.*ab/` filters out non-matching data." (let [q "select * from stream where a ==~ /ab.*ab/" context {"stream" (Observable/just {"a" "ab123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "ab123ab"}] result)))) (testing "select * from stream where e['a']['b'] == 1" (let [q "select * from stream where e['a']['b'] == 1" context {"stream" (Observable/just {"a" {"b" 1}} {"a" {"b" 2}} {"a" {"b" 2}})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" {"b" 1}}] result)))) (testing "select e['a']['b'] from stream where e['a']['b'] == 1" (let [q "select * from stream where e['a']['b'] == 1" context {"stream" (Observable/just {"a" {"b" 1}} {"b" 2} {"a" {"b" 2}})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" {"b" 1}}] result)))) (testing "`select * from stream where a ==+ '123'` filters out non-matching data." (let [q "select * from stream where a ==+ '123'" context {"stream" (Observable/just {"a" "ab123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "ab123ab"}] result))))) (deftest test-optimization-rules (testing "Queries transformed by the optimizer should function as intended." (testing "`select * from stream where a ==~ /abba/` filters out non-matching data. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /abba/" context {"stream" (Observable/just {"a" "ab123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "abba"}] result)))) (testing "`select * from stream where a ==~ /abba.*/` is optimized into a startsWith query which implements the proper predicate." (let [q "select * from stream where a ==~ /abba.*/" context {"stream" (Observable/just {"a" "abba1234"} {"b" 2} {"a" "abba"} {"a" "dabba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "abba1234"} {"a" "abba"}] result)))) (testing "`select * from stream where a ==~ /^abba.*/` is optimized into a startsWith query which implements the proper predicate." (let [q "select * from stream where a ==~ /^abba.*/" context {"stream" (Observable/just {"a" "abba1234"} {"b" 2} {"a" "abba"} {"a" "dabba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "abba1234"} {"a" "abba"}] result)))) (testing "`select * from stream where a ==~ /.*123.*/` filters out non-matching data. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /.*123.*/" context {"stream" (Observable/just {"a" "ab123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "ab123ab"}] result)))) (testing "`select * from stream where a ==~ /.*(abc|def).*/` filters out non-matching data. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /.*(abc|def).*/" context {"stream" (Observable/just {"a" "abc123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "abc123ab"}] result)))) (testing "`select * from stream where a ==~ /abc|def|ghi/` filters out non-matching data. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /abc|def|ghi/" context {"stream" (Observable/just {"a" "ghi"} {"b" 2} {"a" "abba"} {"a" "xyz"} {"a" "abc"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "ghi"} {"a" "abc"}] result)))) (testing "`select * from stream where a ==~ /.*prop\\\"\\:\\\"123.*/` matches nested json. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /.*prop\\\"\\:\\\"123.*/" context {"stream" (Observable/just {"a" "{\"prop\":\"123\"}"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "{\"prop\":\"123\"}"}] result)))) (testing "`select * from stream where a ==~ /^\\(focus\\)/` matches nested json. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /^\\(focus\\).*/" context {"stream" (Observable/just {"a" "(focus)test"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "(focus)test"}] result)))) )) (deftest test-query-limit-clause (testing "select * from stream limit 1 returns one result." (let [q "select * from stream limit 1" context {"stream" (Observable/just {"a" 1} {"b" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1}] result))))) (deftest test-query-select-properties (testing "select a from stream returns only a in results." (let [q "select a from stream" context {"stream" (Observable/just {"a" 1 "b" 2 "c" 3})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1}] result))))) (deftest test-query-order-by (testing "select * from stream order by a" (let [q "select * from stream order by a" context {"stream" (Observable/just {"a" 1} {"a" 3} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1} {"a" 2} {"a" 3}] result)))) (testing "select * from stream order by a desc reverses stream." (let [q "select * from stream order by a desc" context {"stream" (Observable/just {"a" 1} {"a" 3} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 3} {"a" 2} {"a" 1}] result))))) ;;;; ;;;; Modes ;;;; (deftest test-modes (testing "Full mode produces less results than client mode when sampling is enabled. Client mode should disable the sampling." (let [q "select * from stream SAMPLE {'strategy': 'RANDOM', 'threshold': 200}" context {"stream" (Observable/just {"a" 1} {"b" 2} {"c" 3} {"d" 4} {"e" 5} {"f" 6})} full-result (rxb/into [] (eval-mql q context "full")) client-result (rxb/into [] (eval-mql q context "client"))] (is (< (count full-result) (count client-result))) (is (= 6 (count client-result)))))) ;;;; ;;;; WHERE true, WHERE false ;;;; (deftest test-where-true-where-false (testing "select * from stream where true matches all data." (let [q "select * from stream where true" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1} {"b" 2} {"a" 2}] result)))) (testing "select * from stream where false matches no data." (let [q "select * from stream where false" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [] result))))) ;;;; ;;;; Queries without a FROM clause ;;;; (deftest test-query-without-from-clause (testing "select * where true matches all data." (let [q "select * where true" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1} {"b" 2} {"a" 2}] result)))) (testing "select * where false matches no data." (let [q "select * where false" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [] result)))) (testing "select * where a == 2 matches correct data." (let [q "select * where a == 2" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 2}] result))))) ;;;; ;;;; Constants ;;;; (deftest test-select-constants (testing "selecting a string constant" (let [q "select a, 'b' where a == 2" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 2 "b" "b"}] result)))) (testing "selecting a numeric constant" (let [q "select a, 2 where a == 2" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 2 "2" 2}] result))))) ;;;; ;;;; As Clause ;;;; (deftest test-as-clause (testing "select a constant with as clause renames it in client mode" (let [q "select 1 as 'test_id', 'b' as 'code', 3.14 as 'pi', a as 'prop' from stream" context {"stream" (Observable/just {"a" 1})} result (rxb/into [] (eval-mql q context "client"))] (is (= [{"test_id" 1, "code" "b", "pi" 3.14, "prop" 1}] result)))) (testing "select a nil value with as clause does not insert it in client mode" (let [q "select a as 'test', b as 'test' from stream" context {"stream" (Observable/just {"a" 1})} result (rxb/into [] (eval-mql q context "client"))] (is (= [{"test" 1}] result)))) ) ;;;; ;;;; Spaces in Properties ;;;; (deftest test-spaces-in-property-names (testing "selecting a space in a property name" (let [q "select a, e['c '] where e['c '] == 2" context {"stream" (Observable/just {"a" 1, "c " 2} {"b" 2} {"a" 2 "c " 3})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1 "c " 2}] result)))))
null
https://raw.githubusercontent.com/Netflix/mantis-mql/94600fc687afd380e6a063806a5f0dd0be218f34/mql-jvm/src/test/clojure/io/mantisrx/mql/test_query.clj
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Modes WHERE true, WHERE false Queries without a FROM clause Constants As Clause Spaces in Properties
Copyright 2022 Netflix , Inc. distributed under the License is distributed on an " AS IS " BASIS , (ns io.mantisrx.mql.test-query "The objective of this namespace is to verify correct functionality with non-aggregate queries." (:require [clojure.test :refer :all] [io.mantisrx.mql.jvm.core :refer :all] [instaparse.core :as insta] [rx.lang.clojure.core :as rx] [rx.lang.clojure.blocking :as rxb] ) (:import rx.Observable java.util.concurrent.TimeUnit)) (deftest test-simple-query (testing "select * from stream returns everything." (let [q "select * from stream" context {"stream" (Observable/just {"a" 1} {"b" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1} {"b" 2}] result))))) (deftest test-query-where-clause (testing "select * from stream where a == 1 filters out non-matching data." (let [q "select * from stream where a == 1" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1}] result)))) (testing "`select * from stream where a ==~ /ab.*ab/` filters out non-matching data." (let [q "select * from stream where a ==~ /ab.*ab/" context {"stream" (Observable/just {"a" "ab123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "ab123ab"}] result)))) (testing "select * from stream where e['a']['b'] == 1" (let [q "select * from stream where e['a']['b'] == 1" context {"stream" (Observable/just {"a" {"b" 1}} {"a" {"b" 2}} {"a" {"b" 2}})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" {"b" 1}}] result)))) (testing "select e['a']['b'] from stream where e['a']['b'] == 1" (let [q "select * from stream where e['a']['b'] == 1" context {"stream" (Observable/just {"a" {"b" 1}} {"b" 2} {"a" {"b" 2}})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" {"b" 1}}] result)))) (testing "`select * from stream where a ==+ '123'` filters out non-matching data." (let [q "select * from stream where a ==+ '123'" context {"stream" (Observable/just {"a" "ab123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "ab123ab"}] result))))) (deftest test-optimization-rules (testing "Queries transformed by the optimizer should function as intended." (testing "`select * from stream where a ==~ /abba/` filters out non-matching data. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /abba/" context {"stream" (Observable/just {"a" "ab123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "abba"}] result)))) (testing "`select * from stream where a ==~ /abba.*/` is optimized into a startsWith query which implements the proper predicate." (let [q "select * from stream where a ==~ /abba.*/" context {"stream" (Observable/just {"a" "abba1234"} {"b" 2} {"a" "abba"} {"a" "dabba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "abba1234"} {"a" "abba"}] result)))) (testing "`select * from stream where a ==~ /^abba.*/` is optimized into a startsWith query which implements the proper predicate." (let [q "select * from stream where a ==~ /^abba.*/" context {"stream" (Observable/just {"a" "abba1234"} {"b" 2} {"a" "abba"} {"a" "dabba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "abba1234"} {"a" "abba"}] result)))) (testing "`select * from stream where a ==~ /.*123.*/` filters out non-matching data. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /.*123.*/" context {"stream" (Observable/just {"a" "ab123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "ab123ab"}] result)))) (testing "`select * from stream where a ==~ /.*(abc|def).*/` filters out non-matching data. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /.*(abc|def).*/" context {"stream" (Observable/just {"a" "abc123ab"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "abc123ab"}] result)))) (testing "`select * from stream where a ==~ /abc|def|ghi/` filters out non-matching data. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /abc|def|ghi/" context {"stream" (Observable/just {"a" "ghi"} {"b" 2} {"a" "abba"} {"a" "xyz"} {"a" "abc"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "ghi"} {"a" "abc"}] result)))) (testing "`select * from stream where a ==~ /.*prop\\\"\\:\\\"123.*/` matches nested json. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /.*prop\\\"\\:\\\"123.*/" context {"stream" (Observable/just {"a" "{\"prop\":\"123\"}"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "{\"prop\":\"123\"}"}] result)))) (testing "`select * from stream where a ==~ /^\\(focus\\)/` matches nested json. Note that this query is expected to be transformed by the optimizer." (let [q "select * from stream where a ==~ /^\\(focus\\).*/" context {"stream" (Observable/just {"a" "(focus)test"} {"b" 2} {"a" "abba"})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" "(focus)test"}] result)))) )) (deftest test-query-limit-clause (testing "select * from stream limit 1 returns one result." (let [q "select * from stream limit 1" context {"stream" (Observable/just {"a" 1} {"b" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1}] result))))) (deftest test-query-select-properties (testing "select a from stream returns only a in results." (let [q "select a from stream" context {"stream" (Observable/just {"a" 1 "b" 2 "c" 3})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1}] result))))) (deftest test-query-order-by (testing "select * from stream order by a" (let [q "select * from stream order by a" context {"stream" (Observable/just {"a" 1} {"a" 3} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1} {"a" 2} {"a" 3}] result)))) (testing "select * from stream order by a desc reverses stream." (let [q "select * from stream order by a desc" context {"stream" (Observable/just {"a" 1} {"a" 3} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 3} {"a" 2} {"a" 1}] result))))) (deftest test-modes (testing "Full mode produces less results than client mode when sampling is enabled. Client mode should disable the sampling." (let [q "select * from stream SAMPLE {'strategy': 'RANDOM', 'threshold': 200}" context {"stream" (Observable/just {"a" 1} {"b" 2} {"c" 3} {"d" 4} {"e" 5} {"f" 6})} full-result (rxb/into [] (eval-mql q context "full")) client-result (rxb/into [] (eval-mql q context "client"))] (is (< (count full-result) (count client-result))) (is (= 6 (count client-result)))))) (deftest test-where-true-where-false (testing "select * from stream where true matches all data." (let [q "select * from stream where true" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1} {"b" 2} {"a" 2}] result)))) (testing "select * from stream where false matches no data." (let [q "select * from stream where false" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [] result))))) (deftest test-query-without-from-clause (testing "select * where true matches all data." (let [q "select * where true" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1} {"b" 2} {"a" 2}] result)))) (testing "select * where false matches no data." (let [q "select * where false" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [] result)))) (testing "select * where a == 2 matches correct data." (let [q "select * where a == 2" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 2}] result))))) (deftest test-select-constants (testing "selecting a string constant" (let [q "select a, 'b' where a == 2" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 2 "b" "b"}] result)))) (testing "selecting a numeric constant" (let [q "select a, 2 where a == 2" context {"stream" (Observable/just {"a" 1} {"b" 2} {"a" 2})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 2 "2" 2}] result))))) (deftest test-as-clause (testing "select a constant with as clause renames it in client mode" (let [q "select 1 as 'test_id', 'b' as 'code', 3.14 as 'pi', a as 'prop' from stream" context {"stream" (Observable/just {"a" 1})} result (rxb/into [] (eval-mql q context "client"))] (is (= [{"test_id" 1, "code" "b", "pi" 3.14, "prop" 1}] result)))) (testing "select a nil value with as clause does not insert it in client mode" (let [q "select a as 'test', b as 'test' from stream" context {"stream" (Observable/just {"a" 1})} result (rxb/into [] (eval-mql q context "client"))] (is (= [{"test" 1}] result)))) ) (deftest test-spaces-in-property-names (testing "selecting a space in a property name" (let [q "select a, e['c '] where e['c '] == 2" context {"stream" (Observable/just {"a" 1, "c " 2} {"b" 2} {"a" 2 "c " 3})} result (rxb/into [] (eval-mql q context))] (is (= [{"a" 1 "c " 2}] result)))))
b4c5278e9b395ea5b8a17e02692d50c161b60fddc921ef1ed763a47e440572e1
coq/coq
ssrfwd.ml
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) * GNU Lesser General Public License Version 2.1 (* * (see LICENSE file for the text of the license) *) (************************************************************************) This file is ( C ) Copyright 2006 - 2015 Microsoft Corporation and . open Pp open Names open Constr open Context open Proofview.Notations open Ssrmatching_plugin.Ssrmatching open Ssrprinters open Ssrcommon open Ssrtacticals module RelDecl = Context.Rel.Declaration * 8 . Forward chaining tactics ( pose , set , have , suffice , wlog ) (** Defined identifier *) let ssrposetac (id, (_, t)) = let open Proofview.Notations in Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let ist, t = match t.Ssrast.interp_env with | Some ist -> ist, Ssrcommon.ssrterm_of_ast_closure_term t | None -> assert false in let sigma, t, _ = abs_ssrterm ist env sigma t in Proofview.Unsafe.tclEVARS sigma <*> Tactics.pose_tac (Name id) t end let redex_of_pattern_tc env p = let sigma, e = match redex_of_pattern p with | None -> CErrors.anomaly (str "pattern without redex.") | Some (sigma, e) -> sigma, e in let sigma = Typeclasses.resolve_typeclasses ~fail:false env sigma in Evarutil.nf_evar sigma e, Evd.evar_universe_context sigma let ssrsettac id ((_, (pat, pty)), (_, occ)) = let open Proofview.Notations in Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let cl = Proofview.Goal.concl gl in let pty = Option.map (fun { Ssrast.body; interp_env } -> let ist = Option.get interp_env in (mkRHole, Some body), ist) pty in let pat = interp_cpattern env sigma pat pty in let (c, ucst), cl = try fill_occ_pattern ~raise_NoMatch:true env sigma cl pat occ 1 with NoMatch -> redex_of_pattern_tc env pat, cl in let sigma = Evd.merge_universe_context sigma ucst in if Termops.occur_existential sigma c then errorstrm(str"The pattern"++spc()++ pr_econstr_pat env sigma c++spc()++str"did not match and has holes."++spc()++ str"Did you mean pose?") else let c, (sigma, cty) = match EConstr.kind sigma c with | Cast(t, DEFAULTcast, ty) -> t, (sigma, ty) | _ -> c, Typing.type_of env sigma c in let cl' = EConstr.mkLetIn (make_annot (Name id) Sorts.Relevant, c, cty, cl) in Proofview.Unsafe.tclEVARS sigma <*> convert_concl ~check:true cl' <*> introid id end open Util open Printer open Ssrast open Ssripats let ssrhaveNOtcresolution = Summary.ref ~name:"SSR:havenotcresolution" false let () = Goptions.(declare_bool_option { optstage = Summary.Stage.Interp; optkey = ["SsrHave";"NoTCResolution"]; optread = (fun _ -> !ssrhaveNOtcresolution); optdepr = false; optwrite = (fun b -> ssrhaveNOtcresolution := b); }) open Constrexpr open Glob_term let combineCG t1 t2 f g = match t1, t2 with | (x, (t1, None)), (_, (t2, None)) -> x, (g t1 t2, None) | (x, (_, Some t1)), (_, (_, Some t2)) -> x, (mkRHole, Some (f t1 t2)) | _, (_, (_, None)) -> anomaly "have: mixed C-G constr" | _ -> anomaly "have: mixed G-C constr" type cut_kind = Have | HaveTransp | Suff let basecuttac k c = let open Proofview.Notations in let open EConstr in Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Tacmach.project gl in let concl = Proofview.Goal.concl gl in let state = Proofview.Goal.state gl in match Typing.sort_of env sigma c with | exception e when CErrors.noncritical e -> let _, info = Exninfo.capture e in Tacticals.tclZEROMSG ~info (str "Not a proposition or a type.") | sigma, s -> let r = ESorts.relevance_of_sort sigma s in let sigma, f, glf = match k with | HaveTransp -> let name = Context.make_annot Name.Anonymous r in let sigma, p = Evarutil.new_evar env sigma c in let sigma, f = Evarutil.new_evar env sigma (mkLetIn (name,p,c,Vars.lift 1 concl)) in let gp = Proofview_monad.goal_with_state (fst @@ destEvar sigma p) state in let gf = Proofview_monad.goal_with_state (fst @@ destEvar sigma f) state in sigma, f, [gp;gf] | Have | Suff -> let sigma, f = Evarutil.new_evar env sigma (mkArrow c r concl) in let gf = Proofview_monad.goal_with_state (fst @@ destEvar sigma f) state in sigma, f, [gf] in Proofview.Unsafe.tclEVARS sigma <*> Tactics.eapply ~with_classes:false f <*> Proofview.Unsafe.tclGETGOALS >>= begin fun gl -> match k with | Suff -> Proofview.Unsafe.tclSETGOALS (glf @ gl) <*> Proofview.tclFOCUS 1 1 Tactics.reduce_after_refine | Have | HaveTransp -> let ngoals = List.length gl + 1 in Proofview.Unsafe.tclSETGOALS (gl @ glf) <*> Proofview.tclFOCUS ngoals ngoals Tactics.reduce_after_refine end end let basesufftac t = basecuttac Suff t let introstac ipats = tclIPAT ipats let make_ct t = let open CAst in let mkt t = mk_term NoFlag t in let mkl t = (NoFlag, (t, None)) in match Ssrcommon.ssrterm_of_ast_closure_term t with | _, (_, Some { loc; v = CCast (ct, DEFAULTcast, cty)}) -> mkt ct, mkt cty, mkt (mkCHole None), loc | _, (_, Some ct) -> mkt ct, mkt (mkCHole None), mkt (mkCHole None), None | _, (t, None) -> begin match DAst.get t with | GCast (ct, DEFAULTcast, cty) -> mkl ct, mkl cty, mkl mkRHole, t.CAst.loc | _ -> mkl t, mkl mkRHole, mkl mkRHole, None end (* FIXME: understand why we have to play with the goal states *) let drop_state = let map gl = Proofview.with_empty_state (Proofview.drop_state gl) in Proofview.Unsafe.tclGETGOALS >>= fun gls -> Proofview.Unsafe.tclSETGOALS (List.map map gls) let set_state s = let map gl = Proofview.goal_with_state (Proofview.drop_state gl) s in Proofview.Unsafe.tclGETGOALS >>= fun gls -> Proofview.Unsafe.tclSETGOALS (List.map map gls) let assert_is_conv (ctx, concl) = Proofview.Goal.enter begin fun gl -> Proofview.tclORELSE (convert_concl ~check:true (EConstr.it_mkProd_or_LetIn concl ctx)) (fun _ -> Tacticals.tclZEROMSG (str "Given proof term is not of type " ++ pr_econstr_env (Tacmach.pf_env gl) (Tacmach.project gl) (EConstr.mkArrow (EConstr.mkVar (Id.of_string "_")) Sorts.Relevant concl))) end let push_goals gs = Proofview.Goal.enter begin fun gl -> (* FIXME: do we really want to preserve state? *) let gstate = Proofview.Goal.state gl in let map ev = Proofview.goal_with_state ev gstate in Proofview.Unsafe.tclSETGOALS (List.map map (gs @ [Proofview.Goal.goal gl])) end let havetac ist (transp,((((clr, orig_pats), binders), simpl), (((fk, _), t), hint))) suff namefst = let open Proofview.Notations in Ssrcommon.tacMK_SSR_CONST "abstract_key" >>= fun abstract_key -> Ssrcommon.tacMK_SSR_CONST "abstract" >>= fun abstract -> Proofview.Goal.enter begin fun gl -> let concl = Proofview.Goal.concl gl in let gstate = Proofview.Goal.state gl in let pats = tclCompileIPats orig_pats in let binders = tclCompileIPats binders in let simpl = tclCompileIPats simpl in let skols, pats = List.partition (function IOpAbstractVars _ -> true | _ -> false) pats in let itac_mkabs = introstac skols in let itac_c, clr = match clr with | None -> introstac pats, [] | Some clr -> introstac (tclCompileIPats (IPatClear clr :: orig_pats)), clr in let itac, clr = introstac pats, cleartac clr in let binderstac n = let rec aux = function 0 -> [] | n -> IOpInaccessible None :: aux (n-1) in Tacticals.tclTHEN (if binders <> [] then introstac (aux n) else Tacticals.tclIDTAC) (introstac binders) in let simpltac = introstac simpl in let fixtc = not !ssrhaveNOtcresolution && match fk with FwdHint(_,true) -> false | _ -> true in let hint = hinttac ist true hint in let cuttac t = basecuttac (if transp then HaveTransp else Have) t in (* Introduce now abstract constants, so that everything sees them *) let unlock_abs env (idty,args_id) sigma = let sigma, _ = Typing.type_of env sigma idty in unify_HO env sigma args_id.(2) abstract_key in drop_state <*> Tacticals.tclTHENFIRST itac_mkabs (Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let interp sigma rtc t = abs_ssrterm ~resolve_typeclasses:rtc ist env sigma t in let ct, cty, hole, loc = make_ct t in let sigma, cut, itac1, itac2 = match fk, namefst, suff with | FwdHave, true, true -> errorstrm (str"Suff have does not accept a proof term") | FwdHave, false, true -> let cty = combineCG cty hole (mkCArrow ?loc) mkRArrow in let sigma, t, _ = interp sigma false (combineCG ct cty (mkCCast ?loc) mkRCast) in let sigma, ty = Typing.type_of env sigma t in let ctx, _ = EConstr.decompose_prod_n_decls sigma 1 ty in sigma, ty, assert_is_conv (ctx, concl) <*> Tactics.apply t, itac_c | FwdHave, false, false -> let skols = List.flatten (List.map (function | IOpAbstractVars ids -> ids | _ -> assert false) skols) in let skols_args = List.map (fun id -> snd @@ (* FIXME: evar leak *) Ssripats.Internal.examine_abstract env sigma (EConstr.mkVar id)) skols in let sigma = List.fold_right (unlock_abs env) skols_args sigma in let sigma, t, n_evars = interp sigma false (combineCG ct cty (mkCCast ?loc) mkRCast) in if skols <> [] && n_evars <> 0 then CErrors.user_err (Pp.strbrk @@ "Automatic generalization of unresolved implicit "^ "arguments together with abstract variables is "^ "not supported"); let gs = List.map (fun (_,a) -> Ssripats.Internal.find_abstract_proof env sigma false a.(1)) skols_args in let tacopen_skols = push_goals gs in let sigma, ty = Typing.type_of env sigma t in sigma, ty, Tactics.apply t, itac_c <*> simpltac <*> tacopen_skols <*> unfold [abstract; abstract_key] | _,true,true -> let sigma, _, ty, _ = pf_interp_ty ~resolve_typeclasses:fixtc env sigma ist cty in sigma, EConstr.mkArrow ty Sorts.Relevant concl, hint <*> itac, clr | _,false,true -> let sigma, _, ty, _ = pf_interp_ty ~resolve_typeclasses:fixtc env sigma ist cty in sigma, EConstr.mkArrow ty Sorts.Relevant concl, hint, itac_c | _, false, false -> let sigma, n, cty, _ = pf_interp_ty ~resolve_typeclasses:fixtc env sigma ist cty in sigma, cty, (binderstac n) <*> hint, Tacticals.tclTHEN itac_c simpltac | _, true, false -> assert false in Proofview.Unsafe.tclEVARS sigma <*> Tacticals.tclTHENS (cuttac cut) [ itac1; itac2 ] end) <*> set_state gstate end let destProd_or_LetIn sigma c = match EConstr.kind sigma c with | Prod (n,ty,c) -> RelDecl.LocalAssum (n, ty), c | LetIn (n,bo,ty,c) -> RelDecl.LocalDef (n, bo, ty), c | _ -> raise DestKO let wlogtac ist (((clr0, pats),_),_) (gens, ((_, ct))) hint suff ghave = Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let concl = Proofview.Goal.concl gl in let clr0 = Option.default [] clr0 in let pats = tclCompileIPats pats in let mkclr gen clrs = clr_of_wgen gen clrs in let mkpats = function | _, Some ((x, _), _) -> fun pats -> IOpId (hoi_id x) :: pats | _ -> fun x -> x in let ct = match Ssrcommon.ssrterm_of_ast_closure_term ct with | (a, (b, Some ct)) -> begin match ct.CAst.v with | CCast (_, DEFAULTcast, cty) -> a, (b, Some cty) | _ -> anomaly "wlog: ssr cast hole deleted by typecheck" end | (a, (t, None)) -> begin match DAst.get t with | GCast (_, DEFAULTcast, cty) -> a, (cty, None) | _ -> anomaly "wlog: ssr cast hole deleted by typecheck" end in let cut_implies_goal = not (suff || ghave <> `NoGen) in let c, args, ct, sigma = let gens = List.filter (function _, Some _ -> true | _ -> false) gens in let c = EConstr.mkProp in let c = if cut_implies_goal then EConstr.mkArrow c Sorts.Relevant concl else c in let mkabs gen (sigma, args, c) = abs_wgen env sigma false (fun x -> x) gen (args, c) in let sigma, args, c = List.fold_right mkabs gens (sigma, [], c) in let env, _ = List.fold_left (fun (env, c) _ -> let rd, c = destProd_or_LetIn sigma c in EConstr.push_rel rd env, c) (env, c) gens in let sigma, _, ct, _ = pf_interp_ty env sigma ist ct in let rec var2rel c g s = match EConstr.kind sigma c, g with | Prod({binder_name=Anonymous} as x,_,c), [] -> EConstr.mkProd(x, EConstr.Vars.subst_vars sigma s ct, c) | Sort _, [] -> EConstr.Vars.subst_vars sigma s ct | LetIn({binder_name=Name id} as n,b,ty,c), _::g -> EConstr.mkLetIn (n,b,ty,var2rel c g (id::s)) | Prod({binder_name=Name id} as n,ty,c), _::g -> EConstr.mkProd (n,ty,var2rel c g (id::s)) | _ -> CErrors.anomaly(str"SSR: wlog: var2rel: " ++ pr_econstr_env env sigma c) in let c = var2rel c gens [] in let rec pired c = function | [] -> c | t::ts as args -> match EConstr.kind sigma c with | Prod(_,_,c) -> pired (EConstr.Vars.subst1 t c) ts | LetIn(id,b,ty,c) -> EConstr.mkLetIn (id,b,ty,pired c args) | _ -> CErrors.anomaly(str"SSR: wlog: pired: " ++ pr_econstr_env env sigma c) in c, args, pired c args, sigma in let tacipat pats = introstac pats in let tacigens = Tacticals.tclTHEN (Tacticals.tclTHENLIST(List.rev(List.fold_right mkclr gens [cleartac clr0]))) (introstac (List.fold_right mkpats gens [])) in let hinttac = hinttac ist true hint in let cut_kind, fst_goal_tac, snd_goal_tac = match suff, ghave with | true, `NoGen -> Suff, Tacticals.tclTHEN hinttac (tacipat pats), tacigens | false, `NoGen -> Suff, hinttac, Tacticals.tclTHEN tacigens (tacipat pats) | true, `Gen _ -> assert false | false, `Gen id -> if gens = [] then errorstrm(str"gen have requires some generalizations"); let clear0 = cleartac clr0 in let id, name_general_hyp, cleanup, pats = match id, pats with | None, (IOpId id as ip)::pats -> Some id, tacipat [ip], clear0, pats | None, _ -> None, Tacticals.tclIDTAC, clear0, pats | Some (Some id),_ -> Some id, introid id, clear0, pats | Some _,_ -> let id = mk_anon_id "tmp" (Tacmach.pf_ids_of_hyps gl) in Some id, introid id, Tacticals.tclTHEN clear0 (Tactics.clear [id]), pats in let tac_specialize = match id with | None -> Tacticals.tclIDTAC | Some id -> if pats = [] then Tacticals.tclIDTAC else let args = Array.of_list args in debug_ssr (fun () -> str"specialized="++ pr_econstr_env env sigma EConstr.(mkApp (mkVar id,args))); debug_ssr (fun () -> str"specialized_ty="++ pr_econstr_env env sigma ct); Tacticals.tclTHENS (basecuttac Have ct) [Tactics.apply EConstr.(mkApp (mkVar id,args)); Tacticals.tclIDTAC] in Have, (if hint = nohint then tacigens else hinttac), Tacticals.tclTHENLIST [name_general_hyp; tac_specialize; tacipat pats; cleanup] in Proofview.Unsafe.tclEVARS sigma <*> Tacticals.tclTHENS (basecuttac cut_kind c) [fst_goal_tac; snd_goal_tac] end (** The "suffice" tactic *) open Proofview.Notations let sufftac ist ((((clr, pats),binders),simpl), ((_, c), hint)) = let clr = Option.default [] clr in let pats = tclCompileIPats pats in let binders = tclCompileIPats binders in let simpl = tclCompileIPats simpl in let htac = Tacticals.tclTHEN (introstac pats) (hinttac ist true hint) in let c = match Ssrcommon.ssrterm_of_ast_closure_term c with | (a, (b, Some ct)) -> begin match ct.CAst.v with | CCast (_, DEFAULTcast, cty) -> a, (b, Some cty) | _ -> anomaly "suff: ssr cast hole deleted by typecheck" end | (a, (t, None)) -> begin match DAst.get t with | GCast (_, DEFAULTcast, cty) -> a, (cty, None) | _ -> anomaly "suff: ssr cast hole deleted by typecheck" end in let ctac = let open Tacmach in Proofview.Goal.enter begin fun gl -> let sigma, _, ty, _ = pf_interp_ty (pf_env gl) (project gl) ist c in Proofview.Unsafe.tclEVARS sigma <*> basesufftac ty end in Tacticals.tclTHENS ctac [htac; Tacticals.tclTHEN (cleartac clr) (introstac (binders@simpl))] let is_app_evar sigma t = match EConstr.kind sigma t with | Constr.Evar _ -> true | Constr.App(t,_) -> begin match EConstr.kind sigma t with | Constr.Evar _ -> true | _ -> false end | _ -> false let rec ncons n e = match n with | 0 -> [] | n when n > 0 -> e :: ncons (n - 1) e | _ -> failwith "ncons" let intro_lock ipats = let hnf' = Proofview.numgoals >>= fun ng -> Proofview.tclDISPATCH (ncons (ng - 1) ssrsmovetac @ [Proofview.tclUNIT ()]) in let protect_subgoal env sigma hd args = Ssrcommon.tacMK_SSR_CONST "Under_rel" >>= fun under_rel -> Ssrcommon.tacMK_SSR_CONST "Under_rel_from_rel" >>= fun under_from_rel -> Tactics.refine ~typecheck:true (fun sigma -> let lm2 = Array.length args - 2 in let sigma, carrier = Typing.type_of env sigma args.(lm2) in let rel = EConstr.mkApp (hd, Array.sub args 0 lm2) in let rel_args = Array.sub args lm2 2 in let under_rel_args = Array.append [|carrier; rel|] rel_args in let ty = EConstr.mkApp (under_rel, under_rel_args) in let sigma, t = Evarutil.new_evar env sigma ty in sigma, EConstr.mkApp(under_from_rel,Array.append under_rel_args [|t|])) in let rec lock_eq () : unit Proofview.tactic = Proofview.Goal.enter begin fun _ -> Proofview.tclORELSE (Ssripats.tclIPAT [Ssripats.IOpTemporay; Ssripats.IOpEqGen (lock_eq ())]) (fun _exn -> Proofview.Goal.enter begin fun gl -> let c = Proofview.Goal.concl gl in let sigma = Proofview.Goal.sigma gl in let env = Proofview.Goal.env gl in let open EConstr in match kind_of_type sigma c with | AtomicType(hd, args) when Array.length args >= 2 && is_app_evar sigma (Array.last args) && Ssrequality.ssr_is_setoid env sigma hd args (* if the last condition above [ssr_is_setoid ...] holds then [Coq.Classes.RelationClasses] has been required *) || (* if this is not the case, the tactic can still succeed when the considered relation is [Coq.Init.Logic.iff] *) Ssrcommon.is_const_ref env sigma hd (Coqlib.lib_ref "core.iff.type") && Array.length args = 2 && is_app_evar sigma args.(1) -> protect_subgoal env sigma hd args | _ -> let t = Reductionops.whd_all env sigma c in match kind_of_type sigma t with | AtomicType(hd, args) when Ssrcommon.is_ind_ref env sigma hd (Coqlib.lib_ref "core.eq.type") && Array.length args = 3 && is_app_evar sigma args.(2) -> protect_subgoal env sigma hd args | _ -> debug_ssr (fun () -> Pp.(str"under: stop:" ++ pr_econstr_env env sigma t)); Proofview.tclUNIT () end) end in hnf' <*> Ssripats.tclIPATssr ipats <*> lock_eq () let pretty_rename evar_map term varnames = let rec aux term vars = try match vars with | [] -> term | Names.Name.Anonymous :: varnames -> let name, types, body = EConstr.destLambda evar_map term in let res = aux body varnames in EConstr.mkLambda (name, types, res) | Names.Name.Name _ as name :: varnames -> let { Context.binder_relevance = r }, types, body = EConstr.destLambda evar_map term in let res = aux body varnames in EConstr.mkLambda (Context.make_annot name r, types, res) with DestKO -> term in aux term varnames let overtac = ssr_n_tac "over" ~-1 let check_numgoals ?(minus = 0) nh = Proofview.numgoals >>= fun ng -> if nh <> ng then let errmsg = str"Incorrect number of tactics" ++ spc() ++ str"(expected "++int (ng - minus)++str(String.plural ng " tactic") ++ str", was given "++ int (nh - minus)++str")." in CErrors.user_err errmsg else Proofview.tclUNIT () let undertac ?(pad_intro = false) ist ipats ((dir,_),_ as rule) hint = (* total number of implied hints *) let nh = List.length (snd hint) + (if hint = nullhint then 2 else 1) in let varnames = let rec aux acc = function | IPatId id :: rest -> aux (Names.Name.Name id :: acc) rest | IPatClear _ :: rest -> aux acc rest | IPatSimpl _ :: rest -> aux acc rest | IPatAnon (One _ | Drop) :: rest -> aux (Names.Name.Anonymous :: acc) rest | _ -> List.rev acc in aux [] @@ match ipats with | None -> [] | Some (IPatCase(Regular (l :: _)) :: _) -> l | Some l -> l in (* If we find a "=> [|]" we add 1 | to get "=> [||]" for the extra * goal (the one that is left once we run over) *) let ipats = match ipats with | None -> [IPatNoop] typically , ipats = Some [ IPatAnon All ] let new_l = ncons (nh - 1) l in [IPatCase(Regular (new_l @ [[]]))] | Some (IPatCase(Regular []) :: _ as ipats) -> ipats : is the previous line correct / useful ? | Some (IPatCase(Regular l) :: rest) -> IPatCase(Regular(l @ [[]])) :: rest | Some (IPatCase(Block _) :: _ as l) -> l | Some l -> [IPatCase(Regular [l;[]])] in let map_redex env evar_map ~before:_ ~after:t = debug_ssr (fun () -> Pp.(str"under vars: " ++ prlist Names.Name.print varnames)); let evar_map, ty = Typing.type_of env evar_map t in let new_t = (* pretty-rename the bound variables *) try begin match EConstr.destApp evar_map t with (f, ar) -> let lam = Array.last ar in debug_ssr(fun () -> Pp.(str"under: mapping:" ++ pr_econstr_env env evar_map lam)); let new_lam = pretty_rename evar_map lam varnames in let new_ar, len1 = Array.copy ar, pred (Array.length ar) in new_ar.(len1) <- new_lam; EConstr.mkApp (f, new_ar) end with | DestKO -> debug_ssr (fun () -> Pp.(str"under: cannot pretty-rename bound variables with destApp")); t in debug_ssr (fun () -> Pp.(str"under: to:" ++ pr_econstr_env env evar_map new_t)); evar_map, new_t in let undertacs = if hint = nohint then Proofview.tclUNIT () else let betaiota = Tactics.reduct_in_concl ~cast:false ~check:false (Reductionops.nf_betaiota, DEFAULTcast) in (* Usefulness of check_numgoals: tclDISPATCH would be enough, except for the error message w.r.t. the number of provided/expected tactics, as the last one is implied *) check_numgoals ~minus:1 nh <*> Proofview.tclDISPATCH ((List.map (function None -> overtac | Some e -> ssrevaltac ist e <*> overtac) (if hint = nullhint then [None] else snd hint)) @ [betaiota]) in let rew = Ssrequality.ssrrewritetac ~under:true ~map_redex ist [rule] in rew <*> intro_lock ipats <*> undertacs
null
https://raw.githubusercontent.com/coq/coq/8f1590f7840d0dff71fa9b7a7bbc1ed01d779359/plugins/ssr/ssrfwd.ml
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** * Defined identifier FIXME: understand why we have to play with the goal states FIXME: do we really want to preserve state? Introduce now abstract constants, so that everything sees them FIXME: evar leak * The "suffice" tactic if the last condition above [ssr_is_setoid ...] holds then [Coq.Classes.RelationClasses] has been required if this is not the case, the tactic can still succeed when the considered relation is [Coq.Init.Logic.iff] total number of implied hints If we find a "=> [|]" we add 1 | to get "=> [||]" for the extra * goal (the one that is left once we run over) pretty-rename the bound variables Usefulness of check_numgoals: tclDISPATCH would be enough, except for the error message w.r.t. the number of provided/expected tactics, as the last one is implied
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 This file is ( C ) Copyright 2006 - 2015 Microsoft Corporation and . open Pp open Names open Constr open Context open Proofview.Notations open Ssrmatching_plugin.Ssrmatching open Ssrprinters open Ssrcommon open Ssrtacticals module RelDecl = Context.Rel.Declaration * 8 . Forward chaining tactics ( pose , set , have , suffice , wlog ) let ssrposetac (id, (_, t)) = let open Proofview.Notations in Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let ist, t = match t.Ssrast.interp_env with | Some ist -> ist, Ssrcommon.ssrterm_of_ast_closure_term t | None -> assert false in let sigma, t, _ = abs_ssrterm ist env sigma t in Proofview.Unsafe.tclEVARS sigma <*> Tactics.pose_tac (Name id) t end let redex_of_pattern_tc env p = let sigma, e = match redex_of_pattern p with | None -> CErrors.anomaly (str "pattern without redex.") | Some (sigma, e) -> sigma, e in let sigma = Typeclasses.resolve_typeclasses ~fail:false env sigma in Evarutil.nf_evar sigma e, Evd.evar_universe_context sigma let ssrsettac id ((_, (pat, pty)), (_, occ)) = let open Proofview.Notations in Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let cl = Proofview.Goal.concl gl in let pty = Option.map (fun { Ssrast.body; interp_env } -> let ist = Option.get interp_env in (mkRHole, Some body), ist) pty in let pat = interp_cpattern env sigma pat pty in let (c, ucst), cl = try fill_occ_pattern ~raise_NoMatch:true env sigma cl pat occ 1 with NoMatch -> redex_of_pattern_tc env pat, cl in let sigma = Evd.merge_universe_context sigma ucst in if Termops.occur_existential sigma c then errorstrm(str"The pattern"++spc()++ pr_econstr_pat env sigma c++spc()++str"did not match and has holes."++spc()++ str"Did you mean pose?") else let c, (sigma, cty) = match EConstr.kind sigma c with | Cast(t, DEFAULTcast, ty) -> t, (sigma, ty) | _ -> c, Typing.type_of env sigma c in let cl' = EConstr.mkLetIn (make_annot (Name id) Sorts.Relevant, c, cty, cl) in Proofview.Unsafe.tclEVARS sigma <*> convert_concl ~check:true cl' <*> introid id end open Util open Printer open Ssrast open Ssripats let ssrhaveNOtcresolution = Summary.ref ~name:"SSR:havenotcresolution" false let () = Goptions.(declare_bool_option { optstage = Summary.Stage.Interp; optkey = ["SsrHave";"NoTCResolution"]; optread = (fun _ -> !ssrhaveNOtcresolution); optdepr = false; optwrite = (fun b -> ssrhaveNOtcresolution := b); }) open Constrexpr open Glob_term let combineCG t1 t2 f g = match t1, t2 with | (x, (t1, None)), (_, (t2, None)) -> x, (g t1 t2, None) | (x, (_, Some t1)), (_, (_, Some t2)) -> x, (mkRHole, Some (f t1 t2)) | _, (_, (_, None)) -> anomaly "have: mixed C-G constr" | _ -> anomaly "have: mixed G-C constr" type cut_kind = Have | HaveTransp | Suff let basecuttac k c = let open Proofview.Notations in let open EConstr in Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Tacmach.project gl in let concl = Proofview.Goal.concl gl in let state = Proofview.Goal.state gl in match Typing.sort_of env sigma c with | exception e when CErrors.noncritical e -> let _, info = Exninfo.capture e in Tacticals.tclZEROMSG ~info (str "Not a proposition or a type.") | sigma, s -> let r = ESorts.relevance_of_sort sigma s in let sigma, f, glf = match k with | HaveTransp -> let name = Context.make_annot Name.Anonymous r in let sigma, p = Evarutil.new_evar env sigma c in let sigma, f = Evarutil.new_evar env sigma (mkLetIn (name,p,c,Vars.lift 1 concl)) in let gp = Proofview_monad.goal_with_state (fst @@ destEvar sigma p) state in let gf = Proofview_monad.goal_with_state (fst @@ destEvar sigma f) state in sigma, f, [gp;gf] | Have | Suff -> let sigma, f = Evarutil.new_evar env sigma (mkArrow c r concl) in let gf = Proofview_monad.goal_with_state (fst @@ destEvar sigma f) state in sigma, f, [gf] in Proofview.Unsafe.tclEVARS sigma <*> Tactics.eapply ~with_classes:false f <*> Proofview.Unsafe.tclGETGOALS >>= begin fun gl -> match k with | Suff -> Proofview.Unsafe.tclSETGOALS (glf @ gl) <*> Proofview.tclFOCUS 1 1 Tactics.reduce_after_refine | Have | HaveTransp -> let ngoals = List.length gl + 1 in Proofview.Unsafe.tclSETGOALS (gl @ glf) <*> Proofview.tclFOCUS ngoals ngoals Tactics.reduce_after_refine end end let basesufftac t = basecuttac Suff t let introstac ipats = tclIPAT ipats let make_ct t = let open CAst in let mkt t = mk_term NoFlag t in let mkl t = (NoFlag, (t, None)) in match Ssrcommon.ssrterm_of_ast_closure_term t with | _, (_, Some { loc; v = CCast (ct, DEFAULTcast, cty)}) -> mkt ct, mkt cty, mkt (mkCHole None), loc | _, (_, Some ct) -> mkt ct, mkt (mkCHole None), mkt (mkCHole None), None | _, (t, None) -> begin match DAst.get t with | GCast (ct, DEFAULTcast, cty) -> mkl ct, mkl cty, mkl mkRHole, t.CAst.loc | _ -> mkl t, mkl mkRHole, mkl mkRHole, None end let drop_state = let map gl = Proofview.with_empty_state (Proofview.drop_state gl) in Proofview.Unsafe.tclGETGOALS >>= fun gls -> Proofview.Unsafe.tclSETGOALS (List.map map gls) let set_state s = let map gl = Proofview.goal_with_state (Proofview.drop_state gl) s in Proofview.Unsafe.tclGETGOALS >>= fun gls -> Proofview.Unsafe.tclSETGOALS (List.map map gls) let assert_is_conv (ctx, concl) = Proofview.Goal.enter begin fun gl -> Proofview.tclORELSE (convert_concl ~check:true (EConstr.it_mkProd_or_LetIn concl ctx)) (fun _ -> Tacticals.tclZEROMSG (str "Given proof term is not of type " ++ pr_econstr_env (Tacmach.pf_env gl) (Tacmach.project gl) (EConstr.mkArrow (EConstr.mkVar (Id.of_string "_")) Sorts.Relevant concl))) end let push_goals gs = Proofview.Goal.enter begin fun gl -> let gstate = Proofview.Goal.state gl in let map ev = Proofview.goal_with_state ev gstate in Proofview.Unsafe.tclSETGOALS (List.map map (gs @ [Proofview.Goal.goal gl])) end let havetac ist (transp,((((clr, orig_pats), binders), simpl), (((fk, _), t), hint))) suff namefst = let open Proofview.Notations in Ssrcommon.tacMK_SSR_CONST "abstract_key" >>= fun abstract_key -> Ssrcommon.tacMK_SSR_CONST "abstract" >>= fun abstract -> Proofview.Goal.enter begin fun gl -> let concl = Proofview.Goal.concl gl in let gstate = Proofview.Goal.state gl in let pats = tclCompileIPats orig_pats in let binders = tclCompileIPats binders in let simpl = tclCompileIPats simpl in let skols, pats = List.partition (function IOpAbstractVars _ -> true | _ -> false) pats in let itac_mkabs = introstac skols in let itac_c, clr = match clr with | None -> introstac pats, [] | Some clr -> introstac (tclCompileIPats (IPatClear clr :: orig_pats)), clr in let itac, clr = introstac pats, cleartac clr in let binderstac n = let rec aux = function 0 -> [] | n -> IOpInaccessible None :: aux (n-1) in Tacticals.tclTHEN (if binders <> [] then introstac (aux n) else Tacticals.tclIDTAC) (introstac binders) in let simpltac = introstac simpl in let fixtc = not !ssrhaveNOtcresolution && match fk with FwdHint(_,true) -> false | _ -> true in let hint = hinttac ist true hint in let cuttac t = basecuttac (if transp then HaveTransp else Have) t in let unlock_abs env (idty,args_id) sigma = let sigma, _ = Typing.type_of env sigma idty in unify_HO env sigma args_id.(2) abstract_key in drop_state <*> Tacticals.tclTHENFIRST itac_mkabs (Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let interp sigma rtc t = abs_ssrterm ~resolve_typeclasses:rtc ist env sigma t in let ct, cty, hole, loc = make_ct t in let sigma, cut, itac1, itac2 = match fk, namefst, suff with | FwdHave, true, true -> errorstrm (str"Suff have does not accept a proof term") | FwdHave, false, true -> let cty = combineCG cty hole (mkCArrow ?loc) mkRArrow in let sigma, t, _ = interp sigma false (combineCG ct cty (mkCCast ?loc) mkRCast) in let sigma, ty = Typing.type_of env sigma t in let ctx, _ = EConstr.decompose_prod_n_decls sigma 1 ty in sigma, ty, assert_is_conv (ctx, concl) <*> Tactics.apply t, itac_c | FwdHave, false, false -> let skols = List.flatten (List.map (function | IOpAbstractVars ids -> ids | _ -> assert false) skols) in let skols_args = Ssripats.Internal.examine_abstract env sigma (EConstr.mkVar id)) skols in let sigma = List.fold_right (unlock_abs env) skols_args sigma in let sigma, t, n_evars = interp sigma false (combineCG ct cty (mkCCast ?loc) mkRCast) in if skols <> [] && n_evars <> 0 then CErrors.user_err (Pp.strbrk @@ "Automatic generalization of unresolved implicit "^ "arguments together with abstract variables is "^ "not supported"); let gs = List.map (fun (_,a) -> Ssripats.Internal.find_abstract_proof env sigma false a.(1)) skols_args in let tacopen_skols = push_goals gs in let sigma, ty = Typing.type_of env sigma t in sigma, ty, Tactics.apply t, itac_c <*> simpltac <*> tacopen_skols <*> unfold [abstract; abstract_key] | _,true,true -> let sigma, _, ty, _ = pf_interp_ty ~resolve_typeclasses:fixtc env sigma ist cty in sigma, EConstr.mkArrow ty Sorts.Relevant concl, hint <*> itac, clr | _,false,true -> let sigma, _, ty, _ = pf_interp_ty ~resolve_typeclasses:fixtc env sigma ist cty in sigma, EConstr.mkArrow ty Sorts.Relevant concl, hint, itac_c | _, false, false -> let sigma, n, cty, _ = pf_interp_ty ~resolve_typeclasses:fixtc env sigma ist cty in sigma, cty, (binderstac n) <*> hint, Tacticals.tclTHEN itac_c simpltac | _, true, false -> assert false in Proofview.Unsafe.tclEVARS sigma <*> Tacticals.tclTHENS (cuttac cut) [ itac1; itac2 ] end) <*> set_state gstate end let destProd_or_LetIn sigma c = match EConstr.kind sigma c with | Prod (n,ty,c) -> RelDecl.LocalAssum (n, ty), c | LetIn (n,bo,ty,c) -> RelDecl.LocalDef (n, bo, ty), c | _ -> raise DestKO let wlogtac ist (((clr0, pats),_),_) (gens, ((_, ct))) hint suff ghave = Proofview.Goal.enter begin fun gl -> let env = Proofview.Goal.env gl in let sigma = Proofview.Goal.sigma gl in let concl = Proofview.Goal.concl gl in let clr0 = Option.default [] clr0 in let pats = tclCompileIPats pats in let mkclr gen clrs = clr_of_wgen gen clrs in let mkpats = function | _, Some ((x, _), _) -> fun pats -> IOpId (hoi_id x) :: pats | _ -> fun x -> x in let ct = match Ssrcommon.ssrterm_of_ast_closure_term ct with | (a, (b, Some ct)) -> begin match ct.CAst.v with | CCast (_, DEFAULTcast, cty) -> a, (b, Some cty) | _ -> anomaly "wlog: ssr cast hole deleted by typecheck" end | (a, (t, None)) -> begin match DAst.get t with | GCast (_, DEFAULTcast, cty) -> a, (cty, None) | _ -> anomaly "wlog: ssr cast hole deleted by typecheck" end in let cut_implies_goal = not (suff || ghave <> `NoGen) in let c, args, ct, sigma = let gens = List.filter (function _, Some _ -> true | _ -> false) gens in let c = EConstr.mkProp in let c = if cut_implies_goal then EConstr.mkArrow c Sorts.Relevant concl else c in let mkabs gen (sigma, args, c) = abs_wgen env sigma false (fun x -> x) gen (args, c) in let sigma, args, c = List.fold_right mkabs gens (sigma, [], c) in let env, _ = List.fold_left (fun (env, c) _ -> let rd, c = destProd_or_LetIn sigma c in EConstr.push_rel rd env, c) (env, c) gens in let sigma, _, ct, _ = pf_interp_ty env sigma ist ct in let rec var2rel c g s = match EConstr.kind sigma c, g with | Prod({binder_name=Anonymous} as x,_,c), [] -> EConstr.mkProd(x, EConstr.Vars.subst_vars sigma s ct, c) | Sort _, [] -> EConstr.Vars.subst_vars sigma s ct | LetIn({binder_name=Name id} as n,b,ty,c), _::g -> EConstr.mkLetIn (n,b,ty,var2rel c g (id::s)) | Prod({binder_name=Name id} as n,ty,c), _::g -> EConstr.mkProd (n,ty,var2rel c g (id::s)) | _ -> CErrors.anomaly(str"SSR: wlog: var2rel: " ++ pr_econstr_env env sigma c) in let c = var2rel c gens [] in let rec pired c = function | [] -> c | t::ts as args -> match EConstr.kind sigma c with | Prod(_,_,c) -> pired (EConstr.Vars.subst1 t c) ts | LetIn(id,b,ty,c) -> EConstr.mkLetIn (id,b,ty,pired c args) | _ -> CErrors.anomaly(str"SSR: wlog: pired: " ++ pr_econstr_env env sigma c) in c, args, pired c args, sigma in let tacipat pats = introstac pats in let tacigens = Tacticals.tclTHEN (Tacticals.tclTHENLIST(List.rev(List.fold_right mkclr gens [cleartac clr0]))) (introstac (List.fold_right mkpats gens [])) in let hinttac = hinttac ist true hint in let cut_kind, fst_goal_tac, snd_goal_tac = match suff, ghave with | true, `NoGen -> Suff, Tacticals.tclTHEN hinttac (tacipat pats), tacigens | false, `NoGen -> Suff, hinttac, Tacticals.tclTHEN tacigens (tacipat pats) | true, `Gen _ -> assert false | false, `Gen id -> if gens = [] then errorstrm(str"gen have requires some generalizations"); let clear0 = cleartac clr0 in let id, name_general_hyp, cleanup, pats = match id, pats with | None, (IOpId id as ip)::pats -> Some id, tacipat [ip], clear0, pats | None, _ -> None, Tacticals.tclIDTAC, clear0, pats | Some (Some id),_ -> Some id, introid id, clear0, pats | Some _,_ -> let id = mk_anon_id "tmp" (Tacmach.pf_ids_of_hyps gl) in Some id, introid id, Tacticals.tclTHEN clear0 (Tactics.clear [id]), pats in let tac_specialize = match id with | None -> Tacticals.tclIDTAC | Some id -> if pats = [] then Tacticals.tclIDTAC else let args = Array.of_list args in debug_ssr (fun () -> str"specialized="++ pr_econstr_env env sigma EConstr.(mkApp (mkVar id,args))); debug_ssr (fun () -> str"specialized_ty="++ pr_econstr_env env sigma ct); Tacticals.tclTHENS (basecuttac Have ct) [Tactics.apply EConstr.(mkApp (mkVar id,args)); Tacticals.tclIDTAC] in Have, (if hint = nohint then tacigens else hinttac), Tacticals.tclTHENLIST [name_general_hyp; tac_specialize; tacipat pats; cleanup] in Proofview.Unsafe.tclEVARS sigma <*> Tacticals.tclTHENS (basecuttac cut_kind c) [fst_goal_tac; snd_goal_tac] end open Proofview.Notations let sufftac ist ((((clr, pats),binders),simpl), ((_, c), hint)) = let clr = Option.default [] clr in let pats = tclCompileIPats pats in let binders = tclCompileIPats binders in let simpl = tclCompileIPats simpl in let htac = Tacticals.tclTHEN (introstac pats) (hinttac ist true hint) in let c = match Ssrcommon.ssrterm_of_ast_closure_term c with | (a, (b, Some ct)) -> begin match ct.CAst.v with | CCast (_, DEFAULTcast, cty) -> a, (b, Some cty) | _ -> anomaly "suff: ssr cast hole deleted by typecheck" end | (a, (t, None)) -> begin match DAst.get t with | GCast (_, DEFAULTcast, cty) -> a, (cty, None) | _ -> anomaly "suff: ssr cast hole deleted by typecheck" end in let ctac = let open Tacmach in Proofview.Goal.enter begin fun gl -> let sigma, _, ty, _ = pf_interp_ty (pf_env gl) (project gl) ist c in Proofview.Unsafe.tclEVARS sigma <*> basesufftac ty end in Tacticals.tclTHENS ctac [htac; Tacticals.tclTHEN (cleartac clr) (introstac (binders@simpl))] let is_app_evar sigma t = match EConstr.kind sigma t with | Constr.Evar _ -> true | Constr.App(t,_) -> begin match EConstr.kind sigma t with | Constr.Evar _ -> true | _ -> false end | _ -> false let rec ncons n e = match n with | 0 -> [] | n when n > 0 -> e :: ncons (n - 1) e | _ -> failwith "ncons" let intro_lock ipats = let hnf' = Proofview.numgoals >>= fun ng -> Proofview.tclDISPATCH (ncons (ng - 1) ssrsmovetac @ [Proofview.tclUNIT ()]) in let protect_subgoal env sigma hd args = Ssrcommon.tacMK_SSR_CONST "Under_rel" >>= fun under_rel -> Ssrcommon.tacMK_SSR_CONST "Under_rel_from_rel" >>= fun under_from_rel -> Tactics.refine ~typecheck:true (fun sigma -> let lm2 = Array.length args - 2 in let sigma, carrier = Typing.type_of env sigma args.(lm2) in let rel = EConstr.mkApp (hd, Array.sub args 0 lm2) in let rel_args = Array.sub args lm2 2 in let under_rel_args = Array.append [|carrier; rel|] rel_args in let ty = EConstr.mkApp (under_rel, under_rel_args) in let sigma, t = Evarutil.new_evar env sigma ty in sigma, EConstr.mkApp(under_from_rel,Array.append under_rel_args [|t|])) in let rec lock_eq () : unit Proofview.tactic = Proofview.Goal.enter begin fun _ -> Proofview.tclORELSE (Ssripats.tclIPAT [Ssripats.IOpTemporay; Ssripats.IOpEqGen (lock_eq ())]) (fun _exn -> Proofview.Goal.enter begin fun gl -> let c = Proofview.Goal.concl gl in let sigma = Proofview.Goal.sigma gl in let env = Proofview.Goal.env gl in let open EConstr in match kind_of_type sigma c with | AtomicType(hd, args) when Array.length args >= 2 && is_app_evar sigma (Array.last args) && Ssrequality.ssr_is_setoid env sigma hd args || Ssrcommon.is_const_ref env sigma hd (Coqlib.lib_ref "core.iff.type") && Array.length args = 2 && is_app_evar sigma args.(1) -> protect_subgoal env sigma hd args | _ -> let t = Reductionops.whd_all env sigma c in match kind_of_type sigma t with | AtomicType(hd, args) when Ssrcommon.is_ind_ref env sigma hd (Coqlib.lib_ref "core.eq.type") && Array.length args = 3 && is_app_evar sigma args.(2) -> protect_subgoal env sigma hd args | _ -> debug_ssr (fun () -> Pp.(str"under: stop:" ++ pr_econstr_env env sigma t)); Proofview.tclUNIT () end) end in hnf' <*> Ssripats.tclIPATssr ipats <*> lock_eq () let pretty_rename evar_map term varnames = let rec aux term vars = try match vars with | [] -> term | Names.Name.Anonymous :: varnames -> let name, types, body = EConstr.destLambda evar_map term in let res = aux body varnames in EConstr.mkLambda (name, types, res) | Names.Name.Name _ as name :: varnames -> let { Context.binder_relevance = r }, types, body = EConstr.destLambda evar_map term in let res = aux body varnames in EConstr.mkLambda (Context.make_annot name r, types, res) with DestKO -> term in aux term varnames let overtac = ssr_n_tac "over" ~-1 let check_numgoals ?(minus = 0) nh = Proofview.numgoals >>= fun ng -> if nh <> ng then let errmsg = str"Incorrect number of tactics" ++ spc() ++ str"(expected "++int (ng - minus)++str(String.plural ng " tactic") ++ str", was given "++ int (nh - minus)++str")." in CErrors.user_err errmsg else Proofview.tclUNIT () let undertac ?(pad_intro = false) ist ipats ((dir,_),_ as rule) hint = let nh = List.length (snd hint) + (if hint = nullhint then 2 else 1) in let varnames = let rec aux acc = function | IPatId id :: rest -> aux (Names.Name.Name id :: acc) rest | IPatClear _ :: rest -> aux acc rest | IPatSimpl _ :: rest -> aux acc rest | IPatAnon (One _ | Drop) :: rest -> aux (Names.Name.Anonymous :: acc) rest | _ -> List.rev acc in aux [] @@ match ipats with | None -> [] | Some (IPatCase(Regular (l :: _)) :: _) -> l | Some l -> l in let ipats = match ipats with | None -> [IPatNoop] typically , ipats = Some [ IPatAnon All ] let new_l = ncons (nh - 1) l in [IPatCase(Regular (new_l @ [[]]))] | Some (IPatCase(Regular []) :: _ as ipats) -> ipats : is the previous line correct / useful ? | Some (IPatCase(Regular l) :: rest) -> IPatCase(Regular(l @ [[]])) :: rest | Some (IPatCase(Block _) :: _ as l) -> l | Some l -> [IPatCase(Regular [l;[]])] in let map_redex env evar_map ~before:_ ~after:t = debug_ssr (fun () -> Pp.(str"under vars: " ++ prlist Names.Name.print varnames)); let evar_map, ty = Typing.type_of env evar_map t in try begin match EConstr.destApp evar_map t with (f, ar) -> let lam = Array.last ar in debug_ssr(fun () -> Pp.(str"under: mapping:" ++ pr_econstr_env env evar_map lam)); let new_lam = pretty_rename evar_map lam varnames in let new_ar, len1 = Array.copy ar, pred (Array.length ar) in new_ar.(len1) <- new_lam; EConstr.mkApp (f, new_ar) end with | DestKO -> debug_ssr (fun () -> Pp.(str"under: cannot pretty-rename bound variables with destApp")); t in debug_ssr (fun () -> Pp.(str"under: to:" ++ pr_econstr_env env evar_map new_t)); evar_map, new_t in let undertacs = if hint = nohint then Proofview.tclUNIT () else let betaiota = Tactics.reduct_in_concl ~cast:false ~check:false (Reductionops.nf_betaiota, DEFAULTcast) in check_numgoals ~minus:1 nh <*> Proofview.tclDISPATCH ((List.map (function None -> overtac | Some e -> ssrevaltac ist e <*> overtac) (if hint = nullhint then [None] else snd hint)) @ [betaiota]) in let rew = Ssrequality.ssrrewritetac ~under:true ~map_redex ist [rule] in rew <*> intro_lock ipats <*> undertacs
12aa35706263c0a80a55e11cb587a20b10591ac2e00295470863f15271e16248
ocaml/ocaml-re
pcre.mli
type regexp = Core.re type flag = [ `CASELESS | `MULTILINE | `ANCHORED ] type groups = Core.Group.t (** Result of a {!Pcre.full_split} *) type split_result = | Text of string (** Text part of splitted string *) | Delim of string (** Delimiter part of splitted string *) | Group of int * string (** Subgroup of matched delimiter (subgroup_nr, subgroup_str) *) | NoGroup (** Unmatched subgroup *) val re : ?flags:(flag list) -> string -> Core.t * [ re ~flags s ] creates the regexp [ s ] using the pcre syntax . val regexp : ?flags:(flag list) -> string -> regexp * [ re ~flags s ] compiles the regexp [ s ] using the pcre syntax . val extract : rex:regexp -> string -> string array (** [extract ~rex s] executes [rex] on [s] and returns the matching groups. *) val exec : rex:regexp -> ?pos:int -> string -> groups (** Equivalent to {!Core.exec}. *) val get_substring : groups -> int -> string (** Equivalent to {!Core.Group.get}. *) val get_substring_ofs : groups -> int -> int * int (** Equivalent to {!Core.Group.offset}. *) val pmatch : rex:regexp -> string -> bool (** Equivalent to {!Core.execp}. *) val substitute : rex:Core.re -> subst:(string -> string) -> string -> string val full_split : ?max:int -> rex:regexp -> string -> split_result list val split : rex:regexp -> string -> string list val quote : string -> string * { 2 Deprecated } type substrings = Group.t
null
https://raw.githubusercontent.com/ocaml/ocaml-re/09c2745a2d8d1517b3d597396e82e122903b0017/lib/pcre.mli
ocaml
* Result of a {!Pcre.full_split} * Text part of splitted string * Delimiter part of splitted string * Subgroup of matched delimiter (subgroup_nr, subgroup_str) * Unmatched subgroup * [extract ~rex s] executes [rex] on [s] and returns the matching groups. * Equivalent to {!Core.exec}. * Equivalent to {!Core.Group.get}. * Equivalent to {!Core.Group.offset}. * Equivalent to {!Core.execp}.
type regexp = Core.re type flag = [ `CASELESS | `MULTILINE | `ANCHORED ] type groups = Core.Group.t type split_result = val re : ?flags:(flag list) -> string -> Core.t * [ re ~flags s ] creates the regexp [ s ] using the pcre syntax . val regexp : ?flags:(flag list) -> string -> regexp * [ re ~flags s ] compiles the regexp [ s ] using the pcre syntax . val extract : rex:regexp -> string -> string array val exec : rex:regexp -> ?pos:int -> string -> groups val get_substring : groups -> int -> string val get_substring_ofs : groups -> int -> int * int val pmatch : rex:regexp -> string -> bool val substitute : rex:Core.re -> subst:(string -> string) -> string -> string val full_split : ?max:int -> rex:regexp -> string -> split_result list val split : rex:regexp -> string -> string list val quote : string -> string * { 2 Deprecated } type substrings = Group.t
251113df33377cc8b2f0d26112080c695881703d8d1bb3809d260c97d574b82e
moby/datakit
cI_output.mli
type saved = { title : string; commit : string; branch : string; failed : bool; mutable rebuild : [ `Rebuildable of unit Lwt.t Lazy.t | `Rebuilding | `Archived ]; } type logs = | Empty | Live of CI_live_log.t | Saved of saved | Pair of logs * logs type 'a t = 'a CI_result.t * logs val result : 'a t -> 'a CI_result.t val logs : 'a t -> logs val status : _ t -> [ `Success | `Pending | `Failure ] val descr : string t -> string val equal : string t -> string t -> bool (** [equal a b] is [true] iff [a] and [b] are equal for the purposes of saving the output metadata to disk. i.e. they have the same JSON representation. *) val json_of : string t -> Yojson.Basic.t val of_json : Yojson.Basic.t -> string t val pp : 'a Fmt.t -> 'a t Fmt.t
null
https://raw.githubusercontent.com/moby/datakit/e047e55a2dfa3aaec02398d7d7699f4f7afd2b47/ci/src/cI_output.mli
ocaml
* [equal a b] is [true] iff [a] and [b] are equal for the purposes of saving the output metadata to disk. i.e. they have the same JSON representation.
type saved = { title : string; commit : string; branch : string; failed : bool; mutable rebuild : [ `Rebuildable of unit Lwt.t Lazy.t | `Rebuilding | `Archived ]; } type logs = | Empty | Live of CI_live_log.t | Saved of saved | Pair of logs * logs type 'a t = 'a CI_result.t * logs val result : 'a t -> 'a CI_result.t val logs : 'a t -> logs val status : _ t -> [ `Success | `Pending | `Failure ] val descr : string t -> string val equal : string t -> string t -> bool val json_of : string t -> Yojson.Basic.t val of_json : Yojson.Basic.t -> string t val pp : 'a Fmt.t -> 'a t Fmt.t
3aec7e401857aa74637bac1e62e6225936ca0715a5f69cd8fca72037212e6ec3
racket/eopl
main.rkt
#lang racket/base (require "eopl.rkt") ; provides `provide' (provide (all-from-out "eopl.rkt"))
null
https://raw.githubusercontent.com/racket/eopl/43575d6e95dc34ca6e49b305180f696565e16e0f/main.rkt
racket
provides `provide'
#lang racket/base (provide (all-from-out "eopl.rkt"))
36f223774711806c891ac940f52a91f5ef2cd90b06564b337659059081a063a7
xu-hao/QueryArrow
PostgreSQL.hs
# LANGUAGE GADTs , FlexibleInstances , MultiParamTypeClasses , OverloadedStrings , TypeFamilies , DeriveGeneric , OverloadedStrings # module QueryArrow.SQL.LibPQ.PostgreSQL where import QueryArrow.DB.DB import QueryArrow.DB.GenericDatabase import QueryArrow.SQL.Mapping import QueryArrow.Config import QueryArrow.SQL.SQL import Data.Aeson import GHC.Generics import QueryArrow.Plugin import QueryArrow.DB.AbstractDatabaseList import Data.Maybe import Data.IORef import Data.Monoid ((<>)) import Data.ByteString.Char8 (pack, ByteString) import QueryArrow.SQL.LibPQ import Database.PostgreSQL.LibPQ newtype PostgreSQLDB = PostgreSQLDB PostgreSQLDBConfig instance IDatabase2 (GenericDatabase SQLTrans PostgreSQLDB) where newtype ConnectionType (GenericDatabase SQLTrans PostgreSQLDB) = P LibPQDBConnection dbOpen (GenericDatabase _ (PostgreSQLDB ps) _ _) = do conn <- connectdb ("host=" <> pack (db_host ps) <> " port=" <> pack (show (db_port ps)) <> " dbname=" <> pack (db_name ps) <> " user=" <> pack (db_username ps) <> " password=" <> pack (db_password ps)) sid <- newIORef 0 return (P (LibPQDBConnection conn (db_two_phase_commit ps) sid)) instance IDBConnection0 (ConnectionType (GenericDatabase SQLTrans PostgreSQLDB)) where dbBegin (P conn) = dbBegin conn dbPrepare (P conn) = dbPrepare conn dbRollback (P conn) = dbRollback conn dbCommit (P conn) = dbCommit conn dbClose (P conn) = dbClose conn instance IDBConnection (ConnectionType (GenericDatabase SQLTrans PostgreSQLDB)) where type QueryType (ConnectionType (GenericDatabase SQLTrans PostgreSQLDB)) = QueryType LibPQDBConnection type StatementType (ConnectionType (GenericDatabase SQLTrans PostgreSQLDB)) = StatementType LibPQDBConnection prepareQuery (P conn) = prepareQuery conn instance IDatabase (GenericDatabase SQLTrans PostgreSQLDB) where instance FromJSON PostgreSQLDBConfig instance ToJSON PostgreSQLDBConfig data PostgreSQLDBConfig = PostgreSQLDBConfig { db_name :: String, db_namespace :: String, db_host :: String, db_password :: String, db_port :: Int, db_username :: String, db_predicates :: String, db_sql_mapping :: String, db_two_phase_commit :: Bool } deriving (Show, Generic) data PostgreSQLPlugin = PostgreSQLPlugin instance Plugin PostgreSQLPlugin MapResultRow where getDB _ _ ps = do let fsconf = getDBSpecificConfig ps db <- makeICATSQLDBAdapter (db_namespace fsconf) (db_predicates fsconf) (db_sql_mapping fsconf) (Just "nextid") (PostgreSQLDB fsconf) return (AbstractDatabase db)
null
https://raw.githubusercontent.com/xu-hao/QueryArrow/4dd5b8a22c8ed2d24818de5b8bcaa9abc456ef0d/QueryArrow-db-sql-libpq-postgresql/src/QueryArrow/SQL/LibPQ/PostgreSQL.hs
haskell
# LANGUAGE GADTs , FlexibleInstances , MultiParamTypeClasses , OverloadedStrings , TypeFamilies , DeriveGeneric , OverloadedStrings # module QueryArrow.SQL.LibPQ.PostgreSQL where import QueryArrow.DB.DB import QueryArrow.DB.GenericDatabase import QueryArrow.SQL.Mapping import QueryArrow.Config import QueryArrow.SQL.SQL import Data.Aeson import GHC.Generics import QueryArrow.Plugin import QueryArrow.DB.AbstractDatabaseList import Data.Maybe import Data.IORef import Data.Monoid ((<>)) import Data.ByteString.Char8 (pack, ByteString) import QueryArrow.SQL.LibPQ import Database.PostgreSQL.LibPQ newtype PostgreSQLDB = PostgreSQLDB PostgreSQLDBConfig instance IDatabase2 (GenericDatabase SQLTrans PostgreSQLDB) where newtype ConnectionType (GenericDatabase SQLTrans PostgreSQLDB) = P LibPQDBConnection dbOpen (GenericDatabase _ (PostgreSQLDB ps) _ _) = do conn <- connectdb ("host=" <> pack (db_host ps) <> " port=" <> pack (show (db_port ps)) <> " dbname=" <> pack (db_name ps) <> " user=" <> pack (db_username ps) <> " password=" <> pack (db_password ps)) sid <- newIORef 0 return (P (LibPQDBConnection conn (db_two_phase_commit ps) sid)) instance IDBConnection0 (ConnectionType (GenericDatabase SQLTrans PostgreSQLDB)) where dbBegin (P conn) = dbBegin conn dbPrepare (P conn) = dbPrepare conn dbRollback (P conn) = dbRollback conn dbCommit (P conn) = dbCommit conn dbClose (P conn) = dbClose conn instance IDBConnection (ConnectionType (GenericDatabase SQLTrans PostgreSQLDB)) where type QueryType (ConnectionType (GenericDatabase SQLTrans PostgreSQLDB)) = QueryType LibPQDBConnection type StatementType (ConnectionType (GenericDatabase SQLTrans PostgreSQLDB)) = StatementType LibPQDBConnection prepareQuery (P conn) = prepareQuery conn instance IDatabase (GenericDatabase SQLTrans PostgreSQLDB) where instance FromJSON PostgreSQLDBConfig instance ToJSON PostgreSQLDBConfig data PostgreSQLDBConfig = PostgreSQLDBConfig { db_name :: String, db_namespace :: String, db_host :: String, db_password :: String, db_port :: Int, db_username :: String, db_predicates :: String, db_sql_mapping :: String, db_two_phase_commit :: Bool } deriving (Show, Generic) data PostgreSQLPlugin = PostgreSQLPlugin instance Plugin PostgreSQLPlugin MapResultRow where getDB _ _ ps = do let fsconf = getDBSpecificConfig ps db <- makeICATSQLDBAdapter (db_namespace fsconf) (db_predicates fsconf) (db_sql_mapping fsconf) (Just "nextid") (PostgreSQLDB fsconf) return (AbstractDatabase db)
11446557c7bf80203db26a9162549e042201742d08e36988abdb812cf4d56bd4
simingwang/emqx-plugin-kafkav5
tls_sender.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2018 - 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(tls_sender). -behaviour(gen_statem). -include("ssl_internal.hrl"). -include("ssl_alert.hrl"). -include("ssl_handshake.hrl"). -include("ssl_api.hrl"). -include("ssl_record.hrl"). -include("tls_handshake_1_3.hrl"). %% API -export([start_link/0, start_link/1, initialize/2, send_data/2, send_post_handshake/2, send_alert/2, send_and_ack_alert/2, setopts/2, renegotiate/1, peer_renegotiate/1, downgrade/2, update_connection_state/3, dist_tls_socket/1, dist_handshake_complete/3]). %% gen_statem callbacks -export([callback_mode/0, init/1, terminate/3, code_change/4]). -export([init/3, connection/3, handshake/3, death_row/3]). -record(static, {connection_pid, role, socket, socket_options, erl_dist, trackers, transport_cb, negotiated_version, renegotiate_at, key_update_at, %% TLS 1.3 bytes_sent, %% TLS 1.3 dist_handle, log_level }). -record(data, {static = #static{}, connection_states = #{} }). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- -spec start_link() -> {ok, Pid :: pid()} | ignore | {error, Error :: term()}. -spec start_link(list()) -> {ok, Pid :: pid()} | ignore | {error, Error :: term()}. %% Description: Start sender process to avoid dead lock that %% may happen when a socket is busy (busy port) and the %% same process is sending and receiving %%-------------------------------------------------------------------- start_link() -> gen_statem:start_link(?MODULE, [], []). start_link(SpawnOpts) -> gen_statem:start_link(?MODULE, [], SpawnOpts). %%-------------------------------------------------------------------- -spec initialize(pid(), map()) -> ok. %% Description: So TLS connection process can initialize it sender %% process. %%-------------------------------------------------------------------- initialize(Pid, InitMsg) -> gen_statem:call(Pid, {self(), InitMsg}). %%-------------------------------------------------------------------- -spec send_data(pid(), iodata()) -> ok | {error, term()}. %% Description: Send application data %%-------------------------------------------------------------------- send_data(Pid, AppData) -> %% Needs error handling for external API call(Pid, {application_data, AppData}). %%-------------------------------------------------------------------- -spec send_post_handshake(pid(), #key_update{}) -> ok | {error, term()}. %% Description: Send post handshake data %%-------------------------------------------------------------------- send_post_handshake(Pid, HandshakeData) -> call(Pid, {post_handshake_data, HandshakeData}). %%-------------------------------------------------------------------- -spec send_alert(pid(), #alert{}) -> _. %% Description: TLS connection process wants to send an Alert %% in the connection state. %%-------------------------------------------------------------------- send_alert(Pid, Alert) -> gen_statem:cast(Pid, Alert). %%-------------------------------------------------------------------- -spec send_and_ack_alert(pid(), #alert{}) -> _. %% Description: TLS connection process wants to send an Alert %% in the connection state and receive an ack. %%-------------------------------------------------------------------- send_and_ack_alert(Pid, Alert) -> gen_statem:call(Pid, {ack_alert, Alert}, ?DEFAULT_TIMEOUT). %%-------------------------------------------------------------------- -spec setopts(pid(), [{packet, integer() | atom()}]) -> ok | {error, term()}. %% Description: Send application data %%-------------------------------------------------------------------- setopts(Pid, Opts) -> call(Pid, {set_opts, Opts}). %%-------------------------------------------------------------------- -spec renegotiate(pid()) -> {ok, WriteState::map()} | {error, closed}. %% Description: So TLS connection process can synchronize the %% encryption state to be used when handshaking. %%-------------------------------------------------------------------- renegotiate(Pid) -> %% Needs error handling for external API call(Pid, renegotiate). %%-------------------------------------------------------------------- -spec peer_renegotiate(pid()) -> {ok, WriteState::map()} | {error, term()}. %% Description: So TLS connection process can synchronize the %% encryption state to be used when handshaking. %%-------------------------------------------------------------------- peer_renegotiate(Pid) -> gen_statem:call(Pid, renegotiate, ?DEFAULT_TIMEOUT). %%-------------------------------------------------------------------- -spec update_connection_state(pid(), WriteState::map(), tls_record:tls_version()) -> ok. %% Description: So TLS connection process can synchronize the %% encryption state to be used when sending application data. %%-------------------------------------------------------------------- update_connection_state(Pid, NewState, Version) -> gen_statem:cast(Pid, {new_write, NewState, Version}). %%-------------------------------------------------------------------- -spec downgrade(pid(), integer()) -> {ok, ssl_record:connection_state()} | {error, timeout}. %% Description: So TLS connection process can synchronize the %% encryption state to be used when sending application data. %%-------------------------------------------------------------------- downgrade(Pid, Timeout) -> try gen_statem:call(Pid, downgrade, Timeout) of Result -> Result catch _:_ -> {error, timeout} end. %%-------------------------------------------------------------------- -spec dist_handshake_complete(pid(), node(), term()) -> ok. %% Description: Erlang distribution callback %%-------------------------------------------------------------------- dist_handshake_complete(ConnectionPid, Node, DHandle) -> gen_statem:call(ConnectionPid, {dist_handshake_complete, Node, DHandle}). %%-------------------------------------------------------------------- -spec dist_tls_socket(pid()) -> {ok, #sslsocket{}}. %% Description: To enable distribution startup to get a proper "#sslsocket{}" %%-------------------------------------------------------------------- dist_tls_socket(Pid) -> gen_statem:call(Pid, dist_get_tls_socket). %%%=================================================================== %%% gen_statem callbacks %%%=================================================================== %%-------------------------------------------------------------------- -spec callback_mode() -> gen_statem:callback_mode_result(). %%-------------------------------------------------------------------- callback_mode() -> state_functions. %%-------------------------------------------------------------------- -spec init(Args :: term()) -> gen_statem:init_result(atom()). %%-------------------------------------------------------------------- init(_) -> %% As this process is now correctly supervised %% together with the connection process and the significant %% child mechanism we want to handle supervisor shutdown %% to achieve a normal shutdown avoiding SASL reports. process_flag(trap_exit, true), {ok, init, #data{}}. %%-------------------------------------------------------------------- -spec init(gen_statem:event_type(), Msg :: term(), StateData :: term()) -> gen_statem:event_handler_result(atom()). %%-------------------------------------------------------------------- init({call, From}, {Pid, #{current_write := WriteState, role := Role, socket := Socket, socket_options := SockOpts, erl_dist := IsErlDist, trackers := Trackers, transport_cb := Transport, negotiated_version := Version, renegotiate_at := RenegotiateAt, key_update_at := KeyUpdateAt, log_level := LogLevel}}, #data{connection_states = ConnectionStates, static = Static0} = StateData0) -> StateData = StateData0#data{connection_states = ConnectionStates#{current_write => WriteState}, static = Static0#static{connection_pid = Pid, role = Role, socket = Socket, socket_options = SockOpts, erl_dist = IsErlDist, trackers = Trackers, transport_cb = Transport, negotiated_version = Version, renegotiate_at = RenegotiateAt, key_update_at = KeyUpdateAt, bytes_sent = 0, log_level = LogLevel}}, {next_state, handshake, StateData, [{reply, From, ok}]}; init(info = Type, Msg, StateData) -> handle_common(Type, Msg, StateData); init(_, _, _) -> %% Just in case anything else sneaks through {keep_state_and_data, [postpone]}. %%-------------------------------------------------------------------- -spec connection(gen_statem:event_type(), Msg :: term(), StateData :: term()) -> gen_statem:event_handler_result(atom()). %%-------------------------------------------------------------------- connection({call, From}, {application_data, AppData}, #data{static = #static{socket_options = #socket_options{packet = Packet}}} = StateData) -> case encode_packet(Packet, AppData) of {error, _} = Error -> {next_state, ?FUNCTION_NAME, StateData, [{reply, From, Error}]}; Data -> send_application_data(Data, From, ?FUNCTION_NAME, StateData) end; connection({call, From}, {post_handshake_data, HSData}, StateData) -> send_post_handshake_data(HSData, From, ?FUNCTION_NAME, StateData); connection({call, From}, {ack_alert, #alert{} = Alert}, StateData0) -> StateData = send_tls_alert(Alert, StateData0), {next_state, ?FUNCTION_NAME, StateData, [{reply,From,ok}]}; connection({call, From}, renegotiate, #data{connection_states = #{current_write := Write}} = StateData) -> {next_state, handshake, StateData, [{reply, From, {ok, Write}}]}; connection({call, From}, downgrade, #data{connection_states = #{current_write := Write}} = StateData) -> {next_state, death_row, StateData, [{reply,From, {ok, Write}}]}; connection({call, From}, {set_opts, Opts}, StateData) -> handle_set_opts(From, Opts, StateData); connection({call, From}, dist_get_tls_socket, #data{static = #static{transport_cb = Transport, socket = Socket, connection_pid = Pid, trackers = Trackers}} = StateData) -> TLSSocket = tls_gen_connection:socket([Pid, self()], Transport, Socket, Trackers), {next_state, ?FUNCTION_NAME, StateData, [{reply, From, {ok, TLSSocket}}]}; connection({call, From}, {dist_handshake_complete, _Node, DHandle}, #data{static = #static{connection_pid = Pid} = Static} = StateData) -> false = erlang:dist_ctrl_set_opt(DHandle, get_size, true), ok = erlang:dist_ctrl_input_handler(DHandle, Pid), ok = ssl_gen_statem:dist_handshake_complete(Pid, DHandle), %% From now on we execute on normal priority process_flag(priority, normal), {keep_state, StateData#data{static = Static#static{dist_handle = DHandle}}, [{reply,From,ok}| case dist_data(DHandle) of [] -> []; Data -> [{next_event, internal, {application_packets,{self(),undefined},Data}}] end]}; connection(internal, {application_packets, From, Data}, StateData) -> send_application_data(Data, From, ?FUNCTION_NAME, StateData); connection(internal, {post_handshake_data, From, HSData}, StateData) -> send_post_handshake_data(HSData, From, ?FUNCTION_NAME, StateData); connection(cast, #alert{} = Alert, StateData0) -> StateData = send_tls_alert(Alert, StateData0), {next_state, ?FUNCTION_NAME, StateData}; connection(cast, {new_write, WritesState, Version}, #data{connection_states = ConnectionStates, static = Static} = StateData) -> {next_state, connection, StateData#data{connection_states = ConnectionStates#{current_write => WritesState}, static = Static#static{negotiated_version = Version}}}; %% connection(info, dist_data, #data{static = #static{dist_handle = DHandle}}) -> {keep_state_and_data, case dist_data(DHandle) of [] -> []; Data -> [{next_event, internal, {application_packets,{self(),undefined},Data}}] end}; connection(info, tick, StateData) -> consume_ticks(), Data = [<<0:32>>], % encode_packet(4, <<>>) From = {self(), undefined}, send_application_data(Data, From, ?FUNCTION_NAME, StateData); connection(info, {send, From, Ref, Data}, _StateData) -> %% This is for testing only! %% Needed by some OTP distribution %% test suites... From ! {Ref, ok}, {keep_state_and_data, [{next_event, {call, {self(), undefined}}, {application_data, erlang:iolist_to_iovec(Data)}}]}; connection(Type, Msg, StateData) -> handle_common(Type, Msg, StateData). %%-------------------------------------------------------------------- -spec handshake(gen_statem:event_type(), Msg :: term(), StateData :: term()) -> gen_statem:event_handler_result(atom()). %%-------------------------------------------------------------------- handshake({call, From}, {set_opts, Opts}, StateData) -> handle_set_opts(From, Opts, StateData); handshake({call, _}, _, _) -> Postpone all calls to the connection state {keep_state_and_data, [postpone]}; handshake(internal, {application_packets,_,_}, _) -> {keep_state_and_data, [postpone]}; handshake(cast, {new_write, WriteState, Version}, #data{connection_states = ConnectionStates, static = #static{key_update_at = KeyUpdateAt0} = Static} = StateData) -> KeyUpdateAt = key_update_at(Version, WriteState, KeyUpdateAt0), {next_state, connection, StateData#data{connection_states = ConnectionStates#{current_write => WriteState}, static = Static#static{negotiated_version = Version, key_update_at = KeyUpdateAt}}}; handshake(info, dist_data, _) -> {keep_state_and_data, [postpone]}; handshake(info, tick, _) -> %% Ignore - data is sent anyway during handshake consume_ticks(), keep_state_and_data; handshake(info, {send, _, _, _}, _) -> Testing only , OTP distribution test suites ... {keep_state_and_data, [postpone]}; handshake(Type, Msg, StateData) -> handle_common(Type, Msg, StateData). %%-------------------------------------------------------------------- -spec death_row(gen_statem:event_type(), Msg :: term(), StateData :: term()) -> gen_statem:event_handler_result(atom()). %%-------------------------------------------------------------------- death_row(state_timeout, Reason, _State) -> {stop, {shutdown, Reason}}; death_row(info = Type, Msg, State) -> handle_common(Type, Msg, State); death_row(_Type, _Msg, _State) -> %% Waste all other events keep_state_and_data. %%-------------------------------------------------------------------- -spec terminate(Reason :: term(), State :: term(), Data :: term()) -> any(). %%-------------------------------------------------------------------- terminate(_Reason, _State, _Data) -> void. %%-------------------------------------------------------------------- -spec code_change( OldVsn :: term() | {down,term()}, State :: term(), Data :: term(), Extra :: term()) -> {ok, NewState :: term(), NewData :: term()} | (Reason :: term()). %% Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, Data, _Extra) -> {ok, State, Data}. %%%=================================================================== Internal functions %%%=================================================================== handle_set_opts(From, Opts, #data{static = #static{socket_options = SockOpts} = Static} = StateData) -> {keep_state, StateData#data{static = Static#static{socket_options = set_opts(SockOpts, Opts)}}, [{reply, From, ok}]}. handle_common({call, From}, {set_opts, Opts}, #data{static = #static{socket_options = SockOpts} = Static} = StateData) -> {keep_state, StateData#data{static = Static#static{socket_options = set_opts(SockOpts, Opts)}}, [{reply, From, ok}]}; handle_common(info, {'EXIT', _Sup, shutdown}, #data{static = #static{erl_dist = true}} = StateData) -> %% When the connection is on its way down operations begin to fail . We wait for 5 seconds to receive possible exit signals for one of our links to the other %% involved distribution parties, in which case we want to use %% their exit reason for the connection teardown. {next_state, death_row, StateData, [{state_timeout, 5000, shutdown}]}; handle_common(info, {'EXIT', _Dist, Reason}, #data{static = #static{erl_dist = true}} = StateData) -> {stop, {shutdown, Reason}, StateData}; handle_common(info, {'EXIT', _Sup, shutdown}, StateData) -> {stop, shutdown, StateData}; handle_common(info, Msg, #data{static = #static{log_level = Level}}) -> ssl_logger:log(info, Level, #{event => "TLS sender received unexpected info", reason => [{message, Msg}]}, ?LOCATION), keep_state_and_data; handle_common(Type, Msg, #data{static = #static{log_level = Level}}) -> ssl_logger:log(error, Level, #{event => "TLS sender received unexpected event", reason => [{type, Type}, {message, Msg}]}, ?LOCATION), keep_state_and_data. send_tls_alert(#alert{} = Alert, #data{static = #static{negotiated_version = Version, socket = Socket, transport_cb = Transport, log_level = LogLevel}, connection_states = ConnectionStates0} = StateData0) -> {BinMsg, ConnectionStates} = tls_record:encode_alert_record(Alert, Version, ConnectionStates0), tls_socket:send(Transport, Socket, BinMsg), ssl_logger:debug(LogLevel, outbound, 'record', BinMsg), StateData0#data{connection_states = ConnectionStates}. send_application_data(Data, From, StateName, #data{static = #static{connection_pid = Pid, socket = Socket, dist_handle = DistHandle, negotiated_version = Version, transport_cb = Transport, renegotiate_at = RenegotiateAt, key_update_at = KeyUpdateAt, bytes_sent = BytesSent, log_level = LogLevel}, connection_states = ConnectionStates0} = StateData0) -> case time_to_rekey(Version, Data, ConnectionStates0, RenegotiateAt, KeyUpdateAt, BytesSent) of key_update -> KeyUpdate = tls_handshake_1_3:key_update(update_requested), {keep_state_and_data, [{next_event, internal, {post_handshake_data, From, KeyUpdate}}, {next_event, internal, {key_update, From}}, {next_event, internal, {application_packets, From, Data}}]}; renegotiate -> tls_dtls_connection:internal_renegotiation(Pid, ConnectionStates0), {next_state, handshake, StateData0, [{next_event, internal, {application_packets, From, Data}}]}; chunk_and_key_update -> KeyUpdate = tls_handshake_1_3:key_update(update_requested), %% Prevent infinite loop of key updates {Chunk, Rest} = chunk_data(Data, KeyUpdateAt), {keep_state_and_data, [{next_event, internal, {post_handshake_data, From, KeyUpdate}}, {next_event, internal, {application_packets, From, Chunk}}, {next_event, internal, {application_packets, From, Rest}}]}; false -> {Msgs, ConnectionStates} = tls_record:encode_data(Data, Version, ConnectionStates0), StateData = StateData0#data{connection_states = ConnectionStates}, case tls_socket:send(Transport, Socket, Msgs) of ok when DistHandle =/= undefined -> ssl_logger:debug(LogLevel, outbound, 'record', Msgs), StateData1 = update_bytes_sent(Version, StateData, Data), {next_state, StateName, StateData1, []}; Reason when DistHandle =/= undefined -> {next_state, death_row, StateData, [{state_timeout, 5000, Reason}]}; ok -> ssl_logger:debug(LogLevel, outbound, 'record', Msgs), StateData1 = update_bytes_sent(Version, StateData, Data), {next_state, StateName, StateData1, [{reply, From, ok}]}; Result -> {next_state, StateName, StateData, [{reply, From, Result}]} end end. TLS 1.3 Post Handshake Data send_post_handshake_data(Handshake, From, StateName, #data{static = #static{socket = Socket, dist_handle = DistHandle, negotiated_version = Version, transport_cb = Transport, log_level = LogLevel}, connection_states = ConnectionStates0} = StateData0) -> BinHandshake = tls_handshake:encode_handshake(Handshake, Version), {Encoded, ConnectionStates} = tls_record:encode_handshake(BinHandshake, Version, ConnectionStates0), ssl_logger:debug(LogLevel, outbound, 'handshake', Handshake), StateData1 = StateData0#data{connection_states = ConnectionStates}, case tls_socket:send(Transport, Socket, Encoded) of ok when DistHandle =/= undefined -> ssl_logger:debug(LogLevel, outbound, 'record', Encoded), StateData = maybe_update_cipher_key(StateData1, Handshake), {next_state, StateName, StateData, []}; Reason when DistHandle =/= undefined -> {next_state, death_row, StateData1, [{state_timeout, 5000, Reason}]}; ok -> ssl_logger:debug(LogLevel, outbound, 'record', Encoded), StateData = maybe_update_cipher_key(StateData1, Handshake), {next_state, StateName, StateData, [{reply, From, ok}]}; Result -> {next_state, StateName, StateData1, [{reply, From, Result}]} end. maybe_update_cipher_key(#data{connection_states = ConnectionStates0, static = Static0} = StateData, #key_update{}) -> ConnectionStates = tls_connection_1_3:update_cipher_key(current_write, ConnectionStates0), Static = Static0#static{bytes_sent = 0}, StateData#data{connection_states = ConnectionStates, static = Static}; maybe_update_cipher_key(StateData, _) -> StateData. update_bytes_sent(Version, StateData, _) when Version < {3,4} -> StateData; Count bytes sent in TLS 1.3 for AES - GCM update_bytes_sent(_, #data{static = #static{key_update_at = seq_num_wrap}} = StateData, _) -> Chacha20 - Poly1305 update_bytes_sent(_, #data{static = #static{bytes_sent = Sent} = Static} = StateData, Data) -> StateData#data{static = Static#static{bytes_sent = Sent + iolist_size(Data)}}. %% AES-GCM For AES - GCM , up to 2 ^ 24.5 full - size records ( about 24 million ) may be %% encrypted on a given connection while keeping a safety margin of approximately 2 ^ -57 for Authenticated Encryption ( AE ) security . For ChaCha20 / Poly1305 , the record sequence number would wrap before the %% safety limit is reached. key_update_at(Version, #{security_parameters := #security_parameters{ bulk_cipher_algorithm = CipherAlgo}}, KeyUpdateAt) when Version >= {3,4} -> case CipherAlgo of ?AES_GCM -> KeyUpdateAt; ?CHACHA20_POLY1305 -> seq_num_wrap; ?AES_CCM -> KeyUpdateAt; ?AES_CCM_8 -> KeyUpdateAt end; key_update_at(_, _, KeyUpdateAt) -> KeyUpdateAt. -compile({inline, encode_packet/2}). encode_packet(Packet, Data) -> Len = iolist_size(Data), case Packet of 1 when Len < (1 bsl 8) -> [<<Len:8>>|Data]; 2 when Len < (1 bsl 16) -> [<<Len:16>>|Data]; 4 when Len < (1 bsl 32) -> [<<Len:32>>|Data]; N when N =:= 1; N =:= 2; N =:= 4 -> {error, {badarg, {packet_to_large, Len, (1 bsl (Packet bsl 3)) - 1}}}; _ -> Data end. set_opts(SocketOptions, [{packet, N}]) -> SocketOptions#socket_options{packet = N}. time_to_rekey(Version, _Data, #{current_write := #{sequence_number := ?MAX_SEQUENCE_NUMBER}}, _, _, _) when Version >= {3,4} -> key_update; time_to_rekey(Version, _Data, _, _, seq_num_wrap, _) when Version >= {3,4} -> false; time_to_rekey(Version, Data, _, _, KeyUpdateAt, BytesSent) when Version >= {3,4} -> DataSize = iolist_size(Data), case (BytesSent + DataSize) > KeyUpdateAt of true -> %% Handle special case that causes an invite loop of key updates. case DataSize > KeyUpdateAt of true -> chunk_and_key_update; false -> key_update end; false -> false end; time_to_rekey(_, _Data, #{current_write := #{sequence_number := Num}}, RenegotiateAt, _, _) -> %% We could do test: %% is_time_to_renegotiate((erlang:byte_size(_Data) div ? MAX_PLAIN_TEXT_LENGTH ) + 1 , RenegotiateAt ) , but we chose to %% have a some what lower renegotiateAt and a much cheaper test is_time_to_renegotiate(Num, RenegotiateAt). chunk_data(Data, Size) -> {Chunk, Rest} = split_binary(iolist_to_binary(Data), Size), {[Chunk], [Rest]}. is_time_to_renegotiate(N, M) when N < M-> false; is_time_to_renegotiate(_,_) -> renegotiate. call(FsmPid, Event) -> try gen_statem:call(FsmPid, Event) catch exit:{noproc, _} -> {error, closed}; exit:{normal, _} -> {error, closed}; exit:{shutdown,_} -> {error, closed}; exit:{{shutdown, _},_} -> {error, closed} end. -------------- Erlang distribution helpers ------------------------------ To avoid livelock , dist_data/2 will check for more bytes coming from %% distribution channel, if amount of already collected bytes greater %% or equal than the limit defined below. -define(TLS_BUNDLE_SOFT_LIMIT, 16 * 1024 * 1024). dist_data(DHandle) -> dist_data(DHandle, 0). dist_data(DHandle, CurBytes) -> case erlang:dist_ctrl_get_data(DHandle) of none -> erlang:dist_ctrl_get_data_notification(DHandle), []; This is encode_packet(4 , Data ) without check %% since the emulator will always deliver a Data smaller than 4 GB , and the distribution will %% therefore always have to use {packet,4} {Len, Data} when Len + CurBytes >= ?TLS_BUNDLE_SOFT_LIMIT -> Data is of type ( ) ; lets keep it %% as an iovec()... erlang:dist_ctrl_get_data_notification(DHandle), [<<Len:32>> | Data]; {Len, Data} -> Packet = [<<Len:32>> | Data], case dist_data(DHandle, CurBytes + Len) of [] -> Packet; More -> Packet ++ More end end. %% Empty the inbox from distribution ticks - do not let them accumulate consume_ticks() -> receive tick -> consume_ticks() after 0 -> ok end.
null
https://raw.githubusercontent.com/simingwang/emqx-plugin-kafkav5/bbf919e56dbc8fd2d4c1c541084532f844a11cbc/_build/default/rel/emqx_plugin_kafka/lib/ssl-10.7/src/tls_sender.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% API gen_statem callbacks TLS 1.3 TLS 1.3 =================================================================== API =================================================================== -------------------------------------------------------------------- Description: Start sender process to avoid dead lock that may happen when a socket is busy (busy port) and the same process is sending and receiving -------------------------------------------------------------------- -------------------------------------------------------------------- Description: So TLS connection process can initialize it sender process. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Send application data -------------------------------------------------------------------- Needs error handling for external API -------------------------------------------------------------------- Description: Send post handshake data -------------------------------------------------------------------- -------------------------------------------------------------------- Description: TLS connection process wants to send an Alert in the connection state. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: TLS connection process wants to send an Alert in the connection state and receive an ack. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Send application data -------------------------------------------------------------------- -------------------------------------------------------------------- Description: So TLS connection process can synchronize the encryption state to be used when handshaking. -------------------------------------------------------------------- Needs error handling for external API -------------------------------------------------------------------- Description: So TLS connection process can synchronize the encryption state to be used when handshaking. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: So TLS connection process can synchronize the encryption state to be used when sending application data. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: So TLS connection process can synchronize the encryption state to be used when sending application data. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Erlang distribution callback -------------------------------------------------------------------- -------------------------------------------------------------------- Description: To enable distribution startup to get a proper "#sslsocket{}" -------------------------------------------------------------------- =================================================================== gen_statem callbacks =================================================================== -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- As this process is now correctly supervised together with the connection process and the significant child mechanism we want to handle supervisor shutdown to achieve a normal shutdown avoiding SASL reports. -------------------------------------------------------------------- -------------------------------------------------------------------- Just in case anything else sneaks through -------------------------------------------------------------------- -------------------------------------------------------------------- From now on we execute on normal priority encode_packet(4, <<>>) This is for testing only! test suites... -------------------------------------------------------------------- -------------------------------------------------------------------- Ignore - data is sent anyway during handshake -------------------------------------------------------------------- -------------------------------------------------------------------- Waste all other events -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Convert process state when code is changed -------------------------------------------------------------------- =================================================================== =================================================================== When the connection is on its way down operations involved distribution parties, in which case we want to use their exit reason for the connection teardown. Prevent infinite loop of key updates AES-GCM encrypted on a given connection while keeping a safety margin of safety limit is reached. Handle special case that causes an invite loop of key updates. We could do test: is_time_to_renegotiate((erlang:byte_size(_Data) div have a some what lower renegotiateAt and a much cheaper test distribution channel, if amount of already collected bytes greater or equal than the limit defined below. since the emulator will always deliver a Data therefore always have to use {packet,4} as an iovec()... Empty the inbox from distribution ticks - do not let them accumulate
Copyright Ericsson AB 2018 - 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(tls_sender). -behaviour(gen_statem). -include("ssl_internal.hrl"). -include("ssl_alert.hrl"). -include("ssl_handshake.hrl"). -include("ssl_api.hrl"). -include("ssl_record.hrl"). -include("tls_handshake_1_3.hrl"). -export([start_link/0, start_link/1, initialize/2, send_data/2, send_post_handshake/2, send_alert/2, send_and_ack_alert/2, setopts/2, renegotiate/1, peer_renegotiate/1, downgrade/2, update_connection_state/3, dist_tls_socket/1, dist_handshake_complete/3]). -export([callback_mode/0, init/1, terminate/3, code_change/4]). -export([init/3, connection/3, handshake/3, death_row/3]). -record(static, {connection_pid, role, socket, socket_options, erl_dist, trackers, transport_cb, negotiated_version, renegotiate_at, dist_handle, log_level }). -record(data, {static = #static{}, connection_states = #{} }). -spec start_link() -> {ok, Pid :: pid()} | ignore | {error, Error :: term()}. -spec start_link(list()) -> {ok, Pid :: pid()} | ignore | {error, Error :: term()}. start_link() -> gen_statem:start_link(?MODULE, [], []). start_link(SpawnOpts) -> gen_statem:start_link(?MODULE, [], SpawnOpts). -spec initialize(pid(), map()) -> ok. initialize(Pid, InitMsg) -> gen_statem:call(Pid, {self(), InitMsg}). -spec send_data(pid(), iodata()) -> ok | {error, term()}. send_data(Pid, AppData) -> call(Pid, {application_data, AppData}). -spec send_post_handshake(pid(), #key_update{}) -> ok | {error, term()}. send_post_handshake(Pid, HandshakeData) -> call(Pid, {post_handshake_data, HandshakeData}). -spec send_alert(pid(), #alert{}) -> _. send_alert(Pid, Alert) -> gen_statem:cast(Pid, Alert). -spec send_and_ack_alert(pid(), #alert{}) -> _. send_and_ack_alert(Pid, Alert) -> gen_statem:call(Pid, {ack_alert, Alert}, ?DEFAULT_TIMEOUT). -spec setopts(pid(), [{packet, integer() | atom()}]) -> ok | {error, term()}. setopts(Pid, Opts) -> call(Pid, {set_opts, Opts}). -spec renegotiate(pid()) -> {ok, WriteState::map()} | {error, closed}. renegotiate(Pid) -> call(Pid, renegotiate). -spec peer_renegotiate(pid()) -> {ok, WriteState::map()} | {error, term()}. peer_renegotiate(Pid) -> gen_statem:call(Pid, renegotiate, ?DEFAULT_TIMEOUT). -spec update_connection_state(pid(), WriteState::map(), tls_record:tls_version()) -> ok. update_connection_state(Pid, NewState, Version) -> gen_statem:cast(Pid, {new_write, NewState, Version}). -spec downgrade(pid(), integer()) -> {ok, ssl_record:connection_state()} | {error, timeout}. downgrade(Pid, Timeout) -> try gen_statem:call(Pid, downgrade, Timeout) of Result -> Result catch _:_ -> {error, timeout} end. -spec dist_handshake_complete(pid(), node(), term()) -> ok. dist_handshake_complete(ConnectionPid, Node, DHandle) -> gen_statem:call(ConnectionPid, {dist_handshake_complete, Node, DHandle}). -spec dist_tls_socket(pid()) -> {ok, #sslsocket{}}. dist_tls_socket(Pid) -> gen_statem:call(Pid, dist_get_tls_socket). -spec callback_mode() -> gen_statem:callback_mode_result(). callback_mode() -> state_functions. -spec init(Args :: term()) -> gen_statem:init_result(atom()). init(_) -> process_flag(trap_exit, true), {ok, init, #data{}}. -spec init(gen_statem:event_type(), Msg :: term(), StateData :: term()) -> gen_statem:event_handler_result(atom()). init({call, From}, {Pid, #{current_write := WriteState, role := Role, socket := Socket, socket_options := SockOpts, erl_dist := IsErlDist, trackers := Trackers, transport_cb := Transport, negotiated_version := Version, renegotiate_at := RenegotiateAt, key_update_at := KeyUpdateAt, log_level := LogLevel}}, #data{connection_states = ConnectionStates, static = Static0} = StateData0) -> StateData = StateData0#data{connection_states = ConnectionStates#{current_write => WriteState}, static = Static0#static{connection_pid = Pid, role = Role, socket = Socket, socket_options = SockOpts, erl_dist = IsErlDist, trackers = Trackers, transport_cb = Transport, negotiated_version = Version, renegotiate_at = RenegotiateAt, key_update_at = KeyUpdateAt, bytes_sent = 0, log_level = LogLevel}}, {next_state, handshake, StateData, [{reply, From, ok}]}; init(info = Type, Msg, StateData) -> handle_common(Type, Msg, StateData); init(_, _, _) -> {keep_state_and_data, [postpone]}. -spec connection(gen_statem:event_type(), Msg :: term(), StateData :: term()) -> gen_statem:event_handler_result(atom()). connection({call, From}, {application_data, AppData}, #data{static = #static{socket_options = #socket_options{packet = Packet}}} = StateData) -> case encode_packet(Packet, AppData) of {error, _} = Error -> {next_state, ?FUNCTION_NAME, StateData, [{reply, From, Error}]}; Data -> send_application_data(Data, From, ?FUNCTION_NAME, StateData) end; connection({call, From}, {post_handshake_data, HSData}, StateData) -> send_post_handshake_data(HSData, From, ?FUNCTION_NAME, StateData); connection({call, From}, {ack_alert, #alert{} = Alert}, StateData0) -> StateData = send_tls_alert(Alert, StateData0), {next_state, ?FUNCTION_NAME, StateData, [{reply,From,ok}]}; connection({call, From}, renegotiate, #data{connection_states = #{current_write := Write}} = StateData) -> {next_state, handshake, StateData, [{reply, From, {ok, Write}}]}; connection({call, From}, downgrade, #data{connection_states = #{current_write := Write}} = StateData) -> {next_state, death_row, StateData, [{reply,From, {ok, Write}}]}; connection({call, From}, {set_opts, Opts}, StateData) -> handle_set_opts(From, Opts, StateData); connection({call, From}, dist_get_tls_socket, #data{static = #static{transport_cb = Transport, socket = Socket, connection_pid = Pid, trackers = Trackers}} = StateData) -> TLSSocket = tls_gen_connection:socket([Pid, self()], Transport, Socket, Trackers), {next_state, ?FUNCTION_NAME, StateData, [{reply, From, {ok, TLSSocket}}]}; connection({call, From}, {dist_handshake_complete, _Node, DHandle}, #data{static = #static{connection_pid = Pid} = Static} = StateData) -> false = erlang:dist_ctrl_set_opt(DHandle, get_size, true), ok = erlang:dist_ctrl_input_handler(DHandle, Pid), ok = ssl_gen_statem:dist_handshake_complete(Pid, DHandle), process_flag(priority, normal), {keep_state, StateData#data{static = Static#static{dist_handle = DHandle}}, [{reply,From,ok}| case dist_data(DHandle) of [] -> []; Data -> [{next_event, internal, {application_packets,{self(),undefined},Data}}] end]}; connection(internal, {application_packets, From, Data}, StateData) -> send_application_data(Data, From, ?FUNCTION_NAME, StateData); connection(internal, {post_handshake_data, From, HSData}, StateData) -> send_post_handshake_data(HSData, From, ?FUNCTION_NAME, StateData); connection(cast, #alert{} = Alert, StateData0) -> StateData = send_tls_alert(Alert, StateData0), {next_state, ?FUNCTION_NAME, StateData}; connection(cast, {new_write, WritesState, Version}, #data{connection_states = ConnectionStates, static = Static} = StateData) -> {next_state, connection, StateData#data{connection_states = ConnectionStates#{current_write => WritesState}, static = Static#static{negotiated_version = Version}}}; connection(info, dist_data, #data{static = #static{dist_handle = DHandle}}) -> {keep_state_and_data, case dist_data(DHandle) of [] -> []; Data -> [{next_event, internal, {application_packets,{self(),undefined},Data}}] end}; connection(info, tick, StateData) -> consume_ticks(), From = {self(), undefined}, send_application_data(Data, From, ?FUNCTION_NAME, StateData); connection(info, {send, From, Ref, Data}, _StateData) -> Needed by some OTP distribution From ! {Ref, ok}, {keep_state_and_data, [{next_event, {call, {self(), undefined}}, {application_data, erlang:iolist_to_iovec(Data)}}]}; connection(Type, Msg, StateData) -> handle_common(Type, Msg, StateData). -spec handshake(gen_statem:event_type(), Msg :: term(), StateData :: term()) -> gen_statem:event_handler_result(atom()). handshake({call, From}, {set_opts, Opts}, StateData) -> handle_set_opts(From, Opts, StateData); handshake({call, _}, _, _) -> Postpone all calls to the connection state {keep_state_and_data, [postpone]}; handshake(internal, {application_packets,_,_}, _) -> {keep_state_and_data, [postpone]}; handshake(cast, {new_write, WriteState, Version}, #data{connection_states = ConnectionStates, static = #static{key_update_at = KeyUpdateAt0} = Static} = StateData) -> KeyUpdateAt = key_update_at(Version, WriteState, KeyUpdateAt0), {next_state, connection, StateData#data{connection_states = ConnectionStates#{current_write => WriteState}, static = Static#static{negotiated_version = Version, key_update_at = KeyUpdateAt}}}; handshake(info, dist_data, _) -> {keep_state_and_data, [postpone]}; handshake(info, tick, _) -> consume_ticks(), keep_state_and_data; handshake(info, {send, _, _, _}, _) -> Testing only , OTP distribution test suites ... {keep_state_and_data, [postpone]}; handshake(Type, Msg, StateData) -> handle_common(Type, Msg, StateData). -spec death_row(gen_statem:event_type(), Msg :: term(), StateData :: term()) -> gen_statem:event_handler_result(atom()). death_row(state_timeout, Reason, _State) -> {stop, {shutdown, Reason}}; death_row(info = Type, Msg, State) -> handle_common(Type, Msg, State); death_row(_Type, _Msg, _State) -> keep_state_and_data. -spec terminate(Reason :: term(), State :: term(), Data :: term()) -> any(). terminate(_Reason, _State, _Data) -> void. -spec code_change( OldVsn :: term() | {down,term()}, State :: term(), Data :: term(), Extra :: term()) -> {ok, NewState :: term(), NewData :: term()} | (Reason :: term()). code_change(_OldVsn, State, Data, _Extra) -> {ok, State, Data}. Internal functions handle_set_opts(From, Opts, #data{static = #static{socket_options = SockOpts} = Static} = StateData) -> {keep_state, StateData#data{static = Static#static{socket_options = set_opts(SockOpts, Opts)}}, [{reply, From, ok}]}. handle_common({call, From}, {set_opts, Opts}, #data{static = #static{socket_options = SockOpts} = Static} = StateData) -> {keep_state, StateData#data{static = Static#static{socket_options = set_opts(SockOpts, Opts)}}, [{reply, From, ok}]}; handle_common(info, {'EXIT', _Sup, shutdown}, #data{static = #static{erl_dist = true}} = StateData) -> begin to fail . We wait for 5 seconds to receive possible exit signals for one of our links to the other {next_state, death_row, StateData, [{state_timeout, 5000, shutdown}]}; handle_common(info, {'EXIT', _Dist, Reason}, #data{static = #static{erl_dist = true}} = StateData) -> {stop, {shutdown, Reason}, StateData}; handle_common(info, {'EXIT', _Sup, shutdown}, StateData) -> {stop, shutdown, StateData}; handle_common(info, Msg, #data{static = #static{log_level = Level}}) -> ssl_logger:log(info, Level, #{event => "TLS sender received unexpected info", reason => [{message, Msg}]}, ?LOCATION), keep_state_and_data; handle_common(Type, Msg, #data{static = #static{log_level = Level}}) -> ssl_logger:log(error, Level, #{event => "TLS sender received unexpected event", reason => [{type, Type}, {message, Msg}]}, ?LOCATION), keep_state_and_data. send_tls_alert(#alert{} = Alert, #data{static = #static{negotiated_version = Version, socket = Socket, transport_cb = Transport, log_level = LogLevel}, connection_states = ConnectionStates0} = StateData0) -> {BinMsg, ConnectionStates} = tls_record:encode_alert_record(Alert, Version, ConnectionStates0), tls_socket:send(Transport, Socket, BinMsg), ssl_logger:debug(LogLevel, outbound, 'record', BinMsg), StateData0#data{connection_states = ConnectionStates}. send_application_data(Data, From, StateName, #data{static = #static{connection_pid = Pid, socket = Socket, dist_handle = DistHandle, negotiated_version = Version, transport_cb = Transport, renegotiate_at = RenegotiateAt, key_update_at = KeyUpdateAt, bytes_sent = BytesSent, log_level = LogLevel}, connection_states = ConnectionStates0} = StateData0) -> case time_to_rekey(Version, Data, ConnectionStates0, RenegotiateAt, KeyUpdateAt, BytesSent) of key_update -> KeyUpdate = tls_handshake_1_3:key_update(update_requested), {keep_state_and_data, [{next_event, internal, {post_handshake_data, From, KeyUpdate}}, {next_event, internal, {key_update, From}}, {next_event, internal, {application_packets, From, Data}}]}; renegotiate -> tls_dtls_connection:internal_renegotiation(Pid, ConnectionStates0), {next_state, handshake, StateData0, [{next_event, internal, {application_packets, From, Data}}]}; chunk_and_key_update -> KeyUpdate = tls_handshake_1_3:key_update(update_requested), {Chunk, Rest} = chunk_data(Data, KeyUpdateAt), {keep_state_and_data, [{next_event, internal, {post_handshake_data, From, KeyUpdate}}, {next_event, internal, {application_packets, From, Chunk}}, {next_event, internal, {application_packets, From, Rest}}]}; false -> {Msgs, ConnectionStates} = tls_record:encode_data(Data, Version, ConnectionStates0), StateData = StateData0#data{connection_states = ConnectionStates}, case tls_socket:send(Transport, Socket, Msgs) of ok when DistHandle =/= undefined -> ssl_logger:debug(LogLevel, outbound, 'record', Msgs), StateData1 = update_bytes_sent(Version, StateData, Data), {next_state, StateName, StateData1, []}; Reason when DistHandle =/= undefined -> {next_state, death_row, StateData, [{state_timeout, 5000, Reason}]}; ok -> ssl_logger:debug(LogLevel, outbound, 'record', Msgs), StateData1 = update_bytes_sent(Version, StateData, Data), {next_state, StateName, StateData1, [{reply, From, ok}]}; Result -> {next_state, StateName, StateData, [{reply, From, Result}]} end end. TLS 1.3 Post Handshake Data send_post_handshake_data(Handshake, From, StateName, #data{static = #static{socket = Socket, dist_handle = DistHandle, negotiated_version = Version, transport_cb = Transport, log_level = LogLevel}, connection_states = ConnectionStates0} = StateData0) -> BinHandshake = tls_handshake:encode_handshake(Handshake, Version), {Encoded, ConnectionStates} = tls_record:encode_handshake(BinHandshake, Version, ConnectionStates0), ssl_logger:debug(LogLevel, outbound, 'handshake', Handshake), StateData1 = StateData0#data{connection_states = ConnectionStates}, case tls_socket:send(Transport, Socket, Encoded) of ok when DistHandle =/= undefined -> ssl_logger:debug(LogLevel, outbound, 'record', Encoded), StateData = maybe_update_cipher_key(StateData1, Handshake), {next_state, StateName, StateData, []}; Reason when DistHandle =/= undefined -> {next_state, death_row, StateData1, [{state_timeout, 5000, Reason}]}; ok -> ssl_logger:debug(LogLevel, outbound, 'record', Encoded), StateData = maybe_update_cipher_key(StateData1, Handshake), {next_state, StateName, StateData, [{reply, From, ok}]}; Result -> {next_state, StateName, StateData1, [{reply, From, Result}]} end. maybe_update_cipher_key(#data{connection_states = ConnectionStates0, static = Static0} = StateData, #key_update{}) -> ConnectionStates = tls_connection_1_3:update_cipher_key(current_write, ConnectionStates0), Static = Static0#static{bytes_sent = 0}, StateData#data{connection_states = ConnectionStates, static = Static}; maybe_update_cipher_key(StateData, _) -> StateData. update_bytes_sent(Version, StateData, _) when Version < {3,4} -> StateData; Count bytes sent in TLS 1.3 for AES - GCM update_bytes_sent(_, #data{static = #static{key_update_at = seq_num_wrap}} = StateData, _) -> Chacha20 - Poly1305 update_bytes_sent(_, #data{static = #static{bytes_sent = Sent} = Static} = StateData, Data) -> For AES - GCM , up to 2 ^ 24.5 full - size records ( about 24 million ) may be approximately 2 ^ -57 for Authenticated Encryption ( AE ) security . For ChaCha20 / Poly1305 , the record sequence number would wrap before the key_update_at(Version, #{security_parameters := #security_parameters{ bulk_cipher_algorithm = CipherAlgo}}, KeyUpdateAt) when Version >= {3,4} -> case CipherAlgo of ?AES_GCM -> KeyUpdateAt; ?CHACHA20_POLY1305 -> seq_num_wrap; ?AES_CCM -> KeyUpdateAt; ?AES_CCM_8 -> KeyUpdateAt end; key_update_at(_, _, KeyUpdateAt) -> KeyUpdateAt. -compile({inline, encode_packet/2}). encode_packet(Packet, Data) -> Len = iolist_size(Data), case Packet of 1 when Len < (1 bsl 8) -> [<<Len:8>>|Data]; 2 when Len < (1 bsl 16) -> [<<Len:16>>|Data]; 4 when Len < (1 bsl 32) -> [<<Len:32>>|Data]; N when N =:= 1; N =:= 2; N =:= 4 -> {error, {badarg, {packet_to_large, Len, (1 bsl (Packet bsl 3)) - 1}}}; _ -> Data end. set_opts(SocketOptions, [{packet, N}]) -> SocketOptions#socket_options{packet = N}. time_to_rekey(Version, _Data, #{current_write := #{sequence_number := ?MAX_SEQUENCE_NUMBER}}, _, _, _) when Version >= {3,4} -> key_update; time_to_rekey(Version, _Data, _, _, seq_num_wrap, _) when Version >= {3,4} -> false; time_to_rekey(Version, Data, _, _, KeyUpdateAt, BytesSent) when Version >= {3,4} -> DataSize = iolist_size(Data), case (BytesSent + DataSize) > KeyUpdateAt of true -> case DataSize > KeyUpdateAt of true -> chunk_and_key_update; false -> key_update end; false -> false end; time_to_rekey(_, _Data, #{current_write := #{sequence_number := Num}}, RenegotiateAt, _, _) -> ? MAX_PLAIN_TEXT_LENGTH ) + 1 , RenegotiateAt ) , but we chose to is_time_to_renegotiate(Num, RenegotiateAt). chunk_data(Data, Size) -> {Chunk, Rest} = split_binary(iolist_to_binary(Data), Size), {[Chunk], [Rest]}. is_time_to_renegotiate(N, M) when N < M-> false; is_time_to_renegotiate(_,_) -> renegotiate. call(FsmPid, Event) -> try gen_statem:call(FsmPid, Event) catch exit:{noproc, _} -> {error, closed}; exit:{normal, _} -> {error, closed}; exit:{shutdown,_} -> {error, closed}; exit:{{shutdown, _},_} -> {error, closed} end. -------------- Erlang distribution helpers ------------------------------ To avoid livelock , dist_data/2 will check for more bytes coming from -define(TLS_BUNDLE_SOFT_LIMIT, 16 * 1024 * 1024). dist_data(DHandle) -> dist_data(DHandle, 0). dist_data(DHandle, CurBytes) -> case erlang:dist_ctrl_get_data(DHandle) of none -> erlang:dist_ctrl_get_data_notification(DHandle), []; This is encode_packet(4 , Data ) without check smaller than 4 GB , and the distribution will {Len, Data} when Len + CurBytes >= ?TLS_BUNDLE_SOFT_LIMIT -> Data is of type ( ) ; lets keep it erlang:dist_ctrl_get_data_notification(DHandle), [<<Len:32>> | Data]; {Len, Data} -> Packet = [<<Len:32>> | Data], case dist_data(DHandle, CurBytes + Len) of [] -> Packet; More -> Packet ++ More end end. consume_ticks() -> receive tick -> consume_ticks() after 0 -> ok end.
b07034f799b420163cae3f89745acd35c902d491377cafe8a18e2cfe0545d71e
yallop/ocaml-ctypes
test_foreign_values.ml
* Copyright ( c ) 2013 - 2014 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013-2014 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open OUnit2 open Ctypes module Common_tests(S : Cstubs.FOREIGN with type 'a result = 'a and type 'a return = 'a) = struct module M = Functions.Common(S) open M (* Retrieve a struct exposed as a global value. *) let test_retrieving_struct _ = let p = CArray.start (getf !@global_struct str) in let stringp = from_voidp string (to_voidp (allocate (ptr char) p)) in begin let expected = "global string" in assert_equal expected !@stringp; assert_equal (Unsigned.Size_t.of_int (String.length expected)) (getf !@global_struct len) end (* Store a reference to an OCaml function as a global function pointer. *) let test_global_callback _ = begin assert_equal !@plus None; plus <-@ Some (+); assert_equal (sum 1 10) 55; plus <-@ None; end (* Access an array exposed as a global value *) let test_retrieving_array _ = let sarr = !@string_array in begin assert_equal "Hello" (CArray.get sarr 0); assert_equal "world" (CArray.get sarr 1); end; let iarr = !@int_array in begin let expected_ints = Bigarray_compat.(Array1.create int32 c_layout 5) in for i = 0 to 4 do Bigarray_compat.Array1.set expected_ints i (Int32.of_int i) done; assert_equal expected_ints iarr end end module Make_stub_tests(S : Cstubs.FOREIGN with type 'a result = 'a and type 'a return = 'a) = struct module N = Functions.Stubs(S) open N (* Read environment variables from the 'environ' global. *) let test_environ _ = let parse_entry s = match Str.(bounded_split (regexp "=") s 2), "" with [k; v], _ | [k], v -> (String.uppercase_ascii k, v) | _ -> Printf.ksprintf failwith "Parsing %S failed" s in let rec copy_environ acc env = match !@env with None -> acc | Some s -> copy_environ (parse_entry s :: acc) (env +@ 1) in begin let environment = copy_environ [] !@environ in assert_equal ~printer:(fun x -> x) (List.assoc "HOME" environment) (Sys.getenv "HOME") end end module Foreign_tests = Common_tests(Tests_common.Foreign_binder) module Stub_tests = struct include Common_tests(Generated_bindings) include Make_stub_tests(Generated_bindings) end let suite = "Foreign value tests" >::: ["retrieving global struct (foreign)" >:: Foreign_tests.test_retrieving_struct; "global callback function (foreign)" >:: Foreign_tests.test_global_callback; "retrieving global array (foreign)" >:: Foreign_tests.test_retrieving_array; "retrieving global struct (stubs)" >:: Stub_tests.test_retrieving_struct; "retrieving global array (stubs)" >:: Stub_tests.test_retrieving_array; "global callback function (stubs)" >:: Stub_tests.test_global_callback; "reading from 'environ' (stubs)" >:: Stub_tests.test_environ; ] let _ = run_test_tt_main suite
null
https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/tests/test-foreign_values/test_foreign_values.ml
ocaml
Retrieve a struct exposed as a global value. Store a reference to an OCaml function as a global function pointer. Access an array exposed as a global value Read environment variables from the 'environ' global.
* Copyright ( c ) 2013 - 2014 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013-2014 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open OUnit2 open Ctypes module Common_tests(S : Cstubs.FOREIGN with type 'a result = 'a and type 'a return = 'a) = struct module M = Functions.Common(S) open M let test_retrieving_struct _ = let p = CArray.start (getf !@global_struct str) in let stringp = from_voidp string (to_voidp (allocate (ptr char) p)) in begin let expected = "global string" in assert_equal expected !@stringp; assert_equal (Unsigned.Size_t.of_int (String.length expected)) (getf !@global_struct len) end let test_global_callback _ = begin assert_equal !@plus None; plus <-@ Some (+); assert_equal (sum 1 10) 55; plus <-@ None; end let test_retrieving_array _ = let sarr = !@string_array in begin assert_equal "Hello" (CArray.get sarr 0); assert_equal "world" (CArray.get sarr 1); end; let iarr = !@int_array in begin let expected_ints = Bigarray_compat.(Array1.create int32 c_layout 5) in for i = 0 to 4 do Bigarray_compat.Array1.set expected_ints i (Int32.of_int i) done; assert_equal expected_ints iarr end end module Make_stub_tests(S : Cstubs.FOREIGN with type 'a result = 'a and type 'a return = 'a) = struct module N = Functions.Stubs(S) open N let test_environ _ = let parse_entry s = match Str.(bounded_split (regexp "=") s 2), "" with [k; v], _ | [k], v -> (String.uppercase_ascii k, v) | _ -> Printf.ksprintf failwith "Parsing %S failed" s in let rec copy_environ acc env = match !@env with None -> acc | Some s -> copy_environ (parse_entry s :: acc) (env +@ 1) in begin let environment = copy_environ [] !@environ in assert_equal ~printer:(fun x -> x) (List.assoc "HOME" environment) (Sys.getenv "HOME") end end module Foreign_tests = Common_tests(Tests_common.Foreign_binder) module Stub_tests = struct include Common_tests(Generated_bindings) include Make_stub_tests(Generated_bindings) end let suite = "Foreign value tests" >::: ["retrieving global struct (foreign)" >:: Foreign_tests.test_retrieving_struct; "global callback function (foreign)" >:: Foreign_tests.test_global_callback; "retrieving global array (foreign)" >:: Foreign_tests.test_retrieving_array; "retrieving global struct (stubs)" >:: Stub_tests.test_retrieving_struct; "retrieving global array (stubs)" >:: Stub_tests.test_retrieving_array; "global callback function (stubs)" >:: Stub_tests.test_global_callback; "reading from 'environ' (stubs)" >:: Stub_tests.test_environ; ] let _ = run_test_tt_main suite
fbdf9f3088e82cfc626a825c2752d30451359beb4bfa4402f29ed3176269ea84
cemerick/clojurescript.test
basic.cljs
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. test_clojure / test.clj : unit tests for test.clj by January 16 , 2009 Thanks to , , and for ;; contributions and suggestions. (ns cemerick.cljs.test.basic (:require-macros [cemerick.cljs.test :as m :refer (is test-var deftest run-tests deftesthook)]) (:require [cemerick.cljs.test :as t])) (deftest can-test-symbol (let [x true] (is x "Should pass")) (let [x false] (is x "Should fail"))) (deftest can-test-boolean (is true "Should pass") (is false "Should fail")) (deftest can-test-nil (is nil "Should fail")) (deftest can-test-= (is (= 2 (+ 1 1)) "Should pass") (is (= 3 (+ 2 2)) "Should fail")) (deftype A []) (deftest can-test-instance (is (number? (+ 2 2)) "Should pass") (is (string? (+ 1 1)) "Should fail") (is (instance? A (A.)) "Should pass") (is (instance? A (+ 1 1)) "Should fail")) (deftest can-test-thrown (is (thrown? js/Error (js/eval (str (gensym) " + 2"))) "Should pass") ;; No exception is thrown: (is (thrown? js/Error (+ 1 1)) "Should fail") ;; Wrong class of exception is thrown: (is (thrown? js/SyntaxError (throw (js/Error.))) "Should error")) (deftest can-test-thrown-with-msg ;; coming up with error messages that are standard across js runtime isn't easy... (is (thrown-with-msg? js/SyntaxError #"[Uu]nterminated parenthetical|Invalid regular expression" ;; Use eval to prevent advanced mode from transforming it into a literal. ((js/eval "RegExp") "f(")) "Should pass") ;; Wrong message string: (is (thrown-with-msg? js/SyntaxError #"foo" (/ 1 0)) "Should fail") ;; No exception is thrown: (is (thrown? js/Error (+ 1 1)) "Should fail") ;; Wrong class of exception is thrown: (is (thrown-with-msg? js/SyntaxError #"Divide by zero" (js/eval (str (gensym) " + 2"))) "Should error")) (deftest can-catch-unexpected-exceptions (is (= 1 (throw (js/Error.))) "Should error")) (deftest can-test-method-call (is (.match "abc" #"bc") "Should pass") (is (.match "abc" #"d") "Should fail")) (deftest can-test-anonymous-fn (is (#(.match % #"bc") "abc") "Should pass") (is (#(.match % #"d") "abc") "Should fail")) (deftest can-test-regexps (is (re-matches #"^ab.*$" "abbabba") "Should pass") (is (re-matches #"^cd.*$" "abbabba") "Should fail") (is (re-find #"ab" "abbabba") "Should pass") (is (re-find #"cd" "abbabba") "Should fail")) ;; Here, we create an alternate version of test/report, that ;; compares the event with the message, then calls the original ;; 'report' with modified arguments. (declare ^:dynamic original-report) (defn custom-report [{:keys [test-env test-name] :as data}] (let [event (:type data) msg (:message data) expected (:expected data) actual (:actual data) passed (cond (= event :fail) (= msg "Should fail") (= event :pass) (= msg "Should pass") (= event :error) (= msg "Should error") :else true)] (if passed (original-report {:type :pass, :message msg, :test-env test-env :test-name test-name :expected expected, :actual actual}) (original-report {:type :fail, :message (str msg " but got " event) :test-env test-env :test-name test-name :expected expected, :actual actual})))) ;; test-ns-hook will be used by test/test-ns to run tests in this ;; namespace. (deftesthook test-ns-hook [cljs-test-env] (binding [original-report t/report t/report custom-report] (t/test-all-vars cljs-test-env 'cemerick.cljs.test.basic) (t/test-function cljs-test-env can-test-regexps)))
null
https://raw.githubusercontent.com/cemerick/clojurescript.test/e8f42c2a8921c584dc2333f5e2df2251c25098ab/test/cemerick/cljs/test/basic.cljs
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. contributions and suggestions. No exception is thrown: Wrong class of exception is thrown: coming up with error messages that are standard across js runtime isn't easy... Use eval to prevent advanced mode from transforming it into a literal. Wrong message string: No exception is thrown: Wrong class of exception is thrown: Here, we create an alternate version of test/report, that compares the event with the message, then calls the original 'report' with modified arguments. test-ns-hook will be used by test/test-ns to run tests in this namespace.
Copyright ( c ) . All rights reserved . test_clojure / test.clj : unit tests for test.clj by January 16 , 2009 Thanks to , , and for (ns cemerick.cljs.test.basic (:require-macros [cemerick.cljs.test :as m :refer (is test-var deftest run-tests deftesthook)]) (:require [cemerick.cljs.test :as t])) (deftest can-test-symbol (let [x true] (is x "Should pass")) (let [x false] (is x "Should fail"))) (deftest can-test-boolean (is true "Should pass") (is false "Should fail")) (deftest can-test-nil (is nil "Should fail")) (deftest can-test-= (is (= 2 (+ 1 1)) "Should pass") (is (= 3 (+ 2 2)) "Should fail")) (deftype A []) (deftest can-test-instance (is (number? (+ 2 2)) "Should pass") (is (string? (+ 1 1)) "Should fail") (is (instance? A (A.)) "Should pass") (is (instance? A (+ 1 1)) "Should fail")) (deftest can-test-thrown (is (thrown? js/Error (js/eval (str (gensym) " + 2"))) "Should pass") (is (thrown? js/Error (+ 1 1)) "Should fail") (is (thrown? js/SyntaxError (throw (js/Error.))) "Should error")) (deftest can-test-thrown-with-msg (is (thrown-with-msg? js/SyntaxError #"[Uu]nterminated parenthetical|Invalid regular expression" ((js/eval "RegExp") "f(")) "Should pass") (is (thrown-with-msg? js/SyntaxError #"foo" (/ 1 0)) "Should fail") (is (thrown? js/Error (+ 1 1)) "Should fail") (is (thrown-with-msg? js/SyntaxError #"Divide by zero" (js/eval (str (gensym) " + 2"))) "Should error")) (deftest can-catch-unexpected-exceptions (is (= 1 (throw (js/Error.))) "Should error")) (deftest can-test-method-call (is (.match "abc" #"bc") "Should pass") (is (.match "abc" #"d") "Should fail")) (deftest can-test-anonymous-fn (is (#(.match % #"bc") "abc") "Should pass") (is (#(.match % #"d") "abc") "Should fail")) (deftest can-test-regexps (is (re-matches #"^ab.*$" "abbabba") "Should pass") (is (re-matches #"^cd.*$" "abbabba") "Should fail") (is (re-find #"ab" "abbabba") "Should pass") (is (re-find #"cd" "abbabba") "Should fail")) (declare ^:dynamic original-report) (defn custom-report [{:keys [test-env test-name] :as data}] (let [event (:type data) msg (:message data) expected (:expected data) actual (:actual data) passed (cond (= event :fail) (= msg "Should fail") (= event :pass) (= msg "Should pass") (= event :error) (= msg "Should error") :else true)] (if passed (original-report {:type :pass, :message msg, :test-env test-env :test-name test-name :expected expected, :actual actual}) (original-report {:type :fail, :message (str msg " but got " event) :test-env test-env :test-name test-name :expected expected, :actual actual})))) (deftesthook test-ns-hook [cljs-test-env] (binding [original-report t/report t/report custom-report] (t/test-all-vars cljs-test-env 'cemerick.cljs.test.basic) (t/test-function cljs-test-env can-test-regexps)))
7d24256e4093fbbbfa7269c7c8585c8e4a3aa0e30833fa9854b5b3ad4982371e
ncaq/yesod-form-bootstrap4
Bootstrap4.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -Wno-partial-fields #-} | this program based on Yesod . Form . Bootstrap3 of yesod - form yesod - form under MIT license , author is < > module Yesod.Form.Bootstrap4 ( renderBootstrap4 , BootstrapFormLayout(..) , BootstrapGridOptions(..) , bfs , bfsFile , withPlaceholder , withAutofocus , withLargeInput , withSmallInput , bootstrapSubmit , mbootstrapSubmit , BootstrapSubmit(..) ) where import Control.Arrow (second) import Data.String (IsString (..)) import Data.Text (Text) import qualified Data.Text.Lazy as TL import Text.Blaze.Html.Renderer.Text import Yesod.Core import Yesod.Form bfs :: RenderMessage site msg => msg -> FieldSettings site bfs msg = FieldSettings (SomeMessage msg) Nothing Nothing Nothing [("class", "form-control")] bfsFile :: RenderMessage site msg => msg -> FieldSettings site bfsFile msg = FieldSettings (SomeMessage msg) Nothing Nothing Nothing [("class", "form-control-file")] withPlaceholder :: Text -> FieldSettings site -> FieldSettings site withPlaceholder placeholder fs = fs { fsAttrs = newAttrs } where newAttrs = ("placeholder", placeholder) : fsAttrs fs -- | Add an autofocus attribute to a field. withAutofocus :: FieldSettings site -> FieldSettings site withAutofocus fs = fs { fsAttrs = newAttrs } where newAttrs = ("autofocus", "autofocus") : fsAttrs fs -- | Add the @input-lg@ CSS class to a field. withLargeInput :: FieldSettings site -> FieldSettings site withLargeInput fs = fs { fsAttrs = newAttrs } where newAttrs = addClass "form-control-lg" (fsAttrs fs) -- | Add the @input-sm@ CSS class to a field. withSmallInput :: FieldSettings site -> FieldSettings site withSmallInput fs = fs { fsAttrs = newAttrs } where newAttrs = addClass "form-control-sm" (fsAttrs fs) data BootstrapGridOptions = ColXs !Int | ColSm !Int | ColMd !Int | ColLg !Int | ColXl !Int deriving (Eq, Ord, Show, Read) toColumn :: BootstrapGridOptions -> String toColumn (ColXs columns) = "col-xs-" ++ show columns toColumn (ColSm columns) = "col-sm-" ++ show columns toColumn (ColMd columns) = "col-md-" ++ show columns toColumn (ColLg columns) = "col-lg-" ++ show columns toColumn (ColXl columns) = "col-xl-" ++ show columns toOffset :: BootstrapGridOptions -> String toOffset (ColXs columns) = "col-xs-offset-" ++ show columns toOffset (ColSm columns) = "col-sm-offset-" ++ show columns toOffset (ColMd columns) = "col-md-offset-" ++ show columns toOffset (ColLg columns) = "col-lg-offset-" ++ show columns toOffset (ColXl columns) = "col-Xl-offset-" ++ show columns addGO :: BootstrapGridOptions -> BootstrapGridOptions -> BootstrapGridOptions addGO (ColXs a) (ColXs b) = ColXs (a+b) addGO (ColSm a) (ColSm b) = ColSm (a+b) addGO (ColMd a) (ColMd b) = ColMd (a+b) addGO (ColLg a) (ColLg b) = ColLg (a+b) addGO a b | a > b = addGO b a addGO (ColXs a) other = addGO (ColSm a) other addGO (ColSm a) other = addGO (ColMd a) other addGO (ColMd a) other = addGO (ColLg a) other addGO _ _ = error "Yesod.Form.Bootstrap.addGO: never here" -- | The layout used for the bootstrap form. data BootstrapFormLayout = BootstrapBasicForm | BootstrapInlineForm | BootstrapHorizontalForm { bflLabelOffset :: !BootstrapGridOptions , bflLabelSize :: !BootstrapGridOptions , bflInputOffset :: !BootstrapGridOptions , bflInputSize :: !BootstrapGridOptions } deriving (Eq, Ord, Show, Read) -- | Render the given form using Bootstrap v4 conventions. renderBootstrap4 :: Monad m => BootstrapFormLayout -> FormRender m a renderBootstrap4 formLayout aform fragment = do (res, views') <- aFormToForm aform let views = views' [] widget = [whamlet| #{fragment} $forall view <- views $if inputTypeBoolOrCheckBox view ^{renderCheckInput view} $else ^{renderGroupInput view formLayout} |] return (res, widget) FIXME : ` .form - check - input`を`input`につける方法がわからない renderCheckInput :: FieldView site -> WidgetFor site () renderCheckInput view = [whamlet| <div .form-check (fvErrors view):.is-invalid> ^{fvInput view} <label .form-check-label for=#{fvId view}> ^{helpWidget view} |] renderGroupInput :: FieldView site -> BootstrapFormLayout -> WidgetFor site () renderGroupInput view formLayout = [whamlet| $case formLayout $of BootstrapBasicForm $if fvId view /= bootstrapSubmitId <label for=#{fvId view}>#{fvLabel view} ^{fvInput view} ^{helpWidget view} $of BootstrapInlineForm $if fvId view /= bootstrapSubmitId <label .sr-only for=#{fvId view}>#{fvLabel view} ^{fvInput view} ^{helpWidget view} $of BootstrapHorizontalForm labelOffset labelSize inputOffset inputSize $if fvId view /= bootstrapSubmitId <div .row> <label .#{toOffset labelOffset} .#{toColumn labelSize} for=#{fvId view}>#{fvLabel view} <div .#{toOffset inputOffset} .#{toColumn inputSize}> ^{fvInput view} ^{helpWidget view} $else <div .#{toOffset (addGO inputOffset (addGO labelOffset labelSize))} .#{toColumn inputSize}> ^{fvInput view} ^{helpWidget view} |] -- | 入力されたフィールドがcheck形式である必要があるか判定する HTMLの内容を`Monad`の範囲で見る方法が分からなかったため , ワークアラウンドとしてlabelの内容を見て判断します inputTypeBoolOrCheckBox :: FieldView site -> Bool inputTypeBoolOrCheckBox FieldView{fvLabel} = let textLabel = renderHtml fvLabel in "radio" `TL.isInfixOf` textLabel || "checkbox" `TL.isInfixOf` textLabel -- | (Internal) Render a help widget for tooltips and errors. -- .invalid-feedbackを必ず表示する bootstrap 4.1の書式ではinputがerrorでなければエラーメッセージが出ませんが -- yesod-formのAPIではfvInput自体を弄るのが困難ですし yesod - formのAPI上fvErrorsが存在する時は常にエラーメッセージは表示させるべきなので汚いやり方ですが -- styleを上書きして常に表示します helpWidget :: FieldView site -> WidgetFor site () helpWidget view = [whamlet| $maybe err <- fvErrors view <div .invalid-feedback style="display: block;"> #{err} $maybe tt <- fvTooltip view <small .form-text .text-muted> #{tt} |] -- | How the 'bootstrapSubmit' button should be rendered. data BootstrapSubmit msg = BootstrapSubmit { bsValue :: msg -- ^ The text of the submit button. , bsClasses :: Text -- ^ Classes added to the @\<button>@. , bsAttrs :: [(Text, Text)] -- ^ Attributes added to the @\<button>@. } deriving (Eq, Ord, Show, Read) instance IsString msg => IsString (BootstrapSubmit msg) where fromString msg = BootstrapSubmit (fromString msg) "btn-primary" [] -- | A Bootstrap v4 submit button disguised as a field for -- convenience. For example, if your form currently is: -- > Person < $ > areq " Name " Nothing > < * > areq " Surname " Nothing -- -- Then just change it to: -- > Person < $ > areq " Name " Nothing > < * > areq " Surname " Nothing > < * bootstrapSubmit ( " Register " : : BootstrapSubmit Text ) -- -- (Note that '<*' is not a typo.) -- -- Alternatively, you may also just create the submit button -- manually as well in order to have more control over its -- layout. bootstrapSubmit :: (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m) => BootstrapSubmit msg -> AForm m () bootstrapSubmit = formToAForm . fmap (second return) . mbootstrapSubmit -- | Same as 'bootstrapSubmit' but for monadic forms. This isn't -- as useful since you're not going to use 'renderBootstrap4' -- anyway. mbootstrapSubmit :: (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m) => BootstrapSubmit msg -> MForm m (FormResult (), FieldView site) mbootstrapSubmit (BootstrapSubmit msg classes attrs) = let res = FormSuccess () widget = [whamlet|<button class="btn #{classes}" type=submit *{attrs}>_{msg}|] fv = FieldView { fvLabel = "" , fvTooltip = Nothing , fvId = bootstrapSubmitId , fvInput = widget , fvErrors = Nothing , fvRequired = False } in return (res, fv) | A royal hack . Magic i d used to identify whether a field should have no label . A valid HTML4 i d which is probably not -- going to clash with any other id should someone use -- 'bootstrapSubmit' outside 'renderBootstrap4'. bootstrapSubmitId :: Text bootstrapSubmitId = "b:ootstrap___unique__:::::::::::::::::submit-id"
null
https://raw.githubusercontent.com/ncaq/yesod-form-bootstrap4/aadfca38232f2a22a07b3454479882180fd99f41/src/Yesod/Form/Bootstrap4.hs
haskell
# LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedStrings # # LANGUAGE QuasiQuotes # # LANGUAGE TypeFamilies # # OPTIONS_GHC -Wno-partial-fields # | Add an autofocus attribute to a field. | Add the @input-lg@ CSS class to a field. | Add the @input-sm@ CSS class to a field. | The layout used for the bootstrap form. | Render the given form using Bootstrap v4 conventions. | 入力されたフィールドがcheck形式である必要があるか判定する | (Internal) Render a help widget for tooltips and errors. .invalid-feedbackを必ず表示する yesod-formのAPIではfvInput自体を弄るのが困難ですし styleを上書きして常に表示します | How the 'bootstrapSubmit' button should be rendered. ^ The text of the submit button. ^ Classes added to the @\<button>@. ^ Attributes added to the @\<button>@. | A Bootstrap v4 submit button disguised as a field for convenience. For example, if your form currently is: Then just change it to: (Note that '<*' is not a typo.) Alternatively, you may also just create the submit button manually as well in order to have more control over its layout. | Same as 'bootstrapSubmit' but for monadic forms. This isn't as useful since you're not going to use 'renderBootstrap4' anyway. going to clash with any other id should someone use 'bootstrapSubmit' outside 'renderBootstrap4'.
# LANGUAGE FlexibleContexts # | this program based on Yesod . Form . Bootstrap3 of yesod - form yesod - form under MIT license , author is < > module Yesod.Form.Bootstrap4 ( renderBootstrap4 , BootstrapFormLayout(..) , BootstrapGridOptions(..) , bfs , bfsFile , withPlaceholder , withAutofocus , withLargeInput , withSmallInput , bootstrapSubmit , mbootstrapSubmit , BootstrapSubmit(..) ) where import Control.Arrow (second) import Data.String (IsString (..)) import Data.Text (Text) import qualified Data.Text.Lazy as TL import Text.Blaze.Html.Renderer.Text import Yesod.Core import Yesod.Form bfs :: RenderMessage site msg => msg -> FieldSettings site bfs msg = FieldSettings (SomeMessage msg) Nothing Nothing Nothing [("class", "form-control")] bfsFile :: RenderMessage site msg => msg -> FieldSettings site bfsFile msg = FieldSettings (SomeMessage msg) Nothing Nothing Nothing [("class", "form-control-file")] withPlaceholder :: Text -> FieldSettings site -> FieldSettings site withPlaceholder placeholder fs = fs { fsAttrs = newAttrs } where newAttrs = ("placeholder", placeholder) : fsAttrs fs withAutofocus :: FieldSettings site -> FieldSettings site withAutofocus fs = fs { fsAttrs = newAttrs } where newAttrs = ("autofocus", "autofocus") : fsAttrs fs withLargeInput :: FieldSettings site -> FieldSettings site withLargeInput fs = fs { fsAttrs = newAttrs } where newAttrs = addClass "form-control-lg" (fsAttrs fs) withSmallInput :: FieldSettings site -> FieldSettings site withSmallInput fs = fs { fsAttrs = newAttrs } where newAttrs = addClass "form-control-sm" (fsAttrs fs) data BootstrapGridOptions = ColXs !Int | ColSm !Int | ColMd !Int | ColLg !Int | ColXl !Int deriving (Eq, Ord, Show, Read) toColumn :: BootstrapGridOptions -> String toColumn (ColXs columns) = "col-xs-" ++ show columns toColumn (ColSm columns) = "col-sm-" ++ show columns toColumn (ColMd columns) = "col-md-" ++ show columns toColumn (ColLg columns) = "col-lg-" ++ show columns toColumn (ColXl columns) = "col-xl-" ++ show columns toOffset :: BootstrapGridOptions -> String toOffset (ColXs columns) = "col-xs-offset-" ++ show columns toOffset (ColSm columns) = "col-sm-offset-" ++ show columns toOffset (ColMd columns) = "col-md-offset-" ++ show columns toOffset (ColLg columns) = "col-lg-offset-" ++ show columns toOffset (ColXl columns) = "col-Xl-offset-" ++ show columns addGO :: BootstrapGridOptions -> BootstrapGridOptions -> BootstrapGridOptions addGO (ColXs a) (ColXs b) = ColXs (a+b) addGO (ColSm a) (ColSm b) = ColSm (a+b) addGO (ColMd a) (ColMd b) = ColMd (a+b) addGO (ColLg a) (ColLg b) = ColLg (a+b) addGO a b | a > b = addGO b a addGO (ColXs a) other = addGO (ColSm a) other addGO (ColSm a) other = addGO (ColMd a) other addGO (ColMd a) other = addGO (ColLg a) other addGO _ _ = error "Yesod.Form.Bootstrap.addGO: never here" data BootstrapFormLayout = BootstrapBasicForm | BootstrapInlineForm | BootstrapHorizontalForm { bflLabelOffset :: !BootstrapGridOptions , bflLabelSize :: !BootstrapGridOptions , bflInputOffset :: !BootstrapGridOptions , bflInputSize :: !BootstrapGridOptions } deriving (Eq, Ord, Show, Read) renderBootstrap4 :: Monad m => BootstrapFormLayout -> FormRender m a renderBootstrap4 formLayout aform fragment = do (res, views') <- aFormToForm aform let views = views' [] widget = [whamlet| #{fragment} $forall view <- views $if inputTypeBoolOrCheckBox view ^{renderCheckInput view} $else ^{renderGroupInput view formLayout} |] return (res, widget) FIXME : ` .form - check - input`を`input`につける方法がわからない renderCheckInput :: FieldView site -> WidgetFor site () renderCheckInput view = [whamlet| <div .form-check (fvErrors view):.is-invalid> ^{fvInput view} <label .form-check-label for=#{fvId view}> ^{helpWidget view} |] renderGroupInput :: FieldView site -> BootstrapFormLayout -> WidgetFor site () renderGroupInput view formLayout = [whamlet| $case formLayout $of BootstrapBasicForm $if fvId view /= bootstrapSubmitId <label for=#{fvId view}>#{fvLabel view} ^{fvInput view} ^{helpWidget view} $of BootstrapInlineForm $if fvId view /= bootstrapSubmitId <label .sr-only for=#{fvId view}>#{fvLabel view} ^{fvInput view} ^{helpWidget view} $of BootstrapHorizontalForm labelOffset labelSize inputOffset inputSize $if fvId view /= bootstrapSubmitId <div .row> <label .#{toOffset labelOffset} .#{toColumn labelSize} for=#{fvId view}>#{fvLabel view} <div .#{toOffset inputOffset} .#{toColumn inputSize}> ^{fvInput view} ^{helpWidget view} $else <div .#{toOffset (addGO inputOffset (addGO labelOffset labelSize))} .#{toColumn inputSize}> ^{fvInput view} ^{helpWidget view} |] HTMLの内容を`Monad`の範囲で見る方法が分からなかったため , ワークアラウンドとしてlabelの内容を見て判断します inputTypeBoolOrCheckBox :: FieldView site -> Bool inputTypeBoolOrCheckBox FieldView{fvLabel} = let textLabel = renderHtml fvLabel in "radio" `TL.isInfixOf` textLabel || "checkbox" `TL.isInfixOf` textLabel bootstrap 4.1の書式ではinputがerrorでなければエラーメッセージが出ませんが yesod - formのAPI上fvErrorsが存在する時は常にエラーメッセージは表示させるべきなので汚いやり方ですが helpWidget :: FieldView site -> WidgetFor site () helpWidget view = [whamlet| $maybe err <- fvErrors view <div .invalid-feedback style="display: block;"> #{err} $maybe tt <- fvTooltip view <small .form-text .text-muted> #{tt} |] data BootstrapSubmit msg = BootstrapSubmit } deriving (Eq, Ord, Show, Read) instance IsString msg => IsString (BootstrapSubmit msg) where fromString msg = BootstrapSubmit (fromString msg) "btn-primary" [] > Person < $ > areq " Name " Nothing > < * > areq " Surname " Nothing > Person < $ > areq " Name " Nothing > < * > areq " Surname " Nothing > < * bootstrapSubmit ( " Register " : : BootstrapSubmit Text ) bootstrapSubmit :: (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m) => BootstrapSubmit msg -> AForm m () bootstrapSubmit = formToAForm . fmap (second return) . mbootstrapSubmit mbootstrapSubmit :: (RenderMessage site msg, HandlerSite m ~ site, MonadHandler m) => BootstrapSubmit msg -> MForm m (FormResult (), FieldView site) mbootstrapSubmit (BootstrapSubmit msg classes attrs) = let res = FormSuccess () widget = [whamlet|<button class="btn #{classes}" type=submit *{attrs}>_{msg}|] fv = FieldView { fvLabel = "" , fvTooltip = Nothing , fvId = bootstrapSubmitId , fvInput = widget , fvErrors = Nothing , fvRequired = False } in return (res, fv) | A royal hack . Magic i d used to identify whether a field should have no label . A valid HTML4 i d which is probably not bootstrapSubmitId :: Text bootstrapSubmitId = "b:ootstrap___unique__:::::::::::::::::submit-id"
4ef27fcc569ad347b4b3363f38ade641180c2db126b9f913b8706a10dbcd4b47
ocaml-flambda/ocaml-jst
typedtree.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Abstract syntax tree after typing *) * By comparison with { ! : - Every { ! Longindent.t } is accompanied by a resolved { ! Path.t } . - Every {!Longindent.t} is accompanied by a resolved {!Path.t}. *) open Asttypes (* Value expressions for the core language *) type partial = Partial | Total * { 1 Extension points } type attribute = Parsetree.attribute type attributes = attribute list * { 1 Core language } type value = Value_pattern type computation = Computation_pattern type _ pattern_category = | Value : value pattern_category | Computation : computation pattern_category type pattern = value general_pattern and 'k general_pattern = 'k pattern_desc pattern_data and 'a pattern_data = { pat_desc: 'a; pat_loc: Location.t; pat_extra : (pat_extra * Location.t * attributes) list; pat_type: Types.type_expr; pat_env: Env.t; pat_attributes: attributes; } and pat_extra = | Tpat_constraint of core_type * P : T ; pat_extra = ( Tpat_constraint T , _ , _ ) : : ... } ; pat_extra = (Tpat_constraint T, _, _) :: ... } *) | Tpat_type of Path.t * Longident.t loc * # tconst disjunction ; pat_extra = ( Tpat_type ( P , " tconst " ) , _ , _ ) : : ... } where [ disjunction ] is a [ Tpat_or _ ] representing the branches of [ tconst ] . ; pat_extra = (Tpat_type (P, "tconst"), _, _) :: ...} where [disjunction] is a [Tpat_or _] representing the branches of [tconst]. *) | Tpat_open of Path.t * Longident.t loc * Env.t | Tpat_unpack * ( module P ) Tpat_var " P " ; pat_extra = ( Tpat_unpack , _ , _ ) : : ... } ; pat_extra = (Tpat_unpack, _, _) :: ... } *) and 'k pattern_desc = (* value patterns *) | Tpat_any : value pattern_desc (** _ *) | Tpat_var : Ident.t * string loc * Types.value_mode -> value pattern_desc (** x *) | Tpat_alias : value general_pattern * Ident.t * string loc * Types.value_mode -> value pattern_desc (** P as a *) | Tpat_constant : constant -> value pattern_desc * 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n | Tpat_tuple : value general_pattern list -> value pattern_desc * ( P1 , ... , Pn ) Invariant : n > = 2 Invariant: n >= 2 *) | Tpat_construct : Longident.t loc * Types.constructor_description * value general_pattern list * (Ident.t loc list * core_type) option -> value pattern_desc * C ( [ ] , None ) C P ( [ P ] , None ) C ( P1 , ... , Pn ) ( [ P1 ; ... ; Pn ] , None ) C ( P : t ) ( [ P ] , Some ( [ ] , t ) ) C ( P1 , ... , Pn : t ) ( [ P1 ; ... ; Pn ] , Some ( [ ] , t ) ) C ( type a ) ( P : t ) ( [ P ] , Some ( [ a ] , t ) ) C ( type a ) ( P1 , ... , Pn : t ) ( [ P1 ; ... ; Pn ] , Some ( [ a ] , t ) ) C P ([P], None) C (P1, ..., Pn) ([P1; ...; Pn], None) C (P : t) ([P], Some ([], t)) C (P1, ..., Pn : t) ([P1; ...; Pn], Some ([], t)) C (type a) (P : t) ([P], Some ([a], t)) C (type a) (P1, ..., Pn : t) ([P1; ...; Pn], Some ([a], t)) *) | Tpat_variant : label * value general_pattern option * Types.row_desc ref -> value pattern_desc (** `A (None) `A P (Some P) See {!Types.row_desc} for an explanation of the last parameter. *) | Tpat_record : (Longident.t loc * Types.label_description * value general_pattern) list * closed_flag -> value pattern_desc * { l1 = P1 ; ... ; ln = Pn } ( flag = Closed ) { l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open ) Invariant : n > 0 { l1=P1; ...; ln=Pn; _} (flag = Open) Invariant: n > 0 *) | Tpat_array : mutable_flag * value general_pattern list -> value pattern_desc * [ | P1 ; ... ; Pn | ] ( flag = Mutable ) [: P1 ; ... ; Pn :] ( flag = Immutable ) [: P1; ...; Pn :] (flag = Immutable) *) | Tpat_lazy : value general_pattern -> value pattern_desc (** lazy P *) (* computation patterns *) | Tpat_value : tpat_value_argument -> computation pattern_desc (** P Invariant: Tpat_value pattern should not carry pat_attributes or pat_extra metadata coming from user syntax, which must be on the inner pattern node -- to facilitate searching for a certain value pattern constructor with a specific attributed. To enforce this restriction, we made the argument of the Tpat_value constructor a private synonym of [pattern], requiring you to use the [as_computation_pattern] function below instead of using the [Tpat_value] constructor directly. *) | Tpat_exception : value general_pattern -> computation pattern_desc (** exception P *) (* generic constructions *) | Tpat_or : 'k general_pattern * 'k general_pattern * Types.row_desc option -> 'k pattern_desc (** P1 | P2 [row_desc] = [Some _] when translating [Ppat_type _], [None] otherwise. *) and tpat_value_argument = private value general_pattern and expression = { exp_desc: expression_desc; exp_loc: Location.t; exp_extra: (exp_extra * Location.t * attributes) list; exp_type: Types.type_expr; exp_env: Env.t; exp_attributes: attributes; } and exp_extra = | Texp_constraint of core_type (** E : T *) | Texp_coerce of core_type option * core_type * E :> T [ Texp_coerce ( None , T ) ] E : T0 :> T [ Texp_coerce ( Some T0 , T ) ] E : T0 :> T [Texp_coerce (Some T0, T)] *) | Texp_poly of core_type option (** Used for method bodies. *) | Texp_newtype of string (** fun (type t) -> *) and fun_curry_state = | More_args of { partial_mode : Types.alloc_mode } (** [partial_mode] is the mode of the resulting closure if this function is partially applied *) | Final_arg of { partial_mode : Types.alloc_mode } * [ partial_mode ] is relevant for the final arg only because of an optimisation that Simplif does to merge functions , which might result in this arg no longer being final because of an optimisation that Simplif does to merge functions, which might result in this arg no longer being final *) and expression_desc = Texp_ident of Path.t * Longident.t loc * Types.value_description * ident_kind * x M.x *) | Texp_constant of constant * 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n | Texp_let of rec_flag * value_binding list * expression * let P1 = E1 and ... and Pn = EN in E ( flag = ) let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive ) let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive) *) | Texp_function of { arg_label : arg_label; param : Ident.t; cases : value case list; partial : partial; region : bool; curry : fun_curry_state; warnings : Warnings.state; arg_mode : Types.alloc_mode; alloc_mode : Types.alloc_mode} * [ Pexp_fun ] and [ Pexp_function ] both translate to [ Texp_function ] . See { ! for more details . [ param ] is the identifier that is to be used to name the parameter of the function . partial = [ Partial ] if the pattern match is partial [ Total ] otherwise . partial_mode is the mode of the resulting closure if this function is partially applied to a single argument . See {!Parsetree} for more details. [param] is the identifier that is to be used to name the parameter of the function. partial = [Partial] if the pattern match is partial [Total] otherwise. partial_mode is the mode of the resulting closure if this function is partially applied to a single argument. *) | Texp_apply of expression * (arg_label * apply_arg) list * apply_position * Types.alloc_mode * E0 ~l1 : E1 ... ~ln : En The expression can be Omitted if the expression is abstracted over this argument . It currently appears when a label is applied . For example : let f x ~y = x + y in f ~y:3 The resulting typedtree for the application is : Texp_apply ( Texp_ident " f/1037 " , [ ( Nolabel , Omitted _ ) ; ( Labelled " y " , Some ( Texp_constant Const_int 3 ) ) ] ) The expression can be Omitted if the expression is abstracted over this argument. It currently appears when a label is applied. For example: let f x ~y = x + y in f ~y:3 The resulting typedtree for the application is: Texp_apply (Texp_ident "f/1037", [(Nolabel, Omitted _); (Labelled "y", Some (Texp_constant Const_int 3)) ]) *) | Texp_match of expression * computation case list * partial * match E0 with | P1 - > E1 | P2 | exception P3 - > E2 | exception P4 - > E3 [ Texp_match ( E0 , [ ( P1 , E1 ) ; ( P2 | exception P3 , E2 ) ; ( exception P4 , E3 ) ] , _ ) ] | P1 -> E1 | P2 | exception P3 -> E2 | exception P4 -> E3 [Texp_match (E0, [(P1, E1); (P2 | exception P3, E2); (exception P4, E3)], _)] *) | Texp_try of expression * value case list (** try E with P1 -> E1 | ... | PN -> EN *) | Texp_tuple of expression list * Types.alloc_mode (** (E1, ..., EN) *) | Texp_construct of Longident.t loc * Types.constructor_description * expression list * Types.alloc_mode option (** C [] C E [E] C (E1, ..., En) [E1;...;En] [alloc_mode] is the allocation mode of the construct, or [None] if the constructor is [Cstr_unboxed] or [Cstr_constant], in which case it does not need allocation. *) | Texp_variant of label * (expression * Types.alloc_mode) option (** [alloc_mode] is the allocation mode of the variant, or [None] if the variant has no argument, in which case it does not need allocation. *) | Texp_record of { fields : ( Types.label_description * record_label_definition ) array; representation : Types.record_representation; extended_expression : expression option; alloc_mode : Types.alloc_mode option } * { l1 = P1 ; ... ; ln = Pn } ( extended_expression = None ) { E0 with l1 = P1 ; ... ; ln = Pn } ( extended_expression = Some E0 ) Invariant : n > 0 If the type is { l1 : t1 ; l2 : t2 } , the expression { E0 with t2 = P2 } is represented as Texp_record { fields = [ | l1 , Kept t1 ; l2 Override P2 | ] ; representation ; extended_expression = Some E0 } [ alloc_mode ] is the allocation mode of the record , or [ None ] if it is [ Record_unboxed ] , in which case it does not need allocation . { E0 with l1=P1; ...; ln=Pn } (extended_expression = Some E0) Invariant: n > 0 If the type is { l1: t1; l2: t2 }, the expression { E0 with t2=P2 } is represented as Texp_record { fields = [| l1, Kept t1; l2 Override P2 |]; representation; extended_expression = Some E0 } [alloc_mode] is the allocation mode of the record, or [None] if it is [Record_unboxed], in which case it does not need allocation. *) | Texp_field of expression * Longident.t loc * Types.label_description * Types.alloc_mode option (** [alloc_mode] is the allocation mode of the result; available ONLY when getting a (float) field from a [Record_float] record *) | Texp_setfield of expression * Types.alloc_mode * Longident.t loc * Types.label_description * expression (** [alloc_mode] translates to the [modify_mode] of the record *) | Texp_array of mutable_flag * expression list * Types.alloc_mode | Texp_list_comprehension of comprehension | Texp_array_comprehension of mutable_flag * comprehension | Texp_ifthenelse of expression * expression * expression option | Texp_sequence of expression * expression | Texp_while of { wh_cond : expression; wh_cond_region : bool; (* False means allocates in outer region *) wh_body : expression; wh_body_region : bool (* False means allocates in outer region *) } | Texp_for of { for_id : Ident.t; for_pat : Parsetree.pattern; for_from : expression; for_to : expression; for_dir : direction_flag; for_body : expression; for_region : bool; (* for_region = true means we create a region for the body. false means it may allocated in the containing region *) } | Texp_send of expression * meth * apply_position * Types.alloc_mode (** [alloc_mode] is the allocation mode of the result *) | Texp_new of Path.t * Longident.t loc * Types.class_declaration * apply_position | Texp_instvar of Path.t * Path.t * string loc | Texp_setinstvar of Path.t * Path.t * string loc * expression | Texp_override of Path.t * (Ident.t * string loc * expression) list | Texp_letmodule of Ident.t option * string option loc * Types.module_presence * module_expr * expression | Texp_letexception of extension_constructor * expression | Texp_assert of expression | Texp_lazy of expression | Texp_object of class_structure * string list | Texp_pack of module_expr | Texp_letop of { let_ : binding_op; ands : binding_op list; param : Ident.t; body : value case; partial : partial; warnings : Warnings.state; } | Texp_unreachable | Texp_extension_constructor of Longident.t loc * Path.t | Texp_open of open_declaration * expression (** let open[!] M in e *) | Texp_probe of { name:string; handler:expression; } | Texp_probe_is_enabled of { name:string } and ident_kind = Id_value | Id_prim of Types.alloc_mode option and meth = Tmeth_name of string | Tmeth_val of Ident.t | Tmeth_ancestor of Ident.t * Path.t and comprehension = { comp_body : expression; comp_clauses : comprehension_clause list } and comprehension_clause = | Texp_comp_for of comprehension_clause_binding list | Texp_comp_when of expression and comprehension_clause_binding = { comp_cb_iterator : comprehension_iterator; comp_cb_attributes : attribute list } (* We move the pattern into the [comprehension_iterator], compared to the untyped syntax tree, so that range-based iterators can have just an identifier instead of a full pattern *) and comprehension_iterator = | Texp_comp_range of { ident : Ident.t ; pattern : Parsetree.pattern (* Redundant with [ident] *) ; start : expression ; stop : expression ; direction : direction_flag } | Texp_comp_in of { pattern : pattern ; sequence : expression } and 'k case = { c_lhs: 'k general_pattern; c_guard: expression option; c_rhs: expression; } and record_label_definition = | Kept of Types.type_expr | Overridden of Longident.t loc * expression and binding_op = { bop_op_path : Path.t; bop_op_name : string loc; bop_op_val : Types.value_description; bop_op_type : Types.type_expr; (* This is the type at which the operator was used. It is always an instance of [bop_op_val.val_type] *) bop_exp : expression; bop_loc : Location.t; } and ('a, 'b) arg_or_omitted = | Arg of 'a | Omitted of 'b and omitted_parameter = { mode_closure : Types.alloc_mode; mode_arg : Types.alloc_mode; mode_ret : Types.alloc_mode } and apply_arg = (expression, omitted_parameter) arg_or_omitted and apply_position = | Tail (* must be tail-call optimised *) | Nontail (* must not be tail-call optimised *) | Default (* tail-call optimised if in tail position *) (* Value expressions for the class language *) and class_expr = { cl_desc: class_expr_desc; cl_loc: Location.t; cl_type: Types.class_type; cl_env: Env.t; cl_attributes: attributes; } and class_expr_desc = Tcl_ident of Path.t * Longident.t loc * core_type list | Tcl_structure of class_structure | Tcl_fun of arg_label * pattern * (Ident.t * expression) list * class_expr * partial | Tcl_apply of class_expr * (arg_label * apply_arg) list | Tcl_let of rec_flag * value_binding list * (Ident.t * expression) list * class_expr | Tcl_constraint of class_expr * class_type option * string list * string list * Types.MethSet.t (* Visible instance variables, methods and concrete methods *) | Tcl_open of open_description * class_expr and class_structure = { cstr_self: pattern; cstr_fields: class_field list; cstr_type: Types.class_signature; cstr_meths: Ident.t Types.Meths.t; } and class_field = { cf_desc: class_field_desc; cf_loc: Location.t; cf_attributes: attributes; } and class_field_kind = | Tcfk_virtual of core_type | Tcfk_concrete of override_flag * expression and class_field_desc = Tcf_inherit of override_flag * class_expr * string option * (string * Ident.t) list * (string * Ident.t) list (* Inherited instance variables and concrete methods *) | Tcf_val of string loc * mutable_flag * Ident.t * class_field_kind * bool | Tcf_method of string loc * private_flag * class_field_kind | Tcf_constraint of core_type * core_type | Tcf_initializer of expression | Tcf_attribute of attribute (* Value expressions for the module language *) and module_expr = { mod_desc: module_expr_desc; mod_loc: Location.t; mod_type: Types.module_type; mod_env: Env.t; mod_attributes: attributes; } (** Annotations for [Tmod_constraint]. *) and module_type_constraint = | Tmodtype_implicit (** The module type constraint has been synthesized during typechecking. *) | Tmodtype_explicit of module_type (** The module type was in the source file. *) and functor_parameter = | Unit | Named of Ident.t option * string option loc * module_type and module_expr_desc = Tmod_ident of Path.t * Longident.t loc | Tmod_structure of structure | Tmod_functor of functor_parameter * module_expr | Tmod_apply of module_expr * module_expr * module_coercion | Tmod_constraint of module_expr * Types.module_type * module_type_constraint * module_coercion (** ME (constraint = Tmodtype_implicit) (ME : MT) (constraint = Tmodtype_explicit MT) *) | Tmod_unpack of expression * Types.module_type and structure = { str_items : structure_item list; str_type : Types.signature; str_final_env : Env.t; } and structure_item = { str_desc : structure_item_desc; str_loc : Location.t; str_env : Env.t } and structure_item_desc = Tstr_eval of expression * attributes | Tstr_value of rec_flag * value_binding list | Tstr_primitive of value_description | Tstr_type of rec_flag * type_declaration list | Tstr_typext of type_extension | Tstr_exception of type_exception | Tstr_module of module_binding | Tstr_recmodule of module_binding list | Tstr_modtype of module_type_declaration | Tstr_open of open_declaration | Tstr_class of (class_declaration * string list) list | Tstr_class_type of (Ident.t * string loc * class_type_declaration) list | Tstr_include of include_declaration | Tstr_attribute of attribute and module_binding = { mb_id: Ident.t option; mb_name: string option loc; mb_presence: Types.module_presence; mb_expr: module_expr; mb_attributes: attributes; mb_loc: Location.t; } and value_binding = { vb_pat: pattern; vb_expr: expression; vb_attributes: attributes; vb_loc: Location.t; } and module_coercion = Tcoerce_none | Tcoerce_structure of (int * module_coercion) list * (Ident.t * int * module_coercion) list | Tcoerce_functor of module_coercion * module_coercion | Tcoerce_primitive of primitive_coercion | Tcoerce_alias of Env.t * Path.t * module_coercion and module_type = { mty_desc: module_type_desc; mty_type : Types.module_type; mty_env : Env.t; mty_loc: Location.t; mty_attributes: attributes; } and module_type_desc = Tmty_ident of Path.t * Longident.t loc | Tmty_signature of signature | Tmty_functor of functor_parameter * module_type | Tmty_with of module_type * (Path.t * Longident.t loc * with_constraint) list | Tmty_typeof of module_expr | Tmty_alias of Path.t * Longident.t loc and primitive_coercion = { pc_desc: Primitive.description; pc_type: Types.type_expr; pc_poly_mode: Types.alloc_mode option; pc_env: Env.t; pc_loc : Location.t; } and signature = { sig_items : signature_item list; sig_type : Types.signature; sig_final_env : Env.t; } and signature_item = { sig_desc: signature_item_desc; sig_env : Env.t; (* BINANNOT ADDED *) sig_loc: Location.t } and signature_item_desc = Tsig_value of value_description | Tsig_type of rec_flag * type_declaration list | Tsig_typesubst of type_declaration list | Tsig_typext of type_extension | Tsig_exception of type_exception | Tsig_module of module_declaration | Tsig_modsubst of module_substitution | Tsig_recmodule of module_declaration list | Tsig_modtype of module_type_declaration | Tsig_modtypesubst of module_type_declaration | Tsig_open of open_description | Tsig_include of include_description | Tsig_class of class_description list | Tsig_class_type of class_type_declaration list | Tsig_attribute of attribute and module_declaration = { md_id: Ident.t option; md_name: string option loc; md_presence: Types.module_presence; md_type: module_type; md_attributes: attributes; md_loc: Location.t; } and module_substitution = { ms_id: Ident.t; ms_name: string loc; ms_manifest: Path.t; ms_txt: Longident.t loc; ms_attributes: attributes; ms_loc: Location.t; } and module_type_declaration = { mtd_id: Ident.t; mtd_name: string loc; mtd_type: module_type option; mtd_attributes: attributes; mtd_loc: Location.t; } and 'a open_infos = { open_expr: 'a; open_bound_items: Types.signature; open_override: override_flag; open_env: Env.t; open_loc: Location.t; open_attributes: attribute list; } and open_description = (Path.t * Longident.t loc) open_infos and open_declaration = module_expr open_infos and include_kind = | Tincl_structure | Tincl_functor of (Ident.t * module_coercion) list (* S1 -> S2 *) | Tincl_gen_functor of (Ident.t * module_coercion) list (* S1 -> () -> S2 *) and 'a include_infos = { incl_mod: 'a; incl_type: Types.signature; incl_loc: Location.t; incl_kind: include_kind; incl_attributes: attribute list; } and include_description = module_type include_infos and include_declaration = module_expr include_infos and with_constraint = Twith_type of type_declaration | Twith_module of Path.t * Longident.t loc | Twith_modtype of module_type | Twith_typesubst of type_declaration | Twith_modsubst of Path.t * Longident.t loc | Twith_modtypesubst of module_type and core_type = { mutable ctyp_desc : core_type_desc; (** mutable because of [Typeclass.declare_method] *) mutable ctyp_type : Types.type_expr; (** mutable because of [Typeclass.declare_method] *) ctyp_env : Env.t; (* BINANNOT ADDED *) ctyp_loc : Location.t; ctyp_attributes: attributes; } and core_type_desc = Ttyp_any | Ttyp_var of string | Ttyp_arrow of arg_label * core_type * core_type | Ttyp_tuple of core_type list | Ttyp_constr of Path.t * Longident.t loc * core_type list | Ttyp_object of object_field list * closed_flag | Ttyp_class of Path.t * Longident.t loc * core_type list | Ttyp_alias of core_type * string | Ttyp_variant of row_field list * closed_flag * label list option | Ttyp_poly of string list * core_type | Ttyp_package of package_type and package_type = { pack_path : Path.t; pack_fields : (Longident.t loc * core_type) list; pack_type : Types.module_type; pack_txt : Longident.t loc; } and row_field = { rf_desc : row_field_desc; rf_loc : Location.t; rf_attributes : attributes; } and row_field_desc = Ttag of string loc * bool * core_type list | Tinherit of core_type and object_field = { of_desc : object_field_desc; of_loc : Location.t; of_attributes : attributes; } and object_field_desc = | OTtag of string loc * core_type | OTinherit of core_type and value_description = { val_id: Ident.t; val_name: string loc; val_desc: core_type; val_val: Types.value_description; val_prim: string list; val_loc: Location.t; val_attributes: attributes; } and type_declaration = { typ_id: Ident.t; typ_name: string loc; typ_params: (core_type * (variance * injectivity)) list; typ_type: Types.type_declaration; typ_cstrs: (core_type * core_type * Location.t) list; typ_kind: type_kind; typ_private: private_flag; typ_manifest: core_type option; typ_loc: Location.t; typ_attributes: attributes; } and type_kind = Ttype_abstract | Ttype_variant of constructor_declaration list | Ttype_record of label_declaration list | Ttype_open and label_declaration = { ld_id: Ident.t; ld_name: string loc; ld_mutable: mutable_flag; ld_global: Types.global_flag; ld_type: core_type; ld_loc: Location.t; ld_attributes: attributes; } and constructor_declaration = { cd_id: Ident.t; cd_name: string loc; cd_vars: string loc list; cd_args: constructor_arguments; cd_res: core_type option; cd_loc: Location.t; cd_attributes: attributes; } and constructor_arguments = | Cstr_tuple of (core_type * Types.global_flag) list | Cstr_record of label_declaration list and type_extension = { tyext_path: Path.t; tyext_txt: Longident.t loc; tyext_params: (core_type * (variance * injectivity)) list; tyext_constructors: extension_constructor list; tyext_private: private_flag; tyext_loc: Location.t; tyext_attributes: attributes; } and type_exception = { tyexn_constructor: extension_constructor; tyexn_loc: Location.t; tyexn_attributes: attribute list; } and extension_constructor = { ext_id: Ident.t; ext_name: string loc; ext_type : Types.extension_constructor; ext_kind : extension_constructor_kind; ext_loc : Location.t; ext_attributes: attributes; } and extension_constructor_kind = Text_decl of string loc list * constructor_arguments * core_type option | Text_rebind of Path.t * Longident.t loc and class_type = { cltyp_desc: class_type_desc; cltyp_type: Types.class_type; cltyp_env: Env.t; cltyp_loc: Location.t; cltyp_attributes: attributes; } and class_type_desc = Tcty_constr of Path.t * Longident.t loc * core_type list | Tcty_signature of class_signature | Tcty_arrow of arg_label * core_type * class_type | Tcty_open of open_description * class_type and class_signature = { csig_self : core_type; csig_fields : class_type_field list; csig_type : Types.class_signature; } and class_type_field = { ctf_desc: class_type_field_desc; ctf_loc: Location.t; ctf_attributes: attributes; } and class_type_field_desc = | Tctf_inherit of class_type | Tctf_val of (string * mutable_flag * virtual_flag * core_type) | Tctf_method of (string * private_flag * virtual_flag * core_type) | Tctf_constraint of (core_type * core_type) | Tctf_attribute of attribute and class_declaration = class_expr class_infos and class_description = class_type class_infos and class_type_declaration = class_type class_infos and 'a class_infos = { ci_virt: virtual_flag; ci_params: (core_type * (variance * injectivity)) list; ci_id_name : string loc; ci_id_class: Ident.t; ci_id_class_type : Ident.t; ci_id_object : Ident.t; ci_id_typehash : Ident.t; ci_expr: 'a; ci_decl: Types.class_declaration; ci_type_decl : Types.class_type_declaration; ci_loc: Location.t; ci_attributes: attributes; } type implementation = { structure: structure; coercion: module_coercion; signature: Types.signature; shape: Shape.t; } (** A typechecked implementation including its module structure, its exported signature, and a coercion of the module against that signature. If an .mli file is present, the signature will come from that file and be the exported signature of the module. If there isn't one, the signature will be inferred from the module structure. *) (* Auxiliary functions over the a.s.t. *) * [ as_computation_pattern p ] is a computation pattern with description [ Tpat_value p ] , which enforces a correct placement of pat_attributes and pat_extra metadata ( on the inner value pattern , rather than on the computation pattern ) . [Tpat_value p], which enforces a correct placement of pat_attributes and pat_extra metadata (on the inner value pattern, rather than on the computation pattern). *) val as_computation_pattern: pattern -> computation general_pattern val classify_pattern_desc: 'k pattern_desc -> 'k pattern_category val classify_pattern: 'k general_pattern -> 'k pattern_category type pattern_action = { f : 'k . 'k general_pattern -> unit } val shallow_iter_pattern_desc: pattern_action -> 'k pattern_desc -> unit type pattern_transformation = { f : 'k . 'k general_pattern -> 'k general_pattern } val shallow_map_pattern_desc: pattern_transformation -> 'k pattern_desc -> 'k pattern_desc val iter_general_pattern: pattern_action -> 'k general_pattern -> unit val iter_pattern: (pattern -> unit) -> pattern -> unit type pattern_predicate = { f : 'k . 'k general_pattern -> bool } val exists_general_pattern: pattern_predicate -> 'k general_pattern -> bool val exists_pattern: (pattern -> bool) -> pattern -> bool val let_bound_idents: value_binding list -> Ident.t list val let_bound_idents_full: value_binding list -> (Ident.t * string loc * Types.type_expr) list val let_bound_idents_with_modes: value_binding list -> (Ident.t * (Location.t * Types.value_mode) list) list (** Alpha conversion of patterns *) val alpha_pat: (Ident.t * Ident.t) list -> 'k general_pattern -> 'k general_pattern val mknoloc: 'a -> 'a Asttypes.loc val mkloc: 'a -> Location.t -> 'a Asttypes.loc val pat_bound_idents: 'k general_pattern -> Ident.t list val pat_bound_idents_full: 'k general_pattern -> (Ident.t * string loc * Types.type_expr) list (** Splits an or pattern into its value (left) and exception (right) parts. *) val split_pattern: computation general_pattern -> pattern option * pattern option
null
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/4fd53a1f6fa8e93d60e808bc82ee79f622709f09/typing/typedtree.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Abstract syntax tree after typing Value expressions for the core language value patterns * _ * x * P as a * `A (None) `A P (Some P) See {!Types.row_desc} for an explanation of the last parameter. * lazy P computation patterns * P Invariant: Tpat_value pattern should not carry pat_attributes or pat_extra metadata coming from user syntax, which must be on the inner pattern node -- to facilitate searching for a certain value pattern constructor with a specific attributed. To enforce this restriction, we made the argument of the Tpat_value constructor a private synonym of [pattern], requiring you to use the [as_computation_pattern] function below instead of using the [Tpat_value] constructor directly. * exception P generic constructions * P1 | P2 [row_desc] = [Some _] when translating [Ppat_type _], [None] otherwise. * E : T * Used for method bodies. * fun (type t) -> * [partial_mode] is the mode of the resulting closure if this function is partially applied * try E with P1 -> E1 | ... | PN -> EN * (E1, ..., EN) * C [] C E [E] C (E1, ..., En) [E1;...;En] [alloc_mode] is the allocation mode of the construct, or [None] if the constructor is [Cstr_unboxed] or [Cstr_constant], in which case it does not need allocation. * [alloc_mode] is the allocation mode of the variant, or [None] if the variant has no argument, in which case it does not need allocation. * [alloc_mode] is the allocation mode of the result; available ONLY when getting a (float) field from a [Record_float] record * [alloc_mode] translates to the [modify_mode] of the record False means allocates in outer region False means allocates in outer region for_region = true means we create a region for the body. false means it may allocated in the containing region * [alloc_mode] is the allocation mode of the result * let open[!] M in e We move the pattern into the [comprehension_iterator], compared to the untyped syntax tree, so that range-based iterators can have just an identifier instead of a full pattern Redundant with [ident] This is the type at which the operator was used. It is always an instance of [bop_op_val.val_type] must be tail-call optimised must not be tail-call optimised tail-call optimised if in tail position Value expressions for the class language Visible instance variables, methods and concrete methods Inherited instance variables and concrete methods Value expressions for the module language * Annotations for [Tmod_constraint]. * The module type constraint has been synthesized during typechecking. * The module type was in the source file. * ME (constraint = Tmodtype_implicit) (ME : MT) (constraint = Tmodtype_explicit MT) BINANNOT ADDED S1 -> S2 S1 -> () -> S2 * mutable because of [Typeclass.declare_method] * mutable because of [Typeclass.declare_method] BINANNOT ADDED * A typechecked implementation including its module structure, its exported signature, and a coercion of the module against that signature. If an .mli file is present, the signature will come from that file and be the exported signature of the module. If there isn't one, the signature will be inferred from the module structure. Auxiliary functions over the a.s.t. * Alpha conversion of patterns * Splits an or pattern into its value (left) and exception (right) parts.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * By comparison with { ! : - Every { ! Longindent.t } is accompanied by a resolved { ! Path.t } . - Every {!Longindent.t} is accompanied by a resolved {!Path.t}. *) open Asttypes type partial = Partial | Total * { 1 Extension points } type attribute = Parsetree.attribute type attributes = attribute list * { 1 Core language } type value = Value_pattern type computation = Computation_pattern type _ pattern_category = | Value : value pattern_category | Computation : computation pattern_category type pattern = value general_pattern and 'k general_pattern = 'k pattern_desc pattern_data and 'a pattern_data = { pat_desc: 'a; pat_loc: Location.t; pat_extra : (pat_extra * Location.t * attributes) list; pat_type: Types.type_expr; pat_env: Env.t; pat_attributes: attributes; } and pat_extra = | Tpat_constraint of core_type * P : T ; pat_extra = ( Tpat_constraint T , _ , _ ) : : ... } ; pat_extra = (Tpat_constraint T, _, _) :: ... } *) | Tpat_type of Path.t * Longident.t loc * # tconst disjunction ; pat_extra = ( Tpat_type ( P , " tconst " ) , _ , _ ) : : ... } where [ disjunction ] is a [ Tpat_or _ ] representing the branches of [ tconst ] . ; pat_extra = (Tpat_type (P, "tconst"), _, _) :: ...} where [disjunction] is a [Tpat_or _] representing the branches of [tconst]. *) | Tpat_open of Path.t * Longident.t loc * Env.t | Tpat_unpack * ( module P ) Tpat_var " P " ; pat_extra = ( Tpat_unpack , _ , _ ) : : ... } ; pat_extra = (Tpat_unpack, _, _) :: ... } *) and 'k pattern_desc = | Tpat_any : value pattern_desc | Tpat_var : Ident.t * string loc * Types.value_mode -> value pattern_desc | Tpat_alias : value general_pattern * Ident.t * string loc * Types.value_mode -> value pattern_desc | Tpat_constant : constant -> value pattern_desc * 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n | Tpat_tuple : value general_pattern list -> value pattern_desc * ( P1 , ... , Pn ) Invariant : n > = 2 Invariant: n >= 2 *) | Tpat_construct : Longident.t loc * Types.constructor_description * value general_pattern list * (Ident.t loc list * core_type) option -> value pattern_desc * C ( [ ] , None ) C P ( [ P ] , None ) C ( P1 , ... , Pn ) ( [ P1 ; ... ; Pn ] , None ) C ( P : t ) ( [ P ] , Some ( [ ] , t ) ) C ( P1 , ... , Pn : t ) ( [ P1 ; ... ; Pn ] , Some ( [ ] , t ) ) C ( type a ) ( P : t ) ( [ P ] , Some ( [ a ] , t ) ) C ( type a ) ( P1 , ... , Pn : t ) ( [ P1 ; ... ; Pn ] , Some ( [ a ] , t ) ) C P ([P], None) C (P1, ..., Pn) ([P1; ...; Pn], None) C (P : t) ([P], Some ([], t)) C (P1, ..., Pn : t) ([P1; ...; Pn], Some ([], t)) C (type a) (P : t) ([P], Some ([a], t)) C (type a) (P1, ..., Pn : t) ([P1; ...; Pn], Some ([a], t)) *) | Tpat_variant : label * value general_pattern option * Types.row_desc ref -> value pattern_desc | Tpat_record : (Longident.t loc * Types.label_description * value general_pattern) list * closed_flag -> value pattern_desc * { l1 = P1 ; ... ; ln = Pn } ( flag = Closed ) { l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open ) Invariant : n > 0 { l1=P1; ...; ln=Pn; _} (flag = Open) Invariant: n > 0 *) | Tpat_array : mutable_flag * value general_pattern list -> value pattern_desc * [ | P1 ; ... ; Pn | ] ( flag = Mutable ) [: P1 ; ... ; Pn :] ( flag = Immutable ) [: P1; ...; Pn :] (flag = Immutable) *) | Tpat_lazy : value general_pattern -> value pattern_desc | Tpat_value : tpat_value_argument -> computation pattern_desc | Tpat_exception : value general_pattern -> computation pattern_desc | Tpat_or : 'k general_pattern * 'k general_pattern * Types.row_desc option -> 'k pattern_desc and tpat_value_argument = private value general_pattern and expression = { exp_desc: expression_desc; exp_loc: Location.t; exp_extra: (exp_extra * Location.t * attributes) list; exp_type: Types.type_expr; exp_env: Env.t; exp_attributes: attributes; } and exp_extra = | Texp_constraint of core_type | Texp_coerce of core_type option * core_type * E :> T [ Texp_coerce ( None , T ) ] E : T0 :> T [ Texp_coerce ( Some T0 , T ) ] E : T0 :> T [Texp_coerce (Some T0, T)] *) | Texp_poly of core_type option | Texp_newtype of string and fun_curry_state = | More_args of { partial_mode : Types.alloc_mode } | Final_arg of { partial_mode : Types.alloc_mode } * [ partial_mode ] is relevant for the final arg only because of an optimisation that Simplif does to merge functions , which might result in this arg no longer being final because of an optimisation that Simplif does to merge functions, which might result in this arg no longer being final *) and expression_desc = Texp_ident of Path.t * Longident.t loc * Types.value_description * ident_kind * x M.x *) | Texp_constant of constant * 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n | Texp_let of rec_flag * value_binding list * expression * let P1 = E1 and ... and Pn = EN in E ( flag = ) let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive ) let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive) *) | Texp_function of { arg_label : arg_label; param : Ident.t; cases : value case list; partial : partial; region : bool; curry : fun_curry_state; warnings : Warnings.state; arg_mode : Types.alloc_mode; alloc_mode : Types.alloc_mode} * [ Pexp_fun ] and [ Pexp_function ] both translate to [ Texp_function ] . See { ! for more details . [ param ] is the identifier that is to be used to name the parameter of the function . partial = [ Partial ] if the pattern match is partial [ Total ] otherwise . partial_mode is the mode of the resulting closure if this function is partially applied to a single argument . See {!Parsetree} for more details. [param] is the identifier that is to be used to name the parameter of the function. partial = [Partial] if the pattern match is partial [Total] otherwise. partial_mode is the mode of the resulting closure if this function is partially applied to a single argument. *) | Texp_apply of expression * (arg_label * apply_arg) list * apply_position * Types.alloc_mode * E0 ~l1 : E1 ... ~ln : En The expression can be Omitted if the expression is abstracted over this argument . It currently appears when a label is applied . For example : let f x ~y = x + y in f ~y:3 The resulting typedtree for the application is : Texp_apply ( Texp_ident " f/1037 " , [ ( Nolabel , Omitted _ ) ; ( Labelled " y " , Some ( Texp_constant Const_int 3 ) ) ] ) The expression can be Omitted if the expression is abstracted over this argument. It currently appears when a label is applied. For example: let f x ~y = x + y in f ~y:3 The resulting typedtree for the application is: Texp_apply (Texp_ident "f/1037", [(Nolabel, Omitted _); (Labelled "y", Some (Texp_constant Const_int 3)) ]) *) | Texp_match of expression * computation case list * partial * match E0 with | P1 - > E1 | P2 | exception P3 - > E2 | exception P4 - > E3 [ Texp_match ( E0 , [ ( P1 , E1 ) ; ( P2 | exception P3 , E2 ) ; ( exception P4 , E3 ) ] , _ ) ] | P1 -> E1 | P2 | exception P3 -> E2 | exception P4 -> E3 [Texp_match (E0, [(P1, E1); (P2 | exception P3, E2); (exception P4, E3)], _)] *) | Texp_try of expression * value case list | Texp_tuple of expression list * Types.alloc_mode | Texp_construct of Longident.t loc * Types.constructor_description * expression list * Types.alloc_mode option | Texp_variant of label * (expression * Types.alloc_mode) option | Texp_record of { fields : ( Types.label_description * record_label_definition ) array; representation : Types.record_representation; extended_expression : expression option; alloc_mode : Types.alloc_mode option } * { l1 = P1 ; ... ; ln = Pn } ( extended_expression = None ) { E0 with l1 = P1 ; ... ; ln = Pn } ( extended_expression = Some E0 ) Invariant : n > 0 If the type is { l1 : t1 ; l2 : t2 } , the expression { E0 with t2 = P2 } is represented as Texp_record { fields = [ | l1 , Kept t1 ; l2 Override P2 | ] ; representation ; extended_expression = Some E0 } [ alloc_mode ] is the allocation mode of the record , or [ None ] if it is [ Record_unboxed ] , in which case it does not need allocation . { E0 with l1=P1; ...; ln=Pn } (extended_expression = Some E0) Invariant: n > 0 If the type is { l1: t1; l2: t2 }, the expression { E0 with t2=P2 } is represented as Texp_record { fields = [| l1, Kept t1; l2 Override P2 |]; representation; extended_expression = Some E0 } [alloc_mode] is the allocation mode of the record, or [None] if it is [Record_unboxed], in which case it does not need allocation. *) | Texp_field of expression * Longident.t loc * Types.label_description * Types.alloc_mode option | Texp_setfield of expression * Types.alloc_mode * Longident.t loc * Types.label_description * expression | Texp_array of mutable_flag * expression list * Types.alloc_mode | Texp_list_comprehension of comprehension | Texp_array_comprehension of mutable_flag * comprehension | Texp_ifthenelse of expression * expression * expression option | Texp_sequence of expression * expression | Texp_while of { wh_cond : expression; wh_body : expression; } | Texp_for of { for_id : Ident.t; for_pat : Parsetree.pattern; for_from : expression; for_to : expression; for_dir : direction_flag; for_body : expression; for_region : bool; } | Texp_send of expression * meth * apply_position * Types.alloc_mode | Texp_new of Path.t * Longident.t loc * Types.class_declaration * apply_position | Texp_instvar of Path.t * Path.t * string loc | Texp_setinstvar of Path.t * Path.t * string loc * expression | Texp_override of Path.t * (Ident.t * string loc * expression) list | Texp_letmodule of Ident.t option * string option loc * Types.module_presence * module_expr * expression | Texp_letexception of extension_constructor * expression | Texp_assert of expression | Texp_lazy of expression | Texp_object of class_structure * string list | Texp_pack of module_expr | Texp_letop of { let_ : binding_op; ands : binding_op list; param : Ident.t; body : value case; partial : partial; warnings : Warnings.state; } | Texp_unreachable | Texp_extension_constructor of Longident.t loc * Path.t | Texp_open of open_declaration * expression | Texp_probe of { name:string; handler:expression; } | Texp_probe_is_enabled of { name:string } and ident_kind = Id_value | Id_prim of Types.alloc_mode option and meth = Tmeth_name of string | Tmeth_val of Ident.t | Tmeth_ancestor of Ident.t * Path.t and comprehension = { comp_body : expression; comp_clauses : comprehension_clause list } and comprehension_clause = | Texp_comp_for of comprehension_clause_binding list | Texp_comp_when of expression and comprehension_clause_binding = { comp_cb_iterator : comprehension_iterator; comp_cb_attributes : attribute list } and comprehension_iterator = | Texp_comp_range of { ident : Ident.t ; start : expression ; stop : expression ; direction : direction_flag } | Texp_comp_in of { pattern : pattern ; sequence : expression } and 'k case = { c_lhs: 'k general_pattern; c_guard: expression option; c_rhs: expression; } and record_label_definition = | Kept of Types.type_expr | Overridden of Longident.t loc * expression and binding_op = { bop_op_path : Path.t; bop_op_name : string loc; bop_op_val : Types.value_description; bop_op_type : Types.type_expr; bop_exp : expression; bop_loc : Location.t; } and ('a, 'b) arg_or_omitted = | Arg of 'a | Omitted of 'b and omitted_parameter = { mode_closure : Types.alloc_mode; mode_arg : Types.alloc_mode; mode_ret : Types.alloc_mode } and apply_arg = (expression, omitted_parameter) arg_or_omitted and apply_position = and class_expr = { cl_desc: class_expr_desc; cl_loc: Location.t; cl_type: Types.class_type; cl_env: Env.t; cl_attributes: attributes; } and class_expr_desc = Tcl_ident of Path.t * Longident.t loc * core_type list | Tcl_structure of class_structure | Tcl_fun of arg_label * pattern * (Ident.t * expression) list * class_expr * partial | Tcl_apply of class_expr * (arg_label * apply_arg) list | Tcl_let of rec_flag * value_binding list * (Ident.t * expression) list * class_expr | Tcl_constraint of class_expr * class_type option * string list * string list * Types.MethSet.t | Tcl_open of open_description * class_expr and class_structure = { cstr_self: pattern; cstr_fields: class_field list; cstr_type: Types.class_signature; cstr_meths: Ident.t Types.Meths.t; } and class_field = { cf_desc: class_field_desc; cf_loc: Location.t; cf_attributes: attributes; } and class_field_kind = | Tcfk_virtual of core_type | Tcfk_concrete of override_flag * expression and class_field_desc = Tcf_inherit of override_flag * class_expr * string option * (string * Ident.t) list * (string * Ident.t) list | Tcf_val of string loc * mutable_flag * Ident.t * class_field_kind * bool | Tcf_method of string loc * private_flag * class_field_kind | Tcf_constraint of core_type * core_type | Tcf_initializer of expression | Tcf_attribute of attribute and module_expr = { mod_desc: module_expr_desc; mod_loc: Location.t; mod_type: Types.module_type; mod_env: Env.t; mod_attributes: attributes; } and module_type_constraint = | Tmodtype_implicit | Tmodtype_explicit of module_type and functor_parameter = | Unit | Named of Ident.t option * string option loc * module_type and module_expr_desc = Tmod_ident of Path.t * Longident.t loc | Tmod_structure of structure | Tmod_functor of functor_parameter * module_expr | Tmod_apply of module_expr * module_expr * module_coercion | Tmod_constraint of module_expr * Types.module_type * module_type_constraint * module_coercion | Tmod_unpack of expression * Types.module_type and structure = { str_items : structure_item list; str_type : Types.signature; str_final_env : Env.t; } and structure_item = { str_desc : structure_item_desc; str_loc : Location.t; str_env : Env.t } and structure_item_desc = Tstr_eval of expression * attributes | Tstr_value of rec_flag * value_binding list | Tstr_primitive of value_description | Tstr_type of rec_flag * type_declaration list | Tstr_typext of type_extension | Tstr_exception of type_exception | Tstr_module of module_binding | Tstr_recmodule of module_binding list | Tstr_modtype of module_type_declaration | Tstr_open of open_declaration | Tstr_class of (class_declaration * string list) list | Tstr_class_type of (Ident.t * string loc * class_type_declaration) list | Tstr_include of include_declaration | Tstr_attribute of attribute and module_binding = { mb_id: Ident.t option; mb_name: string option loc; mb_presence: Types.module_presence; mb_expr: module_expr; mb_attributes: attributes; mb_loc: Location.t; } and value_binding = { vb_pat: pattern; vb_expr: expression; vb_attributes: attributes; vb_loc: Location.t; } and module_coercion = Tcoerce_none | Tcoerce_structure of (int * module_coercion) list * (Ident.t * int * module_coercion) list | Tcoerce_functor of module_coercion * module_coercion | Tcoerce_primitive of primitive_coercion | Tcoerce_alias of Env.t * Path.t * module_coercion and module_type = { mty_desc: module_type_desc; mty_type : Types.module_type; mty_env : Env.t; mty_loc: Location.t; mty_attributes: attributes; } and module_type_desc = Tmty_ident of Path.t * Longident.t loc | Tmty_signature of signature | Tmty_functor of functor_parameter * module_type | Tmty_with of module_type * (Path.t * Longident.t loc * with_constraint) list | Tmty_typeof of module_expr | Tmty_alias of Path.t * Longident.t loc and primitive_coercion = { pc_desc: Primitive.description; pc_type: Types.type_expr; pc_poly_mode: Types.alloc_mode option; pc_env: Env.t; pc_loc : Location.t; } and signature = { sig_items : signature_item list; sig_type : Types.signature; sig_final_env : Env.t; } and signature_item = { sig_desc: signature_item_desc; sig_loc: Location.t } and signature_item_desc = Tsig_value of value_description | Tsig_type of rec_flag * type_declaration list | Tsig_typesubst of type_declaration list | Tsig_typext of type_extension | Tsig_exception of type_exception | Tsig_module of module_declaration | Tsig_modsubst of module_substitution | Tsig_recmodule of module_declaration list | Tsig_modtype of module_type_declaration | Tsig_modtypesubst of module_type_declaration | Tsig_open of open_description | Tsig_include of include_description | Tsig_class of class_description list | Tsig_class_type of class_type_declaration list | Tsig_attribute of attribute and module_declaration = { md_id: Ident.t option; md_name: string option loc; md_presence: Types.module_presence; md_type: module_type; md_attributes: attributes; md_loc: Location.t; } and module_substitution = { ms_id: Ident.t; ms_name: string loc; ms_manifest: Path.t; ms_txt: Longident.t loc; ms_attributes: attributes; ms_loc: Location.t; } and module_type_declaration = { mtd_id: Ident.t; mtd_name: string loc; mtd_type: module_type option; mtd_attributes: attributes; mtd_loc: Location.t; } and 'a open_infos = { open_expr: 'a; open_bound_items: Types.signature; open_override: override_flag; open_env: Env.t; open_loc: Location.t; open_attributes: attribute list; } and open_description = (Path.t * Longident.t loc) open_infos and open_declaration = module_expr open_infos and include_kind = | Tincl_structure | Tincl_functor of (Ident.t * module_coercion) list | Tincl_gen_functor of (Ident.t * module_coercion) list and 'a include_infos = { incl_mod: 'a; incl_type: Types.signature; incl_loc: Location.t; incl_kind: include_kind; incl_attributes: attribute list; } and include_description = module_type include_infos and include_declaration = module_expr include_infos and with_constraint = Twith_type of type_declaration | Twith_module of Path.t * Longident.t loc | Twith_modtype of module_type | Twith_typesubst of type_declaration | Twith_modsubst of Path.t * Longident.t loc | Twith_modtypesubst of module_type and core_type = { mutable ctyp_desc : core_type_desc; mutable ctyp_type : Types.type_expr; ctyp_loc : Location.t; ctyp_attributes: attributes; } and core_type_desc = Ttyp_any | Ttyp_var of string | Ttyp_arrow of arg_label * core_type * core_type | Ttyp_tuple of core_type list | Ttyp_constr of Path.t * Longident.t loc * core_type list | Ttyp_object of object_field list * closed_flag | Ttyp_class of Path.t * Longident.t loc * core_type list | Ttyp_alias of core_type * string | Ttyp_variant of row_field list * closed_flag * label list option | Ttyp_poly of string list * core_type | Ttyp_package of package_type and package_type = { pack_path : Path.t; pack_fields : (Longident.t loc * core_type) list; pack_type : Types.module_type; pack_txt : Longident.t loc; } and row_field = { rf_desc : row_field_desc; rf_loc : Location.t; rf_attributes : attributes; } and row_field_desc = Ttag of string loc * bool * core_type list | Tinherit of core_type and object_field = { of_desc : object_field_desc; of_loc : Location.t; of_attributes : attributes; } and object_field_desc = | OTtag of string loc * core_type | OTinherit of core_type and value_description = { val_id: Ident.t; val_name: string loc; val_desc: core_type; val_val: Types.value_description; val_prim: string list; val_loc: Location.t; val_attributes: attributes; } and type_declaration = { typ_id: Ident.t; typ_name: string loc; typ_params: (core_type * (variance * injectivity)) list; typ_type: Types.type_declaration; typ_cstrs: (core_type * core_type * Location.t) list; typ_kind: type_kind; typ_private: private_flag; typ_manifest: core_type option; typ_loc: Location.t; typ_attributes: attributes; } and type_kind = Ttype_abstract | Ttype_variant of constructor_declaration list | Ttype_record of label_declaration list | Ttype_open and label_declaration = { ld_id: Ident.t; ld_name: string loc; ld_mutable: mutable_flag; ld_global: Types.global_flag; ld_type: core_type; ld_loc: Location.t; ld_attributes: attributes; } and constructor_declaration = { cd_id: Ident.t; cd_name: string loc; cd_vars: string loc list; cd_args: constructor_arguments; cd_res: core_type option; cd_loc: Location.t; cd_attributes: attributes; } and constructor_arguments = | Cstr_tuple of (core_type * Types.global_flag) list | Cstr_record of label_declaration list and type_extension = { tyext_path: Path.t; tyext_txt: Longident.t loc; tyext_params: (core_type * (variance * injectivity)) list; tyext_constructors: extension_constructor list; tyext_private: private_flag; tyext_loc: Location.t; tyext_attributes: attributes; } and type_exception = { tyexn_constructor: extension_constructor; tyexn_loc: Location.t; tyexn_attributes: attribute list; } and extension_constructor = { ext_id: Ident.t; ext_name: string loc; ext_type : Types.extension_constructor; ext_kind : extension_constructor_kind; ext_loc : Location.t; ext_attributes: attributes; } and extension_constructor_kind = Text_decl of string loc list * constructor_arguments * core_type option | Text_rebind of Path.t * Longident.t loc and class_type = { cltyp_desc: class_type_desc; cltyp_type: Types.class_type; cltyp_env: Env.t; cltyp_loc: Location.t; cltyp_attributes: attributes; } and class_type_desc = Tcty_constr of Path.t * Longident.t loc * core_type list | Tcty_signature of class_signature | Tcty_arrow of arg_label * core_type * class_type | Tcty_open of open_description * class_type and class_signature = { csig_self : core_type; csig_fields : class_type_field list; csig_type : Types.class_signature; } and class_type_field = { ctf_desc: class_type_field_desc; ctf_loc: Location.t; ctf_attributes: attributes; } and class_type_field_desc = | Tctf_inherit of class_type | Tctf_val of (string * mutable_flag * virtual_flag * core_type) | Tctf_method of (string * private_flag * virtual_flag * core_type) | Tctf_constraint of (core_type * core_type) | Tctf_attribute of attribute and class_declaration = class_expr class_infos and class_description = class_type class_infos and class_type_declaration = class_type class_infos and 'a class_infos = { ci_virt: virtual_flag; ci_params: (core_type * (variance * injectivity)) list; ci_id_name : string loc; ci_id_class: Ident.t; ci_id_class_type : Ident.t; ci_id_object : Ident.t; ci_id_typehash : Ident.t; ci_expr: 'a; ci_decl: Types.class_declaration; ci_type_decl : Types.class_type_declaration; ci_loc: Location.t; ci_attributes: attributes; } type implementation = { structure: structure; coercion: module_coercion; signature: Types.signature; shape: Shape.t; } * [ as_computation_pattern p ] is a computation pattern with description [ Tpat_value p ] , which enforces a correct placement of pat_attributes and pat_extra metadata ( on the inner value pattern , rather than on the computation pattern ) . [Tpat_value p], which enforces a correct placement of pat_attributes and pat_extra metadata (on the inner value pattern, rather than on the computation pattern). *) val as_computation_pattern: pattern -> computation general_pattern val classify_pattern_desc: 'k pattern_desc -> 'k pattern_category val classify_pattern: 'k general_pattern -> 'k pattern_category type pattern_action = { f : 'k . 'k general_pattern -> unit } val shallow_iter_pattern_desc: pattern_action -> 'k pattern_desc -> unit type pattern_transformation = { f : 'k . 'k general_pattern -> 'k general_pattern } val shallow_map_pattern_desc: pattern_transformation -> 'k pattern_desc -> 'k pattern_desc val iter_general_pattern: pattern_action -> 'k general_pattern -> unit val iter_pattern: (pattern -> unit) -> pattern -> unit type pattern_predicate = { f : 'k . 'k general_pattern -> bool } val exists_general_pattern: pattern_predicate -> 'k general_pattern -> bool val exists_pattern: (pattern -> bool) -> pattern -> bool val let_bound_idents: value_binding list -> Ident.t list val let_bound_idents_full: value_binding list -> (Ident.t * string loc * Types.type_expr) list val let_bound_idents_with_modes: value_binding list -> (Ident.t * (Location.t * Types.value_mode) list) list val alpha_pat: (Ident.t * Ident.t) list -> 'k general_pattern -> 'k general_pattern val mknoloc: 'a -> 'a Asttypes.loc val mkloc: 'a -> Location.t -> 'a Asttypes.loc val pat_bound_idents: 'k general_pattern -> Ident.t list val pat_bound_idents_full: 'k general_pattern -> (Ident.t * string loc * Types.type_expr) list val split_pattern: computation general_pattern -> pattern option * pattern option
f76d3f84408aacb0891133170ec6e9a6d8f5ea44933275ce076952f97468cb0d
mirage/ocaml-rpc
rpc_lwt.mli
type client_implementation type server_implementation module T : sig type 'a box type ('a, 'b) resultb = ('a, 'b) Result.t box type rpcfn = Rpc.call -> Rpc.response Lwt.t val lift : ('a -> 'b Lwt.t) -> 'a -> 'b box val bind : 'a box -> ('a -> 'b Lwt.t) -> 'b box val return : 'a -> 'a box val get : 'a box -> 'a Lwt.t val ( !@ ) : 'a box -> 'a Lwt.t val put : 'a Lwt.t -> 'a box val ( ~@ ) : 'a Lwt.t -> 'a box end module ErrM : sig val return : 'a -> ('a, 'b) T.resultb val return_err : 'b -> ('a, 'b) T.resultb val checked_bind : ('a, 'b) T.resultb -> ('a -> ('c, 'd) T.resultb) -> ('b -> ('c, 'd) T.resultb) -> ('c, 'd) T.resultb val bind : ('a, 'b) T.resultb -> ('a -> ('c, 'b) T.resultb) -> ('c, 'b) T.resultb val ( >>= ) : ('a, 'b) T.resultb -> ('a -> ('c, 'b) T.resultb) -> ('c, 'b) T.resultb end (** Client generator similar to {!Idl.GenClient} that uses [Lwt]. *) module GenClient () : sig include Idl.RPC with type implementation = client_implementation and type 'a res = T.rpcfn -> 'a and type ('a, 'b) comp = ('a, 'b) T.resultb end (** Server generator similar to {!Idl.GenServer} that uses [Lwt]. *) module GenServer () : sig include Idl.RPC with type implementation = server_implementation and type 'a res = 'a -> unit and type ('a, 'b) comp = ('a, 'b) T.resultb end val server : server_implementation -> T.rpcfn val combine : server_implementation list -> server_implementation
null
https://raw.githubusercontent.com/mirage/ocaml-rpc/c0f6463ea8ccea555c1d1e990a2a9a86b52fa5ae/src/lwt/rpc_lwt.mli
ocaml
* Client generator similar to {!Idl.GenClient} that uses [Lwt]. * Server generator similar to {!Idl.GenServer} that uses [Lwt].
type client_implementation type server_implementation module T : sig type 'a box type ('a, 'b) resultb = ('a, 'b) Result.t box type rpcfn = Rpc.call -> Rpc.response Lwt.t val lift : ('a -> 'b Lwt.t) -> 'a -> 'b box val bind : 'a box -> ('a -> 'b Lwt.t) -> 'b box val return : 'a -> 'a box val get : 'a box -> 'a Lwt.t val ( !@ ) : 'a box -> 'a Lwt.t val put : 'a Lwt.t -> 'a box val ( ~@ ) : 'a Lwt.t -> 'a box end module ErrM : sig val return : 'a -> ('a, 'b) T.resultb val return_err : 'b -> ('a, 'b) T.resultb val checked_bind : ('a, 'b) T.resultb -> ('a -> ('c, 'd) T.resultb) -> ('b -> ('c, 'd) T.resultb) -> ('c, 'd) T.resultb val bind : ('a, 'b) T.resultb -> ('a -> ('c, 'b) T.resultb) -> ('c, 'b) T.resultb val ( >>= ) : ('a, 'b) T.resultb -> ('a -> ('c, 'b) T.resultb) -> ('c, 'b) T.resultb end module GenClient () : sig include Idl.RPC with type implementation = client_implementation and type 'a res = T.rpcfn -> 'a and type ('a, 'b) comp = ('a, 'b) T.resultb end module GenServer () : sig include Idl.RPC with type implementation = server_implementation and type 'a res = 'a -> unit and type ('a, 'b) comp = ('a, 'b) T.resultb end val server : server_implementation -> T.rpcfn val combine : server_implementation list -> server_implementation
eacb5485c3eca2f98c30fc1d2559e61b66f76d40379262178759c2e5e8a74584
takikawa/racket-ppa
test-markup.rkt
; Generate markup for test results #lang racket/base (provide render-value-parameter ; determines how values should be rendered display-test-results-parameter ; determines how test-result markup should be rendered display-test-results! ; call the above get-rewritten-error-message-parameter ; from an exception, extract/translate appropriate message get-rewritten-error-message ; call the above test-object->markup) ; converts test object to markup (require (only-in racket/string string-split) (only-in racket/list append-map) string-constants test-engine/test-engine (only-in simple-tree-text-markup/data markup? empty-markup? srcloc-markup? srcloc-markup-srcloc transform-markup) simple-tree-text-markup/construct simple-tree-text-markup/text simple-tree-text-markup/port (except-in deinprogramm/signature/signature signature-violation) ; clashes with test-engine deinprogramm/quickcheck/quickcheck) (define render-value-parameter (make-parameter (lambda (v port) (fprintf port "~V" v)))) (define render-value (case-lambda ((value) (let ((proc (render-value-parameter))) (if (procedure-arity-includes? proc 2) (let ((port (open-output-string))) (proc value port) (get-output-string)) (proc value)))) ((value port) (let ((proc (render-value-parameter))) (if (procedure-arity-includes? proc 2) (proc value port) (display (proc value) port)))))) (define get-rewritten-error-message-parameter (make-parameter exn-message)) (define (get-rewritten-error-message exn) ((get-rewritten-error-message-parameter) exn)) (define display-test-results-parameter (make-parameter (lambda (markup) (if (port-writes-special? (current-output-port)) (begin (write-special markup) (unless (empty-markup? markup) (newline))) ; an exception message might be printed after the markup (display-markup markup))))) (define (display-test-results! markup) ((display-test-results-parameter) markup)) (define (test-object->markup test-object [disabled? #f]) (cond [disabled? (string-constant test-engine-tests-disabled)] [(and (null? (test-object-tests test-object)) (null? (test-object-signature-violations test-object))) empty-markup] [(and (null? (test-object-failed-checks test-object)) (null? (test-object-signature-violations test-object))) (let ((count (length (test-object-tests test-object)))) (case count [(0) (string-constant test-engine-0-tests-passed)] [(1) (string-constant test-engine-1-test-passed)] [(2) (string-constant test-engine-both-tests-passed)] [else (format (string-constant test-engine-all-n-tests-passed) count)]))] [else (test-object-details->markup test-object)])) (define (test-object-details->markup test-object) (let* ([test-count (length (test-object-tests test-object))] [failed-checks (reverse (test-object-failed-checks test-object))] [failed-check-count (length failed-checks)] [signature-violations (reverse (test-object-signature-violations test-object))]) (vertical (cond [(zero? test-count) (string-constant test-engine-must-be-tested)] [(= 1 test-count) (string-constant test-engine-ran-1-test)] [else (format (string-constant test-engine-ran-n-tests) test-count)]) (if (> test-count 0) (vertical (cond [(and (zero? failed-check-count) (= 1 test-count)) (string-constant test-engine-1-check-passed)] [(zero? failed-check-count) (string-constant test-engine-all-tests-passed)] [(= failed-check-count test-count) (string-constant test-engine-0-tests-passed)] [else (format (string-constant test-engine-m-of-n-tests-failed) failed-check-count test-count)]) empty-line) empty-markup) (cond ((null? signature-violations) empty-markup) ((null? (cdr signature-violations)) (vertical (string-constant test-engine-1-signature-violation) empty-line)) (else (vertical (format (string-constant test-engine-n-signature-violations) (length signature-violations)) empty-line))) (signature-violations->markup signature-violations) (check-failures->markup failed-checks)))) (define (check-failures->markup checks) (if (pair? checks) (vertical (string-constant test-engine-check-failures) (apply vertical (map failed-check->markup checks))) empty-markup)) (define (signature-violations->markup violations) (if (pair? violations) (vertical (string-constant test-engine-signature-violations) (apply vertical (map (lambda (violation) (horizontal " " (signature-violation->markup violation))) violations))) empty-markup)) (define (failed-check->markup failed-check) (if (failed-check-srcloc? failed-check) (error-link->markup (failed-check-reason failed-check) (failed-check-srcloc? failed-check) (fail-reason-srcloc (failed-check-reason failed-check))) (link->markup (failed-check-reason failed-check) (fail-reason-srcloc (failed-check-reason failed-check))))) (define (link->markup reason srcloc) (vertical (horizontal " " (reason->markup reason)) (srcloc-markup srcloc (format-srcloc srcloc)))) (define (format-srcloc srcloc) (let ([line (cond [(srcloc-line srcloc) => number->string] [else (string-constant test-engine-unknown)])] [col (cond [(srcloc-column srcloc) => number->string] [else (string-constant test-engine-unknown)])] [file (srcloc-source srcloc)]) (if (path? file) (let-values (((base name must-be-dir?) (split-path file))) (if (path? name) (format (string-constant test-engine-in-at-line-column) (path->string name) line col) (format (string-constant test-engine-at-line-column) line col))) (format (string-constant test-engine-at-line-column) line col)))) provide properly translated text for (define (markup-reformat-srcloc markup) (transform-markup `((,srcloc-markup? . ,(lambda (srcloc _markup) (srcloc-markup srcloc (format-srcloc srcloc))))) markup)) (define (format->markup format-string . vals) (let loop ((chars (string->list format-string)) (vals vals) (rev-markups '()) (rev-lines '())) (cond ((null? chars) (apply vertical (reverse (cons (apply horizontal (reverse rev-markups)) (reverse rev-lines))))) ; this will normalize ((char=? (car chars) #\~) (case (cadr chars) ((#\n #\~) (loop (cddr chars) vals '() (cons (apply horizontal (reverse rev-markups)) rev-lines))) ((#\F #\f) (loop (cddr chars) (cdr vals) (cons (framed-markup (value->markup (car vals))) rev-markups) rev-lines)) ((#\a #\A) (let ((val (car vals))) (loop (cddr chars) (cdr vals) (if (markup? val) (cons (markup-reformat-srcloc val) rev-markups) (cons (format "~a" (car vals)) rev-markups)) rev-lines))) (else (loop (cddr chars) (cdr vals) (cons (format (string #\~ (cadr chars)) (car vals)) rev-markups) rev-lines)))) (else (let inner-loop ((chars chars) (rev-seen '())) (if (or (null? chars) (char=? (car chars) #\~)) (loop chars vals (cons (list->string (reverse rev-seen)) rev-markups) rev-lines) (inner-loop (cdr chars) (cons (car chars) rev-seen)))))))) (define (value->markup value) (let-values (((port get-markup) (make-markup-output-port/unsafe (lambda (special) (if (markup? special) ; number-markup, typically special (image-markup special "#<image>")))))) (render-value value port) (get-markup))) (define (reason->markup fail) (cond [(unexpected-error/markup? fail) (format->markup (string-constant test-engine-check-encountered-error) (unexpected-error-expected fail) (unexpected-error/markup-error-markup fail))] [(unexpected-error? fail) (format->markup (string-constant test-engine-check-encountered-error) (unexpected-error-expected fail) (get-rewritten-error-message (unexpected-error-exn fail)))] [(unsatisfied-error/markup? fail) (format->markup "check-satisfied for ~a encountered an error.\n :: ~a" (unsatisfied-error-name fail) (unsatisfied-error/markup-error-markup fail))] [(unsatisfied-error? fail) (format->markup "check-satisfied for ~a encountered an error.\n :: ~a" (unsatisfied-error-name fail) (get-rewritten-error-message (unsatisfied-error-exn fail)))] [(unequal? fail) (format->markup (string-constant test-engine-actual-value-differs-error) (unequal-actual fail) (unequal-expected fail))] [(satisfied-failed? fail) (format->markup "Actual value ~F does not satisfy ~a." (satisfied-failed-actual fail) (satisfied-failed-name fail))] [(not-within? fail) (if (string-constant-in-current-language? test-engine-actual-value-not-within-error) (format->markup (string-constant test-engine-actual-value-not-within-error) (not-within-actual fail) (not-within-range fail) (not-within-expected fail)) (format->markup (string-constant test-engine-actual-value-not-within-error/alt-order) (not-within-actual fail) (not-within-expected fail) (not-within-range fail)))] [(incorrect-error/markup? fail) (format->markup (string-constant test-engine-encountered-error-error) (incorrect-error-expected fail) (incorrect-error/markup-error-markup fail))] [(incorrect-error? fail) (format->markup (string-constant test-engine-encountered-error-error) (incorrect-error-expected fail) (get-rewritten-error-message (incorrect-error-exn fail)))] [(expected-error? fail) (cond ((expected-error-message fail) => (lambda (message) (format->markup (string-constant test-engine-expected-error-error) (expected-error-value fail) message))) (else (format->markup (string-constant test-engine-expected-an-error-error) (expected-error-value fail))))] [(not-mem? fail) (horizontal (format->markup (string-constant test-engine-not-mem-error) (not-mem-actual fail)) (apply horizontal (map (lambda (a) (format->markup " ~F" a)) (not-mem-set fail))) ".")] [(not-range? fail) (format->markup (string-constant test-engine-not-range-error) (not-range-actual fail) (not-range-min fail) (not-range-max fail))] [(property-fail? fail) (horizontal (string-constant test-engine-property-fail-error) (apply horizontal (append-map (lambda (arguments) (map (lambda (p) (if (car p) (format->markup " ~a = ~F" (car p) (cdr p)) (format->markup "~F" (cdr p)))) arguments)) (result-arguments-list (property-fail-result fail)))))] [(property-error? fail) (format->markup (string-constant test-engine-property-error-error) (get-rewritten-error-message (property-error-exn fail)))] ;; should not happen [(violated-signature? fail) (format->markup "Unhandled signature violation: got ~F, violated signature ~a, to blame: ~a" (violated-signature-obj fail) (signature-name (violated-signature-signature fail)) (let ((blame (violated-signature-blame fail))) (if blame (syntax->datum blame) '<unknown>)))])) (define (error-link->markup reason srcloc check-srcloc) (vertical (horizontal " " (reason->markup reason)) (horizontal (srcloc-markup check-srcloc (format-srcloc check-srcloc)) (if srcloc (horizontal " " (string-constant test-engine-check-error-cause) " " (srcloc-markup srcloc (format-srcloc srcloc))) empty-markup)))) (define (signature-violation->markup violation) (let* ((signature (signature-violation-signature violation)) (stx (signature-syntax signature)) (srcloc (signature-violation-srcloc violation)) (message (signature-violation-message violation))) (horizontal (cond ((string? message) message) ((signature-got? message) (horizontal (string-constant test-engine-got) " " (framed-markup (value->markup (signature-got-value message))))) (else empty-markup)) (if srcloc (horizontal " " (srcloc-markup srcloc (format-srcloc srcloc))) empty-markup) ", " (string-constant test-engine-signature) " " (srcloc-markup (syntax-srcloc stx) (format-srcloc (syntax-srcloc stx))) (cond ((signature-violation-blame violation) => (lambda (blame) (horizontal " " (string-constant test-engine-to-blame) " " (srcloc-markup (syntax-srcloc blame) (format-srcloc (syntax-srcloc blame)))))) (else empty-markup))))) (define (syntax-srcloc stx) (srcloc (syntax-source stx) (syntax-line stx) (syntax-column stx) (syntax-position stx) (syntax-span stx))) (module+ test (require rackunit (only-in simple-tree-text-markup/data markup? srcloc-markup? srcloc-markup-srcloc markup-folder) (only-in deinprogramm/signature/signature-german make-predicate-signature)) (parameterize ((render-value-parameter (lambda (v) (format "<~V>" v)))) (check-equal? (format->markup "abc") "abc") (check-equal? (format->markup "foo ~F bar ~v~~bar" 5 #f) (vertical (horizontal "foo " (framed-markup "<5>") " bar " "#f") "bar"))) (parameterize ((render-value-parameter (lambda (v) (format "<~V>" v)))) (call-with-current-language 'english (lambda () (check-equal? (reason->markup (unexpected-error (srcloc 'source 1 0 10 20) 'expected (exn "not expected" (current-continuation-marks)))) (vertical (horizontal "check-expect encountered the following error instead of the expected value, " (framed-markup "<'expected>") ". ") " :: not expected"))))) (check-pred markup? (test-object->markup (empty-test-object))) (define fail-unexpected-error (failed-check (unexpected-error (srcloc 'source 1 0 10 20) 'expected (exn "not expected" (current-continuation-marks))) (srcloc 'exn 2 1 30 40))) (define fail-unexpected-error/markup (failed-check (unexpected-error/markup (srcloc 'source 1 0 10 20) 'expected (exn "not expected" (current-continuation-marks)) (vertical "line1" "line2")) (srcloc 'exn 2 1 30 40))) (define fail-unsatisfied-error (failed-check (unsatisfied-error (srcloc 'source 1 0 10 20) "zero?" (exn "not expected" (current-continuation-marks))) #f)) (define fail-unsatisfied-error/markup (failed-check (unsatisfied-error/markup (srcloc 'source 1 0 10 20) "zero?" (exn "not expected" (current-continuation-marks)) (vertical "line1" "line2")) #f)) (define fail-unequal (failed-check (unequal (srcloc 'source 1 0 10 20) 'actual 'expected) #f)) (define fail-not-within (failed-check (not-within (srcloc 'source 1 0 10 20) #i12 #i14 #i0.5) #f)) (define fail-incorrect-error (failed-check (incorrect-error (srcloc 'source 1 0 10 20) "expected" (exn "not expected" (current-continuation-marks))) #f)) (define fail-incorrect-error/markup (failed-check (incorrect-error/markup (srcloc 'source 1 0 10 20) "expected" (exn "not expected" (current-continuation-marks)) (vertical "line1" "line2")) #f)) (define fail-expected-error (failed-check (expected-error (srcloc 'source 1 0 10 20) "error message" (exn "some other error message" (current-continuation-marks))) #f)) (define fail-an-expected-error (failed-check (expected-error (srcloc 'source 1 0 10 20) #f (exn "some error message" (current-continuation-marks))) #f)) (define fail-not-mem (failed-check (not-mem (srcloc 'source 1 0 10 20) 'actual '(expected-1 expected-2)) #f)) (define fail-not-range (failed-check (not-range (srcloc 'source 1 0 10 20) 12 1 10) #f)) (define fail-satisfied-failed (failed-check (satisfied-failed (srcloc 'source 1 0 10 20) 'actual "string?") #f)) (define fail-property-fail (failed-check (property-fail (srcloc 'source 1 0 10 20) (make-result #t '() '(((a . 1) (#f . 2) (c . 3))))) #f)) (define fail-property-error (failed-check (property-error (srcloc 'source 1 0 10 20) (exn "not expected" (current-continuation-marks))) #f)) (define integer (make-predicate-signature 'integer integer? #'integer-marker)) (define fail-violated-signature (failed-check (violated-signature (srcloc 'source 1 0 10 20) 'obj integer #'syntax) #f)) (define signature-violation-1 (signature-violation 'obj integer (signature-got 'got) (srcloc 'signature 2 3 23 333) #f)) (define signature-violation-2 (signature-violation 'obj-2 integer (signature-got 'got-2) (srcloc 'signature 3 4 24 334) #f)) (define signature-violation-3 (signature-violation 'obj-3 integer (signature-got 'got-3) (srcloc 'signature 4 5 25 335) #f)) (define (make-test-object tests failed-checks signature-violations) (let ((test-object (empty-test-object))) (set-test-object-tests! test-object tests) (set-test-object-failed-checks! test-object failed-checks) (set-test-object-signature-violations! test-object signature-violations) test-object)) there are special cases for 1 and 2 (check-pred markup? (test-object->markup (make-test-object (list void) (list fail-unexpected-error) (list signature-violation-1)))) (check-pred markup? (test-object->markup (make-test-object (list void void) (list fail-unexpected-error fail-unsatisfied-error) (list signature-violation-1 signature-violation-2)))) (check-pred markup? (test-object->markup (make-test-object (list void void) (list fail-unexpected-error fail-unexpected-error/markup fail-unsatisfied-error fail-unsatisfied-error/markup fail-unequal fail-not-within fail-incorrect-error fail-incorrect-error/markup fail-not-mem fail-not-range fail-satisfied-failed fail-property-fail fail-property-error fail-violated-signature) (list signature-violation-1 signature-violation-2 signature-violation-3)))) (define markup-srclocs (markup-folder append '() `((,srcloc-markup? . ,(lambda (markup) (list (srcloc-markup-srcloc markup))))))) (check-equal? (markup-srclocs (test-object->markup (make-test-object (list void) (list fail-unexpected-error) '()))) (list (srcloc 'exn 2 1 30 40) (srcloc 'source 1 0 10 20))) )
null
https://raw.githubusercontent.com/takikawa/racket-ppa/caff086a1cd48208815cec2a22645a3091c11d4c/share/pkgs/htdp-lib/test-engine/test-markup.rkt
racket
Generate markup for test results determines how values should be rendered determines how test-result markup should be rendered call the above from an exception, extract/translate appropriate message call the above converts test object to markup clashes with test-engine an exception message might be printed after the markup this will normalize number-markup, typically should not happen
#lang racket/base (require (only-in racket/string string-split) (only-in racket/list append-map) string-constants test-engine/test-engine (only-in simple-tree-text-markup/data markup? empty-markup? srcloc-markup? srcloc-markup-srcloc transform-markup) simple-tree-text-markup/construct simple-tree-text-markup/text simple-tree-text-markup/port deinprogramm/quickcheck/quickcheck) (define render-value-parameter (make-parameter (lambda (v port) (fprintf port "~V" v)))) (define render-value (case-lambda ((value) (let ((proc (render-value-parameter))) (if (procedure-arity-includes? proc 2) (let ((port (open-output-string))) (proc value port) (get-output-string)) (proc value)))) ((value port) (let ((proc (render-value-parameter))) (if (procedure-arity-includes? proc 2) (proc value port) (display (proc value) port)))))) (define get-rewritten-error-message-parameter (make-parameter exn-message)) (define (get-rewritten-error-message exn) ((get-rewritten-error-message-parameter) exn)) (define display-test-results-parameter (make-parameter (lambda (markup) (if (port-writes-special? (current-output-port)) (begin (write-special markup) (unless (empty-markup? markup) (display-markup markup))))) (define (display-test-results! markup) ((display-test-results-parameter) markup)) (define (test-object->markup test-object [disabled? #f]) (cond [disabled? (string-constant test-engine-tests-disabled)] [(and (null? (test-object-tests test-object)) (null? (test-object-signature-violations test-object))) empty-markup] [(and (null? (test-object-failed-checks test-object)) (null? (test-object-signature-violations test-object))) (let ((count (length (test-object-tests test-object)))) (case count [(0) (string-constant test-engine-0-tests-passed)] [(1) (string-constant test-engine-1-test-passed)] [(2) (string-constant test-engine-both-tests-passed)] [else (format (string-constant test-engine-all-n-tests-passed) count)]))] [else (test-object-details->markup test-object)])) (define (test-object-details->markup test-object) (let* ([test-count (length (test-object-tests test-object))] [failed-checks (reverse (test-object-failed-checks test-object))] [failed-check-count (length failed-checks)] [signature-violations (reverse (test-object-signature-violations test-object))]) (vertical (cond [(zero? test-count) (string-constant test-engine-must-be-tested)] [(= 1 test-count) (string-constant test-engine-ran-1-test)] [else (format (string-constant test-engine-ran-n-tests) test-count)]) (if (> test-count 0) (vertical (cond [(and (zero? failed-check-count) (= 1 test-count)) (string-constant test-engine-1-check-passed)] [(zero? failed-check-count) (string-constant test-engine-all-tests-passed)] [(= failed-check-count test-count) (string-constant test-engine-0-tests-passed)] [else (format (string-constant test-engine-m-of-n-tests-failed) failed-check-count test-count)]) empty-line) empty-markup) (cond ((null? signature-violations) empty-markup) ((null? (cdr signature-violations)) (vertical (string-constant test-engine-1-signature-violation) empty-line)) (else (vertical (format (string-constant test-engine-n-signature-violations) (length signature-violations)) empty-line))) (signature-violations->markup signature-violations) (check-failures->markup failed-checks)))) (define (check-failures->markup checks) (if (pair? checks) (vertical (string-constant test-engine-check-failures) (apply vertical (map failed-check->markup checks))) empty-markup)) (define (signature-violations->markup violations) (if (pair? violations) (vertical (string-constant test-engine-signature-violations) (apply vertical (map (lambda (violation) (horizontal " " (signature-violation->markup violation))) violations))) empty-markup)) (define (failed-check->markup failed-check) (if (failed-check-srcloc? failed-check) (error-link->markup (failed-check-reason failed-check) (failed-check-srcloc? failed-check) (fail-reason-srcloc (failed-check-reason failed-check))) (link->markup (failed-check-reason failed-check) (fail-reason-srcloc (failed-check-reason failed-check))))) (define (link->markup reason srcloc) (vertical (horizontal " " (reason->markup reason)) (srcloc-markup srcloc (format-srcloc srcloc)))) (define (format-srcloc srcloc) (let ([line (cond [(srcloc-line srcloc) => number->string] [else (string-constant test-engine-unknown)])] [col (cond [(srcloc-column srcloc) => number->string] [else (string-constant test-engine-unknown)])] [file (srcloc-source srcloc)]) (if (path? file) (let-values (((base name must-be-dir?) (split-path file))) (if (path? name) (format (string-constant test-engine-in-at-line-column) (path->string name) line col) (format (string-constant test-engine-at-line-column) line col))) (format (string-constant test-engine-at-line-column) line col)))) provide properly translated text for (define (markup-reformat-srcloc markup) (transform-markup `((,srcloc-markup? . ,(lambda (srcloc _markup) (srcloc-markup srcloc (format-srcloc srcloc))))) markup)) (define (format->markup format-string . vals) (let loop ((chars (string->list format-string)) (vals vals) (rev-markups '()) (rev-lines '())) (cond ((null? chars) (apply vertical (reverse (cons (apply horizontal (reverse rev-markups)) ((char=? (car chars) #\~) (case (cadr chars) ((#\n #\~) (loop (cddr chars) vals '() (cons (apply horizontal (reverse rev-markups)) rev-lines))) ((#\F #\f) (loop (cddr chars) (cdr vals) (cons (framed-markup (value->markup (car vals))) rev-markups) rev-lines)) ((#\a #\A) (let ((val (car vals))) (loop (cddr chars) (cdr vals) (if (markup? val) (cons (markup-reformat-srcloc val) rev-markups) (cons (format "~a" (car vals)) rev-markups)) rev-lines))) (else (loop (cddr chars) (cdr vals) (cons (format (string #\~ (cadr chars)) (car vals)) rev-markups) rev-lines)))) (else (let inner-loop ((chars chars) (rev-seen '())) (if (or (null? chars) (char=? (car chars) #\~)) (loop chars vals (cons (list->string (reverse rev-seen)) rev-markups) rev-lines) (inner-loop (cdr chars) (cons (car chars) rev-seen)))))))) (define (value->markup value) (let-values (((port get-markup) (make-markup-output-port/unsafe (lambda (special) special (image-markup special "#<image>")))))) (render-value value port) (get-markup))) (define (reason->markup fail) (cond [(unexpected-error/markup? fail) (format->markup (string-constant test-engine-check-encountered-error) (unexpected-error-expected fail) (unexpected-error/markup-error-markup fail))] [(unexpected-error? fail) (format->markup (string-constant test-engine-check-encountered-error) (unexpected-error-expected fail) (get-rewritten-error-message (unexpected-error-exn fail)))] [(unsatisfied-error/markup? fail) (format->markup "check-satisfied for ~a encountered an error.\n :: ~a" (unsatisfied-error-name fail) (unsatisfied-error/markup-error-markup fail))] [(unsatisfied-error? fail) (format->markup "check-satisfied for ~a encountered an error.\n :: ~a" (unsatisfied-error-name fail) (get-rewritten-error-message (unsatisfied-error-exn fail)))] [(unequal? fail) (format->markup (string-constant test-engine-actual-value-differs-error) (unequal-actual fail) (unequal-expected fail))] [(satisfied-failed? fail) (format->markup "Actual value ~F does not satisfy ~a." (satisfied-failed-actual fail) (satisfied-failed-name fail))] [(not-within? fail) (if (string-constant-in-current-language? test-engine-actual-value-not-within-error) (format->markup (string-constant test-engine-actual-value-not-within-error) (not-within-actual fail) (not-within-range fail) (not-within-expected fail)) (format->markup (string-constant test-engine-actual-value-not-within-error/alt-order) (not-within-actual fail) (not-within-expected fail) (not-within-range fail)))] [(incorrect-error/markup? fail) (format->markup (string-constant test-engine-encountered-error-error) (incorrect-error-expected fail) (incorrect-error/markup-error-markup fail))] [(incorrect-error? fail) (format->markup (string-constant test-engine-encountered-error-error) (incorrect-error-expected fail) (get-rewritten-error-message (incorrect-error-exn fail)))] [(expected-error? fail) (cond ((expected-error-message fail) => (lambda (message) (format->markup (string-constant test-engine-expected-error-error) (expected-error-value fail) message))) (else (format->markup (string-constant test-engine-expected-an-error-error) (expected-error-value fail))))] [(not-mem? fail) (horizontal (format->markup (string-constant test-engine-not-mem-error) (not-mem-actual fail)) (apply horizontal (map (lambda (a) (format->markup " ~F" a)) (not-mem-set fail))) ".")] [(not-range? fail) (format->markup (string-constant test-engine-not-range-error) (not-range-actual fail) (not-range-min fail) (not-range-max fail))] [(property-fail? fail) (horizontal (string-constant test-engine-property-fail-error) (apply horizontal (append-map (lambda (arguments) (map (lambda (p) (if (car p) (format->markup " ~a = ~F" (car p) (cdr p)) (format->markup "~F" (cdr p)))) arguments)) (result-arguments-list (property-fail-result fail)))))] [(property-error? fail) (format->markup (string-constant test-engine-property-error-error) (get-rewritten-error-message (property-error-exn fail)))] [(violated-signature? fail) (format->markup "Unhandled signature violation: got ~F, violated signature ~a, to blame: ~a" (violated-signature-obj fail) (signature-name (violated-signature-signature fail)) (let ((blame (violated-signature-blame fail))) (if blame (syntax->datum blame) '<unknown>)))])) (define (error-link->markup reason srcloc check-srcloc) (vertical (horizontal " " (reason->markup reason)) (horizontal (srcloc-markup check-srcloc (format-srcloc check-srcloc)) (if srcloc (horizontal " " (string-constant test-engine-check-error-cause) " " (srcloc-markup srcloc (format-srcloc srcloc))) empty-markup)))) (define (signature-violation->markup violation) (let* ((signature (signature-violation-signature violation)) (stx (signature-syntax signature)) (srcloc (signature-violation-srcloc violation)) (message (signature-violation-message violation))) (horizontal (cond ((string? message) message) ((signature-got? message) (horizontal (string-constant test-engine-got) " " (framed-markup (value->markup (signature-got-value message))))) (else empty-markup)) (if srcloc (horizontal " " (srcloc-markup srcloc (format-srcloc srcloc))) empty-markup) ", " (string-constant test-engine-signature) " " (srcloc-markup (syntax-srcloc stx) (format-srcloc (syntax-srcloc stx))) (cond ((signature-violation-blame violation) => (lambda (blame) (horizontal " " (string-constant test-engine-to-blame) " " (srcloc-markup (syntax-srcloc blame) (format-srcloc (syntax-srcloc blame)))))) (else empty-markup))))) (define (syntax-srcloc stx) (srcloc (syntax-source stx) (syntax-line stx) (syntax-column stx) (syntax-position stx) (syntax-span stx))) (module+ test (require rackunit (only-in simple-tree-text-markup/data markup? srcloc-markup? srcloc-markup-srcloc markup-folder) (only-in deinprogramm/signature/signature-german make-predicate-signature)) (parameterize ((render-value-parameter (lambda (v) (format "<~V>" v)))) (check-equal? (format->markup "abc") "abc") (check-equal? (format->markup "foo ~F bar ~v~~bar" 5 #f) (vertical (horizontal "foo " (framed-markup "<5>") " bar " "#f") "bar"))) (parameterize ((render-value-parameter (lambda (v) (format "<~V>" v)))) (call-with-current-language 'english (lambda () (check-equal? (reason->markup (unexpected-error (srcloc 'source 1 0 10 20) 'expected (exn "not expected" (current-continuation-marks)))) (vertical (horizontal "check-expect encountered the following error instead of the expected value, " (framed-markup "<'expected>") ". ") " :: not expected"))))) (check-pred markup? (test-object->markup (empty-test-object))) (define fail-unexpected-error (failed-check (unexpected-error (srcloc 'source 1 0 10 20) 'expected (exn "not expected" (current-continuation-marks))) (srcloc 'exn 2 1 30 40))) (define fail-unexpected-error/markup (failed-check (unexpected-error/markup (srcloc 'source 1 0 10 20) 'expected (exn "not expected" (current-continuation-marks)) (vertical "line1" "line2")) (srcloc 'exn 2 1 30 40))) (define fail-unsatisfied-error (failed-check (unsatisfied-error (srcloc 'source 1 0 10 20) "zero?" (exn "not expected" (current-continuation-marks))) #f)) (define fail-unsatisfied-error/markup (failed-check (unsatisfied-error/markup (srcloc 'source 1 0 10 20) "zero?" (exn "not expected" (current-continuation-marks)) (vertical "line1" "line2")) #f)) (define fail-unequal (failed-check (unequal (srcloc 'source 1 0 10 20) 'actual 'expected) #f)) (define fail-not-within (failed-check (not-within (srcloc 'source 1 0 10 20) #i12 #i14 #i0.5) #f)) (define fail-incorrect-error (failed-check (incorrect-error (srcloc 'source 1 0 10 20) "expected" (exn "not expected" (current-continuation-marks))) #f)) (define fail-incorrect-error/markup (failed-check (incorrect-error/markup (srcloc 'source 1 0 10 20) "expected" (exn "not expected" (current-continuation-marks)) (vertical "line1" "line2")) #f)) (define fail-expected-error (failed-check (expected-error (srcloc 'source 1 0 10 20) "error message" (exn "some other error message" (current-continuation-marks))) #f)) (define fail-an-expected-error (failed-check (expected-error (srcloc 'source 1 0 10 20) #f (exn "some error message" (current-continuation-marks))) #f)) (define fail-not-mem (failed-check (not-mem (srcloc 'source 1 0 10 20) 'actual '(expected-1 expected-2)) #f)) (define fail-not-range (failed-check (not-range (srcloc 'source 1 0 10 20) 12 1 10) #f)) (define fail-satisfied-failed (failed-check (satisfied-failed (srcloc 'source 1 0 10 20) 'actual "string?") #f)) (define fail-property-fail (failed-check (property-fail (srcloc 'source 1 0 10 20) (make-result #t '() '(((a . 1) (#f . 2) (c . 3))))) #f)) (define fail-property-error (failed-check (property-error (srcloc 'source 1 0 10 20) (exn "not expected" (current-continuation-marks))) #f)) (define integer (make-predicate-signature 'integer integer? #'integer-marker)) (define fail-violated-signature (failed-check (violated-signature (srcloc 'source 1 0 10 20) 'obj integer #'syntax) #f)) (define signature-violation-1 (signature-violation 'obj integer (signature-got 'got) (srcloc 'signature 2 3 23 333) #f)) (define signature-violation-2 (signature-violation 'obj-2 integer (signature-got 'got-2) (srcloc 'signature 3 4 24 334) #f)) (define signature-violation-3 (signature-violation 'obj-3 integer (signature-got 'got-3) (srcloc 'signature 4 5 25 335) #f)) (define (make-test-object tests failed-checks signature-violations) (let ((test-object (empty-test-object))) (set-test-object-tests! test-object tests) (set-test-object-failed-checks! test-object failed-checks) (set-test-object-signature-violations! test-object signature-violations) test-object)) there are special cases for 1 and 2 (check-pred markup? (test-object->markup (make-test-object (list void) (list fail-unexpected-error) (list signature-violation-1)))) (check-pred markup? (test-object->markup (make-test-object (list void void) (list fail-unexpected-error fail-unsatisfied-error) (list signature-violation-1 signature-violation-2)))) (check-pred markup? (test-object->markup (make-test-object (list void void) (list fail-unexpected-error fail-unexpected-error/markup fail-unsatisfied-error fail-unsatisfied-error/markup fail-unequal fail-not-within fail-incorrect-error fail-incorrect-error/markup fail-not-mem fail-not-range fail-satisfied-failed fail-property-fail fail-property-error fail-violated-signature) (list signature-violation-1 signature-violation-2 signature-violation-3)))) (define markup-srclocs (markup-folder append '() `((,srcloc-markup? . ,(lambda (markup) (list (srcloc-markup-srcloc markup))))))) (check-equal? (markup-srclocs (test-object->markup (make-test-object (list void) (list fail-unexpected-error) '()))) (list (srcloc 'exn 2 1 30 40) (srcloc 'source 1 0 10 20))) )
49402d49e717971e44def3a28660f618fd1d4277363c6e5662095cfb46cddda9
ocaml/dune
signal.ml
type t = | Int | Term | Abrt | Alrm | Fpe | Hup | Ill | Kill | Pipe | Quit | Segv | Usr1 | Usr2 | Chld | Cont | Stop | Tstp | Ttin | Ttou | Vtalrm | Prof | Bus | Poll | Sys | Trap | Urg | Xcpu | Xfsz | Unknown of int let all = let open Sys in [ (Abrt, sigabrt) ; (Alrm, sigalrm) ; (Fpe, sigfpe) ; (Hup, sighup) ; (Ill, sigill) ; (Int, sigint) ; (Kill, sigkill) ; (Pipe, sigpipe) ; (Quit, sigquit) ; (Segv, sigsegv) ; (Term, sigterm) ; (Usr1, sigusr1) ; (Usr2, sigusr2) ; (Chld, sigchld) ; (Cont, sigcont) ; (Stop, sigstop) ; (Tstp, sigtstp) ; (Ttin, sigttin) ; (Ttou, sigttou) ; (Vtalrm, sigvtalrm) ; (Prof, sigprof) ; (Bus, sigbus) ; (Poll, sigpoll) ; (Sys, sigsys) ; (Trap, sigtrap) ; (Urg, sigurg) ; (Xcpu, sigxcpu) ; (Xfsz, sigxfsz) ] let name = function | Abrt -> "ABRT" | Alrm -> "ALRM" | Fpe -> "FPE" | Hup -> "HUP" | Ill -> "ILL" | Int -> "INT" | Kill -> "KILL" | Pipe -> "PIPE" | Quit -> "QUIT" | Segv -> "SEGV" | Term -> "TERM" | Usr1 -> "USR1" | Usr2 -> "USR2" | Chld -> "CHLD" | Cont -> "CONT" | Stop -> "STOP" | Tstp -> "TSTP" | Ttin -> "TTIN" | Ttou -> "TTOU" | Vtalrm -> "VTALRM" | Prof -> "PROF" | Bus -> "BUS" | Poll -> "POLL" | Sys -> "SYS" | Trap -> "TRAP" | Urg -> "URG" | Xcpu -> "XCPU" | Xfsz -> "XFSZ" | Unknown n -> Int.to_string n let compare (x : t) (y : t) = Poly.compare x y let to_dyn = let open Dyn in function | Unknown n -> variant "Unknown" [ int n ] | t -> variant (name t) [] include Comparable.Make (struct type nonrec t = t let compare = compare let to_dyn = to_dyn end) let to_int = let table = Map.of_list_exn all in function | Unknown n -> n | t -> Map.find_exn table t let of_int i = let table = Int.Map.of_list_exn (List.map all ~f:(fun (t, i) -> (i, t))) in match Int.Map.find table i with | None -> Unknown i | Some s -> s
null
https://raw.githubusercontent.com/ocaml/dune/714626f4d408e5c71c24ba91d0d520588702ec52/otherlibs/stdune/src/signal.ml
ocaml
type t = | Int | Term | Abrt | Alrm | Fpe | Hup | Ill | Kill | Pipe | Quit | Segv | Usr1 | Usr2 | Chld | Cont | Stop | Tstp | Ttin | Ttou | Vtalrm | Prof | Bus | Poll | Sys | Trap | Urg | Xcpu | Xfsz | Unknown of int let all = let open Sys in [ (Abrt, sigabrt) ; (Alrm, sigalrm) ; (Fpe, sigfpe) ; (Hup, sighup) ; (Ill, sigill) ; (Int, sigint) ; (Kill, sigkill) ; (Pipe, sigpipe) ; (Quit, sigquit) ; (Segv, sigsegv) ; (Term, sigterm) ; (Usr1, sigusr1) ; (Usr2, sigusr2) ; (Chld, sigchld) ; (Cont, sigcont) ; (Stop, sigstop) ; (Tstp, sigtstp) ; (Ttin, sigttin) ; (Ttou, sigttou) ; (Vtalrm, sigvtalrm) ; (Prof, sigprof) ; (Bus, sigbus) ; (Poll, sigpoll) ; (Sys, sigsys) ; (Trap, sigtrap) ; (Urg, sigurg) ; (Xcpu, sigxcpu) ; (Xfsz, sigxfsz) ] let name = function | Abrt -> "ABRT" | Alrm -> "ALRM" | Fpe -> "FPE" | Hup -> "HUP" | Ill -> "ILL" | Int -> "INT" | Kill -> "KILL" | Pipe -> "PIPE" | Quit -> "QUIT" | Segv -> "SEGV" | Term -> "TERM" | Usr1 -> "USR1" | Usr2 -> "USR2" | Chld -> "CHLD" | Cont -> "CONT" | Stop -> "STOP" | Tstp -> "TSTP" | Ttin -> "TTIN" | Ttou -> "TTOU" | Vtalrm -> "VTALRM" | Prof -> "PROF" | Bus -> "BUS" | Poll -> "POLL" | Sys -> "SYS" | Trap -> "TRAP" | Urg -> "URG" | Xcpu -> "XCPU" | Xfsz -> "XFSZ" | Unknown n -> Int.to_string n let compare (x : t) (y : t) = Poly.compare x y let to_dyn = let open Dyn in function | Unknown n -> variant "Unknown" [ int n ] | t -> variant (name t) [] include Comparable.Make (struct type nonrec t = t let compare = compare let to_dyn = to_dyn end) let to_int = let table = Map.of_list_exn all in function | Unknown n -> n | t -> Map.find_exn table t let of_int i = let table = Int.Map.of_list_exn (List.map all ~f:(fun (t, i) -> (i, t))) in match Int.Map.find table i with | None -> Unknown i | Some s -> s
5569c3596ddb5fef85163eba7ce5f8aee1d8200ea85e71ceb27deb8c713c81d3
CATechnologiesTest/arete
module_order.clj
(ns engine.module-order (:require [engine.core :refer :all])) (deforder (:from-module :engine.module-order)) (defrule rule1 [?x :x] => (remove! ?x) (insert! {:type :order}))
null
https://raw.githubusercontent.com/CATechnologiesTest/arete/1ccaa554abd3ee4499cbe2381af2ed2af33fb420/test/engine/module_order.clj
clojure
(ns engine.module-order (:require [engine.core :refer :all])) (deforder (:from-module :engine.module-order)) (defrule rule1 [?x :x] => (remove! ?x) (insert! {:type :order}))
5dc733e43391e469706b7025023eae2bca788b574e36698c63865fb8a157409a
grin-compiler/ghc-whole-program-compiler-project
Stubs.hs
# LANGUAGE LambdaCase # module Stg.Foreign.Stubs where import qualified Data.ByteString.Char8 as BS8 import Stg.Program import Stg.Syntax import Stg.GHC.Symbols genStubs :: FilePath -> IO String genStubs ghcstgappFname = do mods <- getGhcStgAppModules ghcstgappFname let stubs = concat $ [map genStubCode l | ForeignStubs _ _ _ _ l <- map moduleForeignStubs $ mods] fileIncludes = [] -- ["#include \"HsFFI.h\""] code = unlines $ filter (not . null) $ fileIncludes ++ stubs ++ extraHack extraHack = [ "char " ++ n ++ ";" | n <- rtsSymbols ] pure code -- gen code + collect include headers genStubCode :: StubDecl -> String genStubCode = \case StubDeclImport fi ( Just impl ) | CImport _ _ mHeader spec _ < - fi , StubImplImportCApi wrapperName ctys@(ret : args ) < - impl , CFunction target < - spec , StaticTarget _ cName _ isFun < - target - > let ( _ , retCType , retHsType ) = ret ( cParams , cArgs ) = unzip [ ( BS8.unpack t + + " " + + name , name ) | ( i , ( _ , t , _ ) ) < - zip [ 1 .. ] args , let name = " a " + + show i ] returnCommand = case retHsType of ' v ' - > " " _ - > " return " callCommand = if isFun then BS8.unpack cName + + " ( " + + intercalate " , " cArgs + + " ) " else BS8.unpack cName cCode = BS8.unpack retCType + + " " + + BS8.unpack wrapperName + + " ( " + + intercalate " , " cParams + + " ) { " + + returnCommand + + " " + + callCommand + + " ; } " cIncludes = [ " # include " + + show h | Header _ h < - nub $ catMaybes $ mHeader : [ h | ( h , _ , _ ) < - ctys ] ] in unlines $ cIncludes + + [ cCode ] StubDeclImport _ ( Just StubImplImportCWrapper { } ) - > " " StubDeclImport _ Nothing - > " " StubDeclImport fi (Just impl) | CImport _ _ mHeader spec _ <- fi , StubImplImportCApi wrapperName ctys@(ret : args) <- impl , CFunction target <- spec , StaticTarget _ cName _ isFun <- target -> let (_, retCType, retHsType) = ret (cParams, cArgs) = unzip [ (BS8.unpack t ++ " " ++ name, name) | (i, (_, t, _)) <- zip [1..] args , let name = "a" ++ show i ] returnCommand = case retHsType of 'v' -> "" _ -> "return" callCommand = if isFun then BS8.unpack cName ++ "(" ++ intercalate ", " cArgs ++ ")" else BS8.unpack cName cCode = BS8.unpack retCType ++ " " ++ BS8.unpack wrapperName ++ "(" ++ intercalate ", " cParams ++ "){" ++ returnCommand ++ " " ++ callCommand ++ ";}" cIncludes = ["#include " ++ show h | Header _ h <- nub $ catMaybes $ mHeader : [h | (h, _, _) <- ctys]] in unlines $ cIncludes ++ [cCode] StubDeclImport _ (Just StubImplImportCWrapper{}) -> "" StubDeclImport _ Nothing -> "" -} StubDeclImport{} -> "" d@(StubDeclExport (CExport (CExportStatic _ name _) _) _ _) -> unlines [ "// not implemented: " ++ show d , "char " ++ BS8.unpack name ++ ";" -- FIXME: temporary hack , "" ]
null
https://raw.githubusercontent.com/grin-compiler/ghc-whole-program-compiler-project/6e75aaccf4df0d78786f5bb1a28778d54c09a7be/external-stg/lib/Stg/Foreign/Stubs.hs
haskell
["#include \"HsFFI.h\""] gen code + collect include headers FIXME: temporary hack
# LANGUAGE LambdaCase # module Stg.Foreign.Stubs where import qualified Data.ByteString.Char8 as BS8 import Stg.Program import Stg.Syntax import Stg.GHC.Symbols genStubs :: FilePath -> IO String genStubs ghcstgappFname = do mods <- getGhcStgAppModules ghcstgappFname let stubs = concat $ [map genStubCode l | ForeignStubs _ _ _ _ l <- map moduleForeignStubs $ mods] code = unlines $ filter (not . null) $ fileIncludes ++ stubs ++ extraHack extraHack = [ "char " ++ n ++ ";" | n <- rtsSymbols ] pure code genStubCode :: StubDecl -> String genStubCode = \case StubDeclImport fi ( Just impl ) | CImport _ _ mHeader spec _ < - fi , StubImplImportCApi wrapperName ctys@(ret : args ) < - impl , CFunction target < - spec , StaticTarget _ cName _ isFun < - target - > let ( _ , retCType , retHsType ) = ret ( cParams , cArgs ) = unzip [ ( BS8.unpack t + + " " + + name , name ) | ( i , ( _ , t , _ ) ) < - zip [ 1 .. ] args , let name = " a " + + show i ] returnCommand = case retHsType of ' v ' - > " " _ - > " return " callCommand = if isFun then BS8.unpack cName + + " ( " + + intercalate " , " cArgs + + " ) " else BS8.unpack cName cCode = BS8.unpack retCType + + " " + + BS8.unpack wrapperName + + " ( " + + intercalate " , " cParams + + " ) { " + + returnCommand + + " " + + callCommand + + " ; } " cIncludes = [ " # include " + + show h | Header _ h < - nub $ catMaybes $ mHeader : [ h | ( h , _ , _ ) < - ctys ] ] in unlines $ cIncludes + + [ cCode ] StubDeclImport _ ( Just StubImplImportCWrapper { } ) - > " " StubDeclImport _ Nothing - > " " StubDeclImport fi (Just impl) | CImport _ _ mHeader spec _ <- fi , StubImplImportCApi wrapperName ctys@(ret : args) <- impl , CFunction target <- spec , StaticTarget _ cName _ isFun <- target -> let (_, retCType, retHsType) = ret (cParams, cArgs) = unzip [ (BS8.unpack t ++ " " ++ name, name) | (i, (_, t, _)) <- zip [1..] args , let name = "a" ++ show i ] returnCommand = case retHsType of 'v' -> "" _ -> "return" callCommand = if isFun then BS8.unpack cName ++ "(" ++ intercalate ", " cArgs ++ ")" else BS8.unpack cName cCode = BS8.unpack retCType ++ " " ++ BS8.unpack wrapperName ++ "(" ++ intercalate ", " cParams ++ "){" ++ returnCommand ++ " " ++ callCommand ++ ";}" cIncludes = ["#include " ++ show h | Header _ h <- nub $ catMaybes $ mHeader : [h | (h, _, _) <- ctys]] in unlines $ cIncludes ++ [cCode] StubDeclImport _ (Just StubImplImportCWrapper{}) -> "" StubDeclImport _ Nothing -> "" -} StubDeclImport{} -> "" d@(StubDeclExport (CExport (CExportStatic _ name _) _) _ _) -> unlines [ "// not implemented: " ++ show d , "" ]
c84324fd413c52fa433a9360e39ae9ae5ed5c980916371c158600379432b4806
jspahrsummers/RxHaskell
Event.hs
{-# LANGUAGE Safe #-} module Signal.Event ( Event(..) ) where import Control.Exception -- | Represents an event that a signal might send. -- Signals may send any number of ' NextEvent 's , followed by one ' ErrorEvent ' /or/ ' CompletedEvent ' . ^ A value @v@ in the monad . | ErrorEvent IOException -- ^ Sent when an error or exception occurs in the signal. Outside of the monad. | CompletedEvent -- ^ Sent when the signal completes successfully. Outside of the monad. instance Eq v => Eq (Event v) where (NextEvent v) == (NextEvent v') = v == v' (ErrorEvent e) == (ErrorEvent e') = e == e' CompletedEvent == CompletedEvent = True _ == _ = False instance Show v => Show (Event v) where show (NextEvent v) = "NextEvent " ++ show v show (ErrorEvent e) = "ErrorEvent " ++ show e show CompletedEvent = "CompletedEvent"
null
https://raw.githubusercontent.com/jspahrsummers/RxHaskell/19550bb692a6a6e56314fe3aebb1303a22e577ed/Signal/Event.hs
haskell
# LANGUAGE Safe # | Represents an event that a signal might send. ^ Sent when an error or exception occurs in the signal. Outside of the monad. ^ Sent when the signal completes successfully. Outside of the monad.
module Signal.Event ( Event(..) ) where import Control.Exception Signals may send any number of ' NextEvent 's , followed by one ' ErrorEvent ' /or/ ' CompletedEvent ' . ^ A value @v@ in the monad . instance Eq v => Eq (Event v) where (NextEvent v) == (NextEvent v') = v == v' (ErrorEvent e) == (ErrorEvent e') = e == e' CompletedEvent == CompletedEvent = True _ == _ = False instance Show v => Show (Event v) where show (NextEvent v) = "NextEvent " ++ show v show (ErrorEvent e) = "ErrorEvent " ++ show e show CompletedEvent = "CompletedEvent"
9a9e72a2ea949d61411c1128773350cdedaaecb593aa655781cb3347b8cf4ce9
eugenehr/erlyconv
cp863.erl
%% THIS FILE WAS AUTOMATICALLY GENERATED BY gen_src.pl FROM mappings / MICSFT / PC / CP863.TXT AT 2016 - 08 - 19 -module(cp863). -vsn(20160819). -export([to_unicode/1, from_unicode/1]). %% Public functions to_unicode(16#80) -> 16#00c7; to_unicode(16#81) -> 16#00fc; to_unicode(16#82) -> 16#00e9; to_unicode(16#83) -> 16#00e2; to_unicode(16#84) -> 16#00c2; to_unicode(16#85) -> 16#00e0; to_unicode(16#86) -> 16#00b6; to_unicode(16#87) -> 16#00e7; to_unicode(16#88) -> 16#00ea; to_unicode(16#89) -> 16#00eb; to_unicode(16#8a) -> 16#00e8; to_unicode(16#8b) -> 16#00ef; to_unicode(16#8c) -> 16#00ee; to_unicode(16#8d) -> 16#2017; to_unicode(16#8e) -> 16#00c0; to_unicode(16#8f) -> 16#00a7; to_unicode(16#90) -> 16#00c9; to_unicode(16#91) -> 16#00c8; to_unicode(16#92) -> 16#00ca; to_unicode(16#93) -> 16#00f4; to_unicode(16#94) -> 16#00cb; to_unicode(16#95) -> 16#00cf; to_unicode(16#96) -> 16#00fb; to_unicode(16#97) -> 16#00f9; to_unicode(16#98) -> 16#00a4; to_unicode(16#99) -> 16#00d4; to_unicode(16#9a) -> 16#00dc; to_unicode(16#9b) -> 16#00a2; to_unicode(16#9c) -> 16#00a3; to_unicode(16#9d) -> 16#00d9; to_unicode(16#9e) -> 16#00db; to_unicode(16#9f) -> 16#0192; to_unicode(16#a0) -> 16#00a6; to_unicode(16#a1) -> 16#00b4; to_unicode(16#a2) -> 16#00f3; to_unicode(16#a3) -> 16#00fa; to_unicode(16#a4) -> 16#00a8; to_unicode(16#a5) -> 16#00b8; to_unicode(16#a6) -> 16#00b3; to_unicode(16#a7) -> 16#00af; to_unicode(16#a8) -> 16#00ce; to_unicode(16#a9) -> 16#2310; to_unicode(16#aa) -> 16#00ac; to_unicode(16#ab) -> 16#00bd; to_unicode(16#ac) -> 16#00bc; to_unicode(16#ad) -> 16#00be; to_unicode(16#ae) -> 16#00ab; to_unicode(16#af) -> 16#00bb; to_unicode(16#b0) -> 16#2591; to_unicode(16#b1) -> 16#2592; to_unicode(16#b2) -> 16#2593; to_unicode(16#b3) -> 16#2502; to_unicode(16#b4) -> 16#2524; to_unicode(16#b5) -> 16#2561; to_unicode(16#b6) -> 16#2562; to_unicode(16#b7) -> 16#2556; to_unicode(16#b8) -> 16#2555; to_unicode(16#b9) -> 16#2563; to_unicode(16#ba) -> 16#2551; to_unicode(16#bb) -> 16#2557; to_unicode(16#bc) -> 16#255d; to_unicode(16#bd) -> 16#255c; to_unicode(16#be) -> 16#255b; to_unicode(16#bf) -> 16#2510; to_unicode(16#c0) -> 16#2514; to_unicode(16#c1) -> 16#2534; to_unicode(16#c2) -> 16#252c; to_unicode(16#c3) -> 16#251c; to_unicode(16#c4) -> 16#2500; to_unicode(16#c5) -> 16#253c; to_unicode(16#c6) -> 16#255e; to_unicode(16#c7) -> 16#255f; to_unicode(16#c8) -> 16#255a; to_unicode(16#c9) -> 16#2554; to_unicode(16#ca) -> 16#2569; to_unicode(16#cb) -> 16#2566; to_unicode(16#cc) -> 16#2560; to_unicode(16#cd) -> 16#2550; to_unicode(16#ce) -> 16#256c; to_unicode(16#cf) -> 16#2567; to_unicode(16#d0) -> 16#2568; to_unicode(16#d1) -> 16#2564; to_unicode(16#d2) -> 16#2565; to_unicode(16#d3) -> 16#2559; to_unicode(16#d4) -> 16#2558; to_unicode(16#d5) -> 16#2552; to_unicode(16#d6) -> 16#2553; to_unicode(16#d7) -> 16#256b; to_unicode(16#d8) -> 16#256a; to_unicode(16#d9) -> 16#2518; to_unicode(16#da) -> 16#250c; to_unicode(16#db) -> 16#2588; to_unicode(16#dc) -> 16#2584; to_unicode(16#dd) -> 16#258c; to_unicode(16#de) -> 16#2590; to_unicode(16#df) -> 16#2580; to_unicode(16#e0) -> 16#03b1; to_unicode(16#e1) -> 16#00df; to_unicode(16#e2) -> 16#0393; to_unicode(16#e3) -> 16#03c0; to_unicode(16#e4) -> 16#03a3; to_unicode(16#e5) -> 16#03c3; to_unicode(16#e6) -> 16#00b5; to_unicode(16#e7) -> 16#03c4; to_unicode(16#e8) -> 16#03a6; to_unicode(16#e9) -> 16#0398; to_unicode(16#ea) -> 16#03a9; to_unicode(16#eb) -> 16#03b4; to_unicode(16#ec) -> 16#221e; to_unicode(16#ed) -> 16#03c6; to_unicode(16#ee) -> 16#03b5; to_unicode(16#ef) -> 16#2229; to_unicode(16#f0) -> 16#2261; to_unicode(16#f1) -> 16#00b1; to_unicode(16#f2) -> 16#2265; to_unicode(16#f3) -> 16#2264; to_unicode(16#f4) -> 16#2320; to_unicode(16#f5) -> 16#2321; to_unicode(16#f6) -> 16#00f7; to_unicode(16#f7) -> 16#2248; to_unicode(16#f8) -> 16#00b0; to_unicode(16#f9) -> 16#2219; to_unicode(16#fa) -> 16#00b7; to_unicode(16#fb) -> 16#221a; to_unicode(16#fc) -> 16#207f; to_unicode(16#fd) -> 16#00b2; to_unicode(16#fe) -> 16#25a0; to_unicode(16#ff) -> 16#00a0; to_unicode(List) when is_list(List) -> [to_unicode(C) || C <- List]; to_unicode(Bin) when is_binary(Bin) -> bin_to_unicode(Bin, <<>>); to_unicode(Other) -> Other. from_unicode(16#00c7) -> 16#80; from_unicode(16#00fc) -> 16#81; from_unicode(16#00e9) -> 16#82; from_unicode(16#00e2) -> 16#83; from_unicode(16#00c2) -> 16#84; from_unicode(16#00e0) -> 16#85; from_unicode(16#00b6) -> 16#86; from_unicode(16#00e7) -> 16#87; from_unicode(16#00ea) -> 16#88; from_unicode(16#00eb) -> 16#89; from_unicode(16#00e8) -> 16#8a; from_unicode(16#00ef) -> 16#8b; from_unicode(16#00ee) -> 16#8c; from_unicode(16#2017) -> 16#8d; from_unicode(16#00c0) -> 16#8e; from_unicode(16#00a7) -> 16#8f; from_unicode(16#00c9) -> 16#90; from_unicode(16#00c8) -> 16#91; from_unicode(16#00ca) -> 16#92; from_unicode(16#00f4) -> 16#93; from_unicode(16#00cb) -> 16#94; from_unicode(16#00cf) -> 16#95; from_unicode(16#00fb) -> 16#96; from_unicode(16#00f9) -> 16#97; from_unicode(16#00a4) -> 16#98; from_unicode(16#00d4) -> 16#99; from_unicode(16#00dc) -> 16#9a; from_unicode(16#00a2) -> 16#9b; from_unicode(16#00a3) -> 16#9c; from_unicode(16#00d9) -> 16#9d; from_unicode(16#00db) -> 16#9e; from_unicode(16#0192) -> 16#9f; from_unicode(16#00a6) -> 16#a0; from_unicode(16#00b4) -> 16#a1; from_unicode(16#00f3) -> 16#a2; from_unicode(16#00fa) -> 16#a3; from_unicode(16#00a8) -> 16#a4; from_unicode(16#00b8) -> 16#a5; from_unicode(16#00b3) -> 16#a6; from_unicode(16#00af) -> 16#a7; from_unicode(16#00ce) -> 16#a8; from_unicode(16#2310) -> 16#a9; from_unicode(16#00ac) -> 16#aa; from_unicode(16#00bd) -> 16#ab; from_unicode(16#00bc) -> 16#ac; from_unicode(16#00be) -> 16#ad; from_unicode(16#00ab) -> 16#ae; from_unicode(16#00bb) -> 16#af; from_unicode(16#2591) -> 16#b0; from_unicode(16#2592) -> 16#b1; from_unicode(16#2593) -> 16#b2; from_unicode(16#2502) -> 16#b3; from_unicode(16#2524) -> 16#b4; from_unicode(16#2561) -> 16#b5; from_unicode(16#2562) -> 16#b6; from_unicode(16#2556) -> 16#b7; from_unicode(16#2555) -> 16#b8; from_unicode(16#2563) -> 16#b9; from_unicode(16#2551) -> 16#ba; from_unicode(16#2557) -> 16#bb; from_unicode(16#255d) -> 16#bc; from_unicode(16#255c) -> 16#bd; from_unicode(16#255b) -> 16#be; from_unicode(16#2510) -> 16#bf; from_unicode(16#2514) -> 16#c0; from_unicode(16#2534) -> 16#c1; from_unicode(16#252c) -> 16#c2; from_unicode(16#251c) -> 16#c3; from_unicode(16#2500) -> 16#c4; from_unicode(16#253c) -> 16#c5; from_unicode(16#255e) -> 16#c6; from_unicode(16#255f) -> 16#c7; from_unicode(16#255a) -> 16#c8; from_unicode(16#2554) -> 16#c9; from_unicode(16#2569) -> 16#ca; from_unicode(16#2566) -> 16#cb; from_unicode(16#2560) -> 16#cc; from_unicode(16#2550) -> 16#cd; from_unicode(16#256c) -> 16#ce; from_unicode(16#2567) -> 16#cf; from_unicode(16#2568) -> 16#d0; from_unicode(16#2564) -> 16#d1; from_unicode(16#2565) -> 16#d2; from_unicode(16#2559) -> 16#d3; from_unicode(16#2558) -> 16#d4; from_unicode(16#2552) -> 16#d5; from_unicode(16#2553) -> 16#d6; from_unicode(16#256b) -> 16#d7; from_unicode(16#256a) -> 16#d8; from_unicode(16#2518) -> 16#d9; from_unicode(16#250c) -> 16#da; from_unicode(16#2588) -> 16#db; from_unicode(16#2584) -> 16#dc; from_unicode(16#258c) -> 16#dd; from_unicode(16#2590) -> 16#de; from_unicode(16#2580) -> 16#df; from_unicode(16#03b1) -> 16#e0; from_unicode(16#00df) -> 16#e1; from_unicode(16#0393) -> 16#e2; from_unicode(16#03c0) -> 16#e3; from_unicode(16#03a3) -> 16#e4; from_unicode(16#03c3) -> 16#e5; from_unicode(16#00b5) -> 16#e6; from_unicode(16#03c4) -> 16#e7; from_unicode(16#03a6) -> 16#e8; from_unicode(16#0398) -> 16#e9; from_unicode(16#03a9) -> 16#ea; from_unicode(16#03b4) -> 16#eb; from_unicode(16#221e) -> 16#ec; from_unicode(16#03c6) -> 16#ed; from_unicode(16#03b5) -> 16#ee; from_unicode(16#2229) -> 16#ef; from_unicode(16#2261) -> 16#f0; from_unicode(16#00b1) -> 16#f1; from_unicode(16#2265) -> 16#f2; from_unicode(16#2264) -> 16#f3; from_unicode(16#2320) -> 16#f4; from_unicode(16#2321) -> 16#f5; from_unicode(16#00f7) -> 16#f6; from_unicode(16#2248) -> 16#f7; from_unicode(16#00b0) -> 16#f8; from_unicode(16#2219) -> 16#f9; from_unicode(16#00b7) -> 16#fa; from_unicode(16#221a) -> 16#fb; from_unicode(16#207f) -> 16#fc; from_unicode(16#00b2) -> 16#fd; from_unicode(16#25a0) -> 16#fe; from_unicode(16#00a0) -> 16#ff; from_unicode(List) when is_list(List) -> [from_unicode(C) || C <- List]; from_unicode(Bin) when is_binary(Bin) -> bin_from_unicode(Bin, <<>>); from_unicode(Other) -> Other. %% Private functions bin_to_unicode(<<>>, Bin) -> Bin; bin_to_unicode(<<C, Rest/binary>>, Acc) -> U = to_unicode(C), bin_to_unicode(Rest, <<Acc/binary, U/utf8>>). bin_from_unicode(<<>>, Bin) -> Bin; bin_from_unicode(<<U/utf8, Rest/binary>>, Acc) -> C = from_unicode(U), bin_from_unicode(Rest, <<Acc/binary, C>>).
null
https://raw.githubusercontent.com/eugenehr/erlyconv/ecdcd7db8f785c9638cd1ebad37ccd426c050cdf/src/cp863.erl
erlang
THIS FILE WAS AUTOMATICALLY GENERATED BY gen_src.pl Public functions Private functions
FROM mappings / MICSFT / PC / CP863.TXT AT 2016 - 08 - 19 -module(cp863). -vsn(20160819). -export([to_unicode/1, from_unicode/1]). to_unicode(16#80) -> 16#00c7; to_unicode(16#81) -> 16#00fc; to_unicode(16#82) -> 16#00e9; to_unicode(16#83) -> 16#00e2; to_unicode(16#84) -> 16#00c2; to_unicode(16#85) -> 16#00e0; to_unicode(16#86) -> 16#00b6; to_unicode(16#87) -> 16#00e7; to_unicode(16#88) -> 16#00ea; to_unicode(16#89) -> 16#00eb; to_unicode(16#8a) -> 16#00e8; to_unicode(16#8b) -> 16#00ef; to_unicode(16#8c) -> 16#00ee; to_unicode(16#8d) -> 16#2017; to_unicode(16#8e) -> 16#00c0; to_unicode(16#8f) -> 16#00a7; to_unicode(16#90) -> 16#00c9; to_unicode(16#91) -> 16#00c8; to_unicode(16#92) -> 16#00ca; to_unicode(16#93) -> 16#00f4; to_unicode(16#94) -> 16#00cb; to_unicode(16#95) -> 16#00cf; to_unicode(16#96) -> 16#00fb; to_unicode(16#97) -> 16#00f9; to_unicode(16#98) -> 16#00a4; to_unicode(16#99) -> 16#00d4; to_unicode(16#9a) -> 16#00dc; to_unicode(16#9b) -> 16#00a2; to_unicode(16#9c) -> 16#00a3; to_unicode(16#9d) -> 16#00d9; to_unicode(16#9e) -> 16#00db; to_unicode(16#9f) -> 16#0192; to_unicode(16#a0) -> 16#00a6; to_unicode(16#a1) -> 16#00b4; to_unicode(16#a2) -> 16#00f3; to_unicode(16#a3) -> 16#00fa; to_unicode(16#a4) -> 16#00a8; to_unicode(16#a5) -> 16#00b8; to_unicode(16#a6) -> 16#00b3; to_unicode(16#a7) -> 16#00af; to_unicode(16#a8) -> 16#00ce; to_unicode(16#a9) -> 16#2310; to_unicode(16#aa) -> 16#00ac; to_unicode(16#ab) -> 16#00bd; to_unicode(16#ac) -> 16#00bc; to_unicode(16#ad) -> 16#00be; to_unicode(16#ae) -> 16#00ab; to_unicode(16#af) -> 16#00bb; to_unicode(16#b0) -> 16#2591; to_unicode(16#b1) -> 16#2592; to_unicode(16#b2) -> 16#2593; to_unicode(16#b3) -> 16#2502; to_unicode(16#b4) -> 16#2524; to_unicode(16#b5) -> 16#2561; to_unicode(16#b6) -> 16#2562; to_unicode(16#b7) -> 16#2556; to_unicode(16#b8) -> 16#2555; to_unicode(16#b9) -> 16#2563; to_unicode(16#ba) -> 16#2551; to_unicode(16#bb) -> 16#2557; to_unicode(16#bc) -> 16#255d; to_unicode(16#bd) -> 16#255c; to_unicode(16#be) -> 16#255b; to_unicode(16#bf) -> 16#2510; to_unicode(16#c0) -> 16#2514; to_unicode(16#c1) -> 16#2534; to_unicode(16#c2) -> 16#252c; to_unicode(16#c3) -> 16#251c; to_unicode(16#c4) -> 16#2500; to_unicode(16#c5) -> 16#253c; to_unicode(16#c6) -> 16#255e; to_unicode(16#c7) -> 16#255f; to_unicode(16#c8) -> 16#255a; to_unicode(16#c9) -> 16#2554; to_unicode(16#ca) -> 16#2569; to_unicode(16#cb) -> 16#2566; to_unicode(16#cc) -> 16#2560; to_unicode(16#cd) -> 16#2550; to_unicode(16#ce) -> 16#256c; to_unicode(16#cf) -> 16#2567; to_unicode(16#d0) -> 16#2568; to_unicode(16#d1) -> 16#2564; to_unicode(16#d2) -> 16#2565; to_unicode(16#d3) -> 16#2559; to_unicode(16#d4) -> 16#2558; to_unicode(16#d5) -> 16#2552; to_unicode(16#d6) -> 16#2553; to_unicode(16#d7) -> 16#256b; to_unicode(16#d8) -> 16#256a; to_unicode(16#d9) -> 16#2518; to_unicode(16#da) -> 16#250c; to_unicode(16#db) -> 16#2588; to_unicode(16#dc) -> 16#2584; to_unicode(16#dd) -> 16#258c; to_unicode(16#de) -> 16#2590; to_unicode(16#df) -> 16#2580; to_unicode(16#e0) -> 16#03b1; to_unicode(16#e1) -> 16#00df; to_unicode(16#e2) -> 16#0393; to_unicode(16#e3) -> 16#03c0; to_unicode(16#e4) -> 16#03a3; to_unicode(16#e5) -> 16#03c3; to_unicode(16#e6) -> 16#00b5; to_unicode(16#e7) -> 16#03c4; to_unicode(16#e8) -> 16#03a6; to_unicode(16#e9) -> 16#0398; to_unicode(16#ea) -> 16#03a9; to_unicode(16#eb) -> 16#03b4; to_unicode(16#ec) -> 16#221e; to_unicode(16#ed) -> 16#03c6; to_unicode(16#ee) -> 16#03b5; to_unicode(16#ef) -> 16#2229; to_unicode(16#f0) -> 16#2261; to_unicode(16#f1) -> 16#00b1; to_unicode(16#f2) -> 16#2265; to_unicode(16#f3) -> 16#2264; to_unicode(16#f4) -> 16#2320; to_unicode(16#f5) -> 16#2321; to_unicode(16#f6) -> 16#00f7; to_unicode(16#f7) -> 16#2248; to_unicode(16#f8) -> 16#00b0; to_unicode(16#f9) -> 16#2219; to_unicode(16#fa) -> 16#00b7; to_unicode(16#fb) -> 16#221a; to_unicode(16#fc) -> 16#207f; to_unicode(16#fd) -> 16#00b2; to_unicode(16#fe) -> 16#25a0; to_unicode(16#ff) -> 16#00a0; to_unicode(List) when is_list(List) -> [to_unicode(C) || C <- List]; to_unicode(Bin) when is_binary(Bin) -> bin_to_unicode(Bin, <<>>); to_unicode(Other) -> Other. from_unicode(16#00c7) -> 16#80; from_unicode(16#00fc) -> 16#81; from_unicode(16#00e9) -> 16#82; from_unicode(16#00e2) -> 16#83; from_unicode(16#00c2) -> 16#84; from_unicode(16#00e0) -> 16#85; from_unicode(16#00b6) -> 16#86; from_unicode(16#00e7) -> 16#87; from_unicode(16#00ea) -> 16#88; from_unicode(16#00eb) -> 16#89; from_unicode(16#00e8) -> 16#8a; from_unicode(16#00ef) -> 16#8b; from_unicode(16#00ee) -> 16#8c; from_unicode(16#2017) -> 16#8d; from_unicode(16#00c0) -> 16#8e; from_unicode(16#00a7) -> 16#8f; from_unicode(16#00c9) -> 16#90; from_unicode(16#00c8) -> 16#91; from_unicode(16#00ca) -> 16#92; from_unicode(16#00f4) -> 16#93; from_unicode(16#00cb) -> 16#94; from_unicode(16#00cf) -> 16#95; from_unicode(16#00fb) -> 16#96; from_unicode(16#00f9) -> 16#97; from_unicode(16#00a4) -> 16#98; from_unicode(16#00d4) -> 16#99; from_unicode(16#00dc) -> 16#9a; from_unicode(16#00a2) -> 16#9b; from_unicode(16#00a3) -> 16#9c; from_unicode(16#00d9) -> 16#9d; from_unicode(16#00db) -> 16#9e; from_unicode(16#0192) -> 16#9f; from_unicode(16#00a6) -> 16#a0; from_unicode(16#00b4) -> 16#a1; from_unicode(16#00f3) -> 16#a2; from_unicode(16#00fa) -> 16#a3; from_unicode(16#00a8) -> 16#a4; from_unicode(16#00b8) -> 16#a5; from_unicode(16#00b3) -> 16#a6; from_unicode(16#00af) -> 16#a7; from_unicode(16#00ce) -> 16#a8; from_unicode(16#2310) -> 16#a9; from_unicode(16#00ac) -> 16#aa; from_unicode(16#00bd) -> 16#ab; from_unicode(16#00bc) -> 16#ac; from_unicode(16#00be) -> 16#ad; from_unicode(16#00ab) -> 16#ae; from_unicode(16#00bb) -> 16#af; from_unicode(16#2591) -> 16#b0; from_unicode(16#2592) -> 16#b1; from_unicode(16#2593) -> 16#b2; from_unicode(16#2502) -> 16#b3; from_unicode(16#2524) -> 16#b4; from_unicode(16#2561) -> 16#b5; from_unicode(16#2562) -> 16#b6; from_unicode(16#2556) -> 16#b7; from_unicode(16#2555) -> 16#b8; from_unicode(16#2563) -> 16#b9; from_unicode(16#2551) -> 16#ba; from_unicode(16#2557) -> 16#bb; from_unicode(16#255d) -> 16#bc; from_unicode(16#255c) -> 16#bd; from_unicode(16#255b) -> 16#be; from_unicode(16#2510) -> 16#bf; from_unicode(16#2514) -> 16#c0; from_unicode(16#2534) -> 16#c1; from_unicode(16#252c) -> 16#c2; from_unicode(16#251c) -> 16#c3; from_unicode(16#2500) -> 16#c4; from_unicode(16#253c) -> 16#c5; from_unicode(16#255e) -> 16#c6; from_unicode(16#255f) -> 16#c7; from_unicode(16#255a) -> 16#c8; from_unicode(16#2554) -> 16#c9; from_unicode(16#2569) -> 16#ca; from_unicode(16#2566) -> 16#cb; from_unicode(16#2560) -> 16#cc; from_unicode(16#2550) -> 16#cd; from_unicode(16#256c) -> 16#ce; from_unicode(16#2567) -> 16#cf; from_unicode(16#2568) -> 16#d0; from_unicode(16#2564) -> 16#d1; from_unicode(16#2565) -> 16#d2; from_unicode(16#2559) -> 16#d3; from_unicode(16#2558) -> 16#d4; from_unicode(16#2552) -> 16#d5; from_unicode(16#2553) -> 16#d6; from_unicode(16#256b) -> 16#d7; from_unicode(16#256a) -> 16#d8; from_unicode(16#2518) -> 16#d9; from_unicode(16#250c) -> 16#da; from_unicode(16#2588) -> 16#db; from_unicode(16#2584) -> 16#dc; from_unicode(16#258c) -> 16#dd; from_unicode(16#2590) -> 16#de; from_unicode(16#2580) -> 16#df; from_unicode(16#03b1) -> 16#e0; from_unicode(16#00df) -> 16#e1; from_unicode(16#0393) -> 16#e2; from_unicode(16#03c0) -> 16#e3; from_unicode(16#03a3) -> 16#e4; from_unicode(16#03c3) -> 16#e5; from_unicode(16#00b5) -> 16#e6; from_unicode(16#03c4) -> 16#e7; from_unicode(16#03a6) -> 16#e8; from_unicode(16#0398) -> 16#e9; from_unicode(16#03a9) -> 16#ea; from_unicode(16#03b4) -> 16#eb; from_unicode(16#221e) -> 16#ec; from_unicode(16#03c6) -> 16#ed; from_unicode(16#03b5) -> 16#ee; from_unicode(16#2229) -> 16#ef; from_unicode(16#2261) -> 16#f0; from_unicode(16#00b1) -> 16#f1; from_unicode(16#2265) -> 16#f2; from_unicode(16#2264) -> 16#f3; from_unicode(16#2320) -> 16#f4; from_unicode(16#2321) -> 16#f5; from_unicode(16#00f7) -> 16#f6; from_unicode(16#2248) -> 16#f7; from_unicode(16#00b0) -> 16#f8; from_unicode(16#2219) -> 16#f9; from_unicode(16#00b7) -> 16#fa; from_unicode(16#221a) -> 16#fb; from_unicode(16#207f) -> 16#fc; from_unicode(16#00b2) -> 16#fd; from_unicode(16#25a0) -> 16#fe; from_unicode(16#00a0) -> 16#ff; from_unicode(List) when is_list(List) -> [from_unicode(C) || C <- List]; from_unicode(Bin) when is_binary(Bin) -> bin_from_unicode(Bin, <<>>); from_unicode(Other) -> Other. bin_to_unicode(<<>>, Bin) -> Bin; bin_to_unicode(<<C, Rest/binary>>, Acc) -> U = to_unicode(C), bin_to_unicode(Rest, <<Acc/binary, U/utf8>>). bin_from_unicode(<<>>, Bin) -> Bin; bin_from_unicode(<<U/utf8, Rest/binary>>, Acc) -> C = from_unicode(U), bin_from_unicode(Rest, <<Acc/binary, C>>).
d4e952187db045d0fe07caa24ef760af17f1f1df647e02521f83717b5528d7db
esl/ejabberd_tests
metrics_c2s_SUITE.erl
%%============================================================================== Copyright 2013 Erlang Solutions Ltd. %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%============================================================================== -module(metrics_c2s_SUITE). -compile(export_all). -include_lib("escalus/include/escalus.hrl"). -include_lib("common_test/include/ct.hrl"). -define(WAIT_TIME, 100). -import(metrics_helper, [assert_counter/2, get_counter_value/1]). %%-------------------------------------------------------------------- %% Suite configuration %%-------------------------------------------------------------------- all() -> [{group, single}, {group, multiple}, {group, drop}, {group, errors}, {group, count}]. groups() -> [{single, [sequence], [message_one, stanza_one, presence_one, presence_direct_one, iq_one]}, {multiple, [sequence], [messages]}, {drop, [sequence], [bounced ]}, {errors, [sequence], [error_total, error_mesg, error_iq, error_presence]}, {count, [sequence], [stanza_count]}]. suite() -> [{require, ejabberd_node} | escalus:suite()]. %%-------------------------------------------------------------------- Init & teardown %%-------------------------------------------------------------------- init_per_suite(Config) -> Config1 = dynamic_modules:stop_running(mod_offline, Config), escalus:init_per_suite(Config1). end_per_suite(Config) -> dynamic_modules:start_running(Config), escalus:end_per_suite(Config). init_per_group(_GroupName, Config) -> escalus:create_users(Config, {by_name, [alice, bob]}). end_per_group(_GroupName, Config) -> escalus:delete_users(Config, {by_name, [alice, bob]}). init_per_testcase(CaseName, Config) -> escalus:init_per_testcase(CaseName, Config). end_per_testcase(CaseName, Config) -> escalus:end_per_testcase(CaseName, Config). %%-------------------------------------------------------------------- %% Message tests %%-------------------------------------------------------------------- message_one(Config) -> {value, MesgSent} = get_counter_value(xmppMessageSent), {value, MesgReceived} = get_counter_value(xmppMessageReceived), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), assert_counter(MesgSent + 1, xmppMessageSent), assert_counter(MesgReceived + 1, xmppMessageReceived) end). stanza_one(Config) -> escalus:story(Config, [1, 1], fun(Alice, Bob) -> {value, StanzaSent} = get_counter_value(xmppStanzaSent), {value, StanzaReceived} = get_counter_value(xmppStanzaReceived), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), assert_counter(StanzaSent + 1, xmppStanzaSent), assert_counter(StanzaReceived + 1, xmppStanzaReceived) end). presence_one(Config) -> escalus:story(Config, [1], fun(Alice) -> {value, PresenceSent} = get_counter_value(xmppPresenceSent), {value, PresenceReceived} = get_counter_value(xmppPresenceReceived), {value, StanzaSent} = get_counter_value(xmppStanzaSent), {value, StanzaReceived} = get_counter_value(xmppStanzaReceived), escalus:send(Alice, escalus_stanza:presence(<<"available">>)), escalus:wait_for_stanza(Alice), assert_counter(PresenceSent + 1, xmppPresenceSent), assert_counter(PresenceReceived + 1, xmppPresenceReceived), assert_counter(StanzaSent + 1, xmppStanzaSent), assert_counter(StanzaReceived + 1, xmppStanzaReceived) end). presence_direct_one(Config) -> escalus:story(Config, [1, 1], fun(Alice, Bob) -> {value, PresenceSent} = get_counter_value(xmppPresenceSent), {value, PresenceReceived} = get_counter_value(xmppPresenceReceived), {value, StanzaSent} = get_counter_value(xmppStanzaSent), {value, StanzaReceived} = get_counter_value(xmppStanzaReceived), Presence = escalus_stanza:presence_direct(bob, <<"available">>), escalus:send(Alice, Presence), escalus:wait_for_stanza(Bob), assert_counter(PresenceSent + 1, xmppPresenceSent), assert_counter(PresenceReceived + 1, xmppPresenceReceived), assert_counter(StanzaSent + 1, xmppStanzaSent), assert_counter(StanzaReceived + 1, xmppStanzaReceived) end). iq_one(Config) -> escalus:story(Config, [1], fun(Alice) -> {value, IqSent} = get_counter_value(xmppIqSent), {value, IqReceived} = get_counter_value(xmppIqReceived), {value, StanzaSent} = get_counter_value(xmppStanzaSent), {value, StanzaReceived} = get_counter_value(xmppStanzaReceived), escalus_client:send(Alice, escalus_stanza:roster_get()), escalus_client:wait_for_stanza(Alice), assert_counter(IqSent + 1, xmppIqSent), assert_counter(StanzaSent + 1, xmppStanzaSent), assert_counter(StanzaReceived + 1, xmppStanzaReceived), assert_counter(IqReceived + 1, xmppIqReceived) end). messages(Config) -> {value, MesgSent} = get_counter_value(xmppMessageSent), {value, MesgReceived} = get_counter_value(xmppMessageReceived), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)), escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)), escalus_client:wait_for_stanza(Alice), assert_counter(MesgSent + 4, xmppMessageSent), assert_counter(MesgReceived + 4, xmppMessageReceived) end). bounced(Config) -> {value, MesgBounced} = get_counter_value(xmppMessageBounced), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:stop(Bob), timer:sleep(?WAIT_TIME), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), timer:sleep(?WAIT_TIME), assert_counter(MesgBounced + 1, xmppMessageBounced) end). stanza_count(Config) -> escalus:story(Config, [1, 1], fun(Alice, Bob) -> {value, OldStanzaCount} = get_counter_value(xmppStanzaCount), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)), escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)), escalus_client:wait_for_stanza(Alice), {value, StanzaCount} = get_counter_value(xmppStanzaCount), true = StanzaCount >= OldStanzaCount + 4 end). %%----------------------------------------------------- %% Error tests %%----------------------------------------------------- error_total(Config) -> {value, Errors} = get_counter_value(xmppErrorTotal), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:stop(Bob), timer:sleep(?WAIT_TIME), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), timer:sleep(?WAIT_TIME), assert_counter(Errors + 1, xmppErrorTotal) end). error_mesg(Config) -> {value, Errors} = get_counter_value(xmppErrorMessage), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:stop(Bob), timer:sleep(?WAIT_TIME), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), timer:sleep(?WAIT_TIME), assert_counter(Errors + 1, xmppErrorMessage) end). error_presence(Config) -> {value, Errors} = get_counter_value(xmppErrorPresence), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus:send(Alice, escalus_stanza:presence_direct(bob, <<"available">>)), escalus:wait_for_stanza(Bob), ErrorElt = escalus_stanza:error_element(<<"cancel">>, <<"gone">>), Presence = escalus_stanza:presence_direct(alice, <<"error">>, ErrorElt), escalus:send(Bob, Presence), escalus:wait_for_stanza(Alice), assert_counter(Errors + 1, xmppErrorPresence) end). error_iq(Config) -> {value, Errors} = get_counter_value(xmppErrorIq), Alice = escalus_users:get_user_by_name(alice), escalus_users:create_user(Config, Alice), timer:sleep(?WAIT_TIME), assert_counter(Errors + 1, xmppErrorIq).
null
https://raw.githubusercontent.com/esl/ejabberd_tests/913fb0a5a8c1ab753eb35c1e1b491e8572633b54/tests/metrics_c2s_SUITE.erl
erlang
============================================================================== you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================== -------------------------------------------------------------------- Suite configuration -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Message tests -------------------------------------------------------------------- ----------------------------------------------------- Error tests -----------------------------------------------------
Copyright 2013 Erlang Solutions Ltd. Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(metrics_c2s_SUITE). -compile(export_all). -include_lib("escalus/include/escalus.hrl"). -include_lib("common_test/include/ct.hrl"). -define(WAIT_TIME, 100). -import(metrics_helper, [assert_counter/2, get_counter_value/1]). all() -> [{group, single}, {group, multiple}, {group, drop}, {group, errors}, {group, count}]. groups() -> [{single, [sequence], [message_one, stanza_one, presence_one, presence_direct_one, iq_one]}, {multiple, [sequence], [messages]}, {drop, [sequence], [bounced ]}, {errors, [sequence], [error_total, error_mesg, error_iq, error_presence]}, {count, [sequence], [stanza_count]}]. suite() -> [{require, ejabberd_node} | escalus:suite()]. Init & teardown init_per_suite(Config) -> Config1 = dynamic_modules:stop_running(mod_offline, Config), escalus:init_per_suite(Config1). end_per_suite(Config) -> dynamic_modules:start_running(Config), escalus:end_per_suite(Config). init_per_group(_GroupName, Config) -> escalus:create_users(Config, {by_name, [alice, bob]}). end_per_group(_GroupName, Config) -> escalus:delete_users(Config, {by_name, [alice, bob]}). init_per_testcase(CaseName, Config) -> escalus:init_per_testcase(CaseName, Config). end_per_testcase(CaseName, Config) -> escalus:end_per_testcase(CaseName, Config). message_one(Config) -> {value, MesgSent} = get_counter_value(xmppMessageSent), {value, MesgReceived} = get_counter_value(xmppMessageReceived), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), assert_counter(MesgSent + 1, xmppMessageSent), assert_counter(MesgReceived + 1, xmppMessageReceived) end). stanza_one(Config) -> escalus:story(Config, [1, 1], fun(Alice, Bob) -> {value, StanzaSent} = get_counter_value(xmppStanzaSent), {value, StanzaReceived} = get_counter_value(xmppStanzaReceived), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), assert_counter(StanzaSent + 1, xmppStanzaSent), assert_counter(StanzaReceived + 1, xmppStanzaReceived) end). presence_one(Config) -> escalus:story(Config, [1], fun(Alice) -> {value, PresenceSent} = get_counter_value(xmppPresenceSent), {value, PresenceReceived} = get_counter_value(xmppPresenceReceived), {value, StanzaSent} = get_counter_value(xmppStanzaSent), {value, StanzaReceived} = get_counter_value(xmppStanzaReceived), escalus:send(Alice, escalus_stanza:presence(<<"available">>)), escalus:wait_for_stanza(Alice), assert_counter(PresenceSent + 1, xmppPresenceSent), assert_counter(PresenceReceived + 1, xmppPresenceReceived), assert_counter(StanzaSent + 1, xmppStanzaSent), assert_counter(StanzaReceived + 1, xmppStanzaReceived) end). presence_direct_one(Config) -> escalus:story(Config, [1, 1], fun(Alice, Bob) -> {value, PresenceSent} = get_counter_value(xmppPresenceSent), {value, PresenceReceived} = get_counter_value(xmppPresenceReceived), {value, StanzaSent} = get_counter_value(xmppStanzaSent), {value, StanzaReceived} = get_counter_value(xmppStanzaReceived), Presence = escalus_stanza:presence_direct(bob, <<"available">>), escalus:send(Alice, Presence), escalus:wait_for_stanza(Bob), assert_counter(PresenceSent + 1, xmppPresenceSent), assert_counter(PresenceReceived + 1, xmppPresenceReceived), assert_counter(StanzaSent + 1, xmppStanzaSent), assert_counter(StanzaReceived + 1, xmppStanzaReceived) end). iq_one(Config) -> escalus:story(Config, [1], fun(Alice) -> {value, IqSent} = get_counter_value(xmppIqSent), {value, IqReceived} = get_counter_value(xmppIqReceived), {value, StanzaSent} = get_counter_value(xmppStanzaSent), {value, StanzaReceived} = get_counter_value(xmppStanzaReceived), escalus_client:send(Alice, escalus_stanza:roster_get()), escalus_client:wait_for_stanza(Alice), assert_counter(IqSent + 1, xmppIqSent), assert_counter(StanzaSent + 1, xmppStanzaSent), assert_counter(StanzaReceived + 1, xmppStanzaReceived), assert_counter(IqReceived + 1, xmppIqReceived) end). messages(Config) -> {value, MesgSent} = get_counter_value(xmppMessageSent), {value, MesgReceived} = get_counter_value(xmppMessageReceived), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)), escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)), escalus_client:wait_for_stanza(Alice), assert_counter(MesgSent + 4, xmppMessageSent), assert_counter(MesgReceived + 4, xmppMessageReceived) end). bounced(Config) -> {value, MesgBounced} = get_counter_value(xmppMessageBounced), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:stop(Bob), timer:sleep(?WAIT_TIME), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), timer:sleep(?WAIT_TIME), assert_counter(MesgBounced + 1, xmppMessageBounced) end). stanza_count(Config) -> escalus:story(Config, [1, 1], fun(Alice, Bob) -> {value, OldStanzaCount} = get_counter_value(xmppStanzaCount), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)), escalus_client:wait_for_stanza(Alice), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), escalus_client:wait_for_stanza(Bob), escalus_client:send(Bob, escalus_stanza:chat_to(Alice, <<"Hi!">>)), escalus_client:wait_for_stanza(Alice), {value, StanzaCount} = get_counter_value(xmppStanzaCount), true = StanzaCount >= OldStanzaCount + 4 end). error_total(Config) -> {value, Errors} = get_counter_value(xmppErrorTotal), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:stop(Bob), timer:sleep(?WAIT_TIME), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), timer:sleep(?WAIT_TIME), assert_counter(Errors + 1, xmppErrorTotal) end). error_mesg(Config) -> {value, Errors} = get_counter_value(xmppErrorMessage), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus_client:stop(Bob), timer:sleep(?WAIT_TIME), escalus_client:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi!">>)), timer:sleep(?WAIT_TIME), assert_counter(Errors + 1, xmppErrorMessage) end). error_presence(Config) -> {value, Errors} = get_counter_value(xmppErrorPresence), escalus:story(Config, [1, 1], fun(Alice, Bob) -> escalus:send(Alice, escalus_stanza:presence_direct(bob, <<"available">>)), escalus:wait_for_stanza(Bob), ErrorElt = escalus_stanza:error_element(<<"cancel">>, <<"gone">>), Presence = escalus_stanza:presence_direct(alice, <<"error">>, ErrorElt), escalus:send(Bob, Presence), escalus:wait_for_stanza(Alice), assert_counter(Errors + 1, xmppErrorPresence) end). error_iq(Config) -> {value, Errors} = get_counter_value(xmppErrorIq), Alice = escalus_users:get_user_by_name(alice), escalus_users:create_user(Config, Alice), timer:sleep(?WAIT_TIME), assert_counter(Errors + 1, xmppErrorIq).
3daade38d597f109f51a2e7a01a68921384aac02d1e482829c984a7fbea6ef39
quil-lang/sbcl-librarian
package.lisp
(defpackage #:sbcl-librarian.tests.libsquare (:use #:cl #:sbcl-librarian))
null
https://raw.githubusercontent.com/quil-lang/sbcl-librarian/bfeb8c9725eb46dffbef18f333d70e8162f94ef9/tests/libs/libsquare/package.lisp
lisp
(defpackage #:sbcl-librarian.tests.libsquare (:use #:cl #:sbcl-librarian))
664cb05eaeb28ea3b048da71ffb9ead79ba7f971d12c5d1d38cfecc2775cfd35
jserot/caph
xdf.ml
(************************************************************************************) (* *) (* CAPH *) (* -bpclermont.fr *) (* *) (* *) (* *) Copyright 2011 - 2019 . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (************************************************************************************) XDF formatted output open Misc open Printf open Ssval open Static open Interm open Arrays type xdf_config = { mutable xml_version: string; mutable xml_encoding: string; mutable target_package: string; } let cfg = { xml_version = "1.0"; xml_encoding = "UTF-8"; target_package = ""; } type xdf_type = Integer of int | Boolean | Real (* to be extended *) let rec type_of t = let open Types in match real_type t with | Tconstr({tc_name="bool"}, _, _) -> Boolean | Tconstr({tc_name="float"}, _, _) -> Real | Tconstr({tc_name="int"}, [sg], [sz]) as ty -> begin match real_type sg, size_repr sz with | Tconstr({tc_name="_unsigned"},_,_), SzConst s -> Integer s | Tconstr({tc_name="_signed"},_,_), SzConst s -> Integer s | _, _ -> Misc.not_implemented ("XDF translation of type " ^ Pr_type.string_of_type ty) end | ty -> Misc.not_implemented ("XDF translation of type " ^ Pr_type.string_of_type t) let output_io_port oc dir name ty = let open Types in fprintf oc "<Port kind=\"%s\" name=\"%s\">\n" dir name; begin match type_of ty with | Integer s -> fprintf oc " <Type name=\"int\">\n"; fprintf oc " <Entry kind=\"Expr\" name=\"size\">\n"; fprintf oc " <Expr kind=\"Literal\" literal-kind=\"Integer\" value=\"%d\"/>\n" s; fprintf oc " </Entry>\n"; fprintf oc " </Type>\n"; | Boolean -> fprintf oc " <Type name=\"bool\">\n"; fprintf oc " </Type>\n" | Real -> fprintf oc " <Type name=\"real\">\n"; fprintf oc " </Type>\n" end; fprintf oc "</Port>\n" let output_port oc (i,b) = match b.ib_tag with InpB Syntax.StreamIO -> output_io_port oc "Input" b.ib_name b.ib_typ | OutB Syntax.StreamIO ->output_io_port oc "Output" b.ib_name b.ib_typ | _ -> () let string_of_type t = match type_of t with Integer s -> "Integer" | Boolean -> "Boolean" | Real -> "Real" let string_of_val v = match v with Expr.Val_int (i,_) -> string_of_int i | Expr.Val_bool b -> string_of_bool b | Expr.Val_float b -> string_of_float b | _ -> Misc.not_implemented ("XDF translation of value " ^ Expr.string_of_val v) let output_inst_param oc (name,(v,ty)) = fprintf oc " <Parameter name=\"%s\">\n" name; fprintf oc " <Expr kind=\"Literal\" literal-kind=\"%s\" value=\"%s\"/>\n" (string_of_type ty) (string_of_val v); fprintf oc " </Parameter>\n" let box_id i b = b.ib_name ^ "_act_" ^ string_of_int i let full_actor_name n = match cfg.target_package with "" -> n | p -> p ^ "." ^ n ^ "_act" let output_instance oc (i,b) = match b.ib_tag with | RegularB -> fprintf oc "<Instance id=\"%s\">\n" (box_id i b); fprintf oc " <Class name=\"%s\"/>\n" (full_actor_name b.ib_name); List.iter (output_inst_param oc) b.ib_params; fprintf oc "</Instance>\n" | _ -> () let read_annot_file fname = let ic = open_in fname in close_in ic let output_connexion oc anns boxes (wid,(((s,ss),(d,ds)),ty))= let lookup bid = try List.assoc bid boxes with Not_found -> Misc.fatal_error "Xdf.output_connexion" in let src_id, src_slot = let b = lookup s in match b.ib_tag with RegularB -> box_id s b, fst (List.nth b.ib_outs ss) | InpB Syntax.StreamIO -> "", b.ib_name | _ -> Misc.fatal_error "Xdf.output_connexion" in let dst_id, dst_slot = let b = lookup d in match b.ib_tag with RegularB -> box_id d b, fst (List.nth b.ib_ins ds) | OutB Syntax.StreamIO -> "", b.ib_name | _ -> Misc.fatal_error "Xdf.output_connexion" in fprintf oc "<Connection dst=\"%s\" dst-port=\"%s\" src=\"%s\" src-port=\"%s\">\n" dst_id dst_slot src_id src_slot; begin try match List.assoc ("w" ^ string_of_int wid) anns with | "fifo_size", sz -> fprintf oc " <Attribute kind=\"Value\" name=\"bufferSize\">\n"; fprintf oc " <Expr kind=\"Literal\" literal-kind=\"Integer\" value=\"%d\"/>\n" sz; fprintf oc " </Attribute>\n" | _, _ -> () with Not_found -> () end; fprintf oc "</Connection>\n" let output oc name ir = let anns = let fname = Systemc.cfg.Systemc.sc_fifo_stats_file in if Sys.file_exists fname then begin Printf.printf "Reading annotation file %s\n" fname; Vhdl_annot.parse fname end else [] in fprintf oc "<?xml version=\"%s\" encoding=\"%s\"?>\n" cfg.xml_version cfg.xml_encoding; fprintf oc "<XDF name=\"%s\">\n" name; List.iter (output_port oc) ir.ir_boxes; List.iter (output_instance oc) ir.ir_boxes; List.iter (output_connexion oc anns ir.ir_boxes) ir.ir_wires; fprintf oc "</XDF>\n" let output_ir name ir = let fname = Misc.prefix_dir Genmake.target.Genmake.dir name ^ ".xdf" in let oc = open_out fname in output oc name ir; Logfile.write fname; close_out oc
null
https://raw.githubusercontent.com/jserot/caph/2b3b241f0c32aa4fcaf60d4b8529956cca8aa6b1/compiler/xdf.ml
ocaml
********************************************************************************** CAPH -bpclermont.fr ********************************************************************************** to be extended
Copyright 2011 - 2019 . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . XDF formatted output open Misc open Printf open Ssval open Static open Interm open Arrays type xdf_config = { mutable xml_version: string; mutable xml_encoding: string; mutable target_package: string; } let cfg = { xml_version = "1.0"; xml_encoding = "UTF-8"; target_package = ""; } type xdf_type = Integer of int | Boolean | Real let rec type_of t = let open Types in match real_type t with | Tconstr({tc_name="bool"}, _, _) -> Boolean | Tconstr({tc_name="float"}, _, _) -> Real | Tconstr({tc_name="int"}, [sg], [sz]) as ty -> begin match real_type sg, size_repr sz with | Tconstr({tc_name="_unsigned"},_,_), SzConst s -> Integer s | Tconstr({tc_name="_signed"},_,_), SzConst s -> Integer s | _, _ -> Misc.not_implemented ("XDF translation of type " ^ Pr_type.string_of_type ty) end | ty -> Misc.not_implemented ("XDF translation of type " ^ Pr_type.string_of_type t) let output_io_port oc dir name ty = let open Types in fprintf oc "<Port kind=\"%s\" name=\"%s\">\n" dir name; begin match type_of ty with | Integer s -> fprintf oc " <Type name=\"int\">\n"; fprintf oc " <Entry kind=\"Expr\" name=\"size\">\n"; fprintf oc " <Expr kind=\"Literal\" literal-kind=\"Integer\" value=\"%d\"/>\n" s; fprintf oc " </Entry>\n"; fprintf oc " </Type>\n"; | Boolean -> fprintf oc " <Type name=\"bool\">\n"; fprintf oc " </Type>\n" | Real -> fprintf oc " <Type name=\"real\">\n"; fprintf oc " </Type>\n" end; fprintf oc "</Port>\n" let output_port oc (i,b) = match b.ib_tag with InpB Syntax.StreamIO -> output_io_port oc "Input" b.ib_name b.ib_typ | OutB Syntax.StreamIO ->output_io_port oc "Output" b.ib_name b.ib_typ | _ -> () let string_of_type t = match type_of t with Integer s -> "Integer" | Boolean -> "Boolean" | Real -> "Real" let string_of_val v = match v with Expr.Val_int (i,_) -> string_of_int i | Expr.Val_bool b -> string_of_bool b | Expr.Val_float b -> string_of_float b | _ -> Misc.not_implemented ("XDF translation of value " ^ Expr.string_of_val v) let output_inst_param oc (name,(v,ty)) = fprintf oc " <Parameter name=\"%s\">\n" name; fprintf oc " <Expr kind=\"Literal\" literal-kind=\"%s\" value=\"%s\"/>\n" (string_of_type ty) (string_of_val v); fprintf oc " </Parameter>\n" let box_id i b = b.ib_name ^ "_act_" ^ string_of_int i let full_actor_name n = match cfg.target_package with "" -> n | p -> p ^ "." ^ n ^ "_act" let output_instance oc (i,b) = match b.ib_tag with | RegularB -> fprintf oc "<Instance id=\"%s\">\n" (box_id i b); fprintf oc " <Class name=\"%s\"/>\n" (full_actor_name b.ib_name); List.iter (output_inst_param oc) b.ib_params; fprintf oc "</Instance>\n" | _ -> () let read_annot_file fname = let ic = open_in fname in close_in ic let output_connexion oc anns boxes (wid,(((s,ss),(d,ds)),ty))= let lookup bid = try List.assoc bid boxes with Not_found -> Misc.fatal_error "Xdf.output_connexion" in let src_id, src_slot = let b = lookup s in match b.ib_tag with RegularB -> box_id s b, fst (List.nth b.ib_outs ss) | InpB Syntax.StreamIO -> "", b.ib_name | _ -> Misc.fatal_error "Xdf.output_connexion" in let dst_id, dst_slot = let b = lookup d in match b.ib_tag with RegularB -> box_id d b, fst (List.nth b.ib_ins ds) | OutB Syntax.StreamIO -> "", b.ib_name | _ -> Misc.fatal_error "Xdf.output_connexion" in fprintf oc "<Connection dst=\"%s\" dst-port=\"%s\" src=\"%s\" src-port=\"%s\">\n" dst_id dst_slot src_id src_slot; begin try match List.assoc ("w" ^ string_of_int wid) anns with | "fifo_size", sz -> fprintf oc " <Attribute kind=\"Value\" name=\"bufferSize\">\n"; fprintf oc " <Expr kind=\"Literal\" literal-kind=\"Integer\" value=\"%d\"/>\n" sz; fprintf oc " </Attribute>\n" | _, _ -> () with Not_found -> () end; fprintf oc "</Connection>\n" let output oc name ir = let anns = let fname = Systemc.cfg.Systemc.sc_fifo_stats_file in if Sys.file_exists fname then begin Printf.printf "Reading annotation file %s\n" fname; Vhdl_annot.parse fname end else [] in fprintf oc "<?xml version=\"%s\" encoding=\"%s\"?>\n" cfg.xml_version cfg.xml_encoding; fprintf oc "<XDF name=\"%s\">\n" name; List.iter (output_port oc) ir.ir_boxes; List.iter (output_instance oc) ir.ir_boxes; List.iter (output_connexion oc anns ir.ir_boxes) ir.ir_wires; fprintf oc "</XDF>\n" let output_ir name ir = let fname = Misc.prefix_dir Genmake.target.Genmake.dir name ^ ".xdf" in let oc = open_out fname in output oc name ir; Logfile.write fname; close_out oc
9a40a1157b529861ee2b8d43b3eefbbd44f0969d47b005b2d8b536786a2d9981
programaker-project/Programaker-Core
automate_bot_engine_thread_stopping_tests.erl
%%% @doc Automate bot engine tests . %%% @end -module(automate_bot_engine_thread_stopping_tests). -include_lib("eunit/include/eunit.hrl"). %% Data structures -include("../../automate_storage/src/records.hrl"). -include("../src/program_records.hrl"). -include("../src/instructions.hrl"). -include("../../automate_channel_engine/src/records.hrl"). %% Test data -include("just_wait_program.hrl"). -define(APPLICATION, automate_bot_engine). -define(UTILS, automate_bot_engine_test_utils). %%==================================================================== %% Test API %%==================================================================== session_manager_test_() -> {setup , fun setup/0 , fun stop/1 , fun tests/1 }. %% @doc App infrastructure setup. %% @end setup() -> NodeName = node(), %% Use a custom node name to avoid overwriting the actual databases net_kernel:start([testing, shortnames]), {ok, _Pid} = application:ensure_all_started(?APPLICATION), {NodeName}. %% @doc App infrastructure teardown. %% @end stop({_NodeName}) -> %% application:stop(?APPLICATION), ok. tests(_SetupResult) -> [ { "[Bot runner - Stop threads] Start a thread and stop it, the program must continue running" , fun start_thread_and_stop_threads_continues/0 } , { "[Bot runner - Stop threads] Create a program and stop it's threads (none). Nothing happens" , fun start_program_and_stop_threads_nothing/0 } ]. %%%% Bot runner start_thread_and_stop_threads_continues() -> %% Sequence %% %% Test (this) *---+--------------+.............+-----+---------+...........+---------+----------------+ %% ↓ ↓ ↑ ↓ ↓ ↑ ↓ ↓ %% Creates Sends trigger Confirms ↓ Stop threads Confirms Check alive Check alive %% ↓ ↓ ↑ ↓ ↓ ↑ ↓ ↓ %% Program *..............+-+-----------+....( )........+-+---------+.........YES.............( )... %% ↓ ↓ ↓ ↓ %% Creates Check alive Stop Check alive %% ↓ ↓ ↓ ↓ %% Thread *-- wait ........YES..........X NO Program creation {Username, ProgramName, ProgramId} = ?UTILS:create_anonymous_program(), {ok, ChannelId} = automate_channel_engine:create_channel(), %% Launch program ?assertMatch({ok, ProgramId}, automate_storage:update_program( Username, ProgramName, #stored_program_content{ type=?JUST_WAIT_PROGRAM_TYPE , parsed=#{ <<"blocks">> => [[ ?UTILS:monitor_program_trigger(ChannelId) | ?JUST_WAIT_PROGRAM_INSTRUCTIONS ]] , <<"variables">> => ?JUST_WAIT_PROGRAM_VARIABLES } , orig=?JUST_WAIT_PROGRAM_ORIG , pages=#{} })), ?assertMatch(ok, automate_bot_engine_launcher:update_program(ProgramId)), %% Check that program id alive ?assertMatch(ok, ?UTILS:wait_for_program_alive(ProgramId, 10, 100)), {ok, ProgramPid} = automate_storage:get_program_pid(ProgramId), ?assert(is_process_alive(ProgramPid)), %% Trigger sent, thread is spawned ProgramPid ! {channel_engine, ChannelId, #{ ?CHANNEL_MESSAGE_CONTENT => start }}, ok = ?UTILS:wait_for_check_ok( fun() -> case automate_storage:get_threads_from_program(ProgramId) of {ok, [ThreadId]} -> case automate_storage:get_thread_from_id(ThreadId) of {ok, #running_program_thread_entry{runner_pid=undefined}} -> false; {ok, _} -> true end; _ -> false end end, 10, 100), %% Check that thread is alive {ok, [ThreadId]} = automate_storage:get_threads_from_program(ProgramId), {ok, #running_program_thread_entry{runner_pid=ThreadRunnerId}} = automate_storage:get_thread_from_id(ThreadId), ?assert(is_process_alive(ThreadRunnerId)), %% Stop threads ok = automate_bot_engine:stop_program_threads(ProgramId), %% Check that program is alive {ok, ProgramPid2} = automate_storage:get_program_pid(ProgramId), ?assert(is_process_alive(ProgramPid2)), %% Check that thread is dead ?UTILS:wait_for_check_ok( fun() -> case automate_storage:get_threads_from_program(ProgramId) of {ok, []} -> true; _ -> false end end, 10, 100), {ok, FinishedTreads} = automate_storage:get_threads_from_program(ProgramId), ?assert(length(FinishedTreads) == 0), ok. start_program_and_stop_threads_nothing() -> %% Sequence %% %% Test (this) *---+-----------+...........+---------+--→ OK %% ↓ ↓ ↑ ↓ %% Creates Stop threads Confirms Check alive %% ↓ ↓ ↑ ↓ %% Program *...........+-----------+.........YES {Username, ProgramName, ProgramId} = ?UTILS:create_anonymous_program(), {ok, ChannelId} = automate_channel_engine:create_channel(), Program creation TriggerMonitorSignal = { ?TRIGGERED_BY_MONITOR , { ChannelId, #{ ?CHANNEL_MESSAGE_CONTENT => start }}}, %% Launch program ?assertMatch({ok, ProgramId}, automate_storage:update_program( Username, ProgramName, #stored_program_content{ type=?JUST_WAIT_PROGRAM_TYPE , parsed=#{ <<"blocks">> => [[ ?UTILS:monitor_program_trigger(ChannelId) | ?JUST_WAIT_PROGRAM_INSTRUCTIONS ]] , <<"variables">> => ?JUST_WAIT_PROGRAM_VARIABLES } , orig=?JUST_WAIT_PROGRAM_ORIG , pages=#{} })), ?assertMatch(ok, automate_bot_engine_launcher:update_program(ProgramId)), %% Check that program id alive ?assertMatch(ok, ?UTILS:wait_for_program_alive(ProgramId, 10, 100)), {ok, ProgramPid} = automate_storage:get_program_pid(ProgramId), ?assert(is_process_alive(ProgramPid)), %% Stop threads ok = automate_bot_engine:stop_program_threads(ProgramId), %% Check that program is alive {ok, ProgramPid2} = automate_storage:get_program_pid(ProgramId), ?assert(is_process_alive(ProgramPid2)), ok.
null
https://raw.githubusercontent.com/programaker-project/Programaker-Core/ef10fc6d2a228b2096b121170c421f5c29f9f270/backend/apps/automate_bot_engine/test/automate_bot_engine_thread_stopping_tests.erl
erlang
@doc @end Data structures Test data ==================================================================== Test API ==================================================================== @doc App infrastructure setup. @end Use a custom node name to avoid overwriting the actual databases @doc App infrastructure teardown. @end application:stop(?APPLICATION), Bot runner Sequence Test (this) *---+--------------+.............+-----+---------+...........+---------+----------------+ ↓ ↓ ↑ ↓ ↓ ↑ ↓ ↓ Creates Sends trigger Confirms ↓ Stop threads Confirms Check alive Check alive ↓ ↓ ↑ ↓ ↓ ↑ ↓ ↓ Program *..............+-+-----------+....( )........+-+---------+.........YES.............( )... ↓ ↓ ↓ ↓ Creates Check alive Stop Check alive ↓ ↓ ↓ ↓ Thread *-- wait ........YES..........X NO Launch program Check that program id alive Trigger sent, thread is spawned Check that thread is alive Stop threads Check that program is alive Check that thread is dead Sequence Test (this) *---+-----------+...........+---------+--→ OK ↓ ↓ ↑ ↓ Creates Stop threads Confirms Check alive ↓ ↓ ↑ ↓ Program *...........+-----------+.........YES Launch program Check that program id alive Stop threads Check that program is alive
Automate bot engine tests . -module(automate_bot_engine_thread_stopping_tests). -include_lib("eunit/include/eunit.hrl"). -include("../../automate_storage/src/records.hrl"). -include("../src/program_records.hrl"). -include("../src/instructions.hrl"). -include("../../automate_channel_engine/src/records.hrl"). -include("just_wait_program.hrl"). -define(APPLICATION, automate_bot_engine). -define(UTILS, automate_bot_engine_test_utils). session_manager_test_() -> {setup , fun setup/0 , fun stop/1 , fun tests/1 }. setup() -> NodeName = node(), net_kernel:start([testing, shortnames]), {ok, _Pid} = application:ensure_all_started(?APPLICATION), {NodeName}. stop({_NodeName}) -> ok. tests(_SetupResult) -> [ { "[Bot runner - Stop threads] Start a thread and stop it, the program must continue running" , fun start_thread_and_stop_threads_continues/0 } , { "[Bot runner - Stop threads] Create a program and stop it's threads (none). Nothing happens" , fun start_program_and_stop_threads_nothing/0 } ]. start_thread_and_stop_threads_continues() -> Program creation {Username, ProgramName, ProgramId} = ?UTILS:create_anonymous_program(), {ok, ChannelId} = automate_channel_engine:create_channel(), ?assertMatch({ok, ProgramId}, automate_storage:update_program( Username, ProgramName, #stored_program_content{ type=?JUST_WAIT_PROGRAM_TYPE , parsed=#{ <<"blocks">> => [[ ?UTILS:monitor_program_trigger(ChannelId) | ?JUST_WAIT_PROGRAM_INSTRUCTIONS ]] , <<"variables">> => ?JUST_WAIT_PROGRAM_VARIABLES } , orig=?JUST_WAIT_PROGRAM_ORIG , pages=#{} })), ?assertMatch(ok, automate_bot_engine_launcher:update_program(ProgramId)), ?assertMatch(ok, ?UTILS:wait_for_program_alive(ProgramId, 10, 100)), {ok, ProgramPid} = automate_storage:get_program_pid(ProgramId), ?assert(is_process_alive(ProgramPid)), ProgramPid ! {channel_engine, ChannelId, #{ ?CHANNEL_MESSAGE_CONTENT => start }}, ok = ?UTILS:wait_for_check_ok( fun() -> case automate_storage:get_threads_from_program(ProgramId) of {ok, [ThreadId]} -> case automate_storage:get_thread_from_id(ThreadId) of {ok, #running_program_thread_entry{runner_pid=undefined}} -> false; {ok, _} -> true end; _ -> false end end, 10, 100), {ok, [ThreadId]} = automate_storage:get_threads_from_program(ProgramId), {ok, #running_program_thread_entry{runner_pid=ThreadRunnerId}} = automate_storage:get_thread_from_id(ThreadId), ?assert(is_process_alive(ThreadRunnerId)), ok = automate_bot_engine:stop_program_threads(ProgramId), {ok, ProgramPid2} = automate_storage:get_program_pid(ProgramId), ?assert(is_process_alive(ProgramPid2)), ?UTILS:wait_for_check_ok( fun() -> case automate_storage:get_threads_from_program(ProgramId) of {ok, []} -> true; _ -> false end end, 10, 100), {ok, FinishedTreads} = automate_storage:get_threads_from_program(ProgramId), ?assert(length(FinishedTreads) == 0), ok. start_program_and_stop_threads_nothing() -> {Username, ProgramName, ProgramId} = ?UTILS:create_anonymous_program(), {ok, ChannelId} = automate_channel_engine:create_channel(), Program creation TriggerMonitorSignal = { ?TRIGGERED_BY_MONITOR , { ChannelId, #{ ?CHANNEL_MESSAGE_CONTENT => start }}}, ?assertMatch({ok, ProgramId}, automate_storage:update_program( Username, ProgramName, #stored_program_content{ type=?JUST_WAIT_PROGRAM_TYPE , parsed=#{ <<"blocks">> => [[ ?UTILS:monitor_program_trigger(ChannelId) | ?JUST_WAIT_PROGRAM_INSTRUCTIONS ]] , <<"variables">> => ?JUST_WAIT_PROGRAM_VARIABLES } , orig=?JUST_WAIT_PROGRAM_ORIG , pages=#{} })), ?assertMatch(ok, automate_bot_engine_launcher:update_program(ProgramId)), ?assertMatch(ok, ?UTILS:wait_for_program_alive(ProgramId, 10, 100)), {ok, ProgramPid} = automate_storage:get_program_pid(ProgramId), ?assert(is_process_alive(ProgramPid)), ok = automate_bot_engine:stop_program_threads(ProgramId), {ok, ProgramPid2} = automate_storage:get_program_pid(ProgramId), ?assert(is_process_alive(ProgramPid2)), ok.
c7ecf62daa692dbd0f4a95a62facd6db95af5340f6a7d926c1d257215cb48dcb
mzp/bs-lwt
lwt_pool.ml
Lwt * * Copyright ( C ) 2008 * 2012 * Laboratoire PPS - CNRS Université Paris Diderot * * 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 , with linking exceptions ; * either version 2.1 of the License , or ( at your option ) any later version . * See COPYING file for details . * * 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 . * * Copyright (C) 2008 Jérôme Vouillon * 2012 Jérémie Dimino * Laboratoire PPS - CNRS Université Paris Diderot * * 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, with linking exceptions; * either version 2.1 of the License, or (at your option) any later version. * See COPYING file for details. * * 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. *) open Lwt.Infix (* XXX Close after some timeout ... *) type 'a t = { create : unit -> 'a Lwt.t; (* Create a new pool member. *) check : 'a -> (bool -> unit) -> unit; (* Check a member when its use failed. *) validate : 'a -> bool Lwt.t; Validate old pool members . max : int; (* Size of the pool. *) mutable count : int; Number of elements in hte pool . list : 'a Queue.t; (* Available pool members. *) waiters : 'a Lwt.u Lwt_sequence.t; (* Threads waiting for a member. *) } let create m ?(check = fun _ f -> f true) ?(validate = fun _ -> Lwt.return_true) create = { max = m; create = create; validate = validate; check = check; count = 0; list = Queue.create (); waiters = Lwt_sequence.create () } let create_member p = Lwt.catch (fun () -> (* Must be done before p.create to prevent other threads from creating new members if the limit is reached. *) p.count <- p.count + 1; p.create ()) (fun exn -> (* Creation failed, so don't increment count. *) p.count <- p.count - 1; Lwt.fail exn) (* Release a pool member. *) let release p c = match Lwt_sequence.take_opt_l p.waiters with | Some wakener -> (* A thread is waiting, give it the pool member. *) Lwt.wakeup_later wakener c | None -> (* No one is waiting, queue it. *) Queue.push c p.list (* Create a new member when one is thrown away. *) let replace_acquired p = match Lwt_sequence.take_opt_l p.waiters with | None -> (* No one is waiting, do not create a new member to avoid loosing an error if creation fails. *) p.count <- p.count - 1 | Some wakener -> Lwt.on_any (Lwt.apply p.create ()) (fun c -> Lwt.wakeup_later wakener c) (fun exn -> (* Creation failed, notify the waiter of the failure. *) p.count <- p.count - 1; Lwt.wakeup_later_exn wakener exn) let acquire p = if Queue.is_empty p.list then (* No more available member. *) if p.count < p.max then (* Limit not reached: create a new one. *) create_member p else (* Limit reached: wait for a free one. *) Lwt.add_task_r p.waiters else Take the first free member and validate it . let c = Queue.take p.list in Lwt.try_bind (fun () -> p.validate c) (function | true -> Lwt.return c | false -> (* Remove this member and create a new one. *) p.count <- p.count - 1; create_member p) (fun e -> Validation failed : create a new member if at least one thread is waiting . thread is waiting. *) replace_acquired p; Lwt.fail e) (* Release a member when its use failed. *) let checked_release p c = p.check c begin fun ok -> if ok then release p c else replace_acquired p end let use p f = acquire p >>= fun c -> Lwt.catch (fun () -> let t = f c in t >>= fun _ -> release p c; t) (fun e -> checked_release p c; Lwt.fail e)
null
https://raw.githubusercontent.com/mzp/bs-lwt/f37a3c47d038f4efcd65912c41fab95d1e6633ce/lwt/src/core/lwt_pool.ml
ocaml
XXX Close after some timeout ... Create a new pool member. Check a member when its use failed. Size of the pool. Available pool members. Threads waiting for a member. Must be done before p.create to prevent other threads from creating new members if the limit is reached. Creation failed, so don't increment count. Release a pool member. A thread is waiting, give it the pool member. No one is waiting, queue it. Create a new member when one is thrown away. No one is waiting, do not create a new member to avoid loosing an error if creation fails. Creation failed, notify the waiter of the failure. No more available member. Limit not reached: create a new one. Limit reached: wait for a free one. Remove this member and create a new one. Release a member when its use failed.
Lwt * * Copyright ( C ) 2008 * 2012 * Laboratoire PPS - CNRS Université Paris Diderot * * 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 , with linking exceptions ; * either version 2.1 of the License , or ( at your option ) any later version . * See COPYING file for details . * * 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 . * * Copyright (C) 2008 Jérôme Vouillon * 2012 Jérémie Dimino * Laboratoire PPS - CNRS Université Paris Diderot * * 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, with linking exceptions; * either version 2.1 of the License, or (at your option) any later version. * See COPYING file for details. * * 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. *) open Lwt.Infix type 'a t = { create : unit -> 'a Lwt.t; check : 'a -> (bool -> unit) -> unit; validate : 'a -> bool Lwt.t; Validate old pool members . max : int; mutable count : int; Number of elements in hte pool . list : 'a Queue.t; waiters : 'a Lwt.u Lwt_sequence.t; } let create m ?(check = fun _ f -> f true) ?(validate = fun _ -> Lwt.return_true) create = { max = m; create = create; validate = validate; check = check; count = 0; list = Queue.create (); waiters = Lwt_sequence.create () } let create_member p = Lwt.catch (fun () -> p.count <- p.count + 1; p.create ()) (fun exn -> p.count <- p.count - 1; Lwt.fail exn) let release p c = match Lwt_sequence.take_opt_l p.waiters with | Some wakener -> Lwt.wakeup_later wakener c | None -> Queue.push c p.list let replace_acquired p = match Lwt_sequence.take_opt_l p.waiters with | None -> p.count <- p.count - 1 | Some wakener -> Lwt.on_any (Lwt.apply p.create ()) (fun c -> Lwt.wakeup_later wakener c) (fun exn -> p.count <- p.count - 1; Lwt.wakeup_later_exn wakener exn) let acquire p = if Queue.is_empty p.list then if p.count < p.max then create_member p else Lwt.add_task_r p.waiters else Take the first free member and validate it . let c = Queue.take p.list in Lwt.try_bind (fun () -> p.validate c) (function | true -> Lwt.return c | false -> p.count <- p.count - 1; create_member p) (fun e -> Validation failed : create a new member if at least one thread is waiting . thread is waiting. *) replace_acquired p; Lwt.fail e) let checked_release p c = p.check c begin fun ok -> if ok then release p c else replace_acquired p end let use p f = acquire p >>= fun c -> Lwt.catch (fun () -> let t = f c in t >>= fun _ -> release p c; t) (fun e -> checked_release p c; Lwt.fail e)
7ff027041bc5d65a2b55fd936fe17ca0e968a8869d02c562381bf179187f625c
futurice/haskell-mega-repo
Attribute.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} module Personio.Internal.Attribute where import Data.Aeson.Compat import Data.Aeson.Internal (JSONPathElement (Key), (<?>)) import Futurice.Aeson import Futurice.Generics import Futurice.Prelude import Prelude () import qualified Data.HashMap.Strict as HM import qualified Data.Swagger as Swagger import qualified Data.Text as T -- | Personio attribute, i.e. labeled value. data Attribute = Attribute !Text !Value deriving (Eq, Show, Generic) instance ToJSON Attribute where toJSON (Attribute l v) = object [ "label" .= l, "value" .= v ] instance FromJSON Attribute where parseJSON = withObjectDump "Attribute" $ \obj -> Attribute <$> obj .: "label" <*> obj .: "value" instance ToSchema Attribute where declareNamedSchema _ = pure $ Swagger.NamedSchema (Just "Attribute") mempty instance NFData Attribute instance Hashable Attribute instance Arbitrary Attribute where arbitrary = pure (Attribute "arbitrary" "value") ------------------------------------------------------------------------------- -- Parsing ------------------------------------------------------------------------------- data Attributes = Attributes { attrCore :: HashMap Text Value , attrDynamic :: HashMap Text Value } deriving Show instance FromJSON Attributes where parseJSON j = mkAttributes <$> parseJSON j mkAttributes :: HashMap Text Attribute -> Attributes mkAttributes m = Attributes (mapHM toCore m) (mapHM toDynamic m) where toCore k (Attribute _ v) | "dynamic_" `T.isPrefixOf` k = Nothing | otherwise = Just (k, v) toDynamic k (Attribute l v) | "dynamic_" `T.isPrefixOf` k = Just (l, v) | otherwise = Nothing mapHM :: (Eq k2, Hashable k2) => (k1 -> v1 -> Maybe (k2, v2)) -> HashMap k1 v1 -> HashMap k2 v2 mapHM f = HM.fromList . mapMaybe (uncurry f) . HM.toList parseAttribute :: FromJSON a => Attributes -> Text -> Parser a parseAttribute (Attributes obj _) attrName = case HM.lookup attrName obj of Nothing -> fail $ "core attribute " ++ show attrName ++ " not present" Just v -> parseJSON v <?> Key attrName parseDynamicAttribute :: FromJSON a => Attributes -> Text -> Parser a parseDynamicAttribute (Attributes _ obj) attrName = case HM.lookup attrName obj of Nothing -> fail $ "dynamic attribute " ++ show attrName ++ " not present" Just v -> parseJSON v <?> Key attrName
null
https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/personio-client/src/Personio/Internal/Attribute.hs
haskell
# LANGUAGE OverloadedStrings # | Personio attribute, i.e. labeled value. ----------------------------------------------------------------------------- Parsing -----------------------------------------------------------------------------
# LANGUAGE DeriveGeneric # module Personio.Internal.Attribute where import Data.Aeson.Compat import Data.Aeson.Internal (JSONPathElement (Key), (<?>)) import Futurice.Aeson import Futurice.Generics import Futurice.Prelude import Prelude () import qualified Data.HashMap.Strict as HM import qualified Data.Swagger as Swagger import qualified Data.Text as T data Attribute = Attribute !Text !Value deriving (Eq, Show, Generic) instance ToJSON Attribute where toJSON (Attribute l v) = object [ "label" .= l, "value" .= v ] instance FromJSON Attribute where parseJSON = withObjectDump "Attribute" $ \obj -> Attribute <$> obj .: "label" <*> obj .: "value" instance ToSchema Attribute where declareNamedSchema _ = pure $ Swagger.NamedSchema (Just "Attribute") mempty instance NFData Attribute instance Hashable Attribute instance Arbitrary Attribute where arbitrary = pure (Attribute "arbitrary" "value") data Attributes = Attributes { attrCore :: HashMap Text Value , attrDynamic :: HashMap Text Value } deriving Show instance FromJSON Attributes where parseJSON j = mkAttributes <$> parseJSON j mkAttributes :: HashMap Text Attribute -> Attributes mkAttributes m = Attributes (mapHM toCore m) (mapHM toDynamic m) where toCore k (Attribute _ v) | "dynamic_" `T.isPrefixOf` k = Nothing | otherwise = Just (k, v) toDynamic k (Attribute l v) | "dynamic_" `T.isPrefixOf` k = Just (l, v) | otherwise = Nothing mapHM :: (Eq k2, Hashable k2) => (k1 -> v1 -> Maybe (k2, v2)) -> HashMap k1 v1 -> HashMap k2 v2 mapHM f = HM.fromList . mapMaybe (uncurry f) . HM.toList parseAttribute :: FromJSON a => Attributes -> Text -> Parser a parseAttribute (Attributes obj _) attrName = case HM.lookup attrName obj of Nothing -> fail $ "core attribute " ++ show attrName ++ " not present" Just v -> parseJSON v <?> Key attrName parseDynamicAttribute :: FromJSON a => Attributes -> Text -> Parser a parseDynamicAttribute (Attributes _ obj) attrName = case HM.lookup attrName obj of Nothing -> fail $ "dynamic attribute " ++ show attrName ++ " not present" Just v -> parseJSON v <?> Key attrName
c8c1dbd222b2786a68ea300700ea9ba911c183a572244b5dbd381108698d5f16
cac-t-u-s/om-sharp
init-do.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ File author : ;============================================================================ (in-package :om) ;;;==================== INIT - DO ;;;==================== ;;; A general box that evaluates prior to the execution of the patch ;;; Much of its behaviour is similar to the "OUT" boxes, except that ;;; it is not returning anything out ;;; it is also useful to use along with iterator to do something before to start a loop (defclass OMPatchInit (OMPatchComponent) () (:documentation "A box that evaluates prior to the execution of the patch. Can be used along with iterators to do something before to start a loop.")) (defclass OMPatchInitBox (OMPatchComponentBox) ()) (defmethod special-box-p ((name (eql 'init-do))) t) (defmethod get-box-class ((self OMPatchInit)) 'OMPatchInitBox) (defmethod box-symbol ((self OMPatchInit)) 'init-do) (defmethod special-item-reference-class ((item (eql 'init-do))) 'OMPatchInit) (defmethod get-icon-id ((self OMPatchInitBox)) :s-play) (defmethod object-name-in-inspector ((self OMPatchInitBox)) "INIT CALL box") (defmethod omNG-make-special-box ((reference (eql 'init-do)) pos &optional init-args) (let ((name (car (list! init-args)))) (omNG-make-new-boxcall (make-instance 'OMPatchInit :name (if name (string name) "init-do")) pos init-args))) (defmethod create-box-inputs ((self OMPatchInitBox)) (list (make-instance 'box-input :box self :value NIL :name "action"))) (defmethod get-input-doc ((self OMPatchInitBox) name) "to do before to evaluate patch outputs") (defmethod next-optional-input ((self OMPatchInitBox)) t) (defmethod more-optional-input ((self OMPatchInitBox) &key name (value nil val-supplied-p) doc reactive) (declare (ignore name doc)) (add-optional-input self :name "action to do before to evaluate patch outputs" :value (if val-supplied-p value nil) :reactive reactive) t)
null
https://raw.githubusercontent.com/cac-t-u-s/om-sharp/e99c153a554c22ff1d4951e2f44a736602866690/src/visual-language/boxes/init-do.lisp
lisp
============================================================================ om#: visual programming language for computer-assisted music composition ============================================================================ This program is free software. For information on usage and redistribution, see the "LICENSE" file in this distribution. 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. ============================================================================ ============================================================================ ==================== ==================== A general box that evaluates prior to the execution of the patch Much of its behaviour is similar to the "OUT" boxes, except that it is not returning anything out it is also useful to use along with iterator to do something before to start a loop
File author : (in-package :om) INIT - DO (defclass OMPatchInit (OMPatchComponent) () (:documentation "A box that evaluates prior to the execution of the patch. Can be used along with iterators to do something before to start a loop.")) (defclass OMPatchInitBox (OMPatchComponentBox) ()) (defmethod special-box-p ((name (eql 'init-do))) t) (defmethod get-box-class ((self OMPatchInit)) 'OMPatchInitBox) (defmethod box-symbol ((self OMPatchInit)) 'init-do) (defmethod special-item-reference-class ((item (eql 'init-do))) 'OMPatchInit) (defmethod get-icon-id ((self OMPatchInitBox)) :s-play) (defmethod object-name-in-inspector ((self OMPatchInitBox)) "INIT CALL box") (defmethod omNG-make-special-box ((reference (eql 'init-do)) pos &optional init-args) (let ((name (car (list! init-args)))) (omNG-make-new-boxcall (make-instance 'OMPatchInit :name (if name (string name) "init-do")) pos init-args))) (defmethod create-box-inputs ((self OMPatchInitBox)) (list (make-instance 'box-input :box self :value NIL :name "action"))) (defmethod get-input-doc ((self OMPatchInitBox) name) "to do before to evaluate patch outputs") (defmethod next-optional-input ((self OMPatchInitBox)) t) (defmethod more-optional-input ((self OMPatchInitBox) &key name (value nil val-supplied-p) doc reactive) (declare (ignore name doc)) (add-optional-input self :name "action to do before to evaluate patch outputs" :value (if val-supplied-p value nil) :reactive reactive) t)
d13953c8d7cdc01c902d0267c6bc11342d920580d9a49b0c1842a6e8e964e34c
clojerl/clojerl
clj_module.erl
@doc Clojerl compilation module . %% %% Keeps the Core Erlang representation for the modules being %% compiled. %% %% It is mainly used by {@link clj_emitter} to register new %% modules and then add or update function as each form in the %% compiler is processed. -module(clj_module). -behavior(gen_server). -compile({no_auto_import, [get/1, delete_module/1]}). -include("clojerl.hrl"). -include("clojerl_int.hrl"). -include_lib("compiler/src/core_parse.hrl"). -export([ with_context/1 , in_context/0 , all_modules/0 , get_module/1 , ensure_loaded/2 , maybe_ensure_loaded/1 , is_loaded/1 , fake_fun/3 , replace_calls/2 , replace_remote_calls/2 , replace_vars/2 , add_mappings/2 , add_alias/3 , add_attributes/2 , add_exports/2 , add_functions/2 , get_functions/1 , remove_all_functions/1 , add_on_load/2 , is_clojure/1 , is_protocol/1 ]). %% gen_server callbacks -export([ start_link/0 , init/1 , handle_call/3 , handle_cast/2 , handle_info/2 , terminate/2 , code_change/3 ]). -type function_id() :: {atom(), integer()}. -record(module, { name :: atom(), source = "" :: string(), %% ETS table where mappings are kept. The key is the var's %% name as a binary and the value can be either a var or %% a type. mappings :: ets:tid(), %% ETS table where aliases are kept. The key is the var's %% name as a binary and the value is the namespace symbol. aliases :: ets:tid(), %% ETS table where functions are kept. The key is the %% function's name and arity. funs :: ets:tid(), %% ETS table where fake functions are kept. The key is the %% funs value (i.e. Module:Function/Arity). fake_funs :: ets:tid(), %% ETS table where function exports are kept. The key is the %% function's name and arity. exports :: ets:tid(), %% ETS table where expressions that will be included in the %% on_load function are kept. The key is the expression %% itself. on_load :: ets:tid(), %% ETS table where attributes that are kept. attrs :: ets:tid() }). -type clj_module() :: #module{}. -export_type([clj_module/0]). -define(PID_TO_MODULES, 'clj_module_pid_to_modules'). -define(MODULE_TO_FAKE_MODULES, 'clj_module_module_to_fake_modules'). -define(ON_LOAD_FUNCTION, '$_clj_on_load'). -define(MODULE_INFO, 'module_info'). -define(CLJ_MODULE_CONTEXT, '$clj_module_compiling'). %%------------------------------------------------------------------------------ %% Exported Functions %%------------------------------------------------------------------------------ %% @doc Runs the function in a `clj_module' context. %% This is used by { @link clj_compiler } when evaluating or compiling %% an expression. It should be used in conjunction with {@link %% in_context/0} when you need to find out if there is a `clj_module' %% being processed. -spec with_context(fun()) -> ok. with_context(Fun) -> try erlang:put(?CLJ_MODULE_CONTEXT, true), Fun() after erlang:erase(?CLJ_MODULE_CONTEXT) end. %% @doc Checks whether we are in a `clj_module' context. -spec in_context() -> boolean(). in_context() -> erlang:get(?CLJ_MODULE_CONTEXT) =:= true. @doc Returns a list where each element is Core Erlang module . -spec all_modules() -> [cerl:c_module()]. all_modules() -> Self = erlang:self(), {_, All} = clj_utils:ets_get(?PID_TO_MODULES, Self, {Self, []}), lists:map(fun to_module/1, All). @doc Returns the Core Erlang module named ` ModuleName ' . -spec get_module(atom()) -> cerl:c_module(). get_module(ModuleName) when is_atom(ModuleName) -> to_module(fetch_module(ModuleName)). %% @doc Makes sure the clj_module is loaded. -spec ensure_loaded(binary(), module()) -> ok. ensure_loaded(Source, Name) -> case not is_loaded(Name) of true -> load(Source, Name), ok; false -> ok end. %% @doc Ensures a module is loaded when in a compiling context %% %% This is used from in-ns so that namespaces without any vars %% definition still get registered when compiling. %% @end -spec maybe_ensure_loaded(module()) -> ok. maybe_ensure_loaded(Name) -> File = clj_compiler:current_file(), in_context() andalso ensure_loaded(File, Name), ok. @doc Gets the named fake fun that corresponds to the mfa provided . %% %% A fake fun is generated during compile-time and it provides the %% same functionality as its original. The only difference is that %% all calls to functions in the same module are replaced by a call %% to clj_module:fake_fun/3. %% %% This is necessary so that macro functions can be used without %% having to generate, compile and load the binary for the partial %% module each time a macro is found. %% %% A fake module is generated for each fake fun because a previous %% attempt that used erl_eval to generate and execute the fake_fun %% was too slow. %% @end -spec fake_fun(module(), atom(), integer()) -> function(). fake_fun(ModuleName, Function, Arity) -> case fetch_module(ModuleName) of ?NIL -> fun ModuleName:Function/Arity; Module -> FA = {Function, Arity}, case clj_utils:ets_get(Module#module.fake_funs, FA) of ?NIL -> Fun = build_fake_fun(Function, Arity, Module), clj_utils:ets_save(Module#module.fake_funs, {FA, Fun}), Fun; {_, Fun} -> Fun end end. @private %% @doc Replaces all function calls to a currently loaded %% `clj_module' with a call to a {@link fake_fun/3}. -spec replace_calls( cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()} , module() ) -> cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()}. replace_calls(Ast, CurrentModule) -> replace_calls(Ast, CurrentModule, undefined). %% @doc Adds mappings from a symbol to a value. -spec add_mappings( ['clojerl.Var':type() | {binary(), 'erlang.Type':type()}] , module() | clj_module() ) -> clj_module(). add_mappings(_, ?NIL) -> error(badarg); add_mappings(Mappings, ModuleName) when is_atom(ModuleName) -> add_mappings(Mappings, fetch_module(ModuleName)); add_mappings(Mappings, Module) -> AddFun = fun ({K, V}) -> clj_utils:ets_save(Module#module.mappings, {K, V}); (V) -> K = clj_rt:name(V), clj_utils:ets_save(Module#module.mappings, {K, V}) end, lists:foreach(AddFun, Mappings), Module. @doc Adds an alias symbol for a Clojerl namespace . -spec add_alias( 'clojerl.Symbol':type() , 'clojerl.Symbol':type() , module() | clj_module() ) -> clj_module(). add_alias(AliasSym, AliasedNsSym, ModuleName) when is_atom(ModuleName) -> ok = ensure_loaded(<<?NO_SOURCE>>, ModuleName), add_alias(AliasSym, AliasedNsSym, fetch_module(ModuleName)); add_alias(AliasSym, AliasedNsSym, Module) -> K = clj_rt:name(AliasSym), clj_utils:ets_save(Module#module.aliases, {K, AliasedNsSym}), Module. %% @doc Adds arbitrary attributes to the module. -spec add_attributes([{cerl:cerl(), cerl:cerl()}], clj_module() | module()) -> clj_module(). add_attributes(_, ?NIL) -> error(badarg); add_attributes(Attrs, ModuleName) when is_atom(ModuleName) -> add_attributes(Attrs, fetch_module(ModuleName)); add_attributes([], Module) -> Module; add_attributes(Attrs, Module) -> AddAttr = fun(E) -> clj_utils:ets_save(Module#module.attrs, {E}) end, ok = lists:foreach(AddAttr, Attrs), Module. %% @doc Adds exports of functions to the module. -spec add_exports([{atom(), non_neg_integer()}], clj_module() | module()) -> clj_module(). add_exports(_, ?NIL) -> error(badarg); add_exports(Exports, ModuleName) when is_atom(ModuleName) -> add_exports(Exports, fetch_module(ModuleName)); add_exports(Exports, Module) -> AddExport = fun(E) -> clj_utils:ets_save(Module#module.exports, {E}) end, ok = lists:foreach(AddExport, Exports), Module. %% @doc Adds functions to the module. -spec add_functions([{cerl:cerl(), cerl:cerl()}], module() | clj_module()) -> clj_module(). add_functions(_, ?NIL) -> error(badarg); add_functions(Funs, ModuleName) when is_atom(ModuleName) -> add_functions(Funs, fetch_module(ModuleName)); add_functions(Funs, Module) -> SaveFun = fun(F) -> FunctionId = function_id(F), ok = delete_fake_fun(FunctionId, Module), clj_utils:ets_save(Module#module.funs, {FunctionId, F}) end, lists:foreach(SaveFun, Funs), Module. %% @doc Remove all functions in the module. -spec remove_all_functions(module() | clj_module()) -> clj_module(). remove_all_functions(?NIL) -> error(badarg); remove_all_functions(ModuleName) when is_atom(ModuleName) -> remove_all_functions(fetch_module(ModuleName)); remove_all_functions(Module) -> true = ets:delete_all_objects(Module#module.funs), true = ets:delete_all_objects(Module#module.exports), Module. %% @doc Returns all functions in the module. -spec get_functions(module() | clj_module()) -> [{function_id(), {cerl:c_fname(), cerl:c_fun()}}]. get_functions(?NIL) -> error(badarg); get_functions(ModuleName) when is_atom(ModuleName) -> get_functions(fetch_module(ModuleName)); get_functions(Module) -> ets:tab2list(Module#module.funs). %% @doc Adds an on_load expression to the module. -spec add_on_load(cerl:cerl(), module() | clj_module()) -> clj_module(). add_on_load(_, ?NIL) -> error(badarg); add_on_load(Expr, ModuleName) when is_atom(ModuleName) -> add_on_load(Expr, fetch_module(ModuleName)); add_on_load(Expr, Module) -> Index = erlang:unique_integer([monotonic]), clj_utils:ets_save(Module#module.on_load, {Index, Expr}), Module. @doc Checks if the ` Name ' module is a Clojerl module . -spec is_clojure(module()) -> boolean(). is_clojure(Name) -> Key = {?MODULE, is_clojure, Name}, case clj_cache:get(Key) of undefined -> Attrs = Name:module_info(attributes), IsClojure = lists:keymember(clojure, 1, Attrs), clj_cache:put(Key, IsClojure), IsClojure; {ok, Value} -> Value end. @doc Checks if the ` Name ' module is a Clojerl protocol . -spec is_protocol(module() | cerl:c_module()) -> boolean(). is_protocol(Name) when is_atom(Name) -> Key = {?MODULE, is_protocol, Name}, case clj_cache:get(Key) of undefined -> Attrs = Name:module_info(attributes), IsProtocol = lists:keymember(protocol, 1, Attrs), clj_cache:put(Key, IsProtocol), IsProtocol; {ok, Value} -> Value end; is_protocol(CoreModule) -> AllAttrs = cerl:module_attrs(CoreModule), {_, Extracted} = extract_attrs(AllAttrs, [clojure, protocol]), maps:size(Extracted) == 2. %%------------------------------------------------------------------------------ %% gen_server callbacks %%------------------------------------------------------------------------------ @private start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). @private init([]) -> ets:new(?MODULE, [named_table, set, protected, {keypos, 2}]), %% Keeps track of the modules loaded by pid. ets:new(?PID_TO_MODULES, [named_table, set, protected, {keypos, 1}]), %% Keeps track of fake modules created by which modules. %% It's necessary to keep it as a separate table because the %% information needs to survive the compiling processes during %% the cleanup. ets:new(?MODULE_TO_FAKE_MODULES, [named_table, set, protected, {keypos, 1}]), {ok, #{}}. @private handle_call({load, Module}, {Pid, _}, State) -> Module = clj_utils:ets_save(?MODULE, Module), case clj_utils:ets_get(?PID_TO_MODULES, Pid) of ?NIL -> %% Monitor the process so we can cleanup when it dies erlang:monitor(process, Pid), clj_utils:ets_save(?PID_TO_MODULES, {Pid, [Module]}); {Pid, Modules} -> clj_utils:ets_save(?PID_TO_MODULES, {Pid, [Module | Modules]}) end, {reply, ok, State}; handle_call({fetch, ModuleName}, _From, State) -> Module = clj_utils:ets_get(?MODULE, ModuleName), {reply, Module, State}. @private handle_cast({fake_module, Module, FakeModule}, State) -> {_, FakeModules} = clj_utils:ets_get( ?MODULE_TO_FAKE_MODULES , Module , {Module, []} ), clj_utils:ets_save( ?MODULE_TO_FAKE_MODULES , {Module, [FakeModule | FakeModules]} ), {noreply, State}; handle_cast(_Msg, State) -> {noreply, State}. @private %% @doc Cleans up modules when the process dies. handle_info({'DOWN', _MonitorRef, _Type, Pid, _Info}, State) -> {Pid, Modules} = clj_utils:ets_get(?PID_TO_MODULES, Pid, {Pid, []}), [cleanup(M#module.name) || M <- Modules], true = ets:delete(?PID_TO_MODULES, Pid), {noreply, State}; handle_info(_Msg, State) -> {noreply, State}. @private terminate(_Msg, _State) -> ok. @private code_change(_Msg, _From, State) -> {ok, State}. %%------------------------------------------------------------------------------ %% Helper Functions %%------------------------------------------------------------------------------ -spec fetch_module(module()) -> ?NIL | clj_module(). fetch_module(ModuleName) -> gen_server:call(?MODULE, {fetch, ModuleName}). -spec cleanup(module()) -> ok. cleanup(Module) -> ets:delete(?MODULE, Module), {_, FakeModules} = clj_utils:ets_get( ?MODULE_TO_FAKE_MODULES , Module , {Module, []} ), [begin code:purge(M), code:delete(M) end || M <- FakeModules], ok. @private %% @doc %% Loads the module `Name' into memory. This function assumes it is not %% loaded already, so this check should be done before calling it. %% The value of `Source' is used to set the `file' attribute of the module %% if the module's binary is not found, which is interpreted as if the %% module is new. %% @end -spec load(binary(), module()) -> clj_module(). load(Path, Name) when is_binary(Path) -> PathStr = binary_to_list(Path), Module = case code:ensure_loaded(Name) of {module, Name} -> new(PathStr, clj_utils:code_from_binary(Name)); {error, _} -> new(PathStr, Name) end, ok = gen_server:call(?MODULE, {load, Module}), Module. @doc Checks if the module ` Name ' is loaded . -spec is_loaded(module()) -> boolean(). is_loaded(Name) -> ets:member(?MODULE, Name). %% @doc Processes a function's ast and modifies all calls to functions %% in the function's own module for a call to the fun returned by %% clj_module:fake_fun/3. %% @end -spec replace_calls( cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()} , module() , {atom(), arity()} | undefined ) -> cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()}. replace_calls( #c_call{ module = ModuleAst , name = FunctionAst , args = ArgsAsts , anno = Ann } , CurrentModule , FA ) -> %% Only replace the call if the module is loaded. If it is not, then the %% replacement is happening for the evaluation of an expression where the %% called function hasn't been declared in the same evaluation. Module = cerl:concrete(ModuleAst), case is_loaded(Module) of true -> fake_fun_call(Ann, CurrentModule, ModuleAst, FunctionAst, ArgsAsts); false -> ArgsAsts1 = replace_calls(ArgsAsts, CurrentModule, FA), cerl:ann_c_call(Ann, ModuleAst, FunctionAst, ArgsAsts1) end; %% Detect non-remote calls done to other functions in the module, so we %% can replace them with fake_funs when necessary. replace_calls( #c_apply{ op = #c_var{name = {_, _} = FA0} = FNameAst , args = ArgsAsts , anno = Ann } , Module , FA1 ) -> case FA0 =:= FA1 orelse lists:member(?LOCAL, Ann) of true -> ArgsAsts1 = replace_calls(ArgsAsts, Module, FA1), cerl:ann_c_apply(Ann, FNameAst, ArgsAsts1); false -> ModuleAst = cerl:ann_c_atom(Ann, Module), FunctionAst = cerl:ann_c_atom(Ann, cerl:fname_id(FNameAst)), fake_fun_call(Ann, Module, ModuleAst, FunctionAst, ArgsAsts) end; replace_calls(Ast, Module, FA) when is_tuple(Ast) -> list_to_tuple(replace_calls(tuple_to_list(Ast), Module, FA)); replace_calls(Asts, Module, FA) when is_list(Asts) -> [replace_calls(Item, Module, FA) || Item <- Asts]; replace_calls(Ast, _Module, _FA) when is_map(Ast) -> replace_vars(Ast); replace_calls(Ast, _Module, _FA) -> Ast. -spec replace_remote_calls( cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()} , module() ) -> cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()}. replace_remote_calls( #c_call{ module = ModuleAst , name = FunctionAst , args = ArgsAsts , anno = Ann } , CurrentModule ) -> case cerl:concrete(ModuleAst) of CurrentModule -> ArgsAsts1 = replace_remote_calls(ArgsAsts, CurrentModule), Name = cerl:concrete(FunctionAst), Arity = length(ArgsAsts), OpAst = cerl:ann_c_fname(Ann, Name, Arity), cerl:ann_c_apply(Ann, OpAst, ArgsAsts1); _ -> ArgsAsts1 = replace_remote_calls(ArgsAsts, CurrentModule), cerl:ann_c_call(Ann, ModuleAst, FunctionAst, ArgsAsts1) end; replace_remote_calls(Ast, Module) when is_tuple(Ast) -> list_to_tuple(replace_remote_calls(tuple_to_list(Ast), Module)); replace_remote_calls(Asts, Module) when is_list(Asts) -> [replace_remote_calls(Item, Module) || Item <- Asts]; replace_remote_calls(Ast, _Module) -> Ast. -spec replace_vars(T) -> T when T :: any(). replace_vars(X) -> replace_vars(X, true). %% @doc Adds the fake_fun flag to literal vars -spec replace_vars(T, boolean()) -> T when T :: any(). replace_vars(#{?TYPE := 'clojerl.Var'} = Var0, IsFakeFun) -> 'clojerl.Var':fake_fun(Var0, IsFakeFun); replace_vars(Map, IsFakeFun) when is_map(Map) -> Fun = fun(K0, V0, Acc) -> {K1, V1} = replace_vars({K0, V0}, IsFakeFun), Acc#{K1 => V1} end, maps:fold(Fun, #{}, Map); replace_vars(X, IsFakeFun) when is_tuple(X) -> list_to_tuple(replace_vars(tuple_to_list(X), IsFakeFun)); replace_vars(X, IsFakeFun) when is_list(X) -> [replace_vars(Item, IsFakeFun) || Item <- X]; replace_vars(X, _IsFakeFun) -> X. -spec fake_fun_call( [term()] , module() , cerl:cerl() , cerl:cerl() , [cerl:cerl()] ) -> cerl:cerl(). fake_fun_call(Ann, CurrentModule, ModuleAst, FunctionAst, ArgsAsts) -> Args1 = replace_calls(ArgsAsts, CurrentModule), Arity = length(ArgsAsts), CallArgs = [ ModuleAst , FunctionAst , cerl:ann_c_int(Ann, Arity) ], CallAst = cerl:ann_c_call( Ann , cerl:c_atom(?MODULE) , cerl:c_atom(fake_fun) , CallArgs ), VarAst = clj_emitter:new_c_var(Ann), ApplyAst = cerl:ann_c_apply(Ann, VarAst, Args1), cerl:ann_c_let(Ann, [VarAst], CallAst, ApplyAst). @private -spec build_fake_fun(atom(), integer(), clj_module()) -> function(). build_fake_fun(Function, Arity, Module) -> FunctionAst = case clj_utils:ets_get(Module#module.funs, {Function, Arity}) of {_, FunctionAst_} -> FunctionAst_; undefined -> throw({not_found, Module#module.name, Function, Arity}) end, {FName, _} = Fun = replace_calls( FunctionAst , Module#module.name , {Function, Arity} ), Int = erlang:unique_integer([positive]), FakeModuleName = list_to_atom("fake_module_" ++ integer_to_list(Int)), {Names, Defs} = module_info_funs(FakeModuleName), ModuleName = cerl:c_atom(FakeModuleName), Exports = [FName | Names], Clojure = {cerl:c_atom(clojure), cerl:abstract([true])}, FakeModule = cerl:c_module( ModuleName , Exports , [Clojure] , [Fun | Defs] ), try Bindings = #{<<"#'clojure.core/*compile-files*">> => false}, ok = 'clojerl.Var':push_bindings(Bindings), CompileOpts = #{fake => true}, clj_compiler:module(FakeModule, CompileOpts) after ok = 'clojerl.Var':pop_bindings() end, gen_server:cast(?MODULE, {fake_module, Module#module.name, FakeModuleName}), erlang:make_fun(FakeModuleName, Function, Arity). %% @doc Deletes all fake_funs for Module:Function of all arities. %% %% This is used so that they can be replaced with new ones, when %% redifining a function, for example. %% @end -spec delete_fake_fun(function_id(), clj_module()) -> ok. delete_fake_fun(FunctionId, Module) -> true = ets:delete(Module#module.fake_funs, FunctionId), ok. @private -spec to_module(clj_module()) -> cerl:c_module(). to_module(#module{} = Module) -> #module{ name = Name , source = Source , mappings = MappingsTable , aliases = AliasesTable , funs = FunsTable , exports = ExportsTable , on_load = OnLoadTable , attrs = AttrsTable } = Module, add_module_info_functions(Module), FileAttr = {cerl:c_atom(file), cerl:abstract(Source)}, MappingsList = ets:tab2list(MappingsTable), Mappings = maps:from_list(MappingsList), MappingsAttr = {cerl:c_atom(mappings), cerl:abstract([Mappings])}, AliasesList = ets:tab2list(AliasesTable), Aliases = maps:from_list(AliasesList), AliasesAttr = {cerl:c_atom(aliases), cerl:abstract([Aliases])}, Exports = [cerl:c_fname(FName, Arity) || {{FName, Arity}} <- ets:tab2list(ExportsTable) ], ClojureAttr = {cerl:c_atom(clojure), cerl:abstract([true])}, NameSym = clj_rt:symbol(atom_to_binary(Name, utf8)), Meta = case 'clojerl.Namespace':find(NameSym) of ?NIL -> ?NIL; Ns -> 'clojerl.Namespace':meta(Ns) end, MetaAttr = {cerl:c_atom(meta), cerl:abstract([Meta])}, Attrs = [X || {X} <- ets:tab2list(AttrsTable)], UniqueAttrs = lists:usort([ClojureAttr, MetaAttr | Attrs]), AllAttrs = [FileAttr, MappingsAttr, AliasesAttr | UniqueAttrs], Defs = [X || {_, X} <- ets:tab2list(FunsTable)], maybe_on_load(OnLoadTable, cerl:c_atom(Name), Exports, AllAttrs, Defs). add_module_info_functions(Module) -> {_, Funs} = module_info_funs(Module#module.name), add_functions(Funs, Module), add_exports([{module_info, 0}, {module_info, 1}], Module). -spec module_info_funs(module()) -> {[cerl:cerl()], [{cerl:cerl(), cerl:cerl()}]}. module_info_funs(Name) -> InfoName0 = cerl:c_fname(?MODULE_INFO, 0), InfoFun0 = cerl:c_fun( [] , cerl:c_call( cerl:c_atom(erlang) , cerl:c_atom(get_module_info) , [cerl:c_atom(Name)] ) ), InfoName1 = cerl:c_fname(?MODULE_INFO, 1), Arg = cerl:c_var(x), InfoFun1 = cerl:c_fun( [Arg] , cerl:c_call( cerl:c_atom(erlang) , cerl:c_atom(get_module_info) , [cerl:c_atom(Name), Arg] ) ), { [InfoName0, InfoName1] , [ {InfoName0, InfoFun0} , {InfoName1, InfoFun1} ] }. %% @doc Only add an on_load function if there are any expressions to be added. -spec maybe_on_load( ets:tid() , cerl:c_atom() , [cerl:c_var()] , [{cerl:c_atom(), cerl:cerl()}] , [cerl:c_fun()] ) -> cerl:c_module(). maybe_on_load(OnLoadTable, Name, Exports0, Attrs0, Defs0) -> case ets:info(OnLoadTable, size) of 0 -> ?DEBUG({no_on_load, cerl:atom_val(Name)}), cerl:c_module(Name, Exports0, Attrs0, Defs0); _ -> Attr = { cerl:c_atom(on_load) , cerl:abstract([{?ON_LOAD_FUNCTION, 0}]) }, FName = cerl:c_fname(?ON_LOAD_FUNCTION, 0), Fun = on_load_function(OnLoadTable), Def = {FName, Fun}, Attrs1 = lists:usort([Attr | Attrs0]), Defs1 = [Def | Defs0], cerl:c_module(Name, Exports0, Attrs1, Defs1) end. @private -spec on_load_function(ets:tid()) -> empty | cerl:cerl(). on_load_function(OnLoadTable) -> [Head | Tail] = [Expr || {_, Expr} <- lists:sort(ets:tab2list(OnLoadTable))], SeqFun = fun(X, Acc) -> cerl:c_seq(Acc, X) end, Body = lists:foldl(SeqFun, Head, Tail), cerl:c_fun([], cerl:c_seq(Body, cerl:c_atom(ok))). -spec new(string(), atom() | cerl:c_module()) -> clj_module(). new(Path, Name) when is_atom(Name), is_list(Path) -> FileAttr = {cerl:c_atom(file), cerl:abstract(Path)}, new(cerl:c_module(cerl:c_atom(Name), [], [FileAttr], [])); new(Path, #c_module{attrs = Attrs} = CoreModule) when is_list(Path) -> FileAttr = {cerl:c_atom(file), cerl:abstract(Path)}, new(CoreModule#c_module{attrs = [FileAttr | Attrs]}). -spec new(cerl:cerl()) -> clj_module(). new(CoreModule) -> Name = cerl:concrete(cerl:module_name(CoreModule)), Exports = [ {cerl:fname_id(E), cerl:fname_arity(E)} || E <- cerl:module_exports(CoreModule) ], AllAttrs = cerl:module_attrs(CoreModule), Funs = cerl:module_defs(CoreModule), {Attrs, Extracted} = extract_attrs(AllAttrs, [mappings, aliases, file]), Mappings = case maps:get(mappings, Extracted, #{}) of [V] -> V; V -> V end, Aliases = case maps:get(aliases, Extracted, #{}) of [X] -> X; X -> X end, Path = maps:get(file, Extracted, ""), %% Tables need to be public so that other compiler processes can modify them. TableOpts = [set, public, {keypos, 1}], Module = #module{ name = Name , source = Path , mappings = ets:new(mappings, TableOpts) , aliases = ets:new(aliases, TableOpts) , funs = ets:new(funs, TableOpts) , fake_funs = ets:new(fake_funs, TableOpts) , exports = ets:new(exports, TableOpts) , on_load = ets:new(on_load, TableOpts) , attrs = ets:new(attributes, TableOpts) }, Module = add_functions(Funs, Module), Module = add_mappings(maps:to_list(Mappings), Module), [add_alias(A, Ns, Module) || {A, Ns} <- maps:to_list(Aliases)], Module = add_attributes(Attrs, Module), %% Keep expressions from the on_load function. %% IMPORTANT: This means that for wiping them all out, the namespace %% needs to be compiled from scratch. OnLoadId = {?ON_LOAD_FUNCTION, 0}, case clj_utils:ets_get(Module#module.funs, OnLoadId) of ?NIL -> ok; {OnLoadId, {_OnLoadName, OnLoadFun}} -> Body = cerl:fun_body(OnLoadFun), add_on_load(Body, Module), true = ets:delete(Module#module.funs, OnLoadId) end, add_exports(Exports, Module). -spec function_id({cerl:cerl(), cerl:cerl()}) -> function_id(). function_id({Name, _}) -> {cerl:fname_id(Name), cerl:fname_arity(Name)}. -spec extract_attrs([{cerl:c_atom(), cerl:cerl()}], [atom()]) -> {[{cerl:c_atom(), cerl:cerl()}], map()}. extract_attrs(Attrs, Names) -> do_extract_attrs(Attrs, Names, [], #{}). do_extract_attrs([], _Names, NewAttrs, Extracted) -> {NewAttrs, Extracted}; do_extract_attrs( [{NameAbst, ValAbst} = Attr | Attrs] , Names , NewAttrs , Extracted ) -> Name = cerl:concrete(NameAbst), case lists:member(Name, Names) of true -> Val = cerl:concrete(ValAbst), do_extract_attrs(Attrs, Names, NewAttrs, Extracted#{Name => Val}); false -> do_extract_attrs(Attrs, Names, [Attr | NewAttrs], Extracted) end.
null
https://raw.githubusercontent.com/clojerl/clojerl/5b412b87de13811b5a6ee4d82329d6a44dc499f0/src/erl/clj_module.erl
erlang
Keeps the Core Erlang representation for the modules being compiled. It is mainly used by {@link clj_emitter} to register new modules and then add or update function as each form in the compiler is processed. gen_server callbacks ETS table where mappings are kept. The key is the var's name as a binary and the value can be either a var or a type. ETS table where aliases are kept. The key is the var's name as a binary and the value is the namespace symbol. ETS table where functions are kept. The key is the function's name and arity. ETS table where fake functions are kept. The key is the funs value (i.e. Module:Function/Arity). ETS table where function exports are kept. The key is the function's name and arity. ETS table where expressions that will be included in the on_load function are kept. The key is the expression itself. ETS table where attributes that are kept. ------------------------------------------------------------------------------ Exported Functions ------------------------------------------------------------------------------ @doc Runs the function in a `clj_module' context. an expression. It should be used in conjunction with {@link in_context/0} when you need to find out if there is a `clj_module' being processed. @doc Checks whether we are in a `clj_module' context. @doc Makes sure the clj_module is loaded. @doc Ensures a module is loaded when in a compiling context This is used from in-ns so that namespaces without any vars definition still get registered when compiling. @end A fake fun is generated during compile-time and it provides the same functionality as its original. The only difference is that all calls to functions in the same module are replaced by a call to clj_module:fake_fun/3. This is necessary so that macro functions can be used without having to generate, compile and load the binary for the partial module each time a macro is found. A fake module is generated for each fake fun because a previous attempt that used erl_eval to generate and execute the fake_fun was too slow. @end @doc Replaces all function calls to a currently loaded `clj_module' with a call to a {@link fake_fun/3}. @doc Adds mappings from a symbol to a value. @doc Adds arbitrary attributes to the module. @doc Adds exports of functions to the module. @doc Adds functions to the module. @doc Remove all functions in the module. @doc Returns all functions in the module. @doc Adds an on_load expression to the module. ------------------------------------------------------------------------------ gen_server callbacks ------------------------------------------------------------------------------ Keeps track of the modules loaded by pid. Keeps track of fake modules created by which modules. It's necessary to keep it as a separate table because the information needs to survive the compiling processes during the cleanup. Monitor the process so we can cleanup when it dies @doc Cleans up modules when the process dies. ------------------------------------------------------------------------------ Helper Functions ------------------------------------------------------------------------------ @doc Loads the module `Name' into memory. This function assumes it is not loaded already, so this check should be done before calling it. The value of `Source' is used to set the `file' attribute of the module if the module's binary is not found, which is interpreted as if the module is new. @end @doc Processes a function's ast and modifies all calls to functions in the function's own module for a call to the fun returned by clj_module:fake_fun/3. @end Only replace the call if the module is loaded. If it is not, then the replacement is happening for the evaluation of an expression where the called function hasn't been declared in the same evaluation. Detect non-remote calls done to other functions in the module, so we can replace them with fake_funs when necessary. @doc Adds the fake_fun flag to literal vars @doc Deletes all fake_funs for Module:Function of all arities. This is used so that they can be replaced with new ones, when redifining a function, for example. @end @doc Only add an on_load function if there are any expressions to be added. Tables need to be public so that other compiler processes can modify them. Keep expressions from the on_load function. IMPORTANT: This means that for wiping them all out, the namespace needs to be compiled from scratch.
@doc Clojerl compilation module . -module(clj_module). -behavior(gen_server). -compile({no_auto_import, [get/1, delete_module/1]}). -include("clojerl.hrl"). -include("clojerl_int.hrl"). -include_lib("compiler/src/core_parse.hrl"). -export([ with_context/1 , in_context/0 , all_modules/0 , get_module/1 , ensure_loaded/2 , maybe_ensure_loaded/1 , is_loaded/1 , fake_fun/3 , replace_calls/2 , replace_remote_calls/2 , replace_vars/2 , add_mappings/2 , add_alias/3 , add_attributes/2 , add_exports/2 , add_functions/2 , get_functions/1 , remove_all_functions/1 , add_on_load/2 , is_clojure/1 , is_protocol/1 ]). -export([ start_link/0 , init/1 , handle_call/3 , handle_cast/2 , handle_info/2 , terminate/2 , code_change/3 ]). -type function_id() :: {atom(), integer()}. -record(module, { name :: atom(), source = "" :: string(), mappings :: ets:tid(), aliases :: ets:tid(), funs :: ets:tid(), fake_funs :: ets:tid(), exports :: ets:tid(), on_load :: ets:tid(), attrs :: ets:tid() }). -type clj_module() :: #module{}. -export_type([clj_module/0]). -define(PID_TO_MODULES, 'clj_module_pid_to_modules'). -define(MODULE_TO_FAKE_MODULES, 'clj_module_module_to_fake_modules'). -define(ON_LOAD_FUNCTION, '$_clj_on_load'). -define(MODULE_INFO, 'module_info'). -define(CLJ_MODULE_CONTEXT, '$clj_module_compiling'). This is used by { @link clj_compiler } when evaluating or compiling -spec with_context(fun()) -> ok. with_context(Fun) -> try erlang:put(?CLJ_MODULE_CONTEXT, true), Fun() after erlang:erase(?CLJ_MODULE_CONTEXT) end. -spec in_context() -> boolean(). in_context() -> erlang:get(?CLJ_MODULE_CONTEXT) =:= true. @doc Returns a list where each element is Core Erlang module . -spec all_modules() -> [cerl:c_module()]. all_modules() -> Self = erlang:self(), {_, All} = clj_utils:ets_get(?PID_TO_MODULES, Self, {Self, []}), lists:map(fun to_module/1, All). @doc Returns the Core Erlang module named ` ModuleName ' . -spec get_module(atom()) -> cerl:c_module(). get_module(ModuleName) when is_atom(ModuleName) -> to_module(fetch_module(ModuleName)). -spec ensure_loaded(binary(), module()) -> ok. ensure_loaded(Source, Name) -> case not is_loaded(Name) of true -> load(Source, Name), ok; false -> ok end. -spec maybe_ensure_loaded(module()) -> ok. maybe_ensure_loaded(Name) -> File = clj_compiler:current_file(), in_context() andalso ensure_loaded(File, Name), ok. @doc Gets the named fake fun that corresponds to the mfa provided . -spec fake_fun(module(), atom(), integer()) -> function(). fake_fun(ModuleName, Function, Arity) -> case fetch_module(ModuleName) of ?NIL -> fun ModuleName:Function/Arity; Module -> FA = {Function, Arity}, case clj_utils:ets_get(Module#module.fake_funs, FA) of ?NIL -> Fun = build_fake_fun(Function, Arity, Module), clj_utils:ets_save(Module#module.fake_funs, {FA, Fun}), Fun; {_, Fun} -> Fun end end. @private -spec replace_calls( cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()} , module() ) -> cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()}. replace_calls(Ast, CurrentModule) -> replace_calls(Ast, CurrentModule, undefined). -spec add_mappings( ['clojerl.Var':type() | {binary(), 'erlang.Type':type()}] , module() | clj_module() ) -> clj_module(). add_mappings(_, ?NIL) -> error(badarg); add_mappings(Mappings, ModuleName) when is_atom(ModuleName) -> add_mappings(Mappings, fetch_module(ModuleName)); add_mappings(Mappings, Module) -> AddFun = fun ({K, V}) -> clj_utils:ets_save(Module#module.mappings, {K, V}); (V) -> K = clj_rt:name(V), clj_utils:ets_save(Module#module.mappings, {K, V}) end, lists:foreach(AddFun, Mappings), Module. @doc Adds an alias symbol for a Clojerl namespace . -spec add_alias( 'clojerl.Symbol':type() , 'clojerl.Symbol':type() , module() | clj_module() ) -> clj_module(). add_alias(AliasSym, AliasedNsSym, ModuleName) when is_atom(ModuleName) -> ok = ensure_loaded(<<?NO_SOURCE>>, ModuleName), add_alias(AliasSym, AliasedNsSym, fetch_module(ModuleName)); add_alias(AliasSym, AliasedNsSym, Module) -> K = clj_rt:name(AliasSym), clj_utils:ets_save(Module#module.aliases, {K, AliasedNsSym}), Module. -spec add_attributes([{cerl:cerl(), cerl:cerl()}], clj_module() | module()) -> clj_module(). add_attributes(_, ?NIL) -> error(badarg); add_attributes(Attrs, ModuleName) when is_atom(ModuleName) -> add_attributes(Attrs, fetch_module(ModuleName)); add_attributes([], Module) -> Module; add_attributes(Attrs, Module) -> AddAttr = fun(E) -> clj_utils:ets_save(Module#module.attrs, {E}) end, ok = lists:foreach(AddAttr, Attrs), Module. -spec add_exports([{atom(), non_neg_integer()}], clj_module() | module()) -> clj_module(). add_exports(_, ?NIL) -> error(badarg); add_exports(Exports, ModuleName) when is_atom(ModuleName) -> add_exports(Exports, fetch_module(ModuleName)); add_exports(Exports, Module) -> AddExport = fun(E) -> clj_utils:ets_save(Module#module.exports, {E}) end, ok = lists:foreach(AddExport, Exports), Module. -spec add_functions([{cerl:cerl(), cerl:cerl()}], module() | clj_module()) -> clj_module(). add_functions(_, ?NIL) -> error(badarg); add_functions(Funs, ModuleName) when is_atom(ModuleName) -> add_functions(Funs, fetch_module(ModuleName)); add_functions(Funs, Module) -> SaveFun = fun(F) -> FunctionId = function_id(F), ok = delete_fake_fun(FunctionId, Module), clj_utils:ets_save(Module#module.funs, {FunctionId, F}) end, lists:foreach(SaveFun, Funs), Module. -spec remove_all_functions(module() | clj_module()) -> clj_module(). remove_all_functions(?NIL) -> error(badarg); remove_all_functions(ModuleName) when is_atom(ModuleName) -> remove_all_functions(fetch_module(ModuleName)); remove_all_functions(Module) -> true = ets:delete_all_objects(Module#module.funs), true = ets:delete_all_objects(Module#module.exports), Module. -spec get_functions(module() | clj_module()) -> [{function_id(), {cerl:c_fname(), cerl:c_fun()}}]. get_functions(?NIL) -> error(badarg); get_functions(ModuleName) when is_atom(ModuleName) -> get_functions(fetch_module(ModuleName)); get_functions(Module) -> ets:tab2list(Module#module.funs). -spec add_on_load(cerl:cerl(), module() | clj_module()) -> clj_module(). add_on_load(_, ?NIL) -> error(badarg); add_on_load(Expr, ModuleName) when is_atom(ModuleName) -> add_on_load(Expr, fetch_module(ModuleName)); add_on_load(Expr, Module) -> Index = erlang:unique_integer([monotonic]), clj_utils:ets_save(Module#module.on_load, {Index, Expr}), Module. @doc Checks if the ` Name ' module is a Clojerl module . -spec is_clojure(module()) -> boolean(). is_clojure(Name) -> Key = {?MODULE, is_clojure, Name}, case clj_cache:get(Key) of undefined -> Attrs = Name:module_info(attributes), IsClojure = lists:keymember(clojure, 1, Attrs), clj_cache:put(Key, IsClojure), IsClojure; {ok, Value} -> Value end. @doc Checks if the ` Name ' module is a Clojerl protocol . -spec is_protocol(module() | cerl:c_module()) -> boolean(). is_protocol(Name) when is_atom(Name) -> Key = {?MODULE, is_protocol, Name}, case clj_cache:get(Key) of undefined -> Attrs = Name:module_info(attributes), IsProtocol = lists:keymember(protocol, 1, Attrs), clj_cache:put(Key, IsProtocol), IsProtocol; {ok, Value} -> Value end; is_protocol(CoreModule) -> AllAttrs = cerl:module_attrs(CoreModule), {_, Extracted} = extract_attrs(AllAttrs, [clojure, protocol]), maps:size(Extracted) == 2. @private start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). @private init([]) -> ets:new(?MODULE, [named_table, set, protected, {keypos, 2}]), ets:new(?PID_TO_MODULES, [named_table, set, protected, {keypos, 1}]), ets:new(?MODULE_TO_FAKE_MODULES, [named_table, set, protected, {keypos, 1}]), {ok, #{}}. @private handle_call({load, Module}, {Pid, _}, State) -> Module = clj_utils:ets_save(?MODULE, Module), case clj_utils:ets_get(?PID_TO_MODULES, Pid) of ?NIL -> erlang:monitor(process, Pid), clj_utils:ets_save(?PID_TO_MODULES, {Pid, [Module]}); {Pid, Modules} -> clj_utils:ets_save(?PID_TO_MODULES, {Pid, [Module | Modules]}) end, {reply, ok, State}; handle_call({fetch, ModuleName}, _From, State) -> Module = clj_utils:ets_get(?MODULE, ModuleName), {reply, Module, State}. @private handle_cast({fake_module, Module, FakeModule}, State) -> {_, FakeModules} = clj_utils:ets_get( ?MODULE_TO_FAKE_MODULES , Module , {Module, []} ), clj_utils:ets_save( ?MODULE_TO_FAKE_MODULES , {Module, [FakeModule | FakeModules]} ), {noreply, State}; handle_cast(_Msg, State) -> {noreply, State}. @private handle_info({'DOWN', _MonitorRef, _Type, Pid, _Info}, State) -> {Pid, Modules} = clj_utils:ets_get(?PID_TO_MODULES, Pid, {Pid, []}), [cleanup(M#module.name) || M <- Modules], true = ets:delete(?PID_TO_MODULES, Pid), {noreply, State}; handle_info(_Msg, State) -> {noreply, State}. @private terminate(_Msg, _State) -> ok. @private code_change(_Msg, _From, State) -> {ok, State}. -spec fetch_module(module()) -> ?NIL | clj_module(). fetch_module(ModuleName) -> gen_server:call(?MODULE, {fetch, ModuleName}). -spec cleanup(module()) -> ok. cleanup(Module) -> ets:delete(?MODULE, Module), {_, FakeModules} = clj_utils:ets_get( ?MODULE_TO_FAKE_MODULES , Module , {Module, []} ), [begin code:purge(M), code:delete(M) end || M <- FakeModules], ok. @private -spec load(binary(), module()) -> clj_module(). load(Path, Name) when is_binary(Path) -> PathStr = binary_to_list(Path), Module = case code:ensure_loaded(Name) of {module, Name} -> new(PathStr, clj_utils:code_from_binary(Name)); {error, _} -> new(PathStr, Name) end, ok = gen_server:call(?MODULE, {load, Module}), Module. @doc Checks if the module ` Name ' is loaded . -spec is_loaded(module()) -> boolean(). is_loaded(Name) -> ets:member(?MODULE, Name). -spec replace_calls( cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()} , module() , {atom(), arity()} | undefined ) -> cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()}. replace_calls( #c_call{ module = ModuleAst , name = FunctionAst , args = ArgsAsts , anno = Ann } , CurrentModule , FA ) -> Module = cerl:concrete(ModuleAst), case is_loaded(Module) of true -> fake_fun_call(Ann, CurrentModule, ModuleAst, FunctionAst, ArgsAsts); false -> ArgsAsts1 = replace_calls(ArgsAsts, CurrentModule, FA), cerl:ann_c_call(Ann, ModuleAst, FunctionAst, ArgsAsts1) end; replace_calls( #c_apply{ op = #c_var{name = {_, _} = FA0} = FNameAst , args = ArgsAsts , anno = Ann } , Module , FA1 ) -> case FA0 =:= FA1 orelse lists:member(?LOCAL, Ann) of true -> ArgsAsts1 = replace_calls(ArgsAsts, Module, FA1), cerl:ann_c_apply(Ann, FNameAst, ArgsAsts1); false -> ModuleAst = cerl:ann_c_atom(Ann, Module), FunctionAst = cerl:ann_c_atom(Ann, cerl:fname_id(FNameAst)), fake_fun_call(Ann, Module, ModuleAst, FunctionAst, ArgsAsts) end; replace_calls(Ast, Module, FA) when is_tuple(Ast) -> list_to_tuple(replace_calls(tuple_to_list(Ast), Module, FA)); replace_calls(Asts, Module, FA) when is_list(Asts) -> [replace_calls(Item, Module, FA) || Item <- Asts]; replace_calls(Ast, _Module, _FA) when is_map(Ast) -> replace_vars(Ast); replace_calls(Ast, _Module, _FA) -> Ast. -spec replace_remote_calls( cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()} , module() ) -> cerl:cerl() | [cerl:cerl()] | {cerl:cerl(), cerl:cerl()}. replace_remote_calls( #c_call{ module = ModuleAst , name = FunctionAst , args = ArgsAsts , anno = Ann } , CurrentModule ) -> case cerl:concrete(ModuleAst) of CurrentModule -> ArgsAsts1 = replace_remote_calls(ArgsAsts, CurrentModule), Name = cerl:concrete(FunctionAst), Arity = length(ArgsAsts), OpAst = cerl:ann_c_fname(Ann, Name, Arity), cerl:ann_c_apply(Ann, OpAst, ArgsAsts1); _ -> ArgsAsts1 = replace_remote_calls(ArgsAsts, CurrentModule), cerl:ann_c_call(Ann, ModuleAst, FunctionAst, ArgsAsts1) end; replace_remote_calls(Ast, Module) when is_tuple(Ast) -> list_to_tuple(replace_remote_calls(tuple_to_list(Ast), Module)); replace_remote_calls(Asts, Module) when is_list(Asts) -> [replace_remote_calls(Item, Module) || Item <- Asts]; replace_remote_calls(Ast, _Module) -> Ast. -spec replace_vars(T) -> T when T :: any(). replace_vars(X) -> replace_vars(X, true). -spec replace_vars(T, boolean()) -> T when T :: any(). replace_vars(#{?TYPE := 'clojerl.Var'} = Var0, IsFakeFun) -> 'clojerl.Var':fake_fun(Var0, IsFakeFun); replace_vars(Map, IsFakeFun) when is_map(Map) -> Fun = fun(K0, V0, Acc) -> {K1, V1} = replace_vars({K0, V0}, IsFakeFun), Acc#{K1 => V1} end, maps:fold(Fun, #{}, Map); replace_vars(X, IsFakeFun) when is_tuple(X) -> list_to_tuple(replace_vars(tuple_to_list(X), IsFakeFun)); replace_vars(X, IsFakeFun) when is_list(X) -> [replace_vars(Item, IsFakeFun) || Item <- X]; replace_vars(X, _IsFakeFun) -> X. -spec fake_fun_call( [term()] , module() , cerl:cerl() , cerl:cerl() , [cerl:cerl()] ) -> cerl:cerl(). fake_fun_call(Ann, CurrentModule, ModuleAst, FunctionAst, ArgsAsts) -> Args1 = replace_calls(ArgsAsts, CurrentModule), Arity = length(ArgsAsts), CallArgs = [ ModuleAst , FunctionAst , cerl:ann_c_int(Ann, Arity) ], CallAst = cerl:ann_c_call( Ann , cerl:c_atom(?MODULE) , cerl:c_atom(fake_fun) , CallArgs ), VarAst = clj_emitter:new_c_var(Ann), ApplyAst = cerl:ann_c_apply(Ann, VarAst, Args1), cerl:ann_c_let(Ann, [VarAst], CallAst, ApplyAst). @private -spec build_fake_fun(atom(), integer(), clj_module()) -> function(). build_fake_fun(Function, Arity, Module) -> FunctionAst = case clj_utils:ets_get(Module#module.funs, {Function, Arity}) of {_, FunctionAst_} -> FunctionAst_; undefined -> throw({not_found, Module#module.name, Function, Arity}) end, {FName, _} = Fun = replace_calls( FunctionAst , Module#module.name , {Function, Arity} ), Int = erlang:unique_integer([positive]), FakeModuleName = list_to_atom("fake_module_" ++ integer_to_list(Int)), {Names, Defs} = module_info_funs(FakeModuleName), ModuleName = cerl:c_atom(FakeModuleName), Exports = [FName | Names], Clojure = {cerl:c_atom(clojure), cerl:abstract([true])}, FakeModule = cerl:c_module( ModuleName , Exports , [Clojure] , [Fun | Defs] ), try Bindings = #{<<"#'clojure.core/*compile-files*">> => false}, ok = 'clojerl.Var':push_bindings(Bindings), CompileOpts = #{fake => true}, clj_compiler:module(FakeModule, CompileOpts) after ok = 'clojerl.Var':pop_bindings() end, gen_server:cast(?MODULE, {fake_module, Module#module.name, FakeModuleName}), erlang:make_fun(FakeModuleName, Function, Arity). -spec delete_fake_fun(function_id(), clj_module()) -> ok. delete_fake_fun(FunctionId, Module) -> true = ets:delete(Module#module.fake_funs, FunctionId), ok. @private -spec to_module(clj_module()) -> cerl:c_module(). to_module(#module{} = Module) -> #module{ name = Name , source = Source , mappings = MappingsTable , aliases = AliasesTable , funs = FunsTable , exports = ExportsTable , on_load = OnLoadTable , attrs = AttrsTable } = Module, add_module_info_functions(Module), FileAttr = {cerl:c_atom(file), cerl:abstract(Source)}, MappingsList = ets:tab2list(MappingsTable), Mappings = maps:from_list(MappingsList), MappingsAttr = {cerl:c_atom(mappings), cerl:abstract([Mappings])}, AliasesList = ets:tab2list(AliasesTable), Aliases = maps:from_list(AliasesList), AliasesAttr = {cerl:c_atom(aliases), cerl:abstract([Aliases])}, Exports = [cerl:c_fname(FName, Arity) || {{FName, Arity}} <- ets:tab2list(ExportsTable) ], ClojureAttr = {cerl:c_atom(clojure), cerl:abstract([true])}, NameSym = clj_rt:symbol(atom_to_binary(Name, utf8)), Meta = case 'clojerl.Namespace':find(NameSym) of ?NIL -> ?NIL; Ns -> 'clojerl.Namespace':meta(Ns) end, MetaAttr = {cerl:c_atom(meta), cerl:abstract([Meta])}, Attrs = [X || {X} <- ets:tab2list(AttrsTable)], UniqueAttrs = lists:usort([ClojureAttr, MetaAttr | Attrs]), AllAttrs = [FileAttr, MappingsAttr, AliasesAttr | UniqueAttrs], Defs = [X || {_, X} <- ets:tab2list(FunsTable)], maybe_on_load(OnLoadTable, cerl:c_atom(Name), Exports, AllAttrs, Defs). add_module_info_functions(Module) -> {_, Funs} = module_info_funs(Module#module.name), add_functions(Funs, Module), add_exports([{module_info, 0}, {module_info, 1}], Module). -spec module_info_funs(module()) -> {[cerl:cerl()], [{cerl:cerl(), cerl:cerl()}]}. module_info_funs(Name) -> InfoName0 = cerl:c_fname(?MODULE_INFO, 0), InfoFun0 = cerl:c_fun( [] , cerl:c_call( cerl:c_atom(erlang) , cerl:c_atom(get_module_info) , [cerl:c_atom(Name)] ) ), InfoName1 = cerl:c_fname(?MODULE_INFO, 1), Arg = cerl:c_var(x), InfoFun1 = cerl:c_fun( [Arg] , cerl:c_call( cerl:c_atom(erlang) , cerl:c_atom(get_module_info) , [cerl:c_atom(Name), Arg] ) ), { [InfoName0, InfoName1] , [ {InfoName0, InfoFun0} , {InfoName1, InfoFun1} ] }. -spec maybe_on_load( ets:tid() , cerl:c_atom() , [cerl:c_var()] , [{cerl:c_atom(), cerl:cerl()}] , [cerl:c_fun()] ) -> cerl:c_module(). maybe_on_load(OnLoadTable, Name, Exports0, Attrs0, Defs0) -> case ets:info(OnLoadTable, size) of 0 -> ?DEBUG({no_on_load, cerl:atom_val(Name)}), cerl:c_module(Name, Exports0, Attrs0, Defs0); _ -> Attr = { cerl:c_atom(on_load) , cerl:abstract([{?ON_LOAD_FUNCTION, 0}]) }, FName = cerl:c_fname(?ON_LOAD_FUNCTION, 0), Fun = on_load_function(OnLoadTable), Def = {FName, Fun}, Attrs1 = lists:usort([Attr | Attrs0]), Defs1 = [Def | Defs0], cerl:c_module(Name, Exports0, Attrs1, Defs1) end. @private -spec on_load_function(ets:tid()) -> empty | cerl:cerl(). on_load_function(OnLoadTable) -> [Head | Tail] = [Expr || {_, Expr} <- lists:sort(ets:tab2list(OnLoadTable))], SeqFun = fun(X, Acc) -> cerl:c_seq(Acc, X) end, Body = lists:foldl(SeqFun, Head, Tail), cerl:c_fun([], cerl:c_seq(Body, cerl:c_atom(ok))). -spec new(string(), atom() | cerl:c_module()) -> clj_module(). new(Path, Name) when is_atom(Name), is_list(Path) -> FileAttr = {cerl:c_atom(file), cerl:abstract(Path)}, new(cerl:c_module(cerl:c_atom(Name), [], [FileAttr], [])); new(Path, #c_module{attrs = Attrs} = CoreModule) when is_list(Path) -> FileAttr = {cerl:c_atom(file), cerl:abstract(Path)}, new(CoreModule#c_module{attrs = [FileAttr | Attrs]}). -spec new(cerl:cerl()) -> clj_module(). new(CoreModule) -> Name = cerl:concrete(cerl:module_name(CoreModule)), Exports = [ {cerl:fname_id(E), cerl:fname_arity(E)} || E <- cerl:module_exports(CoreModule) ], AllAttrs = cerl:module_attrs(CoreModule), Funs = cerl:module_defs(CoreModule), {Attrs, Extracted} = extract_attrs(AllAttrs, [mappings, aliases, file]), Mappings = case maps:get(mappings, Extracted, #{}) of [V] -> V; V -> V end, Aliases = case maps:get(aliases, Extracted, #{}) of [X] -> X; X -> X end, Path = maps:get(file, Extracted, ""), TableOpts = [set, public, {keypos, 1}], Module = #module{ name = Name , source = Path , mappings = ets:new(mappings, TableOpts) , aliases = ets:new(aliases, TableOpts) , funs = ets:new(funs, TableOpts) , fake_funs = ets:new(fake_funs, TableOpts) , exports = ets:new(exports, TableOpts) , on_load = ets:new(on_load, TableOpts) , attrs = ets:new(attributes, TableOpts) }, Module = add_functions(Funs, Module), Module = add_mappings(maps:to_list(Mappings), Module), [add_alias(A, Ns, Module) || {A, Ns} <- maps:to_list(Aliases)], Module = add_attributes(Attrs, Module), OnLoadId = {?ON_LOAD_FUNCTION, 0}, case clj_utils:ets_get(Module#module.funs, OnLoadId) of ?NIL -> ok; {OnLoadId, {_OnLoadName, OnLoadFun}} -> Body = cerl:fun_body(OnLoadFun), add_on_load(Body, Module), true = ets:delete(Module#module.funs, OnLoadId) end, add_exports(Exports, Module). -spec function_id({cerl:cerl(), cerl:cerl()}) -> function_id(). function_id({Name, _}) -> {cerl:fname_id(Name), cerl:fname_arity(Name)}. -spec extract_attrs([{cerl:c_atom(), cerl:cerl()}], [atom()]) -> {[{cerl:c_atom(), cerl:cerl()}], map()}. extract_attrs(Attrs, Names) -> do_extract_attrs(Attrs, Names, [], #{}). do_extract_attrs([], _Names, NewAttrs, Extracted) -> {NewAttrs, Extracted}; do_extract_attrs( [{NameAbst, ValAbst} = Attr | Attrs] , Names , NewAttrs , Extracted ) -> Name = cerl:concrete(NameAbst), case lists:member(Name, Names) of true -> Val = cerl:concrete(ValAbst), do_extract_attrs(Attrs, Names, NewAttrs, Extracted#{Name => Val}); false -> do_extract_attrs(Attrs, Names, [Attr | NewAttrs], Extracted) end.
db4251456c7f59197965a054ba2494041580631fcb2470f4b02f5bba87a9cf2f
ocaml-explore/explore
test_toc.ml
open Explore.Toc let test_toc () = let toc_testable = Alcotest.testable pp equal in let s = Omd.of_string "# Top\n## Second\n### Third\n" in let correct = [ H (1, "Top"); H (2, "Second"); H (3, "Third") ] in Alcotest.(check toc_testable) "same toc" correct (toc s) let test_transform () = let pp ppf b = Format.pp_print_string ppf (Omd.to_html b) in let omd = Alcotest.testable pp Stdlib.( = ) in let s = Omd.of_string "# OCaml is great\nSome other text after" in let correct = Omd.of_string "# OCaml is great {#ocaml-is-great}\nSome other text after" in Alcotest.check omd "same omd ast" correct (transform s) let test_tree () = let tree = Alcotest.testable pre Stdlib.( = ) in let lst = [ H (1, "a"); H (2, "b"); H (3, "c"); H (2, "d") ] in let t = to_tree lst in let correct = Br ( H (0, ""), [ Br ( H (1, "a"), [ Br (H (2, "b"), [ Br (H (3, "c"), []) ]); Br (H (2, "d"), []) ] ); ] ) in Alcotest.check tree "same heading tree" correct t let tests = [ ("test_toc", `Quick, test_toc); ("test_transform", `Quick, test_transform); ("test_tree", `Quick, test_tree); ]
null
https://raw.githubusercontent.com/ocaml-explore/explore/117768b378959f18a8d818f37779a750e90f3438/explore/tests/test_toc.ml
ocaml
open Explore.Toc let test_toc () = let toc_testable = Alcotest.testable pp equal in let s = Omd.of_string "# Top\n## Second\n### Third\n" in let correct = [ H (1, "Top"); H (2, "Second"); H (3, "Third") ] in Alcotest.(check toc_testable) "same toc" correct (toc s) let test_transform () = let pp ppf b = Format.pp_print_string ppf (Omd.to_html b) in let omd = Alcotest.testable pp Stdlib.( = ) in let s = Omd.of_string "# OCaml is great\nSome other text after" in let correct = Omd.of_string "# OCaml is great {#ocaml-is-great}\nSome other text after" in Alcotest.check omd "same omd ast" correct (transform s) let test_tree () = let tree = Alcotest.testable pre Stdlib.( = ) in let lst = [ H (1, "a"); H (2, "b"); H (3, "c"); H (2, "d") ] in let t = to_tree lst in let correct = Br ( H (0, ""), [ Br ( H (1, "a"), [ Br (H (2, "b"), [ Br (H (3, "c"), []) ]); Br (H (2, "d"), []) ] ); ] ) in Alcotest.check tree "same heading tree" correct t let tests = [ ("test_toc", `Quick, test_toc); ("test_transform", `Quick, test_transform); ("test_tree", `Quick, test_tree); ]
fd902794580b2b8acb2efbd066a60dd5f704bfe851a84495aae70da5e91999f1
DavidAlphaFox/RabbitMQ
rabbit_framing_amqp_0_9_1.erl
Autogenerated code . Do not edit . %% The contents of this file are subject to the Mozilla Public License Version 1.1 ( the " License " ) ; you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% at / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% -module(rabbit_framing_amqp_0_9_1). -include("rabbit_framing.hrl"). -export([version/0]). -export([lookup_method_name/1]). -export([lookup_class_name/1]). -export([method_id/1]). -export([method_has_content/1]). -export([is_method_synchronous/1]). -export([method_record/1]). -export([method_fieldnames/1]). -export([decode_method_fields/2]). -export([decode_properties/2]). -export([encode_method_fields/1]). -export([encode_properties/1]). -export([lookup_amqp_exception/1]). -export([amqp_exception/1]). %% Various types -ifdef(use_specs). -export_type([amqp_field_type/0, amqp_property_type/0, amqp_table/0, amqp_array/0, amqp_value/0, amqp_method_name/0, amqp_method/0, amqp_method_record/0, amqp_method_field_name/0, amqp_property_record/0, amqp_exception/0, amqp_exception_code/0, amqp_class_id/0]). -type(amqp_field_type() :: 'longstr' | 'signedint' | 'decimal' | 'timestamp' | 'table' | 'byte' | 'double' | 'float' | 'long' | 'short' | 'bool' | 'binary' | 'void' | 'array'). -type(amqp_property_type() :: 'shortstr' | 'longstr' | 'octet' | 'short' | 'long' | 'longlong' | 'timestamp' | 'bit' | 'table'). -type(amqp_table() :: [{binary(), amqp_field_type(), amqp_value()}]). -type(amqp_array() :: [{amqp_field_type(), amqp_value()}]). -type(amqp_value() :: binary() | % longstr integer() | % signedint {non_neg_integer(), non_neg_integer()} | % decimal amqp_table() | amqp_array() | byte() | % byte float() | % double integer() | % long integer() | % short boolean() | % bool binary() | % binary 'undefined' | % void non_neg_integer() % timestamp ). -type(amqp_method_name() :: ( 'connection.start' | 'connection.start_ok' | 'connection.secure' | 'connection.secure_ok' | 'connection.tune' | 'connection.tune_ok' | 'connection.open' | 'connection.open_ok' | 'connection.close' | 'connection.close_ok' | 'connection.blocked' | 'connection.unblocked' | 'channel.open' | 'channel.open_ok' | 'channel.flow' | 'channel.flow_ok' | 'channel.close' | 'channel.close_ok' | 'access.request' | 'access.request_ok' | 'exchange.declare' | 'exchange.declare_ok' | 'exchange.delete' | 'exchange.delete_ok' | 'exchange.bind' | 'exchange.bind_ok' | 'exchange.unbind' | 'exchange.unbind_ok' | 'queue.declare' | 'queue.declare_ok' | 'queue.bind' | 'queue.bind_ok' | 'queue.purge' | 'queue.purge_ok' | 'queue.delete' | 'queue.delete_ok' | 'queue.unbind' | 'queue.unbind_ok' | 'basic.qos' | 'basic.qos_ok' | 'basic.consume' | 'basic.consume_ok' | 'basic.cancel' | 'basic.cancel_ok' | 'basic.publish' | 'basic.return' | 'basic.deliver' | 'basic.get' | 'basic.get_ok' | 'basic.get_empty' | 'basic.ack' | 'basic.reject' | 'basic.recover_async' | 'basic.recover' | 'basic.recover_ok' | 'basic.nack' | 'basic.credit' | 'basic.credit_ok' | 'basic.credit_drained' | 'tx.select' | 'tx.select_ok' | 'tx.commit' | 'tx.commit_ok' | 'tx.rollback' | 'tx.rollback_ok' | 'confirm.select' | 'confirm.select_ok' )). -type(amqp_method() :: ( {10, 10} | {10, 11} | {10, 20} | {10, 21} | {10, 30} | {10, 31} | {10, 40} | {10, 41} | {10, 50} | {10, 51} | {10, 60} | {10, 61} | {20, 10} | {20, 11} | {20, 20} | {20, 21} | {20, 40} | {20, 41} | {30, 10} | {30, 11} | {40, 10} | {40, 11} | {40, 20} | {40, 21} | {40, 30} | {40, 31} | {40, 40} | {40, 51} | {50, 10} | {50, 11} | {50, 20} | {50, 21} | {50, 30} | {50, 31} | {50, 40} | {50, 41} | {50, 50} | {50, 51} | {60, 10} | {60, 11} | {60, 20} | {60, 21} | {60, 30} | {60, 31} | {60, 40} | {60, 50} | {60, 60} | {60, 70} | {60, 71} | {60, 72} | {60, 80} | {60, 90} | {60, 100} | {60, 110} | {60, 111} | {60, 120} | {60, 200} | {60, 201} | {60, 202} | {90, 10} | {90, 11} | {90, 20} | {90, 21} | {90, 30} | {90, 31} | {85, 10} | {85, 11} )). -type(amqp_method_record() :: ( #'connection.start'{} | #'connection.start_ok'{} | #'connection.secure'{} | #'connection.secure_ok'{} | #'connection.tune'{} | #'connection.tune_ok'{} | #'connection.open'{} | #'connection.open_ok'{} | #'connection.close'{} | #'connection.close_ok'{} | #'connection.blocked'{} | #'connection.unblocked'{} | #'channel.open'{} | #'channel.open_ok'{} | #'channel.flow'{} | #'channel.flow_ok'{} | #'channel.close'{} | #'channel.close_ok'{} | #'access.request'{} | #'access.request_ok'{} | #'exchange.declare'{} | #'exchange.declare_ok'{} | #'exchange.delete'{} | #'exchange.delete_ok'{} | #'exchange.bind'{} | #'exchange.bind_ok'{} | #'exchange.unbind'{} | #'exchange.unbind_ok'{} | #'queue.declare'{} | #'queue.declare_ok'{} | #'queue.bind'{} | #'queue.bind_ok'{} | #'queue.purge'{} | #'queue.purge_ok'{} | #'queue.delete'{} | #'queue.delete_ok'{} | #'queue.unbind'{} | #'queue.unbind_ok'{} | #'basic.qos'{} | #'basic.qos_ok'{} | #'basic.consume'{} | #'basic.consume_ok'{} | #'basic.cancel'{} | #'basic.cancel_ok'{} | #'basic.publish'{} | #'basic.return'{} | #'basic.deliver'{} | #'basic.get'{} | #'basic.get_ok'{} | #'basic.get_empty'{} | #'basic.ack'{} | #'basic.reject'{} | #'basic.recover_async'{} | #'basic.recover'{} | #'basic.recover_ok'{} | #'basic.nack'{} | #'basic.credit'{} | #'basic.credit_ok'{} | #'basic.credit_drained'{} | #'tx.select'{} | #'tx.select_ok'{} | #'tx.commit'{} | #'tx.commit_ok'{} | #'tx.rollback'{} | #'tx.rollback_ok'{} | #'confirm.select'{} | #'confirm.select_ok'{} )). -type(amqp_method_field_name() :: ( nowait | ticket | nowait | queue | passive | durable | exclusive | auto_delete | client_properties | prefetch_count | nowait | arguments | delivery_tag | multiple | queue | response | message_count | consumer_tag | consumer_count | version_major | version_minor | ticket | queue | locales | delivery_tag | cluster_id | routing_key | message_count | nowait | arguments | response | locale | requeue | redelivered | challenge | ticket | queue | nowait | channel_max | reply_text | frame_max | consumer_tag | heartbeat | exchange | consumer_tag | available | ticket | channel_max | frame_max | heartbeat | if_unused | delivery_tag | ticket | virtual_host | capabilities | insist | known_hosts | consumer_tag | ticket | reply_code | queue | reply_text | class_id | credit | method_id | routing_key | arguments | queue | exchange | reason | nowait | out_of_band | exchange | channel_id | ticket | prefetch_size | active | consumer_tag | credit_drained | global | mechanism | requeue | active | queue | routing_key | reply_code | reply_text | class_id | method_id | consumer_tag | mandatory | no_local | no_ack | no_ack | realm | routing_key | exclusive | passive | active | exclusive | write | message_count | read | ticket | consumer_tag | nowait | ticket | drain | exchange | requeue | type | passive | durable | auto_delete | arguments | delivery_tag | internal | nowait | delivery_tag | arguments | immediate | ticket | ticket | exchange | if_unused | nowait | routing_key | ticket | server_properties | destination | queue | source | routing_key | nowait | arguments | multiple | exchange | mechanisms | ticket | destination | source | routing_key | requeue | nowait | exchange | arguments | if_empty | redelivered | reply_code | exchange | routing_key | message_count )). -type(amqp_property_record() :: ( #'P_connection'{} | #'P_channel'{} | #'P_access'{} | #'P_exchange'{} | #'P_queue'{} | #'P_basic'{} | #'P_tx'{} | #'P_confirm'{} )). -type(amqp_exception() :: ( 'frame_method' | 'frame_header' | 'frame_body' | 'frame_heartbeat' | 'frame_min_size' | 'frame_end' | 'reply_success' | 'content_too_large' | 'no_route' | 'no_consumers' | 'access_refused' | 'not_found' | 'resource_locked' | 'precondition_failed' | 'connection_forced' | 'invalid_path' | 'frame_error' | 'syntax_error' | 'command_invalid' | 'channel_error' | 'unexpected_frame' | 'resource_error' | 'not_allowed' | 'not_implemented' | 'internal_error' )). -type(amqp_exception_code() :: ( 1 | 2 | 3 | 8 | 4096 | 206 | 200 | 311 | 312 | 313 | 403 | 404 | 405 | 406 | 320 | 402 | 501 | 502 | 503 | 504 | 505 | 506 | 530 | 540 | 541 )). -type(amqp_class_id() :: ( 40 | 10 | 50 | 20 | 85 | 90 | 60 | 30 )). -type(amqp_class_name() :: ( 'connection' | 'channel' | 'access' | 'exchange' | 'queue' | 'basic' | 'tx' | 'confirm' )). use_specs %% Method signatures -ifdef(use_specs). -spec(version/0 :: () -> {non_neg_integer(), non_neg_integer(), non_neg_integer()}). -spec(lookup_method_name/1 :: (amqp_method()) -> amqp_method_name()). -spec(lookup_class_name/1 :: (amqp_class_id()) -> amqp_class_name()). -spec(method_id/1 :: (amqp_method_name()) -> amqp_method()). -spec(method_has_content/1 :: (amqp_method_name()) -> boolean()). -spec(is_method_synchronous/1 :: (amqp_method_record()) -> boolean()). -spec(method_record/1 :: (amqp_method_name()) -> amqp_method_record()). -spec(method_fieldnames/1 :: (amqp_method_name()) -> [amqp_method_field_name()]). -spec(decode_method_fields/2 :: (amqp_method_name(), binary()) -> amqp_method_record() | rabbit_types:connection_exit()). -spec(decode_properties/2 :: (non_neg_integer(), binary()) -> amqp_property_record()). -spec(encode_method_fields/1 :: (amqp_method_record()) -> binary()). -spec(encode_properties/1 :: (amqp_property_record()) -> binary()). -spec(lookup_amqp_exception/1 :: (amqp_exception()) -> {boolean(), amqp_exception_code(), binary()}). -spec(amqp_exception/1 :: (amqp_exception_code()) -> amqp_exception()). use_specs bitvalue(true) -> 1; bitvalue(false) -> 0; bitvalue(undefined) -> 0. shortstr_size(S) -> case size(S) of Len when Len =< 255 -> Len; _ -> exit(method_field_shortstr_overflow) end. -define(SHORTSTR_VAL(R, L, V, X), begin <<L:8/unsigned, V:L/binary, X/binary>> = R, {V, X} end). -define(LONGSTR_VAL(R, L, V, X), begin <<L:32/unsigned, V:L/binary, X/binary>> = R, {V, X} end). -define(SHORT_VAL(R, L, V, X), begin <<V:8/unsigned, X/binary>> = R, {V, X} end). -define(LONG_VAL(R, L, V, X), begin <<V:32/unsigned, X/binary>> = R, {V, X} end). -define(LONGLONG_VAL(R, L, V, X), begin <<V:64/unsigned, X/binary>> = R, {V, X} end). -define(OCTET_VAL(R, L, V, X), begin <<V:8/unsigned, X/binary>> = R, {V, X} end). -define(TABLE_VAL(R, L, V, X), begin <<L:32/unsigned, V:L/binary, X/binary>> = R, {rabbit_binary_parser:parse_table(V), X} end). -define(TIMESTAMP_VAL(R, L, V, X), begin <<V:64/unsigned, X/binary>> = R, {V, X} end). -define(SHORTSTR_PROP(X, L), begin L = size(X), if L < 256 -> <<L:8, X:L/binary>>; true -> exit(content_properties_shortstr_overflow) end end). -define(LONGSTR_PROP(X, L), begin L = size(X), <<L:32, X:L/binary>> end). -define(OCTET_PROP(X, L), <<X:8/unsigned>>). -define(SHORT_PROP(X, L), <<X:16/unsigned>>). -define(LONG_PROP(X, L), <<X:32/unsigned>>). -define(LONGLONG_PROP(X, L), <<X:64/unsigned>>). -define(TIMESTAMP_PROP(X, L), <<X:64/unsigned>>). -define(TABLE_PROP(X, T), begin T = rabbit_binary_generator:generate_table(X), <<(size(T)):32, T/binary>> end). version() -> {0, 9, 1}. lookup_method_name({10, 10}) -> 'connection.start'; lookup_method_name({10, 11}) -> 'connection.start_ok'; lookup_method_name({10, 20}) -> 'connection.secure'; lookup_method_name({10, 21}) -> 'connection.secure_ok'; lookup_method_name({10, 30}) -> 'connection.tune'; lookup_method_name({10, 31}) -> 'connection.tune_ok'; lookup_method_name({10, 40}) -> 'connection.open'; lookup_method_name({10, 41}) -> 'connection.open_ok'; lookup_method_name({10, 50}) -> 'connection.close'; lookup_method_name({10, 51}) -> 'connection.close_ok'; lookup_method_name({10, 60}) -> 'connection.blocked'; lookup_method_name({10, 61}) -> 'connection.unblocked'; lookup_method_name({20, 10}) -> 'channel.open'; lookup_method_name({20, 11}) -> 'channel.open_ok'; lookup_method_name({20, 20}) -> 'channel.flow'; lookup_method_name({20, 21}) -> 'channel.flow_ok'; lookup_method_name({20, 40}) -> 'channel.close'; lookup_method_name({20, 41}) -> 'channel.close_ok'; lookup_method_name({30, 10}) -> 'access.request'; lookup_method_name({30, 11}) -> 'access.request_ok'; lookup_method_name({40, 10}) -> 'exchange.declare'; lookup_method_name({40, 11}) -> 'exchange.declare_ok'; lookup_method_name({40, 20}) -> 'exchange.delete'; lookup_method_name({40, 21}) -> 'exchange.delete_ok'; lookup_method_name({40, 30}) -> 'exchange.bind'; lookup_method_name({40, 31}) -> 'exchange.bind_ok'; lookup_method_name({40, 40}) -> 'exchange.unbind'; lookup_method_name({40, 51}) -> 'exchange.unbind_ok'; lookup_method_name({50, 10}) -> 'queue.declare'; lookup_method_name({50, 11}) -> 'queue.declare_ok'; lookup_method_name({50, 20}) -> 'queue.bind'; lookup_method_name({50, 21}) -> 'queue.bind_ok'; lookup_method_name({50, 30}) -> 'queue.purge'; lookup_method_name({50, 31}) -> 'queue.purge_ok'; lookup_method_name({50, 40}) -> 'queue.delete'; lookup_method_name({50, 41}) -> 'queue.delete_ok'; lookup_method_name({50, 50}) -> 'queue.unbind'; lookup_method_name({50, 51}) -> 'queue.unbind_ok'; lookup_method_name({60, 10}) -> 'basic.qos'; lookup_method_name({60, 11}) -> 'basic.qos_ok'; lookup_method_name({60, 20}) -> 'basic.consume'; lookup_method_name({60, 21}) -> 'basic.consume_ok'; lookup_method_name({60, 30}) -> 'basic.cancel'; lookup_method_name({60, 31}) -> 'basic.cancel_ok'; lookup_method_name({60, 40}) -> 'basic.publish'; lookup_method_name({60, 50}) -> 'basic.return'; lookup_method_name({60, 60}) -> 'basic.deliver'; lookup_method_name({60, 70}) -> 'basic.get'; lookup_method_name({60, 71}) -> 'basic.get_ok'; lookup_method_name({60, 72}) -> 'basic.get_empty'; lookup_method_name({60, 80}) -> 'basic.ack'; lookup_method_name({60, 90}) -> 'basic.reject'; lookup_method_name({60, 100}) -> 'basic.recover_async'; lookup_method_name({60, 110}) -> 'basic.recover'; lookup_method_name({60, 111}) -> 'basic.recover_ok'; lookup_method_name({60, 120}) -> 'basic.nack'; lookup_method_name({60, 200}) -> 'basic.credit'; lookup_method_name({60, 201}) -> 'basic.credit_ok'; lookup_method_name({60, 202}) -> 'basic.credit_drained'; lookup_method_name({90, 10}) -> 'tx.select'; lookup_method_name({90, 11}) -> 'tx.select_ok'; lookup_method_name({90, 20}) -> 'tx.commit'; lookup_method_name({90, 21}) -> 'tx.commit_ok'; lookup_method_name({90, 30}) -> 'tx.rollback'; lookup_method_name({90, 31}) -> 'tx.rollback_ok'; lookup_method_name({85, 10}) -> 'confirm.select'; lookup_method_name({85, 11}) -> 'confirm.select_ok'; lookup_method_name({_ClassId, _MethodId} = Id) -> exit({unknown_method_id, Id}). lookup_class_name(10) -> 'connection'; lookup_class_name(20) -> 'channel'; lookup_class_name(30) -> 'access'; lookup_class_name(40) -> 'exchange'; lookup_class_name(50) -> 'queue'; lookup_class_name(60) -> 'basic'; lookup_class_name(90) -> 'tx'; lookup_class_name(85) -> 'confirm'; lookup_class_name(ClassId) -> exit({unknown_class_id, ClassId}). method_id('connection.start') -> {10, 10}; method_id('connection.start_ok') -> {10, 11}; method_id('connection.secure') -> {10, 20}; method_id('connection.secure_ok') -> {10, 21}; method_id('connection.tune') -> {10, 30}; method_id('connection.tune_ok') -> {10, 31}; method_id('connection.open') -> {10, 40}; method_id('connection.open_ok') -> {10, 41}; method_id('connection.close') -> {10, 50}; method_id('connection.close_ok') -> {10, 51}; method_id('connection.blocked') -> {10, 60}; method_id('connection.unblocked') -> {10, 61}; method_id('channel.open') -> {20, 10}; method_id('channel.open_ok') -> {20, 11}; method_id('channel.flow') -> {20, 20}; method_id('channel.flow_ok') -> {20, 21}; method_id('channel.close') -> {20, 40}; method_id('channel.close_ok') -> {20, 41}; method_id('access.request') -> {30, 10}; method_id('access.request_ok') -> {30, 11}; method_id('exchange.declare') -> {40, 10}; method_id('exchange.declare_ok') -> {40, 11}; method_id('exchange.delete') -> {40, 20}; method_id('exchange.delete_ok') -> {40, 21}; method_id('exchange.bind') -> {40, 30}; method_id('exchange.bind_ok') -> {40, 31}; method_id('exchange.unbind') -> {40, 40}; method_id('exchange.unbind_ok') -> {40, 51}; method_id('queue.declare') -> {50, 10}; method_id('queue.declare_ok') -> {50, 11}; method_id('queue.bind') -> {50, 20}; method_id('queue.bind_ok') -> {50, 21}; method_id('queue.purge') -> {50, 30}; method_id('queue.purge_ok') -> {50, 31}; method_id('queue.delete') -> {50, 40}; method_id('queue.delete_ok') -> {50, 41}; method_id('queue.unbind') -> {50, 50}; method_id('queue.unbind_ok') -> {50, 51}; method_id('basic.qos') -> {60, 10}; method_id('basic.qos_ok') -> {60, 11}; method_id('basic.consume') -> {60, 20}; method_id('basic.consume_ok') -> {60, 21}; method_id('basic.cancel') -> {60, 30}; method_id('basic.cancel_ok') -> {60, 31}; method_id('basic.publish') -> {60, 40}; method_id('basic.return') -> {60, 50}; method_id('basic.deliver') -> {60, 60}; method_id('basic.get') -> {60, 70}; method_id('basic.get_ok') -> {60, 71}; method_id('basic.get_empty') -> {60, 72}; method_id('basic.ack') -> {60, 80}; method_id('basic.reject') -> {60, 90}; method_id('basic.recover_async') -> {60, 100}; method_id('basic.recover') -> {60, 110}; method_id('basic.recover_ok') -> {60, 111}; method_id('basic.nack') -> {60, 120}; method_id('basic.credit') -> {60, 200}; method_id('basic.credit_ok') -> {60, 201}; method_id('basic.credit_drained') -> {60, 202}; method_id('tx.select') -> {90, 10}; method_id('tx.select_ok') -> {90, 11}; method_id('tx.commit') -> {90, 20}; method_id('tx.commit_ok') -> {90, 21}; method_id('tx.rollback') -> {90, 30}; method_id('tx.rollback_ok') -> {90, 31}; method_id('confirm.select') -> {85, 10}; method_id('confirm.select_ok') -> {85, 11}; method_id(Name) -> exit({unknown_method_name, Name}). method_has_content('connection.start') -> false; method_has_content('connection.start_ok') -> false; method_has_content('connection.secure') -> false; method_has_content('connection.secure_ok') -> false; method_has_content('connection.tune') -> false; method_has_content('connection.tune_ok') -> false; method_has_content('connection.open') -> false; method_has_content('connection.open_ok') -> false; method_has_content('connection.close') -> false; method_has_content('connection.close_ok') -> false; method_has_content('connection.blocked') -> false; method_has_content('connection.unblocked') -> false; method_has_content('channel.open') -> false; method_has_content('channel.open_ok') -> false; method_has_content('channel.flow') -> false; method_has_content('channel.flow_ok') -> false; method_has_content('channel.close') -> false; method_has_content('channel.close_ok') -> false; method_has_content('access.request') -> false; method_has_content('access.request_ok') -> false; method_has_content('exchange.declare') -> false; method_has_content('exchange.declare_ok') -> false; method_has_content('exchange.delete') -> false; method_has_content('exchange.delete_ok') -> false; method_has_content('exchange.bind') -> false; method_has_content('exchange.bind_ok') -> false; method_has_content('exchange.unbind') -> false; method_has_content('exchange.unbind_ok') -> false; method_has_content('queue.declare') -> false; method_has_content('queue.declare_ok') -> false; method_has_content('queue.bind') -> false; method_has_content('queue.bind_ok') -> false; method_has_content('queue.purge') -> false; method_has_content('queue.purge_ok') -> false; method_has_content('queue.delete') -> false; method_has_content('queue.delete_ok') -> false; method_has_content('queue.unbind') -> false; method_has_content('queue.unbind_ok') -> false; method_has_content('basic.qos') -> false; method_has_content('basic.qos_ok') -> false; method_has_content('basic.consume') -> false; method_has_content('basic.consume_ok') -> false; method_has_content('basic.cancel') -> false; method_has_content('basic.cancel_ok') -> false; method_has_content('basic.publish') -> true; method_has_content('basic.return') -> true; method_has_content('basic.deliver') -> true; method_has_content('basic.get') -> false; method_has_content('basic.get_ok') -> true; method_has_content('basic.get_empty') -> false; method_has_content('basic.ack') -> false; method_has_content('basic.reject') -> false; method_has_content('basic.recover_async') -> false; method_has_content('basic.recover') -> false; method_has_content('basic.recover_ok') -> false; method_has_content('basic.nack') -> false; method_has_content('basic.credit') -> false; method_has_content('basic.credit_ok') -> false; method_has_content('basic.credit_drained') -> false; method_has_content('tx.select') -> false; method_has_content('tx.select_ok') -> false; method_has_content('tx.commit') -> false; method_has_content('tx.commit_ok') -> false; method_has_content('tx.rollback') -> false; method_has_content('tx.rollback_ok') -> false; method_has_content('confirm.select') -> false; method_has_content('confirm.select_ok') -> false; method_has_content(Name) -> exit({unknown_method_name, Name}). is_method_synchronous(#'connection.start'{}) -> true; is_method_synchronous(#'connection.start_ok'{}) -> false; is_method_synchronous(#'connection.secure'{}) -> true; is_method_synchronous(#'connection.secure_ok'{}) -> false; is_method_synchronous(#'connection.tune'{}) -> true; is_method_synchronous(#'connection.tune_ok'{}) -> false; is_method_synchronous(#'connection.open'{}) -> true; is_method_synchronous(#'connection.open_ok'{}) -> false; is_method_synchronous(#'connection.close'{}) -> true; is_method_synchronous(#'connection.close_ok'{}) -> false; is_method_synchronous(#'connection.blocked'{}) -> false; is_method_synchronous(#'connection.unblocked'{}) -> false; is_method_synchronous(#'channel.open'{}) -> true; is_method_synchronous(#'channel.open_ok'{}) -> false; is_method_synchronous(#'channel.flow'{}) -> true; is_method_synchronous(#'channel.flow_ok'{}) -> false; is_method_synchronous(#'channel.close'{}) -> true; is_method_synchronous(#'channel.close_ok'{}) -> false; is_method_synchronous(#'access.request'{}) -> true; is_method_synchronous(#'access.request_ok'{}) -> false; is_method_synchronous(#'exchange.declare'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'exchange.declare_ok'{}) -> false; is_method_synchronous(#'exchange.delete'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'exchange.delete_ok'{}) -> false; is_method_synchronous(#'exchange.bind'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'exchange.bind_ok'{}) -> false; is_method_synchronous(#'exchange.unbind'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'exchange.unbind_ok'{}) -> false; is_method_synchronous(#'queue.declare'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'queue.declare_ok'{}) -> false; is_method_synchronous(#'queue.bind'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'queue.bind_ok'{}) -> false; is_method_synchronous(#'queue.purge'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'queue.purge_ok'{}) -> false; is_method_synchronous(#'queue.delete'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'queue.delete_ok'{}) -> false; is_method_synchronous(#'queue.unbind'{}) -> true; is_method_synchronous(#'queue.unbind_ok'{}) -> false; is_method_synchronous(#'basic.qos'{}) -> true; is_method_synchronous(#'basic.qos_ok'{}) -> false; is_method_synchronous(#'basic.consume'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'basic.consume_ok'{}) -> false; is_method_synchronous(#'basic.cancel'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'basic.cancel_ok'{}) -> false; is_method_synchronous(#'basic.publish'{}) -> false; is_method_synchronous(#'basic.return'{}) -> false; is_method_synchronous(#'basic.deliver'{}) -> false; is_method_synchronous(#'basic.get'{}) -> true; is_method_synchronous(#'basic.get_ok'{}) -> false; is_method_synchronous(#'basic.get_empty'{}) -> false; is_method_synchronous(#'basic.ack'{}) -> false; is_method_synchronous(#'basic.reject'{}) -> false; is_method_synchronous(#'basic.recover_async'{}) -> false; is_method_synchronous(#'basic.recover'{}) -> true; is_method_synchronous(#'basic.recover_ok'{}) -> false; is_method_synchronous(#'basic.nack'{}) -> false; is_method_synchronous(#'basic.credit'{}) -> true; is_method_synchronous(#'basic.credit_ok'{}) -> false; is_method_synchronous(#'basic.credit_drained'{}) -> false; is_method_synchronous(#'tx.select'{}) -> true; is_method_synchronous(#'tx.select_ok'{}) -> false; is_method_synchronous(#'tx.commit'{}) -> true; is_method_synchronous(#'tx.commit_ok'{}) -> false; is_method_synchronous(#'tx.rollback'{}) -> true; is_method_synchronous(#'tx.rollback_ok'{}) -> false; is_method_synchronous(#'confirm.select'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'confirm.select_ok'{}) -> false; is_method_synchronous(Name) -> exit({unknown_method_name, Name}). method_record('connection.start') -> #'connection.start'{}; method_record('connection.start_ok') -> #'connection.start_ok'{}; method_record('connection.secure') -> #'connection.secure'{}; method_record('connection.secure_ok') -> #'connection.secure_ok'{}; method_record('connection.tune') -> #'connection.tune'{}; method_record('connection.tune_ok') -> #'connection.tune_ok'{}; method_record('connection.open') -> #'connection.open'{}; method_record('connection.open_ok') -> #'connection.open_ok'{}; method_record('connection.close') -> #'connection.close'{}; method_record('connection.close_ok') -> #'connection.close_ok'{}; method_record('connection.blocked') -> #'connection.blocked'{}; method_record('connection.unblocked') -> #'connection.unblocked'{}; method_record('channel.open') -> #'channel.open'{}; method_record('channel.open_ok') -> #'channel.open_ok'{}; method_record('channel.flow') -> #'channel.flow'{}; method_record('channel.flow_ok') -> #'channel.flow_ok'{}; method_record('channel.close') -> #'channel.close'{}; method_record('channel.close_ok') -> #'channel.close_ok'{}; method_record('access.request') -> #'access.request'{}; method_record('access.request_ok') -> #'access.request_ok'{}; method_record('exchange.declare') -> #'exchange.declare'{}; method_record('exchange.declare_ok') -> #'exchange.declare_ok'{}; method_record('exchange.delete') -> #'exchange.delete'{}; method_record('exchange.delete_ok') -> #'exchange.delete_ok'{}; method_record('exchange.bind') -> #'exchange.bind'{}; method_record('exchange.bind_ok') -> #'exchange.bind_ok'{}; method_record('exchange.unbind') -> #'exchange.unbind'{}; method_record('exchange.unbind_ok') -> #'exchange.unbind_ok'{}; method_record('queue.declare') -> #'queue.declare'{}; method_record('queue.declare_ok') -> #'queue.declare_ok'{}; method_record('queue.bind') -> #'queue.bind'{}; method_record('queue.bind_ok') -> #'queue.bind_ok'{}; method_record('queue.purge') -> #'queue.purge'{}; method_record('queue.purge_ok') -> #'queue.purge_ok'{}; method_record('queue.delete') -> #'queue.delete'{}; method_record('queue.delete_ok') -> #'queue.delete_ok'{}; method_record('queue.unbind') -> #'queue.unbind'{}; method_record('queue.unbind_ok') -> #'queue.unbind_ok'{}; method_record('basic.qos') -> #'basic.qos'{}; method_record('basic.qos_ok') -> #'basic.qos_ok'{}; method_record('basic.consume') -> #'basic.consume'{}; method_record('basic.consume_ok') -> #'basic.consume_ok'{}; method_record('basic.cancel') -> #'basic.cancel'{}; method_record('basic.cancel_ok') -> #'basic.cancel_ok'{}; method_record('basic.publish') -> #'basic.publish'{}; method_record('basic.return') -> #'basic.return'{}; method_record('basic.deliver') -> #'basic.deliver'{}; method_record('basic.get') -> #'basic.get'{}; method_record('basic.get_ok') -> #'basic.get_ok'{}; method_record('basic.get_empty') -> #'basic.get_empty'{}; method_record('basic.ack') -> #'basic.ack'{}; method_record('basic.reject') -> #'basic.reject'{}; method_record('basic.recover_async') -> #'basic.recover_async'{}; method_record('basic.recover') -> #'basic.recover'{}; method_record('basic.recover_ok') -> #'basic.recover_ok'{}; method_record('basic.nack') -> #'basic.nack'{}; method_record('basic.credit') -> #'basic.credit'{}; method_record('basic.credit_ok') -> #'basic.credit_ok'{}; method_record('basic.credit_drained') -> #'basic.credit_drained'{}; method_record('tx.select') -> #'tx.select'{}; method_record('tx.select_ok') -> #'tx.select_ok'{}; method_record('tx.commit') -> #'tx.commit'{}; method_record('tx.commit_ok') -> #'tx.commit_ok'{}; method_record('tx.rollback') -> #'tx.rollback'{}; method_record('tx.rollback_ok') -> #'tx.rollback_ok'{}; method_record('confirm.select') -> #'confirm.select'{}; method_record('confirm.select_ok') -> #'confirm.select_ok'{}; method_record(Name) -> exit({unknown_method_name, Name}). method_fieldnames('connection.start') -> [version_major, version_minor, server_properties, mechanisms, locales]; method_fieldnames('connection.start_ok') -> [client_properties, mechanism, response, locale]; method_fieldnames('connection.secure') -> [challenge]; method_fieldnames('connection.secure_ok') -> [response]; method_fieldnames('connection.tune') -> [channel_max, frame_max, heartbeat]; method_fieldnames('connection.tune_ok') -> [channel_max, frame_max, heartbeat]; method_fieldnames('connection.open') -> [virtual_host, capabilities, insist]; method_fieldnames('connection.open_ok') -> [known_hosts]; method_fieldnames('connection.close') -> [reply_code, reply_text, class_id, method_id]; method_fieldnames('connection.close_ok') -> []; method_fieldnames('connection.blocked') -> [reason]; method_fieldnames('connection.unblocked') -> []; method_fieldnames('channel.open') -> [out_of_band]; method_fieldnames('channel.open_ok') -> [channel_id]; method_fieldnames('channel.flow') -> [active]; method_fieldnames('channel.flow_ok') -> [active]; method_fieldnames('channel.close') -> [reply_code, reply_text, class_id, method_id]; method_fieldnames('channel.close_ok') -> []; method_fieldnames('access.request') -> [realm, exclusive, passive, active, write, read]; method_fieldnames('access.request_ok') -> [ticket]; method_fieldnames('exchange.declare') -> [ticket, exchange, type, passive, durable, auto_delete, internal, nowait, arguments]; method_fieldnames('exchange.declare_ok') -> []; method_fieldnames('exchange.delete') -> [ticket, exchange, if_unused, nowait]; method_fieldnames('exchange.delete_ok') -> []; method_fieldnames('exchange.bind') -> [ticket, destination, source, routing_key, nowait, arguments]; method_fieldnames('exchange.bind_ok') -> []; method_fieldnames('exchange.unbind') -> [ticket, destination, source, routing_key, nowait, arguments]; method_fieldnames('exchange.unbind_ok') -> []; method_fieldnames('queue.declare') -> [ticket, queue, passive, durable, exclusive, auto_delete, nowait, arguments]; method_fieldnames('queue.declare_ok') -> [queue, message_count, consumer_count]; method_fieldnames('queue.bind') -> [ticket, queue, exchange, routing_key, nowait, arguments]; method_fieldnames('queue.bind_ok') -> []; method_fieldnames('queue.purge') -> [ticket, queue, nowait]; method_fieldnames('queue.purge_ok') -> [message_count]; method_fieldnames('queue.delete') -> [ticket, queue, if_unused, if_empty, nowait]; method_fieldnames('queue.delete_ok') -> [message_count]; method_fieldnames('queue.unbind') -> [ticket, queue, exchange, routing_key, arguments]; method_fieldnames('queue.unbind_ok') -> []; method_fieldnames('basic.qos') -> [prefetch_size, prefetch_count, global]; method_fieldnames('basic.qos_ok') -> []; method_fieldnames('basic.consume') -> [ticket, queue, consumer_tag, no_local, no_ack, exclusive, nowait, arguments]; method_fieldnames('basic.consume_ok') -> [consumer_tag]; method_fieldnames('basic.cancel') -> [consumer_tag, nowait]; method_fieldnames('basic.cancel_ok') -> [consumer_tag]; method_fieldnames('basic.publish') -> [ticket, exchange, routing_key, mandatory, immediate]; method_fieldnames('basic.return') -> [reply_code, reply_text, exchange, routing_key]; method_fieldnames('basic.deliver') -> [consumer_tag, delivery_tag, redelivered, exchange, routing_key]; method_fieldnames('basic.get') -> [ticket, queue, no_ack]; method_fieldnames('basic.get_ok') -> [delivery_tag, redelivered, exchange, routing_key, message_count]; method_fieldnames('basic.get_empty') -> [cluster_id]; method_fieldnames('basic.ack') -> [delivery_tag, multiple]; method_fieldnames('basic.reject') -> [delivery_tag, requeue]; method_fieldnames('basic.recover_async') -> [requeue]; method_fieldnames('basic.recover') -> [requeue]; method_fieldnames('basic.recover_ok') -> []; method_fieldnames('basic.nack') -> [delivery_tag, multiple, requeue]; method_fieldnames('basic.credit') -> [consumer_tag, credit, drain]; method_fieldnames('basic.credit_ok') -> [available]; method_fieldnames('basic.credit_drained') -> [consumer_tag, credit_drained]; method_fieldnames('tx.select') -> []; method_fieldnames('tx.select_ok') -> []; method_fieldnames('tx.commit') -> []; method_fieldnames('tx.commit_ok') -> []; method_fieldnames('tx.rollback') -> []; method_fieldnames('tx.rollback_ok') -> []; method_fieldnames('confirm.select') -> [nowait]; method_fieldnames('confirm.select_ok') -> []; method_fieldnames(Name) -> exit({unknown_method_name, Name}). decode_method_fields('connection.start', <<F0:8/unsigned, F1:8/unsigned, F2Len:32/unsigned, F2Tab:F2Len/binary, F3Len:32/unsigned, F3:F3Len/binary, F4Len:32/unsigned, F4:F4Len/binary>>) -> F2 = rabbit_binary_parser:parse_table(F2Tab), #'connection.start'{version_major = F0, version_minor = F1, server_properties = F2, mechanisms = F3, locales = F4}; decode_method_fields('connection.start_ok', <<F0Len:32/unsigned, F0Tab:F0Len/binary, F1Len:8/unsigned, F1:F1Len/binary, F2Len:32/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary>>) -> F0 = rabbit_binary_parser:parse_table(F0Tab), rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F3), #'connection.start_ok'{client_properties = F0, mechanism = F1, response = F2, locale = F3}; decode_method_fields('connection.secure', <<F0Len:32/unsigned, F0:F0Len/binary>>) -> #'connection.secure'{challenge = F0}; decode_method_fields('connection.secure_ok', <<F0Len:32/unsigned, F0:F0Len/binary>>) -> #'connection.secure_ok'{response = F0}; decode_method_fields('connection.tune', <<F0:16/unsigned, F1:32/unsigned, F2:16/unsigned>>) -> #'connection.tune'{channel_max = F0, frame_max = F1, heartbeat = F2}; decode_method_fields('connection.tune_ok', <<F0:16/unsigned, F1:32/unsigned, F2:16/unsigned>>) -> #'connection.tune_ok'{channel_max = F0, frame_max = F1, heartbeat = F2}; decode_method_fields('connection.open', <<F0Len:8/unsigned, F0:F0Len/binary, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F0), rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), #'connection.open'{virtual_host = F0, capabilities = F1, insist = F2}; decode_method_fields('connection.open_ok', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'connection.open_ok'{known_hosts = F0}; decode_method_fields('connection.close', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2:16/unsigned, F3:16/unsigned>>) -> rabbit_binary_parser:assert_utf8(F1), #'connection.close'{reply_code = F0, reply_text = F1, class_id = F2, method_id = F3}; decode_method_fields('connection.close_ok', <<>>) -> #'connection.close_ok'{}; decode_method_fields('connection.blocked', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'connection.blocked'{reason = F0}; decode_method_fields('connection.unblocked', <<>>) -> #'connection.unblocked'{}; decode_method_fields('channel.open', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'channel.open'{out_of_band = F0}; decode_method_fields('channel.open_ok', <<F0Len:32/unsigned, F0:F0Len/binary>>) -> #'channel.open_ok'{channel_id = F0}; decode_method_fields('channel.flow', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'channel.flow'{active = F0}; decode_method_fields('channel.flow_ok', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'channel.flow_ok'{active = F0}; decode_method_fields('channel.close', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2:16/unsigned, F3:16/unsigned>>) -> rabbit_binary_parser:assert_utf8(F1), #'channel.close'{reply_code = F0, reply_text = F1, class_id = F2, method_id = F3}; decode_method_fields('channel.close_ok', <<>>) -> #'channel.close_ok'{}; decode_method_fields('access.request', <<F0Len:8/unsigned, F0:F0Len/binary, F1Bits:8>>) -> rabbit_binary_parser:assert_utf8(F0), F1 = ((F1Bits band 1) /= 0), F2 = ((F1Bits band 2) /= 0), F3 = ((F1Bits band 4) /= 0), F4 = ((F1Bits band 8) /= 0), F5 = ((F1Bits band 16) /= 0), #'access.request'{realm = F0, exclusive = F1, passive = F2, active = F3, write = F4, read = F5}; decode_method_fields('access.request_ok', <<F0:16/unsigned>>) -> #'access.request_ok'{ticket = F0}; decode_method_fields('exchange.declare', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8, F8Len:32/unsigned, F8Tab:F8Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), F3 = ((F3Bits band 1) /= 0), F4 = ((F3Bits band 2) /= 0), F5 = ((F3Bits band 4) /= 0), F6 = ((F3Bits band 8) /= 0), F7 = ((F3Bits band 16) /= 0), F8 = rabbit_binary_parser:parse_table(F8Tab), #'exchange.declare'{ticket = F0, exchange = F1, type = F2, passive = F3, durable = F4, auto_delete = F5, internal = F6, nowait = F7, arguments = F8}; decode_method_fields('exchange.declare_ok', <<>>) -> #'exchange.declare_ok'{}; decode_method_fields('exchange.delete', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), F3 = ((F2Bits band 2) /= 0), #'exchange.delete'{ticket = F0, exchange = F1, if_unused = F2, nowait = F3}; decode_method_fields('exchange.delete_ok', <<>>) -> #'exchange.delete_ok'{}; decode_method_fields('exchange.bind', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), rabbit_binary_parser:assert_utf8(F3), F4 = ((F4Bits band 1) /= 0), F5 = rabbit_binary_parser:parse_table(F5Tab), #'exchange.bind'{ticket = F0, destination = F1, source = F2, routing_key = F3, nowait = F4, arguments = F5}; decode_method_fields('exchange.bind_ok', <<>>) -> #'exchange.bind_ok'{}; decode_method_fields('exchange.unbind', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), rabbit_binary_parser:assert_utf8(F3), F4 = ((F4Bits band 1) /= 0), F5 = rabbit_binary_parser:parse_table(F5Tab), #'exchange.unbind'{ticket = F0, destination = F1, source = F2, routing_key = F3, nowait = F4, arguments = F5}; decode_method_fields('exchange.unbind_ok', <<>>) -> #'exchange.unbind_ok'{}; decode_method_fields('queue.declare', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8, F7Len:32/unsigned, F7Tab:F7Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), F3 = ((F2Bits band 2) /= 0), F4 = ((F2Bits band 4) /= 0), F5 = ((F2Bits band 8) /= 0), F6 = ((F2Bits band 16) /= 0), F7 = rabbit_binary_parser:parse_table(F7Tab), #'queue.declare'{ticket = F0, queue = F1, passive = F2, durable = F3, exclusive = F4, auto_delete = F5, nowait = F6, arguments = F7}; decode_method_fields('queue.declare_ok', <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned, F2:32/unsigned>>) -> rabbit_binary_parser:assert_utf8(F0), #'queue.declare_ok'{queue = F0, message_count = F1, consumer_count = F2}; decode_method_fields('queue.bind', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), rabbit_binary_parser:assert_utf8(F3), F4 = ((F4Bits band 1) /= 0), F5 = rabbit_binary_parser:parse_table(F5Tab), #'queue.bind'{ticket = F0, queue = F1, exchange = F2, routing_key = F3, nowait = F4, arguments = F5}; decode_method_fields('queue.bind_ok', <<>>) -> #'queue.bind_ok'{}; decode_method_fields('queue.purge', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), #'queue.purge'{ticket = F0, queue = F1, nowait = F2}; decode_method_fields('queue.purge_ok', <<F0:32/unsigned>>) -> #'queue.purge_ok'{message_count = F0}; decode_method_fields('queue.delete', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), F3 = ((F2Bits band 2) /= 0), F4 = ((F2Bits band 4) /= 0), #'queue.delete'{ticket = F0, queue = F1, if_unused = F2, if_empty = F3, nowait = F4}; decode_method_fields('queue.delete_ok', <<F0:32/unsigned>>) -> #'queue.delete_ok'{message_count = F0}; decode_method_fields('queue.unbind', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Len:32/unsigned, F4Tab:F4Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), rabbit_binary_parser:assert_utf8(F3), F4 = rabbit_binary_parser:parse_table(F4Tab), #'queue.unbind'{ticket = F0, queue = F1, exchange = F2, routing_key = F3, arguments = F4}; decode_method_fields('queue.unbind_ok', <<>>) -> #'queue.unbind_ok'{}; decode_method_fields('basic.qos', <<F0:32/unsigned, F1:16/unsigned, F2Bits:8>>) -> F2 = ((F2Bits band 1) /= 0), #'basic.qos'{prefetch_size = F0, prefetch_count = F1, global = F2}; decode_method_fields('basic.qos_ok', <<>>) -> #'basic.qos_ok'{}; decode_method_fields('basic.consume', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8, F7Len:32/unsigned, F7Tab:F7Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), F3 = ((F3Bits band 1) /= 0), F4 = ((F3Bits band 2) /= 0), F5 = ((F3Bits band 4) /= 0), F6 = ((F3Bits band 8) /= 0), F7 = rabbit_binary_parser:parse_table(F7Tab), #'basic.consume'{ticket = F0, queue = F1, consumer_tag = F2, no_local = F3, no_ack = F4, exclusive = F5, nowait = F6, arguments = F7}; decode_method_fields('basic.consume_ok', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'basic.consume_ok'{consumer_tag = F0}; decode_method_fields('basic.cancel', <<F0Len:8/unsigned, F0:F0Len/binary, F1Bits:8>>) -> rabbit_binary_parser:assert_utf8(F0), F1 = ((F1Bits band 1) /= 0), #'basic.cancel'{consumer_tag = F0, nowait = F1}; decode_method_fields('basic.cancel_ok', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'basic.cancel_ok'{consumer_tag = F0}; decode_method_fields('basic.publish', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8>>) -> F3 = ((F3Bits band 1) /= 0), F4 = ((F3Bits band 2) /= 0), #'basic.publish'{ticket = F0, exchange = F1, routing_key = F2, mandatory = F3, immediate = F4}; decode_method_fields('basic.return', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary>>) -> #'basic.return'{reply_code = F0, reply_text = F1, exchange = F2, routing_key = F3}; decode_method_fields('basic.deliver', <<F0Len:8/unsigned, F0:F0Len/binary, F1:64/unsigned, F2Bits:8, F3Len:8/unsigned, F3:F3Len/binary, F4Len:8/unsigned, F4:F4Len/binary>>) -> F2 = ((F2Bits band 1) /= 0), #'basic.deliver'{consumer_tag = F0, delivery_tag = F1, redelivered = F2, exchange = F3, routing_key = F4}; decode_method_fields('basic.get', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), #'basic.get'{ticket = F0, queue = F1, no_ack = F2}; decode_method_fields('basic.get_ok', <<F0:64/unsigned, F1Bits:8, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4:32/unsigned>>) -> F1 = ((F1Bits band 1) /= 0), #'basic.get_ok'{delivery_tag = F0, redelivered = F1, exchange = F2, routing_key = F3, message_count = F4}; decode_method_fields('basic.get_empty', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'basic.get_empty'{cluster_id = F0}; decode_method_fields('basic.ack', <<F0:64/unsigned, F1Bits:8>>) -> F1 = ((F1Bits band 1) /= 0), #'basic.ack'{delivery_tag = F0, multiple = F1}; decode_method_fields('basic.reject', <<F0:64/unsigned, F1Bits:8>>) -> F1 = ((F1Bits band 1) /= 0), #'basic.reject'{delivery_tag = F0, requeue = F1}; decode_method_fields('basic.recover_async', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'basic.recover_async'{requeue = F0}; decode_method_fields('basic.recover', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'basic.recover'{requeue = F0}; decode_method_fields('basic.recover_ok', <<>>) -> #'basic.recover_ok'{}; decode_method_fields('basic.nack', <<F0:64/unsigned, F1Bits:8>>) -> F1 = ((F1Bits band 1) /= 0), F2 = ((F1Bits band 2) /= 0), #'basic.nack'{delivery_tag = F0, multiple = F1, requeue = F2}; decode_method_fields('basic.credit', <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F0), F2 = ((F2Bits band 1) /= 0), #'basic.credit'{consumer_tag = F0, credit = F1, drain = F2}; decode_method_fields('basic.credit_ok', <<F0:32/unsigned>>) -> #'basic.credit_ok'{available = F0}; decode_method_fields('basic.credit_drained', <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned>>) -> rabbit_binary_parser:assert_utf8(F0), #'basic.credit_drained'{consumer_tag = F0, credit_drained = F1}; decode_method_fields('tx.select', <<>>) -> #'tx.select'{}; decode_method_fields('tx.select_ok', <<>>) -> #'tx.select_ok'{}; decode_method_fields('tx.commit', <<>>) -> #'tx.commit'{}; decode_method_fields('tx.commit_ok', <<>>) -> #'tx.commit_ok'{}; decode_method_fields('tx.rollback', <<>>) -> #'tx.rollback'{}; decode_method_fields('tx.rollback_ok', <<>>) -> #'tx.rollback_ok'{}; decode_method_fields('confirm.select', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'confirm.select'{nowait = F0}; decode_method_fields('confirm.select_ok', <<>>) -> #'confirm.select_ok'{}; decode_method_fields(Name, BinaryFields) -> rabbit_misc:frame_error(Name, BinaryFields). decode_properties(10, <<>>) -> #'P_connection'{}; decode_properties(20, <<>>) -> #'P_channel'{}; decode_properties(30, <<>>) -> #'P_access'{}; decode_properties(40, <<>>) -> #'P_exchange'{}; decode_properties(50, <<>>) -> #'P_queue'{}; decode_properties(60, <<P0:1, P1:1, P2:1, P3:1, P4:1, P5:1, P6:1, P7:1, P8:1, P9:1, P10:1, P11:1, P12:1, P13:1, _:2, R0/binary>>) -> {F0, R1} = if P0 =:= 0 -> {undefined, R0}; true -> ?SHORTSTR_VAL(R0, L0, V0, X0) end, {F1, R2} = if P1 =:= 0 -> {undefined, R1}; true -> ?SHORTSTR_VAL(R1, L1, V1, X1) end, {F2, R3} = if P2 =:= 0 -> {undefined, R2}; true -> ?TABLE_VAL(R2, L2, V2, X2) end, {F3, R4} = if P3 =:= 0 -> {undefined, R3}; true -> ?OCTET_VAL(R3, L3, V3, X3) end, {F4, R5} = if P4 =:= 0 -> {undefined, R4}; true -> ?OCTET_VAL(R4, L4, V4, X4) end, {F5, R6} = if P5 =:= 0 -> {undefined, R5}; true -> ?SHORTSTR_VAL(R5, L5, V5, X5) end, {F6, R7} = if P6 =:= 0 -> {undefined, R6}; true -> ?SHORTSTR_VAL(R6, L6, V6, X6) end, {F7, R8} = if P7 =:= 0 -> {undefined, R7}; true -> ?SHORTSTR_VAL(R7, L7, V7, X7) end, {F8, R9} = if P8 =:= 0 -> {undefined, R8}; true -> ?SHORTSTR_VAL(R8, L8, V8, X8) end, {F9, R10} = if P9 =:= 0 -> {undefined, R9}; true -> ?TIMESTAMP_VAL(R9, L9, V9, X9) end, {F10, R11} = if P10 =:= 0 -> {undefined, R10}; true -> ?SHORTSTR_VAL(R10, L10, V10, X10) end, {F11, R12} = if P11 =:= 0 -> {undefined, R11}; true -> ?SHORTSTR_VAL(R11, L11, V11, X11) end, {F12, R13} = if P12 =:= 0 -> {undefined, R12}; true -> ?SHORTSTR_VAL(R12, L12, V12, X12) end, {F13, R14} = if P13 =:= 0 -> {undefined, R13}; true -> ?SHORTSTR_VAL(R13, L13, V13, X13) end, <<>> = R14, #'P_basic'{content_type = F0, content_encoding = F1, headers = F2, delivery_mode = F3, priority = F4, correlation_id = F5, reply_to = F6, expiration = F7, message_id = F8, timestamp = F9, type = F10, user_id = F11, app_id = F12, cluster_id = F13}; decode_properties(90, <<>>) -> #'P_tx'{}; decode_properties(85, <<>>) -> #'P_confirm'{}; decode_properties(ClassId, _BinaryFields) -> exit({unknown_class_id, ClassId}). encode_method_fields(#'connection.start'{version_major = F0, version_minor = F1, server_properties = F2, mechanisms = F3, locales = F4}) -> F2Tab = rabbit_binary_generator:generate_table(F2), F2Len = size(F2Tab), F3Len = size(F3), F4Len = size(F4), <<F0:8/unsigned, F1:8/unsigned, F2Len:32/unsigned, F2Tab:F2Len/binary, F3Len:32/unsigned, F3:F3Len/binary, F4Len:32/unsigned, F4:F4Len/binary>>; encode_method_fields(#'connection.start_ok'{client_properties = F0, mechanism = F1, response = F2, locale = F3}) -> F0Tab = rabbit_binary_generator:generate_table(F0), F0Len = size(F0Tab), F1Len = shortstr_size(F1), F2Len = size(F2), F3Len = shortstr_size(F3), <<F0Len:32/unsigned, F0Tab:F0Len/binary, F1Len:8/unsigned, F1:F1Len/binary, F2Len:32/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary>>; encode_method_fields(#'connection.secure'{challenge = F0}) -> F0Len = size(F0), <<F0Len:32/unsigned, F0:F0Len/binary>>; encode_method_fields(#'connection.secure_ok'{response = F0}) -> F0Len = size(F0), <<F0Len:32/unsigned, F0:F0Len/binary>>; encode_method_fields(#'connection.tune'{channel_max = F0, frame_max = F1, heartbeat = F2}) -> <<F0:16/unsigned, F1:32/unsigned, F2:16/unsigned>>; encode_method_fields(#'connection.tune_ok'{channel_max = F0, frame_max = F1, heartbeat = F2}) -> <<F0:16/unsigned, F1:32/unsigned, F2:16/unsigned>>; encode_method_fields(#'connection.open'{virtual_host = F0, capabilities = F1, insist = F2}) -> F0Len = shortstr_size(F0), F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0)), <<F0Len:8/unsigned, F0:F0Len/binary, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'connection.open_ok'{known_hosts = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'connection.close'{reply_code = F0, reply_text = F1, class_id = F2, method_id = F3}) -> F1Len = shortstr_size(F1), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2:16/unsigned, F3:16/unsigned>>; encode_method_fields(#'connection.close_ok'{}) -> <<>>; encode_method_fields(#'connection.blocked'{reason = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'connection.unblocked'{}) -> <<>>; encode_method_fields(#'channel.open'{out_of_band = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'channel.open_ok'{channel_id = F0}) -> F0Len = size(F0), <<F0Len:32/unsigned, F0:F0Len/binary>>; encode_method_fields(#'channel.flow'{active = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'channel.flow_ok'{active = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'channel.close'{reply_code = F0, reply_text = F1, class_id = F2, method_id = F3}) -> F1Len = shortstr_size(F1), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2:16/unsigned, F3:16/unsigned>>; encode_method_fields(#'channel.close_ok'{}) -> <<>>; encode_method_fields(#'access.request'{realm = F0, exclusive = F1, passive = F2, active = F3, write = F4, read = F5}) -> F0Len = shortstr_size(F0), F1Bits = ((bitvalue(F1) bsl 0) bor (bitvalue(F2) bsl 1) bor (bitvalue(F3) bsl 2) bor (bitvalue(F4) bsl 3) bor (bitvalue(F5) bsl 4)), <<F0Len:8/unsigned, F0:F0Len/binary, F1Bits:8>>; encode_method_fields(#'access.request_ok'{ticket = F0}) -> <<F0:16/unsigned>>; encode_method_fields(#'exchange.declare'{ticket = F0, exchange = F1, type = F2, passive = F3, durable = F4, auto_delete = F5, internal = F6, nowait = F7, arguments = F8}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Bits = ((bitvalue(F3) bsl 0) bor (bitvalue(F4) bsl 1) bor (bitvalue(F5) bsl 2) bor (bitvalue(F6) bsl 3) bor (bitvalue(F7) bsl 4)), F8Tab = rabbit_binary_generator:generate_table(F8), F8Len = size(F8Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8, F8Len:32/unsigned, F8Tab:F8Len/binary>>; encode_method_fields(#'exchange.declare_ok'{}) -> <<>>; encode_method_fields(#'exchange.delete'{ticket = F0, exchange = F1, if_unused = F2, nowait = F3}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0) bor (bitvalue(F3) bsl 1)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'exchange.delete_ok'{}) -> <<>>; encode_method_fields(#'exchange.bind'{ticket = F0, destination = F1, source = F2, routing_key = F3, nowait = F4, arguments = F5}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), F4Bits = ((bitvalue(F4) bsl 0)), F5Tab = rabbit_binary_generator:generate_table(F5), F5Len = size(F5Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>; encode_method_fields(#'exchange.bind_ok'{}) -> <<>>; encode_method_fields(#'exchange.unbind'{ticket = F0, destination = F1, source = F2, routing_key = F3, nowait = F4, arguments = F5}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), F4Bits = ((bitvalue(F4) bsl 0)), F5Tab = rabbit_binary_generator:generate_table(F5), F5Len = size(F5Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>; encode_method_fields(#'exchange.unbind_ok'{}) -> <<>>; encode_method_fields(#'queue.declare'{ticket = F0, queue = F1, passive = F2, durable = F3, exclusive = F4, auto_delete = F5, nowait = F6, arguments = F7}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0) bor (bitvalue(F3) bsl 1) bor (bitvalue(F4) bsl 2) bor (bitvalue(F5) bsl 3) bor (bitvalue(F6) bsl 4)), F7Tab = rabbit_binary_generator:generate_table(F7), F7Len = size(F7Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8, F7Len:32/unsigned, F7Tab:F7Len/binary>>; encode_method_fields(#'queue.declare_ok'{queue = F0, message_count = F1, consumer_count = F2}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned, F2:32/unsigned>>; encode_method_fields(#'queue.bind'{ticket = F0, queue = F1, exchange = F2, routing_key = F3, nowait = F4, arguments = F5}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), F4Bits = ((bitvalue(F4) bsl 0)), F5Tab = rabbit_binary_generator:generate_table(F5), F5Len = size(F5Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>; encode_method_fields(#'queue.bind_ok'{}) -> <<>>; encode_method_fields(#'queue.purge'{ticket = F0, queue = F1, nowait = F2}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'queue.purge_ok'{message_count = F0}) -> <<F0:32/unsigned>>; encode_method_fields(#'queue.delete'{ticket = F0, queue = F1, if_unused = F2, if_empty = F3, nowait = F4}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0) bor (bitvalue(F3) bsl 1) bor (bitvalue(F4) bsl 2)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'queue.delete_ok'{message_count = F0}) -> <<F0:32/unsigned>>; encode_method_fields(#'queue.unbind'{ticket = F0, queue = F1, exchange = F2, routing_key = F3, arguments = F4}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), F4Tab = rabbit_binary_generator:generate_table(F4), F4Len = size(F4Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Len:32/unsigned, F4Tab:F4Len/binary>>; encode_method_fields(#'queue.unbind_ok'{}) -> <<>>; encode_method_fields(#'basic.qos'{prefetch_size = F0, prefetch_count = F1, global = F2}) -> F2Bits = ((bitvalue(F2) bsl 0)), <<F0:32/unsigned, F1:16/unsigned, F2Bits:8>>; encode_method_fields(#'basic.qos_ok'{}) -> <<>>; encode_method_fields(#'basic.consume'{ticket = F0, queue = F1, consumer_tag = F2, no_local = F3, no_ack = F4, exclusive = F5, nowait = F6, arguments = F7}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Bits = ((bitvalue(F3) bsl 0) bor (bitvalue(F4) bsl 1) bor (bitvalue(F5) bsl 2) bor (bitvalue(F6) bsl 3)), F7Tab = rabbit_binary_generator:generate_table(F7), F7Len = size(F7Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8, F7Len:32/unsigned, F7Tab:F7Len/binary>>; encode_method_fields(#'basic.consume_ok'{consumer_tag = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'basic.cancel'{consumer_tag = F0, nowait = F1}) -> F0Len = shortstr_size(F0), F1Bits = ((bitvalue(F1) bsl 0)), <<F0Len:8/unsigned, F0:F0Len/binary, F1Bits:8>>; encode_method_fields(#'basic.cancel_ok'{consumer_tag = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'basic.publish'{ticket = F0, exchange = F1, routing_key = F2, mandatory = F3, immediate = F4}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Bits = ((bitvalue(F3) bsl 0) bor (bitvalue(F4) bsl 1)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8>>; encode_method_fields(#'basic.return'{reply_code = F0, reply_text = F1, exchange = F2, routing_key = F3}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary>>; encode_method_fields(#'basic.deliver'{consumer_tag = F0, delivery_tag = F1, redelivered = F2, exchange = F3, routing_key = F4}) -> F0Len = shortstr_size(F0), F2Bits = ((bitvalue(F2) bsl 0)), F3Len = shortstr_size(F3), F4Len = shortstr_size(F4), <<F0Len:8/unsigned, F0:F0Len/binary, F1:64/unsigned, F2Bits:8, F3Len:8/unsigned, F3:F3Len/binary, F4Len:8/unsigned, F4:F4Len/binary>>; encode_method_fields(#'basic.get'{ticket = F0, queue = F1, no_ack = F2}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'basic.get_ok'{delivery_tag = F0, redelivered = F1, exchange = F2, routing_key = F3, message_count = F4}) -> F1Bits = ((bitvalue(F1) bsl 0)), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), <<F0:64/unsigned, F1Bits:8, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4:32/unsigned>>; encode_method_fields(#'basic.get_empty'{cluster_id = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'basic.ack'{delivery_tag = F0, multiple = F1}) -> F1Bits = ((bitvalue(F1) bsl 0)), <<F0:64/unsigned, F1Bits:8>>; encode_method_fields(#'basic.reject'{delivery_tag = F0, requeue = F1}) -> F1Bits = ((bitvalue(F1) bsl 0)), <<F0:64/unsigned, F1Bits:8>>; encode_method_fields(#'basic.recover_async'{requeue = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'basic.recover'{requeue = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'basic.recover_ok'{}) -> <<>>; encode_method_fields(#'basic.nack'{delivery_tag = F0, multiple = F1, requeue = F2}) -> F1Bits = ((bitvalue(F1) bsl 0) bor (bitvalue(F2) bsl 1)), <<F0:64/unsigned, F1Bits:8>>; encode_method_fields(#'basic.credit'{consumer_tag = F0, credit = F1, drain = F2}) -> F0Len = shortstr_size(F0), F2Bits = ((bitvalue(F2) bsl 0)), <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned, F2Bits:8>>; encode_method_fields(#'basic.credit_ok'{available = F0}) -> <<F0:32/unsigned>>; encode_method_fields(#'basic.credit_drained'{consumer_tag = F0, credit_drained = F1}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned>>; encode_method_fields(#'tx.select'{}) -> <<>>; encode_method_fields(#'tx.select_ok'{}) -> <<>>; encode_method_fields(#'tx.commit'{}) -> <<>>; encode_method_fields(#'tx.commit_ok'{}) -> <<>>; encode_method_fields(#'tx.rollback'{}) -> <<>>; encode_method_fields(#'tx.rollback_ok'{}) -> <<>>; encode_method_fields(#'confirm.select'{nowait = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'confirm.select_ok'{}) -> <<>>; encode_method_fields(Record) -> exit({unknown_method_name, element(1, Record)}). encode_properties(#'P_connection'{}) -> <<>>; encode_properties(#'P_channel'{}) -> <<>>; encode_properties(#'P_access'{}) -> <<>>; encode_properties(#'P_exchange'{}) -> <<>>; encode_properties(#'P_queue'{}) -> <<>>; encode_properties(#'P_basic'{content_type = F0, content_encoding = F1, headers = F2, delivery_mode = F3, priority = F4, correlation_id = F5, reply_to = F6, expiration = F7, message_id = F8, timestamp = F9, type = F10, user_id = F11, app_id = F12, cluster_id = F13}) -> R0 = [<<>>], {P0, R1} = if F0 =:= undefined -> {0, R0}; true -> {1, [?SHORTSTR_PROP(F0, L0) | R0]} end, {P1, R2} = if F1 =:= undefined -> {0, R1}; true -> {1, [?SHORTSTR_PROP(F1, L1) | R1]} end, {P2, R3} = if F2 =:= undefined -> {0, R2}; true -> {1, [?TABLE_PROP(F2, L2) | R2]} end, {P3, R4} = if F3 =:= undefined -> {0, R3}; true -> {1, [?OCTET_PROP(F3, L3) | R3]} end, {P4, R5} = if F4 =:= undefined -> {0, R4}; true -> {1, [?OCTET_PROP(F4, L4) | R4]} end, {P5, R6} = if F5 =:= undefined -> {0, R5}; true -> {1, [?SHORTSTR_PROP(F5, L5) | R5]} end, {P6, R7} = if F6 =:= undefined -> {0, R6}; true -> {1, [?SHORTSTR_PROP(F6, L6) | R6]} end, {P7, R8} = if F7 =:= undefined -> {0, R7}; true -> {1, [?SHORTSTR_PROP(F7, L7) | R7]} end, {P8, R9} = if F8 =:= undefined -> {0, R8}; true -> {1, [?SHORTSTR_PROP(F8, L8) | R8]} end, {P9, R10} = if F9 =:= undefined -> {0, R9}; true -> {1, [?TIMESTAMP_PROP(F9, L9) | R9]} end, {P10, R11} = if F10 =:= undefined -> {0, R10}; true -> {1, [?SHORTSTR_PROP(F10, L10) | R10]} end, {P11, R12} = if F11 =:= undefined -> {0, R11}; true -> {1, [?SHORTSTR_PROP(F11, L11) | R11]} end, {P12, R13} = if F12 =:= undefined -> {0, R12}; true -> {1, [?SHORTSTR_PROP(F12, L12) | R12]} end, {P13, R14} = if F13 =:= undefined -> {0, R13}; true -> {1, [?SHORTSTR_PROP(F13, L13) | R13]} end, list_to_binary([<<P0:1, P1:1, P2:1, P3:1, P4:1, P5:1, P6:1, P7:1, P8:1, P9:1, P10:1, P11:1, P12:1, P13:1, 0:2>> | lists:reverse(R14)]); encode_properties(#'P_tx'{}) -> <<>>; encode_properties(#'P_confirm'{}) -> <<>>; encode_properties(Record) -> exit({unknown_properties_record, Record}). lookup_amqp_exception(content_too_large) -> {false, ?CONTENT_TOO_LARGE, <<"CONTENT_TOO_LARGE">>}; lookup_amqp_exception(no_route) -> {false, ?NO_ROUTE, <<"NO_ROUTE">>}; lookup_amqp_exception(no_consumers) -> {false, ?NO_CONSUMERS, <<"NO_CONSUMERS">>}; lookup_amqp_exception(access_refused) -> {false, ?ACCESS_REFUSED, <<"ACCESS_REFUSED">>}; lookup_amqp_exception(not_found) -> {false, ?NOT_FOUND, <<"NOT_FOUND">>}; lookup_amqp_exception(resource_locked) -> {false, ?RESOURCE_LOCKED, <<"RESOURCE_LOCKED">>}; lookup_amqp_exception(precondition_failed) -> {false, ?PRECONDITION_FAILED, <<"PRECONDITION_FAILED">>}; lookup_amqp_exception(connection_forced) -> {true, ?CONNECTION_FORCED, <<"CONNECTION_FORCED">>}; lookup_amqp_exception(invalid_path) -> {true, ?INVALID_PATH, <<"INVALID_PATH">>}; lookup_amqp_exception(frame_error) -> {true, ?FRAME_ERROR, <<"FRAME_ERROR">>}; lookup_amqp_exception(syntax_error) -> {true, ?SYNTAX_ERROR, <<"SYNTAX_ERROR">>}; lookup_amqp_exception(command_invalid) -> {true, ?COMMAND_INVALID, <<"COMMAND_INVALID">>}; lookup_amqp_exception(channel_error) -> {true, ?CHANNEL_ERROR, <<"CHANNEL_ERROR">>}; lookup_amqp_exception(unexpected_frame) -> {true, ?UNEXPECTED_FRAME, <<"UNEXPECTED_FRAME">>}; lookup_amqp_exception(resource_error) -> {true, ?RESOURCE_ERROR, <<"RESOURCE_ERROR">>}; lookup_amqp_exception(not_allowed) -> {true, ?NOT_ALLOWED, <<"NOT_ALLOWED">>}; lookup_amqp_exception(not_implemented) -> {true, ?NOT_IMPLEMENTED, <<"NOT_IMPLEMENTED">>}; lookup_amqp_exception(internal_error) -> {true, ?INTERNAL_ERROR, <<"INTERNAL_ERROR">>}; lookup_amqp_exception(Code) -> rabbit_log:warning("Unknown AMQP error code '~p'~n", [Code]), {true, ?INTERNAL_ERROR, <<"INTERNAL_ERROR">>}. amqp_exception(?FRAME_METHOD) -> frame_method; amqp_exception(?FRAME_HEADER) -> frame_header; amqp_exception(?FRAME_BODY) -> frame_body; amqp_exception(?FRAME_HEARTBEAT) -> frame_heartbeat; amqp_exception(?FRAME_MIN_SIZE) -> frame_min_size; amqp_exception(?FRAME_END) -> frame_end; amqp_exception(?REPLY_SUCCESS) -> reply_success; amqp_exception(?CONTENT_TOO_LARGE) -> content_too_large; amqp_exception(?NO_ROUTE) -> no_route; amqp_exception(?NO_CONSUMERS) -> no_consumers; amqp_exception(?ACCESS_REFUSED) -> access_refused; amqp_exception(?NOT_FOUND) -> not_found; amqp_exception(?RESOURCE_LOCKED) -> resource_locked; amqp_exception(?PRECONDITION_FAILED) -> precondition_failed; amqp_exception(?CONNECTION_FORCED) -> connection_forced; amqp_exception(?INVALID_PATH) -> invalid_path; amqp_exception(?FRAME_ERROR) -> frame_error; amqp_exception(?SYNTAX_ERROR) -> syntax_error; amqp_exception(?COMMAND_INVALID) -> command_invalid; amqp_exception(?CHANNEL_ERROR) -> channel_error; amqp_exception(?UNEXPECTED_FRAME) -> unexpected_frame; amqp_exception(?RESOURCE_ERROR) -> resource_error; amqp_exception(?NOT_ALLOWED) -> not_allowed; amqp_exception(?NOT_IMPLEMENTED) -> not_implemented; amqp_exception(?INTERNAL_ERROR) -> internal_error; amqp_exception(_Code) -> undefined.
null
https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/src/rabbit_framing_amqp_0_9_1.erl
erlang
compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Various types longstr signedint decimal byte double long short bool binary void timestamp Method signatures
Autogenerated code . Do not edit . The contents of this file are subject to the Mozilla Public License Version 1.1 ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_framing_amqp_0_9_1). -include("rabbit_framing.hrl"). -export([version/0]). -export([lookup_method_name/1]). -export([lookup_class_name/1]). -export([method_id/1]). -export([method_has_content/1]). -export([is_method_synchronous/1]). -export([method_record/1]). -export([method_fieldnames/1]). -export([decode_method_fields/2]). -export([decode_properties/2]). -export([encode_method_fields/1]). -export([encode_properties/1]). -export([lookup_amqp_exception/1]). -export([amqp_exception/1]). -ifdef(use_specs). -export_type([amqp_field_type/0, amqp_property_type/0, amqp_table/0, amqp_array/0, amqp_value/0, amqp_method_name/0, amqp_method/0, amqp_method_record/0, amqp_method_field_name/0, amqp_property_record/0, amqp_exception/0, amqp_exception_code/0, amqp_class_id/0]). -type(amqp_field_type() :: 'longstr' | 'signedint' | 'decimal' | 'timestamp' | 'table' | 'byte' | 'double' | 'float' | 'long' | 'short' | 'bool' | 'binary' | 'void' | 'array'). -type(amqp_property_type() :: 'shortstr' | 'longstr' | 'octet' | 'short' | 'long' | 'longlong' | 'timestamp' | 'bit' | 'table'). -type(amqp_table() :: [{binary(), amqp_field_type(), amqp_value()}]). -type(amqp_array() :: [{amqp_field_type(), amqp_value()}]). amqp_table() | amqp_array() | ). -type(amqp_method_name() :: ( 'connection.start' | 'connection.start_ok' | 'connection.secure' | 'connection.secure_ok' | 'connection.tune' | 'connection.tune_ok' | 'connection.open' | 'connection.open_ok' | 'connection.close' | 'connection.close_ok' | 'connection.blocked' | 'connection.unblocked' | 'channel.open' | 'channel.open_ok' | 'channel.flow' | 'channel.flow_ok' | 'channel.close' | 'channel.close_ok' | 'access.request' | 'access.request_ok' | 'exchange.declare' | 'exchange.declare_ok' | 'exchange.delete' | 'exchange.delete_ok' | 'exchange.bind' | 'exchange.bind_ok' | 'exchange.unbind' | 'exchange.unbind_ok' | 'queue.declare' | 'queue.declare_ok' | 'queue.bind' | 'queue.bind_ok' | 'queue.purge' | 'queue.purge_ok' | 'queue.delete' | 'queue.delete_ok' | 'queue.unbind' | 'queue.unbind_ok' | 'basic.qos' | 'basic.qos_ok' | 'basic.consume' | 'basic.consume_ok' | 'basic.cancel' | 'basic.cancel_ok' | 'basic.publish' | 'basic.return' | 'basic.deliver' | 'basic.get' | 'basic.get_ok' | 'basic.get_empty' | 'basic.ack' | 'basic.reject' | 'basic.recover_async' | 'basic.recover' | 'basic.recover_ok' | 'basic.nack' | 'basic.credit' | 'basic.credit_ok' | 'basic.credit_drained' | 'tx.select' | 'tx.select_ok' | 'tx.commit' | 'tx.commit_ok' | 'tx.rollback' | 'tx.rollback_ok' | 'confirm.select' | 'confirm.select_ok' )). -type(amqp_method() :: ( {10, 10} | {10, 11} | {10, 20} | {10, 21} | {10, 30} | {10, 31} | {10, 40} | {10, 41} | {10, 50} | {10, 51} | {10, 60} | {10, 61} | {20, 10} | {20, 11} | {20, 20} | {20, 21} | {20, 40} | {20, 41} | {30, 10} | {30, 11} | {40, 10} | {40, 11} | {40, 20} | {40, 21} | {40, 30} | {40, 31} | {40, 40} | {40, 51} | {50, 10} | {50, 11} | {50, 20} | {50, 21} | {50, 30} | {50, 31} | {50, 40} | {50, 41} | {50, 50} | {50, 51} | {60, 10} | {60, 11} | {60, 20} | {60, 21} | {60, 30} | {60, 31} | {60, 40} | {60, 50} | {60, 60} | {60, 70} | {60, 71} | {60, 72} | {60, 80} | {60, 90} | {60, 100} | {60, 110} | {60, 111} | {60, 120} | {60, 200} | {60, 201} | {60, 202} | {90, 10} | {90, 11} | {90, 20} | {90, 21} | {90, 30} | {90, 31} | {85, 10} | {85, 11} )). -type(amqp_method_record() :: ( #'connection.start'{} | #'connection.start_ok'{} | #'connection.secure'{} | #'connection.secure_ok'{} | #'connection.tune'{} | #'connection.tune_ok'{} | #'connection.open'{} | #'connection.open_ok'{} | #'connection.close'{} | #'connection.close_ok'{} | #'connection.blocked'{} | #'connection.unblocked'{} | #'channel.open'{} | #'channel.open_ok'{} | #'channel.flow'{} | #'channel.flow_ok'{} | #'channel.close'{} | #'channel.close_ok'{} | #'access.request'{} | #'access.request_ok'{} | #'exchange.declare'{} | #'exchange.declare_ok'{} | #'exchange.delete'{} | #'exchange.delete_ok'{} | #'exchange.bind'{} | #'exchange.bind_ok'{} | #'exchange.unbind'{} | #'exchange.unbind_ok'{} | #'queue.declare'{} | #'queue.declare_ok'{} | #'queue.bind'{} | #'queue.bind_ok'{} | #'queue.purge'{} | #'queue.purge_ok'{} | #'queue.delete'{} | #'queue.delete_ok'{} | #'queue.unbind'{} | #'queue.unbind_ok'{} | #'basic.qos'{} | #'basic.qos_ok'{} | #'basic.consume'{} | #'basic.consume_ok'{} | #'basic.cancel'{} | #'basic.cancel_ok'{} | #'basic.publish'{} | #'basic.return'{} | #'basic.deliver'{} | #'basic.get'{} | #'basic.get_ok'{} | #'basic.get_empty'{} | #'basic.ack'{} | #'basic.reject'{} | #'basic.recover_async'{} | #'basic.recover'{} | #'basic.recover_ok'{} | #'basic.nack'{} | #'basic.credit'{} | #'basic.credit_ok'{} | #'basic.credit_drained'{} | #'tx.select'{} | #'tx.select_ok'{} | #'tx.commit'{} | #'tx.commit_ok'{} | #'tx.rollback'{} | #'tx.rollback_ok'{} | #'confirm.select'{} | #'confirm.select_ok'{} )). -type(amqp_method_field_name() :: ( nowait | ticket | nowait | queue | passive | durable | exclusive | auto_delete | client_properties | prefetch_count | nowait | arguments | delivery_tag | multiple | queue | response | message_count | consumer_tag | consumer_count | version_major | version_minor | ticket | queue | locales | delivery_tag | cluster_id | routing_key | message_count | nowait | arguments | response | locale | requeue | redelivered | challenge | ticket | queue | nowait | channel_max | reply_text | frame_max | consumer_tag | heartbeat | exchange | consumer_tag | available | ticket | channel_max | frame_max | heartbeat | if_unused | delivery_tag | ticket | virtual_host | capabilities | insist | known_hosts | consumer_tag | ticket | reply_code | queue | reply_text | class_id | credit | method_id | routing_key | arguments | queue | exchange | reason | nowait | out_of_band | exchange | channel_id | ticket | prefetch_size | active | consumer_tag | credit_drained | global | mechanism | requeue | active | queue | routing_key | reply_code | reply_text | class_id | method_id | consumer_tag | mandatory | no_local | no_ack | no_ack | realm | routing_key | exclusive | passive | active | exclusive | write | message_count | read | ticket | consumer_tag | nowait | ticket | drain | exchange | requeue | type | passive | durable | auto_delete | arguments | delivery_tag | internal | nowait | delivery_tag | arguments | immediate | ticket | ticket | exchange | if_unused | nowait | routing_key | ticket | server_properties | destination | queue | source | routing_key | nowait | arguments | multiple | exchange | mechanisms | ticket | destination | source | routing_key | requeue | nowait | exchange | arguments | if_empty | redelivered | reply_code | exchange | routing_key | message_count )). -type(amqp_property_record() :: ( #'P_connection'{} | #'P_channel'{} | #'P_access'{} | #'P_exchange'{} | #'P_queue'{} | #'P_basic'{} | #'P_tx'{} | #'P_confirm'{} )). -type(amqp_exception() :: ( 'frame_method' | 'frame_header' | 'frame_body' | 'frame_heartbeat' | 'frame_min_size' | 'frame_end' | 'reply_success' | 'content_too_large' | 'no_route' | 'no_consumers' | 'access_refused' | 'not_found' | 'resource_locked' | 'precondition_failed' | 'connection_forced' | 'invalid_path' | 'frame_error' | 'syntax_error' | 'command_invalid' | 'channel_error' | 'unexpected_frame' | 'resource_error' | 'not_allowed' | 'not_implemented' | 'internal_error' )). -type(amqp_exception_code() :: ( 1 | 2 | 3 | 8 | 4096 | 206 | 200 | 311 | 312 | 313 | 403 | 404 | 405 | 406 | 320 | 402 | 501 | 502 | 503 | 504 | 505 | 506 | 530 | 540 | 541 )). -type(amqp_class_id() :: ( 40 | 10 | 50 | 20 | 85 | 90 | 60 | 30 )). -type(amqp_class_name() :: ( 'connection' | 'channel' | 'access' | 'exchange' | 'queue' | 'basic' | 'tx' | 'confirm' )). use_specs -ifdef(use_specs). -spec(version/0 :: () -> {non_neg_integer(), non_neg_integer(), non_neg_integer()}). -spec(lookup_method_name/1 :: (amqp_method()) -> amqp_method_name()). -spec(lookup_class_name/1 :: (amqp_class_id()) -> amqp_class_name()). -spec(method_id/1 :: (amqp_method_name()) -> amqp_method()). -spec(method_has_content/1 :: (amqp_method_name()) -> boolean()). -spec(is_method_synchronous/1 :: (amqp_method_record()) -> boolean()). -spec(method_record/1 :: (amqp_method_name()) -> amqp_method_record()). -spec(method_fieldnames/1 :: (amqp_method_name()) -> [amqp_method_field_name()]). -spec(decode_method_fields/2 :: (amqp_method_name(), binary()) -> amqp_method_record() | rabbit_types:connection_exit()). -spec(decode_properties/2 :: (non_neg_integer(), binary()) -> amqp_property_record()). -spec(encode_method_fields/1 :: (amqp_method_record()) -> binary()). -spec(encode_properties/1 :: (amqp_property_record()) -> binary()). -spec(lookup_amqp_exception/1 :: (amqp_exception()) -> {boolean(), amqp_exception_code(), binary()}). -spec(amqp_exception/1 :: (amqp_exception_code()) -> amqp_exception()). use_specs bitvalue(true) -> 1; bitvalue(false) -> 0; bitvalue(undefined) -> 0. shortstr_size(S) -> case size(S) of Len when Len =< 255 -> Len; _ -> exit(method_field_shortstr_overflow) end. -define(SHORTSTR_VAL(R, L, V, X), begin <<L:8/unsigned, V:L/binary, X/binary>> = R, {V, X} end). -define(LONGSTR_VAL(R, L, V, X), begin <<L:32/unsigned, V:L/binary, X/binary>> = R, {V, X} end). -define(SHORT_VAL(R, L, V, X), begin <<V:8/unsigned, X/binary>> = R, {V, X} end). -define(LONG_VAL(R, L, V, X), begin <<V:32/unsigned, X/binary>> = R, {V, X} end). -define(LONGLONG_VAL(R, L, V, X), begin <<V:64/unsigned, X/binary>> = R, {V, X} end). -define(OCTET_VAL(R, L, V, X), begin <<V:8/unsigned, X/binary>> = R, {V, X} end). -define(TABLE_VAL(R, L, V, X), begin <<L:32/unsigned, V:L/binary, X/binary>> = R, {rabbit_binary_parser:parse_table(V), X} end). -define(TIMESTAMP_VAL(R, L, V, X), begin <<V:64/unsigned, X/binary>> = R, {V, X} end). -define(SHORTSTR_PROP(X, L), begin L = size(X), if L < 256 -> <<L:8, X:L/binary>>; true -> exit(content_properties_shortstr_overflow) end end). -define(LONGSTR_PROP(X, L), begin L = size(X), <<L:32, X:L/binary>> end). -define(OCTET_PROP(X, L), <<X:8/unsigned>>). -define(SHORT_PROP(X, L), <<X:16/unsigned>>). -define(LONG_PROP(X, L), <<X:32/unsigned>>). -define(LONGLONG_PROP(X, L), <<X:64/unsigned>>). -define(TIMESTAMP_PROP(X, L), <<X:64/unsigned>>). -define(TABLE_PROP(X, T), begin T = rabbit_binary_generator:generate_table(X), <<(size(T)):32, T/binary>> end). version() -> {0, 9, 1}. lookup_method_name({10, 10}) -> 'connection.start'; lookup_method_name({10, 11}) -> 'connection.start_ok'; lookup_method_name({10, 20}) -> 'connection.secure'; lookup_method_name({10, 21}) -> 'connection.secure_ok'; lookup_method_name({10, 30}) -> 'connection.tune'; lookup_method_name({10, 31}) -> 'connection.tune_ok'; lookup_method_name({10, 40}) -> 'connection.open'; lookup_method_name({10, 41}) -> 'connection.open_ok'; lookup_method_name({10, 50}) -> 'connection.close'; lookup_method_name({10, 51}) -> 'connection.close_ok'; lookup_method_name({10, 60}) -> 'connection.blocked'; lookup_method_name({10, 61}) -> 'connection.unblocked'; lookup_method_name({20, 10}) -> 'channel.open'; lookup_method_name({20, 11}) -> 'channel.open_ok'; lookup_method_name({20, 20}) -> 'channel.flow'; lookup_method_name({20, 21}) -> 'channel.flow_ok'; lookup_method_name({20, 40}) -> 'channel.close'; lookup_method_name({20, 41}) -> 'channel.close_ok'; lookup_method_name({30, 10}) -> 'access.request'; lookup_method_name({30, 11}) -> 'access.request_ok'; lookup_method_name({40, 10}) -> 'exchange.declare'; lookup_method_name({40, 11}) -> 'exchange.declare_ok'; lookup_method_name({40, 20}) -> 'exchange.delete'; lookup_method_name({40, 21}) -> 'exchange.delete_ok'; lookup_method_name({40, 30}) -> 'exchange.bind'; lookup_method_name({40, 31}) -> 'exchange.bind_ok'; lookup_method_name({40, 40}) -> 'exchange.unbind'; lookup_method_name({40, 51}) -> 'exchange.unbind_ok'; lookup_method_name({50, 10}) -> 'queue.declare'; lookup_method_name({50, 11}) -> 'queue.declare_ok'; lookup_method_name({50, 20}) -> 'queue.bind'; lookup_method_name({50, 21}) -> 'queue.bind_ok'; lookup_method_name({50, 30}) -> 'queue.purge'; lookup_method_name({50, 31}) -> 'queue.purge_ok'; lookup_method_name({50, 40}) -> 'queue.delete'; lookup_method_name({50, 41}) -> 'queue.delete_ok'; lookup_method_name({50, 50}) -> 'queue.unbind'; lookup_method_name({50, 51}) -> 'queue.unbind_ok'; lookup_method_name({60, 10}) -> 'basic.qos'; lookup_method_name({60, 11}) -> 'basic.qos_ok'; lookup_method_name({60, 20}) -> 'basic.consume'; lookup_method_name({60, 21}) -> 'basic.consume_ok'; lookup_method_name({60, 30}) -> 'basic.cancel'; lookup_method_name({60, 31}) -> 'basic.cancel_ok'; lookup_method_name({60, 40}) -> 'basic.publish'; lookup_method_name({60, 50}) -> 'basic.return'; lookup_method_name({60, 60}) -> 'basic.deliver'; lookup_method_name({60, 70}) -> 'basic.get'; lookup_method_name({60, 71}) -> 'basic.get_ok'; lookup_method_name({60, 72}) -> 'basic.get_empty'; lookup_method_name({60, 80}) -> 'basic.ack'; lookup_method_name({60, 90}) -> 'basic.reject'; lookup_method_name({60, 100}) -> 'basic.recover_async'; lookup_method_name({60, 110}) -> 'basic.recover'; lookup_method_name({60, 111}) -> 'basic.recover_ok'; lookup_method_name({60, 120}) -> 'basic.nack'; lookup_method_name({60, 200}) -> 'basic.credit'; lookup_method_name({60, 201}) -> 'basic.credit_ok'; lookup_method_name({60, 202}) -> 'basic.credit_drained'; lookup_method_name({90, 10}) -> 'tx.select'; lookup_method_name({90, 11}) -> 'tx.select_ok'; lookup_method_name({90, 20}) -> 'tx.commit'; lookup_method_name({90, 21}) -> 'tx.commit_ok'; lookup_method_name({90, 30}) -> 'tx.rollback'; lookup_method_name({90, 31}) -> 'tx.rollback_ok'; lookup_method_name({85, 10}) -> 'confirm.select'; lookup_method_name({85, 11}) -> 'confirm.select_ok'; lookup_method_name({_ClassId, _MethodId} = Id) -> exit({unknown_method_id, Id}). lookup_class_name(10) -> 'connection'; lookup_class_name(20) -> 'channel'; lookup_class_name(30) -> 'access'; lookup_class_name(40) -> 'exchange'; lookup_class_name(50) -> 'queue'; lookup_class_name(60) -> 'basic'; lookup_class_name(90) -> 'tx'; lookup_class_name(85) -> 'confirm'; lookup_class_name(ClassId) -> exit({unknown_class_id, ClassId}). method_id('connection.start') -> {10, 10}; method_id('connection.start_ok') -> {10, 11}; method_id('connection.secure') -> {10, 20}; method_id('connection.secure_ok') -> {10, 21}; method_id('connection.tune') -> {10, 30}; method_id('connection.tune_ok') -> {10, 31}; method_id('connection.open') -> {10, 40}; method_id('connection.open_ok') -> {10, 41}; method_id('connection.close') -> {10, 50}; method_id('connection.close_ok') -> {10, 51}; method_id('connection.blocked') -> {10, 60}; method_id('connection.unblocked') -> {10, 61}; method_id('channel.open') -> {20, 10}; method_id('channel.open_ok') -> {20, 11}; method_id('channel.flow') -> {20, 20}; method_id('channel.flow_ok') -> {20, 21}; method_id('channel.close') -> {20, 40}; method_id('channel.close_ok') -> {20, 41}; method_id('access.request') -> {30, 10}; method_id('access.request_ok') -> {30, 11}; method_id('exchange.declare') -> {40, 10}; method_id('exchange.declare_ok') -> {40, 11}; method_id('exchange.delete') -> {40, 20}; method_id('exchange.delete_ok') -> {40, 21}; method_id('exchange.bind') -> {40, 30}; method_id('exchange.bind_ok') -> {40, 31}; method_id('exchange.unbind') -> {40, 40}; method_id('exchange.unbind_ok') -> {40, 51}; method_id('queue.declare') -> {50, 10}; method_id('queue.declare_ok') -> {50, 11}; method_id('queue.bind') -> {50, 20}; method_id('queue.bind_ok') -> {50, 21}; method_id('queue.purge') -> {50, 30}; method_id('queue.purge_ok') -> {50, 31}; method_id('queue.delete') -> {50, 40}; method_id('queue.delete_ok') -> {50, 41}; method_id('queue.unbind') -> {50, 50}; method_id('queue.unbind_ok') -> {50, 51}; method_id('basic.qos') -> {60, 10}; method_id('basic.qos_ok') -> {60, 11}; method_id('basic.consume') -> {60, 20}; method_id('basic.consume_ok') -> {60, 21}; method_id('basic.cancel') -> {60, 30}; method_id('basic.cancel_ok') -> {60, 31}; method_id('basic.publish') -> {60, 40}; method_id('basic.return') -> {60, 50}; method_id('basic.deliver') -> {60, 60}; method_id('basic.get') -> {60, 70}; method_id('basic.get_ok') -> {60, 71}; method_id('basic.get_empty') -> {60, 72}; method_id('basic.ack') -> {60, 80}; method_id('basic.reject') -> {60, 90}; method_id('basic.recover_async') -> {60, 100}; method_id('basic.recover') -> {60, 110}; method_id('basic.recover_ok') -> {60, 111}; method_id('basic.nack') -> {60, 120}; method_id('basic.credit') -> {60, 200}; method_id('basic.credit_ok') -> {60, 201}; method_id('basic.credit_drained') -> {60, 202}; method_id('tx.select') -> {90, 10}; method_id('tx.select_ok') -> {90, 11}; method_id('tx.commit') -> {90, 20}; method_id('tx.commit_ok') -> {90, 21}; method_id('tx.rollback') -> {90, 30}; method_id('tx.rollback_ok') -> {90, 31}; method_id('confirm.select') -> {85, 10}; method_id('confirm.select_ok') -> {85, 11}; method_id(Name) -> exit({unknown_method_name, Name}). method_has_content('connection.start') -> false; method_has_content('connection.start_ok') -> false; method_has_content('connection.secure') -> false; method_has_content('connection.secure_ok') -> false; method_has_content('connection.tune') -> false; method_has_content('connection.tune_ok') -> false; method_has_content('connection.open') -> false; method_has_content('connection.open_ok') -> false; method_has_content('connection.close') -> false; method_has_content('connection.close_ok') -> false; method_has_content('connection.blocked') -> false; method_has_content('connection.unblocked') -> false; method_has_content('channel.open') -> false; method_has_content('channel.open_ok') -> false; method_has_content('channel.flow') -> false; method_has_content('channel.flow_ok') -> false; method_has_content('channel.close') -> false; method_has_content('channel.close_ok') -> false; method_has_content('access.request') -> false; method_has_content('access.request_ok') -> false; method_has_content('exchange.declare') -> false; method_has_content('exchange.declare_ok') -> false; method_has_content('exchange.delete') -> false; method_has_content('exchange.delete_ok') -> false; method_has_content('exchange.bind') -> false; method_has_content('exchange.bind_ok') -> false; method_has_content('exchange.unbind') -> false; method_has_content('exchange.unbind_ok') -> false; method_has_content('queue.declare') -> false; method_has_content('queue.declare_ok') -> false; method_has_content('queue.bind') -> false; method_has_content('queue.bind_ok') -> false; method_has_content('queue.purge') -> false; method_has_content('queue.purge_ok') -> false; method_has_content('queue.delete') -> false; method_has_content('queue.delete_ok') -> false; method_has_content('queue.unbind') -> false; method_has_content('queue.unbind_ok') -> false; method_has_content('basic.qos') -> false; method_has_content('basic.qos_ok') -> false; method_has_content('basic.consume') -> false; method_has_content('basic.consume_ok') -> false; method_has_content('basic.cancel') -> false; method_has_content('basic.cancel_ok') -> false; method_has_content('basic.publish') -> true; method_has_content('basic.return') -> true; method_has_content('basic.deliver') -> true; method_has_content('basic.get') -> false; method_has_content('basic.get_ok') -> true; method_has_content('basic.get_empty') -> false; method_has_content('basic.ack') -> false; method_has_content('basic.reject') -> false; method_has_content('basic.recover_async') -> false; method_has_content('basic.recover') -> false; method_has_content('basic.recover_ok') -> false; method_has_content('basic.nack') -> false; method_has_content('basic.credit') -> false; method_has_content('basic.credit_ok') -> false; method_has_content('basic.credit_drained') -> false; method_has_content('tx.select') -> false; method_has_content('tx.select_ok') -> false; method_has_content('tx.commit') -> false; method_has_content('tx.commit_ok') -> false; method_has_content('tx.rollback') -> false; method_has_content('tx.rollback_ok') -> false; method_has_content('confirm.select') -> false; method_has_content('confirm.select_ok') -> false; method_has_content(Name) -> exit({unknown_method_name, Name}). is_method_synchronous(#'connection.start'{}) -> true; is_method_synchronous(#'connection.start_ok'{}) -> false; is_method_synchronous(#'connection.secure'{}) -> true; is_method_synchronous(#'connection.secure_ok'{}) -> false; is_method_synchronous(#'connection.tune'{}) -> true; is_method_synchronous(#'connection.tune_ok'{}) -> false; is_method_synchronous(#'connection.open'{}) -> true; is_method_synchronous(#'connection.open_ok'{}) -> false; is_method_synchronous(#'connection.close'{}) -> true; is_method_synchronous(#'connection.close_ok'{}) -> false; is_method_synchronous(#'connection.blocked'{}) -> false; is_method_synchronous(#'connection.unblocked'{}) -> false; is_method_synchronous(#'channel.open'{}) -> true; is_method_synchronous(#'channel.open_ok'{}) -> false; is_method_synchronous(#'channel.flow'{}) -> true; is_method_synchronous(#'channel.flow_ok'{}) -> false; is_method_synchronous(#'channel.close'{}) -> true; is_method_synchronous(#'channel.close_ok'{}) -> false; is_method_synchronous(#'access.request'{}) -> true; is_method_synchronous(#'access.request_ok'{}) -> false; is_method_synchronous(#'exchange.declare'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'exchange.declare_ok'{}) -> false; is_method_synchronous(#'exchange.delete'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'exchange.delete_ok'{}) -> false; is_method_synchronous(#'exchange.bind'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'exchange.bind_ok'{}) -> false; is_method_synchronous(#'exchange.unbind'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'exchange.unbind_ok'{}) -> false; is_method_synchronous(#'queue.declare'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'queue.declare_ok'{}) -> false; is_method_synchronous(#'queue.bind'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'queue.bind_ok'{}) -> false; is_method_synchronous(#'queue.purge'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'queue.purge_ok'{}) -> false; is_method_synchronous(#'queue.delete'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'queue.delete_ok'{}) -> false; is_method_synchronous(#'queue.unbind'{}) -> true; is_method_synchronous(#'queue.unbind_ok'{}) -> false; is_method_synchronous(#'basic.qos'{}) -> true; is_method_synchronous(#'basic.qos_ok'{}) -> false; is_method_synchronous(#'basic.consume'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'basic.consume_ok'{}) -> false; is_method_synchronous(#'basic.cancel'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'basic.cancel_ok'{}) -> false; is_method_synchronous(#'basic.publish'{}) -> false; is_method_synchronous(#'basic.return'{}) -> false; is_method_synchronous(#'basic.deliver'{}) -> false; is_method_synchronous(#'basic.get'{}) -> true; is_method_synchronous(#'basic.get_ok'{}) -> false; is_method_synchronous(#'basic.get_empty'{}) -> false; is_method_synchronous(#'basic.ack'{}) -> false; is_method_synchronous(#'basic.reject'{}) -> false; is_method_synchronous(#'basic.recover_async'{}) -> false; is_method_synchronous(#'basic.recover'{}) -> true; is_method_synchronous(#'basic.recover_ok'{}) -> false; is_method_synchronous(#'basic.nack'{}) -> false; is_method_synchronous(#'basic.credit'{}) -> true; is_method_synchronous(#'basic.credit_ok'{}) -> false; is_method_synchronous(#'basic.credit_drained'{}) -> false; is_method_synchronous(#'tx.select'{}) -> true; is_method_synchronous(#'tx.select_ok'{}) -> false; is_method_synchronous(#'tx.commit'{}) -> true; is_method_synchronous(#'tx.commit_ok'{}) -> false; is_method_synchronous(#'tx.rollback'{}) -> true; is_method_synchronous(#'tx.rollback_ok'{}) -> false; is_method_synchronous(#'confirm.select'{nowait = NoWait}) -> not(NoWait); is_method_synchronous(#'confirm.select_ok'{}) -> false; is_method_synchronous(Name) -> exit({unknown_method_name, Name}). method_record('connection.start') -> #'connection.start'{}; method_record('connection.start_ok') -> #'connection.start_ok'{}; method_record('connection.secure') -> #'connection.secure'{}; method_record('connection.secure_ok') -> #'connection.secure_ok'{}; method_record('connection.tune') -> #'connection.tune'{}; method_record('connection.tune_ok') -> #'connection.tune_ok'{}; method_record('connection.open') -> #'connection.open'{}; method_record('connection.open_ok') -> #'connection.open_ok'{}; method_record('connection.close') -> #'connection.close'{}; method_record('connection.close_ok') -> #'connection.close_ok'{}; method_record('connection.blocked') -> #'connection.blocked'{}; method_record('connection.unblocked') -> #'connection.unblocked'{}; method_record('channel.open') -> #'channel.open'{}; method_record('channel.open_ok') -> #'channel.open_ok'{}; method_record('channel.flow') -> #'channel.flow'{}; method_record('channel.flow_ok') -> #'channel.flow_ok'{}; method_record('channel.close') -> #'channel.close'{}; method_record('channel.close_ok') -> #'channel.close_ok'{}; method_record('access.request') -> #'access.request'{}; method_record('access.request_ok') -> #'access.request_ok'{}; method_record('exchange.declare') -> #'exchange.declare'{}; method_record('exchange.declare_ok') -> #'exchange.declare_ok'{}; method_record('exchange.delete') -> #'exchange.delete'{}; method_record('exchange.delete_ok') -> #'exchange.delete_ok'{}; method_record('exchange.bind') -> #'exchange.bind'{}; method_record('exchange.bind_ok') -> #'exchange.bind_ok'{}; method_record('exchange.unbind') -> #'exchange.unbind'{}; method_record('exchange.unbind_ok') -> #'exchange.unbind_ok'{}; method_record('queue.declare') -> #'queue.declare'{}; method_record('queue.declare_ok') -> #'queue.declare_ok'{}; method_record('queue.bind') -> #'queue.bind'{}; method_record('queue.bind_ok') -> #'queue.bind_ok'{}; method_record('queue.purge') -> #'queue.purge'{}; method_record('queue.purge_ok') -> #'queue.purge_ok'{}; method_record('queue.delete') -> #'queue.delete'{}; method_record('queue.delete_ok') -> #'queue.delete_ok'{}; method_record('queue.unbind') -> #'queue.unbind'{}; method_record('queue.unbind_ok') -> #'queue.unbind_ok'{}; method_record('basic.qos') -> #'basic.qos'{}; method_record('basic.qos_ok') -> #'basic.qos_ok'{}; method_record('basic.consume') -> #'basic.consume'{}; method_record('basic.consume_ok') -> #'basic.consume_ok'{}; method_record('basic.cancel') -> #'basic.cancel'{}; method_record('basic.cancel_ok') -> #'basic.cancel_ok'{}; method_record('basic.publish') -> #'basic.publish'{}; method_record('basic.return') -> #'basic.return'{}; method_record('basic.deliver') -> #'basic.deliver'{}; method_record('basic.get') -> #'basic.get'{}; method_record('basic.get_ok') -> #'basic.get_ok'{}; method_record('basic.get_empty') -> #'basic.get_empty'{}; method_record('basic.ack') -> #'basic.ack'{}; method_record('basic.reject') -> #'basic.reject'{}; method_record('basic.recover_async') -> #'basic.recover_async'{}; method_record('basic.recover') -> #'basic.recover'{}; method_record('basic.recover_ok') -> #'basic.recover_ok'{}; method_record('basic.nack') -> #'basic.nack'{}; method_record('basic.credit') -> #'basic.credit'{}; method_record('basic.credit_ok') -> #'basic.credit_ok'{}; method_record('basic.credit_drained') -> #'basic.credit_drained'{}; method_record('tx.select') -> #'tx.select'{}; method_record('tx.select_ok') -> #'tx.select_ok'{}; method_record('tx.commit') -> #'tx.commit'{}; method_record('tx.commit_ok') -> #'tx.commit_ok'{}; method_record('tx.rollback') -> #'tx.rollback'{}; method_record('tx.rollback_ok') -> #'tx.rollback_ok'{}; method_record('confirm.select') -> #'confirm.select'{}; method_record('confirm.select_ok') -> #'confirm.select_ok'{}; method_record(Name) -> exit({unknown_method_name, Name}). method_fieldnames('connection.start') -> [version_major, version_minor, server_properties, mechanisms, locales]; method_fieldnames('connection.start_ok') -> [client_properties, mechanism, response, locale]; method_fieldnames('connection.secure') -> [challenge]; method_fieldnames('connection.secure_ok') -> [response]; method_fieldnames('connection.tune') -> [channel_max, frame_max, heartbeat]; method_fieldnames('connection.tune_ok') -> [channel_max, frame_max, heartbeat]; method_fieldnames('connection.open') -> [virtual_host, capabilities, insist]; method_fieldnames('connection.open_ok') -> [known_hosts]; method_fieldnames('connection.close') -> [reply_code, reply_text, class_id, method_id]; method_fieldnames('connection.close_ok') -> []; method_fieldnames('connection.blocked') -> [reason]; method_fieldnames('connection.unblocked') -> []; method_fieldnames('channel.open') -> [out_of_band]; method_fieldnames('channel.open_ok') -> [channel_id]; method_fieldnames('channel.flow') -> [active]; method_fieldnames('channel.flow_ok') -> [active]; method_fieldnames('channel.close') -> [reply_code, reply_text, class_id, method_id]; method_fieldnames('channel.close_ok') -> []; method_fieldnames('access.request') -> [realm, exclusive, passive, active, write, read]; method_fieldnames('access.request_ok') -> [ticket]; method_fieldnames('exchange.declare') -> [ticket, exchange, type, passive, durable, auto_delete, internal, nowait, arguments]; method_fieldnames('exchange.declare_ok') -> []; method_fieldnames('exchange.delete') -> [ticket, exchange, if_unused, nowait]; method_fieldnames('exchange.delete_ok') -> []; method_fieldnames('exchange.bind') -> [ticket, destination, source, routing_key, nowait, arguments]; method_fieldnames('exchange.bind_ok') -> []; method_fieldnames('exchange.unbind') -> [ticket, destination, source, routing_key, nowait, arguments]; method_fieldnames('exchange.unbind_ok') -> []; method_fieldnames('queue.declare') -> [ticket, queue, passive, durable, exclusive, auto_delete, nowait, arguments]; method_fieldnames('queue.declare_ok') -> [queue, message_count, consumer_count]; method_fieldnames('queue.bind') -> [ticket, queue, exchange, routing_key, nowait, arguments]; method_fieldnames('queue.bind_ok') -> []; method_fieldnames('queue.purge') -> [ticket, queue, nowait]; method_fieldnames('queue.purge_ok') -> [message_count]; method_fieldnames('queue.delete') -> [ticket, queue, if_unused, if_empty, nowait]; method_fieldnames('queue.delete_ok') -> [message_count]; method_fieldnames('queue.unbind') -> [ticket, queue, exchange, routing_key, arguments]; method_fieldnames('queue.unbind_ok') -> []; method_fieldnames('basic.qos') -> [prefetch_size, prefetch_count, global]; method_fieldnames('basic.qos_ok') -> []; method_fieldnames('basic.consume') -> [ticket, queue, consumer_tag, no_local, no_ack, exclusive, nowait, arguments]; method_fieldnames('basic.consume_ok') -> [consumer_tag]; method_fieldnames('basic.cancel') -> [consumer_tag, nowait]; method_fieldnames('basic.cancel_ok') -> [consumer_tag]; method_fieldnames('basic.publish') -> [ticket, exchange, routing_key, mandatory, immediate]; method_fieldnames('basic.return') -> [reply_code, reply_text, exchange, routing_key]; method_fieldnames('basic.deliver') -> [consumer_tag, delivery_tag, redelivered, exchange, routing_key]; method_fieldnames('basic.get') -> [ticket, queue, no_ack]; method_fieldnames('basic.get_ok') -> [delivery_tag, redelivered, exchange, routing_key, message_count]; method_fieldnames('basic.get_empty') -> [cluster_id]; method_fieldnames('basic.ack') -> [delivery_tag, multiple]; method_fieldnames('basic.reject') -> [delivery_tag, requeue]; method_fieldnames('basic.recover_async') -> [requeue]; method_fieldnames('basic.recover') -> [requeue]; method_fieldnames('basic.recover_ok') -> []; method_fieldnames('basic.nack') -> [delivery_tag, multiple, requeue]; method_fieldnames('basic.credit') -> [consumer_tag, credit, drain]; method_fieldnames('basic.credit_ok') -> [available]; method_fieldnames('basic.credit_drained') -> [consumer_tag, credit_drained]; method_fieldnames('tx.select') -> []; method_fieldnames('tx.select_ok') -> []; method_fieldnames('tx.commit') -> []; method_fieldnames('tx.commit_ok') -> []; method_fieldnames('tx.rollback') -> []; method_fieldnames('tx.rollback_ok') -> []; method_fieldnames('confirm.select') -> [nowait]; method_fieldnames('confirm.select_ok') -> []; method_fieldnames(Name) -> exit({unknown_method_name, Name}). decode_method_fields('connection.start', <<F0:8/unsigned, F1:8/unsigned, F2Len:32/unsigned, F2Tab:F2Len/binary, F3Len:32/unsigned, F3:F3Len/binary, F4Len:32/unsigned, F4:F4Len/binary>>) -> F2 = rabbit_binary_parser:parse_table(F2Tab), #'connection.start'{version_major = F0, version_minor = F1, server_properties = F2, mechanisms = F3, locales = F4}; decode_method_fields('connection.start_ok', <<F0Len:32/unsigned, F0Tab:F0Len/binary, F1Len:8/unsigned, F1:F1Len/binary, F2Len:32/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary>>) -> F0 = rabbit_binary_parser:parse_table(F0Tab), rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F3), #'connection.start_ok'{client_properties = F0, mechanism = F1, response = F2, locale = F3}; decode_method_fields('connection.secure', <<F0Len:32/unsigned, F0:F0Len/binary>>) -> #'connection.secure'{challenge = F0}; decode_method_fields('connection.secure_ok', <<F0Len:32/unsigned, F0:F0Len/binary>>) -> #'connection.secure_ok'{response = F0}; decode_method_fields('connection.tune', <<F0:16/unsigned, F1:32/unsigned, F2:16/unsigned>>) -> #'connection.tune'{channel_max = F0, frame_max = F1, heartbeat = F2}; decode_method_fields('connection.tune_ok', <<F0:16/unsigned, F1:32/unsigned, F2:16/unsigned>>) -> #'connection.tune_ok'{channel_max = F0, frame_max = F1, heartbeat = F2}; decode_method_fields('connection.open', <<F0Len:8/unsigned, F0:F0Len/binary, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F0), rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), #'connection.open'{virtual_host = F0, capabilities = F1, insist = F2}; decode_method_fields('connection.open_ok', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'connection.open_ok'{known_hosts = F0}; decode_method_fields('connection.close', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2:16/unsigned, F3:16/unsigned>>) -> rabbit_binary_parser:assert_utf8(F1), #'connection.close'{reply_code = F0, reply_text = F1, class_id = F2, method_id = F3}; decode_method_fields('connection.close_ok', <<>>) -> #'connection.close_ok'{}; decode_method_fields('connection.blocked', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'connection.blocked'{reason = F0}; decode_method_fields('connection.unblocked', <<>>) -> #'connection.unblocked'{}; decode_method_fields('channel.open', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'channel.open'{out_of_band = F0}; decode_method_fields('channel.open_ok', <<F0Len:32/unsigned, F0:F0Len/binary>>) -> #'channel.open_ok'{channel_id = F0}; decode_method_fields('channel.flow', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'channel.flow'{active = F0}; decode_method_fields('channel.flow_ok', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'channel.flow_ok'{active = F0}; decode_method_fields('channel.close', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2:16/unsigned, F3:16/unsigned>>) -> rabbit_binary_parser:assert_utf8(F1), #'channel.close'{reply_code = F0, reply_text = F1, class_id = F2, method_id = F3}; decode_method_fields('channel.close_ok', <<>>) -> #'channel.close_ok'{}; decode_method_fields('access.request', <<F0Len:8/unsigned, F0:F0Len/binary, F1Bits:8>>) -> rabbit_binary_parser:assert_utf8(F0), F1 = ((F1Bits band 1) /= 0), F2 = ((F1Bits band 2) /= 0), F3 = ((F1Bits band 4) /= 0), F4 = ((F1Bits band 8) /= 0), F5 = ((F1Bits band 16) /= 0), #'access.request'{realm = F0, exclusive = F1, passive = F2, active = F3, write = F4, read = F5}; decode_method_fields('access.request_ok', <<F0:16/unsigned>>) -> #'access.request_ok'{ticket = F0}; decode_method_fields('exchange.declare', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8, F8Len:32/unsigned, F8Tab:F8Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), F3 = ((F3Bits band 1) /= 0), F4 = ((F3Bits band 2) /= 0), F5 = ((F3Bits band 4) /= 0), F6 = ((F3Bits band 8) /= 0), F7 = ((F3Bits band 16) /= 0), F8 = rabbit_binary_parser:parse_table(F8Tab), #'exchange.declare'{ticket = F0, exchange = F1, type = F2, passive = F3, durable = F4, auto_delete = F5, internal = F6, nowait = F7, arguments = F8}; decode_method_fields('exchange.declare_ok', <<>>) -> #'exchange.declare_ok'{}; decode_method_fields('exchange.delete', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), F3 = ((F2Bits band 2) /= 0), #'exchange.delete'{ticket = F0, exchange = F1, if_unused = F2, nowait = F3}; decode_method_fields('exchange.delete_ok', <<>>) -> #'exchange.delete_ok'{}; decode_method_fields('exchange.bind', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), rabbit_binary_parser:assert_utf8(F3), F4 = ((F4Bits band 1) /= 0), F5 = rabbit_binary_parser:parse_table(F5Tab), #'exchange.bind'{ticket = F0, destination = F1, source = F2, routing_key = F3, nowait = F4, arguments = F5}; decode_method_fields('exchange.bind_ok', <<>>) -> #'exchange.bind_ok'{}; decode_method_fields('exchange.unbind', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), rabbit_binary_parser:assert_utf8(F3), F4 = ((F4Bits band 1) /= 0), F5 = rabbit_binary_parser:parse_table(F5Tab), #'exchange.unbind'{ticket = F0, destination = F1, source = F2, routing_key = F3, nowait = F4, arguments = F5}; decode_method_fields('exchange.unbind_ok', <<>>) -> #'exchange.unbind_ok'{}; decode_method_fields('queue.declare', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8, F7Len:32/unsigned, F7Tab:F7Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), F3 = ((F2Bits band 2) /= 0), F4 = ((F2Bits band 4) /= 0), F5 = ((F2Bits band 8) /= 0), F6 = ((F2Bits band 16) /= 0), F7 = rabbit_binary_parser:parse_table(F7Tab), #'queue.declare'{ticket = F0, queue = F1, passive = F2, durable = F3, exclusive = F4, auto_delete = F5, nowait = F6, arguments = F7}; decode_method_fields('queue.declare_ok', <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned, F2:32/unsigned>>) -> rabbit_binary_parser:assert_utf8(F0), #'queue.declare_ok'{queue = F0, message_count = F1, consumer_count = F2}; decode_method_fields('queue.bind', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), rabbit_binary_parser:assert_utf8(F3), F4 = ((F4Bits band 1) /= 0), F5 = rabbit_binary_parser:parse_table(F5Tab), #'queue.bind'{ticket = F0, queue = F1, exchange = F2, routing_key = F3, nowait = F4, arguments = F5}; decode_method_fields('queue.bind_ok', <<>>) -> #'queue.bind_ok'{}; decode_method_fields('queue.purge', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), #'queue.purge'{ticket = F0, queue = F1, nowait = F2}; decode_method_fields('queue.purge_ok', <<F0:32/unsigned>>) -> #'queue.purge_ok'{message_count = F0}; decode_method_fields('queue.delete', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), F3 = ((F2Bits band 2) /= 0), F4 = ((F2Bits band 4) /= 0), #'queue.delete'{ticket = F0, queue = F1, if_unused = F2, if_empty = F3, nowait = F4}; decode_method_fields('queue.delete_ok', <<F0:32/unsigned>>) -> #'queue.delete_ok'{message_count = F0}; decode_method_fields('queue.unbind', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Len:32/unsigned, F4Tab:F4Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), rabbit_binary_parser:assert_utf8(F3), F4 = rabbit_binary_parser:parse_table(F4Tab), #'queue.unbind'{ticket = F0, queue = F1, exchange = F2, routing_key = F3, arguments = F4}; decode_method_fields('queue.unbind_ok', <<>>) -> #'queue.unbind_ok'{}; decode_method_fields('basic.qos', <<F0:32/unsigned, F1:16/unsigned, F2Bits:8>>) -> F2 = ((F2Bits band 1) /= 0), #'basic.qos'{prefetch_size = F0, prefetch_count = F1, global = F2}; decode_method_fields('basic.qos_ok', <<>>) -> #'basic.qos_ok'{}; decode_method_fields('basic.consume', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8, F7Len:32/unsigned, F7Tab:F7Len/binary>>) -> rabbit_binary_parser:assert_utf8(F1), rabbit_binary_parser:assert_utf8(F2), F3 = ((F3Bits band 1) /= 0), F4 = ((F3Bits band 2) /= 0), F5 = ((F3Bits band 4) /= 0), F6 = ((F3Bits band 8) /= 0), F7 = rabbit_binary_parser:parse_table(F7Tab), #'basic.consume'{ticket = F0, queue = F1, consumer_tag = F2, no_local = F3, no_ack = F4, exclusive = F5, nowait = F6, arguments = F7}; decode_method_fields('basic.consume_ok', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'basic.consume_ok'{consumer_tag = F0}; decode_method_fields('basic.cancel', <<F0Len:8/unsigned, F0:F0Len/binary, F1Bits:8>>) -> rabbit_binary_parser:assert_utf8(F0), F1 = ((F1Bits band 1) /= 0), #'basic.cancel'{consumer_tag = F0, nowait = F1}; decode_method_fields('basic.cancel_ok', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'basic.cancel_ok'{consumer_tag = F0}; decode_method_fields('basic.publish', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8>>) -> F3 = ((F3Bits band 1) /= 0), F4 = ((F3Bits band 2) /= 0), #'basic.publish'{ticket = F0, exchange = F1, routing_key = F2, mandatory = F3, immediate = F4}; decode_method_fields('basic.return', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary>>) -> #'basic.return'{reply_code = F0, reply_text = F1, exchange = F2, routing_key = F3}; decode_method_fields('basic.deliver', <<F0Len:8/unsigned, F0:F0Len/binary, F1:64/unsigned, F2Bits:8, F3Len:8/unsigned, F3:F3Len/binary, F4Len:8/unsigned, F4:F4Len/binary>>) -> F2 = ((F2Bits band 1) /= 0), #'basic.deliver'{consumer_tag = F0, delivery_tag = F1, redelivered = F2, exchange = F3, routing_key = F4}; decode_method_fields('basic.get', <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F1), F2 = ((F2Bits band 1) /= 0), #'basic.get'{ticket = F0, queue = F1, no_ack = F2}; decode_method_fields('basic.get_ok', <<F0:64/unsigned, F1Bits:8, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4:32/unsigned>>) -> F1 = ((F1Bits band 1) /= 0), #'basic.get_ok'{delivery_tag = F0, redelivered = F1, exchange = F2, routing_key = F3, message_count = F4}; decode_method_fields('basic.get_empty', <<F0Len:8/unsigned, F0:F0Len/binary>>) -> rabbit_binary_parser:assert_utf8(F0), #'basic.get_empty'{cluster_id = F0}; decode_method_fields('basic.ack', <<F0:64/unsigned, F1Bits:8>>) -> F1 = ((F1Bits band 1) /= 0), #'basic.ack'{delivery_tag = F0, multiple = F1}; decode_method_fields('basic.reject', <<F0:64/unsigned, F1Bits:8>>) -> F1 = ((F1Bits band 1) /= 0), #'basic.reject'{delivery_tag = F0, requeue = F1}; decode_method_fields('basic.recover_async', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'basic.recover_async'{requeue = F0}; decode_method_fields('basic.recover', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'basic.recover'{requeue = F0}; decode_method_fields('basic.recover_ok', <<>>) -> #'basic.recover_ok'{}; decode_method_fields('basic.nack', <<F0:64/unsigned, F1Bits:8>>) -> F1 = ((F1Bits band 1) /= 0), F2 = ((F1Bits band 2) /= 0), #'basic.nack'{delivery_tag = F0, multiple = F1, requeue = F2}; decode_method_fields('basic.credit', <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned, F2Bits:8>>) -> rabbit_binary_parser:assert_utf8(F0), F2 = ((F2Bits band 1) /= 0), #'basic.credit'{consumer_tag = F0, credit = F1, drain = F2}; decode_method_fields('basic.credit_ok', <<F0:32/unsigned>>) -> #'basic.credit_ok'{available = F0}; decode_method_fields('basic.credit_drained', <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned>>) -> rabbit_binary_parser:assert_utf8(F0), #'basic.credit_drained'{consumer_tag = F0, credit_drained = F1}; decode_method_fields('tx.select', <<>>) -> #'tx.select'{}; decode_method_fields('tx.select_ok', <<>>) -> #'tx.select_ok'{}; decode_method_fields('tx.commit', <<>>) -> #'tx.commit'{}; decode_method_fields('tx.commit_ok', <<>>) -> #'tx.commit_ok'{}; decode_method_fields('tx.rollback', <<>>) -> #'tx.rollback'{}; decode_method_fields('tx.rollback_ok', <<>>) -> #'tx.rollback_ok'{}; decode_method_fields('confirm.select', <<F0Bits:8>>) -> F0 = ((F0Bits band 1) /= 0), #'confirm.select'{nowait = F0}; decode_method_fields('confirm.select_ok', <<>>) -> #'confirm.select_ok'{}; decode_method_fields(Name, BinaryFields) -> rabbit_misc:frame_error(Name, BinaryFields). decode_properties(10, <<>>) -> #'P_connection'{}; decode_properties(20, <<>>) -> #'P_channel'{}; decode_properties(30, <<>>) -> #'P_access'{}; decode_properties(40, <<>>) -> #'P_exchange'{}; decode_properties(50, <<>>) -> #'P_queue'{}; decode_properties(60, <<P0:1, P1:1, P2:1, P3:1, P4:1, P5:1, P6:1, P7:1, P8:1, P9:1, P10:1, P11:1, P12:1, P13:1, _:2, R0/binary>>) -> {F0, R1} = if P0 =:= 0 -> {undefined, R0}; true -> ?SHORTSTR_VAL(R0, L0, V0, X0) end, {F1, R2} = if P1 =:= 0 -> {undefined, R1}; true -> ?SHORTSTR_VAL(R1, L1, V1, X1) end, {F2, R3} = if P2 =:= 0 -> {undefined, R2}; true -> ?TABLE_VAL(R2, L2, V2, X2) end, {F3, R4} = if P3 =:= 0 -> {undefined, R3}; true -> ?OCTET_VAL(R3, L3, V3, X3) end, {F4, R5} = if P4 =:= 0 -> {undefined, R4}; true -> ?OCTET_VAL(R4, L4, V4, X4) end, {F5, R6} = if P5 =:= 0 -> {undefined, R5}; true -> ?SHORTSTR_VAL(R5, L5, V5, X5) end, {F6, R7} = if P6 =:= 0 -> {undefined, R6}; true -> ?SHORTSTR_VAL(R6, L6, V6, X6) end, {F7, R8} = if P7 =:= 0 -> {undefined, R7}; true -> ?SHORTSTR_VAL(R7, L7, V7, X7) end, {F8, R9} = if P8 =:= 0 -> {undefined, R8}; true -> ?SHORTSTR_VAL(R8, L8, V8, X8) end, {F9, R10} = if P9 =:= 0 -> {undefined, R9}; true -> ?TIMESTAMP_VAL(R9, L9, V9, X9) end, {F10, R11} = if P10 =:= 0 -> {undefined, R10}; true -> ?SHORTSTR_VAL(R10, L10, V10, X10) end, {F11, R12} = if P11 =:= 0 -> {undefined, R11}; true -> ?SHORTSTR_VAL(R11, L11, V11, X11) end, {F12, R13} = if P12 =:= 0 -> {undefined, R12}; true -> ?SHORTSTR_VAL(R12, L12, V12, X12) end, {F13, R14} = if P13 =:= 0 -> {undefined, R13}; true -> ?SHORTSTR_VAL(R13, L13, V13, X13) end, <<>> = R14, #'P_basic'{content_type = F0, content_encoding = F1, headers = F2, delivery_mode = F3, priority = F4, correlation_id = F5, reply_to = F6, expiration = F7, message_id = F8, timestamp = F9, type = F10, user_id = F11, app_id = F12, cluster_id = F13}; decode_properties(90, <<>>) -> #'P_tx'{}; decode_properties(85, <<>>) -> #'P_confirm'{}; decode_properties(ClassId, _BinaryFields) -> exit({unknown_class_id, ClassId}). encode_method_fields(#'connection.start'{version_major = F0, version_minor = F1, server_properties = F2, mechanisms = F3, locales = F4}) -> F2Tab = rabbit_binary_generator:generate_table(F2), F2Len = size(F2Tab), F3Len = size(F3), F4Len = size(F4), <<F0:8/unsigned, F1:8/unsigned, F2Len:32/unsigned, F2Tab:F2Len/binary, F3Len:32/unsigned, F3:F3Len/binary, F4Len:32/unsigned, F4:F4Len/binary>>; encode_method_fields(#'connection.start_ok'{client_properties = F0, mechanism = F1, response = F2, locale = F3}) -> F0Tab = rabbit_binary_generator:generate_table(F0), F0Len = size(F0Tab), F1Len = shortstr_size(F1), F2Len = size(F2), F3Len = shortstr_size(F3), <<F0Len:32/unsigned, F0Tab:F0Len/binary, F1Len:8/unsigned, F1:F1Len/binary, F2Len:32/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary>>; encode_method_fields(#'connection.secure'{challenge = F0}) -> F0Len = size(F0), <<F0Len:32/unsigned, F0:F0Len/binary>>; encode_method_fields(#'connection.secure_ok'{response = F0}) -> F0Len = size(F0), <<F0Len:32/unsigned, F0:F0Len/binary>>; encode_method_fields(#'connection.tune'{channel_max = F0, frame_max = F1, heartbeat = F2}) -> <<F0:16/unsigned, F1:32/unsigned, F2:16/unsigned>>; encode_method_fields(#'connection.tune_ok'{channel_max = F0, frame_max = F1, heartbeat = F2}) -> <<F0:16/unsigned, F1:32/unsigned, F2:16/unsigned>>; encode_method_fields(#'connection.open'{virtual_host = F0, capabilities = F1, insist = F2}) -> F0Len = shortstr_size(F0), F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0)), <<F0Len:8/unsigned, F0:F0Len/binary, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'connection.open_ok'{known_hosts = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'connection.close'{reply_code = F0, reply_text = F1, class_id = F2, method_id = F3}) -> F1Len = shortstr_size(F1), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2:16/unsigned, F3:16/unsigned>>; encode_method_fields(#'connection.close_ok'{}) -> <<>>; encode_method_fields(#'connection.blocked'{reason = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'connection.unblocked'{}) -> <<>>; encode_method_fields(#'channel.open'{out_of_band = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'channel.open_ok'{channel_id = F0}) -> F0Len = size(F0), <<F0Len:32/unsigned, F0:F0Len/binary>>; encode_method_fields(#'channel.flow'{active = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'channel.flow_ok'{active = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'channel.close'{reply_code = F0, reply_text = F1, class_id = F2, method_id = F3}) -> F1Len = shortstr_size(F1), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2:16/unsigned, F3:16/unsigned>>; encode_method_fields(#'channel.close_ok'{}) -> <<>>; encode_method_fields(#'access.request'{realm = F0, exclusive = F1, passive = F2, active = F3, write = F4, read = F5}) -> F0Len = shortstr_size(F0), F1Bits = ((bitvalue(F1) bsl 0) bor (bitvalue(F2) bsl 1) bor (bitvalue(F3) bsl 2) bor (bitvalue(F4) bsl 3) bor (bitvalue(F5) bsl 4)), <<F0Len:8/unsigned, F0:F0Len/binary, F1Bits:8>>; encode_method_fields(#'access.request_ok'{ticket = F0}) -> <<F0:16/unsigned>>; encode_method_fields(#'exchange.declare'{ticket = F0, exchange = F1, type = F2, passive = F3, durable = F4, auto_delete = F5, internal = F6, nowait = F7, arguments = F8}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Bits = ((bitvalue(F3) bsl 0) bor (bitvalue(F4) bsl 1) bor (bitvalue(F5) bsl 2) bor (bitvalue(F6) bsl 3) bor (bitvalue(F7) bsl 4)), F8Tab = rabbit_binary_generator:generate_table(F8), F8Len = size(F8Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8, F8Len:32/unsigned, F8Tab:F8Len/binary>>; encode_method_fields(#'exchange.declare_ok'{}) -> <<>>; encode_method_fields(#'exchange.delete'{ticket = F0, exchange = F1, if_unused = F2, nowait = F3}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0) bor (bitvalue(F3) bsl 1)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'exchange.delete_ok'{}) -> <<>>; encode_method_fields(#'exchange.bind'{ticket = F0, destination = F1, source = F2, routing_key = F3, nowait = F4, arguments = F5}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), F4Bits = ((bitvalue(F4) bsl 0)), F5Tab = rabbit_binary_generator:generate_table(F5), F5Len = size(F5Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>; encode_method_fields(#'exchange.bind_ok'{}) -> <<>>; encode_method_fields(#'exchange.unbind'{ticket = F0, destination = F1, source = F2, routing_key = F3, nowait = F4, arguments = F5}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), F4Bits = ((bitvalue(F4) bsl 0)), F5Tab = rabbit_binary_generator:generate_table(F5), F5Len = size(F5Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>; encode_method_fields(#'exchange.unbind_ok'{}) -> <<>>; encode_method_fields(#'queue.declare'{ticket = F0, queue = F1, passive = F2, durable = F3, exclusive = F4, auto_delete = F5, nowait = F6, arguments = F7}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0) bor (bitvalue(F3) bsl 1) bor (bitvalue(F4) bsl 2) bor (bitvalue(F5) bsl 3) bor (bitvalue(F6) bsl 4)), F7Tab = rabbit_binary_generator:generate_table(F7), F7Len = size(F7Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8, F7Len:32/unsigned, F7Tab:F7Len/binary>>; encode_method_fields(#'queue.declare_ok'{queue = F0, message_count = F1, consumer_count = F2}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned, F2:32/unsigned>>; encode_method_fields(#'queue.bind'{ticket = F0, queue = F1, exchange = F2, routing_key = F3, nowait = F4, arguments = F5}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), F4Bits = ((bitvalue(F4) bsl 0)), F5Tab = rabbit_binary_generator:generate_table(F5), F5Len = size(F5Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Bits:8, F5Len:32/unsigned, F5Tab:F5Len/binary>>; encode_method_fields(#'queue.bind_ok'{}) -> <<>>; encode_method_fields(#'queue.purge'{ticket = F0, queue = F1, nowait = F2}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'queue.purge_ok'{message_count = F0}) -> <<F0:32/unsigned>>; encode_method_fields(#'queue.delete'{ticket = F0, queue = F1, if_unused = F2, if_empty = F3, nowait = F4}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0) bor (bitvalue(F3) bsl 1) bor (bitvalue(F4) bsl 2)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'queue.delete_ok'{message_count = F0}) -> <<F0:32/unsigned>>; encode_method_fields(#'queue.unbind'{ticket = F0, queue = F1, exchange = F2, routing_key = F3, arguments = F4}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), F4Tab = rabbit_binary_generator:generate_table(F4), F4Len = size(F4Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4Len:32/unsigned, F4Tab:F4Len/binary>>; encode_method_fields(#'queue.unbind_ok'{}) -> <<>>; encode_method_fields(#'basic.qos'{prefetch_size = F0, prefetch_count = F1, global = F2}) -> F2Bits = ((bitvalue(F2) bsl 0)), <<F0:32/unsigned, F1:16/unsigned, F2Bits:8>>; encode_method_fields(#'basic.qos_ok'{}) -> <<>>; encode_method_fields(#'basic.consume'{ticket = F0, queue = F1, consumer_tag = F2, no_local = F3, no_ack = F4, exclusive = F5, nowait = F6, arguments = F7}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Bits = ((bitvalue(F3) bsl 0) bor (bitvalue(F4) bsl 1) bor (bitvalue(F5) bsl 2) bor (bitvalue(F6) bsl 3)), F7Tab = rabbit_binary_generator:generate_table(F7), F7Len = size(F7Tab), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8, F7Len:32/unsigned, F7Tab:F7Len/binary>>; encode_method_fields(#'basic.consume_ok'{consumer_tag = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'basic.cancel'{consumer_tag = F0, nowait = F1}) -> F0Len = shortstr_size(F0), F1Bits = ((bitvalue(F1) bsl 0)), <<F0Len:8/unsigned, F0:F0Len/binary, F1Bits:8>>; encode_method_fields(#'basic.cancel_ok'{consumer_tag = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'basic.publish'{ticket = F0, exchange = F1, routing_key = F2, mandatory = F3, immediate = F4}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Bits = ((bitvalue(F3) bsl 0) bor (bitvalue(F4) bsl 1)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Bits:8>>; encode_method_fields(#'basic.return'{reply_code = F0, reply_text = F1, exchange = F2, routing_key = F3}) -> F1Len = shortstr_size(F1), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary>>; encode_method_fields(#'basic.deliver'{consumer_tag = F0, delivery_tag = F1, redelivered = F2, exchange = F3, routing_key = F4}) -> F0Len = shortstr_size(F0), F2Bits = ((bitvalue(F2) bsl 0)), F3Len = shortstr_size(F3), F4Len = shortstr_size(F4), <<F0Len:8/unsigned, F0:F0Len/binary, F1:64/unsigned, F2Bits:8, F3Len:8/unsigned, F3:F3Len/binary, F4Len:8/unsigned, F4:F4Len/binary>>; encode_method_fields(#'basic.get'{ticket = F0, queue = F1, no_ack = F2}) -> F1Len = shortstr_size(F1), F2Bits = ((bitvalue(F2) bsl 0)), <<F0:16/unsigned, F1Len:8/unsigned, F1:F1Len/binary, F2Bits:8>>; encode_method_fields(#'basic.get_ok'{delivery_tag = F0, redelivered = F1, exchange = F2, routing_key = F3, message_count = F4}) -> F1Bits = ((bitvalue(F1) bsl 0)), F2Len = shortstr_size(F2), F3Len = shortstr_size(F3), <<F0:64/unsigned, F1Bits:8, F2Len:8/unsigned, F2:F2Len/binary, F3Len:8/unsigned, F3:F3Len/binary, F4:32/unsigned>>; encode_method_fields(#'basic.get_empty'{cluster_id = F0}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary>>; encode_method_fields(#'basic.ack'{delivery_tag = F0, multiple = F1}) -> F1Bits = ((bitvalue(F1) bsl 0)), <<F0:64/unsigned, F1Bits:8>>; encode_method_fields(#'basic.reject'{delivery_tag = F0, requeue = F1}) -> F1Bits = ((bitvalue(F1) bsl 0)), <<F0:64/unsigned, F1Bits:8>>; encode_method_fields(#'basic.recover_async'{requeue = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'basic.recover'{requeue = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'basic.recover_ok'{}) -> <<>>; encode_method_fields(#'basic.nack'{delivery_tag = F0, multiple = F1, requeue = F2}) -> F1Bits = ((bitvalue(F1) bsl 0) bor (bitvalue(F2) bsl 1)), <<F0:64/unsigned, F1Bits:8>>; encode_method_fields(#'basic.credit'{consumer_tag = F0, credit = F1, drain = F2}) -> F0Len = shortstr_size(F0), F2Bits = ((bitvalue(F2) bsl 0)), <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned, F2Bits:8>>; encode_method_fields(#'basic.credit_ok'{available = F0}) -> <<F0:32/unsigned>>; encode_method_fields(#'basic.credit_drained'{consumer_tag = F0, credit_drained = F1}) -> F0Len = shortstr_size(F0), <<F0Len:8/unsigned, F0:F0Len/binary, F1:32/unsigned>>; encode_method_fields(#'tx.select'{}) -> <<>>; encode_method_fields(#'tx.select_ok'{}) -> <<>>; encode_method_fields(#'tx.commit'{}) -> <<>>; encode_method_fields(#'tx.commit_ok'{}) -> <<>>; encode_method_fields(#'tx.rollback'{}) -> <<>>; encode_method_fields(#'tx.rollback_ok'{}) -> <<>>; encode_method_fields(#'confirm.select'{nowait = F0}) -> F0Bits = ((bitvalue(F0) bsl 0)), <<F0Bits:8>>; encode_method_fields(#'confirm.select_ok'{}) -> <<>>; encode_method_fields(Record) -> exit({unknown_method_name, element(1, Record)}). encode_properties(#'P_connection'{}) -> <<>>; encode_properties(#'P_channel'{}) -> <<>>; encode_properties(#'P_access'{}) -> <<>>; encode_properties(#'P_exchange'{}) -> <<>>; encode_properties(#'P_queue'{}) -> <<>>; encode_properties(#'P_basic'{content_type = F0, content_encoding = F1, headers = F2, delivery_mode = F3, priority = F4, correlation_id = F5, reply_to = F6, expiration = F7, message_id = F8, timestamp = F9, type = F10, user_id = F11, app_id = F12, cluster_id = F13}) -> R0 = [<<>>], {P0, R1} = if F0 =:= undefined -> {0, R0}; true -> {1, [?SHORTSTR_PROP(F0, L0) | R0]} end, {P1, R2} = if F1 =:= undefined -> {0, R1}; true -> {1, [?SHORTSTR_PROP(F1, L1) | R1]} end, {P2, R3} = if F2 =:= undefined -> {0, R2}; true -> {1, [?TABLE_PROP(F2, L2) | R2]} end, {P3, R4} = if F3 =:= undefined -> {0, R3}; true -> {1, [?OCTET_PROP(F3, L3) | R3]} end, {P4, R5} = if F4 =:= undefined -> {0, R4}; true -> {1, [?OCTET_PROP(F4, L4) | R4]} end, {P5, R6} = if F5 =:= undefined -> {0, R5}; true -> {1, [?SHORTSTR_PROP(F5, L5) | R5]} end, {P6, R7} = if F6 =:= undefined -> {0, R6}; true -> {1, [?SHORTSTR_PROP(F6, L6) | R6]} end, {P7, R8} = if F7 =:= undefined -> {0, R7}; true -> {1, [?SHORTSTR_PROP(F7, L7) | R7]} end, {P8, R9} = if F8 =:= undefined -> {0, R8}; true -> {1, [?SHORTSTR_PROP(F8, L8) | R8]} end, {P9, R10} = if F9 =:= undefined -> {0, R9}; true -> {1, [?TIMESTAMP_PROP(F9, L9) | R9]} end, {P10, R11} = if F10 =:= undefined -> {0, R10}; true -> {1, [?SHORTSTR_PROP(F10, L10) | R10]} end, {P11, R12} = if F11 =:= undefined -> {0, R11}; true -> {1, [?SHORTSTR_PROP(F11, L11) | R11]} end, {P12, R13} = if F12 =:= undefined -> {0, R12}; true -> {1, [?SHORTSTR_PROP(F12, L12) | R12]} end, {P13, R14} = if F13 =:= undefined -> {0, R13}; true -> {1, [?SHORTSTR_PROP(F13, L13) | R13]} end, list_to_binary([<<P0:1, P1:1, P2:1, P3:1, P4:1, P5:1, P6:1, P7:1, P8:1, P9:1, P10:1, P11:1, P12:1, P13:1, 0:2>> | lists:reverse(R14)]); encode_properties(#'P_tx'{}) -> <<>>; encode_properties(#'P_confirm'{}) -> <<>>; encode_properties(Record) -> exit({unknown_properties_record, Record}). lookup_amqp_exception(content_too_large) -> {false, ?CONTENT_TOO_LARGE, <<"CONTENT_TOO_LARGE">>}; lookup_amqp_exception(no_route) -> {false, ?NO_ROUTE, <<"NO_ROUTE">>}; lookup_amqp_exception(no_consumers) -> {false, ?NO_CONSUMERS, <<"NO_CONSUMERS">>}; lookup_amqp_exception(access_refused) -> {false, ?ACCESS_REFUSED, <<"ACCESS_REFUSED">>}; lookup_amqp_exception(not_found) -> {false, ?NOT_FOUND, <<"NOT_FOUND">>}; lookup_amqp_exception(resource_locked) -> {false, ?RESOURCE_LOCKED, <<"RESOURCE_LOCKED">>}; lookup_amqp_exception(precondition_failed) -> {false, ?PRECONDITION_FAILED, <<"PRECONDITION_FAILED">>}; lookup_amqp_exception(connection_forced) -> {true, ?CONNECTION_FORCED, <<"CONNECTION_FORCED">>}; lookup_amqp_exception(invalid_path) -> {true, ?INVALID_PATH, <<"INVALID_PATH">>}; lookup_amqp_exception(frame_error) -> {true, ?FRAME_ERROR, <<"FRAME_ERROR">>}; lookup_amqp_exception(syntax_error) -> {true, ?SYNTAX_ERROR, <<"SYNTAX_ERROR">>}; lookup_amqp_exception(command_invalid) -> {true, ?COMMAND_INVALID, <<"COMMAND_INVALID">>}; lookup_amqp_exception(channel_error) -> {true, ?CHANNEL_ERROR, <<"CHANNEL_ERROR">>}; lookup_amqp_exception(unexpected_frame) -> {true, ?UNEXPECTED_FRAME, <<"UNEXPECTED_FRAME">>}; lookup_amqp_exception(resource_error) -> {true, ?RESOURCE_ERROR, <<"RESOURCE_ERROR">>}; lookup_amqp_exception(not_allowed) -> {true, ?NOT_ALLOWED, <<"NOT_ALLOWED">>}; lookup_amqp_exception(not_implemented) -> {true, ?NOT_IMPLEMENTED, <<"NOT_IMPLEMENTED">>}; lookup_amqp_exception(internal_error) -> {true, ?INTERNAL_ERROR, <<"INTERNAL_ERROR">>}; lookup_amqp_exception(Code) -> rabbit_log:warning("Unknown AMQP error code '~p'~n", [Code]), {true, ?INTERNAL_ERROR, <<"INTERNAL_ERROR">>}. amqp_exception(?FRAME_METHOD) -> frame_method; amqp_exception(?FRAME_HEADER) -> frame_header; amqp_exception(?FRAME_BODY) -> frame_body; amqp_exception(?FRAME_HEARTBEAT) -> frame_heartbeat; amqp_exception(?FRAME_MIN_SIZE) -> frame_min_size; amqp_exception(?FRAME_END) -> frame_end; amqp_exception(?REPLY_SUCCESS) -> reply_success; amqp_exception(?CONTENT_TOO_LARGE) -> content_too_large; amqp_exception(?NO_ROUTE) -> no_route; amqp_exception(?NO_CONSUMERS) -> no_consumers; amqp_exception(?ACCESS_REFUSED) -> access_refused; amqp_exception(?NOT_FOUND) -> not_found; amqp_exception(?RESOURCE_LOCKED) -> resource_locked; amqp_exception(?PRECONDITION_FAILED) -> precondition_failed; amqp_exception(?CONNECTION_FORCED) -> connection_forced; amqp_exception(?INVALID_PATH) -> invalid_path; amqp_exception(?FRAME_ERROR) -> frame_error; amqp_exception(?SYNTAX_ERROR) -> syntax_error; amqp_exception(?COMMAND_INVALID) -> command_invalid; amqp_exception(?CHANNEL_ERROR) -> channel_error; amqp_exception(?UNEXPECTED_FRAME) -> unexpected_frame; amqp_exception(?RESOURCE_ERROR) -> resource_error; amqp_exception(?NOT_ALLOWED) -> not_allowed; amqp_exception(?NOT_IMPLEMENTED) -> not_implemented; amqp_exception(?INTERNAL_ERROR) -> internal_error; amqp_exception(_Code) -> undefined.
79d66de43d48071503893f584667482c4d136b0402bc88e5f76456c5bd4a75e5
saikyun/clobits
wasd_rect.clj
(set! *warn-on-reflection* true) ; reflection warnings on structs means ; that native image will crash when accessing fields (ns clobits.examples.sdl.wasd-rect (:require [clobits.native-interop :refer [*native-image*]] ; this just sets *native-image* [clobits.examples.sdl.constants :as cs]) (:import [clobits.sdl Surface Rect]) (:gen-class)) (if *native-image* (do (println "In native image context") (require '[clobits.sdl.ni :as sdl])) (do (println "In polyglot context") (require '[clobits.sdl.poly :as sdl]))) (comment (.getMemberKeys (.getMember (.execute (.getMember sdl/polyglot-lib "_SHADOWING_get_e") (clojure.core/object-array [])) "key")) (.getMember sdl/polyglot-lib "SDL_KeyCode") ) (defmacro case+ "Same as case, but evaluates dispatch values, needed for referring to class and def'ed constants as well as java.util.Enum instances." [value & clauses] (let [clauses (partition 2 2 nil clauses) default (when (-> clauses last count (== 1)) (last clauses)) clauses (if default (drop-last clauses) clauses) eval-dispatch (fn [d] (if (list? d) (map eval d) (eval d)))] `(case ~value ~@(concat (->> clauses (map #(-> % first eval-dispatch (list (second %)))) (mapcat identity)) default)))) (defn handle-input [state] (loop [state state] (if (= 0 (sdl/poll-event (sdl/get-e))) state (case (.type (sdl/get-e)) 256 (assoc state :quit true) 768 ;; key down (do (case+ (.sym (.keysym (.key (sdl/get-e)))) cs/d (update state :down conj :right) cs/a (update state :down conj :left) cs/w (update state :down conj :up) cs/s (update state :down conj :down) (do (println "key down" (.sym (.keysym (.key (sdl/get-e))))) state))) 769 ;; key up (case+ (.sym (.keysym (.key (sdl/get-e)))) cs/d (update state :down disj :right) cs/a (update state :down disj :left) cs/w (update state :down disj :up) cs/s (update state :down disj :down) (do (println "key up" (.sym (.keysym (.key (sdl/get-e))))) state)) (do #_(println "event type" (.type (sdl/get-e))) (recur state)))))) (defn main-loop [window ^Surface screen ^Rect rect state] (let [state (cond-> (handle-input state) (-> state :down :right) (update-in [:pos :x] inc) (-> state :down :left) (update-in [:pos :x] dec) (-> state :down :down) (update-in [:pos :y] inc) (-> state :down :up) (update-in [:pos :y] dec))] (.set_x rect (-> state :pos :x)) (.set_y rect (-> state :pos :y)) (sdl/fill-rect screen (sdl/get-null) (sdl/map-rgb (.format screen) 0 0 0)) (sdl/fill-rect screen rect (sdl/map-rgb (.format screen) 0xFF 0 0)) (sdl/update-window-surface window) state)) (defn -main [& args] (sdl/init (sdl/get-sdl-init-video)) (let [window (sdl/create-window (sdl/gen-title) 0 0 640 480 (sdl/get-sdl-window-shown)) screen (sdl/get-window-surface window) rect (sdl/create-rect 0 0 100 50)] (.set_format screen (.format screen)) (println "rgb1" (sdl/map-rgb (.format screen) 0xFF 0xFF 0xFF)) (println "rgb2" (sdl/map-rgb (.format screen) 0xFF 0 0)) (loop [state {:quit false :down #{} :pos {:x 0 :y 0}}] (let [state (try (main-loop window screen rect state) (catch Exception e (println "Got error" e) state))] (when-not (:quit state) (Thread/sleep 10) (recur state)))) (sdl/quit))) (comment (-main) )
null
https://raw.githubusercontent.com/saikyun/clobits/67bc60cbf6bed8a5178d552d3485e4117fb4df10/examples/sdl/src/clobits/examples/sdl/wasd_rect.clj
clojure
reflection warnings on structs means that native image will crash when accessing fields this just sets *native-image* key down key up
(ns clobits.examples.sdl.wasd-rect [clobits.examples.sdl.constants :as cs]) (:import [clobits.sdl Surface Rect]) (:gen-class)) (if *native-image* (do (println "In native image context") (require '[clobits.sdl.ni :as sdl])) (do (println "In polyglot context") (require '[clobits.sdl.poly :as sdl]))) (comment (.getMemberKeys (.getMember (.execute (.getMember sdl/polyglot-lib "_SHADOWING_get_e") (clojure.core/object-array [])) "key")) (.getMember sdl/polyglot-lib "SDL_KeyCode") ) (defmacro case+ "Same as case, but evaluates dispatch values, needed for referring to class and def'ed constants as well as java.util.Enum instances." [value & clauses] (let [clauses (partition 2 2 nil clauses) default (when (-> clauses last count (== 1)) (last clauses)) clauses (if default (drop-last clauses) clauses) eval-dispatch (fn [d] (if (list? d) (map eval d) (eval d)))] `(case ~value ~@(concat (->> clauses (map #(-> % first eval-dispatch (list (second %)))) (mapcat identity)) default)))) (defn handle-input [state] (loop [state state] (if (= 0 (sdl/poll-event (sdl/get-e))) state (case (.type (sdl/get-e)) 256 (assoc state :quit true) (do (case+ (.sym (.keysym (.key (sdl/get-e)))) cs/d (update state :down conj :right) cs/a (update state :down conj :left) cs/w (update state :down conj :up) cs/s (update state :down conj :down) (do (println "key down" (.sym (.keysym (.key (sdl/get-e))))) state))) (case+ (.sym (.keysym (.key (sdl/get-e)))) cs/d (update state :down disj :right) cs/a (update state :down disj :left) cs/w (update state :down disj :up) cs/s (update state :down disj :down) (do (println "key up" (.sym (.keysym (.key (sdl/get-e))))) state)) (do #_(println "event type" (.type (sdl/get-e))) (recur state)))))) (defn main-loop [window ^Surface screen ^Rect rect state] (let [state (cond-> (handle-input state) (-> state :down :right) (update-in [:pos :x] inc) (-> state :down :left) (update-in [:pos :x] dec) (-> state :down :down) (update-in [:pos :y] inc) (-> state :down :up) (update-in [:pos :y] dec))] (.set_x rect (-> state :pos :x)) (.set_y rect (-> state :pos :y)) (sdl/fill-rect screen (sdl/get-null) (sdl/map-rgb (.format screen) 0 0 0)) (sdl/fill-rect screen rect (sdl/map-rgb (.format screen) 0xFF 0 0)) (sdl/update-window-surface window) state)) (defn -main [& args] (sdl/init (sdl/get-sdl-init-video)) (let [window (sdl/create-window (sdl/gen-title) 0 0 640 480 (sdl/get-sdl-window-shown)) screen (sdl/get-window-surface window) rect (sdl/create-rect 0 0 100 50)] (.set_format screen (.format screen)) (println "rgb1" (sdl/map-rgb (.format screen) 0xFF 0xFF 0xFF)) (println "rgb2" (sdl/map-rgb (.format screen) 0xFF 0 0)) (loop [state {:quit false :down #{} :pos {:x 0 :y 0}}] (let [state (try (main-loop window screen rect state) (catch Exception e (println "Got error" e) state))] (when-not (:quit state) (Thread/sleep 10) (recur state)))) (sdl/quit))) (comment (-main) )
eeee72b0e93d3b1d5de6696c0302dbb04fbadb6c0e8a1ff6da5ba527f2c2c077
ates/bb
bb.erl
-module(bb). -export([start/1]). -export([float2list/1]). -export([float2list/2]). -export([float2binary/1]). -export([from_json/1]). -export([get_env/1]). -export([get_env/2]). -export([timestamp/0]). -export([signature/2]). -export([to_binary/1]). -export([fee/0]). start(Opts) -> bb_stream:start_link(Opts). float2list(Value) when is_float(Value) -> float2list(Value, 8). float2list(Value, N) -> erlang:float_to_list(Value, [{decimals, N}]). float2binary(Value) when is_float(Value) -> erlang:float_to_binary(Value, [{decimals, application:get_env(bb, d, 8)}]). from_json(Data) -> jsx:decode(Data, [return_maps, {labels, atom}]). get_env(Option) -> get_env(Option, undefined). get_env(Option, Default) -> application:get_env(bb, Option, Default). timestamp() -> erlang:system_time(milli_seconds). signature(Query, Secret) -> Hash = crypto:hmac(sha256, Secret, Query), list_to_binary(lists:flatten([io_lib:format("~2.16.0b", [N]) || <<N:8>> <= Hash])). to_binary(Data) when is_list(Data) -> list_to_binary(Data); to_binary(Data) when is_atom(Data) -> atom_to_binary(Data, latin1); to_binary(Data) when is_integer(Data) -> integer_to_binary(Data); to_binary(Data) when is_float(Data) -> float_to_binary(Data); to_binary(Data) when is_binary(Data) -> Data. fee() -> application:get_env(?MODULE, fee, 0.10).
null
https://raw.githubusercontent.com/ates/bb/a189335a2912e589b61d43e589f53edce6fa8421/src/bb.erl
erlang
-module(bb). -export([start/1]). -export([float2list/1]). -export([float2list/2]). -export([float2binary/1]). -export([from_json/1]). -export([get_env/1]). -export([get_env/2]). -export([timestamp/0]). -export([signature/2]). -export([to_binary/1]). -export([fee/0]). start(Opts) -> bb_stream:start_link(Opts). float2list(Value) when is_float(Value) -> float2list(Value, 8). float2list(Value, N) -> erlang:float_to_list(Value, [{decimals, N}]). float2binary(Value) when is_float(Value) -> erlang:float_to_binary(Value, [{decimals, application:get_env(bb, d, 8)}]). from_json(Data) -> jsx:decode(Data, [return_maps, {labels, atom}]). get_env(Option) -> get_env(Option, undefined). get_env(Option, Default) -> application:get_env(bb, Option, Default). timestamp() -> erlang:system_time(milli_seconds). signature(Query, Secret) -> Hash = crypto:hmac(sha256, Secret, Query), list_to_binary(lists:flatten([io_lib:format("~2.16.0b", [N]) || <<N:8>> <= Hash])). to_binary(Data) when is_list(Data) -> list_to_binary(Data); to_binary(Data) when is_atom(Data) -> atom_to_binary(Data, latin1); to_binary(Data) when is_integer(Data) -> integer_to_binary(Data); to_binary(Data) when is_float(Data) -> float_to_binary(Data); to_binary(Data) when is_binary(Data) -> Data. fee() -> application:get_env(?MODULE, fee, 0.10).
fdd13e181a89875f96642febf2b9f5c4afcad27c5fb4fce1789e1ff3ea79e2b7
jwiegley/gitlib
Smoke.hs
{-# LANGUAGE OverloadedStrings #-} # OPTIONS_GHC -fno - warn - unused - do - bind # # OPTIONS_GHC -fno - warn - wrong - do - bind # # OPTIONS_GHC -fno - warn - name - shadowing # module Main where import qualified Git.CmdLine as Cli import qualified Git.Smoke as Git import Test.Hspec.HUnit () import Test.Hspec.Runner main :: IO () main = hspec $ Git.smokeTestSpec Cli.cliFactory Cli.cliFactory Smoke.hs ends here
null
https://raw.githubusercontent.com/jwiegley/gitlib/7d7ee1a62de723e3ebbbcaf7c262d6b43936329c/gitlib-cmdline/test/Smoke.hs
haskell
# LANGUAGE OverloadedStrings #
# OPTIONS_GHC -fno - warn - unused - do - bind # # OPTIONS_GHC -fno - warn - wrong - do - bind # # OPTIONS_GHC -fno - warn - name - shadowing # module Main where import qualified Git.CmdLine as Cli import qualified Git.Smoke as Git import Test.Hspec.HUnit () import Test.Hspec.Runner main :: IO () main = hspec $ Git.smokeTestSpec Cli.cliFactory Cli.cliFactory Smoke.hs ends here
b74b5d742a86055079eae2f5d9f5043f6052dd7cf9f7c2467f2e4a53650607f8
BebeSparkelSparkel/biparsing
Main.hs
module Main where import GHC.Generics import Biparse import Control.Monad ( (>=>), (<=<) ) import Control.Monad.Trans.State.Lazy( StateT, evalStateT, get ) import Data.Bifunctor ( bimap ) import Data.Functor.Barbie ( FunctorB(bmap) ) import Data.Functor.Identity ( Identity ) import Lens.Micro import Prelude as P import System.Environment (getArgs) import System.Exit (exitWith, ExitCode( ExitFailure) ) import Data.Monoid.Generic ( GenericSemigroup, GenericMonoid ) import Data.Bifunctor( Bifunctor(first) ) lines :: Iso String [String] lines = Biparser P.lines unlines type LineNumber = Int type NumberedLine = (LineNumber, String) number :: Biparser ([String] -> [NumberedLine]) ([String] -> [String]) number = undefined data GroupCodeValueType a = GroupCodeValueType Int a groupCodeValueTypes :: Biparser ([NumberedLine] -> [(LineNumber, GroupCodeValueType String)]) ([GroupCodeValueType String] -> [String]) groupCodeValueTypes = Biparser parse serialize where parse = data DXF h c t b e o m = DXF { header :: m h , classes :: m c , tables :: m t , blocks :: m b , entities :: m e , objects :: m o } deriving Generic -- deriving Semigroup via GenericSemigroup (DXF h c t b e o m) deriving Monoid via GenericMonoid ( DXF h c t b e o m ) instance ( Semigroup (m h) , Semigroup (m c) , Semigroup (m t) , Semigroup (m b) , Semigroup (m e) , Semigroup (m o) ) => Semigroup (DXF h c t b e o m) where x <> y = undefined instance ( Monoid (m h) , Monoid (m c) , Monoid (m t) , Monoid (m b) , Monoid (m e) , Monoid (m o) ) => Monoid (DXF h c t b e o m) where mempty = DXF mempty mempty mempty mempty mempty mempty data Section = Header | Classes | Tables | Blocks | Entities | Objects sectionFromString :: String -> Maybe Section sectionFromString = undefined data Result a = Error (Maybe LineNumber) String | ErrorMultiple [(Maybe LineNumber, String)] | Success a deriving (Generic, Functor) instance Applicative Result where pure = Success (<*>) = undefined instance Monad Result where (>>=) = undefined section :: Biparser (StateT [NumberedLine] Result (Section, [NumberedLine])) ([NumberedLine] -> [NumberedLine]) section = Biparser parser id where parser = undefined -- parser = do -- get >>= \ls -> case ls of ( _ , " 0 " ) : ( _ , " SECTION " ) : ( _ , " 2 " ) : - > case ls ' of type RawSections m = DXF [NumberedLine] [NumberedLine] [NumberedLine] [NumberedLine] [NumberedLine] [NumberedLine] m sections :: Biparser ([NumberedLine] -> Result (RawSections Identity)) ((RawSections Identity) -> [NumberedLine]) sections = first (\f -> errorIfNotAllSectionsFound <=< evalStateT (f mempty)) ( addSection header <=>> addSection classes <=>> addSection tables <=>> addSection blocks <=>> addSection entities <=>> addSection objects ) where setterBySection :: Section -> NumberedLine -> RawSections a -> RawSections a setterBySection = undefined getterBySection :: Section -> RawSections a -> a [NumberedLine] getterBySection = undefined addSection :: (RawSections a -> a [NumberedLine]) -> Biparser (RawSections Maybe -> StateT [NumberedLine] Result (RawSections Maybe)) (RawSections Identity -> [NumberedLine]) addSection getter = undefined addSection s nls = flip evalStateT nls do ( section , sectionLines ) < - s -- case section of -- Header (<=>>) :: (Semigroup c, Monad m) => Biparser (a -> m a) (b -> c) -> Biparser (a -> m a) (b -> c) -> Biparser (a -> m a) (b -> c) Biparser x y <=>> Biparser x' y' = Biparser (x >=> x') \z -> y z <> y' z errorIfNotAllSectionsFound :: RawSections Maybe -> Result (RawSections Identity) errorIfNotAllSectionsFound = undefined subSequence header ( \x y - > x { header = y } ) " Missing the HEADER section " > = > subSequence classes ( \x y - > x { classes = y } ) " Missing the CLASSES section " > = > subSequence tables ( \x y - > x { tables = y } ) " Missing the TABLES section " > = > subSequence blocks ( \x y - > x { blocks = y } ) " Missing the BLOCKS section " > = > subSequence entities ( \x y - > x { entities = y } ) " Missing the ENTITIES section " > = > subSequence objects ( \x y - > x { objects = y } ) " Missing the OBJECTS section " -- where -- subSequence :: (a -> m b) -> (a -> n b -> c) -> String -> a -> Result c -- subSequence = undefined pheader :: Biparser (DXF h c t b e o m -> Result (DXF h c t b e o m) pheader main :: IO () main = getArgs >>= pure . (^? ix 0) >>= \case Nothing -> do print "Error: Need DXF file argument." exitWith $ ExitFailure 1 Just fileName -> do contents <- readFile fileName putStr contents
null
https://raw.githubusercontent.com/BebeSparkelSparkel/biparsing/a34bf6638ea033bffc9ab4d1742e2433f43cf932/app/Main.hs
haskell
deriving Semigroup via GenericSemigroup (DXF h c t b e o m) parser = do get >>= \ls -> case ls of case section of Header where subSequence :: (a -> m b) -> (a -> n b -> c) -> String -> a -> Result c subSequence = undefined
module Main where import GHC.Generics import Biparse import Control.Monad ( (>=>), (<=<) ) import Control.Monad.Trans.State.Lazy( StateT, evalStateT, get ) import Data.Bifunctor ( bimap ) import Data.Functor.Barbie ( FunctorB(bmap) ) import Data.Functor.Identity ( Identity ) import Lens.Micro import Prelude as P import System.Environment (getArgs) import System.Exit (exitWith, ExitCode( ExitFailure) ) import Data.Monoid.Generic ( GenericSemigroup, GenericMonoid ) import Data.Bifunctor( Bifunctor(first) ) lines :: Iso String [String] lines = Biparser P.lines unlines type LineNumber = Int type NumberedLine = (LineNumber, String) number :: Biparser ([String] -> [NumberedLine]) ([String] -> [String]) number = undefined data GroupCodeValueType a = GroupCodeValueType Int a groupCodeValueTypes :: Biparser ([NumberedLine] -> [(LineNumber, GroupCodeValueType String)]) ([GroupCodeValueType String] -> [String]) groupCodeValueTypes = Biparser parse serialize where parse = data DXF h c t b e o m = DXF { header :: m h , classes :: m c , tables :: m t , blocks :: m b , entities :: m e , objects :: m o } deriving Generic deriving Monoid via GenericMonoid ( DXF h c t b e o m ) instance ( Semigroup (m h) , Semigroup (m c) , Semigroup (m t) , Semigroup (m b) , Semigroup (m e) , Semigroup (m o) ) => Semigroup (DXF h c t b e o m) where x <> y = undefined instance ( Monoid (m h) , Monoid (m c) , Monoid (m t) , Monoid (m b) , Monoid (m e) , Monoid (m o) ) => Monoid (DXF h c t b e o m) where mempty = DXF mempty mempty mempty mempty mempty mempty data Section = Header | Classes | Tables | Blocks | Entities | Objects sectionFromString :: String -> Maybe Section sectionFromString = undefined data Result a = Error (Maybe LineNumber) String | ErrorMultiple [(Maybe LineNumber, String)] | Success a deriving (Generic, Functor) instance Applicative Result where pure = Success (<*>) = undefined instance Monad Result where (>>=) = undefined section :: Biparser (StateT [NumberedLine] Result (Section, [NumberedLine])) ([NumberedLine] -> [NumberedLine]) section = Biparser parser id where parser = undefined ( _ , " 0 " ) : ( _ , " SECTION " ) : ( _ , " 2 " ) : - > case ls ' of type RawSections m = DXF [NumberedLine] [NumberedLine] [NumberedLine] [NumberedLine] [NumberedLine] [NumberedLine] m sections :: Biparser ([NumberedLine] -> Result (RawSections Identity)) ((RawSections Identity) -> [NumberedLine]) sections = first (\f -> errorIfNotAllSectionsFound <=< evalStateT (f mempty)) ( addSection header <=>> addSection classes <=>> addSection tables <=>> addSection blocks <=>> addSection entities <=>> addSection objects ) where setterBySection :: Section -> NumberedLine -> RawSections a -> RawSections a setterBySection = undefined getterBySection :: Section -> RawSections a -> a [NumberedLine] getterBySection = undefined addSection :: (RawSections a -> a [NumberedLine]) -> Biparser (RawSections Maybe -> StateT [NumberedLine] Result (RawSections Maybe)) (RawSections Identity -> [NumberedLine]) addSection getter = undefined addSection s nls = flip evalStateT nls do ( section , sectionLines ) < - s (<=>>) :: (Semigroup c, Monad m) => Biparser (a -> m a) (b -> c) -> Biparser (a -> m a) (b -> c) -> Biparser (a -> m a) (b -> c) Biparser x y <=>> Biparser x' y' = Biparser (x >=> x') \z -> y z <> y' z errorIfNotAllSectionsFound :: RawSections Maybe -> Result (RawSections Identity) errorIfNotAllSectionsFound = undefined subSequence header ( \x y - > x { header = y } ) " Missing the HEADER section " > = > subSequence classes ( \x y - > x { classes = y } ) " Missing the CLASSES section " > = > subSequence tables ( \x y - > x { tables = y } ) " Missing the TABLES section " > = > subSequence blocks ( \x y - > x { blocks = y } ) " Missing the BLOCKS section " > = > subSequence entities ( \x y - > x { entities = y } ) " Missing the ENTITIES section " > = > subSequence objects ( \x y - > x { objects = y } ) " Missing the OBJECTS section " pheader :: Biparser (DXF h c t b e o m -> Result (DXF h c t b e o m) pheader main :: IO () main = getArgs >>= pure . (^? ix 0) >>= \case Nothing -> do print "Error: Need DXF file argument." exitWith $ ExitFailure 1 Just fileName -> do contents <- readFile fileName putStr contents
1b4cf0ad738c7b95797c0a66b6aec6e6e85bceec8a194d0f1f9a5e130e3122e6
wiseman/coole-radar
cooleradar_test.cljs
(ns lemondronor.cooleradar-test (:require [cljs.test :refer (deftest is)] [lemondronor.cooleradar :as cooleradar])) (def epsilon 0.0000001) (defn a= [a b] (< (Math/abs (- a b)) epsilon)) (defn normalize-angle [a] (mod (+ a (* 2 Math/PI)) (* 2 Math/PI))) (defn angles= [a b] (a= (normalize-angle a) (normalize-angle b))) (deftest bearing->angle (is (angles= (cooleradar/bearing->angle 0) (/ Math/PI 2))) (is (angles= (cooleradar/bearing->angle (/ Math/PI 2)) 0)) (is (angles= (cooleradar/bearing->angle Math/PI) (* 2 (/ 3 4) Math/PI)))) (def pos1 {:lat 34.133856404730224 :lon -118.19234294423293}) (def pos2 {:lat 34.1576265 :lon -118.29006930000001}) (deftest distance (is (a= (cooleradar/distance pos1 pos2) 9.3763996))) (deftest bearing (is (a= (cooleradar/bearing pos1 pos2) (cooleradar/to-radians 286.40522)))) (deftest update-radar (let [radar0 {:lat 1 :lon 2 :rpm 1} now (.getTime (js/Date.)) radar1 (cooleradar/update-radar radar0 now) radar2 (cooleradar/update-radar radar1 (+ now 1000)) radar3 (cooleradar/update-radar radar2 (+ now 2000))] (is (= radar1 {:lat 1 :lon 2 :rpm 1 :prev-bearing 0 :bearing 0 :prev-update-time now})) (is (= [(:lat radar2) (:lon radar2)] [1 2])) (is (= (:prev-bearing radar2) 0)) (is (= (:prev-update-time radar2) (+ now 1000))) (is (angles= (:bearing radar2) (cooleradar/to-radians (* 1 (/ 360 60))))) (is (angles= (:bearing radar3) (cooleradar/to-radians (* 2 (/ 360 60)))))))
null
https://raw.githubusercontent.com/wiseman/coole-radar/287940817d58e4e6cbb081a6fef2b034df83eb29/src/test/lemondronor/cooleradar_test.cljs
clojure
(ns lemondronor.cooleradar-test (:require [cljs.test :refer (deftest is)] [lemondronor.cooleradar :as cooleradar])) (def epsilon 0.0000001) (defn a= [a b] (< (Math/abs (- a b)) epsilon)) (defn normalize-angle [a] (mod (+ a (* 2 Math/PI)) (* 2 Math/PI))) (defn angles= [a b] (a= (normalize-angle a) (normalize-angle b))) (deftest bearing->angle (is (angles= (cooleradar/bearing->angle 0) (/ Math/PI 2))) (is (angles= (cooleradar/bearing->angle (/ Math/PI 2)) 0)) (is (angles= (cooleradar/bearing->angle Math/PI) (* 2 (/ 3 4) Math/PI)))) (def pos1 {:lat 34.133856404730224 :lon -118.19234294423293}) (def pos2 {:lat 34.1576265 :lon -118.29006930000001}) (deftest distance (is (a= (cooleradar/distance pos1 pos2) 9.3763996))) (deftest bearing (is (a= (cooleradar/bearing pos1 pos2) (cooleradar/to-radians 286.40522)))) (deftest update-radar (let [radar0 {:lat 1 :lon 2 :rpm 1} now (.getTime (js/Date.)) radar1 (cooleradar/update-radar radar0 now) radar2 (cooleradar/update-radar radar1 (+ now 1000)) radar3 (cooleradar/update-radar radar2 (+ now 2000))] (is (= radar1 {:lat 1 :lon 2 :rpm 1 :prev-bearing 0 :bearing 0 :prev-update-time now})) (is (= [(:lat radar2) (:lon radar2)] [1 2])) (is (= (:prev-bearing radar2) 0)) (is (= (:prev-update-time radar2) (+ now 1000))) (is (angles= (:bearing radar2) (cooleradar/to-radians (* 1 (/ 360 60))))) (is (angles= (:bearing radar3) (cooleradar/to-radians (* 2 (/ 360 60)))))))
6dabd0e779253c3b19ba3be88bb46ba56f59ba1d1a5524b180d69966423f4e94
ocurrent/ocurrent
service.ml
open Lwt.Infix type t = No_context let id = "docker-service" module Key = struct type t = { name : string; docker_context : string option; } [@@deriving to_yojson] let digest t = Yojson.Safe.to_string (to_yojson t) end module Value = struct type t = { image : Image.t; } let digest { image } = Yojson.Safe.to_string @@ `Assoc [ "image", `String (Image.hash image); ] end module Outcome = Current.Unit let cmd { Key.name; docker_context } { Value.image } = Cmd.docker ~docker_context ["service"; "update"; "--image"; Image.hash image; name] let publish No_context job key value = Current.Job.start job ~level:Current.Level.Dangerous >>= fun () -> Current.Process.exec ~cancellable:true ~job (cmd key value) let pp f (key, value) = Cmd.pp f (cmd key value) let auto_cancel = false
null
https://raw.githubusercontent.com/ocurrent/ocurrent/344af83279e9ba17f5f32d0a0351c228a6f42863/plugins/docker/service.ml
ocaml
open Lwt.Infix type t = No_context let id = "docker-service" module Key = struct type t = { name : string; docker_context : string option; } [@@deriving to_yojson] let digest t = Yojson.Safe.to_string (to_yojson t) end module Value = struct type t = { image : Image.t; } let digest { image } = Yojson.Safe.to_string @@ `Assoc [ "image", `String (Image.hash image); ] end module Outcome = Current.Unit let cmd { Key.name; docker_context } { Value.image } = Cmd.docker ~docker_context ["service"; "update"; "--image"; Image.hash image; name] let publish No_context job key value = Current.Job.start job ~level:Current.Level.Dangerous >>= fun () -> Current.Process.exec ~cancellable:true ~job (cmd key value) let pp f (key, value) = Cmd.pp f (cmd key value) let auto_cancel = false
b6ffd9a597e79760c0617dc73640af7daff622a03a36d2a92c33dd7aec01fbca
ocaml-multicore/tezos
shell_services_test_helpers.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2021 Nomadic Labs , < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Lib_test.Qcheck2_helpers let raw_context_gen = let open Tezos_shell_services.Block_services in let module MapGen = MakeMapGen (TzString.Map) in let open QCheck2 in let open Gen in (* Factor used to limit the depth of the tree. *) let max_depth_factor = 10 in fix (fun self current_depth_factor -> frequency [ (max_depth_factor, map (fun b -> Key b) bytes_gen); (max_depth_factor, pure Cut); ( current_depth_factor, map (fun d -> Dir d) (MapGen.gen_of_size (0 -- 10) string (self (current_depth_factor / 2))) ); ]) max_depth_factor let print_raw_context = Format.asprintf "%a" Tezos_shell_services.Block_services.pp_raw_context * Strings that are valid Irmin hashes . Taken from the output of : [ tezos - client rpc get /chains / main / blocks / head / context / merkle_tree / active_delegates_with_rolls ] [tezos-client rpc get /chains/main/blocks/head/context/merkle_tree/active_delegates_with_rolls] *) let irmin_hashes = [ "CoVbip7pyXZDp1umo3cGUbCWJUA8wDkPbWR56wKqS434DiDSwGWC"; "CoVuTbwGSJyu9xD7vYYxxcqCFwCPf55UBqu8iqRcHYrs3Gu31v8y"; "CoUiEnajKeukmYFUgWTJF2z3v24MycpTaomF8a9hRzVy7as9hvgy"; "CoVngnGTJfudgcayQqtz2ZyWTUFB6zHmhvV1itjncRzYS4wndhH8"; "CoVe9oDs8t8WgH9JHB3DqbvxCZw1Q5ky7qBsZfMiLeKe6RiSMHn1"; "CoVXSYbKxP7jJL4ZSZnCsyynEZ6aeR7HR59UVKCDZdMGa8QCLFfW"; "CoVSQwz1mSz28kNCBso3F3ZHuLj5GXwXovu4byqweTa96bJAzTX6"; "CoVEow8t8iz6gfxB7daEHjFRD5suzdhb3wNZ5rMnoUTdjbYvxbez"; "CoVZDcjRgjmKnAhetUtb1AVQYwuUi3fBK7js11vjBETPuG5FcU8o"; "CoWRLgT2SwZkCWCwyTBxxkxPxYFvTWtHfKqX8MFQ1hNWL4SS1qdU"; "CoWVK1YzoDnMGrNioKL9Mze6s4XX8Uw9Vp9hPHYXqHfaFpwnmXmA"; "CoVnWzSVjbYHCQLD53JGJfWRSjUBrkbtCrNMgmsXX6bMhy7CE7E6"; ] let irmin_hash_gen = QCheck2.Gen.oneofl irmin_hashes let merkle_node_gen = let open Tezos_shell_services.Block_services in let module MapGen = MakeMapGen (TzString.Map) in let open QCheck2.Gen in let max_depth_factor = 4 in fix (fun self current_depth_factor -> frequency [ ( max_depth_factor, map (fun (kind, hash) -> Hash (kind, hash)) (pair (oneofl [Contents; Node]) irmin_hash_gen) ); ( max_depth_factor, map (fun raw_context -> Data raw_context) raw_context_gen ); ( current_depth_factor, map (fun merkle_node_map -> Continue merkle_node_map) (MapGen.gen_of_size (0 -- 5) (small_string ?gen:None) (self (current_depth_factor / 2))) ); ]) max_depth_factor let print_merkle_node = Format.asprintf "%a" Tezos_shell_services.Block_services.pp_merkle_node let merkle_tree_gen = let open MakeMapGen (TzString.Map) in gen_of_size QCheck2.Gen.(0 -- 5) (QCheck2.Gen.small_string ?gen:None) merkle_node_gen let print_merkle_tree = Format.asprintf "%a" Tezos_shell_services.Block_services.pp_merkle_tree
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/lib_shell_services/test_helpers/shell_services_test_helpers.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** Factor used to limit the depth of the tree.
Copyright ( c ) 2021 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Lib_test.Qcheck2_helpers let raw_context_gen = let open Tezos_shell_services.Block_services in let module MapGen = MakeMapGen (TzString.Map) in let open QCheck2 in let open Gen in let max_depth_factor = 10 in fix (fun self current_depth_factor -> frequency [ (max_depth_factor, map (fun b -> Key b) bytes_gen); (max_depth_factor, pure Cut); ( current_depth_factor, map (fun d -> Dir d) (MapGen.gen_of_size (0 -- 10) string (self (current_depth_factor / 2))) ); ]) max_depth_factor let print_raw_context = Format.asprintf "%a" Tezos_shell_services.Block_services.pp_raw_context * Strings that are valid Irmin hashes . Taken from the output of : [ tezos - client rpc get /chains / main / blocks / head / context / merkle_tree / active_delegates_with_rolls ] [tezos-client rpc get /chains/main/blocks/head/context/merkle_tree/active_delegates_with_rolls] *) let irmin_hashes = [ "CoVbip7pyXZDp1umo3cGUbCWJUA8wDkPbWR56wKqS434DiDSwGWC"; "CoVuTbwGSJyu9xD7vYYxxcqCFwCPf55UBqu8iqRcHYrs3Gu31v8y"; "CoUiEnajKeukmYFUgWTJF2z3v24MycpTaomF8a9hRzVy7as9hvgy"; "CoVngnGTJfudgcayQqtz2ZyWTUFB6zHmhvV1itjncRzYS4wndhH8"; "CoVe9oDs8t8WgH9JHB3DqbvxCZw1Q5ky7qBsZfMiLeKe6RiSMHn1"; "CoVXSYbKxP7jJL4ZSZnCsyynEZ6aeR7HR59UVKCDZdMGa8QCLFfW"; "CoVSQwz1mSz28kNCBso3F3ZHuLj5GXwXovu4byqweTa96bJAzTX6"; "CoVEow8t8iz6gfxB7daEHjFRD5suzdhb3wNZ5rMnoUTdjbYvxbez"; "CoVZDcjRgjmKnAhetUtb1AVQYwuUi3fBK7js11vjBETPuG5FcU8o"; "CoWRLgT2SwZkCWCwyTBxxkxPxYFvTWtHfKqX8MFQ1hNWL4SS1qdU"; "CoWVK1YzoDnMGrNioKL9Mze6s4XX8Uw9Vp9hPHYXqHfaFpwnmXmA"; "CoVnWzSVjbYHCQLD53JGJfWRSjUBrkbtCrNMgmsXX6bMhy7CE7E6"; ] let irmin_hash_gen = QCheck2.Gen.oneofl irmin_hashes let merkle_node_gen = let open Tezos_shell_services.Block_services in let module MapGen = MakeMapGen (TzString.Map) in let open QCheck2.Gen in let max_depth_factor = 4 in fix (fun self current_depth_factor -> frequency [ ( max_depth_factor, map (fun (kind, hash) -> Hash (kind, hash)) (pair (oneofl [Contents; Node]) irmin_hash_gen) ); ( max_depth_factor, map (fun raw_context -> Data raw_context) raw_context_gen ); ( current_depth_factor, map (fun merkle_node_map -> Continue merkle_node_map) (MapGen.gen_of_size (0 -- 5) (small_string ?gen:None) (self (current_depth_factor / 2))) ); ]) max_depth_factor let print_merkle_node = Format.asprintf "%a" Tezos_shell_services.Block_services.pp_merkle_node let merkle_tree_gen = let open MakeMapGen (TzString.Map) in gen_of_size QCheck2.Gen.(0 -- 5) (QCheck2.Gen.small_string ?gen:None) merkle_node_gen let print_merkle_tree = Format.asprintf "%a" Tezos_shell_services.Block_services.pp_merkle_tree
e0f48df44dfc4a05a56ca845a7f06e8e5ccfbf52f774b1757633b18d1db2e17e
fukamachi/clozure-cl
x8664-freebsd-syscalls.lisp
-*-Mode : LISP ; Package : CCL -*- ;;; Copyright ( C ) 2006 - 2009 Clozure Associates This file is part of Clozure CL . ;;; Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the ;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL, which is distributed with Clozure CL as the file " LGPL " . Where these ;;; conflict, the preamble takes precedence. ;;; ;;; Clozure CL is referenced in the preamble as the "LIBRARY." ;;; ;;; The LLGPL is also available online at ;;; (in-package "CCL") (eval-when (:compile-toplevel :load-toplevel :execute) (require "SYSCALL")) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::read 3 (:unsigned-fullword :address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::write 4 (:unsigned-fullword :address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::open 5 (:address :unsigned-fullword :unsigned-fullword) :signed-fullword :min-args 2) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::close 6 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::stat 188 (:address :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fstat 189 (:unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::lstat 190 (:address :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::lseek 199 (:unsigned-fullword :unsigned-doubleword :signed-doubleword :unsigned-fullword) :signed-doubleword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::exit 1 (:signed-fullword) :void) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fork 2 () :signed-fullword) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::creat 85 (:address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::link 9 (:address :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::unlink 10 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::execve 59 (:address :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::chdir 12 (:address) :signed-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::time 201 (:address) :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mknod 14 (:address :unsigned-fullword :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::chmod 15 (:address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::lchown 254 (:address :unsigned-fullword :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpid 20 () :unsigned-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mount 21 (:address :address :address :unsigned-fullword :address) :signed-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::umount2 166 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setuid 23 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getuid 24 () :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ptrace 26 (:unsigned-fullword :unsigned-fullword :address :address) :signed-fullword) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::alarm 37 (:unsigned-fullword) :unsigned-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::pause 34 () :signed-fullword) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::utime 132 (:address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::access 33 (:address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sync 36 () :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::kill 37 (:signed-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rename 128 (:address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mkdir 136 (:address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rmdir 137 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::dup 41 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::pipe 42 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::times 100 (:address) :unsigned-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::brk 12 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setgid 181 (:unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getgid 47 () :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::geteuid 25 () :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getegid 43 () :unsigned-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::acct 51 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ioctl 54 (:unsigned-fullword :signed-fullword :address) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fcntl 92 (:unsigned-fullword :signed-fullword :signed-fullword) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setpgid 82 (:signed-fullword :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::umask 60 (:unsigned-fullword) :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::chroot 61 (:address) :signed-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ustat 136 (:unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::dup2 90 (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getppid 39 () :unsigned-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpgrp 81 () :unsigned-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setsid 147 () :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigaction 416 (:unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getrusage 117 (:signed-fullword :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::gettimeofday 116 (:address :address) :void) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ftruncate 201 (:unsigned-fullword :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fchmod 91 (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fchmod 124 (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::socket 97 (:signed-fullword :signed-fullword :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::connect 98 (:signed-fullword :address :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::accept 30 (:signed-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sendto 133 (:unsigned-fullword :address :unsigned-fullword :unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::recvfrom 29 (:unsigned-fullword :address :unsigned-long :unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sendmsg 28 (:unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::recvmsg 27 (:unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::shutdown 134 (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::bind 104 (:signed-fullword :address :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::listen 106 (:signed-fullword :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpeername 31 (:signed-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getsockname 32 (:signed-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::socketpair 135 (:signed-fullword :signed-fullword :signed-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setsockopt 105 (:unsigned-fullword :signed-fullword :signed-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getsockopt 118 (:unsigned-fullword :signed-fullword :unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fsync 95 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::uname 164 (:address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fchdir 13 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::select 93 (:unsigned-fullword :address :address :address :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getcwd 326 (:address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::poll 209 ((:* (:struct :pollfd)) :int :int) :int) #+notdefinedyet (progn (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sgetmask 68 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ssetmask 69 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setreuid 70 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setregid 71 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigsuspend 72 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigpending 73 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sethostname 74 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setrlimit 75 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getrlimit 76 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::settimeofday 79 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getgroups 80 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setgroups 81 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::symlink 83 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::oldlstat 84 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::readlink 58 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::uselib 86 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::swapon 87 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::reboot 88 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::readdir 89 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::truncate 92 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fchown 95 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpriority 96 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setpriority 97 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::statfs 99 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fstatfs 100 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ioperm 101 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::syslog 103 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setitimer 38 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getitimer 36 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::olduname 109 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::iopl 110 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::vhangup 111 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::idle 112 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::vm86 113 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::wait4 7 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::swapoff 115 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sysinfo 116 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ipc 117 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigreturn 119 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::clone 120 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setdomainname 121 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::modify_ldt 123 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::adjtimex 124 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mprotect 10 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigprocmask 126 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::create_module 127 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::init_module 128 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::delete_module 129 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::get_kernel_syms 130 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::quotactl 131 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpgid 132 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::bdflush 134 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sysfs 135 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::personality 136 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setfsuid 138 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setfsgid 139 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getdents 141 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::_newselect 142 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::flock 143 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::msync 26 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::readv 19 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::writev 20 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getsid 147 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fdatasync 148 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::_sysctl 149 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mlock 150 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::munlock 151 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mlockall 152 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::munlockall 153 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_setparam 154 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_getparam 155 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_setscheduler 156 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_getscheduler 157 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_yield 24 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_get_priority_max 159 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_get_priority_min 160 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_rr_get_interval 161 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::nanosleep 35 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mremap 25 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setresuid 164 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getresuid 165 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::query_module 166 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::nfsservctl 168 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setresgid 169 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getresgid 170 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::prctl 171 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigreturn 15 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigaction 13 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigprocmask 14 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigpending 175 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigtimedwait 176 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigqueueinfo 177 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigsuspend 178 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::pread 17 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::pwrite 18 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::chown 181 (:address) ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::capget 183 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::capset 184 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigaltstack 185 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sendfile 40 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpmsg 187 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::putpmsg 188 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::vfork 189 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mmap 9 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::munmap 73 () ) )
null
https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/library/x8664-freebsd-syscalls.lisp
lisp
Package : CCL -*- file "LICENSE". The LLGPL consists of a preamble and the LGPL, conflict, the preamble takes precedence. Clozure CL is referenced in the preamble as the "LIBRARY." The LLGPL is also available online at
Copyright ( C ) 2006 - 2009 Clozure Associates This file is part of Clozure CL . Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the which is distributed with Clozure CL as the file " LGPL " . Where these (in-package "CCL") (eval-when (:compile-toplevel :load-toplevel :execute) (require "SYSCALL")) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::read 3 (:unsigned-fullword :address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::write 4 (:unsigned-fullword :address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::open 5 (:address :unsigned-fullword :unsigned-fullword) :signed-fullword :min-args 2) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::close 6 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::stat 188 (:address :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fstat 189 (:unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::lstat 190 (:address :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::lseek 199 (:unsigned-fullword :unsigned-doubleword :signed-doubleword :unsigned-fullword) :signed-doubleword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::exit 1 (:signed-fullword) :void) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fork 2 () :signed-fullword) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::creat 85 (:address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::link 9 (:address :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::unlink 10 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::execve 59 (:address :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::chdir 12 (:address) :signed-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::time 201 (:address) :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mknod 14 (:address :unsigned-fullword :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::chmod 15 (:address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::lchown 254 (:address :unsigned-fullword :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpid 20 () :unsigned-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mount 21 (:address :address :address :unsigned-fullword :address) :signed-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::umount2 166 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setuid 23 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getuid 24 () :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ptrace 26 (:unsigned-fullword :unsigned-fullword :address :address) :signed-fullword) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::alarm 37 (:unsigned-fullword) :unsigned-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::pause 34 () :signed-fullword) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::utime 132 (:address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::access 33 (:address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sync 36 () :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::kill 37 (:signed-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rename 128 (:address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mkdir 136 (:address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rmdir 137 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::dup 41 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::pipe 42 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::times 100 (:address) :unsigned-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::brk 12 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setgid 181 (:unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getgid 47 () :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::geteuid 25 () :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getegid 43 () :unsigned-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::acct 51 (:address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ioctl 54 (:unsigned-fullword :signed-fullword :address) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fcntl 92 (:unsigned-fullword :signed-fullword :signed-fullword) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setpgid 82 (:signed-fullword :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::umask 60 (:unsigned-fullword) :unsigned-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::chroot 61 (:address) :signed-fullword ) #+notyet (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ustat 136 (:unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::dup2 90 (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getppid 39 () :unsigned-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpgrp 81 () :unsigned-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setsid 147 () :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigaction 416 (:unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getrusage 117 (:signed-fullword :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::gettimeofday 116 (:address :address) :void) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ftruncate 201 (:unsigned-fullword :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fchmod 91 (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fchmod 124 (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::socket 97 (:signed-fullword :signed-fullword :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::connect 98 (:signed-fullword :address :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::accept 30 (:signed-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sendto 133 (:unsigned-fullword :address :unsigned-fullword :unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::recvfrom 29 (:unsigned-fullword :address :unsigned-long :unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sendmsg 28 (:unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::recvmsg 27 (:unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::shutdown 134 (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::bind 104 (:signed-fullword :address :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::listen 106 (:signed-fullword :signed-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpeername 31 (:signed-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getsockname 32 (:signed-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::socketpair 135 (:signed-fullword :signed-fullword :signed-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setsockopt 105 (:unsigned-fullword :signed-fullword :signed-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getsockopt 118 (:unsigned-fullword :signed-fullword :unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fsync 95 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::uname 164 (:address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fchdir 13 (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::select 93 (:unsigned-fullword :address :address :address :address) :signed-fullword) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getcwd 326 (:address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::poll 209 ((:* (:struct :pollfd)) :int :int) :int) #+notdefinedyet (progn (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sgetmask 68 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ssetmask 69 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setreuid 70 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setregid 71 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigsuspend 72 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigpending 73 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sethostname 74 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setrlimit 75 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getrlimit 76 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::settimeofday 79 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getgroups 80 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setgroups 81 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::symlink 83 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::oldlstat 84 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::readlink 58 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::uselib 86 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::swapon 87 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::reboot 88 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::readdir 89 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::truncate 92 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fchown 95 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpriority 96 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setpriority 97 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::statfs 99 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fstatfs 100 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ioperm 101 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::syslog 103 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setitimer 38 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getitimer 36 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::olduname 109 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::iopl 110 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::vhangup 111 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::idle 112 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::vm86 113 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::wait4 7 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::swapoff 115 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sysinfo 116 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::ipc 117 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigreturn 119 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::clone 120 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setdomainname 121 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::modify_ldt 123 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::adjtimex 124 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mprotect 10 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigprocmask 126 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::create_module 127 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::init_module 128 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::delete_module 129 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::get_kernel_syms 130 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::quotactl 131 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpgid 132 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::bdflush 134 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sysfs 135 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::personality 136 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setfsuid 138 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setfsgid 139 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getdents 141 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::_newselect 142 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::flock 143 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::msync 26 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::readv 19 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::writev 20 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getsid 147 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::fdatasync 148 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::_sysctl 149 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mlock 150 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::munlock 151 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mlockall 152 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::munlockall 153 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_setparam 154 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_getparam 155 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_setscheduler 156 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_getscheduler 157 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_yield 24 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_get_priority_max 159 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_get_priority_min 160 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sched_rr_get_interval 161 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::nanosleep 35 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mremap 25 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setresuid 164 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getresuid 165 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::query_module 166 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::nfsservctl 168 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::setresgid 169 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getresgid 170 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::prctl 171 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigreturn 15 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigaction 13 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigprocmask 14 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigpending 175 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigtimedwait 176 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigqueueinfo 177 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::rt_sigsuspend 178 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::pread 17 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::pwrite 18 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::chown 181 (:address) ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::capget 183 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::capset 184 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sigaltstack 185 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::sendfile 40 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::getpmsg 187 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::putpmsg 188 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::vfork 189 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::mmap 9 () ) (define-syscall (logior platform-os-freebsd platform-cpu-x86 platform-word-size-64) syscalls::munmap 73 () ) )
5452d177bc3f6d34f01efe1863f8b7e1370cf3b96fe93c16118052ee94b56704
alanz/ghc-exactprint
BadTelescope.hs
{-# LANGUAGE TypeInType #-} module BadTelescope where import Data.Kind data SameKind :: k -> k -> * data X a k (b :: k) (c :: SameKind a b)
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/pre-ghc86/BadTelescope.hs
haskell
# LANGUAGE TypeInType #
module BadTelescope where import Data.Kind data SameKind :: k -> k -> * data X a k (b :: k) (c :: SameKind a b)
a1fe75994ae3ee7284c07e2a5e7936a0c3db615a59f63d67e8ac72570714eac1
hcarty/ocaml-gdal
data_source.mli
* { 1 OGR Data Sources } (** These are bindings and wrappers around the [OGR_DS_*] API. *) type t (** Data source *) exception Data_source_error type driver_t * OGR driver val get_driver_by_name : string -> driver_t option val get_driver_by_name_exn : string -> driver_t (** [get_driver_by_name name] returns the driver associated with [name]. *) val create : ?options:string list -> driver_t -> string -> t option val create_exn : ?options:string list -> driver_t -> string -> t (** [create ?options driver name] *) val copy : ?options:string list -> driver_t -> t -> string -> t option val copy_exn : ?options:string list -> driver_t -> t -> string -> t (** [copy ?options driver src name] creates a copy of [src] using [driver]. *) val of_source : ?write:bool -> string -> [ `Invalid_source | `Ok of t ] * [ of_source ? write name ] opens the source [ name ] for access . @param write defaults to false ( read - only ) @param name is source - type specific . See the upstream OGR documentation for more information . @return ` Invalid_source if [ name ] does not represent a valid data source . @param write defaults to false (read-only) @param name is source-type specific. See the upstream OGR documentation for more information. @return `Invalid_source if [name] does not represent a valid data source. *) val of_source_exn : ?write:bool -> string -> t * Like { ! } but raises { ! Invalid_source } if there is an error with the data source . the data source. *) val destroy : t -> unit (** [destroy t] releases the resources associated with [t]. *) val with_source : ?write:bool -> string -> (t -> 'a) -> [ `Invalid_source | `Ok of 'a ] * [ with_source ? write name f ] opens [ name ] and calls [ f src ] if [ name ] is a valid data source . The data source passed to [ f ] will be closed if [ f ] returns normally or raises an exception . This is a wrapper around { ! } . See its documentation for a description of the expected arguments . valid data source. The data source passed to [f] will be closed if [f] returns normally or raises an exception. This is a wrapper around {!of_source}. See its documentation for a description of the expected arguments. *) val with_source_exn : ?write:bool -> string -> (t -> 'a) -> 'a (** Like {!with_source} but raises {!Invalid_source} if there is an error with the data source. *) val get_layer_by_name : t -> string -> Layer.t val get_layer : t -> int -> Layer.t (** [get_layer* src id] returns a {!Layer.t} extracted from [src]. *) val get_layer_count : t -> int (** [get_layer_count src] returns the number of layers in [src]. *) val create_layer : ?spatial_reference:Spatial_reference.t -> ?geometry_type:Geometry.wkb_t -> ?options:string list -> t -> string -> Layer.t option * [ ? spatial_reference ? geometry_type ? options ds name ] creates a layer named [ name ] in [ ds ] . @param spatial_reference defaults to no spatial reference . @param geometry_type defaults to { ! Geometry . Unknown } @param options defaults to an empty list . @return [ Some layer ] on success or [ None ] if the layer could not be created . layer named [name] in [ds]. @param spatial_reference defaults to no spatial reference. @param geometry_type defaults to {!Geometry.Unknown} @param options defaults to an empty list. @return [Some layer] on success or [None] if the layer could not be created. *) val create_layer_exn : ?spatial_reference:Spatial_reference.t -> ?geometry_type:Geometry.wkb_t -> ?options:string list -> t -> string -> Layer.t * [ create_layer_exn ? spatial_reference ? geometry_type ? options ds name ] is like { ! } except that it raises { ! Data_source_error } if the layer can not be created . like {!create_layer} except that it raises {!Data_source_error} if the layer can not be created. *) val copy_layer : ?options:string list -> t -> Layer.t -> string -> Layer.t option (** [copy_layer ?options ds src name] copies [src] to a layer named [name] in [ds]. @param options defaults to an empty list. @return [Some layer] on success or [None] if the layer could not be copied/created. *) val copy_layer_exn : ?options:string list -> t -> Layer.t -> string -> Layer.t (** [copy_layer_exn ?options ds src name] is like {!copy_layer} except that it raises {!Data_source_error} if the layer can not be copied. *) (**/**) val t : t Ctypes.typ * { 2 Low level wrappers } (** These should not be necessary under normal circumstances. *) val release : t -> unit (** @raise Data_source_error *)
null
https://raw.githubusercontent.com/hcarty/ocaml-gdal/9c225c1e3f8002ec7614b3c1657e5f05e4e0e821/src/data_source.mli
ocaml
* These are bindings and wrappers around the [OGR_DS_*] API. * Data source * [get_driver_by_name name] returns the driver associated with [name]. * [create ?options driver name] * [copy ?options driver src name] creates a copy of [src] using [driver]. * [destroy t] releases the resources associated with [t]. * Like {!with_source} but raises {!Invalid_source} if there is an error with the data source. * [get_layer* src id] returns a {!Layer.t} extracted from [src]. * [get_layer_count src] returns the number of layers in [src]. * [copy_layer ?options ds src name] copies [src] to a layer named [name] in [ds]. @param options defaults to an empty list. @return [Some layer] on success or [None] if the layer could not be copied/created. * [copy_layer_exn ?options ds src name] is like {!copy_layer} except that it raises {!Data_source_error} if the layer can not be copied. */* * These should not be necessary under normal circumstances. * @raise Data_source_error
* { 1 OGR Data Sources } type t exception Data_source_error type driver_t * OGR driver val get_driver_by_name : string -> driver_t option val get_driver_by_name_exn : string -> driver_t val create : ?options:string list -> driver_t -> string -> t option val create_exn : ?options:string list -> driver_t -> string -> t val copy : ?options:string list -> driver_t -> t -> string -> t option val copy_exn : ?options:string list -> driver_t -> t -> string -> t val of_source : ?write:bool -> string -> [ `Invalid_source | `Ok of t ] * [ of_source ? write name ] opens the source [ name ] for access . @param write defaults to false ( read - only ) @param name is source - type specific . See the upstream OGR documentation for more information . @return ` Invalid_source if [ name ] does not represent a valid data source . @param write defaults to false (read-only) @param name is source-type specific. See the upstream OGR documentation for more information. @return `Invalid_source if [name] does not represent a valid data source. *) val of_source_exn : ?write:bool -> string -> t * Like { ! } but raises { ! Invalid_source } if there is an error with the data source . the data source. *) val destroy : t -> unit val with_source : ?write:bool -> string -> (t -> 'a) -> [ `Invalid_source | `Ok of 'a ] * [ with_source ? write name f ] opens [ name ] and calls [ f src ] if [ name ] is a valid data source . The data source passed to [ f ] will be closed if [ f ] returns normally or raises an exception . This is a wrapper around { ! } . See its documentation for a description of the expected arguments . valid data source. The data source passed to [f] will be closed if [f] returns normally or raises an exception. This is a wrapper around {!of_source}. See its documentation for a description of the expected arguments. *) val with_source_exn : ?write:bool -> string -> (t -> 'a) -> 'a val get_layer_by_name : t -> string -> Layer.t val get_layer : t -> int -> Layer.t val get_layer_count : t -> int val create_layer : ?spatial_reference:Spatial_reference.t -> ?geometry_type:Geometry.wkb_t -> ?options:string list -> t -> string -> Layer.t option * [ ? spatial_reference ? geometry_type ? options ds name ] creates a layer named [ name ] in [ ds ] . @param spatial_reference defaults to no spatial reference . @param geometry_type defaults to { ! Geometry . Unknown } @param options defaults to an empty list . @return [ Some layer ] on success or [ None ] if the layer could not be created . layer named [name] in [ds]. @param spatial_reference defaults to no spatial reference. @param geometry_type defaults to {!Geometry.Unknown} @param options defaults to an empty list. @return [Some layer] on success or [None] if the layer could not be created. *) val create_layer_exn : ?spatial_reference:Spatial_reference.t -> ?geometry_type:Geometry.wkb_t -> ?options:string list -> t -> string -> Layer.t * [ create_layer_exn ? spatial_reference ? geometry_type ? options ds name ] is like { ! } except that it raises { ! Data_source_error } if the layer can not be created . like {!create_layer} except that it raises {!Data_source_error} if the layer can not be created. *) val copy_layer : ?options:string list -> t -> Layer.t -> string -> Layer.t option val copy_layer_exn : ?options:string list -> t -> Layer.t -> string -> Layer.t val t : t Ctypes.typ * { 2 Low level wrappers } val release : t -> unit
a3fe24d68cd44cb398a8b06c0f2a4e644188e8e1582d5b58e3dabc13558f4d10
TyOverby/mono
node_path.mli
open! Core open! Import * Represents the shortest unambiguous path through the Computation.t data structure , including the path through any contained [ Value.t]s . Several of the constructors in Computation.t only contain a single inner computation or value ; thus , keeping track of these segments in all the paths is often unnecessary . Thus , we can more properly model this path as with two parts : - the list of choices made ; nodes which do not require a choice do not make it into the list . - a number representing the amount of nodes descended into after the last choice point . Whenever a choice point gets added , we reset the number of nodes descended back to 0 , since that number is no longer helpful for keeping the paths unique . structure, including the path through any contained [Value.t]s. Several of the constructors in Computation.t only contain a single inner computation or value; thus, keeping track of these segments in all the paths is often unnecessary. Thus, we can more properly model this path as with two parts: - the list of choices made; nodes which do not require a choice do not make it into the list. - a number representing the amount of nodes descended into after the last choice point. Whenever a choice point gets added, we reset the number of nodes descended back to 0, since that number is no longer helpful for keeping the paths unique. *) type t [@@deriving bin_io, sexp] include Comparable.S_binable with type t := t * The [ of_string ] and [ to_string ] functions operate on short , yet semi - human - readable strings . For example : { [ { choices = [ 1 ; 2 ; 3 ] ; descend = 4 } ] } is serialized to " 1 - 2 - 3_4 " semi-human-readable strings. For example: {[ { choices = [ 1; 2; 3]; descend = 4 } ]} is serialized to "1-2-3_4" *) include Stringable.S with type t := t type builder (** The empty node path. *) val empty : builder (** Adds a choice point to that input path. The provided number says which of the choices at that point was taken. When traversing a computation or value, if any case has multiple recursive calls, you should add a choice point to the path built up in each of those calls, with each call using a different number. *) val choice_point : builder -> int -> builder (** Adds an extra segment to the input path. All such segments get forgotten when the next choice point is added. *) val descend : builder -> builder val finalize : builder -> t
null
https://raw.githubusercontent.com/TyOverby/mono/7666c0328d194bf9a569fb65babc0486f2aaa40d/vendor/janestreet-bonsai/src/node_path.mli
ocaml
* The empty node path. * Adds a choice point to that input path. The provided number says which of the choices at that point was taken. When traversing a computation or value, if any case has multiple recursive calls, you should add a choice point to the path built up in each of those calls, with each call using a different number. * Adds an extra segment to the input path. All such segments get forgotten when the next choice point is added.
open! Core open! Import * Represents the shortest unambiguous path through the Computation.t data structure , including the path through any contained [ Value.t]s . Several of the constructors in Computation.t only contain a single inner computation or value ; thus , keeping track of these segments in all the paths is often unnecessary . Thus , we can more properly model this path as with two parts : - the list of choices made ; nodes which do not require a choice do not make it into the list . - a number representing the amount of nodes descended into after the last choice point . Whenever a choice point gets added , we reset the number of nodes descended back to 0 , since that number is no longer helpful for keeping the paths unique . structure, including the path through any contained [Value.t]s. Several of the constructors in Computation.t only contain a single inner computation or value; thus, keeping track of these segments in all the paths is often unnecessary. Thus, we can more properly model this path as with two parts: - the list of choices made; nodes which do not require a choice do not make it into the list. - a number representing the amount of nodes descended into after the last choice point. Whenever a choice point gets added, we reset the number of nodes descended back to 0, since that number is no longer helpful for keeping the paths unique. *) type t [@@deriving bin_io, sexp] include Comparable.S_binable with type t := t * The [ of_string ] and [ to_string ] functions operate on short , yet semi - human - readable strings . For example : { [ { choices = [ 1 ; 2 ; 3 ] ; descend = 4 } ] } is serialized to " 1 - 2 - 3_4 " semi-human-readable strings. For example: {[ { choices = [ 1; 2; 3]; descend = 4 } ]} is serialized to "1-2-3_4" *) include Stringable.S with type t := t type builder val empty : builder val choice_point : builder -> int -> builder val descend : builder -> builder val finalize : builder -> t
fffb2555e851e320e5b946c8ea1ef4809be0fb2839712629ed7388c59b6df61d
spectrum-finance/cardano-dex-contracts
Contracts.hs
module Tests.Contracts where import Control.Monad import Hedgehog import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.Hedgehog as HH import ErgoDex.PValidators checkContractsRecovering = testGroup "ContractsRecovering" [ HH.testProperty "swap_contract_recovering" swapRecovering , HH.testProperty "pool_contract_recovering" poolRecovering , HH.testProperty "deposit_contract_recovering" depositRecovering , HH.testProperty "redeem_contract_recovering" redeemRecovering ] swapRecovering :: Property swapRecovering = withTests 1 . property $ evalIO (void (swapValidator)) depositRecovering :: Property depositRecovering = withTests 1 . property $ evalIO (void depositValidator) redeemRecovering :: Property redeemRecovering = withTests 1 . property $ evalIO (void redeemValidator) poolRecovering :: Property poolRecovering = withTests 1 . property $ evalIO (void poolValidator)
null
https://raw.githubusercontent.com/spectrum-finance/cardano-dex-contracts/87bdbc26dbe9ae5f6c59e608d728330f8166f19c/cardano-dex-contracts-offchain/test/Tests/Contracts.hs
haskell
module Tests.Contracts where import Control.Monad import Hedgehog import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.Hedgehog as HH import ErgoDex.PValidators checkContractsRecovering = testGroup "ContractsRecovering" [ HH.testProperty "swap_contract_recovering" swapRecovering , HH.testProperty "pool_contract_recovering" poolRecovering , HH.testProperty "deposit_contract_recovering" depositRecovering , HH.testProperty "redeem_contract_recovering" redeemRecovering ] swapRecovering :: Property swapRecovering = withTests 1 . property $ evalIO (void (swapValidator)) depositRecovering :: Property depositRecovering = withTests 1 . property $ evalIO (void depositValidator) redeemRecovering :: Property redeemRecovering = withTests 1 . property $ evalIO (void redeemValidator) poolRecovering :: Property poolRecovering = withTests 1 . property $ evalIO (void poolValidator)
29a06cda3fe0b4381a275915498a466c0d2f58b46b75c413fd345870d396ea68
ethercrow/opentelemetry-haskell
Eventlog.hs
# LANGUAGE CPP # {-# LANGUAGE GADTs #-} # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # module OpenTelemetry.Eventlog ( -- * Spans beginSpan, endSpan, withSpan, withSpan_, setSpanId, setTraceId, setTag, addEvent, setParentSpanContext, SpanInFlight (..), -- * Metrics mkCounter, mkUpDownCounter, mkValueRecorder, mkSumObserver, mkUpDownSumObserver, mkValueObserver, add, record, observe, MI.Instrument, MI.SomeInstrument (..), MI.Counter, MI.UpDownCounter, MI.ValueRecorder, MI.SumObserver, MI.UpDownSumObserver, MI.ValueObserver, MI.Synchronicity (..), MI.Additivity (..), MI.Monotonicity (..), MI.InstrumentName, MI.InstrumentId, MI.instrumentName, MI.instrumentId, ) where import Control.Monad.Catch import Control.Monad.IO.Class import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BS8 import OpenTelemetry.Eventlog_Internal (SpanInFlight (..)) import qualified OpenTelemetry.Eventlog_Internal as I import qualified OpenTelemetry.Metrics_Internal as MI import OpenTelemetry.SpanContext import Prelude hiding (span) #if __GLASGOW_HASKELL__ < 808 import Data.Unique import Debug.Trace import OpenTelemetry.Metrics_Internal beginSpan :: MonadIO m => String -> m SpanInFlight beginSpan operation = do u64 <- fromIntegral . hashUnique <$> liftIO newUnique liftIO $ traceEventIO (I.beginSpan' (SpanInFlight u64) operation) pure $ SpanInFlight u64 endSpan :: MonadIO m => SpanInFlight -> m () endSpan = liftIO . traceEventIO . I.endSpan' setTag :: MonadIO m => SpanInFlight -> String -> BS.ByteString -> m () setTag sp k v = liftIO . traceEventIO $ I.setTag' sp k v addEvent :: MonadIO m => SpanInFlight -> String -> BS.ByteString -> m () addEvent sp k v = liftIO . traceEventIO $ I.addEvent' sp k v setParentSpanContext :: MonadIO m => SpanInFlight -> SpanContext -> m () setParentSpanContext sp ctx = liftIO . traceEventIO $ I.setParentSpanContext' sp ctx setTraceId :: MonadIO m => SpanInFlight -> TraceId -> m () setTraceId sp tid = liftIO . traceEventIO $ I.setTraceId' sp tid setSpanId :: MonadIO m => SpanInFlight -> SpanId -> m () setSpanId sp sid = liftIO . traceEventIO $ I.setSpanId' sp sid createInstrument :: MonadIO io => MI.Instrument s a m -> io () createInstrument = liftIO . traceEventIO . I.createInstrument' writeMetric :: MonadIO io => MI.Instrument s a m -> Int -> io () writeMetric i v = liftIO $ traceEventIO $ I.writeMetric' (instrumentId i) v mkCounter :: MonadIO m => MI.InstrumentName -> m MI.Counter mkCounter name = do inst <- MI.Counter name <$> I.nextInstrumentId createInstrument inst return inst mkUpDownCounter :: MonadIO m => MI.InstrumentName -> m MI.UpDownCounter mkUpDownCounter name = do inst <- MI.UpDownCounter name <$> I.nextInstrumentId createInstrument inst return inst mkValueRecorder :: MonadIO m => MI.InstrumentName -> m MI.ValueRecorder mkValueRecorder name = do inst <- MI.ValueRecorder name <$> I.nextInstrumentId createInstrument inst return inst mkSumObserver :: MonadIO m => MI.InstrumentName -> m MI.SumObserver mkSumObserver name = do inst <- MI.SumObserver name <$> I.nextInstrumentId createInstrument inst return inst mkUpDownSumObserver :: MonadIO m => MI.InstrumentName -> m MI.UpDownSumObserver mkUpDownSumObserver name = do inst <- MI.UpDownSumObserver name <$> I.nextInstrumentId createInstrument inst return inst mkValueObserver :: MonadIO m => MI.InstrumentName -> m MI.ValueObserver mkValueObserver name = do inst <- MI.ValueObserver name <$> I.nextInstrumentId createInstrument inst return inst | Take a measurement for a synchronous , additive instrument ( ' Counter ' , ' ' ) add :: MonadIO io => MI.Instrument 'MI.Synchronous 'MI.Additive m' -> Int -> io () add = writeMetric -- | Take a measurement for a synchronous, non-additive instrument ('ValueRecorder') record :: MonadIO io => MI.Instrument 'MI.Synchronous 'MI.NonAdditive m' -> Int -> io () record = writeMetric | Take a measurement for an asynchronous instrument ( ' SumObserver ' , ' UpDownSumObserver ' , ' ValueObserver ' ) observe :: MonadIO io => MI.Instrument 'MI.Asynchronous a m' -> Int -> io () observe = writeMetric withSpan :: forall m a. (MonadIO m, MonadMask m) => String -> (SpanInFlight -> m a) -> m a withSpan operation action = fst <$> generalBracket (liftIO $ beginSpan operation) ( \span exitcase -> liftIO $ do case exitcase of ExitCaseSuccess _ -> pure () ExitCaseException e -> do setTag span "error" "true" setTag span "error.message" (BS8.pack $ show e) ExitCaseAbort -> do setTag span "error" "true" setTag span "error.message" "abort" liftIO $ endSpan span ) action withSpan_ :: (MonadIO m, MonadMask m) => String -> m a -> m a withSpan_ operation action = withSpan operation (const action) #else # INLINE withSpan # withSpan :: forall m a. (MonadIO m, MonadMask m) => BS.ByteString -> (SpanInFlight -> m a) -> m a withSpan operation action = fst <$> generalBracket (liftIO $ beginSpan operation) ( \sp exitcase -> liftIO $ do case exitcase of ExitCaseSuccess _ -> pure () ExitCaseException e -> do setTag sp "error" "true" setTag sp "error.message" (BS8.pack $ take I.maxMsgLen $ show e) ExitCaseAbort -> do setTag sp "error" "true" setTag sp "error.message" "abort" liftIO $ endSpan sp ) action {-# INLINE withSpan_ #-} withSpan_ :: (MonadIO m, MonadMask m) => BS.ByteString -> m a -> m a withSpan_ operation action = withSpan operation (const action) # INLINE setSpanId # setSpanId :: MonadIO m => SpanInFlight -> SpanId -> m () setSpanId sp sid = I.traceBuilder $ I.builder_setSpanId sp sid # INLINE setTraceId # setTraceId :: MonadIO m => SpanInFlight -> TraceId -> m () setTraceId sp tid = I.traceBuilder $ I.builder_setTraceId sp tid # INLINE beginSpan # beginSpan :: MonadIO m => BS.ByteString -> m SpanInFlight beginSpan operation = do u <- I.nextLocalSpan I.traceBuilder $ I.builder_beginSpan u operation pure u # INLINE endSpan # endSpan :: MonadIO m => SpanInFlight -> m () endSpan sp = I.traceBuilder $ I.builder_endSpan sp # INLINE setTag # setTag :: MonadIO m => SpanInFlight -> BS.ByteString -> BS.ByteString -> m () setTag sp k v = I.traceBuilder $ I.builder_setTag sp k v # INLINE addEvent # addEvent :: MonadIO m => SpanInFlight -> BS.ByteString -> BS.ByteString -> m () addEvent sp k v = I.traceBuilder $ I.builder_addEvent sp k v # INLINE setParentSpanContext # setParentSpanContext :: MonadIO m => SpanInFlight -> SpanContext -> m () setParentSpanContext sp ctx = I.traceBuilder $ I.builder_setParentSpanContext sp ctx # INLINE mkCounter # mkCounter :: MonadIO m => MI.InstrumentName -> m MI.Counter mkCounter name = do inst <- MI.Counter name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkUpDownCounter # mkUpDownCounter :: MonadIO m => MI.InstrumentName -> m MI.UpDownCounter mkUpDownCounter name = do inst <- MI.UpDownCounter name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkValueRecorder # mkValueRecorder :: MonadIO m => MI.InstrumentName -> m MI.ValueRecorder mkValueRecorder name = do inst <- MI.ValueRecorder name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkSumObserver # mkSumObserver :: MonadIO m => MI.InstrumentName -> m MI.SumObserver mkSumObserver name = do inst <- MI.SumObserver name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkUpDownSumObserver # mkUpDownSumObserver :: MonadIO m => MI.InstrumentName -> m MI.UpDownSumObserver mkUpDownSumObserver name = do inst <- MI.UpDownSumObserver name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkValueObserver # mkValueObserver :: MonadIO m => MI.InstrumentName -> m MI.ValueObserver mkValueObserver name = do inst <- MI.ValueObserver name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst | Take a measurement for a synchronous , additive instrument ( ' Counter ' , ' ' ) # INLINE add # add :: MonadIO m => MI.Instrument 'MI.Synchronous 'MI.Additive m' -> Int -> m () add i v = I.traceBuilder $ I.builder_captureMetric (MI.instrumentId i) v -- | Take a measurement for a synchronous, non-additive instrument ('ValueRecorder') # INLINE record # record :: MonadIO m => MI.Instrument 'MI.Synchronous 'MI.NonAdditive m' -> Int -> m () record i v = I.traceBuilder $ I.builder_captureMetric (MI.instrumentId i) v | Take a measurement for an asynchronous instrument ( ' SumObserver ' , ' UpDownSumObserver ' , ' ValueObserver ' ) # INLINE observe # observe :: MonadIO m => MI.Instrument 'MI.Asynchronous a m' -> Int -> m () observe i v = I.traceBuilder $ I.builder_captureMetric (MI.instrumentId i) v #endif
null
https://raw.githubusercontent.com/ethercrow/opentelemetry-haskell/33cb21735da555d4ef9c144a26f26bd1ca4a160a/opentelemetry/src/OpenTelemetry/Eventlog.hs
haskell
# LANGUAGE GADTs # # LANGUAGE OverloadedStrings # * Spans * Metrics | Take a measurement for a synchronous, non-additive instrument ('ValueRecorder') # INLINE withSpan_ # | Take a measurement for a synchronous, non-additive instrument ('ValueRecorder')
# LANGUAGE CPP # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE PatternSynonyms # module OpenTelemetry.Eventlog beginSpan, endSpan, withSpan, withSpan_, setSpanId, setTraceId, setTag, addEvent, setParentSpanContext, SpanInFlight (..), mkCounter, mkUpDownCounter, mkValueRecorder, mkSumObserver, mkUpDownSumObserver, mkValueObserver, add, record, observe, MI.Instrument, MI.SomeInstrument (..), MI.Counter, MI.UpDownCounter, MI.ValueRecorder, MI.SumObserver, MI.UpDownSumObserver, MI.ValueObserver, MI.Synchronicity (..), MI.Additivity (..), MI.Monotonicity (..), MI.InstrumentName, MI.InstrumentId, MI.instrumentName, MI.instrumentId, ) where import Control.Monad.Catch import Control.Monad.IO.Class import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BS8 import OpenTelemetry.Eventlog_Internal (SpanInFlight (..)) import qualified OpenTelemetry.Eventlog_Internal as I import qualified OpenTelemetry.Metrics_Internal as MI import OpenTelemetry.SpanContext import Prelude hiding (span) #if __GLASGOW_HASKELL__ < 808 import Data.Unique import Debug.Trace import OpenTelemetry.Metrics_Internal beginSpan :: MonadIO m => String -> m SpanInFlight beginSpan operation = do u64 <- fromIntegral . hashUnique <$> liftIO newUnique liftIO $ traceEventIO (I.beginSpan' (SpanInFlight u64) operation) pure $ SpanInFlight u64 endSpan :: MonadIO m => SpanInFlight -> m () endSpan = liftIO . traceEventIO . I.endSpan' setTag :: MonadIO m => SpanInFlight -> String -> BS.ByteString -> m () setTag sp k v = liftIO . traceEventIO $ I.setTag' sp k v addEvent :: MonadIO m => SpanInFlight -> String -> BS.ByteString -> m () addEvent sp k v = liftIO . traceEventIO $ I.addEvent' sp k v setParentSpanContext :: MonadIO m => SpanInFlight -> SpanContext -> m () setParentSpanContext sp ctx = liftIO . traceEventIO $ I.setParentSpanContext' sp ctx setTraceId :: MonadIO m => SpanInFlight -> TraceId -> m () setTraceId sp tid = liftIO . traceEventIO $ I.setTraceId' sp tid setSpanId :: MonadIO m => SpanInFlight -> SpanId -> m () setSpanId sp sid = liftIO . traceEventIO $ I.setSpanId' sp sid createInstrument :: MonadIO io => MI.Instrument s a m -> io () createInstrument = liftIO . traceEventIO . I.createInstrument' writeMetric :: MonadIO io => MI.Instrument s a m -> Int -> io () writeMetric i v = liftIO $ traceEventIO $ I.writeMetric' (instrumentId i) v mkCounter :: MonadIO m => MI.InstrumentName -> m MI.Counter mkCounter name = do inst <- MI.Counter name <$> I.nextInstrumentId createInstrument inst return inst mkUpDownCounter :: MonadIO m => MI.InstrumentName -> m MI.UpDownCounter mkUpDownCounter name = do inst <- MI.UpDownCounter name <$> I.nextInstrumentId createInstrument inst return inst mkValueRecorder :: MonadIO m => MI.InstrumentName -> m MI.ValueRecorder mkValueRecorder name = do inst <- MI.ValueRecorder name <$> I.nextInstrumentId createInstrument inst return inst mkSumObserver :: MonadIO m => MI.InstrumentName -> m MI.SumObserver mkSumObserver name = do inst <- MI.SumObserver name <$> I.nextInstrumentId createInstrument inst return inst mkUpDownSumObserver :: MonadIO m => MI.InstrumentName -> m MI.UpDownSumObserver mkUpDownSumObserver name = do inst <- MI.UpDownSumObserver name <$> I.nextInstrumentId createInstrument inst return inst mkValueObserver :: MonadIO m => MI.InstrumentName -> m MI.ValueObserver mkValueObserver name = do inst <- MI.ValueObserver name <$> I.nextInstrumentId createInstrument inst return inst | Take a measurement for a synchronous , additive instrument ( ' Counter ' , ' ' ) add :: MonadIO io => MI.Instrument 'MI.Synchronous 'MI.Additive m' -> Int -> io () add = writeMetric record :: MonadIO io => MI.Instrument 'MI.Synchronous 'MI.NonAdditive m' -> Int -> io () record = writeMetric | Take a measurement for an asynchronous instrument ( ' SumObserver ' , ' UpDownSumObserver ' , ' ValueObserver ' ) observe :: MonadIO io => MI.Instrument 'MI.Asynchronous a m' -> Int -> io () observe = writeMetric withSpan :: forall m a. (MonadIO m, MonadMask m) => String -> (SpanInFlight -> m a) -> m a withSpan operation action = fst <$> generalBracket (liftIO $ beginSpan operation) ( \span exitcase -> liftIO $ do case exitcase of ExitCaseSuccess _ -> pure () ExitCaseException e -> do setTag span "error" "true" setTag span "error.message" (BS8.pack $ show e) ExitCaseAbort -> do setTag span "error" "true" setTag span "error.message" "abort" liftIO $ endSpan span ) action withSpan_ :: (MonadIO m, MonadMask m) => String -> m a -> m a withSpan_ operation action = withSpan operation (const action) #else # INLINE withSpan # withSpan :: forall m a. (MonadIO m, MonadMask m) => BS.ByteString -> (SpanInFlight -> m a) -> m a withSpan operation action = fst <$> generalBracket (liftIO $ beginSpan operation) ( \sp exitcase -> liftIO $ do case exitcase of ExitCaseSuccess _ -> pure () ExitCaseException e -> do setTag sp "error" "true" setTag sp "error.message" (BS8.pack $ take I.maxMsgLen $ show e) ExitCaseAbort -> do setTag sp "error" "true" setTag sp "error.message" "abort" liftIO $ endSpan sp ) action withSpan_ :: (MonadIO m, MonadMask m) => BS.ByteString -> m a -> m a withSpan_ operation action = withSpan operation (const action) # INLINE setSpanId # setSpanId :: MonadIO m => SpanInFlight -> SpanId -> m () setSpanId sp sid = I.traceBuilder $ I.builder_setSpanId sp sid # INLINE setTraceId # setTraceId :: MonadIO m => SpanInFlight -> TraceId -> m () setTraceId sp tid = I.traceBuilder $ I.builder_setTraceId sp tid # INLINE beginSpan # beginSpan :: MonadIO m => BS.ByteString -> m SpanInFlight beginSpan operation = do u <- I.nextLocalSpan I.traceBuilder $ I.builder_beginSpan u operation pure u # INLINE endSpan # endSpan :: MonadIO m => SpanInFlight -> m () endSpan sp = I.traceBuilder $ I.builder_endSpan sp # INLINE setTag # setTag :: MonadIO m => SpanInFlight -> BS.ByteString -> BS.ByteString -> m () setTag sp k v = I.traceBuilder $ I.builder_setTag sp k v # INLINE addEvent # addEvent :: MonadIO m => SpanInFlight -> BS.ByteString -> BS.ByteString -> m () addEvent sp k v = I.traceBuilder $ I.builder_addEvent sp k v # INLINE setParentSpanContext # setParentSpanContext :: MonadIO m => SpanInFlight -> SpanContext -> m () setParentSpanContext sp ctx = I.traceBuilder $ I.builder_setParentSpanContext sp ctx # INLINE mkCounter # mkCounter :: MonadIO m => MI.InstrumentName -> m MI.Counter mkCounter name = do inst <- MI.Counter name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkUpDownCounter # mkUpDownCounter :: MonadIO m => MI.InstrumentName -> m MI.UpDownCounter mkUpDownCounter name = do inst <- MI.UpDownCounter name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkValueRecorder # mkValueRecorder :: MonadIO m => MI.InstrumentName -> m MI.ValueRecorder mkValueRecorder name = do inst <- MI.ValueRecorder name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkSumObserver # mkSumObserver :: MonadIO m => MI.InstrumentName -> m MI.SumObserver mkSumObserver name = do inst <- MI.SumObserver name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkUpDownSumObserver # mkUpDownSumObserver :: MonadIO m => MI.InstrumentName -> m MI.UpDownSumObserver mkUpDownSumObserver name = do inst <- MI.UpDownSumObserver name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst # INLINE mkValueObserver # mkValueObserver :: MonadIO m => MI.InstrumentName -> m MI.ValueObserver mkValueObserver name = do inst <- MI.ValueObserver name <$> I.nextInstrumentId I.traceBuilder $ I.builder_declareInstrument inst return inst | Take a measurement for a synchronous , additive instrument ( ' Counter ' , ' ' ) # INLINE add # add :: MonadIO m => MI.Instrument 'MI.Synchronous 'MI.Additive m' -> Int -> m () add i v = I.traceBuilder $ I.builder_captureMetric (MI.instrumentId i) v # INLINE record # record :: MonadIO m => MI.Instrument 'MI.Synchronous 'MI.NonAdditive m' -> Int -> m () record i v = I.traceBuilder $ I.builder_captureMetric (MI.instrumentId i) v | Take a measurement for an asynchronous instrument ( ' SumObserver ' , ' UpDownSumObserver ' , ' ValueObserver ' ) # INLINE observe # observe :: MonadIO m => MI.Instrument 'MI.Asynchronous a m' -> Int -> m () observe i v = I.traceBuilder $ I.builder_captureMetric (MI.instrumentId i) v #endif
d08b33af997091e7de696bff7c8680c1dbbe2e045a78aa7213d8eacd6e571ca3
ocaml-flambda/flambda-backend
flambda.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , OCamlPro and , (* *) (* Copyright 2013--2016 OCamlPro SAS *) Copyright 2014 - -2016 Jane Street Group LLC (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) [@@@ocaml.warning "+a-4-9-30-40-41-42"] (** Intermediate language used for tree-based analysis and optimization. *) (** Whether the callee in a function application is known at compile time. *) type call_kind = | Indirect | Direct of Closure_id.t * Simple constants . ( " Structured constants " are rewritten to invocations of [ ] so that they easily take part in optimizations . ) of [Pmakeblock] so that they easily take part in optimizations.) *) type const = | Int of int | Char of char * [ ] is kept separate from [ Int ] to improve printing (** The application of a function to a list of arguments. *) type apply = { (* CR-soon mshinwell: rename func -> callee, and lhs_of_application -> callee *) func : Variable.t; args : Variable.t list; result_layout : Lambda.layout; kind : call_kind; dbg : Debuginfo.t; reg_close : Lambda.region_close; mode : Lambda.alloc_mode; inlined : Lambda.inlined_attribute; (** Instructions from the source code as to whether the callee should be inlined. *) specialise : Lambda.specialise_attribute; (** Instructions from the source code as to whether the callee should be specialised. *) probe : Lambda.probe; (** Instruction from the source as to whether the call is a probe *) } * The update of a mutable variable . Mutable variables are distinct from immutable variables in Flambda . immutable variables in Flambda. *) type assign = { being_assigned : Mutable_variable.t; new_value : Variable.t; } (** The invocation of a method. *) type send = { kind : Lambda.meth_kind; meth : Variable.t; obj : Variable.t; args : Variable.t list; dbg : Debuginfo.t; reg_close : Lambda.region_close; mode : Lambda.alloc_mode; result_layout : Lambda.layout; } (** For details on these types, see projection.mli. *) type project_closure = Projection.project_closure type move_within_set_of_closures = Projection.move_within_set_of_closures type project_var = Projection.project_var (** See [free_vars] and [specialised_args], below. *) (* CR-someday mshinwell: move to separate module and make [Identifiable]. (Or maybe nearly Identifiable; having a special map that enforces invariants might be good.) *) type specialised_to = { var : Variable.t; (** The "outer variable". *) projection : Projection.t option; (** The [projecting_from] value (see projection.mli) of any [projection] must be another free variable or specialised argument (depending on whether this record type is involved in [free_vars] or [specialised_args] respectively) in the same set of closures. As such, this field describes a relation of projections between either the [free_vars] or the [specialised_args]. *) kind : Lambda.layout; } * Flambda terms are partitioned in a pseudo - ANF manner ; many terms are required to be [ let]-bound . This in particular ensures there is always a variable name for an expression that may be lifted out ( for example if it is found to be constant ) . Note : All bound variables in Flambda terms must be distinct . [ Flambda_invariants ] verifies this . required to be [let]-bound. This in particular ensures there is always a variable name for an expression that may be lifted out (for example if it is found to be constant). Note: All bound variables in Flambda terms must be distinct. [Flambda_invariants] verifies this. *) type t = | Var of Variable.t | Let of let_expr | Let_mutable of let_mutable | Let_rec of (Variable.t * named) list * t * CR - someday lwhite : give the same fields as Let . | Apply of apply | Send of send | Assign of assign | If_then_else of Variable.t * t * t * Lambda.layout | Switch of Variable.t * switch | String_switch of Variable.t * (string * t) list * t option * Lambda.layout * Restrictions on [ Lambda . ] also apply to [ String_switch ] . | Static_raise of Static_exception.t * Variable.t list | Static_catch of Static_exception.t * ( Variable.t * Lambda.layout ) list * t * t * Lambda.layout | Try_with of t * Variable.t * t * Lambda.layout | While of t * t | For of for_loop | Region of t | Tail of t | Proved_unreachable (** Values of type [named] will always be [let]-bound to a [Variable.t]. *) and named = | Symbol of Symbol.t | Const of const | Allocated_const of Allocated_const.t | Read_mutable of Mutable_variable.t | Read_symbol_field of Symbol.t * int * During the lifting of [ let ] bindings to [ program ] constructions after closure conversion , we generate symbols and their corresponding definitions ( which may or may not be constant ) , together with field accesses to such symbols . We would like it to be the case that such field accesses are simplified to the relevant component of the symbol concerned . ( The rationale is to generate efficient code and share constants as expected : see e.g. tests / asmcomp / staticalloc.ml . ) The components of the symbol would be identified by other symbols . This sort of access pattern is feasible because the top - level structure of symbols is statically allocated and fixed at compile time . It may seem that [ ( Pfield , ... ) ] expressions could be used to perform the field accesses . However for simplicity , to avoid having to keep track of properties of individual fields of blocks , [ Inconstant_idents ] never deems a [ Prim ( Pfield , ... ) ] expression to be constant . This would in general prevent field accesses to symbols from being simplified in the way we would like , since [ Lift_constants ] would not assign new symbols ( i.e. the things we would like to simplify to ) to the various projections from the symbols in question . To circumvent this problem we use [ Read_symbol_field ] when generating projections from the top level of symbols . Owing to the properties of symbols described above , such expressions may be eligible for declaration as constant by [ Inconstant_idents ] ( and thus themselves lifted to another symbol ) , without any further complication . [ Read_symbol_field ] may only be used when the definition of the symbol is in scope in the [ program ] . For external unresolved symbols , [ Pfield ] may still be used ; it will be changed to [ Read_symbol_field ] by [ Inline_and_simplify ] when ( and if ) the symbol is imported . closure conversion, we generate symbols and their corresponding definitions (which may or may not be constant), together with field accesses to such symbols. We would like it to be the case that such field accesses are simplified to the relevant component of the symbol concerned. (The rationale is to generate efficient code and share constants as expected: see e.g. tests/asmcomp/staticalloc.ml.) The components of the symbol would be identified by other symbols. This sort of access pattern is feasible because the top-level structure of symbols is statically allocated and fixed at compile time. It may seem that [Prim (Pfield, ...)] expressions could be used to perform the field accesses. However for simplicity, to avoid having to keep track of properties of individual fields of blocks, [Inconstant_idents] never deems a [Prim (Pfield, ...)] expression to be constant. This would in general prevent field accesses to symbols from being simplified in the way we would like, since [Lift_constants] would not assign new symbols (i.e. the things we would like to simplify to) to the various projections from the symbols in question. To circumvent this problem we use [Read_symbol_field] when generating projections from the top level of symbols. Owing to the properties of symbols described above, such expressions may be eligible for declaration as constant by [Inconstant_idents] (and thus themselves lifted to another symbol), without any further complication. [Read_symbol_field] may only be used when the definition of the symbol is in scope in the [program]. For external unresolved symbols, [Pfield] may still be used; it will be changed to [Read_symbol_field] by [Inline_and_simplify] when (and if) the symbol is imported. *) | Set_of_closures of set_of_closures | Project_closure of project_closure | Move_within_set_of_closures of move_within_set_of_closures | Project_var of project_var | Prim of Clambda_primitives.primitive * Variable.t list * Debuginfo.t * ANF escape hatch . CR - someday mshinwell : use [ letcont]-style construct to remove e.g. [ While ] and [ For ] . [While] and [For]. *) (* CR-someday mshinwell: try to produce a tighter definition of a "switch" (and translate to that earlier) so that middle- and back-end code for these can be reduced. *) (* CR-someday mshinwell: remove [Expr], but to do this easily would probably require a continuation-binding construct. *) (* CR-someday mshinwell: Since we lack expression identifiers on every term, we should probably introduce [Mutable_var] into [named] if we introduce more complicated analyses on these in the future. Alternatively, maybe consider removing mutable variables altogether. *) and let_expr = private { var : Variable.t; defining_expr : named; body : t; (* CR-someday mshinwell: we could consider having these be keys into some kind of global cache, to reduce memory usage. *) free_vars_of_defining_expr : Variable.Set.t; (** A cache of the free variables in the defining expression of the [let]. *) free_vars_of_body : Variable.Set.t; (** A cache of the free variables of the body of the [let]. This is an important optimization. *) } and let_mutable = { var : Mutable_variable.t; initial_value : Variable.t; contents_kind : Lambda.layout; body : t; } * The representation of a set of function declarations ( possibly mutually recursive ) . Such a set encapsulates the declarations themselves , information about their defining environment , and information used specifically for optimization . Before a function can be applied it must be " projected " from a set of closures to yield a " closure " . This is done using [ Project_closure ] ( see above ) . Given a closure , not only can it be applied , but information about its defining environment can be retrieved ( using [ Project_var ] , see above ) . At runtime , a [ set_of_closures ] corresponds to an OCaml value with tag [ Closure_tag ] ( possibly with inline [ Infix_tag](s ) ) . As an optimization , an operation ( [ Move_within_set_of_closures ] ) is provided ( see above ) which enables one closure within a set to be located given another closure in the same set . This avoids keeping a pointer to the whole set of closures alive when compiling , for example , mutually - recursive functions . recursive). Such a set encapsulates the declarations themselves, information about their defining environment, and information used specifically for optimization. Before a function can be applied it must be "projected" from a set of closures to yield a "closure". This is done using [Project_closure] (see above). Given a closure, not only can it be applied, but information about its defining environment can be retrieved (using [Project_var], see above). At runtime, a [set_of_closures] corresponds to an OCaml value with tag [Closure_tag] (possibly with inline [Infix_tag](s)). As an optimization, an operation ([Move_within_set_of_closures]) is provided (see above) which enables one closure within a set to be located given another closure in the same set. This avoids keeping a pointer to the whole set of closures alive when compiling, for example, mutually-recursive functions. *) and set_of_closures = private { function_decls : function_declarations; CR - soon mshinwell : consider renaming [ free_vars ] . Also , it 's still really confusing which side of this map to use when . " Vars bound by the closure " is the domain . Another example of when this is confusing : let bound_vars_approx = ( Env.find_approx env ) set.free_vars in in [ Build_export_info ] . confusing which side of this map to use when. "Vars bound by the closure" is the domain. Another example of when this is confusing: let bound_vars_approx = Variable.Map.map (Env.find_approx env) set.free_vars in in [Build_export_info]. *) (* CR-soon mshinwell: I'd like to arrange these maps so that it's impossible to put invalid projection information into them (in particular, so that we enforce that the relation stays within the domain of the map). *) free_vars : specialised_to Variable.Map.t; * Mapping from all variables free in the body of the [ function_decls ] to variables in scope at the definition point of the [ set_of_closures ] . The domain of this map is sometimes known as the " variables bound by the closure " . variables in scope at the definition point of the [set_of_closures]. The domain of this map is sometimes known as the "variables bound by the closure". *) specialised_args : specialised_to Variable.Map.t; * Parameters whose corresponding arguments are known to always alias a particular value . These are the only parameters that may , during [ Inline_and_simplify ] , have non - unknown approximations . An argument may only be specialised to a variable in the scope of the corresponding set of closures declaration . Usually , that variable itself also appears in the position of the specialised argument at all call sites of the function . However it may also be the case ( for example in code generated as a result of [ Augment_specialised_args ] ) that the various call sites of such a function have differing variables in the position of the specialised argument . This is permissible * so long as it is certain they all alias the same value * . Great care must be taken in transformations that result in this situation since there are no invariant checks for correctness . As an example , supposing all call sites of f are represented here : [ let x = ... in let f a b c = ... in let y = ... in f x y 1 ; f x y 1 ] the specialised arguments of f can ( but does not necessarily ) contain the association [ a ] - > [ x ] , but can not contain [ b ] - > [ y ] because [ f ] is not in the scope of [ y ] . If f were the recursive function [ let rec f a b c = f a 1 2 in ] , [ a ] - > [ x ] would still be a valid specialised argument because all recursive calls maintain the invariant . This information is used for optimization purposes , if such a binding is known , it is possible to specialise the body of the function according to its parameter . This is usually introduced when specialising a recursive function , for instance . [ let rec map f = function | [ ] - > [ ] | h : : t - > f h : : map f t let l = let succ x = x + 1 in map succ l ] [ map ] can be duplicated in [ map_succ ] to be specialised for the argument [ f ] . This will result in [ let l = let succ x = x + 1 in let rec map f = function | [ ] - > [ ] | h : : t - > f h : : map f t in map succ l ] with map having [ f ] - > [ succ ] in its [ specialised_args ] field . Specialised argument information for arguments that are used must never be erased . This ensures that specialised arguments whose approximations describe closures maintain those approximations , which is essential to transport the closure freshening information to the point of use ( e.g. a [ Project_var ] from such an argument ) . particular value. These are the only parameters that may, during [Inline_and_simplify], have non-unknown approximations. An argument may only be specialised to a variable in the scope of the corresponding set of closures declaration. Usually, that variable itself also appears in the position of the specialised argument at all call sites of the function. However it may also be the case (for example in code generated as a result of [Augment_specialised_args]) that the various call sites of such a function have differing variables in the position of the specialised argument. This is permissible *so long as it is certain they all alias the same value*. Great care must be taken in transformations that result in this situation since there are no invariant checks for correctness. As an example, supposing all call sites of f are represented here: [let x = ... in let f a b c = ... in let y = ... in f x y 1; f x y 1] the specialised arguments of f can (but does not necessarily) contain the association [a] -> [x], but cannot contain [b] -> [y] because [f] is not in the scope of [y]. If f were the recursive function [let rec f a b c = f a 1 2 in], [a] -> [x] would still be a valid specialised argument because all recursive calls maintain the invariant. This information is used for optimization purposes, if such a binding is known, it is possible to specialise the body of the function according to its parameter. This is usually introduced when specialising a recursive function, for instance. [let rec map f = function | [] -> [] | h :: t -> f h :: map f t let map_succ l = let succ x = x + 1 in map succ l] [map] can be duplicated in [map_succ] to be specialised for the argument [f]. This will result in [let map_succ l = let succ x = x + 1 in let rec map f = function | [] -> [] | h :: t -> f h :: map f t in map succ l] with map having [f] -> [succ] in its [specialised_args] field. Specialised argument information for arguments that are used must never be erased. This ensures that specialised arguments whose approximations describe closures maintain those approximations, which is essential to transport the closure freshening information to the point of use (e.g. a [Project_var] from such an argument). *) direct_call_surrogates : Variable.t Variable.Map.t; (** If [direct_call_surrogates] maps [fun_var1] to [fun_var2] then direct calls to [fun_var1] should be redirected to [fun_var2]. This is used to reduce the overhead of transformations that introduce wrapper functions (which will be inlined at direct call sites, but will penalise indirect call sites). [direct_call_surrogates] may not be transitively closed. *) alloc_mode : Lambda.alloc_mode; (** Whether these closures are allocated on the heap or locally. *) } and function_declarations = private { is_classic_mode: bool; * Indicates whether this [ function_declarations ] was compiled with -Oclassic . with -Oclassic. *) set_of_closures_id : Set_of_closures_id.t; * An identifier ( unique across all Flambda trees currently in memory ) of the set of closures associated with this set of function declarations . of the set of closures associated with this set of function declarations. *) set_of_closures_origin : Set_of_closures_origin.t; (** An identifier of the original set of closures on which this set of function declarations is based. Used to prevent different specialisations of the same functions from being inlined/specialised within each other. *) funs : function_declaration Variable.Map.t; (** The function(s) defined by the set of function declarations. The keys of this map are often referred to in the code as "fun_var"s. *) } and function_declaration = private { closure_origin: Closure_origin.t; params : Parameter.t list; return_layout : Lambda.layout; alloc_mode : Lambda.alloc_mode; region : bool; body : t; (* CR-soon mshinwell: inconsistent naming free_variables/free_vars here and above *) free_variables : Variable.Set.t; (** All variables free in the *body* of the function. For example, a variable that is bound as one of the function's parameters will still be included in this set. This field is present as an optimization. *) free_symbols : Symbol.Set.t; (** All symbols that occur in the function's body. (Symbols can never be bound in a function's body; the only thing that binds symbols is the [program] constructions below.) *) stub : bool; * A stub function is a generated function used to prepare arguments or return values to allow indirect calls to functions with a special calling convention . For instance indirect calls to tuplified functions must go through a stub . will be unconditionally inlined . return values to allow indirect calls to functions with a special calling convention. For instance indirect calls to tuplified functions must go through a stub. Stubs will be unconditionally inlined. *) dbg : Debuginfo.t; (** Debug info for the function declaration. *) inline : Lambda.inline_attribute; (** Inlining requirements from the source code. *) specialise : Lambda.specialise_attribute; (** Specialising requirements from the source code. *) check : Lambda.check_attribute; (** Check function properties requirements from the source code *) is_a_functor : bool; (** Whether the function is known definitively to be a functor. *) poll: Lambda.poll_attribute; (** Behaviour for polls *) } (** Equivalent to the similar type in [Lambda]. *) and switch = { numconsts : Numbers.Int.Set.t; (** Integer cases *) consts : (int * t) list; (** Integer cases *) numblocks : Numbers.Int.Set.t; (** Number of tag block cases *) blocks : (int * t) list; (** Tag block cases *) failaction : t option; (** Action to take if none matched *) kind : Lambda.layout } (** Equivalent to the similar type in [Lambda]. *) and for_loop = { bound_var : Variable.t; from_value : Variable.t; to_value : Variable.t; direction : Asttypes.direction_flag; body : t } (** Like a subset of [Flambda.named], except that instead of [Variable.t]s we have [Symbol.t]s, and everything is a constant (i.e. with a fixed value known at compile time). Values of this type describe constants that will be directly assigned to symbols in the object file (see below). *) and constant_defining_value = | Allocated_const of Allocated_const.t (** A single constant. These are never "simple constants" (type [const]) but instead more complicated constructions. *) | Block of Tag.t * constant_defining_value_block_field list (** A pre-allocated block full of constants (either simple constants or references to other constants, see below). *) | Set_of_closures of set_of_closures (** A closed (and thus constant) set of closures. (That is to say, [free_vars] must be empty.) *) | Project_closure of Symbol.t * Closure_id.t * Selection of one closure from a constant set of closures . Analogous to the equivalent operation on expressions . Analogous to the equivalent operation on expressions. *) and constant_defining_value_block_field = | Symbol of Symbol.t | Const of const module Constant_defining_value : Identifiable.S with type t = constant_defining_value type expr = t * A " program " is the contents of one compilation unit . It describes the various values that are assigned to symbols ( and in some cases fields of such symbols ) in the object file . As such , it is closely related to the compilation of toplevel modules . various values that are assigned to symbols (and in some cases fields of such symbols) in the object file. As such, it is closely related to the compilation of toplevel modules. *) type program_body = | Let_symbol of Symbol.t * constant_defining_value * program_body (** Define the given symbol to have the given constant value. *) | Let_rec_symbol of (Symbol.t * constant_defining_value) list * program_body * As for [ Let_symbol ] , but recursive . This is needed to treat examples like this , where a constant set of closures is lifted to toplevel : let rec f x = f x After lifting this produces ( in pseudo - Flambda ): Let_rec_symbol set_of_closures_symbol = ( Set_of_closures { f x - > let applied_function = Symbol f_closure in Apply ( applied_function , x ) } ) and f_closure = Project_closure ( set_of_closures_symbol , f ) Use of [ Let_rec_symbol ] , by virtue of the special handling in [ Inline_and_simplify.define_let_rec_symbol_approx ] , enables the approximation of the set of closures to be present in order to correctly simplify the [ Project_closure ] construction . ( See [ Inline_and_simplify.simplify_project_closure ] for that part . ) like this, where a constant set of closures is lifted to toplevel: let rec f x = f x After lifting this produces (in pseudo-Flambda): Let_rec_symbol set_of_closures_symbol = (Set_of_closures { f x -> let applied_function = Symbol f_closure in Apply (applied_function, x) }) and f_closure = Project_closure (set_of_closures_symbol, f) Use of [Let_rec_symbol], by virtue of the special handling in [Inline_and_simplify.define_let_rec_symbol_approx], enables the approximation of the set of closures to be present in order to correctly simplify the [Project_closure] construction. (See [Inline_and_simplify.simplify_project_closure] for that part.) *) | Initialize_symbol of Symbol.t * Tag.t * t list * program_body (** Define the given symbol as a constant block of the given size and tag; but with a possibly non-constant initializer. The initializer will be executed at most once (from the entry point of the compilation unit). *) | Effect of t * program_body (** Cause the given expression, which may have a side effect, to be executed. The resulting value is discarded. [Effect] constructions are never re-ordered. *) | End of Symbol.t (** [End] accepts the root symbol: the only symbol that can never be eliminated. *) type program = { imported_symbols : Symbol.Set.t; program_body : program_body; } (** Compute the free variables of a term. (This is O(1) for [Let]s). If [ignore_uses_as_callee], all free variables inside [Apply] expressions are ignored. Likewise [ignore_uses_in_project_var] for [Project_var] expressions. *) val free_variables : ?ignore_uses_as_callee:unit -> ?ignore_uses_as_argument:unit -> ?ignore_uses_in_project_var:unit -> t -> Variable.Set.t (** Compute the free variables of a named expression. *) val free_variables_named : ?ignore_uses_in_project_var:unit -> named -> Variable.Set.t (** Compute _all_ variables occurring inside an expression. *) val used_variables : ?ignore_uses_as_callee:unit -> ?ignore_uses_as_argument:unit -> ?ignore_uses_in_project_var:unit -> t -> Variable.Set.t (** Compute _all_ variables occurring inside a named expression. *) val used_variables_named : ?ignore_uses_in_project_var:unit -> named -> Variable.Set.t val free_symbols : expr -> Symbol.Set.t val free_symbols_named : named -> Symbol.Set.t val free_symbols_program : program -> Symbol.Set.t * Used to avoid exceeding the stack limit when handling expressions with multiple consecutive nested [ Let]-expressions . This saves rewriting large simplification functions in CPS . This function provides for the rewriting or elimination of expressions during the fold . multiple consecutive nested [Let]-expressions. This saves rewriting large simplification functions in CPS. This function provides for the rewriting or elimination of expressions during the fold. *) val fold_lets_option : t -> init:'a -> for_defining_expr:('a -> Variable.t -> named -> 'a * Variable.t * named) -> for_last_body:('a -> t -> t * 'b) (* CR-someday mshinwell: consider making [filter_defining_expr] optional *) -> filter_defining_expr:('b -> Variable.t -> named -> Variable.Set.t -> 'b * Variable.t * named option) -> t * 'b (** Like [fold_lets_option], but just a map. *) val map_lets : t -> for_defining_expr:(Variable.t -> named -> named) -> for_last_body:(t -> t) -> after_rebuild:(t -> t) -> t (** Like [map_lets], but just an iterator. *) val iter_lets : t -> for_defining_expr:(Variable.t -> named -> unit) -> for_last_body:(t -> unit) -> for_each_let:(t -> unit) -> unit (** Creates a [Let] expression. (This computes the free variables of the defining expression and the body.) *) val create_let : Variable.t -> named -> t -> t (** Apply the specified function [f] to the defining expression of the given [Let]-expression, returning a new [Let]. *) val map_defining_expr_of_let : let_expr -> f:(named -> named) -> t (** A module for the manipulation of terms where the recomputation of free variable sets is to be kept to a minimum. *) module With_free_variables : sig type 'a t (** O(1) time. *) val of_defining_expr_of_let : let_expr -> named t (** O(1) time. *) val of_body_of_let : let_expr -> expr t (** Takes the time required to calculate the free variables of the given term (proportional to the size of the term, except that the calculation for [Let] is O(1)). *) val of_expr : expr -> expr t val of_named : named -> named t (** Takes the time required to calculate the free variables of the given [expr]. *) val create_let_reusing_defining_expr : Variable.t -> named t -> expr -> expr (** Takes the time required to calculate the free variables of the given [named]. *) val create_let_reusing_body : Variable.t -> named -> expr t -> expr (** O(1) time. *) val create_let_reusing_both : Variable.t -> named t -> expr t -> expr (** The equivalent of the [Expr] constructor. *) val expr : expr t -> named t val contents : 'a t -> 'a (** O(1) time. *) val free_variables : _ t -> Variable.Set.t end (** Create a function declaration. This calculates the free variables and symbols occurring in the specified [body]. *) val create_function_declaration : params:Parameter.t list -> alloc_mode:Lambda.alloc_mode -> region:bool -> body:t -> stub:bool -> return_layout:Lambda.layout -> inline:Lambda.inline_attribute -> specialise:Lambda.specialise_attribute -> check:Lambda.check_attribute -> is_a_functor:bool -> closure_origin:Closure_origin.t -> poll:Lambda.poll_attribute -> function_declaration (** Create a function declaration based on another function declaration *) val update_function_declaration_body : function_declaration -> body:t -> function_declaration (** Create a set of function declarations given the individual declarations. *) val create_function_declarations : is_classic_mode:bool -> funs:function_declaration Variable.Map.t -> function_declarations (** Create a set of function declarations with a given set of closures origin. *) val create_function_declarations_with_origin : is_classic_mode:bool -> funs:function_declaration Variable.Map.t -> set_of_closures_origin:Set_of_closures_origin.t -> function_declarations (** Change only the code of a function declaration. *) val update_body_of_function_declaration : function_declaration -> body:expr -> function_declaration (** Create a set of function declarations based on another set of function declarations. *) val update_function_declarations : function_declarations -> funs:function_declaration Variable.Map.t -> function_declarations val create_function_declarations_with_closures_origin : is_classic_mode: bool -> funs:function_declaration Variable.Map.t -> set_of_closures_origin:Set_of_closures_origin.t -> function_declarations val import_function_declarations_for_pack : function_declarations -> (Set_of_closures_id.t -> Set_of_closures_id.t) -> (Set_of_closures_origin.t -> Set_of_closures_origin.t) -> function_declarations (** Create a set of closures. Checks are made to ensure that [free_vars] and [specialised_args] are reasonable. *) val create_set_of_closures : function_decls:function_declarations -> free_vars:specialised_to Variable.Map.t -> specialised_args:specialised_to Variable.Map.t -> direct_call_surrogates:Variable.t Variable.Map.t -> set_of_closures (** Given a function declaration, find which of its parameters (if any) are used in the body. *) val used_params : function_declaration -> Variable.Set.t type maybe_named = | Is_expr of t | Is_named of named * This function is designed for the internal use of [ Flambda_iterators ] . See that module for iterators to be used over Flambda terms . See that module for iterators to be used over Flambda terms. *) val iter_general : toplevel:bool -> (t -> unit) -> (named -> unit) -> maybe_named -> unit val print : Format.formatter -> t -> unit val print_named : Format.formatter -> named -> unit val print_program : Format.formatter -> program -> unit val print_const : Format.formatter -> const -> unit val print_constant_defining_value : Format.formatter -> constant_defining_value -> unit val print_function_declaration : Format.formatter -> Variable.t * function_declaration -> unit val print_function_declarations : Format.formatter -> function_declarations -> unit val print_project_closure : Format.formatter -> project_closure -> unit val print_move_within_set_of_closures : Format.formatter -> move_within_set_of_closures -> unit val print_project_var : Format.formatter -> project_var -> unit val print_set_of_closures : Format.formatter -> set_of_closures -> unit val print_specialised_to : Format.formatter -> specialised_to -> unit val equal_call_kind : call_kind -> call_kind -> bool val equal_specialised_to : specialised_to -> specialised_to -> bool val compare_const : const -> const -> int val compare_project_var : project_var -> project_var -> int val compare_move_within_set_of_closures : move_within_set_of_closures -> move_within_set_of_closures -> int val compare_project_closure : project_closure -> project_closure -> int
null
https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/651e3119bfd6ed8d79d3139054093872b735fda1/middle_end/flambda/flambda.mli
ocaml
************************************************************************ OCaml Copyright 2013--2016 OCamlPro SAS All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Intermediate language used for tree-based analysis and optimization. * Whether the callee in a function application is known at compile time. * The application of a function to a list of arguments. CR-soon mshinwell: rename func -> callee, and lhs_of_application -> callee * Instructions from the source code as to whether the callee should be inlined. * Instructions from the source code as to whether the callee should be specialised. * Instruction from the source as to whether the call is a probe * The invocation of a method. * For details on these types, see projection.mli. * See [free_vars] and [specialised_args], below. CR-someday mshinwell: move to separate module and make [Identifiable]. (Or maybe nearly Identifiable; having a special map that enforces invariants might be good.) * The "outer variable". * The [projecting_from] value (see projection.mli) of any [projection] must be another free variable or specialised argument (depending on whether this record type is involved in [free_vars] or [specialised_args] respectively) in the same set of closures. As such, this field describes a relation of projections between either the [free_vars] or the [specialised_args]. * Values of type [named] will always be [let]-bound to a [Variable.t]. CR-someday mshinwell: try to produce a tighter definition of a "switch" (and translate to that earlier) so that middle- and back-end code for these can be reduced. CR-someday mshinwell: remove [Expr], but to do this easily would probably require a continuation-binding construct. CR-someday mshinwell: Since we lack expression identifiers on every term, we should probably introduce [Mutable_var] into [named] if we introduce more complicated analyses on these in the future. Alternatively, maybe consider removing mutable variables altogether. CR-someday mshinwell: we could consider having these be keys into some kind of global cache, to reduce memory usage. * A cache of the free variables in the defining expression of the [let]. * A cache of the free variables of the body of the [let]. This is an important optimization. CR-soon mshinwell: I'd like to arrange these maps so that it's impossible to put invalid projection information into them (in particular, so that we enforce that the relation stays within the domain of the map). * If [direct_call_surrogates] maps [fun_var1] to [fun_var2] then direct calls to [fun_var1] should be redirected to [fun_var2]. This is used to reduce the overhead of transformations that introduce wrapper functions (which will be inlined at direct call sites, but will penalise indirect call sites). [direct_call_surrogates] may not be transitively closed. * Whether these closures are allocated on the heap or locally. * An identifier of the original set of closures on which this set of function declarations is based. Used to prevent different specialisations of the same functions from being inlined/specialised within each other. * The function(s) defined by the set of function declarations. The keys of this map are often referred to in the code as "fun_var"s. CR-soon mshinwell: inconsistent naming free_variables/free_vars here and above * All variables free in the *body* of the function. For example, a variable that is bound as one of the function's parameters will still be included in this set. This field is present as an optimization. * All symbols that occur in the function's body. (Symbols can never be bound in a function's body; the only thing that binds symbols is the [program] constructions below.) * Debug info for the function declaration. * Inlining requirements from the source code. * Specialising requirements from the source code. * Check function properties requirements from the source code * Whether the function is known definitively to be a functor. * Behaviour for polls * Equivalent to the similar type in [Lambda]. * Integer cases * Integer cases * Number of tag block cases * Tag block cases * Action to take if none matched * Equivalent to the similar type in [Lambda]. * Like a subset of [Flambda.named], except that instead of [Variable.t]s we have [Symbol.t]s, and everything is a constant (i.e. with a fixed value known at compile time). Values of this type describe constants that will be directly assigned to symbols in the object file (see below). * A single constant. These are never "simple constants" (type [const]) but instead more complicated constructions. * A pre-allocated block full of constants (either simple constants or references to other constants, see below). * A closed (and thus constant) set of closures. (That is to say, [free_vars] must be empty.) * Define the given symbol to have the given constant value. * Define the given symbol as a constant block of the given size and tag; but with a possibly non-constant initializer. The initializer will be executed at most once (from the entry point of the compilation unit). * Cause the given expression, which may have a side effect, to be executed. The resulting value is discarded. [Effect] constructions are never re-ordered. * [End] accepts the root symbol: the only symbol that can never be eliminated. * Compute the free variables of a term. (This is O(1) for [Let]s). If [ignore_uses_as_callee], all free variables inside [Apply] expressions are ignored. Likewise [ignore_uses_in_project_var] for [Project_var] expressions. * Compute the free variables of a named expression. * Compute _all_ variables occurring inside an expression. * Compute _all_ variables occurring inside a named expression. CR-someday mshinwell: consider making [filter_defining_expr] optional * Like [fold_lets_option], but just a map. * Like [map_lets], but just an iterator. * Creates a [Let] expression. (This computes the free variables of the defining expression and the body.) * Apply the specified function [f] to the defining expression of the given [Let]-expression, returning a new [Let]. * A module for the manipulation of terms where the recomputation of free variable sets is to be kept to a minimum. * O(1) time. * O(1) time. * Takes the time required to calculate the free variables of the given term (proportional to the size of the term, except that the calculation for [Let] is O(1)). * Takes the time required to calculate the free variables of the given [expr]. * Takes the time required to calculate the free variables of the given [named]. * O(1) time. * The equivalent of the [Expr] constructor. * O(1) time. * Create a function declaration. This calculates the free variables and symbols occurring in the specified [body]. * Create a function declaration based on another function declaration * Create a set of function declarations given the individual declarations. * Create a set of function declarations with a given set of closures origin. * Change only the code of a function declaration. * Create a set of function declarations based on another set of function declarations. * Create a set of closures. Checks are made to ensure that [free_vars] and [specialised_args] are reasonable. * Given a function declaration, find which of its parameters (if any) are used in the body.
, OCamlPro and , Copyright 2014 - -2016 Jane Street Group LLC the GNU Lesser General Public License version 2.1 , with the [@@@ocaml.warning "+a-4-9-30-40-41-42"] type call_kind = | Indirect | Direct of Closure_id.t * Simple constants . ( " Structured constants " are rewritten to invocations of [ ] so that they easily take part in optimizations . ) of [Pmakeblock] so that they easily take part in optimizations.) *) type const = | Int of int | Char of char * [ ] is kept separate from [ Int ] to improve printing type apply = { func : Variable.t; args : Variable.t list; result_layout : Lambda.layout; kind : call_kind; dbg : Debuginfo.t; reg_close : Lambda.region_close; mode : Lambda.alloc_mode; inlined : Lambda.inlined_attribute; specialise : Lambda.specialise_attribute; probe : Lambda.probe; } * The update of a mutable variable . Mutable variables are distinct from immutable variables in Flambda . immutable variables in Flambda. *) type assign = { being_assigned : Mutable_variable.t; new_value : Variable.t; } type send = { kind : Lambda.meth_kind; meth : Variable.t; obj : Variable.t; args : Variable.t list; dbg : Debuginfo.t; reg_close : Lambda.region_close; mode : Lambda.alloc_mode; result_layout : Lambda.layout; } type project_closure = Projection.project_closure type move_within_set_of_closures = Projection.move_within_set_of_closures type project_var = Projection.project_var type specialised_to = { var : Variable.t; projection : Projection.t option; kind : Lambda.layout; } * Flambda terms are partitioned in a pseudo - ANF manner ; many terms are required to be [ let]-bound . This in particular ensures there is always a variable name for an expression that may be lifted out ( for example if it is found to be constant ) . Note : All bound variables in Flambda terms must be distinct . [ Flambda_invariants ] verifies this . required to be [let]-bound. This in particular ensures there is always a variable name for an expression that may be lifted out (for example if it is found to be constant). Note: All bound variables in Flambda terms must be distinct. [Flambda_invariants] verifies this. *) type t = | Var of Variable.t | Let of let_expr | Let_mutable of let_mutable | Let_rec of (Variable.t * named) list * t * CR - someday lwhite : give the same fields as Let . | Apply of apply | Send of send | Assign of assign | If_then_else of Variable.t * t * t * Lambda.layout | Switch of Variable.t * switch | String_switch of Variable.t * (string * t) list * t option * Lambda.layout * Restrictions on [ Lambda . ] also apply to [ String_switch ] . | Static_raise of Static_exception.t * Variable.t list | Static_catch of Static_exception.t * ( Variable.t * Lambda.layout ) list * t * t * Lambda.layout | Try_with of t * Variable.t * t * Lambda.layout | While of t * t | For of for_loop | Region of t | Tail of t | Proved_unreachable and named = | Symbol of Symbol.t | Const of const | Allocated_const of Allocated_const.t | Read_mutable of Mutable_variable.t | Read_symbol_field of Symbol.t * int * During the lifting of [ let ] bindings to [ program ] constructions after closure conversion , we generate symbols and their corresponding definitions ( which may or may not be constant ) , together with field accesses to such symbols . We would like it to be the case that such field accesses are simplified to the relevant component of the symbol concerned . ( The rationale is to generate efficient code and share constants as expected : see e.g. tests / asmcomp / staticalloc.ml . ) The components of the symbol would be identified by other symbols . This sort of access pattern is feasible because the top - level structure of symbols is statically allocated and fixed at compile time . It may seem that [ ( Pfield , ... ) ] expressions could be used to perform the field accesses . However for simplicity , to avoid having to keep track of properties of individual fields of blocks , [ Inconstant_idents ] never deems a [ Prim ( Pfield , ... ) ] expression to be constant . This would in general prevent field accesses to symbols from being simplified in the way we would like , since [ Lift_constants ] would not assign new symbols ( i.e. the things we would like to simplify to ) to the various projections from the symbols in question . To circumvent this problem we use [ Read_symbol_field ] when generating projections from the top level of symbols . Owing to the properties of symbols described above , such expressions may be eligible for declaration as constant by [ Inconstant_idents ] ( and thus themselves lifted to another symbol ) , without any further complication . [ Read_symbol_field ] may only be used when the definition of the symbol is in scope in the [ program ] . For external unresolved symbols , [ Pfield ] may still be used ; it will be changed to [ Read_symbol_field ] by [ Inline_and_simplify ] when ( and if ) the symbol is imported . closure conversion, we generate symbols and their corresponding definitions (which may or may not be constant), together with field accesses to such symbols. We would like it to be the case that such field accesses are simplified to the relevant component of the symbol concerned. (The rationale is to generate efficient code and share constants as expected: see e.g. tests/asmcomp/staticalloc.ml.) The components of the symbol would be identified by other symbols. This sort of access pattern is feasible because the top-level structure of symbols is statically allocated and fixed at compile time. It may seem that [Prim (Pfield, ...)] expressions could be used to perform the field accesses. However for simplicity, to avoid having to keep track of properties of individual fields of blocks, [Inconstant_idents] never deems a [Prim (Pfield, ...)] expression to be constant. This would in general prevent field accesses to symbols from being simplified in the way we would like, since [Lift_constants] would not assign new symbols (i.e. the things we would like to simplify to) to the various projections from the symbols in question. To circumvent this problem we use [Read_symbol_field] when generating projections from the top level of symbols. Owing to the properties of symbols described above, such expressions may be eligible for declaration as constant by [Inconstant_idents] (and thus themselves lifted to another symbol), without any further complication. [Read_symbol_field] may only be used when the definition of the symbol is in scope in the [program]. For external unresolved symbols, [Pfield] may still be used; it will be changed to [Read_symbol_field] by [Inline_and_simplify] when (and if) the symbol is imported. *) | Set_of_closures of set_of_closures | Project_closure of project_closure | Move_within_set_of_closures of move_within_set_of_closures | Project_var of project_var | Prim of Clambda_primitives.primitive * Variable.t list * Debuginfo.t * ANF escape hatch . CR - someday mshinwell : use [ letcont]-style construct to remove e.g. [ While ] and [ For ] . [While] and [For]. *) and let_expr = private { var : Variable.t; defining_expr : named; body : t; free_vars_of_defining_expr : Variable.Set.t; free_vars_of_body : Variable.Set.t; } and let_mutable = { var : Mutable_variable.t; initial_value : Variable.t; contents_kind : Lambda.layout; body : t; } * The representation of a set of function declarations ( possibly mutually recursive ) . Such a set encapsulates the declarations themselves , information about their defining environment , and information used specifically for optimization . Before a function can be applied it must be " projected " from a set of closures to yield a " closure " . This is done using [ Project_closure ] ( see above ) . Given a closure , not only can it be applied , but information about its defining environment can be retrieved ( using [ Project_var ] , see above ) . At runtime , a [ set_of_closures ] corresponds to an OCaml value with tag [ Closure_tag ] ( possibly with inline [ Infix_tag](s ) ) . As an optimization , an operation ( [ Move_within_set_of_closures ] ) is provided ( see above ) which enables one closure within a set to be located given another closure in the same set . This avoids keeping a pointer to the whole set of closures alive when compiling , for example , mutually - recursive functions . recursive). Such a set encapsulates the declarations themselves, information about their defining environment, and information used specifically for optimization. Before a function can be applied it must be "projected" from a set of closures to yield a "closure". This is done using [Project_closure] (see above). Given a closure, not only can it be applied, but information about its defining environment can be retrieved (using [Project_var], see above). At runtime, a [set_of_closures] corresponds to an OCaml value with tag [Closure_tag] (possibly with inline [Infix_tag](s)). As an optimization, an operation ([Move_within_set_of_closures]) is provided (see above) which enables one closure within a set to be located given another closure in the same set. This avoids keeping a pointer to the whole set of closures alive when compiling, for example, mutually-recursive functions. *) and set_of_closures = private { function_decls : function_declarations; CR - soon mshinwell : consider renaming [ free_vars ] . Also , it 's still really confusing which side of this map to use when . " Vars bound by the closure " is the domain . Another example of when this is confusing : let bound_vars_approx = ( Env.find_approx env ) set.free_vars in in [ Build_export_info ] . confusing which side of this map to use when. "Vars bound by the closure" is the domain. Another example of when this is confusing: let bound_vars_approx = Variable.Map.map (Env.find_approx env) set.free_vars in in [Build_export_info]. *) free_vars : specialised_to Variable.Map.t; * Mapping from all variables free in the body of the [ function_decls ] to variables in scope at the definition point of the [ set_of_closures ] . The domain of this map is sometimes known as the " variables bound by the closure " . variables in scope at the definition point of the [set_of_closures]. The domain of this map is sometimes known as the "variables bound by the closure". *) specialised_args : specialised_to Variable.Map.t; * Parameters whose corresponding arguments are known to always alias a particular value . These are the only parameters that may , during [ Inline_and_simplify ] , have non - unknown approximations . An argument may only be specialised to a variable in the scope of the corresponding set of closures declaration . Usually , that variable itself also appears in the position of the specialised argument at all call sites of the function . However it may also be the case ( for example in code generated as a result of [ Augment_specialised_args ] ) that the various call sites of such a function have differing variables in the position of the specialised argument . This is permissible * so long as it is certain they all alias the same value * . Great care must be taken in transformations that result in this situation since there are no invariant checks for correctness . As an example , supposing all call sites of f are represented here : [ let x = ... in let f a b c = ... in let y = ... in f x y 1 ; f x y 1 ] the specialised arguments of f can ( but does not necessarily ) contain the association [ a ] - > [ x ] , but can not contain [ b ] - > [ y ] because [ f ] is not in the scope of [ y ] . If f were the recursive function [ let rec f a b c = f a 1 2 in ] , [ a ] - > [ x ] would still be a valid specialised argument because all recursive calls maintain the invariant . This information is used for optimization purposes , if such a binding is known , it is possible to specialise the body of the function according to its parameter . This is usually introduced when specialising a recursive function , for instance . [ let rec map f = function | [ ] - > [ ] | h : : t - > f h : : map f t let l = let succ x = x + 1 in map succ l ] [ map ] can be duplicated in [ map_succ ] to be specialised for the argument [ f ] . This will result in [ let l = let succ x = x + 1 in let rec map f = function | [ ] - > [ ] | h : : t - > f h : : map f t in map succ l ] with map having [ f ] - > [ succ ] in its [ specialised_args ] field . Specialised argument information for arguments that are used must never be erased . This ensures that specialised arguments whose approximations describe closures maintain those approximations , which is essential to transport the closure freshening information to the point of use ( e.g. a [ Project_var ] from such an argument ) . particular value. These are the only parameters that may, during [Inline_and_simplify], have non-unknown approximations. An argument may only be specialised to a variable in the scope of the corresponding set of closures declaration. Usually, that variable itself also appears in the position of the specialised argument at all call sites of the function. However it may also be the case (for example in code generated as a result of [Augment_specialised_args]) that the various call sites of such a function have differing variables in the position of the specialised argument. This is permissible *so long as it is certain they all alias the same value*. Great care must be taken in transformations that result in this situation since there are no invariant checks for correctness. As an example, supposing all call sites of f are represented here: [let x = ... in let f a b c = ... in let y = ... in f x y 1; f x y 1] the specialised arguments of f can (but does not necessarily) contain the association [a] -> [x], but cannot contain [b] -> [y] because [f] is not in the scope of [y]. If f were the recursive function [let rec f a b c = f a 1 2 in], [a] -> [x] would still be a valid specialised argument because all recursive calls maintain the invariant. This information is used for optimization purposes, if such a binding is known, it is possible to specialise the body of the function according to its parameter. This is usually introduced when specialising a recursive function, for instance. [let rec map f = function | [] -> [] | h :: t -> f h :: map f t let map_succ l = let succ x = x + 1 in map succ l] [map] can be duplicated in [map_succ] to be specialised for the argument [f]. This will result in [let map_succ l = let succ x = x + 1 in let rec map f = function | [] -> [] | h :: t -> f h :: map f t in map succ l] with map having [f] -> [succ] in its [specialised_args] field. Specialised argument information for arguments that are used must never be erased. This ensures that specialised arguments whose approximations describe closures maintain those approximations, which is essential to transport the closure freshening information to the point of use (e.g. a [Project_var] from such an argument). *) direct_call_surrogates : Variable.t Variable.Map.t; alloc_mode : Lambda.alloc_mode; } and function_declarations = private { is_classic_mode: bool; * Indicates whether this [ function_declarations ] was compiled with -Oclassic . with -Oclassic. *) set_of_closures_id : Set_of_closures_id.t; * An identifier ( unique across all Flambda trees currently in memory ) of the set of closures associated with this set of function declarations . of the set of closures associated with this set of function declarations. *) set_of_closures_origin : Set_of_closures_origin.t; funs : function_declaration Variable.Map.t; } and function_declaration = private { closure_origin: Closure_origin.t; params : Parameter.t list; return_layout : Lambda.layout; alloc_mode : Lambda.alloc_mode; region : bool; body : t; free_variables : Variable.Set.t; free_symbols : Symbol.Set.t; stub : bool; * A stub function is a generated function used to prepare arguments or return values to allow indirect calls to functions with a special calling convention . For instance indirect calls to tuplified functions must go through a stub . will be unconditionally inlined . return values to allow indirect calls to functions with a special calling convention. For instance indirect calls to tuplified functions must go through a stub. Stubs will be unconditionally inlined. *) dbg : Debuginfo.t; inline : Lambda.inline_attribute; specialise : Lambda.specialise_attribute; check : Lambda.check_attribute; is_a_functor : bool; poll: Lambda.poll_attribute; } and switch = { kind : Lambda.layout } and for_loop = { bound_var : Variable.t; from_value : Variable.t; to_value : Variable.t; direction : Asttypes.direction_flag; body : t } and constant_defining_value = | Allocated_const of Allocated_const.t | Block of Tag.t * constant_defining_value_block_field list | Set_of_closures of set_of_closures | Project_closure of Symbol.t * Closure_id.t * Selection of one closure from a constant set of closures . Analogous to the equivalent operation on expressions . Analogous to the equivalent operation on expressions. *) and constant_defining_value_block_field = | Symbol of Symbol.t | Const of const module Constant_defining_value : Identifiable.S with type t = constant_defining_value type expr = t * A " program " is the contents of one compilation unit . It describes the various values that are assigned to symbols ( and in some cases fields of such symbols ) in the object file . As such , it is closely related to the compilation of toplevel modules . various values that are assigned to symbols (and in some cases fields of such symbols) in the object file. As such, it is closely related to the compilation of toplevel modules. *) type program_body = | Let_symbol of Symbol.t * constant_defining_value * program_body | Let_rec_symbol of (Symbol.t * constant_defining_value) list * program_body * As for [ Let_symbol ] , but recursive . This is needed to treat examples like this , where a constant set of closures is lifted to toplevel : let rec f x = f x After lifting this produces ( in pseudo - Flambda ): Let_rec_symbol set_of_closures_symbol = ( Set_of_closures { f x - > let applied_function = Symbol f_closure in Apply ( applied_function , x ) } ) and f_closure = Project_closure ( set_of_closures_symbol , f ) Use of [ Let_rec_symbol ] , by virtue of the special handling in [ Inline_and_simplify.define_let_rec_symbol_approx ] , enables the approximation of the set of closures to be present in order to correctly simplify the [ Project_closure ] construction . ( See [ Inline_and_simplify.simplify_project_closure ] for that part . ) like this, where a constant set of closures is lifted to toplevel: let rec f x = f x After lifting this produces (in pseudo-Flambda): Let_rec_symbol set_of_closures_symbol = (Set_of_closures { f x -> let applied_function = Symbol f_closure in Apply (applied_function, x) }) and f_closure = Project_closure (set_of_closures_symbol, f) Use of [Let_rec_symbol], by virtue of the special handling in [Inline_and_simplify.define_let_rec_symbol_approx], enables the approximation of the set of closures to be present in order to correctly simplify the [Project_closure] construction. (See [Inline_and_simplify.simplify_project_closure] for that part.) *) | Initialize_symbol of Symbol.t * Tag.t * t list * program_body | Effect of t * program_body | End of Symbol.t type program = { imported_symbols : Symbol.Set.t; program_body : program_body; } val free_variables : ?ignore_uses_as_callee:unit -> ?ignore_uses_as_argument:unit -> ?ignore_uses_in_project_var:unit -> t -> Variable.Set.t val free_variables_named : ?ignore_uses_in_project_var:unit -> named -> Variable.Set.t val used_variables : ?ignore_uses_as_callee:unit -> ?ignore_uses_as_argument:unit -> ?ignore_uses_in_project_var:unit -> t -> Variable.Set.t val used_variables_named : ?ignore_uses_in_project_var:unit -> named -> Variable.Set.t val free_symbols : expr -> Symbol.Set.t val free_symbols_named : named -> Symbol.Set.t val free_symbols_program : program -> Symbol.Set.t * Used to avoid exceeding the stack limit when handling expressions with multiple consecutive nested [ Let]-expressions . This saves rewriting large simplification functions in CPS . This function provides for the rewriting or elimination of expressions during the fold . multiple consecutive nested [Let]-expressions. This saves rewriting large simplification functions in CPS. This function provides for the rewriting or elimination of expressions during the fold. *) val fold_lets_option : t -> init:'a -> for_defining_expr:('a -> Variable.t -> named -> 'a * Variable.t * named) -> for_last_body:('a -> t -> t * 'b) -> filter_defining_expr:('b -> Variable.t -> named -> Variable.Set.t -> 'b * Variable.t * named option) -> t * 'b val map_lets : t -> for_defining_expr:(Variable.t -> named -> named) -> for_last_body:(t -> t) -> after_rebuild:(t -> t) -> t val iter_lets : t -> for_defining_expr:(Variable.t -> named -> unit) -> for_last_body:(t -> unit) -> for_each_let:(t -> unit) -> unit val create_let : Variable.t -> named -> t -> t val map_defining_expr_of_let : let_expr -> f:(named -> named) -> t module With_free_variables : sig type 'a t val of_defining_expr_of_let : let_expr -> named t val of_body_of_let : let_expr -> expr t val of_expr : expr -> expr t val of_named : named -> named t val create_let_reusing_defining_expr : Variable.t -> named t -> expr -> expr val create_let_reusing_body : Variable.t -> named -> expr t -> expr val create_let_reusing_both : Variable.t -> named t -> expr t -> expr val expr : expr t -> named t val contents : 'a t -> 'a val free_variables : _ t -> Variable.Set.t end val create_function_declaration : params:Parameter.t list -> alloc_mode:Lambda.alloc_mode -> region:bool -> body:t -> stub:bool -> return_layout:Lambda.layout -> inline:Lambda.inline_attribute -> specialise:Lambda.specialise_attribute -> check:Lambda.check_attribute -> is_a_functor:bool -> closure_origin:Closure_origin.t -> poll:Lambda.poll_attribute -> function_declaration val update_function_declaration_body : function_declaration -> body:t -> function_declaration val create_function_declarations : is_classic_mode:bool -> funs:function_declaration Variable.Map.t -> function_declarations val create_function_declarations_with_origin : is_classic_mode:bool -> funs:function_declaration Variable.Map.t -> set_of_closures_origin:Set_of_closures_origin.t -> function_declarations val update_body_of_function_declaration : function_declaration -> body:expr -> function_declaration val update_function_declarations : function_declarations -> funs:function_declaration Variable.Map.t -> function_declarations val create_function_declarations_with_closures_origin : is_classic_mode: bool -> funs:function_declaration Variable.Map.t -> set_of_closures_origin:Set_of_closures_origin.t -> function_declarations val import_function_declarations_for_pack : function_declarations -> (Set_of_closures_id.t -> Set_of_closures_id.t) -> (Set_of_closures_origin.t -> Set_of_closures_origin.t) -> function_declarations val create_set_of_closures : function_decls:function_declarations -> free_vars:specialised_to Variable.Map.t -> specialised_args:specialised_to Variable.Map.t -> direct_call_surrogates:Variable.t Variable.Map.t -> set_of_closures val used_params : function_declaration -> Variable.Set.t type maybe_named = | Is_expr of t | Is_named of named * This function is designed for the internal use of [ Flambda_iterators ] . See that module for iterators to be used over Flambda terms . See that module for iterators to be used over Flambda terms. *) val iter_general : toplevel:bool -> (t -> unit) -> (named -> unit) -> maybe_named -> unit val print : Format.formatter -> t -> unit val print_named : Format.formatter -> named -> unit val print_program : Format.formatter -> program -> unit val print_const : Format.formatter -> const -> unit val print_constant_defining_value : Format.formatter -> constant_defining_value -> unit val print_function_declaration : Format.formatter -> Variable.t * function_declaration -> unit val print_function_declarations : Format.formatter -> function_declarations -> unit val print_project_closure : Format.formatter -> project_closure -> unit val print_move_within_set_of_closures : Format.formatter -> move_within_set_of_closures -> unit val print_project_var : Format.formatter -> project_var -> unit val print_set_of_closures : Format.formatter -> set_of_closures -> unit val print_specialised_to : Format.formatter -> specialised_to -> unit val equal_call_kind : call_kind -> call_kind -> bool val equal_specialised_to : specialised_to -> specialised_to -> bool val compare_const : const -> const -> int val compare_project_var : project_var -> project_var -> int val compare_move_within_set_of_closures : move_within_set_of_closures -> move_within_set_of_closures -> int val compare_project_closure : project_closure -> project_closure -> int
820f5fe4f5a846c0325e6d7bd9eafd68ee4157d9d69fbe9ccc7df3a06c59e740
mejgun/haskell-tdlib
SetName.hs
{-# LANGUAGE OverloadedStrings #-} -- | module TD.Query.SetName where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U -- | Changes the first and last name of the current user @first_name The new value of the first name for the current user ; 1 - 64 characters @last_name The new value of the optional last name for the current user ; 0 - 64 characters data SetName = SetName { -- | last_name :: Maybe String, -- | first_name :: Maybe String } deriving (Eq) instance Show SetName where show SetName { last_name = last_name_, first_name = first_name_ } = "SetName" ++ U.cc [ U.p "last_name" last_name_, U.p "first_name" first_name_ ] instance T.ToJSON SetName where toJSON SetName { last_name = last_name_, first_name = first_name_ } = A.object [ "@type" A..= T.String "setName", "last_name" A..= last_name_, "first_name" A..= first_name_ ]
null
https://raw.githubusercontent.com/mejgun/haskell-tdlib/81516bd04c25c7371d4a9a5c972499791111c407/src/TD/Query/SetName.hs
haskell
# LANGUAGE OverloadedStrings # | | | |
module TD.Query.SetName where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U Changes the first and last name of the current user @first_name The new value of the first name for the current user ; 1 - 64 characters @last_name The new value of the optional last name for the current user ; 0 - 64 characters data SetName = SetName last_name :: Maybe String, first_name :: Maybe String } deriving (Eq) instance Show SetName where show SetName { last_name = last_name_, first_name = first_name_ } = "SetName" ++ U.cc [ U.p "last_name" last_name_, U.p "first_name" first_name_ ] instance T.ToJSON SetName where toJSON SetName { last_name = last_name_, first_name = first_name_ } = A.object [ "@type" A..= T.String "setName", "last_name" A..= last_name_, "first_name" A..= first_name_ ]
15cc051ef040294980885a07e57331aa31f878175e5a9aeed780af08b74c197c
clojure-garden/clojure-garden
slack_ctl.clj
(ns platform.slack.slack-ctl)
null
https://raw.githubusercontent.com/clojure-garden/clojure-garden/c6929c58c5d0fcc26b9ce0d7ba469269b4fda7b0/modules/backend/src/platform/slack/slack_ctl.clj
clojure
(ns platform.slack.slack-ctl)
e1ba897e42dc62c82aae88303f9205365683d66e70f4d8feb6d8f8285a3b6e52
ocaml/oasis
BaseCustom.ml
(******************************************************************************) OASIS : architecture for building OCaml libraries and applications (* *) Copyright ( C ) 2011 - 2016 , Copyright ( C ) 2008 - 2011 , OCamlCore SARL (* *) (* This library is free software; you can redistribute it and/or modify it *) (* under the terms of the GNU Lesser General Public License as published by *) the Free Software Foundation ; either version 2.1 of the License , or ( at (* your option) any later version, with the OCaml static compilation *) (* exception. *) (* *) (* 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 file COPYING for more *) (* details. *) (* *) You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA (******************************************************************************) open BaseEnv open BaseMessage open OASISTypes open OASISGettext let run cmd args extra_args = OASISExec.run ~ctxt:!BaseContext.default ~quote:false (var_expand cmd) (List.map var_expand (args @ (Array.to_list extra_args))) let hook ?(failsafe=false) cstm f e = let optional_command lst = let printer = function | Some (cmd, args) -> String.concat " " (cmd :: args) | None -> s_ "No command" in match var_choose ~name:(s_ "Pre/Post Command") ~printer lst with | Some (cmd, args) -> begin try run cmd args [||] with e when failsafe -> warning (f_ "Command '%s' fail with error: %s") (String.concat " " (cmd :: args)) (match e with | Failure msg -> msg | e -> Printexc.to_string e) end | None -> () in let res = optional_command cstm.pre_command; f e in optional_command cstm.post_command; res
null
https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/src/base/BaseCustom.ml
ocaml
**************************************************************************** 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 your option) any later version, with the OCaml static compilation exception. 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 file COPYING for more details. ****************************************************************************
OASIS : architecture for building OCaml libraries and applications Copyright ( C ) 2011 - 2016 , Copyright ( C ) 2008 - 2011 , OCamlCore SARL the Free Software Foundation ; either version 2.1 of the License , or ( at You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA open BaseEnv open BaseMessage open OASISTypes open OASISGettext let run cmd args extra_args = OASISExec.run ~ctxt:!BaseContext.default ~quote:false (var_expand cmd) (List.map var_expand (args @ (Array.to_list extra_args))) let hook ?(failsafe=false) cstm f e = let optional_command lst = let printer = function | Some (cmd, args) -> String.concat " " (cmd :: args) | None -> s_ "No command" in match var_choose ~name:(s_ "Pre/Post Command") ~printer lst with | Some (cmd, args) -> begin try run cmd args [||] with e when failsafe -> warning (f_ "Command '%s' fail with error: %s") (String.concat " " (cmd :: args)) (match e with | Failure msg -> msg | e -> Printexc.to_string e) end | None -> () in let res = optional_command cstm.pre_command; f e in optional_command cstm.post_command; res
28116853d25d11f31245aab8e3d99f175493725f65605a43ce233bb145243fc0
fortytools/holumbus
Test.hs
# OPTIONS # -- ------------------------------------------------------------ module Main where import Control.DeepSeq import qualified Data.Binary as B import Data.Char import Data.Function import Data.Function.Selector ( update, getS ) ( nub , sortBy ) import Data.Maybe import Hayoo.HackagePackage import Hayoo.Haddock import Hayoo.IndexConfig import Hayoo.IndexTypes import Hayoo.PackageArchive import Hayoo.URIConfig import Holumbus.Index.Common import Holumbus.Crawler import Holumbus.Crawler.CacheCore import Holumbus.Crawler.IndexerCore import System.FilePath import System.CPUTime import System.Console.GetOpt import System.Environment import System.Exit import System.IO import Text.XML.HXT.Core -- ------------------------------------------------------------ main :: IO () main = do ix <- loadCompactInverted "ix.bin.idx" wordsIx ix countOccIx ix return () -- ------------------------------------------------------------ loadCompactInverted :: String -> IO CompactInverted loadCompactInverted = loadIx -- ------------------------------------------------------------ loadIx :: (NFData i, HolIndex i) => FilePath -> IO i loadIx f = withCpuTime $ do msg $ "load index from binary file " ++ show f ix <- loadFromBinFile f rnf ix `seq` msg $ "loading finished" return ix -- ------------------------------------------------------------ wordsIx :: (HolIndex i) => i -> IO () wordsIx ix = withCpuTime $ do msg $ "number of words in index: " ++ show (sizeWords ix) -- msg $ "words in index:\n" ++ unwords allW where allW = [w | c <- contexts ix, (w, _) <- allWords ix c] countOccIx :: (HolIndex i) => i -> IO () countOccIx ix = withCpuTime $ do msg $ "count occurrences by looking up all words once" msg $ "index contains " ++ show wc ++ " words with " ++ show oc ++ " occurrences" where cws = [(c, w) | c <- contexts ix, (w, _) <- allWords ix c] oc = sum [ sizeOccurrences os | (c, w) <- cws, (_, os) <- lookupNoCase ix c w] wc = sizeWords ix -- ---------------------------------------- msg :: String -> IO () msg = hPutStrLn stderr -- ------------------------------------------------------------ withCpuTime :: IO a -> IO a withCpuTime p = do start <- getCPUTime res <- p end <- getCPUTime msg $ "cpu time for last action: " ++ showTime (end - start) ++ " sec." return res showTime :: Integer -> String showTime = fill ' ' 10 . addDot 3 . fill '0' 4 . show . msec where five8 = 5 * (10::Integer)^(8::Int) ten9 = 2 * five8 msec :: Integer -> Integer msec t = (t + five8) `div` ten9 addDot n = reverse . (\ (x, y) -> x ++ "." ++ y) . splitAt n . reverse fill c n s | length s < n = reverse . take n . (++ replicate n c) . reverse $ s | otherwise = s -- ---------------------------------------- -- ---------------------------------------- type Key = [Char] type Sym = Char type KeyParser = KeySet -> KeySet newtype KeySet = KS { unKS :: [(Sym, KeySet)] } deriving (Show) mapKS :: ([(Sym, KeySet)] -> [(Sym, KeySet)]) -> KeySet -> KeySet mapKS f = KS . f . unKS -- ---------------------------------------- -- | /O(max(L , R))/ Find all values where the string is a prefix of the key . prefixFindNoCaseWithKey : : Key - > PrefixTree a - > [ ( Key , a ) ] prefixFindNoCaseWithKey k = toList . cutPx ' ( similarKeys kpIgnoreCase k ) prefixFindNoCase : : Key - > PrefixTree a - > [ a ] prefixFindNoCase k = elems . cutPx ' ( similarKeys kpIgnoreCase k ) lookupNoCase : : Key - > PrefixTree a - > [ ( Key , a ) ] lookupNoCase k = toList . cutAllPx ' ( similarKeys kpIgnoreCase k ) -- ---------------------------------------- similarKeys : : - > Key - > KeySet similarKeys _ kp [ ] = val ( ) empty similarKeys kp k = foldr melt empty $ kp k where melt ( k ' , r ' ) t ' = union ' const ( siseq k ' ( similarKeys kp r ' ) ) t ' similarKeys ' : : - > Key - > [ Key ] similarKeys ' kp = keys . similarKeys kp -- | /O(max(L,R))/ Find all values where the string is a prefix of the key. prefixFindNoCaseWithKey :: Key -> PrefixTree a -> [(Key, a)] prefixFindNoCaseWithKey k = toList . cutPx' (similarKeys kpIgnoreCase k) prefixFindNoCase :: Key -> PrefixTree a -> [a] prefixFindNoCase k = elems . cutPx' (similarKeys kpIgnoreCase k) lookupNoCase :: Key -> PrefixTree a -> [(Key, a)] lookupNoCase k = toList . cutAllPx' (similarKeys kpIgnoreCase k) -- ---------------------------------------- similarKeys :: KeyParser -> Key -> KeySet similarKeys _kp [] = val () empty similarKeys kp k = foldr melt empty $ kp k where melt (k', r') t' = union' const (siseq k' (similarKeys kp r')) t' similarKeys' :: KeyParser -> Key -> [Key] similarKeys' kp = keys . similarKeys kp -} -- ---------------------------------------- -- | Identity key parser mkKeySet :: Key -> KeySet mkKeySet [] = KS [] mkKeySet (x:xs) = KS [(x, mkKeySet xs)] kpIgnoreCase0 :: KeyParser kpIgnoreCase0 = kpSym (\ x -> [toUpper x, toLower x]) kpDeep :: KeyParser -> KeyParser kpDeep kp = mapKS (map (second kp)) . kp kpSym :: (Sym -> Key) -> KeyParser kpSym f = mapKS (concat . fmap toSyms) where toSyms (x, ks) = fmap (\ c -> (c, ks)) . sort . nub . f $ x -- | Sequential combination of key parsers : : - > KeyParser - > KeyParser concatMap ( uncurry p2 ) $ kp1 k where p2 k ' r ' = fmap ( \ k '' - > ( k '' , r ' ) ) $ similarKeys ' kp2 k ' -- | Key parser for case kpIgnoreCase : : kpIgnoreCase [ ] = [ ] kpIgnoreCase ( x : xs ) = fmap ( \ c - > ( [ c ] , xs ) ) . L.nub $ [ toLower x , toUpper x ] -- | Key parser for german umlaut substituion -- TODO : extend parser for iso - latin-1 kpUmlaut : : kpUmlaut [ ] = [ ] kpUmlaut ( x : xs ) = fmap ( \ s - > ( s , xs ) ) . ( [ x ] :) . maybeToList . L.lookup x $ esc where esc = [ ( ' ' , " Ae " ) , ( ' \214 ' , " " ) , ( ' \220 ' , " Ue " ) , ( ' \228 ' , " ae " ) , ( ' \246 ' , " oe " ) , ( ' \252 ' , " ue " ) , ( ' \223 ' , " ss " ) ] -- | Sequential combination of key parsers kpSeq :: KeyParser -> KeyParser -> KeyParser kpSeq kp1 kp2 k = concatMap (uncurry p2) $ kp1 k where p2 k' r' = fmap (\ k'' -> (k'', r')) $ similarKeys' kp2 k' -- | Key parser for case insignificat keys kpIgnoreCase :: KeyParser kpIgnoreCase [] = [] kpIgnoreCase (x:xs) = fmap (\ c -> ([c], xs)) . L.nub $ [toLower x, toUpper x] -- | Key parser for german umlaut substituion -- TODO: extend parser for iso-latin-1 kpUmlaut :: KeyParser kpUmlaut [] = [] kpUmlaut (x:xs) = fmap (\ s -> (s,xs)) . ([x]:) . maybeToList . L.lookup x $ esc where esc = [ ('\196', "Ae") , ('\214', "Oe") , ('\220', "Ue") , ('\228', "ae") , ('\246', "oe") , ('\252', "ue") , ('\223', "ss") ] -} -- ---------------------------------------- -- | Set of strings implemented as lazy prefix tree . -- @type PrefixSet = PrefixTree ( ) @ is not feasable because of the strict fields in the PrefixTree definition data PrefixSet = PSempty | PSelem PrefixSet | PSnext Sym PrefixSet PrefixSet deriving ( Show ) emptyPS : : PrefixSet emptyPS = PSempty elemPS : : PrefixSet - > PrefixSet elemPS s@(PSelem _ ) = s elemPS s = PSelem s elem0PS : : PrefixSet elem0PS = elemPS emptyPS nextPS : : Sym - > PrefixSet - > PrefixSet - > PrefixSet nextPS _ PSempty n = n nextPS s c n = PSnext s c n lastPS : : Sym - > PrefixSet - > PrefixSet lastPS s c = nextPS s c emptyPS nullPS : : PrefixSet - > Bool nullPS PSempty = True nullPS _ = False singlePS : : Key - > PrefixSet singlePS = foldr ( \ c r - > lastPS c r ) elem0PS prefixPS : : Key - > PrefixSet prefixPS = foldr ( \ c r - > elemPS ( lastPS c r ) ) elem0PS unionPS : : PrefixSet - > PrefixSet - > PrefixSet unionPS PSempty ps2 = ps2 unionPS ps1 PSempty = ps1 unionPS ( PSelem ps1 ) ( PSelem ps2 ) = PSelem ( unionPS ps1 ps2 ) unionPS ( PSelem ps1 ) ps2 = PSelem ( unionPS ps1 ps2 ) unionPS ps1 ( PSelem ps2 ) = PSelem ( unionPS ps1 ps2 ) unionPS ps1@(PSnext ) ps2@(PSnext c2 s2 n2 ) | c1 < c2 = nextPS c1 s1 ( unionPS n1 ps2 ) | c1 > c2 = nextPS c2 s2 ( unionPS ps1 n2 ) | otherwise = nextPS c1 ( unionPS s1 s2 ) ( unionPS n1 n2 ) foldPS : : ( Key - > b - > b ) - > b - > ( Key - > Key ) - > PrefixSet - > b foldPS f r kf PSempty = r foldPS f r kf ( PSelem ps1 ) = let r ' = foldPS f r kf ps1 in f ( kf [ ] ) r ' foldPS f r kf ( PSnext c1 s1 n1 ) = let r ' = foldPS f r kf n1 in foldPS f r ' ( kf . ( c1 :)) s1 foldWithKeyPS : : ( Key - > b - > b ) - > b - > PrefixSet - > b foldWithKeyPS f e = foldPS f e i d elemsPS : : PrefixSet - > [ Key ] elemsPS = foldWithKeyPS ( :) [ ] fuzzyCharsPS : : ( Sym - > [ Sym ] ) - > PrefixSet - > PrefixSet fuzzyCharsPS f PSempty = PSempty fuzzyCharsPS f ( PSelem ps ) = PSelem $ fuzzyCharsPS f ps fuzzyCharsPS f ( PSnext c s n ) = unionPS ps1 ( fuzzyCharsPS f n ) where s ' = fuzzyCharsPS f s cs = sort . nub . f $ c ps1 = foldr ( \ c ' r ' - > nextPS c ' s ' r ' ) emptyPS $ cs noCasePS : : PrefixSet - > PrefixSet noCasePS = fuzzyCharsPS ( \ x - > [ toUpper x , toLower x ] ) noLowerCasePS : : PrefixSet - > PrefixSet noLowerCasePS = fuzzyCharsPS ( \ x - > [ toUpper x , x ] ) -- ------------------------------------------------------------ e1 = singlePS " abc " e2 = prefixPS " abc " e3 = foldl unionPS emptyPS . map singlePS $ [ " zeus","anna","anton","an " ] -- ------------------------------------------------------------ -- | Set of strings implemented as lazy prefix tree. -- @type PrefixSet = PrefixTree ()@ is not feasable because of the strict fields in the PrefixTree definition data PrefixSet = PSempty | PSelem PrefixSet | PSnext Sym PrefixSet PrefixSet deriving (Show) emptyPS :: PrefixSet emptyPS = PSempty elemPS :: PrefixSet -> PrefixSet elemPS s@(PSelem _) = s elemPS s = PSelem s elem0PS :: PrefixSet elem0PS = elemPS emptyPS nextPS :: Sym -> PrefixSet -> PrefixSet -> PrefixSet nextPS _ PSempty n = n nextPS s c n = PSnext s c n lastPS :: Sym -> PrefixSet -> PrefixSet lastPS s c = nextPS s c emptyPS nullPS :: PrefixSet -> Bool nullPS PSempty = True nullPS _ = False singlePS :: Key -> PrefixSet singlePS = foldr (\ c r -> lastPS c r) elem0PS prefixPS :: Key -> PrefixSet prefixPS = foldr (\ c r -> elemPS (lastPS c r)) elem0PS unionPS :: PrefixSet -> PrefixSet -> PrefixSet unionPS PSempty ps2 = ps2 unionPS ps1 PSempty = ps1 unionPS (PSelem ps1) (PSelem ps2) = PSelem (unionPS ps1 ps2) unionPS (PSelem ps1) ps2 = PSelem (unionPS ps1 ps2) unionPS ps1 (PSelem ps2) = PSelem (unionPS ps1 ps2) unionPS ps1@(PSnext c1 s1 n1) ps2@(PSnext c2 s2 n2) | c1 < c2 = nextPS c1 s1 (unionPS n1 ps2) | c1 > c2 = nextPS c2 s2 (unionPS ps1 n2) | otherwise = nextPS c1 (unionPS s1 s2) (unionPS n1 n2) foldPS :: (Key -> b -> b) -> b -> (Key -> Key) -> PrefixSet -> b foldPS f r kf PSempty = r foldPS f r kf (PSelem ps1) = let r' = foldPS f r kf ps1 in f (kf []) r' foldPS f r kf (PSnext c1 s1 n1) = let r' = foldPS f r kf n1 in foldPS f r' (kf . (c1:)) s1 foldWithKeyPS :: (Key -> b -> b) -> b -> PrefixSet -> b foldWithKeyPS f e = foldPS f e id elemsPS :: PrefixSet -> [Key] elemsPS = foldWithKeyPS (:) [] fuzzyCharsPS :: (Sym -> [Sym]) -> PrefixSet -> PrefixSet fuzzyCharsPS f PSempty = PSempty fuzzyCharsPS f (PSelem ps) = PSelem $ fuzzyCharsPS f ps fuzzyCharsPS f (PSnext c s n) = unionPS ps1 (fuzzyCharsPS f n) where s' = fuzzyCharsPS f s cs = sort . nub . f $ c ps1 = foldr (\ c' r' -> nextPS c' s' r') emptyPS $ cs noCasePS :: PrefixSet -> PrefixSet noCasePS = fuzzyCharsPS (\ x -> [toUpper x, toLower x]) noLowerCasePS :: PrefixSet -> PrefixSet noLowerCasePS = fuzzyCharsPS (\ x -> [toUpper x, x]) -- ------------------------------------------------------------ e1 = singlePS "abc" e2 = prefixPS "abc" e3 = foldl unionPS emptyPS . map singlePS $ ["zeus","anna","anton","an"] -- ------------------------------------------------------------ -}
null
https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/crawl2/examples/hayoo/Test.hs
haskell
------------------------------------------------------------ ------------------------------------------------------------ ------------------------------------------------------------ ------------------------------------------------------------ ------------------------------------------------------------ msg $ "words in index:\n" ++ unwords allW ---------------------------------------- ------------------------------------------------------------ ---------------------------------------- ---------------------------------------- ---------------------------------------- | /O(max(L , R))/ Find all values where the string is a prefix of the key . ---------------------------------------- | /O(max(L,R))/ Find all values where the string is a prefix of the key. ---------------------------------------- ---------------------------------------- | Identity key parser | Sequential combination of key parsers | Key parser for case | Key parser for german umlaut substituion TODO : extend parser for iso - latin-1 | Sequential combination of key parsers | Key parser for case insignificat keys | Key parser for german umlaut substituion TODO: extend parser for iso-latin-1 ---------------------------------------- | Set of strings implemented as lazy prefix tree . @type PrefixSet = PrefixTree ( ) @ is not feasable because of the strict fields in the PrefixTree definition ------------------------------------------------------------ ------------------------------------------------------------ | Set of strings implemented as lazy prefix tree. @type PrefixSet = PrefixTree ()@ is not feasable because of the strict fields in the PrefixTree definition ------------------------------------------------------------ ------------------------------------------------------------
# OPTIONS # module Main where import Control.DeepSeq import qualified Data.Binary as B import Data.Char import Data.Function import Data.Function.Selector ( update, getS ) ( nub , sortBy ) import Data.Maybe import Hayoo.HackagePackage import Hayoo.Haddock import Hayoo.IndexConfig import Hayoo.IndexTypes import Hayoo.PackageArchive import Hayoo.URIConfig import Holumbus.Index.Common import Holumbus.Crawler import Holumbus.Crawler.CacheCore import Holumbus.Crawler.IndexerCore import System.FilePath import System.CPUTime import System.Console.GetOpt import System.Environment import System.Exit import System.IO import Text.XML.HXT.Core main :: IO () main = do ix <- loadCompactInverted "ix.bin.idx" wordsIx ix countOccIx ix return () loadCompactInverted :: String -> IO CompactInverted loadCompactInverted = loadIx loadIx :: (NFData i, HolIndex i) => FilePath -> IO i loadIx f = withCpuTime $ do msg $ "load index from binary file " ++ show f ix <- loadFromBinFile f rnf ix `seq` msg $ "loading finished" return ix wordsIx :: (HolIndex i) => i -> IO () wordsIx ix = withCpuTime $ do msg $ "number of words in index: " ++ show (sizeWords ix) where allW = [w | c <- contexts ix, (w, _) <- allWords ix c] countOccIx :: (HolIndex i) => i -> IO () countOccIx ix = withCpuTime $ do msg $ "count occurrences by looking up all words once" msg $ "index contains " ++ show wc ++ " words with " ++ show oc ++ " occurrences" where cws = [(c, w) | c <- contexts ix, (w, _) <- allWords ix c] oc = sum [ sizeOccurrences os | (c, w) <- cws, (_, os) <- lookupNoCase ix c w] wc = sizeWords ix msg :: String -> IO () msg = hPutStrLn stderr withCpuTime :: IO a -> IO a withCpuTime p = do start <- getCPUTime res <- p end <- getCPUTime msg $ "cpu time for last action: " ++ showTime (end - start) ++ " sec." return res showTime :: Integer -> String showTime = fill ' ' 10 . addDot 3 . fill '0' 4 . show . msec where five8 = 5 * (10::Integer)^(8::Int) ten9 = 2 * five8 msec :: Integer -> Integer msec t = (t + five8) `div` ten9 addDot n = reverse . (\ (x, y) -> x ++ "." ++ y) . splitAt n . reverse fill c n s | length s < n = reverse . take n . (++ replicate n c) . reverse $ s | otherwise = s type Key = [Char] type Sym = Char type KeyParser = KeySet -> KeySet newtype KeySet = KS { unKS :: [(Sym, KeySet)] } deriving (Show) mapKS :: ([(Sym, KeySet)] -> [(Sym, KeySet)]) -> KeySet -> KeySet mapKS f = KS . f . unKS prefixFindNoCaseWithKey : : Key - > PrefixTree a - > [ ( Key , a ) ] prefixFindNoCaseWithKey k = toList . cutPx ' ( similarKeys kpIgnoreCase k ) prefixFindNoCase : : Key - > PrefixTree a - > [ a ] prefixFindNoCase k = elems . cutPx ' ( similarKeys kpIgnoreCase k ) lookupNoCase : : Key - > PrefixTree a - > [ ( Key , a ) ] lookupNoCase k = toList . cutAllPx ' ( similarKeys kpIgnoreCase k ) similarKeys : : - > Key - > KeySet similarKeys _ kp [ ] = val ( ) empty similarKeys kp k = foldr melt empty $ kp k where melt ( k ' , r ' ) t ' = union ' const ( siseq k ' ( similarKeys kp r ' ) ) t ' similarKeys ' : : - > Key - > [ Key ] similarKeys ' kp = keys . similarKeys kp prefixFindNoCaseWithKey :: Key -> PrefixTree a -> [(Key, a)] prefixFindNoCaseWithKey k = toList . cutPx' (similarKeys kpIgnoreCase k) prefixFindNoCase :: Key -> PrefixTree a -> [a] prefixFindNoCase k = elems . cutPx' (similarKeys kpIgnoreCase k) lookupNoCase :: Key -> PrefixTree a -> [(Key, a)] lookupNoCase k = toList . cutAllPx' (similarKeys kpIgnoreCase k) similarKeys :: KeyParser -> Key -> KeySet similarKeys _kp [] = val () empty similarKeys kp k = foldr melt empty $ kp k where melt (k', r') t' = union' const (siseq k' (similarKeys kp r')) t' similarKeys' :: KeyParser -> Key -> [Key] similarKeys' kp = keys . similarKeys kp -} mkKeySet :: Key -> KeySet mkKeySet [] = KS [] mkKeySet (x:xs) = KS [(x, mkKeySet xs)] kpIgnoreCase0 :: KeyParser kpIgnoreCase0 = kpSym (\ x -> [toUpper x, toLower x]) kpDeep :: KeyParser -> KeyParser kpDeep kp = mapKS (map (second kp)) . kp kpSym :: (Sym -> Key) -> KeyParser kpSym f = mapKS (concat . fmap toSyms) where toSyms (x, ks) = fmap (\ c -> (c, ks)) . sort . nub . f $ x : : - > KeyParser - > KeyParser concatMap ( uncurry p2 ) $ kp1 k where p2 k ' r ' = fmap ( \ k '' - > ( k '' , r ' ) ) $ similarKeys ' kp2 k ' kpIgnoreCase : : kpIgnoreCase [ ] = [ ] kpIgnoreCase ( x : xs ) = fmap ( \ c - > ( [ c ] , xs ) ) . L.nub $ [ toLower x , toUpper x ] kpUmlaut : : kpUmlaut [ ] = [ ] kpUmlaut ( x : xs ) = fmap ( \ s - > ( s , xs ) ) . ( [ x ] :) . maybeToList . L.lookup x $ esc where esc = [ ( ' ' , " Ae " ) , ( ' \214 ' , " " ) , ( ' \220 ' , " Ue " ) , ( ' \228 ' , " ae " ) , ( ' \246 ' , " oe " ) , ( ' \252 ' , " ue " ) , ( ' \223 ' , " ss " ) ] kpSeq :: KeyParser -> KeyParser -> KeyParser kpSeq kp1 kp2 k = concatMap (uncurry p2) $ kp1 k where p2 k' r' = fmap (\ k'' -> (k'', r')) $ similarKeys' kp2 k' kpIgnoreCase :: KeyParser kpIgnoreCase [] = [] kpIgnoreCase (x:xs) = fmap (\ c -> ([c], xs)) . L.nub $ [toLower x, toUpper x] kpUmlaut :: KeyParser kpUmlaut [] = [] kpUmlaut (x:xs) = fmap (\ s -> (s,xs)) . ([x]:) . maybeToList . L.lookup x $ esc where esc = [ ('\196', "Ae") , ('\214', "Oe") , ('\220', "Ue") , ('\228', "ae") , ('\246', "oe") , ('\252', "ue") , ('\223', "ss") ] -} data PrefixSet = PSempty | PSelem PrefixSet | PSnext Sym PrefixSet PrefixSet deriving ( Show ) emptyPS : : PrefixSet emptyPS = PSempty elemPS : : PrefixSet - > PrefixSet elemPS s@(PSelem _ ) = s elemPS s = PSelem s elem0PS : : PrefixSet elem0PS = elemPS emptyPS nextPS : : Sym - > PrefixSet - > PrefixSet - > PrefixSet nextPS _ PSempty n = n nextPS s c n = PSnext s c n lastPS : : Sym - > PrefixSet - > PrefixSet lastPS s c = nextPS s c emptyPS nullPS : : PrefixSet - > Bool nullPS PSempty = True nullPS _ = False singlePS : : Key - > PrefixSet singlePS = foldr ( \ c r - > lastPS c r ) elem0PS prefixPS : : Key - > PrefixSet prefixPS = foldr ( \ c r - > elemPS ( lastPS c r ) ) elem0PS unionPS : : PrefixSet - > PrefixSet - > PrefixSet unionPS PSempty ps2 = ps2 unionPS ps1 PSempty = ps1 unionPS ( PSelem ps1 ) ( PSelem ps2 ) = PSelem ( unionPS ps1 ps2 ) unionPS ( PSelem ps1 ) ps2 = PSelem ( unionPS ps1 ps2 ) unionPS ps1 ( PSelem ps2 ) = PSelem ( unionPS ps1 ps2 ) unionPS ps1@(PSnext ) ps2@(PSnext c2 s2 n2 ) | c1 < c2 = nextPS c1 s1 ( unionPS n1 ps2 ) | c1 > c2 = nextPS c2 s2 ( unionPS ps1 n2 ) | otherwise = nextPS c1 ( unionPS s1 s2 ) ( unionPS n1 n2 ) foldPS : : ( Key - > b - > b ) - > b - > ( Key - > Key ) - > PrefixSet - > b foldPS f r kf PSempty = r foldPS f r kf ( PSelem ps1 ) = let r ' = foldPS f r kf ps1 in f ( kf [ ] ) r ' foldPS f r kf ( PSnext c1 s1 n1 ) = let r ' = foldPS f r kf n1 in foldPS f r ' ( kf . ( c1 :)) s1 foldWithKeyPS : : ( Key - > b - > b ) - > b - > PrefixSet - > b foldWithKeyPS f e = foldPS f e i d elemsPS : : PrefixSet - > [ Key ] elemsPS = foldWithKeyPS ( :) [ ] fuzzyCharsPS : : ( Sym - > [ Sym ] ) - > PrefixSet - > PrefixSet fuzzyCharsPS f PSempty = PSempty fuzzyCharsPS f ( PSelem ps ) = PSelem $ fuzzyCharsPS f ps fuzzyCharsPS f ( PSnext c s n ) = unionPS ps1 ( fuzzyCharsPS f n ) where s ' = fuzzyCharsPS f s cs = sort . nub . f $ c ps1 = foldr ( \ c ' r ' - > nextPS c ' s ' r ' ) emptyPS $ cs noCasePS : : PrefixSet - > PrefixSet noCasePS = fuzzyCharsPS ( \ x - > [ toUpper x , toLower x ] ) noLowerCasePS : : PrefixSet - > PrefixSet noLowerCasePS = fuzzyCharsPS ( \ x - > [ toUpper x , x ] ) e1 = singlePS " abc " e2 = prefixPS " abc " e3 = foldl unionPS emptyPS . map singlePS $ [ " zeus","anna","anton","an " ] data PrefixSet = PSempty | PSelem PrefixSet | PSnext Sym PrefixSet PrefixSet deriving (Show) emptyPS :: PrefixSet emptyPS = PSempty elemPS :: PrefixSet -> PrefixSet elemPS s@(PSelem _) = s elemPS s = PSelem s elem0PS :: PrefixSet elem0PS = elemPS emptyPS nextPS :: Sym -> PrefixSet -> PrefixSet -> PrefixSet nextPS _ PSempty n = n nextPS s c n = PSnext s c n lastPS :: Sym -> PrefixSet -> PrefixSet lastPS s c = nextPS s c emptyPS nullPS :: PrefixSet -> Bool nullPS PSempty = True nullPS _ = False singlePS :: Key -> PrefixSet singlePS = foldr (\ c r -> lastPS c r) elem0PS prefixPS :: Key -> PrefixSet prefixPS = foldr (\ c r -> elemPS (lastPS c r)) elem0PS unionPS :: PrefixSet -> PrefixSet -> PrefixSet unionPS PSempty ps2 = ps2 unionPS ps1 PSempty = ps1 unionPS (PSelem ps1) (PSelem ps2) = PSelem (unionPS ps1 ps2) unionPS (PSelem ps1) ps2 = PSelem (unionPS ps1 ps2) unionPS ps1 (PSelem ps2) = PSelem (unionPS ps1 ps2) unionPS ps1@(PSnext c1 s1 n1) ps2@(PSnext c2 s2 n2) | c1 < c2 = nextPS c1 s1 (unionPS n1 ps2) | c1 > c2 = nextPS c2 s2 (unionPS ps1 n2) | otherwise = nextPS c1 (unionPS s1 s2) (unionPS n1 n2) foldPS :: (Key -> b -> b) -> b -> (Key -> Key) -> PrefixSet -> b foldPS f r kf PSempty = r foldPS f r kf (PSelem ps1) = let r' = foldPS f r kf ps1 in f (kf []) r' foldPS f r kf (PSnext c1 s1 n1) = let r' = foldPS f r kf n1 in foldPS f r' (kf . (c1:)) s1 foldWithKeyPS :: (Key -> b -> b) -> b -> PrefixSet -> b foldWithKeyPS f e = foldPS f e id elemsPS :: PrefixSet -> [Key] elemsPS = foldWithKeyPS (:) [] fuzzyCharsPS :: (Sym -> [Sym]) -> PrefixSet -> PrefixSet fuzzyCharsPS f PSempty = PSempty fuzzyCharsPS f (PSelem ps) = PSelem $ fuzzyCharsPS f ps fuzzyCharsPS f (PSnext c s n) = unionPS ps1 (fuzzyCharsPS f n) where s' = fuzzyCharsPS f s cs = sort . nub . f $ c ps1 = foldr (\ c' r' -> nextPS c' s' r') emptyPS $ cs noCasePS :: PrefixSet -> PrefixSet noCasePS = fuzzyCharsPS (\ x -> [toUpper x, toLower x]) noLowerCasePS :: PrefixSet -> PrefixSet noLowerCasePS = fuzzyCharsPS (\ x -> [toUpper x, x]) e1 = singlePS "abc" e2 = prefixPS "abc" e3 = foldl unionPS emptyPS . map singlePS $ ["zeus","anna","anton","an"] -}
7e2f008887315142ea3fbd56aefc44f1d1cfef126360983c71296f4af60e9434
mirage/bloomf
bloomf.ml
type priv = { m : int; k : int; p_len : (int * int) list; b : Bitv.t } type 'a t = priv let copy t = { m = t.m; k = t.k; p_len = t.p_len; b = Bitv.copy t.b } let rec gcd a b = if b = 0 then a else gcd b (a mod b) let partition_lengths m k = let rec aux sum acc i = if List.length acc = k then (sum, acc) else let rec loop step = let k = i + step in let gcd_k = gcd k in if List.for_all (fun p -> gcd_k p = 1) acc then aux (sum + k) (k :: acc) (k + 1) else loop (step + 1) in loop 1 in aux 0 [] (m / k) let v m k = let m, lengths = partition_lengths m k in let p_len = let rec aux acc off = function | [] -> acc | h :: t -> aux ((off, h) :: acc) (off + h) t in aux [] 0 lengths in try let b = Bitv.create m false in { m; k; p_len; b } with Invalid_argument _ -> invalid_arg "Bloomf.create" let estimate_parameters n p = let log2 = log 2. in let nf = float_of_int n in let m = ceil (-.nf *. log p /. log (2. ** log2)) in let k = ceil (log2 *. m /. nf) in (m, k) let create ?(error_rate = 0.01) n_items = let m, k = estimate_parameters n_items error_rate in if error_rate <= 0. || error_rate >= 1. then invalid_arg "Bloomf.create"; v (int_of_float m) (int_of_float k) let add_priv t hashed_data = let rec loop = function | [] -> () | (off, len) :: tl -> let loc = off + (hashed_data mod len) in let () = Bitv.unsafe_set t.b loc true in loop tl in loop t.p_len let add bf data = add_priv bf (Hashtbl.hash data) let op f bf1 bf2 = if bf1.k <> bf2.k || bf1.m <> bf2.m then invalid_arg "incompatible bloom filters"; { m = bf1.m; k = bf2.k; p_len = bf1.p_len; b = f bf1.b bf2.b } let union bf1 bf2 = op Bitv.bw_or bf1 bf2 let inter bf1 bf2 = op Bitv.bw_and bf1 bf2 let mem_priv t hashed_data = let rec loop = function | [] -> true | (off, len) :: tl -> let loc = off + (hashed_data mod len) in let res = Bitv.unsafe_get t.b loc in if res then loop tl else false in loop t.p_len let mem bf data = mem_priv bf (Hashtbl.hash data) let clear t = Bitv.fill t.b 0 t.m false Bitv.pop is really slow let size_estimate t = let mf = float_of_int t.m in let kf = float_of_int t.k in let xf = float_of_int (Bitv.pop t.b) in int_of_float (-.mf /. kf *. log (1. -. (xf /. mf))) Serialisers external set_64 : bytes -> int -> int64 -> unit = "%caml_string_set64u" external swap64 : int64 -> int64 = "%bswap_int64" let set_uint64 buf off v = if not Sys.big_endian then set_64 buf off (swap64 v) else set_64 buf off v type priv = { m : int ; k : int ; p_len : ( int * int ) list ; b : Bitv.t } let to_bytes t = let enc_b = Bitv.to_bytes t.b in let enc_b_len = Bytes.length enc_b in let enc_p_len_len = 16 * List.length t.p_len in let len = 8 + 8 + 8 + enc_p_len_len + enc_b_len in let buf = Bytes.create len in set_uint64 buf 0 (Int64.of_int t.m); set_uint64 buf 8 (Int64.of_int t.k); set_uint64 buf 16 (Int64.of_int (List.length t.p_len)); List.iteri (fun i (i1, i2) -> set_uint64 buf (24 + (8 * (2 * i))) (Int64.of_int i1); set_uint64 buf (24 + (8 * ((2 * i) + 1))) (Int64.of_int i2)) t.p_len; Bytes.blit enc_b 0 buf (24 + enc_p_len_len) enc_b_len; buf external get_64 : bytes -> int -> int64 = "%caml_string_get64" let get_uint64 buf off = if not Sys.big_endian then swap64 (get_64 buf off) else get_64 buf off let of_bytes buf = try let m = get_uint64 buf 0 |> Int64.to_int in let k = get_uint64 buf 8 |> Int64.to_int in let p_len_len = get_uint64 buf 16 |> Int64.to_int in let p_len = List.init p_len_len (fun i -> let i1 = get_uint64 buf (24 + (8 * (2 * i))) |> Int64.to_int in let i2 = get_uint64 buf (24 + (8 * ((2 * i) + 1))) |> Int64.to_int in (i1, i2)) in let read = 24 + (16 * p_len_len) in let b = Bytes.sub buf read (Bytes.length buf - read) |> Bitv.of_bytes in Ok { m; k; p_len; b } with _ -> Error (`Msg "invalid serialisation format") module type Hashable = sig type t val hash : t -> int end module Make (H : Hashable) = struct type t = priv let create = create let copy = copy let add bf data = add_priv bf (H.hash data) let mem bf data = mem_priv bf (H.hash data) let clear = clear let size_estimate = size_estimate let to_bytes = to_bytes let of_bytes = of_bytes end
null
https://raw.githubusercontent.com/mirage/bloomf/084961d207cec4c3b041baa8a62bce12a3290a55/src/bloomf.ml
ocaml
type priv = { m : int; k : int; p_len : (int * int) list; b : Bitv.t } type 'a t = priv let copy t = { m = t.m; k = t.k; p_len = t.p_len; b = Bitv.copy t.b } let rec gcd a b = if b = 0 then a else gcd b (a mod b) let partition_lengths m k = let rec aux sum acc i = if List.length acc = k then (sum, acc) else let rec loop step = let k = i + step in let gcd_k = gcd k in if List.for_all (fun p -> gcd_k p = 1) acc then aux (sum + k) (k :: acc) (k + 1) else loop (step + 1) in loop 1 in aux 0 [] (m / k) let v m k = let m, lengths = partition_lengths m k in let p_len = let rec aux acc off = function | [] -> acc | h :: t -> aux ((off, h) :: acc) (off + h) t in aux [] 0 lengths in try let b = Bitv.create m false in { m; k; p_len; b } with Invalid_argument _ -> invalid_arg "Bloomf.create" let estimate_parameters n p = let log2 = log 2. in let nf = float_of_int n in let m = ceil (-.nf *. log p /. log (2. ** log2)) in let k = ceil (log2 *. m /. nf) in (m, k) let create ?(error_rate = 0.01) n_items = let m, k = estimate_parameters n_items error_rate in if error_rate <= 0. || error_rate >= 1. then invalid_arg "Bloomf.create"; v (int_of_float m) (int_of_float k) let add_priv t hashed_data = let rec loop = function | [] -> () | (off, len) :: tl -> let loc = off + (hashed_data mod len) in let () = Bitv.unsafe_set t.b loc true in loop tl in loop t.p_len let add bf data = add_priv bf (Hashtbl.hash data) let op f bf1 bf2 = if bf1.k <> bf2.k || bf1.m <> bf2.m then invalid_arg "incompatible bloom filters"; { m = bf1.m; k = bf2.k; p_len = bf1.p_len; b = f bf1.b bf2.b } let union bf1 bf2 = op Bitv.bw_or bf1 bf2 let inter bf1 bf2 = op Bitv.bw_and bf1 bf2 let mem_priv t hashed_data = let rec loop = function | [] -> true | (off, len) :: tl -> let loc = off + (hashed_data mod len) in let res = Bitv.unsafe_get t.b loc in if res then loop tl else false in loop t.p_len let mem bf data = mem_priv bf (Hashtbl.hash data) let clear t = Bitv.fill t.b 0 t.m false Bitv.pop is really slow let size_estimate t = let mf = float_of_int t.m in let kf = float_of_int t.k in let xf = float_of_int (Bitv.pop t.b) in int_of_float (-.mf /. kf *. log (1. -. (xf /. mf))) Serialisers external set_64 : bytes -> int -> int64 -> unit = "%caml_string_set64u" external swap64 : int64 -> int64 = "%bswap_int64" let set_uint64 buf off v = if not Sys.big_endian then set_64 buf off (swap64 v) else set_64 buf off v type priv = { m : int ; k : int ; p_len : ( int * int ) list ; b : Bitv.t } let to_bytes t = let enc_b = Bitv.to_bytes t.b in let enc_b_len = Bytes.length enc_b in let enc_p_len_len = 16 * List.length t.p_len in let len = 8 + 8 + 8 + enc_p_len_len + enc_b_len in let buf = Bytes.create len in set_uint64 buf 0 (Int64.of_int t.m); set_uint64 buf 8 (Int64.of_int t.k); set_uint64 buf 16 (Int64.of_int (List.length t.p_len)); List.iteri (fun i (i1, i2) -> set_uint64 buf (24 + (8 * (2 * i))) (Int64.of_int i1); set_uint64 buf (24 + (8 * ((2 * i) + 1))) (Int64.of_int i2)) t.p_len; Bytes.blit enc_b 0 buf (24 + enc_p_len_len) enc_b_len; buf external get_64 : bytes -> int -> int64 = "%caml_string_get64" let get_uint64 buf off = if not Sys.big_endian then swap64 (get_64 buf off) else get_64 buf off let of_bytes buf = try let m = get_uint64 buf 0 |> Int64.to_int in let k = get_uint64 buf 8 |> Int64.to_int in let p_len_len = get_uint64 buf 16 |> Int64.to_int in let p_len = List.init p_len_len (fun i -> let i1 = get_uint64 buf (24 + (8 * (2 * i))) |> Int64.to_int in let i2 = get_uint64 buf (24 + (8 * ((2 * i) + 1))) |> Int64.to_int in (i1, i2)) in let read = 24 + (16 * p_len_len) in let b = Bytes.sub buf read (Bytes.length buf - read) |> Bitv.of_bytes in Ok { m; k; p_len; b } with _ -> Error (`Msg "invalid serialisation format") module type Hashable = sig type t val hash : t -> int end module Make (H : Hashable) = struct type t = priv let create = create let copy = copy let add bf data = add_priv bf (H.hash data) let mem bf data = mem_priv bf (H.hash data) let clear = clear let size_estimate = size_estimate let to_bytes = to_bytes let of_bytes = of_bytes end
70c8c44e21038ba43b19bf789b8b99d81722ac38efaa0a22306cac65174d45e3
TrustInSoft/tis-kernel
logic_env.mli
(**************************************************************************) (* *) 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 Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) ( Institut National de Recherche en Informatique et en (* Automatique) *) (* *) (* 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 ) . (* *) (**************************************************************************) (** {1 Global Logic Environment} *) open Cil_types * { 2 Global Tables } module Logic_info: State_builder.Hashtbl with type key = string and type data = Cil_types.logic_info module Logic_type_info: State_builder.Hashtbl with type key = string and type data = Cil_types.logic_type_info module Logic_ctor_info: State_builder.Hashtbl with type key = string and type data = Cil_types.logic_ctor_info (** @since Oxygen-20120901 *) module Model_info: State_builder.Hashtbl with type key = string and type data = Cil_types.model_info (** @since Oxygen-20120901 *) module Lemmas: State_builder.Hashtbl with type key = string and type data = Cil_types.global_annotation val builtin_states: State.t list (** {2 Shortcuts to the functions of the modules above} *) (** Prepare all internal tables before their uses: clear all tables except builtins. *) val prepare_tables : unit -> unit * { 3 Add an user - defined object } * add_logic_function_gen takes as argument a function eq_logic_info which decides whether two logic_info are identical . It is intended to be Logic_utils.is_same_logic_profile , but this one can not be called from here since it will cause a circular dependency Logic_env < - Logic_utils < - Cil < - Logic_env . { b Do not use this function directly } unless you 're really sure about what you 're doing . Use { ! Logic_utils.add_logic_function } instead . which decides whether two logic_info are identical. It is intended to be Logic_utils.is_same_logic_profile, but this one can not be called from here since it will cause a circular dependency Logic_env <- Logic_utils <- Cil <- Logic_env. {b Do not use this function directly} unless you're really sure about what you're doing. Use {!Logic_utils.add_logic_function} instead. *) val add_logic_function_gen: (logic_info -> logic_info -> bool) -> logic_info -> unit val add_logic_type: string -> logic_type_info -> unit val add_logic_ctor: string -> logic_ctor_info -> unit (** @since Oxygen-20120901 *) val add_model_field: model_info -> unit * { 3 Add a builtin object } module Builtins: sig val apply: unit -> unit (** adds all requested objects in the environment. *) val extend: (unit -> unit) -> unit * request an addition in the environment . Use one of the functions below in the body of the argument . in the body of the argument. *) end (** logic function/predicates that are effectively used in current project. *) module Logic_builtin_used: sig val add: logic_info -> unit val mem: logic_info -> bool val iter: (logic_info -> unit) -> unit val self: State.t end * see add_logic_function_gen above val add_builtin_logic_function_gen: (builtin_logic_info -> builtin_logic_info -> bool) -> builtin_logic_info -> unit val add_builtin_logic_type: string -> logic_type_info -> unit val add_builtin_logic_ctor: string -> logic_ctor_info -> unit val is_builtin_logic_function: string -> bool val is_builtin_logic_type: string -> bool val is_builtin_logic_ctor: string -> bool val iter_builtin_logic_function: (builtin_logic_info -> unit) -> unit val iter_builtin_logic_type: (logic_type_info -> unit) -> unit val iter_builtin_logic_ctor: (logic_ctor_info -> unit) -> unit * { 3 searching the environment } val find_all_logic_functions : string -> logic_info list (** returns all model fields of the same name. @since Oxygen-20120901 *) val find_all_model_fields: string -> model_info list (** [find_model_info field typ] returns the model field associated to [field] in type [typ]. @raise Not_found if no such type exists. @since Oxygen-20120901 *) val find_model_field: string -> typ -> model_info (** cons is a logic function with no argument. It is used as a variable, but may occasionally need to find associated logic_info. @raise Not_found if the given varinfo is not associated to a global logic constant. *) val find_logic_cons: logic_var -> logic_info val find_logic_type: string -> logic_type_info val find_logic_ctor: string -> logic_ctor_info * { 3 tests of existence } val is_logic_function: string -> bool val is_logic_type: string -> bool val is_logic_ctor: string -> bool (** @since Oxygen-20120901 *) val is_model_field: string -> bool * { 3 removing } val remove_logic_function: string -> unit val remove_logic_type: string -> unit val remove_logic_ctor: string -> unit (** @since Oxygen-20120901 *) val remove_model_field: string -> unit * { 2 Typename table } (** marks an identifier as being a typename in the logic *) val add_typename: string -> unit (** marks temporarily a typename as being a normal identifier in the logic *) val hide_typename: string -> unit (** removes latest typename status associated to a given identifier *) val remove_typename: string -> unit (** erases all the typename status *) val reset_typenames: unit -> unit (** returns the typename status of the given identifier. *) val typename_status: string -> bool (** marks builtin logical types as logical typenames for the logic lexer. *) val builtin_types_as_typenames: unit -> unit * { 2 Internal use } val init_dependencies: State.t -> unit * Used to postpone dependency of Lenv global tables wrt Cil_state , which is initialized afterwards . is initialized afterwards. *) (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/kernel_services/ast_queries/logic_env.mli
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) Automatique) 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. ************************************************************************ * {1 Global Logic Environment} * @since Oxygen-20120901 * @since Oxygen-20120901 * {2 Shortcuts to the functions of the modules above} * Prepare all internal tables before their uses: clear all tables except builtins. * @since Oxygen-20120901 * adds all requested objects in the environment. * logic function/predicates that are effectively used in current project. * returns all model fields of the same name. @since Oxygen-20120901 * [find_model_info field typ] returns the model field associated to [field] in type [typ]. @raise Not_found if no such type exists. @since Oxygen-20120901 * cons is a logic function with no argument. It is used as a variable, but may occasionally need to find associated logic_info. @raise Not_found if the given varinfo is not associated to a global logic constant. * @since Oxygen-20120901 * @since Oxygen-20120901 * marks an identifier as being a typename in the logic * marks temporarily a typename as being a normal identifier in the logic * removes latest typename status associated to a given identifier * erases all the typename status * returns the typename status of the given identifier. * marks builtin logical types as logical typenames for the logic lexer. Local Variables: compile-command: "make -C ../../.." End:
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 Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies ( Institut National de Recherche en Informatique et en 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 * { 2 Global Tables } module Logic_info: State_builder.Hashtbl with type key = string and type data = Cil_types.logic_info module Logic_type_info: State_builder.Hashtbl with type key = string and type data = Cil_types.logic_type_info module Logic_ctor_info: State_builder.Hashtbl with type key = string and type data = Cil_types.logic_ctor_info module Model_info: State_builder.Hashtbl with type key = string and type data = Cil_types.model_info module Lemmas: State_builder.Hashtbl with type key = string and type data = Cil_types.global_annotation val builtin_states: State.t list val prepare_tables : unit -> unit * { 3 Add an user - defined object } * add_logic_function_gen takes as argument a function eq_logic_info which decides whether two logic_info are identical . It is intended to be Logic_utils.is_same_logic_profile , but this one can not be called from here since it will cause a circular dependency Logic_env < - Logic_utils < - Cil < - Logic_env . { b Do not use this function directly } unless you 're really sure about what you 're doing . Use { ! Logic_utils.add_logic_function } instead . which decides whether two logic_info are identical. It is intended to be Logic_utils.is_same_logic_profile, but this one can not be called from here since it will cause a circular dependency Logic_env <- Logic_utils <- Cil <- Logic_env. {b Do not use this function directly} unless you're really sure about what you're doing. Use {!Logic_utils.add_logic_function} instead. *) val add_logic_function_gen: (logic_info -> logic_info -> bool) -> logic_info -> unit val add_logic_type: string -> logic_type_info -> unit val add_logic_ctor: string -> logic_ctor_info -> unit val add_model_field: model_info -> unit * { 3 Add a builtin object } module Builtins: sig val apply: unit -> unit val extend: (unit -> unit) -> unit * request an addition in the environment . Use one of the functions below in the body of the argument . in the body of the argument. *) end module Logic_builtin_used: sig val add: logic_info -> unit val mem: logic_info -> bool val iter: (logic_info -> unit) -> unit val self: State.t end * see add_logic_function_gen above val add_builtin_logic_function_gen: (builtin_logic_info -> builtin_logic_info -> bool) -> builtin_logic_info -> unit val add_builtin_logic_type: string -> logic_type_info -> unit val add_builtin_logic_ctor: string -> logic_ctor_info -> unit val is_builtin_logic_function: string -> bool val is_builtin_logic_type: string -> bool val is_builtin_logic_ctor: string -> bool val iter_builtin_logic_function: (builtin_logic_info -> unit) -> unit val iter_builtin_logic_type: (logic_type_info -> unit) -> unit val iter_builtin_logic_ctor: (logic_ctor_info -> unit) -> unit * { 3 searching the environment } val find_all_logic_functions : string -> logic_info list val find_all_model_fields: string -> model_info list val find_model_field: string -> typ -> model_info val find_logic_cons: logic_var -> logic_info val find_logic_type: string -> logic_type_info val find_logic_ctor: string -> logic_ctor_info * { 3 tests of existence } val is_logic_function: string -> bool val is_logic_type: string -> bool val is_logic_ctor: string -> bool val is_model_field: string -> bool * { 3 removing } val remove_logic_function: string -> unit val remove_logic_type: string -> unit val remove_logic_ctor: string -> unit val remove_model_field: string -> unit * { 2 Typename table } val add_typename: string -> unit val hide_typename: string -> unit val remove_typename: string -> unit val reset_typenames: unit -> unit val typename_status: string -> bool val builtin_types_as_typenames: unit -> unit * { 2 Internal use } val init_dependencies: State.t -> unit * Used to postpone dependency of Lenv global tables wrt Cil_state , which is initialized afterwards . is initialized afterwards. *)
902b24317165f32411f80128c5391998b4ae7a639c5be8a0476fbaeeb2814674
mzp/coq-for-ipad
gluMat.mli
$ I d : gluMat.mli , v 1.1 1998/01/29 11:46:06 garrigue Exp $ open Gl val look_at : eye:point3 -> center:point3 -> up:vect3 -> unit val ortho2d : x:float * float -> y:float * float -> unit val perspective : fovy:float -> aspect:float -> z:float * float -> unit val pick_matrix : x:float -> y:float -> width:float -> height:float -> unit val project : point3 -> point3 val unproject : point3 -> point3
null
https://raw.githubusercontent.com/mzp/coq-for-ipad/4fb3711723e2581a170ffd734e936f210086396e/src/ocaml-3.12.0/otherlibs/lablGL/gluMat.mli
ocaml
$ I d : gluMat.mli , v 1.1 1998/01/29 11:46:06 garrigue Exp $ open Gl val look_at : eye:point3 -> center:point3 -> up:vect3 -> unit val ortho2d : x:float * float -> y:float * float -> unit val perspective : fovy:float -> aspect:float -> z:float * float -> unit val pick_matrix : x:float -> y:float -> width:float -> height:float -> unit val project : point3 -> point3 val unproject : point3 -> point3
d9d8d24ebf89e8d43e11c00412ba63527d8d08a1065f908fefeb37f10c9b9b1d
atlas-engineer/nyxt
remembrance.lisp
SPDX - FileCopyrightText : Atlas Engineer LLC SPDX - License - Identifier : BSD-3 - Clause (in-package :nyxt/tests/renderer) (defun set-url-blocking (url &optional (buffer (nyxt:current-buffer))) (nyxt:buffer-load url) (let ((p (lpara:promise))) (hooks:once-on (nyxt:buffer-loaded-hook buffer) (_) (lpara:fulfill p)) (lpara:force p))) (defvar +url1+ (quri:make-uri-file :path (asdf:system-relative-pathname :nyxt "tests/test-data/hello.html"))) (defvar +url2+ (quri:make-uri-file :path (asdf:system-relative-pathname :nyxt "tests/test-data/lorem.html"))) (define-test remembrance () (nyxt:start :no-config t :no-auto-config t :socket "/tmp/nyxt-test.socket" :profile "test") (nyxt:enable-modes* 'nyxt/remembrance-mode:remembrance-mode (nyxt:current-buffer)) (let ((mode (nyxt:find-submode 'nyxt/remembrance-mode:remembrance-mode))) (assert-equality 'uiop:pathname-equal (nfiles:join +test-root+ (uiop:xdg-cache-home "nyxt" "remembrance.cache/")) (nfiles:expand (nyxt/remembrance-mode::cache-path mode))) (assert-number-equal 0 (nyxt/remembrance-mode::cache-size mode)) (set-url-blocking +url1+) (assert-number-equal 1 (nyxt/remembrance-mode::cache-size mode)) (set-url-blocking +url2+) TODO : For some reason loading a second URL does not trigger the on - signal- * methods in headless mode . ;; WebKitGTK bug? ( assert - number - equal 2 ( nyxt / remembrance - mode::cache - size mode ) ) (uiop:delete-directory-tree (nfiles:expand (nyxt/remembrance-mode::cache-path mode)) :validate t)) (nyxt:quit))
null
https://raw.githubusercontent.com/atlas-engineer/nyxt/9fa14dc2d267ce65ed7894247e92d6edc00d3e77/tests/renderer-offline/remembrance.lisp
lisp
WebKitGTK bug?
SPDX - FileCopyrightText : Atlas Engineer LLC SPDX - License - Identifier : BSD-3 - Clause (in-package :nyxt/tests/renderer) (defun set-url-blocking (url &optional (buffer (nyxt:current-buffer))) (nyxt:buffer-load url) (let ((p (lpara:promise))) (hooks:once-on (nyxt:buffer-loaded-hook buffer) (_) (lpara:fulfill p)) (lpara:force p))) (defvar +url1+ (quri:make-uri-file :path (asdf:system-relative-pathname :nyxt "tests/test-data/hello.html"))) (defvar +url2+ (quri:make-uri-file :path (asdf:system-relative-pathname :nyxt "tests/test-data/lorem.html"))) (define-test remembrance () (nyxt:start :no-config t :no-auto-config t :socket "/tmp/nyxt-test.socket" :profile "test") (nyxt:enable-modes* 'nyxt/remembrance-mode:remembrance-mode (nyxt:current-buffer)) (let ((mode (nyxt:find-submode 'nyxt/remembrance-mode:remembrance-mode))) (assert-equality 'uiop:pathname-equal (nfiles:join +test-root+ (uiop:xdg-cache-home "nyxt" "remembrance.cache/")) (nfiles:expand (nyxt/remembrance-mode::cache-path mode))) (assert-number-equal 0 (nyxt/remembrance-mode::cache-size mode)) (set-url-blocking +url1+) (assert-number-equal 1 (nyxt/remembrance-mode::cache-size mode)) (set-url-blocking +url2+) TODO : For some reason loading a second URL does not trigger the on - signal- * methods in headless mode . ( assert - number - equal 2 ( nyxt / remembrance - mode::cache - size mode ) ) (uiop:delete-directory-tree (nfiles:expand (nyxt/remembrance-mode::cache-path mode)) :validate t)) (nyxt:quit))
fa6b9677b075b76461f53fda69a9fff264de14057efb92aec2847fd99f692383
exercism/erlang
scrabble_score.erl
-module(scrabble_score). -export([score/1]). score(_Word) -> undefined.
null
https://raw.githubusercontent.com/exercism/erlang/57ac2707dae643682950715e74eb271f732e2100/exercises/practice/scrabble-score/src/scrabble_score.erl
erlang
-module(scrabble_score). -export([score/1]). score(_Word) -> undefined.
42773b78674d06fb41ac57506092503929f41c748b12ab52a60abbf5c463699e
ocamllabs/ocaml-modular-implicits
Test.ml
(* with module *) module type S = sig type t and s = t end;; module type S' = S with type t := int;; module type S = sig module rec M : sig end and N : sig end end;; module type S' = S with module M := String;; (* with module type *) module type S = sig module type T module F(X : T ) : T end ; ; module type T0 = sig type t end ; ; module type S1 = S with module type T = T0 ; ; module type S2 = S with module type T : = T0 ; ; module type S3 = S with module type T : = sig type t = int end ; ; module H = struct include ( : module type of with type statistics : = Hashtbl.statistics and module type S : = . S and module Make : = . Make and module : = . MakeSeeded and module type SeededS : = . SeededS and module type HashedType : = . HashedType and module type SeededHashedType : = . SeededHashedType ) end ; ; module type S = sig module type T module F(X:T) : T end;; module type T0 = sig type t end;; module type S1 = S with module type T = T0;; module type S2 = S with module type T := T0;; module type S3 = S with module type T := sig type t = int end;; module H = struct include (Hashtbl : module type of Hashtbl with type statistics := Hashtbl.statistics and module type S := Hashtbl.S and module Make := Hashtbl.Make and module MakeSeeded := Hashtbl.MakeSeeded and module type SeededS := Hashtbl.SeededS and module type HashedType := Hashtbl.HashedType and module type SeededHashedType := Hashtbl.SeededHashedType) end;; *) (* A subtle problem appearing with -principal *) type -'a t class type c = object method m : [ `A ] t end;; module M : sig val v : (#c as 'a) -> 'a end = struct let v x = ignore (x :> c); x end;; PR#4838 let id = let module M = struct end in fun x -> x;; (* PR#4511 *) let ko = let module M = struct end in fun _ -> ();; PR#5993 module M : sig type -'a t = private int end = struct type +'a t = private int end ;; (* PR#6005 *) module type A = sig type t = X of int end;; type u = X of bool;; module type B = A with type t = u;; (* fail *) PR#5815 module type S = sig exception Foo of int exception Foo of bool end;; PR#6410 module F(X : sig end) = struct let x = 3 end;; F.x;; (* fail *)
null
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/typing-modules/Test.ml
ocaml
with module with module type A subtle problem appearing with -principal PR#4511 PR#6005 fail fail
module type S = sig type t and s = t end;; module type S' = S with type t := int;; module type S = sig module rec M : sig end and N : sig end end;; module type S' = S with module M := String;; module type S = sig module type T module F(X : T ) : T end ; ; module type T0 = sig type t end ; ; module type S1 = S with module type T = T0 ; ; module type S2 = S with module type T : = T0 ; ; module type S3 = S with module type T : = sig type t = int end ; ; module H = struct include ( : module type of with type statistics : = Hashtbl.statistics and module type S : = . S and module Make : = . Make and module : = . MakeSeeded and module type SeededS : = . SeededS and module type HashedType : = . HashedType and module type SeededHashedType : = . SeededHashedType ) end ; ; module type S = sig module type T module F(X:T) : T end;; module type T0 = sig type t end;; module type S1 = S with module type T = T0;; module type S2 = S with module type T := T0;; module type S3 = S with module type T := sig type t = int end;; module H = struct include (Hashtbl : module type of Hashtbl with type statistics := Hashtbl.statistics and module type S := Hashtbl.S and module Make := Hashtbl.Make and module MakeSeeded := Hashtbl.MakeSeeded and module type SeededS := Hashtbl.SeededS and module type HashedType := Hashtbl.HashedType and module type SeededHashedType := Hashtbl.SeededHashedType) end;; *) type -'a t class type c = object method m : [ `A ] t end;; module M : sig val v : (#c as 'a) -> 'a end = struct let v x = ignore (x :> c); x end;; PR#4838 let id = let module M = struct end in fun x -> x;; let ko = let module M = struct end in fun _ -> ();; PR#5993 module M : sig type -'a t = private int end = struct type +'a t = private int end ;; module type A = sig type t = X of int end;; type u = X of bool;; PR#5815 module type S = sig exception Foo of int exception Foo of bool end;; PR#6410 module F(X : sig end) = struct let x = 3 end;;
6bebee3ec81eb331e164e6f6b70e1d99a8a343350f5228a5854a095ecca9bb86
ucsd-progsys/dsolve
myset.mli
type set val empty: set val mem: 'a -> set -> bool val eq: set -> set -> bool val of_list: 'a list -> set val cap: set -> set -> set val cup: set -> set -> set val sng: 'a -> set val mns: set -> set -> set
null
https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/theories/myset.mli
ocaml
type set val empty: set val mem: 'a -> set -> bool val eq: set -> set -> bool val of_list: 'a list -> set val cap: set -> set -> set val cup: set -> set -> set val sng: 'a -> set val mns: set -> set -> set
81fbb2b7942d7bcdbe1a7ed5747e22a550e918c078aa5829a131d87924f8ca94
lamdu/lamdu
TagPane.hs
# LANGUAGE TypeFamilies # module Lamdu.GUI.TagPane ( make ) where import qualified Control.Lens as Lens import qualified Data.Char as Char import Data.Property (Property(..), pVal) import qualified Data.Property as Property import qualified Data.Set as Set import qualified Data.Text as Text import GUI.Momentu (TextWidget, Aligned(..), WithTextPos(..), Widget, (/-/), (/|/), noMods) import qualified GUI.Momentu as M import qualified GUI.Momentu.Align as Align import qualified GUI.Momentu.Element as Element import GUI.Momentu.Element.Id (ElemId) import qualified GUI.Momentu.EventMap as E import GUI.Momentu.Glue (hbox) import qualified GUI.Momentu.I18N as MomentuTexts import qualified GUI.Momentu.ModKey as ModKey import qualified GUI.Momentu.State as GuiState import qualified GUI.Momentu.Widget as Widget import qualified GUI.Momentu.Widgets.DropDownList as DropDownList import qualified GUI.Momentu.Widgets.FocusDelegator as FocusDelegator import qualified GUI.Momentu.Widgets.Grid as Grid import qualified GUI.Momentu.Widgets.Spacer as Spacer import qualified GUI.Momentu.Widgets.TextEdit as TextEdit import qualified GUI.Momentu.Widgets.TextEdit.Property as TextEdits import qualified GUI.Momentu.Widgets.TextView as TextView import qualified Lamdu.CharClassification as Chars import qualified Lamdu.Config as Config import qualified Lamdu.Config.Theme.TextColors as TextColors import Lamdu.Data.Tag (TextsInLang(..)) import qualified Lamdu.Data.Tag as Tag import Lamdu.Formatting (Format(..)) import Lamdu.GUI.Styled (addValFrame, label, info, withColor) import qualified Lamdu.I18N.CodeUI as Texts import Lamdu.I18N.LangId (LangId(..), _LangId) import qualified Lamdu.Sugar.Types as Sugar import Lamdu.Prelude tagRenameId :: ElemId -> ElemId tagRenameId = (<> "rename") disallowedNameChars :: Set Char disallowedNameChars = Set.fromList ",[]\\`()" makeTagNameEdit :: _ => Property f Text -> ElemId -> m (TextWidget f) makeTagNameEdit prop myId = TextEdits.makeWordEdit ?? pure " " ?? (prop & Property.pSet %~ (. (Lens.ix 0 %~ Char.toLower))) ?? tagRenameId myId <&> Align.tValue . Widget.eventMapMaker . Lens.mapped %~ E.filterChars (`Set.notMember` disallowedNameChars) makeSymbolNameEdit :: _ => Property f Text -> ElemId -> m (TextWidget f) makeSymbolNameEdit prop myId = TextEdits.makeWordEdit <*> (Lens.view (has . Texts.typeOperatorHere) <&> pure) ?? prop ?? tagRenameId myId <&> Align.tValue . Widget.eventMapMaker . Lens.mapped %~ E.filterChars allowedSymbolChars where allowedSymbolChars = Set.member ?? Set.fromList Chars.operator `Set.difference` disallowedNameChars makeFocusableTagNameEdit :: _ => ElemId -> Property o Text -> m (TextWidget o) makeFocusableTagNameEdit myId prop = do env <- Lens.view id let fdConfig = FocusDelegator.Config { FocusDelegator.focusChildKeys = env ^. has . Config.jumpToDefinitionKeys , FocusDelegator.focusChildDoc = E.toDoc env [ has . MomentuTexts.edit , has . Texts.tag , has . Texts.renameTag ] , FocusDelegator.focusParentKeys = [ noMods ModKey.Key'Escape , noMods ModKey.Key'Enter ] , FocusDelegator.focusParentDoc = E.toDoc env [ has . MomentuTexts.edit , has . Texts.tag , has . Texts.stopEditing ] } (FocusDelegator.make ?? fdConfig ?? FocusDelegator.FocusEntryParent ?? myId <&> (Align.tValue %~)) <*> makeTagNameEdit prop myId makeLanguageTitle :: _ => ElemId -> LangId -> m (TextWidget o) makeLanguageTitle myId lang = TextView.make <*> (Lens.view has <&> getLang) <*> pure (myId <> "lang-title") <&> Align.tValue %~ Widget.fromView where getLang :: Map LangId Text -> Text getLang x = x ^. Lens.at lang & fromMaybe (lang ^. _LangId & Lens.ix 0 %~ Char.toUpper) data TextsRow a = TextsRow { _language :: a , _space0 :: a , _name :: a , _space1 :: a , _abbreviation :: a , _space2 :: a , _disambig :: a } deriving (Functor, Foldable, Traversable) langElemId :: ElemId -> LangId -> ElemId langElemId parentId lang = parentId <> M.asElemId lang nameId :: ElemId -> ElemId nameId = (<> "name") hspace :: _ => m (TextWidget f) hspace = Spacer.stdHSpace <&> Widget.fromView <&> WithTextPos 0 hspaceOf :: Widget.R -> TextWidget f hspaceOf w = Spacer.makeHorizontal w & Widget.fromView & WithTextPos 0 textsRow :: _ => m (TextWidget f) -> m (TextWidget f) -> m (TextWidget f) -> m (TextWidget f) -> m (TextsRow (Aligned (Widget f))) textsRow lang name abbrev disambig = TextsRow lang hspace name hspace abbrev hspace disambig & sequenceA <&> Lens.mapped %~ Align.fromWithTextPos 0 makeLangRow :: _ => ElemId -> (LangId -> TextsInLang -> o ()) -> LangId -> TextsInLang -> m (TextsRow (Aligned (Widget o))) makeLangRow parentId setName lang langNames = textsRow (makeLanguageTitle langId lang & info) (makeFocusableTagNameEdit (nameId langId) nameProp) (mkProp Tag.abbreviation & makeFocusableTagNameEdit (mkId "abbr")) (mkProp Tag.disambiguationText & makeFocusableTagNameEdit (mkId "disamb")) where mkId suffix = langId <> suffix langId = langElemId parentId lang nameProp = setName lang . (\x -> langNames & Tag.name .~ x) & Property (langNames ^. Tag.name) mkProp l = setName lang . (\x -> langNames & Lens.cloneLens l .~ if x == "" then Nothing else Just x) & Property (langNames ^. Lens.cloneLens l . Lens._Just) makeMissingLangRow :: _ => ElemId -> (LangId -> TextsInLang -> o ()) -> LangId -> m (TextsRow (Aligned (Widget o))) makeMissingLangRow parentId setName lang = textsRow (makeLanguageTitle langId lang & info) (makeFocusableTagNameEdit (nameId langId) nameProp) (pure Element.empty) (pure Element.empty) where langId = langElemId parentId lang nameProp = setName lang . (\x -> TextsInLang x Nothing Nothing) & Property "" makeLangsTable :: (MonadReader env m, _) => ElemId -> Map LangId TextsInLang -> (LangId -> TextsInLang -> o ()) -> m (Widget o) makeLangsTable myId tagTexts setName = do lang <- Lens.view has let currentLang = case tagTexts ^. Lens.at lang of Nothing -> makeMissingLangRow myId setName lang Just cur -> makeLangRow myId setName lang cur let editOtherLangs = tagTexts ^@.. Lens.itraversed & filter ((/= lang) . fst) <&> uncurry (makeLangRow myId setName) Grid.make <*> sequence (heading : currentLang : editOtherLangs) <&> snd where -- the type of Styled.label is RankN, so duplicate a bit of -- code to avoid complicating too much here toWidget = fmap Widget.fromView heading = textsRow (label MomentuTexts.language <&> toWidget) (label Texts.name <&> toWidget) (label Texts.abbreviation <&> toWidget) (label Texts.disambiguationText <&> toWidget) & info data SymType = NoSymbol | UniversalSymbol | DirectionalSymbol deriving Eq makeSymbol :: _ => ElemId -> Property o Tag.Symbol -> m (TextWidget o, TextWidget o) makeSymbol myId symProp = case symProp ^. pVal of Tag.NoSymbol -> flip (,) Element.empty <$> makeDropDownList NoSymbol (toSym "" "") Tag.UniversalSymbol text -> (,) <$> makeDropDownList UniversalSymbol (toSym text text) <*> nameEdit (Property text (set . Tag.UniversalSymbol)) "universal" Tag.DirectionalSymbol (Tag.DirOp ltr rtl) -> (,) <$> makeDropDownList DirectionalSymbol (toSym ltr rtl) <*> ( (label Texts.leftToRightSymbol & info <&> fmap Widget.fromView) /|/ hspace /|/ nameEdit (Property ltr (`setDirectional` rtl)) "ltr" /|/ hspace /|/ info (label Texts.rightToLeftSymbol) /|/ hspace /|/ nameEdit (Property rtl (setDirectional ltr)) "rtl" ) where set = void . Property.set symProp setDirectional ltr rtl = Tag.DirOp ltr rtl & Tag.DirectionalSymbol & set toSym _ _ NoSymbol = Tag.NoSymbol toSym "" rtl UniversalSymbol = Tag.UniversalSymbol rtl toSym ltr _ UniversalSymbol = Tag.UniversalSymbol ltr toSym ltr rtl DirectionalSymbol = Tag.DirectionalSymbol (Tag.DirOp ltr rtl) mkId suffix = myId <> suffix nameEdit prop = makeSymbolNameEdit prop . mkId focusableLabel l suffix = TextView.makeFocusable <*> Lens.view (has . l) ?? mkId suffix makeDropDownList curType toTagSym = do noSymLabel <- focusableLabel Texts.noSymbol "nosym" uniLabel <- focusableLabel Texts.symbol "unisym" dirLabel <- focusableLabel Texts.directionalSymbol "dirsym" defConf <- DropDownList.defaultConfig <*> Lens.view (has . Texts.symbolType) DropDownList.make ?? Property curType (set . toTagSym) ?? [ (NoSymbol, noSymLabel) , (UniversalSymbol, uniLabel) , (DirectionalSymbol, dirLabel) ] ?? defConf ?? mkId "symType" & withColor TextColors.actionTextColor parseInt :: Text -> Maybe Int parseInt newText | newText /= Text.strip newText = Nothing | newText == "" = Just 0 | otherwise = tryParse newText makeIntEdit :: _ => ElemId -> Property o Int -> m (TextWidget o) makeIntEdit myId prop = do text <- M.readWidgetState myId <&> (^? Lens._Just . Lens.filtered ((== Just prevVal) . parseInt)) <&> fromMaybe prevValStr TextEdit.make ?? TextEdit.Modes "0" "0" ?? text ?? myId <&> Align.tValue . Widget.eventMapMaker . Lens.mapped %~ -- Avoid taking keys that don't belong to us, -- so weakerEvents with them will work. E.filter (Lens.has Lens._Just . parseInt . fst) <&> Align.tValue . Widget.updates %~ \(newText, eventRes) -> eventRes <> GuiState.updateWidgetState myId newText <$ (parseInt newText & parseAssert & Property.set prop) where parseAssert = error "parsing int failed" & fromMaybe prevVal = Property.value prop prevValStr = show prevVal & Text.pack makeOrderEdit :: _ => ElemId -> Property o Int -> m (TextWidget o) makeOrderEdit tagPaneId prop = info (label Texts.order) /|/ hspace /|/ makeIntEdit orderEditId prop where orderEditId = tagPaneId <> "tagOrder" make :: _ => Sugar.TagPane o -> ElemId -> m (Widget o) make tagPane myId = Lens.view has >>= \lang -> addValFrame <*> do (symbol, nextLine) <- makeSymbol myId symbolProp langsTable <- makeLangsTable myId (tagPane ^. Sugar.tpTagData . Tag.tagTexts) (tagPane ^. Sugar.tpSetTexts) orderEdit <- makeOrderEdit myId orderProp let totalWidth = max (nextLine ^. Element.width) (langsTable ^. Element.width) let gap = totalWidth - (symbol ^. Element.width + orderEdit ^. Element.width) pure langsTable /-/ (hbox ?? [symbol, hspaceOf gap, orderEdit] <&> (^. Align.tValue)) /-/ pure (nextLine ^. Align.tValue) & local (Element.elemIdPrefix .~ M.asElemId myId) & GuiState.assignCursor myId (nameId (langElemId myId lang)) where orderProp = Property (tagPane ^. Sugar.tpTagData . Tag.tagOrder) (tagPane ^. Sugar.tpSetOrder) symbolProp = Property (tagPane ^. Sugar.tpTagData . Tag.tagSymbol) (tagPane ^. Sugar.tpSetSymbol)
null
https://raw.githubusercontent.com/lamdu/lamdu/5b15688e53ccbf7448ff11134b3e51ed082c6b6c/src/Lamdu/GUI/TagPane.hs
haskell
the type of Styled.label is RankN, so duplicate a bit of code to avoid complicating too much here Avoid taking keys that don't belong to us, so weakerEvents with them will work.
# LANGUAGE TypeFamilies # module Lamdu.GUI.TagPane ( make ) where import qualified Control.Lens as Lens import qualified Data.Char as Char import Data.Property (Property(..), pVal) import qualified Data.Property as Property import qualified Data.Set as Set import qualified Data.Text as Text import GUI.Momentu (TextWidget, Aligned(..), WithTextPos(..), Widget, (/-/), (/|/), noMods) import qualified GUI.Momentu as M import qualified GUI.Momentu.Align as Align import qualified GUI.Momentu.Element as Element import GUI.Momentu.Element.Id (ElemId) import qualified GUI.Momentu.EventMap as E import GUI.Momentu.Glue (hbox) import qualified GUI.Momentu.I18N as MomentuTexts import qualified GUI.Momentu.ModKey as ModKey import qualified GUI.Momentu.State as GuiState import qualified GUI.Momentu.Widget as Widget import qualified GUI.Momentu.Widgets.DropDownList as DropDownList import qualified GUI.Momentu.Widgets.FocusDelegator as FocusDelegator import qualified GUI.Momentu.Widgets.Grid as Grid import qualified GUI.Momentu.Widgets.Spacer as Spacer import qualified GUI.Momentu.Widgets.TextEdit as TextEdit import qualified GUI.Momentu.Widgets.TextEdit.Property as TextEdits import qualified GUI.Momentu.Widgets.TextView as TextView import qualified Lamdu.CharClassification as Chars import qualified Lamdu.Config as Config import qualified Lamdu.Config.Theme.TextColors as TextColors import Lamdu.Data.Tag (TextsInLang(..)) import qualified Lamdu.Data.Tag as Tag import Lamdu.Formatting (Format(..)) import Lamdu.GUI.Styled (addValFrame, label, info, withColor) import qualified Lamdu.I18N.CodeUI as Texts import Lamdu.I18N.LangId (LangId(..), _LangId) import qualified Lamdu.Sugar.Types as Sugar import Lamdu.Prelude tagRenameId :: ElemId -> ElemId tagRenameId = (<> "rename") disallowedNameChars :: Set Char disallowedNameChars = Set.fromList ",[]\\`()" makeTagNameEdit :: _ => Property f Text -> ElemId -> m (TextWidget f) makeTagNameEdit prop myId = TextEdits.makeWordEdit ?? pure " " ?? (prop & Property.pSet %~ (. (Lens.ix 0 %~ Char.toLower))) ?? tagRenameId myId <&> Align.tValue . Widget.eventMapMaker . Lens.mapped %~ E.filterChars (`Set.notMember` disallowedNameChars) makeSymbolNameEdit :: _ => Property f Text -> ElemId -> m (TextWidget f) makeSymbolNameEdit prop myId = TextEdits.makeWordEdit <*> (Lens.view (has . Texts.typeOperatorHere) <&> pure) ?? prop ?? tagRenameId myId <&> Align.tValue . Widget.eventMapMaker . Lens.mapped %~ E.filterChars allowedSymbolChars where allowedSymbolChars = Set.member ?? Set.fromList Chars.operator `Set.difference` disallowedNameChars makeFocusableTagNameEdit :: _ => ElemId -> Property o Text -> m (TextWidget o) makeFocusableTagNameEdit myId prop = do env <- Lens.view id let fdConfig = FocusDelegator.Config { FocusDelegator.focusChildKeys = env ^. has . Config.jumpToDefinitionKeys , FocusDelegator.focusChildDoc = E.toDoc env [ has . MomentuTexts.edit , has . Texts.tag , has . Texts.renameTag ] , FocusDelegator.focusParentKeys = [ noMods ModKey.Key'Escape , noMods ModKey.Key'Enter ] , FocusDelegator.focusParentDoc = E.toDoc env [ has . MomentuTexts.edit , has . Texts.tag , has . Texts.stopEditing ] } (FocusDelegator.make ?? fdConfig ?? FocusDelegator.FocusEntryParent ?? myId <&> (Align.tValue %~)) <*> makeTagNameEdit prop myId makeLanguageTitle :: _ => ElemId -> LangId -> m (TextWidget o) makeLanguageTitle myId lang = TextView.make <*> (Lens.view has <&> getLang) <*> pure (myId <> "lang-title") <&> Align.tValue %~ Widget.fromView where getLang :: Map LangId Text -> Text getLang x = x ^. Lens.at lang & fromMaybe (lang ^. _LangId & Lens.ix 0 %~ Char.toUpper) data TextsRow a = TextsRow { _language :: a , _space0 :: a , _name :: a , _space1 :: a , _abbreviation :: a , _space2 :: a , _disambig :: a } deriving (Functor, Foldable, Traversable) langElemId :: ElemId -> LangId -> ElemId langElemId parentId lang = parentId <> M.asElemId lang nameId :: ElemId -> ElemId nameId = (<> "name") hspace :: _ => m (TextWidget f) hspace = Spacer.stdHSpace <&> Widget.fromView <&> WithTextPos 0 hspaceOf :: Widget.R -> TextWidget f hspaceOf w = Spacer.makeHorizontal w & Widget.fromView & WithTextPos 0 textsRow :: _ => m (TextWidget f) -> m (TextWidget f) -> m (TextWidget f) -> m (TextWidget f) -> m (TextsRow (Aligned (Widget f))) textsRow lang name abbrev disambig = TextsRow lang hspace name hspace abbrev hspace disambig & sequenceA <&> Lens.mapped %~ Align.fromWithTextPos 0 makeLangRow :: _ => ElemId -> (LangId -> TextsInLang -> o ()) -> LangId -> TextsInLang -> m (TextsRow (Aligned (Widget o))) makeLangRow parentId setName lang langNames = textsRow (makeLanguageTitle langId lang & info) (makeFocusableTagNameEdit (nameId langId) nameProp) (mkProp Tag.abbreviation & makeFocusableTagNameEdit (mkId "abbr")) (mkProp Tag.disambiguationText & makeFocusableTagNameEdit (mkId "disamb")) where mkId suffix = langId <> suffix langId = langElemId parentId lang nameProp = setName lang . (\x -> langNames & Tag.name .~ x) & Property (langNames ^. Tag.name) mkProp l = setName lang . (\x -> langNames & Lens.cloneLens l .~ if x == "" then Nothing else Just x) & Property (langNames ^. Lens.cloneLens l . Lens._Just) makeMissingLangRow :: _ => ElemId -> (LangId -> TextsInLang -> o ()) -> LangId -> m (TextsRow (Aligned (Widget o))) makeMissingLangRow parentId setName lang = textsRow (makeLanguageTitle langId lang & info) (makeFocusableTagNameEdit (nameId langId) nameProp) (pure Element.empty) (pure Element.empty) where langId = langElemId parentId lang nameProp = setName lang . (\x -> TextsInLang x Nothing Nothing) & Property "" makeLangsTable :: (MonadReader env m, _) => ElemId -> Map LangId TextsInLang -> (LangId -> TextsInLang -> o ()) -> m (Widget o) makeLangsTable myId tagTexts setName = do lang <- Lens.view has let currentLang = case tagTexts ^. Lens.at lang of Nothing -> makeMissingLangRow myId setName lang Just cur -> makeLangRow myId setName lang cur let editOtherLangs = tagTexts ^@.. Lens.itraversed & filter ((/= lang) . fst) <&> uncurry (makeLangRow myId setName) Grid.make <*> sequence (heading : currentLang : editOtherLangs) <&> snd where toWidget = fmap Widget.fromView heading = textsRow (label MomentuTexts.language <&> toWidget) (label Texts.name <&> toWidget) (label Texts.abbreviation <&> toWidget) (label Texts.disambiguationText <&> toWidget) & info data SymType = NoSymbol | UniversalSymbol | DirectionalSymbol deriving Eq makeSymbol :: _ => ElemId -> Property o Tag.Symbol -> m (TextWidget o, TextWidget o) makeSymbol myId symProp = case symProp ^. pVal of Tag.NoSymbol -> flip (,) Element.empty <$> makeDropDownList NoSymbol (toSym "" "") Tag.UniversalSymbol text -> (,) <$> makeDropDownList UniversalSymbol (toSym text text) <*> nameEdit (Property text (set . Tag.UniversalSymbol)) "universal" Tag.DirectionalSymbol (Tag.DirOp ltr rtl) -> (,) <$> makeDropDownList DirectionalSymbol (toSym ltr rtl) <*> ( (label Texts.leftToRightSymbol & info <&> fmap Widget.fromView) /|/ hspace /|/ nameEdit (Property ltr (`setDirectional` rtl)) "ltr" /|/ hspace /|/ info (label Texts.rightToLeftSymbol) /|/ hspace /|/ nameEdit (Property rtl (setDirectional ltr)) "rtl" ) where set = void . Property.set symProp setDirectional ltr rtl = Tag.DirOp ltr rtl & Tag.DirectionalSymbol & set toSym _ _ NoSymbol = Tag.NoSymbol toSym "" rtl UniversalSymbol = Tag.UniversalSymbol rtl toSym ltr _ UniversalSymbol = Tag.UniversalSymbol ltr toSym ltr rtl DirectionalSymbol = Tag.DirectionalSymbol (Tag.DirOp ltr rtl) mkId suffix = myId <> suffix nameEdit prop = makeSymbolNameEdit prop . mkId focusableLabel l suffix = TextView.makeFocusable <*> Lens.view (has . l) ?? mkId suffix makeDropDownList curType toTagSym = do noSymLabel <- focusableLabel Texts.noSymbol "nosym" uniLabel <- focusableLabel Texts.symbol "unisym" dirLabel <- focusableLabel Texts.directionalSymbol "dirsym" defConf <- DropDownList.defaultConfig <*> Lens.view (has . Texts.symbolType) DropDownList.make ?? Property curType (set . toTagSym) ?? [ (NoSymbol, noSymLabel) , (UniversalSymbol, uniLabel) , (DirectionalSymbol, dirLabel) ] ?? defConf ?? mkId "symType" & withColor TextColors.actionTextColor parseInt :: Text -> Maybe Int parseInt newText | newText /= Text.strip newText = Nothing | newText == "" = Just 0 | otherwise = tryParse newText makeIntEdit :: _ => ElemId -> Property o Int -> m (TextWidget o) makeIntEdit myId prop = do text <- M.readWidgetState myId <&> (^? Lens._Just . Lens.filtered ((== Just prevVal) . parseInt)) <&> fromMaybe prevValStr TextEdit.make ?? TextEdit.Modes "0" "0" ?? text ?? myId <&> Align.tValue . Widget.eventMapMaker . Lens.mapped %~ E.filter (Lens.has Lens._Just . parseInt . fst) <&> Align.tValue . Widget.updates %~ \(newText, eventRes) -> eventRes <> GuiState.updateWidgetState myId newText <$ (parseInt newText & parseAssert & Property.set prop) where parseAssert = error "parsing int failed" & fromMaybe prevVal = Property.value prop prevValStr = show prevVal & Text.pack makeOrderEdit :: _ => ElemId -> Property o Int -> m (TextWidget o) makeOrderEdit tagPaneId prop = info (label Texts.order) /|/ hspace /|/ makeIntEdit orderEditId prop where orderEditId = tagPaneId <> "tagOrder" make :: _ => Sugar.TagPane o -> ElemId -> m (Widget o) make tagPane myId = Lens.view has >>= \lang -> addValFrame <*> do (symbol, nextLine) <- makeSymbol myId symbolProp langsTable <- makeLangsTable myId (tagPane ^. Sugar.tpTagData . Tag.tagTexts) (tagPane ^. Sugar.tpSetTexts) orderEdit <- makeOrderEdit myId orderProp let totalWidth = max (nextLine ^. Element.width) (langsTable ^. Element.width) let gap = totalWidth - (symbol ^. Element.width + orderEdit ^. Element.width) pure langsTable /-/ (hbox ?? [symbol, hspaceOf gap, orderEdit] <&> (^. Align.tValue)) /-/ pure (nextLine ^. Align.tValue) & local (Element.elemIdPrefix .~ M.asElemId myId) & GuiState.assignCursor myId (nameId (langElemId myId lang)) where orderProp = Property (tagPane ^. Sugar.tpTagData . Tag.tagOrder) (tagPane ^. Sugar.tpSetOrder) symbolProp = Property (tagPane ^. Sugar.tpTagData . Tag.tagSymbol) (tagPane ^. Sugar.tpSetSymbol)
b8dc2d8fcadae27e7595e7c4b7b9072a7174210ddc1d791acddada793b952753
GaloisInc/saw-script
Main.hs
{-# LANGUAGE RankNTypes #-} module Main where import System.Environment( getArgs ) import System.Exit( exitFailure ) import System.Console.GetOpt import System.IO import qualified Data.ByteString as BS import Data.Text ( pack ) import Data.Version import qualified Cryptol.Eval as E import qualified Cryptol.TypeCheck.AST as T import qualified Cryptol.ModuleSystem as CM import qualified Cryptol.ModuleSystem.Env as CME import qualified Cryptol.Parser as P import qualified Cryptol.TypeCheck.Solver.SMT as SMT import Cryptol.Utils.PP import Cryptol.Utils.Logger (quietLogger) import qualified Data.AIG.CompactGraph as AIG import qualified Data.AIG.Interface as AIG import qualified Data.AIG.Operations as AIG import qualified Verifier.SAW.Cryptol as C import Verifier.SAW.SharedTerm import qualified Verifier.SAW.Cryptol.Prelude as C import Verifier.SAW.CryptolEnv (schemaNoUser, meSolverConfig) import qualified Verifier.SAW.Simulator.BitBlast as BBSim import qualified Paths_cryptol_saw_core as Paths data CSS = CSS { output :: FilePath , cssMode :: CmdMode } deriving (Show) data CmdMode = NormalMode | HelpMode | VersionMode deriving (Show, Eq) emptyCSS :: CSS emptyCSS = CSS { output = "" , cssMode = NormalMode } options :: [OptDescr (CSS -> CSS)] options = [ Option ['o'] ["output"] (ReqArg (\x css -> css{ output = x }) "FILE") "output file" , Option ['h'] ["help"] (NoArg (\css -> css{ cssMode = HelpMode })) "display help" , Option ['v'] ["version"] (NoArg (\css -> css{ cssMode = VersionMode })) "version" ] version_string :: String version_string = unlines [ "Cryptol Symbolic Simulator (css) version "++showVersion Paths.version , "Copyright 2014 Galois, Inc. All rights reserved." ] header :: String header = "css [options] <input module> <function to simulate>" main :: IO () main = do args <- getArgs case getOpt RequireOrder options args of (flags,optArgs,[]) -> cssMain (foldr ($) emptyCSS flags) optArgs (_,_,errs) -> do hPutStr stderr (concat errs ++ usageInfo header options) exitFailure defaultEvalOpts :: E.EvalOpts defaultEvalOpts = E.EvalOpts quietLogger E.defaultPPOpts cssMain :: CSS -> [String] -> IO () cssMain css [inputModule,name] | cssMode css == NormalMode = do let out = if null (output css) then name++".aig" else (output css) modEnv <- CM.initialModuleEnv let minp = CM.ModuleInput True (pure defaultEvalOpts) BS.readFile modEnv (e,warn) <- SMT.withSolver (return ()) (meSolverConfig modEnv) $ \s -> CM.loadModuleByPath inputModule (minp s) mapM_ (print . pp) warn case e of Left msg -> print msg >> exitFailure Right (_,menv) -> processModule menv out name cssMain css _ | cssMode css == VersionMode = do hPutStr stdout version_string cssMain css _ | cssMode css == HelpMode = do hPutStr stdout (usageInfo header options) cssMain _ _ = do hPutStr stdout (usageInfo header options) exitFailure processModule :: CM.ModuleEnv -> FilePath -> String -> IO () processModule menv fout funcName = do sc <- mkSharedContext C.scLoadPreludeModule sc C.scLoadCryptolModule sc tm <- extractCryptol sc menv funcName writeAIG sc fout tm writeAIG :: SharedContext -> FilePath -> Term -> IO () writeAIG sc f t = do BBSim.withBitBlastedTerm AIG.compactProxy sc mempty t $ \be ls -> do AIG.writeAiger f (AIG.Network be (AIG.bvToList ls)) extractCryptol :: SharedContext -> CM.ModuleEnv -> String -> IO Term extractCryptol sc modEnv input = do let declGroups = concatMap T.mDecls (CME.loadedModules modEnv) env <- C.importDeclGroups sc C.emptyEnv declGroups pexpr <- case P.parseExpr (pack input) of Left err -> fail (show (P.ppError err)) Right x -> return x let minp = CM.ModuleInput True (pure defaultEvalOpts) BS.readFile modEnv (exprResult, exprWarnings) <- SMT.withSolver (return ()) (meSolverConfig modEnv) $ \s -> CM.checkExpr pexpr (minp s) mapM_ (print . pp) exprWarnings ((_, expr, schema), _modEnv') <- case exprResult of Left err -> fail (show (pp err)) Right x -> return x putStrLn $ "Extracting expression of type " ++ show (pp (schemaNoUser schema)) C.importExpr sc env expr
null
https://raw.githubusercontent.com/GaloisInc/saw-script/65d764b0e5cc0f4608b75448354e8c47f06a8cdc/cryptol-saw-core/css/Main.hs
haskell
# LANGUAGE RankNTypes #
module Main where import System.Environment( getArgs ) import System.Exit( exitFailure ) import System.Console.GetOpt import System.IO import qualified Data.ByteString as BS import Data.Text ( pack ) import Data.Version import qualified Cryptol.Eval as E import qualified Cryptol.TypeCheck.AST as T import qualified Cryptol.ModuleSystem as CM import qualified Cryptol.ModuleSystem.Env as CME import qualified Cryptol.Parser as P import qualified Cryptol.TypeCheck.Solver.SMT as SMT import Cryptol.Utils.PP import Cryptol.Utils.Logger (quietLogger) import qualified Data.AIG.CompactGraph as AIG import qualified Data.AIG.Interface as AIG import qualified Data.AIG.Operations as AIG import qualified Verifier.SAW.Cryptol as C import Verifier.SAW.SharedTerm import qualified Verifier.SAW.Cryptol.Prelude as C import Verifier.SAW.CryptolEnv (schemaNoUser, meSolverConfig) import qualified Verifier.SAW.Simulator.BitBlast as BBSim import qualified Paths_cryptol_saw_core as Paths data CSS = CSS { output :: FilePath , cssMode :: CmdMode } deriving (Show) data CmdMode = NormalMode | HelpMode | VersionMode deriving (Show, Eq) emptyCSS :: CSS emptyCSS = CSS { output = "" , cssMode = NormalMode } options :: [OptDescr (CSS -> CSS)] options = [ Option ['o'] ["output"] (ReqArg (\x css -> css{ output = x }) "FILE") "output file" , Option ['h'] ["help"] (NoArg (\css -> css{ cssMode = HelpMode })) "display help" , Option ['v'] ["version"] (NoArg (\css -> css{ cssMode = VersionMode })) "version" ] version_string :: String version_string = unlines [ "Cryptol Symbolic Simulator (css) version "++showVersion Paths.version , "Copyright 2014 Galois, Inc. All rights reserved." ] header :: String header = "css [options] <input module> <function to simulate>" main :: IO () main = do args <- getArgs case getOpt RequireOrder options args of (flags,optArgs,[]) -> cssMain (foldr ($) emptyCSS flags) optArgs (_,_,errs) -> do hPutStr stderr (concat errs ++ usageInfo header options) exitFailure defaultEvalOpts :: E.EvalOpts defaultEvalOpts = E.EvalOpts quietLogger E.defaultPPOpts cssMain :: CSS -> [String] -> IO () cssMain css [inputModule,name] | cssMode css == NormalMode = do let out = if null (output css) then name++".aig" else (output css) modEnv <- CM.initialModuleEnv let minp = CM.ModuleInput True (pure defaultEvalOpts) BS.readFile modEnv (e,warn) <- SMT.withSolver (return ()) (meSolverConfig modEnv) $ \s -> CM.loadModuleByPath inputModule (minp s) mapM_ (print . pp) warn case e of Left msg -> print msg >> exitFailure Right (_,menv) -> processModule menv out name cssMain css _ | cssMode css == VersionMode = do hPutStr stdout version_string cssMain css _ | cssMode css == HelpMode = do hPutStr stdout (usageInfo header options) cssMain _ _ = do hPutStr stdout (usageInfo header options) exitFailure processModule :: CM.ModuleEnv -> FilePath -> String -> IO () processModule menv fout funcName = do sc <- mkSharedContext C.scLoadPreludeModule sc C.scLoadCryptolModule sc tm <- extractCryptol sc menv funcName writeAIG sc fout tm writeAIG :: SharedContext -> FilePath -> Term -> IO () writeAIG sc f t = do BBSim.withBitBlastedTerm AIG.compactProxy sc mempty t $ \be ls -> do AIG.writeAiger f (AIG.Network be (AIG.bvToList ls)) extractCryptol :: SharedContext -> CM.ModuleEnv -> String -> IO Term extractCryptol sc modEnv input = do let declGroups = concatMap T.mDecls (CME.loadedModules modEnv) env <- C.importDeclGroups sc C.emptyEnv declGroups pexpr <- case P.parseExpr (pack input) of Left err -> fail (show (P.ppError err)) Right x -> return x let minp = CM.ModuleInput True (pure defaultEvalOpts) BS.readFile modEnv (exprResult, exprWarnings) <- SMT.withSolver (return ()) (meSolverConfig modEnv) $ \s -> CM.checkExpr pexpr (minp s) mapM_ (print . pp) exprWarnings ((_, expr, schema), _modEnv') <- case exprResult of Left err -> fail (show (pp err)) Right x -> return x putStrLn $ "Extracting expression of type " ++ show (pp (schemaNoUser schema)) C.importExpr sc env expr
f38d9948d6d6264e81d82bdcf0c5ab56d352fac90c5ab808dcf458ee9b49c46b
rescript-lang/syntax
Benchmark.ml
module ResParser = Res_core module Doc = Res_doc module CommentTable = Res_comments_table module Parser = Res_parser module Printer = Res_printer module IO : sig val readFile : string -> string end = struct random chunk size : 2 ^ 15 , TODO : why do we guess randomly ? let chunkSize = 32768 let readFile filename = let chan = open_in filename in let buffer = Buffer.create chunkSize in let chunk = (Bytes.create [@doesNotRaise]) chunkSize in let rec loop () = let len = try input chan chunk 0 chunkSize with Invalid_argument _ -> 0 in if len == 0 then ( close_in_noerr chan; Buffer.contents buffer) else ( Buffer.add_subbytes buffer chunk 0 len; loop ()) in loop () end module Time : sig type t val now : unit -> t val toUint64 : t -> int64 [@@live] let = ns val nanosecond : t [@@live] val microsecond : t [@@live] val millisecond : t [@@live] val second : t [@@live] val minute : t [@@live] val hour : t [@@live] val zero : t val diff : t -> t -> t val add : t -> t -> t val print : t -> float end = struct (* nanoseconds *) type t = int64 let zero = 0L let toUint64 s = s let nanosecond = 1L let microsecond = Int64.mul 1000L nanosecond let millisecond = Int64.mul 1000L microsecond let second = Int64.mul 1000L millisecond let minute = Int64.mul 60L second let hour = Int64.mul 60L minute TODO : we could do this inside caml_absolute_time external init : unit -> unit = "caml_mach_initialize" let () = init () external now : unit -> t = "caml_mach_absolute_time" let diff t1 t2 = Int64.sub t2 t1 let add t1 t2 = Int64.add t1 t2 let print t = Int64.to_float t *. 1e-6 end module Benchmark : sig type t val make : name:string -> f:(t -> unit) -> unit -> t val launch : t -> unit val report : t -> unit end = struct type t = { name: string; mutable start: Time.t; mutable n: int; (* current iterations count *) mutable duration: Time.t; benchFunc: t -> unit; mutable timerOn: bool; mutable result : benchmarkResult ; (* The initial states *) mutable startAllocs: float; mutable startBytes: float; (* The net total of this test after being run. *) mutable netAllocs: float; mutable netBytes: float; } let report b = print_endline (Format.sprintf "Benchmark: %s" b.name); print_endline (Format.sprintf "Nbr of iterations: %d" b.n); print_endline (Format.sprintf "Benchmark ran during: %fms" (Time.print b.duration)); print_endline (Format.sprintf "Avg time/op: %fms" (Time.print b.duration /. float_of_int b.n)); print_endline (Format.sprintf "Allocs/op: %d" (int_of_float (b.netAllocs /. float_of_int b.n))); print_endline (Format.sprintf "B/op: %d" (int_of_float (b.netBytes /. float_of_int b.n))); (* return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds() *) print_newline (); () let make ~name ~f () = { name; start = Time.zero; n = 0; benchFunc = f; duration = Time.zero; timerOn = false; startAllocs = 0.; startBytes = 0.; netAllocs = 0.; netBytes = 0.; } (* total amount of memory allocated by the program since it started in words *) let mallocs () = let stats = Gc.quick_stat () in stats.minor_words +. stats.major_words -. stats.promoted_words let startTimer b = if not b.timerOn then ( let allocatedWords = mallocs () in b.startAllocs <- allocatedWords; b.startBytes <- allocatedWords *. 8.; b.start <- Time.now (); b.timerOn <- true) let stopTimer b = if b.timerOn then ( let allocatedWords = mallocs () in let diff = Time.diff b.start (Time.now ()) in b.duration <- Time.add b.duration diff; b.netAllocs <- b.netAllocs +. (allocatedWords -. b.startAllocs); b.netBytes <- b.netBytes +. ((allocatedWords *. 8.) -. b.startBytes); b.timerOn <- false) let resetTimer b = if b.timerOn then ( let allocatedWords = mallocs () in b.startAllocs <- allocatedWords; b.netAllocs <- allocatedWords *. 8.; b.start <- Time.now ()); b.netAllocs <- 0.; b.netBytes <- 0. let runIteration b n = Gc.full_major (); b.n <- n; resetTimer b; startTimer b; b.benchFunc b; stopTimer b let launch b = 150 runs * all the benchmarks means around 1 m of benchmark time for n = 1 to 150 do runIteration b n done end module Benchmarks : sig val run : unit -> unit end = struct type action = Parse | Print let string_of_action action = match action with | Parse -> "parser" | Print -> "printer" (* TODO: we could at Reason here *) type lang = Ocaml | Rescript let string_of_lang lang = match lang with | Ocaml -> "ocaml" | Rescript -> "rescript" let parseOcaml src filename = let lexbuf = Lexing.from_string src in Location.init lexbuf filename; Parse.implementation lexbuf let parseRescript src filename = let p = Parser.make src filename in let structure = ResParser.parseImplementation p in assert (p.diagnostics == []); structure let benchmark filename lang action = let src = IO.readFile filename in let name = filename ^ " " ^ string_of_lang lang ^ " " ^ string_of_action action in let benchmarkFn = match (lang, action) with | Rescript, Parse -> fun _ -> let _ = Sys.opaque_identity (parseRescript src filename) in () | Ocaml, Parse -> fun _ -> let _ = Sys.opaque_identity (parseOcaml src filename) in () | Rescript, Print -> let p = Parser.make src filename in let ast = ResParser.parseImplementation p in fun _ -> let _ = Sys.opaque_identity (let cmtTbl = CommentTable.make () in let comments = List.rev p.Parser.comments in let () = CommentTable.walkStructure ast cmtTbl comments in Doc.toString ~width:80 (Printer.printStructure ast cmtTbl)) in () | _ -> fun _ -> () in let b = Benchmark.make ~name ~f:benchmarkFn () in Benchmark.launch b; Benchmark.report b let run () = benchmark "./benchmarks/data/RedBlackTree.res" Rescript Parse; benchmark "./benchmarks/data/RedBlackTree.ml" Ocaml Parse; benchmark "./benchmarks/data/RedBlackTree.res" Rescript Print; benchmark "./benchmarks/data/RedBlackTreeNoComments.res" Rescript Print; benchmark "./benchmarks/data/Napkinscript.res" Rescript Parse; benchmark "./benchmarks/data/Napkinscript.ml" Ocaml Parse; benchmark "./benchmarks/data/Napkinscript.res" Rescript Print; benchmark "./benchmarks/data/HeroGraphic.res" Rescript Parse; benchmark "./benchmarks/data/HeroGraphic.ml" Ocaml Parse; benchmark "./benchmarks/data/HeroGraphic.res" Rescript Print end let () = Benchmarks.run ()
null
https://raw.githubusercontent.com/rescript-lang/syntax/67fec537284579e58bee8e70120bff8e03688fa8/benchmarks/Benchmark.ml
ocaml
nanoseconds current iterations count The initial states The net total of this test after being run. return (float64(r.Bytes) * float64(r.N) / 1e6) / r.T.Seconds() total amount of memory allocated by the program since it started in words TODO: we could at Reason here
module ResParser = Res_core module Doc = Res_doc module CommentTable = Res_comments_table module Parser = Res_parser module Printer = Res_printer module IO : sig val readFile : string -> string end = struct random chunk size : 2 ^ 15 , TODO : why do we guess randomly ? let chunkSize = 32768 let readFile filename = let chan = open_in filename in let buffer = Buffer.create chunkSize in let chunk = (Bytes.create [@doesNotRaise]) chunkSize in let rec loop () = let len = try input chan chunk 0 chunkSize with Invalid_argument _ -> 0 in if len == 0 then ( close_in_noerr chan; Buffer.contents buffer) else ( Buffer.add_subbytes buffer chunk 0 len; loop ()) in loop () end module Time : sig type t val now : unit -> t val toUint64 : t -> int64 [@@live] let = ns val nanosecond : t [@@live] val microsecond : t [@@live] val millisecond : t [@@live] val second : t [@@live] val minute : t [@@live] val hour : t [@@live] val zero : t val diff : t -> t -> t val add : t -> t -> t val print : t -> float end = struct type t = int64 let zero = 0L let toUint64 s = s let nanosecond = 1L let microsecond = Int64.mul 1000L nanosecond let millisecond = Int64.mul 1000L microsecond let second = Int64.mul 1000L millisecond let minute = Int64.mul 60L second let hour = Int64.mul 60L minute TODO : we could do this inside caml_absolute_time external init : unit -> unit = "caml_mach_initialize" let () = init () external now : unit -> t = "caml_mach_absolute_time" let diff t1 t2 = Int64.sub t2 t1 let add t1 t2 = Int64.add t1 t2 let print t = Int64.to_float t *. 1e-6 end module Benchmark : sig type t val make : name:string -> f:(t -> unit) -> unit -> t val launch : t -> unit val report : t -> unit end = struct type t = { name: string; mutable start: Time.t; mutable duration: Time.t; benchFunc: t -> unit; mutable timerOn: bool; mutable result : benchmarkResult ; mutable startAllocs: float; mutable startBytes: float; mutable netAllocs: float; mutable netBytes: float; } let report b = print_endline (Format.sprintf "Benchmark: %s" b.name); print_endline (Format.sprintf "Nbr of iterations: %d" b.n); print_endline (Format.sprintf "Benchmark ran during: %fms" (Time.print b.duration)); print_endline (Format.sprintf "Avg time/op: %fms" (Time.print b.duration /. float_of_int b.n)); print_endline (Format.sprintf "Allocs/op: %d" (int_of_float (b.netAllocs /. float_of_int b.n))); print_endline (Format.sprintf "B/op: %d" (int_of_float (b.netBytes /. float_of_int b.n))); print_newline (); () let make ~name ~f () = { name; start = Time.zero; n = 0; benchFunc = f; duration = Time.zero; timerOn = false; startAllocs = 0.; startBytes = 0.; netAllocs = 0.; netBytes = 0.; } let mallocs () = let stats = Gc.quick_stat () in stats.minor_words +. stats.major_words -. stats.promoted_words let startTimer b = if not b.timerOn then ( let allocatedWords = mallocs () in b.startAllocs <- allocatedWords; b.startBytes <- allocatedWords *. 8.; b.start <- Time.now (); b.timerOn <- true) let stopTimer b = if b.timerOn then ( let allocatedWords = mallocs () in let diff = Time.diff b.start (Time.now ()) in b.duration <- Time.add b.duration diff; b.netAllocs <- b.netAllocs +. (allocatedWords -. b.startAllocs); b.netBytes <- b.netBytes +. ((allocatedWords *. 8.) -. b.startBytes); b.timerOn <- false) let resetTimer b = if b.timerOn then ( let allocatedWords = mallocs () in b.startAllocs <- allocatedWords; b.netAllocs <- allocatedWords *. 8.; b.start <- Time.now ()); b.netAllocs <- 0.; b.netBytes <- 0. let runIteration b n = Gc.full_major (); b.n <- n; resetTimer b; startTimer b; b.benchFunc b; stopTimer b let launch b = 150 runs * all the benchmarks means around 1 m of benchmark time for n = 1 to 150 do runIteration b n done end module Benchmarks : sig val run : unit -> unit end = struct type action = Parse | Print let string_of_action action = match action with | Parse -> "parser" | Print -> "printer" type lang = Ocaml | Rescript let string_of_lang lang = match lang with | Ocaml -> "ocaml" | Rescript -> "rescript" let parseOcaml src filename = let lexbuf = Lexing.from_string src in Location.init lexbuf filename; Parse.implementation lexbuf let parseRescript src filename = let p = Parser.make src filename in let structure = ResParser.parseImplementation p in assert (p.diagnostics == []); structure let benchmark filename lang action = let src = IO.readFile filename in let name = filename ^ " " ^ string_of_lang lang ^ " " ^ string_of_action action in let benchmarkFn = match (lang, action) with | Rescript, Parse -> fun _ -> let _ = Sys.opaque_identity (parseRescript src filename) in () | Ocaml, Parse -> fun _ -> let _ = Sys.opaque_identity (parseOcaml src filename) in () | Rescript, Print -> let p = Parser.make src filename in let ast = ResParser.parseImplementation p in fun _ -> let _ = Sys.opaque_identity (let cmtTbl = CommentTable.make () in let comments = List.rev p.Parser.comments in let () = CommentTable.walkStructure ast cmtTbl comments in Doc.toString ~width:80 (Printer.printStructure ast cmtTbl)) in () | _ -> fun _ -> () in let b = Benchmark.make ~name ~f:benchmarkFn () in Benchmark.launch b; Benchmark.report b let run () = benchmark "./benchmarks/data/RedBlackTree.res" Rescript Parse; benchmark "./benchmarks/data/RedBlackTree.ml" Ocaml Parse; benchmark "./benchmarks/data/RedBlackTree.res" Rescript Print; benchmark "./benchmarks/data/RedBlackTreeNoComments.res" Rescript Print; benchmark "./benchmarks/data/Napkinscript.res" Rescript Parse; benchmark "./benchmarks/data/Napkinscript.ml" Ocaml Parse; benchmark "./benchmarks/data/Napkinscript.res" Rescript Print; benchmark "./benchmarks/data/HeroGraphic.res" Rescript Parse; benchmark "./benchmarks/data/HeroGraphic.ml" Ocaml Parse; benchmark "./benchmarks/data/HeroGraphic.res" Rescript Print end let () = Benchmarks.run ()
f19c6ec70ebd6c0db47aa2a29cd18d7dd472cb1bc3734be8daa208764f49be5f
CrossRef/event-data-query
end_to_end_test.clj
(ns event-data-query.end-to-end-test "Load Events from an archive, index, query." (:require [clojure.test :refer :all] [event-data-query.elastic :as elastic] [event-data-query.ingest :as ingest] [event-data-query.server :as server] [qbits.spandex :as s] [clj-time.core :as clj-time] [clj-http.fake :as fake] [ring.mock.request :as mock] [config.core :refer [env]] [clojure.data.json :as json])) (defn get-response [url-path message-key] (-> (mock/request :get url-path) server/app :body (json/read-str :key-fn keyword) :message message-key)) (deftest end-to-end (testing "Events ingested and can be ingested from the archive and retrieved from each Events collection." (is (= (-> env :query-deployment) "test_") "Precondition: Expected the QUERY_DEPLOYMENT config to be '_test'.") Do this on the 2nd of January , which will result in querying the archive for the 1st . (clj-time/do-at (clj-time/date-time 2018 01 02 12 00) (with-redefs [ ; We're not filtering anything out in this test. event-data-common.whitelist/filter-events identity Fake out fetching metadata from RAs for Scholix examples . ; These match deposits in the resources/test/end-to-end.json event-data-query.work-cache/get-for-dois (fn [_] {"-9006(99)00007-0" {:content-type "journal-article" :ra "crossref" :doi "10.1016/s0305-9006(99)00007-0"} "-30455" {:content-type "text" :ra "datacite" :doi "10.5167/UZH-30455"}})] Clear the index first if it exists . (try (:status (s/request @elastic/connection {:url "/test_*" :method :delete})) (catch Exception _ nil)) ; Create indexes. (elastic/ensure-indexes) (fake/with-fake-routes-in-isolation { Serve up all test data in the first partition . "-01-01/00" (fn [request] {:status 200 :body (slurp "resources/test/end-to-end.json")}) ; The rest are blank. #"-01-01/.*" (fn [request] {:status 200 :body "[]"})} (ingest/bus-backfill-days (clj-time/now) 1)) ; Force Elastic to wait for indexes. (is (= 200 (:status (s/request @elastic/connection {:url "_refresh" :method :post})))) ; Use both the "events" endpoints and the "events ids" endpoint to check they both return the right selection of Events. (let [standard-events (get-response "/v1/events" :events) distinct-events (get-response "/v1/events/distinct" :events) edited-events (get-response "/v1/events/edited" :events) deleted-events (get-response "/v1/events/deleted" :events) experimental-events (get-response "/v1/events/experimental" :events) scholix-events (get-response "/v1/events/scholix" :link-packages) standard-event-ids (get-response "/v1/events/ids" :event-ids) distinct-event-ids (get-response "/v1/events/distinct/ids" :event-ids) edited-event-ids (get-response "/v1/events/edited/ids" :event-ids) deleted-event-ids (get-response "/v1/events/deleted/ids" :event-ids) experimental-event-ids (get-response "/v1/events/experimental/ids" :event-ids) scholix-event-ids (get-response "/v1/events/scholix/ids" :link-package-ids) Test case - insensitivity in subject and object DOI matching . subj-doi-lower (get-response "/v1/events?subj-id=10.1016%2fs0305-9006(99)00007-0" :events) subj-doi-upper (get-response "/v1/events?subj-id=10.1016%2fS0305-9006(99)00007-0" :events) obj-doi-lower (get-response "/v1/events?obj-id=10.1016%2fs0305-9006(99)00007-0" :events) obj-doi-upper (get-response "/v1/events?obj-id=10.1016%2fS0305-9006(99)00007-0" :events)] (is (= (->> standard-events (map :id) set) (set standard-event-ids) #{ ; Standard 1 "00000000-0000-0000-0000-000000000001" ; Standard 2 "00000000-0000-0000-0000-000000000002" Edited 1 "00000000-0000-0000-0000-000000000005" Edited 2 "00000000-0000-0000-0000-000000000006" Scholix 1 "00000000-0000-0000-0000-000000000009" Scholix 2 "00000000-0000-0000-0000-00000000000a" ; Twitter "00000000-0000-0000-0000-00000000000b"}) "/standard and /standard/ids return the right set of Events") (is (= (->> distinct-events (map :id) set) (set distinct-event-ids) #{ ; Standard 2 "00000000-0000-0000-0000-000000000002" Edited 1 "00000000-0000-0000-0000-000000000005" Edited 2 "00000000-0000-0000-0000-000000000006" Scholix 1 "00000000-0000-0000-0000-000000000009" Scholix 2 "00000000-0000-0000-0000-00000000000a" ; Twitter "00000000-0000-0000-0000-00000000000b"}) "/distinct and /distinct/ids return the right set of Events") (is (= (->> edited-events (map :id) set) (set edited-event-ids) Edited 1 "00000000-0000-0000-0000-000000000005" Edited 2 "00000000-0000-0000-0000-000000000006"}) "/edited and /edited/ids return the right set of Events") (is (= (->> deleted-events (map :id) set) (set deleted-event-ids) Deleted 1 "00000000-0000-0000-0000-000000000007" Deleted 2 "00000000-0000-0000-0000-000000000008"}) "/deleted and /deleted/ids return the right set of Events") (is (= (->> experimental-events (map :id) set) (set experimental-event-ids) #{; Experimental 1 "00000000-0000-0000-0000-000000000003" Experimental 2 "00000000-0000-0000-0000-000000000004"}) "/experimental and /experimental/ids return the right set of Events") (is (= (set scholix-events) #{{:LinkPublicationDate "2018-01-01T00:01:01Z", :LinkProvider [{:Name "crossref"}], :RelationshipType {:Name "References"}, :LicenseURL "/", :Url "-0000-0000-0000-00000000000a", :Source {:Identifier {:ID "10.1016/s0305-9006(99)00007-0", :IDScheme "DOI", :IDUrl "-9006(99)00007-0"}, :Type {:Name "literature", :SubType "journal-article", :SubTypeSchema "crossref"}}, :Target {:Identifier {:ID "10.5167/UZH-30455", :IDScheme "DOI", :IDUrl "-30455"}, :Type {:Name "literature", :SubType "text", :SubTypeSchema "datacite"}}} {:LinkPublicationDate "2018-01-01T00:01:01Z", :LinkProvider [{:Name "datacite"}], :RelationshipType {:Name "IsReferencedBy"}, :LicenseURL "/", :Url "-0000-0000-0000-000000000009", :Source {:Identifier {:ID "10.5167/UZH-30455", :IDScheme "DOI", :IDUrl "-30455"}, :Type {:Name "literature", :SubType "text", :SubTypeSchema "datacite"}}, :Target {:Identifier {:ID "10.1016/s0305-9006(99)00007-0", :IDScheme "DOI", :IDUrl "-9006(99)00007-0"}, :Type {:Name "literature", :SubType "journal-article", :SubTypeSchema "crossref"}}}})) (is (= subj-doi-lower subj-doi-upper) "subj-id query should return the same, case invariant") (is (= obj-doi-lower obj-doi-upper) "subj-id query should return the same, case invariant"))))))
null
https://raw.githubusercontent.com/CrossRef/event-data-query/ede3c91afccd89dbb7053e81dd425bc3c3ad966a/test/event_data_query/end_to_end_test.clj
clojure
We're not filtering anything out in this test. These match deposits in the resources/test/end-to-end.json Create indexes. The rest are blank. Force Elastic to wait for indexes. Use both the "events" endpoints and the "events ids" endpoint to check they both return the right selection of Events. Standard 1 Standard 2 Twitter Standard 2 Twitter Experimental 1
(ns event-data-query.end-to-end-test "Load Events from an archive, index, query." (:require [clojure.test :refer :all] [event-data-query.elastic :as elastic] [event-data-query.ingest :as ingest] [event-data-query.server :as server] [qbits.spandex :as s] [clj-time.core :as clj-time] [clj-http.fake :as fake] [ring.mock.request :as mock] [config.core :refer [env]] [clojure.data.json :as json])) (defn get-response [url-path message-key] (-> (mock/request :get url-path) server/app :body (json/read-str :key-fn keyword) :message message-key)) (deftest end-to-end (testing "Events ingested and can be ingested from the archive and retrieved from each Events collection." (is (= (-> env :query-deployment) "test_") "Precondition: Expected the QUERY_DEPLOYMENT config to be '_test'.") Do this on the 2nd of January , which will result in querying the archive for the 1st . (clj-time/do-at (clj-time/date-time 2018 01 02 12 00) (with-redefs [ event-data-common.whitelist/filter-events identity Fake out fetching metadata from RAs for Scholix examples . event-data-query.work-cache/get-for-dois (fn [_] {"-9006(99)00007-0" {:content-type "journal-article" :ra "crossref" :doi "10.1016/s0305-9006(99)00007-0"} "-30455" {:content-type "text" :ra "datacite" :doi "10.5167/UZH-30455"}})] Clear the index first if it exists . (try (:status (s/request @elastic/connection {:url "/test_*" :method :delete})) (catch Exception _ nil)) (elastic/ensure-indexes) (fake/with-fake-routes-in-isolation { Serve up all test data in the first partition . "-01-01/00" (fn [request] {:status 200 :body (slurp "resources/test/end-to-end.json")}) #"-01-01/.*" (fn [request] {:status 200 :body "[]"})} (ingest/bus-backfill-days (clj-time/now) 1)) (is (= 200 (:status (s/request @elastic/connection {:url "_refresh" :method :post})))) (let [standard-events (get-response "/v1/events" :events) distinct-events (get-response "/v1/events/distinct" :events) edited-events (get-response "/v1/events/edited" :events) deleted-events (get-response "/v1/events/deleted" :events) experimental-events (get-response "/v1/events/experimental" :events) scholix-events (get-response "/v1/events/scholix" :link-packages) standard-event-ids (get-response "/v1/events/ids" :event-ids) distinct-event-ids (get-response "/v1/events/distinct/ids" :event-ids) edited-event-ids (get-response "/v1/events/edited/ids" :event-ids) deleted-event-ids (get-response "/v1/events/deleted/ids" :event-ids) experimental-event-ids (get-response "/v1/events/experimental/ids" :event-ids) scholix-event-ids (get-response "/v1/events/scholix/ids" :link-package-ids) Test case - insensitivity in subject and object DOI matching . subj-doi-lower (get-response "/v1/events?subj-id=10.1016%2fs0305-9006(99)00007-0" :events) subj-doi-upper (get-response "/v1/events?subj-id=10.1016%2fS0305-9006(99)00007-0" :events) obj-doi-lower (get-response "/v1/events?obj-id=10.1016%2fs0305-9006(99)00007-0" :events) obj-doi-upper (get-response "/v1/events?obj-id=10.1016%2fS0305-9006(99)00007-0" :events)] (is (= (->> standard-events (map :id) set) (set standard-event-ids) "00000000-0000-0000-0000-000000000001" "00000000-0000-0000-0000-000000000002" Edited 1 "00000000-0000-0000-0000-000000000005" Edited 2 "00000000-0000-0000-0000-000000000006" Scholix 1 "00000000-0000-0000-0000-000000000009" Scholix 2 "00000000-0000-0000-0000-00000000000a" "00000000-0000-0000-0000-00000000000b"}) "/standard and /standard/ids return the right set of Events") (is (= (->> distinct-events (map :id) set) (set distinct-event-ids) "00000000-0000-0000-0000-000000000002" Edited 1 "00000000-0000-0000-0000-000000000005" Edited 2 "00000000-0000-0000-0000-000000000006" Scholix 1 "00000000-0000-0000-0000-000000000009" Scholix 2 "00000000-0000-0000-0000-00000000000a" "00000000-0000-0000-0000-00000000000b"}) "/distinct and /distinct/ids return the right set of Events") (is (= (->> edited-events (map :id) set) (set edited-event-ids) Edited 1 "00000000-0000-0000-0000-000000000005" Edited 2 "00000000-0000-0000-0000-000000000006"}) "/edited and /edited/ids return the right set of Events") (is (= (->> deleted-events (map :id) set) (set deleted-event-ids) Deleted 1 "00000000-0000-0000-0000-000000000007" Deleted 2 "00000000-0000-0000-0000-000000000008"}) "/deleted and /deleted/ids return the right set of Events") (is (= (->> experimental-events (map :id) set) (set experimental-event-ids) "00000000-0000-0000-0000-000000000003" Experimental 2 "00000000-0000-0000-0000-000000000004"}) "/experimental and /experimental/ids return the right set of Events") (is (= (set scholix-events) #{{:LinkPublicationDate "2018-01-01T00:01:01Z", :LinkProvider [{:Name "crossref"}], :RelationshipType {:Name "References"}, :LicenseURL "/", :Url "-0000-0000-0000-00000000000a", :Source {:Identifier {:ID "10.1016/s0305-9006(99)00007-0", :IDScheme "DOI", :IDUrl "-9006(99)00007-0"}, :Type {:Name "literature", :SubType "journal-article", :SubTypeSchema "crossref"}}, :Target {:Identifier {:ID "10.5167/UZH-30455", :IDScheme "DOI", :IDUrl "-30455"}, :Type {:Name "literature", :SubType "text", :SubTypeSchema "datacite"}}} {:LinkPublicationDate "2018-01-01T00:01:01Z", :LinkProvider [{:Name "datacite"}], :RelationshipType {:Name "IsReferencedBy"}, :LicenseURL "/", :Url "-0000-0000-0000-000000000009", :Source {:Identifier {:ID "10.5167/UZH-30455", :IDScheme "DOI", :IDUrl "-30455"}, :Type {:Name "literature", :SubType "text", :SubTypeSchema "datacite"}}, :Target {:Identifier {:ID "10.1016/s0305-9006(99)00007-0", :IDScheme "DOI", :IDUrl "-9006(99)00007-0"}, :Type {:Name "literature", :SubType "journal-article", :SubTypeSchema "crossref"}}}})) (is (= subj-doi-lower subj-doi-upper) "subj-id query should return the same, case invariant") (is (= obj-doi-lower obj-doi-upper) "subj-id query should return the same, case invariant"))))))
5cb0402482211ae020f7e6d7842225a6dae0e93affd1263d94033a2d0370f266
jnavila/plotkicadsch
listPainter.ml
open Kicadsch.Sigs type image_data = Buffer.t type t = | Text of kolor * string * orientation * coord * size * justify * style | Line of kolor * size * coord * coord | Rect of kolor * kolor * coord * coord | Circle of kolor * kolor * coord * int | Arc of kolor * kolor * coord * coord * coord * int | Image of coord * float * image_data | Format of coord | Zone of coord * coord type listcanevas = t list module L = struct type t = listcanevas type painterContext = listcanevas let paint_text ?(kolor = `Black) text (o : orientation) coords s j stl ctx = Text (kolor, text, o, coords, s, j, stl) :: ctx let paint_line ?(kolor = `Black) ?(width = Size 2) pt_start pt_end ctx = Line (kolor, width, pt_start, pt_end) :: ctx let paint_rect ?(kolor = `Black) ?(fill = `NoColor) pt dims ctx = Rect (kolor, fill, pt, dims) :: ctx let paint_circle ?(kolor = `Black) ?(fill = `NoColor) center radius ctx = Circle (kolor, fill, center, radius) :: ctx let paint_arc ?(kolor = `Black) ?(fill = `NoColor) pt_center pt_start pt_stop radius ctx = Arc (kolor, fill, pt_center, pt_start, pt_stop, radius) :: ctx let paint_image corner scale b c = Image (corner, scale, b) :: c let get_context () = [] let set_canevas_size x y c = Format (Coord (x, y)) :: c end
null
https://raw.githubusercontent.com/jnavila/plotkicadsch/a8afb216bf04aeaeb9088ef264407b094553d145/plotkicadsch/src/listPainter.ml
ocaml
open Kicadsch.Sigs type image_data = Buffer.t type t = | Text of kolor * string * orientation * coord * size * justify * style | Line of kolor * size * coord * coord | Rect of kolor * kolor * coord * coord | Circle of kolor * kolor * coord * int | Arc of kolor * kolor * coord * coord * coord * int | Image of coord * float * image_data | Format of coord | Zone of coord * coord type listcanevas = t list module L = struct type t = listcanevas type painterContext = listcanevas let paint_text ?(kolor = `Black) text (o : orientation) coords s j stl ctx = Text (kolor, text, o, coords, s, j, stl) :: ctx let paint_line ?(kolor = `Black) ?(width = Size 2) pt_start pt_end ctx = Line (kolor, width, pt_start, pt_end) :: ctx let paint_rect ?(kolor = `Black) ?(fill = `NoColor) pt dims ctx = Rect (kolor, fill, pt, dims) :: ctx let paint_circle ?(kolor = `Black) ?(fill = `NoColor) center radius ctx = Circle (kolor, fill, center, radius) :: ctx let paint_arc ?(kolor = `Black) ?(fill = `NoColor) pt_center pt_start pt_stop radius ctx = Arc (kolor, fill, pt_center, pt_start, pt_stop, radius) :: ctx let paint_image corner scale b c = Image (corner, scale, b) :: c let get_context () = [] let set_canevas_size x y c = Format (Coord (x, y)) :: c end
7deae67f8054cff836a0692017a225611825e18a8fc2c73f225fdc4826ac5262
janestreet/memtrace_viewer
filtered_trace.mli
open! Core open Memtrace_viewer_common module Event : sig type t = Location.t Event.t [@@deriving sexp_of] end type t val create : trace:Raw_trace.t -> loc_cache:Location.Cache.t -> filter:Filter.t -> t val word_size : t -> Byte_units.t val sample_rate : t -> float module Mode : sig type t = | Preserve_backtraces (** Events will have backtraces but may not be in the right order and may not have accurate timestamps *) | Preserve_times (** Events will come in the correct order, with accurate times, but have empty backtraces *) end val iter : t -> mode:Mode.t -> (Time_ns.Span.t -> Event.t -> unit) -> unit module Call_sites : sig module Callees_from_call_site : sig type t = Location.Hash_set.t end module Calls_from_location : sig type t = Callees_from_call_site.t Call_site.Table.t end type t = Calls_from_location.t Location.Table.t end val iter_and_gather_call_sites : t -> mode:Mode.t -> (Time_ns.Span.t -> Event.t -> unit) -> Call_sites.t
null
https://raw.githubusercontent.com/janestreet/memtrace_viewer/46439f8bd16e77c5aa38632c9c4aa53175121d4d/server/src/filtered_trace.mli
ocaml
* Events will have backtraces but may not be in the right order and may not have accurate timestamps * Events will come in the correct order, with accurate times, but have empty backtraces
open! Core open Memtrace_viewer_common module Event : sig type t = Location.t Event.t [@@deriving sexp_of] end type t val create : trace:Raw_trace.t -> loc_cache:Location.Cache.t -> filter:Filter.t -> t val word_size : t -> Byte_units.t val sample_rate : t -> float module Mode : sig type t = | Preserve_backtraces | Preserve_times end val iter : t -> mode:Mode.t -> (Time_ns.Span.t -> Event.t -> unit) -> unit module Call_sites : sig module Callees_from_call_site : sig type t = Location.Hash_set.t end module Calls_from_location : sig type t = Callees_from_call_site.t Call_site.Table.t end type t = Calls_from_location.t Location.Table.t end val iter_and_gather_call_sites : t -> mode:Mode.t -> (Time_ns.Span.t -> Event.t -> unit) -> Call_sites.t
e62212e400daab93d9d8456c172de22374e8fbeda8e8f1303d9ded4ac6392a3a
tomhanika/conexp-clj
contexts.clj
;; Copyright ⓒ the conexp-clj developers; 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 LICENSE 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 conexp.io.contexts (:require [conexp.base :refer :all] [conexp.fca.contexts :refer :all] [conexp.io.util :refer :all] [conexp.fca.many-valued-contexts :refer :all] [conexp.io.latex :refer :all] [conexp.io.json :refer :all] [clojure.string :refer (split)] [clojure.data.xml :as xml] [clojure.data.json :as json] [json-schema.core :as json-schema] [clojure.data.csv :as csv] [clojure.java.io :as io]) (:import [java.io PushbackReader])) ;;; Input format dispatch (define-format-dispatch "context") (set-default-context-format! :simple) ;;; Formats ;; Simple conexp-clj Format (add-context-input-format :simple (fn [rdr] (= "conexp-clj simple" (read-line)))) (define-context-output-format :simple [ctx file] (with-out-writer file (binding [*print-length* nil] (println "conexp-clj simple") (prn {:context [(objects ctx) (attributes ctx) (incidence-relation ctx)]})))) (define-context-input-format :simple [file] (with-in-reader file (let [_ (get-line) hash-map (binding [*in* (PushbackReader. *in*)] (read)), context (:context hash-map)] (when-not context (unsupported-operation "File " file " does not contain a context.")) (apply make-context context)))) (add-context-input-format :burmeister (fn [rdr] (= "B" (read-line)))) (define-context-output-format :burmeister [ctx file] (with-out-writer file (println \B) (println) (println (count (objects ctx))) (println (count (attributes ctx))) (println) (doseq [g (objects ctx)] (println g)) (doseq [m (attributes ctx)] (println m)) (let [inz (incidence ctx)] (doseq [g (objects ctx)] (doseq [m (attributes ctx)] (print (if (inz [g m]) "X" "."))) (println))))) (define-context-input-format :burmeister [file] (with-in-reader file " B\n\n " , we do n't support names number-of-objects (Integer/parseInt (.trim (get-line))) number-of-attributes (Integer/parseInt (.trim (get-line))) _ (get-line) ; "\n" seq-of-objects (get-lines number-of-objects) seq-of-attributes (get-lines number-of-attributes)] (loop [objs seq-of-objects incidence #{}] (if (empty? objs) (make-context-nc (set seq-of-objects) (set seq-of-attributes) incidence) (let [line (get-line)] (recur (rest objs) (into incidence (for [idx-m (range number-of-attributes) :when (#{\X,\x} (nth line idx-m))] [(first objs) (nth seq-of-attributes idx-m)]))))))))) , aka without names (add-context-input-format :anonymous-burmeister (fn [rdr] (= "A" (read-line)))) (define-context-output-format :anonymous-burmeister [ctx file] (with-out-writer file (println \A) (println (count (objects ctx))) (println (count (attributes ctx))) (let [inz (incidence ctx)] (doseq [g (objects ctx)] (doseq [m (attributes ctx)] (print (if (inz [g m]) "X" "."))) (println))))) (define-context-input-format :anonymous-burmeister [file] (with-in-reader file (let [_ (get-lines 1), ; "A\n" number-of-objects (Integer/parseInt (.trim (get-line))), number-of-attributes (Integer/parseInt (.trim (get-line))), seq-of-objects (range number-of-objects), seq-of-attributes (range number-of-attributes)] (loop [objs seq-of-objects incidence #{}] (if (empty? objs) (make-context-nc (set seq-of-objects) (set seq-of-attributes) incidence) (let [line (get-line)] (recur (rest objs) (into incidence (for [idx-m (range number-of-attributes) :when (#{\X,\x} (nth line idx-m))] [(first objs) (nth seq-of-attributes idx-m)]))))))))) ;; XML helpers (defn- find-tags [seq-of-hashes tag] (for [hash seq-of-hashes :when (= tag (:tag hash))] hash)) (defn- find-tag [seq-of-hashes tag] (first (find-tags seq-of-hashes tag))) (defn- trim [^String str] (.trim str)) (defn- hash-from-pairs [pairs] (into {} pairs)) ;; ConExp (add-context-input-format :conexp (fn [rdr] (try (= :ConceptualSystem (-> (xml/parse rdr) :tag)) (catch Exception _)))) (define-context-input-format :conexp [file] (with-in-reader file (let [xml-tree (xml/parse *in*) contexts (:content (first (find-tags (:content xml-tree) :Contexts)))] (cond (= 0 (count contexts)) (throw (IllegalArgumentException. (str "No context specified in " file))) (< 1 (count contexts)) (throw (IllegalArgumentException. (str "More than one context specified in " file)))) (let [context (first contexts) atts-map (find-tag (:content context) :Attributes) objs-map (find-tag (:content context) :Objects) obj-idxs-map (hash-from-pairs (for [obj-map (:content objs-map)] [(apply str (-> obj-map :content (find-tag :Name) :content)) (set-of (get-in att [:attrs :AttributeIdentifier]) [att (-> obj-map :content (find-tag :Intent) :content)])])) idx-atts-map (hash-from-pairs (for [att-map (:content atts-map)] [(get-in att-map [:attrs :Identifier]) (apply str (-> att-map :content (find-tag :Name) :content))]))] (assert (distinct? (vals idx-atts-map)) "Names of attributes must be different.") (make-context-nc (set (keys obj-idxs-map)) (set (vals idx-atts-map)) (set-of [g (idx-atts-map idx) ] [[g att-idxs] obj-idxs-map idx att-idxs])))))) (defn- ctx->xml-vector [ctx id] (let [ctx-atts (zipmap (attributes ctx) (iterate inc 0)) ctx-objs (objects ctx) attributes (vector :Attributes (map (fn [[att id]] [:Attribute {:Identifier id} [:Name att]]) ctx-atts)) objects (vector :Objects (for [obj ctx-objs] [:Object [:Name obj] (vector :Intent (for [att (object-derivation ctx #{obj})] [:HasAttribute {:AttributeIdentifier (ctx-atts att)}]))]))] [:Context {:Identifier "0", :Type "Binary"} attributes objects])) (define-context-output-format :conexp [ctx file] (with-out-writer file (xml/emit (xml/sexp-as-element [:ConceptualSystem [:Version {:MajorNumber "1", :MinorNumber "0"}] [:Contexts (ctx->xml-vector ctx 0)]]) *out*))) ;; Galicia (.bin.xml) (add-context-input-format :galicia (fn [rdr] (try (let [xml-tree (xml/parse rdr)] (and (= :Galicia_Document (-> xml-tree :tag)) (= :BinaryContext (-> xml-tree :content first :tag)))) (catch Exception _)))) (define-context-output-format :galicia [ctx file] (let [atts (apply hash-map (interleave (attributes ctx) (iterate inc 0))) objs (apply hash-map (interleave (objects ctx) (iterate inc 0))) atts-vector (sort #(< (atts %1) (atts %2)) (attributes ctx)) objs-vector (sort #(< (objs %1) (objs %2)) (objects ctx))] (with-out-writer file (xml/emit (xml/sexp-as-element [:Galicia_Document [:BinaryContext {:numberObj (str (count objs-vector)), :numberAtt (str (count atts-vector))} [:Name "conexp-clj generated context"] (for [obj objs-vector] [:Object obj]) (for [att atts-vector] [:Attribute att]) (for [[g m] (incidence-relation ctx)] [:BinRel {:idxO (str (objs g)), :idxA (str (atts m))}])]]) *out*)))) (define-context-input-format :galicia [file] (with-in-reader file (let [ctx-xml-tree (-> (xml/parse *in*) :content first) nr-objs (Integer/parseInt (-> ctx-xml-tree :attrs :numberObj)) nr-atts (Integer/parseInt (-> ctx-xml-tree :attrs :numberAtt)) can be done better ( one run instead of three ) objs (map (comp first :content) (filter #(= (:tag %) :Object) (-> ctx-xml-tree :content))) atts (map (comp first :content) (filter #(= (:tag %) :Attribute) (-> ctx-xml-tree :content))) idxs (map #(vector (Integer/parseInt (:idxO (:attrs %))) (Integer/parseInt (:idxA (:attrs %)))) (filter #(= (:tag %) :BinRel) (-> ctx-xml-tree :content)))] (make-context-nc objs atts (set-of [(nth objs idxO) (nth atts idxA)] [[idxO idxA] idxs]))))) ;; Colibri (.bri, .con) (add-context-input-format :colibri (fn [rdr] (let [comment #"^\s*#.*$" blank #"^\s*$" row #"^\s*.+\s*:.*;\s*$"] (forall [line (line-seq rdr)] (or (re-matches comment line) (re-matches blank line) (re-matches row line)))))) (define-context-output-format :colibri [ctx file] (when (some (fn [m] (and (string? m) (some #(#{\ ,\:,\;} %) m))) (attributes ctx)) (unsupported-operation "Cannot export to :colibri format, object or attribute names contain invalid characters.")) (when (not (empty? (difference (attributes ctx) (set-of m [[g m] (incidence-relation ctx)])))) (unsupported-operation "Cannot export to :colibri format, context contains empty columns.")) (with-out-writer file (doseq [g (objects ctx)] (print g) (print ":") (doseq [m (object-derivation ctx #{g})] (print "\t") (print m)) (print ";\n")))) (define-context-input-format :colibri [file] (with-in-reader file (loop [objs #{}, inz #{}] (let [line (read-line)] (cond (not line) (make-context-nc objs (set-of m [[g m] inz]) inz), (or (re-matches #"^\s*$" line) ; blank (re-matches #"^\s*#.*$" line)) ; comment (recur objs inz), :else (let [[_ g atts] (re-matches #"^\s*(.+)\s*:\s*(.+)?\s*;\s*(?:#.*)?$" line) atts (and atts (split atts #"\s+"))] (recur (conj objs g) (union inz (set-of [g m] [m atts]))))))))) Comma Seperated Values ( .csv ) (add-context-input-format :csv (fn [rdr] (try (let [first-line (read-line)] (and (re-matches #"^[^,]+,[^,]+$" first-line) ;; do not read empty json context as csv (not= first-line "{\"objectsn:[],\"attributes\":[],\"incidence\":[]}"))) (catch Exception _)))) (define-context-input-format :csv [file] (with-open [reader (io/reader file)] (let [csv-list (doall (csv/read-csv reader)) obj (set (map first csv-list)) attr (set (map second csv-list)) incidence (set csv-list)] (make-context-nc obj attr incidence)))) (define-context-output-format :csv [ctx file] (when (some (fn [x] (and (string? x) (some #(= \, %) x))) (concat (objects ctx) (attributes ctx))) (unsupported-operation "Cannot export to :csv format, object or attribute names contain \",\".")) (with-open [writer (io/writer file)] (csv/write-csv writer (incidence-relation ctx)))) ;; Binary CSV (:binary-csv) (add-context-input-format :binary-csv (fn [rdr] (= "binary CSV" (read-line)))) (define-context-input-format :binary-csv [file] (with-open [reader (io/reader file)] remove the first element [ binary CSV ] (doall (csv/read-csv reader))) num-objects (count csv-list) num-attributes (count (first csv-list)) incidences (map #(Integer/parseInt %) (into [] (apply concat csv-list)))] (make-context-from-matrix num-objects num-attributes incidences)))) (define-context-output-format :binary-csv [ctx file] (when (or (empty? (objects ctx)) (empty? (attributes ctx))) (unsupported-operation "Cannot export empty context in binary-csv format")) (when (some (fn [x] (and (string? x) (some #(= \, %) x))) (concat (objects ctx) (attributes ctx))) (unsupported-operation "Cannot export to :binary-csv format, object or attribute names contain \",\".")) (let [objs (sort (objects ctx)), atts (sort (attributes ctx)) output-matrix (for [obj objs] (for [att atts] (if (incident? ctx obj att) 1 0)))] (with-open [writer (io/writer file)] (csv/write-csv writer add " binary CSV as first line of output )))) (add-context-input-format :named-binary-csv (fn [rdr] (try (= "NB" (subs (read-line) 0 2)) ;; if file is empty, read-line returns nil (catch NullPointerException _) first line of file can contain less than 2 characters (catch StringIndexOutOfBoundsException _)))) (define-context-input-format :named-binary-csv [file] (with-open [reader (io/reader file)] (let [csv-list (doall (csv/read-csv reader))] (let [M ((comp rest first) csv-list) rows (rest csv-list) G (reduce (fn [s row] (conj s (first row))) [] rows) I (reduce (fn [s row] (into s (map #(Integer/parseInt %) (rest row)))) [] rows)] (make-context-from-matrix G M I))))) (define-context-output-format :named-binary-csv [ctx file] (when (or (empty? (objects ctx)) (empty? (attributes ctx))) (unsupported-operation "Cannot export empty context in named-binary-csv format")) (when (some (fn [x] (and (string? x) (some #(= \, %) x))) (concat (objects ctx) (attributes ctx))) (unsupported-operation "Cannot export to :named-binary-csv format, object or attribute names contain \",\".")) (let [objs (sort (objects ctx)), atts (sort (attributes ctx)) output-matrix (conj (for [obj objs] (into [obj] (for [att atts] (if (incident? ctx obj att) 1 0)))) (into ["NB"] atts))] (with-open [writer (io/writer file)] (csv/write-csv writer output-matrix)))) ;; output as tex array (define-context-output-format :tex [ctx file] (with-out-writer file (println (latex ctx)))) ;; fcalgs (add-context-input-format :fcalgs (fn [rdr] (try (forall [line (line-seq rdr), x line] (or (= x \space) (Character/isDigit ^Character x))) (catch Exception _ false)))) (define-context-input-format :fcalgs [file] (with-in-reader file (loop [count 0, incidence #{}] (if-let [line (read-line)] (recur (inc count) (into incidence (for [x (read-string (str "(" line ")"))] [count x]))) (let [objects (set-of g [[g _] incidence]), attributes (set-of m [[_ m] incidence])] (make-context objects attributes incidence)))))) (define-context-output-format :fcalgs [context file] (with-out-writer file (when-not (and (= (set-of-range (count (objects context))) (objects context)) (= (set-of-range (count (attributes context))) (attributes context))) (unsupported-operation "Format :fcalgs can only store contexts with " "integral objects and attributes >= 0, counting upwards.")) (when (let [max-att (dec (count (attributes context)))] (forall [g (objects context)] (not ((incidence context) [g max-att])))) (unsupported-operation "Cannot store context with last column empty in format :fcalgs")) (when (exists [g (objects context)] (forall [m (attributes context)] (not ((incidence context) [g m])))) (unsupported-operation "Cannot store context with empty rows in format :fcalgs")) (let [object-count (count (objects context)) attribute-count (count (attributes context))] (doseq [g (range object-count)] (doseq [m (range attribute-count)] (when ((incidence context) [g m]) (print (str m " ")))) (println))))) ;; GraphML (define-context-input-format :graphml [file] (try (let [graphml (xml/parse (reader file))] (if (= :graphml (:tag graphml)) (doall (for [graph (:content graphml) :when (= :graph (:tag graph))] (let [default (:edgedefault (:attrs graph)) nodes (filter #(= :node (:tag %)) (:content graph)) edges (filter #(= :edge (:tag %)) (:content graph)) hyperedges (filter #(= :hyperedge (:tag %)) (:content graph))] (if (empty? hyperedges) ;; nodes X nodes context generated from normal graph (let [objects (set (for [node nodes] (:id (:attrs node)))) incidence (map #(filter identity %) (apply concat (for [edge edges] (let [attributes (:attrs edge) src-trg [(:source attributes) (:target attributes)] data (:content edge) value (first (:content (first data)))] (when (< 1 (count data)) (illegal-argument (str "Multiple data values for" " edges are not" " supported."))) (when (= clojure.data.xml.Element (type value)) (illegal-argument (str "Only single values are" " supported as edge" " data."))) (if (or (not (:directed attributes)) (= default "undirected")) (map #(conj % value) (list src-trg (vec (reverse src-trg)))) (conj src-trg value)))))) weights (filter #(= (count %) 3) incidence)] (if (empty? weights) (make-context objects objects (set incidence)) (make-mv-context objects objects (set weights)))) ;; edges X nodes context generated from hypergraph (let [objects (set (for [node nodes] (:id (:attrs node)))) attributes (set (concat (for [hyper hyperedges] (:id (:attrs hyper))) (for [edge edges] (:id (:attrs edge))))) ;; read in hyperedges incidence1 (apply concat (for [hyper hyperedges] (for [endpoint (:content hyper)] (filter identity [(:node (:attrs endpoint)) (:id (:attrs hyper))])))) ;; read in normal edges incidence2 (apply concat (for [edge edges] (map #(filter identity %) (list [(:target (:attrs edge)) (:id (:attrs edge))] [(:source (:attrs edge)) (:id (:attrs edge))])))) incidence (set (concat incidence1 incidence2))] (if (empty? (filter #(< (count %) 2) incidence)) (make-context objects attributes incidence) (illegal-argument (str "All edges and hyperedges of an" " hypergraph need ids.")))))))) (illegal-argument "XML file does not contain GraphML."))) (catch java.io.FileNotFoundException _ (illegal-argument "Specified file not found.")) (catch javax.xml.stream.XMLStreamException _ (illegal-argument "Specified file does not contain valid XML.")))) (define-context-output-format :tex [ctx file & options] (let [{:keys [objorder attrorder] :or {objorder (constantly true), attrorder (constantly true)}} options] (with-out-writer file (println "\\begin{cxt}") (println "\\cxtName{}") (let [attr (sort-by attrorder (attributes ctx)) obj (sort-by objorder (objects ctx))] (doseq [a attr] (println (str "\\att{" a "}"))) (doseq [o obj] (println (str "\\obj{" (clojure.string/join "" (for [a attr] (if ((incidence ctx) [o a]) "x" "."))) "}{" o "}"))) (println "\\end{cxt}"))))) ;; Json helpers (defn- object->json "Returns an objects with its attributes as a map that can easily be converted into json format. Example output: {object: \"b\", attributes: [\"1\", \"2\"]}" [ctx object] {:object object :attributes (filter #(incident? ctx object %) (attributes ctx))}) (defn ctx->json "Returns a formal context as a map that can easily be converted into json format. Example: {:objects #{\"b\"} :attributes #{\"1\" \"2\"} :incidence #{[\"b\" \"1\"] [\"b\" \"2\"]}" [ctx] {:objects (objects ctx) :attributes (attributes ctx) :incidence (if (= (type ctx) clojure.lang.PersistentHashSet) (incidence ctx) (into #{} (for [o (objects ctx) a (attributes ctx) :when (incident? ctx o a)] [o a])))} ;; {:attributes (into () (attributes ctx)) ;; :adjacency-list ;; (mapv (partial object->json ctx) (objects ctx))} ) (defn- json-ctx->incidence "Returns the incidence of a json context as set of tuples." [json-ctx] (set-of [o a] [o [(:object json-ctx)], a (:attributes json-ctx)])) (defn json->ctx "Returns a Context object for the given json context." [json-ctx] (let [attributes (:attributes json-ctx) objects (:objects json-ctx) incidence (:incidence json-ctx)] (make-context objects attributes incidence))) ;; Json Format (src/main/resources/schemas/context_schema_v1.1.json) (add-context-input-format :json (fn [rdr] (try (json-object? rdr) (catch Exception _)))) (define-context-output-format :json [ctx file] (with-out-writer file (print (json/write-str (ctx->json ctx))))) (define-context-input-format :json [file] (with-in-reader file (let [file-content (json/read *in* :key-fn keyword) schema-file "src/main/resources/schemas/context_schema_v1.1.json"] (assert (matches-schema? file-content schema-file) (str "The input file does not match the schema given at " schema-file ".")) (json->ctx file-content)))) TODO ;; slf csc csx ? ;; tuples ;;; nil
null
https://raw.githubusercontent.com/tomhanika/conexp-clj/9f53c71913fa39b95516c388d9e426bec34e3a77/src/main/clojure/conexp/io/contexts.clj
clojure
Copyright ⓒ the conexp-clj developers; all rights reserved. The use and distribution terms for this software are covered by the which can be found in the file LICENSE 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. Input format dispatch Formats Simple conexp-clj Format "\n" "A\n" XML helpers ConExp Galicia (.bin.xml) Colibri (.bri, .con) } %) m))) blank comment do not read empty json context as csv Binary CSV (:binary-csv) if file is empty, read-line returns nil output as tex array fcalgs GraphML nodes X nodes context generated from normal graph edges X nodes context generated from hypergraph read in hyperedges read in normal edges Json helpers {:attributes (into () (attributes ctx)) :adjacency-list (mapv (partial object->json ctx) (objects ctx))} Json Format (src/main/resources/schemas/context_schema_v1.1.json) slf tuples
Eclipse Public License 1.0 ( -1.0.php ) (ns conexp.io.contexts (:require [conexp.base :refer :all] [conexp.fca.contexts :refer :all] [conexp.io.util :refer :all] [conexp.fca.many-valued-contexts :refer :all] [conexp.io.latex :refer :all] [conexp.io.json :refer :all] [clojure.string :refer (split)] [clojure.data.xml :as xml] [clojure.data.json :as json] [json-schema.core :as json-schema] [clojure.data.csv :as csv] [clojure.java.io :as io]) (:import [java.io PushbackReader])) (define-format-dispatch "context") (set-default-context-format! :simple) (add-context-input-format :simple (fn [rdr] (= "conexp-clj simple" (read-line)))) (define-context-output-format :simple [ctx file] (with-out-writer file (binding [*print-length* nil] (println "conexp-clj simple") (prn {:context [(objects ctx) (attributes ctx) (incidence-relation ctx)]})))) (define-context-input-format :simple [file] (with-in-reader file (let [_ (get-line) hash-map (binding [*in* (PushbackReader. *in*)] (read)), context (:context hash-map)] (when-not context (unsupported-operation "File " file " does not contain a context.")) (apply make-context context)))) (add-context-input-format :burmeister (fn [rdr] (= "B" (read-line)))) (define-context-output-format :burmeister [ctx file] (with-out-writer file (println \B) (println) (println (count (objects ctx))) (println (count (attributes ctx))) (println) (doseq [g (objects ctx)] (println g)) (doseq [m (attributes ctx)] (println m)) (let [inz (incidence ctx)] (doseq [g (objects ctx)] (doseq [m (attributes ctx)] (print (if (inz [g m]) "X" "."))) (println))))) (define-context-input-format :burmeister [file] (with-in-reader file " B\n\n " , we do n't support names number-of-objects (Integer/parseInt (.trim (get-line))) number-of-attributes (Integer/parseInt (.trim (get-line))) seq-of-objects (get-lines number-of-objects) seq-of-attributes (get-lines number-of-attributes)] (loop [objs seq-of-objects incidence #{}] (if (empty? objs) (make-context-nc (set seq-of-objects) (set seq-of-attributes) incidence) (let [line (get-line)] (recur (rest objs) (into incidence (for [idx-m (range number-of-attributes) :when (#{\X,\x} (nth line idx-m))] [(first objs) (nth seq-of-attributes idx-m)]))))))))) , aka without names (add-context-input-format :anonymous-burmeister (fn [rdr] (= "A" (read-line)))) (define-context-output-format :anonymous-burmeister [ctx file] (with-out-writer file (println \A) (println (count (objects ctx))) (println (count (attributes ctx))) (let [inz (incidence ctx)] (doseq [g (objects ctx)] (doseq [m (attributes ctx)] (print (if (inz [g m]) "X" "."))) (println))))) (define-context-input-format :anonymous-burmeister [file] (with-in-reader file number-of-objects (Integer/parseInt (.trim (get-line))), number-of-attributes (Integer/parseInt (.trim (get-line))), seq-of-objects (range number-of-objects), seq-of-attributes (range number-of-attributes)] (loop [objs seq-of-objects incidence #{}] (if (empty? objs) (make-context-nc (set seq-of-objects) (set seq-of-attributes) incidence) (let [line (get-line)] (recur (rest objs) (into incidence (for [idx-m (range number-of-attributes) :when (#{\X,\x} (nth line idx-m))] [(first objs) (nth seq-of-attributes idx-m)]))))))))) (defn- find-tags [seq-of-hashes tag] (for [hash seq-of-hashes :when (= tag (:tag hash))] hash)) (defn- find-tag [seq-of-hashes tag] (first (find-tags seq-of-hashes tag))) (defn- trim [^String str] (.trim str)) (defn- hash-from-pairs [pairs] (into {} pairs)) (add-context-input-format :conexp (fn [rdr] (try (= :ConceptualSystem (-> (xml/parse rdr) :tag)) (catch Exception _)))) (define-context-input-format :conexp [file] (with-in-reader file (let [xml-tree (xml/parse *in*) contexts (:content (first (find-tags (:content xml-tree) :Contexts)))] (cond (= 0 (count contexts)) (throw (IllegalArgumentException. (str "No context specified in " file))) (< 1 (count contexts)) (throw (IllegalArgumentException. (str "More than one context specified in " file)))) (let [context (first contexts) atts-map (find-tag (:content context) :Attributes) objs-map (find-tag (:content context) :Objects) obj-idxs-map (hash-from-pairs (for [obj-map (:content objs-map)] [(apply str (-> obj-map :content (find-tag :Name) :content)) (set-of (get-in att [:attrs :AttributeIdentifier]) [att (-> obj-map :content (find-tag :Intent) :content)])])) idx-atts-map (hash-from-pairs (for [att-map (:content atts-map)] [(get-in att-map [:attrs :Identifier]) (apply str (-> att-map :content (find-tag :Name) :content))]))] (assert (distinct? (vals idx-atts-map)) "Names of attributes must be different.") (make-context-nc (set (keys obj-idxs-map)) (set (vals idx-atts-map)) (set-of [g (idx-atts-map idx) ] [[g att-idxs] obj-idxs-map idx att-idxs])))))) (defn- ctx->xml-vector [ctx id] (let [ctx-atts (zipmap (attributes ctx) (iterate inc 0)) ctx-objs (objects ctx) attributes (vector :Attributes (map (fn [[att id]] [:Attribute {:Identifier id} [:Name att]]) ctx-atts)) objects (vector :Objects (for [obj ctx-objs] [:Object [:Name obj] (vector :Intent (for [att (object-derivation ctx #{obj})] [:HasAttribute {:AttributeIdentifier (ctx-atts att)}]))]))] [:Context {:Identifier "0", :Type "Binary"} attributes objects])) (define-context-output-format :conexp [ctx file] (with-out-writer file (xml/emit (xml/sexp-as-element [:ConceptualSystem [:Version {:MajorNumber "1", :MinorNumber "0"}] [:Contexts (ctx->xml-vector ctx 0)]]) *out*))) (add-context-input-format :galicia (fn [rdr] (try (let [xml-tree (xml/parse rdr)] (and (= :Galicia_Document (-> xml-tree :tag)) (= :BinaryContext (-> xml-tree :content first :tag)))) (catch Exception _)))) (define-context-output-format :galicia [ctx file] (let [atts (apply hash-map (interleave (attributes ctx) (iterate inc 0))) objs (apply hash-map (interleave (objects ctx) (iterate inc 0))) atts-vector (sort #(< (atts %1) (atts %2)) (attributes ctx)) objs-vector (sort #(< (objs %1) (objs %2)) (objects ctx))] (with-out-writer file (xml/emit (xml/sexp-as-element [:Galicia_Document [:BinaryContext {:numberObj (str (count objs-vector)), :numberAtt (str (count atts-vector))} [:Name "conexp-clj generated context"] (for [obj objs-vector] [:Object obj]) (for [att atts-vector] [:Attribute att]) (for [[g m] (incidence-relation ctx)] [:BinRel {:idxO (str (objs g)), :idxA (str (atts m))}])]]) *out*)))) (define-context-input-format :galicia [file] (with-in-reader file (let [ctx-xml-tree (-> (xml/parse *in*) :content first) nr-objs (Integer/parseInt (-> ctx-xml-tree :attrs :numberObj)) nr-atts (Integer/parseInt (-> ctx-xml-tree :attrs :numberAtt)) can be done better ( one run instead of three ) objs (map (comp first :content) (filter #(= (:tag %) :Object) (-> ctx-xml-tree :content))) atts (map (comp first :content) (filter #(= (:tag %) :Attribute) (-> ctx-xml-tree :content))) idxs (map #(vector (Integer/parseInt (:idxO (:attrs %))) (Integer/parseInt (:idxA (:attrs %)))) (filter #(= (:tag %) :BinRel) (-> ctx-xml-tree :content)))] (make-context-nc objs atts (set-of [(nth objs idxO) (nth atts idxA)] [[idxO idxA] idxs]))))) (add-context-input-format :colibri (fn [rdr] (let [comment #"^\s*#.*$" blank #"^\s*$" row #"^\s*.+\s*:.*;\s*$"] (forall [line (line-seq rdr)] (or (re-matches comment line) (re-matches blank line) (re-matches row line)))))) (define-context-output-format :colibri [ctx file] (when (some (fn [m] (attributes ctx)) (unsupported-operation "Cannot export to :colibri format, object or attribute names contain invalid characters.")) (when (not (empty? (difference (attributes ctx) (set-of m [[g m] (incidence-relation ctx)])))) (unsupported-operation "Cannot export to :colibri format, context contains empty columns.")) (with-out-writer file (doseq [g (objects ctx)] (print g) (print ":") (doseq [m (object-derivation ctx #{g})] (print "\t") (print m)) (print ";\n")))) (define-context-input-format :colibri [file] (with-in-reader file (loop [objs #{}, inz #{}] (let [line (read-line)] (cond (not line) (make-context-nc objs (set-of m [[g m] inz]) inz), (recur objs inz), :else (let [[_ g atts] (re-matches #"^\s*(.+)\s*:\s*(.+)?\s*;\s*(?:#.*)?$" line) atts (and atts (split atts #"\s+"))] (recur (conj objs g) (union inz (set-of [g m] [m atts]))))))))) Comma Seperated Values ( .csv ) (add-context-input-format :csv (fn [rdr] (try (let [first-line (read-line)] (and (re-matches #"^[^,]+,[^,]+$" first-line) (not= first-line "{\"objectsn:[],\"attributes\":[],\"incidence\":[]}"))) (catch Exception _)))) (define-context-input-format :csv [file] (with-open [reader (io/reader file)] (let [csv-list (doall (csv/read-csv reader)) obj (set (map first csv-list)) attr (set (map second csv-list)) incidence (set csv-list)] (make-context-nc obj attr incidence)))) (define-context-output-format :csv [ctx file] (when (some (fn [x] (and (string? x) (some #(= \, %) x))) (concat (objects ctx) (attributes ctx))) (unsupported-operation "Cannot export to :csv format, object or attribute names contain \",\".")) (with-open [writer (io/writer file)] (csv/write-csv writer (incidence-relation ctx)))) (add-context-input-format :binary-csv (fn [rdr] (= "binary CSV" (read-line)))) (define-context-input-format :binary-csv [file] (with-open [reader (io/reader file)] remove the first element [ binary CSV ] (doall (csv/read-csv reader))) num-objects (count csv-list) num-attributes (count (first csv-list)) incidences (map #(Integer/parseInt %) (into [] (apply concat csv-list)))] (make-context-from-matrix num-objects num-attributes incidences)))) (define-context-output-format :binary-csv [ctx file] (when (or (empty? (objects ctx)) (empty? (attributes ctx))) (unsupported-operation "Cannot export empty context in binary-csv format")) (when (some (fn [x] (and (string? x) (some #(= \, %) x))) (concat (objects ctx) (attributes ctx))) (unsupported-operation "Cannot export to :binary-csv format, object or attribute names contain \",\".")) (let [objs (sort (objects ctx)), atts (sort (attributes ctx)) output-matrix (for [obj objs] (for [att atts] (if (incident? ctx obj att) 1 0)))] (with-open [writer (io/writer file)] (csv/write-csv writer add " binary CSV as first line of output )))) (add-context-input-format :named-binary-csv (fn [rdr] (try (= "NB" (subs (read-line) 0 2)) (catch NullPointerException _) first line of file can contain less than 2 characters (catch StringIndexOutOfBoundsException _)))) (define-context-input-format :named-binary-csv [file] (with-open [reader (io/reader file)] (let [csv-list (doall (csv/read-csv reader))] (let [M ((comp rest first) csv-list) rows (rest csv-list) G (reduce (fn [s row] (conj s (first row))) [] rows) I (reduce (fn [s row] (into s (map #(Integer/parseInt %) (rest row)))) [] rows)] (make-context-from-matrix G M I))))) (define-context-output-format :named-binary-csv [ctx file] (when (or (empty? (objects ctx)) (empty? (attributes ctx))) (unsupported-operation "Cannot export empty context in named-binary-csv format")) (when (some (fn [x] (and (string? x) (some #(= \, %) x))) (concat (objects ctx) (attributes ctx))) (unsupported-operation "Cannot export to :named-binary-csv format, object or attribute names contain \",\".")) (let [objs (sort (objects ctx)), atts (sort (attributes ctx)) output-matrix (conj (for [obj objs] (into [obj] (for [att atts] (if (incident? ctx obj att) 1 0)))) (into ["NB"] atts))] (with-open [writer (io/writer file)] (csv/write-csv writer output-matrix)))) (define-context-output-format :tex [ctx file] (with-out-writer file (println (latex ctx)))) (add-context-input-format :fcalgs (fn [rdr] (try (forall [line (line-seq rdr), x line] (or (= x \space) (Character/isDigit ^Character x))) (catch Exception _ false)))) (define-context-input-format :fcalgs [file] (with-in-reader file (loop [count 0, incidence #{}] (if-let [line (read-line)] (recur (inc count) (into incidence (for [x (read-string (str "(" line ")"))] [count x]))) (let [objects (set-of g [[g _] incidence]), attributes (set-of m [[_ m] incidence])] (make-context objects attributes incidence)))))) (define-context-output-format :fcalgs [context file] (with-out-writer file (when-not (and (= (set-of-range (count (objects context))) (objects context)) (= (set-of-range (count (attributes context))) (attributes context))) (unsupported-operation "Format :fcalgs can only store contexts with " "integral objects and attributes >= 0, counting upwards.")) (when (let [max-att (dec (count (attributes context)))] (forall [g (objects context)] (not ((incidence context) [g max-att])))) (unsupported-operation "Cannot store context with last column empty in format :fcalgs")) (when (exists [g (objects context)] (forall [m (attributes context)] (not ((incidence context) [g m])))) (unsupported-operation "Cannot store context with empty rows in format :fcalgs")) (let [object-count (count (objects context)) attribute-count (count (attributes context))] (doseq [g (range object-count)] (doseq [m (range attribute-count)] (when ((incidence context) [g m]) (print (str m " ")))) (println))))) (define-context-input-format :graphml [file] (try (let [graphml (xml/parse (reader file))] (if (= :graphml (:tag graphml)) (doall (for [graph (:content graphml) :when (= :graph (:tag graph))] (let [default (:edgedefault (:attrs graph)) nodes (filter #(= :node (:tag %)) (:content graph)) edges (filter #(= :edge (:tag %)) (:content graph)) hyperedges (filter #(= :hyperedge (:tag %)) (:content graph))] (if (empty? hyperedges) (let [objects (set (for [node nodes] (:id (:attrs node)))) incidence (map #(filter identity %) (apply concat (for [edge edges] (let [attributes (:attrs edge) src-trg [(:source attributes) (:target attributes)] data (:content edge) value (first (:content (first data)))] (when (< 1 (count data)) (illegal-argument (str "Multiple data values for" " edges are not" " supported."))) (when (= clojure.data.xml.Element (type value)) (illegal-argument (str "Only single values are" " supported as edge" " data."))) (if (or (not (:directed attributes)) (= default "undirected")) (map #(conj % value) (list src-trg (vec (reverse src-trg)))) (conj src-trg value)))))) weights (filter #(= (count %) 3) incidence)] (if (empty? weights) (make-context objects objects (set incidence)) (make-mv-context objects objects (set weights)))) (let [objects (set (for [node nodes] (:id (:attrs node)))) attributes (set (concat (for [hyper hyperedges] (:id (:attrs hyper))) (for [edge edges] (:id (:attrs edge))))) incidence1 (apply concat (for [hyper hyperedges] (for [endpoint (:content hyper)] (filter identity [(:node (:attrs endpoint)) (:id (:attrs hyper))])))) incidence2 (apply concat (for [edge edges] (map #(filter identity %) (list [(:target (:attrs edge)) (:id (:attrs edge))] [(:source (:attrs edge)) (:id (:attrs edge))])))) incidence (set (concat incidence1 incidence2))] (if (empty? (filter #(< (count %) 2) incidence)) (make-context objects attributes incidence) (illegal-argument (str "All edges and hyperedges of an" " hypergraph need ids.")))))))) (illegal-argument "XML file does not contain GraphML."))) (catch java.io.FileNotFoundException _ (illegal-argument "Specified file not found.")) (catch javax.xml.stream.XMLStreamException _ (illegal-argument "Specified file does not contain valid XML.")))) (define-context-output-format :tex [ctx file & options] (let [{:keys [objorder attrorder] :or {objorder (constantly true), attrorder (constantly true)}} options] (with-out-writer file (println "\\begin{cxt}") (println "\\cxtName{}") (let [attr (sort-by attrorder (attributes ctx)) obj (sort-by objorder (objects ctx))] (doseq [a attr] (println (str "\\att{" a "}"))) (doseq [o obj] (println (str "\\obj{" (clojure.string/join "" (for [a attr] (if ((incidence ctx) [o a]) "x" "."))) "}{" o "}"))) (println "\\end{cxt}"))))) (defn- object->json "Returns an objects with its attributes as a map that can easily be converted into json format. Example output: {object: \"b\", attributes: [\"1\", \"2\"]}" [ctx object] {:object object :attributes (filter #(incident? ctx object %) (attributes ctx))}) (defn ctx->json "Returns a formal context as a map that can easily be converted into json format. Example: {:objects #{\"b\"} :attributes #{\"1\" \"2\"} :incidence #{[\"b\" \"1\"] [\"b\" \"2\"]}" [ctx] {:objects (objects ctx) :attributes (attributes ctx) :incidence (if (= (type ctx) clojure.lang.PersistentHashSet) (incidence ctx) (into #{} (for [o (objects ctx) a (attributes ctx) :when (incident? ctx o a)] [o a])))} ) (defn- json-ctx->incidence "Returns the incidence of a json context as set of tuples." [json-ctx] (set-of [o a] [o [(:object json-ctx)], a (:attributes json-ctx)])) (defn json->ctx "Returns a Context object for the given json context." [json-ctx] (let [attributes (:attributes json-ctx) objects (:objects json-ctx) incidence (:incidence json-ctx)] (make-context objects attributes incidence))) (add-context-input-format :json (fn [rdr] (try (json-object? rdr) (catch Exception _)))) (define-context-output-format :json [ctx file] (with-out-writer file (print (json/write-str (ctx->json ctx))))) (define-context-input-format :json [file] (with-in-reader file (let [file-content (json/read *in* :key-fn keyword) schema-file "src/main/resources/schemas/context_schema_v1.1.json"] (assert (matches-schema? file-content schema-file) (str "The input file does not match the schema given at " schema-file ".")) (json->ctx file-content)))) TODO csc csx ? nil
ab61987f11f601566ef464f8cba7f236babcdac79097ad7eb82eb19c7425990d
cloojure/tupelo
quote.cljc
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the Eclipse Public ; License 1.0 (-1.0.php) which can be found in the ; file epl-v10.html at the root of this distribution. By using this software in any ; fashion, you are agreeing to be bound by the terms of this license. ; You must not remove this notice, or any other, from this software. (ns tst.tupelo.quote ;--------------------------------------------------------------------------------------------------- ; -cljs/2019/10/12/clojurescript-macros.html ; -12-18-clojurescript-macro-tower-and-loop.html #?(:cljs (:require-macros ; [tupelo.core] [tupelo.quote] [tupelo.testy] )) (:require [clojure.test] ; sometimes this is required - not sure why [clojure.walk :as walk] [tupelo.quote :as q] [tupelo.core :as t :refer [glue grab it-> forv spy spyx spyxx vals->map xfirst xsecond]] [tupelo.testy :refer [deftest testing is dotest isnt is= isnt= is-set= is-nonblank= throws? throws-not? define-fixture]] )) #?(:cljs (enable-console-print!)) (dotest (is= (q/tmpl-fn (quote [a b (insert (+ 2 3))])) (quote [a b 5])) (let [a 1 b 2] (is= `[a b ~(+ 2 3)] ; problem with clojure.core/syntax-quote (quote [tst.tupelo.quote/a tst.tupelo.quote/b 5])) (is= (q/tmpl [a b (insert (+ 2 3))]) [1 2 5]) ; desired result )) (def vec234 [2 3 4]) (dotest (is (q/insert-form? (quote (insert (+ 2 3))))) (is (q/splice-form? (quote (splice (+ 2 3))))) (is= (q/tmpl-fn (quote {:a 1 :b (insert (+ 2 3))})) {:a 1, :b 5}) (is= (q/tmpl-fn (quote [a b (insert (+ 2 3))])) (quote [a b 5])) (is= (q/tmpl {:a 1 :b (insert (+ 2 3))}) {:a 1, :b 5}) (is= (q/tmpl {:a 1 :b (insert (vec (range 3)))}) {:a 1, :b [0 1 2]}) (is= (q/tmpl {:a 1 :b (insert vec234)}) {:a 1, :b [2 3 4]}) (let [result (q/tmpl (list 1 2 (insert (inc 2)) 4 5))] (is (list? result)) (is= result (quote (1 2 3 4 5)))) (is= (q/tmpl-fn (quote [1 (splice (range 2 5)) 5])) [1 2 3 4 5]) must be fully - qualified here [1 2 3 4 5]) (is= (q/tmpl [1 (splice vec234) 5]) ; unqualified name OK here [1 2 3 4 5]) (is= (q/tmpl [1 (splice (t/thru 2 4)) 5]) [1 2 3 4 5]) (is= (q/tmpl [1 (insert (t/thru 2 4)) 5]) [1 [2 3 4] 5]) (is= [1 [2 3 4] 5] (q/tmpl [1 (insert (t/thru 2 4)) 5])) (is= [1 2 3 4 5] (q/tmpl [1 (splice (t/thru 2 4)) 5])) (is= 3 (eval (quote (+ 1 2))))) (comment ; demo (let [a 1 b (inc a)] (println :1 (quote [a b])) (println :2 '{:out [~a ~b]}) ; ***** doesn't work ***** (println :3 `{:out [~a ~b]}) ; (println (td/quote-template {:out (unquote [a b])})) ; ***** fails due to locals ***** (println :4 (q/tmpl {:out (insert [a-1400 b-1400])})) ; globals are OK (println :5 (q/tmpl {:a 1 :b (insert (+ 2 3))})) ; global function works too ( println : 6 ( q / tmpl { : out ( insert [ a b ] ) } ) ) ; fails when try to use locals )) # todo review & merge ( from tupelo.data/quoted ns ) (comment (ns tst.tupelo.quoted (:use tupelo.core tupelo.test) (:require [clojure.walk :as walk] )) (comment (defn unquoted-form? [form] (and (list? form) (= (quote unquoted) (first form)))) (defn quoted-impl [form] (spyx form) (let [env-pairs (atom []) form-walked (walk/prewalk (fn [item] (t/with-nil-default item (when (unquoted-form? item) (let ; -spy [payload (only (rest item)) gsym (gensym "unq-val-") pair [gsym payload]] (swap! env-pairs t/append pair) gsym)))) form) >> (spyx-pretty env-pairs) >> (spyx-pretty form-walked) let-form (list (quote let) (apply glue @env-pairs) form-walked)] let-form)) (defmacro quoted [form] (quoted-impl form)) (defmacro shower [& form] `(prn (quote ~form))) (dotest (is (unquoted-form? (quote (unquoted xxx)))) (isnt (unquoted-form? (quote (something xxx)))) (comment ; or do (spy-pretty :impl-4 (quoted-impl (quote (+ (unquoted (+ 1 2)) (unquoted (+ 3 4)) (unquoted (+ 5 6)) (unquoted (+ 7 8)))))) (comment ; => (sample result) (let [unq-val-32909 (+ 1 2) unq-val-32910 (+ 3 4) unq-val-32911 (+ 5 6) unq-val-32912 (+ 7 8)] (+ unq-val-32909 unq-val-32910 unq-val-32911 unq-val-32912)))) (newline) (println :-----------------------------------------------------------------------------) (spy-pretty :shower (quoted-impl (quote (shower (+ (unquoted (+ 1 2)) (unquoted (+ 3 4)) (unquoted (+ 5 6)) (unquoted (+ 7 8)))))))) ) )
null
https://raw.githubusercontent.com/cloojure/tupelo/4105fefbb1c4d1b2f06fa4993f9dd007e5e41e00/test/cljc/tst/tupelo/quote.cljc
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. --------------------------------------------------------------------------------------------------- -cljs/2019/10/12/clojurescript-macros.html -12-18-clojurescript-macro-tower-and-loop.html [tupelo.core] sometimes this is required - not sure why problem with clojure.core/syntax-quote desired result unqualified name OK here demo ***** doesn't work ***** (println (td/quote-template {:out (unquote [a b])})) ; ***** fails due to locals ***** globals are OK global function works too fails when try to use locals -spy or do => (sample result)
Copyright ( c ) . All rights reserved . (ns tst.tupelo.quote #?(:cljs (:require-macros [tupelo.quote] [tupelo.testy] )) (:require [clojure.walk :as walk] [tupelo.quote :as q] [tupelo.core :as t :refer [glue grab it-> forv spy spyx spyxx vals->map xfirst xsecond]] [tupelo.testy :refer [deftest testing is dotest isnt is= isnt= is-set= is-nonblank= throws? throws-not? define-fixture]] )) #?(:cljs (enable-console-print!)) (dotest (is= (q/tmpl-fn (quote [a b (insert (+ 2 3))])) (quote [a b 5])) (let [a 1 b 2] (quote [tst.tupelo.quote/a tst.tupelo.quote/b 5])) (is= (q/tmpl [a b (insert (+ 2 3))]) )) (def vec234 [2 3 4]) (dotest (is (q/insert-form? (quote (insert (+ 2 3))))) (is (q/splice-form? (quote (splice (+ 2 3))))) (is= (q/tmpl-fn (quote {:a 1 :b (insert (+ 2 3))})) {:a 1, :b 5}) (is= (q/tmpl-fn (quote [a b (insert (+ 2 3))])) (quote [a b 5])) (is= (q/tmpl {:a 1 :b (insert (+ 2 3))}) {:a 1, :b 5}) (is= (q/tmpl {:a 1 :b (insert (vec (range 3)))}) {:a 1, :b [0 1 2]}) (is= (q/tmpl {:a 1 :b (insert vec234)}) {:a 1, :b [2 3 4]}) (let [result (q/tmpl (list 1 2 (insert (inc 2)) 4 5))] (is (list? result)) (is= result (quote (1 2 3 4 5)))) (is= (q/tmpl-fn (quote [1 (splice (range 2 5)) 5])) [1 2 3 4 5]) must be fully - qualified here [1 2 3 4 5]) [1 2 3 4 5]) (is= (q/tmpl [1 (splice (t/thru 2 4)) 5]) [1 2 3 4 5]) (is= (q/tmpl [1 (insert (t/thru 2 4)) 5]) [1 [2 3 4] 5]) (is= [1 [2 3 4] 5] (q/tmpl [1 (insert (t/thru 2 4)) 5])) (is= [1 2 3 4 5] (q/tmpl [1 (splice (t/thru 2 4)) 5])) (is= 3 (eval (quote (+ 1 2))))) (let [a 1 b (inc a)] (println :1 (quote [a b])) (println :3 `{:out [~a ~b]}) )) # todo review & merge ( from tupelo.data/quoted ns ) (comment (ns tst.tupelo.quoted (:use tupelo.core tupelo.test) (:require [clojure.walk :as walk] )) (comment (defn unquoted-form? [form] (and (list? form) (= (quote unquoted) (first form)))) (defn quoted-impl [form] (spyx form) (let [env-pairs (atom []) form-walked (walk/prewalk (fn [item] (t/with-nil-default item (when (unquoted-form? item) [payload (only (rest item)) gsym (gensym "unq-val-") pair [gsym payload]] (swap! env-pairs t/append pair) gsym)))) form) >> (spyx-pretty env-pairs) >> (spyx-pretty form-walked) let-form (list (quote let) (apply glue @env-pairs) form-walked)] let-form)) (defmacro quoted [form] (quoted-impl form)) (defmacro shower [& form] `(prn (quote ~form))) (dotest (is (unquoted-form? (quote (unquoted xxx)))) (isnt (unquoted-form? (quote (something xxx)))) (spy-pretty :impl-4 (quoted-impl (quote (+ (unquoted (+ 1 2)) (unquoted (+ 3 4)) (unquoted (+ 5 6)) (unquoted (+ 7 8)))))) (let [unq-val-32909 (+ 1 2) unq-val-32910 (+ 3 4) unq-val-32911 (+ 5 6) unq-val-32912 (+ 7 8)] (+ unq-val-32909 unq-val-32910 unq-val-32911 unq-val-32912)))) (newline) (println :-----------------------------------------------------------------------------) (spy-pretty :shower (quoted-impl (quote (shower (+ (unquoted (+ 1 2)) (unquoted (+ 3 4)) (unquoted (+ 5 6)) (unquoted (+ 7 8)))))))) ) )
904171c73a8408738fa3e85846161e3881c529e19822afdbede5048792967a45
ocsigen/ocaml-eliom
printast.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Para , INRIA Rocquencourt (* *) Copyright 1999 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open Asttypes;; open Format;; open Lexing;; open Location;; open Parsetree;; let fmt_position with_name f l = let fname = if with_name then l.pos_fname else "" in if l.pos_lnum = -1 then fprintf f "%s[%d]" fname l.pos_cnum else fprintf f "%s[%d,%d+%d]" fname l.pos_lnum l.pos_bol (l.pos_cnum - l.pos_bol) ;; let fmt_location f loc = let p_2nd_name = loc.loc_start.pos_fname <> loc.loc_end.pos_fname in fprintf f "(%a..%a)" (fmt_position true) loc.loc_start (fmt_position p_2nd_name) loc.loc_end; if loc.loc_ghost then fprintf f " ghost"; ;; let rec fmt_longident_aux f x = match x with | Longident.Lident (s) -> fprintf f "%s" s; | Longident.Ldot (y, s) -> fprintf f "%a.%s" fmt_longident_aux y s; | Longident.Lapply (y, z) -> fprintf f "%a(%a)" fmt_longident_aux y fmt_longident_aux z; ;; let fmt_longident f x = fprintf f "\"%a\"" fmt_longident_aux x;; let fmt_longident_loc f (x : Longident.t loc) = fprintf f "\"%a\" %a" fmt_longident_aux x.txt fmt_location x.loc; ;; let fmt_string_loc f (x : string loc) = fprintf f "\"%s\" %a" x.txt fmt_location x.loc; ;; let fmt_char_option f = function | None -> fprintf f "None" | Some c -> fprintf f "Some %c" c let fmt_constant f x = match x with | Pconst_integer (i,m) -> fprintf f "PConst_int (%s,%a)" i fmt_char_option m; | Pconst_char (c) -> fprintf f "PConst_char %02x" (Char.code c); | Pconst_string (s, None) -> fprintf f "PConst_string(%S,None)" s; | Pconst_string (s, Some delim) -> fprintf f "PConst_string (%S,Some %S)" s delim; | Pconst_float (s,m) -> fprintf f "PConst_float (%s,%a)" s fmt_char_option m; ;; let fmt_mutable_flag f x = match x with | Immutable -> fprintf f "Immutable"; | Mutable -> fprintf f "Mutable"; ;; let fmt_virtual_flag f x = match x with | Virtual -> fprintf f "Virtual"; | Concrete -> fprintf f "Concrete"; ;; let fmt_override_flag f x = match x with | Override -> fprintf f "Override"; | Fresh -> fprintf f "Fresh"; ;; let fmt_closed_flag f x = match x with | Closed -> fprintf f "Closed" | Open -> fprintf f "Open" let fmt_rec_flag f x = match x with | Nonrecursive -> fprintf f "Nonrec"; | Recursive -> fprintf f "Rec"; ;; let fmt_direction_flag f x = match x with | Upto -> fprintf f "Up"; | Downto -> fprintf f "Down"; ;; let fmt_private_flag f x = match x with | Public -> fprintf f "Public"; | Private -> fprintf f "Private"; ;; let line i f s (*...*) = fprintf f "%s" (String.make ((2*i) mod 72) ' '); fprintf f s (*...*) ;; let list i f ppf l = match l with | [] -> line i ppf "[]\n"; | _ :: _ -> line i ppf "[\n"; List.iter (f (i+1) ppf) l; line i ppf "]\n"; ;; let option i f ppf x = match x with | None -> line i ppf "None\n"; | Some x -> line i ppf "Some\n"; f (i+1) ppf x; ;; let longident_loc i ppf li = line i ppf "%a\n" fmt_longident_loc li;; let string i ppf s = line i ppf "\"%s\"\n" s;; let string_loc i ppf s = line i ppf "%a\n" fmt_string_loc s;; let arg_label i ppf = function | Nolabel -> line i ppf "Nolabel\n" | Optional s -> line i ppf "Optional \"%s\"\n" s | Labelled s -> line i ppf "Labelled \"%s\"\n" s ;; let rec core_type i ppf x = line i ppf "core_type %a\n" fmt_location x.ptyp_loc; attributes i ppf x.ptyp_attributes; let i = i+1 in match x.ptyp_desc with | Ptyp_any -> line i ppf "Ptyp_any\n"; | Ptyp_var (s) -> line i ppf "Ptyp_var %s\n" s; | Ptyp_arrow (l, ct1, ct2) -> line i ppf "Ptyp_arrow\n"; arg_label i ppf l; core_type i ppf ct1; core_type i ppf ct2; | Ptyp_tuple l -> line i ppf "Ptyp_tuple\n"; list i core_type ppf l; | Ptyp_constr (li, l) -> line i ppf "Ptyp_constr %a\n" fmt_longident_loc li; list i core_type ppf l; | Ptyp_variant (l, closed, low) -> line i ppf "Ptyp_variant closed=%a\n" fmt_closed_flag closed; list i label_x_bool_x_core_type_list ppf l; option i (fun i -> list i string) ppf low | Ptyp_object (l, c) -> line i ppf "Ptyp_object %a\n" fmt_closed_flag c; let i = i + 1 in List.iter (fun (s, attrs, t) -> line i ppf "method %s\n" s; attributes i ppf attrs; core_type (i + 1) ppf t ) l | Ptyp_class (li, l) -> line i ppf "Ptyp_class %a\n" fmt_longident_loc li; list i core_type ppf l | Ptyp_alias (ct, s) -> line i ppf "Ptyp_alias \"%s\"\n" s; core_type i ppf ct; | Ptyp_poly (sl, ct) -> line i ppf "Ptyp_poly%a\n" (fun ppf -> List.iter (fun x -> fprintf ppf " '%s" x)) sl; core_type i ppf ct; | Ptyp_package (s, l) -> line i ppf "Ptyp_package %a\n" fmt_longident_loc s; list i package_with ppf l; | Ptyp_extension (s, arg) -> line i ppf "Ptyp_extension \"%s\"\n" s.txt; payload i ppf arg and package_with i ppf (s, t) = line i ppf "with type %a\n" fmt_longident_loc s; core_type i ppf t and pattern i ppf x = line i ppf "pattern %a\n" fmt_location x.ppat_loc; attributes i ppf x.ppat_attributes; let i = i+1 in match x.ppat_desc with | Ppat_any -> line i ppf "Ppat_any\n"; | Ppat_var (s) -> line i ppf "Ppat_var %a\n" fmt_string_loc s; | Ppat_alias (p, s) -> line i ppf "Ppat_alias %a\n" fmt_string_loc s; pattern i ppf p; | Ppat_constant (c) -> line i ppf "Ppat_constant %a\n" fmt_constant c; | Ppat_interval (c1, c2) -> line i ppf "Ppat_interval %a..%a\n" fmt_constant c1 fmt_constant c2; | Ppat_tuple (l) -> line i ppf "Ppat_tuple\n"; list i pattern ppf l; | Ppat_construct (li, po) -> line i ppf "Ppat_construct %a\n" fmt_longident_loc li; option i pattern ppf po; | Ppat_variant (l, po) -> line i ppf "Ppat_variant \"%s\"\n" l; option i pattern ppf po; | Ppat_record (l, c) -> line i ppf "Ppat_record %a\n" fmt_closed_flag c; list i longident_x_pattern ppf l; | Ppat_array (l) -> line i ppf "Ppat_array\n"; list i pattern ppf l; | Ppat_or (p1, p2) -> line i ppf "Ppat_or\n"; pattern i ppf p1; pattern i ppf p2; | Ppat_lazy p -> line i ppf "Ppat_lazy\n"; pattern i ppf p; | Ppat_constraint (p, ct) -> line i ppf "Ppat_constraint\n"; pattern i ppf p; core_type i ppf ct; | Ppat_type (li) -> line i ppf "Ppat_type\n"; longident_loc i ppf li | Ppat_unpack s -> line i ppf "Ppat_unpack %a\n" fmt_string_loc s; | Ppat_exception p -> line i ppf "Ppat_exception\n"; pattern i ppf p | Ppat_extension (s, arg) -> line i ppf "Ppat_extension \"%s\"\n" s.txt; payload i ppf arg and expression i ppf x = line i ppf "expression %a\n" fmt_location x.pexp_loc; attributes i ppf x.pexp_attributes; let i = i+1 in match x.pexp_desc with | Pexp_ident (li) -> line i ppf "Pexp_ident %a\n" fmt_longident_loc li; | Pexp_constant (c) -> line i ppf "Pexp_constant %a\n" fmt_constant c; | Pexp_let (rf, l, e) -> line i ppf "Pexp_let %a\n" fmt_rec_flag rf; list i value_binding ppf l; expression i ppf e; | Pexp_function l -> line i ppf "Pexp_function\n"; list i case ppf l; | Pexp_fun (l, eo, p, e) -> line i ppf "Pexp_fun\n"; arg_label i ppf l; option i expression ppf eo; pattern i ppf p; expression i ppf e; | Pexp_apply (e, l) -> line i ppf "Pexp_apply\n"; expression i ppf e; list i label_x_expression ppf l; | Pexp_match (e, l) -> line i ppf "Pexp_match\n"; expression i ppf e; list i case ppf l; | Pexp_try (e, l) -> line i ppf "Pexp_try\n"; expression i ppf e; list i case ppf l; | Pexp_tuple (l) -> line i ppf "Pexp_tuple\n"; list i expression ppf l; | Pexp_construct (li, eo) -> line i ppf "Pexp_construct %a\n" fmt_longident_loc li; option i expression ppf eo; | Pexp_variant (l, eo) -> line i ppf "Pexp_variant \"%s\"\n" l; option i expression ppf eo; | Pexp_record (l, eo) -> line i ppf "Pexp_record\n"; list i longident_x_expression ppf l; option i expression ppf eo; | Pexp_field (e, li) -> line i ppf "Pexp_field\n"; expression i ppf e; longident_loc i ppf li; | Pexp_setfield (e1, li, e2) -> line i ppf "Pexp_setfield\n"; expression i ppf e1; longident_loc i ppf li; expression i ppf e2; | Pexp_array (l) -> line i ppf "Pexp_array\n"; list i expression ppf l; | Pexp_ifthenelse (e1, e2, eo) -> line i ppf "Pexp_ifthenelse\n"; expression i ppf e1; expression i ppf e2; option i expression ppf eo; | Pexp_sequence (e1, e2) -> line i ppf "Pexp_sequence\n"; expression i ppf e1; expression i ppf e2; | Pexp_while (e1, e2) -> line i ppf "Pexp_while\n"; expression i ppf e1; expression i ppf e2; | Pexp_for (p, e1, e2, df, e3) -> line i ppf "Pexp_for %a\n" fmt_direction_flag df; pattern i ppf p; expression i ppf e1; expression i ppf e2; expression i ppf e3; | Pexp_constraint (e, ct) -> line i ppf "Pexp_constraint\n"; expression i ppf e; core_type i ppf ct; | Pexp_coerce (e, cto1, cto2) -> line i ppf "Pexp_coerce\n"; expression i ppf e; option i core_type ppf cto1; core_type i ppf cto2; | Pexp_send (e, s) -> line i ppf "Pexp_send \"%s\"\n" s; expression i ppf e; | Pexp_new (li) -> line i ppf "Pexp_new %a\n" fmt_longident_loc li; | Pexp_setinstvar (s, e) -> line i ppf "Pexp_setinstvar %a\n" fmt_string_loc s; expression i ppf e; | Pexp_override (l) -> line i ppf "Pexp_override\n"; list i string_x_expression ppf l; | Pexp_letmodule (s, me, e) -> line i ppf "Pexp_letmodule %a\n" fmt_string_loc s; module_expr i ppf me; expression i ppf e; | Pexp_assert (e) -> line i ppf "Pexp_assert\n"; expression i ppf e; | Pexp_lazy (e) -> line i ppf "Pexp_lazy\n"; expression i ppf e; | Pexp_poly (e, cto) -> line i ppf "Pexp_poly\n"; expression i ppf e; option i core_type ppf cto; | Pexp_object s -> line i ppf "Pexp_object\n"; class_structure i ppf s | Pexp_newtype (s, e) -> line i ppf "Pexp_newtype \"%s\"\n" s; expression i ppf e | Pexp_pack me -> line i ppf "Pexp_pack\n"; module_expr i ppf me | Pexp_open (ovf, m, e) -> line i ppf "Pexp_open %a \"%a\"\n" fmt_override_flag ovf fmt_longident_loc m; expression i ppf e | Pexp_extension (s, arg) -> line i ppf "Pexp_extension \"%s\"\n" s.txt; payload i ppf arg | Pexp_unreachable -> line i ppf "Pexp_unreachable" and value_description i ppf x = line i ppf "value_description %a %a\n" fmt_string_loc x.pval_name fmt_location x.pval_loc; attributes i ppf x.pval_attributes; core_type (i+1) ppf x.pval_type; list (i+1) string ppf x.pval_prim and type_parameter i ppf (x, _variance) = core_type i ppf x and type_declaration i ppf x = line i ppf "type_declaration %a %a\n" fmt_string_loc x.ptype_name fmt_location x.ptype_loc; attributes i ppf x.ptype_attributes; let i = i+1 in line i ppf "ptype_params =\n"; list (i+1) type_parameter ppf x.ptype_params; line i ppf "ptype_cstrs =\n"; list (i+1) core_type_x_core_type_x_location ppf x.ptype_cstrs; line i ppf "ptype_kind =\n"; type_kind (i+1) ppf x.ptype_kind; line i ppf "ptype_private = %a\n" fmt_private_flag x.ptype_private; line i ppf "ptype_manifest =\n"; option (i+1) core_type ppf x.ptype_manifest and attributes i ppf l = let i = i + 1 in List.iter (fun (s, arg) -> line i ppf "attribute \"%s\"\n" s.txt; payload (i + 1) ppf arg; ) l and payload i ppf = function | PStr x -> structure i ppf x | PSig x -> signature i ppf x | PTyp x -> core_type i ppf x | PPat (x, None) -> pattern i ppf x | PPat (x, Some g) -> pattern i ppf x; line i ppf "<when>\n"; expression (i + 1) ppf g and type_kind i ppf x = match x with | Ptype_abstract -> line i ppf "Ptype_abstract\n" | Ptype_variant l -> line i ppf "Ptype_variant\n"; list (i+1) constructor_decl ppf l; | Ptype_record l -> line i ppf "Ptype_record\n"; list (i+1) label_decl ppf l; | Ptype_open -> line i ppf "Ptype_open\n"; and type_extension i ppf x = line i ppf "type_extension\n"; attributes i ppf x.ptyext_attributes; let i = i+1 in line i ppf "ptyext_path = %a\n" fmt_longident_loc x.ptyext_path; line i ppf "ptyext_params =\n"; list (i+1) type_parameter ppf x.ptyext_params; line i ppf "ptyext_constructors =\n"; list (i+1) extension_constructor ppf x.ptyext_constructors; line i ppf "ptyext_private = %a\n" fmt_private_flag x.ptyext_private; and extension_constructor i ppf x = line i ppf "extension_constructor %a\n" fmt_location x.pext_loc; attributes i ppf x.pext_attributes; let i = i + 1 in line i ppf "pext_name = \"%s\"\n" x.pext_name.txt; line i ppf "pext_kind =\n"; extension_constructor_kind (i + 1) ppf x.pext_kind; and extension_constructor_kind i ppf x = match x with Pext_decl(a, r) -> line i ppf "Pext_decl\n"; constructor_arguments (i+1) ppf a; option (i+1) core_type ppf r; | Pext_rebind li -> line i ppf "Pext_rebind\n"; line (i+1) ppf "%a\n" fmt_longident_loc li; and class_type i ppf x = line i ppf "class_type %a\n" fmt_location x.pcty_loc; attributes i ppf x.pcty_attributes; let i = i+1 in match x.pcty_desc with | Pcty_constr (li, l) -> line i ppf "Pcty_constr %a\n" fmt_longident_loc li; list i core_type ppf l; | Pcty_signature (cs) -> line i ppf "Pcty_signature\n"; class_signature i ppf cs; | Pcty_arrow (l, co, cl) -> line i ppf "Pcty_arrow\n"; arg_label i ppf l; core_type i ppf co; class_type i ppf cl; | Pcty_extension (s, arg) -> line i ppf "Pcty_extension \"%s\"\n" s.txt; payload i ppf arg and class_signature i ppf cs = line i ppf "class_signature\n"; core_type (i+1) ppf cs.pcsig_self; list (i+1) class_type_field ppf cs.pcsig_fields; and class_type_field i ppf x = line i ppf "class_type_field %a\n" fmt_location x.pctf_loc; let i = i+1 in attributes i ppf x.pctf_attributes; match x.pctf_desc with | Pctf_inherit (ct) -> line i ppf "Pctf_inherit\n"; class_type i ppf ct; | Pctf_val (s, mf, vf, ct) -> line i ppf "Pctf_val \"%s\" %a %a\n" s fmt_mutable_flag mf fmt_virtual_flag vf; core_type (i+1) ppf ct; | Pctf_method (s, pf, vf, ct) -> line i ppf "Pctf_method \"%s\" %a %a\n" s fmt_private_flag pf fmt_virtual_flag vf; core_type (i+1) ppf ct; | Pctf_constraint (ct1, ct2) -> line i ppf "Pctf_constraint\n"; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; | Pctf_attribute (s, arg) -> line i ppf "Pctf_attribute \"%s\"\n" s.txt; payload i ppf arg | Pctf_extension (s, arg) -> line i ppf "Pctf_extension \"%s\"\n" s.txt; payload i ppf arg and class_description i ppf x = line i ppf "class_description %a\n" fmt_location x.pci_loc; attributes i ppf x.pci_attributes; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.pci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.pci_params; line i ppf "pci_name = %a\n" fmt_string_loc x.pci_name; line i ppf "pci_expr =\n"; class_type (i+1) ppf x.pci_expr; and class_type_declaration i ppf x = line i ppf "class_type_declaration %a\n" fmt_location x.pci_loc; attributes i ppf x.pci_attributes; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.pci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.pci_params; line i ppf "pci_name = %a\n" fmt_string_loc x.pci_name; line i ppf "pci_expr =\n"; class_type (i+1) ppf x.pci_expr; and class_expr i ppf x = line i ppf "class_expr %a\n" fmt_location x.pcl_loc; attributes i ppf x.pcl_attributes; let i = i+1 in match x.pcl_desc with | Pcl_constr (li, l) -> line i ppf "Pcl_constr %a\n" fmt_longident_loc li; list i core_type ppf l; | Pcl_structure (cs) -> line i ppf "Pcl_structure\n"; class_structure i ppf cs; | Pcl_fun (l, eo, p, e) -> line i ppf "Pcl_fun\n"; arg_label i ppf l; option i expression ppf eo; pattern i ppf p; class_expr i ppf e; | Pcl_apply (ce, l) -> line i ppf "Pcl_apply\n"; class_expr i ppf ce; list i label_x_expression ppf l; | Pcl_let (rf, l, ce) -> line i ppf "Pcl_let %a\n" fmt_rec_flag rf; list i value_binding ppf l; class_expr i ppf ce; | Pcl_constraint (ce, ct) -> line i ppf "Pcl_constraint\n"; class_expr i ppf ce; class_type i ppf ct; | Pcl_extension (s, arg) -> line i ppf "Pcl_extension \"%s\"\n" s.txt; payload i ppf arg and class_structure i ppf { pcstr_self = p; pcstr_fields = l } = line i ppf "class_structure\n"; pattern (i+1) ppf p; list (i+1) class_field ppf l; and class_field i ppf x = line i ppf "class_field %a\n" fmt_location x.pcf_loc; let i = i + 1 in attributes i ppf x.pcf_attributes; match x.pcf_desc with | Pcf_inherit (ovf, ce, so) -> line i ppf "Pcf_inherit %a\n" fmt_override_flag ovf; class_expr (i+1) ppf ce; option (i+1) string ppf so; | Pcf_val (s, mf, k) -> line i ppf "Pcf_val %a\n" fmt_mutable_flag mf; line (i+1) ppf "%a\n" fmt_string_loc s; class_field_kind (i+1) ppf k | Pcf_method (s, pf, k) -> line i ppf "Pcf_method %a\n" fmt_private_flag pf; line (i+1) ppf "%a\n" fmt_string_loc s; class_field_kind (i+1) ppf k | Pcf_constraint (ct1, ct2) -> line i ppf "Pcf_constraint\n"; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; | Pcf_initializer (e) -> line i ppf "Pcf_initializer\n"; expression (i+1) ppf e; | Pcf_attribute (s, arg) -> line i ppf "Pcf_attribute \"%s\"\n" s.txt; payload i ppf arg | Pcf_extension (s, arg) -> line i ppf "Pcf_extension \"%s\"\n" s.txt; payload i ppf arg and class_field_kind i ppf = function | Cfk_concrete (o, e) -> line i ppf "Concrete %a\n" fmt_override_flag o; expression i ppf e | Cfk_virtual t -> line i ppf "Virtual\n"; core_type i ppf t and class_declaration i ppf x = line i ppf "class_declaration %a\n" fmt_location x.pci_loc; attributes i ppf x.pci_attributes; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.pci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.pci_params; line i ppf "pci_name = %a\n" fmt_string_loc x.pci_name; line i ppf "pci_expr =\n"; class_expr (i+1) ppf x.pci_expr; and module_type i ppf x = line i ppf "module_type %a\n" fmt_location x.pmty_loc; attributes i ppf x.pmty_attributes; let i = i+1 in match x.pmty_desc with | Pmty_ident li -> line i ppf "Pmty_ident %a\n" fmt_longident_loc li; | Pmty_alias li -> line i ppf "Pmty_alias %a\n" fmt_longident_loc li; | Pmty_signature (s) -> line i ppf "Pmty_signature\n"; signature i ppf s; | Pmty_functor (s, mt1, mt2) -> line i ppf "Pmty_functor %a\n" fmt_string_loc s; Misc.may (module_type i ppf) mt1; module_type i ppf mt2; | Pmty_with (mt, l) -> line i ppf "Pmty_with\n"; module_type i ppf mt; list i with_constraint ppf l; | Pmty_typeof m -> line i ppf "Pmty_typeof\n"; module_expr i ppf m; | Pmty_extension (s, arg) -> line i ppf "Pmod_extension \"%s\"\n" s.txt; payload i ppf arg and signature i ppf x = list i signature_item ppf x and signature_item i ppf x = line i ppf "signature_item %a\n" fmt_location x.psig_loc; let i = i+1 in match x.psig_desc with | Psig_value vd -> line i ppf "Psig_value\n"; value_description i ppf vd; | Psig_type (rf, l) -> line i ppf "Psig_type %a\n" fmt_rec_flag rf; list i type_declaration ppf l; | Psig_typext te -> line i ppf "Psig_typext\n"; type_extension i ppf te | Psig_exception ext -> line i ppf "Psig_exception\n"; extension_constructor i ppf ext; | Psig_module pmd -> line i ppf "Psig_module %a\n" fmt_string_loc pmd.pmd_name; attributes i ppf pmd.pmd_attributes; module_type i ppf pmd.pmd_type | Psig_recmodule decls -> line i ppf "Psig_recmodule\n"; list i module_declaration ppf decls; | Psig_modtype x -> line i ppf "Psig_modtype %a\n" fmt_string_loc x.pmtd_name; attributes i ppf x.pmtd_attributes; modtype_declaration i ppf x.pmtd_type | Psig_open od -> line i ppf "Psig_open %a %a\n" fmt_override_flag od.popen_override fmt_longident_loc od.popen_lid; attributes i ppf od.popen_attributes | Psig_include incl -> line i ppf "Psig_include\n"; module_type i ppf incl.pincl_mod; attributes i ppf incl.pincl_attributes | Psig_class (l) -> line i ppf "Psig_class\n"; list i class_description ppf l; | Psig_class_type (l) -> line i ppf "Psig_class_type\n"; list i class_type_declaration ppf l; | Psig_extension ((s, arg), attrs) -> line i ppf "Psig_extension \"%s\"\n" s.txt; attributes i ppf attrs; payload i ppf arg | Psig_attribute (s, arg) -> line i ppf "Psig_attribute \"%s\"\n" s.txt; payload i ppf arg and modtype_declaration i ppf = function | None -> line i ppf "#abstract" | Some mt -> module_type (i+1) ppf mt and with_constraint i ppf x = match x with | Pwith_type (lid, td) -> line i ppf "Pwith_type %a\n" fmt_longident_loc lid; type_declaration (i+1) ppf td; | Pwith_typesubst (td) -> line i ppf "Pwith_typesubst\n"; type_declaration (i+1) ppf td; | Pwith_module (lid1, lid2) -> line i ppf "Pwith_module %a = %a\n" fmt_longident_loc lid1 fmt_longident_loc lid2; | Pwith_modsubst (s, li) -> line i ppf "Pwith_modsubst %a = %a\n" fmt_string_loc s fmt_longident_loc li; and module_expr i ppf x = line i ppf "module_expr %a\n" fmt_location x.pmod_loc; attributes i ppf x.pmod_attributes; let i = i+1 in match x.pmod_desc with | Pmod_ident (li) -> line i ppf "Pmod_ident %a\n" fmt_longident_loc li; | Pmod_structure (s) -> line i ppf "Pmod_structure\n"; structure i ppf s; | Pmod_functor (s, mt, me) -> line i ppf "Pmod_functor %a\n" fmt_string_loc s; Misc.may (module_type i ppf) mt; module_expr i ppf me; | Pmod_apply (me1, me2) -> line i ppf "Pmod_apply\n"; module_expr i ppf me1; module_expr i ppf me2; | Pmod_constraint (me, mt) -> line i ppf "Pmod_constraint\n"; module_expr i ppf me; module_type i ppf mt; | Pmod_unpack (e) -> line i ppf "Pmod_unpack\n"; expression i ppf e; | Pmod_extension (s, arg) -> line i ppf "Pmod_extension \"%s\"\n" s.txt; payload i ppf arg and structure i ppf x = list i structure_item ppf x and structure_item i ppf x = line i ppf "structure_item %a\n" fmt_location x.pstr_loc; let i = i+1 in match x.pstr_desc with | Pstr_eval (e, attrs) -> line i ppf "Pstr_eval\n"; attributes i ppf attrs; expression i ppf e; | Pstr_value (rf, l) -> line i ppf "Pstr_value %a\n" fmt_rec_flag rf; list i value_binding ppf l; | Pstr_primitive vd -> line i ppf "Pstr_primitive\n"; value_description i ppf vd; | Pstr_type (rf, l) -> line i ppf "Pstr_type %a\n" fmt_rec_flag rf; list i type_declaration ppf l; | Pstr_typext te -> line i ppf "Pstr_typext\n"; type_extension i ppf te | Pstr_exception ext -> line i ppf "Pstr_exception\n"; extension_constructor i ppf ext; | Pstr_module x -> line i ppf "Pstr_module\n"; module_binding i ppf x | Pstr_recmodule bindings -> line i ppf "Pstr_recmodule\n"; list i module_binding ppf bindings; | Pstr_modtype x -> line i ppf "Pstr_modtype %a\n" fmt_string_loc x.pmtd_name; attributes i ppf x.pmtd_attributes; modtype_declaration i ppf x.pmtd_type | Pstr_open od -> line i ppf "Pstr_open %a %a\n" fmt_override_flag od.popen_override fmt_longident_loc od.popen_lid; attributes i ppf od.popen_attributes | Pstr_class (l) -> line i ppf "Pstr_class\n"; list i class_declaration ppf l; | Pstr_class_type (l) -> line i ppf "Pstr_class_type\n"; list i class_type_declaration ppf l; | Pstr_include incl -> line i ppf "Pstr_include"; attributes i ppf incl.pincl_attributes; module_expr i ppf incl.pincl_mod | Pstr_extension ((s, arg), attrs) -> line i ppf "Pstr_extension \"%s\"\n" s.txt; attributes i ppf attrs; payload i ppf arg | Pstr_attribute (s, arg) -> line i ppf "Pstr_attribute \"%s\"\n" s.txt; payload i ppf arg and module_declaration i ppf pmd = string_loc i ppf pmd.pmd_name; attributes i ppf pmd.pmd_attributes; module_type (i+1) ppf pmd.pmd_type; and module_binding i ppf x = string_loc i ppf x.pmb_name; attributes i ppf x.pmb_attributes; module_expr (i+1) ppf x.pmb_expr and core_type_x_core_type_x_location i ppf (ct1, ct2, l) = line i ppf "<constraint> %a\n" fmt_location l; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; and constructor_decl i ppf {pcd_name; pcd_args; pcd_res; pcd_loc; pcd_attributes} = line i ppf "%a\n" fmt_location pcd_loc; line (i+1) ppf "%a\n" fmt_string_loc pcd_name; attributes i ppf pcd_attributes; constructor_arguments (i+1) ppf pcd_args; option (i+1) core_type ppf pcd_res and constructor_arguments i ppf = function | Pcstr_tuple l -> list i core_type ppf l | Pcstr_record l -> list i label_decl ppf l and label_decl i ppf {pld_name; pld_mutable; pld_type; pld_loc; pld_attributes}= line i ppf "%a\n" fmt_location pld_loc; attributes i ppf pld_attributes; line (i+1) ppf "%a\n" fmt_mutable_flag pld_mutable; line (i+1) ppf "%a" fmt_string_loc pld_name; core_type (i+1) ppf pld_type and longident_x_pattern i ppf (li, p) = line i ppf "%a\n" fmt_longident_loc li; pattern (i+1) ppf p; and case i ppf {pc_lhs; pc_guard; pc_rhs} = line i ppf "<case>\n"; pattern (i+1) ppf pc_lhs; begin match pc_guard with | None -> () | Some g -> line (i+1) ppf "<when>\n"; expression (i + 2) ppf g end; expression (i+1) ppf pc_rhs; and value_binding i ppf x = line i ppf "<def>\n"; attributes (i+1) ppf x.pvb_attributes; pattern (i+1) ppf x.pvb_pat; expression (i+1) ppf x.pvb_expr and string_x_expression i ppf (s, e) = line i ppf "<override> %a\n" fmt_string_loc s; expression (i+1) ppf e; and longident_x_expression i ppf (li, e) = line i ppf "%a\n" fmt_longident_loc li; expression (i+1) ppf e; and label_x_expression i ppf (l,e) = line i ppf "<arg>\n"; arg_label i ppf l; expression (i+1) ppf e; and label_x_bool_x_core_type_list i ppf x = match x with Rtag (l, attrs, b, ctl) -> line i ppf "Rtag \"%s\" %s\n" l (string_of_bool b); attributes (i+1) ppf attrs; list (i+1) core_type ppf ctl | Rinherit (ct) -> line i ppf "Rinherit\n"; core_type (i+1) ppf ct ;; let rec toplevel_phrase i ppf x = match x with | Ptop_def (s) -> line i ppf "Ptop_def\n"; structure (i+1) ppf s; | Ptop_dir (s, da) -> line i ppf "Ptop_dir \"%s\"\n" s; directive_argument i ppf da; and directive_argument i ppf x = match x with | Pdir_none -> line i ppf "Pdir_none\n" | Pdir_string (s) -> line i ppf "Pdir_string \"%s\"\n" s; | Pdir_int (n, None) -> line i ppf "Pdir_int %s\n" n; | Pdir_int (n, Some m) -> line i ppf "Pdir_int %s%c\n" n m; | Pdir_ident (li) -> line i ppf "Pdir_ident %a\n" fmt_longident li; | Pdir_bool (b) -> line i ppf "Pdir_bool %s\n" (string_of_bool b); ;; let interface ppf x = list 0 signature_item ppf x;; let implementation ppf x = list 0 structure_item ppf x;; let top_phrase ppf x = toplevel_phrase 0 ppf x;;
null
https://raw.githubusercontent.com/ocsigen/ocaml-eliom/497c6707f477cb3086dc6d8124384e74a8c379ae/parsing/printast.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ ... ...
, projet Para , INRIA Rocquencourt Copyright 1999 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Asttypes;; open Format;; open Lexing;; open Location;; open Parsetree;; let fmt_position with_name f l = let fname = if with_name then l.pos_fname else "" in if l.pos_lnum = -1 then fprintf f "%s[%d]" fname l.pos_cnum else fprintf f "%s[%d,%d+%d]" fname l.pos_lnum l.pos_bol (l.pos_cnum - l.pos_bol) ;; let fmt_location f loc = let p_2nd_name = loc.loc_start.pos_fname <> loc.loc_end.pos_fname in fprintf f "(%a..%a)" (fmt_position true) loc.loc_start (fmt_position p_2nd_name) loc.loc_end; if loc.loc_ghost then fprintf f " ghost"; ;; let rec fmt_longident_aux f x = match x with | Longident.Lident (s) -> fprintf f "%s" s; | Longident.Ldot (y, s) -> fprintf f "%a.%s" fmt_longident_aux y s; | Longident.Lapply (y, z) -> fprintf f "%a(%a)" fmt_longident_aux y fmt_longident_aux z; ;; let fmt_longident f x = fprintf f "\"%a\"" fmt_longident_aux x;; let fmt_longident_loc f (x : Longident.t loc) = fprintf f "\"%a\" %a" fmt_longident_aux x.txt fmt_location x.loc; ;; let fmt_string_loc f (x : string loc) = fprintf f "\"%s\" %a" x.txt fmt_location x.loc; ;; let fmt_char_option f = function | None -> fprintf f "None" | Some c -> fprintf f "Some %c" c let fmt_constant f x = match x with | Pconst_integer (i,m) -> fprintf f "PConst_int (%s,%a)" i fmt_char_option m; | Pconst_char (c) -> fprintf f "PConst_char %02x" (Char.code c); | Pconst_string (s, None) -> fprintf f "PConst_string(%S,None)" s; | Pconst_string (s, Some delim) -> fprintf f "PConst_string (%S,Some %S)" s delim; | Pconst_float (s,m) -> fprintf f "PConst_float (%s,%a)" s fmt_char_option m; ;; let fmt_mutable_flag f x = match x with | Immutable -> fprintf f "Immutable"; | Mutable -> fprintf f "Mutable"; ;; let fmt_virtual_flag f x = match x with | Virtual -> fprintf f "Virtual"; | Concrete -> fprintf f "Concrete"; ;; let fmt_override_flag f x = match x with | Override -> fprintf f "Override"; | Fresh -> fprintf f "Fresh"; ;; let fmt_closed_flag f x = match x with | Closed -> fprintf f "Closed" | Open -> fprintf f "Open" let fmt_rec_flag f x = match x with | Nonrecursive -> fprintf f "Nonrec"; | Recursive -> fprintf f "Rec"; ;; let fmt_direction_flag f x = match x with | Upto -> fprintf f "Up"; | Downto -> fprintf f "Down"; ;; let fmt_private_flag f x = match x with | Public -> fprintf f "Public"; | Private -> fprintf f "Private"; ;; fprintf f "%s" (String.make ((2*i) mod 72) ' '); ;; let list i f ppf l = match l with | [] -> line i ppf "[]\n"; | _ :: _ -> line i ppf "[\n"; List.iter (f (i+1) ppf) l; line i ppf "]\n"; ;; let option i f ppf x = match x with | None -> line i ppf "None\n"; | Some x -> line i ppf "Some\n"; f (i+1) ppf x; ;; let longident_loc i ppf li = line i ppf "%a\n" fmt_longident_loc li;; let string i ppf s = line i ppf "\"%s\"\n" s;; let string_loc i ppf s = line i ppf "%a\n" fmt_string_loc s;; let arg_label i ppf = function | Nolabel -> line i ppf "Nolabel\n" | Optional s -> line i ppf "Optional \"%s\"\n" s | Labelled s -> line i ppf "Labelled \"%s\"\n" s ;; let rec core_type i ppf x = line i ppf "core_type %a\n" fmt_location x.ptyp_loc; attributes i ppf x.ptyp_attributes; let i = i+1 in match x.ptyp_desc with | Ptyp_any -> line i ppf "Ptyp_any\n"; | Ptyp_var (s) -> line i ppf "Ptyp_var %s\n" s; | Ptyp_arrow (l, ct1, ct2) -> line i ppf "Ptyp_arrow\n"; arg_label i ppf l; core_type i ppf ct1; core_type i ppf ct2; | Ptyp_tuple l -> line i ppf "Ptyp_tuple\n"; list i core_type ppf l; | Ptyp_constr (li, l) -> line i ppf "Ptyp_constr %a\n" fmt_longident_loc li; list i core_type ppf l; | Ptyp_variant (l, closed, low) -> line i ppf "Ptyp_variant closed=%a\n" fmt_closed_flag closed; list i label_x_bool_x_core_type_list ppf l; option i (fun i -> list i string) ppf low | Ptyp_object (l, c) -> line i ppf "Ptyp_object %a\n" fmt_closed_flag c; let i = i + 1 in List.iter (fun (s, attrs, t) -> line i ppf "method %s\n" s; attributes i ppf attrs; core_type (i + 1) ppf t ) l | Ptyp_class (li, l) -> line i ppf "Ptyp_class %a\n" fmt_longident_loc li; list i core_type ppf l | Ptyp_alias (ct, s) -> line i ppf "Ptyp_alias \"%s\"\n" s; core_type i ppf ct; | Ptyp_poly (sl, ct) -> line i ppf "Ptyp_poly%a\n" (fun ppf -> List.iter (fun x -> fprintf ppf " '%s" x)) sl; core_type i ppf ct; | Ptyp_package (s, l) -> line i ppf "Ptyp_package %a\n" fmt_longident_loc s; list i package_with ppf l; | Ptyp_extension (s, arg) -> line i ppf "Ptyp_extension \"%s\"\n" s.txt; payload i ppf arg and package_with i ppf (s, t) = line i ppf "with type %a\n" fmt_longident_loc s; core_type i ppf t and pattern i ppf x = line i ppf "pattern %a\n" fmt_location x.ppat_loc; attributes i ppf x.ppat_attributes; let i = i+1 in match x.ppat_desc with | Ppat_any -> line i ppf "Ppat_any\n"; | Ppat_var (s) -> line i ppf "Ppat_var %a\n" fmt_string_loc s; | Ppat_alias (p, s) -> line i ppf "Ppat_alias %a\n" fmt_string_loc s; pattern i ppf p; | Ppat_constant (c) -> line i ppf "Ppat_constant %a\n" fmt_constant c; | Ppat_interval (c1, c2) -> line i ppf "Ppat_interval %a..%a\n" fmt_constant c1 fmt_constant c2; | Ppat_tuple (l) -> line i ppf "Ppat_tuple\n"; list i pattern ppf l; | Ppat_construct (li, po) -> line i ppf "Ppat_construct %a\n" fmt_longident_loc li; option i pattern ppf po; | Ppat_variant (l, po) -> line i ppf "Ppat_variant \"%s\"\n" l; option i pattern ppf po; | Ppat_record (l, c) -> line i ppf "Ppat_record %a\n" fmt_closed_flag c; list i longident_x_pattern ppf l; | Ppat_array (l) -> line i ppf "Ppat_array\n"; list i pattern ppf l; | Ppat_or (p1, p2) -> line i ppf "Ppat_or\n"; pattern i ppf p1; pattern i ppf p2; | Ppat_lazy p -> line i ppf "Ppat_lazy\n"; pattern i ppf p; | Ppat_constraint (p, ct) -> line i ppf "Ppat_constraint\n"; pattern i ppf p; core_type i ppf ct; | Ppat_type (li) -> line i ppf "Ppat_type\n"; longident_loc i ppf li | Ppat_unpack s -> line i ppf "Ppat_unpack %a\n" fmt_string_loc s; | Ppat_exception p -> line i ppf "Ppat_exception\n"; pattern i ppf p | Ppat_extension (s, arg) -> line i ppf "Ppat_extension \"%s\"\n" s.txt; payload i ppf arg and expression i ppf x = line i ppf "expression %a\n" fmt_location x.pexp_loc; attributes i ppf x.pexp_attributes; let i = i+1 in match x.pexp_desc with | Pexp_ident (li) -> line i ppf "Pexp_ident %a\n" fmt_longident_loc li; | Pexp_constant (c) -> line i ppf "Pexp_constant %a\n" fmt_constant c; | Pexp_let (rf, l, e) -> line i ppf "Pexp_let %a\n" fmt_rec_flag rf; list i value_binding ppf l; expression i ppf e; | Pexp_function l -> line i ppf "Pexp_function\n"; list i case ppf l; | Pexp_fun (l, eo, p, e) -> line i ppf "Pexp_fun\n"; arg_label i ppf l; option i expression ppf eo; pattern i ppf p; expression i ppf e; | Pexp_apply (e, l) -> line i ppf "Pexp_apply\n"; expression i ppf e; list i label_x_expression ppf l; | Pexp_match (e, l) -> line i ppf "Pexp_match\n"; expression i ppf e; list i case ppf l; | Pexp_try (e, l) -> line i ppf "Pexp_try\n"; expression i ppf e; list i case ppf l; | Pexp_tuple (l) -> line i ppf "Pexp_tuple\n"; list i expression ppf l; | Pexp_construct (li, eo) -> line i ppf "Pexp_construct %a\n" fmt_longident_loc li; option i expression ppf eo; | Pexp_variant (l, eo) -> line i ppf "Pexp_variant \"%s\"\n" l; option i expression ppf eo; | Pexp_record (l, eo) -> line i ppf "Pexp_record\n"; list i longident_x_expression ppf l; option i expression ppf eo; | Pexp_field (e, li) -> line i ppf "Pexp_field\n"; expression i ppf e; longident_loc i ppf li; | Pexp_setfield (e1, li, e2) -> line i ppf "Pexp_setfield\n"; expression i ppf e1; longident_loc i ppf li; expression i ppf e2; | Pexp_array (l) -> line i ppf "Pexp_array\n"; list i expression ppf l; | Pexp_ifthenelse (e1, e2, eo) -> line i ppf "Pexp_ifthenelse\n"; expression i ppf e1; expression i ppf e2; option i expression ppf eo; | Pexp_sequence (e1, e2) -> line i ppf "Pexp_sequence\n"; expression i ppf e1; expression i ppf e2; | Pexp_while (e1, e2) -> line i ppf "Pexp_while\n"; expression i ppf e1; expression i ppf e2; | Pexp_for (p, e1, e2, df, e3) -> line i ppf "Pexp_for %a\n" fmt_direction_flag df; pattern i ppf p; expression i ppf e1; expression i ppf e2; expression i ppf e3; | Pexp_constraint (e, ct) -> line i ppf "Pexp_constraint\n"; expression i ppf e; core_type i ppf ct; | Pexp_coerce (e, cto1, cto2) -> line i ppf "Pexp_coerce\n"; expression i ppf e; option i core_type ppf cto1; core_type i ppf cto2; | Pexp_send (e, s) -> line i ppf "Pexp_send \"%s\"\n" s; expression i ppf e; | Pexp_new (li) -> line i ppf "Pexp_new %a\n" fmt_longident_loc li; | Pexp_setinstvar (s, e) -> line i ppf "Pexp_setinstvar %a\n" fmt_string_loc s; expression i ppf e; | Pexp_override (l) -> line i ppf "Pexp_override\n"; list i string_x_expression ppf l; | Pexp_letmodule (s, me, e) -> line i ppf "Pexp_letmodule %a\n" fmt_string_loc s; module_expr i ppf me; expression i ppf e; | Pexp_assert (e) -> line i ppf "Pexp_assert\n"; expression i ppf e; | Pexp_lazy (e) -> line i ppf "Pexp_lazy\n"; expression i ppf e; | Pexp_poly (e, cto) -> line i ppf "Pexp_poly\n"; expression i ppf e; option i core_type ppf cto; | Pexp_object s -> line i ppf "Pexp_object\n"; class_structure i ppf s | Pexp_newtype (s, e) -> line i ppf "Pexp_newtype \"%s\"\n" s; expression i ppf e | Pexp_pack me -> line i ppf "Pexp_pack\n"; module_expr i ppf me | Pexp_open (ovf, m, e) -> line i ppf "Pexp_open %a \"%a\"\n" fmt_override_flag ovf fmt_longident_loc m; expression i ppf e | Pexp_extension (s, arg) -> line i ppf "Pexp_extension \"%s\"\n" s.txt; payload i ppf arg | Pexp_unreachable -> line i ppf "Pexp_unreachable" and value_description i ppf x = line i ppf "value_description %a %a\n" fmt_string_loc x.pval_name fmt_location x.pval_loc; attributes i ppf x.pval_attributes; core_type (i+1) ppf x.pval_type; list (i+1) string ppf x.pval_prim and type_parameter i ppf (x, _variance) = core_type i ppf x and type_declaration i ppf x = line i ppf "type_declaration %a %a\n" fmt_string_loc x.ptype_name fmt_location x.ptype_loc; attributes i ppf x.ptype_attributes; let i = i+1 in line i ppf "ptype_params =\n"; list (i+1) type_parameter ppf x.ptype_params; line i ppf "ptype_cstrs =\n"; list (i+1) core_type_x_core_type_x_location ppf x.ptype_cstrs; line i ppf "ptype_kind =\n"; type_kind (i+1) ppf x.ptype_kind; line i ppf "ptype_private = %a\n" fmt_private_flag x.ptype_private; line i ppf "ptype_manifest =\n"; option (i+1) core_type ppf x.ptype_manifest and attributes i ppf l = let i = i + 1 in List.iter (fun (s, arg) -> line i ppf "attribute \"%s\"\n" s.txt; payload (i + 1) ppf arg; ) l and payload i ppf = function | PStr x -> structure i ppf x | PSig x -> signature i ppf x | PTyp x -> core_type i ppf x | PPat (x, None) -> pattern i ppf x | PPat (x, Some g) -> pattern i ppf x; line i ppf "<when>\n"; expression (i + 1) ppf g and type_kind i ppf x = match x with | Ptype_abstract -> line i ppf "Ptype_abstract\n" | Ptype_variant l -> line i ppf "Ptype_variant\n"; list (i+1) constructor_decl ppf l; | Ptype_record l -> line i ppf "Ptype_record\n"; list (i+1) label_decl ppf l; | Ptype_open -> line i ppf "Ptype_open\n"; and type_extension i ppf x = line i ppf "type_extension\n"; attributes i ppf x.ptyext_attributes; let i = i+1 in line i ppf "ptyext_path = %a\n" fmt_longident_loc x.ptyext_path; line i ppf "ptyext_params =\n"; list (i+1) type_parameter ppf x.ptyext_params; line i ppf "ptyext_constructors =\n"; list (i+1) extension_constructor ppf x.ptyext_constructors; line i ppf "ptyext_private = %a\n" fmt_private_flag x.ptyext_private; and extension_constructor i ppf x = line i ppf "extension_constructor %a\n" fmt_location x.pext_loc; attributes i ppf x.pext_attributes; let i = i + 1 in line i ppf "pext_name = \"%s\"\n" x.pext_name.txt; line i ppf "pext_kind =\n"; extension_constructor_kind (i + 1) ppf x.pext_kind; and extension_constructor_kind i ppf x = match x with Pext_decl(a, r) -> line i ppf "Pext_decl\n"; constructor_arguments (i+1) ppf a; option (i+1) core_type ppf r; | Pext_rebind li -> line i ppf "Pext_rebind\n"; line (i+1) ppf "%a\n" fmt_longident_loc li; and class_type i ppf x = line i ppf "class_type %a\n" fmt_location x.pcty_loc; attributes i ppf x.pcty_attributes; let i = i+1 in match x.pcty_desc with | Pcty_constr (li, l) -> line i ppf "Pcty_constr %a\n" fmt_longident_loc li; list i core_type ppf l; | Pcty_signature (cs) -> line i ppf "Pcty_signature\n"; class_signature i ppf cs; | Pcty_arrow (l, co, cl) -> line i ppf "Pcty_arrow\n"; arg_label i ppf l; core_type i ppf co; class_type i ppf cl; | Pcty_extension (s, arg) -> line i ppf "Pcty_extension \"%s\"\n" s.txt; payload i ppf arg and class_signature i ppf cs = line i ppf "class_signature\n"; core_type (i+1) ppf cs.pcsig_self; list (i+1) class_type_field ppf cs.pcsig_fields; and class_type_field i ppf x = line i ppf "class_type_field %a\n" fmt_location x.pctf_loc; let i = i+1 in attributes i ppf x.pctf_attributes; match x.pctf_desc with | Pctf_inherit (ct) -> line i ppf "Pctf_inherit\n"; class_type i ppf ct; | Pctf_val (s, mf, vf, ct) -> line i ppf "Pctf_val \"%s\" %a %a\n" s fmt_mutable_flag mf fmt_virtual_flag vf; core_type (i+1) ppf ct; | Pctf_method (s, pf, vf, ct) -> line i ppf "Pctf_method \"%s\" %a %a\n" s fmt_private_flag pf fmt_virtual_flag vf; core_type (i+1) ppf ct; | Pctf_constraint (ct1, ct2) -> line i ppf "Pctf_constraint\n"; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; | Pctf_attribute (s, arg) -> line i ppf "Pctf_attribute \"%s\"\n" s.txt; payload i ppf arg | Pctf_extension (s, arg) -> line i ppf "Pctf_extension \"%s\"\n" s.txt; payload i ppf arg and class_description i ppf x = line i ppf "class_description %a\n" fmt_location x.pci_loc; attributes i ppf x.pci_attributes; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.pci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.pci_params; line i ppf "pci_name = %a\n" fmt_string_loc x.pci_name; line i ppf "pci_expr =\n"; class_type (i+1) ppf x.pci_expr; and class_type_declaration i ppf x = line i ppf "class_type_declaration %a\n" fmt_location x.pci_loc; attributes i ppf x.pci_attributes; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.pci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.pci_params; line i ppf "pci_name = %a\n" fmt_string_loc x.pci_name; line i ppf "pci_expr =\n"; class_type (i+1) ppf x.pci_expr; and class_expr i ppf x = line i ppf "class_expr %a\n" fmt_location x.pcl_loc; attributes i ppf x.pcl_attributes; let i = i+1 in match x.pcl_desc with | Pcl_constr (li, l) -> line i ppf "Pcl_constr %a\n" fmt_longident_loc li; list i core_type ppf l; | Pcl_structure (cs) -> line i ppf "Pcl_structure\n"; class_structure i ppf cs; | Pcl_fun (l, eo, p, e) -> line i ppf "Pcl_fun\n"; arg_label i ppf l; option i expression ppf eo; pattern i ppf p; class_expr i ppf e; | Pcl_apply (ce, l) -> line i ppf "Pcl_apply\n"; class_expr i ppf ce; list i label_x_expression ppf l; | Pcl_let (rf, l, ce) -> line i ppf "Pcl_let %a\n" fmt_rec_flag rf; list i value_binding ppf l; class_expr i ppf ce; | Pcl_constraint (ce, ct) -> line i ppf "Pcl_constraint\n"; class_expr i ppf ce; class_type i ppf ct; | Pcl_extension (s, arg) -> line i ppf "Pcl_extension \"%s\"\n" s.txt; payload i ppf arg and class_structure i ppf { pcstr_self = p; pcstr_fields = l } = line i ppf "class_structure\n"; pattern (i+1) ppf p; list (i+1) class_field ppf l; and class_field i ppf x = line i ppf "class_field %a\n" fmt_location x.pcf_loc; let i = i + 1 in attributes i ppf x.pcf_attributes; match x.pcf_desc with | Pcf_inherit (ovf, ce, so) -> line i ppf "Pcf_inherit %a\n" fmt_override_flag ovf; class_expr (i+1) ppf ce; option (i+1) string ppf so; | Pcf_val (s, mf, k) -> line i ppf "Pcf_val %a\n" fmt_mutable_flag mf; line (i+1) ppf "%a\n" fmt_string_loc s; class_field_kind (i+1) ppf k | Pcf_method (s, pf, k) -> line i ppf "Pcf_method %a\n" fmt_private_flag pf; line (i+1) ppf "%a\n" fmt_string_loc s; class_field_kind (i+1) ppf k | Pcf_constraint (ct1, ct2) -> line i ppf "Pcf_constraint\n"; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; | Pcf_initializer (e) -> line i ppf "Pcf_initializer\n"; expression (i+1) ppf e; | Pcf_attribute (s, arg) -> line i ppf "Pcf_attribute \"%s\"\n" s.txt; payload i ppf arg | Pcf_extension (s, arg) -> line i ppf "Pcf_extension \"%s\"\n" s.txt; payload i ppf arg and class_field_kind i ppf = function | Cfk_concrete (o, e) -> line i ppf "Concrete %a\n" fmt_override_flag o; expression i ppf e | Cfk_virtual t -> line i ppf "Virtual\n"; core_type i ppf t and class_declaration i ppf x = line i ppf "class_declaration %a\n" fmt_location x.pci_loc; attributes i ppf x.pci_attributes; let i = i+1 in line i ppf "pci_virt = %a\n" fmt_virtual_flag x.pci_virt; line i ppf "pci_params =\n"; list (i+1) type_parameter ppf x.pci_params; line i ppf "pci_name = %a\n" fmt_string_loc x.pci_name; line i ppf "pci_expr =\n"; class_expr (i+1) ppf x.pci_expr; and module_type i ppf x = line i ppf "module_type %a\n" fmt_location x.pmty_loc; attributes i ppf x.pmty_attributes; let i = i+1 in match x.pmty_desc with | Pmty_ident li -> line i ppf "Pmty_ident %a\n" fmt_longident_loc li; | Pmty_alias li -> line i ppf "Pmty_alias %a\n" fmt_longident_loc li; | Pmty_signature (s) -> line i ppf "Pmty_signature\n"; signature i ppf s; | Pmty_functor (s, mt1, mt2) -> line i ppf "Pmty_functor %a\n" fmt_string_loc s; Misc.may (module_type i ppf) mt1; module_type i ppf mt2; | Pmty_with (mt, l) -> line i ppf "Pmty_with\n"; module_type i ppf mt; list i with_constraint ppf l; | Pmty_typeof m -> line i ppf "Pmty_typeof\n"; module_expr i ppf m; | Pmty_extension (s, arg) -> line i ppf "Pmod_extension \"%s\"\n" s.txt; payload i ppf arg and signature i ppf x = list i signature_item ppf x and signature_item i ppf x = line i ppf "signature_item %a\n" fmt_location x.psig_loc; let i = i+1 in match x.psig_desc with | Psig_value vd -> line i ppf "Psig_value\n"; value_description i ppf vd; | Psig_type (rf, l) -> line i ppf "Psig_type %a\n" fmt_rec_flag rf; list i type_declaration ppf l; | Psig_typext te -> line i ppf "Psig_typext\n"; type_extension i ppf te | Psig_exception ext -> line i ppf "Psig_exception\n"; extension_constructor i ppf ext; | Psig_module pmd -> line i ppf "Psig_module %a\n" fmt_string_loc pmd.pmd_name; attributes i ppf pmd.pmd_attributes; module_type i ppf pmd.pmd_type | Psig_recmodule decls -> line i ppf "Psig_recmodule\n"; list i module_declaration ppf decls; | Psig_modtype x -> line i ppf "Psig_modtype %a\n" fmt_string_loc x.pmtd_name; attributes i ppf x.pmtd_attributes; modtype_declaration i ppf x.pmtd_type | Psig_open od -> line i ppf "Psig_open %a %a\n" fmt_override_flag od.popen_override fmt_longident_loc od.popen_lid; attributes i ppf od.popen_attributes | Psig_include incl -> line i ppf "Psig_include\n"; module_type i ppf incl.pincl_mod; attributes i ppf incl.pincl_attributes | Psig_class (l) -> line i ppf "Psig_class\n"; list i class_description ppf l; | Psig_class_type (l) -> line i ppf "Psig_class_type\n"; list i class_type_declaration ppf l; | Psig_extension ((s, arg), attrs) -> line i ppf "Psig_extension \"%s\"\n" s.txt; attributes i ppf attrs; payload i ppf arg | Psig_attribute (s, arg) -> line i ppf "Psig_attribute \"%s\"\n" s.txt; payload i ppf arg and modtype_declaration i ppf = function | None -> line i ppf "#abstract" | Some mt -> module_type (i+1) ppf mt and with_constraint i ppf x = match x with | Pwith_type (lid, td) -> line i ppf "Pwith_type %a\n" fmt_longident_loc lid; type_declaration (i+1) ppf td; | Pwith_typesubst (td) -> line i ppf "Pwith_typesubst\n"; type_declaration (i+1) ppf td; | Pwith_module (lid1, lid2) -> line i ppf "Pwith_module %a = %a\n" fmt_longident_loc lid1 fmt_longident_loc lid2; | Pwith_modsubst (s, li) -> line i ppf "Pwith_modsubst %a = %a\n" fmt_string_loc s fmt_longident_loc li; and module_expr i ppf x = line i ppf "module_expr %a\n" fmt_location x.pmod_loc; attributes i ppf x.pmod_attributes; let i = i+1 in match x.pmod_desc with | Pmod_ident (li) -> line i ppf "Pmod_ident %a\n" fmt_longident_loc li; | Pmod_structure (s) -> line i ppf "Pmod_structure\n"; structure i ppf s; | Pmod_functor (s, mt, me) -> line i ppf "Pmod_functor %a\n" fmt_string_loc s; Misc.may (module_type i ppf) mt; module_expr i ppf me; | Pmod_apply (me1, me2) -> line i ppf "Pmod_apply\n"; module_expr i ppf me1; module_expr i ppf me2; | Pmod_constraint (me, mt) -> line i ppf "Pmod_constraint\n"; module_expr i ppf me; module_type i ppf mt; | Pmod_unpack (e) -> line i ppf "Pmod_unpack\n"; expression i ppf e; | Pmod_extension (s, arg) -> line i ppf "Pmod_extension \"%s\"\n" s.txt; payload i ppf arg and structure i ppf x = list i structure_item ppf x and structure_item i ppf x = line i ppf "structure_item %a\n" fmt_location x.pstr_loc; let i = i+1 in match x.pstr_desc with | Pstr_eval (e, attrs) -> line i ppf "Pstr_eval\n"; attributes i ppf attrs; expression i ppf e; | Pstr_value (rf, l) -> line i ppf "Pstr_value %a\n" fmt_rec_flag rf; list i value_binding ppf l; | Pstr_primitive vd -> line i ppf "Pstr_primitive\n"; value_description i ppf vd; | Pstr_type (rf, l) -> line i ppf "Pstr_type %a\n" fmt_rec_flag rf; list i type_declaration ppf l; | Pstr_typext te -> line i ppf "Pstr_typext\n"; type_extension i ppf te | Pstr_exception ext -> line i ppf "Pstr_exception\n"; extension_constructor i ppf ext; | Pstr_module x -> line i ppf "Pstr_module\n"; module_binding i ppf x | Pstr_recmodule bindings -> line i ppf "Pstr_recmodule\n"; list i module_binding ppf bindings; | Pstr_modtype x -> line i ppf "Pstr_modtype %a\n" fmt_string_loc x.pmtd_name; attributes i ppf x.pmtd_attributes; modtype_declaration i ppf x.pmtd_type | Pstr_open od -> line i ppf "Pstr_open %a %a\n" fmt_override_flag od.popen_override fmt_longident_loc od.popen_lid; attributes i ppf od.popen_attributes | Pstr_class (l) -> line i ppf "Pstr_class\n"; list i class_declaration ppf l; | Pstr_class_type (l) -> line i ppf "Pstr_class_type\n"; list i class_type_declaration ppf l; | Pstr_include incl -> line i ppf "Pstr_include"; attributes i ppf incl.pincl_attributes; module_expr i ppf incl.pincl_mod | Pstr_extension ((s, arg), attrs) -> line i ppf "Pstr_extension \"%s\"\n" s.txt; attributes i ppf attrs; payload i ppf arg | Pstr_attribute (s, arg) -> line i ppf "Pstr_attribute \"%s\"\n" s.txt; payload i ppf arg and module_declaration i ppf pmd = string_loc i ppf pmd.pmd_name; attributes i ppf pmd.pmd_attributes; module_type (i+1) ppf pmd.pmd_type; and module_binding i ppf x = string_loc i ppf x.pmb_name; attributes i ppf x.pmb_attributes; module_expr (i+1) ppf x.pmb_expr and core_type_x_core_type_x_location i ppf (ct1, ct2, l) = line i ppf "<constraint> %a\n" fmt_location l; core_type (i+1) ppf ct1; core_type (i+1) ppf ct2; and constructor_decl i ppf {pcd_name; pcd_args; pcd_res; pcd_loc; pcd_attributes} = line i ppf "%a\n" fmt_location pcd_loc; line (i+1) ppf "%a\n" fmt_string_loc pcd_name; attributes i ppf pcd_attributes; constructor_arguments (i+1) ppf pcd_args; option (i+1) core_type ppf pcd_res and constructor_arguments i ppf = function | Pcstr_tuple l -> list i core_type ppf l | Pcstr_record l -> list i label_decl ppf l and label_decl i ppf {pld_name; pld_mutable; pld_type; pld_loc; pld_attributes}= line i ppf "%a\n" fmt_location pld_loc; attributes i ppf pld_attributes; line (i+1) ppf "%a\n" fmt_mutable_flag pld_mutable; line (i+1) ppf "%a" fmt_string_loc pld_name; core_type (i+1) ppf pld_type and longident_x_pattern i ppf (li, p) = line i ppf "%a\n" fmt_longident_loc li; pattern (i+1) ppf p; and case i ppf {pc_lhs; pc_guard; pc_rhs} = line i ppf "<case>\n"; pattern (i+1) ppf pc_lhs; begin match pc_guard with | None -> () | Some g -> line (i+1) ppf "<when>\n"; expression (i + 2) ppf g end; expression (i+1) ppf pc_rhs; and value_binding i ppf x = line i ppf "<def>\n"; attributes (i+1) ppf x.pvb_attributes; pattern (i+1) ppf x.pvb_pat; expression (i+1) ppf x.pvb_expr and string_x_expression i ppf (s, e) = line i ppf "<override> %a\n" fmt_string_loc s; expression (i+1) ppf e; and longident_x_expression i ppf (li, e) = line i ppf "%a\n" fmt_longident_loc li; expression (i+1) ppf e; and label_x_expression i ppf (l,e) = line i ppf "<arg>\n"; arg_label i ppf l; expression (i+1) ppf e; and label_x_bool_x_core_type_list i ppf x = match x with Rtag (l, attrs, b, ctl) -> line i ppf "Rtag \"%s\" %s\n" l (string_of_bool b); attributes (i+1) ppf attrs; list (i+1) core_type ppf ctl | Rinherit (ct) -> line i ppf "Rinherit\n"; core_type (i+1) ppf ct ;; let rec toplevel_phrase i ppf x = match x with | Ptop_def (s) -> line i ppf "Ptop_def\n"; structure (i+1) ppf s; | Ptop_dir (s, da) -> line i ppf "Ptop_dir \"%s\"\n" s; directive_argument i ppf da; and directive_argument i ppf x = match x with | Pdir_none -> line i ppf "Pdir_none\n" | Pdir_string (s) -> line i ppf "Pdir_string \"%s\"\n" s; | Pdir_int (n, None) -> line i ppf "Pdir_int %s\n" n; | Pdir_int (n, Some m) -> line i ppf "Pdir_int %s%c\n" n m; | Pdir_ident (li) -> line i ppf "Pdir_ident %a\n" fmt_longident li; | Pdir_bool (b) -> line i ppf "Pdir_bool %s\n" (string_of_bool b); ;; let interface ppf x = list 0 signature_item ppf x;; let implementation ppf x = list 0 structure_item ppf x;; let top_phrase ppf x = toplevel_phrase 0 ppf x;;
51176c0f91d92ba5df7e08cbb299c886fc84903aedf6aa076eff46739a55656e
matterandvoid-space/todomvc-fulcro-subscriptions
util.cljc
(ns space.matterandvoid.todomvc.util (:refer-clojure :exclude [uuid]) (:require [com.yetanalytics.squuid :refer [generate-squuid]])) (defn uuid [] (generate-squuid))
null
https://raw.githubusercontent.com/matterandvoid-space/todomvc-fulcro-subscriptions/e2e244936efe1005fa2cac204a24758b067aac4e/src/main/space/matterandvoid/todomvc/util.cljc
clojure
(ns space.matterandvoid.todomvc.util (:refer-clojure :exclude [uuid]) (:require [com.yetanalytics.squuid :refer [generate-squuid]])) (defn uuid [] (generate-squuid))
969e74c508ec84f7c5a0b0279c4a08f82412f33cbc9d2913e171a32963a51a13
into-docker/unixsocket-http
SingletonSocketFactory.clj
(ns ^:no-doc unixsocket-http.impl.SingletonSocketFactory "Wrapper around a `SocketFactory` that will cache the created socket." (:gen-class :name unixsocket_http.impl.SingletonSocketFactory :extends javax.net.SocketFactory :init init :state socket :constructors {[javax.net.SocketFactory] []} :methods [[getSocket [] java.net.Socket]]) (:import [java.net InetAddress InetSocketAddress Socket] [javax.net SocketFactory])) # # Constructor (defn -init [^SocketFactory factory] [[] (delay (.createSocket factory))]) # # Methods (defn- get-socket ^Socket [^unixsocket_http.impl.SingletonSocketFactory this] @(.-socket this)) (defn -createSocket ([this] (get-socket this)) ([this ^InetAddress _ ^Integer _] (doto (get-socket this) (.connect (InetSocketAddress. 0)))) ([this ^InetAddress _ ^Integer _ ^InetAddress _ ^Integer _] (doto (get-socket this) (.connect (InetSocketAddress. 0))))) (defn -getSocket [this] (get-socket this)) (defn -toString [^unixsocket_http.impl.SingletonSocketFactory this] (str (.-socket this)))
null
https://raw.githubusercontent.com/into-docker/unixsocket-http/2f40386664744e32394c48641fe1c5adbc121875/src/unixsocket_http/impl/SingletonSocketFactory.clj
clojure
(ns ^:no-doc unixsocket-http.impl.SingletonSocketFactory "Wrapper around a `SocketFactory` that will cache the created socket." (:gen-class :name unixsocket_http.impl.SingletonSocketFactory :extends javax.net.SocketFactory :init init :state socket :constructors {[javax.net.SocketFactory] []} :methods [[getSocket [] java.net.Socket]]) (:import [java.net InetAddress InetSocketAddress Socket] [javax.net SocketFactory])) # # Constructor (defn -init [^SocketFactory factory] [[] (delay (.createSocket factory))]) # # Methods (defn- get-socket ^Socket [^unixsocket_http.impl.SingletonSocketFactory this] @(.-socket this)) (defn -createSocket ([this] (get-socket this)) ([this ^InetAddress _ ^Integer _] (doto (get-socket this) (.connect (InetSocketAddress. 0)))) ([this ^InetAddress _ ^Integer _ ^InetAddress _ ^Integer _] (doto (get-socket this) (.connect (InetSocketAddress. 0))))) (defn -getSocket [this] (get-socket this)) (defn -toString [^unixsocket_http.impl.SingletonSocketFactory this] (str (.-socket this)))
1e0568fdd6f7fd629b2e497b67b6021613b69b75f34377179e5c2e9d071ca80e
Octachron/codept
name.ml
module Core = struct type t = string type name = t let compare (x:name) (y:name) = compare x y let pp = Pp.string let pp_opt ppf = function | None -> pp ppf "_" | Some s -> pp ppf s end include Core module Set = struct include Set.Make(Core) let pp ppf s = Pp.(clist Core.pp) ppf (elements s) let of_list = List.fold_left (fun set x -> add x set) empty end type set = Set.t module Map = struct include (Map.Make(Core)) let find_opt k m = try Some(find k m) with Not_found -> None let union' s = union (fun _key _m1 m2 -> Some m2) s let update key f m = try add key (f (find key m)) m with Not_found -> m end type 'a map = 'a Map.t
null
https://raw.githubusercontent.com/Octachron/codept/2d2a95fde3f67cdd0f5a1b68d8b8b47aefef9290/lib/name.ml
ocaml
module Core = struct type t = string type name = t let compare (x:name) (y:name) = compare x y let pp = Pp.string let pp_opt ppf = function | None -> pp ppf "_" | Some s -> pp ppf s end include Core module Set = struct include Set.Make(Core) let pp ppf s = Pp.(clist Core.pp) ppf (elements s) let of_list = List.fold_left (fun set x -> add x set) empty end type set = Set.t module Map = struct include (Map.Make(Core)) let find_opt k m = try Some(find k m) with Not_found -> None let union' s = union (fun _key _m1 m2 -> Some m2) s let update key f m = try add key (f (find key m)) m with Not_found -> m end type 'a map = 'a Map.t
e6a9d54dbc18ea67c6677bbae222f72ff447321aab089976ecd4e39971cf10c1
footprintanalytics/footprint-web
activity.clj
(ns metabase.models.activity (:require [metabase.api.common :as api] [metabase.events :as events] [metabase.models.card :refer [Card]] [metabase.models.dashboard :refer [Dashboard]] [metabase.models.interface :as mi] [metabase.models.metric :refer [Metric]] [metabase.models.pulse :refer [Pulse]] [metabase.models.segment :refer [Segment]] [metabase.util :as u] [toucan.db :as db] [toucan.models :as models])) ;;; ------------------------------------------------- Perms Checking ------------------------------------------------- (def ^:private model->entity {"card" Card "dashboard" Dashboard "metric" Metric "pulse" Pulse "segment" Segment}) (defmulti can-? "Implementation for `can-read?`/`can-write?` for items in the activity feed. Dispatches off of the activity `:topic`, e.g. `:user-joined`. `perms-check-fn` is `can-read?` or `can-write?` and should be called as needed on models the activity records." {:arglists '([perms-check-fn activity])} (fn [_ {:keys [topic]}] topic)) ;; For now only admins can see when another user joined -- we don't want every user knowing about every other user. In ;; the future we might want to change this and come up with some sort of system where we can determine which users get ;; to see other users -- perhaps if they are in a group together other than 'All Users' (defmethod can-? :user-joined [_ _] api/*is-superuser?*) ;; For every other activity topic we'll look at the read/write perms for the object the activty is about (e.g. a Card ;; or Dashboard). For all other activity feed items with no model everyone can read/write (defmethod can-? :default [perms-check-fn {model :model, model-id :model_id}] (if-let [object (when-let [entity (model->entity model)] (entity model-id))] (perms-check-fn object) true)) ;;; ----------------------------------------------- Entity & Lifecycle ----------------------------------------------- (models/defmodel Activity :activity) (defn- pre-insert [activity] (let [defaults {:timestamp :%now :details {}}] (merge defaults activity))) (u/strict-extend #_{:clj-kondo/ignore [:metabase/disallow-class-or-type-on-model]} (class Activity) models/IModel (merge models/IModelDefaults {:types (constantly {:details :json, :topic :keyword}) :pre-insert pre-insert})) (defmethod mi/can-read? Activity [& args] (apply can-? mi/can-read? args)) (defmethod mi/can-write? Activity [& args] (apply can-? mi/can-write? args)) ;;; ------------------------------------------------------ Etc. ------------------------------------------------------ ;; ## Persistence Functions TODO - this is probably the exact wrong way to have written this functionality . ;; This could have been a multimethod or protocol, and various entity classes could implement it; ;; Furthermore, we could have just used *current-user-id* to get the responsible user, instead of leaving it open to ;; user error. (defn record-activity! "Inserts a new `Activity` entry. Takes the following kwargs: :topic Required. The activity topic. :object Optional. The activity object being saved. :database-id Optional. ID of the `Database` related to the activity. :table-id Optional. ID of the `Table` related to the activity. :details-fn Optional. Gets called with `object` as the arg and the result is saved as the `:details` of the Activity. :user-id Optional. ID of the `User` responsible for the activity. defaults to (events/object->user-id object) :model Optional. name of the model representing the activity. defaults to (events/topic->model topic) :model-id Optional. ID of the model representing the activity. defaults to (events/object->model-id topic object) ex: (record-activity! :topic :segment-update :object segment :database-id 1 :table-id 13 :details-fn #(dissoc % :some-key))" {:style/indent 0} [& {:keys [topic object details-fn database-id table-id user-id model model-id]}] {:pre [(keyword? topic)]} (let [object (or object {})] (db/insert! Activity :topic topic :user_id (or user-id (events/object->user-id object)) :model (or model (events/topic->model topic)) :model_id (or model-id (events/object->model-id topic object)) :database_id database-id :table_id table-id :custom_id (:custom_id object) :details (if (fn? details-fn) (details-fn object) object))))
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/models/activity.clj
clojure
------------------------------------------------- Perms Checking ------------------------------------------------- For now only admins can see when another user joined -- we don't want every user knowing about every other user. In the future we might want to change this and come up with some sort of system where we can determine which users get to see other users -- perhaps if they are in a group together other than 'All Users' For every other activity topic we'll look at the read/write perms for the object the activty is about (e.g. a Card or Dashboard). For all other activity feed items with no model everyone can read/write ----------------------------------------------- Entity & Lifecycle ----------------------------------------------- ------------------------------------------------------ Etc. ------------------------------------------------------ ## Persistence Functions This could have been a multimethod or protocol, and various entity classes could implement it; Furthermore, we could have just used *current-user-id* to get the responsible user, instead of leaving it open to user error.
(ns metabase.models.activity (:require [metabase.api.common :as api] [metabase.events :as events] [metabase.models.card :refer [Card]] [metabase.models.dashboard :refer [Dashboard]] [metabase.models.interface :as mi] [metabase.models.metric :refer [Metric]] [metabase.models.pulse :refer [Pulse]] [metabase.models.segment :refer [Segment]] [metabase.util :as u] [toucan.db :as db] [toucan.models :as models])) (def ^:private model->entity {"card" Card "dashboard" Dashboard "metric" Metric "pulse" Pulse "segment" Segment}) (defmulti can-? "Implementation for `can-read?`/`can-write?` for items in the activity feed. Dispatches off of the activity `:topic`, e.g. `:user-joined`. `perms-check-fn` is `can-read?` or `can-write?` and should be called as needed on models the activity records." {:arglists '([perms-check-fn activity])} (fn [_ {:keys [topic]}] topic)) (defmethod can-? :user-joined [_ _] api/*is-superuser?*) (defmethod can-? :default [perms-check-fn {model :model, model-id :model_id}] (if-let [object (when-let [entity (model->entity model)] (entity model-id))] (perms-check-fn object) true)) (models/defmodel Activity :activity) (defn- pre-insert [activity] (let [defaults {:timestamp :%now :details {}}] (merge defaults activity))) (u/strict-extend #_{:clj-kondo/ignore [:metabase/disallow-class-or-type-on-model]} (class Activity) models/IModel (merge models/IModelDefaults {:types (constantly {:details :json, :topic :keyword}) :pre-insert pre-insert})) (defmethod mi/can-read? Activity [& args] (apply can-? mi/can-read? args)) (defmethod mi/can-write? Activity [& args] (apply can-? mi/can-write? args)) TODO - this is probably the exact wrong way to have written this functionality . (defn record-activity! "Inserts a new `Activity` entry. Takes the following kwargs: :topic Required. The activity topic. :object Optional. The activity object being saved. :database-id Optional. ID of the `Database` related to the activity. :table-id Optional. ID of the `Table` related to the activity. :details-fn Optional. Gets called with `object` as the arg and the result is saved as the `:details` of the Activity. :user-id Optional. ID of the `User` responsible for the activity. defaults to (events/object->user-id object) :model Optional. name of the model representing the activity. defaults to (events/topic->model topic) :model-id Optional. ID of the model representing the activity. defaults to (events/object->model-id topic object) ex: (record-activity! :topic :segment-update :object segment :database-id 1 :table-id 13 :details-fn #(dissoc % :some-key))" {:style/indent 0} [& {:keys [topic object details-fn database-id table-id user-id model model-id]}] {:pre [(keyword? topic)]} (let [object (or object {})] (db/insert! Activity :topic topic :user_id (or user-id (events/object->user-id object)) :model (or model (events/topic->model topic)) :model_id (or model-id (events/object->model-id topic object)) :database_id database-id :table_id table-id :custom_id (:custom_id object) :details (if (fn? details-fn) (details-fn object) object))))
660682a50d4eaba2faa575fa3ef3ca03c0fd64cfd9ece0f4bb6871cd67c221ce
robert-strandh/SICL
eliminate-append-values.lisp
(cl:in-package #:sicl-hir-transformations) ;;; When we start, the CAR of the cell in the VALUES-LOCATION contains ;;; a pointer to the cell where we should start adding values. So the first instruction is to load the CAR of the cell in the ;;; VALUES-LOCATION into the CELL-LOCATION. (defun make-initial-instructions (successor values-location value-count-location cell-location dynamic-environment-location) (make-instance 'cleavir-ir:compute-return-value-count-instruction :output value-count-location :dynamic-environment-location dynamic-environment-location :successor (make-instance 'cleavir-ir:car-instruction :input values-location :output cell-location :dynamic-environment-location dynamic-environment-location :successor successor))) (defun make-incrementation-instruction (successor index-location dynamic-environment-location) (make-instance 'cleavir-ir:unsigned-add-instruction :augend index-location :addend (make-instance 'cleavir-ir:constant-input :value 1) :output index-location :dynamic-environment-location dynamic-environment-location :successor successor)) ;;; The final instruction sets the CAR of the cell in the ;;; VALUES-LOCATION to the CELL-LOCATION, thereby either indicating the start cell for the next APPEND - VALUES - INSTRUCTION , or ;;; indicating the end of the list of arguments to supply to the function invoked by MULTIPLE - VALUE - CALL . (defun make-final-instruction (successor values-location cell-location dynamic-environment-location) (make-instance 'cleavir-ir:rplaca-instruction :inputs (list values-location cell-location) :dynamic-environment-location dynamic-environment-location :successor successor)) (defun make-test-step (true-successor false-successor value-count-location index-input cell-location dynamic-environment-location) (let ((temp-location (make-instance 'cleavir-ir:lexical-location :name (gensym "temp")))) ;; Check whether there are more values to access. (make-instance 'cleavir-ir:unsigned-less-instruction :inputs (list index-input value-count-location) :dynamic-environment-location dynamic-environment-location :successors (list ;; This branch is taken when there are more values to access. ;; Access the value indicated by INDEX-INPUT, and put it in a ;; temporary location. (make-instance 'cleavir-ir:return-value-instruction :input index-input :output temp-location :dynamic-environment-location dynamic-environment-location :successor ;; The put the value in the temporary location in the CAR of ;; the cell indicated by CELL-LOCATION. (make-instance 'cleavir-ir:rplaca-instruction :inputs (list cell-location temp-location) :dynamic-environment-location dynamic-environment-location :successor ;; Finally, advance the CELL-LOCATION to the next cell in ;; the list. (make-instance 'cleavir-ir:cdr-instruction :input cell-location :output cell-location :dynamic-environment-location dynamic-environment-location :successor true-successor))) false-successor)))) (defun make-loop (successor value-count-location cell-location dynamic-environment-location) (let* ((index-location (make-instance 'cleavir-ir:lexical-location :name (gensym "index"))) (nop (make-instance 'cleavir-ir:nop-instruction)) (increment (make-incrementation-instruction nop index-location dynamic-environment-location)) (test (make-test-step increment successor value-count-location index-location cell-location dynamic-environment-location))) (rplaca (cleavir-ir:successors increment) test) (push increment (cleavir-ir:predecessors test)) (make-instance 'cleavir-ir:assignment-instruction :input (make-instance 'cleavir-ir:constant-input :value 5) :output index-location :dynamic-environment-location dynamic-environment-location :successor test))) ;;; This function is charged with computing a sequence of instructions that are meant to replace a single APPEND - VALUES - INSTRUCTION . It returns the first instruction and the last instruction of the sequence as two values . (defun make-replacement (successor values-location dynamic-environment-location) (let* ((cell-location (make-instance 'cleavir-ir:lexical-location :name (gensym "cell"))) (value-count-location (make-instance 'cleavir-ir:lexical-location :name (gensym "VC"))) (final (make-final-instruction successor values-location cell-location dynamic-environment-location)) (true-branch (make-loop final value-count-location cell-location dynamic-environment-location))) (loop for i downfrom 4 to 0 do (setf true-branch (make-test-step true-branch final value-count-location (make-instance 'cleavir-ir:constant-input :value i) cell-location dynamic-environment-location))) (values (make-initial-instructions true-branch values-location value-count-location cell-location dynamic-environment-location) final))) (defun eliminate-append-values-instruction (instruction) (let* ((values-location (first (cleavir-ir:outputs instruction))) (dynamic-environment-location (cleavir-ir:dynamic-environment-location instruction)) (successor (cleavir-ir:first-successor instruction))) (multiple-value-bind (first last) (make-replacement successor values-location dynamic-environment-location) (setf (cleavir-ir:predecessors first) (cleavir-ir:predecessors instruction)) (loop for predecessor in (cleavir-ir:predecessors first) do (setf (cleavir-ir:successors predecessor) (substitute first instruction (cleavir-ir:successors predecessor)))) (setf (cleavir-ir:predecessors successor) (substitute last instruction (cleavir-ir:predecessors successor)))))) (defun eliminate-append-values-instructions (initial-instruction) (cleavir-ir:map-instructions-arbitrary-order (lambda (instruction) (when (typep instruction 'cleavir-ir:append-values-instruction) (eliminate-append-values-instruction instruction))) initial-instruction))
null
https://raw.githubusercontent.com/robert-strandh/SICL/bd3ec8f991d9455541d1629a3c672ae3d46dc16d/Code/Compiler/HIR-transformations/eliminate-append-values.lisp
lisp
When we start, the CAR of the cell in the VALUES-LOCATION contains a pointer to the cell where we should start adding values. So the VALUES-LOCATION into the CELL-LOCATION. The final instruction sets the CAR of the cell in the VALUES-LOCATION to the CELL-LOCATION, thereby either indicating indicating the end of the list of arguments to supply to the Check whether there are more values to access. This branch is taken when there are more values to access. Access the value indicated by INDEX-INPUT, and put it in a temporary location. The put the value in the temporary location in the CAR of the cell indicated by CELL-LOCATION. Finally, advance the CELL-LOCATION to the next cell in the list. This function is charged with computing a sequence of instructions
(cl:in-package #:sicl-hir-transformations) first instruction is to load the CAR of the cell in the (defun make-initial-instructions (successor values-location value-count-location cell-location dynamic-environment-location) (make-instance 'cleavir-ir:compute-return-value-count-instruction :output value-count-location :dynamic-environment-location dynamic-environment-location :successor (make-instance 'cleavir-ir:car-instruction :input values-location :output cell-location :dynamic-environment-location dynamic-environment-location :successor successor))) (defun make-incrementation-instruction (successor index-location dynamic-environment-location) (make-instance 'cleavir-ir:unsigned-add-instruction :augend index-location :addend (make-instance 'cleavir-ir:constant-input :value 1) :output index-location :dynamic-environment-location dynamic-environment-location :successor successor)) the start cell for the next APPEND - VALUES - INSTRUCTION , or function invoked by MULTIPLE - VALUE - CALL . (defun make-final-instruction (successor values-location cell-location dynamic-environment-location) (make-instance 'cleavir-ir:rplaca-instruction :inputs (list values-location cell-location) :dynamic-environment-location dynamic-environment-location :successor successor)) (defun make-test-step (true-successor false-successor value-count-location index-input cell-location dynamic-environment-location) (let ((temp-location (make-instance 'cleavir-ir:lexical-location :name (gensym "temp")))) (make-instance 'cleavir-ir:unsigned-less-instruction :inputs (list index-input value-count-location) :dynamic-environment-location dynamic-environment-location :successors (list (make-instance 'cleavir-ir:return-value-instruction :input index-input :output temp-location :dynamic-environment-location dynamic-environment-location :successor (make-instance 'cleavir-ir:rplaca-instruction :inputs (list cell-location temp-location) :dynamic-environment-location dynamic-environment-location :successor (make-instance 'cleavir-ir:cdr-instruction :input cell-location :output cell-location :dynamic-environment-location dynamic-environment-location :successor true-successor))) false-successor)))) (defun make-loop (successor value-count-location cell-location dynamic-environment-location) (let* ((index-location (make-instance 'cleavir-ir:lexical-location :name (gensym "index"))) (nop (make-instance 'cleavir-ir:nop-instruction)) (increment (make-incrementation-instruction nop index-location dynamic-environment-location)) (test (make-test-step increment successor value-count-location index-location cell-location dynamic-environment-location))) (rplaca (cleavir-ir:successors increment) test) (push increment (cleavir-ir:predecessors test)) (make-instance 'cleavir-ir:assignment-instruction :input (make-instance 'cleavir-ir:constant-input :value 5) :output index-location :dynamic-environment-location dynamic-environment-location :successor test))) that are meant to replace a single APPEND - VALUES - INSTRUCTION . It returns the first instruction and the last instruction of the sequence as two values . (defun make-replacement (successor values-location dynamic-environment-location) (let* ((cell-location (make-instance 'cleavir-ir:lexical-location :name (gensym "cell"))) (value-count-location (make-instance 'cleavir-ir:lexical-location :name (gensym "VC"))) (final (make-final-instruction successor values-location cell-location dynamic-environment-location)) (true-branch (make-loop final value-count-location cell-location dynamic-environment-location))) (loop for i downfrom 4 to 0 do (setf true-branch (make-test-step true-branch final value-count-location (make-instance 'cleavir-ir:constant-input :value i) cell-location dynamic-environment-location))) (values (make-initial-instructions true-branch values-location value-count-location cell-location dynamic-environment-location) final))) (defun eliminate-append-values-instruction (instruction) (let* ((values-location (first (cleavir-ir:outputs instruction))) (dynamic-environment-location (cleavir-ir:dynamic-environment-location instruction)) (successor (cleavir-ir:first-successor instruction))) (multiple-value-bind (first last) (make-replacement successor values-location dynamic-environment-location) (setf (cleavir-ir:predecessors first) (cleavir-ir:predecessors instruction)) (loop for predecessor in (cleavir-ir:predecessors first) do (setf (cleavir-ir:successors predecessor) (substitute first instruction (cleavir-ir:successors predecessor)))) (setf (cleavir-ir:predecessors successor) (substitute last instruction (cleavir-ir:predecessors successor)))))) (defun eliminate-append-values-instructions (initial-instruction) (cleavir-ir:map-instructions-arbitrary-order (lambda (instruction) (when (typep instruction 'cleavir-ir:append-values-instruction) (eliminate-append-values-instruction instruction))) initial-instruction))
18536add9c44719a50ed3cea0b5d284891ecd692918de25e95aa30d0a24c7e39
CloudI/CloudI
tcp_reverse_app.erl
%% Feel free to use, reuse and abuse the code in this file. @private -module(tcp_reverse_app). -behaviour(application). %% API. -export([start/2]). -export([stop/1]). %% API. start(_Type, _Args) -> {ok, _} = ranch:start_listener(tcp_reverse, ranch_tcp, [{port, 5555}], reverse_protocol, []), tcp_reverse_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/CloudI/CloudI/75b93bb0e7dc4734f5cd1ef913788e44b577a3d5/src/external/cloudi_x_ranch/examples/tcp_reverse/src/tcp_reverse_app.erl
erlang
Feel free to use, reuse and abuse the code in this file. API. API.
@private -module(tcp_reverse_app). -behaviour(application). -export([start/2]). -export([stop/1]). start(_Type, _Args) -> {ok, _} = ranch:start_listener(tcp_reverse, ranch_tcp, [{port, 5555}], reverse_protocol, []), tcp_reverse_sup:start_link(). stop(_State) -> ok.
3b132130620f41f02248daf00fb2441e3c028f2ee2a0759eff0e0860fd6965ed
ktakashi/sagittarius-scheme
c64.scm
-*- mode : scheme ; coding : utf-8 ; -*- ;;; ;;; srfi/%3a160/base/c64.scm - Homogeneous numeric vector datatypes (base) ;;; Copyright ( c ) 2020 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!nounbound (library (srfi :160 base c64) (export make-c64vector c64vector c64vector? <c64vector> c64vector-length c64vector-ref c64vector-set! c64vector->list list->c64vector) (import (rnrs) (srfi :4 numeric-vectors)) (define-tagged-vector "c64" 2 make-f32vector f32vector-length equal? f32vector-ref-f32-as-complex f32vector-set-complex-as-f32!) (define (f32vector-ref-f32-as-complex vec index) (let ((real (f32vector-ref vec index)) (imag (f32vector-ref vec (+ index 1)))) (if (zero? imag) real (make-rectangular real imag)))) (define (f32vector-set-complex-as-f32! vec index value) (let ((real (real-part value)) (imag (imag-part value))) (f32vector-set! vec index real) (f32vector-set! vec (+ index 1) imag))) )
null
https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/3971b131d463696297c320dbe595dffd08867dac/sitelib/srfi/%253a160/base/c64.scm
scheme
coding : utf-8 ; -*- srfi/%3a160/base/c64.scm - Homogeneous numeric vector datatypes (base) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright ( c ) 2020 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING #!nounbound (library (srfi :160 base c64) (export make-c64vector c64vector c64vector? <c64vector> c64vector-length c64vector-ref c64vector-set! c64vector->list list->c64vector) (import (rnrs) (srfi :4 numeric-vectors)) (define-tagged-vector "c64" 2 make-f32vector f32vector-length equal? f32vector-ref-f32-as-complex f32vector-set-complex-as-f32!) (define (f32vector-ref-f32-as-complex vec index) (let ((real (f32vector-ref vec index)) (imag (f32vector-ref vec (+ index 1)))) (if (zero? imag) real (make-rectangular real imag)))) (define (f32vector-set-complex-as-f32! vec index value) (let ((real (real-part value)) (imag (imag-part value))) (f32vector-set! vec index real) (f32vector-set! vec (+ index 1) imag))) )
28c0ce1b9f7169b5727cbeee2efd50b1f9b52b3893f9e7f94fd07e6e3f8c071c
armedbear/abcl
lispfunctions.lisp
;;; lispfunctions.lisp ;;; Copyright ( C ) 2008 $ Id$ ;;; ;;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License ;;; along with this program; if not, write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . param comes from java , so accessing it require calling - value on it (defun void-function (param) (format t "in void-function, param: ~a~%" (jobject-lisp-value param))) params come from java , so accessing them require calling - value on them (defun int-function (jparam1 jparam2) (let* ((param1 (jobject-lisp-value jparam1)) (param2 (jobject-lisp-value jparam2)) (result (+ param1 param2))) (format t "in int-function, params: ~a ~a~%result: ~a~%" param1 param2 result) result))
null
https://raw.githubusercontent.com/armedbear/abcl/36a4b5994227d768882ff6458b3df9f79caac664/examples/java-to-lisp-2/lispfunctions.lisp
lisp
lispfunctions.lisp This program is free software; you can redistribute it and/or either version 2 This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software
Copyright ( C ) 2008 $ Id$ modify it under the terms of the GNU General Public License of the License , or ( at your option ) any later version . You should have received a copy of the GNU General Public License Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . param comes from java , so accessing it require calling - value on it (defun void-function (param) (format t "in void-function, param: ~a~%" (jobject-lisp-value param))) params come from java , so accessing them require calling - value on them (defun int-function (jparam1 jparam2) (let* ((param1 (jobject-lisp-value jparam1)) (param2 (jobject-lisp-value jparam2)) (result (+ param1 param2))) (format t "in int-function, params: ~a ~a~%result: ~a~%" param1 param2 result) result))
c29c7e8b127113e5aadb86f87e03addd80cafda16235100ce74e756cb5d9674a
AbstractMachinesLab/caramel
ctype.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) Operations on core types open Asttypes open Types module Unification_trace: sig (** Unification traces are used to explain unification errors when printing error messages *) type position = First | Second type desc = { t: type_expr; expanded: type_expr option } type 'a diff = { got: 'a; expected: 'a} (** Scope escape related errors *) type 'a escape = | Constructor of Path.t | Univ of type_expr * The type_expr argument of [ Univ ] is always a [ Tunivar _ ] , we keep a [ type_expr ] to track renaming in { ! } we keep a [type_expr] to track renaming in {!Printtyp} *) | Self | Module_type of Path.t | Equation of 'a (** Errors for polymorphic variants *) type fixed_row_case = | Cannot_be_closed | Cannot_add_tags of string list type variant = | No_intersection | No_tags of position * (Asttypes.label * row_field) list | Incompatible_types_for of string | Fixed_row of position * fixed_row_case * fixed_explanation (** Fixed row types, e.g. ['a. [> `X] as 'a] *) type obj = | Missing_field of position * string | Abstract_row of position | Self_cannot_be_closed type 'a elt = | Diff of 'a diff | Variant of variant | Obj of obj | Escape of {context: type_expr option; kind:'a escape} | Incompatible_fields of {name:string; diff: type_expr diff } | Rec_occur of type_expr * type_expr type t = desc elt list val diff: type_expr -> type_expr -> desc elt (** [map_diff f {expected;got}] is [{expected=f expected; got=f got}] *) val map_diff: ('a -> 'b) -> 'a diff -> 'b diff (** [flatten f trace] flattens all elements of type {!desc} in [trace] to either [f x.t expanded] if [x.expanded=Some expanded] or [f x.t x.t] otherwise *) val flatten: (type_expr -> type_expr -> 'a) -> t -> 'a elt list (** Switch [expected] and [got] *) val swap: t -> t (** [explain trace f] calls [f] on trace elements starting from the end until [f ~prev elt] is [Some _], returns that or [None] if the end of the trace is reached. *) val explain: 'a elt list -> (prev:'a elt option -> 'a elt -> 'b option) -> 'b option * specific val map_types : (type_expr -> type_expr) -> t -> t end exception Unify of Unification_trace.t exception Tags of label * label exception Subtype of Unification_trace.t * Unification_trace.t exception Cannot_expand exception Cannot_apply val init_def: int -> unit (* Set the initial variable level *) val begin_def: unit -> unit (* Raise the variable level by one at the beginning of a definition. *) val end_def: unit -> unit Lower the variable level by one at the end of a definition val begin_class_def: unit -> unit val raise_nongen_level: unit -> unit val reset_global_level: unit -> unit (* Reset the global level before typing an expression *) val increase_global_level: unit -> int val restore_global_level: int -> unit This pair of functions is only used in Typetexp type levels = { current_level: int; nongen_level: int; global_level: int; saved_level: (int * int) list; } val save_levels: unit -> levels val set_levels: levels -> unit val create_scope : unit -> int val newty: type_desc -> type_expr val newvar: ?name:string -> unit -> type_expr val newvar2: ?name:string -> int -> type_expr (* Return a fresh variable *) val new_global_var: ?name:string -> unit -> type_expr (* Return a fresh variable, bound at toplevel (as type variables ['a] in type constraints). *) val newobj: type_expr -> type_expr val newconstr: Path.t -> type_expr list -> type_expr val none: type_expr (* A dummy type expression *) val repr: type_expr -> type_expr (* Return the canonical representative of a type. *) val object_fields: type_expr -> type_expr val flatten_fields: type_expr -> (string * field_kind * type_expr) list * type_expr (* Transform a field type into a list of pairs label-type *) (* The fields are sorted *) val associate_fields: (string * field_kind * type_expr) list -> (string * field_kind * type_expr) list -> (string * field_kind * type_expr * field_kind * type_expr) list * (string * field_kind * type_expr) list * (string * field_kind * type_expr) list val opened_object: type_expr -> bool val close_object: type_expr -> bool val row_variable: type_expr -> type_expr (* Return the row variable of an open object type *) val set_object_name: Ident.t -> type_expr -> type_expr list -> type_expr -> unit val remove_object_name: type_expr -> unit val hide_private_methods: type_expr -> unit val find_cltype_for_path: Env.t -> Path.t -> type_declaration * type_expr val sort_row_fields: (label * row_field) list -> (label * row_field) list val merge_row_fields: (label * row_field) list -> (label * row_field) list -> (label * row_field) list * (label * row_field) list * (label * row_field * row_field) list val filter_row_fields: bool -> (label * row_field) list -> (label * row_field) list val generalize: type_expr -> unit in - place the given type val lower_contravariant: Env.t -> type_expr -> unit (* Lower level of type variables inside contravariant branches; to be used before generalize for expansive expressions *) val generalize_structure: type_expr -> unit (* Same, but variables are only lowered to !current_level *) val generalize_spine: type_expr -> unit (* Special function to generalize a method during inference *) val correct_levels: type_expr -> type_expr (* Returns a copy with decreasing levels *) val limited_generalize: type_expr -> type_expr -> unit (* Only generalize some part of the type Make the remaining of the type non-generalizable *) val check_scope_escape : Env.t -> int -> type_expr -> unit (* [check_scope_escape env lvl ty] ensures that [ty] could be raised to the level [lvl] without any scope escape. Raises [Unify] otherwise *) val instance: ?partial:bool -> type_expr -> type_expr (* Take an instance of a type scheme *) (* partial=None -> normal partial=false -> newvar() for non generic subterms partial=true -> newty2 ty.level Tvar for non generic subterms *) val generic_instance: type_expr -> type_expr (* Same as instance, but new nodes at generic_level *) val instance_list: type_expr list -> type_expr list (* Take an instance of a list of type schemes *) val existential_name: constructor_description -> type_expr -> string val instance_constructor: ?in_pattern:Env.t ref * int -> constructor_description -> type_expr list * type_expr (* Same, for a constructor *) val instance_parameterized_type: ?keep_names:bool -> type_expr list -> type_expr -> type_expr list * type_expr val instance_parameterized_type_2: type_expr list -> type_expr list -> type_expr -> type_expr list * type_expr list * type_expr val instance_declaration: type_declaration -> type_declaration val generic_instance_declaration: type_declaration -> type_declaration (* Same as instance_declaration, but new nodes at generic_level *) val instance_class: type_expr list -> class_type -> type_expr list * class_type val instance_poly: ?keep_names:bool -> bool -> type_expr list -> type_expr -> type_expr list * type_expr (* Take an instance of a type scheme containing free univars *) val instance_label: bool -> label_description -> type_expr list * type_expr * type_expr (* Same, for a label *) val apply: Env.t -> type_expr list -> type_expr -> type_expr list -> type_expr (* [apply [p1...pN] t [a1...aN]] match the arguments [ai] to the parameters [pi] and returns the corresponding instance of [t]. Exception [Cannot_apply] is raised in case of failure. *) val expand_head_once: Env.t -> type_expr -> type_expr val expand_head: Env.t -> type_expr -> type_expr val try_expand_once_opt: Env.t -> type_expr -> type_expr val expand_head_opt: Env.t -> type_expr -> type_expr (** The compiler's own version of [expand_head] necessary for type-based optimisations. *) val full_expand: Env.t -> type_expr -> type_expr val extract_concrete_typedecl: Env.t -> type_expr -> Path.t * Path.t * type_declaration Return the original path of the types , and the first concrete type declaration found expanding it . Raise [ Not_found ] if none appears or not a type constructor . type declaration found expanding it. Raise [Not_found] if none appears or not a type constructor. *) val enforce_constraints: Env.t -> type_expr -> unit val unify: Env.t -> type_expr -> type_expr -> unit Unify the two types given . Raise [ Unify ] if not possible . val unify_gadt: equations_level:int -> Env.t ref -> type_expr -> type_expr -> unit Unify the two types given and update the environment with the local constraints . Raise [ Unify ] if not possible . local constraints. Raise [Unify] if not possible. *) val unify_var: Env.t -> type_expr -> type_expr -> unit Same as [ unify ] , but allow free univars when first type is a variable . is a variable. *) val with_passive_variants: ('a -> 'b) -> ('a -> 'b) (* Call [f] in passive_variants mode, for exhaustiveness check. *) val filter_arrow: Env.t -> type_expr -> arg_label -> type_expr * type_expr (* A special case of unification (with l:'a -> 'b). *) val filter_method: Env.t -> string -> private_flag -> type_expr -> type_expr (* A special case of unification (with {m : 'a; 'b}). *) val check_filter_method: Env.t -> string -> private_flag -> type_expr -> unit (* A special case of unification (with {m : 'a; 'b}), returning unit. *) val occur_in: Env.t -> type_expr -> type_expr -> bool val deep_occur: type_expr -> type_expr -> bool val filter_self_method: Env.t -> string -> private_flag -> (Ident.t * type_expr) Meths.t ref -> type_expr -> Ident.t * type_expr val moregeneral: Env.t -> bool -> type_expr -> type_expr -> bool Check if the first type scheme is more general than the second . val rigidify: type_expr -> type_expr list " Rigidify " a type and return its type variable val all_distinct_vars: Env.t -> type_expr list -> bool (* Check those types are all distinct type variables *) val matches: Env.t -> type_expr -> type_expr -> bool Same as [ moregeneral false ] , implemented using the two above functions and backtracking . Ignore levels functions and backtracking. Ignore levels *) val reify_univars : Types.type_expr -> Types.type_expr (* Replaces all the variables of a type by a univar. *) type class_match_failure = CM_Virtual_class | CM_Parameter_arity_mismatch of int * int | CM_Type_parameter_mismatch of Env.t * Unification_trace.t | CM_Class_type_mismatch of Env.t * class_type * class_type | CM_Parameter_mismatch of Env.t * Unification_trace.t | CM_Val_type_mismatch of string * Env.t * Unification_trace.t | CM_Meth_type_mismatch of string * Env.t * Unification_trace.t | CM_Non_mutable_value of string | CM_Non_concrete_value of string | CM_Missing_value of string | CM_Missing_method of string | CM_Hide_public of string | CM_Hide_virtual of string * string | CM_Public_method of string | CM_Private_method of string | CM_Virtual_method of string val match_class_types: ?trace:bool -> Env.t -> class_type -> class_type -> class_match_failure list Check if the first class type is more general than the second . val equal: Env.t -> bool -> type_expr list -> type_expr list -> bool (* [equal env [x1...xn] tau [y1...yn] sigma] checks whether the parameterized types [/\x1.../\xn.tau] and [/\y1.../\yn.sigma] are equivalent. *) val match_class_declarations: Env.t -> type_expr list -> class_type -> type_expr list -> class_type -> class_match_failure list Check if the first class type is more general than the second . val enlarge_type: Env.t -> type_expr -> type_expr * bool (* Make a type larger, flag is true if some pruning had to be done *) val subtype: Env.t -> type_expr -> type_expr -> unit -> unit (* [subtype env t1 t2] checks that [t1] is a subtype of [t2]. It accumulates the constraints the type variables must enforce and returns a function that enforces this constraints. *) exception Nondep_cannot_erase of Ident.t val nondep_type: Env.t -> Ident.t list -> type_expr -> type_expr (* Return a type equivalent to the given type but without references to any of the given identifiers. Raise [Nondep_cannot_erase id] if no such type exists because [id], in particular, could not be erased. *) val nondep_type_decl: Env.t -> Ident.t list -> bool -> type_declaration -> type_declaration (* Same for type declarations. *) val nondep_extension_constructor: Env.t -> Ident.t list -> extension_constructor -> extension_constructor (* Same for extension constructor *) val nondep_class_declaration: Env.t -> Ident.t list -> class_declaration -> class_declaration (* Same for class declarations. *) val nondep_cltype_declaration: Env.t -> Ident.t list -> class_type_declaration -> class_type_declaration (* Same for class type declarations. *) correct_abbrev : - > Path.t - > type_expr list - > type_expr - > unit val cyclic_abbrev: Env.t -> Ident.t -> type_expr -> bool val is_contractive: Env.t -> Path.t -> bool val normalize_type: Env.t -> type_expr -> unit val closed_schema: Env.t -> type_expr -> bool (* Check whether the given type scheme contains no non-generic type variables *) val free_variables: ?env:Env.t -> type_expr -> type_expr list (* If env present, then check for incomplete definitions too *) val closed_type_decl: type_declaration -> type_expr option val closed_extension_constructor: extension_constructor -> type_expr option type closed_class_failure = CC_Method of type_expr * bool * string * type_expr | CC_Value of type_expr * bool * string * type_expr val closed_class: type_expr list -> class_signature -> closed_class_failure option (* Check whether all type variables are bound *) val unalias: type_expr -> type_expr val signature_of_class_type: class_type -> class_signature val self_type: class_type -> type_expr val class_type_arity: class_type -> int val arity: type_expr -> int (* Return the arity (as for curried functions) of the given type. *) val collapse_conj_params: Env.t -> type_expr list -> unit (* Collapse conjunctive types in class parameters *) val get_current_level: unit -> int val wrap_trace_gadt_instances: Env.t -> ('a -> 'b) -> 'a -> 'b val reset_reified_var_counter: unit -> unit val immediacy : Env.t -> type_expr -> Type_immediacy.t val maybe_pointer_type : Env.t -> type_expr -> bool (* True if type is possibly pointer, false if definitely not a pointer *) (* Stubs *) val package_subtype : (Env.t -> Path.t -> Longident.t list -> type_expr list -> Path.t -> Longident.t list -> type_expr list -> bool) ref val mcomp : Env.t -> type_expr -> type_expr -> unit
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/src/ocaml/typing/410/ctype.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Unification traces are used to explain unification errors when printing error messages * Scope escape related errors * Errors for polymorphic variants * Fixed row types, e.g. ['a. [> `X] as 'a] * [map_diff f {expected;got}] is [{expected=f expected; got=f got}] * [flatten f trace] flattens all elements of type {!desc} in [trace] to either [f x.t expanded] if [x.expanded=Some expanded] or [f x.t x.t] otherwise * Switch [expected] and [got] * [explain trace f] calls [f] on trace elements starting from the end until [f ~prev elt] is [Some _], returns that or [None] if the end of the trace is reached. Set the initial variable level Raise the variable level by one at the beginning of a definition. Reset the global level before typing an expression Return a fresh variable Return a fresh variable, bound at toplevel (as type variables ['a] in type constraints). A dummy type expression Return the canonical representative of a type. Transform a field type into a list of pairs label-type The fields are sorted Return the row variable of an open object type Lower level of type variables inside contravariant branches; to be used before generalize for expansive expressions Same, but variables are only lowered to !current_level Special function to generalize a method during inference Returns a copy with decreasing levels Only generalize some part of the type Make the remaining of the type non-generalizable [check_scope_escape env lvl ty] ensures that [ty] could be raised to the level [lvl] without any scope escape. Raises [Unify] otherwise Take an instance of a type scheme partial=None -> normal partial=false -> newvar() for non generic subterms partial=true -> newty2 ty.level Tvar for non generic subterms Same as instance, but new nodes at generic_level Take an instance of a list of type schemes Same, for a constructor Same as instance_declaration, but new nodes at generic_level Take an instance of a type scheme containing free univars Same, for a label [apply [p1...pN] t [a1...aN]] match the arguments [ai] to the parameters [pi] and returns the corresponding instance of [t]. Exception [Cannot_apply] is raised in case of failure. * The compiler's own version of [expand_head] necessary for type-based optimisations. Call [f] in passive_variants mode, for exhaustiveness check. A special case of unification (with l:'a -> 'b). A special case of unification (with {m : 'a; 'b}). A special case of unification (with {m : 'a; 'b}), returning unit. Check those types are all distinct type variables Replaces all the variables of a type by a univar. [equal env [x1...xn] tau [y1...yn] sigma] checks whether the parameterized types [/\x1.../\xn.tau] and [/\y1.../\yn.sigma] are equivalent. Make a type larger, flag is true if some pruning had to be done [subtype env t1 t2] checks that [t1] is a subtype of [t2]. It accumulates the constraints the type variables must enforce and returns a function that enforces this constraints. Return a type equivalent to the given type but without references to any of the given identifiers. Raise [Nondep_cannot_erase id] if no such type exists because [id], in particular, could not be erased. Same for type declarations. Same for extension constructor Same for class declarations. Same for class type declarations. Check whether the given type scheme contains no non-generic type variables If env present, then check for incomplete definitions too Check whether all type variables are bound Return the arity (as for curried functions) of the given type. Collapse conjunctive types in class parameters True if type is possibly pointer, false if definitely not a pointer Stubs
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the Operations on core types open Asttypes open Types module Unification_trace: sig type position = First | Second type desc = { t: type_expr; expanded: type_expr option } type 'a diff = { got: 'a; expected: 'a} type 'a escape = | Constructor of Path.t | Univ of type_expr * The type_expr argument of [ Univ ] is always a [ Tunivar _ ] , we keep a [ type_expr ] to track renaming in { ! } we keep a [type_expr] to track renaming in {!Printtyp} *) | Self | Module_type of Path.t | Equation of 'a type fixed_row_case = | Cannot_be_closed | Cannot_add_tags of string list type variant = | No_intersection | No_tags of position * (Asttypes.label * row_field) list | Incompatible_types_for of string | Fixed_row of position * fixed_row_case * fixed_explanation type obj = | Missing_field of position * string | Abstract_row of position | Self_cannot_be_closed type 'a elt = | Diff of 'a diff | Variant of variant | Obj of obj | Escape of {context: type_expr option; kind:'a escape} | Incompatible_fields of {name:string; diff: type_expr diff } | Rec_occur of type_expr * type_expr type t = desc elt list val diff: type_expr -> type_expr -> desc elt val map_diff: ('a -> 'b) -> 'a diff -> 'b diff val flatten: (type_expr -> type_expr -> 'a) -> t -> 'a elt list val swap: t -> t val explain: 'a elt list -> (prev:'a elt option -> 'a elt -> 'b option) -> 'b option * specific val map_types : (type_expr -> type_expr) -> t -> t end exception Unify of Unification_trace.t exception Tags of label * label exception Subtype of Unification_trace.t * Unification_trace.t exception Cannot_expand exception Cannot_apply val init_def: int -> unit val begin_def: unit -> unit val end_def: unit -> unit Lower the variable level by one at the end of a definition val begin_class_def: unit -> unit val raise_nongen_level: unit -> unit val reset_global_level: unit -> unit val increase_global_level: unit -> int val restore_global_level: int -> unit This pair of functions is only used in Typetexp type levels = { current_level: int; nongen_level: int; global_level: int; saved_level: (int * int) list; } val save_levels: unit -> levels val set_levels: levels -> unit val create_scope : unit -> int val newty: type_desc -> type_expr val newvar: ?name:string -> unit -> type_expr val newvar2: ?name:string -> int -> type_expr val new_global_var: ?name:string -> unit -> type_expr val newobj: type_expr -> type_expr val newconstr: Path.t -> type_expr list -> type_expr val none: type_expr val repr: type_expr -> type_expr val object_fields: type_expr -> type_expr val flatten_fields: type_expr -> (string * field_kind * type_expr) list * type_expr val associate_fields: (string * field_kind * type_expr) list -> (string * field_kind * type_expr) list -> (string * field_kind * type_expr * field_kind * type_expr) list * (string * field_kind * type_expr) list * (string * field_kind * type_expr) list val opened_object: type_expr -> bool val close_object: type_expr -> bool val row_variable: type_expr -> type_expr val set_object_name: Ident.t -> type_expr -> type_expr list -> type_expr -> unit val remove_object_name: type_expr -> unit val hide_private_methods: type_expr -> unit val find_cltype_for_path: Env.t -> Path.t -> type_declaration * type_expr val sort_row_fields: (label * row_field) list -> (label * row_field) list val merge_row_fields: (label * row_field) list -> (label * row_field) list -> (label * row_field) list * (label * row_field) list * (label * row_field * row_field) list val filter_row_fields: bool -> (label * row_field) list -> (label * row_field) list val generalize: type_expr -> unit in - place the given type val lower_contravariant: Env.t -> type_expr -> unit val generalize_structure: type_expr -> unit val generalize_spine: type_expr -> unit val correct_levels: type_expr -> type_expr val limited_generalize: type_expr -> type_expr -> unit val check_scope_escape : Env.t -> int -> type_expr -> unit val instance: ?partial:bool -> type_expr -> type_expr val generic_instance: type_expr -> type_expr val instance_list: type_expr list -> type_expr list val existential_name: constructor_description -> type_expr -> string val instance_constructor: ?in_pattern:Env.t ref * int -> constructor_description -> type_expr list * type_expr val instance_parameterized_type: ?keep_names:bool -> type_expr list -> type_expr -> type_expr list * type_expr val instance_parameterized_type_2: type_expr list -> type_expr list -> type_expr -> type_expr list * type_expr list * type_expr val instance_declaration: type_declaration -> type_declaration val generic_instance_declaration: type_declaration -> type_declaration val instance_class: type_expr list -> class_type -> type_expr list * class_type val instance_poly: ?keep_names:bool -> bool -> type_expr list -> type_expr -> type_expr list * type_expr val instance_label: bool -> label_description -> type_expr list * type_expr * type_expr val apply: Env.t -> type_expr list -> type_expr -> type_expr list -> type_expr val expand_head_once: Env.t -> type_expr -> type_expr val expand_head: Env.t -> type_expr -> type_expr val try_expand_once_opt: Env.t -> type_expr -> type_expr val expand_head_opt: Env.t -> type_expr -> type_expr val full_expand: Env.t -> type_expr -> type_expr val extract_concrete_typedecl: Env.t -> type_expr -> Path.t * Path.t * type_declaration Return the original path of the types , and the first concrete type declaration found expanding it . Raise [ Not_found ] if none appears or not a type constructor . type declaration found expanding it. Raise [Not_found] if none appears or not a type constructor. *) val enforce_constraints: Env.t -> type_expr -> unit val unify: Env.t -> type_expr -> type_expr -> unit Unify the two types given . Raise [ Unify ] if not possible . val unify_gadt: equations_level:int -> Env.t ref -> type_expr -> type_expr -> unit Unify the two types given and update the environment with the local constraints . Raise [ Unify ] if not possible . local constraints. Raise [Unify] if not possible. *) val unify_var: Env.t -> type_expr -> type_expr -> unit Same as [ unify ] , but allow free univars when first type is a variable . is a variable. *) val with_passive_variants: ('a -> 'b) -> ('a -> 'b) val filter_arrow: Env.t -> type_expr -> arg_label -> type_expr * type_expr val filter_method: Env.t -> string -> private_flag -> type_expr -> type_expr val check_filter_method: Env.t -> string -> private_flag -> type_expr -> unit val occur_in: Env.t -> type_expr -> type_expr -> bool val deep_occur: type_expr -> type_expr -> bool val filter_self_method: Env.t -> string -> private_flag -> (Ident.t * type_expr) Meths.t ref -> type_expr -> Ident.t * type_expr val moregeneral: Env.t -> bool -> type_expr -> type_expr -> bool Check if the first type scheme is more general than the second . val rigidify: type_expr -> type_expr list " Rigidify " a type and return its type variable val all_distinct_vars: Env.t -> type_expr list -> bool val matches: Env.t -> type_expr -> type_expr -> bool Same as [ moregeneral false ] , implemented using the two above functions and backtracking . Ignore levels functions and backtracking. Ignore levels *) val reify_univars : Types.type_expr -> Types.type_expr type class_match_failure = CM_Virtual_class | CM_Parameter_arity_mismatch of int * int | CM_Type_parameter_mismatch of Env.t * Unification_trace.t | CM_Class_type_mismatch of Env.t * class_type * class_type | CM_Parameter_mismatch of Env.t * Unification_trace.t | CM_Val_type_mismatch of string * Env.t * Unification_trace.t | CM_Meth_type_mismatch of string * Env.t * Unification_trace.t | CM_Non_mutable_value of string | CM_Non_concrete_value of string | CM_Missing_value of string | CM_Missing_method of string | CM_Hide_public of string | CM_Hide_virtual of string * string | CM_Public_method of string | CM_Private_method of string | CM_Virtual_method of string val match_class_types: ?trace:bool -> Env.t -> class_type -> class_type -> class_match_failure list Check if the first class type is more general than the second . val equal: Env.t -> bool -> type_expr list -> type_expr list -> bool val match_class_declarations: Env.t -> type_expr list -> class_type -> type_expr list -> class_type -> class_match_failure list Check if the first class type is more general than the second . val enlarge_type: Env.t -> type_expr -> type_expr * bool val subtype: Env.t -> type_expr -> type_expr -> unit -> unit exception Nondep_cannot_erase of Ident.t val nondep_type: Env.t -> Ident.t list -> type_expr -> type_expr val nondep_type_decl: Env.t -> Ident.t list -> bool -> type_declaration -> type_declaration val nondep_extension_constructor: Env.t -> Ident.t list -> extension_constructor -> extension_constructor val nondep_class_declaration: Env.t -> Ident.t list -> class_declaration -> class_declaration val nondep_cltype_declaration: Env.t -> Ident.t list -> class_type_declaration -> class_type_declaration correct_abbrev : - > Path.t - > type_expr list - > type_expr - > unit val cyclic_abbrev: Env.t -> Ident.t -> type_expr -> bool val is_contractive: Env.t -> Path.t -> bool val normalize_type: Env.t -> type_expr -> unit val closed_schema: Env.t -> type_expr -> bool val free_variables: ?env:Env.t -> type_expr -> type_expr list val closed_type_decl: type_declaration -> type_expr option val closed_extension_constructor: extension_constructor -> type_expr option type closed_class_failure = CC_Method of type_expr * bool * string * type_expr | CC_Value of type_expr * bool * string * type_expr val closed_class: type_expr list -> class_signature -> closed_class_failure option val unalias: type_expr -> type_expr val signature_of_class_type: class_type -> class_signature val self_type: class_type -> type_expr val class_type_arity: class_type -> int val arity: type_expr -> int val collapse_conj_params: Env.t -> type_expr list -> unit val get_current_level: unit -> int val wrap_trace_gadt_instances: Env.t -> ('a -> 'b) -> 'a -> 'b val reset_reified_var_counter: unit -> unit val immediacy : Env.t -> type_expr -> Type_immediacy.t val maybe_pointer_type : Env.t -> type_expr -> bool val package_subtype : (Env.t -> Path.t -> Longident.t list -> type_expr list -> Path.t -> Longident.t list -> type_expr list -> bool) ref val mcomp : Env.t -> type_expr -> type_expr -> unit